transformers
225 строк · 8.1 Кб
1# coding=utf-8
2# Copyright 2021 The HuggingFace Team. All rights reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15"""
16Utility that prepares the repository for releases (or patches) by updating all versions in the relevant places. It
17also performs some post-release cleanup, by updating the links in the main README to respective model doc pages (from
18main to stable).
19
20To prepare for a release, use from the root of the repo on the release branch with:
21
22```bash
23python release.py
24```
25
26or use `make pre-release`.
27
28To prepare for a patch release, use from the root of the repo on the release branch with:
29
30```bash
31python release.py --patch
32```
33
34or use `make pre-patch`.
35
36To do the post-release cleanup, use from the root of the repo on the main branch with:
37
38```bash
39python release.py --post_release
40```
41
42or use `make post-release`.
43"""
44import argparse45import os46import re47
48import packaging.version49
50
51# All paths are defined with the intent that this script should be run from the root of the repo.
52PATH_TO_EXAMPLES = "examples/"53# This maps a type of file to the pattern to look for when searching where the version is defined, as well as the
54# template to follow when replacing it with the new version.
55REPLACE_PATTERNS = {56"examples": (re.compile(r'^check_min_version\("[^"]+"\)\s*$', re.MULTILINE), 'check_min_version("VERSION")\n'),57"init": (re.compile(r'^__version__\s+=\s+"([^"]+)"\s*$', re.MULTILINE), '__version__ = "VERSION"\n'),58"setup": (re.compile(r'^(\s*)version\s*=\s*"[^"]+",', re.MULTILINE), r'\1version="VERSION",'),59}
60# This maps a type of file to its path in Transformers
61REPLACE_FILES = {62"init": "src/transformers/__init__.py",63"setup": "setup.py",64}
65README_FILE = "README.md"66
67
68def update_version_in_file(fname: str, version: str, file_type: str):69"""70Update the version of Transformers in one file.
71
72Args:
73fname (`str`): The path to the file where we want to update the version.
74version (`str`): The new version to set in the file.
75file_type (`str`): The type of the file (should be a key in `REPLACE_PATTERNS`).
76"""
77with open(fname, "r", encoding="utf-8", newline="\n") as f:78code = f.read()79re_pattern, replace = REPLACE_PATTERNS[file_type]80replace = replace.replace("VERSION", version)81code = re_pattern.sub(replace, code)82with open(fname, "w", encoding="utf-8", newline="\n") as f:83f.write(code)84
85
86def update_version_in_examples(version: str):87"""88Update the version in all examples files.
89
90Args:
91version (`str`): The new version to set in the examples.
92"""
93for folder, directories, fnames in os.walk(PATH_TO_EXAMPLES):94# Removing some of the folders with non-actively maintained examples from the walk95if "research_projects" in directories:96directories.remove("research_projects")97if "legacy" in directories:98directories.remove("legacy")99for fname in fnames:100if fname.endswith(".py"):101update_version_in_file(os.path.join(folder, fname), version, file_type="examples")102
103
104def global_version_update(version: str, patch: bool = False):105"""106Update the version in all needed files.
107
108Args:
109version (`str`): The new version to set everywhere.
110patch (`bool`, *optional*, defaults to `False`): Whether or not this is a patch release.
111"""
112for pattern, fname in REPLACE_FILES.items():113update_version_in_file(fname, version, pattern)114if not patch:115# We don't update the version in the examples for patch releases.116update_version_in_examples(version)117
118
119def clean_main_ref_in_model_list():120"""121Replace the links from main doc to stable doc in the model list of the README.
122"""
123# If the introduction or the conclusion of the list change, the prompts may need to be updated.124_start_prompt = "🤗 Transformers currently provides the following architectures"125_end_prompt = "1. Want to contribute a new model?"126with open(README_FILE, "r", encoding="utf-8", newline="\n") as f:127lines = f.readlines()128
129# Find the start of the list.130start_index = 0131while not lines[start_index].startswith(_start_prompt):132start_index += 1133start_index += 1134
135index = start_index136# Update the lines in the model list.137while not lines[index].startswith(_end_prompt):138if lines[index].startswith("1."):139lines[index] = lines[index].replace(140"https://huggingface.co/docs/transformers/main/model_doc",141"https://huggingface.co/docs/transformers/model_doc",142)143index += 1144
145with open(README_FILE, "w", encoding="utf-8", newline="\n") as f:146f.writelines(lines)147
148
149def get_version() -> packaging.version.Version:150"""151Reads the current version in the main __init__.
152"""
153with open(REPLACE_FILES["init"], "r") as f:154code = f.read()155default_version = REPLACE_PATTERNS["init"][0].search(code).groups()[0]156return packaging.version.parse(default_version)157
158
159def pre_release_work(patch: bool = False):160"""161Do all the necessary pre-release steps:
162- figure out the next minor release version and ask confirmation
163- update the version eveywhere
164- clean-up the model list in the main README
165
166Args:
167patch (`bool`, *optional*, defaults to `False`): Whether or not this is a patch release.
168"""
169# First let's get the default version: base version if we are in dev, bump minor otherwise.170default_version = get_version()171if patch and default_version.is_devrelease:172raise ValueError("Can't create a patch version from the dev branch, checkout a released version!")173if default_version.is_devrelease:174default_version = default_version.base_version175elif patch:176default_version = f"{default_version.major}.{default_version.minor}.{default_version.micro + 1}"177else:178default_version = f"{default_version.major}.{default_version.minor + 1}.0"179
180# Now let's ask nicely if we have found the right version.181version = input(f"Which version are you releasing? [{default_version}]")182if len(version) == 0:183version = default_version184
185print(f"Updating version to {version}.")186global_version_update(version, patch=patch)187if not patch:188print("Cleaning main README, don't forget to run `make fix-copies`.")189clean_main_ref_in_model_list()190
191
192def post_release_work():193"""194Do all the necesarry post-release steps:
195- figure out the next dev version and ask confirmation
196- update the version eveywhere
197- clean-up the model list in the main README
198"""
199# First let's get the current version200current_version = get_version()201dev_version = f"{current_version.major}.{current_version.minor + 1}.0.dev0"202current_version = current_version.base_version203
204# Check with the user we got that right.205version = input(f"Which version are we developing now? [{dev_version}]")206if len(version) == 0:207version = dev_version208
209print(f"Updating version to {version}.")210global_version_update(version)211print("Cleaning main README, don't forget to run `make fix-copies`.")212clean_main_ref_in_model_list()213
214
215if __name__ == "__main__":216parser = argparse.ArgumentParser()217parser.add_argument("--post_release", action="store_true", help="Whether this is pre or post release.")218parser.add_argument("--patch", action="store_true", help="Whether or not this is a patch release.")219args = parser.parse_args()220if not args.post_release:221pre_release_work(patch=args.patch)222elif args.patch:223print("Nothing to do after a patch :-)")224else:225post_release_work()226