• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1"""This file contains helpers for cmake."""
2
3def _quote(s):
4    """Quotes the given string for use in a shell command.
5
6    This function double-quotes the given string (in case it contains spaces or
7    other special characters) and escapes any special characters (dollar signs,
8    double-quotes, and backslashes) that may be present.
9
10    Args:
11      s: The string to quote.
12
13    Returns:
14      An escaped and quoted version of the string that can be passed to a shell
15      command.
16    """
17    return ('"' +
18            s.replace("\\", "\\\\").replace("$", "\\$").replace('"', "\\\"") +
19            '"')
20
21def cmake_var_string(cmake_vars):
22    """Converts a dictionary to an input suitable for expand_cmake_vars.
23
24    Ideally we would jist stringify in the expand_cmake_vars() rule, but select()
25    interacts badly with genrules.
26
27    Args:
28      cmake_vars: a dictionary with string keys and values that are convertable to
29        strings.
30
31    Returns:
32      cmake_vars in a form suitable for passing to expand_cmake_vars.
33    """
34    return " ".join([
35        _quote("{}={}".format(k, str(v)))
36        for (k, v) in cmake_vars.items()
37    ])
38
39def expand_cmake_vars(name, src, dst, cmake_vars):
40    """Expands #cmakedefine, #cmakedefine01, and CMake variables in a text file.
41
42    Args:
43      name: the name of the rule
44      src: the input of the rule
45      dst: the output of the rule
46      cmake_vars: a string containing the CMake variables, as generated by
47        cmake_var_string.
48    """
49    expand_cmake_vars_tool = "@org_tensorflow//third_party/llvm_openmp:expand_cmake_vars"
50    native.genrule(
51        name = name,
52        srcs = [src],
53        tools = [expand_cmake_vars_tool],
54        outs = [dst],
55        cmd = ("$(location {}) ".format(expand_cmake_vars_tool) + cmake_vars +
56               "< $< > $@"),
57    )
58