Skip to content

Commit 808523a

Browse files
committed
feat: --exclude flag
Signed-off-by: Ilya Lesikov <ilya@lesikov.com>
1 parent 66192e7 commit 808523a

File tree

2 files changed

+30
-4
lines changed

2 files changed

+30
-4
lines changed

internal/cli/root.go

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,13 @@ import (
1111

1212
func init() {
1313
rootCmd.Flags().BoolVarP(&checkOnly, "check", "c", false, "Check if files need formatting (exit 1 if changes needed)")
14+
rootCmd.Flags().StringArrayVarP(&excludePatterns, "exclude", "e", nil, "Exclude files matching glob pattern (can be specified multiple times)")
1415
}
1516

1617
var (
17-
checkOnly bool
18-
rootCmd = &cobra.Command{
18+
checkOnly bool
19+
excludePatterns []string
20+
rootCmd = &cobra.Command{
1921
Use: "wormatter <path>...",
2022
Short: "A highly opinionated Go source code formatter",
2123
Long: "Wormatter is a DST-based Go source code formatter. Highly opinionated, but very comprehensive. Gofumpt built-in.",
@@ -33,7 +35,10 @@ func Execute() {
3335
}
3436

3537
func run(_ *cobra.Command, args []string) error {
36-
opts := formatter.Options{CheckOnly: checkOnly}
38+
opts := formatter.Options{
39+
CheckOnly: checkOnly,
40+
ExcludePatterns: excludePatterns,
41+
}
3742

3843
for _, path := range args {
3944
info, err := os.Stat(path)

pkg/formatter/file.go

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@ import (
1818
var ErrNeedsFormatting = errors.New("file needs formatting")
1919

2020
type Options struct {
21-
CheckOnly bool
21+
CheckOnly bool
22+
ExcludePatterns []string
2223
}
2324

2425
func FormatDirectory(dir string, opts Options) error {
@@ -27,6 +28,9 @@ func FormatDirectory(dir string, opts Options) error {
2728
return err
2829
}
2930
if !d.IsDir() && strings.HasSuffix(path, ".go") {
31+
if matchesAnyPattern(path, opts.ExcludePatterns) {
32+
return nil
33+
}
3034
if err := FormatFile(path, opts); err != nil {
3135
return err
3236
}
@@ -37,6 +41,10 @@ func FormatDirectory(dir string, opts Options) error {
3741
}
3842

3943
func FormatFile(filePath string, opts Options) error {
44+
if matchesAnyPattern(filePath, opts.ExcludePatterns) {
45+
return nil
46+
}
47+
4048
fset := token.NewFileSet()
4149
f, err := decorator.ParseFile(fset, filePath, nil, parser.ParseComments)
4250
if err != nil {
@@ -87,3 +95,16 @@ func FormatFile(filePath string, opts Options) error {
8795

8896
return os.WriteFile(filePath, formatted, 0o644)
8997
}
98+
99+
func matchesAnyPattern(path string, patterns []string) bool {
100+
for _, pattern := range patterns {
101+
if matched, _ := filepath.Match(pattern, path); matched {
102+
return true
103+
}
104+
if matched, _ := filepath.Match(pattern, filepath.Base(path)); matched {
105+
return true
106+
}
107+
}
108+
109+
return false
110+
}

0 commit comments

Comments
 (0)