codingutf8 2021 the huggingface team licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache orglicenseslicense2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license utility that prepares the repository for releases or patches by updating all versions in the relevant places it also performs some postrelease cleanup by updating the links in the main readme to respective model doc pages from main to stable to prepare for a release use from the root of the repo on the release branch with bash python release py or use make prerelease to prepare for a patch release use from the root of the repo on the release branch with bash python release py patch or use make prepatch to do the postrelease cleanup use from the root of the repo on the main branch with bash python release py postrelease or use make postrelease all paths are defined with the intent that this script should be run from the root of the repo this maps a type of file to the pattern to look for when searching where the version is defined as well as the template to follow when replacing it with the new version this maps a type of file to its path in transformers update the version of transformers in one file args fname str the path to the file where we want to update the version version str the new version to set in the file filetype str the type of the file should be a key in replacepatterns update the version in all examples files args version str the new version to set in the examples removing some of the folders with nonactively maintained examples from the walk update the version in all needed files args version str the new version to set everywhere patch bool optional defaults to false whether or not this is a patch release we don t update the version in the examples for patch releases replace the links from main doc to stable doc in the model list of the readme if the introduction or the conclusion of the list change the prompts may need to be updated find the start of the list update the lines in the model list reads the current version in the main init do all the necessary prerelease steps figure out the next minor release version and ask confirmation update the version eveywhere cleanup the model list in the main readme args patch bool optional defaults to false whether or not this is a patch release first let s get the default version base version if we are in dev bump minor otherwise now let s ask nicely if we have found the right version do all the necesarry postrelease steps figure out the next dev version and ask confirmation update the version eveywhere cleanup the model list in the main readme first let s get the current version check with the user we got that right coding utf 8 2021 the huggingface team licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache org licenses license 2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license utility that prepares the repository for releases or patches by updating all versions in the relevant places it also performs some post release cleanup by updating the links in the main readme to respective model doc pages from main to stable to prepare for a release use from the root of the repo on the release branch with bash python release py or use make pre release to prepare for a patch release use from the root of the repo on the release branch with bash python release py patch or use make pre patch to do the post release cleanup use from the root of the repo on the main branch with bash python release py post_release or use make post release all paths are defined with the intent that this script should be run from the root of the repo this maps a type of file to the pattern to look for when searching where the version is defined as well as the template to follow when replacing it with the new version this maps a type of file to its path in transformers update the version of transformers in one file args fname str the path to the file where we want to update the version version str the new version to set in the file file_type str the type of the file should be a key in replace_patterns update the version in all examples files args version str the new version to set in the examples removing some of the folders with non actively maintained examples from the walk update the version in all needed files args version str the new version to set everywhere patch bool optional defaults to false whether or not this is a patch release we don t update the version in the examples for patch releases replace the links from main doc to stable doc in the model list of the readme if the introduction or the conclusion of the list change the prompts may need to be updated find the start of the list update the lines in the model list reads the current version in the main __init__ do all the necessary pre release steps figure out the next minor release version and ask confirmation update the version eveywhere clean up the model list in the main readme args patch bool optional defaults to false whether or not this is a patch release first let s get the default version base version if we are in dev bump minor otherwise now let s ask nicely if we have found the right version do all the necesarry post release steps figure out the next dev version and ask confirmation update the version eveywhere clean up the model list in the main readme first let s get the current version check with the user we got that right
import argparse
import os
import re

import packaging.version



PATH_TO_EXAMPLES = "examples/"


REPLACE_PATTERNS = {
    "examples": (re.compile(r'^check_min_version\("[^"]+"\)\s*$', re.MULTILINE), 'check_min_version("VERSION")\n'),
    "init": (re.compile(r'^__version__\s+=\s+"([^"]+)"\s*$', re.MULTILINE), '__version__ = "VERSION"\n'),
    "setup": (re.compile(r'^(\s*)version\s*=\s*"[^"]+",', re.MULTILINE), r'\1version="VERSION",'),
}

