@@ -0,0 +1,234 @@
1+#!/usr/bin/env nix-shell
2+#! nix-shell -i python3 -p bundix common-updater-scripts nix nix-prefetch-git python3 python3Packages.requests python3Packages.lxml python3Packages.click python3Packages.click-log
3+
4+import click
5+import click_log
6+import os
7+import re
8+import logging
9+import subprocess
10+import json
11+import pathlib
12+from typing import Iterable
13+
14+import requests
15+from xml.etree import ElementTree
16+
17+logger = logging.getLogger(__name__)
18+
19+
20+class GitLabRepo:
21+ def __init__(self, owner: str, repo: str):
22+ self.owner = owner
23+ self.repo = repo
24+
25+ @property
26+ def url(self):
27+ return f"https://gitlab.com/{self.owner}/{self.repo}"
28+
29+ @property
30+ def tags(self) -> Iterable[str]:
31+ r = requests.get(self.url + "/tags?format=atom", stream=True)
32+
33+ tree = ElementTree.fromstring(r.content)
34+ return sorted((e.text for e in tree.findall(
35+ '{http://www.w3.org/2005/Atom}entry/{http://www.w3.org/2005/Atom}title')), reverse=True)
36+
37+ def get_git_hash(self, rev: str):
38+ out = subprocess.check_output(['nix-prefetch-git', self.url, rev])
39+ j = json.loads(out)
40+ return j['sha256']
41+
42+ def get_deb_url(self, flavour: str, version: str, arch: str = 'amd64') -> str:
43+ """
44+ gitlab builds debian packages, which we currently need as we don't build the frontend on our own
45+ this returns the url of a given flavour, version and arch
46+ :param flavour: 'ce' or 'ee'
47+ :param version: a version, without 'v' prefix and '-ee' suffix
48+ :param arch: amd64
49+ :return: url of the debian package
50+ """
51+ if self.owner != "gitlab-org" or self.repo not in ['gitlab-ce', 'gitlab-ee']:
52+ raise Exception(f"don't know how to get deb_url for {self.url}")
53+ return f"https://packages.gitlab.com/gitlab/gitlab-{flavour}/packages" + \
54+ f"/debian/stretch/gitlab-{flavour}_{version}-{flavour}.0_{arch}.deb/download.deb"
55+
56+ def get_deb_hash(self, flavour: str, version: str) -> str:
57+ out = subprocess.check_output(['nix-prefetch-url', self.get_deb_url(flavour, version)])
58+ return out.decode('utf-8').strip()
59+
60+ @staticmethod
61+ def rev2version(tag: str) -> str:
62+ """
63+ normalize a tag to a version number.
64+ This obviously isn't very smart if we don't pass something that looks like a tag
65+ :param tag: the tag to normalize
66+ :return: a normalized version number
67+ """
68+ # strip v prefix
69+ version = re.sub(r"^v", '', tag)
70+ # strip -ee suffix
71+ return re.sub(r"-ee$", '', version)
72+
73+ def get_file(self, filepath, rev):
74+ """
75+ returns file contents at a given rev
76+ :param filepath: the path to the file, relative to the repo root
77+ :param rev: the rev to fetch at
78+ :return:
79+ """
80+ return requests.get(self.url + f"/raw/{rev}/{filepath}").text
81+
82+ def get_data(self, rev, flavour):
83+ version = self.rev2version(rev)
84+
85+ passthru = {v: self.get_file(v, rev).strip() for v in ['GITALY_SERVER_VERSION', 'GITLAB_PAGES_VERSION',
86+ 'GITLAB_SHELL_VERSION', 'GITLAB_WORKHORSE_VERSION']}
87+ return dict(version=self.rev2version(rev),
88+ repo_hash=self.get_git_hash(rev),
89+ deb_hash=self.get_deb_hash(flavour, version),
90+ deb_url=self.get_deb_url(flavour, version),
91+ owner=self.owner,
92+ repo=self.repo,
93+ rev=rev,
94+ passthru=passthru)
95+
96+
97+def _flavour2gitlabrepo(flavour: str):
98+ if flavour not in ['ce', 'ee']:
99+ raise Exception(f"unknown gitlab flavour: {flavour}, needs to be ce or ee")
100+
101+ owner = 'gitlab-org'
102+ repo = 'gitlab-' + flavour
103+
104+ return GitLabRepo(owner, repo)
105+
106+
107+def _update_data_json(filename: str, repo: GitLabRepo, rev: str, flavour: str):
108+ flavour_data = repo.get_data(rev, flavour)
109+
110+ if not os.path.exists(filename):
111+ with open(filename, 'w') as f:
112+ json.dump({flavour: flavour_data}, f, indent=2)
113+ else:
114+ with open(filename, 'r+') as f:
115+ data = json.load(f)
116+ data[flavour] = flavour_data
117+ f.seek(0)
118+ json.dump(data, f, indent=2)
119+
120+
121+def _get_data_json():
122+ data_file_path = pathlib.Path(__file__).parent / 'data.json'
123+ with open(data_file_path, 'r') as f:
124+ return json.load(f)
125+
126+
127+def _call_update_source_version(pkg, version):
128+ """calls update-source-version from nixpkgs root dir"""
129+ nixpkgs_path = pathlib.Path(__file__).parent / '../../../../'
130+ return subprocess.check_output(['update-source-version', pkg, version], cwd=nixpkgs_path)
131+
132+
133+@click_log.simple_verbosity_option(logger)
134+@click.group()
135+def cli():
136+ pass
137+
138+
139+@cli.command('update-data')
140+@click.option('--rev', default='latest', help='The rev to use, \'latest\' points to the latest (stable) tag')
141+@click.argument('flavour')
142+def update_data(rev: str, flavour: str):
143+ """Update data.nix for a selected flavour"""
144+ r = _flavour2gitlabrepo(flavour)
145+
146+ if rev == 'latest':
147+ # filter out pre and re releases
148+ rev = next(filter(lambda x: not ('rc' in x or x.endswith('pre')), r.tags))
149+ logger.debug(f"Using rev {rev}")
150+
151+ version = r.rev2version(rev)
152+ logger.debug(f"Using version {version}")
153+
154+ data_file_path = pathlib.Path(__file__).parent / 'data.json'
155+
156+ _update_data_json(filename=data_file_path.as_posix(),
157+ repo=r,
158+ rev=rev,
159+ flavour=flavour)
160+
161+
162+@cli.command('update-rubyenv')
163+@click.argument('flavour')
164+def update_rubyenv(flavour):
165+ """Update rubyEnv-${flavour}"""
166+ if flavour not in ['ce', 'ee']:
167+ raise Exception(f"unknown gitlab flavour: {flavour}, needs to be ce or ee")
168+
169+ r = _flavour2gitlabrepo(flavour)
170+ rubyenv_dir = pathlib.Path(__file__).parent / f"rubyEnv-{flavour}"
171+
172+ # load rev from data.json
173+ data = _get_data_json()
174+ rev = data[flavour]['rev']
175+
176+ for fn in ['Gemfile.lock', 'Gemfile']:
177+ with open(rubyenv_dir / fn, 'w') as f:
178+ f.write(r.get_file(fn, rev))
179+
180+ subprocess.check_output(['bundix'], cwd=rubyenv_dir)
181+
182+
183+@cli.command('update-gitaly')
184+def update_gitaly():
185+ """Update gitaly"""
186+ data = _get_data_json()
187+ gitaly_server_version = data['ce']['passthru']['GITALY_SERVER_VERSION']
188+ r = GitLabRepo('gitlab-org', 'gitaly')
189+ rubyenv_dir = pathlib.Path(__file__).parent / 'gitaly'
190+
191+ for fn in ['Gemfile.lock', 'Gemfile']:
192+ with open(rubyenv_dir / fn, 'w') as f:
193+ f.write(r.get_file(f"ruby/{fn}", f"v{gitaly_server_version}"))
194+
195+ subprocess.check_output(['bundix'], cwd=rubyenv_dir)
196+ # currently broken, as `gitaly.meta.position` returns
197+ # pkgs/development/go-modules/generic/default.nix
198+ # so update-source-version doesn't know where to update hashes
199+ # _call_update_source_version('gitaly', gitaly_server_version)
200+ gitaly_hash = r.get_git_hash(f"v{gitaly_server_version}")
201+ click.echo(f"Please update gitaly/default.nix to version {gitaly_server_version} and hash {gitaly_hash}")
202+
203+
204+
205+@cli.command('update-gitlab-shell')
206+def update_gitlab_shell():
207+ """Update gitlab-shell"""
208+ data = _get_data_json()
209+ gitlab_shell_version = data['ce']['passthru']['GITLAB_SHELL_VERSION']
210+ _call_update_source_version('gitlab-shell', gitlab_shell_version)
211+
212+
213+@cli.command('update-gitlab-workhorse')
214+def update_gitlab_workhorse():
215+ """Update gitlab-shell"""
216+ data = _get_data_json()
217+ gitlab_workhorse_version = data['ce']['passthru']['GITLAB_WORKHORSE_VERSION']
218+ _call_update_source_version('gitlab-workhorse', gitlab_workhorse_version)
219+
220+
221+@cli.command('update-all')
222+@click.pass_context
223+def update_all(ctx):
224+ """Update gitlab ce and ee data.nix and rubyenvs to the latest stable release"""
225+ for flavour in ['ce', 'ee']:
226+ ctx.invoke(update_data, rev='latest', flavour=flavour)
227+ ctx.invoke(update_rubyenv, flavour=flavour)
228+ ctx.invoke(update_gitaly)
229+ ctx.invoke(update_gitlab_shell)
230+ ctx.invoke(update_gitlab_workhorse)
231+
232+
233+if __name__ == '__main__':
234+ cli()