bumpversion-0.5.3/0000755000076500000240000000000012513425757014331 5ustar filipstaff00000000000000bumpversion-0.5.3/bumpversion/0000755000076500000240000000000012513425757016702 5ustar filipstaff00000000000000bumpversion-0.5.3/bumpversion/__init__.py0000644000076500000240000007733712513425613021023 0ustar filipstaff00000000000000# -*- coding: utf-8 -*- from __future__ import unicode_literals try: from configparser import RawConfigParser, NoOptionError except ImportError: from ConfigParser import RawConfigParser, NoOptionError try: from StringIO import StringIO except: from io import StringIO import argparse import os import re import sre_constants import subprocess import warnings import io from string import Formatter from datetime import datetime from difflib import unified_diff from tempfile import NamedTemporaryFile import sys import codecs if sys.version_info[0] == 2: sys.stdout = codecs.getwriter('utf-8')(sys.stdout) __VERSION__ = '0.5.3' DESCRIPTION = 'bumpversion: v{} (using Python v{})'.format( __VERSION__, sys.version.split("\n")[0].split(" ")[0], ) import logging logger = logging.getLogger("bumpversion.logger") logger_list = logging.getLogger("bumpversion.list") from argparse import _AppendAction class DiscardDefaultIfSpecifiedAppendAction(_AppendAction): ''' Fixes bug http://bugs.python.org/issue16399 for 'append' action ''' def __call__(self, parser, namespace, values, option_string=None): if getattr(self, "_discarded_default", None) is None: setattr(namespace, self.dest, []) self._discarded_default = True super(DiscardDefaultIfSpecifiedAppendAction, self).__call__( parser, namespace, values, option_string=None) time_context = { 'now': datetime.now(), 'utcnow': datetime.utcnow(), } class BaseVCS(object): @classmethod def commit(cls, message): f = NamedTemporaryFile('wb', delete=False) f.write(message.encode('utf-8')) f.close() subprocess.check_output(cls._COMMIT_COMMAND + [f.name], env=dict( list(os.environ.items()) + [(b'HGENCODING', b'utf-8')] )) os.unlink(f.name) @classmethod def is_usable(cls): try: return subprocess.call( cls._TEST_USABLE_COMMAND, stderr=subprocess.PIPE, stdout=subprocess.PIPE ) == 0 except OSError as e: if e.errno == 2: # mercurial is not installed then, ok. return False raise class Git(BaseVCS): _TEST_USABLE_COMMAND = ["git", "rev-parse", "--git-dir"] _COMMIT_COMMAND = ["git", "commit", "-F"] @classmethod def assert_nondirty(cls): lines = [ line.strip() for line in subprocess.check_output( ["git", "status", "--porcelain"]).splitlines() if not line.strip().startswith(b"??") ] if lines: raise WorkingDirectoryIsDirtyException( "Git working directory is not clean:\n{}".format( b"\n".join(lines))) @classmethod def latest_tag_info(cls): try: # git-describe doesn't update the git-index, so we do that subprocess.check_output(["git", "update-index", "--refresh"]) # get info about the latest tag in git describe_out = subprocess.check_output([ "git", "describe", "--dirty", "--tags", "--long", "--abbrev=40", "--match=v*", ], stderr=subprocess.STDOUT ).decode().split("-") except subprocess.CalledProcessError: # logger.warn("Error when running git describe") return {} info = {} if describe_out[-1].strip() == "dirty": info["dirty"] = True describe_out.pop() info["commit_sha"] = describe_out.pop().lstrip("g") info["distance_to_latest_tag"] = int(describe_out.pop()) info["current_version"] = "-".join(describe_out).lstrip("v") return info @classmethod def add_path(cls, path): subprocess.check_output(["git", "add", "--update", path]) @classmethod def tag(cls, name): subprocess.check_output(["git", "tag", name]) class Mercurial(BaseVCS): _TEST_USABLE_COMMAND = ["hg", "root"] _COMMIT_COMMAND = ["hg", "commit", "--logfile"] @classmethod def latest_tag_info(cls): return {} @classmethod def assert_nondirty(cls): lines = [ line.strip() for line in subprocess.check_output( ["hg", "status", "-mard"]).splitlines() if not line.strip().startswith(b"??") ] if lines: raise WorkingDirectoryIsDirtyException( "Mercurial working directory is not clean:\n{}".format( b"\n".join(lines))) @classmethod def add_path(cls, path): pass @classmethod def tag(cls, name): subprocess.check_output(["hg", "tag", name]) VCS = [Git, Mercurial] def prefixed_environ(): return dict((("${}".format(key), value) for key, value in os.environ.items())) class ConfiguredFile(object): def __init__(self, path, versionconfig): self.path = path self._versionconfig = versionconfig def should_contain_version(self, version, context): context['current_version'] = self._versionconfig.serialize(version, context) serialized_version = self._versionconfig.search.format(**context) if self.contains(serialized_version): return msg = "Did not find '{}' or '{}' in file {}".format(version.original, serialized_version, self.path) if version.original: assert self.contains(version.original), msg return assert False, msg def contains(self, search): with io.open(self.path, 'rb') as f: search_lines = search.splitlines() lookbehind = [] for lineno, line in enumerate(f.readlines()): lookbehind.append(line.decode('utf-8').rstrip("\n")) if len(lookbehind) > len(search_lines): lookbehind = lookbehind[1:] if (search_lines[0] in lookbehind[0] and search_lines[-1] in lookbehind[-1] and search_lines[1:-1] == lookbehind[1:-1]): logger.info("Found '{}' in {} at line {}: {}".format( search, self.path, lineno - (len(lookbehind) - 1), line.decode('utf-8').rstrip())) return True return False def replace(self, current_version, new_version, context, dry_run): with io.open(self.path, 'rb') as f: file_content_before = f.read().decode('utf-8') context['current_version'] = self._versionconfig.serialize(current_version, context) context['new_version'] = self._versionconfig.serialize(new_version, context) search_for = self._versionconfig.search.format(**context) replace_with = self._versionconfig.replace.format(**context) file_content_after = file_content_before.replace( search_for, replace_with ) if file_content_before == file_content_after: # TODO expose this to be configurable file_content_after = file_content_before.replace( current_version.original, replace_with, ) if file_content_before != file_content_after: logger.info("{} file {}:".format( "Would change" if dry_run else "Changing", self.path, )) logger.info("\n".join(list(unified_diff( file_content_before.splitlines(), file_content_after.splitlines(), lineterm="", fromfile="a/"+self.path, tofile="b/"+self.path )))) else: logger.info("{} file {}".format( "Would not change" if dry_run else "Not changing", self.path, )) if not dry_run: with io.open(self.path, 'wb') as f: f.write(file_content_after.encode('utf-8')) def __str__(self): return self.path def __repr__(self): return ''.format(self.path) class VersionPartConfiguration(object): pass class ConfiguredVersionPartConfiguration(object): def __init__(self, values, optional_value=None, first_value=None): assert len(values) > 0 self._values = values if optional_value is None: optional_value = values[0] assert optional_value in values self.optional_value = optional_value if first_value is None: first_value = values[0] assert first_value in values self.first_value = first_value def bump(self, value): return self._values[self._values.index(value)+1] class NumericVersionPartConfiguration(VersionPartConfiguration): optional_value = "0" FIRST_NUMERIC = re.compile('([^\d]*)(\d+)(.*)') def __init__(self, first_value=None): if first_value is None: first_value = "0" int(first_value) # make sure that it's numeric self.first_value = first_value @classmethod def bump(cls, value): part_prefix, numeric_version, part_suffix = cls.FIRST_NUMERIC.search(value).groups() bumped_numeric = str(int(numeric_version) + 1) return "".join([part_prefix, bumped_numeric, part_suffix]) class VersionPart(object): def __init__(self, value, config=None): self._value = value if config is None: config = NumericVersionPartConfiguration() self.config = config @property def value(self): return self._value or self.config.optional_value def copy(self): return VersionPart(self._value) def bump(self): return VersionPart(self.config.bump(self.value), self.config) def is_optional(self): return self.value == self.config.optional_value def __format__(self, format_spec): return self.value def __repr__(self): return ''.format( self.config.__class__.__name__, self.value ) def null(self): return VersionPart(self.config.first_value, self.config) class IncompleteVersionRepresenationException(Exception): def __init__(self, message): self.message = message class MissingValueForSerializationException(Exception): def __init__(self, message): self.message = message class WorkingDirectoryIsDirtyException(Exception): def __init__(self, message): self.message = message def keyvaluestring(d): return ", ".join("{}={}".format(k, v) for k, v in sorted(d.items())) class Version(object): def __init__(self, values, original=None): self._values = dict(values) self.original = original def __getitem__(self, key): return self._values[key] def __len__(self): return len(self._values) def __iter__(self): return iter(self._values) def __repr__(self): return ''.format(keyvaluestring(self._values)) def bump(self, part_name, order): bumped = False new_values = {} for label in order: if not label in self._values: continue elif label == part_name: new_values[label] = self._values[label].bump() bumped = True elif bumped: new_values[label] = self._values[label].null() else: new_values[label] = self._values[label].copy() new_version = Version(new_values) return new_version class VersionConfig(object): """ Holds a complete representation of a version string """ def __init__(self, parse, serialize, search, replace, part_configs=None): try: self.parse_regex = re.compile(parse, re.VERBOSE) except sre_constants.error as e: logger.error("--parse '{}' is not a valid regex".format(parse)) raise e self.serialize_formats = serialize if not part_configs: part_configs = {} self.part_configs = part_configs self.search = search self.replace = replace def _labels_for_format(self, serialize_format): return ( label for _, label, _, _ in Formatter().parse(serialize_format) if label ) def order(self): # currently, order depends on the first given serialization format # this seems like a good idea because this should be the most complete format return self._labels_for_format(self.serialize_formats[0]) def parse(self, version_string): regexp_one_line = "".join([l.split("#")[0].strip() for l in self.parse_regex.pattern.splitlines()]) logger.info("Parsing version '{}' using regexp '{}'".format(version_string, regexp_one_line)) match = self.parse_regex.search(version_string) _parsed = {} if not match: logger.warn("Evaluating 'parse' option: '{}' does not parse current version '{}'".format( self.parse_regex.pattern, version_string)) return for key, value in match.groupdict().items(): _parsed[key] = VersionPart(value, self.part_configs.get(key)) v = Version(_parsed, version_string) logger.info("Parsed the following values: %s" % keyvaluestring(v._values)) return v def _serialize(self, version, serialize_format, context, raise_if_incomplete=False): """ Attempts to serialize a version with the given serialization format. Raises MissingValueForSerializationException if not serializable """ values = context.copy() for k in version: values[k] = version[k] # TODO dump complete context on debug level try: # test whether all parts required in the format have values serialized = serialize_format.format(**values) except KeyError as e: missing_key = getattr(e, 'message', # Python 2 e.args[0] # Python 3 ) raise MissingValueForSerializationException( "Did not find key {} in {} when serializing version number".format( repr(missing_key), repr(version))) keys_needing_representation = set() found_required = False for k in self.order(): v = values[k] if not isinstance(v, VersionPart): # values coming from environment variables don't need # representation continue if not v.is_optional(): found_required = True keys_needing_representation.add(k) elif not found_required: keys_needing_representation.add(k) required_by_format = set(self._labels_for_format(serialize_format)) # try whether all parsed keys are represented if raise_if_incomplete: if not (keys_needing_representation <= required_by_format): raise IncompleteVersionRepresenationException( "Could not represent '{}' in format '{}'".format( "', '".join(keys_needing_representation ^ required_by_format), serialize_format, )) return serialized def _choose_serialize_format(self, version, context): chosen = None # logger.info("Available serialization formats: '{}'".format("', '".join(self.serialize_formats))) for serialize_format in self.serialize_formats: try: self._serialize(version, serialize_format, context, raise_if_incomplete=True) chosen = serialize_format # logger.info("Found '{}' to be a usable serialization format".format(chosen)) except IncompleteVersionRepresenationException as e: # logger.info(e.message) if not chosen: chosen = serialize_format except MissingValueForSerializationException as e: logger.info(e.message) raise e if not chosen: raise KeyError("Did not find suitable serialization format") # logger.info("Selected serialization format '{}'".format(chosen)) return chosen def serialize(self, version, context): serialized = self._serialize(version, self._choose_serialize_format(version, context), context) # logger.info("Serialized to '{}'".format(serialized)) return serialized OPTIONAL_ARGUMENTS_THAT_TAKE_VALUES = [ '--config-file', '--current-version', '--message', '--new-version', '--parse', '--serialize', '--search', '--replace', '--tag-name', ] def split_args_in_optional_and_positional(args): # manually parsing positional arguments because stupid argparse can't mix # positional and optional arguments positions = [] for i, arg in enumerate(args): previous = None if i > 0: previous = args[i-1] if ((not arg.startswith('--')) and (previous not in OPTIONAL_ARGUMENTS_THAT_TAKE_VALUES)): positions.append(i) positionals = [arg for i, arg in enumerate(args) if i in positions] args = [arg for i, arg in enumerate(args) if i not in positions] return (positionals, args) def main(original_args=None): positionals, args = split_args_in_optional_and_positional( sys.argv[1:] if original_args is None else original_args ) if len(positionals[1:]) > 2: warnings.warn("Giving multiple files on the command line will be deprecated, please use [bumpversion:file:...] in a config file.", PendingDeprecationWarning) parser1 = argparse.ArgumentParser(add_help=False) parser1.add_argument( '--config-file', metavar='FILE', default=argparse.SUPPRESS, required=False, help='Config file to read most of the variables from (default: .bumpversion.cfg)') parser1.add_argument( '--verbose', action='count', default=0, help='Print verbose logging to stderr', required=False) parser1.add_argument( '--list', action='store_true', default=False, help='List machine readable information', required=False) parser1.add_argument( '--allow-dirty', action='store_true', default=False, help="Don't abort if working directory is dirty", required=False) known_args, remaining_argv = parser1.parse_known_args(args) logformatter = logging.Formatter('%(message)s') if len(logger.handlers) == 0: ch = logging.StreamHandler(sys.stderr) ch.setFormatter(logformatter) logger.addHandler(ch) if len(logger_list.handlers) == 0: ch2 = logging.StreamHandler(sys.stdout) ch2.setFormatter(logformatter) logger_list.addHandler(ch2) if known_args.list: logger_list.setLevel(1) log_level = { 0: logging.WARNING, 1: logging.INFO, 2: logging.DEBUG, }.get(known_args.verbose, logging.DEBUG) logger.setLevel(log_level) logger.debug("Starting {}".format(DESCRIPTION)) defaults = {} vcs_info = {} for vcs in VCS: if vcs.is_usable(): vcs_info.update(vcs.latest_tag_info()) if 'current_version' in vcs_info: defaults['current_version'] = vcs_info['current_version'] config = RawConfigParser('') # don't transform keys to lowercase (which would be the default) config.optionxform = lambda option: option config.add_section('bumpversion') explicit_config = hasattr(known_args, 'config_file') if explicit_config: config_file = known_args.config_file elif not os.path.exists('.bumpversion.cfg') and \ os.path.exists('setup.cfg'): config_file = 'setup.cfg' else: config_file = '.bumpversion.cfg' config_file_exists = os.path.exists(config_file) part_configs = {} files = [] if config_file_exists: logger.info("Reading config file {}:".format(config_file)) logger.info(io.open(config_file, 'rt', encoding='utf-8').read()) config.readfp(io.open(config_file, 'rt', encoding='utf-8')) log_config = StringIO() config.write(log_config) if 'files' in dict(config.items("bumpversion")): warnings.warn( "'files =' configuration is will be deprecated, please use [bumpversion:file:...]", PendingDeprecationWarning ) defaults.update(dict(config.items("bumpversion"))) for listvaluename in ("serialize",): try: value = config.get("bumpversion", listvaluename) defaults[listvaluename] = list(filter(None, (x.strip() for x in value.splitlines()))) except NoOptionError: pass # no default value then ;) for boolvaluename in ("commit", "tag", "dry_run"): try: defaults[boolvaluename] = config.getboolean( "bumpversion", boolvaluename) except NoOptionError: pass # no default value then ;) for section_name in config.sections(): section_name_match = re.compile("^bumpversion:(file|part):(.+)").match(section_name) if not section_name_match: continue section_prefix, section_value = section_name_match.groups() section_config = dict(config.items(section_name)) if section_prefix == "part": ThisVersionPartConfiguration = NumericVersionPartConfiguration if 'values' in section_config: section_config['values'] = list(filter(None, (x.strip() for x in section_config['values'].splitlines()))) ThisVersionPartConfiguration = ConfiguredVersionPartConfiguration part_configs[section_value] = ThisVersionPartConfiguration(**section_config) elif section_prefix == "file": filename = section_value if 'serialize' in section_config: section_config['serialize'] = list(filter(None, (x.strip() for x in section_config['serialize'].splitlines()))) section_config['part_configs'] = part_configs if not 'parse' in section_config: section_config['parse'] = defaults.get("parse", '(?P\d+)\.(?P\d+)\.(?P\d+)') if not 'serialize' in section_config: section_config['serialize'] = defaults.get('serialize', [str('{major}.{minor}.{patch}')]) if not 'search' in section_config: section_config['search'] = defaults.get("search", '{current_version}') if not 'replace' in section_config: section_config['replace'] = defaults.get("replace", '{new_version}') files.append(ConfiguredFile(filename, VersionConfig(**section_config))) else: message = "Could not read config file at {}".format(config_file) if explicit_config: raise argparse.ArgumentTypeError(message) else: logger.info(message) parser2 = argparse.ArgumentParser(prog='bumpversion', add_help=False, parents=[parser1]) parser2.set_defaults(**defaults) parser2.add_argument('--current-version', metavar='VERSION', help='Version that needs to be updated', required=False) parser2.add_argument('--parse', metavar='REGEX', help='Regex parsing the version string', default=defaults.get("parse", '(?P\d+)\.(?P\d+)\.(?P\d+)')) parser2.add_argument('--serialize', metavar='FORMAT', action=DiscardDefaultIfSpecifiedAppendAction, help='How to format what is parsed back to a version', default=defaults.get("serialize", [str('{major}.{minor}.{patch}')])) parser2.add_argument('--search', metavar='SEARCH', help='Template for complete string to search', default=defaults.get("search", '{current_version}')) parser2.add_argument('--replace', metavar='REPLACE', help='Template for complete string to replace', default=defaults.get("replace", '{new_version}')) known_args, remaining_argv = parser2.parse_known_args(args) defaults.update(vars(known_args)) assert type(known_args.serialize) == list context = dict(list(time_context.items()) + list(prefixed_environ().items()) + list(vcs_info.items())) try: vc = VersionConfig( parse=known_args.parse, serialize=known_args.serialize, search=known_args.search, replace=known_args.replace, part_configs=part_configs, ) except sre_constants.error as e: sys.exit(1) current_version = vc.parse(known_args.current_version) if known_args.current_version else None new_version = None if not 'new_version' in defaults and known_args.current_version: try: if current_version and len(positionals) > 0: logger.info("Attempting to increment part '{}'".format(positionals[0])) new_version = current_version.bump(positionals[0], vc.order()) logger.info("Values are now: " + keyvaluestring(new_version._values)) defaults['new_version'] = vc.serialize(new_version, context) except MissingValueForSerializationException as e: logger.info("Opportunistic finding of new_version failed: " + e.message) except IncompleteVersionRepresenationException as e: logger.info("Opportunistic finding of new_version failed: " + e.message) except KeyError as e: logger.info("Opportunistic finding of new_version failed") parser3 = argparse.ArgumentParser( prog='bumpversion', description=DESCRIPTION, formatter_class=argparse.ArgumentDefaultsHelpFormatter, conflict_handler='resolve', parents=[parser2], ) parser3.set_defaults(**defaults) parser3.add_argument('--current-version', metavar='VERSION', help='Version that needs to be updated', required=not 'current_version' in defaults) parser3.add_argument('--dry-run', '-n', action='store_true', default=False, help="Don't write any files, just pretend.") parser3.add_argument('--new-version', metavar='VERSION', help='New version that should be in the files', required=not 'new_version' in defaults) commitgroup = parser3.add_mutually_exclusive_group() commitgroup.add_argument('--commit', action='store_true', dest="commit", help='Commit to version control', default=defaults.get("commit", False)) commitgroup.add_argument('--no-commit', action='store_false', dest="commit", help='Do not commit to version control', default=argparse.SUPPRESS) taggroup = parser3.add_mutually_exclusive_group() taggroup.add_argument('--tag', action='store_true', dest="tag", default=defaults.get("tag", False), help='Create a tag in version control') taggroup.add_argument('--no-tag', action='store_false', dest="tag", help='Do not create a tag in version control', default=argparse.SUPPRESS) parser3.add_argument('--tag-name', metavar='TAG_NAME', help='Tag name (only works with --tag)', default=defaults.get('tag_name', 'v{new_version}')) parser3.add_argument('--message', '-m', metavar='COMMIT_MSG', help='Commit message', default=defaults.get('message', 'Bump version: {current_version} → {new_version}')) file_names = [] if 'files' in defaults: assert defaults['files'] != None file_names = defaults['files'].split(' ') parser3.add_argument('part', help='Part of the version to be bumped.') parser3.add_argument('files', metavar='file', nargs='*', help='Files to change', default=file_names) args = parser3.parse_args(remaining_argv + positionals) if args.dry_run: logger.info("Dry run active, won't touch any files.") if args.new_version: new_version = vc.parse(args.new_version) logger.info("New version will be '{}'".format(args.new_version)) file_names = file_names or positionals[1:] for file_name in file_names: files.append(ConfiguredFile(file_name, vc)) for vcs in VCS: if vcs.is_usable(): try: vcs.assert_nondirty() except WorkingDirectoryIsDirtyException as e: if not defaults['allow_dirty']: logger.warn( "{}\n\nUse --allow-dirty to override this if you know what you're doing.".format(e.message)) raise break else: vcs = None # make sure files exist and contain version string logger.info("Asserting files {} contain the version string:".format(", ".join([str(f) for f in files]))) for f in files: f.should_contain_version(current_version, context) # change version string in files for f in files: f.replace(current_version, new_version, context, args.dry_run) commit_files = [f.path for f in files] config.set('bumpversion', 'new_version', args.new_version) for key, value in config.items('bumpversion'): logger_list.info("{}={}".format(key, value)) config.remove_option('bumpversion', 'new_version') config.set('bumpversion', 'current_version', args.new_version) new_config = StringIO() try: write_to_config_file = (not args.dry_run) and config_file_exists logger.info("{} to config file {}:".format( "Would write" if not write_to_config_file else "Writing", config_file, )) config.write(new_config) logger.info(new_config.getvalue()) if write_to_config_file: with io.open(config_file, 'wb') as f: f.write(new_config.getvalue().encode('utf-8')) except UnicodeEncodeError: warnings.warn( "Unable to write UTF-8 to config file, because of an old configparser version. " "Update with `pip install --upgrade configparser`." ) if config_file_exists: commit_files.append(config_file) if not vcs: return assert vcs.is_usable(), "Did find '{}' unusable, unable to commit.".format(vcs.__name__) do_commit = (not args.dry_run) and args.commit do_tag = (not args.dry_run) and args.tag logger.info("{} {} commit".format( "Would prepare" if not do_commit else "Preparing", vcs.__name__, )) for path in commit_files: logger.info("{} changes in file '{}' to {}".format( "Would add" if not do_commit else "Adding", path, vcs.__name__, )) if do_commit: vcs.add_path(path) vcs_context = { "current_version": args.current_version, "new_version": args.new_version, } vcs_context.update(time_context) vcs_context.update(prefixed_environ()) commit_message = args.message.format(**vcs_context) logger.info("{} to {} with message '{}'".format( "Would commit" if not do_commit else "Committing", vcs.__name__, commit_message, )) if do_commit: vcs.commit(message=commit_message) tag_name = args.tag_name.format(**vcs_context) logger.info("{} '{}' in {}".format( "Would tag" if not do_tag else "Tagging", tag_name, vcs.__name__ )) if do_tag: vcs.tag(tag_name) bumpversion-0.5.3/bumpversion.egg-info/0000755000076500000240000000000012513425757020374 5ustar filipstaff00000000000000bumpversion-0.5.3/bumpversion.egg-info/dependency_links.txt0000644000076500000240000000000112513425755024440 0ustar filipstaff00000000000000 bumpversion-0.5.3/bumpversion.egg-info/entry_points.txt0000644000076500000240000000006212513425755023666 0ustar filipstaff00000000000000[console_scripts] bumpversion = bumpversion:main bumpversion-0.5.3/bumpversion.egg-info/PKG-INFO0000644000076500000240000005166212513425755021501 0ustar filipstaff00000000000000Metadata-Version: 1.1 Name: bumpversion Version: 0.5.3 Summary: Version-bump your software with a single command! Home-page: https://github.com/peritus/bumpversion Author: Filip Noetzel Author-email: filip+bumpversion@j03.de License: MIT Description: =========== bumpversion =========== A small command line tool to simplify releasing software by updating all version strings in your source code by the correct increment. Also creates commits and tags: - version formats are highly configurable - works without any VCS, but happily reads tag information from and writes commits and tags to Git and Mercurial if available - just handles text files, so it's not specific to any programming language .. image:: https://travis-ci.org/peritus/bumpversion.png?branch=master :target: https://travis-ci.org/peritus/bumpversion .. image:: https://ci.appveyor.com/api/projects/status/bxq8185bpq9u3sjd/branch/master?svg=true :target: https://ci.appveyor.com/project/peritus/bumpversion Screencast ========== .. image:: https://dl.dropboxusercontent.com/u/8735936/Screen%20Shot%202013-04-12%20at%202.43.46%20PM.png :target: https://asciinema.org/a/3828 Installation ============ You can download and install the latest version of this software from the Python package index (PyPI) as follows:: pip install --upgrade bumpversion Usage ===== There are two modes of operation: On the command line for single-file operation and using a configuration file for more complex multi-file operations. :: bumpversion [options] part [file] ``part`` (required) The part of the version to increase, e.g. ``minor``. Valid values include those given in the ``--serialize`` / ``--parse`` option. Example `bumping 0.5.1 to 0.6.0`:: bumpversion --current-version 0.5.1 minor src/VERSION ``[file]`` **default: none** (optional) The file that will be modified. If not given, the list of ``[bumpversion:file:…]`` sections from the configuration file will be used. If no files are mentioned on the configuration file either, are no files will be modified. Example `bumping 1.1.9 to 2.0.0`:: bumpversion --current-version 1.1.9 major setup.py Configuration +++++++++++++ All options can optionally be specified in a config file called ``.bumpversion.cfg`` so that once you know how ``bumpversion`` needs to be configured for one particular software package, you can run it without specifying options later. You should add that file to VCS so others can also bump versions. Options on the command line take precedence over those from the config file, which take precedence over those derived from the environment and then from the defaults. Example ``.bumpversion.cfg``:: [bumpversion] current_version = 0.2.9 commit = True tag = True [bumpversion:file:setup.py] If no ``.bumpversion.cfg`` exists, ``bumpversion`` will also look into ``setup.cfg`` for configuration. Global configuration -------------------- General configuration is grouped in a ``[bumpversion]`` section. ``current_version =`` **no default value** (required) The current version of the software package before bumping. Also available as ``--current-version`` (e.g. ``bumpversion --current-version 0.5.1 patch setup.py``) ``new_version =`` **no default value** (optional) The version of the software package after the increment. If not given will be automatically determined. Also available as ``--new-version`` (e.g. `to go from 0.5.1 directly to 0.6.1`: ``bumpversion --current-version 0.5.1 --new-version 0.6.1 patch setup.py``). ``tag = (True | False)`` **default:** False (`Don't create a tag`) Whether to create a tag, that is the new version, prefixed with the character "``v``". If you are using git, don't forget to ``git-push`` with the ``--tags`` flag. Also available on the command line as ``(--tag | --no-tag)``. ``tag_name =`` **default:** "``v{new_version}``" The name of the tag that will be created. Only valid when using ``--tag`` / ``tag = True``. This is templated using the `Python Format String Syntax `_. Available in the template context are ``current_version`` and ``new_version`` as well as all environment variables (prefixed with ``$``). You can also use the variables ``now`` or ``utcnow`` to get a current timestamp. Both accept datetime formatting (when used like as in ``{now:%d.%m.%Y}``). Also available as ``--tag-name`` (e.g. ``bumpversion --message 'Jenkins Build {$BUILD_NUMBER}: {new_version}' patch``). ``commit = (True | False)`` **default:** ``False`` (`Don't create a commit`) Whether to create a commit using git or Mercurial. Also available as ``(--commit | --no-commit)``. ``message =`` **default:** "``Bump version: {current_version} → {new_version}``" The commit message to use when creating a commit. Only valid when using ``--commit`` / ``commit = True``. This is templated using the `Python Format String Syntax `_. Available in the template context are ``current_version`` and ``new_version`` as well as all environment variables (prefixed with ``$``). You can also use the variables ``now`` or ``utcnow`` to get a current timestamp. Both accept datetime formatting (when used like as in ``{now:%d.%m.%Y}``). Also available as ``--message`` (e.g.: ``bumpversion --message '[{now:%Y-%m-%d}] Jenkins Build {$BUILD_NUMBER}: {new_version}' patch``) Part specific configuration --------------------------- A version string consists of one or more parts, e.g. the version ``1.0.2`` has three parts, separated by a dot (``.``) character. In the default configuration these parts are named `major`, `minor`, `patch`, however you can customize that using the ``parse``/``serialize`` option. By default all parts considered numeric, that is their initial value is ``0`` and they are increased as integers. Also, the value ``0`` is considered to be optional if it's not needed for serialization, i.e. the version ``1.4.0`` is equal to ``1.4`` if ``{major}.{minor}`` is given as a ``serialize`` value. For advanced versioning schemes, non-numeric parts may be desirable (e.g. to identify `alpha or beta versions `_, to indicate the stage of development, the flavor of the software package or a release name). To do so, you can use a ``[bumpversion:part:…]`` section containing the part's name (e.g. a part named ``release_name`` is configured in a section called ``[bumpversion:part:release_name]``. The following options are valid inside a part configuration: ``values =`` **default**: numeric (i.e. ``0``, ``1``, ``2``, …) Explicit list of all values that will be iterated when bumping that specific part. Example:: [bumpversion:part:release_name] values = witty-warthog ridiculous-rat marvelous-mantis ``optional_value =`` **default**: The first entry in ``values =``. If the value of the part matches this value it is considered optional, i.e. it's representation in a ``--serialize`` possibility is not required. Example:: [bumpversion] current_version = 1.alpha parse = (?P\d+)\.(?P.*) serialize = {num}.{release} {num} [bumpversion:part:release] optional_value = gamma values = alpha beta gamma Here, ``bumpversion release`` would bump ``1.alpha`` to ``1.beta``. Executing ``bumpversion release`` again would bump ``1.beta`` to ``1``, because `release` being ``gamma`` is configured optional. ``first_value =`` **default**: The first entry in ``values =``. When the part is reset, the value will be set to the value specified here. File specific configuration --------------------------- ``[bumpversion:file:…]`` ``parse =`` **default:** "``(?P\d+)\.(?P\d+)\.(?P\d+)``" Regular expression (using `Python regular expression syntax `_) on how to find and parse the version string. Is required to parse all strings produced by ``serialize =``. Named matching groups ("``(?P...)``") provide values to as the ``part`` argument. Also available as ``--parse`` ``serialize =`` **default:** "``{major}.{minor}.{patch}``" Template specifying how to serialize the version parts back to a version string. This is templated using the `Python Format String Syntax `_. Available in the template context are parsed values of the named groups specified in ``parse =`` as well as all environment variables (prefixed with ``$``). Can be specified multiple times, bumpversion will try the serialization formats beginning with the first and choose the last one where all values can be represented like this:: serialize = {major}.{minor} {major} Given the example above, the new version *1.9* it will be serialized as ``1.9``, but the version *2.0* will be serialized as ``2``. Also available as ``--serialize``. Multiple values on the command line are given like ``--serialize {major}.{minor} --serialize {major}`` ``search =`` **default:** "``{current_version}``" Template string how to search for the string to be replaced in the file. Useful if the remotest possibility exists that the current version number might be multiple times in the file and you mean to only bump one of the occurences. Can be multiple lines, templated using `Python Format String Syntax `_. ``replace =`` **default:** "``{new_version}``" Template to create the string that will replace the current version number in the file. Given this ``requirements.txt``:: Django>=1.5.6,<1.6 MyProject==1.5.6 using this ``.bumpversion.cfg`` will ensure only the line containing ``MyProject`` will be changed:: [bumpversion] current_version = 1.5.6 [bumpversion:file:requirements.txt] search = MyProject=={current_version} replace = MyProject=={new_version} Can be multiple lines, templated using `Python Format String Syntax `_. Options ======= Most of the configuration values above can also be given as an option. Additionally, the following options are available: ``--dry-run, -n`` Don't touch any files, just pretend. Best used with ``--verbose``. ``--allow-dirty`` Normally, bumpversion will abort if the working directory is dirty to protect yourself from releasing unversioned files and/or overwriting unsaved changes. Use this option to override this check. ``--verbose`` Print useful information to stderr ``--list`` List machine readable information to stdout for consumption by other programs. Example output:: current_version=0.0.18 new_version=0.0.19 ``-h, --help`` Print help and exit Development =========== Development of this happens on GitHub, patches including tests, documentation are very welcome, as well as bug reports! Also please open an issue if this tool does not support every aspect of bumping versions in your development workflow, as it is intended to be very versatile. How to release bumpversion itself +++++++++++++++++++++++++++++++++ Execute the following commands:: git checkout master git pull tox bumpversion release python setup.py sdist bdist_wheel upload bumpversion --no-tag patch git push origin master --tags License ======= bumpversion is licensed under the MIT License - see the LICENSE.rst file for details Changes ======= **unreleased** **v0.5.3** - Fix bug where ``--new-version`` value was not used when config was present (thanks @cscetbon @ecordell (`#60 `_) - Preserve case of keys config file (thanks theskumar `#75 `_) - Windows CRLF improvements (thanks @thebjorn) **v0.5.1** - Document file specific options ``search =`` and ``replace =`` (introduced in 0.5.0) - Fix parsing individual labels from ``serialize =`` config even if there are characters after the last label (thanks @mskrajnowski `#56 `_). - Fix: Don't crash in git repositories that have tags that contain hyphens (`#51 `_) (`#52 `_). - Fix: Log actual content of the config file, not what ConfigParser prints after reading it. - Fix: Support multiline values in ``search =`` - also load configuration from ``setup.cfg`` (thanks @t-8ch `#57 `_). **v0.5.0** This is a major one, containing two larger features, that require some changes in the configuration format. This release is fully backwards compatible to *v0.4.1*, however deprecates two uses that will be removed in a future version. - New feature: Part specific configuration - New feature: File specific configuration - New feature: parse option can now span multiple line (allows to comment complex regular expressions. See `re.VERBOSE in the Python documentation `_ for details, `this testcase `_ as an example.) - New feature: ``--allow-dirty`` (`#42 `_). - Fix: Save the files in binary mode to avoid mutating newlines (thanks @jaraco `#45 `_). - License: bumpversion is now licensed under the MIT License (`#47 `_) - Deprecate multiple files on the command line (use a configuration file instead, or invoke ``bumpversion`` multiple times) - Deprecate 'files =' configuration (use file specific configuration instead) **v0.4.1** - Add --list option (`#39 `_) - Use temporary files for handing over commit/tag messages to git/hg (`#36 `_) - Fix: don't encode stdout as utf-8 on py3 (`#40 `_) - Fix: logging of content of config file was wrong **v0.4.0** - Add --verbose option (`#21 `_ `#30 `_) - Allow option --serialize multiple times **v0.3.8** - Fix: --parse/--serialize didn't work from cfg (`#34 `_) **v0.3.7** - Don't fail if git or hg is not installed (thanks @keimlink) - "files" option is now optional (`#16 `_) - Fix bug related to dirty work dir (`#28 `_) **v0.3.6** - Fix --tag default (thanks @keimlink) **v0.3.5** - add {now} and {utcnow} to context - use correct file encoding writing to config file. NOTE: If you are using Python2 and want to use UTF-8 encoded characters in your config file, you need to update ConfigParser like using 'pip install -U configparser' - leave current_version in config even if available from vcs tags (was confusing) - print own version number in usage - allow bumping parts that contain non-numerics - various fixes regarding file encoding **v0.3.4** - bugfix: tag_name and message in .bumpversion.cfg didn't have an effect (`#9 `_) **v0.3.3** - add --tag-name option - now works on Python 3.2, 3.3 and PyPy **v0.3.2** - bugfix: Read only tags from `git describe` that look like versions **v0.3.1** - bugfix: ``--help`` in git workdir raising AssertionError - bugfix: fail earlier if one of files does not exist - bugfix: ``commit = True`` / ``tag = True`` in .bumpversion.cfg had no effect **v0.3.0** - **BREAKING CHANGE** The ``--bump`` argument was removed, this is now the first positional argument. If you used ``bumpversion --bump major`` before, you can use ``bumpversion major`` now. If you used ``bumpversion`` without arguments before, you now need to specify the part (previous default was ``patch``) as in ``bumpversion patch``). **v0.2.2** - add --no-commit, --no-tag **v0.2.1** - If available, use git to learn about current version **v0.2.0** - Mercurial support **v0.1.1** - Only create a tag when it's requested (thanks @gvangool) **v0.1.0** - Initial public version Platform: UNKNOWN Classifier: Development Status :: 4 - Beta Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.2 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: Implementation :: PyPy bumpversion-0.5.3/bumpversion.egg-info/SOURCES.txt0000644000076500000240000000036312513425756022261 0ustar filipstaff00000000000000MANIFEST.in README.rst setup.cfg setup.py bumpversion/__init__.py bumpversion.egg-info/PKG-INFO bumpversion.egg-info/SOURCES.txt bumpversion.egg-info/dependency_links.txt bumpversion.egg-info/entry_points.txt bumpversion.egg-info/top_level.txtbumpversion-0.5.3/bumpversion.egg-info/top_level.txt0000644000076500000240000000001412513425755023117 0ustar filipstaff00000000000000bumpversion bumpversion-0.5.3/MANIFEST.in0000644000076500000240000000002412121015557016047 0ustar filipstaff00000000000000include README.rst bumpversion-0.5.3/PKG-INFO0000644000076500000240000005166212513425757015440 0ustar filipstaff00000000000000Metadata-Version: 1.1 Name: bumpversion Version: 0.5.3 Summary: Version-bump your software with a single command! Home-page: https://github.com/peritus/bumpversion Author: Filip Noetzel Author-email: filip+bumpversion@j03.de License: MIT Description: =========== bumpversion =========== A small command line tool to simplify releasing software by updating all version strings in your source code by the correct increment. Also creates commits and tags: - version formats are highly configurable - works without any VCS, but happily reads tag information from and writes commits and tags to Git and Mercurial if available - just handles text files, so it's not specific to any programming language .. image:: https://travis-ci.org/peritus/bumpversion.png?branch=master :target: https://travis-ci.org/peritus/bumpversion .. image:: https://ci.appveyor.com/api/projects/status/bxq8185bpq9u3sjd/branch/master?svg=true :target: https://ci.appveyor.com/project/peritus/bumpversion Screencast ========== .. image:: https://dl.dropboxusercontent.com/u/8735936/Screen%20Shot%202013-04-12%20at%202.43.46%20PM.png :target: https://asciinema.org/a/3828 Installation ============ You can download and install the latest version of this software from the Python package index (PyPI) as follows:: pip install --upgrade bumpversion Usage ===== There are two modes of operation: On the command line for single-file operation and using a configuration file for more complex multi-file operations. :: bumpversion [options] part [file] ``part`` (required) The part of the version to increase, e.g. ``minor``. Valid values include those given in the ``--serialize`` / ``--parse`` option. Example `bumping 0.5.1 to 0.6.0`:: bumpversion --current-version 0.5.1 minor src/VERSION ``[file]`` **default: none** (optional) The file that will be modified. If not given, the list of ``[bumpversion:file:…]`` sections from the configuration file will be used. If no files are mentioned on the configuration file either, are no files will be modified. Example `bumping 1.1.9 to 2.0.0`:: bumpversion --current-version 1.1.9 major setup.py Configuration +++++++++++++ All options can optionally be specified in a config file called ``.bumpversion.cfg`` so that once you know how ``bumpversion`` needs to be configured for one particular software package, you can run it without specifying options later. You should add that file to VCS so others can also bump versions. Options on the command line take precedence over those from the config file, which take precedence over those derived from the environment and then from the defaults. Example ``.bumpversion.cfg``:: [bumpversion] current_version = 0.2.9 commit = True tag = True [bumpversion:file:setup.py] If no ``.bumpversion.cfg`` exists, ``bumpversion`` will also look into ``setup.cfg`` for configuration. Global configuration -------------------- General configuration is grouped in a ``[bumpversion]`` section. ``current_version =`` **no default value** (required) The current version of the software package before bumping. Also available as ``--current-version`` (e.g. ``bumpversion --current-version 0.5.1 patch setup.py``) ``new_version =`` **no default value** (optional) The version of the software package after the increment. If not given will be automatically determined. Also available as ``--new-version`` (e.g. `to go from 0.5.1 directly to 0.6.1`: ``bumpversion --current-version 0.5.1 --new-version 0.6.1 patch setup.py``). ``tag = (True | False)`` **default:** False (`Don't create a tag`) Whether to create a tag, that is the new version, prefixed with the character "``v``". If you are using git, don't forget to ``git-push`` with the ``--tags`` flag. Also available on the command line as ``(--tag | --no-tag)``. ``tag_name =`` **default:** "``v{new_version}``" The name of the tag that will be created. Only valid when using ``--tag`` / ``tag = True``. This is templated using the `Python Format String Syntax `_. Available in the template context are ``current_version`` and ``new_version`` as well as all environment variables (prefixed with ``$``). You can also use the variables ``now`` or ``utcnow`` to get a current timestamp. Both accept datetime formatting (when used like as in ``{now:%d.%m.%Y}``). Also available as ``--tag-name`` (e.g. ``bumpversion --message 'Jenkins Build {$BUILD_NUMBER}: {new_version}' patch``). ``commit = (True | False)`` **default:** ``False`` (`Don't create a commit`) Whether to create a commit using git or Mercurial. Also available as ``(--commit | --no-commit)``. ``message =`` **default:** "``Bump version: {current_version} → {new_version}``" The commit message to use when creating a commit. Only valid when using ``--commit`` / ``commit = True``. This is templated using the `Python Format String Syntax `_. Available in the template context are ``current_version`` and ``new_version`` as well as all environment variables (prefixed with ``$``). You can also use the variables ``now`` or ``utcnow`` to get a current timestamp. Both accept datetime formatting (when used like as in ``{now:%d.%m.%Y}``). Also available as ``--message`` (e.g.: ``bumpversion --message '[{now:%Y-%m-%d}] Jenkins Build {$BUILD_NUMBER}: {new_version}' patch``) Part specific configuration --------------------------- A version string consists of one or more parts, e.g. the version ``1.0.2`` has three parts, separated by a dot (``.``) character. In the default configuration these parts are named `major`, `minor`, `patch`, however you can customize that using the ``parse``/``serialize`` option. By default all parts considered numeric, that is their initial value is ``0`` and they are increased as integers. Also, the value ``0`` is considered to be optional if it's not needed for serialization, i.e. the version ``1.4.0`` is equal to ``1.4`` if ``{major}.{minor}`` is given as a ``serialize`` value. For advanced versioning schemes, non-numeric parts may be desirable (e.g. to identify `alpha or beta versions `_, to indicate the stage of development, the flavor of the software package or a release name). To do so, you can use a ``[bumpversion:part:…]`` section containing the part's name (e.g. a part named ``release_name`` is configured in a section called ``[bumpversion:part:release_name]``. The following options are valid inside a part configuration: ``values =`` **default**: numeric (i.e. ``0``, ``1``, ``2``, …) Explicit list of all values that will be iterated when bumping that specific part. Example:: [bumpversion:part:release_name] values = witty-warthog ridiculous-rat marvelous-mantis ``optional_value =`` **default**: The first entry in ``values =``. If the value of the part matches this value it is considered optional, i.e. it's representation in a ``--serialize`` possibility is not required. Example:: [bumpversion] current_version = 1.alpha parse = (?P\d+)\.(?P.*) serialize = {num}.{release} {num} [bumpversion:part:release] optional_value = gamma values = alpha beta gamma Here, ``bumpversion release`` would bump ``1.alpha`` to ``1.beta``. Executing ``bumpversion release`` again would bump ``1.beta`` to ``1``, because `release` being ``gamma`` is configured optional. ``first_value =`` **default**: The first entry in ``values =``. When the part is reset, the value will be set to the value specified here. File specific configuration --------------------------- ``[bumpversion:file:…]`` ``parse =`` **default:** "``(?P\d+)\.(?P\d+)\.(?P\d+)``" Regular expression (using `Python regular expression syntax `_) on how to find and parse the version string. Is required to parse all strings produced by ``serialize =``. Named matching groups ("``(?P...)``") provide values to as the ``part`` argument. Also available as ``--parse`` ``serialize =`` **default:** "``{major}.{minor}.{patch}``" Template specifying how to serialize the version parts back to a version string. This is templated using the `Python Format String Syntax `_. Available in the template context are parsed values of the named groups specified in ``parse =`` as well as all environment variables (prefixed with ``$``). Can be specified multiple times, bumpversion will try the serialization formats beginning with the first and choose the last one where all values can be represented like this:: serialize = {major}.{minor} {major} Given the example above, the new version *1.9* it will be serialized as ``1.9``, but the version *2.0* will be serialized as ``2``. Also available as ``--serialize``. Multiple values on the command line are given like ``--serialize {major}.{minor} --serialize {major}`` ``search =`` **default:** "``{current_version}``" Template string how to search for the string to be replaced in the file. Useful if the remotest possibility exists that the current version number might be multiple times in the file and you mean to only bump one of the occurences. Can be multiple lines, templated using `Python Format String Syntax `_. ``replace =`` **default:** "``{new_version}``" Template to create the string that will replace the current version number in the file. Given this ``requirements.txt``:: Django>=1.5.6,<1.6 MyProject==1.5.6 using this ``.bumpversion.cfg`` will ensure only the line containing ``MyProject`` will be changed:: [bumpversion] current_version = 1.5.6 [bumpversion:file:requirements.txt] search = MyProject=={current_version} replace = MyProject=={new_version} Can be multiple lines, templated using `Python Format String Syntax `_. Options ======= Most of the configuration values above can also be given as an option. Additionally, the following options are available: ``--dry-run, -n`` Don't touch any files, just pretend. Best used with ``--verbose``. ``--allow-dirty`` Normally, bumpversion will abort if the working directory is dirty to protect yourself from releasing unversioned files and/or overwriting unsaved changes. Use this option to override this check. ``--verbose`` Print useful information to stderr ``--list`` List machine readable information to stdout for consumption by other programs. Example output:: current_version=0.0.18 new_version=0.0.19 ``-h, --help`` Print help and exit Development =========== Development of this happens on GitHub, patches including tests, documentation are very welcome, as well as bug reports! Also please open an issue if this tool does not support every aspect of bumping versions in your development workflow, as it is intended to be very versatile. How to release bumpversion itself +++++++++++++++++++++++++++++++++ Execute the following commands:: git checkout master git pull tox bumpversion release python setup.py sdist bdist_wheel upload bumpversion --no-tag patch git push origin master --tags License ======= bumpversion is licensed under the MIT License - see the LICENSE.rst file for details Changes ======= **unreleased** **v0.5.3** - Fix bug where ``--new-version`` value was not used when config was present (thanks @cscetbon @ecordell (`#60 `_) - Preserve case of keys config file (thanks theskumar `#75 `_) - Windows CRLF improvements (thanks @thebjorn) **v0.5.1** - Document file specific options ``search =`` and ``replace =`` (introduced in 0.5.0) - Fix parsing individual labels from ``serialize =`` config even if there are characters after the last label (thanks @mskrajnowski `#56 `_). - Fix: Don't crash in git repositories that have tags that contain hyphens (`#51 `_) (`#52 `_). - Fix: Log actual content of the config file, not what ConfigParser prints after reading it. - Fix: Support multiline values in ``search =`` - also load configuration from ``setup.cfg`` (thanks @t-8ch `#57 `_). **v0.5.0** This is a major one, containing two larger features, that require some changes in the configuration format. This release is fully backwards compatible to *v0.4.1*, however deprecates two uses that will be removed in a future version. - New feature: Part specific configuration - New feature: File specific configuration - New feature: parse option can now span multiple line (allows to comment complex regular expressions. See `re.VERBOSE in the Python documentation `_ for details, `this testcase `_ as an example.) - New feature: ``--allow-dirty`` (`#42 `_). - Fix: Save the files in binary mode to avoid mutating newlines (thanks @jaraco `#45 `_). - License: bumpversion is now licensed under the MIT License (`#47 `_) - Deprecate multiple files on the command line (use a configuration file instead, or invoke ``bumpversion`` multiple times) - Deprecate 'files =' configuration (use file specific configuration instead) **v0.4.1** - Add --list option (`#39 `_) - Use temporary files for handing over commit/tag messages to git/hg (`#36 `_) - Fix: don't encode stdout as utf-8 on py3 (`#40 `_) - Fix: logging of content of config file was wrong **v0.4.0** - Add --verbose option (`#21 `_ `#30 `_) - Allow option --serialize multiple times **v0.3.8** - Fix: --parse/--serialize didn't work from cfg (`#34 `_) **v0.3.7** - Don't fail if git or hg is not installed (thanks @keimlink) - "files" option is now optional (`#16 `_) - Fix bug related to dirty work dir (`#28 `_) **v0.3.6** - Fix --tag default (thanks @keimlink) **v0.3.5** - add {now} and {utcnow} to context - use correct file encoding writing to config file. NOTE: If you are using Python2 and want to use UTF-8 encoded characters in your config file, you need to update ConfigParser like using 'pip install -U configparser' - leave current_version in config even if available from vcs tags (was confusing) - print own version number in usage - allow bumping parts that contain non-numerics - various fixes regarding file encoding **v0.3.4** - bugfix: tag_name and message in .bumpversion.cfg didn't have an effect (`#9 `_) **v0.3.3** - add --tag-name option - now works on Python 3.2, 3.3 and PyPy **v0.3.2** - bugfix: Read only tags from `git describe` that look like versions **v0.3.1** - bugfix: ``--help`` in git workdir raising AssertionError - bugfix: fail earlier if one of files does not exist - bugfix: ``commit = True`` / ``tag = True`` in .bumpversion.cfg had no effect **v0.3.0** - **BREAKING CHANGE** The ``--bump`` argument was removed, this is now the first positional argument. If you used ``bumpversion --bump major`` before, you can use ``bumpversion major`` now. If you used ``bumpversion`` without arguments before, you now need to specify the part (previous default was ``patch``) as in ``bumpversion patch``). **v0.2.2** - add --no-commit, --no-tag **v0.2.1** - If available, use git to learn about current version **v0.2.0** - Mercurial support **v0.1.1** - Only create a tag when it's requested (thanks @gvangool) **v0.1.0** - Initial public version Platform: UNKNOWN Classifier: Development Status :: 4 - Beta Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.2 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: Implementation :: PyPy bumpversion-0.5.3/README.rst0000644000076500000240000004057512513425713016023 0ustar filipstaff00000000000000=========== bumpversion =========== Version-bump your software with a single command! A small command line tool to simplify releasing software by updating all version strings in your source code by the correct increment. Also creates commits and tags: - version formats are highly configurable - works without any VCS, but happily reads tag information from and writes commits and tags to Git and Mercurial if available - just handles text files, so it's not specific to any programming language .. image:: https://travis-ci.org/peritus/bumpversion.png?branch=master :target: https://travis-ci.org/peritus/bumpversion .. image:: https://ci.appveyor.com/api/projects/status/bxq8185bpq9u3sjd/branch/master?svg=true :target: https://ci.appveyor.com/project/peritus/bumpversion Screencast ========== .. image:: https://dl.dropboxusercontent.com/u/8735936/Screen%20Shot%202013-04-12%20at%202.43.46%20PM.png :target: https://asciinema.org/a/3828 Installation ============ You can download and install the latest version of this software from the Python package index (PyPI) as follows:: pip install --upgrade bumpversion Usage ===== There are two modes of operation: On the command line for single-file operation and using a `configuration file <#configuration>`_ for more complex multi-file operations. :: bumpversion [options] part [file] ``part`` (required) The part of the version to increase, e.g. ``minor``. Valid values include those given in the ``--serialize`` / ``--parse`` option. Example `bumping 0.5.1 to 0.6.0`:: bumpversion --current-version 0.5.1 minor src/VERSION ``[file]`` **default: none** (optional) The file that will be modified. If not given, the list of ``[bumpversion:file:…]`` sections from the configuration file will be used. If no files are mentioned on the configuration file either, are no files will be modified. Example `bumping 1.1.9 to 2.0.0`:: bumpversion --current-version 1.1.9 major setup.py Configuration +++++++++++++ All options can optionally be specified in a config file called ``.bumpversion.cfg`` so that once you know how ``bumpversion`` needs to be configured for one particular software package, you can run it without specifying options later. You should add that file to VCS so others can also bump versions. Options on the command line take precedence over those from the config file, which take precedence over those derived from the environment and then from the defaults. Example ``.bumpversion.cfg``:: [bumpversion] current_version = 0.2.9 commit = True tag = True [bumpversion:file:setup.py] If no ``.bumpversion.cfg`` exists, ``bumpversion`` will also look into ``setup.cfg`` for configuration. Global configuration -------------------- General configuration is grouped in a ``[bumpversion]`` section. ``current_version =`` **no default value** (required) The current version of the software package before bumping. Also available as ``--current-version`` (e.g. ``bumpversion --current-version 0.5.1 patch setup.py``) ``new_version =`` **no default value** (optional) The version of the software package after the increment. If not given will be automatically determined. Also available as ``--new-version`` (e.g. `to go from 0.5.1 directly to 0.6.1`: ``bumpversion --current-version 0.5.1 --new-version 0.6.1 patch setup.py``). ``tag = (True | False)`` **default:** False (`Don't create a tag`) Whether to create a tag, that is the new version, prefixed with the character "``v``". If you are using git, don't forget to ``git-push`` with the ``--tags`` flag. Also available on the command line as ``(--tag | --no-tag)``. ``tag_name =`` **default:** "``v{new_version}``" The name of the tag that will be created. Only valid when using ``--tag`` / ``tag = True``. This is templated using the `Python Format String Syntax `_. Available in the template context are ``current_version`` and ``new_version`` as well as all environment variables (prefixed with ``$``). You can also use the variables ``now`` or ``utcnow`` to get a current timestamp. Both accept datetime formatting (when used like as in ``{now:%d.%m.%Y}``). Also available as ``--tag-name`` (e.g. ``bumpversion --message 'Jenkins Build {$BUILD_NUMBER}: {new_version}' patch``). ``commit = (True | False)`` **default:** ``False`` (`Don't create a commit`) Whether to create a commit using git or Mercurial. Also available as ``(--commit | --no-commit)``. ``message =`` **default:** "``Bump version: {current_version} → {new_version}``" The commit message to use when creating a commit. Only valid when using ``--commit`` / ``commit = True``. This is templated using the `Python Format String Syntax `_. Available in the template context are ``current_version`` and ``new_version`` as well as all environment variables (prefixed with ``$``). You can also use the variables ``now`` or ``utcnow`` to get a current timestamp. Both accept datetime formatting (when used like as in ``{now:%d.%m.%Y}``). Also available as ``--message`` (e.g.: ``bumpversion --message '[{now:%Y-%m-%d}] Jenkins Build {$BUILD_NUMBER}: {new_version}' patch``) Part specific configuration --------------------------- A version string consists of one or more parts, e.g. the version ``1.0.2`` has three parts, separated by a dot (``.``) character. In the default configuration these parts are named `major`, `minor`, `patch`, however you can customize that using the ``parse``/``serialize`` option. By default all parts considered numeric, that is their initial value is ``0`` and they are increased as integers. Also, the value ``0`` is considered to be optional if it's not needed for serialization, i.e. the version ``1.4.0`` is equal to ``1.4`` if ``{major}.{minor}`` is given as a ``serialize`` value. For advanced versioning schemes, non-numeric parts may be desirable (e.g. to identify `alpha or beta versions `_, to indicate the stage of development, the flavor of the software package or a release name). To do so, you can use a ``[bumpversion:part:…]`` section containing the part's name (e.g. a part named ``release_name`` is configured in a section called ``[bumpversion:part:release_name]``. The following options are valid inside a part configuration: ``values =`` **default**: numeric (i.e. ``0``, ``1``, ``2``, …) Explicit list of all values that will be iterated when bumping that specific part. Example:: [bumpversion:part:release_name] values = witty-warthog ridiculous-rat marvelous-mantis ``optional_value =`` **default**: The first entry in ``values =``. If the value of the part matches this value it is considered optional, i.e. it's representation in a ``--serialize`` possibility is not required. Example:: [bumpversion] current_version = 1.alpha parse = (?P\d+)\.(?P.*) serialize = {num}.{release} {num} [bumpversion:part:release] optional_value = gamma values = alpha beta gamma Here, ``bumpversion release`` would bump ``1.alpha`` to ``1.beta``. Executing ``bumpversion release`` again would bump ``1.beta`` to ``1``, because `release` being ``gamma`` is configured optional. ``first_value =`` **default**: The first entry in ``values =``. When the part is reset, the value will be set to the value specified here. File specific configuration --------------------------- ``[bumpversion:file:…]`` ``parse =`` **default:** "``(?P\d+)\.(?P\d+)\.(?P\d+)``" Regular expression (using `Python regular expression syntax `_) on how to find and parse the version string. Is required to parse all strings produced by ``serialize =``. Named matching groups ("``(?P...)``") provide values to as the ``part`` argument. Also available as ``--parse`` ``serialize =`` **default:** "``{major}.{minor}.{patch}``" Template specifying how to serialize the version parts back to a version string. This is templated using the `Python Format String Syntax `_. Available in the template context are parsed values of the named groups specified in ``parse =`` as well as all environment variables (prefixed with ``$``). Can be specified multiple times, bumpversion will try the serialization formats beginning with the first and choose the last one where all values can be represented like this:: serialize = {major}.{minor} {major} Given the example above, the new version *1.9* it will be serialized as ``1.9``, but the version *2.0* will be serialized as ``2``. Also available as ``--serialize``. Multiple values on the command line are given like ``--serialize {major}.{minor} --serialize {major}`` ``search =`` **default:** "``{current_version}``" Template string how to search for the string to be replaced in the file. Useful if the remotest possibility exists that the current version number might be multiple times in the file and you mean to only bump one of the occurences. Can be multiple lines, templated using `Python Format String Syntax `_. ``replace =`` **default:** "``{new_version}``" Template to create the string that will replace the current version number in the file. Given this ``requirements.txt``:: Django>=1.5.6,<1.6 MyProject==1.5.6 using this ``.bumpversion.cfg`` will ensure only the line containing ``MyProject`` will be changed:: [bumpversion] current_version = 1.5.6 [bumpversion:file:requirements.txt] search = MyProject=={current_version} replace = MyProject=={new_version} Can be multiple lines, templated using `Python Format String Syntax `_. Options ======= Most of the configuration values above can also be given as an option. Additionally, the following options are available: ``--dry-run, -n`` Don't touch any files, just pretend. Best used with ``--verbose``. ``--allow-dirty`` Normally, bumpversion will abort if the working directory is dirty to protect yourself from releasing unversioned files and/or overwriting unsaved changes. Use this option to override this check. ``--verbose`` Print useful information to stderr ``--list`` List machine readable information to stdout for consumption by other programs. Example output:: current_version=0.0.18 new_version=0.0.19 ``-h, --help`` Print help and exit Development =========== Development of this happens on GitHub, patches including tests, documentation are very welcome, as well as bug reports! Also please open an issue if this tool does not support every aspect of bumping versions in your development workflow, as it is intended to be very versatile. How to release bumpversion itself +++++++++++++++++++++++++++++++++ Execute the following commands:: git checkout master git pull tox bumpversion release python setup.py sdist bdist_wheel upload bumpversion --no-tag patch git push origin master --tags License ======= bumpversion is licensed under the MIT License - see the LICENSE.rst file for details Changes ======= **unreleased** **v0.5.3** - Fix bug where ``--new-version`` value was not used when config was present (thanks @cscetbon @ecordell (`#60 `_) - Preserve case of keys config file (thanks theskumar `#75 `_) - Windows CRLF improvements (thanks @thebjorn) **v0.5.1** - Document file specific options ``search =`` and ``replace =`` (introduced in 0.5.0) - Fix parsing individual labels from ``serialize =`` config even if there are characters after the last label (thanks @mskrajnowski `#56 `_). - Fix: Don't crash in git repositories that have tags that contain hyphens (`#51 `_) (`#52 `_). - Fix: Log actual content of the config file, not what ConfigParser prints after reading it. - Fix: Support multiline values in ``search =`` - also load configuration from ``setup.cfg`` (thanks @t-8ch `#57 `_). **v0.5.0** This is a major one, containing two larger features, that require some changes in the configuration format. This release is fully backwards compatible to *v0.4.1*, however deprecates two uses that will be removed in a future version. - New feature: `Part specific configuration <#part-specific-configuration>`_ - New feature: `File specific configuration <#file-specific-configuration>`_ - New feature: parse option can now span multiple line (allows to comment complex regular expressions. See `re.VERBOSE in the Python documentation `_ for details, `this testcase `_ as an example.) - New feature: ``--allow-dirty`` (`#42 `_). - Fix: Save the files in binary mode to avoid mutating newlines (thanks @jaraco `#45 `_). - License: bumpversion is now licensed under the MIT License (`#47 `_) - Deprecate multiple files on the command line (use a `configuration file <#configuration>`_ instead, or invoke ``bumpversion`` multiple times) - Deprecate 'files =' configuration (use `file specific configuration <#file-specific-configuration>`_ instead) **v0.4.1** - Add --list option (`#39 `_) - Use temporary files for handing over commit/tag messages to git/hg (`#36 `_) - Fix: don't encode stdout as utf-8 on py3 (`#40 `_) - Fix: logging of content of config file was wrong **v0.4.0** - Add --verbose option (`#21 `_ `#30 `_) - Allow option --serialize multiple times **v0.3.8** - Fix: --parse/--serialize didn't work from cfg (`#34 `_) **v0.3.7** - Don't fail if git or hg is not installed (thanks @keimlink) - "files" option is now optional (`#16 `_) - Fix bug related to dirty work dir (`#28 `_) **v0.3.6** - Fix --tag default (thanks @keimlink) **v0.3.5** - add {now} and {utcnow} to context - use correct file encoding writing to config file. NOTE: If you are using Python2 and want to use UTF-8 encoded characters in your config file, you need to update ConfigParser like using 'pip install -U configparser' - leave current_version in config even if available from vcs tags (was confusing) - print own version number in usage - allow bumping parts that contain non-numerics - various fixes regarding file encoding **v0.3.4** - bugfix: tag_name and message in .bumpversion.cfg didn't have an effect (`#9 `_) **v0.3.3** - add --tag-name option - now works on Python 3.2, 3.3 and PyPy **v0.3.2** - bugfix: Read only tags from `git describe` that look like versions **v0.3.1** - bugfix: ``--help`` in git workdir raising AssertionError - bugfix: fail earlier if one of files does not exist - bugfix: ``commit = True`` / ``tag = True`` in .bumpversion.cfg had no effect **v0.3.0** - **BREAKING CHANGE** The ``--bump`` argument was removed, this is now the first positional argument. If you used ``bumpversion --bump major`` before, you can use ``bumpversion major`` now. If you used ``bumpversion`` without arguments before, you now need to specify the part (previous default was ``patch``) as in ``bumpversion patch``). **v0.2.2** - add --no-commit, --no-tag **v0.2.1** - If available, use git to learn about current version **v0.2.0** - Mercurial support **v0.1.1** - Only create a tag when it's requested (thanks @gvangool) **v0.1.0** - Initial public version bumpversion-0.5.3/setup.cfg0000644000076500000240000000012212513425757016145 0ustar filipstaff00000000000000[wheel] universal = 1 [egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 bumpversion-0.5.3/setup.py0000644000076500000240000000233412513425613016034 0ustar filipstaff00000000000000import re from setuptools import setup description = 'Version-bump your software with a single command!' long_description = re.sub( "\`(.*)\<#.*\>\`\_", r"\1", str(open('README.rst', 'rb').read()).replace(description, '') ) setup( name='bumpversion', version='0.5.3', url='https://github.com/peritus/bumpversion', author='Filip Noetzel', author_email='filip+bumpversion@j03.de', license='MIT', packages=['bumpversion'], description=description, long_description=long_description, entry_points={ 'console_scripts': [ 'bumpversion = bumpversion:main', ] }, classifiers=( 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: Implementation :: PyPy', ), )