From 7c9188151bdf1b4015ccf397a7eb32dbd7287941 Mon Sep 17 00:00:00 2001 From: Steve Manuel Date: Tue, 26 Mar 2019 14:06:10 -0600 Subject: [PATCH] lib: export report handling into library code from cmd (#105) --- cmd/protolock/main.go | 32 +++----------------------------- report.go | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 29 deletions(-) create mode 100644 report.go diff --git a/cmd/protolock/main.go b/cmd/protolock/main.go index f6b61dc..7a1c83d 100644 --- a/cmd/protolock/main.go +++ b/cmd/protolock/main.go @@ -5,7 +5,6 @@ import ( "fmt" "io" "os" - "sort" "github.com/nilslice/protolock" ) @@ -126,39 +125,14 @@ func status(cfg *protolock.Config) { os.Exit(1) } } - handleReport(report, err) -} - -func handleReport(report *protolock.Report, err error) { - if len(report.Warnings) > 0 { - // sort the warnings so they are grouped by file location - orderByPathAndMessage(report.Warnings) - - for _, w := range report.Warnings { - fmt.Fprintf( - os.Stdout, - "CONFLICT: %s [%s]\n", - w.Message, w.Filepath, - ) - } - os.Exit(1) - } + code, err := protolock.HandleReport(report, os.Stdout, err) if err != nil { fmt.Println(err) + os.Exit(1) } -} -func orderByPathAndMessage(warnings []protolock.Warning) { - sort.Slice(warnings, func(i, j int) bool { - if warnings[i].Filepath < warnings[j].Filepath { - return true - } - if warnings[i].Filepath > warnings[j].Filepath { - return false - } - return warnings[i].Message < warnings[j].Message - }) + os.Exit(code) } func saveToLockFile(cfg protolock.Config, r io.Reader) error { diff --git a/report.go b/report.go new file mode 100644 index 0000000..ea3a760 --- /dev/null +++ b/report.go @@ -0,0 +1,39 @@ +package protolock + +import ( + "fmt" + "io" + "sort" +) + +// HandleReport checks a report for warnigs and writes warnings to an io.Writer. +// The returned int (an exit code) is 1 if warnings are encountered. +func HandleReport(report *Report, w io.Writer, err error) (int, error) { + if len(report.Warnings) > 0 { + // sort the warnings so they are grouped by file location + orderByPathAndMessage(report.Warnings) + + for _, warning := range report.Warnings { + fmt.Fprintf( + w, + "CONFLICT: %s [%s]\n", + warning.Message, warning.Filepath, + ) + } + return 1, err + } + + return 0, err +} + +func orderByPathAndMessage(warnings []Warning) { + sort.Slice(warnings, func(i, j int) bool { + if warnings[i].Filepath < warnings[j].Filepath { + return true + } + if warnings[i].Filepath > warnings[j].Filepath { + return false + } + return warnings[i].Message < warnings[j].Message + }) +}