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

feat: add notify based formatter #510

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
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
13 changes: 9 additions & 4 deletions cmd/format/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ func Run(v *viper.Viper, statz *stats.Stats, cmd *cobra.Command, paths []string)
// start traversing
files := make([]*walk.File, BatchSize)

LOOP:
for {
// read the next batch
readCtx, cancel := context.WithTimeout(ctx, 1*time.Second)
Expand All @@ -180,17 +181,21 @@ func Run(v *viper.Viper, statz *stats.Stats, cmd *cobra.Command, paths []string)
return fmt.Errorf("formatting failure: %w", err)
}

if errors.Is(err, io.EOF) {
switch {
case errors.Is(err, io.EOF):
// we have finished traversing
break
} else if err != nil {
break LOOP
case cfg.Watch && errors.Is(err, context.DeadlineExceeded):
// we timed out reading files, try again
continue
case err != nil:
// something went wrong
return fmt.Errorf("failed to read files: %w", err)
}
}

// finalize formatting
formatErr := formatter.Close(ctx)
formatErr := formatter.Close()

// close the walker, ensuring any pending file release hooks finish
if err = walker.Close(); err != nil {
Expand Down
11 changes: 11 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ type Config struct {
Walk string `mapstructure:"walk" toml:"walk,omitempty"`
WorkingDirectory string `mapstructure:"working-dir" toml:"-"`
Stdin bool `mapstructure:"stdin" toml:"-"` // not allowed in config
Watch bool `mapstructure:"watch" toml:"-"` // not allowed in config

FormatterConfigs map[string]*Formatter `mapstructure:"formatter" toml:"formatter,omitempty"`

Expand Down Expand Up @@ -98,6 +99,10 @@ func SetFlags(fs *pflag.FlagSet) {
"stdin", false,
"Format the context passed in via stdin.",
)
fs.Bool(
"watch", false,
"Watch the filesystem for changes and apply formatters when changes are detected. (env $TREEFMT_WATCH)",
)
fs.String(
"tree-root", "",
"The root directory from which treefmt will start walking the filesystem (defaults to the directory "+
Expand Down Expand Up @@ -157,6 +162,7 @@ func FromViper(v *viper.Viper) (*Config, error) {
"clear-cache": false,
"no-cache": false,
"stdin": false,
"watch": false,
"working-dir": ".",
}

Expand Down Expand Up @@ -185,6 +191,11 @@ func FromViper(v *viper.Viper) (*Config, error) {
cfg.Walk = walk.Stdin.String()
}

// if the watch flag was passed, we force the watch walk type
if cfg.Watch {
cfg.Walk = walk.Watch.String()
}

// determine the tree root
if cfg.TreeRoot == "" {
// if none was specified, we first try with tree-root-file
Expand Down
6 changes: 4 additions & 2 deletions format/composite.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,8 @@ func (c *CompositeFormatter) Apply(ctx context.Context, files []*walk.File) erro
}
}

c.scheduler.apply(ctx)

return nil
}

Expand Down Expand Up @@ -136,8 +138,8 @@ func (c *CompositeFormatter) signature() (signature, error) {

// Close finalizes the processing of the CompositeFormatter, ensuring that any remaining batches are applied and
// all formatters have completed their tasks. It returns an error if any formatting failures were detected.
func (c *CompositeFormatter) Close(ctx context.Context) error {
return c.scheduler.close(ctx)
func (c *CompositeFormatter) Close() error {
return c.scheduler.close()
}

func NewCompositeFormatter(
Expand Down
4 changes: 3 additions & 1 deletion format/scheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -203,14 +203,16 @@ func (s *scheduler) schedule(ctx context.Context, key batchKey, batch []*walk.Fi
})
}

func (s *scheduler) close(ctx context.Context) error {
func (s *scheduler) apply(ctx context.Context) {
// schedule any partial batches that remain
for key, batch := range s.batches {
if len(batch) > 0 {
s.schedule(ctx, key, batch)
}
}
}

func (s *scheduler) close() error {
// wait for processing to complete
if err := s.eg.Wait(); err != nil {
return fmt.Errorf("failed to wait for formatters: %w", err)
Expand Down
37 changes: 37 additions & 0 deletions test/test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,43 @@ import (
"golang.org/x/sys/unix"
)

//nolint:gochecknoglobals
var ExamplesPaths = []string{
"elm/elm.json",
"elm/src/Main.elm",
"emoji 🕰️/README.md",
"go/go.mod",
"go/main.go",
"haskell/CHANGELOG.md",
"haskell/Foo.hs",
"haskell/Main.hs",
"haskell/Nested/Foo.hs",
"haskell/Setup.hs",
"haskell/haskell.cabal",
"haskell/treefmt.toml",
"haskell-frontend/CHANGELOG.md",
"haskell-frontend/Main.hs",
"haskell-frontend/Setup.hs",
"haskell-frontend/haskell-frontend.cabal",
"html/index.html",
"html/scripts/.gitkeep",
"javascript/source/hello.js",
"nix/sources.nix",
"nixpkgs.toml",
"python/main.py",
"python/requirements.txt",
"python/virtualenv_proxy.py",
"ruby/bundler.rb",
"rust/Cargo.toml",
"rust/src/main.rs",
"shell/foo.sh",
"terraform/main.tf",
"terraform/two.tf",
"touch.toml",
"treefmt.toml",
"yaml/test.yaml",
}

func WriteConfig(t *testing.T, path string, cfg *config.Config) {
t.Helper()

Expand Down
39 changes: 1 addition & 38 deletions walk/filesystem_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,43 +13,6 @@ import (
"github.com/stretchr/testify/require"
)

//nolint:gochecknoglobals
var examplesPaths = []string{
"elm/elm.json",
"elm/src/Main.elm",
"emoji 🕰️/README.md",
"go/go.mod",
"go/main.go",
"haskell/CHANGELOG.md",
"haskell/Foo.hs",
"haskell/Main.hs",
"haskell/Nested/Foo.hs",
"haskell/Setup.hs",
"haskell/haskell.cabal",
"haskell/treefmt.toml",
"haskell-frontend/CHANGELOG.md",
"haskell-frontend/Main.hs",
"haskell-frontend/Setup.hs",
"haskell-frontend/haskell-frontend.cabal",
"html/index.html",
"html/scripts/.gitkeep",
"javascript/source/hello.js",
"nix/sources.nix",
"nixpkgs.toml",
"python/main.py",
"python/requirements.txt",
"python/virtualenv_proxy.py",
"ruby/bundler.rb",
"rust/Cargo.toml",
"rust/src/main.rs",
"shell/foo.sh",
"terraform/main.tf",
"terraform/two.tf",
"touch.toml",
"treefmt.toml",
"yaml/test.yaml",
}

func TestFilesystemReader(t *testing.T) {
as := require.New(t)

Expand All @@ -67,7 +30,7 @@ func TestFilesystemReader(t *testing.T) {
n, err := r.Read(ctx, files)

for i := count; i < count+n; i++ {
as.Equal(examplesPaths[i], files[i-count].RelPath)
as.Equal(test.ExamplesPaths[i], files[i-count].RelPath)
}

count += n
Expand Down
12 changes: 8 additions & 4 deletions walk/type_enum.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions walk/walk.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ const (
Stdin
Filesystem
Git
Watch

BatchSize = 1024
)
Expand Down Expand Up @@ -215,6 +216,8 @@ func NewReader(
reader = NewFilesystemReader(root, path, statz, BatchSize)
case Git:
reader, err = NewGitReader(root, path, statz)
case Watch:
reader, err = NewWatchReader(root, path, statz, BatchSize)

default:
return nil, fmt.Errorf("unknown walk type: %v", walkType)
Expand Down
Loading