mirror of https://github.com/miguelmota/cointop
Revert "Add stripansi dependency, update dependencies and vendor"
This reverts commit 9c9a471062
.
pull/118/head
parent
cae7d520f0
commit
9c1102625e
@ -1,27 +1,29 @@
|
||||
module github.com/miguelmota/cointop
|
||||
|
||||
go 1.16
|
||||
|
||||
require (
|
||||
github.com/BurntSushi/toml v0.3.1
|
||||
github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d
|
||||
github.com/anaskhan96/soup v1.1.1 // indirect
|
||||
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be // indirect
|
||||
github.com/creack/pty v1.1.11
|
||||
github.com/fatih/color v1.10.0
|
||||
github.com/fatih/color v1.9.0
|
||||
github.com/gen2brain/beeep v0.0.0-20200526185328-e9c15c258e28
|
||||
github.com/gliderlabs/ssh v0.3.2
|
||||
github.com/maruel/panicparse v1.6.1
|
||||
github.com/mattn/go-runewidth v0.0.12
|
||||
github.com/michaeldv/termbox-go v0.0.0-20150618033820-675ffd907b74 // indirect
|
||||
github.com/gliderlabs/ssh v0.3.0
|
||||
github.com/maruel/panicparse v1.5.0
|
||||
github.com/mattn/go-colorable v0.1.7 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.9
|
||||
github.com/miguelmota/go-coinmarketcap v0.1.7
|
||||
github.com/miguelmota/gocui v0.4.2
|
||||
github.com/miguelmota/termbox-go v0.0.0-20191229070316-58d4fcbce2a7
|
||||
github.com/mitchellh/go-wordwrap v1.0.1
|
||||
github.com/mop-tracker/mop v0.2.0 // indirect
|
||||
github.com/olekukonko/tablewriter v0.0.5
|
||||
github.com/mitchellh/go-wordwrap v1.0.0
|
||||
github.com/olekukonko/tablewriter v0.0.4
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible
|
||||
github.com/spf13/cobra v1.1.3
|
||||
github.com/spf13/cobra v1.0.0
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
github.com/tomnomnom/xtermcolor v0.0.0-20160428124646-b78803f00a7e
|
||||
golang.org/x/crypto v0.0.0-20210415154028-4f45737414dc
|
||||
golang.org/x/text v0.3.6
|
||||
golang.org/x/crypto v0.0.0-20200728195943-123391ffb6de
|
||||
golang.org/x/net v0.0.0-20200707034311-ab3426394381 // indirect
|
||||
golang.org/x/sys v0.0.0-20200810151505-1b9f1253b3ed // indirect
|
||||
golang.org/x/text v0.3.3
|
||||
)
|
||||
|
||||
go 1.13
|
||||
|
@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2018 Andrew Carlson
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
@ -1,30 +0,0 @@
|
||||
Strip ANSI
|
||||
==========
|
||||
|
||||
This Go package removes ANSI escape codes from strings.
|
||||
|
||||
Ideally, we would prevent these from appearing in any text we want to process.
|
||||
However, sometimes this can't be helped, and we need to be able to deal with that noise.
|
||||
This will use a regexp to remove those unwanted escape codes.
|
||||
|
||||
|
||||
## Install
|
||||
|
||||
```sh
|
||||
$ go get -u github.com/acarl005/stripansi
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```go
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/acarl005/stripansi"
|
||||
)
|
||||
|
||||
func main() {
|
||||
msg := "\x1b[38;5;140m foo\x1b[0m bar"
|
||||
cleanMsg := stripansi.Strip(msg)
|
||||
fmt.Println(cleanMsg) // " foo bar"
|
||||
}
|
||||
```
|
@ -1,13 +0,0 @@
|
||||
package stripansi
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
)
|
||||
|
||||
const ansi = "[\u001B\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\u0007)|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"
|
||||
|
||||
var re = regexp.MustCompile(ansi)
|
||||
|
||||
func Strip(str string) string {
|
||||
return re.ReplaceAllString(str, "")
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
## v1.1
|
||||
|
||||
### Added
|
||||
|
||||
- Cookies can be added to the HTTP request, either via the `Cookies` map or the `Cookie()` function
|
||||
- Function `GetWithClient()` provides the ability to send the request with a custom HTTP client
|
||||
- Function `FindStrict()` finds the first instance of the mentioned tag with the exact matching values of the provided attribute (previously `Find()`)
|
||||
- Function `FindAllStrict()` finds all the instances of the mentioned tag with the exact matching values of the attributes (previously `FindAll()`)
|
||||
|
||||
## Changed
|
||||
|
||||
- Function `Find()` now finds the first instance of the mentioned tag with any matching values of the provided attribute.
|
||||
- Function `FindAll()` now finds all the instances of the mentioned tag with any matching values of the provided attribute.
|
||||
|
||||
---
|
@ -1,7 +1,8 @@
|
||||
github.com/mattn/go-colorable v0.1.8 h1:c1ghPdyEDarC70ftn0y+A/Ee++9zz8ljHG1b13eJ0s8=
|
||||
github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
|
||||
github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
|
||||
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
||||
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae h1:/WDfKMnPU+m5M4xB+6x4kaepxRw6jWvR5iDRdvjHgy8=
|
||||
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
github.com/mattn/go-colorable v0.1.4 h1:snbPLB8fVfU9iwbbo30TPtbLRzwWu6aJS6Xh4eaaviA=
|
||||
github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
|
||||
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
|
||||
github.com/mattn/go-isatty v0.0.11 h1:FxPOTFNqGkuDUGi3H/qkUbQO4ZiBa2brKq5r0l8TGeM=
|
||||
github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE=
|
||||
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4=
|
||||
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
|
@ -1,2 +0,0 @@
|
||||
github.com/rivo/uniseg v0.1.0 h1:+2KBaVoUmb9XzDsrx/Ct0W/EYOSFf/nWTauy++DprtY=
|
||||
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
@ -1,2 +1,2 @@
|
||||
github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
|
||||
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
|
||||
github.com/mattn/go-runewidth v0.0.7 h1:Ei8KR0497xHyKJPAv59M1dkC+rOZCMBJ+t3fZ+twI54=
|
||||
github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
|
||||
|
@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2019 Oliver Kuederle
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
@ -1,62 +0,0 @@
|
||||
# Unicode Text Segmentation for Go
|
||||
|
||||
[![Godoc Reference](https://img.shields.io/badge/godoc-reference-blue.svg)](https://godoc.org/github.com/rivo/uniseg)
|
||||
[![Go Report](https://img.shields.io/badge/go%20report-A%2B-brightgreen.svg)](https://goreportcard.com/report/github.com/rivo/uniseg)
|
||||
|
||||
This Go package implements Unicode Text Segmentation according to [Unicode Standard Annex #29](http://unicode.org/reports/tr29/) (Unicode version 12.0.0).
|
||||
|
||||
At this point, only the determination of grapheme cluster boundaries is implemented.
|
||||
|
||||
## Background
|
||||
|
||||
In Go, [strings are read-only slices of bytes](https://blog.golang.org/strings). They can be turned into Unicode code points using the `for` loop or by casting: `[]rune(str)`. However, multiple code points may be combined into one user-perceived character or what the Unicode specification calls "grapheme cluster". Here are some examples:
|
||||
|
||||
|String|Bytes (UTF-8)|Code points (runes)|Grapheme clusters|
|
||||
|-|-|-|-|
|
||||
|Käse|6 bytes: `4b 61 cc 88 73 65`|5 code points: `4b 61 308 73 65`|4 clusters: `[4b],[61 308],[73],[65]`|
|
||||
|🏳️🌈|14 bytes: `f0 9f 8f b3 ef b8 8f e2 80 8d f0 9f 8c 88`|4 code points: `1f3f3 fe0f 200d 1f308`|1 cluster: `[1f3f3 fe0f 200d 1f308]`|
|
||||
|🇩🇪|8 bytes: `f0 9f 87 a9 f0 9f 87 aa`|2 code points: `1f1e9 1f1ea`|1 cluster: `[1f1e9 1f1ea]`|
|
||||
|
||||
This package provides a tool to iterate over these grapheme clusters. This may be used to determine the number of user-perceived characters, to split strings in their intended places, or to extract individual characters which form a unit.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
go get github.com/rivo/uniseg
|
||||
```
|
||||
|
||||
## Basic Example
|
||||
|
||||
```go
|
||||
package uniseg
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/rivo/uniseg"
|
||||
)
|
||||
|
||||
func main() {
|
||||
gr := uniseg.NewGraphemes("👍🏼!")
|
||||
for gr.Next() {
|
||||
fmt.Printf("%x ", gr.Runes())
|
||||
}
|
||||
// Output: [1f44d 1f3fc] [21]
|
||||
}
|
||||
```
|
||||
|
||||
## Documentation
|
||||
|
||||
Refer to https://godoc.org/github.com/rivo/uniseg for the package's documentation.
|
||||
|
||||
## Dependencies
|
||||
|
||||
This package does not depend on any packages outside the standard library.
|
||||
|
||||
## Your Feedback
|
||||
|
||||
Add your issue here on GitHub. Feel free to get in touch if you have any questions.
|
||||
|
||||
## Version
|
||||
|
||||
Version tags will be introduced once Golang modules are official. Consider this version 0.1.
|
@ -1,8 +0,0 @@
|
||||
/*
|
||||
Package uniseg implements Unicode Text Segmentation according to Unicode
|
||||
Standard Annex #29 (http://unicode.org/reports/tr29/).
|
||||
|
||||
At this point, only the determination of grapheme cluster boundaries is
|
||||
implemented.
|
||||
*/
|
||||
package uniseg
|
@ -1,3 +0,0 @@
|
||||
module github.com/rivo/uniseg
|
||||
|
||||
go 1.12
|
@ -1,258 +0,0 @@
|
||||
package uniseg
|
||||
|
||||
// The states of the grapheme cluster parser.
|
||||
const (
|
||||
grAny = iota
|
||||
grCR
|
||||
grControlLF
|
||||
grL
|
||||
grLVV
|
||||
grLVTT
|
||||
grPrepend
|
||||
grExtendedPictographic
|
||||
grExtendedPictographicZWJ
|
||||
grRIOdd
|
||||
grRIEven
|
||||
)
|
||||
|
||||
// The grapheme cluster parser's breaking instructions.
|
||||
const (
|
||||
grNoBoundary = iota
|
||||
grBoundary
|
||||
)
|
||||
|
||||
// The grapheme cluster parser's state transitions. Maps (state, property) to
|
||||
// (new state, breaking instruction, rule number). The breaking instruction
|
||||
// always refers to the boundary between the last and next code point.
|
||||
//
|
||||
// This map is queried as follows:
|
||||
//
|
||||
// 1. Find specific state + specific property. Stop if found.
|
||||
// 2. Find specific state + any property.
|
||||
// 3. Find any state + specific property.
|
||||
// 4. If only (2) or (3) (but not both) was found, stop.
|
||||
// 5. If both (2) and (3) were found, use state and breaking instruction from
|
||||
// the transition with the lower rule number, prefer (3) if rule numbers
|
||||
// are equal. Stop.
|
||||
// 6. Assume grAny and grBoundary.
|
||||
var grTransitions = map[[2]int][3]int{
|
||||
// GB5
|
||||
{grAny, prCR}: {grCR, grBoundary, 50},
|
||||
{grAny, prLF}: {grControlLF, grBoundary, 50},
|
||||
{grAny, prControl}: {grControlLF, grBoundary, 50},
|
||||
|
||||
// GB4
|
||||
{grCR, prAny}: {grAny, grBoundary, 40},
|
||||
{grControlLF, prAny}: {grAny, grBoundary, 40},
|
||||
|
||||
// GB3.
|
||||
{grCR, prLF}: {grAny, grNoBoundary, 30},
|
||||
|
||||
// GB6.
|
||||
{grAny, prL}: {grL, grBoundary, 9990},
|
||||
{grL, prL}: {grL, grNoBoundary, 60},
|
||||
{grL, prV}: {grLVV, grNoBoundary, 60},
|
||||
{grL, prLV}: {grLVV, grNoBoundary, 60},
|
||||
{grL, prLVT}: {grLVTT, grNoBoundary, 60},
|
||||
|
||||
// GB7.
|
||||
{grAny, prLV}: {grLVV, grBoundary, 9990},
|
||||
{grAny, prV}: {grLVV, grBoundary, 9990},
|
||||
{grLVV, prV}: {grLVV, grNoBoundary, 70},
|
||||
{grLVV, prT}: {grLVTT, grNoBoundary, 70},
|
||||
|
||||
// GB8.
|
||||
{grAny, prLVT}: {grLVTT, grBoundary, 9990},
|
||||
{grAny, prT}: {grLVTT, grBoundary, 9990},
|
||||
{grLVTT, prT}: {grLVTT, grNoBoundary, 80},
|
||||
|
||||
// GB9.
|
||||
{grAny, prExtend}: {grAny, grNoBoundary, 90},
|
||||
{grAny, prZWJ}: {grAny, grNoBoundary, 90},
|
||||
|
||||
// GB9a.
|
||||
{grAny, prSpacingMark}: {grAny, grNoBoundary, 91},
|
||||
|
||||
// GB9b.
|
||||
{grAny, prPreprend}: {grPrepend, grBoundary, 9990},
|
||||
{grPrepend, prAny}: {grAny, grNoBoundary, 92},
|
||||
|
||||
// GB11.
|
||||
{grAny, prExtendedPictographic}: {grExtendedPictographic, grBoundary, 9990},
|
||||
{grExtendedPictographic, prExtend}: {grExtendedPictographic, grNoBoundary, 110},
|
||||
{grExtendedPictographic, prZWJ}: {grExtendedPictographicZWJ, grNoBoundary, 110},
|
||||
{grExtendedPictographicZWJ, prExtendedPictographic}: {grExtendedPictographic, grNoBoundary, 110},
|
||||
|
||||
// GB12 / GB13.
|
||||
{grAny, prRegionalIndicator}: {grRIOdd, grBoundary, 9990},
|
||||
{grRIOdd, prRegionalIndicator}: {grRIEven, grNoBoundary, 120},
|
||||
{grRIEven, prRegionalIndicator}: {grRIOdd, grBoundary, 120},
|
||||
}
|
||||
|
||||
// Graphemes implements an iterator over Unicode extended grapheme clusters,
|
||||
// specified in the Unicode Standard Annex #29. Grapheme clusters correspond to
|
||||
// "user-perceived characters". These characters often consist of multiple
|
||||
// code points (e.g. the "woman kissing woman" emoji consists of 8 code points:
|
||||
// woman + ZWJ + heavy black heart (2 code points) + ZWJ + kiss mark + ZWJ +
|
||||
// woman) and the rules described in Annex #29 must be applied to group those
|
||||
// code points into clusters perceived by the user as one character.
|
||||
type Graphemes struct {
|
||||
// The code points over which this class iterates.
|
||||
codePoints []rune
|
||||
|
||||
// The (byte-based) indices of the code points into the original string plus
|
||||
// len(original string). Thus, len(indices) = len(codePoints) + 1.
|
||||
indices []int
|
||||
|
||||
// The current grapheme cluster to be returned. These are indices into
|
||||
// codePoints/indices. If start == end, we either haven't started iterating
|
||||
// yet (0) or the iteration has already completed (1).
|
||||
start, end int
|
||||
|
||||
// The index of the next code point to be parsed.
|
||||
pos int
|
||||
|
||||
// The current state of the code point parser.
|
||||
state int
|
||||
}
|
||||
|
||||
// NewGraphemes returns a new grapheme cluster iterator.
|
||||
func NewGraphemes(s string) *Graphemes {
|
||||
g := &Graphemes{}
|
||||
for index, codePoint := range s {
|
||||
g.codePoints = append(g.codePoints, codePoint)
|
||||
g.indices = append(g.indices, index)
|
||||
}
|
||||
g.indices = append(g.indices, len(s))
|
||||
g.Next() // Parse ahead.
|
||||
return g
|
||||
}
|
||||
|
||||
// Next advances the iterator by one grapheme cluster and returns false if no
|
||||
// clusters are left. This function must be called before the first cluster is
|
||||
// accessed.
|
||||
func (g *Graphemes) Next() bool {
|
||||
g.start = g.end
|
||||
|
||||
// The state transition gives us a boundary instruction BEFORE the next code
|
||||
// point so we always need to stay ahead by one code point.
|
||||
|
||||
// Parse the next code point.
|
||||
for g.pos <= len(g.codePoints) {
|
||||
// GB2.
|
||||
if g.pos == len(g.codePoints) {
|
||||
g.end = g.pos
|
||||
g.pos++
|
||||
break
|
||||
}
|
||||
|
||||
// Determine the property of the next character.
|
||||
nextProperty := property(g.codePoints[g.pos])
|
||||
g.pos++
|
||||
|
||||
// Find the applicable transition.
|
||||
var boundary bool
|
||||
transition, ok := grTransitions[[2]int{g.state, nextProperty}]
|
||||
if ok {
|
||||
// We have a specific transition. We'll use it.
|
||||
g.state = transition[0]
|
||||
boundary = transition[1] == grBoundary
|
||||
} else {
|
||||
// No specific transition found. Try the less specific ones.
|
||||
transAnyProp, okAnyProp := grTransitions[[2]int{g.state, prAny}]
|
||||
transAnyState, okAnyState := grTransitions[[2]int{grAny, nextProperty}]
|
||||
if okAnyProp && okAnyState {
|
||||
// Both apply. We'll use a mix (see comments for grTransitions).
|
||||
g.state = transAnyState[0]
|
||||
boundary = transAnyState[1] == grBoundary
|
||||
if transAnyProp[2] < transAnyState[2] {
|
||||
g.state = transAnyProp[0]
|
||||
boundary = transAnyProp[1] == grBoundary
|
||||
}
|
||||
} else if okAnyProp {
|
||||
// We only have a specific state.
|
||||
g.state = transAnyProp[0]
|
||||
boundary = transAnyProp[1] == grBoundary
|
||||
// This branch will probably never be reached because okAnyState will
|
||||
// always be true given the current transition map. But we keep it here
|
||||
// for future modifications to the transition map where this may not be
|
||||
// true anymore.
|
||||
} else if okAnyState {
|
||||
// We only have a specific property.
|
||||
g.state = transAnyState[0]
|
||||
boundary = transAnyState[1] == grBoundary
|
||||
} else {
|
||||
// No known transition. GB999: Any x Any.
|
||||
g.state = grAny
|
||||
boundary = true
|
||||
}
|
||||
}
|
||||
|
||||
// If we found a cluster boundary, let's stop here. The current cluster will
|
||||
// be the one that just ended.
|
||||
if g.pos-1 == 0 /* GB1 */ || boundary {
|
||||
g.end = g.pos - 1
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return g.start != g.end
|
||||
}
|
||||
|
||||
// Runes returns a slice of runes (code points) which corresponds to the current
|
||||
// grapheme cluster. If the iterator is already past the end or Next() has not
|
||||
// yet been called, nil is returned.
|
||||
func (g *Graphemes) Runes() []rune {
|
||||
if g.start == g.end {
|
||||
return nil
|
||||
}
|
||||
return g.codePoints[g.start:g.end]
|
||||
}
|
||||
|
||||
// Str returns a substring of the original string which corresponds to the
|
||||
// current grapheme cluster. If the iterator is already past the end or Next()
|
||||
// has not yet been called, an empty string is returned.
|
||||
func (g *Graphemes) Str() string {
|
||||
if g.start == g.end {
|
||||
return ""
|
||||
}
|
||||
return string(g.codePoints[g.start:g.end])
|
||||
}
|
||||
|
||||
// Bytes returns a byte slice which corresponds to the current grapheme cluster.
|
||||
// If the iterator is already past the end or Next() has not yet been called,
|
||||
// nil is returned.
|
||||
func (g *Graphemes) Bytes() []byte {
|
||||
if g.start == g.end {
|
||||
return nil
|
||||
}
|
||||
return []byte(string(g.codePoints[g.start:g.end]))
|
||||
}
|
||||
|
||||
// Positions returns the interval of the current grapheme cluster as byte
|
||||
// positions into the original string. The first returned value "from" indexes
|
||||
// the first byte and the second returned value "to" indexes the first byte that
|
||||
// is not included anymore, i.e. str[from:to] is the current grapheme cluster of
|
||||
// the original string "str". If Next() has not yet been called, both values are
|
||||
// 0. If the iterator is already past the end, both values are 1.
|
||||
func (g *Graphemes) Positions() (int, int) {
|
||||
return g.indices[g.start], g.indices[g.end]
|
||||
}
|
||||
|
||||
// Reset puts the iterator into its initial state such that the next call to
|
||||
// Next() sets it to the first grapheme cluster again.
|
||||
func (g *Graphemes) Reset() {
|
||||
g.start, g.end, g.pos, g.state = 0, 0, 0, grAny
|
||||
g.Next() // Parse ahead again.
|
||||
}
|
||||
|
||||
// GraphemeClusterCount returns the number of user-perceived characters
|
||||
// (grapheme clusters) for the given string. To calculate this number, it
|
||||
// iterates through the string using the Graphemes iterator.
|
||||
func GraphemeClusterCount(s string) (n int) {
|
||||
g := NewGraphemes(s)
|
||||
for g.Next() {
|
||||
n++
|
||||
}
|
||||
return
|
||||
}
|
File diff suppressed because it is too large
Load Diff
@ -1,48 +0,0 @@
|
||||
run:
|
||||
deadline: 5m
|
||||
|
||||
linters:
|
||||
disable-all: true
|
||||
enable:
|
||||
#- bodyclose
|
||||
- deadcode
|
||||
#- depguard
|
||||
#- dogsled
|
||||
#- dupl
|
||||
- errcheck
|
||||
#- exhaustive
|
||||
#- funlen
|
||||
- gas
|
||||
#- gochecknoinits
|
||||
- goconst
|
||||
#- gocritic
|
||||
#- gocyclo
|
||||
#- gofmt
|
||||
- goimports
|
||||
- golint
|
||||
#- gomnd
|
||||
#- goprintffuncname
|
||||
#- gosec
|
||||
#- gosimple
|
||||
- govet
|
||||
- ineffassign
|
||||
- interfacer
|
||||
#- lll
|
||||
- maligned
|
||||
- megacheck
|
||||
#- misspell
|
||||
#- nakedret
|
||||
#- noctx
|
||||
#- nolintlint
|
||||
#- rowserrcheck
|
||||
#- scopelint
|
||||
#- staticcheck
|
||||
- structcheck
|
||||
#- stylecheck
|
||||
#- typecheck
|
||||
- unconvert
|
||||
#- unparam
|
||||
#- unused
|
||||
- varcheck
|
||||
#- whitespace
|
||||
fast: false
|
@ -1,51 +0,0 @@
|
||||
# Cobra Changelog
|
||||
|
||||
## v1.1.3
|
||||
|
||||
* **Fix:** release-branch.cobra1.1 only: Revert "Deprecate Go < 1.14" to maintain backward compatibility
|
||||
|
||||
## v1.1.2
|
||||
|
||||
### Notable Changes
|
||||
|
||||
* Bump license year to 2021 in golden files (#1309) @Bowbaq
|
||||
* Enhance PowerShell completion with custom comp (#1208) @Luap99
|
||||
* Update gopkg.in/yaml.v2 to v2.4.0: The previous breaking change in yaml.v2 v2.3.0 has been reverted, see go-yaml/yaml#670
|
||||
* Documentation readability improvements (#1228 etc.) @zaataylor etc.
|
||||
* Use golangci-lint: Repair warnings and errors resulting from linting (#1044) @umarcor
|
||||
|
||||
## v1.1.1
|
||||
|
||||
* **Fix:** yaml.v2 2.3.0 contained a unintended breaking change. This release reverts to yaml.v2 v2.2.8 which has recent critical CVE fixes, but does not have the breaking changes. See https://github.com/spf13/cobra/pull/1259 for context.
|
||||
* **Fix:** correct internal formatting for go-md2man v2 (which caused man page generation to be broken). See https://github.com/spf13/cobra/issues/1049 for context.
|
||||
|
||||
## v1.1.0
|
||||
|
||||
### Notable Changes
|
||||
|
||||
* Extend Go completions and revamp zsh comp (#1070)
|
||||
* Fix man page doc generation - no auto generated tag when `cmd.DisableAutoGenTag = true` (#1104) @jpmcb
|
||||
* Add completion for help command (#1136)
|
||||
* Complete subcommands when TraverseChildren is set (#1171)
|
||||
* Fix stderr printing functions (#894)
|
||||
* fix: fish output redirection (#1247)
|
||||
|
||||
## v1.0.0
|
||||
|
||||
Announcing v1.0.0 of Cobra. 🎉
|
||||
|
||||
### Notable Changes
|
||||
* Fish completion (including support for Go custom completion) @marckhouzam
|
||||
* API (urgent): Rename BashCompDirectives to ShellCompDirectives @marckhouzam
|
||||
* Remove/replace SetOutput on Command - deprecated @jpmcb
|
||||
* add support for autolabel stale PR @xchapter7x
|
||||
* Add Labeler Actions @xchapter7x
|
||||
* Custom completions coded in Go (instead of Bash) @marckhouzam
|
||||
* Partial Revert of #922 @jharshman
|
||||
* Add Makefile to project @jharshman
|
||||
* Correct documentation for InOrStdin @desponda
|
||||
* Apply formatting to templates @jharshman
|
||||
* Revert change so help is printed on stdout again @marckhouzam
|
||||
* Update md2man to v2.0.0 @pdf
|
||||
* update viper to v1.4.0 @umarcor
|
||||
* Update cmd/root.go example in README.md @jharshman
|
@ -1,37 +0,0 @@
|
||||
## Cobra User Contract
|
||||
|
||||
### Versioning
|
||||
Cobra will follow a steady release cadence. Non breaking changes will be released as minor versions quarterly. Patch bug releases are at the discretion of the maintainers. Users can expect security patch fixes to be released within relatively short order of a CVE becoming known. For more information on security patch fixes see the CVE section below. Releases will follow [Semantic Versioning](https://semver.org/). Users tracking the Master branch should expect unpredictable breaking changes as the project continues to move forward. For stability, it is highly recommended to use a release.
|
||||
|
||||
### Backward Compatibility
|
||||
We will maintain two major releases in a moving window. The N-1 release will only receive bug fixes and security updates and will be dropped once N+1 is released.
|
||||
|
||||
### Deprecation
|
||||
Deprecation of Go versions or dependent packages will only occur in major releases. To reduce the change of this taking users by surprise, any large deprecation will be preceded by an announcement in the [#cobra slack channel](https://gophers.slack.com/archives/CD3LP1199) and an Issue on Github.
|
||||
|
||||
### CVE
|
||||
Maintainers will make every effort to release security patches in the case of a medium to high severity CVE directly impacting the library. The speed in which these patches reach a release is up to the discretion of the maintainers. A low severity CVE may be a lower priority than a high severity one.
|
||||
|
||||
### Communication
|
||||
Cobra maintainers will use GitHub issues and the [#cobra slack channel](https://gophers.slack.com/archives/CD3LP1199) as the primary means of communication with the community. This is to foster open communication with all users and contributors.
|
||||
|
||||
### Breaking Changes
|
||||
Breaking changes are generally allowed in the master branch, as this is the branch used to develop the next release of Cobra.
|
||||
|
||||
There may be times, however, when master is closed for breaking changes. This is likely to happen as we near the release of a new version.
|
||||
|
||||
Breaking changes are not allowed in release branches, as these represent minor versions that have already been released. These version have consumers who expect the APIs, behaviors, etc, to remain stable during the lifetime of the patch stream for the minor release.
|
||||
|
||||
Examples of breaking changes include:
|
||||
- Removing or renaming exported constant, variable, type, or function.
|
||||
- Updating the version of critical libraries such as `spf13/pflag`, `spf13/viper` etc...
|
||||
- Some version updates may be acceptable for picking up bug fixes, but maintainers must exercise caution when reviewing.
|
||||
|
||||
There may, at times, need to be exceptions where breaking changes are allowed in release branches. These are at the discretion of the project's maintainers, and must be carefully considered before merging.
|
||||
|
||||
### CI Testing
|
||||
Maintainers will ensure the Cobra test suite utilizes the current supported versions of Golang.
|
||||
|
||||
### Disclaimer
|
||||
Changes to this document and the contents therein are at the discretion of the maintainers.
|
||||
None of the contents of this document are legally binding in any way to the maintainers or the users.
|
@ -1,50 +0,0 @@
|
||||
# Contributing to Cobra
|
||||
|
||||
Thank you so much for contributing to Cobra. We appreciate your time and help.
|
||||
Here are some guidelines to help you get started.
|
||||
|
||||
## Code of Conduct
|
||||
|
||||
Be kind and respectful to the members of the community. Take time to educate
|
||||
others who are seeking help. Harassment of any kind will not be tolerated.
|
||||
|
||||
## Questions
|
||||
|
||||
If you have questions regarding Cobra, feel free to ask it in the community
|
||||
[#cobra Slack channel][cobra-slack]
|
||||
|
||||
## Filing a bug or feature
|
||||
|
||||
1. Before filing an issue, please check the existing issues to see if a
|
||||
similar one was already opened. If there is one already opened, feel free
|
||||
to comment on it.
|
||||
1. If you believe you've found a bug, please provide detailed steps of
|
||||
reproduction, the version of Cobra and anything else you believe will be
|
||||
useful to help troubleshoot it (e.g. OS environment, environment variables,
|
||||
etc...). Also state the current behavior vs. the expected behavior.
|
||||
1. If you'd like to see a feature or an enhancement please open an issue with
|
||||
a clear title and description of what the feature is and why it would be
|
||||
beneficial to the project and its users.
|
||||
|
||||
## Submitting changes
|
||||
|
||||
1. CLA: Upon submitting a Pull Request (PR), contributors will be prompted to
|
||||
sign a CLA. Please sign the CLA :slightly_smiling_face:
|
||||
1. Tests: If you are submitting code, please ensure you have adequate tests
|
||||
for the feature. Tests can be run via `go test ./...` or `make test`.
|
||||
1. Since this is golang project, ensure the new code is properly formatted to
|
||||
ensure code consistency. Run `make all`.
|
||||
|
||||
### Quick steps to contribute
|
||||
|
||||
1. Fork the project.
|
||||
1. Download your fork to your PC (`git clone https://github.com/your_username/cobra && cd cobra`)
|
||||
1. Create your feature branch (`git checkout -b my-new-feature`)
|
||||
1. Make changes and run tests (`make test`)
|
||||
1. Add them to staging (`git add .`)
|
||||
1. Commit your changes (`git commit -m 'Add some feature'`)
|
||||
1. Push to the branch (`git push origin my-new-feature`)
|
||||
1. Create new pull request
|
||||
|
||||
<!-- Links -->
|
||||
[cobra-slack]: https://gophers.slack.com/archives/CD3LP1199
|
@ -1,4 +1,7 @@
|
||||
## Generating Fish Completions For Your cobra.Command
|
||||
## Generating Fish Completions for your own cobra.Command
|
||||
|
||||
Please refer to [Shell Completions](shell_completions.md) for details.
|
||||
Cobra supports native Fish completions generated from the root `cobra.Command`. You can use the `command.GenFishCompletion()` or `command.GenFishCompletionFile()` functions. You must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users.
|
||||
|
||||
### Limitations
|
||||
|
||||
* Custom completions implemented using the `ValidArgsFunction` and `RegisterFlagCompletionFunc()` are supported automatically but the ones implemented in Bash scripting are not.
|
||||
|
@ -1,3 +1,14 @@
|
||||
# Generating PowerShell Completions For Your Own cobra.Command
|
||||
|
||||
Please refer to [Shell Completions](shell_completions.md#powershell-completions) for details.
|
||||
Cobra can generate PowerShell completion scripts. Users need PowerShell version 5.0 or above, which comes with Windows 10 and can be downloaded separately for Windows 7 or 8.1. They can then write the completions to a file and source this file from their PowerShell profile, which is referenced by the `$Profile` environment variable. See `Get-Help about_Profiles` for more info about PowerShell profiles.
|
||||
|
||||
# What's supported
|
||||
|
||||
- Completion for subcommands using their `.Short` description
|
||||
- Completion for non-hidden flags using their `.Name` and `.Shorthand`
|
||||
|
||||
# What's not yet supported
|
||||
|
||||
- Command aliases
|
||||
- Required, filename or custom flags (they will work like normal flags)
|
||||
- Custom completion scripts
|
||||
|
@ -1,38 +0,0 @@
|
||||
## Projects using Cobra
|
||||
|
||||
- [Arduino CLI](https://github.com/arduino/arduino-cli)
|
||||
- [Bleve](http://www.blevesearch.com/)
|
||||
- [CockroachDB](http://www.cockroachlabs.com/)
|
||||
- [Cosmos SDK](https://github.com/cosmos/cosmos-sdk)
|
||||
- [Delve](https://github.com/derekparker/delve)
|
||||
- [Docker (distribution)](https://github.com/docker/distribution)
|
||||
- [Etcd](https://etcd.io/)
|
||||
- [Gardener](https://github.com/gardener/gardenctl)
|
||||
- [Giant Swarm's gsctl](https://github.com/giantswarm/gsctl)
|
||||
- [Git Bump](https://github.com/erdaltsksn/git-bump)
|
||||
- [Github CLI](https://github.com/cli/cli)
|
||||
- [GitHub Labeler](https://github.com/erdaltsksn/gh-label)
|
||||
- [Golangci-lint](https://golangci-lint.run)
|
||||
- [GopherJS](http://www.gopherjs.org/)
|
||||
- [Helm](https://helm.sh)
|
||||
- [Hugo](https://gohugo.io)
|
||||
- [Istio](https://istio.io)
|
||||
- [Kool](https://github.com/kool-dev/kool)
|
||||
- [Kubernetes](http://kubernetes.io/)
|
||||
- [Linkerd](https://linkerd.io/)
|
||||
- [Mattermost-server](https://github.com/mattermost/mattermost-server)
|
||||
- [Metal Stack CLI](https://github.com/metal-stack/metalctl)
|
||||
- [Moby (former Docker)](https://github.com/moby/moby)
|
||||
- [Nanobox](https://github.com/nanobox-io/nanobox)/[Nanopack](https://github.com/nanopack)
|
||||
- [OpenShift](https://www.openshift.com/)
|
||||
- [Ory Hydra](https://github.com/ory/hydra)
|
||||
- [Ory Kratos](https://github.com/ory/kratos)
|
||||
- [Pouch](https://github.com/alibaba/pouch)
|
||||
- [ProjectAtomic (enterprise)](http://www.projectatomic.io/)
|
||||
- [Prototool](https://github.com/uber/prototool)
|
||||
- [Random](https://github.com/erdaltsksn/random)
|
||||
- [Rclone](https://rclone.org/)
|
||||
- [Skaffold](https://skaffold.dev/)
|
||||
- [Tendermint](https://github.com/tendermint/tendermint)
|
||||
- [Twitch CLI](https://github.com/twitchdev/twitch-cli)
|
||||
- [Werf](https://werf.io/)
|
@ -1,483 +0,0 @@
|
||||
# Generating shell completions
|
||||
|
||||
Cobra can generate shell completions for multiple shells.
|
||||
The currently supported shells are:
|
||||
- Bash
|
||||
- Zsh
|
||||
- fish
|
||||
- PowerShell
|
||||
|
||||
If you are using the generator, you can create a completion command by running
|
||||
|
||||
```bash
|
||||
cobra add completion
|
||||
```
|
||||
and then modifying the generated `cmd/completion.go` file to look something like this
|
||||
(writing the shell script to stdout allows the most flexible use):
|
||||
|
||||
```go
|
||||
var completionCmd = &cobra.Command{
|
||||
Use: "completion [bash|zsh|fish|powershell]",
|
||||
Short: "Generate completion script",
|
||||
Long: `To load completions:
|
||||
|
||||
Bash:
|
||||
|
||||
$ source <(yourprogram completion bash)
|
||||
|
||||
# To load completions for each session, execute once:
|
||||
# Linux:
|
||||
$ yourprogram completion bash > /etc/bash_completion.d/yourprogram
|
||||
# macOS:
|
||||
$ yourprogram completion bash > /usr/local/etc/bash_completion.d/yourprogram
|
||||
|
||||
Zsh:
|
||||
|
||||
# If shell completion is not already enabled in your environment,
|
||||
# you will need to enable it. You can execute the following once:
|
||||
|
||||
$ echo "autoload -U compinit; compinit" >> ~/.zshrc
|
||||
|
||||
# To load completions for each session, execute once:
|
||||
$ yourprogram completion zsh > "${fpath[1]}/_yourprogram"
|
||||
|
||||
# You will need to start a new shell for this setup to take effect.
|
||||
|
||||
fish:
|
||||
|
||||
$ yourprogram completion fish | source
|
||||
|
||||
# To load completions for each session, execute once:
|
||||
$ yourprogram completion fish > ~/.config/fish/completions/yourprogram.fish
|
||||
|
||||
PowerShell:
|
||||
|
||||
PS> yourprogram completion powershell | Out-String | Invoke-Expression
|
||||
|
||||
# To load completions for every new session, run:
|
||||
PS> yourprogram completion powershell > yourprogram.ps1
|
||||
# and source this file from your PowerShell profile.
|
||||
`,
|
||||
DisableFlagsInUseLine: true,
|
||||
ValidArgs: []string{"bash", "zsh", "fish", "powershell"},
|
||||
Args: cobra.ExactValidArgs(1),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
switch args[0] {
|
||||
case "bash":
|
||||
cmd.Root().GenBashCompletion(os.Stdout)
|
||||
case "zsh":
|
||||
cmd.Root().GenZshCompletion(os.Stdout)
|
||||
case "fish":
|
||||
cmd.Root().GenFishCompletion(os.Stdout, true)
|
||||
case "powershell":
|
||||
cmd.Root().GenPowerShellCompletion(os.Stdout)
|
||||
}
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** The cobra generator may include messages printed to stdout, for example, if the config file is loaded; this will break the auto-completion script so must be removed.
|
||||
|
||||
# Customizing completions
|
||||
|
||||
The generated completion scripts will automatically handle completing commands and flags. However, you can make your completions much more powerful by providing information to complete your program's nouns and flag values.
|
||||
|
||||
## Completion of nouns
|
||||
|
||||
### Static completion of nouns
|
||||
|
||||
Cobra allows you to provide a pre-defined list of completion choices for your nouns using the `ValidArgs` field.
|
||||
For example, if you want `kubectl get [tab][tab]` to show a list of valid "nouns" you have to set them.
|
||||
Some simplified code from `kubectl get` looks like:
|
||||
|
||||
```go
|
||||
validArgs []string = { "pod", "node", "service", "replicationcontroller" }
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)",
|
||||
Short: "Display one or many resources",
|
||||
Long: get_long,
|
||||
Example: get_example,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
cobra.CheckErr(RunGet(f, out, cmd, args))
|
||||
},
|
||||
ValidArgs: validArgs,
|
||||
}
|
||||
```
|
||||
|
||||
Notice we put the `ValidArgs` field on the `get` sub-command. Doing so will give results like:
|
||||
|
||||
```bash
|
||||
$ kubectl get [tab][tab]
|
||||
node pod replicationcontroller service
|
||||
```
|
||||
|
||||
#### Aliases for nouns
|
||||
|
||||
If your nouns have aliases, you can define them alongside `ValidArgs` using `ArgAliases`:
|
||||
|
||||
```go
|
||||
argAliases []string = { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" }
|
||||
|
||||
cmd := &cobra.Command{
|
||||
...
|
||||
ValidArgs: validArgs,
|
||||
ArgAliases: argAliases
|
||||
}
|
||||
```
|
||||
|
||||
The aliases are not shown to the user on tab completion, but they are accepted as valid nouns by
|
||||
the completion algorithm if entered manually, e.g. in:
|
||||
|
||||
```bash
|
||||
$ kubectl get rc [tab][tab]
|
||||
backend frontend database
|
||||
```
|
||||
|
||||
Note that without declaring `rc` as an alias, the completion algorithm would not know to show the list of
|
||||
replication controllers following `rc`.
|
||||
|
||||
### Dynamic completion of nouns
|
||||
|
||||
In some cases it is not possible to provide a list of completions in advance. Instead, the list of completions must be determined at execution-time. In a similar fashion as for static completions, you can use the `ValidArgsFunction` field to provide a Go function that Cobra will execute when it needs the list of completion choices for the nouns of a command. Note that either `ValidArgs` or `ValidArgsFunction` can be used for a single cobra command, but not both.
|
||||
Simplified code from `helm status` looks like:
|
||||
|
||||
```go
|
||||
cmd := &cobra.Command{
|
||||
Use: "status RELEASE_NAME",
|
||||
Short: "Display the status of the named release",
|
||||
Long: status_long,
|
||||
RunE: func(cmd *cobra.Command, args []string) {
|
||||
RunGet(args[0])
|
||||
},
|
||||
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
if len(args) != 0 {
|
||||
return nil, cobra.ShellCompDirectiveNoFileComp
|
||||
}
|
||||
return getReleasesFromCluster(toComplete), cobra.ShellCompDirectiveNoFileComp
|
||||
},
|
||||
}
|
||||
```
|
||||
Where `getReleasesFromCluster()` is a Go function that obtains the list of current Helm releases running on the Kubernetes cluster.
|
||||
Notice we put the `ValidArgsFunction` on the `status` sub-command. Let's assume the Helm releases on the cluster are: `harbor`, `notary`, `rook` and `thanos` then this dynamic completion will give results like:
|
||||
|
||||
```bash
|
||||
$ helm status [tab][tab]
|
||||
harbor notary rook thanos
|
||||
```
|
||||
You may have noticed the use of `cobra.ShellCompDirective`. These directives are bit fields allowing to control some shell completion behaviors for your particular completion. You can combine them with the bit-or operator such as `cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp`
|
||||
```go
|
||||
// Indicates that the shell will perform its default behavior after completions
|
||||
// have been provided (this implies none of the other directives).
|
||||
ShellCompDirectiveDefault
|
||||
|
||||
// Indicates an error occurred and completions should be ignored.
|
||||
ShellCompDirectiveError
|
||||
|
||||
// Indicates that the shell should not add a space after the completion,
|
||||
// even if there is a single completion provided.
|
||||
ShellCompDirectiveNoSpace
|
||||
|
||||
// Indicates that the shell should not provide file completion even when
|
||||
// no completion is provided.
|
||||
ShellCompDirectiveNoFileComp
|
||||
|
||||
// Indicates that the returned completions should be used as file extension filters.
|
||||
// For example, to complete only files of the form *.json or *.yaml:
|
||||
// return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt
|
||||
// For flags, using MarkFlagFilename() and MarkPersistentFlagFilename()
|
||||
// is a shortcut to using this directive explicitly.
|
||||
//
|
||||
ShellCompDirectiveFilterFileExt
|
||||
|
||||
// Indicates that only directory names should be provided in file completion.
|
||||
// For example:
|
||||
// return nil, ShellCompDirectiveFilterDirs
|
||||
// For flags, using MarkFlagDirname() is a shortcut to using this directive explicitly.
|
||||
//
|
||||
// To request directory names within another directory, the returned completions
|
||||
// should specify a single directory name within which to search. For example,
|
||||
// to complete directories within "themes/":
|
||||
// return []string{"themes"}, ShellCompDirectiveFilterDirs
|
||||
//
|
||||
ShellCompDirectiveFilterDirs
|
||||
```
|
||||
|
||||
***Note***: When using the `ValidArgsFunction`, Cobra will call your registered function after having parsed all flags and arguments provided in the command-line. You therefore don't need to do this parsing yourself. For example, when a user calls `helm status --namespace my-rook-ns [tab][tab]`, Cobra will call your registered `ValidArgsFunction` after having parsed the `--namespace` flag, as it would have done when calling the `RunE` function.
|
||||
|
||||
#### Debugging
|
||||
|
||||
Cobra achieves dynamic completion through the use of a hidden command called by the completion script. To debug your Go completion code, you can call this hidden command directly:
|
||||
```bash
|
||||
$ helm __complete status har<ENTER>
|
||||
harbor
|
||||
:4
|
||||
Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr
|
||||
```
|
||||
***Important:*** If the noun to complete is empty (when the user has not yet typed any letters of that noun), you must pass an empty parameter to the `__complete` command:
|
||||
```bash
|
||||
$ helm __complete status ""<ENTER>
|
||||
harbor
|
||||
notary
|
||||
rook
|
||||
thanos
|
||||
:4
|
||||
Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr
|
||||
```
|
||||
Calling the `__complete` command directly allows you to run the Go debugger to troubleshoot your code. You can also add printouts to your code; Cobra provides the following functions to use for printouts in Go completion code:
|
||||
```go
|
||||
// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE
|
||||
// is set to a file path) and optionally prints to stderr.
|
||||
cobra.CompDebug(msg string, printToStdErr bool) {
|
||||
cobra.CompDebugln(msg string, printToStdErr bool)
|
||||
|
||||
// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE
|
||||
// is set to a file path) and to stderr.
|
||||
cobra.CompError(msg string)
|
||||
cobra.CompErrorln(msg string)
|
||||
```
|
||||
***Important:*** You should **not** leave traces that print directly to stdout in your completion code as they will be interpreted as completion choices by the completion script. Instead, use the cobra-provided debugging traces functions mentioned above.
|
||||
|
||||
## Completions for flags
|
||||
|
||||
### Mark flags as required
|
||||
|
||||
Most of the time completions will only show sub-commands. But if a flag is required to make a sub-command work, you probably want it to show up when the user types [tab][tab]. You can mark a flag as 'Required' like so:
|
||||
|
||||
```go
|
||||
cmd.MarkFlagRequired("pod")
|
||||
cmd.MarkFlagRequired("container")
|
||||
```
|
||||
|
||||
and you'll get something like
|
||||
|
||||
```bash
|
||||
$ kubectl exec [tab][tab]
|
||||
-c --container= -p --pod=
|
||||
```
|
||||
|
||||
### Specify dynamic flag completion
|
||||
|
||||
As for nouns, Cobra provides a way of defining dynamic completion of flags. To provide a Go function that Cobra will execute when it needs the list of completion choices for a flag, you must register the function using the `command.RegisterFlagCompletionFunc()` function.
|
||||
|
||||
```go
|
||||
flagName := "output"
|
||||
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
return []string{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault
|
||||
})
|
||||
```
|
||||
Notice that calling `RegisterFlagCompletionFunc()` is done through the `command` with which the flag is associated. In our example this dynamic completion will give results like so:
|
||||
|
||||
```bash
|
||||
$ helm status --output [tab][tab]
|
||||
json table yaml
|
||||
```
|
||||
|
||||
#### Debugging
|
||||
|
||||
You can also easily debug your Go completion code for flags:
|
||||
```bash
|
||||
$ helm __complete status --output ""
|
||||
json
|
||||
table
|
||||
yaml
|
||||
:4
|
||||
Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr
|
||||
```
|
||||
***Important:*** You should **not** leave traces that print to stdout in your completion code as they will be interpreted as completion choices by the completion script. Instead, use the cobra-provided debugging traces functions mentioned further above.
|
||||
|
||||
### Specify valid filename extensions for flags that take a filename
|
||||
|
||||
To limit completions of flag values to file names with certain extensions you can either use the different `MarkFlagFilename()` functions or a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterFileExt`, like so:
|
||||
```go
|
||||
flagName := "output"
|
||||
cmd.MarkFlagFilename(flagName, "yaml", "json")
|
||||
```
|
||||
or
|
||||
```go
|
||||
flagName := "output"
|
||||
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
return []string{"yaml", "json"}, ShellCompDirectiveFilterFileExt})
|
||||
```
|
||||
|
||||
### Limit flag completions to directory names
|
||||
|
||||
To limit completions of flag values to directory names you can either use the `MarkFlagDirname()` functions or a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs`, like so:
|
||||
```go
|
||||
flagName := "output"
|
||||
cmd.MarkFlagDirname(flagName)
|
||||
```
|
||||
or
|
||||
```go
|
||||
flagName := "output"
|
||||
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
return nil, cobra.ShellCompDirectiveFilterDirs
|
||||
})
|
||||
```
|
||||
To limit completions of flag values to directory names *within another directory* you can use a combination of `RegisterFlagCompletionFunc()` and `ShellCompDirectiveFilterDirs` like so:
|
||||
```go
|
||||
flagName := "output"
|
||||
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
return []string{"themes"}, cobra.ShellCompDirectiveFilterDirs
|
||||
})
|
||||
```
|
||||
### Descriptions for completions
|
||||
|
||||
`zsh`, `fish` and `powershell` allow for descriptions to annotate completion choices. For commands and flags, Cobra will provide the descriptions automatically, based on usage information. For example, using zsh:
|
||||
```
|
||||
$ helm s[tab]
|
||||
search -- search for a keyword in charts
|
||||
show -- show information of a chart
|
||||
status -- displays the status of the named release
|
||||
```
|
||||
while using fish:
|
||||
```
|
||||
$ helm s[tab]
|
||||
search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release)
|
||||
```
|
||||
|
||||
Cobra allows you to add annotations to your own completions. Simply add the annotation text after each completion, following a `\t` separator. This technique applies to completions returned by `ValidArgs`, `ValidArgsFunction` and `RegisterFlagCompletionFunc()`. For example:
|
||||
```go
|
||||
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
return []string{"harbor\tAn image registry", "thanos\tLong-term metrics"}, cobra.ShellCompDirectiveNoFileComp
|
||||
}}
|
||||
```
|
||||
or
|
||||
```go
|
||||
ValidArgs: []string{"bash\tCompletions for bash", "zsh\tCompletions for zsh"}
|
||||
```
|
||||
## Bash completions
|
||||
|
||||
### Dependencies
|
||||
|
||||
The bash completion script generated by Cobra requires the `bash_completion` package. You should update the help text of your completion command to show how to install the `bash_completion` package ([Kubectl docs](https://kubernetes.io/docs/tasks/tools/install-kubectl/#enabling-shell-autocompletion))
|
||||
|
||||
### Aliases
|
||||
|
||||
You can also configure `bash` aliases for your program and they will also support completions.
|
||||
|
||||
```bash
|
||||
alias aliasname=origcommand
|
||||
complete -o default -F __start_origcommand aliasname
|
||||
|
||||
# and now when you run `aliasname` completion will make
|
||||
# suggestions as it did for `origcommand`.
|
||||
|
||||
$ aliasname <tab><tab>
|
||||
completion firstcommand secondcommand
|
||||
```
|
||||
### Bash legacy dynamic completions
|
||||
|
||||
For backward compatibility, Cobra still supports its bash legacy dynamic completion solution.
|
||||
Please refer to [Bash Completions](bash_completions.md) for details.
|
||||
|
||||
## Zsh completions
|
||||
|
||||
Cobra supports native zsh completion generated from the root `cobra.Command`.
|
||||
The generated completion script should be put somewhere in your `$fpath` and be named
|
||||
`_<yourProgram>`. You will need to start a new shell for the completions to become available.
|
||||
|
||||
Zsh supports descriptions for completions. Cobra will provide the description automatically,
|
||||
based on usage information. Cobra provides a way to completely disable such descriptions by
|
||||
using `GenZshCompletionNoDesc()` or `GenZshCompletionFileNoDesc()`. You can choose to make
|
||||
this a configurable option to your users.
|
||||
```
|
||||
# With descriptions
|
||||
$ helm s[tab]
|
||||
search -- search for a keyword in charts
|
||||
show -- show information of a chart
|
||||
status -- displays the status of the named release
|
||||
|
||||
# Without descriptions
|
||||
$ helm s[tab]
|
||||
search show status
|
||||
```
|
||||
*Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`.
|
||||
|
||||
### Limitations
|
||||
|
||||
* Custom completions implemented in Bash scripting (legacy) are not supported and will be ignored for `zsh` (including the use of the `BashCompCustom` flag annotation).
|
||||
* You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`).
|
||||
* The function `MarkFlagCustom()` is not supported and will be ignored for `zsh`.
|
||||
* You should instead use `RegisterFlagCompletionFunc()`.
|
||||
|
||||
### Zsh completions standardization
|
||||
|
||||
Cobra 1.1 standardized its zsh completion support to align it with its other shell completions. Although the API was kept backward-compatible, some small changes in behavior were introduced.
|
||||
Please refer to [Zsh Completions](zsh_completions.md) for details.
|
||||
|
||||
## fish completions
|
||||
|
||||
Cobra supports native fish completions generated from the root `cobra.Command`. You can use the `command.GenFishCompletion()` or `command.GenFishCompletionFile()` functions. You must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users.
|
||||
```
|
||||
# With descriptions
|
||||
$ helm s[tab]
|
||||
search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release)
|
||||
|
||||
# Without descriptions
|
||||
$ helm s[tab]
|
||||
search show status
|
||||
```
|
||||
*Note*: Because of backward-compatibility requirements, we were forced to have a different API to disable completion descriptions between `zsh` and `fish`.
|
||||
|
||||
### Limitations
|
||||
|
||||
* Custom completions implemented in bash scripting (legacy) are not supported and will be ignored for `fish` (including the use of the `BashCompCustom` flag annotation).
|
||||
* You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`).
|
||||
* The function `MarkFlagCustom()` is not supported and will be ignored for `fish`.
|
||||
* You should instead use `RegisterFlagCompletionFunc()`.
|
||||
* The following flag completion annotations are not supported and will be ignored for `fish`:
|
||||
* `BashCompFilenameExt` (filtering by file extension)
|
||||
* `BashCompSubdirsInDir` (filtering by directory)
|
||||
* The functions corresponding to the above annotations are consequently not supported and will be ignored for `fish`:
|
||||
* `MarkFlagFilename()` and `MarkPersistentFlagFilename()` (filtering by file extension)
|
||||
* `MarkFlagDirname()` and `MarkPersistentFlagDirname()` (filtering by directory)
|
||||
* Similarly, the following completion directives are not supported and will be ignored for `fish`:
|
||||
* `ShellCompDirectiveFilterFileExt` (filtering by file extension)
|
||||
* `ShellCompDirectiveFilterDirs` (filtering by directory)
|
||||
|
||||
## PowerShell completions
|
||||
|
||||
Cobra supports native PowerShell completions generated from the root `cobra.Command`. You can use the `command.GenPowerShellCompletion()` or `command.GenPowerShellCompletionFile()` functions. To include descriptions use `command.GenPowerShellCompletionWithDesc()` and `command.GenPowerShellCompletionFileWithDesc()`. Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users.
|
||||
|
||||
The script is designed to support all three PowerShell completion modes:
|
||||
|
||||
* TabCompleteNext (default windows style - on each key press the next option is displayed)
|
||||
* Complete (works like bash)
|
||||
* MenuComplete (works like zsh)
|
||||
|
||||
You set the mode with `Set-PSReadLineKeyHandler -Key Tab -Function <mode>`. Descriptions are only displayed when using the `Complete` or `MenuComplete` mode.
|
||||
|
||||
Users need PowerShell version 5.0 or above, which comes with Windows 10 and can be downloaded separately for Windows 7 or 8.1. They can then write the completions to a file and source this file from their PowerShell profile, which is referenced by the `$Profile` environment variable. See `Get-Help about_Profiles` for more info about PowerShell profiles.
|
||||
|
||||
```
|
||||
# With descriptions and Mode 'Complete'
|
||||
$ helm s[tab]
|
||||
search (search for a keyword in charts) show (show information of a chart) status (displays the status of the named release)
|
||||
|
||||
# With descriptions and Mode 'MenuComplete' The description of the current selected value will be displayed below the suggestions.
|
||||
$ helm s[tab]
|
||||
search show status
|
||||
|
||||
search for a keyword in charts
|
||||
|
||||
# Without descriptions
|
||||
$ helm s[tab]
|
||||
search show status
|
||||
```
|
||||
|
||||
### Limitations
|
||||
|
||||
* Custom completions implemented in bash scripting (legacy) are not supported and will be ignored for `powershell` (including the use of the `BashCompCustom` flag annotation).
|
||||
* You should instead use `ValidArgsFunction` and `RegisterFlagCompletionFunc()` which are portable to the different shells (`bash`, `zsh`, `fish`, `powershell`).
|
||||
* The function `MarkFlagCustom()` is not supported and will be ignored for `powershell`.
|
||||
* You should instead use `RegisterFlagCompletionFunc()`.
|
||||
* The following flag completion annotations are not supported and will be ignored for `powershell`:
|
||||
* `BashCompFilenameExt` (filtering by file extension)
|
||||
* `BashCompSubdirsInDir` (filtering by directory)
|
||||
* The functions corresponding to the above annotations are consequently not supported and will be ignored for `powershell`:
|
||||
* `MarkFlagFilename()` and `MarkPersistentFlagFilename()` (filtering by file extension)
|
||||
* `MarkFlagDirname()` and `MarkPersistentFlagDirname()` (filtering by directory)
|
||||
* Similarly, the following completion directives are not supported and will be ignored for `powershell`:
|
||||
* `ShellCompDirectiveFilterFileExt` (filtering by file extension)
|
||||
* `ShellCompDirectiveFilterDirs` (filtering by directory)
|
@ -1,240 +1,336 @@
|
||||
package cobra
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"text/template"
|
||||
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
// GenZshCompletionFile generates zsh completion file including descriptions.
|
||||
func (c *Command) GenZshCompletionFile(filename string) error {
|
||||
return c.genZshCompletionFile(filename, true)
|
||||
const (
|
||||
zshCompArgumentAnnotation = "cobra_annotations_zsh_completion_argument_annotation"
|
||||
zshCompArgumentFilenameComp = "cobra_annotations_zsh_completion_argument_file_completion"
|
||||
zshCompArgumentWordComp = "cobra_annotations_zsh_completion_argument_word_completion"
|
||||
zshCompDirname = "cobra_annotations_zsh_dirname"
|
||||
)
|
||||
|
||||
var (
|
||||
zshCompFuncMap = template.FuncMap{
|
||||
"genZshFuncName": zshCompGenFuncName,
|
||||
"extractFlags": zshCompExtractFlag,
|
||||
"genFlagEntryForZshArguments": zshCompGenFlagEntryForArguments,
|
||||
"extractArgsCompletions": zshCompExtractArgumentCompletionHintsForRendering,
|
||||
}
|
||||
zshCompletionText = `
|
||||
{{/* should accept Command (that contains subcommands) as parameter */}}
|
||||
{{define "argumentsC" -}}
|
||||
{{ $cmdPath := genZshFuncName .}}
|
||||
function {{$cmdPath}} {
|
||||
local -a commands
|
||||
|
||||
_arguments -C \{{- range extractFlags .}}
|
||||
{{genFlagEntryForZshArguments .}} \{{- end}}
|
||||
"1: :->cmnds" \
|
||||
"*::arg:->args"
|
||||
|
||||
case $state in
|
||||
cmnds)
|
||||
commands=({{range .Commands}}{{if not .Hidden}}
|
||||
"{{.Name}}:{{.Short}}"{{end}}{{end}}
|
||||
)
|
||||
_describe "command" commands
|
||||
;;
|
||||
esac
|
||||
|
||||
case "$words[1]" in {{- range .Commands}}{{if not .Hidden}}
|
||||
{{.Name}})
|
||||
{{$cmdPath}}_{{.Name}}
|
||||
;;{{end}}{{end}}
|
||||
esac
|
||||
}
|
||||
{{range .Commands}}{{if not .Hidden}}
|
||||
{{template "selectCmdTemplate" .}}
|
||||
{{- end}}{{end}}
|
||||
{{- end}}
|
||||
|
||||
{{/* should accept Command without subcommands as parameter */}}
|
||||
{{define "arguments" -}}
|
||||
function {{genZshFuncName .}} {
|
||||
{{" _arguments"}}{{range extractFlags .}} \
|
||||
{{genFlagEntryForZshArguments . -}}
|
||||
{{end}}{{range extractArgsCompletions .}} \
|
||||
{{.}}{{end}}
|
||||
}
|
||||
{{end}}
|
||||
|
||||
{{/* dispatcher for commands with or without subcommands */}}
|
||||
{{define "selectCmdTemplate" -}}
|
||||
{{if .Hidden}}{{/* ignore hidden*/}}{{else -}}
|
||||
{{if .Commands}}{{template "argumentsC" .}}{{else}}{{template "arguments" .}}{{end}}
|
||||
{{- end}}
|
||||
{{- end}}
|
||||
|
||||
{{/* template entry point */}}
|
||||
{{define "Main" -}}
|
||||
#compdef _{{.Name}} {{.Name}}
|
||||
|
||||
{{template "selectCmdTemplate" .}}
|
||||
{{end}}
|
||||
`
|
||||
)
|
||||
|
||||
// GenZshCompletion generates zsh completion file including descriptions
|
||||
// and writes it to the passed writer.
|
||||
func (c *Command) GenZshCompletion(w io.Writer) error {
|
||||
return c.genZshCompletion(w, true)
|
||||
// zshCompArgsAnnotation is used to encode/decode zsh completion for
|
||||
// arguments to/from Command.Annotations.
|
||||
type zshCompArgsAnnotation map[int]zshCompArgHint
|
||||
|
||||
type zshCompArgHint struct {
|
||||
// Indicates the type of the completion to use. One of:
|
||||
// zshCompArgumentFilenameComp or zshCompArgumentWordComp
|
||||
Tipe string `json:"type"`
|
||||
|
||||
// A value for the type above (globs for file completion or words)
|
||||
Options []string `json:"options"`
|
||||
}
|
||||
|
||||
// GenZshCompletionFileNoDesc generates zsh completion file without descriptions.
|
||||
func (c *Command) GenZshCompletionFileNoDesc(filename string) error {
|
||||
return c.genZshCompletionFile(filename, false)
|
||||
// GenZshCompletionFile generates zsh completion file.
|
||||
func (c *Command) GenZshCompletionFile(filename string) error {
|
||||
outFile, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer outFile.Close()
|
||||
|
||||
return c.GenZshCompletion(outFile)
|
||||
}
|
||||
|
||||
// GenZshCompletionNoDesc generates zsh completion file without descriptions
|
||||
// and writes it to the passed writer.
|
||||
func (c *Command) GenZshCompletionNoDesc(w io.Writer) error {
|
||||
return c.genZshCompletion(w, false)
|
||||
// GenZshCompletion generates a zsh completion file and writes to the passed
|
||||
// writer. The completion always run on the root command regardless of the
|
||||
// command it was called from.
|
||||
func (c *Command) GenZshCompletion(w io.Writer) error {
|
||||
tmpl, err := template.New("Main").Funcs(zshCompFuncMap).Parse(zshCompletionText)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error creating zsh completion template: %v", err)
|
||||
}
|
||||
return tmpl.Execute(w, c.Root())
|
||||
}
|
||||
|
||||
// MarkZshCompPositionalArgumentFile only worked for zsh and its behavior was
|
||||
// not consistent with Bash completion. It has therefore been disabled.
|
||||
// Instead, when no other completion is specified, file completion is done by
|
||||
// default for every argument. One can disable file completion on a per-argument
|
||||
// basis by using ValidArgsFunction and ShellCompDirectiveNoFileComp.
|
||||
// To achieve file extension filtering, one can use ValidArgsFunction and
|
||||
// ShellCompDirectiveFilterFileExt.
|
||||
//
|
||||
// Deprecated
|
||||
// MarkZshCompPositionalArgumentFile marks the specified argument (first
|
||||
// argument is 1) as completed by file selection. patterns (e.g. "*.txt") are
|
||||
// optional - if not provided the completion will search for all files.
|
||||
func (c *Command) MarkZshCompPositionalArgumentFile(argPosition int, patterns ...string) error {
|
||||
return nil
|
||||
if argPosition < 1 {
|
||||
return fmt.Errorf("Invalid argument position (%d)", argPosition)
|
||||
}
|
||||
annotation, err := c.zshCompGetArgsAnnotations()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if c.zshcompArgsAnnotationnIsDuplicatePosition(annotation, argPosition) {
|
||||
return fmt.Errorf("Duplicate annotation for positional argument at index %d", argPosition)
|
||||
}
|
||||
annotation[argPosition] = zshCompArgHint{
|
||||
Tipe: zshCompArgumentFilenameComp,
|
||||
Options: patterns,
|
||||
}
|
||||
return c.zshCompSetArgsAnnotations(annotation)
|
||||
}
|
||||
|
||||
// MarkZshCompPositionalArgumentWords only worked for zsh. It has therefore
|
||||
// been disabled.
|
||||
// To achieve the same behavior across all shells, one can use
|
||||
// ValidArgs (for the first argument only) or ValidArgsFunction for
|
||||
// any argument (can include the first one also).
|
||||
//
|
||||
// Deprecated
|
||||
// MarkZshCompPositionalArgumentWords marks the specified positional argument
|
||||
// (first argument is 1) as completed by the provided words. At east one word
|
||||
// must be provided, spaces within words will be offered completion with
|
||||
// "word\ word".
|
||||
func (c *Command) MarkZshCompPositionalArgumentWords(argPosition int, words ...string) error {
|
||||
return nil
|
||||
if argPosition < 1 {
|
||||
return fmt.Errorf("Invalid argument position (%d)", argPosition)
|
||||
}
|
||||
if len(words) == 0 {
|
||||
return fmt.Errorf("Trying to set empty word list for positional argument %d", argPosition)
|
||||
}
|
||||
annotation, err := c.zshCompGetArgsAnnotations()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if c.zshcompArgsAnnotationnIsDuplicatePosition(annotation, argPosition) {
|
||||
return fmt.Errorf("Duplicate annotation for positional argument at index %d", argPosition)
|
||||
}
|
||||
annotation[argPosition] = zshCompArgHint{
|
||||
Tipe: zshCompArgumentWordComp,
|
||||
Options: words,
|
||||
}
|
||||
return c.zshCompSetArgsAnnotations(annotation)
|
||||
}
|
||||
|
||||
func (c *Command) genZshCompletionFile(filename string, includeDesc bool) error {
|
||||
outFile, err := os.Create(filename)
|
||||
func zshCompExtractArgumentCompletionHintsForRendering(c *Command) ([]string, error) {
|
||||
var result []string
|
||||
annotation, err := c.zshCompGetArgsAnnotations()
|
||||
if err != nil {
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
defer outFile.Close()
|
||||
for k, v := range annotation {
|
||||
s, err := zshCompRenderZshCompArgHint(k, v)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, s)
|
||||
}
|
||||
if len(c.ValidArgs) > 0 {
|
||||
if _, positionOneExists := annotation[1]; !positionOneExists {
|
||||
s, err := zshCompRenderZshCompArgHint(1, zshCompArgHint{
|
||||
Tipe: zshCompArgumentWordComp,
|
||||
Options: c.ValidArgs,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, s)
|
||||
}
|
||||
}
|
||||
sort.Strings(result)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func zshCompRenderZshCompArgHint(i int, z zshCompArgHint) (string, error) {
|
||||
switch t := z.Tipe; t {
|
||||
case zshCompArgumentFilenameComp:
|
||||
var globs []string
|
||||
for _, g := range z.Options {
|
||||
globs = append(globs, fmt.Sprintf(`-g "%s"`, g))
|
||||
}
|
||||
return fmt.Sprintf(`'%d: :_files %s'`, i, strings.Join(globs, " ")), nil
|
||||
case zshCompArgumentWordComp:
|
||||
var words []string
|
||||
for _, w := range z.Options {
|
||||
words = append(words, fmt.Sprintf("%q", w))
|
||||
}
|
||||
return fmt.Sprintf(`'%d: :(%s)'`, i, strings.Join(words, " ")), nil
|
||||
default:
|
||||
return "", fmt.Errorf("Invalid zsh argument completion annotation: %s", t)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Command) zshcompArgsAnnotationnIsDuplicatePosition(annotation zshCompArgsAnnotation, position int) bool {
|
||||
_, dup := annotation[position]
|
||||
return dup
|
||||
}
|
||||
|
||||
func (c *Command) zshCompGetArgsAnnotations() (zshCompArgsAnnotation, error) {
|
||||
annotation := make(zshCompArgsAnnotation)
|
||||
annotationString, ok := c.Annotations[zshCompArgumentAnnotation]
|
||||
if !ok {
|
||||
return annotation, nil
|
||||
}
|
||||
err := json.Unmarshal([]byte(annotationString), &annotation)
|
||||
if err != nil {
|
||||
return annotation, fmt.Errorf("Error unmarshaling zsh argument annotation: %v", err)
|
||||
}
|
||||
return annotation, nil
|
||||
}
|
||||
|
||||
func (c *Command) zshCompSetArgsAnnotations(annotation zshCompArgsAnnotation) error {
|
||||
jsn, err := json.Marshal(annotation)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error marshaling zsh argument annotation: %v", err)
|
||||
}
|
||||
if c.Annotations == nil {
|
||||
c.Annotations = make(map[string]string)
|
||||
}
|
||||
c.Annotations[zshCompArgumentAnnotation] = string(jsn)
|
||||
return nil
|
||||
}
|
||||
|
||||
func zshCompGenFuncName(c *Command) string {
|
||||
if c.HasParent() {
|
||||
return zshCompGenFuncName(c.Parent()) + "_" + c.Name()
|
||||
}
|
||||
return "_" + c.Name()
|
||||
}
|
||||
|
||||
func zshCompExtractFlag(c *Command) []*pflag.Flag {
|
||||
var flags []*pflag.Flag
|
||||
c.LocalFlags().VisitAll(func(f *pflag.Flag) {
|
||||
if !f.Hidden {
|
||||
flags = append(flags, f)
|
||||
}
|
||||
})
|
||||
c.InheritedFlags().VisitAll(func(f *pflag.Flag) {
|
||||
if !f.Hidden {
|
||||
flags = append(flags, f)
|
||||
}
|
||||
})
|
||||
return flags
|
||||
}
|
||||
|
||||
// zshCompGenFlagEntryForArguments returns an entry that matches _arguments
|
||||
// zsh-completion parameters. It's too complicated to generate in a template.
|
||||
func zshCompGenFlagEntryForArguments(f *pflag.Flag) string {
|
||||
if f.Name == "" || f.Shorthand == "" {
|
||||
return zshCompGenFlagEntryForSingleOptionFlag(f)
|
||||
}
|
||||
return zshCompGenFlagEntryForMultiOptionFlag(f)
|
||||
}
|
||||
|
||||
func zshCompGenFlagEntryForSingleOptionFlag(f *pflag.Flag) string {
|
||||
var option, multiMark, extras string
|
||||
|
||||
if zshCompFlagCouldBeSpecifiedMoreThenOnce(f) {
|
||||
multiMark = "*"
|
||||
}
|
||||
|
||||
option = "--" + f.Name
|
||||
if option == "--" {
|
||||
option = "-" + f.Shorthand
|
||||
}
|
||||
extras = zshCompGenFlagEntryExtras(f)
|
||||
|
||||
return fmt.Sprintf(`'%s%s[%s]%s'`, multiMark, option, zshCompQuoteFlagDescription(f.Usage), extras)
|
||||
}
|
||||
|
||||
func zshCompGenFlagEntryForMultiOptionFlag(f *pflag.Flag) string {
|
||||
var options, parenMultiMark, curlyMultiMark, extras string
|
||||
|
||||
if zshCompFlagCouldBeSpecifiedMoreThenOnce(f) {
|
||||
parenMultiMark = "*"
|
||||
curlyMultiMark = "\\*"
|
||||
}
|
||||
|
||||
options = fmt.Sprintf(`'(%s-%s %s--%s)'{%s-%s,%s--%s}`,
|
||||
parenMultiMark, f.Shorthand, parenMultiMark, f.Name, curlyMultiMark, f.Shorthand, curlyMultiMark, f.Name)
|
||||
extras = zshCompGenFlagEntryExtras(f)
|
||||
|
||||
return fmt.Sprintf(`%s'[%s]%s'`, options, zshCompQuoteFlagDescription(f.Usage), extras)
|
||||
}
|
||||
|
||||
func zshCompGenFlagEntryExtras(f *pflag.Flag) string {
|
||||
if f.NoOptDefVal != "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
extras := ":" // allow options for flag (even without assistance)
|
||||
for key, values := range f.Annotations {
|
||||
switch key {
|
||||
case zshCompDirname:
|
||||
extras = fmt.Sprintf(":filename:_files -g %q", values[0])
|
||||
case BashCompFilenameExt:
|
||||
extras = ":filename:_files"
|
||||
for _, pattern := range values {
|
||||
extras = extras + fmt.Sprintf(` -g "%s"`, pattern)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return extras
|
||||
}
|
||||
|
||||
func zshCompFlagCouldBeSpecifiedMoreThenOnce(f *pflag.Flag) bool {
|
||||
return strings.Contains(f.Value.Type(), "Slice") ||
|
||||
strings.Contains(f.Value.Type(), "Array")
|
||||
}
|
||||
|
||||
return c.genZshCompletion(outFile, includeDesc)
|
||||
}
|
||||
|
||||
func (c *Command) genZshCompletion(w io.Writer, includeDesc bool) error {
|
||||
buf := new(bytes.Buffer)
|
||||
genZshComp(buf, c.Name(), includeDesc)
|
||||
_, err := buf.WriteTo(w)
|
||||
return err
|
||||
}
|
||||
|
||||
func genZshComp(buf io.StringWriter, name string, includeDesc bool) {
|
||||
compCmd := ShellCompRequestCmd
|
||||
if !includeDesc {
|
||||
compCmd = ShellCompNoDescRequestCmd
|
||||
}
|
||||
WriteStringAndCheck(buf, fmt.Sprintf(`#compdef _%[1]s %[1]s
|
||||
|
||||
# zsh completion for %-36[1]s -*- shell-script -*-
|
||||
|
||||
__%[1]s_debug()
|
||||
{
|
||||
local file="$BASH_COMP_DEBUG_FILE"
|
||||
if [[ -n ${file} ]]; then
|
||||
echo "$*" >> "${file}"
|
||||
fi
|
||||
}
|
||||
|
||||
_%[1]s()
|
||||
{
|
||||
local shellCompDirectiveError=%[3]d
|
||||
local shellCompDirectiveNoSpace=%[4]d
|
||||
local shellCompDirectiveNoFileComp=%[5]d
|
||||
local shellCompDirectiveFilterFileExt=%[6]d
|
||||
local shellCompDirectiveFilterDirs=%[7]d
|
||||
|
||||
local lastParam lastChar flagPrefix requestComp out directive compCount comp lastComp
|
||||
local -a completions
|
||||
|
||||
__%[1]s_debug "\n========= starting completion logic =========="
|
||||
__%[1]s_debug "CURRENT: ${CURRENT}, words[*]: ${words[*]}"
|
||||
|
||||
# The user could have moved the cursor backwards on the command-line.
|
||||
# We need to trigger completion from the $CURRENT location, so we need
|
||||
# to truncate the command-line ($words) up to the $CURRENT location.
|
||||
# (We cannot use $CURSOR as its value does not work when a command is an alias.)
|
||||
words=("${=words[1,CURRENT]}")
|
||||
__%[1]s_debug "Truncated words[*]: ${words[*]},"
|
||||
|
||||
lastParam=${words[-1]}
|
||||
lastChar=${lastParam[-1]}
|
||||
__%[1]s_debug "lastParam: ${lastParam}, lastChar: ${lastChar}"
|
||||
|
||||
# For zsh, when completing a flag with an = (e.g., %[1]s -n=<TAB>)
|
||||
# completions must be prefixed with the flag
|
||||
setopt local_options BASH_REMATCH
|
||||
if [[ "${lastParam}" =~ '-.*=' ]]; then
|
||||
# We are dealing with a flag with an =
|
||||
flagPrefix="-P ${BASH_REMATCH}"
|
||||
fi
|
||||
|
||||
# Prepare the command to obtain completions
|
||||
requestComp="${words[1]} %[2]s ${words[2,-1]}"
|
||||
if [ "${lastChar}" = "" ]; then
|
||||
# If the last parameter is complete (there is a space following it)
|
||||
# We add an extra empty parameter so we can indicate this to the go completion code.
|
||||
__%[1]s_debug "Adding extra empty parameter"
|
||||
requestComp="${requestComp} \"\""
|
||||
fi
|
||||
|
||||
__%[1]s_debug "About to call: eval ${requestComp}"
|
||||
|
||||
# Use eval to handle any environment variables and such
|
||||
out=$(eval ${requestComp} 2>/dev/null)
|
||||
__%[1]s_debug "completion output: ${out}"
|
||||
|
||||
# Extract the directive integer following a : from the last line
|
||||
local lastLine
|
||||
while IFS='\n' read -r line; do
|
||||
lastLine=${line}
|
||||
done < <(printf "%%s\n" "${out[@]}")
|
||||
__%[1]s_debug "last line: ${lastLine}"
|
||||
|
||||
if [ "${lastLine[1]}" = : ]; then
|
||||
directive=${lastLine[2,-1]}
|
||||
# Remove the directive including the : and the newline
|
||||
local suffix
|
||||
(( suffix=${#lastLine}+2))
|
||||
out=${out[1,-$suffix]}
|
||||
else
|
||||
# There is no directive specified. Leave $out as is.
|
||||
__%[1]s_debug "No directive found. Setting do default"
|
||||
directive=0
|
||||
fi
|
||||
|
||||
__%[1]s_debug "directive: ${directive}"
|
||||
__%[1]s_debug "completions: ${out}"
|
||||
__%[1]s_debug "flagPrefix: ${flagPrefix}"
|
||||
|
||||
if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then
|
||||
__%[1]s_debug "Completion received error. Ignoring completions."
|
||||
return
|
||||
fi
|
||||
|
||||
compCount=0
|
||||
while IFS='\n' read -r comp; do
|
||||
if [ -n "$comp" ]; then
|
||||
# If requested, completions are returned with a description.
|
||||
# The description is preceded by a TAB character.
|
||||
# For zsh's _describe, we need to use a : instead of a TAB.
|
||||
# We first need to escape any : as part of the completion itself.
|
||||
comp=${comp//:/\\:}
|
||||
|
||||
local tab=$(printf '\t')
|
||||
comp=${comp//$tab/:}
|
||||
|
||||
((compCount++))
|
||||
__%[1]s_debug "Adding completion: ${comp}"
|
||||
completions+=${comp}
|
||||
lastComp=$comp
|
||||
fi
|
||||
done < <(printf "%%s\n" "${out[@]}")
|
||||
|
||||
if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then
|
||||
# File extension filtering
|
||||
local filteringCmd
|
||||
filteringCmd='_files'
|
||||
for filter in ${completions[@]}; do
|
||||
if [ ${filter[1]} != '*' ]; then
|
||||
# zsh requires a glob pattern to do file filtering
|
||||
filter="\*.$filter"
|
||||
fi
|
||||
filteringCmd+=" -g $filter"
|
||||
done
|
||||
filteringCmd+=" ${flagPrefix}"
|
||||
|
||||
__%[1]s_debug "File filtering command: $filteringCmd"
|
||||
_arguments '*:filename:'"$filteringCmd"
|
||||
elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then
|
||||
# File completion for directories only
|
||||
local subDir
|
||||
subdir="${completions[1]}"
|
||||
if [ -n "$subdir" ]; then
|
||||
__%[1]s_debug "Listing directories in $subdir"
|
||||
pushd "${subdir}" >/dev/null 2>&1
|
||||
else
|
||||
__%[1]s_debug "Listing directories in ."
|
||||
fi
|
||||
|
||||
_arguments '*:dirname:_files -/'" ${flagPrefix}"
|
||||
if [ -n "$subdir" ]; then
|
||||
popd >/dev/null 2>&1
|
||||
fi
|
||||
elif [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ] && [ ${compCount} -eq 1 ]; then
|
||||
__%[1]s_debug "Activating nospace."
|
||||
# We can use compadd here as there is no description when
|
||||
# there is only one completion.
|
||||
compadd -S '' "${lastComp}"
|
||||
elif [ ${compCount} -eq 0 ]; then
|
||||
if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then
|
||||
__%[1]s_debug "deactivating file completion"
|
||||
else
|
||||
# Perform file completion
|
||||
__%[1]s_debug "activating file completion"
|
||||
_arguments '*:filename:_files'" ${flagPrefix}"
|
||||
fi
|
||||
else
|
||||
_describe "completions" completions $(echo $flagPrefix)
|
||||
fi
|
||||
}
|
||||
|
||||
# don't run the completion function when being source-ed or eval-ed
|
||||
if [ "$funcstack[1]" = "_%[1]s" ]; then
|
||||
_%[1]s
|
||||
fi
|
||||
`, name, compCmd,
|
||||
ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,
|
||||
ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))
|
||||
func zshCompQuoteFlagDescription(s string) string {
|
||||
return strings.Replace(s, "'", `'\''`, -1)
|
||||
}
|
||||
|
@ -1,48 +1,39 @@
|
||||
## Generating Zsh Completion For Your cobra.Command
|
||||
|
||||
Please refer to [Shell Completions](shell_completions.md) for details.
|
||||
|
||||
## Zsh completions standardization
|
||||
|
||||
Cobra 1.1 standardized its zsh completion support to align it with its other shell completions. Although the API was kept backwards-compatible, some small changes in behavior were introduced.
|
||||
|
||||
### Deprecation summary
|
||||
|
||||
See further below for more details on these deprecations.
|
||||
|
||||
* `cmd.MarkZshCompPositionalArgumentFile(pos, []string{})` is no longer needed. It is therefore **deprecated** and silently ignored.
|
||||
* `cmd.MarkZshCompPositionalArgumentFile(pos, glob[])` is **deprecated** and silently ignored.
|
||||
* Instead use `ValidArgsFunction` with `ShellCompDirectiveFilterFileExt`.
|
||||
* `cmd.MarkZshCompPositionalArgumentWords()` is **deprecated** and silently ignored.
|
||||
* Instead use `ValidArgsFunction`.
|
||||
|
||||
### Behavioral changes
|
||||
|
||||
**Noun completion**
|
||||
|Old behavior|New behavior|
|
||||
|---|---|
|
||||
|No file completion by default (opposite of bash)|File completion by default; use `ValidArgsFunction` with `ShellCompDirectiveNoFileComp` to turn off file completion on a per-argument basis|
|
||||
|Completion of flag names without the `-` prefix having been typed|Flag names are only completed if the user has typed the first `-`|
|
||||
`cmd.MarkZshCompPositionalArgumentFile(pos, []string{})` used to turn on file completion on a per-argument position basis|File completion for all arguments by default; `cmd.MarkZshCompPositionalArgumentFile()` is **deprecated** and silently ignored|
|
||||
|`cmd.MarkZshCompPositionalArgumentFile(pos, glob[])` used to turn on file completion **with glob filtering** on a per-argument position basis (zsh-specific)|`cmd.MarkZshCompPositionalArgumentFile()` is **deprecated** and silently ignored; use `ValidArgsFunction` with `ShellCompDirectiveFilterFileExt` for file **extension** filtering (not full glob filtering)|
|
||||
|`cmd.MarkZshCompPositionalArgumentWords(pos, words[])` used to provide completion choices on a per-argument position basis (zsh-specific)|`cmd.MarkZshCompPositionalArgumentWords()` is **deprecated** and silently ignored; use `ValidArgsFunction` to achieve the same behavior|
|
||||
|
||||
**Flag-value completion**
|
||||
|
||||
|Old behavior|New behavior|
|
||||
|---|---|
|
||||
|No file completion by default (opposite of bash)|File completion by default; use `RegisterFlagCompletionFunc()` with `ShellCompDirectiveNoFileComp` to turn off file completion|
|
||||
|`cmd.MarkFlagFilename(flag, []string{})` and similar used to turn on file completion|File completion by default; `cmd.MarkFlagFilename(flag, []string{})` no longer needed in this context and silently ignored|
|
||||
|`cmd.MarkFlagFilename(flag, glob[])` used to turn on file completion **with glob filtering** (syntax of `[]string{"*.yaml", "*.yml"}` incompatible with bash)|Will continue to work, however, support for bash syntax is added and should be used instead so as to work for all shells (`[]string{"yaml", "yml"}`)|
|
||||
|`cmd.MarkFlagDirname(flag)` only completes directories (zsh-specific)|Has been added for all shells|
|
||||
|Completion of a flag name does not repeat, unless flag is of type `*Array` or `*Slice` (not supported by bash)|Retained for `zsh` and added to `fish`|
|
||||
|Completion of a flag name does not provide the `=` form (unlike bash)|Retained for `zsh` and added to `fish`|
|
||||
|
||||
**Improvements**
|
||||
|
||||
* Custom completion support (`ValidArgsFunction` and `RegisterFlagCompletionFunc()`)
|
||||
* File completion by default if no other completions found
|
||||
* Handling of required flags
|
||||
* File extension filtering no longer mutually exclusive with bash usage
|
||||
* Completion of directory names *within* another directory
|
||||
* Support for `=` form of flags
|
||||
## Generating Zsh Completion for your cobra.Command
|
||||
|
||||
Cobra supports native Zsh completion generated from the root `cobra.Command`.
|
||||
The generated completion script should be put somewhere in your `$fpath` named
|
||||
`_<YOUR COMMAND>`.
|
||||
|
||||
### What's Supported
|
||||
|
||||
* Completion for all non-hidden subcommands using their `.Short` description.
|
||||
* Completion for all non-hidden flags using the following rules:
|
||||
* Filename completion works by marking the flag with `cmd.MarkFlagFilename...`
|
||||
family of commands.
|
||||
* The requirement for argument to the flag is decided by the `.NoOptDefVal`
|
||||
flag value - if it's empty then completion will expect an argument.
|
||||
* Flags of one of the various `*Array` and `*Slice` types supports multiple
|
||||
specifications (with or without argument depending on the specific type).
|
||||
* Completion of positional arguments using the following rules:
|
||||
* Argument position for all options below starts at `1`. If argument position
|
||||
`0` is requested it will raise an error.
|
||||
* Use `command.MarkZshCompPositionalArgumentFile` to complete filenames. Glob
|
||||
patterns (e.g. `"*.log"`) are optional - if not specified it will offer to
|
||||
complete all file types.
|
||||
* Use `command.MarkZshCompPositionalArgumentWords` to offer specific words for
|
||||
completion. At least one word is required.
|
||||
* It's possible to specify completion for some arguments and leave some
|
||||
unspecified (e.g. offer words for second argument but nothing for first
|
||||
argument). This will cause no completion for first argument but words
|
||||
completion for second argument.
|
||||
* If no argument completion was specified for 1st argument (but optionally was
|
||||
specified for 2nd) and the command has `ValidArgs` it will be used as
|
||||
completion options for 1st argument.
|
||||
* Argument completions only offered for commands with no subcommands.
|
||||
|
||||
### What's not yet Supported
|
||||
|
||||
* Custom completion scripts are not supported yet (We should probably create zsh
|
||||
specific one, doesn't make sense to re-use the bash one as the functions will
|
||||
be different).
|
||||
* Whatever other feature you're looking for and doesn't exist :)
|
||||
|
@ -1,173 +0,0 @@
|
||||
// Copyright 2020 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package cpu
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// Minimal copy of functionality from x/sys/unix so the cpu package can call
|
||||
// sysctl without depending on x/sys/unix.
|
||||
|
||||
const (
|
||||
_CTL_QUERY = -2
|
||||
|
||||
_SYSCTL_VERS_1 = 0x1000000
|
||||
)
|
||||
|
||||
var _zero uintptr
|
||||
|
||||
func sysctl(mib []int32, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) {
|
||||
var _p0 unsafe.Pointer
|
||||
if len(mib) > 0 {
|
||||
_p0 = unsafe.Pointer(&mib[0])
|
||||
} else {
|
||||
_p0 = unsafe.Pointer(&_zero)
|
||||
}
|
||||
_, _, errno := syscall.Syscall6(
|
||||
syscall.SYS___SYSCTL,
|
||||
uintptr(_p0),
|
||||
uintptr(len(mib)),
|
||||
uintptr(unsafe.Pointer(old)),
|
||||
uintptr(unsafe.Pointer(oldlen)),
|
||||
uintptr(unsafe.Pointer(new)),
|
||||
uintptr(newlen))
|
||||
if errno != 0 {
|
||||
return errno
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type sysctlNode struct {
|
||||
Flags uint32
|
||||
Num int32
|
||||
Name [32]int8
|
||||
Ver uint32
|
||||
__rsvd uint32
|
||||
Un [16]byte
|
||||
_sysctl_size [8]byte
|
||||
_sysctl_func [8]byte
|
||||
_sysctl_parent [8]byte
|
||||
_sysctl_desc [8]byte
|
||||
}
|
||||
|
||||
func sysctlNodes(mib []int32) ([]sysctlNode, error) {
|
||||
var olen uintptr
|
||||
|
||||
// Get a list of all sysctl nodes below the given MIB by performing
|
||||
// a sysctl for the given MIB with CTL_QUERY appended.
|
||||
mib = append(mib, _CTL_QUERY)
|
||||
qnode := sysctlNode{Flags: _SYSCTL_VERS_1}
|
||||
qp := (*byte)(unsafe.Pointer(&qnode))
|
||||
sz := unsafe.Sizeof(qnode)
|
||||
if err := sysctl(mib, nil, &olen, qp, sz); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Now that we know the size, get the actual nodes.
|
||||
nodes := make([]sysctlNode, olen/sz)
|
||||
np := (*byte)(unsafe.Pointer(&nodes[0]))
|
||||
if err := sysctl(mib, np, &olen, qp, sz); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
func nametomib(name string) ([]int32, error) {
|
||||
// Split name into components.
|
||||
var parts []string
|
||||
last := 0
|
||||
for i := 0; i < len(name); i++ {
|
||||
if name[i] == '.' {
|
||||
parts = append(parts, name[last:i])
|
||||
last = i + 1
|
||||
}
|
||||
}
|
||||
parts = append(parts, name[last:])
|
||||
|
||||
mib := []int32{}
|
||||
// Discover the nodes and construct the MIB OID.
|
||||
for partno, part := range parts {
|
||||
nodes, err := sysctlNodes(mib)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, node := range nodes {
|
||||
n := make([]byte, 0)
|
||||
for i := range node.Name {
|
||||
if node.Name[i] != 0 {
|
||||
n = append(n, byte(node.Name[i]))
|
||||
}
|
||||
}
|
||||
if string(n) == part {
|
||||
mib = append(mib, int32(node.Num))
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(mib) != partno+1 {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return mib, nil
|
||||
}
|
||||
|
||||
// aarch64SysctlCPUID is struct aarch64_sysctl_cpu_id from NetBSD's <aarch64/armreg.h>
|
||||
type aarch64SysctlCPUID struct {
|
||||
midr uint64 /* Main ID Register */
|
||||
revidr uint64 /* Revision ID Register */
|
||||
mpidr uint64 /* Multiprocessor Affinity Register */
|
||||
aa64dfr0 uint64 /* A64 Debug Feature Register 0 */
|
||||
aa64dfr1 uint64 /* A64 Debug Feature Register 1 */
|
||||
aa64isar0 uint64 /* A64 Instruction Set Attribute Register 0 */
|
||||
aa64isar1 uint64 /* A64 Instruction Set Attribute Register 1 */
|
||||
aa64mmfr0 uint64 /* A64 Memory Model Feature Register 0 */
|
||||
aa64mmfr1 uint64 /* A64 Memory Model Feature Register 1 */
|
||||
aa64mmfr2 uint64 /* A64 Memory Model Feature Register 2 */
|
||||
aa64pfr0 uint64 /* A64 Processor Feature Register 0 */
|
||||
aa64pfr1 uint64 /* A64 Processor Feature Register 1 */
|
||||
aa64zfr0 uint64 /* A64 SVE Feature ID Register 0 */
|
||||
mvfr0 uint32 /* Media and VFP Feature Register 0 */
|
||||
mvfr1 uint32 /* Media and VFP Feature Register 1 */
|
||||
mvfr2 uint32 /* Media and VFP Feature Register 2 */
|
||||
pad uint32
|
||||
clidr uint64 /* Cache Level ID Register */
|
||||
ctr uint64 /* Cache Type Register */
|
||||
}
|
||||
|
||||
func sysctlCPUID(name string) (*aarch64SysctlCPUID, error) {
|
||||
mib, err := nametomib(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
out := aarch64SysctlCPUID{}
|
||||
n := unsafe.Sizeof(out)
|
||||
_, _, errno := syscall.Syscall6(
|
||||
syscall.SYS___SYSCTL,
|
||||
uintptr(unsafe.Pointer(&mib[0])),
|
||||
uintptr(len(mib)),
|
||||
uintptr(unsafe.Pointer(&out)),
|
||||
uintptr(unsafe.Pointer(&n)),
|
||||
uintptr(0),
|
||||
uintptr(0))
|
||||
if errno != 0 {
|
||||
return nil, errno
|
||||
}
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
func doinit() {
|
||||
cpuid, err := sysctlCPUID("machdep.cpu0.cpu_id")
|
||||
if err != nil {
|
||||
setMinimalFeatures()
|
||||
return
|
||||
}
|
||||
parseARM64SystemRegisters(cpuid.aa64isar0, cpuid.aa64isar1, cpuid.aa64pfr0)
|
||||
|
||||
Initialized = true
|
||||
}
|
@ -1,12 +0,0 @@
|
||||
// Copyright 2020 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// +build !linux
|
||||
// +build mips64 mips64le
|
||||
|
||||
package cpu
|
||||
|
||||
func archInit() {
|
||||
Initialized = true
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue