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

Add Command.SetContext #1551

Merged
merged 4 commits into from Mar 18, 2022
Merged

Add Command.SetContext #1551

merged 4 commits into from Mar 18, 2022

Conversation

joshcarp
Copy link
Contributor

@joshcarp joshcarp commented Dec 6, 2021

Basically the same as #1517 but uses the Set<field> naming convention instead of WithContext

Context setting without execution is important because it means that more design patterns can be achieved.

Currently I am using functional options in a project and I can add behaviour through functional options as such:

type GrptlOption func(*cobra.Command) error

func WithFileDescriptors(descriptors ...protoreflect.FileDescriptor) GrptlOption {
	return func(cmd *cobra.Command) error {
		err := CommandFromFileDescriptors(cmd, descriptors...)
		if err != nil {
			return err
		}
		return nil
	}
}

I've got a lot more options and this pattern allows me to have nice abstracted pieces of logic that interact with the cobra command.

This Pattern also allows for adding extra information to a call through PreRun functions:

cmd := &cobra.Command{
		Use: "Foobar",
		PersistentPreRun: func(cmd *cobra.Command, args []string) {
			err :=cmd.SetContext(metadata.AppendToOutgoingContext(context.Background(), "pre", "run"))
		},
	}

This is a veer nice abstraction and allows for these functions to be very modular

The issue I'm facing at the moment is that I can't write a nifty option (something like WithAuthentication) because that needs access to reading and setting the context. Currently I can only read the context.

Needing to use ExecuteContext breaks this abstraction because I need to run it right at the end.

@CLAassistant
Copy link

CLAassistant commented Dec 6, 2021

CLA assistant check
All committers have signed the CLA.

@jpmcb
Copy link
Collaborator

jpmcb commented Dec 8, 2021

Awesome! Thanks for this contribution. I'd love some community feedback as well.

And is it possible you could write some tests for this?

I think this would be great for a v2.0 - will hold till we get some more feedback

@joshcarp
Copy link
Contributor Author

joshcarp commented Dec 8, 2021

Hey, added some tests; the main use cases I see are:

  • Setting context before a run (as an alternative to cmd.ExecuteContext())
    • This would allow packages to add information to the context using functional options for example
  • Setting the context through a PreRun or PersistentPreRun hook

I've put tests for both these cases, also one to ensure that ExecuteContext overwrites any SetContext that was called before

@jackzampolin
Copy link

Would love to see this merged soon. Would make parsing config in PersistentPreRunE and setting the values on context much easier!!

@alexykot
Copy link

alexykot commented Feb 1, 2022

I'd like to have this merged asap as well.

I've started designing my CLI tool and intended to use the context to populate the core data needed by all subcommands, only to find out that there is no legit way right now to update the context after it was passed into the root ExecuteContext() call.

I intend to use it exactly as the second use case above describes - parse and load additional data in the PreRun hook, add it to the context, and pass this enriched context along for all downstream subcommands to use.

It's not possible to do that today, so for now I'll have to do all loading before handing off the execution to cobra. I hope this will be merged quickly and I'll be able to use a more elegant way to load data when appropriate rather than fully upfront.

@marckhouzam
Copy link
Collaborator

@johnSchnake WDYT?

@johnSchnake
Copy link
Collaborator

I like this PR as its so narrowly scoped. Just needs to fix up the golangci-lint issues and I think this should merge.

@joshcarp
Copy link
Contributor Author

joshcarp commented Mar 16, 2022

To respond to the question of "why is this needed?":

Currently to pass around information from pre run hooks a global variable needs to be declared:

func TestFoo(t *testing.T){
	globalVar := "default"
	root := &Command{
		Use: "root",
		PreRun: func(cmd *Command, args []string) {
			globalVar = "not default"
		},
		Run: func(cmd *Command, args []string) {
			fmt.Println(globalVar)
		},
	}
	root.ExecuteContext(context.Background())
}

To avoid using global variables, and to allow for cleaner implementation we can use SetContext instead:

func TestFoo(t *testing.T){
	root := &Command{
		Use: "root",
		PreRun: func(cmd *Command, args []string) {
			ctx := context.WithValue(cmd.Context(), key{}, val)
			cmd.SetContext(ctx)
		},
		Run: func(cmd *Command, args []string) {
			fmt.Println(cmd.Context().Value(key{}))
		},
	}
        ctx := context.WithValue(cmd.Context(), "key", "default")
	root.ExecuteContext(ctx)
}

