feat(cmd): add unified diff output option for formatting
* Implemented `-d`/`--diff` flag to print unified diffs. * Added `unifiedDiff` function for generating diffs. * Config discovery now merges fields from `.pgtidy.yaml`.
This commit is contained in:
+25
-6
@@ -12,12 +12,14 @@ import (
|
||||
|
||||
// cmdFmt implements `pgtidy fmt`. It follows the gofmt model: with no flags it
|
||||
// prints the formatted result to stdout; -w rewrites in place; -l lists files
|
||||
// that differ; --check exits non-zero if any input is unformatted.
|
||||
// that differ; --check exits non-zero if any input is unformatted; -d prints a
|
||||
// unified diff for each file that would change.
|
||||
func cmdFmt(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
|
||||
var (
|
||||
write bool
|
||||
list bool
|
||||
check bool
|
||||
diff bool
|
||||
files []string
|
||||
)
|
||||
for _, a := range args {
|
||||
@@ -28,6 +30,8 @@ func cmdFmt(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
|
||||
list = true
|
||||
case "--check":
|
||||
check = true
|
||||
case "-d", "--diff":
|
||||
diff = true
|
||||
case "-h", "--help":
|
||||
usage(stdout)
|
||||
return 0
|
||||
@@ -40,8 +44,16 @@ func cmdFmt(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: discover and parse .pgtidy.yaml; for now use the house-style default.
|
||||
st := config.Default()
|
||||
// Discover config: walk up from the working directory.
|
||||
wd, err := os.Getwd()
|
||||
if err != nil {
|
||||
wd = "."
|
||||
}
|
||||
st, err := config.Load(wd)
|
||||
if err != nil {
|
||||
fmt.Fprintf(stderr, "%v\n", err)
|
||||
return 2
|
||||
}
|
||||
|
||||
// stdin → stdout when no files are given.
|
||||
if len(files) == 0 {
|
||||
@@ -51,13 +63,16 @@ func cmdFmt(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
|
||||
return 2
|
||||
}
|
||||
out := format.File(parser.Parse(string(src)), st)
|
||||
if check {
|
||||
switch {
|
||||
case check:
|
||||
if out != string(src) {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
case diff:
|
||||
io.WriteString(stdout, unifiedDiff(string(src), out, "stdin"))
|
||||
default:
|
||||
io.WriteString(stdout, out)
|
||||
}
|
||||
io.WriteString(stdout, out)
|
||||
return 0
|
||||
}
|
||||
|
||||
@@ -87,6 +102,10 @@ func cmdFmt(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
|
||||
if changed {
|
||||
fmt.Fprintln(stdout, path)
|
||||
}
|
||||
case diff:
|
||||
if changed {
|
||||
io.WriteString(stdout, unifiedDiff(string(src), out, path))
|
||||
}
|
||||
case check:
|
||||
// handled after loop via anyDiff
|
||||
default:
|
||||
|
||||
Reference in New Issue
Block a user