Path: blob/21.2-virgl/bin/gen_calendar_entries.py
4545 views
#!/usr/bin/env python31# SPDX-License-Identifier: MIT23# Copyright © 2021 Intel Corporation45# Permission is hereby granted, free of charge, to any person obtaining a copy6# of this software and associated documentation files (the "Software"), to deal7# in the Software without restriction, including without limitation the rights8# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell9# copies of the Software, and to permit persons to whom the Software is10# furnished to do so, subject to the following conditions:1112# The above copyright notice and this permission notice shall be included in13# all copies or substantial portions of the Software.1415# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR16# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,17# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE18# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER19# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,20# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE21# SOFTWARE.2223"""Helper script for manipulating the release calendar."""2425from __future__ import annotations26import argparse27import csv28import contextlib29import datetime30import pathlib31import subprocess32import typing3334if typing.TYPE_CHECKING:35import _csv36from typing_extensions import Protocol3738class RCArguments(Protocol):39"""Typing information for release-candidate command arguments."""4041manager: str4243class FinalArguments(Protocol):44"""Typing information for release command arguments."""4546series: str47manager: str48zero_released: bool4950class ExtendArguments(Protocol):51"""Typing information for extend command arguments."""5253series: str54count: int555657CalendarRowType = typing.Tuple[typing.Optional[str], str, str, str, typing.Optional[str]]585960_ROOT = pathlib.Path(__file__).parent.parent61CALENDAR_CSV = _ROOT / 'docs' / 'release-calendar.csv'62VERSION = _ROOT / 'VERSION'63LAST_RELEASE = 'This is the last planned release of the {}.x series.'64OR_FINAL = 'Or {}.0 final.'656667def read_calendar() -> typing.List[CalendarRowType]:68"""Read the calendar and return a list of it's rows."""69with CALENDAR_CSV.open('r') as f:70return [typing.cast('CalendarRowType', tuple(r)) for r in csv.reader(f)]717273def commit(message: str) -> None:74"""Commit the changes the the release-calendar.csv file."""75subprocess.run(['git', 'commit', str(CALENDAR_CSV), '--message', message])76777879def _calculate_release_start(major: str, minor: str) -> datetime.date:80"""Calclulate the start of the release for release candidates.8182This is quarterly, on the second wednesday, in Januray, April, July, and Octobor.83"""84quarter = datetime.date.fromisoformat(f'20{major}-0{[1, 4, 7, 10][int(minor)]}-01')8586# Wednesday is 387day = quarter.isoweekday()88if day > 3:89# this will walk back into the previous month, it's much simpler to90# duplicate the 14 than handle the calculations for the month and year91# changing.92return quarter.replace(day=quarter.day - day + 3 + 14)93elif day < 3:94quarter = quarter.replace(day=quarter.day + 3 - day)95return quarter.replace(day=quarter.day + 14)969798def release_candidate(args: RCArguments) -> None:99"""Add release candidate entries."""100with VERSION.open('r') as f:101version = f.read().rstrip('-devel')102major, minor, _ = version.split('.')103date = _calculate_release_start(major, minor)104105data = read_calendar()106107with CALENDAR_CSV.open('w') as f:108writer = csv.writer(f)109writer.writerows(data)110111writer.writerow([f'{major}.{minor}', date.isoformat(), f'{major}.{minor}.0-rc1', args.manager])112for row in range(2, 4):113date = date + datetime.timedelta(days=7)114writer.writerow([None, date.isoformat(), f'{major}.{minor}.0-rc{row}', args.manager])115date = date + datetime.timedelta(days=7)116writer.writerow([None, date.isoformat(), f'{major}.{minor}.0-rc4', args.manager, OR_FINAL.format(f'{major}.{minor}')])117118commit(f'docs: Add calendar entries for {major}.{minor} release candidates.')119120121def _calculate_next_release_date(next_is_zero: bool) -> datetime.date:122"""Calculate the date of the next release.123124If the next is .0, we have the release in seven days, if the next is .1,125then it's in 14126"""127date = datetime.date.today()128day = date.isoweekday()129if day < 3:130delta = 3 - day131elif day > 3:132# this will walk back into the previous month, it's much simpler to133# duplicate the 14 than handle the calculations for the month and year134# changing.135delta = (3 - day)136else:137delta = 0138delta += 7139if not next_is_zero:140delta += 7141return date + datetime.timedelta(days=delta)142143144def final_release(args: FinalArguments) -> None:145"""Add final release entries."""146data = read_calendar()147date = _calculate_next_release_date(not args.zero_released)148149with CALENDAR_CSV.open('w') as f:150writer = csv.writer(f)151writer.writerows(data)152153base = 1 if args.zero_released else 0154155writer.writerow([args.series, date.isoformat(), f'{args.series}.{base}', args.manager])156for row in range(base + 1, 3):157date = date + datetime.timedelta(days=14)158writer.writerow([None, date.isoformat(), f'{args.series}.{row}', args.manager])159date = date + datetime.timedelta(days=14)160writer.writerow([None, date.isoformat(), f'{args.series}.3', args.manager, LAST_RELEASE.format(args.series)])161162commit(f'docs: Add calendar entries for {args.series} release.')163164165def extend(args: ExtendArguments) -> None:166"""Extend a release."""167@contextlib.contextmanager168def write_existing(writer: _csv._writer, current: typing.List[CalendarRowType]) -> typing.Iterator[CalendarRowType]:169"""Write the orinal file, yield to insert new entries.170171This is a bit clever, basically what happens it writes out the172original csv file until it reaches the start of the release after the173one we're appending, then it yields the last row. When control is174returned it writes out the rest of the original calendar data.175"""176last_row: typing.Optional[CalendarRowType] = None177in_wanted = False178for row in current:179if in_wanted and row[0]:180in_wanted = False181assert last_row is not None182yield last_row183if row[0] == args.series:184in_wanted = True185if in_wanted and len(row) >= 5 and row[4] in {LAST_RELEASE.format(args.series), OR_FINAL.format(args.series)}:186# If this was the last planned release and we're adding more,187# then we need to remove that message and add it elsewhere188r = list(row)189r[4] = None190# Mypy can't figure this out…191row = typing.cast('CalendarRowType', tuple(r))192last_row = row193writer.writerow(row)194# If this is the only entry we can hit a case where the contextmanager195# hasn't yielded196if in_wanted:197yield row198199current = read_calendar()200201with CALENDAR_CSV.open('w') as f:202writer = csv.writer(f)203with write_existing(writer, current) as row:204# Get rid of -rcX as well205if '-rc' in row[2]:206first_point = int(row[2].split('rc')[-1]) + 1207template = '{}.0-rc{}'208days = 7209else:210first_point = int(row[2].split('-')[0].split('.')[-1]) + 1211template = '{}.{}'212days = 14213214date = datetime.date.fromisoformat(row[1])215for i in range(first_point, first_point + args.count):216date = date + datetime.timedelta(days=days)217r = [None, date.isoformat(), template.format(args.series, i), row[3], None]218if i == first_point + args.count - 1:219if days == 14:220r[4] = LAST_RELEASE.format(args.series)221else:222r[4] = OR_FINAL.format(args.series)223writer.writerow(r)224225commit(f'docs: Extend calendar entries for {args.series} by {args.count} releases.')226227228def main() -> None:229parser = argparse.ArgumentParser()230sub = parser.add_subparsers()231232rc = sub.add_parser('release-candidate', aliases=['rc'], help='Generate calendar entries for a release candidate.')233rc.add_argument('manager', help="the name of the person managing the release.")234rc.set_defaults(func=release_candidate)235236fr = sub.add_parser('release', help='Generate calendar entries for a final release.')237fr.add_argument('manager', help="the name of the person managing the release.")238fr.add_argument('series', help='The series to extend, such as "29.3" or "30.0".')239fr.add_argument('--zero-released', action='store_true', help='The .0 release was today, the next release is .1')240fr.set_defaults(func=final_release)241242ex = sub.add_parser('extend', help='Generate additional entries for a release.')243ex.add_argument('series', help='The series to extend, such as "29.3" or "30.0".')244ex.add_argument('count', type=int, help='The number of new entries to add.')245ex.set_defaults(func=extend)246247args = parser.parse_args()248args.func(args)249250251if __name__ == "__main__":252main()253254255