1#!/usr/bin/env python3
2# Copyright (C) 2019 The Android Open Source Project
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#      http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16import argparse
17import os
18import sys
19
20# Converts the SQL metrics for trace processor into a C++ header with the SQL
21# as a string constant to allow trace processor to exectue the metrics.
22
23REPLACEMENT_HEADER = '''/*
24 * Copyright (C) 2019 The Android Open Source Project
25 *
26 * Licensed under the Apache License, Version 2.0 (the "License");
27 * you may not use this file except in compliance with the License.
28 * You may obtain a copy of the License at
29 *
30 *      http://www.apache.org/licenses/LICENSE-2.0
31 *
32 * Unless required by applicable law or agreed to in writing, software
33 * distributed under the License is distributed on an "AS IS" BASIS,
34 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
35 * See the License for the specific language governing permissions and
36 * limitations under the License.
37 */
38
39/*
40 *******************************************************************************
41 * AUTOGENERATED BY tools/gen_merged_sql_metrics - DO NOT EDIT
42 *******************************************************************************
43 */
44
45 #include <string.h>
46'''
47
48NAMESPACE_BEGIN = '''
49namespace perfetto {
50namespace trace_processor {
51namespace metrics {
52namespace sql_metrics {
53'''
54
55FILE_TO_SQL_STRUCT = '''
56struct FileToSql {
57  const char* path;
58  const char* sql;
59};
60'''
61
62NAMESPACE_END = '''
63}  // namespace sql_metrics
64}  // namespace metrics
65}  // namespace trace_processor
66}  // namsepace perfetto
67'''
68
69
70def filename_to_variable(filename):
71  return "k" + "".join([x.capitalize() for x in filename.split("_")])
72
73
74def main():
75  parser = argparse.ArgumentParser()
76  parser.add_argument('--cpp_out', required=True)
77  parser.add_argument('sql_files', nargs='*')
78  args = parser.parse_args()
79
80  root_path = os.path.commonprefix([os.path.abspath(x) for x in args.sql_files])
81
82  # Extract the SQL output from each file.
83  sql_outputs = {}
84  for file_name in args.sql_files:
85    with open(file_name, 'r') as f:
86      relpath = os.path.relpath(file_name, root_path)
87      sql_outputs[relpath] = "".join(
88          x for x in f.readlines() if not x.startswith('--'))
89
90  with open(args.cpp_out, 'w+') as output:
91    output.write(REPLACEMENT_HEADER)
92    output.write(NAMESPACE_BEGIN)
93
94    # Create the C++ variable for each SQL file.
95    for path, sql in sql_outputs.items():
96      name = os.path.basename(path)
97      variable = filename_to_variable(os.path.splitext(name)[0])
98      output.write('\nconst char {}[] = '.format(variable))
99      # MSVC doesn't like string literals that are individually longer than 16k.
100      # However it's still fine "if" "we" "concatenate" "many" "of" "them".
101      # This code splits the sql in string literals of ~1000 chars each.
102      line_groups = ['']
103      for line in sql.split('\n'):
104        line_groups[-1] += line + '\n'
105        if len(line_groups[-1]) > 1000:
106          line_groups.append('')
107
108      for line in line_groups:
109        output.write('R"_d3l1m1t3r_({})_d3l1m1t3r_"\n'.format(line))
110      output.write(';\n')
111
112    output.write(FILE_TO_SQL_STRUCT)
113
114    # Create mapping of filename to variable name for each variable.
115    output.write("\nconst FileToSql kFileToSql[] = {")
116    for path in sql_outputs.keys():
117      name = os.path.basename(path)
118      variable = filename_to_variable(os.path.splitext(name)[0])
119
120      # This is for Windows which has \ as a path separator.
121      path = path.replace("\\", "/")
122      output.write('\n  {{"{}", {}}},\n'.format(path, variable))
123    output.write("};\n")
124
125    output.write(NAMESPACE_END)
126
127  return 0
128
129
130if __name__ == '__main__':
131  sys.exit(main())
132