2023-12-23 15:50:47 +03:00
|
|
|
package cli
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-01-03 11:08:57 +03:00
|
|
|
"errors"
|
2023-12-23 15:50:47 +03:00
|
|
|
"fmt"
|
2024-06-04 20:23:04 +03:00
|
|
|
"io"
|
2023-12-26 13:11:32 +03:00
|
|
|
"os"
|
|
|
|
"os/signal"
|
2024-04-25 14:16:04 +03:00
|
|
|
"path/filepath"
|
|
|
|
"runtime"
|
2024-05-06 18:05:10 +03:00
|
|
|
"runtime/pprof"
|
2023-12-26 13:11:32 +03:00
|
|
|
"syscall"
|
2023-12-23 15:50:47 +03:00
|
|
|
|
2024-04-19 12:57:41 +03:00
|
|
|
"git.numtide.com/numtide/treefmt/format"
|
2024-05-01 13:15:39 +03:00
|
|
|
"git.numtide.com/numtide/treefmt/stats"
|
2024-04-19 12:57:41 +03:00
|
|
|
|
2024-02-15 12:20:01 +03:00
|
|
|
"git.numtide.com/numtide/treefmt/cache"
|
|
|
|
"git.numtide.com/numtide/treefmt/config"
|
|
|
|
"git.numtide.com/numtide/treefmt/walk"
|
2023-12-23 15:50:47 +03:00
|
|
|
|
|
|
|
"github.com/charmbracelet/log"
|
|
|
|
"golang.org/x/sync/errgroup"
|
|
|
|
)
|
|
|
|
|
2024-04-19 12:57:41 +03:00
|
|
|
const (
|
|
|
|
BatchSize = 1024
|
|
|
|
)
|
|
|
|
|
2024-06-06 21:16:34 +03:00
|
|
|
var ErrFailOnChange = errors.New("unexpected changes detected, --fail-on-change is enabled")
|
2024-01-03 16:10:54 +03:00
|
|
|
|
2024-04-19 12:57:41 +03:00
|
|
|
func (f *Format) Run() (err error) {
|
2024-05-26 19:35:50 +03:00
|
|
|
// set log level and other options
|
2024-06-06 21:16:34 +03:00
|
|
|
f.configureLogging()
|
2024-05-26 19:35:50 +03:00
|
|
|
|
2024-05-06 18:05:10 +03:00
|
|
|
// cpu profiling
|
2024-06-06 21:16:34 +03:00
|
|
|
if f.CpuProfile != "" {
|
|
|
|
cpuProfile, err := os.Create(f.CpuProfile)
|
2024-05-06 18:05:10 +03:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to open file for writing cpu profile: %w", err)
|
|
|
|
} else if err = pprof.StartCPUProfile(cpuProfile); err != nil {
|
|
|
|
return fmt.Errorf("failed to start cpu profile: %w", err)
|
|
|
|
}
|
|
|
|
defer func() {
|
|
|
|
pprof.StopCPUProfile()
|
|
|
|
if err := cpuProfile.Close(); err != nil {
|
|
|
|
log.Errorf("failed to close cpu profile: %v", err)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
2024-05-02 12:56:32 +03:00
|
|
|
// create a prefixed logger
|
2024-05-17 12:48:53 +03:00
|
|
|
log.SetPrefix("format")
|
2023-12-23 15:50:47 +03:00
|
|
|
|
2024-05-02 12:56:32 +03:00
|
|
|
// ensure cache is closed on return
|
2023-12-23 15:50:47 +03:00
|
|
|
defer func() {
|
|
|
|
if err := cache.Close(); err != nil {
|
2024-05-17 12:48:53 +03:00
|
|
|
log.Errorf("failed to close cache: %v", err)
|
2023-12-23 15:50:47 +03:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2024-05-30 16:43:26 +03:00
|
|
|
// find the config file unless specified
|
2024-06-06 21:16:34 +03:00
|
|
|
if f.ConfigFile == "" {
|
2024-05-30 16:43:26 +03:00
|
|
|
pwd, err := os.Getwd()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2024-06-06 21:16:34 +03:00
|
|
|
f.ConfigFile, _, err = findUp(pwd, "treefmt.toml")
|
2024-05-30 16:43:26 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-05-30 20:56:26 +03:00
|
|
|
// default the tree root to the directory containing the config file
|
2024-06-06 21:16:34 +03:00
|
|
|
if f.TreeRoot == "" {
|
|
|
|
f.TreeRoot = filepath.Dir(f.ConfigFile)
|
2024-05-30 20:56:26 +03:00
|
|
|
}
|
2024-05-30 16:43:26 +03:00
|
|
|
|
2024-05-30 20:56:26 +03:00
|
|
|
// search the tree root using the --tree-root-file if specified
|
2024-06-06 21:16:34 +03:00
|
|
|
if f.TreeRootFile != "" {
|
2024-05-30 20:56:26 +03:00
|
|
|
pwd, err := os.Getwd()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2024-06-06 21:16:34 +03:00
|
|
|
_, f.TreeRoot, err = findUp(pwd, f.TreeRootFile)
|
2024-05-30 20:56:26 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2024-05-30 16:43:26 +03:00
|
|
|
}
|
|
|
|
|
2024-06-06 21:16:34 +03:00
|
|
|
log.Debugf("config-file=%s tree-root=%s", f.ConfigFile, f.TreeRoot)
|
2024-05-30 16:43:26 +03:00
|
|
|
|
2023-12-23 15:50:47 +03:00
|
|
|
// read config
|
2024-06-06 21:16:34 +03:00
|
|
|
cfg, err := config.ReadFile(f.ConfigFile, f.Formatters)
|
2023-12-23 15:50:47 +03:00
|
|
|
if err != nil {
|
2024-06-06 21:16:34 +03:00
|
|
|
return fmt.Errorf("failed to read config file %v: %w", f.ConfigFile, err)
|
2023-12-23 15:50:47 +03:00
|
|
|
}
|
|
|
|
|
2024-05-02 12:56:32 +03:00
|
|
|
// compile global exclude globs
|
2024-06-14 12:30:13 +03:00
|
|
|
if f.globalExcludes, err = format.CompileGlobs(cfg.Global.Excludes); err != nil {
|
2024-05-02 13:40:49 +03:00
|
|
|
return fmt.Errorf("failed to compile global excludes: %w", err)
|
2023-12-25 15:26:18 +03:00
|
|
|
}
|
|
|
|
|
2024-05-24 13:42:40 +03:00
|
|
|
// initialise formatters
|
2024-06-06 21:16:34 +03:00
|
|
|
f.formatters = make(map[string]*format.Formatter)
|
2024-01-12 14:46:04 +03:00
|
|
|
|
2024-05-24 13:42:40 +03:00
|
|
|
for name, formatterCfg := range cfg.Formatters {
|
2024-06-14 12:30:13 +03:00
|
|
|
formatter, err := format.NewFormatter(name, f.TreeRoot, formatterCfg)
|
2024-05-24 13:42:40 +03:00
|
|
|
|
2024-06-06 21:16:34 +03:00
|
|
|
if errors.Is(err, format.ErrCommandNotFound) && f.AllowMissingFormatter {
|
2024-05-24 13:42:40 +03:00
|
|
|
log.Debugf("formatter command not found: %v", name)
|
2024-01-12 14:46:04 +03:00
|
|
|
continue
|
2023-12-23 18:00:39 +03:00
|
|
|
} else if err != nil {
|
2024-01-02 13:33:50 +03:00
|
|
|
return fmt.Errorf("%w: failed to initialise formatter: %v", err, name)
|
2023-12-23 15:50:47 +03:00
|
|
|
}
|
2024-01-12 14:46:04 +03:00
|
|
|
|
2024-05-02 13:28:22 +03:00
|
|
|
// store formatter by name
|
2024-06-06 21:16:34 +03:00
|
|
|
f.formatters[name] = formatter
|
2024-01-12 14:46:04 +03:00
|
|
|
}
|
2023-12-23 15:50:47 +03:00
|
|
|
|
2024-04-19 12:57:41 +03:00
|
|
|
// open the cache
|
2024-06-06 21:16:34 +03:00
|
|
|
if err = cache.Open(f.TreeRoot, f.ClearCache, f.formatters); err != nil {
|
2023-12-23 15:50:47 +03:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2024-04-19 12:57:41 +03:00
|
|
|
// create an app context and listen for shutdown
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
defer cancel()
|
2023-12-23 15:50:47 +03:00
|
|
|
|
2024-04-19 12:57:41 +03:00
|
|
|
go func() {
|
|
|
|
exit := make(chan os.Signal, 1)
|
|
|
|
signal.Notify(exit, os.Interrupt, syscall.SIGTERM)
|
|
|
|
<-exit
|
|
|
|
cancel()
|
|
|
|
}()
|
2023-12-23 15:50:47 +03:00
|
|
|
|
2024-05-02 12:56:32 +03:00
|
|
|
// initialise stats collection
|
|
|
|
stats.Init()
|
|
|
|
|
2024-05-02 13:28:22 +03:00
|
|
|
// create an overall error group for executing high level tasks concurrently
|
2023-12-23 15:50:47 +03:00
|
|
|
eg, ctx := errgroup.WithContext(ctx)
|
|
|
|
|
2024-05-02 13:28:22 +03:00
|
|
|
// create a channel for files needing to be processed
|
|
|
|
// we use a multiple of batch size here as a rudimentary concurrency optimization based on the host machine
|
2024-06-06 21:16:34 +03:00
|
|
|
f.filesCh = make(chan *walk.File, BatchSize*runtime.NumCPU())
|
2024-04-19 12:57:41 +03:00
|
|
|
|
2024-05-02 13:28:22 +03:00
|
|
|
// create a channel for files that have been processed
|
2024-06-06 21:16:34 +03:00
|
|
|
f.processedCh = make(chan *walk.File, cap(f.filesCh))
|
2024-04-19 12:57:41 +03:00
|
|
|
|
2024-05-02 13:28:22 +03:00
|
|
|
// start concurrent processing tasks in reverse order
|
2024-06-06 21:16:34 +03:00
|
|
|
eg.Go(f.updateCache(ctx))
|
|
|
|
eg.Go(f.applyFormatters(ctx))
|
|
|
|
eg.Go(f.walkFilesystem(ctx))
|
2024-04-19 12:57:41 +03:00
|
|
|
|
|
|
|
// wait for everything to complete
|
|
|
|
return eg.Wait()
|
|
|
|
}
|
|
|
|
|
2024-06-06 21:16:34 +03:00
|
|
|
func (f *Format) updateCache(ctx context.Context) func() error {
|
2024-05-02 13:28:22 +03:00
|
|
|
return func() error {
|
|
|
|
// used to batch updates for more efficient txs
|
|
|
|
batch := make([]*walk.File, 0, BatchSize)
|
|
|
|
|
|
|
|
// apply a batch
|
|
|
|
processBatch := func() error {
|
2024-06-06 21:16:34 +03:00
|
|
|
if f.Stdin {
|
2024-06-04 20:23:04 +03:00
|
|
|
// do nothing
|
|
|
|
return nil
|
|
|
|
}
|
2024-05-02 13:28:22 +03:00
|
|
|
if err := cache.Update(batch); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
batch = batch[:0]
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
LOOP:
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
// detect ctx cancellation
|
|
|
|
case <-ctx.Done():
|
|
|
|
return ctx.Err()
|
|
|
|
// respond to processed files
|
2024-06-06 21:16:34 +03:00
|
|
|
case file, ok := <-f.processedCh:
|
2024-05-02 13:28:22 +03:00
|
|
|
if !ok {
|
|
|
|
// channel has been closed, no further files to process
|
|
|
|
break LOOP
|
|
|
|
}
|
2024-06-04 20:23:04 +03:00
|
|
|
|
2024-06-06 21:16:34 +03:00
|
|
|
if f.Stdin {
|
2024-06-04 20:23:04 +03:00
|
|
|
// dump file into stdout
|
|
|
|
f, err := os.Open(file.Path)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to open %s: %w", file.Path, err)
|
|
|
|
}
|
|
|
|
if _, err = io.Copy(os.Stdout, f); err != nil {
|
|
|
|
return fmt.Errorf("failed to copy %s to stdout: %w", file.Path, err)
|
|
|
|
}
|
|
|
|
if err = os.Remove(f.Name()); err != nil {
|
|
|
|
return fmt.Errorf("failed to remove temp file %s: %w", file.Path, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
stats.Add(stats.Formatted, 1)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2024-05-02 13:28:22 +03:00
|
|
|
// append to batch and process if we have enough
|
|
|
|
batch = append(batch, file)
|
|
|
|
if len(batch) == BatchSize {
|
|
|
|
if err := processBatch(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// final flush
|
|
|
|
if err := processBatch(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// if fail on change has been enabled, check that no files were actually formatted, throwing an error if so
|
2024-06-06 21:16:34 +03:00
|
|
|
if f.FailOnChange && stats.Value(stats.Formatted) != 0 {
|
2024-05-02 13:28:22 +03:00
|
|
|
return ErrFailOnChange
|
|
|
|
}
|
|
|
|
|
2024-06-04 20:23:04 +03:00
|
|
|
// print stats to stdout unless we are processing stdin and printing the results to stdout
|
2024-06-06 21:16:34 +03:00
|
|
|
if !f.Stdin {
|
2024-06-04 20:23:04 +03:00
|
|
|
stats.Print()
|
|
|
|
}
|
2024-05-02 13:28:22 +03:00
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-06-06 21:16:34 +03:00
|
|
|
func (f *Format) walkFilesystem(ctx context.Context) func() error {
|
2024-04-19 12:57:41 +03:00
|
|
|
return func() error {
|
2024-06-04 19:05:56 +03:00
|
|
|
eg, ctx := errgroup.WithContext(ctx)
|
|
|
|
pathsCh := make(chan string, BatchSize)
|
|
|
|
|
2024-06-04 20:23:04 +03:00
|
|
|
// By default, we use the cli arg, but if the stdin flag has been set we force a filesystem walk
|
|
|
|
// since we will only be processing one file from a temp directory
|
2024-06-06 21:16:34 +03:00
|
|
|
walkerType := f.Walk
|
2024-06-04 20:23:04 +03:00
|
|
|
|
2024-06-06 21:16:34 +03:00
|
|
|
if f.Stdin {
|
2024-06-04 20:23:04 +03:00
|
|
|
walkerType = walk.Filesystem
|
|
|
|
|
|
|
|
// check we have only received one path arg which we use for the file extension / matching to formatters
|
2024-06-06 21:16:34 +03:00
|
|
|
if len(f.Paths) != 1 {
|
2024-06-04 20:23:04 +03:00
|
|
|
return fmt.Errorf("only one path should be specified when using the --stdin flag")
|
|
|
|
}
|
|
|
|
|
|
|
|
// read stdin into a temporary file with the same file extension
|
2024-06-06 21:16:34 +03:00
|
|
|
pattern := fmt.Sprintf("*%s", filepath.Ext(f.Paths[0]))
|
2024-06-04 20:23:04 +03:00
|
|
|
file, err := os.CreateTemp("", pattern)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to create a temporary file for processing stdin: %w", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if _, err = io.Copy(file, os.Stdin); err != nil {
|
|
|
|
return fmt.Errorf("failed to copy stdin into a temporary file")
|
|
|
|
}
|
|
|
|
|
2024-06-06 21:16:34 +03:00
|
|
|
f.Paths[0] = file.Name()
|
2024-06-04 20:23:04 +03:00
|
|
|
}
|
|
|
|
|
2024-06-04 19:05:56 +03:00
|
|
|
walkPaths := func() error {
|
|
|
|
defer close(pathsCh)
|
|
|
|
|
|
|
|
var idx int
|
2024-06-06 21:16:34 +03:00
|
|
|
for idx < len(f.Paths) {
|
2024-06-04 19:05:56 +03:00
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return ctx.Err()
|
|
|
|
default:
|
2024-06-06 21:16:34 +03:00
|
|
|
pathsCh <- f.Paths[idx]
|
2024-06-04 19:05:56 +03:00
|
|
|
idx += 1
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-06-06 21:16:34 +03:00
|
|
|
if len(f.Paths) > 0 {
|
2024-06-04 19:05:56 +03:00
|
|
|
eg.Go(walkPaths)
|
|
|
|
} else {
|
|
|
|
// no explicit paths to process, so we only need to process root
|
2024-06-06 21:16:34 +03:00
|
|
|
pathsCh <- f.TreeRoot
|
2024-06-04 19:05:56 +03:00
|
|
|
close(pathsCh)
|
2024-04-19 12:57:41 +03:00
|
|
|
}
|
|
|
|
|
2024-05-02 13:28:22 +03:00
|
|
|
// create a filesystem walker
|
2024-06-06 21:16:34 +03:00
|
|
|
walker, err := walk.New(walkerType, f.TreeRoot, pathsCh)
|
2024-04-19 12:57:41 +03:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to create walker: %w", err)
|
|
|
|
}
|
|
|
|
|
2024-05-02 13:28:22 +03:00
|
|
|
// close the files channel when we're done walking the file system
|
2024-06-06 21:16:34 +03:00
|
|
|
defer close(f.filesCh)
|
2024-04-19 12:57:41 +03:00
|
|
|
|
2024-06-04 20:23:04 +03:00
|
|
|
// if no cache has been configured, or we are processing from stdin, we invoke the walker directly
|
2024-06-06 21:16:34 +03:00
|
|
|
if f.NoCache || f.Stdin {
|
2024-05-01 21:03:26 +03:00
|
|
|
return walker.Walk(ctx, func(file *walk.File, err error) error {
|
2024-04-19 12:57:41 +03:00
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return ctx.Err()
|
|
|
|
default:
|
|
|
|
// ignore symlinks and directories
|
2024-05-01 21:03:26 +03:00
|
|
|
if !(file.Info.IsDir() || file.Info.Mode()&os.ModeSymlink == os.ModeSymlink) {
|
2024-05-01 13:15:39 +03:00
|
|
|
stats.Add(stats.Traversed, 1)
|
|
|
|
stats.Add(stats.Emitted, 1)
|
2024-06-06 21:16:34 +03:00
|
|
|
f.filesCh <- file
|
2024-04-19 12:57:41 +03:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
2023-12-23 15:50:47 +03:00
|
|
|
|
2024-05-02 13:28:22 +03:00
|
|
|
// otherwise we pass the walker to the cache and have it generate files for processing based on whether or not
|
|
|
|
// they have been added/changed since the last invocation
|
2024-06-06 21:16:34 +03:00
|
|
|
if err = cache.ChangeSet(ctx, walker, f.filesCh); err != nil {
|
2024-04-19 12:57:41 +03:00
|
|
|
return fmt.Errorf("failed to generate change set: %w", err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
2023-12-23 15:50:47 +03:00
|
|
|
|
2024-06-15 12:57:55 +03:00
|
|
|
// applyFormatters
|
2024-06-06 21:16:34 +03:00
|
|
|
func (f *Format) applyFormatters(ctx context.Context) func() error {
|
2024-06-15 12:57:55 +03:00
|
|
|
// create our own errgroup for concurrent formatting tasks.
|
|
|
|
// we don't want a cancel clause, in order to let formatters run up to the end.
|
|
|
|
fg := errgroup.Group{}
|
2024-05-24 13:42:40 +03:00
|
|
|
// simple optimization to avoid too many concurrent formatting tasks
|
|
|
|
// we can queue them up faster than the formatters can process them, this paces things a bit
|
|
|
|
fg.SetLimit(runtime.NumCPU())
|
2024-05-02 13:28:22 +03:00
|
|
|
|
2024-05-24 13:42:40 +03:00
|
|
|
// track batches of formatting task based on their batch keys, which are determined by the unique sequence of
|
|
|
|
// formatters which should be applied to their respective files
|
|
|
|
batches := make(map[string][]*format.Task)
|
2023-12-23 15:50:47 +03:00
|
|
|
|
2024-05-24 13:42:40 +03:00
|
|
|
apply := func(key string, flush bool) {
|
|
|
|
// lookup the batch and exit early if it's empty
|
2024-05-02 13:28:22 +03:00
|
|
|
batch := batches[key]
|
2024-05-24 13:42:40 +03:00
|
|
|
if len(batch) == 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// process the batch if it's full, or we've been asked to flush partial batches
|
|
|
|
if flush || len(batch) == BatchSize {
|
2024-01-12 14:46:04 +03:00
|
|
|
|
2024-05-24 13:42:40 +03:00
|
|
|
// copy the batch as we re-use it for the next batch
|
|
|
|
tasks := make([]*format.Task, len(batch))
|
|
|
|
copy(tasks, batch)
|
2023-12-23 15:50:47 +03:00
|
|
|
|
2024-05-24 13:42:40 +03:00
|
|
|
// asynchronously apply the sequence formatters to the batch
|
2024-04-19 12:57:41 +03:00
|
|
|
fg.Go(func() error {
|
2024-05-24 13:42:40 +03:00
|
|
|
// iterate the formatters, applying them in sequence to the batch of tasks
|
|
|
|
// we get the formatters list from the first task since they have all the same formatters list
|
|
|
|
for _, f := range tasks[0].Formatters {
|
|
|
|
if err := f.Apply(ctx, tasks); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2024-04-19 12:57:41 +03:00
|
|
|
}
|
2024-05-24 13:42:40 +03:00
|
|
|
|
|
|
|
// pass each file to the processed channel
|
|
|
|
for _, task := range tasks {
|
2024-06-06 21:16:34 +03:00
|
|
|
f.processedCh <- task.File
|
2024-04-19 12:57:41 +03:00
|
|
|
}
|
2024-05-24 13:42:40 +03:00
|
|
|
|
2024-04-19 12:57:41 +03:00
|
|
|
return nil
|
|
|
|
})
|
2024-01-10 18:45:57 +03:00
|
|
|
|
2024-05-02 13:28:22 +03:00
|
|
|
// reset the batch
|
2024-04-19 12:57:41 +03:00
|
|
|
batches[key] = batch[:0]
|
2024-01-10 18:45:57 +03:00
|
|
|
}
|
2024-04-19 12:57:41 +03:00
|
|
|
}
|
2024-01-10 18:45:57 +03:00
|
|
|
|
2024-05-24 13:42:40 +03:00
|
|
|
tryApply := func(task *format.Task) {
|
|
|
|
// append to batch
|
|
|
|
key := task.BatchKey
|
|
|
|
batches[key] = append(batches[key], task)
|
|
|
|
// try to apply
|
|
|
|
apply(key, false)
|
2024-04-19 12:57:41 +03:00
|
|
|
}
|
feat: support --no-cache
Signed-off-by: Brian McGee <brian@bmcgee.ie>
diff --git a/cli/cli.go b/cli/cli.go
index 8b23262..b370ee7 100644
--- a/cli/cli.go
+++ b/cli/cli.go
@@ -11,6 +11,7 @@ var Cli = Format{}
type Format struct {
AllowMissingFormatter bool `default:"false" help:"Do not exit with error if a configured formatter is missing"`
WorkingDirectory kong.ChangeDirFlag `default:"." short:"C" help:"Run as if treefmt was started in the specified working directory instead of the current working directory"`
+ NoCache bool `help:"Ignore the evaluation cache entirely. Useful for CI"`
ClearCache bool `short:"c" help:"Reset the evaluation cache. Use in case the cache is not precise enough"`
ConfigFile string `type:"existingfile" default:"./treefmt.toml"`
FailOnChange bool `help:"Exit with error if any changes were made. Useful for CI."`
diff --git a/cli/format.go b/cli/format.go
index 6c46096..14ac16c 100644
--- a/cli/format.go
+++ b/cli/format.go
@@ -5,6 +5,7 @@ import (
"context"
"errors"
"fmt"
+ "io/fs"
"os"
"os/signal"
"strings"
@@ -168,6 +169,20 @@ func (f *Format) Run() error {
var changes int
+ processBatch := func() error {
+ if Cli.NoCache {
+ changes += len(batch)
+ } else {
+ count, err := cache.Update(batch)
+ if err != nil {
+ return err
+ }
+ changes += count
+ }
+ batch = batch[:0]
+ return nil
+ }
+
LOOP:
for {
select {
@@ -179,22 +194,17 @@ func (f *Format) Run() error {
}
batch = append(batch, path)
if len(batch) == batchSize {
- count, err := cache.Update(batch)
- if err != nil {
+ if err = processBatch(); err != nil {
return err
}
- changes += count
- batch = batch[:0]
}
}
}
// final flush
- count, err := cache.Update(batch)
- if err != nil {
+ if err = processBatch(); err != nil {
return err
}
- changes += count
if Cli.FailOnChange && changes != 0 {
return ErrFailOnChange
@@ -251,6 +261,22 @@ func (f *Format) Run() error {
}
defer close(pathsCh)
+
+ if Cli.NoCache {
+ return walker.Walk(ctx, func(path string, info fs.FileInfo, err error) error {
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ default:
+ // ignore symlinks and directories
+ if !(info.IsDir() || info.Mode()&os.ModeSymlink == os.ModeSymlink) {
+ pathsCh <- path
+ }
+ return nil
+ }
+ })
+ }
+
return cache.ChangeSet(ctx, walker, pathsCh)
})
diff --git a/cli/format_test.go b/cli/format_test.go
index fb389fe..2349767 100644
--- a/cli/format_test.go
+++ b/cli/format_test.go
@@ -216,6 +216,15 @@ func TestCache(t *testing.T) {
as.NoError(err)
as.Contains(string(out), "0 files changed")
+ // clear cache
+ out, err = cmd(t, "--config-file", configPath, "--tree-root", tempDir, "-c")
+ as.NoError(err)
+ as.Contains(string(out), fmt.Sprintf("%d files changed", 29))
+
+ out, err = cmd(t, "--config-file", configPath, "--tree-root", tempDir)
+ as.NoError(err)
+ as.Contains(string(out), "0 files changed")
+
// no cache
out, err = cmd(t, "--config-file", configPath, "--tree-root", tempDir, "--no-cache")
as.NoError(err)
diff --git a/nix/packages.nix b/nix/packages.nix
index 127eb08..e0f8604 100644
--- a/nix/packages.nix
+++ b/nix/packages.nix
@@ -13,7 +13,7 @@
packages = rec {
treefmt = inputs'.gomod2nix.legacyPackages.buildGoApplication rec {
pname = "treefmt";
- version = "0.0.1+dev";
+ version = "2.0.0+dev";
# ensure we are using the same version of go to build with
inherit (pkgs) go;
diff --git a/cli/cli.go b/cli/cli.go
index 8b23262..b370ee7 100644
--- a/cli/cli.go
+++ b/cli/cli.go
@@ -11,6 +11,7 @@ var Cli = Format{}
type Format struct {
AllowMissingFormatter bool `default:"false" help:"Do not exit with error if a configured formatter is missing"`
WorkingDirectory kong.ChangeDirFlag `default:"." short:"C" help:"Run as if treefmt was started in the specified working directory instead of the current working directory"`
+ NoCache bool `help:"Ignore the evaluation cache entirely. Useful for CI"`
ClearCache bool `short:"c" help:"Reset the evaluation cache. Use in case the cache is not precise enough"`
ConfigFile string `type:"existingfile" default:"./treefmt.toml"`
FailOnChange bool `help:"Exit with error if any changes were made. Useful for CI."`
diff --git a/cli/format.go b/cli/format.go
index 6c46096..14ac16c 100644
--- a/cli/format.go
+++ b/cli/format.go
@@ -5,6 +5,7 @@ import (
"context"
"errors"
"fmt"
+ "io/fs"
"os"
"os/signal"
"strings"
@@ -168,6 +169,20 @@ func (f *Format) Run() error {
var changes int
+ processBatch := func() error {
+ if Cli.NoCache {
+ changes += len(batch)
+ } else {
+ count, err := cache.Update(batch)
+ if err != nil {
+ return err
+ }
+ changes += count
+ }
+ batch = batch[:0]
+ return nil
+ }
+
LOOP:
for {
select {
@@ -179,22 +194,17 @@ func (f *Format) Run() error {
}
batch = append(batch, path)
if len(batch) == batchSize {
- count, err := cache.Update(batch)
- if err != nil {
+ if err = processBatch(); err != nil {
return err
}
- changes += count
- batch = batch[:0]
}
}
}
// final flush
- count, err := cache.Update(batch)
- if err != nil {
+ if err = processBatch(); err != nil {
return err
}
- changes += count
if Cli.FailOnChange && changes != 0 {
return ErrFailOnChange
@@ -251,6 +261,22 @@ func (f *Format) Run() error {
}
defer close(pathsCh)
+
+ if Cli.NoCache {
+ return walker.Walk(ctx, func(path string, info fs.FileInfo, err error) error {
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ default:
+ // ignore symlinks and directories
+ if !(info.IsDir() || info.Mode()&os.ModeSymlink == os.ModeSymlink) {
+ pathsCh <- path
+ }
+ return nil
+ }
+ })
+ }
+
return cache.ChangeSet(ctx, walker, pathsCh)
})
diff --git a/nix/packages.nix b/nix/packages.nix
index 127eb08..e0f8604 100644
--- a/nix/packages.nix
+++ b/nix/packages.nix
@@ -13,7 +13,7 @@
packages = rec {
treefmt = inputs'.gomod2nix.legacyPackages.buildGoApplication rec {
pname = "treefmt";
- version = "0.0.1+dev";
+ version = "2.0.0+dev";
# ensure we are using the same version of go to build with
inherit (pkgs) go;
2024-02-15 13:37:33 +03:00
|
|
|
|
2024-04-19 12:57:41 +03:00
|
|
|
return func() error {
|
|
|
|
defer func() {
|
|
|
|
// close processed channel
|
2024-06-06 21:16:34 +03:00
|
|
|
close(f.processedCh)
|
2024-04-19 12:57:41 +03:00
|
|
|
}()
|
2023-12-23 15:50:47 +03:00
|
|
|
|
2024-05-24 13:42:40 +03:00
|
|
|
// iterate the files channel
|
2024-06-06 21:16:34 +03:00
|
|
|
for file := range f.filesCh {
|
2024-05-17 13:46:05 +03:00
|
|
|
|
2024-06-14 12:30:13 +03:00
|
|
|
// first check if this file has been globally excluded
|
|
|
|
if format.PathMatches(file.RelPath, f.globalExcludes) {
|
|
|
|
log.Debugf("path matched global excludes: %s", file.RelPath)
|
|
|
|
// mark it as processed and continue to the next
|
|
|
|
f.processedCh <- file
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
// check if any formatters are interested in this file
|
2024-05-24 13:42:40 +03:00
|
|
|
var matches []*format.Formatter
|
2024-06-06 21:16:34 +03:00
|
|
|
for _, formatter := range f.formatters {
|
2024-05-24 13:42:40 +03:00
|
|
|
if formatter.Wants(file) {
|
|
|
|
matches = append(matches, formatter)
|
2024-04-19 12:57:41 +03:00
|
|
|
}
|
|
|
|
}
|
2024-05-24 13:42:40 +03:00
|
|
|
|
2024-06-14 12:30:13 +03:00
|
|
|
// see if any formatters matched
|
2024-05-24 13:42:40 +03:00
|
|
|
if len(matches) == 0 {
|
2024-06-06 21:16:34 +03:00
|
|
|
if f.OnUnmatched == log.FatalLevel {
|
2024-06-14 12:30:13 +03:00
|
|
|
return fmt.Errorf("no formatter for path: %s", file.RelPath)
|
2024-05-26 19:35:50 +03:00
|
|
|
}
|
2024-06-14 12:30:13 +03:00
|
|
|
log.Logf(f.OnUnmatched, "no formatter for path: %s", file.RelPath)
|
|
|
|
// mark it as processed and continue to the next
|
2024-06-06 21:16:34 +03:00
|
|
|
f.processedCh <- file
|
2024-05-24 13:42:40 +03:00
|
|
|
} else {
|
|
|
|
// record the match
|
2024-05-17 13:46:05 +03:00
|
|
|
stats.Add(stats.Matched, 1)
|
2024-05-24 13:42:40 +03:00
|
|
|
// create a new format task, add it to a batch based on its batch key and try to apply if the batch is full
|
|
|
|
task := format.NewTask(file, matches)
|
|
|
|
tryApply(&task)
|
2024-05-01 13:15:39 +03:00
|
|
|
}
|
2024-04-19 12:57:41 +03:00
|
|
|
}
|
2023-12-23 18:00:39 +03:00
|
|
|
|
2024-04-19 12:57:41 +03:00
|
|
|
// flush any partial batches which remain
|
2024-05-24 13:42:40 +03:00
|
|
|
for key := range batches {
|
|
|
|
apply(key, true)
|
|
|
|
}
|
2024-04-19 12:57:41 +03:00
|
|
|
|
|
|
|
// wait for all outstanding formatting tasks to complete
|
|
|
|
if err := fg.Wait(); err != nil {
|
2024-05-24 13:42:40 +03:00
|
|
|
return fmt.Errorf("formatting failure: %w", err)
|
2024-04-19 12:57:41 +03:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2023-12-23 15:50:47 +03:00
|
|
|
}
|
2024-05-30 16:43:26 +03:00
|
|
|
|
|
|
|
func findUp(searchDir string, fileName string) (path string, dir string, err error) {
|
|
|
|
for _, dir := range eachDir(searchDir) {
|
|
|
|
path := filepath.Join(dir, fileName)
|
|
|
|
if fileExists(path) {
|
|
|
|
return path, dir, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return "", "", fmt.Errorf("could not find %s in %s", fileName, searchDir)
|
|
|
|
}
|
|
|
|
|
|
|
|
func eachDir(path string) (paths []string) {
|
|
|
|
path, err := filepath.Abs(path)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
paths = []string{path}
|
|
|
|
|
|
|
|
if path == "/" {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
for i := len(path) - 1; i >= 0; i-- {
|
|
|
|
if path[i] == os.PathSeparator {
|
|
|
|
path = path[:i]
|
|
|
|
if path == "" {
|
|
|
|
path = "/"
|
|
|
|
}
|
|
|
|
paths = append(paths, path)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func fileExists(path string) bool {
|
|
|
|
// Some broken filesystems like SSHFS return file information on stat() but
|
|
|
|
// then cannot open the file. So we use os.Open.
|
|
|
|
f, err := os.Open(path)
|
|
|
|
if err != nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
defer f.Close()
|
|
|
|
|
|
|
|
// Next, check that the file is a regular file.
|
|
|
|
fi, err := f.Stat()
|
|
|
|
if err != nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
return fi.Mode().IsRegular()
|
|
|
|
}
|