2025年4月

之前整理过如何快速的检出指定tag的chromium源码。
这次整理成python脚本,可以在当前目录直接运行。自动完成代码检出,并有出错重试的功能。

import argparse
import os
import time
import shutil

_gcl_context = """
solutions = [
  {
    "name": "src",
    "url": "https://chromium.googlesource.com/chromium/src.git",
    "managed": False,
    "custom_deps": {},
    "custom_vars": {"checkout_pgo_profiles": True,},
  },
]
"""


def delete_error_git_dir(path):
    for dirpath, dirnames, _ in os.walk(path):
        for dirname in dirnames:
            full_dir_path = os.path.join(dirpath, dirname)
            if dirname == ".git" and len(
                    os.listdir(os.path.dirname(full_dir_path))) == 1:
                print(
                    f"Deleting error .git directory: {full_dir_path} and its contents..."
                )
                try:
                    if os.name == "nt":
                        os.system(f"rmdir /s /q {full_dir_path}")
                    else:
                        shutil.rmtree(full_dir_path)
                except OSError as e:
                    print(f"Error deleting {full_dir_path}: {str(e)}")
                    exit(1)


def _run_command_with_success(cmd):
    while 0 != os.system(cmd):
        print(f"Command:'{cmd}' failed! Start retry!")
        delete_error_git_dir("src")
    print(f"Command:'{cmd}' success!")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Checkout chromium code with tag.")
    parser.add_argument("tag", type=str, help="Tag to checkout.")
    parser.add_argument("-u",
                        "--upgrade",
                        action="store_true",
                        help="Upgrade existing code to a specified tag.")
    parser.add_argument(
        "--os",
        type=str,
        help="Specify the target platform for Chromium. For example: --os mac."
    )
    args = parser.parse_args()
    if not args.tag:
        parser.error('the "tag" argument is necessary')

    start = time.time()
    with open(".gclient", "w") as gcl:
        gcl.write(_gcl_context)
        if args.os:
            gcl.write(f'target_os = ["{args.os}"]\n')

    # checkout chromium
    if args.upgrade and os.path.exists("src"):
        print(f"Start upgrade chromium code to tag {args.tag} !")
        _run_command_with_success(
            f"git -C \"src\" fetch origin refs/tags/{args.tag}")
        os.system(f"git -C \"src\" checkout -b local_{args.tag} {args.tag}")
    elif os.path.exists("src"):
        print("Have 'src' directory, so skip checkout tag!")
    else:
        print(f"Start checkout chromium tag {args.tag} !")
        _run_command_with_success(
            f"git clone --depth 2 -b {args.tag} https://chromium.googlesource.com/chromium/src.git"
        )

    # run hook
    print("Start run hook!")
    _run_command_with_success(
        "gclient sync -D --with_branch_heads --with_tags")

    print(
        f"checkout chromium {args.tag} Ok! Use time:{time.strftime('%H:%M:%S', time.gmtime(time.time() - start))} !"
    )