Skip to content

Commit

Permalink
lib: export report handling into library code from cmd (#105)
Browse files Browse the repository at this point in the history
  • Loading branch information
nilslice committed Mar 26, 2019
1 parent 96c3d71 commit 7c91881
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 29 deletions.
32 changes: 3 additions & 29 deletions cmd/protolock/main.go
Expand Up @@ -5,7 +5,6 @@ import (
"fmt"
"io"
"os"
"sort"

"github.com/nilslice/protolock"
)
Expand Down Expand Up @@ -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 {
Expand Down
39 changes: 39 additions & 0 deletions 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
})
}

0 comments on commit 7c91881

Please sign in to comment.