1#!/usr/bin/env python3
2#
3# Add version information to poky.yaml based upon current git branch/tags
4# Also generate the list of available manuals (releases.rst file)
5#
6# Copyright Linux Foundation
7# Author: Richard Purdie <richard.purdie@linuxfoundation.org>
8# Author: Quentin Schulz <foss@0leil.net>
9#
10# SPDX-License-Identifier: MIT
11#
12
13
14import subprocess
15import collections
16import sys
17import os
18import itertools
19import re
20
21ourversion = None
22if len(sys.argv) == 2:
23    ourversion = sys.argv[1]
24
25ourversion = None
26if len(sys.argv) == 2:
27    ourversion = sys.argv[1]
28
29activereleases = ["nanbield", "kirkstone", "dunfell"]
30devbranch = "scarthgap"
31ltsseries = ["kirkstone", "dunfell"]
32
33# used by run-docs-builds to get the default page
34if ourversion == "getlatest":
35    print(activereleases[0])
36    sys.exit(0)
37
38release_series = collections.OrderedDict()
39release_series["scarthgap"] = "5.0"
40release_series["nanbield"] = "4.3"
41release_series["mickledore"] = "4.2"
42release_series["langdale"] = "4.1"
43release_series["kirkstone"] = "4.0"
44release_series["honister"] = "3.4"
45release_series["hardknott"] = "3.3"
46release_series["gatesgarth"] = "3.2"
47release_series["dunfell"] = "3.1"
48release_series["zeus"] = "3.0"
49release_series["warrior"] = "2.7"
50release_series["thud"] = "2.6"
51release_series["sumo"] = "2.5"
52release_series["rocko"] = "2.4"
53release_series["pyro"] = "2.3"
54release_series["morty"] = "2.2"
55release_series["krogoth"] = "2.1"
56release_series["jethro"] = "2.0"
57release_series["jethro-pre"] = "1.9"
58release_series["fido"] = "1.8"
59release_series["dizzy"] = "1.7"
60release_series["daisy"] = "1.6"
61release_series["dora"] = "1.5"
62release_series["dylan"] = "1.4"
63release_series["danny"] = "1.3"
64release_series["denzil"] = "1.2"
65release_series["edison"] = "1.1"
66release_series["bernard"] = "1.0"
67release_series["laverne"] = "0.9"
68
69
70bitbake_mapping = {
71    "scarthgap" : "2.8",
72    "nanbield" : "2.6",
73    "mickledore" : "2.4",
74    "langdale" : "2.2",
75    "kirkstone" : "2.0",
76    "honister" : "1.52",
77    "hardknott" : "1.50",
78    "gatesgarth" : "1.48",
79    "dunfell" : "1.46",
80}
81
82# 3.4 onwards doesn't have poky version
83# Early 3.4 release docs do reference it though
84poky_mapping = {
85    "3.4" : "26.0",
86    "3.3" : "25.0",
87    "3.2" : "24.0",
88    "3.1" : "23.0",
89}
90
91ourseries = None
92ourbranch = None
93bitbakeversion = None
94docconfver = None
95
96# Test tags exist and inform the user to fetch if not
97try:
98    subprocess.run(["git", "show", "yocto-%s" % release_series[activereleases[0]]], capture_output=True, check=True)
99except subprocess.CalledProcessError:
100    sys.exit("Please run 'git fetch --tags' before building the documentation")
101
102# Try and figure out what we are
103tags = subprocess.run(["git", "tag", "--points-at", "HEAD"], capture_output=True, text=True).stdout
104for t in tags.split():
105    if t.startswith("yocto-"):
106        ourversion = t[6:]
107
108if ourversion:
109    # We're a tagged release
110    components = ourversion.split(".")
111    baseversion = components[0] + "." + components[1]
112    docconfver = ourversion
113    for i in release_series:
114        if release_series[i] == baseversion:
115            ourseries = i
116            ourbranch = i
117            if i in bitbake_mapping:
118                bitbakeversion = bitbake_mapping[i]
119else:
120    # We're floating on a branch
121    branch = subprocess.run(["git", "branch", "--show-current"], capture_output=True, text=True).stdout.strip()
122    ourbranch = branch
123    if branch != "master" and branch not in release_series:
124        # We're not on a known release branch so we have to guess. Compare the numbers of commits
125        # from each release branch and assume the smallest number of commits is the one we're based off
126        possible_branch = None
127        branch_count = 0
128        for b in itertools.chain(release_series.keys(), ["master"]):
129            result = subprocess.run(["git", "log", "--format=oneline",  "HEAD..origin/" + b], capture_output=True, text=True)
130            if result.returncode == 0:
131                count = result.stdout.count('\n')
132                if not possible_branch or count < branch_count:
133                    print("Branch %s has count %s" % (b, count))
134                    possible_branch = b
135                    branch_count = count
136        if possible_branch:
137            branch = possible_branch
138        else:
139            branch = "master"
140        print("Nearest release branch estimated to be %s" % branch)
141    if branch == "master":
142        ourseries = devbranch
143        docconfver = "dev"
144        bitbakeversion = "dev"
145    elif branch in release_series:
146        ourseries = branch
147        if branch in bitbake_mapping:
148            bitbakeversion = bitbake_mapping[branch]
149    else:
150        sys.exit("Unknown series for branch %s" % branch)
151
152    previoustags = subprocess.run(["git", "tag", "--merged", "HEAD"], capture_output=True, text=True).stdout
153    previoustags = [t[6:] for t in previoustags.split() if t.startswith("yocto-" + release_series[ourseries])]
154    futuretags = subprocess.run(["git", "tag", "--merged", ourbranch], capture_output=True, text=True).stdout
155    futuretags = [t[6:] for t in futuretags.split() if t.startswith("yocto-" + release_series[ourseries])]
156
157    # Append .999 against the last known version
158    if len(previoustags) != len(futuretags):
159        ourversion = previoustags[-1] + ".999"
160    else:
161        ourversion = release_series[ourseries] + ".999"
162    if not docconfver:
163        docconfver = ourversion
164
165series = [k for k in release_series]
166previousseries = series[series.index(ourseries)+1:] or [""]
167lastlts = [k for k in previousseries if k in ltsseries] or "dunfell"
168
169print("Version calculated to be %s" % ourversion)
170print("Release series calculated to be %s" % ourseries)
171
172replacements = {
173    "DISTRO" : ourversion,
174    "DISTRO_NAME_NO_CAP" : ourseries,
175    "DISTRO_NAME" : ourseries.capitalize(),
176    "DISTRO_NAME_NO_CAP_MINUS_ONE" : previousseries[0],
177    "DISTRO_NAME_NO_CAP_LTS" : lastlts[0],
178    "YOCTO_DOC_VERSION" : ourversion,
179    "DISTRO_REL_TAG" : "yocto-" + ourversion,
180    "DOCCONF_VERSION" : docconfver,
181    "BITBAKE_SERIES" : bitbakeversion,
182}
183
184if release_series[ourseries] in poky_mapping:
185    pokyversion = poky_mapping[release_series[ourseries]]
186    if ourversion != release_series[ourseries]:
187        pokyversion = pokyversion + "." + ourversion.rsplit(".", 1)[1]
188    else:
189        pokyversion = pokyversion + ".0"
190    replacements["POKYVERSION"] = pokyversion
191
192if os.path.exists("poky.yaml.in"):
193    with open("poky.yaml.in", "r") as r, open("poky.yaml", "w") as w:
194        lines = r.readlines()
195        for line in lines:
196            data = line.split(":")
197            k = data[0].strip()
198            if k in replacements:
199                w.write("%s : \"%s\"\n" % (k, replacements[k]))
200            else:
201                w.write(line)
202
203    print("poky.yaml generated from poky.yaml.in")
204
205
206# In the switcher list of versions we display:
207#  - latest dev
208#  - latest stable release
209#  - latest LTS
210#  - latest for each releases listed as active
211#  - latest doc version in current series
212#  - current doc version
213# (with duplicates removed)
214
215versions = []
216with open("sphinx-static/switchers.js.in", "r") as r, open("sphinx-static/switchers.js", "w") as w:
217    lines = r.readlines()
218    for line in lines:
219        if "ALL_RELEASES_PLACEHOLDER" in line:
220            w.write(str(list(release_series.keys())))
221            continue
222        if "VERSIONS_PLACEHOLDER" in line:
223            w.write("    'dev': { 'title': 'Unstable (dev)', 'obsolete': false,},\n")
224            for branch in activereleases + ([ourseries] if ourseries not in activereleases else []):
225                if branch == devbranch:
226                    continue
227                branch_versions = subprocess.run('git tag --list yocto-%s*' % (release_series[branch]), shell=True, capture_output=True, text=True).stdout.split()
228                branch_versions = sorted([v.replace("yocto-" +  release_series[branch] + ".", "").replace("yocto-" +  release_series[branch], "0") for v in branch_versions], key=int)
229                if not branch_versions:
230                    continue
231                version = release_series[branch]
232                if branch_versions[-1] != "0":
233                    version = version + "." + branch_versions[-1]
234                versions.append(version)
235                w.write("    '%s': {'title': '%s (%s)', 'obsolete': %s,},\n" % (version, branch.capitalize(), version, str(branch not in activereleases).lower()))
236            if ourversion not in versions and ourseries != devbranch:
237                w.write("    '%s': {'title': '%s (%s)', 'obsolete': %s,},\n" % (ourversion, ourseries.capitalize(), ourversion, str(ourseries not in activereleases).lower()))
238        else:
239            w.write(line)
240
241print("switchers.js generated from switchers.js.in")
242
243# generate releases.rst
244
245# list missing tags in yocto-docs
246missing_tags = [
247        'yocto-0.9',
248        'yocto-1.0', 'yocto-1.0.1',
249        'yocto-1.1', 'yocto-1.1.1',
250        'yocto-1.2',
251        'yocto-1.4.4', 'yocto-1.4.5',
252        'yocto-1.5', 'yocto-1.5.2', 'yocto-1.5.3', 'yocto-1.5.4',
253        'yocto-1.6', 'yocto-1.6.1', 'yocto-1.6.2',
254        'yocto-1.7', 'yocto-1.7.1',
255        'yocto-1.9',
256        'yocto-2.5.3',
257        'yocto-3.1', 'yocto-3.1.1', 'yocto-3.1.2', 'yocto-3.1.3',
258        ]
259
260semver = re.compile(r'yocto-(\d+)\.(\d+)(?:\.)?(\d*)')
261
262# git is able to properly order semver versions but not python
263# instead of adding a dependency on semver module, let's convert the version
264# into a decimal number, e.g. 11.23.1 will be 112301 and 1.5 will be 010500 so
265# it can be used as a key for the sorting algorithm.
266# This can be removed once all the old tags are re-created.
267def tag_to_semver_like(v):
268    v_semver = semver.search(v)
269    v_maj, v_min, v_patch = v_semver.groups('0')
270    return int("{:0>2}{:0>2}{:0>2}".format(v_maj, v_min, v_patch), 10)
271
272yocto_tags = subprocess.run(["git", "tag", "--list", "--sort=version:refname", "yocto-*"], capture_output=True, text=True).stdout
273yocto_tags = sorted(yocto_tags.split() + missing_tags, key=tag_to_semver_like)
274tags = [tag[6:] for tag in yocto_tags]
275
276with open('releases.rst', 'w') as f:
277    f.write('===========================\n')
278    f.write(' Supported Release Manuals\n')
279    f.write('===========================\n')
280    f.write('\n')
281
282    for activerelease in activereleases:
283        title = "Release Series %s (%s)" % (release_series[activerelease], activerelease)
284        f.write('*' * len(title) + '\n')
285        f.write(title + '\n')
286        f.write('*' * len(title) + '\n')
287        f.write('\n')
288
289        for tag in tags:
290            if tag == release_series[activerelease] or tag.startswith('%s.' % release_series[activerelease]):
291                f.write('- :yocto_docs:`%s Documentation </%s>`\n' % (tag, tag))
292        f.write('\n')
293
294    f.write('==========================\n')
295    f.write(' Outdated Release Manuals\n')
296    f.write('==========================\n')
297    f.write('\n')
298
299    for series in release_series:
300        if series == devbranch or series in activereleases:
301            continue
302
303        if series == "jethro-pre":
304            continue
305
306        title = "Release Series %s (%s)" % (release_series[series], series)
307        f.write('*' * len(title) + '\n')
308        f.write(title + '\n')
309        f.write('*' * len(title) + '\n')
310        f.write('\n')
311        if series == "jethro":
312            f.write('- :yocto_docs:`1.9 Documentation </1.9>`\n')
313        for tag in tags:
314            if tag == release_series[series] or tag.startswith('%s.' % release_series[series]):
315                f.write('- :yocto_docs:`%s Documentation </%s>`\n' % (tag, tag))
316        f.write('\n')
317