Commit 7539399a authored by Shik Chen's avatar Shik Chen Committed by Commit Bot

CCA: Switch python style to PEP8

Chromium switched to PEP8 for new code. Reformatted with the new config,
and rename function from CamelCase to snake_case.
https://chromium.googlesource.com/chromium/src/+/master/styleguide/python/python.md

Bug: 1019581
Test: yapf utils/cca.py
Tricium: disable
Change-Id: I9607653182cd28c6df137bf9b4d2fc07b23aa438
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1994851Reviewed-by: default avatarWei Lee <wtlee@chromium.org>
Commit-Queue: Shik Chen <shik@chromium.org>
Cr-Commit-Position: refs/heads/master@{#730082}
parent ad2a47ee
[style] [style]
based_on_style = chromium based_on_style = pep8
...@@ -18,273 +18,281 @@ import time ...@@ -18,273 +18,281 @@ import time
@functools.lru_cache(1) @functools.lru_cache(1)
def GetChromiumRoot(): def get_chromium_root():
path = os.path.realpath('../../../../../') path = os.path.realpath('../../../../../')
assert os.path.basename(path) == 'src' assert os.path.basename(path) == 'src'
return path return path
def ShellJoin(cmd): def shell_join(cmd):
return ' '.join(shlex.quote(c) for c in cmd) return ' '.join(shlex.quote(c) for c in cmd)
def Run(args): def run(args):
logging.debug(f'$ {ShellJoin(args)}') logging.debug(f'$ {shell_join(args)}')
subprocess.check_call(args) subprocess.check_call(args)
def BuildLocaleStrings(): def build_locale_strings():
grit_cmd = [ grit_cmd = [
os.path.join(GetChromiumRoot(), 'tools/grit/grit.py'), os.path.join(get_chromium_root(), 'tools/grit/grit.py'),
'-i', '-i',
'src/strings/camera_strings.grd', 'src/strings/camera_strings.grd',
'build', 'build',
'-o', '-o',
'build/strings', 'build/strings',
] ]
Run(grit_cmd) run(grit_cmd)
def BuildMojomBindings(mojom_bindings): def build_mojom_bindings(mojom_bindings):
pylib = os.path.join(GetChromiumRoot(), 'mojo/public/tools/bindings/pylib') pylib = os.path.join(get_chromium_root(),
sys.path.insert(0, pylib) 'mojo/public/tools/bindings/pylib')
# pylint: disable=import-error,import-outside-toplevel sys.path.insert(0, pylib)
from mojom.parse.parser import Parse # pylint: disable=import-error,import-outside-toplevel
from mojom.parse.parser import Parse
mojom_paths = set()
mojom_paths = set()
def AddPath(mojom):
path = os.path.join(GetChromiumRoot(), mojom) def add_path(mojom):
if path in mojom_paths: path = os.path.join(get_chromium_root(), mojom)
return if path in mojom_paths:
mojom_paths.add(path) return
mojom_paths.add(path)
with open(path) as f:
code = f.read() with open(path) as f:
ast = Parse(code, path) code = f.read()
for imp in ast.import_list: ast = Parse(code, path)
AddPath(imp.import_filename) for imp in ast.import_list:
add_path(imp.import_filename)
for binding in mojom_bindings:
mojom = re.sub('-lite.js$', '', binding) for binding in mojom_bindings:
AddPath(mojom) mojom = re.sub('-lite.js$', '', binding)
add_path(mojom)
# It's needed for generating mojo_bindings_lite.js.
AddPath('mojo/public/interfaces/bindings/interface_control_messages.mojom') # It's needed for generating mojo_bindings_lite.js.
add_path(
if not os.path.exists('build/mojo'): 'mojo/public/interfaces/bindings/interface_control_messages.mojom')
os.makedirs('build/mojo')
if not os.path.exists('build/mojo'):
generator = os.path.join( os.makedirs('build/mojo')
GetChromiumRoot(),
'mojo/public/tools/bindings/mojom_bindings_generator.py') generator = os.path.join(
get_chromium_root(),
precompile_cmd = [ 'mojo/public/tools/bindings/mojom_bindings_generator.py')
generator,
'--use_bundled_pylibs', precompile_cmd = [
'precompile', generator,
'-o', '--use_bundled_pylibs',
'build/mojo', 'precompile',
] '-o',
Run(precompile_cmd) 'build/mojo',
]
parse_cmd = [ run(precompile_cmd)
generator,
'--use_bundled_pylibs', parse_cmd = [
'parse', generator,
'-d', '--use_bundled_pylibs',
GetChromiumRoot(), 'parse',
'-o', '-d',
'build/mojo', get_chromium_root(),
] + list(mojom_paths) '-o',
Run(parse_cmd) 'build/mojo',
] + list(mojom_paths)
generate_cmd = [ run(parse_cmd)
generator,
'--use_bundled_pylibs', generate_cmd = [
'generate', generator,
'-d', '--use_bundled_pylibs',
GetChromiumRoot(), 'generate',
'-I', '-d',
GetChromiumRoot(), get_chromium_root(),
'--bytecode_path', '-I',
'build/mojo', get_chromium_root(),
'-o', '--bytecode_path',
'build/mojo', 'build/mojo',
'-g', '-o',
'javascript', 'build/mojo',
'--js_bindings_mode', '-g',
'new', 'javascript',
] + list(mojom_paths) '--js_bindings_mode',
Run(generate_cmd) 'new',
] + list(mojom_paths)
generate_binding_lite_cmd = [ run(generate_cmd)
os.path.join(GetChromiumRoot(),
('mojo/public/tools/bindings/' + generate_binding_lite_cmd = [
'concatenate_and_replace_closure_exports.py')), os.path.join(get_chromium_root(),
os.path.join(GetChromiumRoot(), 'mojo/public/js/bindings_lite.js'), ('mojo/public/tools/bindings/' +
os.path.join(GetChromiumRoot(), 'mojo/public/js/interface_support.js'), 'concatenate_and_replace_closure_exports.py')),
('build/mojo/mojo/public/interfaces/' + os.path.join(get_chromium_root(), 'mojo/public/js/bindings_lite.js'),
'bindings/interface_control_messages.mojom-lite.js'), os.path.join(get_chromium_root(),
'build/mojo/mojo_bindings_lite.js', 'mojo/public/js/interface_support.js'),
] ('build/mojo/mojo/public/interfaces/' +
Run(generate_binding_lite_cmd) 'bindings/interface_control_messages.mojom-lite.js'),
'build/mojo/mojo_bindings_lite.js',
]
def BuildCCA(overlay=None, key=None): run(generate_binding_lite_cmd)
with open('BUILD.gn') as f:
mojom_bindings = re.findall(r'root_gen_dir/(.*mojom-lite\.js)', f.read())
mojo_files = ['mojo_bindings_lite.js'] + mojom_bindings def build_cca(overlay=None, key=None):
with open('BUILD.gn') as f:
# TODO(shik): Check mtime and rebuild them if the source is updated. mojom_bindings = re.findall(r'root_gen_dir/(.*mojom-lite\.js)',
if not os.path.exists('build/strings'): f.read())
BuildLocaleStrings() mojo_files = ['mojo_bindings_lite.js'] + mojom_bindings
if any(not os.path.exists(os.path.join('build/mojo', f)) for f in mojo_files):
BuildMojomBindings(mojom_bindings) # TODO(shik): Check mtime and rebuild them if the source is updated.
if not os.path.exists('build/strings'):
shutil.rmtree('build/camera', ignore_errors=True) build_locale_strings()
dir_util.copy_tree('src', 'build/camera') if any(not os.path.exists(os.path.join('build/mojo', f))
for f in mojo_files: for f in mojo_files):
shutil.copy2(os.path.join('build/mojo', f), 'build/camera/js/mojo') build_mojom_bindings(mojom_bindings)
dir_util.copy_tree('build/strings', 'build/camera')
shutil.rmtree('build/camera', ignore_errors=True)
if overlay == 'dev': dir_util.copy_tree('src', 'build/camera')
dir_util.copy_tree('utils/dev', 'build/camera') for f in mojo_files:
shutil.copy2(os.path.join('build/mojo', f), 'build/camera/js/mojo')
git_cmd = ['git', 'rev-parse', 'HEAD'] dir_util.copy_tree('build/strings', 'build/camera')
commit_hash = subprocess.check_output(git_cmd, text=True).strip()[:8]
timestamp = time.strftime("%F %T") if overlay == 'dev':
dir_util.copy_tree('utils/dev', 'build/camera')
with open('src/manifest.json') as f:
manifest = json.load(f) git_cmd = ['git', 'rev-parse', 'HEAD']
manifest['version_name'] = f'Dev {commit_hash} @ {timestamp}' commit_hash = subprocess.check_output(git_cmd, text=True).strip()[:8]
if key is not None: timestamp = time.strftime("%F %T")
manifest['key'] = key
with open('build/camera/manifest.json', 'w') as f: with open('src/manifest.json') as f:
json.dump(manifest, f, indent=2) manifest = json.load(f)
manifest['version_name'] = f'Dev {commit_hash} @ {timestamp}'
if key is not None:
def Deploy(args): manifest['key'] = key
BuildCCA() with open('build/camera/manifest.json', 'w') as f:
cmd = [ json.dump(manifest, f, indent=2)
'rsync',
'--archive',
'--checksum', def deploy(args):
'--chown=chronos:chronos', build_cca()
'--omit-dir-times', cmd = [
'--perms', 'rsync',
'--verbose', '--archive',
'build/camera/', '--checksum',
f'{args.device}:/opt/google/chrome/resources/chromeos/camera', '--chown=chronos:chronos',
] '--omit-dir-times',
Run(cmd) '--perms',
'--verbose',
'build/camera/',
def Test(args): f'{args.device}:/opt/google/chrome/resources/chromeos/camera',
assert 'CCAUI' not in args.device, ( ]
'The first argument should be <device> instead of a test name pattern.') run(cmd)
tast_cmd = ['local_test_runner'] + args.pattern
cmd = [
'ssh', def test(args):
args.device, assert 'CCAUI' not in args.device, (
ShellJoin(tast_cmd), 'The first argument should be <device> instead of a test name pattern.'
] )
Run(cmd) tast_cmd = ['local_test_runner'] + args.pattern
cmd = [
'ssh',
def Pack(args): args.device,
assert os.path.exists(args.key), f'There is no key at {args.key}' shell_join(tast_cmd),
]
pubkey = None run(cmd)
if shutil.which('openssl'):
openssl_cmd = ['openssl', 'rsa', '-in', args.key, '-pubout']
openssl_output = subprocess.check_output( def pack(args):
openssl_cmd, stderr=subprocess.DEVNULL, text=True) assert os.path.exists(args.key), f'There is no key at {args.key}'
pubkey = ''.join(openssl_output.splitlines()[1:-1])
BuildCCA(overlay='dev', key=pubkey) pubkey = None
if shutil.which('openssl'):
if os.path.exists('build/camera.crx'): openssl_cmd = ['openssl', 'rsa', '-in', args.key, '-pubout']
os.remove('build/camera.crx') openssl_output = subprocess.check_output(openssl_cmd,
pack_cmd = [ stderr=subprocess.DEVNULL,
'google-chrome', text=True)
'--disable-gpu', # suppress an error about sandbox on gpu process pubkey = ''.join(openssl_output.splitlines()[1:-1])
'--pack-extension=build/camera', build_cca(overlay='dev', key=pubkey)
shlex.quote(f'--pack-extension-key={args.key}'),
] if os.path.exists('build/camera.crx'):
if shutil.which('xvfb-run'): os.remove('build/camera.crx')
# Run it in a virtual X server environment pack_cmd = [
pack_cmd.insert(0, 'xvfb-run') 'google-chrome',
Run(pack_cmd) '--disable-gpu', # suppress an error about sandbox on gpu process
assert os.path.exists('build/camera.crx') '--pack-extension=build/camera',
shutil.move('build/camera.crx', args.output) shlex.quote(f'--pack-extension-key={args.key}'),
]
# TODO(shik): Add an option to deploy/install the packed crx on device if shutil.which('xvfb-run'):
# Run it in a virtual X server environment
pack_cmd.insert(0, 'xvfb-run')
def Lint(args): run(pack_cmd)
root = GetChromiumRoot() assert os.path.exists('build/camera.crx')
node = os.path.join(root, 'third_party/node/linux/node-linux-x64/bin/node') shutil.move('build/camera.crx', args.output)
eslint = os.path.join(root,
'third_party/node/node_modules/eslint/bin/eslint.js') # TODO(shik): Add an option to deploy/install the packed crx on device
subprocess.call([node, eslint, 'src/js'])
def lint(args):
def ParseArgs(args): root = get_chromium_root()
parser = argparse.ArgumentParser(description='CCA developer tools.') node = os.path.join(root, 'third_party/node/linux/node-linux-x64/bin/node')
parser.add_argument('--debug', action='store_true') eslint = os.path.join(
subparsers = parser.add_subparsers() root, 'third_party/node/node_modules/eslint/bin/eslint.js')
subprocess.call([node, eslint, 'src/js'])
deploy_parser = subparsers.add_parser(
'deploy', help='deploy to device', description='Deploy CCA to device.')
deploy_parser.add_argument('device') def parse_args(args):
deploy_parser.set_defaults(func=Deploy) parser = argparse.ArgumentParser(description='CCA developer tools.')
parser.add_argument('--debug', action='store_true')
test_parser = subparsers.add_parser( subparsers = parser.add_subparsers()
'test', help='run tests', description='Run CCA tests on device.')
test_parser.add_argument('device') deploy_parser = subparsers.add_parser('deploy',
test_parser.add_argument( help='deploy to device',
'pattern', description='Deploy CCA to device.')
nargs='*', deploy_parser.add_argument('device')
default=['camera.CCAUI*'], deploy_parser.set_defaults(func=deploy)
help='test patterns. (default: camera.CCAUI*)')
test_parser.set_defaults(func=Test) test_parser = subparsers.add_parser('test',
help='run tests',
pack_parser = subparsers.add_parser( description='Run CCA tests on device.')
'pack', help='pack crx', description='Pack CCA into a crx.') test_parser.add_argument('device')
pack_parser.add_argument( test_parser.add_argument('pattern',
'-o', nargs='*',
'--output', default=['camera.CCAUI*'],
help='output file (default: build/camera.crx)', help='test patterns. (default: camera.CCAUI*)')
default='build/camera.crx') test_parser.set_defaults(func=test)
pack_parser.add_argument(
'-k', pack_parser = subparsers.add_parser('pack',
'--key', help='pack crx',
help='private key file (default: camera.pem)', description='Pack CCA into a crx.')
default='camera.pem') pack_parser.add_argument('-o',
pack_parser.set_defaults(func=Pack) '--output',
help='output file (default: build/camera.crx)',
lint_parser = subparsers.add_parser( default='build/camera.crx')
'lint', help='check code', description='Check coding styles.') pack_parser.add_argument('-k',
lint_parser.set_defaults(func=Lint) '--key',
parser.set_defaults(func=lambda _args: lint.print_help()) help='private key file (default: camera.pem)',
default='camera.pem')
return parser.parse_args(args) pack_parser.set_defaults(func=pack)
lint_parser = subparsers.add_parser('lint',
def Main(args): help='check code',
cca_root = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) description='Check coding styles.')
assert os.path.basename(cca_root) == 'camera' lint_parser.set_defaults(func=lint)
os.chdir(cca_root) parser.set_defaults(func=lambda _args: parser.print_help())
args = ParseArgs(args) return parser.parse_args(args)
log_level = logging.DEBUG if args.debug else logging.INFO
log_format = '%(asctime)s - %(levelname)s - %(funcName)s: %(message)s' def main(args):
logging.basicConfig(level=log_level, format=log_format) cca_root = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
assert os.path.basename(cca_root) == 'camera'
logging.debug(f'args = {args}') os.chdir(cca_root)
return args.func(args)
args = parse_args(args)
log_level = logging.DEBUG if args.debug else logging.INFO
log_format = '%(asctime)s - %(levelname)s - %(funcName)s: %(message)s'
logging.basicConfig(level=log_level, format=log_format)
logging.debug(f'args = {args}')
return args.func(args)
if __name__ == '__main__': if __name__ == '__main__':
sys.exit(Main(sys.argv[1:])) sys.exit(main(sys.argv[1:]))
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment