|
| 1 | +package secrethub |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + |
| 6 | + "github.com/secrethub/secrethub-cli/internals/cli/ui" |
| 7 | + "github.com/secrethub/secrethub-cli/internals/secrethub/command" |
| 8 | +) |
| 9 | + |
| 10 | +// EnvReadCommand is a command to read the value of a single environment variable. |
| 11 | +type EnvReadCommand struct { |
| 12 | + io ui.IO |
| 13 | + newClient newClientFunc |
| 14 | + environment *environment |
| 15 | + key string |
| 16 | +} |
| 17 | + |
| 18 | +// NewEnvReadCommand creates a new EnvReadCommand. |
| 19 | +func NewEnvReadCommand(io ui.IO, newClient newClientFunc) *EnvReadCommand { |
| 20 | + return &EnvReadCommand{ |
| 21 | + io: io, |
| 22 | + newClient: newClient, |
| 23 | + environment: newEnvironment(io), |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +// Register adds a CommandClause and it's args and flags to a Registerer. |
| 28 | +func (cmd *EnvReadCommand) Register(r command.Registerer) { |
| 29 | + clause := r.Command("read", "[BETA] Read the value of a single environment variable.") |
| 30 | + clause.HelpLong("This command is hidden because it is still in beta. Future versions may break.") |
| 31 | + clause.Arg("key", "the key of the environment variable to read").StringVar(&cmd.key) |
| 32 | + |
| 33 | + cmd.environment.register(clause) |
| 34 | + |
| 35 | + command.BindAction(clause, cmd.Run) |
| 36 | +} |
| 37 | + |
| 38 | +// Run executes the command. |
| 39 | +func (cmd *EnvReadCommand) Run() error { |
| 40 | + env, err := cmd.environment.env() |
| 41 | + if err != nil { |
| 42 | + return err |
| 43 | + } |
| 44 | + |
| 45 | + value, found := env[cmd.key] |
| 46 | + if !found { |
| 47 | + return fmt.Errorf("no environment variable with that key is set") |
| 48 | + } |
| 49 | + |
| 50 | + secretReader := newSecretReader(cmd.newClient) |
| 51 | + |
| 52 | + res, err := value.resolve(secretReader) |
| 53 | + if err != nil { |
| 54 | + return err |
| 55 | + } |
| 56 | + |
| 57 | + fmt.Fprintln(cmd.io.Stdout(), res) |
| 58 | + |
| 59 | + return nil |
| 60 | +} |
0 commit comments