@@ -3,12 +3,17 @@ package main
33import (
44 "fmt"
55 "github.com/hephbuild/heph/bootstrap"
6+ "github.com/hephbuild/heph/buildfiles"
67 "github.com/hephbuild/heph/config"
78 "github.com/hephbuild/heph/log/log"
9+ "github.com/hephbuild/heph/packages"
810 "github.com/hephbuild/heph/targetrun"
911 "github.com/hephbuild/heph/utils"
12+ "github.com/hephbuild/heph/utils/ads"
1013 "github.com/hephbuild/heph/utils/finalizers"
14+ "github.com/hephbuild/heph/utils/xstarlark"
1115 "github.com/spf13/cobra"
16+ "go.uber.org/multierr"
1217 "os"
1318 "runtime"
1419 "runtime/pprof"
@@ -34,6 +39,7 @@ var params *[]string
3439var summary * bool
3540var summaryGen * bool
3641var jaegerEndpoint * string
42+ var check * bool
3743
3844func getRunOpts () bootstrap.RunOpts {
3945 return bootstrap.RunOpts {
@@ -70,6 +76,8 @@ func init() {
7076 runCmd .Flags ().AddFlag (NewBoolStrFlag (& catOutput , "cat-out" , "" , "Print target output content, --cat-out=<name> to filter output" ))
7177 alwaysOut = runCmd .Flags ().Bool ("always-out" , false , "Ensure output will be present in cache" )
7278
79+ check = fmtCmd .Flags ().Bool ("check" , false , "Only check formatting" )
80+
7381 rootCmd .AddCommand (runCmd )
7482 rootCmd .AddCommand (cleanCmd )
7583 rootCmd .AddCommand (queryCmd )
@@ -78,6 +86,7 @@ func init() {
7886 rootCmd .AddCommand (validateCmd )
7987 rootCmd .AddCommand (setupCmd )
8088 rootCmd .AddCommand (searchCmd )
89+ rootCmd .AddCommand (fmtCmd )
8190
8291 cpuprofile = rootCmd .PersistentFlags ().String ("cpuprofile" , "" , "CPU Profile file" )
8392 memprofile = rootCmd .PersistentFlags ().String ("memprofile" , "" , "Mem Profile file" )
@@ -299,3 +308,54 @@ var setupCmd = &cobra.Command{
299308 return nil
300309 },
301310}
311+
312+ var fmtCmd = & cobra.Command {
313+ Use : "fmt" ,
314+ Short : "Format build files" ,
315+ Args : cobra .ArbitraryArgs ,
316+ RunE : func (cmd * cobra.Command , args []string ) error {
317+ ctx := cmd .Context ()
318+
319+ bs , err := bootstrapBase (ctx )
320+ if err != nil {
321+ return err
322+ }
323+
324+ buildfilesState := buildfiles .NewState (buildfiles.State {
325+ Ignore : bs .Config .BuildFiles .Ignore ,
326+ })
327+
328+ var files []string
329+ if len (args ) == 0 {
330+ cfiles , err := buildfilesState .CollectFiles (ctx , bs .Root .Root .Abs ())
331+ if err != nil {
332+ return err
333+ }
334+
335+ files = ads .Map (cfiles , func (f * packages.SourceFile ) string {
336+ return f .Path
337+ })
338+ } else {
339+ files = args
340+ }
341+
342+ cfg := xstarlark.FmtConfig {
343+ IndentSize : bs .Config .Fmt .IndentSize ,
344+ }
345+
346+ var errs error
347+ for _ , file := range files {
348+ f := xstarlark .FmtFix
349+ if * check {
350+ f = xstarlark .FmtCheck
351+ }
352+
353+ err := f (file , cfg )
354+ if err != nil {
355+ errs = multierr .Append (errs , fmt .Errorf ("%v: %w" , file , err ))
356+ }
357+ }
358+
359+ return errs
360+ },
361+ }
0 commit comments