"""This file contains helpers for cmake."""

def _quote(s):
    """Quotes the given string for use in a shell command.

    This function double-quotes the given string (in case it contains spaces or
    other special characters) and escapes any special characters (dollar signs,
    double-quotes, and backslashes) that may be present.

    Args:
      s: The string to quote.

    Returns:
      An escaped and quoted version of the string that can be passed to a shell
      command.
    """
    return ('"' +
            s.replace("\\", "\\\\").replace("$", "\\$").replace('"', "\\\"") +
            '"')

def cmake_var_string(cmake_vars):
    """Converts a dictionary to an input suitable for expand_cmake_vars.

    Ideally we would jist stringify in the expand_cmake_vars() rule, but select()
    interacts badly with genrules.

    Args:
      cmake_vars: a dictionary with string keys and values that are convertable to
        strings.

    Returns:
      cmake_vars in a form suitable for passing to expand_cmake_vars.
    """
    return " ".join([
        _quote("{}={}".format(k, str(v)))
        for (k, v) in cmake_vars.items()
    ])

def expand_cmake_vars(name, src, dst, cmake_vars):
    """Expands #cmakedefine, #cmakedefine01, and CMake variables in a text file.

    Args:
      name: the name of the rule
      src: the input of the rule
      dst: the output of the rule
      cmake_vars: a string containing the CMake variables, as generated by
        cmake_var_string.
    """
    expand_cmake_vars_tool = "@org_tensorflow//third_party/llvm_openmp:expand_cmake_vars"
    native.genrule(
        name = name,
        srcs = [src],
        tools = [expand_cmake_vars_tool],
        outs = [dst],
        cmd = ("$(location {}) ".format(expand_cmake_vars_tool) + cmake_vars +
               "< $< > $@"),
    )
