github.com/grafana/tanka@v0.26.1-0.20240506093700-c22cfc35c21a/cmd/tk/util.go (about)

     1  package main
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"io"
     7  	"os"
     8  	"os/exec"
     9  	"strings"
    10  
    11  	"github.com/google/go-jsonnet/formatter"
    12  )
    13  
    14  func pageln(i ...interface{}) error {
    15  	return fPageln(strings.NewReader(fmt.Sprint(i...)))
    16  }
    17  
    18  // fPageln invokes the systems pager with the supplied data.
    19  // If the PAGER environment variable is empty, no pager is used.
    20  // If the PAGER environment variable is unset, use GNU less with convenience flags.
    21  func fPageln(r io.Reader) error {
    22  	pager, ok := os.LookupEnv("PAGER")
    23  	if !ok {
    24  		// --RAW-CONTROL-CHARS  Honors colors from diff. Must be in all caps, otherwise display issues occur.
    25  		// --quit-if-one-screen Closer to the git experience.
    26  		// --no-init            Don't clear the screen when exiting.
    27  		pager = "less --RAW-CONTROL-CHARS --quit-if-one-screen --no-init"
    28  	}
    29  
    30  	if interactive && pager != "" {
    31  		cmd := exec.Command("sh", "-c", pager)
    32  		cmd.Stdin = r
    33  		cmd.Stdout = os.Stdout
    34  		cmd.Stderr = os.Stderr
    35  
    36  		if err := cmd.Run(); err == nil {
    37  			return nil
    38  		}
    39  	}
    40  
    41  	_, err := io.Copy(os.Stdout, r)
    42  	return err
    43  }
    44  
    45  // writeJSON writes the given object to the path as a JSON file
    46  func writeJSON(i interface{}, path string) error {
    47  	out, err := json.MarshalIndent(i, "", "  ")
    48  	if err != nil {
    49  		return fmt.Errorf("marshalling: %s", err)
    50  	}
    51  
    52  	if err := os.WriteFile(path, append(out, '\n'), 0644); err != nil {
    53  		return fmt.Errorf("writing %s: %s", path, err)
    54  	}
    55  
    56  	return nil
    57  }
    58  
    59  // writeJsonnet writes the given object to the path as a formatted Jsonnet file
    60  func writeJsonnet(i interface{}, path string) error {
    61  	out, err := json.MarshalIndent(i, "", "  ")
    62  	if err != nil {
    63  		return fmt.Errorf("marshalling: %s", err)
    64  	}
    65  
    66  	main, err := formatter.Format(path, string(out), formatter.DefaultOptions())
    67  	if err != nil {
    68  		return fmt.Errorf("formatting %s: %s", path, err)
    69  	}
    70  
    71  	if err := os.WriteFile(path, []byte(main), 0644); err != nil {
    72  		return fmt.Errorf("writing %s: %s", path, err)
    73  	}
    74  
    75  	return nil
    76  }