Skip to content

Commit 2542f3b

Browse files
committed
Use clang-format for .c and .h files
Because clang-format is not used universally, this change adds a check so that we only run clang-format if a .clang-format file can be found higher up in the directory tree.
1 parent ff0314d commit 2542f3b

File tree

1 file changed

+30
-7
lines changed

1 file changed

+30
-7
lines changed

acme/acmego/main.go

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@
2121
// The other known extensions and formatters are:
2222
//
2323
// .rs - rustfmt
24-
//
2524
package main
2625

2726
import (
@@ -32,6 +31,7 @@ import (
3231
"log"
3332
"os"
3433
"os/exec"
34+
"path/filepath"
3535
"strconv"
3636
"strings"
3737
"unicode/utf8"
@@ -41,13 +41,36 @@ import (
4141

4242
var gofmt = flag.Bool("f", false, "format the entire file after Put")
4343

44-
var formatters = map[string][]string{
45-
".go": []string{"goimports"},
44+
type formatter struct {
45+
cmd []string
46+
enabled func(string) bool
47+
}
48+
49+
func enabledAlways(string) bool { return true }
50+
51+
var formatters = map[string]formatter{
52+
".go": {[]string{"goimports"}, enabledAlways},
53+
}
54+
55+
func findClangFormatFile(path string) bool {
56+
for {
57+
newpath := filepath.Clean(filepath.Join(path, ".."))
58+
if path == newpath {
59+
break
60+
}
61+
path = newpath
62+
if fi, err := os.Stat(filepath.Join(path, ".clang-format")); err == nil {
63+
return !fi.IsDir()
64+
}
65+
}
66+
return false
4667
}
4768

4869
// Non-Go formatters (only loaded with -f option).
49-
var otherFormatters = map[string][]string{
50-
".rs": []string{"rustfmt", "--emit", "stdout"},
70+
var otherFormatters = map[string]formatter{
71+
".rs": {[]string{"rustfmt", "--emit", "stdout"}, enabledAlways},
72+
".c": {[]string{"clang-format"}, findClangFormatFile},
73+
".h": {[]string{"clang-format"}, findClangFormatFile},
5174
}
5275

5376
func main() {
@@ -71,8 +94,8 @@ func main() {
7194
continue
7295
}
7396
for suffix, formatter := range formatters {
74-
if strings.HasSuffix(event.Name, suffix) {
75-
reformat(event.ID, event.Name, formatter)
97+
if strings.HasSuffix(event.Name, suffix) && formatter.enabled(event.Name) {
98+
reformat(event.ID, event.Name, formatter.cmd)
7699
break
77100
}
78101
}

0 commit comments

Comments
 (0)