github.com/GGP1/kure@v0.8.4/commands/config/edit/edit.go (about)

     1  package edit
     2  
     3  import (
     4  	"os"
     5  	"os/exec"
     6  
     7  	"github.com/GGP1/kure/auth"
     8  	cmdutil "github.com/GGP1/kure/commands"
     9  	"github.com/GGP1/kure/config"
    10  
    11  	"github.com/pkg/errors"
    12  	"github.com/spf13/cobra"
    13  	bolt "go.etcd.io/bbolt"
    14  )
    15  
    16  const example = `
    17  kure config edit`
    18  
    19  // NewCmd returns a new command.
    20  func NewCmd(db *bolt.DB) *cobra.Command {
    21  	return &cobra.Command{
    22  		Use:     "edit",
    23  		Short:   "Edit the current configuration file",
    24  		Example: example,
    25  		PreRunE: auth.Login(db),
    26  		RunE:    runEdit(),
    27  	}
    28  }
    29  
    30  func runEdit() cmdutil.RunEFunc {
    31  	return func(cmd *cobra.Command, args []string) error {
    32  		path := config.Filename()
    33  
    34  		f, err := os.OpenFile(path, os.O_RDWR, 0o600)
    35  		if err != nil {
    36  			return errors.Wrap(err, "opening configuration file")
    37  		}
    38  		defer f.Close()
    39  
    40  		editor := cmdutil.SelectEditor()
    41  		bin, err := exec.LookPath(editor)
    42  		if err != nil {
    43  			return errors.Errorf("%q executable not found", editor)
    44  		}
    45  
    46  		edit := exec.Command(bin, path)
    47  		edit.Stdin = os.Stdin
    48  		edit.Stdout = os.Stdout
    49  
    50  		if err := edit.Run(); err != nil {
    51  			return errors.Wrap(err, "running edit command")
    52  		}
    53  
    54  		return nil
    55  	}
    56  }