github.com/octohelm/cuemod@v0.9.4/pkg/cuex/format/format.go (about)

     1  package format
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  	"fmt"
     7  	"io"
     8  	"os"
     9  	"path/filepath"
    10  
    11  	"cuelang.org/go/cue/format"
    12  	"github.com/go-courier/logr"
    13  )
    14  
    15  // FormatOpts
    16  type FormatOpts struct {
    17  	// ReplaceFile when enabled, will write formatted code to same file
    18  	ReplaceFile bool `flag:"write,w" desc:"write result to (source) file instead of stdout"`
    19  	// PrintNames when enabled, will print formatted result of each file
    20  	PrintNames bool `flag:"list,l" `
    21  }
    22  
    23  // FormatFiles format jsonnet files
    24  func FormatFiles(ctx context.Context, files []string, opt FormatOpts) error {
    25  	log := logr.FromContext(ctx)
    26  
    27  	writeFile := func(file string, data []byte) error {
    28  		f, _ := os.OpenFile(file, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0)
    29  		defer f.Close()
    30  		_, err := io.Copy(f, bytes.NewBuffer(data))
    31  		return err
    32  	}
    33  
    34  	cwd, _ := os.Getwd()
    35  
    36  	for i := range files {
    37  		file := files[i]
    38  
    39  		data, err := os.ReadFile(file)
    40  		if err != nil {
    41  			return err
    42  		}
    43  
    44  		file, _ = filepath.Rel(cwd, file)
    45  
    46  		formatted, changed, err := Format(data)
    47  		if err != nil {
    48  			return err
    49  		}
    50  
    51  		if changed {
    52  			if opt.PrintNames {
    53  				log.Info(fmt.Sprintf("`%s` formatted.", file))
    54  			}
    55  
    56  			if opt.ReplaceFile {
    57  				if err := writeFile(file, formatted); err != nil {
    58  					return err
    59  				}
    60  			} else {
    61  				fmt.Printf(`
    62  // %s 
    63  
    64  %s
    65  `, file, formatted)
    66  			}
    67  		} else {
    68  			if opt.PrintNames {
    69  				log.Info(fmt.Sprintf("`%s` no changes.", file))
    70  			}
    71  		}
    72  	}
    73  
    74  	return nil
    75  }
    76  
    77  func Format(src []byte) ([]byte, bool, error) {
    78  	formatted, err := format.Source(src, format.Simplify())
    79  	if err != nil {
    80  		return nil, false, err
    81  	}
    82  	return formatted, !bytes.Equal(formatted, src), nil
    83  }