Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stop using init() to setup cobra commands #5

Merged
merged 2 commits into from
Jun 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 34 additions & 33 deletions cmd/backup.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0
http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
Expand All @@ -26,11 +26,12 @@ import (
"github.com/endorama/devid/internal/backup"
)

// backupCmd represents the backup command.
var backupCmd = &cobra.Command{ //nolint:gochecknoglobals // required by cobra
Use: "backup",
Short: "backup a persona",
Long: `Create encrypted backup of a persona.
func Backup() *cobra.Command {
// backupCmd represents the backup command.
var backupCmd = &cobra.Command{ //nolint:gochecknoglobals // required by cobra
Use: "backup",
Short: "backup a persona",
Long: `Create encrypted backup of a persona.

The backup is compressed (.tar.gz) and encrypted using age (filippo.io/age).
Encryption requires a passphrase that is automatically generated using a safe
Expand All @@ -39,36 +40,36 @@ RNG function and printed after backup creation.
This command loads the current persona from DEVID_ACTIVE_PERSONA environment variable, and this
value takes precedence over the --persona flag.
`,
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
p, err := utils.LoadPersona(cmd)
if err != nil {
ui.Fatal(fmt.Errorf("cannot instantiate persona: %w", err), noPersonaLoadedExitCode)
}
passphrase := utils.GeneratePassphrase()
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
p, err := utils.LoadPersona(cmd)
if err != nil {
ui.Fatal(fmt.Errorf("cannot instantiate persona: %w", err), noPersonaLoadedExitCode)
}
passphrase := utils.GeneratePassphrase()

ui.Outputf(fmt.Sprintf("creating backup for persona: %s\n", p.Name()))
ui.Outputf(fmt.Sprintf("creating backup for persona: %s\n", p.Name()))

out, err := os.Create(fmt.Sprintf("%s.tar.gz.age", p.Name()))
if err != nil {
ui.Fatal(fmt.Errorf("cannot create file: %w", err), genericExitCode)
}
defer out.Close()
out, err := os.Create(fmt.Sprintf("%s.tar.gz.age", p.Name()))
if err != nil {
ui.Fatal(fmt.Errorf("cannot create file: %w", err), genericExitCode)
}
defer out.Close()

b, err := backup.NewTask(p.Name(), p.Location(), out)
if err != nil {
ui.Fatal(fmt.Errorf("cannot create backup task: %w", err), genericExitCode)
}
err = backup.Perform(b, passphrase)
if err != nil {
ui.Fatal(err, genericExitCode)
}
b, err := backup.NewTask(p.Name(), p.Location(), out)
if err != nil {
ui.Fatal(fmt.Errorf("cannot create backup task: %w", err), genericExitCode)
}
err = backup.Perform(b, passphrase)
if err != nil {
ui.Fatal(err, genericExitCode)
}

ui.Infof("Encryption passphrase is: %s", passphrase)
},
}

func init() { //nolint:gochecknoinits // required by cobra
ui.Infof("Encryption passphrase is: %s", passphrase)
},
}
backupCmd.Flags().String("persona", "", "The persona to backup")
rootCmd.AddCommand(backupCmd)

return backupCmd

}
35 changes: 35 additions & 0 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package cmd

import (
"github.com/endorama/devid/cmd/ui"
"github.com/spf13/cobra"
)

var cli *cobra.Command

// Init initialises a cobra CLI with all commands from this package.
func Init() {
cli = RootCmd()
cli.AddCommand(
Backup(),
Delete(),
Edit(),
List(),
New(),
Rehash(),
Shell(),
Whoami(),
)
}

// Execute perform execution of the global CLI initialised with Init().
// panics if Init() has not been called.
func Execute() {
if cli == nil {
panic("cli has not been initialised, have you called Init()?")
}

if err := cli.Execute(); err != nil {
ui.Fatal(err, genericExitCode)
}
}
44 changes: 22 additions & 22 deletions cmd/delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0
http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
Expand All @@ -25,11 +25,11 @@ import (
"github.com/endorama/devid/cmd/utils"
)

// deleteCmd represents the delete command.
var deleteCmd = &cobra.Command{ //nolint:gochecknoglobals // required by cobra
Use: "delete",
Short: "delete a persona",
Long: `Delete a persona using a secure deletion function.
func Delete() *cobra.Command {
deleteCmd := &cobra.Command{
Use: "delete",
Short: "delete a persona",
Long: `Delete a persona using a secure deletion function.

All content from the persona's folder will be destroyed through this command.

Expand All @@ -43,24 +43,24 @@ further details.
This command loads the current persona from DEVID_ACTIVE_PERSONA environment variable, and this
value takes precedence over the --persona flag.
`,
Run: func(cmd *cobra.Command, args []string) {
p, err := utils.LoadPersona(cmd)
if err != nil {
ui.Fatal(fmt.Errorf("cannot instantiate persona: %w", err), noPersonaLoadedExitCode)
}
Run: func(cmd *cobra.Command, args []string) {
p, err := utils.LoadPersona(cmd)
if err != nil {
ui.Fatal(fmt.Errorf("cannot instantiate persona: %w", err), noPersonaLoadedExitCode)
}

// TODO: ask for confirmation (and add it to command docs)
// TODO: ask for confirmation (and add it to command docs)

shredTimes := 3
shredconf := shred.Conf{Times: shredTimes, Zeros: true, Remove: true}
err = shredconf.Dir(p.Location())
if err != nil {
ui.Fatal(err, genericExitCode)
}
},
}
shredTimes := 3
shredconf := shred.Conf{Times: shredTimes, Zeros: true, Remove: true}
err = shredconf.Dir(p.Location())
if err != nil {
ui.Fatal(err, genericExitCode)
}
},
}

func init() { //nolint:gochecknoinits // required by cobra
deleteCmd.Flags().String("persona", "", "The persona to delete")
rootCmd.AddCommand(deleteCmd)

return deleteCmd
}
40 changes: 20 additions & 20 deletions cmd/edit.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0
http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
Expand All @@ -25,11 +25,11 @@ import (
"github.com/endorama/devid/internal/utils"
)

// editCmd represents the edit command.
var editCmd = &cobra.Command{ //nolint:gochecknoglobals // required by cobra
Use: "edit",
Short: "edit a persona definition file in your $EDITOR",
Long: fmt.Sprintf(`Open within EDITOR the specified persona configuration file.
func Edit() *cobra.Command {
editCmd := &cobra.Command{ //nolint:gochecknoglobals // required by cobra
Use: "edit",
Short: "edit a persona definition file in your $EDITOR",
Long: fmt.Sprintf(`Open within EDITOR the specified persona configuration file.

For security EDITOR variable content is matched against a list of valid editor executable paths.
NOTE however that if some of this commands are not available on your system is still possible to
Expand All @@ -40,20 +40,20 @@ Allowed EDITOR values: %s
This command loads the current persona from DEVID_ACTIVE_PERSONA environment variable, and this
value takes precedence over the --persona flag.
`, utils.AllowedEditors),
Run: func(cmd *cobra.Command, args []string) {
p, err := cmdutils.LoadPersona(cmd)
if err != nil {
ui.Fatal(fmt.Errorf("cannot instantiate persona: %w", err), genericExitCode)
}

err = utils.OpenWithEditor(p.File())
if err != nil {
ui.Fatal(err, genericExitCode)
}
},
}
Run: func(cmd *cobra.Command, args []string) {
p, err := cmdutils.LoadPersona(cmd)
if err != nil {
ui.Fatal(fmt.Errorf("cannot instantiate persona: %w", err), genericExitCode)
}

err = utils.OpenWithEditor(p.File())
if err != nil {
ui.Fatal(err, genericExitCode)
}
},
}

func init() { //nolint:gochecknoinits // required by cobra
editCmd.Flags().String("persona", "", "The persona to backup")
rootCmd.AddCommand(editCmd)

return editCmd
}
40 changes: 20 additions & 20 deletions cmd/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0
http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
Expand All @@ -27,26 +27,26 @@ import (
)

// listCmd represents the list command.
var listCmd = &cobra.Command{ //nolint:gochecknoglobals // required by cobra
Use: "list",
Short: "list personas",
Long: `List all available personas.`,
Run: func(cmd *cobra.Command, args []string) {
files, err := ioutil.ReadDir(viper.GetString("personas_location"))
if err != nil {
ui.Fatal(fmt.Errorf("cannot read folder content: %w", err), noPersonaLoadedExitCode)
}
for _, f := range files {
if f.IsDir() {
p, _ := persona.New(f.Name())
if p.Exists() {
ui.Outputf(p.Name())
func List() *cobra.Command {
listCmd := &cobra.Command{ //nolint:gochecknoglobals // required by cobra
Use: "list",
Short: "list personas",
Long: `List all available personas.`,
Run: func(cmd *cobra.Command, args []string) {
files, err := ioutil.ReadDir(viper.GetString("personas_location"))
if err != nil {
ui.Fatal(fmt.Errorf("cannot read folder content: %w", err), noPersonaLoadedExitCode)
}
for _, f := range files {
if f.IsDir() {
p, _ := persona.New(f.Name())
if p.Exists() {
ui.Outputf(p.Name())
}
}
}
}
},
}
},
}

func init() { //nolint:gochecknoinits // required by cobra
rootCmd.AddCommand(listCmd)
return listCmd
}
24 changes: 12 additions & 12 deletions cmd/new.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0
http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
Expand All @@ -28,26 +28,26 @@ import (
)

// newCmd represents the new command.
var newCmd = &cobra.Command{ //nolint:gochecknoglobals // required by cobra
Use: "new [name]",
Short: "create a persona",
Long: fmt.Sprintf(`Create a new, empty, persona configuration file, opens it within EDITOR.
func New() *cobra.Command {
newCmd := &cobra.Command{ //nolint:gochecknoglobals // required by cobra
Use: "new [name]",
Short: "create a persona",
Long: fmt.Sprintf(`Create a new, empty, persona configuration file, opens it within EDITOR.

For security EDITOR variable content is matched against a list of valid editor executable paths.
NOTE however that if some of this commands are not available on your system is still possible to
trigger an unknown command execution trough this command.

Allowed EDITOR values: %s
`, utils.AllowedEditors),
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
runCommand(args)
},
}
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
runCommand(args)
},
}

func init() { //nolint:gochecknoinits // required by cobra
// add --overwrite to overwrite already existing profile
rootCmd.AddCommand(newCmd)
return newCmd
}

func runCommand(args []string) {
Expand Down
Loading