summaryrefslogtreecommitdiffstats
path: root/chrome/test/chromedriver/cpp_source.py
blob: dd6114b38e6bfb6dd673216a75f41ff85a25e83d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Writes C++ header/cc source files for embedding resources into C++."""

import datetime
import os
import sys


def WriteSource(base_name,
                dir_from_src,
                output_dir,
                global_string_map):
  """Writes C++ header/cc source files for the given map of string variables.

  Args:
      base_name: The basename of the file, without the extension.
      dir_from_src: Path from src to the directory that will contain the file,
          using forward slashes.
      output_dir: Directory to output the sources to.
      global_string_map: Map of variable names to their string values. These
          variables will be available as globals.
  """
  copyright_header_template = (
      '// Copyright %s The Chromium Authors. All rights reserved.\n'
      '// Use of this source code is governed by a BSD-style license '
      'that can be\n'
      '// found in the LICENSE file.\n\n'
      '// This file was generated at (%s) by running:\n'
      '//     %s')
  copyright_header = copyright_header_template % (
      datetime.date.today().year,
      datetime.datetime.now().isoformat(' '),
      ' '.join(sys.argv))

  # Write header file.
  externs = []
  for name in global_string_map.iterkeys():
    externs += ['extern const char %s[];' % name]

  temp = '_'.join(dir_from_src.split('/') + [base_name])
  define = temp.upper() + '_H_'
  header = '\n'.join([
      copyright_header,
      '',
      '#ifndef ' + define,
      '#define ' + define,
      '',
      '\n'.join(externs),
      '',
      '#endif  // ' + define])
  header += '\n'

  with open(os.path.join(output_dir, base_name + '.h'), 'w') as f:
    f.write(header)

  # Write cc file.
  def EscapeLine(line):
    return line.replace('\\', '\\\\').replace('"', '\\"')

  definitions = []
  for name, contents in global_string_map.iteritems():
    lines = []
    if '\n' not in contents:
      lines = ['    "%s"' % EscapeLine(contents)]
    else:
      for line in contents.split('\n'):
        lines += ['    "%s\\n"' % EscapeLine(line)]
    definitions += ['const char %s[] =\n%s;' % (name, '\n'.join(lines))]

  cc = '\n'.join([
      copyright_header,
      '',
      '#include "%s"' % (dir_from_src + '/' + base_name + '.h'),
      '',
      '\n'.join(definitions)])
  cc += '\n'

  with open(os.path.join(output_dir, base_name + '.cc'), 'w') as f:
    f.write(cc)