From 200c5086e5fc45988a659691bdd3a8f54f1a33b9 Mon Sep 17 00:00:00 2001 From: Anders Ingemann Date: Sat, 20 Dec 2014 15:40:48 +0100 Subject: [PATCH] Extend sed_i to raise Exceptions when the expected amount of replacements is not met --- bootstrapvz/common/exceptions.py | 8 ++++++++ bootstrapvz/common/tools.py | 23 +++++++++++++++++++++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/bootstrapvz/common/exceptions.py b/bootstrapvz/common/exceptions.py index dee0d53..2e1930e 100644 --- a/bootstrapvz/common/exceptions.py +++ b/bootstrapvz/common/exceptions.py @@ -26,3 +26,11 @@ class TaskListError(Exception): class TaskError(Exception): pass + + +class NoMatchesError(Exception): + pass + + +class TooManyMatchesError(Exception): + pass diff --git a/bootstrapvz/common/tools.py b/bootstrapvz/common/tools.py index 79d5202..1715c66 100644 --- a/bootstrapvz/common/tools.py +++ b/bootstrapvz/common/tools.py @@ -56,11 +56,30 @@ def log_call(command, stdin=None, env=None, shell=False, cwd=None): return process.returncode, stdout, stderr -def sed_i(file_path, pattern, subst): +def sed_i(file_path, pattern, subst, expected_replacements=1): + replacement_count = inline_replace(file_path, pattern, subst) + if replacement_count < expected_replacements: + from exceptions import NoMatchesError + msg = ('There were no matches for the expression `{exp}\' in the file `{path}\'' + .format(exp=pattern, path=file_path)) + raise NoMatchesError(msg) + if replacement_count > expected_replacements: + from exceptions import TooManyMatchesError + msg = ('There were too many matches for the expression `{exp}\' in the file `{path}\'' + .format(exp=pattern, path=file_path)) + raise TooManyMatchesError(msg) + + +def inline_replace(file_path, pattern, subst): import fileinput import re + replacement_count = 0 for line in fileinput.input(files=file_path, inplace=True): - print re.sub(pattern, subst, line), + replacement = re.sub(pattern, subst, line) + if replacement != line: + replacement_count += 1 + print replacement, + return replacement_count def load_json(path):