-
Notifications
You must be signed in to change notification settings - Fork 173
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
Rethink Cobra code structure to remove use of global variables #2773
Comments
I wrote up a similar issue #3183 that ended up being a duplicate. Copying the context over to here, cause there's code links and an example in
|
Describe what should be investigated or refactored
The getting started guide in the Cobra documentations demos the library by using the
init()
function to register the command and configure flags. Which has resulted in a lot of projects following this pattern for their own code. The subsequent examples in the documentation does not use this pattern.Error propagation becomes a large challenge when using functions
init()
as errors cannot be returned and they are magically called when the module is loaded. Additionally testing can become a hassle. This has led to problems like #2756 because there is no easy path to deal with these problems. As the functions are called automatically there is no easy way to pass function parameters, which instead led to using global variables to pass critical information. This includes things like command flags, embedded file systems, and build flags. Using such a pattern creates loose coupling between where the data is set and consumed.My suggestion is that we refactor the CLI code base a bit to remove any use of the
init()
function. This would mean following a pattern similar to what has been suggested in this issue.spf13/cobra#1041 (comment)
To make things clean we could have a single function for each subcommand/package which would then be responsible for calling and configuring commands downstream. This way we could pass any dependencies down from main to the subcommand which needs it.
Links to any relevant code
zarf/main.go
Lines 43 to 44 in 81f1c70
zarf/src/cmd/initialize.go
Lines 179 to 228 in 81f1c70
Additional context
N/A
The text was updated successfully, but these errors were encountered: