Skip to content

Migration Guide Command Restructuring

Eric Klatzer edited this page Jan 17, 2025 · 1 revision

Migration Guide Command Restructuring

With the recent update to the project structure, we've organized subcommands into dedicated subfolders to improve organization and maintainability. This change affects how you should manage your custom subcommands. Please follow the steps below to migrate your custom subcommands to the new structure.

⚠️ Changes to the sub-commands server (serverCmd), probe (probeCmd), env (envCmd) and db (dbCmd) and the related sub-commands must be migrated to the new schema, as the existing variable of the command is no longer present in the package cmd.

Overview of the new structure

├── db
│   ├── db.go
│   ├── migrate.go
│   └── seed.go
├── env
│   └── env.go
├── probe
│   ├── liveness.go
│   ├── probe.go
│   └── readiness.go
├── README.md
├── root.go
└── server
    └── server.go

Migration Steps

  1. Locate your custom subcommands: Identify which custom subcommands you've attached to any of the original commands (server (serverCmd), probe (probeCmd), env (envCmd) and db (dbCmd)). Other commands can optionally be migrated, but it is not mandatory.

  2. Move the subcommands to the appropriate sub-directory: Subcommands need to be moved to the dedicated package. For example subcommands related to database operations should be moved to the /db directory and placed in an appropriate file such as migrate.go or seed.go.

  3. Refactor the setup of the command: Replace the existing variable for the &cobra.Command and the func init() setting up the command by a new func new...() *cobra.Command returning the command as shown in the following example:

Existing func init():

var livenessCmd = &cobra.Command{
	Use:   "liveness",
	Short: "Runs liveness probes",
	Run: func(cmd *cobra.Command, _ []string /* args */) {

		verbose, err := cmd.Flags().GetBool(verboseFlag)
		if err != nil {
			log.Fatal().Err(err).Msg("Failed to parse args")
		}
		runLiveness(verbose)
	},
}

func init() {
	probeCmd.AddCommand(livenessCmd)
	livenessCmd.Flags().BoolP(verboseFlag, "v", false, "Show verbose output.")
}

Replaced by:

type LivenessFlags struct {
	Verbose bool
}

func newLiveness() *cobra.Command {
	var flags LivenessFlags

	cmd := &cobra.Command{
		Use:   "liveness",
		Short: "Runs liveness probes",
		Run: func(_ *cobra.Command, _ []string) {
			livenessCmdFunc(flags)
		},
	}

	cmd.Flags().BoolVarP(&flags.Verbose, verboseFlag, "v", false, "Show verbose output.")

	return cmd
}
  1. Attach the command to the parent-command: Use the created func new...() *cobra.Command in the setup of the parent command. For example for adding a sub-command to probe go to the probe.go and add your newly created setup func to the setup of the command:
cmd.AddCommand(
  newLiveness(),
  newReadiness(),
  # add your setup func here
)