bumpver/src/pycalver/rewrite.py

61 lines
1.7 KiB
Python
Raw Normal View History

2018-09-02 21:48:12 +02:00
# This file is part of the pycalver project
# https://github.com/mbarkhau/pycalver
#
# (C) 2018 Manuel Barkhau (@mbarkhau)
# SPDX-License-Identifier: MIT
2018-09-03 22:23:51 +02:00
import io
2018-09-02 21:48:12 +02:00
import difflib
2018-09-03 22:23:51 +02:00
import logging
import typing as typ
from . import parse
2018-09-02 21:48:12 +02:00
log = logging.getLogger("pycalver.rewrite")
2018-11-04 21:11:42 +01:00
def rewrite_lines(
old_lines: typ.List[str], patterns: typ.List[str], new_version: str
) -> typ.List[str]:
new_version_nfo = parse.parse_version_info(new_version)
2018-09-03 22:23:51 +02:00
new_version_fmt_kwargs = new_version_nfo._asdict()
2018-11-04 21:11:42 +01:00
new_lines = old_lines.copy()
matches: typ.List[parse.PatternMatch] = parse.parse_patterns(old_lines, patterns)
for m in matches:
replacement = m.pattern.format(**new_version_fmt_kwargs)
span_l, span_r = m.span
new_line = m.line[:span_l] + replacement + m.line[span_r:]
new_lines[m.lineno] = new_line
return new_lines
def rewrite(
new_version: str, file_patterns: typ.Dict[str, typ.List[str]], dry=False, verbose=False
) -> None:
2018-09-03 22:23:51 +02:00
for filepath, patterns in file_patterns.items():
with io.open(filepath, mode="rt", encoding="utf-8") as fh:
content = fh.read()
2018-11-04 21:11:42 +01:00
# TODO (mb 2018-09-18): Detect line sep
line_sep = "\n"
2018-09-03 22:23:51 +02:00
2018-11-04 21:11:42 +01:00
old_lines = content.splitlines()
new_lines = rewrite_lines(old_lines, patterns, new_version)
2018-09-03 22:23:51 +02:00
if dry or verbose:
2018-11-04 21:11:42 +01:00
diff_lines = difflib.unified_diff(
old_lines, new_lines, lineterm="", fromfile="a/" + filepath, tofile="b/" + filepath
)
print("\n".join(diff_lines))
2018-09-03 22:23:51 +02:00
if dry:
continue
2018-11-04 21:11:42 +01:00
new_content = line_sep.join(new_lines)
2018-09-03 22:23:51 +02:00
with io.open(filepath, mode="wt", encoding="utf-8") as fh:
fh.write(new_content)