xref: /aosp_15_r20/external/perfetto/ui/format-sources (revision 6dbdd20afdafa5e3ca9b8809fa73465d530080dc)
1#!/usr/bin/env python3
2# Copyright (C) 2024 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
19import subprocess
20
21UI_DIR = os.path.abspath(os.path.dirname(__file__))
22ROOT_DIR = os.path.dirname(UI_DIR)
23PRETTIER_PATH = os.path.join(ROOT_DIR, 'ui/node_modules/.bin/prettier')
24ESLINT_PATH = os.path.join(ROOT_DIR, 'ui/node_modules/.bin/eslint')
25
26
27def main():
28  parser = argparse.ArgumentParser()
29  parser.add_argument('--check-only', action='store_true')
30  parser.add_argument('--no-prettier', action='store_true')
31  parser.add_argument('--no-eslint', action='store_true')
32  parser.add_argument(
33      '--all',
34      action='store_true',
35      help='Prettify all .ts sources, not just the changed ones')
36  parser.add_argument('filelist', nargs='*')
37  args = parser.parse_args()
38
39  # We want to execute all the commands relative to UI_DIR, because eslint looks
40  # for eslintrc in cwd. However, the user might pass paths that are relative to
41  # the current cwd, which might be != UI_DIR.
42  # So before running chdir relativize all the passed paths to UI_DIR
43  filelist = [
44      os.path.relpath(os.path.abspath(x), UI_DIR) for x in args.filelist
45  ]
46  os.chdir(UI_DIR)
47
48  # Need to add 'node' to the search path.
49  os.environ['PATH'] += os.pathsep + os.path.join(ROOT_DIR, 'tools')
50
51  if not os.path.exists(PRETTIER_PATH):
52    print('Cannot find %s' % PRETTIER_PATH)
53    print('Run tools/install-build-deps --ui')
54    return 1
55
56  with open('.prettierignore', 'r') as f:
57    ignorelist = set(f.read().strip().split('\n'))
58
59  all_files = set()
60  for root, _dirs, files in os.walk('src'):
61    if root in ignorelist:
62      continue
63    for file in files:
64      file_path = os.path.join(root, file)
65      if os.path.splitext(file)[1].lower() in ['.ts', '.js', '.scss']:
66        all_files.add(file_path)
67
68  files_to_check = []
69  git_cmd = []
70  if args.all:
71    files_to_check = list(all_files)
72  elif filelist:
73    files_to_check = filelist
74  else:
75    upstream_branch = get_upstream_branch()
76    git_cmd = ['git', 'diff', '--name-only', upstream_branch]
77    git_output = subprocess.check_output(git_cmd, text=True).strip()
78    changed_files = set(git_output.split('\n') if git_output else [])
79    changed_files = [os.path.relpath(x, 'ui') for x in changed_files]
80    files_to_check = all_files.intersection(changed_files)
81
82  prettier_args = ['--log-level=warn']
83  eslint_args = []
84  if args.check_only:
85    prettier_args += ['--check']
86  else:
87    eslint_args += ['--fix']
88    prettier_args += ['--write']
89
90  if len(files_to_check) == 0:
91    if not args.check_only:
92      # Be quiet when invoked by git cl presubmit.
93      print('No changed files detected by `%s`' % ' '.join(git_cmd))
94      print('Pass --all to prettify all ts/js/scss files in the repo')
95    return 0
96
97  # Run prettier first
98  if not args.no_prettier:
99    print('Running prettier on %d files' % len(files_to_check))
100    call_or_die([PRETTIER_PATH] + prettier_args + list(files_to_check))
101
102  # Then run eslint (but not on .scss)
103  if not args.no_eslint:
104    ts_js_only = lambda f: f.endswith('.ts') or f.endswith('.js')
105    files_to_check = list(filter(ts_js_only, files_to_check))
106    if len(files_to_check) > 0:
107      print('Running eslint on %d files' % len(files_to_check))
108      call_or_die([ESLINT_PATH] + eslint_args + files_to_check)
109
110
111# Like subprocess.check_call, but in case of errors dies without printing a
112# useless stacktrace that just muddies the stdout.
113def call_or_die(cmd):
114  try:
115    subprocess.check_call(cmd)
116  except subprocess.CalledProcessError as ex:
117    print('`%s` returned %d' % (' '.join(cmd)[:128], ex.returncode))
118    sys.exit(ex.returncode)
119
120
121def get_upstream_branch():
122  try:
123    cmd = ['git', 'rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}']
124    res = subprocess.check_output(cmd, text=True, stderr=subprocess.DEVNULL)
125    return res.strip()
126  except subprocess.CalledProcessError:
127    return 'origin/main'
128
129
130if __name__ == '__main__':
131  sys.exit(main())
132