REPLACE_FILES = {
    "init": "src/transformers/__init__.py",
    "setup": "setup.py",
}
README_FILE = "README.md"


def update_version_in_file(fname: str, version: str, file_type: str):
    
    with open(fname, "r", encoding="utf-8", newline="\n") as f:
        code = f.read()
    re_pattern, replace = REPLACE_PATTERNS[file_type]
    replace = replace.replace("VERSION", version)
    code = re_pattern.sub(replace, code)
    with open(fname, "w", encoding="utf-8", newline="\n") as f:
        f.write(code)


def update_version_in_examples(version: str):
    
    for folder, directories, fnames in os.walk(PATH_TO_EXAMPLES):
        
        if "research_projects" in directories:
            directories.remove("research_projects")
        if "legacy" in directories:
            directories.remove("legacy")
        for fname in fnames:
            if fname.endswith(".py"):
                update_version_in_file(os.path.join(folder, fname), version, file_type="examples")


def global_version_update(version: str, patch: bool = False):
    
    for pattern, fname in REPLACE_FILES.items():
        update_version_in_file(fname, version, pattern)
    if not patch:
        
        update_version_in_examples(version)


def clean_main_ref_in_model_list():
    
    
    _start_prompt = "🤗 Transformers currently provides the following architectures"
    _end_prompt = "1. Want to contribute a new model?"
    with open(README_FILE, "r", encoding="utf-8", newline="\n") as f:
        lines = f.readlines()

    
    start_index = 0
    while not lines[start_index].startswith(_start_prompt):
        start_index += 1
    start_index += 1

    index = start_index
    
    while not lines[index].startswith(_end_prompt):
        if lines[index].startswith("1."):
            lines[index] = lines[index].replace(
                "https://huggingface.co/docs/transformers/main/model_doc",
                "https://huggingface.co/docs/transformers/model_doc",
            )
        index += 1

    with open(README_FILE, "w", encoding="utf-8", newline="\n") as f:
        f.writelines(lines)


def get_version() -> packaging.version.Version:
    
    with open(REPLACE_FILES["init"], "r") as f:
        code = f.read()
    default_version = REPLACE_PATTERNS["init"][0].search(code).groups()[0]
    return packaging.version.parse(default_version)


def pre_release_work(patch: bool = False):
    
    
    default_version = get_version()
    if patch and default_version.is_devrelease:
        raise ValueError("Can't create a patch version from the dev branch, checkout a released version!")
    if default_version.is_devrelease:
        default_version = default_version.base_version
    elif patch:
        default_version = f"{default_version.major}.{default_version.minor}.{default_version.micro + 1}"
    else:
        default_version = f"{default_version.major}.{default_version.minor + 1}.0"

    
    version = input(f"Which version are you releasing? [{default_version}]")
    if len(version) == 0:
        version = default_version

    print(f"Updating version to {version}.")
    global_version_update(version, patch=patch)
    if not patch:
        print("Cleaning main README, don't forget to run `make fix-copies`.")
        clean_main_ref_in_model_list()


def post_release_work():
    
    
    current_version = get_version()
    dev_version = f"{current_version.major}.{current_version.minor + 1}.0.dev0"
    current_version = current_version.base_version

    
    version = input(f"Which version are we developing now? [{dev_version}]")
    if len(version) == 0:
        version = dev_version

    print(f"Updating version to {version}.")
    global_version_update(version)
    print("Cleaning main README, don't forget to run `make fix-copies`.")
    clean_main_ref_in_model_list()


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--post_release", action="store_true", help="Whether this is pre or post release.")
    parser.add_argument("--patch", action="store_true", help="Whether or not this is a patch release.")
    args = parser.parse_args()
    if not args.post_release:
        pre_release_work(patch=args.patch)
    elif args.patch:
        print("Nothing to do after a patch :-)")
    else:
        post_release_work()