This greatly simplifies the readability and maintainability of code because everything is stored within the context.Context and no reference to external global variables is made.

I have already simulated this by using a mutable pointer that can be found here: https://github.com/joshcarp/grpctl/blob/main/context.go

I use it to set Authorisation headers which would be a nightmare if I needed to make implementations refer to global variables in my package.

@marckhouzam marckhouzam added kind/feature A feature request for cobra; new or enhanced behavior area/cobra-command Core `cobra.Command` implementations lgtm Denotes "looks good to me" from maintainers and signals other collaboratores that a PR is ready labels Mar 18, 2022
Copy link
Collaborator

@marckhouzam marckhouzam left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

The tests are great and give a good understanding of what will now be possible.

@marckhouzam
Copy link
Collaborator

Based on the fact that @johnSchnake also thinks this is good (#1551 (comment)), I will merge.

@marckhouzam marckhouzam merged commit f848943 into spf13:master Mar 18, 2022
@joshcarp joshcarp deleted the feature/setcontext branch March 18, 2022 10:02
@joshcarp
Copy link
Contributor Author

joshcarp commented Mar 18, 2022

@marckhouzam thanks!
Also I forgot to link the issue so this can be closed now: #563

@marckhouzam
Copy link
Collaborator

@marckhouzam thanks! Also I forgot to link the issue so this can be closed now: #563

Thanks for following up @joshcarp and thanks for this contribution, it seems it will bring some elegance to the usage of Cobra!

aviator-app bot pushed a commit to airplanedev/cli that referenced this pull request Jun 24, 2022
[![Mend Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com)

This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [github.com/golang-jwt/jwt/v4](https://togithub.com/golang-jwt/jwt) | require | patch | `v4.4.1` -> `v4.4.2` |
| [github.com/spf13/cobra](https://togithub.com/spf13/cobra) | require | minor | `v1.4.0` -> `v1.5.0` |
| [github.com/stretchr/testify](https://togithub.com/stretchr/testify) | require | patch | `v1.7.2` -> `v1.7.5` |

---

### Release Notes

<details>
<summary>golang-jwt/jwt</summary>

### [`v4.4.2`](https://togithub.com/golang-jwt/jwt/releases/tag/v4.4.2)

[Compare Source](https://togithub.com/golang-jwt/jwt/compare/v4.4.1...v4.4.2)

#### What's Changed

-   Added MicahParks/keyfunc to extensions by [@&#8203;oxisto](https://togithub.com/oxisto) in [golang-jwt/jwt#194
-   Update link to v4 on pkg.go.dev page by [@&#8203;polRk](https://togithub.com/polRk) in [golang-jwt/jwt#195
-   add installation guidelines to the README file  by [@&#8203;morelmiles](https://togithub.com/morelmiles) in [golang-jwt/jwt#204
-   chore: replace ioutil with io and os by [@&#8203;estensen](https://togithub.com/estensen) in [golang-jwt/jwt#198
-   CI check for Go code formatting by [@&#8203;mfridman](https://togithub.com/mfridman) in [golang-jwt/jwt#206
-   Create SECURITY.md by [@&#8203;mfridman](https://togithub.com/mfridman) in [golang-jwt/jwt#171
-   Update SECURITY.md by [@&#8203;oxisto](https://togithub.com/oxisto) in [golang-jwt/jwt#207
-   Fixed integer overflow in NumericDate.MarshalJSON by [@&#8203;qqiao](https://togithub.com/qqiao) in [golang-jwt/jwt#200
-   Claims in rsa_test.go Table Driven Test are Unused by [@&#8203;gkech](https://togithub.com/gkech) in [golang-jwt/jwt#212

#### New Contributors

-   [@&#8203;polRk](https://togithub.com/polRk) made their first contribution in [golang-jwt/jwt#195
-   [@&#8203;morelmiles](https://togithub.com/morelmiles) made their first contribution in [golang-jwt/jwt#204
-   [@&#8203;estensen](https://togithub.com/estensen) made their first contribution in [golang-jwt/jwt#198
-   [@&#8203;qqiao](https://togithub.com/qqiao) made their first contribution in [golang-jwt/jwt#200
-   [@&#8203;gkech](https://togithub.com/gkech) made their first contribution in [golang-jwt/jwt#212

**Full Changelog**: golang-jwt/jwt@v4.4.1...v4.4.2

</details>

<details>
<summary>spf13/cobra</summary>

### [`v1.5.0`](https://togithub.com/spf13/cobra/releases/tag/v1.5.0)

[Compare Source](https://togithub.com/spf13/cobra/compare/v1.4.0...v1.5.0)

#### Spring 2022 Release 🌥️

Hello everyone! Welcome to another release of cobra. Completions continue to get better and better. This release adds a few really cool new features. We also continue to patch versions of our dependencies as they become available via dependabot. Happy coding!

#### Active help 👐🏼

Shout out to [@&#8203;marckhouzam](https://togithub.com/marckhouzam) for a big value add: Active Help [spf13/cobra#1482. With active help, a program can provide some inline warnings or hints for users as they hit tab. Now, your CLIs can be even more intuitive to use!

Currently active help is only supported for bash V2 and zsh. Marc wrote a whole guide on how to do this, so make sure to give it a good read to learn how you can add this to your cobra code! https://github.com/spf13/cobra/blob/master/active_help.md

#### Group flags 🧑🏼‍🤝‍🧑🏼

Cobra now has the ability to mark flags as required or exclusive as a ***group***. Shout out to our newest maintainer [@&#8203;johnSchnake](https://togithub.com/johnSchnake) for this! [spf13/cobra#1654 Let's say you have a `username` flag that ***MUST*** be partnered with a `password` flag. Well, now, you can enforce those as being required together:

```go
rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)")
rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)")
rootCmd.MarkFlagsRequiredTogether("username", "password")
```

Flags may also be marked as "mutally exclusive" with the `MarkFlagsMutuallyExclusive(string, string ... )` command API. Refer to our [user guide documentation](https://togithub.com/spf13/cobra/blob/master/user_guide.md) for further info!

#### Completions 👀

-   Add backwards-compatibility tests for legacyArgs() by [@&#8203;marckhouzam](https://togithub.com/marckhouzam) in [spf13/cobra#1547
-   feat: Add how to load completions in your current zsh session by [@&#8203;ondrejsika](https://togithub.com/ondrejsika) in [spf13/cobra#1608
-   Introduce FixedCompletions by [@&#8203;emersion](https://togithub.com/emersion) in [spf13/cobra#1574
-   Add shell completion to flag groups by [@&#8203;marckhouzam](https://togithub.com/marckhouzam) in [spf13/cobra#1659
-   Modify brew prefix path in macOS system by [@&#8203;imxw](https://togithub.com/imxw) in [spf13/cobra#1719
-   perf(bash-v2): use backslash escape string expansion for tab by [@&#8203;scop](https://togithub.com/scop) in [spf13/cobra#1682
-   style(bash-v2): out is not an array variable, do not refer to it as such by [@&#8203;scop](https://togithub.com/scop) in [spf13/cobra#1681
-   perf(bash-v2): standard completion optimizations by [@&#8203;scop](https://togithub.com/scop) in [spf13/cobra#1683
-   style(bash): out is not an array variable, do not refer to it as such by [@&#8203;scop](https://togithub.com/scop) in [spf13/cobra#1684
-   perf(bash-v2): short-circuit descriptionless candidate lists by [@&#8203;scop](https://togithub.com/scop) in [spf13/cobra#1686
-   perf(bash-v2): speed up filtering entries with descriptions by [@&#8203;scop](https://togithub.com/scop) in [spf13/cobra#1689
-   perf(bash-v2): speed up filtering menu-complete descriptions by [@&#8203;scop](https://togithub.com/scop) in [spf13/cobra#1692
-   fix(bash-v2): skip empty completions when filtering descriptions by [@&#8203;scop](https://togithub.com/scop) in [spf13/cobra#1691
-   perf(bash-v2): read directly to COMPREPLY on descriptionless short circuit by [@&#8203;scop](https://togithub.com/scop) in [spf13/cobra#1700
-   fix: Don't complete \_command on zsh by [@&#8203;twpayne](https://togithub.com/twpayne) in [spf13/cobra#1690
-   Improve fish_completions code quality by [@&#8203;t29kida](https://togithub.com/t29kida) in [spf13/cobra#1515
-   Fix handling of descriptions for bash v3 by [@&#8203;marckhouzam](https://togithub.com/marckhouzam) in [spf13/cobra#1735
-   undefined or nil Args default to ArbitraryArgs by [@&#8203;umarcor](https://togithub.com/umarcor) in [spf13/cobra#1612
-   Add Command.SetContext by [@&#8203;joshcarp](https://togithub.com/joshcarp) in [spf13/cobra#1551
-   Wrap printf tab with quotes by [@&#8203;PapaCharlie](https://togithub.com/PapaCharlie) in [spf13/cobra#1665

#### Documentation 📝

-   Fixed typos in completions docs - [@&#8203;cuishuang](https://togithub.com/cuishuang) [spf13/cobra#1625
-   Removed `CHANGELOG.md` as it isn't updated - [@&#8203;johnSchnake](https://togithub.com/johnSchnake) [spf13/cobra#1634
-   Minor typo fix in `shell_completion.md` - [@&#8203;danieldn](https://togithub.com/danieldn) [spf13/cobra#1678
-   Changed branch name in the cobra generator link to 'main' - [@&#8203;skywalker2909](https://togithub.com/skywalker2909) [spf13/cobra#1645
-   Fix Command.Context comment by [@&#8203;katexochen](https://togithub.com/katexochen) in [spf13/cobra#1639
-   Change appropriate links from http:// to https:// where applicable - [@&#8203;deining](https://togithub.com/deining) [spf13/cobra#1695

#### Testing & CI ⚙️

-   Test on Golang 1.18 - [@&#8203;umarcor](https://togithub.com/umarcor) [spf13/cobra#1635
-   Use `RICHGO_FORCE_COLOR` - [@&#8203;umarcor](https://togithub.com/umarcor) [spf13/cobra#1647
-   Adds size labeler GitHub action by [@&#8203;jpmcb](https://togithub.com/jpmcb) in [spf13/cobra#1610
-   Update `stale-bot` settings - [@&#8203;jpmcb](https://togithub.com/jpmcb) [spf13/cobra#1609

#### Beep boop, bot commits 🤖

-   Bumped golangci/golangci-lint-action from 3.1.0 to 3.2.0 - [@&#8203;dependabot](https://togithub.com/dependabot) [spf13/cobra#1697
-   Bump codelytv/pr-size-labeler from 1.8.0 to 1.8.1 - [@&#8203;dependabot](https://togithub.com/dependabot) [spf13/cobra#1661
-   Bump actions/stale from 1 to 5 by [@&#8203;dependabot](https://togithub.com/dependabot) in [spf13/cobra#1618
-   Bump actions/cache from 2 to 3 by [@&#8203;dependabot](https://togithub.com/dependabot) in [spf13/cobra#1640
-   Bump actions/labeler from 3 to 4 by [@&#8203;dependabot](https://togithub.com/dependabot) in [spf13/cobra#1620
-   Bump golangci/golangci-lint-action from 2 to 3.1.0 by [@&#8203;dependabot](https://togithub.com/dependabot) in [spf13/cobra#1615
-   Bump actions/checkout from 2 to 3 by [@&#8203;dependabot](https://togithub.com/dependabot) in [spf13/cobra#1619
-   Bump github.com/cpuguy83/go-md2man/v2 from 2.0.1 to 2.0.2 by [@&#8203;dependabot](https://togithub.com/dependabot) in [spf13/cobra#1688
-   Bump actions/setup-go from 2 to 3 by [@&#8203;dependabot](https://togithub.com/dependabot) in [spf13/cobra#1660

#### Misc 💭

-   Use `errors.Is()` to check for errors - [@&#8203;Luap99](https://togithub.com/Luap99) [spf13/cobra#1730
-   Prefer ReplaceAll instead of Replace(..., -1) by [@&#8203;WhyNotHugo](https://togithub.com/WhyNotHugo) in [spf13/cobra#1530
-   Add Kubescape to projects - [@&#8203;avinashupadhya99](https://togithub.com/avinashupadhya99) [spf13/cobra#1642
-   Add Pulumi as a project using cobra by [@&#8203;iwahbe](https://togithub.com/iwahbe) in [spf13/cobra#1720
-   Add Polygon Edge as a project using Cobra by [@&#8203;zivkovicmilos](https://togithub.com/zivkovicmilos) in [spf13/cobra#1672

Shoutout to *ALL* our contributors (and all the new first time contributors!!) - great work everyone!! Cobra and it's huge impact wouldn't be possible without you 👏🏼  🚀  🐍

**Full Changelog**: spf13/cobra@v1.4.0...v1.5.0

</details>

<details>
<summary>stretchr/testify</summary>

### [`v1.7.5`](https://togithub.com/stretchr/testify/compare/v1.7.4...v1.7.5)

[Compare Source](https://togithub.com/stretchr/testify/compare/v1.7.4...v1.7.5)

### [`v1.7.4`](https://togithub.com/stretchr/testify/compare/v1.7.3...v1.7.4)

[Compare Source](https://togithub.com/stretchr/testify/compare/v1.7.3...v1.7.4)

### [`v1.7.3`](https://togithub.com/stretchr/testify/compare/v1.7.2...v1.7.3)

[Compare Source](https://togithub.com/stretchr/testify/compare/v1.7.2...v1.7.3)

</details>

---

### Configuration

📅 **Schedule**: Branch creation - "before 5am on Thursday" in timezone America/New_York, Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

👻 **Immortal**: This PR will be recreated if closed unmerged. Get [config help](https://togithub.com/renovatebot/renovate/discussions) if that's undesired.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, click this checkbox.
gcf-merge-on-green bot pushed a commit to renovate-bot/gapic-showcase that referenced this pull request Jun 27, 2022
…is#1128)

[![Mend Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com)

This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [github.com/spf13/cobra](https://togithub.com/spf13/cobra) | require | minor | `v1.4.0` -> `v1.5.0` |

---

### Release Notes

<details>
<summary>spf13/cobra</summary>

### [`v1.5.0`](https://togithub.com/spf13/cobra/releases/tag/v1.5.0)

[Compare Source](https://togithub.com/spf13/cobra/compare/v1.4.0...v1.5.0)

#### Spring 2022 Release 🌥️

Hello everyone! Welcome to another release of cobra. Completions continue to get better and better. This release adds a few really cool new features. We also continue to patch versions of our dependencies as they become available via dependabot. Happy coding!

#### Active help 👐🏼

Shout out to [@&#8203;marckhouzam](https://togithub.com/marckhouzam) for a big value add: Active Help [spf13/cobra#1482. With active help, a program can provide some inline warnings or hints for users as they hit tab. Now, your CLIs can be even more intuitive to use!

Currently active help is only supported for bash V2 and zsh. Marc wrote a whole guide on how to do this, so make sure to give it a good read to learn how you can add this to your cobra code! https://github.com/spf13/cobra/blob/master/active_help.md

#### Group flags 🧑🏼‍🤝‍🧑🏼

Cobra now has the ability to mark flags as required or exclusive as a ***group***. Shout out to our newest maintainer [@&#8203;johnSchnake](https://togithub.com/johnSchnake) for this! [spf13/cobra#1654 Let's say you have a `username` flag that ***MUST*** be partnered with a `password` flag. Well, now, you can enforce those as being required together:

```go
rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)")
rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)")
rootCmd.MarkFlagsRequiredTogether("username", "password")
```

Flags may also be marked as "mutally exclusive" with the `MarkFlagsMutuallyExclusive(string, string ... )` command API. Refer to our [user guide documentation](https://togithub.com/spf13/cobra/blob/master/user_guide.md) for further info!

#### Completions 👀

-   Add backwards-compatibility tests for legacyArgs() by [@&#8203;marckhouzam](https://togithub.com/marckhouzam) in [spf13/cobra#1547
-   feat: Add how to load completions in your current zsh session by [@&#8203;ondrejsika](https://togithub.com/ondrejsika) in [spf13/cobra#1608
-   Introduce FixedCompletions by [@&#8203;emersion](https://togithub.com/emersion) in [spf13/cobra#1574
-   Add shell completion to flag groups by [@&#8203;marckhouzam](https://togithub.com/marckhouzam) in [spf13/cobra#1659
-   Modify brew prefix path in macOS system by [@&#8203;imxw](https://togithub.com/imxw) in [spf13/cobra#1719
-   perf(bash-v2): use backslash escape string expansion for tab by [@&#8203;scop](https://togithub.com/scop) in [spf13/cobra#1682
-   style(bash-v2): out is not an array variable, do not refer to it as such by [@&#8203;scop](https://togithub.com/scop) in [spf13/cobra#1681
-   perf(bash-v2): standard completion optimizations by [@&#8203;scop](https://togithub.com/scop) in [spf13/cobra#1683
-   style(bash): out is not an array variable, do not refer to it as such by [@&#8203;scop](https://togithub.com/scop) in [spf13/cobra#1684
-   perf(bash-v2): short-circuit descriptionless candidate lists by [@&#8203;scop](https://togithub.com/scop) in [spf13/cobra#1686
-   perf(bash-v2): speed up filtering entries with descriptions by [@&#8203;scop](https://togithub.com/scop) in [spf13/cobra#1689
-   perf(bash-v2): speed up filtering menu-complete descriptions by [@&#8203;scop](https://togithub.com/scop) in [spf13/cobra#1692
-   fix(bash-v2): skip empty completions when filtering descriptions by [@&#8203;scop](https://togithub.com/scop) in [spf13/cobra#1691
-   perf(bash-v2): read directly to COMPREPLY on descriptionless short circuit by [@&#8203;scop](https://togithub.com/scop) in [spf13/cobra#1700
-   fix: Don't complete \_command on zsh by [@&#8203;twpayne](https://togithub.com/twpayne) in [spf13/cobra#1690
-   Improve fish_completions code quality by [@&#8203;t29kida](https://togithub.com/t29kida) in [spf13/cobra#1515
-   Fix handling of descriptions for bash v3 by [@&#8203;marckhouzam](https://togithub.com/marckhouzam) in [spf13/cobra#1735
-   undefined or nil Args default to ArbitraryArgs by [@&#8203;umarcor](https://togithub.com/umarcor) in [spf13/cobra#1612
-   Add Command.SetContext by [@&#8203;joshcarp](https://togithub.com/joshcarp) in [spf13/cobra#1551
-   Wrap printf tab with quotes by [@&#8203;PapaCharlie](https://togithub.com/PapaCharlie) in [spf13/cobra#1665

#### Documentation 📝

-   Fixed typos in completions docs - [@&#8203;cuishuang](https://togithub.com/cuishuang) [spf13/cobra#1625
-   Removed `CHANGELOG.md` as it isn't updated - [@&#8203;johnSchnake](https://togithub.com/johnSchnake) [spf13/cobra#1634
-   Minor typo fix in `shell_completion.md` - [@&#8203;danieldn](https://togithub.com/danieldn) [spf13/cobra#1678
-   Changed branch name in the cobra generator link to 'main' - [@&#8203;skywalker2909](https://togithub.com/skywalker2909) [spf13/cobra#1645
-   Fix Command.Context comment by [@&#8203;katexochen](https://togithub.com/katexochen) in [spf13/cobra#1639
-   Change appropriate links from http:// to https:// where applicable - [@&#8203;deining](https://togithub.com/deining) [spf13/cobra#1695

#### Testing & CI ⚙️

-   Test on Golang 1.18 - [@&#8203;umarcor](https://togithub.com/umarcor) [spf13/cobra#1635
-   Use `RICHGO_FORCE_COLOR` - [@&#8203;umarcor](https://togithub.com/umarcor) [spf13/cobra#1647
-   Adds size labeler GitHub action by [@&#8203;jpmcb](https://togithub.com/jpmcb) in [spf13/cobra#1610
-   Update `stale-bot` settings - [@&#8203;jpmcb](https://togithub.com/jpmcb) [spf13/cobra#1609

#### Beep boop, bot commits 🤖

-   Bumped golangci/golangci-lint-action from 3.1.0 to 3.2.0 - [@&#8203;dependabot](https://togithub.com/dependabot) [spf13/cobra#1697
-   Bump codelytv/pr-size-labeler from 1.8.0 to 1.8.1 - [@&#8203;dependabot](https://togithub.com/dependabot) [spf13/cobra#1661
-   Bump actions/stale from 1 to 5 by [@&#8203;dependabot](https://togithub.com/dependabot) in [spf13/cobra#1618
-   Bump actions/cache from 2 to 3 by [@&#8203;dependabot](https://togithub.com/dependabot) in [spf13/cobra#1640
-   Bump actions/labeler from 3 to 4 by [@&#8203;dependabot](https://togithub.com/dependabot) in [spf13/cobra#1620
-   Bump golangci/golangci-lint-action from 2 to 3.1.0 by [@&#8203;dependabot](https://togithub.com/dependabot) in [spf13/cobra#1615
-   Bump actions/checkout from 2 to 3 by [@&#8203;dependabot](https://togithub.com/dependabot) in [spf13/cobra#1619
-   Bump github.com/cpuguy83/go-md2man/v2 from 2.0.1 to 2.0.2 by [@&#8203;dependabot](https://togithub.com/dependabot) in [spf13/cobra#1688
-   Bump actions/setup-go from 2 to 3 by [@&#8203;dependabot](https://togithub.com/dependabot) in [spf13/cobra#1660

#### Misc 💭

-   Use `errors.Is()` to check for errors - [@&#8203;Luap99](https://togithub.com/Luap99) [spf13/cobra#1730
-   Prefer ReplaceAll instead of Replace(..., -1) by [@&#8203;WhyNotHugo](https://togithub.com/WhyNotHugo) in [spf13/cobra#1530
-   Add Kubescape to projects - [@&#8203;avinashupadhya99](https://togithub.com/avinashupadhya99) [spf13/cobra#1642
-   Add Pulumi as a project using cobra by [@&#8203;iwahbe](https://togithub.com/iwahbe) in [spf13/cobra#1720
-   Add Polygon Edge as a project using Cobra by [@&#8203;zivkovicmilos](https://togithub.com/zivkovicmilos) in [spf13/cobra#1672

Shoutout to *ALL* our contributors (and all the new first time contributors!!) - great work everyone!! Cobra and it's huge impact wouldn't be possible without you 👏🏼  🚀  🐍

**Full Changelog**: spf13/cobra@v1.4.0...v1.5.0

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, click this checkbox.

---

This PR has been generated by [Mend Renovate](https://www.mend.io/free-developer-tools/renovate/). View repository job log [here](https://app.renovatebot.com/dashboard#github/googleapis/gapic-showcase).
hoshsadiq pushed a commit to zulucmd/zulu that referenced this pull request Dec 31, 2022
Basically the same as spf13/cobra#1517 but
uses the `Set<field>` naming convention instead of `WithContext`

Context setting without execution is important because it means
that more design patterns can be achieved.

Currently I am using functional options in a project and I can add
behaviour through functional options as such:
```go
type GrptlOption func(*cobra.Command) error

func WithFileDescriptors(descriptors ...protoreflect.FileDescriptor) GrptlOption {
	return func(cmd *cobra.Command) error {
		err := CommandFromFileDescriptors(cmd, descriptors...)
		if err != nil {
			return err
		}
		return nil
	}
}
```

I've got a lot more options and this pattern allows me to have nice
abstracted pieces of logic that interact with the cobra command.

This Pattern also allows for adding extra information to a call
through `PreRun` functions:

```go

cmd := &cobra.Command{
		Use: "Foobar",
		PersistentPreRun: func(cmd *cobra.Command, args []string) {
			err :=cmd.SetContext(metadata.AppendToOutgoingContext(context.Background(), "pre", "run"))
		},
	}
```

This is a veer nice abstraction and allows for these functions to be
very modular

The issue I'm facing at the moment is that I can't write a nifty
option (something like `WithAuthentication`) because that needs access
to reading and setting the context. Currently I can only read the
context.

Needing to use `ExecuteContext` breaks this abstraction because I need
to run it right at the end.

Merge spf13/cobra#1551

Fixes spf13/cobra#1517
Fixes spf13/cobra#1118
Fixes spf13/cobra#563
@ashleydavies
Copy link

ashleydavies commented Jul 5, 2023

Sorry, this isn't related to this PR directly, so I worry it's an undesirable comment, but hopefully you don't mind too much..!

I really wanted to say that the way y'all manage milestones in this repository (I can see above: "@marckhouzam added this to the 1.5.0 milestone") is tremendously helpful and appreciated. I'm so used to digging into tags and digging around for a commit hash, figuring out what version I needed for this feature was so refreshing.

Little things like that make it so much easier to consume a project, and I imagine sometimes must feel like toil or busywork, so wanted to just say it's really helpful 😄 thank you all!

edit: Also, of course, I'm here because this contribution helped me - thanks @joshcarp! 😄

@marckhouzam
Copy link
Collaborator

Well, we never mind such kind comments ❤️
Thanks @ashleydavies !
Credit goes to @jpmcb for setting things up and to @umarcor for keeping use disciplined 👏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area/cobra-command Core `cobra.Command` implementations kind/feature A feature request for cobra; new or enhanced behavior lgtm Denotes "looks good to me" from maintainers and signals other collaboratores that a PR is ready
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

8 participants