1#! /usr/bin/env nix-shell
2#! nix-shell -p common-updater-scripts python3
3#! nix-shell -i python
4
5import csv
6import json
7import re
8import shlex
9import subprocess
10from os.path import abspath, dirname, splitext
11from urllib.request import urlopen
12
13# CrOS version numbers look like this:
14# [<chrome-major-version>.]<tip-build>.<branch-build>.<branch-branch-build>
15#
16# As far as I can tell, branches are where internal Google
17# modifications are added to turn Chromium OS into Chrome OS, and
18# branch branches are used for fixes for specific devices. So for
19# Chromium OS they will always be 0. This is a best guess, and is not
20# documented.
21with urlopen('https://chromiumdash.appspot.com/cros/download_serving_builds_csv?deviceCategory=ChromeOS') as resp:
22 reader = csv.reader(map(bytes.decode, resp))
23 header = next(reader)
24 cr_stable_index = header.index('cr_stable')
25 cros_stable_index = header.index('cros_stable')
26 chrome_version = []
27 platform_version = []
28
29 for line in reader:
30 this_chrome_version_str = line[cr_stable_index]
31 if "no update" in this_chrome_version_str:
32 continue
33 this_chrome_version = list(map(int, this_chrome_version_str.split('.')))
34 this_platform_version = list(map(int, line[cros_stable_index].split('.')))
35 chrome_version = max(chrome_version, this_chrome_version)
36 platform_version = max(platform_version, this_platform_version)
37
38chrome_major_version = chrome_version[0]
39chromeos_tip_build = platform_version[0]
40release_branch = f'release-R{chrome_major_version}-{chromeos_tip_build}.B'
41
42# Determine the git revision.
43with urlopen(f'https://chromium.googlesource.com/chromiumos/platform2/+/refs/heads/{release_branch}?format=JSON') as resp:
44 resp.readline() # Remove )]}' header
45 rev = json.load(resp)['commit']
46
47# Determine the patch version by counting the commits that have been
48# added to the release branch since it forked off the chromeos branch.
49with urlopen(f'https://chromium.googlesource.com/chromiumos/platform2/+log/refs/heads/main..{rev}/vm_tools/sommelier?format=JSON') as resp:
50 resp.readline() # Remove )]}' header
51 branch_commits = json.load(resp)['log']
52 version = f'{chrome_major_version}.{len(branch_commits)}'
53
54# Update the version, git revision, and hash in sommelier's default.nix.
55subprocess.run(['update-source-version', 'sommelier', f'--rev={rev}', version])
56
57# Find the path to sommelier's default.nix, so Cargo.lock can be written
58# into the same directory.
59argv = ['nix-instantiate', '--eval', '--json', '-A', 'sommelier.meta.position']
60position = json.loads(subprocess.check_output(argv).decode('utf-8'))
61filename = re.match(r'[^:]*', position)[0]