summaryrefslogtreecommitdiffstats
path: root/chromium/tools/oobe/generate_screen_template.py
blob: 5430447015f1ad5ad82d8f14caf4dd30fca98c6e (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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
#!/usr/bin/env python3
# Copyright 2023 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Generate sample ChromeOS OOBE screen with a given name.

Screen will implement all needed interfaces on the C++ side and will be included
in the corresponding BUILD files.

Script will generate sample JS and HTML files that user will be able to display
in the OOBE's WebView. Corresponding BUILD files will be updated.

If --no-webview flag is specified previous step will be skipped.

After generation is complete user still needs to manually insert screen into the
OOBE's wizard controller flow and add WebView content to the screens.js file.

usage: generate_screen_template.py [-h] [--no-webview] name

positional arguments:
  name          Name of a new screen. Expected to be in the camel case
                (e.g. MarketingOptIn). No "Screen" suffix is needed.

options:
  -h, --help    show this help message and exit
  --no-webview  Indicates whether user wants to skip creation of JS/HTML files.
                (default: False)
"""

import argparse
import logging
import os
import re
import subprocess
import sys

# Configure logging with timestamp and log level.
logging.basicConfig(level=logging.INFO,
                    format="[%(asctime)s:%(levelname)s] %(message)s")

if __name__ == '__main__':
  # Need to add directories with other scripts to the PATH variable to be able
  # to use them inside the tools/oobe folder.
  sys.path.append(os.path.abspath(os.path.join(sys.path[0], '..')))
import sort_sources


def GetGitRoot() -> str:
  """Retrieves absolute path to the repository root.

  Returns:
    An absolute path to the repository root in utf-8.
  """
  job = subprocess.Popen(['git', 'rev-parse', '--show-toplevel'],
                         stdout=subprocess.PIPE)
  out, err = job.communicate()
  if job.returncode != 0:
    logging.error('Error getting a git root: %s', err.decode('utf-8'))
    sys.exit(1)
  return out.decode('utf-8').strip()


GIT_ROOT = GetGitRoot()
SCREEN_GN_FILE_PATH = os.path.join(GIT_ROOT, 'chrome/browser/ash/BUILD.gn')
HANDLER_GN_FILE_PATH = os.path.join(GIT_ROOT, 'chrome/browser/ui/BUILD.gn')
WEBVIEW_JS_LIBRARY_GN_FILE_PATH = os.path.join(
    GIT_ROOT, 'chrome/browser/resources/chromeos/login/screens/common/BUILD.gn')
WEBVIEW_GN_FILE_PATH = os.path.join(
    GIT_ROOT, 'chrome/browser/resources/chromeos/login/BUILD.gn')


def IsCamelCase(screen_name: str) -> bool:
  """Checks whether new screen's name is in the camel case.

  Args:
    screen_name: A string that represents new screen name.

  Returns:
    A boolean value that represents whether given screen name is in the camel
    case.
  """
  return re.match('^([A-Z][a-z]+)+$', screen_name)


def GetScreenNameWords(screen_name: str) -> list[str]:
  """Breaks camel-case screen name into the words.

  Splits given camel case string into the logical lexems thath will be used to
  substitute new screen's name inside the generated C++/JS files.

  Args:
    screen_name: A string that represents new screen name in camel case.

  Returns:
    An array of strings that represent logical lexems in a given camel case
    screen name.
  """
  return re.sub('([A-Z][a-z]+)', r' \1', re.sub('([A-Z]+)', r' \1',
                                                screen_name)).split()


def FindAndReplace(name_words: list[str], file_path: str):
  """Applies set of replace rules to a file.

  Reads content of a file from a given path and applies set of replace rules
  to it's content. Overrides file content in the end.

  Args:
    name_words: An array of strings that represents logical lexems of a new
      screen's name.
    file_path: An absolute path to a file.
  """
  rules = [
      # Update placeholder class camel case name to the corresponding new
      # screen's name. E.g. `class PlaceholderScreen`` will become
      # `class MyNewScreen`.`
      lambda content: re.sub('Placeholder', ''.join(name_words), content),

      # Update include guards.
      lambda content: re.sub('PLACEHOLDER', '_'.join(
          word.upper() for word in name_words), content),

      # Update include paths for both screen and handler. This simple substitute
      # should be sufficient because new CPP files will be in the same folder
      # with their copies.
      lambda content: re.sub('placeholder_screen', ('_'.join(
          word.lower() for word in name_words) + '_screen'), content),

      # Update screen id inside the handler and element id inside the JS file.
      lambda content: re.sub('placeholder', '-'.join(
          word.lower() for word in name_words), content)
  ]

  with open(file_path, encoding='utf-8') as f:
    content = f.read()
    for rule in rules:
      content = rule(content)

  with open(file_path, mode='w', encoding='utf-8', newline='\n') as f:
    f.write(content)

  logging.info('Updated source file: %s', file_path)


def UpdateGnFile(name_words: list[str], gn_file_path: str):
  """Updates given GN file with the new include rules.

  Tries to find one of the RegEx rules in each line of the GN file and inserts
  new lines right after it. Sorts sources of the update GN file.

  Args:
    name_words: An array of strings that represents logical lexems of a new
      screen's name.
    gn_file_path: An absolute path to a GN file.
  """
  with open(gn_file_path, encoding='utf-8') as f:
    content = f.readlines()

  result = []
  for line in content:
    result.append(line)
    is_cpp_include = re.search(r'placeholder_screen.*\.h', line)
    is_js_include = re.search(r'placeholder.js', line)
    if is_cpp_include or is_js_include:
      new_file = re.sub('placeholder',
                        '_'.join(word.lower() for word in name_words), line)
      if is_cpp_include:
        result.append(re.sub('\.h', '.cc', new_file))
      result.append(new_file)

  with open(gn_file_path, mode='w', encoding='utf-8', newline='\n') as f:
    f.writelines(result)

  # Currently, works only with the CPP includes.
  sort_sources.ProcessFile(gn_file_path, should_confirm=False)

  logging.info('Updated GN file: %s', gn_file_path)


def UpdateWebviewGnFile(name_words: list[str], gn_file_path: str):
  """Updates WebView GN file.

  It does the following steps;
    1) If ":placeholder" rule found it adds new rule right after it.
    2) If "js_library("placeholder")" rule found function copies it's content,
       replaces all needed names and pastes result right after an original rule.
    3) If "placeholder.js" rule found it adds new rule right after it.

  This function doesn't sort sources order inside the GN file, as sort_sources
  doesn't support JS files yet.

  Args:
    name_words: An array of strings that represents logical lexems of a new
      screen's name.
    gn_file_path: An absolute path to a GN file.
  """
  with open(gn_file_path, encoding='utf-8') as f:
    content = f.readlines()

  result = []
  inside_closure_rule = False
  closure = []
  for line in content:
    result.append(line)
    if inside_closure_rule:
      closure.append(line)
      if re.match('}', line):
        inside_closure_rule = False
        result.append('\n')
        for closure_line in closure:
          if re.search('placeholder', closure_line):
            result.append(
                re.sub('placeholder',
                       '_'.join(word.lower() for word in name_words),
                       closure_line))
          else:
            result.append(closure_line)
    else:
      if re.search(':placeholder', line) or re.search(r'"placeholder.js"',
                                                      line):
        result.append(
            re.sub(r'placeholder',
                   '_'.join(word.lower() for word in name_words), line))
      elif re.search(r'js_library\("placeholder"\)', line):
        inside_closure_rule = True
        closure.append(line)

  with open(gn_file_path, mode='w', encoding='utf-8', newline='\n') as f:
    f.writelines(result)

  logging.info('Updated GN file: %s', gn_file_path)


def FindPlacholderFilesPaths(globs: list[str]) -> list[str]:
  """Finds placeholder files inside git repository with the git grep.

  Args:
    globs: List of strings that represents expected file extensions.

  Returns:
    An array of string paths to the placeholder files.

  Raises:
    Exception if subprocess failed.
  """
  job = subprocess.Popen(
      ['git', 'grep', '-E', '--name-only', 'PlaceholderScreen', '--'] + globs,
      stdout=subprocess.PIPE,
      cwd=GIT_ROOT)
  out, err = job.communicate()
  if job.returncode != 0:
    raise Exception(f'Error executing git grep: {err.decode("utf-8")}')

  return [path.decode('utf-8') for path in out.splitlines()]


def CopyPlaceholderFile(path: str, new_file_path: str):
  """Executes cp command to create a copy of the placeholder file.

  Args:
    path: Path to the original plachoolder file.
    new_file_path: Path to a new file.

  Raises:
    Exception if subprocess failed.
  """
  job = subprocess.Popen(['cp', path, new_file_path], cwd=GIT_ROOT)
  _, err = job.communicate()
  if job.returncode != 0:
    raise Exception(f'Error copying files: {err.decode("utf-8")}')

  logging.info('Created new file: %s', new_file_path)


def GenerateCppFiles(name_words: list[str]):
  """Generates header and source files for screen and handler classes.

  This function does the following operations:
    1) Copy content of the PlaceholderScreen class, which implements all needed
       intefaces, into a new files with a given screen name.
    2) Do a series of find and replace operations to move
       includes/header guards/class names/etc to a new name.
    3) Add new files to the corresponding BUILD.gn files, sort build list to
       preserve a right order.

  Args:
    name_words: An array of strings that represents logical lexems of a new
      screen's name.
  """
  cpp_globs = ['*.cc', '*.h']
  paths = FindPlacholderFilesPaths(cpp_globs)
  assert (
      len(paths) == 4
  ), 'There should be only 4 CPP files to copy (screen/handler .h and .cc)'

  for path in paths:
    new_file_path = re.sub('placeholder',
                           '_'.join(s.lower() for s in name_words), path)

    CopyPlaceholderFile(path, new_file_path)

    FindAndReplace(name_words, os.path.join(GIT_ROOT, new_file_path))

  cpp_gn_files = [SCREEN_GN_FILE_PATH, HANDLER_GN_FILE_PATH]
  for name in cpp_gn_files:
    UpdateGnFile(name_words, name)


def GenerateWebviewFiles(name_words: list[str]):
  """Generates JS and HTML files for a new screen.

  This function does the following operations:
    1) Copy content of the placeholder.js and placeholder.html files
    2) Do a find and replace operations over new JS file.
    3) Add JS file to the corresponding BUILD.gn file, generate closure rule
       for it.

  JS BUILD.gn rules currently will not be sorted, as sort_sources doesn't
  support those extensions.

  Args:
    name_words: An array of strings that represents logical lexems of a new
      screen's name.
  """
  webview_globs = ['*.js']
  paths = FindPlacholderFilesPaths(webview_globs)

  assert (len(paths) == 1), 'Only 1 JS file should be found'

  # HTML file doesn't contain any words that could be used verify it's
  # correctness, so we can generate it's path from the corresponding JS file.
  paths.append(re.sub(r'\.js', '.html', paths[0]))

  for path in paths:
    new_file_path = re.sub('placeholder',
                           '_'.join(s.lower() for s in name_words), path)

    CopyPlaceholderFile(path, new_file_path)

    if new_file_path[-3:] == '.js':
      FindAndReplace(name_words, os.path.join(GIT_ROOT, new_file_path))

  UpdateGnFile(name_words, WEBVIEW_GN_FILE_PATH)
  UpdateWebviewGnFile(name_words, WEBVIEW_JS_LIBRARY_GN_FILE_PATH)


def GenerateScreen(name_words: list[str], no_webview: bool):
  """Executes new screen generation flow.

  Args:
    name_words: An array of strings that represents logical lexems of a new
      screen's name.
    no_webview: True if WebView files should not be generated.
  """
  logging.info('Generating screen and handler files')
  GenerateCppFiles(name_words)
  if no_webview:
    logging.info('--no-webview flag is specified, skipping WebView generation')
    return
  logging.info('Generating WebView files')
  GenerateWebviewFiles(name_words)


def main():
  parser = argparse.ArgumentParser(
      formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  parser.add_argument(
      'name',
      help="""Name of a new screen. Expected to be in the camel case
      (e.g. MarketingOptIn). No "Screen" suffix is needed.""")
  parser.add_argument(
      '--no-webview',
      help='Indicates whether user wants to skip creation of JS/HTML files.',
      action='store_true')

  options = parser.parse_args()
  if not IsCamelCase(options.name):
    logging.error('Screen name must be in the camel case')
    parser.print_help()
    return 1
  screen_name_words = GetScreenNameWords(options.name)
  if screen_name_words[-1].lower() == 'screen':
    logging.error(
        '"Screen" suffix is not needed, it will be added automatically')
    parser.print_help()
    return 1

  # Catching all kinds of errors here to generate non-zero exit code.
  # This might be used in future to add a test to the CQ to verify that script
  # works properly.
  try:
    GenerateScreen(screen_name_words, options.no_webview)
  except Exception as ex:
    logging.error(str(ex))
    return 1

  return 0


if __name__ == '__main__':
  sys.exit(main())