├── .github ├── dependabot.yml └── workflows │ └── test.yml ├── .gitignore ├── LICENSE ├── README.md ├── example └── main.go ├── go.mod ├── go.sum ├── shell.go └── shell_test.go /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "gomod" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "weekly" 12 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | jobs: 10 | build: 11 | runs-on: ${{ matrix.os }} 12 | strategy: 13 | matrix: 14 | os: [macos-latest, ubuntu-latest, windows-latest] 15 | steps: 16 | - uses: actions/checkout@v2 17 | 18 | - uses: actions/setup-go@v2 19 | with: 20 | go-version: 1.24 21 | 22 | - name: Build 23 | run: go build 24 | 25 | - name: Test 26 | run: go test -v ./... 27 | 28 | lint: 29 | runs-on: ubuntu-latest 30 | steps: 31 | - uses: actions/checkout@v2 32 | 33 | - uses: actions/setup-go@v2 34 | with: 35 | go-version: 1.24 36 | 37 | - uses: golangci/golangci-lint-action@v2.5.2 38 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cobra-shell 2 | 3 | ![logo](https://cobra.dev/home/logo.png) 4 | 5 | ## Description 6 | 7 | Leverages the Cobra completion API to generate an interactive shell for any [Cobra](https://github.com/spf13/cobra) CLI, powered by [go-prompt](https://github.com/c-bata/go-prompt). 8 | 9 | * On-the-fly autocompletion for all commands 10 | * Static and dynamic autocompletion for args and flags, as described [here](https://github.com/spf13/cobra/blob/master/shell_completions.md) 11 | * Full prompt customizability 12 | 13 | ## Usage 14 | 15 | 16 | 17 | ## Download 18 | 19 | ``` 20 | go get github.com/brianstrauch/cobra-shell 21 | ``` 22 | 23 | ## Example 24 | 25 | ``` 26 | package main 27 | 28 | import ( 29 | shell "github.com/brianstrauch/cobra-shell" 30 | "github.com/spf13/cobra" 31 | ) 32 | 33 | func main() { 34 | cmd := &cobra.Command{Use: "example"} 35 | cmd.AddCommand(shell.New()) 36 | _ = cmd.Execute() 37 | } 38 | ``` 39 | -------------------------------------------------------------------------------- /example/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | shell "github.com/brianstrauch/cobra-shell" 5 | 6 | "github.com/spf13/cobra" 7 | ) 8 | 9 | func main() { 10 | cmd := &cobra.Command{Use: "example"} 11 | 12 | subcommand := &cobra.Command{ 13 | Use: "subcommand", 14 | Short: "A subcommand.", 15 | ValidArgs: []string{"a", "b", "c"}, 16 | Run: func(_ *cobra.Command, _ []string) {}, 17 | } 18 | 19 | subcommand.Flags().String("flag", "", "A flag.") 20 | _ = subcommand.RegisterFlagCompletionFunc("flag", func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) { 21 | return []string{"a", "b", "c"}, cobra.ShellCompDirectiveNoFileComp 22 | }) 23 | 24 | cmd.AddCommand(subcommand) 25 | cmd.AddCommand(shell.New(cmd, nil)) 26 | 27 | _ = cmd.Execute() 28 | } 29 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/brianstrauch/cobra-shell 2 | 3 | go 1.24 4 | 5 | require ( 6 | github.com/c-bata/go-prompt v0.2.6 7 | github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 8 | github.com/spf13/cobra v1.9.1 9 | github.com/spf13/pflag v1.0.6 10 | github.com/stretchr/testify v1.10.0 11 | golang.org/x/term v0.32.0 12 | ) 13 | 14 | require ( 15 | github.com/davecgh/go-spew v1.1.1 // indirect 16 | github.com/inconshreveable/mousetrap v1.1.0 // indirect 17 | github.com/mattn/go-colorable v0.1.7 // indirect 18 | github.com/mattn/go-isatty v0.0.12 // indirect 19 | github.com/mattn/go-runewidth v0.0.9 // indirect 20 | github.com/mattn/go-tty v0.0.3 // indirect 21 | github.com/pkg/term v1.2.0-beta.2 // indirect 22 | github.com/pmezard/go-difflib v1.0.0 // indirect 23 | golang.org/x/sys v0.33.0 // indirect 24 | gopkg.in/yaml.v3 v3.0.1 // indirect 25 | ) 26 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/c-bata/go-prompt v0.2.6 h1:POP+nrHE+DfLYx370bedwNhsqmpCUynWPxuHi0C5vZI= 2 | github.com/c-bata/go-prompt v0.2.6/go.mod h1:/LMAke8wD2FsNu9EXNdHxNLbd9MedkPnCdfpU9wwHfY= 3 | github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= 4 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 5 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 6 | github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= 7 | github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= 8 | github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= 9 | github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= 10 | github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= 11 | github.com/mattn/go-colorable v0.1.7 h1:bQGKb3vps/j0E9GfJQ03JyhRuxsvdAanXlT9BTw3mdw= 12 | github.com/mattn/go-colorable v0.1.7/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= 13 | github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= 14 | github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84= 15 | github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= 16 | github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= 17 | github.com/mattn/go-runewidth v0.0.6/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= 18 | github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0= 19 | github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= 20 | github.com/mattn/go-tty v0.0.3 h1:5OfyWorkyO7xP52Mq7tB36ajHDG5OHrmBGIS/DtakQI= 21 | github.com/mattn/go-tty v0.0.3/go.mod h1:ihxohKRERHTVzN+aSVRwACLCeqIoZAWpoICkkvrWyR0= 22 | github.com/pkg/term v1.2.0-beta.2 h1:L3y/h2jkuBVFdWiJvNfYfKmzcCnILw7mJWm2JQuMppw= 23 | github.com/pkg/term v1.2.0-beta.2/go.mod h1:E25nymQcrSllhX42Ok8MRm1+hyBdHY0dCeiKZ9jpNGw= 24 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 25 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 26 | github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= 27 | github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo= 28 | github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0= 29 | github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= 30 | github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= 31 | github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= 32 | github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 33 | golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 34 | golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 35 | golang.org/x/sys v0.0.0-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 36 | golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 37 | golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 38 | golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 39 | golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 40 | golang.org/x/sys v0.0.0-20200918174421-af09f7315aff/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 41 | golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw= 42 | golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= 43 | golang.org/x/term v0.32.0 h1:DR4lr0TjUs3epypdhTOkMmuF5CDFJ/8pOnbzMZPQ7bg= 44 | golang.org/x/term v0.32.0/go.mod h1:uZG1FhGx848Sqfsq4/DlJr3xGGsYMu/L5GW4abiaEPQ= 45 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 46 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 47 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 48 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 49 | -------------------------------------------------------------------------------- /shell.go: -------------------------------------------------------------------------------- 1 | package cobrashell 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "os" 7 | "sort" 8 | "strings" 9 | 10 | "github.com/c-bata/go-prompt" 11 | "github.com/google/shlex" 12 | "github.com/spf13/cobra" 13 | "github.com/spf13/pflag" 14 | "golang.org/x/term" 15 | ) 16 | 17 | type cobraShell struct { 18 | root *cobra.Command 19 | refresh func() *cobra.Command 20 | cache map[string][]prompt.Suggest 21 | stdin *term.State 22 | } 23 | 24 | // New creates a Cobra CLI command named "shell" which runs an interactive shell prompt for the root command. 25 | func New(root *cobra.Command, refresh func() *cobra.Command, opts ...prompt.Option) *cobra.Command { 26 | shell := &cobraShell{ 27 | root: root, 28 | refresh: refresh, 29 | cache: make(map[string][]prompt.Suggest), 30 | } 31 | 32 | prefix := fmt.Sprintf("> %s ", root.Name()) 33 | opts = append(opts, prompt.OptionPrefix(prefix), prompt.OptionShowCompletionAtStart()) 34 | 35 | return &cobra.Command{ 36 | Use: "shell", 37 | Short: "Start an interactive shell.", 38 | Run: func(cmd *cobra.Command, _ []string) { 39 | shell.saveStdin() 40 | 41 | shell.editCommandTree(cmd) 42 | prompt.New(shell.executor, shell.completer, opts...).Run() 43 | 44 | shell.restoreStdin() 45 | }, 46 | } 47 | } 48 | 49 | func (s *cobraShell) editCommandTree(shell *cobra.Command) { 50 | s.root.RemoveCommand(shell) 51 | 52 | // Hide the "completion" command 53 | if cmd, _, err := s.root.Find([]string{"completion"}); err == nil { 54 | // TODO: Remove this command 55 | cmd.Hidden = true 56 | } 57 | 58 | s.root.AddCommand(&cobra.Command{ 59 | Use: "exit", 60 | Short: "Exit the interactive shell.", 61 | Run: func(*cobra.Command, []string) { 62 | // TODO: Exit cleanly without help from the os package 63 | os.Exit(0) 64 | }, 65 | }) 66 | 67 | initDefaultHelpFlag(s.root) 68 | } 69 | 70 | func initDefaultHelpFlag(cmd *cobra.Command) { 71 | cmd.InitDefaultHelpFlag() 72 | 73 | for _, subcommand := range cmd.Commands() { 74 | initDefaultHelpFlag(subcommand) 75 | } 76 | } 77 | 78 | func (s *cobraShell) saveStdin() { 79 | state, err := term.GetState(int(os.Stdin.Fd())) 80 | if err != nil { 81 | return 82 | } 83 | s.stdin = state 84 | } 85 | 86 | func (s *cobraShell) executor(line string) { 87 | // Allow command to read from stdin 88 | s.restoreStdin() 89 | 90 | args, _ := shlex.Split(line) 91 | _ = execute(s.root, args) 92 | 93 | if s.refresh != nil { 94 | s.root = s.refresh() 95 | s.editCommandTree(s.root) 96 | } else { 97 | if cmd, _, err := s.root.Find(args); err == nil { 98 | cmd.Flags().VisitAll(func(flag *pflag.Flag) { 99 | flag.Changed = false 100 | }) 101 | } 102 | } 103 | 104 | s.cache = make(map[string][]prompt.Suggest) 105 | } 106 | 107 | func (s *cobraShell) restoreStdin() { 108 | if s.stdin != nil { 109 | _ = term.Restore(int(os.Stdin.Fd()), s.stdin) 110 | } 111 | } 112 | 113 | func (s *cobraShell) completer(d prompt.Document) []prompt.Suggest { 114 | args, err := buildCompletionArgs(d.CurrentLine()) 115 | if err != nil { 116 | return nil 117 | } 118 | 119 | if !isFlag(args[len(args)-1]) { 120 | // Clear partial strings to generate all possible completions 121 | args[len(args)-1] = "" 122 | } 123 | key := strings.Join(args, " ") 124 | 125 | suggestions, ok := s.cache[key] 126 | if !ok { 127 | out, err := readCommandOutput(s.root, args) 128 | if err != nil { 129 | return nil 130 | } 131 | suggestions = parseSuggestions(out) 132 | s.cache[key] = suggestions 133 | } 134 | 135 | return prompt.FilterHasPrefix(suggestions, d.GetWordBeforeCursor(), true) 136 | } 137 | 138 | func buildCompletionArgs(input string) ([]string, error) { 139 | args, err := shlex.Split(input) 140 | 141 | args = append([]string{"__complete"}, args...) 142 | if input == "" || input[len(input)-1] == ' ' { 143 | args = append(args, "") 144 | } 145 | 146 | return args, err 147 | } 148 | 149 | func readCommandOutput(cmd *cobra.Command, args []string) (string, error) { 150 | buf := new(bytes.Buffer) 151 | 152 | stdout := cmd.OutOrStdout() 153 | stderr := os.Stderr 154 | 155 | cmd.SetOut(buf) 156 | _, os.Stderr, _ = os.Pipe() 157 | 158 | err := execute(cmd, args) 159 | 160 | cmd.SetOut(stdout) 161 | os.Stderr = stderr 162 | 163 | return buf.String(), err 164 | } 165 | 166 | func execute(cmd *cobra.Command, args []string) error { 167 | if cmd, _, err := cmd.Find(args); err == nil { 168 | // Reset flag values between runs due to a limitation in Cobra 169 | cmd.Flags().VisitAll(func(flag *pflag.Flag) { 170 | if val, ok := flag.Value.(pflag.SliceValue); ok { 171 | _ = val.Replace([]string{}) 172 | } else { 173 | _ = flag.Value.Set(flag.DefValue) 174 | } 175 | 176 | _ = cmd.Flags().SetAnnotation(flag.Name, cobra.BashCompOneRequiredFlag, []string{"false"}) 177 | }) 178 | 179 | cmd.InitDefaultHelpFlag() 180 | } 181 | 182 | cmd.SetArgs(args) 183 | return cmd.Execute() 184 | } 185 | 186 | func parseSuggestions(out string) []prompt.Suggest { 187 | var suggestions []prompt.Suggest 188 | 189 | x := strings.Split(out, "\n") 190 | if len(x) < 2 { 191 | return nil 192 | } 193 | 194 | for _, line := range x[:len(x)-2] { 195 | x := strings.SplitN(line, "\t", 2) 196 | 197 | if isShorthandFlag(x[0]) { 198 | continue 199 | } 200 | 201 | suggestion := prompt.Suggest{Text: escapeSpecialCharacters(x[0])} 202 | if len(x) > 1 { 203 | suggestion.Description = x[1] 204 | } 205 | 206 | suggestions = append(suggestions, suggestion) 207 | } 208 | 209 | sort.Slice(suggestions, func(i, j int) bool { 210 | it := suggestions[i].Text 211 | jt := suggestions[j].Text 212 | 213 | if isFlag(it) && isFlag(jt) { 214 | return it < jt 215 | } 216 | 217 | if isFlag(it) { 218 | return false 219 | } 220 | 221 | if isFlag(jt) { 222 | return true 223 | } 224 | 225 | return it < jt 226 | }) 227 | 228 | return suggestions 229 | } 230 | 231 | func escapeSpecialCharacters(val string) string { 232 | for _, c := range []string{`\`, `"`, "$", "`", "!"} { 233 | val = strings.ReplaceAll(val, c, `\`+c) 234 | } 235 | 236 | if strings.ContainsAny(val, " #&*;<>?[]|~") { 237 | val = fmt.Sprintf(`"%s"`, val) 238 | } 239 | 240 | return val 241 | } 242 | 243 | func isFlag(arg string) bool { 244 | return strings.HasPrefix(arg, "-") 245 | } 246 | 247 | func isShorthandFlag(arg string) bool { 248 | return isFlag(arg) && !strings.HasPrefix(arg, "--") 249 | } 250 | -------------------------------------------------------------------------------- /shell_test.go: -------------------------------------------------------------------------------- 1 | package cobrashell 2 | 3 | import ( 4 | "errors" 5 | "testing" 6 | 7 | "github.com/c-bata/go-prompt" 8 | "github.com/spf13/cobra" 9 | "github.com/stretchr/testify/require" 10 | ) 11 | 12 | func TestBuildCompletionArgs_Empty(t *testing.T) { 13 | args, err := buildCompletionArgs("") 14 | require.NoError(t, err) 15 | 16 | expected := []string{"__complete", ""} 17 | require.Equal(t, expected, args) 18 | } 19 | 20 | func TestBuildCompletionArgs_CurrentArg(t *testing.T) { 21 | args, err := buildCompletionArgs("a b") 22 | require.NoError(t, err) 23 | 24 | expected := []string{"__complete", "a", "b"} 25 | require.Equal(t, expected, args) 26 | } 27 | 28 | func TestBuildCompletionArgs_MultiwordString(t *testing.T) { 29 | args, err := buildCompletionArgs(`a "b c"`) 30 | require.NoError(t, err) 31 | 32 | expected := []string{"__complete", "a", "b c"} 33 | require.Equal(t, expected, args) 34 | } 35 | 36 | func TestBuildCompletionArgs_NextArg(t *testing.T) { 37 | args, err := buildCompletionArgs("a b ") 38 | require.NoError(t, err) 39 | 40 | expected := []string{"__complete", "a", "b", ""} 41 | require.Equal(t, expected, args) 42 | } 43 | 44 | func TestReadCommandOutput_Stdout(t *testing.T) { 45 | cmd := &cobra.Command{ 46 | Use: "command", 47 | Run: func(cmd *cobra.Command, args []string) { 48 | cmd.Print("out") 49 | }, 50 | } 51 | 52 | out, err := readCommandOutput(cmd, []string{}) 53 | require.NoError(t, err) 54 | require.Equal(t, "out", out) 55 | } 56 | 57 | func TestReadCommandOutput_Stderr(t *testing.T) { 58 | cmd := &cobra.Command{ 59 | Use: "command", 60 | Run: func(cmd *cobra.Command, args []string) { 61 | cmd.PrintErr("out") 62 | }, 63 | } 64 | 65 | out, err := readCommandOutput(cmd, []string{}) 66 | require.NoError(t, err) 67 | require.Empty(t, out) 68 | } 69 | 70 | func TestReadCommandOutput_Err(t *testing.T) { 71 | cmd := &cobra.Command{ 72 | Use: "command", 73 | RunE: func(cmd *cobra.Command, args []string) error { 74 | return errors.New("err") 75 | }, 76 | } 77 | 78 | _, err := readCommandOutput(cmd, []string{}) 79 | require.Error(t, err) 80 | } 81 | 82 | func TestParseSuggestions_WithDescription(t *testing.T) { 83 | out := `command-with-description description 84 | :4 85 | Completion ended with directive: ShellCompDirectiveNoFileComp` 86 | expected := []prompt.Suggest{{Text: "command-with-description", Description: "description"}} 87 | require.Equal(t, expected, parseSuggestions(out)) 88 | } 89 | 90 | func TestParseSuggestions_WithoutDescription(t *testing.T) { 91 | out := `command-without-description 92 | :4 93 | Completion ended with directive: ShellCompDirectiveNoFileComp` 94 | expected := []prompt.Suggest{{Text: "command-without-description"}} 95 | require.Equal(t, expected, parseSuggestions(out)) 96 | } 97 | 98 | func TestParseSuggestions_HideShorthandFlags(t *testing.T) { 99 | out := `--flag A flag. 100 | -f A flag. 101 | :4 102 | Completion ended with directive: ShellCompDirectiveNoFileComp` 103 | expected := []prompt.Suggest{{Text: "--flag", Description: "A flag."}} 104 | require.Equal(t, expected, parseSuggestions(out)) 105 | } 106 | 107 | func TestParseSuggestions_Sort(t *testing.T) { 108 | out := `b 109 | a 110 | :4 111 | Completion ended with directive: ShellCompDirectiveNoFileComp` 112 | expected := []prompt.Suggest{{Text: "a"}, {Text: "b"}} 113 | require.Equal(t, expected, parseSuggestions(out)) 114 | } 115 | 116 | func TestEscapeSpecialCharacters_Spaces(t *testing.T) { 117 | require.Equal(t, `"string with spaces"`, escapeSpecialCharacters("string with spaces")) 118 | } 119 | 120 | func TestEscapeSpecialCharacters_All(t *testing.T) { 121 | require.Equal(t, "\\\\\\\"\\$\\`\\!", escapeSpecialCharacters("\\\"$`!")) 122 | } 123 | 124 | func TestEditCommandTree_RemoveShell(t *testing.T) { 125 | root := &cobra.Command{} 126 | shell := &cobra.Command{Use: "shell"} 127 | root.AddCommand(shell) 128 | 129 | s := &cobraShell{root: root} 130 | s.editCommandTree(shell) 131 | require.False(t, hasSubcommand(root, "shell")) 132 | } 133 | 134 | func TestEditCommandTree_AddExit(t *testing.T) { 135 | root := &cobra.Command{} 136 | 137 | s := &cobraShell{root: root} 138 | s.editCommandTree(nil) 139 | require.True(t, hasSubcommand(root, "exit")) 140 | } 141 | 142 | func hasSubcommand(cmd *cobra.Command, name string) bool { 143 | for _, subcommand := range cmd.Commands() { 144 | if subcommand.Name() == name { 145 | return true 146 | } 147 | } 148 | return false 149 | } 150 | --------------------------------------------------------------------------------