spf13 / spf13/cobra

Passing in a common struct from rootCmd and its subcommands

Open
#2,005 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Go
Stars
44.6k
Forks
3.5k
PR merge metrics
No merged PRs in 30d

Description

I have a struct which will contain information about my cloud environments:

type foo struct {
	country     string
	region      string
	project     string
	environment string
}

I will init this root.go and have all the fields for this struct set.

My main issue now is that, I have code in the subcommands like:

rootcmd run --all
or
rootcmd destroy --all

that depend on the information provided by this foo struct. Such as which region I should be running, or which environment I should be destroying. How can I do something like this? Passing information and letting all sub/child commands know about it and use it.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with root.go and the definitions of the run and destroy subcommands to identify how the shared environment information is currently initialized and consumed. Clarify and document the supported approach for making that struct available to child commands, with both example command paths behaving consistently as the definition of done.

Written by the indexing model from the issue text.

Assessment

Tech stack
go
Domain
cli
Issue type
Documentation
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
20/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.