Your contribution is welcome! Thank you for your interest in contributing to the STACKIT CLI. We greatly value your feedback, feature requests, additions to the code, bug reports or documentation extensions.
- Developer Guide
- Useful Make commands
- Repository structure
- Implementing a new command
- Onboarding a new STACKIT service
- Local development
- Code Contributions
- Bug Reports
Prerequisites:
These commands can be executed from the project root:
make project-tools
: install the required dependenciesmake build
: compile the CLI and save the binary under ./bin/stackitmake lint
: lint the codemake generate-docs
: generate Markdown documentation for every commandmake test
: run unit tests
The CLI commands are located under internal/cmd
, where each folder includes the source code for each subcommand (including their own subcommands). Inside pkg
you can find several useful packages that are shared by the commands and provide additional functionality such as flags
, globalflags
, tables
, etc.
Let's suppose you want to implement a new command bar
, that would be the direct child of an existing command stackit foo
(meaning it would be invoked as stackit foo bar
):
- You would start by creating a new folder
bar/
insideinternal/cmd/foo/
- Following with the creation of a file
bar.go
inside your new folderinternal/cmd/foo/bar/
- The Go package should be similar to the command usage, in this case
package bar
would be an adequate name - Please refer to the Command file structure section for details on the structure of the file itself
- The Go package should be similar to the command usage, in this case
- To register the command
bar
as a child of the existing commandfoo
, addcmd.AddCommand(bar.NewCmd(p))
to theaddSubcommands
method of the constructor of thefoo
command- In this case,
p
is theprinter
that is passed from the root command to all subcommands of the tree (refer to the Outputs, prints and debug logs section for more details regarding theprinter
)
- In this case,
Please remember to run make generate-docs
after your changes to keep the commands' documentation updated.
Below is a typical structure of a CLI command:
package bar
import (
(...)
)
// Define consts for command flags
const (
someArg = "MY_ARG"
someFlag = "my-flag"
)
// Struct to model user input (arguments and/or flags)
type inputModel struct {
*globalflags.GlobalFlagModel
MyArg string
MyFlag *string
}
// "bar" command constructor
func NewCmd(p *print.Printer) *cobra.Command {
cmd := &cobra.Command{
Use: "bar",
Short: "Short description of the command (is shown in the help of parent command)",
Long: "Long description of the command. Can contain some more information about the command usage. It is shown in the help of the current command.",
Args: args.SingleArg(someArg, utils.ValidateUUID), // Validate argument, with an optional validation function
Example: examples.Build(
examples.NewExample(
`Do something with command "bar"`,
"$ stackit foo bar arg-value --my-flag flag-value"),
...
),
RunE: func(cmd *cobra.Command, args []string) error {
ctx := context.Background()
model, err := parseInput(p, cmd, args)
if err != nil {
return err
}
// Configure API client
apiClient, err := client.ConfigureClient(p, cmd)
if err != nil {
return err
}
// Call API
req := buildRequest(ctx, model, apiClient)
resp, err := req.Execute()
if err != nil {
return fmt.Errorf("(...): %w", err)
}
projectLabel, err := projectname.GetProjectName(ctx, p, cmd)
if err != nil {
projectLabel = model.ProjectId
}
// Check API response "resp" and output accordingly
if resp.Item == nil {
p.Info("(...)", projectLabel)
return nil
}
return outputResult(p, cmd, model.OutputFormat, instances)
},
}
configureFlags(cmd)
return cmd
}
// Configure command flags (type, default value, and description)
func configureFlags(cmd *cobra.Command) {
cmd.Flags().StringP(myFlag, "defaultValue", "My flag description")
}
// Parse user input (arguments and/or flags)
func parseInput(cmd *cobra.Command, inputArgs []string) (*inputModel, error) {
myArg := inputArgs[0]
globalFlags := globalflags.Parse(cmd)
if globalFlags.ProjectId == "" {
return nil, &errors.ProjectIdError{}
}
model := inputModel{
GlobalFlagModel: globalFlags,
MyArg myArg,
MyFlag: flags.FlagToStringPointer(cmd, myFlag),
}, nil
// Write the input model to the debug logs
if p.IsVerbosityDebug() {
modelStr, err := print.BuildDebugStrFromInputModel(model)
if err != nil {
p.Debug(print.ErrorLevel, "convert model to string for debugging: %v", err)
} else {
p.Debug(print.DebugLevel, "parsed input values: %s", modelStr)
}
}
return &model, nil
}
// Build request to the API
func buildRequest(ctx context.Context, model *inputModel, apiClient *foo.APIClient) foo.ApiListInstancesRequest {
req := apiClient.GetBar(ctx, model.ProjectId, model.MyArg, someParam)
return req
}
// Output result based on the configured output format
func outputResult(p *print.Printer, cmd *cobra.Command, outputFormat string, resources []foo.Resource) error {
switch outputFormat {
case print.JSONOutputFormat:
details, err := json.MarshalIndent(resources, "", " ")
if err != nil {
return fmt.Errorf("marshal resource list: %w", err)
}
p.Outputln(string(details))
return nil
case print.YAMLOutputFormat:
details, err := yaml.Marshal(resources)
if err != nil {
return fmt.Errorf("marshal resource list: %w", err)
}
p.Outputln(string(details))
return nil
default:
table := tables.NewTable()
table.SetHeader("ID", "NAME", "STATE")
for i := range resources {
resource := resources[i]
table.AddRow(*resource.ResourceId, *resource.Name, *resource.State)
}
err := table.Display(cmd)
if err != nil {
return fmt.Errorf("render table: %w", err)
}
return nil
}
}
Please remember to always add unit tests for parseInput
, buildRequest
(in bar_test.go
), and any other util functions used.
If the new command bar
is the first command in the CLI using a STACKIT service foo
, please refer to Onboarding a new STACKIT service.
The CLI has 4 different verbosity levels:
error
: For only displaying errorswarning
: For displaying user facing warnings (and all of the above)info
(default): For displaying user facing info, such as operation success messages and spinners (and all of the above)debug
: For displaying structured logs with different levels, including errors (and all of the above)
For prints that are specific to a certain log level, you can use the methods defined in the print
package: Error
, Warn
, Info
, and Debug
.
For command outputs that should always be displayed, no matter the defined verbosity, you should use the print
methods Outputf
and Outputln
. These should only be used for the actual output of the commands, which can usually be described by "I ran the command to see this".
If you want to add a command that uses a STACKIT service foo
that was not yet used by the CLI, you will first need to implement a few extra steps to configure the new service:
-
Add a
FooCustomEndpointKey
key ininternal/pkg/config/config.go
(and add it toConfigKeys
and set the to default to""
usingviper.SetDefault
) -
Update the
stackit config unset
andstackit config unset
commands by adding flags to set and unset a custom endpoint for thefoo
service API, respectively, and update their unit tests -
Set up the SDK client configuration, using the authentication method configured in the CLI
-
This is done in
internal/pkg/services/foo/client/client.go
-
Below is an example of a typical
client.go
file structure:package client import ( (...) "github.com/stackitcloud/stackit-sdk-go/services/foo" ) func ConfigureClient(cmd *cobra.Command) (*foo.APIClient, error) { var err error var apiClient foo.APIClient var cfgOptions []sdkConfig.ConfigurationOption authCfgOption, err := auth.AuthenticationConfig(cmd, auth.AuthorizeUser) if err != nil { return nil, &errors.AuthError{} } cfgOptions = append(cfgOptions, authCfgOption, sdkConfig.WithRegion("eu01")) // Configuring region is needed if "foo" is a regional API customEndpoint := viper.GetString(config.fooCustomEndpointKey) if customEndpoint != "" { cfgOptions = append(cfgOptions, sdkConfig.WithEndpoint(customEndpoint)) } apiClient, err = foo.NewAPIClient(cfgOptions...) if err != nil { return nil, &errors.AuthError{} } return apiClient, nil }
-
To test your changes, you can either:
-
Build the application locally by running:
$ go build -o ./bin/stackit
To use the application from the root of the repository, you can run:
$ ./bin/stackit [group] [subgroup] [command] [flags]
-
Skip building and run the Go application directly using:
$ go run . [group] [subgroup] [command] [flags]
To make your contribution, follow these steps:
- Check open or recently closed Pull Requests and Issues to make sure the contribution you are making has not been already tackled by someone else.
- Fork the repo.
- Make your changes in a branch that is up-to-date with the original repo's
main
branch. - Commit your changes including a descriptive message
- Create a pull request with your changes.
- The pull request will be reviewed by the repo maintainers. If you need to make further changes, make additional commits to keep commit history. When the PR is merged, commits will be squashed.
If you would like to report a bug, please open a GitHub issue.
To ensure we can provide the best support to your issue, follow these guidelines:
- Go through the existing issues to check if your issue has already been reported.
- Make sure you are using the latest version of the STACKIT CLI, we will not provide bug fixes for older versions. Also, latest versions may have the fix for your bug.
- Please provide as much information as you can about your environment, e.g. your version of Go, your version of the CLI, which operating system you are using and the corresponding version.
- Include in your issue the steps to reproduce it, along with code snippets and/or information about your specific use case. This will make the support process much easier and efficient.