1# Copyright 2024 The Chromium Authors 2# Use of this source code is governed by a BSD-style license that can be 3# found in the LICENSE file. 4""" Reads version files from the chromium source code. """ 5 6import argparse 7import logging 8import os.path 9 10from typing import Dict 11 12from common import DIR_SRC_ROOT 13 14 15def chrome_version() -> Dict[str, int]: 16 """ Returns a replica of //chrome/VERSION, crashes if the file does not 17 exist. This function does not assume the existence of all the fields, but 18 treats missing ones as 0; on the other hand, the unexpected fields would be 19 also ignored.""" 20 file = os.path.join(DIR_SRC_ROOT, 'chrome', 'VERSION') 21 assert os.path.exists(file) 22 result = {} 23 24 def parse_line(field: str, line: str) -> bool: 25 if line.startswith(field.upper() + '='): 26 result[field] = int(line[len(field.upper()) + 1:].rstrip()) 27 return True 28 return False 29 30 with open(file, 'r') as reader: 31 for line in reader: 32 if (not parse_line('major', line) 33 and not parse_line('minor', line) 34 and not parse_line('build', line) 35 and not parse_line('patch', line)): 36 logging.warning('Unexpected line %s in the VERSION file', line) 37 return result 38 39 40def chrome_version_str() -> str: 41 """ Returns the chrome_version in a string representation. """ 42 version = chrome_version() 43 return (f'{version["major"]}.{version["minor"]}.' 44 f'{version["build"]}.{version["patch"]}') 45 46 47def _load_git_args() -> argparse.Namespace: 48 parser = argparse.ArgumentParser() 49 parser.add_argument('--git-revision', default=None) 50 parser.add_argument('--gerrit-issue', type=int, default=None) 51 parser.add_argument('--gerrit-patchset', type=int, default=None) 52 parser.add_argument('--buildbucket-id', type=int, default=None) 53 args, _ = parser.parse_known_args() 54 # The args look like 55 # '--git-revision=e98127af84bf5b33a6e657c90dfd3f3a731eb28c' 56 # '--gerrit-issue=5009604' 57 # '--gerrit-patchset=16' 58 # '--buildbucket-id=8756180599882888289' 59 # on a try build. CI builds have only git-revision. 60 return args 61 62 63_GIT_ARGS: argparse.Namespace = _load_git_args() 64 65 66def is_try_build() -> bool: 67 """ Returns whether current build is running as a try-build, or unmerged 68 change. This function crashes if the info cannot be retrieved. """ 69 assert _GIT_ARGS.git_revision 70 return _GIT_ARGS.gerrit_issue is not None 71 72 73def git_revision() -> str: 74 """ Returns the git revision to identify the current change list or the 75 commit info of the CI build. This function crashes if the info cannot be 76 retrieved. """ 77 assert _GIT_ARGS.git_revision 78 if not is_try_build(): 79 return _GIT_ARGS.git_revision 80 return (f'{_GIT_ARGS.git_revision}/{_GIT_ARGS.gerrit_issue}/' 81 f'{_GIT_ARGS.gerrit_patchset}') 82