Skip to content

Commit

Permalink
Add a very limited --verbose option
Browse files Browse the repository at this point in the history
Fixes #21
  • Loading branch information
peritus committed Jan 29, 2014
1 parent 654f764 commit 5ed87f2
Show file tree
Hide file tree
Showing 3 changed files with 88 additions and 22 deletions.
61 changes: 45 additions & 16 deletions bumpversion/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@

import argparse
import os
import warnings
import re
import sre_constants
import subprocess
Expand All @@ -34,6 +33,9 @@
sys.version.split("\n")[0].split(" ")[0],
)

import logging
logger = logging.getLogger("bumpversion")

from argparse import _AppendAction
class DiscardDefaultIfSpecifiedAppendAction(_AppendAction):

Expand All @@ -42,7 +44,6 @@ class DiscardDefaultIfSpecifiedAppendAction(_AppendAction):
'''

def __call__(self, parser, namespace, values, option_string=None):
warnings.warn("{}".format(locals()))
if getattr(self, "_discarded_default", None) is None:
setattr(namespace, self.dest, [])
self._discarded_default = True
Expand Down Expand Up @@ -215,8 +216,9 @@ def __init__(self, parse_regex, serialize_formats, context=None):

try:
self.parse_regex = re.compile(parse_regex)
except:
warnings.warn("--patch '{}' is not a valid regex".format(parse_regex))
except sre_constants.error as e:
logger.error("--parse '{}' is not a valid regex".format(parse_regex))
raise e

self.serialize_formats = serialize_formats

Expand All @@ -241,7 +243,8 @@ def parse(self, version_string):

self._parsed = {}
if not match:
warnings.warn("'{}' does not parse current version".format(self.parse_regex.pattern))
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():
Expand All @@ -261,10 +264,12 @@ def _serialize(self, serialize_format, raise_if_incomplete=False):
serialized = serialize_format.format(**values)

except KeyError as e:
assert hasattr(e, 'message'), dir(e)
missing_key = getattr(e,
'message', # Python 2
e.args[0] # Python 3
)
raise KeyError("Did not find key {} in {} when serializing version number".format(
repr(e.message), repr(self._parsed)))

repr(missing_key), repr(self._parsed)))

keys_needing_representation = set([k for k, v in self._parsed.items() if not v.is_optional()])

Expand Down Expand Up @@ -377,8 +382,26 @@ def main(original_args=None):
'--config-file', default='.bumpversion.cfg', metavar='FILE',
help='Config file to read most of the variables from', required=False)

parser1.add_argument(
'--verbose', '-v', action='count', default=0,
help='Print verbose logging to stderr', required=False)

known_args, remaining_argv = parser1.parse_known_args(args)

if len(logger.handlers) == 0:
ch = logging.StreamHandler(sys.stderr)
logformatter = logging.Formatter('[%(levelname)s] %(message)s\n')
ch.setFormatter(logformatter)
logger.addHandler(ch)

log_level = {
0: logging.WARNING,
1: logging.INFO,
2: logging.DEBUG,
}.get(known_args.verbose, logging.DEBUG)

logger.setLevel(log_level)

defaults = {}
vcs_info = {}

Expand Down Expand Up @@ -410,9 +433,12 @@ def main(original_args=None):
except NoOptionError:
pass # no default value then ;)

elif known_args.config_file != parser1.get_default('config_file'):
raise argparse.ArgumentTypeError("Could not read config file at {}".format(
known_args.config_file))
else:
message = "Could not read config file at {}".format(known_args.config_file)
if known_args.config_file != parser1.get_default('config_file'):
raise argparse.ArgumentTypeError(message)
else:
logger.info(message)

parser2 = argparse.ArgumentParser(add_help=False, parents=[parser1])
parser2.set_defaults(**defaults)
Expand All @@ -438,11 +464,14 @@ def main(original_args=None):
'utcnow': datetime.utcnow(),
}

v = Version(
known_args.parse,
known_args.serialize,
context=dict(list(time_context.items()) + list(prefixed_environ().items()) + list(vcs_info.items()))
)
try:
v = Version(
known_args.parse,
known_args.serialize,
context=dict(list(time_context.items()) + list(prefixed_environ().items()) + list(vcs_info.items()))
)
except sre_constants.error as e:
sys.exit(1)

if not 'new_version' in defaults and known_args.current_version:
v.parse(known_args.current_version)
Expand Down
47 changes: 41 additions & 6 deletions tests.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
# -*- coding: utf-8 -*-

from __future__ import unicode_literals
from __future__ import unicode_literals, print_function

import pytest
import sys
import logging
import mock

import argparse
import subprocess
Expand All @@ -26,10 +28,10 @@
)

EXPECTED_USAGE = ("""
usage: py.test [-h] [--config-file FILE] [--parse REGEX] [--serialize FORMAT]
[--current-version VERSION] [--dry-run] --new-version VERSION
[--commit | --no-commit] [--tag | --no-tag]
[--tag-name TAG_NAME] [--message COMMIT_MSG]
usage: py.test [-h] [--config-file FILE] [--verbose] [--parse REGEX]
[--serialize FORMAT] [--current-version VERSION] [--dry-run]
--new-version VERSION [--commit | --no-commit]
[--tag | --no-tag] [--tag-name TAG_NAME] [--message COMMIT_MSG]
part [file [file ...]]
%s
Expand All @@ -42,6 +44,7 @@
-h, --help show this help message and exit
--config-file FILE Config file to read most of the variables from
(default: .bumpversion.cfg)
--verbose, -v Print verbose logging to stderr (default: 0)
--parse REGEX Regex parsing the version string (default:
(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+))
--serialize FORMAT How to format what is parsed back to a version
Expand Down Expand Up @@ -90,7 +93,7 @@ def test_regression_help_in_workdir(tmpdir, capsys, vcs):
out, err = capsys.readouterr()

if vcs == "git":
assert "usage: py.test [-h] [--config-file FILE] [--parse REGEX]" in out
assert "usage: py.test [-h] [--config-file FILE] [--verbose] [--parse REGEX]" in out
assert "Version that needs to be updated (default: 1.7.2013)" in out
assert "[--new-version VERSION]" in out
else:
Expand Down Expand Up @@ -773,3 +776,35 @@ def test_multiple_serialize_twopart_patch_configfile(tmpdir):

assert '0.6.1' == tmpdir.join("fileD").read()


def test_log_no_config_file_info_message(tmpdir, capsys):
tmpdir.chdir()

tmpdir.join("blargh.txt").write("1.0.0")

with mock.patch("bumpversion.logger") as logger:
main(['--verbose', '--verbose', '--current-version', '1.0.0', 'patch', 'blargh.txt'])

logger.info.assert_called_with(
"Could not read config file at .bumpversion.cfg"
)

def test_log_parse_doesnt_parse_current_version(tmpdir):
tmpdir.chdir()

with mock.patch("bumpversion.logger") as logger:
main(['--parse', 'xxx', '--current-version', '12', '--new-version', '13', 'patch'])

logger.warn.assert_called_with(
"Evaluating 'parse' option: 'xxx' does not parse current version '12'"
)

def test_log_invalid_regex_exit(tmpdir):
tmpdir.chdir()

with pytest.raises(SystemExit):
with mock.patch("bumpversion.logger") as logger:
main(['--parse', '*kittens*', '--current-version', '12', '--new-version', '13', 'patch'])

logger.error.assert_called_with("--parse '*kittens*' is not a valid regex")

2 changes: 2 additions & 0 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ envlist = py33, py32, py27, py27-configparser, pypy
[testenv]
deps=
pytest
mock
commands=
py.test tests.py

[testenv:py27-configparser]
deps=
pytest
mock
configparser

0 comments on commit 5ed87f2

Please sign in to comment.