|
| 1 | +/* |
| 2 | +SPDX-FileCopyrightText: 2021 SAP SE or an SAP affiliate company and Gardener contributors |
| 3 | +SPDX-License-Identifier: Apache-2.0 |
| 4 | +*/ |
| 5 | + |
| 6 | +package target |
| 7 | + |
| 8 | +import ( |
| 9 | + "errors" |
| 10 | + "fmt" |
| 11 | + "io/ioutil" |
| 12 | + "os" |
| 13 | + "os/exec" |
| 14 | + |
| 15 | + "github.com/spf13/cobra" |
| 16 | + |
| 17 | + "github.com/gardener/gardenctl-v2/internal/util" |
| 18 | + "github.com/gardener/gardenctl-v2/pkg/cmd/base" |
| 19 | +) |
| 20 | + |
| 21 | +const ( |
| 22 | + historyFile string = "history" |
| 23 | +) |
| 24 | + |
| 25 | +// NewCmdHistory returns a new target history command. |
| 26 | +func NewCmdHistory(f util.Factory, o base.Options) *cobra.Command { |
| 27 | + cmd := &cobra.Command{ |
| 28 | + Use: "history", |
| 29 | + Short: "Print the target history", |
| 30 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 31 | + return runHistoryCommand(f, o) |
| 32 | + }, |
| 33 | + } |
| 34 | + |
| 35 | + return cmd |
| 36 | +} |
| 37 | + |
| 38 | +func runHistoryCommand(f util.Factory, o base.Options) error { |
| 39 | + if err := checkInstalled("fzf"); err != nil { |
| 40 | + return errors.New("fzf not installed. Please install from https://github.com/junegunn/fzf") |
| 41 | + } |
| 42 | + |
| 43 | + if err := HistoryOutput(historyPath(f), o); err != nil { |
| 44 | + return err |
| 45 | + } |
| 46 | + |
| 47 | + return nil |
| 48 | +} |
| 49 | + |
| 50 | +func HistoryWrite(path string, s string) error { |
| 51 | + f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666) |
| 52 | + if err != nil { |
| 53 | + return fmt.Errorf("history file open error %s", path) |
| 54 | + } |
| 55 | + defer f.Close() |
| 56 | + |
| 57 | + if _, err := f.WriteString(s); err != nil { |
| 58 | + return fmt.Errorf("history file write error %s", path) |
| 59 | + } |
| 60 | + |
| 61 | + return nil |
| 62 | +} |
| 63 | + |
| 64 | +func HistoryOutput(path string, o base.Options) error { |
| 65 | + content, err := ioutil.ReadFile(path) |
| 66 | + if err != nil { |
| 67 | + return err |
| 68 | + } |
| 69 | + |
| 70 | + return o.PrintObject(string(content)) |
| 71 | +} |
| 72 | + |
| 73 | +func checkInstalled(name string) error { |
| 74 | + if _, err := exec.LookPath(name); err != nil { |
| 75 | + return fmt.Errorf(name + " is not installed") |
| 76 | + } |
| 77 | + |
| 78 | + return nil |
| 79 | +} |
| 80 | + |
| 81 | +func historyPath(f util.Factory) string { |
| 82 | + return f.GardenHomeDir() + "/" + historyFile |
| 83 | +} |
0 commit comments