chromium/ash/webui/settings/public/constants/gen_routes.py

#!/usr/bin/env python3
# Copyright 2022 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Helper tool to generate cpp header file with all routes paths.

All route paths are defined in `routes.mojom` as string constants.
Unfortunately there is no collection in the generated cpp binding that contains
all these strings. Instead of manually write all the routes in a cpp file, this
tool automatically generates it to avoid human errors.

"""

import argparse
import os
import pathlib
import sys

# Path of the <chromium>/src directory.
CHROMIUM_SRC_PATH = pathlib.Path(__file__).parents[5].resolve(strict=True)
if CHROMIUM_SRC_PATH.name != 'src':
    raise AssertionError(
        f'CHROMIUM_SRC_PATH "{CHROMIUM_SRC_PATH}" should end in "src".')

# Insert chromium mojom path to beginning to make sure we prefer this one.
# https://crbug.com/1422422
sys.path.insert(0, os.path.join(CHROMIUM_SRC_PATH, "mojo/public/tools/mojom"))
from mojom.generate.module import Constant
from mojom.generate.module import Module


def parse_arguments(arguments):
    parser = argparse.ArgumentParser()
    parser.add_argument('--gen_dir',
                        help='The generated files path for routes.mojom',
                        required=True)
    return parser.parse_args(arguments)


def main(args):
    parsed_args = parse_arguments(args)
    module_path = os.path.join(parsed_args.gen_dir, 'routes.mojom-module')

    with open(module_path, 'rb') as f:
        module = Module.Load(f)

    this_file_path = os.path.relpath(pathlib.Path(__file__), CHROMIUM_SRC_PATH)
    result = f'''// This file is autogenerated by {this_file_path}

// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef ASH_WEBUI_SETTINGS_PUBLIC_CONSTANTS_ROUTES_H_
#define ASH_WEBUI_SETTINGS_PUBLIC_CONSTANTS_ROUTES_H_

#include "ash/webui/settings/public/constants/routes.mojom.h"

namespace chromeos::settings {{

inline const char* const kPaths[] = {{
'''
    for c in module.constants:
        result += f'  mojom::{c.mojom_name},\n'
    result += '''
};

}  // namespace chromeos::settings

#endif  // ASH_WEBUI_SETTINGS_PUBLIC_CONSTANTS_ROUTES_H_
'''
    output_path = os.path.join(parsed_args.gen_dir, 'routes.h')
    with open(output_path, 'w') as f:
        f.write(result)


if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))