github.com/google/yamlfmt@v0.12.2-0.20240514121411-7f77800e2681/cmd/yamlfmt/main.go (about)

     1  // Copyright 2022 Google LLC
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package main
    16  
    17  import (
    18  	"flag"
    19  	"fmt"
    20  	"log"
    21  	"os"
    22  
    23  	"github.com/google/yamlfmt"
    24  	"github.com/google/yamlfmt/command"
    25  	"github.com/google/yamlfmt/formatters/basic"
    26  	"github.com/google/yamlfmt/internal/logger"
    27  )
    28  
    29  var (
    30  	version = "dev"
    31  	commit  = "none"
    32  )
    33  
    34  func main() {
    35  	if err := run(); err != nil {
    36  		l := log.New(os.Stderr, "", 0)
    37  		l.Fatal(err)
    38  	}
    39  }
    40  
    41  func run() error {
    42  	bindArrayFlags()
    43  	configureHelp()
    44  	flag.Parse()
    45  
    46  	if *flagVersion {
    47  		fmt.Printf("yamlfmt %s (%s)\n", version, commit)
    48  		return nil
    49  	}
    50  
    51  	for _, code := range flagDebug {
    52  		logger.ActivateDebugCode(code)
    53  	}
    54  
    55  	c := &command.Command{
    56  		Operation: getOperationFromFlag(),
    57  		Registry:  getFullRegistry(),
    58  		Quiet:     *flagQuiet,
    59  	}
    60  
    61  	configData := map[string]any{}
    62  	configPath, err := getConfigPath()
    63  	if err != nil {
    64  		return err
    65  	}
    66  	if configPath != "" {
    67  		configData, err = readConfig(configPath)
    68  		if err != nil {
    69  			return err
    70  		}
    71  	}
    72  
    73  	commandConfig, err := makeCommandConfigFromData(configData)
    74  	if err != nil {
    75  		return err
    76  	}
    77  	c.Config = commandConfig
    78  
    79  	return c.Run()
    80  }
    81  
    82  func getFullRegistry() *yamlfmt.Registry {
    83  	return yamlfmt.NewFormatterRegistry(&basic.BasicFormatterFactory{})
    84  }