From f4d43315cbc5849ac3eb327ea7a5c23423f47829 Mon Sep 17 00:00:00 2001 From: Kenichi Kamiya Date: Wed, 24 Apr 2024 05:00:29 +0900 Subject: [PATCH] Skip to modify the file if the updater returned errors (#161) * Check results are keeping updatable format even after replaced * Add failing example for bad result --- examples/simple.txt | 3 ++- internal/selfup.go | 17 ++++++++++------- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/examples/simple.txt b/examples/simple.txt index 0bea5c6..841ac44 100644 --- a/examples/simple.txt +++ b/examples/simple.txt @@ -1,3 +1,4 @@ will_be_replaced: '0.39.0' # selfup { "regex": "\\d[^']+", "script": "echo 0.76.9" } not_be_replacedA: '0.39.0' # selfup { "regex": "\\d[^']+", "script": "echo 0.39.0" } -not_be_replacedB: ':<' # selfup { "regex": ":<", "script": "echo ':)'" } +not_be_replacedB: ':<' # selfup { "regex": ":[<\\)]", "script": "echo ':)'" } +broken: ':<' # selfup { "regex": ":[<\\)]", "script": "this_command_does_not_exist_so_raise_errors_and_do_not_update_this_file" } diff --git a/internal/selfup.go b/internal/selfup.go index 6df8836..d19b105 100644 --- a/internal/selfup.go +++ b/internal/selfup.go @@ -69,9 +69,17 @@ func Update(path string, prefix string, skipBy string, isColor bool) (Result, er } replacer := strings.TrimSuffix(string(out), "\n") extracted := re.FindString(head) + replaced := strings.Replace(head, extracted, replacer, 1) + if !isChanged { + isChanged = replaced != head + } + extractedToEnsure := re.FindString(replaced) + if replacer != extractedToEnsure { + return Result{}, xerrors.Errorf("%s:%d: The result of updater command has malformed format: %s", path, lineNumber, replacer) + } estimation := " " suffix := "" - if extracted != replacer { + if replaced != head { replacedCount += 1 estimation = "✓" if isColor { @@ -80,13 +88,8 @@ func Update(path string, prefix string, skipBy string, isColor bool) (Result, er } suffix = fmt.Sprintf(" => %s", replacer) } - fmt.Println(fmt.Sprintf("%s %s:%d: %s", estimation, path, lineNumber, extracted) + suffix) - - replaced := strings.Replace(head, extracted, replacer, 1) - if !isChanged { - isChanged = replaced != head - } newLines = append(newLines, replaced+match+tail) + fmt.Println(fmt.Sprintf("%s %s:%d: %s", estimation, path, lineNumber, extracted) + suffix) } return Result{