Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use clang-format for .c and .h files #112

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 30 additions & 7 deletions acme/acmego/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
// The other known extensions and formatters are:
//
// .rs - rustfmt
//
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line got deleted, ironically, by acmego. I need to add a comment about .c and .h here.

package main

import (
Expand All @@ -32,6 +31,7 @@ import (
"log"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"unicode/utf8"
Expand All @@ -41,13 +41,36 @@ import (

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

var formatters = map[string][]string{
".go": []string{"goimports"},
type formatter struct {
cmd []string
enabled func(string) bool
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suppose we could have a method Enabled() which returns true if this callback field is nil.

}

func enabledAlways(string) bool { return true }

var formatters = map[string]formatter{
".go": {[]string{"goimports"}, enabledAlways},
}

func findClangFormatFile(path string) bool {
for {
newpath := filepath.Clean(filepath.Join(path, ".."))
if path == newpath {
break
}
path = newpath
if fi, err := os.Stat(filepath.Join(path, ".clang-format")); err == nil {
return !fi.IsDir()
}
}
return false
}

// Non-Go formatters (only loaded with -f option).
var otherFormatters = map[string][]string{
".rs": []string{"rustfmt", "--emit", "stdout"},
var otherFormatters = map[string]formatter{
".rs": {[]string{"rustfmt", "--emit", "stdout"}, enabledAlways},
".c": {[]string{"clang-format"}, findClangFormatFile},
".h": {[]string{"clang-format"}, findClangFormatFile},
}

func main() {
Expand All @@ -71,8 +94,8 @@ func main() {
continue
}
for suffix, formatter := range formatters {
if strings.HasSuffix(event.Name, suffix) {
reformat(event.ID, event.Name, formatter)
if strings.HasSuffix(event.Name, suffix) && formatter.enabled(event.Name) {
reformat(event.ID, event.Name, formatter.cmd)
break
}
}
Expand Down