id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
13,600
ikeikeikeike/go-sitemap-generator
stm/location.go
Filesize
func (loc *Location) Filesize() int64 { f, _ := os.Open(loc.Path()) defer f.Close() fi, err := f.Stat() if err != nil { return 0 } return fi.Size() }
go
func (loc *Location) Filesize() int64 { f, _ := os.Open(loc.Path()) defer f.Close() fi, err := f.Stat() if err != nil { return 0 } return fi.Size() }
[ "func", "(", "loc", "*", "Location", ")", "Filesize", "(", ")", "int64", "{", "f", ",", "_", ":=", "os", ".", "Open", "(", "loc", ".", "Path", "(", ")", ")", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "fi", ",", "err", ":=", "f", ".", "Stat", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", "\n", "}", "\n\n", "return", "fi", ".", "Size", "(", ")", "\n", "}" ]
// Filesize returns file size this struct has.
[ "Filesize", "returns", "file", "size", "this", "struct", "has", "." ]
c473e35ca5f0ce3059e2417fa95959adfd3428ce
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/location.go#L71-L81
13,601
ikeikeikeike/go-sitemap-generator
stm/location.go
Filename
func (loc *Location) Filename() string { nmr := loc.Namer() if loc.filename == "" && nmr == nil { log.Fatal("[F] No filename or namer set") } if loc.filename == "" { loc.filename = nmr.String() if !loc.opts.compress { newName := reGzip.ReplaceAllString(loc.filename, "") loc.filename = newName } } return loc.filename }
go
func (loc *Location) Filename() string { nmr := loc.Namer() if loc.filename == "" && nmr == nil { log.Fatal("[F] No filename or namer set") } if loc.filename == "" { loc.filename = nmr.String() if !loc.opts.compress { newName := reGzip.ReplaceAllString(loc.filename, "") loc.filename = newName } } return loc.filename }
[ "func", "(", "loc", "*", "Location", ")", "Filename", "(", ")", "string", "{", "nmr", ":=", "loc", ".", "Namer", "(", ")", "\n", "if", "loc", ".", "filename", "==", "\"", "\"", "&&", "nmr", "==", "nil", "{", "log", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "loc", ".", "filename", "==", "\"", "\"", "{", "loc", ".", "filename", "=", "nmr", ".", "String", "(", ")", "\n\n", "if", "!", "loc", ".", "opts", ".", "compress", "{", "newName", ":=", "reGzip", ".", "ReplaceAllString", "(", "loc", ".", "filename", ",", "\"", "\"", ")", "\n", "loc", ".", "filename", "=", "newName", "\n", "}", "\n", "}", "\n", "return", "loc", ".", "filename", "\n", "}" ]
// Filename returns sitemap filename.
[ "Filename", "returns", "sitemap", "filename", "." ]
c473e35ca5f0ce3059e2417fa95959adfd3428ce
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/location.go#L92-L107
13,602
ikeikeikeike/go-sitemap-generator
stm/location.go
ReserveName
func (loc *Location) ReserveName() string { nmr := loc.Namer() if nmr != nil { loc.Filename() nmr.Next() } return loc.filename }
go
func (loc *Location) ReserveName() string { nmr := loc.Namer() if nmr != nil { loc.Filename() nmr.Next() } return loc.filename }
[ "func", "(", "loc", "*", "Location", ")", "ReserveName", "(", ")", "string", "{", "nmr", ":=", "loc", ".", "Namer", "(", ")", "\n", "if", "nmr", "!=", "nil", "{", "loc", ".", "Filename", "(", ")", "\n", "nmr", ".", "Next", "(", ")", "\n", "}", "\n\n", "return", "loc", ".", "filename", "\n", "}" ]
// ReserveName returns that sets filename if this struct didn't keep filename and // it returns reserved filename if this struct keeps filename also.
[ "ReserveName", "returns", "that", "sets", "filename", "if", "this", "struct", "didn", "t", "keep", "filename", "and", "it", "returns", "reserved", "filename", "if", "this", "struct", "keeps", "filename", "also", "." ]
c473e35ca5f0ce3059e2417fa95959adfd3428ce
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/location.go#L111-L119
13,603
ikeikeikeike/go-sitemap-generator
stm/location.go
Write
func (loc *Location) Write(data []byte, linkCount int) { loc.opts.adp.Write(loc, data) if !loc.IsVerbose() { return } output := loc.Summary(linkCount) if output != "" { println(output) } }
go
func (loc *Location) Write(data []byte, linkCount int) { loc.opts.adp.Write(loc, data) if !loc.IsVerbose() { return } output := loc.Summary(linkCount) if output != "" { println(output) } }
[ "func", "(", "loc", "*", "Location", ")", "Write", "(", "data", "[", "]", "byte", ",", "linkCount", "int", ")", "{", "loc", ".", "opts", ".", "adp", ".", "Write", "(", "loc", ",", "data", ")", "\n", "if", "!", "loc", ".", "IsVerbose", "(", ")", "{", "return", "\n", "}", "\n\n", "output", ":=", "loc", ".", "Summary", "(", "linkCount", ")", "\n", "if", "output", "!=", "\"", "\"", "{", "println", "(", "output", ")", "\n", "}", "\n", "}" ]
// Write writes sitemap and index files that used from Adapter interface.
[ "Write", "writes", "sitemap", "and", "index", "files", "that", "used", "from", "Adapter", "interface", "." ]
c473e35ca5f0ce3059e2417fa95959adfd3428ce
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/location.go#L135-L146
13,604
ikeikeikeike/go-sitemap-generator
stm/location.go
Summary
func (loc *Location) Summary(linkCount int) string { nmr := loc.Namer() if nmr.IsStart() { return "" } out := fmt.Sprintf("%s '%d' links", loc.PathInPublic(), linkCount) size := loc.Filesize() if size <= 0 { return out } return fmt.Sprintf("%s / %d bytes", out, size) }
go
func (loc *Location) Summary(linkCount int) string { nmr := loc.Namer() if nmr.IsStart() { return "" } out := fmt.Sprintf("%s '%d' links", loc.PathInPublic(), linkCount) size := loc.Filesize() if size <= 0 { return out } return fmt.Sprintf("%s / %d bytes", out, size) }
[ "func", "(", "loc", "*", "Location", ")", "Summary", "(", "linkCount", "int", ")", "string", "{", "nmr", ":=", "loc", ".", "Namer", "(", ")", "\n", "if", "nmr", ".", "IsStart", "(", ")", "{", "return", "\"", "\"", "\n", "}", "\n\n", "out", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "loc", ".", "PathInPublic", "(", ")", ",", "linkCount", ")", "\n\n", "size", ":=", "loc", ".", "Filesize", "(", ")", "\n", "if", "size", "<=", "0", "{", "return", "out", "\n", "}", "\n\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "out", ",", "size", ")", "\n", "}" ]
// Summary outputs to generated file summary for console.
[ "Summary", "outputs", "to", "generated", "file", "summary", "for", "console", "." ]
c473e35ca5f0ce3059e2417fa95959adfd3428ce
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/location.go#L149-L164
13,605
ikeikeikeike/go-sitemap-generator
stm/namer.go
NewNamer
func NewNamer(opts *NOpts) *Namer { if opts.extension == "" { opts.extension = ".xml.gz" } namer := &Namer{opts: opts} namer.Reset() return namer }
go
func NewNamer(opts *NOpts) *Namer { if opts.extension == "" { opts.extension = ".xml.gz" } namer := &Namer{opts: opts} namer.Reset() return namer }
[ "func", "NewNamer", "(", "opts", "*", "NOpts", ")", "*", "Namer", "{", "if", "opts", ".", "extension", "==", "\"", "\"", "{", "opts", ".", "extension", "=", "\"", "\"", "\n", "}", "\n\n", "namer", ":=", "&", "Namer", "{", "opts", ":", "opts", "}", "\n", "namer", ".", "Reset", "(", ")", "\n", "return", "namer", "\n", "}" ]
// NewNamer returns created the Namer's pointer
[ "NewNamer", "returns", "created", "the", "Namer", "s", "pointer" ]
c473e35ca5f0ce3059e2417fa95959adfd3428ce
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/namer.go#L9-L17
13,606
ikeikeikeike/go-sitemap-generator
stm/namer.go
String
func (n *Namer) String() string { ext := n.opts.extension if n.count == 0 { return fmt.Sprintf("%s%s", n.opts.base, ext) } return fmt.Sprintf("%s%d%s", n.opts.base, n.count, ext) }
go
func (n *Namer) String() string { ext := n.opts.extension if n.count == 0 { return fmt.Sprintf("%s%s", n.opts.base, ext) } return fmt.Sprintf("%s%d%s", n.opts.base, n.count, ext) }
[ "func", "(", "n", "*", "Namer", ")", "String", "(", ")", "string", "{", "ext", ":=", "n", ".", "opts", ".", "extension", "\n", "if", "n", ".", "count", "==", "0", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "n", ".", "opts", ".", "base", ",", "ext", ")", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "n", ".", "opts", ".", "base", ",", "n", ".", "count", ",", "ext", ")", "\n", "}" ]
// String returns that combines filename base and file extension.
[ "String", "returns", "that", "combines", "filename", "base", "and", "file", "extension", "." ]
c473e35ca5f0ce3059e2417fa95959adfd3428ce
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/namer.go#L34-L40
13,607
ikeikeikeike/go-sitemap-generator
stm/namer.go
Next
func (n *Namer) Next() *Namer { if n.IsStart() { n.count = n.opts.start } else { n.count++ } return n }
go
func (n *Namer) Next() *Namer { if n.IsStart() { n.count = n.opts.start } else { n.count++ } return n }
[ "func", "(", "n", "*", "Namer", ")", "Next", "(", ")", "*", "Namer", "{", "if", "n", ".", "IsStart", "(", ")", "{", "n", ".", "count", "=", "n", ".", "opts", ".", "start", "\n", "}", "else", "{", "n", ".", "count", "++", "\n", "}", "\n", "return", "n", "\n", "}" ]
// Next is going to go to next index for filename.
[ "Next", "is", "going", "to", "go", "to", "next", "index", "for", "filename", "." ]
c473e35ca5f0ce3059e2417fa95959adfd3428ce
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/namer.go#L53-L60
13,608
ikeikeikeike/go-sitemap-generator
stm/namer.go
Previous
func (n *Namer) Previous() *Namer { if n.IsStart() { log.Fatal("[F] Already at the start of the series") } if n.count <= n.opts.start { n.count = n.opts.zero } else { n.count-- } return n }
go
func (n *Namer) Previous() *Namer { if n.IsStart() { log.Fatal("[F] Already at the start of the series") } if n.count <= n.opts.start { n.count = n.opts.zero } else { n.count-- } return n }
[ "func", "(", "n", "*", "Namer", ")", "Previous", "(", ")", "*", "Namer", "{", "if", "n", ".", "IsStart", "(", ")", "{", "log", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "n", ".", "count", "<=", "n", ".", "opts", ".", "start", "{", "n", ".", "count", "=", "n", ".", "opts", ".", "zero", "\n", "}", "else", "{", "n", ".", "count", "--", "\n", "}", "\n", "return", "n", "\n", "}" ]
// Previous is going to go to previous index for filename.
[ "Previous", "is", "going", "to", "go", "to", "previous", "index", "for", "filename", "." ]
c473e35ca5f0ce3059e2417fa95959adfd3428ce
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/namer.go#L63-L73
13,609
ikeikeikeike/go-sitemap-generator
stm/utils.go
ToLowerString
func ToLowerString(befores []string) (afters []string) { for _, name := range befores { afters = append(afters, strings.ToLower(name)) } return afters }
go
func ToLowerString(befores []string) (afters []string) { for _, name := range befores { afters = append(afters, strings.ToLower(name)) } return afters }
[ "func", "ToLowerString", "(", "befores", "[", "]", "string", ")", "(", "afters", "[", "]", "string", ")", "{", "for", "_", ",", "name", ":=", "range", "befores", "{", "afters", "=", "append", "(", "afters", ",", "strings", ".", "ToLower", "(", "name", ")", ")", "\n", "}", "\n", "return", "afters", "\n", "}" ]
// ToLowerString converts lower strings from including capital or upper strings.
[ "ToLowerString", "converts", "lower", "strings", "from", "including", "capital", "or", "upper", "strings", "." ]
c473e35ca5f0ce3059e2417fa95959adfd3428ce
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/utils.go#L165-L170
13,610
ikeikeikeike/go-sitemap-generator
stm/utils.go
spaceDecompose
func spaceDecompose(str string) (space, key string) { colon := strings.IndexByte(str, ':') if colon == -1 { return "", str } return str[:colon], str[colon+1:] }
go
func spaceDecompose(str string) (space, key string) { colon := strings.IndexByte(str, ':') if colon == -1 { return "", str } return str[:colon], str[colon+1:] }
[ "func", "spaceDecompose", "(", "str", "string", ")", "(", "space", ",", "key", "string", ")", "{", "colon", ":=", "strings", ".", "IndexByte", "(", "str", ",", "':'", ")", "\n", "if", "colon", "==", "-", "1", "{", "return", "\"", "\"", ",", "str", "\n", "}", "\n", "return", "str", "[", ":", "colon", "]", ",", "str", "[", "colon", "+", "1", ":", "]", "\n", "}" ]
// spaceDecompose is separating strings for the SetBuilderElementValue
[ "spaceDecompose", "is", "separating", "strings", "for", "the", "SetBuilderElementValue" ]
c473e35ca5f0ce3059e2417fa95959adfd3428ce
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/utils.go#L191-L197
13,611
ikeikeikeike/go-sitemap-generator
stm/options.go
NewOptions
func NewOptions() *Options { // Default values return &Options{ defaultHost: "http://www.example.com", sitemapsHost: "", // http://s3.amazonaws.com/sitemap-generator/, publicPath: "public/", sitemapsPath: "sitemaps/", filename: "sitemap", verbose: true, compress: true, pretty: false, adp: NewFileAdapter(), } }
go
func NewOptions() *Options { // Default values return &Options{ defaultHost: "http://www.example.com", sitemapsHost: "", // http://s3.amazonaws.com/sitemap-generator/, publicPath: "public/", sitemapsPath: "sitemaps/", filename: "sitemap", verbose: true, compress: true, pretty: false, adp: NewFileAdapter(), } }
[ "func", "NewOptions", "(", ")", "*", "Options", "{", "// Default values", "return", "&", "Options", "{", "defaultHost", ":", "\"", "\"", ",", "sitemapsHost", ":", "\"", "\"", ",", "// http://s3.amazonaws.com/sitemap-generator/,", "publicPath", ":", "\"", "\"", ",", "sitemapsPath", ":", "\"", "\"", ",", "filename", ":", "\"", "\"", ",", "verbose", ":", "true", ",", "compress", ":", "true", ",", "pretty", ":", "false", ",", "adp", ":", "NewFileAdapter", "(", ")", ",", "}", "\n", "}" ]
// NewOptions returns the created the Options's pointer
[ "NewOptions", "returns", "the", "created", "the", "Options", "s", "pointer" ]
c473e35ca5f0ce3059e2417fa95959adfd3428ce
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/options.go#L4-L17
13,612
ikeikeikeike/go-sitemap-generator
stm/options.go
SitemapsHost
func (opts *Options) SitemapsHost() string { if opts.sitemapsHost != "" { return opts.sitemapsHost } return opts.defaultHost }
go
func (opts *Options) SitemapsHost() string { if opts.sitemapsHost != "" { return opts.sitemapsHost } return opts.defaultHost }
[ "func", "(", "opts", "*", "Options", ")", "SitemapsHost", "(", ")", "string", "{", "if", "opts", ".", "sitemapsHost", "!=", "\"", "\"", "{", "return", "opts", ".", "sitemapsHost", "\n", "}", "\n", "return", "opts", ".", "defaultHost", "\n", "}" ]
// SitemapsHost sets that arg from Sitemap.SitemapsHost method
[ "SitemapsHost", "sets", "that", "arg", "from", "Sitemap", ".", "SitemapsHost", "method" ]
c473e35ca5f0ce3059e2417fa95959adfd3428ce
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/options.go#L80-L85
13,613
ikeikeikeike/go-sitemap-generator
stm/options.go
IndexLocation
func (opts *Options) IndexLocation() *Location { o := opts.Clone() o.nmr = NewNamer(&NOpts{base: opts.filename}) return NewLocation(o) }
go
func (opts *Options) IndexLocation() *Location { o := opts.Clone() o.nmr = NewNamer(&NOpts{base: opts.filename}) return NewLocation(o) }
[ "func", "(", "opts", "*", "Options", ")", "IndexLocation", "(", ")", "*", "Location", "{", "o", ":=", "opts", ".", "Clone", "(", ")", "\n", "o", ".", "nmr", "=", "NewNamer", "(", "&", "NOpts", "{", "base", ":", "opts", ".", "filename", "}", ")", "\n", "return", "NewLocation", "(", "o", ")", "\n", "}" ]
// IndexLocation returns the Location's pointer with // set option to arguments for BuilderIndexfile struct.
[ "IndexLocation", "returns", "the", "Location", "s", "pointer", "with", "set", "option", "to", "arguments", "for", "BuilderIndexfile", "struct", "." ]
c473e35ca5f0ce3059e2417fa95959adfd3428ce
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/options.go#L95-L99
13,614
ikeikeikeike/go-sitemap-generator
stm/options.go
Namer
func (opts *Options) Namer() *Namer { if opts.nmr == nil { opts.nmr = NewNamer(&NOpts{base: opts.filename, zero: 1, start: 2}) } return opts.nmr }
go
func (opts *Options) Namer() *Namer { if opts.nmr == nil { opts.nmr = NewNamer(&NOpts{base: opts.filename, zero: 1, start: 2}) } return opts.nmr }
[ "func", "(", "opts", "*", "Options", ")", "Namer", "(", ")", "*", "Namer", "{", "if", "opts", ".", "nmr", "==", "nil", "{", "opts", ".", "nmr", "=", "NewNamer", "(", "&", "NOpts", "{", "base", ":", "opts", ".", "filename", ",", "zero", ":", "1", ",", "start", ":", "2", "}", ")", "\n", "}", "\n", "return", "opts", ".", "nmr", "\n", "}" ]
// Namer returns Namer's pointer cache. If didn't create that yet, // It also returns created Namer's pointer.
[ "Namer", "returns", "Namer", "s", "pointer", "cache", ".", "If", "didn", "t", "create", "that", "yet", "It", "also", "returns", "created", "Namer", "s", "pointer", "." ]
c473e35ca5f0ce3059e2417fa95959adfd3428ce
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/options.go#L103-L108
13,615
ikeikeikeike/go-sitemap-generator
stm/adapter_file.go
gzip
func (adp *FileAdapter) gzip(file *os.File, data []byte) { gz := gzip.NewWriter(file) defer gz.Close() gz.Write(data) }
go
func (adp *FileAdapter) gzip(file *os.File, data []byte) { gz := gzip.NewWriter(file) defer gz.Close() gz.Write(data) }
[ "func", "(", "adp", "*", "FileAdapter", ")", "gzip", "(", "file", "*", "os", ".", "File", ",", "data", "[", "]", "byte", ")", "{", "gz", ":=", "gzip", ".", "NewWriter", "(", "file", ")", "\n", "defer", "gz", ".", "Close", "(", ")", "\n", "gz", ".", "Write", "(", "data", ")", "\n", "}" ]
// gzip will create sitemap file as a gzip.
[ "gzip", "will", "create", "sitemap", "file", "as", "a", "gzip", "." ]
c473e35ca5f0ce3059e2417fa95959adfd3428ce
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/adapter_file.go#L50-L54
13,616
ikeikeikeike/go-sitemap-generator
stm/adapter_file.go
plain
func (adp *FileAdapter) plain(file *os.File, data []byte) { file.Write(data) defer file.Close() }
go
func (adp *FileAdapter) plain(file *os.File, data []byte) { file.Write(data) defer file.Close() }
[ "func", "(", "adp", "*", "FileAdapter", ")", "plain", "(", "file", "*", "os", ".", "File", ",", "data", "[", "]", "byte", ")", "{", "file", ".", "Write", "(", "data", ")", "\n", "defer", "file", ".", "Close", "(", ")", "\n", "}" ]
// plain will create uncompressed file.
[ "plain", "will", "create", "uncompressed", "file", "." ]
c473e35ca5f0ce3059e2417fa95959adfd3428ce
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/adapter_file.go#L57-L60
13,617
ikeikeikeike/go-sitemap-generator
stm/builder_indexurl.go
NewSitemapIndexURL
func NewSitemapIndexURL(opts *Options, url URL) SitemapURL { return &sitemapIndexURL{opts: opts, data: url} }
go
func NewSitemapIndexURL(opts *Options, url URL) SitemapURL { return &sitemapIndexURL{opts: opts, data: url} }
[ "func", "NewSitemapIndexURL", "(", "opts", "*", "Options", ",", "url", "URL", ")", "SitemapURL", "{", "return", "&", "sitemapIndexURL", "{", "opts", ":", "opts", ",", "data", ":", "url", "}", "\n", "}" ]
// NewSitemapIndexURL and NewSitemapURL are almost the same behavior.
[ "NewSitemapIndexURL", "and", "NewSitemapURL", "are", "almost", "the", "same", "behavior", "." ]
c473e35ca5f0ce3059e2417fa95959adfd3428ce
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/builder_indexurl.go#L10-L12
13,618
ikeikeikeike/go-sitemap-generator
stm/builder_indexurl.go
XML
func (su *sitemapIndexURL) XML() []byte { doc := etree.NewDocument() sitemap := doc.CreateElement("sitemap") SetBuilderElementValue(sitemap, su.data, "loc") if _, ok := SetBuilderElementValue(sitemap, su.data, "lastmod"); !ok { lastmod := sitemap.CreateElement("lastmod") lastmod.SetText(time.Now().Format(time.RFC3339)) } if su.opts.pretty { doc.Indent(2) } buf := poolBuffer.Get() doc.WriteTo(buf) bytes := buf.Bytes() poolBuffer.Put(buf) return bytes }
go
func (su *sitemapIndexURL) XML() []byte { doc := etree.NewDocument() sitemap := doc.CreateElement("sitemap") SetBuilderElementValue(sitemap, su.data, "loc") if _, ok := SetBuilderElementValue(sitemap, su.data, "lastmod"); !ok { lastmod := sitemap.CreateElement("lastmod") lastmod.SetText(time.Now().Format(time.RFC3339)) } if su.opts.pretty { doc.Indent(2) } buf := poolBuffer.Get() doc.WriteTo(buf) bytes := buf.Bytes() poolBuffer.Put(buf) return bytes }
[ "func", "(", "su", "*", "sitemapIndexURL", ")", "XML", "(", ")", "[", "]", "byte", "{", "doc", ":=", "etree", ".", "NewDocument", "(", ")", "\n", "sitemap", ":=", "doc", ".", "CreateElement", "(", "\"", "\"", ")", "\n\n", "SetBuilderElementValue", "(", "sitemap", ",", "su", ".", "data", ",", "\"", "\"", ")", "\n\n", "if", "_", ",", "ok", ":=", "SetBuilderElementValue", "(", "sitemap", ",", "su", ".", "data", ",", "\"", "\"", ")", ";", "!", "ok", "{", "lastmod", ":=", "sitemap", ".", "CreateElement", "(", "\"", "\"", ")", "\n", "lastmod", ".", "SetText", "(", "time", ".", "Now", "(", ")", ".", "Format", "(", "time", ".", "RFC3339", ")", ")", "\n", "}", "\n\n", "if", "su", ".", "opts", ".", "pretty", "{", "doc", ".", "Indent", "(", "2", ")", "\n", "}", "\n", "buf", ":=", "poolBuffer", ".", "Get", "(", ")", "\n", "doc", ".", "WriteTo", "(", "buf", ")", "\n\n", "bytes", ":=", "buf", ".", "Bytes", "(", ")", "\n", "poolBuffer", ".", "Put", "(", "buf", ")", "\n\n", "return", "bytes", "\n", "}" ]
// XML and sitemapIndexURL.XML are almost the same behavior.
[ "XML", "and", "sitemapIndexURL", ".", "XML", "are", "almost", "the", "same", "behavior", "." ]
c473e35ca5f0ce3059e2417fa95959adfd3428ce
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/builder_indexurl.go#L21-L42
13,619
ikeikeikeike/go-sitemap-generator
stm/builder_file.go
NewBuilderFile
func NewBuilderFile(opts *Options, loc *Location) *BuilderFile { b := &BuilderFile{opts: opts, loc: loc} b.clear() return b }
go
func NewBuilderFile(opts *Options, loc *Location) *BuilderFile { b := &BuilderFile{opts: opts, loc: loc} b.clear() return b }
[ "func", "NewBuilderFile", "(", "opts", "*", "Options", ",", "loc", "*", "Location", ")", "*", "BuilderFile", "{", "b", ":=", "&", "BuilderFile", "{", "opts", ":", "opts", ",", "loc", ":", "loc", "}", "\n", "b", ".", "clear", "(", ")", "\n", "return", "b", "\n", "}" ]
// NewBuilderFile returns the created the BuilderFile's pointer
[ "NewBuilderFile", "returns", "the", "created", "the", "BuilderFile", "s", "pointer" ]
c473e35ca5f0ce3059e2417fa95959adfd3428ce
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/builder_file.go#L20-L24
13,620
ikeikeikeike/go-sitemap-generator
stm/builder_file.go
Add
func (b *BuilderFile) Add(url interface{}) BuilderError { u := MergeMap(url.(URL), URL{{"host", b.loc.opts.defaultHost}}, ) b.linkcnt++ smu, err := NewSitemapURL(b.opts, u) if err != nil { log.Fatalf("[F] Sitemap: %s", err) } bytes := smu.XML() if !b.isFileCanFit(bytes) { return &builderFileError{error: err, full: true} } b.content = append(b.content, bytes...) return nil }
go
func (b *BuilderFile) Add(url interface{}) BuilderError { u := MergeMap(url.(URL), URL{{"host", b.loc.opts.defaultHost}}, ) b.linkcnt++ smu, err := NewSitemapURL(b.opts, u) if err != nil { log.Fatalf("[F] Sitemap: %s", err) } bytes := smu.XML() if !b.isFileCanFit(bytes) { return &builderFileError{error: err, full: true} } b.content = append(b.content, bytes...) return nil }
[ "func", "(", "b", "*", "BuilderFile", ")", "Add", "(", "url", "interface", "{", "}", ")", "BuilderError", "{", "u", ":=", "MergeMap", "(", "url", ".", "(", "URL", ")", ",", "URL", "{", "{", "\"", "\"", ",", "b", ".", "loc", ".", "opts", ".", "defaultHost", "}", "}", ",", ")", "\n\n", "b", ".", "linkcnt", "++", "\n\n", "smu", ",", "err", ":=", "NewSitemapURL", "(", "b", ".", "opts", ",", "u", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "bytes", ":=", "smu", ".", "XML", "(", ")", "\n\n", "if", "!", "b", ".", "isFileCanFit", "(", "bytes", ")", "{", "return", "&", "builderFileError", "{", "error", ":", "err", ",", "full", ":", "true", "}", "\n", "}", "\n\n", "b", ".", "content", "=", "append", "(", "b", ".", "content", ",", "bytes", "...", ")", "\n\n", "return", "nil", "\n", "}" ]
// Add method joins old bytes with creates bytes by it calls from Sitemap.Add method.
[ "Add", "method", "joins", "old", "bytes", "with", "creates", "bytes", "by", "it", "calls", "from", "Sitemap", ".", "Add", "method", "." ]
c473e35ca5f0ce3059e2417fa95959adfd3428ce
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/builder_file.go#L36-L57
13,621
ikeikeikeike/go-sitemap-generator
stm/builder_file.go
isFileCanFit
func (b *BuilderFile) isFileCanFit(bytes []byte) bool { r := len(append(b.content, bytes...)) < MaxSitemapFilesize r = r && b.linkcnt < MaxSitemapLinks return r && b.newscnt < MaxSitemapNews }
go
func (b *BuilderFile) isFileCanFit(bytes []byte) bool { r := len(append(b.content, bytes...)) < MaxSitemapFilesize r = r && b.linkcnt < MaxSitemapLinks return r && b.newscnt < MaxSitemapNews }
[ "func", "(", "b", "*", "BuilderFile", ")", "isFileCanFit", "(", "bytes", "[", "]", "byte", ")", "bool", "{", "r", ":=", "len", "(", "append", "(", "b", ".", "content", ",", "bytes", "...", ")", ")", "<", "MaxSitemapFilesize", "\n", "r", "=", "r", "&&", "b", ".", "linkcnt", "<", "MaxSitemapLinks", "\n", "return", "r", "&&", "b", ".", "newscnt", "<", "MaxSitemapNews", "\n", "}" ]
// isFileCanFit checks bytes to bigger than consts values.
[ "isFileCanFit", "checks", "bytes", "to", "bigger", "than", "consts", "values", "." ]
c473e35ca5f0ce3059e2417fa95959adfd3428ce
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/builder_file.go#L60-L64
13,622
ikeikeikeike/go-sitemap-generator
stm/builder_file.go
XMLContent
func (b *BuilderFile) XMLContent() []byte { c := bytes.Join(bytes.Fields(XMLHeader), []byte(" ")) c = append(append(c, b.Content()...), XMLFooter...) return c }
go
func (b *BuilderFile) XMLContent() []byte { c := bytes.Join(bytes.Fields(XMLHeader), []byte(" ")) c = append(append(c, b.Content()...), XMLFooter...) return c }
[ "func", "(", "b", "*", "BuilderFile", ")", "XMLContent", "(", ")", "[", "]", "byte", "{", "c", ":=", "bytes", ".", "Join", "(", "bytes", ".", "Fields", "(", "XMLHeader", ")", ",", "[", "]", "byte", "(", "\"", "\"", ")", ")", "\n", "c", "=", "append", "(", "append", "(", "c", ",", "b", ".", "Content", "(", ")", "...", ")", ",", "XMLFooter", "...", ")", "\n\n", "return", "c", "\n", "}" ]
// XMLContent will return an XML of the sitemap built
[ "XMLContent", "will", "return", "an", "XML", "of", "the", "sitemap", "built" ]
c473e35ca5f0ce3059e2417fa95959adfd3428ce
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/builder_file.go#L77-L82
13,623
ikeikeikeike/go-sitemap-generator
stm/builder_file.go
Write
func (b *BuilderFile) Write() { b.loc.ReserveName() c := b.XMLContent() b.loc.Write(c, b.linkcnt) b.clear() }
go
func (b *BuilderFile) Write() { b.loc.ReserveName() c := b.XMLContent() b.loc.Write(c, b.linkcnt) b.clear() }
[ "func", "(", "b", "*", "BuilderFile", ")", "Write", "(", ")", "{", "b", ".", "loc", ".", "ReserveName", "(", ")", "\n\n", "c", ":=", "b", ".", "XMLContent", "(", ")", "\n\n", "b", ".", "loc", ".", "Write", "(", "c", ",", "b", ".", "linkcnt", ")", "\n", "b", ".", "clear", "(", ")", "\n", "}" ]
// Write will write pooled bytes with header and footer to // Location path for output sitemap file.
[ "Write", "will", "write", "pooled", "bytes", "with", "header", "and", "footer", "to", "Location", "path", "for", "output", "sitemap", "file", "." ]
c473e35ca5f0ce3059e2417fa95959adfd3428ce
https://github.com/ikeikeikeike/go-sitemap-generator/blob/c473e35ca5f0ce3059e2417fa95959adfd3428ce/stm/builder_file.go#L86-L93
13,624
agl/ed25519
extra25519/extra25519.go
PrivateKeyToCurve25519
func PrivateKeyToCurve25519(curve25519Private *[32]byte, privateKey *[64]byte) { h := sha512.New() h.Write(privateKey[:32]) digest := h.Sum(nil) digest[0] &= 248 digest[31] &= 127 digest[31] |= 64 copy(curve25519Private[:], digest) }
go
func PrivateKeyToCurve25519(curve25519Private *[32]byte, privateKey *[64]byte) { h := sha512.New() h.Write(privateKey[:32]) digest := h.Sum(nil) digest[0] &= 248 digest[31] &= 127 digest[31] |= 64 copy(curve25519Private[:], digest) }
[ "func", "PrivateKeyToCurve25519", "(", "curve25519Private", "*", "[", "32", "]", "byte", ",", "privateKey", "*", "[", "64", "]", "byte", ")", "{", "h", ":=", "sha512", ".", "New", "(", ")", "\n", "h", ".", "Write", "(", "privateKey", "[", ":", "32", "]", ")", "\n", "digest", ":=", "h", ".", "Sum", "(", "nil", ")", "\n\n", "digest", "[", "0", "]", "&=", "248", "\n", "digest", "[", "31", "]", "&=", "127", "\n", "digest", "[", "31", "]", "|=", "64", "\n\n", "copy", "(", "curve25519Private", "[", ":", "]", ",", "digest", ")", "\n", "}" ]
// PrivateKeyToCurve25519 converts an ed25519 private key into a corresponding // curve25519 private key such that the resulting curve25519 public key will // equal the result from PublicKeyToCurve25519.
[ "PrivateKeyToCurve25519", "converts", "an", "ed25519", "private", "key", "into", "a", "corresponding", "curve25519", "private", "key", "such", "that", "the", "resulting", "curve25519", "public", "key", "will", "equal", "the", "result", "from", "PublicKeyToCurve25519", "." ]
5312a61534124124185d41f09206b9fef1d88403
https://github.com/agl/ed25519/blob/5312a61534124124185d41f09206b9fef1d88403/extra25519/extra25519.go#L16-L26
13,625
agl/ed25519
extra25519/extra25519.go
PublicKeyToCurve25519
func PublicKeyToCurve25519(curve25519Public *[32]byte, publicKey *[32]byte) bool { var A edwards25519.ExtendedGroupElement if !A.FromBytes(publicKey) { return false } // A.Z = 1 as a postcondition of FromBytes. var x edwards25519.FieldElement edwardsToMontgomeryX(&x, &A.Y) edwards25519.FeToBytes(curve25519Public, &x) return true }
go
func PublicKeyToCurve25519(curve25519Public *[32]byte, publicKey *[32]byte) bool { var A edwards25519.ExtendedGroupElement if !A.FromBytes(publicKey) { return false } // A.Z = 1 as a postcondition of FromBytes. var x edwards25519.FieldElement edwardsToMontgomeryX(&x, &A.Y) edwards25519.FeToBytes(curve25519Public, &x) return true }
[ "func", "PublicKeyToCurve25519", "(", "curve25519Public", "*", "[", "32", "]", "byte", ",", "publicKey", "*", "[", "32", "]", "byte", ")", "bool", "{", "var", "A", "edwards25519", ".", "ExtendedGroupElement", "\n", "if", "!", "A", ".", "FromBytes", "(", "publicKey", ")", "{", "return", "false", "\n", "}", "\n\n", "// A.Z = 1 as a postcondition of FromBytes.", "var", "x", "edwards25519", ".", "FieldElement", "\n", "edwardsToMontgomeryX", "(", "&", "x", ",", "&", "A", ".", "Y", ")", "\n", "edwards25519", ".", "FeToBytes", "(", "curve25519Public", ",", "&", "x", ")", "\n", "return", "true", "\n", "}" ]
// PublicKeyToCurve25519 converts an Ed25519 public key into the curve25519 // public key that would be generated from the same private key.
[ "PublicKeyToCurve25519", "converts", "an", "Ed25519", "public", "key", "into", "the", "curve25519", "public", "key", "that", "would", "be", "generated", "from", "the", "same", "private", "key", "." ]
5312a61534124124185d41f09206b9fef1d88403
https://github.com/agl/ed25519/blob/5312a61534124124185d41f09206b9fef1d88403/extra25519/extra25519.go#L45-L56
13,626
agl/ed25519
extra25519/extra25519.go
feBytesLE
func feBytesLE(a, b *[32]byte) int32 { equalSoFar := int32(-1) greater := int32(0) for i := uint(31); i < 32; i-- { x := int32(a[i]) y := int32(b[i]) greater = (^equalSoFar & greater) | (equalSoFar & ((x - y) >> 31)) equalSoFar = equalSoFar & (((x ^ y) - 1) >> 31) } return int32(^equalSoFar & 1 & greater) }
go
func feBytesLE(a, b *[32]byte) int32 { equalSoFar := int32(-1) greater := int32(0) for i := uint(31); i < 32; i-- { x := int32(a[i]) y := int32(b[i]) greater = (^equalSoFar & greater) | (equalSoFar & ((x - y) >> 31)) equalSoFar = equalSoFar & (((x ^ y) - 1) >> 31) } return int32(^equalSoFar & 1 & greater) }
[ "func", "feBytesLE", "(", "a", ",", "b", "*", "[", "32", "]", "byte", ")", "int32", "{", "equalSoFar", ":=", "int32", "(", "-", "1", ")", "\n", "greater", ":=", "int32", "(", "0", ")", "\n\n", "for", "i", ":=", "uint", "(", "31", ")", ";", "i", "<", "32", ";", "i", "--", "{", "x", ":=", "int32", "(", "a", "[", "i", "]", ")", "\n", "y", ":=", "int32", "(", "b", "[", "i", "]", ")", "\n\n", "greater", "=", "(", "^", "equalSoFar", "&", "greater", ")", "|", "(", "equalSoFar", "&", "(", "(", "x", "-", "y", ")", ">>", "31", ")", ")", "\n", "equalSoFar", "=", "equalSoFar", "&", "(", "(", "(", "x", "^", "y", ")", "-", "1", ")", ">>", "31", ")", "\n", "}", "\n\n", "return", "int32", "(", "^", "equalSoFar", "&", "1", "&", "greater", ")", "\n", "}" ]
// feBytesLess returns one if a <= b and zero otherwise.
[ "feBytesLess", "returns", "one", "if", "a", "<", "=", "b", "and", "zero", "otherwise", "." ]
5312a61534124124185d41f09206b9fef1d88403
https://github.com/agl/ed25519/blob/5312a61534124124185d41f09206b9fef1d88403/extra25519/extra25519.go#L74-L87
13,627
agl/ed25519
extra25519/extra25519.go
RepresentativeToPublicKey
func RepresentativeToPublicKey(publicKey, representative *[32]byte) { var rr2, v, e edwards25519.FieldElement edwards25519.FeFromBytes(&rr2, representative) edwards25519.FeSquare2(&rr2, &rr2) rr2[0]++ edwards25519.FeInvert(&rr2, &rr2) edwards25519.FeMul(&v, &edwards25519.A, &rr2) edwards25519.FeNeg(&v, &v) var v2, v3 edwards25519.FieldElement edwards25519.FeSquare(&v2, &v) edwards25519.FeMul(&v3, &v, &v2) edwards25519.FeAdd(&e, &v3, &v) edwards25519.FeMul(&v2, &v2, &edwards25519.A) edwards25519.FeAdd(&e, &v2, &e) chi(&e, &e) var eBytes [32]byte edwards25519.FeToBytes(&eBytes, &e) // eBytes[1] is either 0 (for e = 1) or 0xff (for e = -1) eIsMinus1 := int32(eBytes[1]) & 1 var negV edwards25519.FieldElement edwards25519.FeNeg(&negV, &v) edwards25519.FeCMove(&v, &negV, eIsMinus1) edwards25519.FeZero(&v2) edwards25519.FeCMove(&v2, &edwards25519.A, eIsMinus1) edwards25519.FeSub(&v, &v, &v2) edwards25519.FeToBytes(publicKey, &v) }
go
func RepresentativeToPublicKey(publicKey, representative *[32]byte) { var rr2, v, e edwards25519.FieldElement edwards25519.FeFromBytes(&rr2, representative) edwards25519.FeSquare2(&rr2, &rr2) rr2[0]++ edwards25519.FeInvert(&rr2, &rr2) edwards25519.FeMul(&v, &edwards25519.A, &rr2) edwards25519.FeNeg(&v, &v) var v2, v3 edwards25519.FieldElement edwards25519.FeSquare(&v2, &v) edwards25519.FeMul(&v3, &v, &v2) edwards25519.FeAdd(&e, &v3, &v) edwards25519.FeMul(&v2, &v2, &edwards25519.A) edwards25519.FeAdd(&e, &v2, &e) chi(&e, &e) var eBytes [32]byte edwards25519.FeToBytes(&eBytes, &e) // eBytes[1] is either 0 (for e = 1) or 0xff (for e = -1) eIsMinus1 := int32(eBytes[1]) & 1 var negV edwards25519.FieldElement edwards25519.FeNeg(&negV, &v) edwards25519.FeCMove(&v, &negV, eIsMinus1) edwards25519.FeZero(&v2) edwards25519.FeCMove(&v2, &edwards25519.A, eIsMinus1) edwards25519.FeSub(&v, &v, &v2) edwards25519.FeToBytes(publicKey, &v) }
[ "func", "RepresentativeToPublicKey", "(", "publicKey", ",", "representative", "*", "[", "32", "]", "byte", ")", "{", "var", "rr2", ",", "v", ",", "e", "edwards25519", ".", "FieldElement", "\n", "edwards25519", ".", "FeFromBytes", "(", "&", "rr2", ",", "representative", ")", "\n\n", "edwards25519", ".", "FeSquare2", "(", "&", "rr2", ",", "&", "rr2", ")", "\n", "rr2", "[", "0", "]", "++", "\n", "edwards25519", ".", "FeInvert", "(", "&", "rr2", ",", "&", "rr2", ")", "\n", "edwards25519", ".", "FeMul", "(", "&", "v", ",", "&", "edwards25519", ".", "A", ",", "&", "rr2", ")", "\n", "edwards25519", ".", "FeNeg", "(", "&", "v", ",", "&", "v", ")", "\n\n", "var", "v2", ",", "v3", "edwards25519", ".", "FieldElement", "\n", "edwards25519", ".", "FeSquare", "(", "&", "v2", ",", "&", "v", ")", "\n", "edwards25519", ".", "FeMul", "(", "&", "v3", ",", "&", "v", ",", "&", "v2", ")", "\n", "edwards25519", ".", "FeAdd", "(", "&", "e", ",", "&", "v3", ",", "&", "v", ")", "\n", "edwards25519", ".", "FeMul", "(", "&", "v2", ",", "&", "v2", ",", "&", "edwards25519", ".", "A", ")", "\n", "edwards25519", ".", "FeAdd", "(", "&", "e", ",", "&", "v2", ",", "&", "e", ")", "\n", "chi", "(", "&", "e", ",", "&", "e", ")", "\n", "var", "eBytes", "[", "32", "]", "byte", "\n", "edwards25519", ".", "FeToBytes", "(", "&", "eBytes", ",", "&", "e", ")", "\n", "// eBytes[1] is either 0 (for e = 1) or 0xff (for e = -1)", "eIsMinus1", ":=", "int32", "(", "eBytes", "[", "1", "]", ")", "&", "1", "\n", "var", "negV", "edwards25519", ".", "FieldElement", "\n", "edwards25519", ".", "FeNeg", "(", "&", "negV", ",", "&", "v", ")", "\n", "edwards25519", ".", "FeCMove", "(", "&", "v", ",", "&", "negV", ",", "eIsMinus1", ")", "\n\n", "edwards25519", ".", "FeZero", "(", "&", "v2", ")", "\n", "edwards25519", ".", "FeCMove", "(", "&", "v2", ",", "&", "edwards25519", ".", "A", ",", "eIsMinus1", ")", "\n", "edwards25519", ".", "FeSub", "(", "&", "v", ",", "&", "v", ",", "&", "v2", ")", "\n\n", "edwards25519", ".", "FeToBytes", "(", "publicKey", ",", "&", "v", ")", "\n", "}" ]
// RepresentativeToPublicKey converts a uniform representative value for a // curve25519 public key, as produced by ScalarBaseMult, to a curve25519 public // key.
[ "RepresentativeToPublicKey", "converts", "a", "uniform", "representative", "value", "for", "a", "curve25519", "public", "key", "as", "produced", "by", "ScalarBaseMult", "to", "a", "curve25519", "public", "key", "." ]
5312a61534124124185d41f09206b9fef1d88403
https://github.com/agl/ed25519/blob/5312a61534124124185d41f09206b9fef1d88403/extra25519/extra25519.go#L310-L340
13,628
agl/ed25519
edwards25519/edwards25519.go
equal
func equal(b, c int32) int32 { x := uint32(b ^ c) x-- return int32(x >> 31) }
go
func equal(b, c int32) int32 { x := uint32(b ^ c) x-- return int32(x >> 31) }
[ "func", "equal", "(", "b", ",", "c", "int32", ")", "int32", "{", "x", ":=", "uint32", "(", "b", "^", "c", ")", "\n", "x", "--", "\n", "return", "int32", "(", "x", ">>", "31", ")", "\n", "}" ]
// equal returns 1 if b == c and 0 otherwise.
[ "equal", "returns", "1", "if", "b", "==", "c", "and", "0", "otherwise", "." ]
5312a61534124124185d41f09206b9fef1d88403
https://github.com/agl/ed25519/blob/5312a61534124124185d41f09206b9fef1d88403/edwards25519/edwards25519.go#L932-L936
13,629
agl/ed25519
ed25519.go
Verify
func Verify(publicKey *[PublicKeySize]byte, message []byte, sig *[SignatureSize]byte) bool { if sig[63]&224 != 0 { return false } var A edwards25519.ExtendedGroupElement if !A.FromBytes(publicKey) { return false } edwards25519.FeNeg(&A.X, &A.X) edwards25519.FeNeg(&A.T, &A.T) h := sha512.New() h.Write(sig[:32]) h.Write(publicKey[:]) h.Write(message) var digest [64]byte h.Sum(digest[:0]) var hReduced [32]byte edwards25519.ScReduce(&hReduced, &digest) var R edwards25519.ProjectiveGroupElement var b [32]byte copy(b[:], sig[32:]) edwards25519.GeDoubleScalarMultVartime(&R, &hReduced, &A, &b) var checkR [32]byte R.ToBytes(&checkR) return subtle.ConstantTimeCompare(sig[:32], checkR[:]) == 1 }
go
func Verify(publicKey *[PublicKeySize]byte, message []byte, sig *[SignatureSize]byte) bool { if sig[63]&224 != 0 { return false } var A edwards25519.ExtendedGroupElement if !A.FromBytes(publicKey) { return false } edwards25519.FeNeg(&A.X, &A.X) edwards25519.FeNeg(&A.T, &A.T) h := sha512.New() h.Write(sig[:32]) h.Write(publicKey[:]) h.Write(message) var digest [64]byte h.Sum(digest[:0]) var hReduced [32]byte edwards25519.ScReduce(&hReduced, &digest) var R edwards25519.ProjectiveGroupElement var b [32]byte copy(b[:], sig[32:]) edwards25519.GeDoubleScalarMultVartime(&R, &hReduced, &A, &b) var checkR [32]byte R.ToBytes(&checkR) return subtle.ConstantTimeCompare(sig[:32], checkR[:]) == 1 }
[ "func", "Verify", "(", "publicKey", "*", "[", "PublicKeySize", "]", "byte", ",", "message", "[", "]", "byte", ",", "sig", "*", "[", "SignatureSize", "]", "byte", ")", "bool", "{", "if", "sig", "[", "63", "]", "&", "224", "!=", "0", "{", "return", "false", "\n", "}", "\n\n", "var", "A", "edwards25519", ".", "ExtendedGroupElement", "\n", "if", "!", "A", ".", "FromBytes", "(", "publicKey", ")", "{", "return", "false", "\n", "}", "\n", "edwards25519", ".", "FeNeg", "(", "&", "A", ".", "X", ",", "&", "A", ".", "X", ")", "\n", "edwards25519", ".", "FeNeg", "(", "&", "A", ".", "T", ",", "&", "A", ".", "T", ")", "\n\n", "h", ":=", "sha512", ".", "New", "(", ")", "\n", "h", ".", "Write", "(", "sig", "[", ":", "32", "]", ")", "\n", "h", ".", "Write", "(", "publicKey", "[", ":", "]", ")", "\n", "h", ".", "Write", "(", "message", ")", "\n", "var", "digest", "[", "64", "]", "byte", "\n", "h", ".", "Sum", "(", "digest", "[", ":", "0", "]", ")", "\n\n", "var", "hReduced", "[", "32", "]", "byte", "\n", "edwards25519", ".", "ScReduce", "(", "&", "hReduced", ",", "&", "digest", ")", "\n\n", "var", "R", "edwards25519", ".", "ProjectiveGroupElement", "\n", "var", "b", "[", "32", "]", "byte", "\n", "copy", "(", "b", "[", ":", "]", ",", "sig", "[", "32", ":", "]", ")", "\n", "edwards25519", ".", "GeDoubleScalarMultVartime", "(", "&", "R", ",", "&", "hReduced", ",", "&", "A", ",", "&", "b", ")", "\n\n", "var", "checkR", "[", "32", "]", "byte", "\n", "R", ".", "ToBytes", "(", "&", "checkR", ")", "\n", "return", "subtle", ".", "ConstantTimeCompare", "(", "sig", "[", ":", "32", "]", ",", "checkR", "[", ":", "]", ")", "==", "1", "\n", "}" ]
// Verify returns true iff sig is a valid signature of message by publicKey.
[ "Verify", "returns", "true", "iff", "sig", "is", "a", "valid", "signature", "of", "message", "by", "publicKey", "." ]
5312a61534124124185d41f09206b9fef1d88403
https://github.com/agl/ed25519/blob/5312a61534124124185d41f09206b9fef1d88403/ed25519.go#L97-L127
13,630
mkideal/cli
_examples/018-custom-parser/main.go
Parse
func (parser *myParser) Parse(s string) error { typ := reflect.TypeOf(parser.ptr) val := reflect.ValueOf(parser.ptr) if typ.Kind() == reflect.Ptr { kind := reflect.Indirect(val).Type().Kind() if kind == reflect.Struct { typElem, valElem := typ.Elem(), val.Elem() numField := valElem.NumField() for i := 0; i < numField; i++ { _, valField := typElem.Field(i), valElem.Field(i) if valField.Kind() == reflect.Int && valField.CanSet() { valField.SetInt(2) } if valField.Kind() == reflect.String && valField.CanSet() { valField.SetString("B") } } } } return nil }
go
func (parser *myParser) Parse(s string) error { typ := reflect.TypeOf(parser.ptr) val := reflect.ValueOf(parser.ptr) if typ.Kind() == reflect.Ptr { kind := reflect.Indirect(val).Type().Kind() if kind == reflect.Struct { typElem, valElem := typ.Elem(), val.Elem() numField := valElem.NumField() for i := 0; i < numField; i++ { _, valField := typElem.Field(i), valElem.Field(i) if valField.Kind() == reflect.Int && valField.CanSet() { valField.SetInt(2) } if valField.Kind() == reflect.String && valField.CanSet() { valField.SetString("B") } } } } return nil }
[ "func", "(", "parser", "*", "myParser", ")", "Parse", "(", "s", "string", ")", "error", "{", "typ", ":=", "reflect", ".", "TypeOf", "(", "parser", ".", "ptr", ")", "\n", "val", ":=", "reflect", ".", "ValueOf", "(", "parser", ".", "ptr", ")", "\n", "if", "typ", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "kind", ":=", "reflect", ".", "Indirect", "(", "val", ")", ".", "Type", "(", ")", ".", "Kind", "(", ")", "\n", "if", "kind", "==", "reflect", ".", "Struct", "{", "typElem", ",", "valElem", ":=", "typ", ".", "Elem", "(", ")", ",", "val", ".", "Elem", "(", ")", "\n", "numField", ":=", "valElem", ".", "NumField", "(", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "numField", ";", "i", "++", "{", "_", ",", "valField", ":=", "typElem", ".", "Field", "(", "i", ")", ",", "valElem", ".", "Field", "(", "i", ")", "\n", "if", "valField", ".", "Kind", "(", ")", "==", "reflect", ".", "Int", "&&", "valField", ".", "CanSet", "(", ")", "{", "valField", ".", "SetInt", "(", "2", ")", "\n", "}", "\n", "if", "valField", ".", "Kind", "(", ")", "==", "reflect", ".", "String", "&&", "valField", ".", "CanSet", "(", ")", "{", "valField", ".", "SetString", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Parse implements FlagParser.Parse interface
[ "Parse", "implements", "FlagParser", ".", "Parse", "interface" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/_examples/018-custom-parser/main.go#L19-L41
13,631
mkideal/cli
cliutil.go
HelpCommandFn
func HelpCommandFn(ctx *Context) error { var ( args = ctx.NativeArgs() parent = ctx.Command().Parent() ) if len(args) == 0 { ctx.String(parent.Usage(ctx)) return nil } var ( child = parent.Route(args) clr = ctx.Color() ) if child == nil { return fmt.Errorf("command %s not found", clr.Yellow(strings.Join(args, " "))) } ctx.String(child.Usage(ctx)) return nil }
go
func HelpCommandFn(ctx *Context) error { var ( args = ctx.NativeArgs() parent = ctx.Command().Parent() ) if len(args) == 0 { ctx.String(parent.Usage(ctx)) return nil } var ( child = parent.Route(args) clr = ctx.Color() ) if child == nil { return fmt.Errorf("command %s not found", clr.Yellow(strings.Join(args, " "))) } ctx.String(child.Usage(ctx)) return nil }
[ "func", "HelpCommandFn", "(", "ctx", "*", "Context", ")", "error", "{", "var", "(", "args", "=", "ctx", ".", "NativeArgs", "(", ")", "\n", "parent", "=", "ctx", ".", "Command", "(", ")", ".", "Parent", "(", ")", "\n", ")", "\n", "if", "len", "(", "args", ")", "==", "0", "{", "ctx", ".", "String", "(", "parent", ".", "Usage", "(", "ctx", ")", ")", "\n", "return", "nil", "\n", "}", "\n", "var", "(", "child", "=", "parent", ".", "Route", "(", "args", ")", "\n", "clr", "=", "ctx", ".", "Color", "(", ")", "\n", ")", "\n", "if", "child", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "clr", ".", "Yellow", "(", "strings", ".", "Join", "(", "args", ",", "\"", "\"", ")", ")", ")", "\n", "}", "\n", "ctx", ".", "String", "(", "child", ".", "Usage", "(", "ctx", ")", ")", "\n", "return", "nil", "\n", "}" ]
// HelpCommandFn implements buildin help command function
[ "HelpCommandFn", "implements", "buildin", "help", "command", "function" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/cliutil.go#L29-L47
13,632
mkideal/cli
cliutil.go
HelpCommand
func HelpCommand(desc string) *Command { return &Command{ Name: "help", Desc: desc, CanSubRoute: true, NoHook: true, Fn: HelpCommandFn, } }
go
func HelpCommand(desc string) *Command { return &Command{ Name: "help", Desc: desc, CanSubRoute: true, NoHook: true, Fn: HelpCommandFn, } }
[ "func", "HelpCommand", "(", "desc", "string", ")", "*", "Command", "{", "return", "&", "Command", "{", "Name", ":", "\"", "\"", ",", "Desc", ":", "desc", ",", "CanSubRoute", ":", "true", ",", "NoHook", ":", "true", ",", "Fn", ":", "HelpCommandFn", ",", "}", "\n", "}" ]
// HelpCommand returns a buildin help command
[ "HelpCommand", "returns", "a", "buildin", "help", "command" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/cliutil.go#L50-L58
13,633
mkideal/cli
cliutil.go
Daemon
func Daemon(ctx *Context, successPrefix string) error { cmd := exec.Command(os.Args[0], ctx.NativeArgs()...) serr, err := cmd.StderrPipe() if err != nil { return err } if err := cmd.Start(); err != nil { return err } reader := bufio.NewReader(serr) line, err := reader.ReadString('\n') if err != nil { return err } if strings.HasPrefix(line, successPrefix) { ctx.String(line) cmd.Process.Release() } else { cmd.Process.Kill() line = strings.TrimSuffix(line, "\n") return fmt.Errorf(line) } return nil }
go
func Daemon(ctx *Context, successPrefix string) error { cmd := exec.Command(os.Args[0], ctx.NativeArgs()...) serr, err := cmd.StderrPipe() if err != nil { return err } if err := cmd.Start(); err != nil { return err } reader := bufio.NewReader(serr) line, err := reader.ReadString('\n') if err != nil { return err } if strings.HasPrefix(line, successPrefix) { ctx.String(line) cmd.Process.Release() } else { cmd.Process.Kill() line = strings.TrimSuffix(line, "\n") return fmt.Errorf(line) } return nil }
[ "func", "Daemon", "(", "ctx", "*", "Context", ",", "successPrefix", "string", ")", "error", "{", "cmd", ":=", "exec", ".", "Command", "(", "os", ".", "Args", "[", "0", "]", ",", "ctx", ".", "NativeArgs", "(", ")", "...", ")", "\n", "serr", ",", "err", ":=", "cmd", ".", "StderrPipe", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "cmd", ".", "Start", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "reader", ":=", "bufio", ".", "NewReader", "(", "serr", ")", "\n", "line", ",", "err", ":=", "reader", ".", "ReadString", "(", "'\\n'", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "strings", ".", "HasPrefix", "(", "line", ",", "successPrefix", ")", "{", "ctx", ".", "String", "(", "line", ")", "\n", "cmd", ".", "Process", ".", "Release", "(", ")", "\n", "}", "else", "{", "cmd", ".", "Process", ".", "Kill", "(", ")", "\n", "line", "=", "strings", ".", "TrimSuffix", "(", "line", ",", "\"", "\\n", "\"", ")", "\n", "return", "fmt", ".", "Errorf", "(", "line", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Daemon startup app as a daemon process, success if result from stderr has prefix successPrefix
[ "Daemon", "startup", "app", "as", "a", "daemon", "process", "success", "if", "result", "from", "stderr", "has", "prefix", "successPrefix" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/cliutil.go#L61-L85
13,634
mkideal/cli
cliutil.go
ReadJSON
func ReadJSON(r io.Reader, argv interface{}) error { return json.NewDecoder(r).Decode(argv) }
go
func ReadJSON(r io.Reader, argv interface{}) error { return json.NewDecoder(r).Decode(argv) }
[ "func", "ReadJSON", "(", "r", "io", ".", "Reader", ",", "argv", "interface", "{", "}", ")", "error", "{", "return", "json", ".", "NewDecoder", "(", "r", ")", ".", "Decode", "(", "argv", ")", "\n", "}" ]
// ReadJSON reads data as a json structure into argv
[ "ReadJSON", "reads", "data", "as", "a", "json", "structure", "into", "argv" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/cliutil.go#L93-L95
13,635
mkideal/cli
cliutil.go
ReadJSONFromFile
func ReadJSONFromFile(filename string, argv interface{}) error { file, err := os.Open(filename) if err == nil { defer file.Close() err = ReadJSON(file, argv) } return err }
go
func ReadJSONFromFile(filename string, argv interface{}) error { file, err := os.Open(filename) if err == nil { defer file.Close() err = ReadJSON(file, argv) } return err }
[ "func", "ReadJSONFromFile", "(", "filename", "string", ",", "argv", "interface", "{", "}", ")", "error", "{", "file", ",", "err", ":=", "os", ".", "Open", "(", "filename", ")", "\n", "if", "err", "==", "nil", "{", "defer", "file", ".", "Close", "(", ")", "\n", "err", "=", "ReadJSON", "(", "file", ",", "argv", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// ReadJSONFromFile is similar to ReadJSON, but read from file
[ "ReadJSONFromFile", "is", "similar", "to", "ReadJSON", "but", "read", "from", "file" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/cliutil.go#L98-L105
13,636
mkideal/cli
cliutil.go
ReadJSONConfigFromFile
func ReadJSONConfigFromFile(filename string, argv interface{}) error { file, err := os.Open(filename) if err == nil { defer file.Close() err = ReadJSON(file, argv) } else { exe, e := os.Executable() if e != nil { return e } // allow self-config .json files to go with the executable file, #40 file, err = os.Open(filepath.Dir(exe) + string(filepath.Separator) + filename) if err == nil { defer file.Close() err = ReadJSON(file, argv) } } return err }
go
func ReadJSONConfigFromFile(filename string, argv interface{}) error { file, err := os.Open(filename) if err == nil { defer file.Close() err = ReadJSON(file, argv) } else { exe, e := os.Executable() if e != nil { return e } // allow self-config .json files to go with the executable file, #40 file, err = os.Open(filepath.Dir(exe) + string(filepath.Separator) + filename) if err == nil { defer file.Close() err = ReadJSON(file, argv) } } return err }
[ "func", "ReadJSONConfigFromFile", "(", "filename", "string", ",", "argv", "interface", "{", "}", ")", "error", "{", "file", ",", "err", ":=", "os", ".", "Open", "(", "filename", ")", "\n", "if", "err", "==", "nil", "{", "defer", "file", ".", "Close", "(", ")", "\n", "err", "=", "ReadJSON", "(", "file", ",", "argv", ")", "\n", "}", "else", "{", "exe", ",", "e", ":=", "os", ".", "Executable", "(", ")", "\n", "if", "e", "!=", "nil", "{", "return", "e", "\n", "}", "\n", "// allow self-config .json files to go with the executable file, #40", "file", ",", "err", "=", "os", ".", "Open", "(", "filepath", ".", "Dir", "(", "exe", ")", "+", "string", "(", "filepath", ".", "Separator", ")", "+", "filename", ")", "\n", "if", "err", "==", "nil", "{", "defer", "file", ".", "Close", "(", ")", "\n", "err", "=", "ReadJSON", "(", "file", ",", "argv", ")", "\n", "}", "\n", "}", "\n", "return", "err", "\n", "}" ]
// ReadJSONConfigFromFile is similar to ReadJSONFromFile, but allows reading file from where the executable file resides as well
[ "ReadJSONConfigFromFile", "is", "similar", "to", "ReadJSONFromFile", "but", "allows", "reading", "file", "from", "where", "the", "executable", "file", "resides", "as", "well" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/cliutil.go#L108-L126
13,637
mkideal/cli
_examples/012-decoder/main.go
Decode
func (d *exampleDecoder) Decode(s string) error { d.list = strings.Split(s, ",") return nil }
go
func (d *exampleDecoder) Decode(s string) error { d.list = strings.Split(s, ",") return nil }
[ "func", "(", "d", "*", "exampleDecoder", ")", "Decode", "(", "s", "string", ")", "error", "{", "d", ".", "list", "=", "strings", ".", "Split", "(", "s", ",", "\"", "\"", ")", "\n", "return", "nil", "\n", "}" ]
// Decode implements cli.Decoder interface
[ "Decode", "implements", "cli", ".", "Decoder", "interface" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/_examples/012-decoder/main.go#L15-L18
13,638
mkideal/cli
command.go
Register
func (cmd *Command) Register(child *Command) *Command { if child == nil { debug.Panicf("command `%s` try register a nil command", cmd.Name) } if !IsValidCommandName(child.Name) { debug.Panicf("illegal command name `%s`", cmd.Name) } if cmd.children == nil { cmd.children = []*Command{} } if child.parent != nil { debug.Panicf("command `%s` has been child of `%s`", child.Name, child.parent.Name) } if cmd.findChild(child.Name) != nil { debug.Panicf("repeat register child `%s` for command `%s`", child.Name, cmd.Name) } if child.Aliases != nil { for _, alias := range child.Aliases { if cmd.findChild(alias) != nil { debug.Panicf("repeat register child `%s` for command `%s`", alias, cmd.Name) } } } cmd.children = append(cmd.children, child) child.parent = cmd return child }
go
func (cmd *Command) Register(child *Command) *Command { if child == nil { debug.Panicf("command `%s` try register a nil command", cmd.Name) } if !IsValidCommandName(child.Name) { debug.Panicf("illegal command name `%s`", cmd.Name) } if cmd.children == nil { cmd.children = []*Command{} } if child.parent != nil { debug.Panicf("command `%s` has been child of `%s`", child.Name, child.parent.Name) } if cmd.findChild(child.Name) != nil { debug.Panicf("repeat register child `%s` for command `%s`", child.Name, cmd.Name) } if child.Aliases != nil { for _, alias := range child.Aliases { if cmd.findChild(alias) != nil { debug.Panicf("repeat register child `%s` for command `%s`", alias, cmd.Name) } } } cmd.children = append(cmd.children, child) child.parent = cmd return child }
[ "func", "(", "cmd", "*", "Command", ")", "Register", "(", "child", "*", "Command", ")", "*", "Command", "{", "if", "child", "==", "nil", "{", "debug", ".", "Panicf", "(", "\"", "\"", ",", "cmd", ".", "Name", ")", "\n", "}", "\n", "if", "!", "IsValidCommandName", "(", "child", ".", "Name", ")", "{", "debug", ".", "Panicf", "(", "\"", "\"", ",", "cmd", ".", "Name", ")", "\n", "}", "\n", "if", "cmd", ".", "children", "==", "nil", "{", "cmd", ".", "children", "=", "[", "]", "*", "Command", "{", "}", "\n", "}", "\n", "if", "child", ".", "parent", "!=", "nil", "{", "debug", ".", "Panicf", "(", "\"", "\"", ",", "child", ".", "Name", ",", "child", ".", "parent", ".", "Name", ")", "\n", "}", "\n", "if", "cmd", ".", "findChild", "(", "child", ".", "Name", ")", "!=", "nil", "{", "debug", ".", "Panicf", "(", "\"", "\"", ",", "child", ".", "Name", ",", "cmd", ".", "Name", ")", "\n", "}", "\n", "if", "child", ".", "Aliases", "!=", "nil", "{", "for", "_", ",", "alias", ":=", "range", "child", ".", "Aliases", "{", "if", "cmd", ".", "findChild", "(", "alias", ")", "!=", "nil", "{", "debug", ".", "Panicf", "(", "\"", "\"", ",", "alias", ",", "cmd", ".", "Name", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "cmd", ".", "children", "=", "append", "(", "cmd", ".", "children", ",", "child", ")", "\n", "child", ".", "parent", "=", "cmd", "\n\n", "return", "child", "\n", "}" ]
// Register registers a child command
[ "Register", "registers", "a", "child", "command" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/command.go#L111-L138
13,639
mkideal/cli
command.go
RegisterFunc
func (cmd *Command) RegisterFunc(name string, fn CommandFunc, argvFn ArgvFunc) *Command { return cmd.Register(&Command{Name: name, Fn: fn, Argv: argvFn}) }
go
func (cmd *Command) RegisterFunc(name string, fn CommandFunc, argvFn ArgvFunc) *Command { return cmd.Register(&Command{Name: name, Fn: fn, Argv: argvFn}) }
[ "func", "(", "cmd", "*", "Command", ")", "RegisterFunc", "(", "name", "string", ",", "fn", "CommandFunc", ",", "argvFn", "ArgvFunc", ")", "*", "Command", "{", "return", "cmd", ".", "Register", "(", "&", "Command", "{", "Name", ":", "name", ",", "Fn", ":", "fn", ",", "Argv", ":", "argvFn", "}", ")", "\n", "}" ]
// RegisterFunc registers handler as child command
[ "RegisterFunc", "registers", "handler", "as", "child", "command" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/command.go#L141-L143
13,640
mkideal/cli
command.go
RegisterTree
func (cmd *Command) RegisterTree(forest ...*CommandTree) { for _, tree := range forest { cmd.Register(tree.command) if tree.forest != nil && len(tree.forest) > 0 { tree.command.RegisterTree(tree.forest...) } } }
go
func (cmd *Command) RegisterTree(forest ...*CommandTree) { for _, tree := range forest { cmd.Register(tree.command) if tree.forest != nil && len(tree.forest) > 0 { tree.command.RegisterTree(tree.forest...) } } }
[ "func", "(", "cmd", "*", "Command", ")", "RegisterTree", "(", "forest", "...", "*", "CommandTree", ")", "{", "for", "_", ",", "tree", ":=", "range", "forest", "{", "cmd", ".", "Register", "(", "tree", ".", "command", ")", "\n", "if", "tree", ".", "forest", "!=", "nil", "&&", "len", "(", "tree", ".", "forest", ")", ">", "0", "{", "tree", ".", "command", ".", "RegisterTree", "(", "tree", ".", "forest", "...", ")", "\n", "}", "\n", "}", "\n", "}" ]
// RegisterTree registers a command tree
[ "RegisterTree", "registers", "a", "command", "tree" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/command.go#L146-L153
13,641
mkideal/cli
command.go
RunWith
func (cmd *Command) RunWith(args []string, writer io.Writer, resp http.ResponseWriter, httpMethods ...string) error { fds := []uintptr{} if writer == nil { writer = colorable.NewColorableStdout() fds = append(fds, os.Stdout.Fd()) } clr := color.Color{} colorSwitch(&clr, writer, fds...) var ctx *Context var suggestion string ctx, suggestion, err := cmd.prepare(clr, args, writer, resp, httpMethods...) if err == ExitError { return nil } if err != nil { if cmd.OnRootPrepareError != nil { err = cmd.OnRootPrepareError(err) } if err != nil { return wrapErr(err, suggestion, clr) } return nil } if ctx.command.NoHook { return ctx.command.Fn(ctx) } funcs := []func(*Context) error{ ctx.command.OnBefore, cmd.OnRootBefore, ctx.command.Fn, cmd.OnRootAfter, ctx.command.OnAfter, } for _, f := range funcs { if f != nil { if err := f(ctx); err != nil { if err == ExitError { return nil } return err } } } return nil }
go
func (cmd *Command) RunWith(args []string, writer io.Writer, resp http.ResponseWriter, httpMethods ...string) error { fds := []uintptr{} if writer == nil { writer = colorable.NewColorableStdout() fds = append(fds, os.Stdout.Fd()) } clr := color.Color{} colorSwitch(&clr, writer, fds...) var ctx *Context var suggestion string ctx, suggestion, err := cmd.prepare(clr, args, writer, resp, httpMethods...) if err == ExitError { return nil } if err != nil { if cmd.OnRootPrepareError != nil { err = cmd.OnRootPrepareError(err) } if err != nil { return wrapErr(err, suggestion, clr) } return nil } if ctx.command.NoHook { return ctx.command.Fn(ctx) } funcs := []func(*Context) error{ ctx.command.OnBefore, cmd.OnRootBefore, ctx.command.Fn, cmd.OnRootAfter, ctx.command.OnAfter, } for _, f := range funcs { if f != nil { if err := f(ctx); err != nil { if err == ExitError { return nil } return err } } } return nil }
[ "func", "(", "cmd", "*", "Command", ")", "RunWith", "(", "args", "[", "]", "string", ",", "writer", "io", ".", "Writer", ",", "resp", "http", ".", "ResponseWriter", ",", "httpMethods", "...", "string", ")", "error", "{", "fds", ":=", "[", "]", "uintptr", "{", "}", "\n", "if", "writer", "==", "nil", "{", "writer", "=", "colorable", ".", "NewColorableStdout", "(", ")", "\n", "fds", "=", "append", "(", "fds", ",", "os", ".", "Stdout", ".", "Fd", "(", ")", ")", "\n", "}", "\n", "clr", ":=", "color", ".", "Color", "{", "}", "\n", "colorSwitch", "(", "&", "clr", ",", "writer", ",", "fds", "...", ")", "\n\n", "var", "ctx", "*", "Context", "\n", "var", "suggestion", "string", "\n", "ctx", ",", "suggestion", ",", "err", ":=", "cmd", ".", "prepare", "(", "clr", ",", "args", ",", "writer", ",", "resp", ",", "httpMethods", "...", ")", "\n", "if", "err", "==", "ExitError", "{", "return", "nil", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "if", "cmd", ".", "OnRootPrepareError", "!=", "nil", "{", "err", "=", "cmd", ".", "OnRootPrepareError", "(", "err", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "wrapErr", "(", "err", ",", "suggestion", ",", "clr", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n\n", "if", "ctx", ".", "command", ".", "NoHook", "{", "return", "ctx", ".", "command", ".", "Fn", "(", "ctx", ")", "\n", "}", "\n\n", "funcs", ":=", "[", "]", "func", "(", "*", "Context", ")", "error", "{", "ctx", ".", "command", ".", "OnBefore", ",", "cmd", ".", "OnRootBefore", ",", "ctx", ".", "command", ".", "Fn", ",", "cmd", ".", "OnRootAfter", ",", "ctx", ".", "command", ".", "OnAfter", ",", "}", "\n", "for", "_", ",", "f", ":=", "range", "funcs", "{", "if", "f", "!=", "nil", "{", "if", "err", ":=", "f", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "if", "err", "==", "ExitError", "{", "return", "nil", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// RunWith runs the command with args and writer,httpMethods
[ "RunWith", "runs", "the", "command", "with", "args", "and", "writer", "httpMethods" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/command.go#L181-L229
13,642
mkideal/cli
command.go
Usage
func (cmd *Command) Usage(ctx *Context) string { if cmd.UsageFn != nil { return cmd.UsageFn() } return cmd.defaultUsageFn(ctx) }
go
func (cmd *Command) Usage(ctx *Context) string { if cmd.UsageFn != nil { return cmd.UsageFn() } return cmd.defaultUsageFn(ctx) }
[ "func", "(", "cmd", "*", "Command", ")", "Usage", "(", "ctx", "*", "Context", ")", "string", "{", "if", "cmd", ".", "UsageFn", "!=", "nil", "{", "return", "cmd", ".", "UsageFn", "(", ")", "\n", "}", "\n", "return", "cmd", ".", "defaultUsageFn", "(", "ctx", ")", "\n", "}" ]
// Usage returns the usage string of command
[ "Usage", "returns", "the", "usage", "string", "of", "command" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/command.go#L374-L379
13,643
mkideal/cli
command.go
Root
func (cmd *Command) Root() *Command { ancestor := cmd for ancestor.parent != nil { ancestor = ancestor.parent } return ancestor }
go
func (cmd *Command) Root() *Command { ancestor := cmd for ancestor.parent != nil { ancestor = ancestor.parent } return ancestor }
[ "func", "(", "cmd", "*", "Command", ")", "Root", "(", ")", "*", "Command", "{", "ancestor", ":=", "cmd", "\n", "for", "ancestor", ".", "parent", "!=", "nil", "{", "ancestor", "=", "ancestor", ".", "parent", "\n", "}", "\n", "return", "ancestor", "\n", "}" ]
// Root returns command's ancestor
[ "Root", "returns", "command", "s", "ancestor" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/command.go#L447-L453
13,644
mkideal/cli
command.go
Route
func (cmd *Command) Route(router []string) *Command { child, end := cmd.SubRoute(router) if end != len(router) { return nil } return child }
go
func (cmd *Command) Route(router []string) *Command { child, end := cmd.SubRoute(router) if end != len(router) { return nil } return child }
[ "func", "(", "cmd", "*", "Command", ")", "Route", "(", "router", "[", "]", "string", ")", "*", "Command", "{", "child", ",", "end", ":=", "cmd", ".", "SubRoute", "(", "router", ")", "\n", "if", "end", "!=", "len", "(", "router", ")", "{", "return", "nil", "\n", "}", "\n", "return", "child", "\n", "}" ]
// Route finds command full matching router
[ "Route", "finds", "command", "full", "matching", "router" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/command.go#L456-L462
13,645
mkideal/cli
command.go
SubRoute
func (cmd *Command) SubRoute(router []string) (*Command, int) { cur := cmd for i, name := range router { child := cur.findChild(name) if child == nil { return cur, i } cur = child } return cur, len(router) }
go
func (cmd *Command) SubRoute(router []string) (*Command, int) { cur := cmd for i, name := range router { child := cur.findChild(name) if child == nil { return cur, i } cur = child } return cur, len(router) }
[ "func", "(", "cmd", "*", "Command", ")", "SubRoute", "(", "router", "[", "]", "string", ")", "(", "*", "Command", ",", "int", ")", "{", "cur", ":=", "cmd", "\n", "for", "i", ",", "name", ":=", "range", "router", "{", "child", ":=", "cur", ".", "findChild", "(", "name", ")", "\n", "if", "child", "==", "nil", "{", "return", "cur", ",", "i", "\n", "}", "\n", "cur", "=", "child", "\n", "}", "\n", "return", "cur", ",", "len", "(", "router", ")", "\n", "}" ]
// SubRoute finds command partial matching router
[ "SubRoute", "finds", "command", "partial", "matching", "router" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/command.go#L465-L475
13,646
mkideal/cli
command.go
findChild
func (cmd *Command) findChild(name string) *Command { if cmd.nochild() { return nil } for _, child := range cmd.children { if child.Name == name { return child } if child.Aliases != nil { for _, alias := range child.Aliases { if alias == name { return child } } } } return nil }
go
func (cmd *Command) findChild(name string) *Command { if cmd.nochild() { return nil } for _, child := range cmd.children { if child.Name == name { return child } if child.Aliases != nil { for _, alias := range child.Aliases { if alias == name { return child } } } } return nil }
[ "func", "(", "cmd", "*", "Command", ")", "findChild", "(", "name", "string", ")", "*", "Command", "{", "if", "cmd", ".", "nochild", "(", ")", "{", "return", "nil", "\n", "}", "\n", "for", "_", ",", "child", ":=", "range", "cmd", ".", "children", "{", "if", "child", ".", "Name", "==", "name", "{", "return", "child", "\n", "}", "\n", "if", "child", ".", "Aliases", "!=", "nil", "{", "for", "_", ",", "alias", ":=", "range", "child", ".", "Aliases", "{", "if", "alias", "==", "name", "{", "return", "child", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// findChild finds child command by name
[ "findChild", "finds", "child", "command", "by", "name" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/command.go#L478-L495
13,647
mkideal/cli
command.go
ListChildren
func (cmd *Command) ListChildren() []string { if cmd.nochild() { return []string{} } ret := make([]string, 0, len(cmd.children)) for _, child := range cmd.children { ret = append(ret, child.Name) } return ret }
go
func (cmd *Command) ListChildren() []string { if cmd.nochild() { return []string{} } ret := make([]string, 0, len(cmd.children)) for _, child := range cmd.children { ret = append(ret, child.Name) } return ret }
[ "func", "(", "cmd", "*", "Command", ")", "ListChildren", "(", ")", "[", "]", "string", "{", "if", "cmd", ".", "nochild", "(", ")", "{", "return", "[", "]", "string", "{", "}", "\n", "}", "\n\n", "ret", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "cmd", ".", "children", ")", ")", "\n", "for", "_", ",", "child", ":=", "range", "cmd", ".", "children", "{", "ret", "=", "append", "(", "ret", ",", "child", ".", "Name", ")", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// ListChildren returns all names of command children
[ "ListChildren", "returns", "all", "names", "of", "command", "children" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/command.go#L498-L508
13,648
mkideal/cli
command.go
ChildrenDescriptions
func (cmd *Command) ChildrenDescriptions(prefix, indent string) string { if cmd.nochild() { return "" } buff := bytes.NewBufferString("") length := 0 for _, child := range cmd.children { if len(child.Name) > length { length = len(child.Name) } } format := fmt.Sprintf("%s%%-%ds%s%%s%%s\n", prefix, length, indent) for _, child := range cmd.children { aliases := "" if child.Aliases != nil && len(child.Aliases) > 0 { aliasesBuff := bytes.NewBufferString("(aliases ") aliasesBuff.WriteString(strings.Join(child.Aliases, ",")) aliasesBuff.WriteString(")") aliases = aliasesBuff.String() } fmt.Fprintf(buff, format, child.Name, child.Desc, aliases) } return buff.String() }
go
func (cmd *Command) ChildrenDescriptions(prefix, indent string) string { if cmd.nochild() { return "" } buff := bytes.NewBufferString("") length := 0 for _, child := range cmd.children { if len(child.Name) > length { length = len(child.Name) } } format := fmt.Sprintf("%s%%-%ds%s%%s%%s\n", prefix, length, indent) for _, child := range cmd.children { aliases := "" if child.Aliases != nil && len(child.Aliases) > 0 { aliasesBuff := bytes.NewBufferString("(aliases ") aliasesBuff.WriteString(strings.Join(child.Aliases, ",")) aliasesBuff.WriteString(")") aliases = aliasesBuff.String() } fmt.Fprintf(buff, format, child.Name, child.Desc, aliases) } return buff.String() }
[ "func", "(", "cmd", "*", "Command", ")", "ChildrenDescriptions", "(", "prefix", ",", "indent", "string", ")", "string", "{", "if", "cmd", ".", "nochild", "(", ")", "{", "return", "\"", "\"", "\n", "}", "\n", "buff", ":=", "bytes", ".", "NewBufferString", "(", "\"", "\"", ")", "\n", "length", ":=", "0", "\n", "for", "_", ",", "child", ":=", "range", "cmd", ".", "children", "{", "if", "len", "(", "child", ".", "Name", ")", ">", "length", "{", "length", "=", "len", "(", "child", ".", "Name", ")", "\n", "}", "\n", "}", "\n", "format", ":=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "prefix", ",", "length", ",", "indent", ")", "\n", "for", "_", ",", "child", ":=", "range", "cmd", ".", "children", "{", "aliases", ":=", "\"", "\"", "\n", "if", "child", ".", "Aliases", "!=", "nil", "&&", "len", "(", "child", ".", "Aliases", ")", ">", "0", "{", "aliasesBuff", ":=", "bytes", ".", "NewBufferString", "(", "\"", "\"", ")", "\n", "aliasesBuff", ".", "WriteString", "(", "strings", ".", "Join", "(", "child", ".", "Aliases", ",", "\"", "\"", ")", ")", "\n", "aliasesBuff", ".", "WriteString", "(", "\"", "\"", ")", "\n", "aliases", "=", "aliasesBuff", ".", "String", "(", ")", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "buff", ",", "format", ",", "child", ".", "Name", ",", "child", ".", "Desc", ",", "aliases", ")", "\n", "}", "\n", "return", "buff", ".", "String", "(", ")", "\n", "}" ]
// ChildrenDescriptions returns all children's brief infos by one string
[ "ChildrenDescriptions", "returns", "all", "children", "s", "brief", "infos", "by", "one", "string" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/command.go#L511-L534
13,649
mkideal/cli
command.go
Suggestions
func (cmd *Command) Suggestions(path string) []string { if cmd.parent != nil { return cmd.Root().Suggestions(path) } var ( cmds = []*Command{cmd} targets = []string{} ) for len(cmds) > 0 { if cmds[0].nochild() { cmds = cmds[1:] } else { for _, child := range cmds[0].children { targets = append(targets, child.Path()) } cmds = append(cmds[0].children, cmds[1:]...) } } dists := []editDistanceRank{} for i, size := 0, len(targets); i < size; i++ { if d, ok := match(path, targets[i]); ok { dists = append(dists, editDistanceRank{s: targets[i], d: d}) } } sort.Sort(editDistanceRankSlice(dists)) for i := 0; i < len(dists); i++ { targets[i] = dists[i].s } return targets[:len(dists)] }
go
func (cmd *Command) Suggestions(path string) []string { if cmd.parent != nil { return cmd.Root().Suggestions(path) } var ( cmds = []*Command{cmd} targets = []string{} ) for len(cmds) > 0 { if cmds[0].nochild() { cmds = cmds[1:] } else { for _, child := range cmds[0].children { targets = append(targets, child.Path()) } cmds = append(cmds[0].children, cmds[1:]...) } } dists := []editDistanceRank{} for i, size := 0, len(targets); i < size; i++ { if d, ok := match(path, targets[i]); ok { dists = append(dists, editDistanceRank{s: targets[i], d: d}) } } sort.Sort(editDistanceRankSlice(dists)) for i := 0; i < len(dists); i++ { targets[i] = dists[i].s } return targets[:len(dists)] }
[ "func", "(", "cmd", "*", "Command", ")", "Suggestions", "(", "path", "string", ")", "[", "]", "string", "{", "if", "cmd", ".", "parent", "!=", "nil", "{", "return", "cmd", ".", "Root", "(", ")", ".", "Suggestions", "(", "path", ")", "\n", "}", "\n\n", "var", "(", "cmds", "=", "[", "]", "*", "Command", "{", "cmd", "}", "\n", "targets", "=", "[", "]", "string", "{", "}", "\n", ")", "\n", "for", "len", "(", "cmds", ")", ">", "0", "{", "if", "cmds", "[", "0", "]", ".", "nochild", "(", ")", "{", "cmds", "=", "cmds", "[", "1", ":", "]", "\n", "}", "else", "{", "for", "_", ",", "child", ":=", "range", "cmds", "[", "0", "]", ".", "children", "{", "targets", "=", "append", "(", "targets", ",", "child", ".", "Path", "(", ")", ")", "\n", "}", "\n", "cmds", "=", "append", "(", "cmds", "[", "0", "]", ".", "children", ",", "cmds", "[", "1", ":", "]", "...", ")", "\n", "}", "\n", "}", "\n\n", "dists", ":=", "[", "]", "editDistanceRank", "{", "}", "\n", "for", "i", ",", "size", ":=", "0", ",", "len", "(", "targets", ")", ";", "i", "<", "size", ";", "i", "++", "{", "if", "d", ",", "ok", ":=", "match", "(", "path", ",", "targets", "[", "i", "]", ")", ";", "ok", "{", "dists", "=", "append", "(", "dists", ",", "editDistanceRank", "{", "s", ":", "targets", "[", "i", "]", ",", "d", ":", "d", "}", ")", "\n", "}", "\n", "}", "\n", "sort", ".", "Sort", "(", "editDistanceRankSlice", "(", "dists", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "dists", ")", ";", "i", "++", "{", "targets", "[", "i", "]", "=", "dists", "[", "i", "]", ".", "s", "\n", "}", "\n", "return", "targets", "[", ":", "len", "(", "dists", ")", "]", "\n", "}" ]
// Suggestions returns all similar commands
[ "Suggestions", "returns", "all", "similar", "commands" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/command.go#L541-L572
13,650
mkideal/cli
ext/decoders.go
SetReader
func (r *Reader) SetReader(reader io.Reader) { r.Close() r.reader = reader if file, ok := reader.(*os.File); ok { r.filename = file.Name() } else { r.filename = "" } }
go
func (r *Reader) SetReader(reader io.Reader) { r.Close() r.reader = reader if file, ok := reader.(*os.File); ok { r.filename = file.Name() } else { r.filename = "" } }
[ "func", "(", "r", "*", "Reader", ")", "SetReader", "(", "reader", "io", ".", "Reader", ")", "{", "r", ".", "Close", "(", ")", "\n", "r", ".", "reader", "=", "reader", "\n", "if", "file", ",", "ok", ":=", "reader", ".", "(", "*", "os", ".", "File", ")", ";", "ok", "{", "r", ".", "filename", "=", "file", ".", "Name", "(", ")", "\n", "}", "else", "{", "r", ".", "filename", "=", "\"", "\"", "\n", "}", "\n", "}" ]
// SetReader replaces the native reader
[ "SetReader", "replaces", "the", "native", "reader" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/ext/decoders.go#L176-L184
13,651
mkideal/cli
ext/decoders.go
Read
func (r Reader) Read(data []byte) (n int, err error) { if r.reader == nil { return os.Stdin.Read(data) } return r.reader.Read(data) }
go
func (r Reader) Read(data []byte) (n int, err error) { if r.reader == nil { return os.Stdin.Read(data) } return r.reader.Read(data) }
[ "func", "(", "r", "Reader", ")", "Read", "(", "data", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "if", "r", ".", "reader", "==", "nil", "{", "return", "os", ".", "Stdin", ".", "Read", "(", "data", ")", "\n", "}", "\n", "return", "r", ".", "reader", ".", "Read", "(", "data", ")", "\n", "}" ]
// Read implementes io.Reader
[ "Read", "implementes", "io", ".", "Reader" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/ext/decoders.go#L187-L192
13,652
mkideal/cli
ext/decoders.go
SetWriter
func (w *Writer) SetWriter(writer io.Writer) { w.Close() w.writer = writer if file, ok := w.writer.(*os.File); ok { w.filename = file.Name() } else { w.filename = "" } }
go
func (w *Writer) SetWriter(writer io.Writer) { w.Close() w.writer = writer if file, ok := w.writer.(*os.File); ok { w.filename = file.Name() } else { w.filename = "" } }
[ "func", "(", "w", "*", "Writer", ")", "SetWriter", "(", "writer", "io", ".", "Writer", ")", "{", "w", ".", "Close", "(", ")", "\n", "w", ".", "writer", "=", "writer", "\n", "if", "file", ",", "ok", ":=", "w", ".", "writer", ".", "(", "*", "os", ".", "File", ")", ";", "ok", "{", "w", ".", "filename", "=", "file", ".", "Name", "(", ")", "\n", "}", "else", "{", "w", ".", "filename", "=", "\"", "\"", "\n", "}", "\n", "}" ]
// SetWriter replaces the native writer
[ "SetWriter", "replaces", "the", "native", "writer" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/ext/decoders.go#L240-L248
13,653
mkideal/cli
ext/decoders.go
Write
func (w *Writer) Write(data []byte) (n int, err error) { if w.writer == nil { if w.filename == "" { w.writer = os.Stdout w.filename = os.Stdout.Name() } else { file, err := os.Create(w.filename) if err != nil { return 0, err } w.writer = file } } return w.writer.Write(data) }
go
func (w *Writer) Write(data []byte) (n int, err error) { if w.writer == nil { if w.filename == "" { w.writer = os.Stdout w.filename = os.Stdout.Name() } else { file, err := os.Create(w.filename) if err != nil { return 0, err } w.writer = file } } return w.writer.Write(data) }
[ "func", "(", "w", "*", "Writer", ")", "Write", "(", "data", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "if", "w", ".", "writer", "==", "nil", "{", "if", "w", ".", "filename", "==", "\"", "\"", "{", "w", ".", "writer", "=", "os", ".", "Stdout", "\n", "w", ".", "filename", "=", "os", ".", "Stdout", ".", "Name", "(", ")", "\n", "}", "else", "{", "file", ",", "err", ":=", "os", ".", "Create", "(", "w", ".", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "w", ".", "writer", "=", "file", "\n", "}", "\n", "}", "\n", "return", "w", ".", "writer", ".", "Write", "(", "data", ")", "\n", "}" ]
// Write implementes io.Writer interface
[ "Write", "implementes", "io", ".", "Writer", "interface" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/ext/decoders.go#L251-L265
13,654
mkideal/cli
clil/log.go
NewLog
func NewLog(level string) (*log.Logger, error) { lvl, err := colog.ParseLevel(level) if err != nil { return nil, err } cl := colog.NewCoLog(os.Stderr, "", log.Lshortfile|log.Ldate|log.Ltime) cl.SetMinLevel(lvl) cl.SetDefaultLevel(lvl) lg := cl.NewLogger() return lg, nil }
go
func NewLog(level string) (*log.Logger, error) { lvl, err := colog.ParseLevel(level) if err != nil { return nil, err } cl := colog.NewCoLog(os.Stderr, "", log.Lshortfile|log.Ldate|log.Ltime) cl.SetMinLevel(lvl) cl.SetDefaultLevel(lvl) lg := cl.NewLogger() return lg, nil }
[ "func", "NewLog", "(", "level", "string", ")", "(", "*", "log", ".", "Logger", ",", "error", ")", "{", "lvl", ",", "err", ":=", "colog", ".", "ParseLevel", "(", "level", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "cl", ":=", "colog", ".", "NewCoLog", "(", "os", ".", "Stderr", ",", "\"", "\"", ",", "log", ".", "Lshortfile", "|", "log", ".", "Ldate", "|", "log", ".", "Ltime", ")", "\n", "cl", ".", "SetMinLevel", "(", "lvl", ")", "\n", "cl", ".", "SetDefaultLevel", "(", "lvl", ")", "\n", "lg", ":=", "cl", ".", "NewLogger", "(", ")", "\n", "return", "lg", ",", "nil", "\n", "}" ]
// NewLog creates new logger
[ "NewLog", "creates", "new", "logger" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/clil/log.go#L11-L23
13,655
mkideal/cli
parser.go
RegisterFlagParser
func RegisterFlagParser(name string, creator FlagParserCreator) { if _, ok := parserCreators[name]; ok { panic("RegisterFlagParser has registered: " + name) } parserCreators[name] = creator }
go
func RegisterFlagParser(name string, creator FlagParserCreator) { if _, ok := parserCreators[name]; ok { panic("RegisterFlagParser has registered: " + name) } parserCreators[name] = creator }
[ "func", "RegisterFlagParser", "(", "name", "string", ",", "creator", "FlagParserCreator", ")", "{", "if", "_", ",", "ok", ":=", "parserCreators", "[", "name", "]", ";", "ok", "{", "panic", "(", "\"", "\"", "+", "name", ")", "\n", "}", "\n", "parserCreators", "[", "name", "]", "=", "creator", "\n", "}" ]
// RegisterFlagParser registers FlagParserCreator by name
[ "RegisterFlagParser", "registers", "FlagParserCreator", "by", "name" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/parser.go#L19-L24
13,656
mkideal/cli
editor.go
LaunchEditor
func LaunchEditor(editor string) (content []byte, err error) { return launchEditorWithFilename(editor, randomFilename()) }
go
func LaunchEditor(editor string) (content []byte, err error) { return launchEditorWithFilename(editor, randomFilename()) }
[ "func", "LaunchEditor", "(", "editor", "string", ")", "(", "content", "[", "]", "byte", ",", "err", "error", ")", "{", "return", "launchEditorWithFilename", "(", "editor", ",", "randomFilename", "(", ")", ")", "\n", "}" ]
// LaunchEditor launchs the specified editor with a random filename
[ "LaunchEditor", "launchs", "the", "specified", "editor", "with", "a", "random", "filename" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/editor.go#L32-L34
13,657
mkideal/cli
context.go
NOpt
func (ctx *Context) NOpt() int { if ctx.flagSet == nil || ctx.flagSet.flagSlice == nil { return 0 } n := 0 for _, fl := range ctx.flagSet.flagSlice { if fl.isSet { n++ } } return n }
go
func (ctx *Context) NOpt() int { if ctx.flagSet == nil || ctx.flagSet.flagSlice == nil { return 0 } n := 0 for _, fl := range ctx.flagSet.flagSlice { if fl.isSet { n++ } } return n }
[ "func", "(", "ctx", "*", "Context", ")", "NOpt", "(", ")", "int", "{", "if", "ctx", ".", "flagSet", "==", "nil", "||", "ctx", ".", "flagSet", ".", "flagSlice", "==", "nil", "{", "return", "0", "\n", "}", "\n", "n", ":=", "0", "\n", "for", "_", ",", "fl", ":=", "range", "ctx", ".", "flagSet", ".", "flagSlice", "{", "if", "fl", ".", "isSet", "{", "n", "++", "\n", "}", "\n", "}", "\n", "return", "n", "\n", "}" ]
// NOpt returns num of options
[ "NOpt", "returns", "num", "of", "options" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/context.go#L92-L103
13,658
mkideal/cli
context.go
Argv
func (ctx *Context) Argv() interface{} { if ctx.argvList == nil || len(ctx.argvList) == 0 { return nil } return ctx.argvList[0] }
go
func (ctx *Context) Argv() interface{} { if ctx.argvList == nil || len(ctx.argvList) == 0 { return nil } return ctx.argvList[0] }
[ "func", "(", "ctx", "*", "Context", ")", "Argv", "(", ")", "interface", "{", "}", "{", "if", "ctx", ".", "argvList", "==", "nil", "||", "len", "(", "ctx", ".", "argvList", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "return", "ctx", ".", "argvList", "[", "0", "]", "\n", "}" ]
// Argv returns parsed args object
[ "Argv", "returns", "parsed", "args", "object" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/context.go#L106-L111
13,659
mkideal/cli
context.go
RootArgv
func (ctx *Context) RootArgv() interface{} { if isEmptyArgvList(ctx.argvList) { return nil } index := len(ctx.argvList) - 1 return ctx.argvList[index] }
go
func (ctx *Context) RootArgv() interface{} { if isEmptyArgvList(ctx.argvList) { return nil } index := len(ctx.argvList) - 1 return ctx.argvList[index] }
[ "func", "(", "ctx", "*", "Context", ")", "RootArgv", "(", ")", "interface", "{", "}", "{", "if", "isEmptyArgvList", "(", "ctx", ".", "argvList", ")", "{", "return", "nil", "\n", "}", "\n", "index", ":=", "len", "(", "ctx", ".", "argvList", ")", "-", "1", "\n", "return", "ctx", ".", "argvList", "[", "index", "]", "\n", "}" ]
// RootArgv returns parsed root args object
[ "RootArgv", "returns", "parsed", "root", "args", "object" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/context.go#L114-L120
13,660
mkideal/cli
context.go
GetArgvList
func (ctx *Context) GetArgvList(curr interface{}, parents ...interface{}) error { if isEmptyArgvList(ctx.argvList) { return argvError{isEmpty: true} } for i, argv := range append([]interface{}{curr}, parents...) { if argv == nil { continue } if i >= len(ctx.argvList) { return argvError{isOutOfRange: true} } if ctx.argvList[i] == nil { return argvError{ith: i, msg: "source is nil"} } buf := bytes.NewBufferString("") if err := json.NewEncoder(buf).Encode(ctx.argvList[i]); err != nil { return err } if err := json.NewDecoder(buf).Decode(argv); err != nil { return err } } return nil }
go
func (ctx *Context) GetArgvList(curr interface{}, parents ...interface{}) error { if isEmptyArgvList(ctx.argvList) { return argvError{isEmpty: true} } for i, argv := range append([]interface{}{curr}, parents...) { if argv == nil { continue } if i >= len(ctx.argvList) { return argvError{isOutOfRange: true} } if ctx.argvList[i] == nil { return argvError{ith: i, msg: "source is nil"} } buf := bytes.NewBufferString("") if err := json.NewEncoder(buf).Encode(ctx.argvList[i]); err != nil { return err } if err := json.NewDecoder(buf).Decode(argv); err != nil { return err } } return nil }
[ "func", "(", "ctx", "*", "Context", ")", "GetArgvList", "(", "curr", "interface", "{", "}", ",", "parents", "...", "interface", "{", "}", ")", "error", "{", "if", "isEmptyArgvList", "(", "ctx", ".", "argvList", ")", "{", "return", "argvError", "{", "isEmpty", ":", "true", "}", "\n", "}", "\n", "for", "i", ",", "argv", ":=", "range", "append", "(", "[", "]", "interface", "{", "}", "{", "curr", "}", ",", "parents", "...", ")", "{", "if", "argv", "==", "nil", "{", "continue", "\n", "}", "\n", "if", "i", ">=", "len", "(", "ctx", ".", "argvList", ")", "{", "return", "argvError", "{", "isOutOfRange", ":", "true", "}", "\n", "}", "\n", "if", "ctx", ".", "argvList", "[", "i", "]", "==", "nil", "{", "return", "argvError", "{", "ith", ":", "i", ",", "msg", ":", "\"", "\"", "}", "\n", "}", "\n\n", "buf", ":=", "bytes", ".", "NewBufferString", "(", "\"", "\"", ")", "\n", "if", "err", ":=", "json", ".", "NewEncoder", "(", "buf", ")", ".", "Encode", "(", "ctx", ".", "argvList", "[", "i", "]", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "json", ".", "NewDecoder", "(", "buf", ")", ".", "Decode", "(", "argv", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetArgvList gets argv objects
[ "GetArgvList", "gets", "argv", "objects" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/context.go#L123-L147
13,661
mkideal/cli
context.go
GetArgvAt
func (ctx *Context) GetArgvAt(argv interface{}, i int) error { if isEmptyArgvList(ctx.argvList) { return argvError{isEmpty: true} } if argv == nil { return errors.New("argv is nil") } if i >= len(ctx.argvList) { return argvError{isOutOfRange: true} } if ctx.argvList[i] == nil { return argvError{ith: i, msg: "source is nil"} } buf := bytes.NewBufferString("") if err := json.NewEncoder(buf).Encode(ctx.argvList[i]); err != nil { return err } return json.NewDecoder(buf).Decode(argv) }
go
func (ctx *Context) GetArgvAt(argv interface{}, i int) error { if isEmptyArgvList(ctx.argvList) { return argvError{isEmpty: true} } if argv == nil { return errors.New("argv is nil") } if i >= len(ctx.argvList) { return argvError{isOutOfRange: true} } if ctx.argvList[i] == nil { return argvError{ith: i, msg: "source is nil"} } buf := bytes.NewBufferString("") if err := json.NewEncoder(buf).Encode(ctx.argvList[i]); err != nil { return err } return json.NewDecoder(buf).Decode(argv) }
[ "func", "(", "ctx", "*", "Context", ")", "GetArgvAt", "(", "argv", "interface", "{", "}", ",", "i", "int", ")", "error", "{", "if", "isEmptyArgvList", "(", "ctx", ".", "argvList", ")", "{", "return", "argvError", "{", "isEmpty", ":", "true", "}", "\n", "}", "\n", "if", "argv", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "i", ">=", "len", "(", "ctx", ".", "argvList", ")", "{", "return", "argvError", "{", "isOutOfRange", ":", "true", "}", "\n", "}", "\n", "if", "ctx", ".", "argvList", "[", "i", "]", "==", "nil", "{", "return", "argvError", "{", "ith", ":", "i", ",", "msg", ":", "\"", "\"", "}", "\n", "}", "\n\n", "buf", ":=", "bytes", ".", "NewBufferString", "(", "\"", "\"", ")", "\n", "if", "err", ":=", "json", ".", "NewEncoder", "(", "buf", ")", ".", "Encode", "(", "ctx", ".", "argvList", "[", "i", "]", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "json", ".", "NewDecoder", "(", "buf", ")", ".", "Decode", "(", "argv", ")", "\n", "}" ]
// GetArgvAt gets the i-th argv object
[ "GetArgvAt", "gets", "the", "i", "-", "th", "argv", "object" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/context.go#L150-L169
13,662
mkideal/cli
context.go
IsSet
func (ctx *Context) IsSet(flag string, aliasFlags ...string) bool { fl, ok := ctx.flagSet.flagMap[flag] if ok { return fl.isSet } for _, alias := range aliasFlags { if fl, ok := ctx.flagSet.flagMap[alias]; ok { return fl.isSet } } return false }
go
func (ctx *Context) IsSet(flag string, aliasFlags ...string) bool { fl, ok := ctx.flagSet.flagMap[flag] if ok { return fl.isSet } for _, alias := range aliasFlags { if fl, ok := ctx.flagSet.flagMap[alias]; ok { return fl.isSet } } return false }
[ "func", "(", "ctx", "*", "Context", ")", "IsSet", "(", "flag", "string", ",", "aliasFlags", "...", "string", ")", "bool", "{", "fl", ",", "ok", ":=", "ctx", ".", "flagSet", ".", "flagMap", "[", "flag", "]", "\n", "if", "ok", "{", "return", "fl", ".", "isSet", "\n", "}", "\n", "for", "_", ",", "alias", ":=", "range", "aliasFlags", "{", "if", "fl", ",", "ok", ":=", "ctx", ".", "flagSet", ".", "flagMap", "[", "alias", "]", ";", "ok", "{", "return", "fl", ".", "isSet", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsSet determins whether `flag` is set
[ "IsSet", "determins", "whether", "flag", "is", "set" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/context.go#L172-L183
13,663
mkideal/cli
context.go
FormValues
func (ctx *Context) FormValues() url.Values { if ctx.flagSet == nil { debug.Panicf("ctx.flagSet == nil") } return ctx.flagSet.values }
go
func (ctx *Context) FormValues() url.Values { if ctx.flagSet == nil { debug.Panicf("ctx.flagSet == nil") } return ctx.flagSet.values }
[ "func", "(", "ctx", "*", "Context", ")", "FormValues", "(", ")", "url", ".", "Values", "{", "if", "ctx", ".", "flagSet", "==", "nil", "{", "debug", ".", "Panicf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "ctx", ".", "flagSet", ".", "values", "\n", "}" ]
// FormValues returns parsed args as url.Values
[ "FormValues", "returns", "parsed", "args", "as", "url", ".", "Values" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/context.go#L186-L191
13,664
mkideal/cli
context.go
Writer
func (ctx *Context) Writer() io.Writer { if ctx.writer == nil { ctx.writer = colorable.NewColorableStdout() } return ctx.writer }
go
func (ctx *Context) Writer() io.Writer { if ctx.writer == nil { ctx.writer = colorable.NewColorableStdout() } return ctx.writer }
[ "func", "(", "ctx", "*", "Context", ")", "Writer", "(", ")", "io", ".", "Writer", "{", "if", "ctx", ".", "writer", "==", "nil", "{", "ctx", ".", "writer", "=", "colorable", ".", "NewColorableStdout", "(", ")", "\n", "}", "\n", "return", "ctx", ".", "writer", "\n", "}" ]
// Writer returns writer
[ "Writer", "returns", "writer" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/context.go#L209-L214
13,665
mkideal/cli
context.go
String
func (ctx *Context) String(format string, args ...interface{}) *Context { fmt.Fprintf(ctx.Writer(), format, args...) return ctx }
go
func (ctx *Context) String(format string, args ...interface{}) *Context { fmt.Fprintf(ctx.Writer(), format, args...) return ctx }
[ "func", "(", "ctx", "*", "Context", ")", "String", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "*", "Context", "{", "fmt", ".", "Fprintf", "(", "ctx", ".", "Writer", "(", ")", ",", "format", ",", "args", "...", ")", "\n", "return", "ctx", "\n", "}" ]
// String writes formatted string to writer
[ "String", "writes", "formatted", "string", "to", "writer" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/context.go#L227-L230
13,666
mkideal/cli
context.go
JSON
func (ctx *Context) JSON(obj interface{}) *Context { data, err := json.Marshal(obj) if err == nil { fmt.Fprint(ctx.Writer(), string(data)) } return ctx }
go
func (ctx *Context) JSON(obj interface{}) *Context { data, err := json.Marshal(obj) if err == nil { fmt.Fprint(ctx.Writer(), string(data)) } return ctx }
[ "func", "(", "ctx", "*", "Context", ")", "JSON", "(", "obj", "interface", "{", "}", ")", "*", "Context", "{", "data", ",", "err", ":=", "json", ".", "Marshal", "(", "obj", ")", "\n", "if", "err", "==", "nil", "{", "fmt", ".", "Fprint", "(", "ctx", ".", "Writer", "(", ")", ",", "string", "(", "data", ")", ")", "\n", "}", "\n", "return", "ctx", "\n", "}" ]
// JSON writes json string of obj to writer
[ "JSON", "writes", "json", "string", "of", "obj", "to", "writer" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/context.go#L233-L239
13,667
mkideal/cli
context.go
JSONIndent
func (ctx *Context) JSONIndent(obj interface{}, prefix, indent string) *Context { data, err := json.MarshalIndent(obj, prefix, indent) if err == nil { fmt.Fprint(ctx.Writer(), string(data)) } return ctx }
go
func (ctx *Context) JSONIndent(obj interface{}, prefix, indent string) *Context { data, err := json.MarshalIndent(obj, prefix, indent) if err == nil { fmt.Fprint(ctx.Writer(), string(data)) } return ctx }
[ "func", "(", "ctx", "*", "Context", ")", "JSONIndent", "(", "obj", "interface", "{", "}", ",", "prefix", ",", "indent", "string", ")", "*", "Context", "{", "data", ",", "err", ":=", "json", ".", "MarshalIndent", "(", "obj", ",", "prefix", ",", "indent", ")", "\n", "if", "err", "==", "nil", "{", "fmt", ".", "Fprint", "(", "ctx", ".", "Writer", "(", ")", ",", "string", "(", "data", ")", ")", "\n", "}", "\n", "return", "ctx", "\n", "}" ]
// JSONIndent writes pretty json string of obj to writer
[ "JSONIndent", "writes", "pretty", "json", "string", "of", "obj", "to", "writer" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/context.go#L247-L253
13,668
mkideal/cli
context.go
JSONIndentln
func (ctx *Context) JSONIndentln(obj interface{}, prefix, indent string) *Context { return ctx.JSONIndent(obj, prefix, indent).String("\n") }
go
func (ctx *Context) JSONIndentln(obj interface{}, prefix, indent string) *Context { return ctx.JSONIndent(obj, prefix, indent).String("\n") }
[ "func", "(", "ctx", "*", "Context", ")", "JSONIndentln", "(", "obj", "interface", "{", "}", ",", "prefix", ",", "indent", "string", ")", "*", "Context", "{", "return", "ctx", ".", "JSONIndent", "(", "obj", ",", "prefix", ",", "indent", ")", ".", "String", "(", "\"", "\\n", "\"", ")", "\n", "}" ]
// JSONIndentln writes pretty json string of obj end with "\n" to writer
[ "JSONIndentln", "writes", "pretty", "json", "string", "of", "obj", "end", "with", "\\", "n", "to", "writer" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/context.go#L256-L258
13,669
mkideal/cli
cli.go
Run
func Run(argv interface{}, fn CommandFunc, descs ...string) int { return RunWithArgs(argv, os.Args, fn, descs...) }
go
func Run(argv interface{}, fn CommandFunc, descs ...string) int { return RunWithArgs(argv, os.Args, fn, descs...) }
[ "func", "Run", "(", "argv", "interface", "{", "}", ",", "fn", "CommandFunc", ",", "descs", "...", "string", ")", "int", "{", "return", "RunWithArgs", "(", "argv", ",", "os", ".", "Args", ",", "fn", ",", "descs", "...", ")", "\n", "}" ]
// Run runs a single command app
[ "Run", "runs", "a", "single", "command", "app" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/cli.go#L14-L16
13,670
mkideal/cli
cli.go
RunWithArgs
func RunWithArgs(argv interface{}, args []string, fn CommandFunc, descs ...string) int { desc := "" if len(descs) > 0 { desc = strings.Join(descs, "\n") } err := (&Command{ Name: args[0], Desc: desc, Argv: func() interface{} { return argv }, CanSubRoute: true, Fn: fn, }).Run(args[1:]) if err != nil { fmt.Fprintln(os.Stderr, err) return 1 } return 0 }
go
func RunWithArgs(argv interface{}, args []string, fn CommandFunc, descs ...string) int { desc := "" if len(descs) > 0 { desc = strings.Join(descs, "\n") } err := (&Command{ Name: args[0], Desc: desc, Argv: func() interface{} { return argv }, CanSubRoute: true, Fn: fn, }).Run(args[1:]) if err != nil { fmt.Fprintln(os.Stderr, err) return 1 } return 0 }
[ "func", "RunWithArgs", "(", "argv", "interface", "{", "}", ",", "args", "[", "]", "string", ",", "fn", "CommandFunc", ",", "descs", "...", "string", ")", "int", "{", "desc", ":=", "\"", "\"", "\n", "if", "len", "(", "descs", ")", ">", "0", "{", "desc", "=", "strings", ".", "Join", "(", "descs", ",", "\"", "\\n", "\"", ")", "\n", "}", "\n", "err", ":=", "(", "&", "Command", "{", "Name", ":", "args", "[", "0", "]", ",", "Desc", ":", "desc", ",", "Argv", ":", "func", "(", ")", "interface", "{", "}", "{", "return", "argv", "}", ",", "CanSubRoute", ":", "true", ",", "Fn", ":", "fn", ",", "}", ")", ".", "Run", "(", "args", "[", "1", ":", "]", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Fprintln", "(", "os", ".", "Stderr", ",", "err", ")", "\n", "return", "1", "\n", "}", "\n", "return", "0", "\n", "}" ]
// RunWithArgs is similar to Run, but with args instead of os.Args
[ "RunWithArgs", "is", "similar", "to", "Run", "but", "with", "args", "instead", "of", "os", ".", "Args" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/cli.go#L19-L36
13,671
mkideal/cli
cli.go
Root
func Root(root *Command, forest ...*CommandTree) *Command { root.RegisterTree(forest...) return root }
go
func Root(root *Command, forest ...*CommandTree) *Command { root.RegisterTree(forest...) return root }
[ "func", "Root", "(", "root", "*", "Command", ",", "forest", "...", "*", "CommandTree", ")", "*", "Command", "{", "root", ".", "RegisterTree", "(", "forest", "...", ")", "\n", "return", "root", "\n", "}" ]
// Root registers forest for root and returns root
[ "Root", "registers", "forest", "for", "root", "and", "returns", "root" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/cli.go#L39-L42
13,672
mkideal/cli
cli.go
Tree
func Tree(cmd *Command, forest ...*CommandTree) *CommandTree { return &CommandTree{ command: cmd, forest: forest, } }
go
func Tree(cmd *Command, forest ...*CommandTree) *CommandTree { return &CommandTree{ command: cmd, forest: forest, } }
[ "func", "Tree", "(", "cmd", "*", "Command", ",", "forest", "...", "*", "CommandTree", ")", "*", "CommandTree", "{", "return", "&", "CommandTree", "{", "command", ":", "cmd", ",", "forest", ":", "forest", ",", "}", "\n", "}" ]
// Tree creates a CommandTree
[ "Tree", "creates", "a", "CommandTree" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/cli.go#L45-L50
13,673
mkideal/cli
cli.go
Parse
func Parse(args []string, argv interface{}) error { clr := color.Color{} fset := parseArgv(args, argv, clr) return fset.err }
go
func Parse(args []string, argv interface{}) error { clr := color.Color{} fset := parseArgv(args, argv, clr) return fset.err }
[ "func", "Parse", "(", "args", "[", "]", "string", ",", "argv", "interface", "{", "}", ")", "error", "{", "clr", ":=", "color", ".", "Color", "{", "}", "\n", "fset", ":=", "parseArgv", "(", "args", ",", "argv", ",", "clr", ")", "\n", "return", "fset", ".", "err", "\n", "}" ]
// Parse parses args to object argv
[ "Parse", "parses", "args", "to", "object", "argv" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/cli.go#L53-L57
13,674
mkideal/cli
clis/support.go
Basename
func Basename(s string) string { n := strings.LastIndexByte(s, '.') if n > 0 { return s[:n] } return s }
go
func Basename(s string) string { n := strings.LastIndexByte(s, '.') if n > 0 { return s[:n] } return s }
[ "func", "Basename", "(", "s", "string", ")", "string", "{", "n", ":=", "strings", ".", "LastIndexByte", "(", "s", ",", "'.'", ")", "\n", "if", "n", ">", "0", "{", "return", "s", "[", ":", "n", "]", "\n", "}", "\n", "return", "s", "\n", "}" ]
// Basename returns the file name without extension.
[ "Basename", "returns", "the", "file", "name", "without", "extension", "." ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/clis/support.go#L51-L57
13,675
mkideal/cli
clis/support.go
AbortOn
func AbortOn(errCase string, e error) { if e != nil { fmt.Fprintf(os.Stderr, "[%s] %s, %s: %v\n", color.White(progname), color.Red("Error"), errCase, e) os.Exit(1) } }
go
func AbortOn(errCase string, e error) { if e != nil { fmt.Fprintf(os.Stderr, "[%s] %s, %s: %v\n", color.White(progname), color.Red("Error"), errCase, e) os.Exit(1) } }
[ "func", "AbortOn", "(", "errCase", "string", ",", "e", "error", ")", "{", "if", "e", "!=", "nil", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\n", "\"", ",", "color", ".", "White", "(", "progname", ")", ",", "color", ".", "Red", "(", "\"", "\"", ")", ",", "errCase", ",", "e", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "}" ]
// abortOn will quit on anticipated errors gracefully without stack trace
[ "abortOn", "will", "quit", "on", "anticipated", "errors", "gracefully", "without", "stack", "trace" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/clis/support.go#L77-L83
13,676
mkideal/cli
clis/support.go
Verbose
func Verbose(levelSet int, format string, args ...interface{}) { if Opts.Verbose >= levelSet { fmt.Fprintf(os.Stderr, "[%s] ", color.White(progname)) fmt.Fprintf(os.Stderr, format+"\n", args...) } }
go
func Verbose(levelSet int, format string, args ...interface{}) { if Opts.Verbose >= levelSet { fmt.Fprintf(os.Stderr, "[%s] ", color.White(progname)) fmt.Fprintf(os.Stderr, format+"\n", args...) } }
[ "func", "Verbose", "(", "levelSet", "int", ",", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "if", "Opts", ".", "Verbose", ">=", "levelSet", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\"", ",", "color", ".", "White", "(", "progname", ")", ")", "\n", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "format", "+", "\"", "\\n", "\"", ",", "args", "...", ")", "\n", "}", "\n", "}" ]
// verbose will print info to stderr according to the verbose level setting
[ "verbose", "will", "print", "info", "to", "stderr", "according", "to", "the", "verbose", "level", "setting" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/clis/support.go#L86-L91
13,677
mkideal/cli
http.go
RegisterHTTP
func (cmd *Command) RegisterHTTP(ctxs ...*Context) error { clr := color.Color{} clr.Disable() if len(ctxs) > 0 { clr = ctxs[0].color } if cmd.routersMap == nil { cmd.routersMap = make(map[string]string) } commands := []*Command{cmd} for len(commands) > 0 { c := commands[0] commands = commands[1:] if c.HTTPRouters != nil { for _, r := range c.HTTPRouters { if _, exists := c.routersMap[r]; exists { return throwRouterRepeat(clr.Yellow(r)) } cmd.routersMap[r] = c.Path() } } if c.nochild() { continue } commands = append(commands, c.children...) } return nil }
go
func (cmd *Command) RegisterHTTP(ctxs ...*Context) error { clr := color.Color{} clr.Disable() if len(ctxs) > 0 { clr = ctxs[0].color } if cmd.routersMap == nil { cmd.routersMap = make(map[string]string) } commands := []*Command{cmd} for len(commands) > 0 { c := commands[0] commands = commands[1:] if c.HTTPRouters != nil { for _, r := range c.HTTPRouters { if _, exists := c.routersMap[r]; exists { return throwRouterRepeat(clr.Yellow(r)) } cmd.routersMap[r] = c.Path() } } if c.nochild() { continue } commands = append(commands, c.children...) } return nil }
[ "func", "(", "cmd", "*", "Command", ")", "RegisterHTTP", "(", "ctxs", "...", "*", "Context", ")", "error", "{", "clr", ":=", "color", ".", "Color", "{", "}", "\n", "clr", ".", "Disable", "(", ")", "\n", "if", "len", "(", "ctxs", ")", ">", "0", "{", "clr", "=", "ctxs", "[", "0", "]", ".", "color", "\n", "}", "\n", "if", "cmd", ".", "routersMap", "==", "nil", "{", "cmd", ".", "routersMap", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "}", "\n", "commands", ":=", "[", "]", "*", "Command", "{", "cmd", "}", "\n", "for", "len", "(", "commands", ")", ">", "0", "{", "c", ":=", "commands", "[", "0", "]", "\n", "commands", "=", "commands", "[", "1", ":", "]", "\n", "if", "c", ".", "HTTPRouters", "!=", "nil", "{", "for", "_", ",", "r", ":=", "range", "c", ".", "HTTPRouters", "{", "if", "_", ",", "exists", ":=", "c", ".", "routersMap", "[", "r", "]", ";", "exists", "{", "return", "throwRouterRepeat", "(", "clr", ".", "Yellow", "(", "r", ")", ")", "\n", "}", "\n", "cmd", ".", "routersMap", "[", "r", "]", "=", "c", ".", "Path", "(", ")", "\n", "}", "\n", "}", "\n", "if", "c", ".", "nochild", "(", ")", "{", "continue", "\n", "}", "\n", "commands", "=", "append", "(", "commands", ",", "c", ".", "children", "...", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// RegisterHTTP init HTTPRouters for command
[ "RegisterHTTP", "init", "HTTPRouters", "for", "command" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/http.go#L16-L43
13,678
mkideal/cli
http.go
ServeHTTP
func (cmd *Command) ServeHTTP(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { return } var ( path = r.URL.Path found = false ) if cmd.routersMap != nil { path, found = cmd.routersMap[path] } if !found { path = strings.TrimPrefix(r.URL.Path, "/") path = strings.TrimSuffix(path, "/") } router := strings.Split(path, "/") args := make([]string, 0, len(r.Form)*2+len(router)) for _, r := range router { args = append(args, r) } for key, values := range r.Form { if len(key) == 0 || len(values) == 0 { continue } if !strings.HasPrefix(key, dashOne) { if len(key) == 1 { key = dashOne + key } else { key = dashTwo + key } } args = append(args, key, values[len(values)-1]) } debug.Debugf("agent: %s", r.UserAgent()) debug.Debugf("path: %s", path) debug.Debugf("args: %q", args) buf := new(bytes.Buffer) statusCode := http.StatusOK if err := cmd.RunWith(args, buf, w, r.Method); err != nil { buf.Write([]byte(err.Error())) nativeError := err if werr, ok := err.(wrapError); ok { nativeError = werr.err } switch nativeError.(type) { case commandNotFoundError: statusCode = http.StatusNotFound case methodNotAllowedError: statusCode = http.StatusMethodNotAllowed default: statusCode = http.StatusInternalServerError } } debug.Debugf("resp: %s", buf.String()) w.WriteHeader(statusCode) w.Write(buf.Bytes()) }
go
func (cmd *Command) ServeHTTP(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { return } var ( path = r.URL.Path found = false ) if cmd.routersMap != nil { path, found = cmd.routersMap[path] } if !found { path = strings.TrimPrefix(r.URL.Path, "/") path = strings.TrimSuffix(path, "/") } router := strings.Split(path, "/") args := make([]string, 0, len(r.Form)*2+len(router)) for _, r := range router { args = append(args, r) } for key, values := range r.Form { if len(key) == 0 || len(values) == 0 { continue } if !strings.HasPrefix(key, dashOne) { if len(key) == 1 { key = dashOne + key } else { key = dashTwo + key } } args = append(args, key, values[len(values)-1]) } debug.Debugf("agent: %s", r.UserAgent()) debug.Debugf("path: %s", path) debug.Debugf("args: %q", args) buf := new(bytes.Buffer) statusCode := http.StatusOK if err := cmd.RunWith(args, buf, w, r.Method); err != nil { buf.Write([]byte(err.Error())) nativeError := err if werr, ok := err.(wrapError); ok { nativeError = werr.err } switch nativeError.(type) { case commandNotFoundError: statusCode = http.StatusNotFound case methodNotAllowedError: statusCode = http.StatusMethodNotAllowed default: statusCode = http.StatusInternalServerError } } debug.Debugf("resp: %s", buf.String()) w.WriteHeader(statusCode) w.Write(buf.Bytes()) }
[ "func", "(", "cmd", "*", "Command", ")", "ServeHTTP", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "if", "err", ":=", "r", ".", "ParseForm", "(", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n\n", "var", "(", "path", "=", "r", ".", "URL", ".", "Path", "\n", "found", "=", "false", "\n", ")", "\n", "if", "cmd", ".", "routersMap", "!=", "nil", "{", "path", ",", "found", "=", "cmd", ".", "routersMap", "[", "path", "]", "\n", "}", "\n", "if", "!", "found", "{", "path", "=", "strings", ".", "TrimPrefix", "(", "r", ".", "URL", ".", "Path", ",", "\"", "\"", ")", "\n", "path", "=", "strings", ".", "TrimSuffix", "(", "path", ",", "\"", "\"", ")", "\n", "}", "\n\n", "router", ":=", "strings", ".", "Split", "(", "path", ",", "\"", "\"", ")", "\n", "args", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "r", ".", "Form", ")", "*", "2", "+", "len", "(", "router", ")", ")", "\n", "for", "_", ",", "r", ":=", "range", "router", "{", "args", "=", "append", "(", "args", ",", "r", ")", "\n", "}", "\n", "for", "key", ",", "values", ":=", "range", "r", ".", "Form", "{", "if", "len", "(", "key", ")", "==", "0", "||", "len", "(", "values", ")", "==", "0", "{", "continue", "\n", "}", "\n", "if", "!", "strings", ".", "HasPrefix", "(", "key", ",", "dashOne", ")", "{", "if", "len", "(", "key", ")", "==", "1", "{", "key", "=", "dashOne", "+", "key", "\n", "}", "else", "{", "key", "=", "dashTwo", "+", "key", "\n", "}", "\n", "}", "\n", "args", "=", "append", "(", "args", ",", "key", ",", "values", "[", "len", "(", "values", ")", "-", "1", "]", ")", "\n", "}", "\n", "debug", ".", "Debugf", "(", "\"", "\"", ",", "r", ".", "UserAgent", "(", ")", ")", "\n", "debug", ".", "Debugf", "(", "\"", "\"", ",", "path", ")", "\n", "debug", ".", "Debugf", "(", "\"", "\"", ",", "args", ")", "\n\n", "buf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "statusCode", ":=", "http", ".", "StatusOK", "\n", "if", "err", ":=", "cmd", ".", "RunWith", "(", "args", ",", "buf", ",", "w", ",", "r", ".", "Method", ")", ";", "err", "!=", "nil", "{", "buf", ".", "Write", "(", "[", "]", "byte", "(", "err", ".", "Error", "(", ")", ")", ")", "\n", "nativeError", ":=", "err", "\n", "if", "werr", ",", "ok", ":=", "err", ".", "(", "wrapError", ")", ";", "ok", "{", "nativeError", "=", "werr", ".", "err", "\n", "}", "\n", "switch", "nativeError", ".", "(", "type", ")", "{", "case", "commandNotFoundError", ":", "statusCode", "=", "http", ".", "StatusNotFound", "\n\n", "case", "methodNotAllowedError", ":", "statusCode", "=", "http", ".", "StatusMethodNotAllowed", "\n\n", "default", ":", "statusCode", "=", "http", ".", "StatusInternalServerError", "\n", "}", "\n", "}", "\n", "debug", ".", "Debugf", "(", "\"", "\"", ",", "buf", ".", "String", "(", ")", ")", "\n", "w", ".", "WriteHeader", "(", "statusCode", ")", "\n", "w", ".", "Write", "(", "buf", ".", "Bytes", "(", ")", ")", "\n", "}" ]
// ServeHTTP implements HTTP handler
[ "ServeHTTP", "implements", "HTTP", "handler" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/http.go#L46-L107
13,679
mkideal/cli
http.go
ListenAndServeHTTP
func (cmd *Command) ListenAndServeHTTP(addr string) error { cmd.SetIsServer(true) return http.ListenAndServe(addr, cmd) }
go
func (cmd *Command) ListenAndServeHTTP(addr string) error { cmd.SetIsServer(true) return http.ListenAndServe(addr, cmd) }
[ "func", "(", "cmd", "*", "Command", ")", "ListenAndServeHTTP", "(", "addr", "string", ")", "error", "{", "cmd", ".", "SetIsServer", "(", "true", ")", "\n", "return", "http", ".", "ListenAndServe", "(", "addr", ",", "cmd", ")", "\n", "}" ]
// ListenAndServeHTTP set IsServer flag with true and startup http service
[ "ListenAndServeHTTP", "set", "IsServer", "flag", "with", "true", "and", "startup", "http", "service" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/http.go#L110-L113
13,680
mkideal/cli
http.go
Serve
func (cmd *Command) Serve(listeners ...net.Listener) (err error) { cmd.SetIsServer(true) var g sync.WaitGroup for _, ln := range listeners { g.Add(1) go func(ln net.Listener) { if e := http.Serve(ln, cmd); e != nil { panic(e.Error()) } g.Done() }(ln) } g.Wait() return }
go
func (cmd *Command) Serve(listeners ...net.Listener) (err error) { cmd.SetIsServer(true) var g sync.WaitGroup for _, ln := range listeners { g.Add(1) go func(ln net.Listener) { if e := http.Serve(ln, cmd); e != nil { panic(e.Error()) } g.Done() }(ln) } g.Wait() return }
[ "func", "(", "cmd", "*", "Command", ")", "Serve", "(", "listeners", "...", "net", ".", "Listener", ")", "(", "err", "error", ")", "{", "cmd", ".", "SetIsServer", "(", "true", ")", "\n", "var", "g", "sync", ".", "WaitGroup", "\n", "for", "_", ",", "ln", ":=", "range", "listeners", "{", "g", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", "ln", "net", ".", "Listener", ")", "{", "if", "e", ":=", "http", ".", "Serve", "(", "ln", ",", "cmd", ")", ";", "e", "!=", "nil", "{", "panic", "(", "e", ".", "Error", "(", ")", ")", "\n", "}", "\n", "g", ".", "Done", "(", ")", "\n", "}", "(", "ln", ")", "\n", "}", "\n", "g", ".", "Wait", "(", ")", "\n", "return", "\n", "}" ]
// Serve set IsServer with true and serve http with listeners
[ "Serve", "set", "IsServer", "with", "true", "and", "serve", "http", "with", "listeners" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/http.go#L116-L130
13,681
mkideal/cli
http.go
RPC
func (cmd *Command) RPC(httpc *http.Client, ctx *Context) error { addr := "http://rpc/" + ctx.Command().pathWithSep("/") method := "POST" if cmd.HTTPMethods != nil && len(cmd.HTTPMethods) > 0 { method = cmd.HTTPMethods[0] } var body io.Reader if values := ctx.FormValues(); values != nil { body = strings.NewReader(values.Encode()) } req, err := http.NewRequest(method, addr, body) if err != nil { return err } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("User-Agent", "cli-RPC") resp, err := httpc.Do(req) if err != nil { return err } defer resp.Body.Close() _, err = io.Copy(ctx, resp.Body) return err }
go
func (cmd *Command) RPC(httpc *http.Client, ctx *Context) error { addr := "http://rpc/" + ctx.Command().pathWithSep("/") method := "POST" if cmd.HTTPMethods != nil && len(cmd.HTTPMethods) > 0 { method = cmd.HTTPMethods[0] } var body io.Reader if values := ctx.FormValues(); values != nil { body = strings.NewReader(values.Encode()) } req, err := http.NewRequest(method, addr, body) if err != nil { return err } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("User-Agent", "cli-RPC") resp, err := httpc.Do(req) if err != nil { return err } defer resp.Body.Close() _, err = io.Copy(ctx, resp.Body) return err }
[ "func", "(", "cmd", "*", "Command", ")", "RPC", "(", "httpc", "*", "http", ".", "Client", ",", "ctx", "*", "Context", ")", "error", "{", "addr", ":=", "\"", "\"", "+", "ctx", ".", "Command", "(", ")", ".", "pathWithSep", "(", "\"", "\"", ")", "\n", "method", ":=", "\"", "\"", "\n", "if", "cmd", ".", "HTTPMethods", "!=", "nil", "&&", "len", "(", "cmd", ".", "HTTPMethods", ")", ">", "0", "{", "method", "=", "cmd", ".", "HTTPMethods", "[", "0", "]", "\n", "}", "\n", "var", "body", "io", ".", "Reader", "\n", "if", "values", ":=", "ctx", ".", "FormValues", "(", ")", ";", "values", "!=", "nil", "{", "body", "=", "strings", ".", "NewReader", "(", "values", ".", "Encode", "(", ")", ")", "\n", "}", "\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "method", ",", "addr", ",", "body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "resp", ",", "err", ":=", "httpc", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "_", ",", "err", "=", "io", ".", "Copy", "(", "ctx", ",", "resp", ".", "Body", ")", "\n", "return", "err", "\n", "}" ]
// RPC runs the command from remote
[ "RPC", "runs", "the", "command", "from", "remote" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/http.go#L133-L156
13,682
mkideal/cli
ext/shell.go
InstallBashCompletion
func InstallBashCompletion(root *cli.Command) error { if root.Name == "" { return fmt.Errorf("root command's name is empty") } compFilename := "." + root.Name + "_compeltion" compFilepath := filepath.Join(os.Getenv("HOME"), compFilename) compFile, err := os.OpenFile(compFilepath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666) if err != nil { return err } buff, err := genBashCompletion(root) if err != nil { return err } if _, err := compFile.Write(buff.Bytes()); err != nil { return err } bashrcFiles := []string{ ".bashrc", ".bash_profile", } var dstFile *os.File for _, bashFilename := range bashrcFiles { dstFilepath := filepath.Join(os.Getenv("HOME"), bashFilename) dstFile, err = os.OpenFile(dstFilepath, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666) if err == nil { break } } if dstFile == nil { return fmt.Errorf("no destination bash file") } data, err := ioutil.ReadAll(dstFile) if err != nil { return err } subslice := fmt.Sprintf("[ -f ~/%s ] && . ~/%s", compFilename, compFilename) if !bytes.Contains(data, []byte(subslice)) { _, err = dstFile.WriteString("\n#Auto-generated by cli\n" + subslice) } return err }
go
func InstallBashCompletion(root *cli.Command) error { if root.Name == "" { return fmt.Errorf("root command's name is empty") } compFilename := "." + root.Name + "_compeltion" compFilepath := filepath.Join(os.Getenv("HOME"), compFilename) compFile, err := os.OpenFile(compFilepath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666) if err != nil { return err } buff, err := genBashCompletion(root) if err != nil { return err } if _, err := compFile.Write(buff.Bytes()); err != nil { return err } bashrcFiles := []string{ ".bashrc", ".bash_profile", } var dstFile *os.File for _, bashFilename := range bashrcFiles { dstFilepath := filepath.Join(os.Getenv("HOME"), bashFilename) dstFile, err = os.OpenFile(dstFilepath, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666) if err == nil { break } } if dstFile == nil { return fmt.Errorf("no destination bash file") } data, err := ioutil.ReadAll(dstFile) if err != nil { return err } subslice := fmt.Sprintf("[ -f ~/%s ] && . ~/%s", compFilename, compFilename) if !bytes.Contains(data, []byte(subslice)) { _, err = dstFile.WriteString("\n#Auto-generated by cli\n" + subslice) } return err }
[ "func", "InstallBashCompletion", "(", "root", "*", "cli", ".", "Command", ")", "error", "{", "if", "root", ".", "Name", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "compFilename", ":=", "\"", "\"", "+", "root", ".", "Name", "+", "\"", "\"", "\n", "compFilepath", ":=", "filepath", ".", "Join", "(", "os", ".", "Getenv", "(", "\"", "\"", ")", ",", "compFilename", ")", "\n", "compFile", ",", "err", ":=", "os", ".", "OpenFile", "(", "compFilepath", ",", "os", ".", "O_WRONLY", "|", "os", ".", "O_TRUNC", "|", "os", ".", "O_CREATE", ",", "0666", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "buff", ",", "err", ":=", "genBashCompletion", "(", "root", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "_", ",", "err", ":=", "compFile", ".", "Write", "(", "buff", ".", "Bytes", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "bashrcFiles", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "}", "\n", "var", "dstFile", "*", "os", ".", "File", "\n", "for", "_", ",", "bashFilename", ":=", "range", "bashrcFiles", "{", "dstFilepath", ":=", "filepath", ".", "Join", "(", "os", ".", "Getenv", "(", "\"", "\"", ")", ",", "bashFilename", ")", "\n", "dstFile", ",", "err", "=", "os", ".", "OpenFile", "(", "dstFilepath", ",", "os", ".", "O_CREATE", "|", "os", ".", "O_APPEND", "|", "os", ".", "O_RDWR", ",", "0666", ")", "\n", "if", "err", "==", "nil", "{", "break", "\n", "}", "\n", "}", "\n", "if", "dstFile", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "data", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "dstFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "subslice", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "compFilename", ",", "compFilename", ")", "\n", "if", "!", "bytes", ".", "Contains", "(", "data", ",", "[", "]", "byte", "(", "subslice", ")", ")", "{", "_", ",", "err", "=", "dstFile", ".", "WriteString", "(", "\"", "\\n", "\\n", "\"", "+", "subslice", ")", "\n", "}", "\n\n", "return", "err", "\n", "}" ]
// InstallBashCompletion install bash_completion
[ "InstallBashCompletion", "install", "bash_completion" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/ext/shell.go#L15-L59
13,683
mkideal/cli
_examples/010-validator/main.go
Validate
func (argv *argT) Validate(ctx *cli.Context) error { if argv.Age < 0 || argv.Age > 300 { return fmt.Errorf("age %d out of range", argv.Age) } if argv.Gender != "male" && argv.Gender != "female" { return fmt.Errorf("invalid gender %s", ctx.Color().Yellow(argv.Gender)) } return nil }
go
func (argv *argT) Validate(ctx *cli.Context) error { if argv.Age < 0 || argv.Age > 300 { return fmt.Errorf("age %d out of range", argv.Age) } if argv.Gender != "male" && argv.Gender != "female" { return fmt.Errorf("invalid gender %s", ctx.Color().Yellow(argv.Gender)) } return nil }
[ "func", "(", "argv", "*", "argT", ")", "Validate", "(", "ctx", "*", "cli", ".", "Context", ")", "error", "{", "if", "argv", ".", "Age", "<", "0", "||", "argv", ".", "Age", ">", "300", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "argv", ".", "Age", ")", "\n", "}", "\n", "if", "argv", ".", "Gender", "!=", "\"", "\"", "&&", "argv", ".", "Gender", "!=", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ctx", ".", "Color", "(", ")", ".", "Yellow", "(", "argv", ".", "Gender", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate implements cli.Validator interface
[ "Validate", "implements", "cli", ".", "Validator", "interface" ]
41df2d00b0edfa4614da67cf68f41df9d4e55539
https://github.com/mkideal/cli/blob/41df2d00b0edfa4614da67cf68f41df9d4e55539/_examples/010-validator/main.go#L17-L25
13,684
nats-io/nuid
nuid.go
New
func New() *NUID { n := &NUID{ seq: prand.Int63n(maxSeq), inc: minInc + prand.Int63n(maxInc-minInc), pre: make([]byte, preLen), } n.RandomizePrefix() return n }
go
func New() *NUID { n := &NUID{ seq: prand.Int63n(maxSeq), inc: minInc + prand.Int63n(maxInc-minInc), pre: make([]byte, preLen), } n.RandomizePrefix() return n }
[ "func", "New", "(", ")", "*", "NUID", "{", "n", ":=", "&", "NUID", "{", "seq", ":", "prand", ".", "Int63n", "(", "maxSeq", ")", ",", "inc", ":", "minInc", "+", "prand", ".", "Int63n", "(", "maxInc", "-", "minInc", ")", ",", "pre", ":", "make", "(", "[", "]", "byte", ",", "preLen", ")", ",", "}", "\n", "n", ".", "RandomizePrefix", "(", ")", "\n", "return", "n", "\n", "}" ]
// New will generate a new NUID and properly initialize the prefix, sequential start, and sequential increment.
[ "New", "will", "generate", "a", "new", "NUID", "and", "properly", "initialize", "the", "prefix", "sequential", "start", "and", "sequential", "increment", "." ]
4b96681fa6d28dd0ab5fe79bac63b3a493d9ee94
https://github.com/nats-io/nuid/blob/4b96681fa6d28dd0ab5fe79bac63b3a493d9ee94/nuid.go#L75-L83
13,685
nats-io/nuid
nuid.go
Next
func Next() string { globalNUID.Lock() nuid := globalNUID.Next() globalNUID.Unlock() return nuid }
go
func Next() string { globalNUID.Lock() nuid := globalNUID.Next() globalNUID.Unlock() return nuid }
[ "func", "Next", "(", ")", "string", "{", "globalNUID", ".", "Lock", "(", ")", "\n", "nuid", ":=", "globalNUID", ".", "Next", "(", ")", "\n", "globalNUID", ".", "Unlock", "(", ")", "\n", "return", "nuid", "\n", "}" ]
// Generate the next NUID string from the global locked NUID instance.
[ "Generate", "the", "next", "NUID", "string", "from", "the", "global", "locked", "NUID", "instance", "." ]
4b96681fa6d28dd0ab5fe79bac63b3a493d9ee94
https://github.com/nats-io/nuid/blob/4b96681fa6d28dd0ab5fe79bac63b3a493d9ee94/nuid.go#L86-L91
13,686
nats-io/nuid
nuid.go
Next
func (n *NUID) Next() string { // Increment and capture. n.seq += n.inc if n.seq >= maxSeq { n.RandomizePrefix() n.resetSequential() } seq := n.seq // Copy prefix var b [totalLen]byte bs := b[:preLen] copy(bs, n.pre) // copy in the seq in base62. for i, l := len(b), seq; i > preLen; l /= base { i -= 1 b[i] = digits[l%base] } return string(b[:]) }
go
func (n *NUID) Next() string { // Increment and capture. n.seq += n.inc if n.seq >= maxSeq { n.RandomizePrefix() n.resetSequential() } seq := n.seq // Copy prefix var b [totalLen]byte bs := b[:preLen] copy(bs, n.pre) // copy in the seq in base62. for i, l := len(b), seq; i > preLen; l /= base { i -= 1 b[i] = digits[l%base] } return string(b[:]) }
[ "func", "(", "n", "*", "NUID", ")", "Next", "(", ")", "string", "{", "// Increment and capture.", "n", ".", "seq", "+=", "n", ".", "inc", "\n", "if", "n", ".", "seq", ">=", "maxSeq", "{", "n", ".", "RandomizePrefix", "(", ")", "\n", "n", ".", "resetSequential", "(", ")", "\n", "}", "\n", "seq", ":=", "n", ".", "seq", "\n\n", "// Copy prefix", "var", "b", "[", "totalLen", "]", "byte", "\n", "bs", ":=", "b", "[", ":", "preLen", "]", "\n", "copy", "(", "bs", ",", "n", ".", "pre", ")", "\n\n", "// copy in the seq in base62.", "for", "i", ",", "l", ":=", "len", "(", "b", ")", ",", "seq", ";", "i", ">", "preLen", ";", "l", "/=", "base", "{", "i", "-=", "1", "\n", "b", "[", "i", "]", "=", "digits", "[", "l", "%", "base", "]", "\n", "}", "\n", "return", "string", "(", "b", "[", ":", "]", ")", "\n", "}" ]
// Generate the next NUID string.
[ "Generate", "the", "next", "NUID", "string", "." ]
4b96681fa6d28dd0ab5fe79bac63b3a493d9ee94
https://github.com/nats-io/nuid/blob/4b96681fa6d28dd0ab5fe79bac63b3a493d9ee94/nuid.go#L94-L114
13,687
nats-io/nuid
nuid.go
resetSequential
func (n *NUID) resetSequential() { n.seq = prand.Int63n(maxSeq) n.inc = minInc + prand.Int63n(maxInc-minInc) }
go
func (n *NUID) resetSequential() { n.seq = prand.Int63n(maxSeq) n.inc = minInc + prand.Int63n(maxInc-minInc) }
[ "func", "(", "n", "*", "NUID", ")", "resetSequential", "(", ")", "{", "n", ".", "seq", "=", "prand", ".", "Int63n", "(", "maxSeq", ")", "\n", "n", ".", "inc", "=", "minInc", "+", "prand", ".", "Int63n", "(", "maxInc", "-", "minInc", ")", "\n", "}" ]
// Resets the sequential portion of the NUID.
[ "Resets", "the", "sequential", "portion", "of", "the", "NUID", "." ]
4b96681fa6d28dd0ab5fe79bac63b3a493d9ee94
https://github.com/nats-io/nuid/blob/4b96681fa6d28dd0ab5fe79bac63b3a493d9ee94/nuid.go#L117-L120
13,688
abiosoft/ishell
command.go
AddCmd
func (c *Cmd) AddCmd(cmd *Cmd) { if c.children == nil { c.children = make(map[string]*Cmd) } c.children[cmd.Name] = cmd }
go
func (c *Cmd) AddCmd(cmd *Cmd) { if c.children == nil { c.children = make(map[string]*Cmd) } c.children[cmd.Name] = cmd }
[ "func", "(", "c", "*", "Cmd", ")", "AddCmd", "(", "cmd", "*", "Cmd", ")", "{", "if", "c", ".", "children", "==", "nil", "{", "c", ".", "children", "=", "make", "(", "map", "[", "string", "]", "*", "Cmd", ")", "\n", "}", "\n", "c", ".", "children", "[", "cmd", ".", "Name", "]", "=", "cmd", "\n", "}" ]
// AddCmd adds cmd as a subcommand.
[ "AddCmd", "adds", "cmd", "as", "a", "subcommand", "." ]
8b8aa74a85127192b469453a72fd7971b47481fb
https://github.com/abiosoft/ishell/blob/8b8aa74a85127192b469453a72fd7971b47481fb/command.go#L36-L41
13,689
abiosoft/ishell
command.go
Children
func (c *Cmd) Children() []*Cmd { var cmds []*Cmd for _, cmd := range c.children { cmds = append(cmds, cmd) } sort.Sort(cmdSorter(cmds)) return cmds }
go
func (c *Cmd) Children() []*Cmd { var cmds []*Cmd for _, cmd := range c.children { cmds = append(cmds, cmd) } sort.Sort(cmdSorter(cmds)) return cmds }
[ "func", "(", "c", "*", "Cmd", ")", "Children", "(", ")", "[", "]", "*", "Cmd", "{", "var", "cmds", "[", "]", "*", "Cmd", "\n", "for", "_", ",", "cmd", ":=", "range", "c", ".", "children", "{", "cmds", "=", "append", "(", "cmds", ",", "cmd", ")", "\n", "}", "\n", "sort", ".", "Sort", "(", "cmdSorter", "(", "cmds", ")", ")", "\n", "return", "cmds", "\n", "}" ]
// Children returns the subcommands of c.
[ "Children", "returns", "the", "subcommands", "of", "c", "." ]
8b8aa74a85127192b469453a72fd7971b47481fb
https://github.com/abiosoft/ishell/blob/8b8aa74a85127192b469453a72fd7971b47481fb/command.go#L49-L56
13,690
abiosoft/ishell
command.go
HelpText
func (c Cmd) HelpText() string { var b bytes.Buffer p := func(s ...interface{}) { fmt.Fprintln(&b) if len(s) > 0 { fmt.Fprintln(&b, s...) } } if c.LongHelp != "" { p(c.LongHelp) } else if c.Help != "" { p(c.Help) } else if c.Name != "" { p(c.Name, "has no help") } if c.hasSubcommand() { p("Commands:") w := tabwriter.NewWriter(&b, 0, 4, 2, ' ', 0) for _, child := range c.Children() { fmt.Fprintf(w, "\t%s\t\t\t%s\n", child.Name, child.Help) } w.Flush() p() } return b.String() }
go
func (c Cmd) HelpText() string { var b bytes.Buffer p := func(s ...interface{}) { fmt.Fprintln(&b) if len(s) > 0 { fmt.Fprintln(&b, s...) } } if c.LongHelp != "" { p(c.LongHelp) } else if c.Help != "" { p(c.Help) } else if c.Name != "" { p(c.Name, "has no help") } if c.hasSubcommand() { p("Commands:") w := tabwriter.NewWriter(&b, 0, 4, 2, ' ', 0) for _, child := range c.Children() { fmt.Fprintf(w, "\t%s\t\t\t%s\n", child.Name, child.Help) } w.Flush() p() } return b.String() }
[ "func", "(", "c", "Cmd", ")", "HelpText", "(", ")", "string", "{", "var", "b", "bytes", ".", "Buffer", "\n", "p", ":=", "func", "(", "s", "...", "interface", "{", "}", ")", "{", "fmt", ".", "Fprintln", "(", "&", "b", ")", "\n", "if", "len", "(", "s", ")", ">", "0", "{", "fmt", ".", "Fprintln", "(", "&", "b", ",", "s", "...", ")", "\n", "}", "\n", "}", "\n", "if", "c", ".", "LongHelp", "!=", "\"", "\"", "{", "p", "(", "c", ".", "LongHelp", ")", "\n", "}", "else", "if", "c", ".", "Help", "!=", "\"", "\"", "{", "p", "(", "c", ".", "Help", ")", "\n", "}", "else", "if", "c", ".", "Name", "!=", "\"", "\"", "{", "p", "(", "c", ".", "Name", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "hasSubcommand", "(", ")", "{", "p", "(", "\"", "\"", ")", "\n", "w", ":=", "tabwriter", ".", "NewWriter", "(", "&", "b", ",", "0", ",", "4", ",", "2", ",", "' '", ",", "0", ")", "\n", "for", "_", ",", "child", ":=", "range", "c", ".", "Children", "(", ")", "{", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\t", "\\t", "\\t", "\\t", "\\n", "\"", ",", "child", ".", "Name", ",", "child", ".", "Help", ")", "\n", "}", "\n", "w", ".", "Flush", "(", ")", "\n", "p", "(", ")", "\n", "}", "\n", "return", "b", ".", "String", "(", ")", "\n", "}" ]
// HelpText returns the computed help of the command and its subcommands.
[ "HelpText", "returns", "the", "computed", "help", "of", "the", "command", "and", "its", "subcommands", "." ]
8b8aa74a85127192b469453a72fd7971b47481fb
https://github.com/abiosoft/ishell/blob/8b8aa74a85127192b469453a72fd7971b47481fb/command.go#L69-L94
13,691
abiosoft/ishell
command.go
findChildCmd
func (c *Cmd) findChildCmd(name string) *Cmd { // find perfect matches first if cmd, ok := c.children[name]; ok { return cmd } // find alias matching the name for _, cmd := range c.children { for _, alias := range cmd.Aliases { if alias == name { return cmd } } } return nil }
go
func (c *Cmd) findChildCmd(name string) *Cmd { // find perfect matches first if cmd, ok := c.children[name]; ok { return cmd } // find alias matching the name for _, cmd := range c.children { for _, alias := range cmd.Aliases { if alias == name { return cmd } } } return nil }
[ "func", "(", "c", "*", "Cmd", ")", "findChildCmd", "(", "name", "string", ")", "*", "Cmd", "{", "// find perfect matches first", "if", "cmd", ",", "ok", ":=", "c", ".", "children", "[", "name", "]", ";", "ok", "{", "return", "cmd", "\n", "}", "\n\n", "// find alias matching the name", "for", "_", ",", "cmd", ":=", "range", "c", ".", "children", "{", "for", "_", ",", "alias", ":=", "range", "cmd", ".", "Aliases", "{", "if", "alias", "==", "name", "{", "return", "cmd", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// findChildCmd returns the subcommand with matching name or alias.
[ "findChildCmd", "returns", "the", "subcommand", "with", "matching", "name", "or", "alias", "." ]
8b8aa74a85127192b469453a72fd7971b47481fb
https://github.com/abiosoft/ishell/blob/8b8aa74a85127192b469453a72fd7971b47481fb/command.go#L97-L113
13,692
abiosoft/ishell
command.go
FindCmd
func (c Cmd) FindCmd(args []string) (*Cmd, []string) { var cmd *Cmd for i, arg := range args { if cmd1 := c.findChildCmd(arg); cmd1 != nil { cmd = cmd1 c = *cmd continue } return cmd, args[i:] } return cmd, nil }
go
func (c Cmd) FindCmd(args []string) (*Cmd, []string) { var cmd *Cmd for i, arg := range args { if cmd1 := c.findChildCmd(arg); cmd1 != nil { cmd = cmd1 c = *cmd continue } return cmd, args[i:] } return cmd, nil }
[ "func", "(", "c", "Cmd", ")", "FindCmd", "(", "args", "[", "]", "string", ")", "(", "*", "Cmd", ",", "[", "]", "string", ")", "{", "var", "cmd", "*", "Cmd", "\n", "for", "i", ",", "arg", ":=", "range", "args", "{", "if", "cmd1", ":=", "c", ".", "findChildCmd", "(", "arg", ")", ";", "cmd1", "!=", "nil", "{", "cmd", "=", "cmd1", "\n", "c", "=", "*", "cmd", "\n", "continue", "\n", "}", "\n", "return", "cmd", ",", "args", "[", "i", ":", "]", "\n", "}", "\n", "return", "cmd", ",", "nil", "\n", "}" ]
// FindCmd finds the matching Cmd for args. // It returns the Cmd and the remaining args.
[ "FindCmd", "finds", "the", "matching", "Cmd", "for", "args", ".", "It", "returns", "the", "Cmd", "and", "the", "remaining", "args", "." ]
8b8aa74a85127192b469453a72fd7971b47481fb
https://github.com/abiosoft/ishell/blob/8b8aa74a85127192b469453a72fd7971b47481fb/command.go#L117-L128
13,693
abiosoft/ishell
ishell.go
NewWithConfig
func NewWithConfig(conf *readline.Config) *Shell { rl, err := readline.NewEx(conf) if err != nil { log.Println("Shell or operating system not supported.") log.Fatal(err) } return NewWithReadline(rl) }
go
func NewWithConfig(conf *readline.Config) *Shell { rl, err := readline.NewEx(conf) if err != nil { log.Println("Shell or operating system not supported.") log.Fatal(err) } return NewWithReadline(rl) }
[ "func", "NewWithConfig", "(", "conf", "*", "readline", ".", "Config", ")", "*", "Shell", "{", "rl", ",", "err", ":=", "readline", ".", "NewEx", "(", "conf", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Println", "(", "\"", "\"", ")", "\n", "log", ".", "Fatal", "(", "err", ")", "\n", "}", "\n\n", "return", "NewWithReadline", "(", "rl", ")", "\n", "}" ]
// NewWithConfig creates a new shell with custom readline config.
[ "NewWithConfig", "creates", "a", "new", "shell", "with", "custom", "readline", "config", "." ]
8b8aa74a85127192b469453a72fd7971b47481fb
https://github.com/abiosoft/ishell/blob/8b8aa74a85127192b469453a72fd7971b47481fb/ishell.go#L71-L79
13,694
abiosoft/ishell
ishell.go
NewWithReadline
func NewWithReadline(rl *readline.Instance) *Shell { shell := &Shell{ rootCmd: &Cmd{}, reader: &shellReader{ scanner: rl, prompt: rl.Config.Prompt, multiPrompt: defaultMultiPrompt, showPrompt: true, buf: &bytes.Buffer{}, completer: readline.NewPrefixCompleter(), }, writer: rl.Config.Stdout, autoHelp: true, } shell.Actions = &shellActionsImpl{Shell: shell} shell.progressBar = newProgressBar(shell) addDefaultFuncs(shell) return shell }
go
func NewWithReadline(rl *readline.Instance) *Shell { shell := &Shell{ rootCmd: &Cmd{}, reader: &shellReader{ scanner: rl, prompt: rl.Config.Prompt, multiPrompt: defaultMultiPrompt, showPrompt: true, buf: &bytes.Buffer{}, completer: readline.NewPrefixCompleter(), }, writer: rl.Config.Stdout, autoHelp: true, } shell.Actions = &shellActionsImpl{Shell: shell} shell.progressBar = newProgressBar(shell) addDefaultFuncs(shell) return shell }
[ "func", "NewWithReadline", "(", "rl", "*", "readline", ".", "Instance", ")", "*", "Shell", "{", "shell", ":=", "&", "Shell", "{", "rootCmd", ":", "&", "Cmd", "{", "}", ",", "reader", ":", "&", "shellReader", "{", "scanner", ":", "rl", ",", "prompt", ":", "rl", ".", "Config", ".", "Prompt", ",", "multiPrompt", ":", "defaultMultiPrompt", ",", "showPrompt", ":", "true", ",", "buf", ":", "&", "bytes", ".", "Buffer", "{", "}", ",", "completer", ":", "readline", ".", "NewPrefixCompleter", "(", ")", ",", "}", ",", "writer", ":", "rl", ".", "Config", ".", "Stdout", ",", "autoHelp", ":", "true", ",", "}", "\n", "shell", ".", "Actions", "=", "&", "shellActionsImpl", "{", "Shell", ":", "shell", "}", "\n", "shell", ".", "progressBar", "=", "newProgressBar", "(", "shell", ")", "\n", "addDefaultFuncs", "(", "shell", ")", "\n", "return", "shell", "\n", "}" ]
// NewWithReadline creates a new shell with a custom readline instance.
[ "NewWithReadline", "creates", "a", "new", "shell", "with", "a", "custom", "readline", "instance", "." ]
8b8aa74a85127192b469453a72fd7971b47481fb
https://github.com/abiosoft/ishell/blob/8b8aa74a85127192b469453a72fd7971b47481fb/ishell.go#L82-L100
13,695
abiosoft/ishell
ishell.go
Active
func (s *Shell) Active() bool { s.activeMutex.RLock() defer s.activeMutex.RUnlock() return s.active }
go
func (s *Shell) Active() bool { s.activeMutex.RLock() defer s.activeMutex.RUnlock() return s.active }
[ "func", "(", "s", "*", "Shell", ")", "Active", "(", ")", "bool", "{", "s", ".", "activeMutex", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "activeMutex", ".", "RUnlock", "(", ")", "\n", "return", "s", ".", "active", "\n", "}" ]
// Active tells if the shell is active. i.e. Start is previously called.
[ "Active", "tells", "if", "the", "shell", "is", "active", ".", "i", ".", "e", ".", "Start", "is", "previously", "called", "." ]
8b8aa74a85127192b469453a72fd7971b47481fb
https://github.com/abiosoft/ishell/blob/8b8aa74a85127192b469453a72fd7971b47481fb/ishell.go#L220-L224
13,696
abiosoft/ishell
ishell.go
CustomCompleter
func (s *Shell) CustomCompleter(completer readline.AutoCompleter) { s.customCompleter = true s.setCompleter(completer) }
go
func (s *Shell) CustomCompleter(completer readline.AutoCompleter) { s.customCompleter = true s.setCompleter(completer) }
[ "func", "(", "s", "*", "Shell", ")", "CustomCompleter", "(", "completer", "readline", ".", "AutoCompleter", ")", "{", "s", ".", "customCompleter", "=", "true", "\n", "s", ".", "setCompleter", "(", "completer", ")", "\n", "}" ]
// CustomCompleter allows use of custom implementation of readline.Autocompleter.
[ "CustomCompleter", "allows", "use", "of", "custom", "implementation", "of", "readline", ".", "Autocompleter", "." ]
8b8aa74a85127192b469453a72fd7971b47481fb
https://github.com/abiosoft/ishell/blob/8b8aa74a85127192b469453a72fd7971b47481fb/ishell.go#L371-L374
13,697
abiosoft/ishell
ishell.go
SetHistoryPath
func (s *Shell) SetHistoryPath(path string) { // Using scanner.SetHistoryPath doesn't initialize things properly and // history file is never written. Simpler to just create a new readline // Instance. config := s.reader.scanner.Config.Clone() config.HistoryFile = path s.reader.scanner, _ = readline.NewEx(config) }
go
func (s *Shell) SetHistoryPath(path string) { // Using scanner.SetHistoryPath doesn't initialize things properly and // history file is never written. Simpler to just create a new readline // Instance. config := s.reader.scanner.Config.Clone() config.HistoryFile = path s.reader.scanner, _ = readline.NewEx(config) }
[ "func", "(", "s", "*", "Shell", ")", "SetHistoryPath", "(", "path", "string", ")", "{", "// Using scanner.SetHistoryPath doesn't initialize things properly and", "// history file is never written. Simpler to just create a new readline", "// Instance.", "config", ":=", "s", ".", "reader", ".", "scanner", ".", "Config", ".", "Clone", "(", ")", "\n", "config", ".", "HistoryFile", "=", "path", "\n", "s", ".", "reader", ".", "scanner", ",", "_", "=", "readline", ".", "NewEx", "(", "config", ")", "\n", "}" ]
// SetHistoryPath sets where readlines history file location. Use an empty // string to disable history file. It is empty by default.
[ "SetHistoryPath", "sets", "where", "readlines", "history", "file", "location", ".", "Use", "an", "empty", "string", "to", "disable", "history", "file", ".", "It", "is", "empty", "by", "default", "." ]
8b8aa74a85127192b469453a72fd7971b47481fb
https://github.com/abiosoft/ishell/blob/8b8aa74a85127192b469453a72fd7971b47481fb/ishell.go#L418-L425
13,698
abiosoft/ishell
ishell.go
SetHomeHistoryPath
func (s *Shell) SetHomeHistoryPath(path string) { home := os.Getenv("HOME") if runtime.GOOS == "windows" { home = os.Getenv("USERPROFILE") } abspath := filepath.Join(home, path) s.SetHistoryPath(abspath) }
go
func (s *Shell) SetHomeHistoryPath(path string) { home := os.Getenv("HOME") if runtime.GOOS == "windows" { home = os.Getenv("USERPROFILE") } abspath := filepath.Join(home, path) s.SetHistoryPath(abspath) }
[ "func", "(", "s", "*", "Shell", ")", "SetHomeHistoryPath", "(", "path", "string", ")", "{", "home", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "if", "runtime", ".", "GOOS", "==", "\"", "\"", "{", "home", "=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "}", "\n", "abspath", ":=", "filepath", ".", "Join", "(", "home", ",", "path", ")", "\n", "s", ".", "SetHistoryPath", "(", "abspath", ")", "\n", "}" ]
// SetHomeHistoryPath is a convenience method that sets the history path // in user's home directory.
[ "SetHomeHistoryPath", "is", "a", "convenience", "method", "that", "sets", "the", "history", "path", "in", "user", "s", "home", "directory", "." ]
8b8aa74a85127192b469453a72fd7971b47481fb
https://github.com/abiosoft/ishell/blob/8b8aa74a85127192b469453a72fd7971b47481fb/ishell.go#L429-L436
13,699
abiosoft/ishell
ishell.go
SetPager
func (s *Shell) SetPager(pager string, args []string) { s.pager = pager s.pagerArgs = args }
go
func (s *Shell) SetPager(pager string, args []string) { s.pager = pager s.pagerArgs = args }
[ "func", "(", "s", "*", "Shell", ")", "SetPager", "(", "pager", "string", ",", "args", "[", "]", "string", ")", "{", "s", ".", "pager", "=", "pager", "\n", "s", ".", "pagerArgs", "=", "args", "\n", "}" ]
// SetPager sets the pager and its arguments for paged output
[ "SetPager", "sets", "the", "pager", "and", "its", "arguments", "for", "paged", "output" ]
8b8aa74a85127192b469453a72fd7971b47481fb
https://github.com/abiosoft/ishell/blob/8b8aa74a85127192b469453a72fd7971b47481fb/ishell.go#L444-L447