repo
stringlengths 5
67
| path
stringlengths 4
218
| func_name
stringlengths 0
151
| original_string
stringlengths 52
373k
| language
stringclasses 6
values | code
stringlengths 52
373k
| code_tokens
listlengths 10
512
| docstring
stringlengths 3
47.2k
| docstring_tokens
listlengths 3
234
| sha
stringlengths 40
40
| url
stringlengths 85
339
| partition
stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
justinfx/gofileseq
|
fileseq.go
|
FramesToFrameRange
|
func FramesToFrameRange(frames []int, sorted bool, zfill int) string {
count := len(frames)
if count == 0 {
return ""
}
if count == 1 {
return zfillInt(frames[0], zfill)
}
if sorted {
sort.Ints(frames)
}
var i, frame, step int
var start, end string
var buf strings.Builder
// Keep looping until all frames are consumed
for len(frames) > 0 {
count = len(frames)
// If we get to the last element, just write it
// and end
if count <= 2 {
for _, frame = range frames {
if buf.Len() > 0 {
buf.WriteString(",")
}
buf.WriteString(zfillInt(frame, zfill))
}
break
}
// At this point, we have 3 or more frames to check.
// Scan the current window of the slice to see how
// many frames we can consume into a group
step = frames[1] - frames[0]
for i = 0; i < len(frames)-1; i++ {
// We have scanned as many frames as we can
// for this group. Now write them and stop
// looping on this window
if (frames[i+1] - frames[i]) != step {
break
}
}
// Subsequent groups are comma-separated
if buf.Len() > 0 {
buf.WriteString(",")
}
// We only have a single frame to write for this group
if i == 0 {
buf.WriteString(zfillInt(frames[0], zfill))
frames = frames[1:]
continue
}
// First do a check to see if we could have gotten a larger range
// out of subsequent values with a different step size
if i == 1 && count > 3 {
// Check if the next two pairwise frames have the same step.
// If so, then it is better than our current grouping.
if (frames[2] - frames[1]) == (frames[3] - frames[2]) {
// Just consume the first frame, and allow the next
// loop to scan the new stepping
buf.WriteString(zfillInt(frames[0], zfill))
frames = frames[1:]
continue
}
}
// Otherwise write out this step range
start = zfillInt(frames[0], zfill)
end = zfillInt(frames[i], zfill)
buf.WriteString(fmt.Sprintf("%s-%s", start, end))
if step > 1 {
buf.WriteString(fmt.Sprintf("x%d", step))
}
frames = frames[i+1:]
}
return buf.String()
}
|
go
|
func FramesToFrameRange(frames []int, sorted bool, zfill int) string {
count := len(frames)
if count == 0 {
return ""
}
if count == 1 {
return zfillInt(frames[0], zfill)
}
if sorted {
sort.Ints(frames)
}
var i, frame, step int
var start, end string
var buf strings.Builder
// Keep looping until all frames are consumed
for len(frames) > 0 {
count = len(frames)
// If we get to the last element, just write it
// and end
if count <= 2 {
for _, frame = range frames {
if buf.Len() > 0 {
buf.WriteString(",")
}
buf.WriteString(zfillInt(frame, zfill))
}
break
}
// At this point, we have 3 or more frames to check.
// Scan the current window of the slice to see how
// many frames we can consume into a group
step = frames[1] - frames[0]
for i = 0; i < len(frames)-1; i++ {
// We have scanned as many frames as we can
// for this group. Now write them and stop
// looping on this window
if (frames[i+1] - frames[i]) != step {
break
}
}
// Subsequent groups are comma-separated
if buf.Len() > 0 {
buf.WriteString(",")
}
// We only have a single frame to write for this group
if i == 0 {
buf.WriteString(zfillInt(frames[0], zfill))
frames = frames[1:]
continue
}
// First do a check to see if we could have gotten a larger range
// out of subsequent values with a different step size
if i == 1 && count > 3 {
// Check if the next two pairwise frames have the same step.
// If so, then it is better than our current grouping.
if (frames[2] - frames[1]) == (frames[3] - frames[2]) {
// Just consume the first frame, and allow the next
// loop to scan the new stepping
buf.WriteString(zfillInt(frames[0], zfill))
frames = frames[1:]
continue
}
}
// Otherwise write out this step range
start = zfillInt(frames[0], zfill)
end = zfillInt(frames[i], zfill)
buf.WriteString(fmt.Sprintf("%s-%s", start, end))
if step > 1 {
buf.WriteString(fmt.Sprintf("x%d", step))
}
frames = frames[i+1:]
}
return buf.String()
}
|
[
"func",
"FramesToFrameRange",
"(",
"frames",
"[",
"]",
"int",
",",
"sorted",
"bool",
",",
"zfill",
"int",
")",
"string",
"{",
"count",
":=",
"len",
"(",
"frames",
")",
"\n",
"if",
"count",
"==",
"0",
"{",
"return",
"\"\"",
"\n",
"}",
"\n",
"if",
"count",
"==",
"1",
"{",
"return",
"zfillInt",
"(",
"frames",
"[",
"0",
"]",
",",
"zfill",
")",
"\n",
"}",
"\n",
"if",
"sorted",
"{",
"sort",
".",
"Ints",
"(",
"frames",
")",
"\n",
"}",
"\n",
"var",
"i",
",",
"frame",
",",
"step",
"int",
"\n",
"var",
"start",
",",
"end",
"string",
"\n",
"var",
"buf",
"strings",
".",
"Builder",
"\n",
"for",
"len",
"(",
"frames",
")",
">",
"0",
"{",
"count",
"=",
"len",
"(",
"frames",
")",
"\n",
"if",
"count",
"<=",
"2",
"{",
"for",
"_",
",",
"frame",
"=",
"range",
"frames",
"{",
"if",
"buf",
".",
"Len",
"(",
")",
">",
"0",
"{",
"buf",
".",
"WriteString",
"(",
"\",\"",
")",
"\n",
"}",
"\n",
"buf",
".",
"WriteString",
"(",
"zfillInt",
"(",
"frame",
",",
"zfill",
")",
")",
"\n",
"}",
"\n",
"break",
"\n",
"}",
"\n",
"step",
"=",
"frames",
"[",
"1",
"]",
"-",
"frames",
"[",
"0",
"]",
"\n",
"for",
"i",
"=",
"0",
";",
"i",
"<",
"len",
"(",
"frames",
")",
"-",
"1",
";",
"i",
"++",
"{",
"if",
"(",
"frames",
"[",
"i",
"+",
"1",
"]",
"-",
"frames",
"[",
"i",
"]",
")",
"!=",
"step",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"buf",
".",
"Len",
"(",
")",
">",
"0",
"{",
"buf",
".",
"WriteString",
"(",
"\",\"",
")",
"\n",
"}",
"\n",
"if",
"i",
"==",
"0",
"{",
"buf",
".",
"WriteString",
"(",
"zfillInt",
"(",
"frames",
"[",
"0",
"]",
",",
"zfill",
")",
")",
"\n",
"frames",
"=",
"frames",
"[",
"1",
":",
"]",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"i",
"==",
"1",
"&&",
"count",
">",
"3",
"{",
"if",
"(",
"frames",
"[",
"2",
"]",
"-",
"frames",
"[",
"1",
"]",
")",
"==",
"(",
"frames",
"[",
"3",
"]",
"-",
"frames",
"[",
"2",
"]",
")",
"{",
"buf",
".",
"WriteString",
"(",
"zfillInt",
"(",
"frames",
"[",
"0",
"]",
",",
"zfill",
")",
")",
"\n",
"frames",
"=",
"frames",
"[",
"1",
":",
"]",
"\n",
"continue",
"\n",
"}",
"\n",
"}",
"\n",
"start",
"=",
"zfillInt",
"(",
"frames",
"[",
"0",
"]",
",",
"zfill",
")",
"\n",
"end",
"=",
"zfillInt",
"(",
"frames",
"[",
"i",
"]",
",",
"zfill",
")",
"\n",
"buf",
".",
"WriteString",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"%s-%s\"",
",",
"start",
",",
"end",
")",
")",
"\n",
"if",
"step",
">",
"1",
"{",
"buf",
".",
"WriteString",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"x%d\"",
",",
"step",
")",
")",
"\n",
"}",
"\n",
"frames",
"=",
"frames",
"[",
"i",
"+",
"1",
":",
"]",
"\n",
"}",
"\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}"
] |
// FramesToFrameRange takes a slice of frame numbers and
// compresses them into a frame range string.
//
// If sorted == true, pre-sort the frames instead of respecting
// their current order in the range.
//
// If zfill > 1, then pad out each number with "0" to the given
// total width.
|
[
"FramesToFrameRange",
"takes",
"a",
"slice",
"of",
"frame",
"numbers",
"and",
"compresses",
"them",
"into",
"a",
"frame",
"range",
"string",
".",
"If",
"sorted",
"==",
"true",
"pre",
"-",
"sort",
"the",
"frames",
"instead",
"of",
"respecting",
"their",
"current",
"order",
"in",
"the",
"range",
".",
"If",
"zfill",
">",
"1",
"then",
"pad",
"out",
"each",
"number",
"with",
"0",
"to",
"the",
"given",
"total",
"width",
"."
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/fileseq.go#L89-L171
|
test
|
justinfx/gofileseq
|
fileseq.go
|
frameRangeMatches
|
func frameRangeMatches(frange string) ([][]string, error) {
for _, k := range defaultPadding.AllChars() {
frange = strings.Replace(frange, k, "", -1)
}
var (
matched bool
match []string
rx *regexp.Regexp
)
frange = strings.Replace(frange, " ", "", -1)
// For each comma-sep component, we will parse a frame range
parts := strings.Split(frange, ",")
size := len(parts)
matches := make([][]string, size, size)
for i, part := range parts {
matched = false
// Build up frames for all comma-sep components
for _, rx = range rangePatterns {
if match = rx.FindStringSubmatch(part); match == nil {
continue
}
matched = true
matches[i] = match[1:]
}
// If any component of the comma-sep frame range fails to
// parse, we bail out
if !matched {
err := fmt.Errorf("Failed to parse frame range: %s on part %q", frange, part)
return nil, err
}
}
return matches, nil
}
|
go
|
func frameRangeMatches(frange string) ([][]string, error) {
for _, k := range defaultPadding.AllChars() {
frange = strings.Replace(frange, k, "", -1)
}
var (
matched bool
match []string
rx *regexp.Regexp
)
frange = strings.Replace(frange, " ", "", -1)
// For each comma-sep component, we will parse a frame range
parts := strings.Split(frange, ",")
size := len(parts)
matches := make([][]string, size, size)
for i, part := range parts {
matched = false
// Build up frames for all comma-sep components
for _, rx = range rangePatterns {
if match = rx.FindStringSubmatch(part); match == nil {
continue
}
matched = true
matches[i] = match[1:]
}
// If any component of the comma-sep frame range fails to
// parse, we bail out
if !matched {
err := fmt.Errorf("Failed to parse frame range: %s on part %q", frange, part)
return nil, err
}
}
return matches, nil
}
|
[
"func",
"frameRangeMatches",
"(",
"frange",
"string",
")",
"(",
"[",
"]",
"[",
"]",
"string",
",",
"error",
")",
"{",
"for",
"_",
",",
"k",
":=",
"range",
"defaultPadding",
".",
"AllChars",
"(",
")",
"{",
"frange",
"=",
"strings",
".",
"Replace",
"(",
"frange",
",",
"k",
",",
"\"\"",
",",
"-",
"1",
")",
"\n",
"}",
"\n",
"var",
"(",
"matched",
"bool",
"\n",
"match",
"[",
"]",
"string",
"\n",
"rx",
"*",
"regexp",
".",
"Regexp",
"\n",
")",
"\n",
"frange",
"=",
"strings",
".",
"Replace",
"(",
"frange",
",",
"\" \"",
",",
"\"\"",
",",
"-",
"1",
")",
"\n",
"parts",
":=",
"strings",
".",
"Split",
"(",
"frange",
",",
"\",\"",
")",
"\n",
"size",
":=",
"len",
"(",
"parts",
")",
"\n",
"matches",
":=",
"make",
"(",
"[",
"]",
"[",
"]",
"string",
",",
"size",
",",
"size",
")",
"\n",
"for",
"i",
",",
"part",
":=",
"range",
"parts",
"{",
"matched",
"=",
"false",
"\n",
"for",
"_",
",",
"rx",
"=",
"range",
"rangePatterns",
"{",
"if",
"match",
"=",
"rx",
".",
"FindStringSubmatch",
"(",
"part",
")",
";",
"match",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"matched",
"=",
"true",
"\n",
"matches",
"[",
"i",
"]",
"=",
"match",
"[",
"1",
":",
"]",
"\n",
"}",
"\n",
"if",
"!",
"matched",
"{",
"err",
":=",
"fmt",
".",
"Errorf",
"(",
"\"Failed to parse frame range: %s on part %q\"",
",",
"frange",
",",
"part",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"matches",
",",
"nil",
"\n",
"}"
] |
// frameRangeMatches breaks down the string frame range
// into groups of range matches, for further processing.
|
[
"frameRangeMatches",
"breaks",
"down",
"the",
"string",
"frame",
"range",
"into",
"groups",
"of",
"range",
"matches",
"for",
"further",
"processing",
"."
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/fileseq.go#L175-L215
|
test
|
justinfx/gofileseq
|
fileseq.go
|
toRange
|
func toRange(start, end, step int) []int {
nums := []int{}
if step < 1 {
step = 1
}
if start <= end {
for i := start; i <= end; {
nums = append(nums, i)
i += step
}
} else {
for i := start; i >= end; {
nums = append(nums, i)
i -= step
}
}
return nums
}
|
go
|
func toRange(start, end, step int) []int {
nums := []int{}
if step < 1 {
step = 1
}
if start <= end {
for i := start; i <= end; {
nums = append(nums, i)
i += step
}
} else {
for i := start; i >= end; {
nums = append(nums, i)
i -= step
}
}
return nums
}
|
[
"func",
"toRange",
"(",
"start",
",",
"end",
",",
"step",
"int",
")",
"[",
"]",
"int",
"{",
"nums",
":=",
"[",
"]",
"int",
"{",
"}",
"\n",
"if",
"step",
"<",
"1",
"{",
"step",
"=",
"1",
"\n",
"}",
"\n",
"if",
"start",
"<=",
"end",
"{",
"for",
"i",
":=",
"start",
";",
"i",
"<=",
"end",
";",
"{",
"nums",
"=",
"append",
"(",
"nums",
",",
"i",
")",
"\n",
"i",
"+=",
"step",
"\n",
"}",
"\n",
"}",
"else",
"{",
"for",
"i",
":=",
"start",
";",
"i",
">=",
"end",
";",
"{",
"nums",
"=",
"append",
"(",
"nums",
",",
"i",
")",
"\n",
"i",
"-=",
"step",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nums",
"\n",
"}"
] |
// Expands a start, end, and stepping value
// into the full range of int values.
|
[
"Expands",
"a",
"start",
"end",
"and",
"stepping",
"value",
"into",
"the",
"full",
"range",
"of",
"int",
"values",
"."
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/fileseq.go#L219-L236
|
test
|
justinfx/gofileseq
|
cmd/seqls/manager.go
|
NewWorkManager
|
func NewWorkManager() *workManager {
var fileopts []fileseq.FileOption
if Options.AllFiles {
fileopts = append(fileopts, fileseq.HiddenFiles)
}
if !Options.SeqsOnly {
fileopts = append(fileopts, fileseq.SingleFiles)
}
s := &workManager{
inDirs: make(chan string),
inSeqs: make(chan *fileseq.FileSequence),
outSeqs: make(chan fileseq.FileSequences),
fileOpts: fileopts,
}
return s
}
|
go
|
func NewWorkManager() *workManager {
var fileopts []fileseq.FileOption
if Options.AllFiles {
fileopts = append(fileopts, fileseq.HiddenFiles)
}
if !Options.SeqsOnly {
fileopts = append(fileopts, fileseq.SingleFiles)
}
s := &workManager{
inDirs: make(chan string),
inSeqs: make(chan *fileseq.FileSequence),
outSeqs: make(chan fileseq.FileSequences),
fileOpts: fileopts,
}
return s
}
|
[
"func",
"NewWorkManager",
"(",
")",
"*",
"workManager",
"{",
"var",
"fileopts",
"[",
"]",
"fileseq",
".",
"FileOption",
"\n",
"if",
"Options",
".",
"AllFiles",
"{",
"fileopts",
"=",
"append",
"(",
"fileopts",
",",
"fileseq",
".",
"HiddenFiles",
")",
"\n",
"}",
"\n",
"if",
"!",
"Options",
".",
"SeqsOnly",
"{",
"fileopts",
"=",
"append",
"(",
"fileopts",
",",
"fileseq",
".",
"SingleFiles",
")",
"\n",
"}",
"\n",
"s",
":=",
"&",
"workManager",
"{",
"inDirs",
":",
"make",
"(",
"chan",
"string",
")",
",",
"inSeqs",
":",
"make",
"(",
"chan",
"*",
"fileseq",
".",
"FileSequence",
")",
",",
"outSeqs",
":",
"make",
"(",
"chan",
"fileseq",
".",
"FileSequences",
")",
",",
"fileOpts",
":",
"fileopts",
",",
"}",
"\n",
"return",
"s",
"\n",
"}"
] |
// Create a new workManager, with input and output channels,
// with a given list of options
|
[
"Create",
"a",
"new",
"workManager",
"with",
"input",
"and",
"output",
"channels",
"with",
"a",
"given",
"list",
"of",
"options"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/cmd/seqls/manager.go#L34-L50
|
test
|
justinfx/gofileseq
|
cmd/seqls/manager.go
|
processSources
|
func (w *workManager) processSources() {
var (
ok bool
path string
seq *fileseq.FileSequence
)
fileopts := w.fileOpts
inDirs := w.inDirs
inSeqs := w.inSeqs
outSeqs := w.outSeqs
isDone := func() bool {
return (inDirs == nil && inSeqs == nil)
}
for !isDone() {
select {
// Directory paths will be scanned for contents
case path, ok = <-inDirs:
if !ok {
inDirs = nil
continue
}
seqs, err := fileseq.FindSequencesOnDisk(path, fileopts...)
if err != nil {
fmt.Fprintf(errOut, "%s %q: %s\n", ErrorPath, path, err)
continue
}
outSeqs <- seqs
// Sequence paths will be scanned for a direct match
// against the sequence pattern
case seq, ok = <-inSeqs:
if !ok {
inSeqs = nil
continue
}
path, err := seq.Format("{{dir}}{{base}}{{pad}}{{ext}}")
if err != nil {
fmt.Fprintf(errOut, "%s %q: Not a valid path\n", ErrorPattern, path)
continue
}
seq, err := fileseq.FindSequenceOnDisk(path)
if err != nil {
if !os.IsNotExist(err) {
fmt.Fprintf(errOut, "%s %q: %s\n", ErrorPattern, path, err)
}
continue
}
if seq != nil {
outSeqs <- fileseq.FileSequences{seq}
}
}
}
}
|
go
|
func (w *workManager) processSources() {
var (
ok bool
path string
seq *fileseq.FileSequence
)
fileopts := w.fileOpts
inDirs := w.inDirs
inSeqs := w.inSeqs
outSeqs := w.outSeqs
isDone := func() bool {
return (inDirs == nil && inSeqs == nil)
}
for !isDone() {
select {
// Directory paths will be scanned for contents
case path, ok = <-inDirs:
if !ok {
inDirs = nil
continue
}
seqs, err := fileseq.FindSequencesOnDisk(path, fileopts...)
if err != nil {
fmt.Fprintf(errOut, "%s %q: %s\n", ErrorPath, path, err)
continue
}
outSeqs <- seqs
// Sequence paths will be scanned for a direct match
// against the sequence pattern
case seq, ok = <-inSeqs:
if !ok {
inSeqs = nil
continue
}
path, err := seq.Format("{{dir}}{{base}}{{pad}}{{ext}}")
if err != nil {
fmt.Fprintf(errOut, "%s %q: Not a valid path\n", ErrorPattern, path)
continue
}
seq, err := fileseq.FindSequenceOnDisk(path)
if err != nil {
if !os.IsNotExist(err) {
fmt.Fprintf(errOut, "%s %q: %s\n", ErrorPattern, path, err)
}
continue
}
if seq != nil {
outSeqs <- fileseq.FileSequences{seq}
}
}
}
}
|
[
"func",
"(",
"w",
"*",
"workManager",
")",
"processSources",
"(",
")",
"{",
"var",
"(",
"ok",
"bool",
"\n",
"path",
"string",
"\n",
"seq",
"*",
"fileseq",
".",
"FileSequence",
"\n",
")",
"\n",
"fileopts",
":=",
"w",
".",
"fileOpts",
"\n",
"inDirs",
":=",
"w",
".",
"inDirs",
"\n",
"inSeqs",
":=",
"w",
".",
"inSeqs",
"\n",
"outSeqs",
":=",
"w",
".",
"outSeqs",
"\n",
"isDone",
":=",
"func",
"(",
")",
"bool",
"{",
"return",
"(",
"inDirs",
"==",
"nil",
"&&",
"inSeqs",
"==",
"nil",
")",
"\n",
"}",
"\n",
"for",
"!",
"isDone",
"(",
")",
"{",
"select",
"{",
"case",
"path",
",",
"ok",
"=",
"<-",
"inDirs",
":",
"if",
"!",
"ok",
"{",
"inDirs",
"=",
"nil",
"\n",
"continue",
"\n",
"}",
"\n",
"seqs",
",",
"err",
":=",
"fileseq",
".",
"FindSequencesOnDisk",
"(",
"path",
",",
"fileopts",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Fprintf",
"(",
"errOut",
",",
"\"%s %q: %s\\n\"",
",",
"\\n",
",",
"ErrorPath",
",",
"path",
")",
"\n",
"err",
"\n",
"}",
"\n",
"continue",
"\n",
"outSeqs",
"<-",
"seqs",
"}",
"\n",
"}",
"\n",
"}"
] |
// processSources pulls from input channels, and processes
// them into the output channel until there is no more work
|
[
"processSources",
"pulls",
"from",
"input",
"channels",
"and",
"processes",
"them",
"into",
"the",
"output",
"channel",
"until",
"there",
"is",
"no",
"more",
"work"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/cmd/seqls/manager.go#L103-L163
|
test
|
justinfx/gofileseq
|
cmd/seqls/manager.go
|
isInputDone
|
func (w *workManager) isInputDone() bool {
if w.inDirs != nil {
return false
}
if w.inSeqs != nil {
return false
}
return true
}
|
go
|
func (w *workManager) isInputDone() bool {
if w.inDirs != nil {
return false
}
if w.inSeqs != nil {
return false
}
return true
}
|
[
"func",
"(",
"w",
"*",
"workManager",
")",
"isInputDone",
"(",
")",
"bool",
"{",
"if",
"w",
".",
"inDirs",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"w",
".",
"inSeqs",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] |
// Returns true if the input channels are nil
|
[
"Returns",
"true",
"if",
"the",
"input",
"channels",
"are",
"nil"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/cmd/seqls/manager.go#L196-L204
|
test
|
justinfx/gofileseq
|
cmd/seqls/manager.go
|
closeInputs
|
func (w *workManager) closeInputs() {
if w.inDirs != nil {
close(w.inDirs)
}
if w.inSeqs != nil {
close(w.inSeqs)
}
}
|
go
|
func (w *workManager) closeInputs() {
if w.inDirs != nil {
close(w.inDirs)
}
if w.inSeqs != nil {
close(w.inSeqs)
}
}
|
[
"func",
"(",
"w",
"*",
"workManager",
")",
"closeInputs",
"(",
")",
"{",
"if",
"w",
".",
"inDirs",
"!=",
"nil",
"{",
"close",
"(",
"w",
".",
"inDirs",
")",
"\n",
"}",
"\n",
"if",
"w",
".",
"inSeqs",
"!=",
"nil",
"{",
"close",
"(",
"w",
".",
"inSeqs",
")",
"\n",
"}",
"\n",
"}"
] |
// CloseInputs closes the input channels indicating
// that no more paths will be loaded.
|
[
"CloseInputs",
"closes",
"the",
"input",
"channels",
"indicating",
"that",
"no",
"more",
"paths",
"will",
"be",
"loaded",
"."
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/cmd/seqls/manager.go#L208-L216
|
test
|
justinfx/gofileseq
|
cmd/seqls/manager.go
|
load
|
func (w *workManager) load(paths []string) {
dirs, seqs := preparePaths(paths)
for _, s := range seqs {
w.inSeqs <- s
}
for _, r := range dirs {
w.inDirs <- r
}
}
|
go
|
func (w *workManager) load(paths []string) {
dirs, seqs := preparePaths(paths)
for _, s := range seqs {
w.inSeqs <- s
}
for _, r := range dirs {
w.inDirs <- r
}
}
|
[
"func",
"(",
"w",
"*",
"workManager",
")",
"load",
"(",
"paths",
"[",
"]",
"string",
")",
"{",
"dirs",
",",
"seqs",
":=",
"preparePaths",
"(",
"paths",
")",
"\n",
"for",
"_",
",",
"s",
":=",
"range",
"seqs",
"{",
"w",
".",
"inSeqs",
"<-",
"s",
"\n",
"}",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"dirs",
"{",
"w",
".",
"inDirs",
"<-",
"r",
"\n",
"}",
"\n",
"}"
] |
// loadStandard takes paths and loads them into the
// dir input channel for processing
|
[
"loadStandard",
"takes",
"paths",
"and",
"loads",
"them",
"into",
"the",
"dir",
"input",
"channel",
"for",
"processing"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/cmd/seqls/manager.go#L228-L238
|
test
|
justinfx/gofileseq
|
cmd/seqls/manager.go
|
loadRecursive
|
func (w *workManager) loadRecursive(paths []string) {
walkFn := func(path string, info os.FileInfo, err error) error {
if err != nil {
return nil
}
var isDir bool
if info.IsDir() {
isDir = true
} else if info, err = os.Stat(path); err == nil && info.IsDir() {
isDir = true
}
if isDir {
if !Options.AllFiles {
// Skip tranversing into hidden dirs
if len(info.Name()) > 1 && strings.HasPrefix(info.Name(), ".") {
return walk.SkipDir
}
}
// Add the path to the input channel for sequence scanning
w.inDirs <- path
}
return nil
}
dirs, seqs := preparePaths(paths)
for _, s := range seqs {
w.inSeqs <- s
}
for _, r := range dirs {
r := r
if err := walk.Walk(r, walkFn); err != nil {
if err != walk.SkipDir {
fmt.Fprintf(errOut, "%s %q: %s\n", ErrorPath, r, err)
}
}
}
}
|
go
|
func (w *workManager) loadRecursive(paths []string) {
walkFn := func(path string, info os.FileInfo, err error) error {
if err != nil {
return nil
}
var isDir bool
if info.IsDir() {
isDir = true
} else if info, err = os.Stat(path); err == nil && info.IsDir() {
isDir = true
}
if isDir {
if !Options.AllFiles {
// Skip tranversing into hidden dirs
if len(info.Name()) > 1 && strings.HasPrefix(info.Name(), ".") {
return walk.SkipDir
}
}
// Add the path to the input channel for sequence scanning
w.inDirs <- path
}
return nil
}
dirs, seqs := preparePaths(paths)
for _, s := range seqs {
w.inSeqs <- s
}
for _, r := range dirs {
r := r
if err := walk.Walk(r, walkFn); err != nil {
if err != walk.SkipDir {
fmt.Fprintf(errOut, "%s %q: %s\n", ErrorPath, r, err)
}
}
}
}
|
[
"func",
"(",
"w",
"*",
"workManager",
")",
"loadRecursive",
"(",
"paths",
"[",
"]",
"string",
")",
"{",
"walkFn",
":=",
"func",
"(",
"path",
"string",
",",
"info",
"os",
".",
"FileInfo",
",",
"err",
"error",
")",
"error",
"{",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"var",
"isDir",
"bool",
"\n",
"if",
"info",
".",
"IsDir",
"(",
")",
"{",
"isDir",
"=",
"true",
"\n",
"}",
"else",
"if",
"info",
",",
"err",
"=",
"os",
".",
"Stat",
"(",
"path",
")",
";",
"err",
"==",
"nil",
"&&",
"info",
".",
"IsDir",
"(",
")",
"{",
"isDir",
"=",
"true",
"\n",
"}",
"\n",
"if",
"isDir",
"{",
"if",
"!",
"Options",
".",
"AllFiles",
"{",
"if",
"len",
"(",
"info",
".",
"Name",
"(",
")",
")",
">",
"1",
"&&",
"strings",
".",
"HasPrefix",
"(",
"info",
".",
"Name",
"(",
")",
",",
"\".\"",
")",
"{",
"return",
"walk",
".",
"SkipDir",
"\n",
"}",
"\n",
"}",
"\n",
"w",
".",
"inDirs",
"<-",
"path",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"dirs",
",",
"seqs",
":=",
"preparePaths",
"(",
"paths",
")",
"\n",
"for",
"_",
",",
"s",
":=",
"range",
"seqs",
"{",
"w",
".",
"inSeqs",
"<-",
"s",
"\n",
"}",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"dirs",
"{",
"r",
":=",
"r",
"\n",
"if",
"err",
":=",
"walk",
".",
"Walk",
"(",
"r",
",",
"walkFn",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"err",
"!=",
"walk",
".",
"SkipDir",
"{",
"fmt",
".",
"Fprintf",
"(",
"errOut",
",",
"\"%s %q: %s\\n\"",
",",
"\\n",
",",
"ErrorPath",
",",
"r",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// Parallel walk the root paths and populate the path
// channel for the worker routines to consume.
|
[
"Parallel",
"walk",
"the",
"root",
"paths",
"and",
"populate",
"the",
"path",
"channel",
"for",
"the",
"worker",
"routines",
"to",
"consume",
"."
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/cmd/seqls/manager.go#L242-L287
|
test
|
justinfx/gofileseq
|
cmd/seqls/manager.go
|
preparePaths
|
func preparePaths(paths []string) ([]string, fileseq.FileSequences) {
var (
fi os.FileInfo
err error
)
dirs := make([]string, 0)
seqs := make(fileseq.FileSequences, 0)
previous := make(map[string]struct{})
for _, p := range paths {
p := strings.TrimSpace(filepath.Clean(p))
if p == "" {
continue
}
if _, seen := previous[p]; seen {
continue
}
previous[p] = struct{}{}
if fi, err = os.Stat(p); err != nil {
// If the path doesn't exist, test it for
// a valid fileseq pattern
if seq, err := fileseq.NewFileSequence(p); err == nil {
seqs = append(seqs, seq)
continue
}
fmt.Fprintf(errOut, "%s %q: %s\n", ErrorPath, p, err)
continue
}
if !fi.IsDir() {
continue
}
dirs = append(dirs, p)
}
return dirs, seqs
}
|
go
|
func preparePaths(paths []string) ([]string, fileseq.FileSequences) {
var (
fi os.FileInfo
err error
)
dirs := make([]string, 0)
seqs := make(fileseq.FileSequences, 0)
previous := make(map[string]struct{})
for _, p := range paths {
p := strings.TrimSpace(filepath.Clean(p))
if p == "" {
continue
}
if _, seen := previous[p]; seen {
continue
}
previous[p] = struct{}{}
if fi, err = os.Stat(p); err != nil {
// If the path doesn't exist, test it for
// a valid fileseq pattern
if seq, err := fileseq.NewFileSequence(p); err == nil {
seqs = append(seqs, seq)
continue
}
fmt.Fprintf(errOut, "%s %q: %s\n", ErrorPath, p, err)
continue
}
if !fi.IsDir() {
continue
}
dirs = append(dirs, p)
}
return dirs, seqs
}
|
[
"func",
"preparePaths",
"(",
"paths",
"[",
"]",
"string",
")",
"(",
"[",
"]",
"string",
",",
"fileseq",
".",
"FileSequences",
")",
"{",
"var",
"(",
"fi",
"os",
".",
"FileInfo",
"\n",
"err",
"error",
"\n",
")",
"\n",
"dirs",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
")",
"\n",
"seqs",
":=",
"make",
"(",
"fileseq",
".",
"FileSequences",
",",
"0",
")",
"\n",
"previous",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"paths",
"{",
"p",
":=",
"strings",
".",
"TrimSpace",
"(",
"filepath",
".",
"Clean",
"(",
"p",
")",
")",
"\n",
"if",
"p",
"==",
"\"\"",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"_",
",",
"seen",
":=",
"previous",
"[",
"p",
"]",
";",
"seen",
"{",
"continue",
"\n",
"}",
"\n",
"previous",
"[",
"p",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"if",
"fi",
",",
"err",
"=",
"os",
".",
"Stat",
"(",
"p",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"seq",
",",
"err",
":=",
"fileseq",
".",
"NewFileSequence",
"(",
"p",
")",
";",
"err",
"==",
"nil",
"{",
"seqs",
"=",
"append",
"(",
"seqs",
",",
"seq",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintf",
"(",
"errOut",
",",
"\"%s %q: %s\\n\"",
",",
"\\n",
",",
"ErrorPath",
",",
"p",
")",
"\n",
"err",
"\n",
"}",
"\n",
"continue",
"\n",
"if",
"!",
"fi",
".",
"IsDir",
"(",
")",
"{",
"continue",
"\n",
"}",
"\n",
"}",
"\n",
"dirs",
"=",
"append",
"(",
"dirs",
",",
"p",
")",
"\n",
"}"
] |
// Take a list of paths and reduce them to cleaned
// and unique paths. Return two slices, separated by
// directory paths, and sequence patterns
|
[
"Take",
"a",
"list",
"of",
"paths",
"and",
"reduce",
"them",
"to",
"cleaned",
"and",
"unique",
"paths",
".",
"Return",
"two",
"slices",
"separated",
"by",
"directory",
"paths",
"and",
"sequence",
"patterns"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/cmd/seqls/manager.go#L292-L334
|
test
|
justinfx/gofileseq
|
pad.go
|
PadFrameRange
|
func PadFrameRange(frange string, pad int) string {
// We don't need to do anything if they gave us
// an invalid pad number
if pad < 2 {
return frange
}
size := strings.Count(frange, ",") + 1
parts := make([]string, size, size)
for i, part := range strings.Split(frange, ",") {
didMatch := false
for _, rx := range rangePatterns {
matched := rx.FindStringSubmatch(part)
if len(matched) == 0 {
continue
}
matched = matched[1:]
size = len(matched)
switch size {
case 1:
parts[i] = zfillString(matched[0], pad)
case 2:
parts[i] = fmt.Sprintf("%s-%s",
zfillString(matched[0], pad),
zfillString(matched[1], pad))
case 4:
parts[i] = fmt.Sprintf("%s-%s%s%s",
zfillString(matched[0], pad),
zfillString(matched[1], pad),
matched[2], matched[3])
default:
// No match. Try the next pattern
continue
}
// If we got here, we matched a case and can stop
// checking the rest of the patterns
didMatch = true
break
}
// If we didn't match one of our expected patterns
// then just take the original part and add it unmodified
if !didMatch {
parts = append(parts, part)
}
}
return strings.Join(parts, ",")
}
|
go
|
func PadFrameRange(frange string, pad int) string {
// We don't need to do anything if they gave us
// an invalid pad number
if pad < 2 {
return frange
}
size := strings.Count(frange, ",") + 1
parts := make([]string, size, size)
for i, part := range strings.Split(frange, ",") {
didMatch := false
for _, rx := range rangePatterns {
matched := rx.FindStringSubmatch(part)
if len(matched) == 0 {
continue
}
matched = matched[1:]
size = len(matched)
switch size {
case 1:
parts[i] = zfillString(matched[0], pad)
case 2:
parts[i] = fmt.Sprintf("%s-%s",
zfillString(matched[0], pad),
zfillString(matched[1], pad))
case 4:
parts[i] = fmt.Sprintf("%s-%s%s%s",
zfillString(matched[0], pad),
zfillString(matched[1], pad),
matched[2], matched[3])
default:
// No match. Try the next pattern
continue
}
// If we got here, we matched a case and can stop
// checking the rest of the patterns
didMatch = true
break
}
// If we didn't match one of our expected patterns
// then just take the original part and add it unmodified
if !didMatch {
parts = append(parts, part)
}
}
return strings.Join(parts, ",")
}
|
[
"func",
"PadFrameRange",
"(",
"frange",
"string",
",",
"pad",
"int",
")",
"string",
"{",
"if",
"pad",
"<",
"2",
"{",
"return",
"frange",
"\n",
"}",
"\n",
"size",
":=",
"strings",
".",
"Count",
"(",
"frange",
",",
"\",\"",
")",
"+",
"1",
"\n",
"parts",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"size",
",",
"size",
")",
"\n",
"for",
"i",
",",
"part",
":=",
"range",
"strings",
".",
"Split",
"(",
"frange",
",",
"\",\"",
")",
"{",
"didMatch",
":=",
"false",
"\n",
"for",
"_",
",",
"rx",
":=",
"range",
"rangePatterns",
"{",
"matched",
":=",
"rx",
".",
"FindStringSubmatch",
"(",
"part",
")",
"\n",
"if",
"len",
"(",
"matched",
")",
"==",
"0",
"{",
"continue",
"\n",
"}",
"\n",
"matched",
"=",
"matched",
"[",
"1",
":",
"]",
"\n",
"size",
"=",
"len",
"(",
"matched",
")",
"\n",
"switch",
"size",
"{",
"case",
"1",
":",
"parts",
"[",
"i",
"]",
"=",
"zfillString",
"(",
"matched",
"[",
"0",
"]",
",",
"pad",
")",
"\n",
"case",
"2",
":",
"parts",
"[",
"i",
"]",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%s-%s\"",
",",
"zfillString",
"(",
"matched",
"[",
"0",
"]",
",",
"pad",
")",
",",
"zfillString",
"(",
"matched",
"[",
"1",
"]",
",",
"pad",
")",
")",
"\n",
"case",
"4",
":",
"parts",
"[",
"i",
"]",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%s-%s%s%s\"",
",",
"zfillString",
"(",
"matched",
"[",
"0",
"]",
",",
"pad",
")",
",",
"zfillString",
"(",
"matched",
"[",
"1",
"]",
",",
"pad",
")",
",",
"matched",
"[",
"2",
"]",
",",
"matched",
"[",
"3",
"]",
")",
"\n",
"default",
":",
"continue",
"\n",
"}",
"\n",
"didMatch",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"if",
"!",
"didMatch",
"{",
"parts",
"=",
"append",
"(",
"parts",
",",
"part",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"strings",
".",
"Join",
"(",
"parts",
",",
"\",\"",
")",
"\n",
"}"
] |
// PadFrameRange takes a frame range string and returns a
// new range with each number padded out with zeros to a given width
|
[
"PadFrameRange",
"takes",
"a",
"frame",
"range",
"string",
"and",
"returns",
"a",
"new",
"range",
"with",
"each",
"number",
"padded",
"out",
"with",
"zeros",
"to",
"a",
"given",
"width"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/pad.go#L127-L176
|
test
|
justinfx/gofileseq
|
pad.go
|
zfillString
|
func zfillString(src string, z int) string {
size := len(src)
if size >= z {
return src
}
fill := strings.Repeat("0", z-size)
if strings.HasPrefix(src, "-") {
return fmt.Sprintf("-%s%s", fill, src[1:])
}
return fmt.Sprintf("%s%s", fill, src)
}
|
go
|
func zfillString(src string, z int) string {
size := len(src)
if size >= z {
return src
}
fill := strings.Repeat("0", z-size)
if strings.HasPrefix(src, "-") {
return fmt.Sprintf("-%s%s", fill, src[1:])
}
return fmt.Sprintf("%s%s", fill, src)
}
|
[
"func",
"zfillString",
"(",
"src",
"string",
",",
"z",
"int",
")",
"string",
"{",
"size",
":=",
"len",
"(",
"src",
")",
"\n",
"if",
"size",
">=",
"z",
"{",
"return",
"src",
"\n",
"}",
"\n",
"fill",
":=",
"strings",
".",
"Repeat",
"(",
"\"0\"",
",",
"z",
"-",
"size",
")",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"src",
",",
"\"-\"",
")",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"-%s%s\"",
",",
"fill",
",",
"src",
"[",
"1",
":",
"]",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%s%s\"",
",",
"fill",
",",
"src",
")",
"\n",
"}"
] |
// Left pads a string to a given with, using "0".
// If the string begins with a negative "-" character, then
// padding is inserted between the "-" and the remaining characters.
|
[
"Left",
"pads",
"a",
"string",
"to",
"a",
"given",
"with",
"using",
"0",
".",
"If",
"the",
"string",
"begins",
"with",
"a",
"negative",
"-",
"character",
"then",
"padding",
"is",
"inserted",
"between",
"the",
"-",
"and",
"the",
"remaining",
"characters",
"."
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/pad.go#L181-L192
|
test
|
justinfx/gofileseq
|
pad.go
|
zfillInt
|
func zfillInt(src int, z int) string {
if z < 2 {
return strconv.Itoa(src)
}
return fmt.Sprintf(fmt.Sprintf("%%0%dd", z), src)
}
|
go
|
func zfillInt(src int, z int) string {
if z < 2 {
return strconv.Itoa(src)
}
return fmt.Sprintf(fmt.Sprintf("%%0%dd", z), src)
}
|
[
"func",
"zfillInt",
"(",
"src",
"int",
",",
"z",
"int",
")",
"string",
"{",
"if",
"z",
"<",
"2",
"{",
"return",
"strconv",
".",
"Itoa",
"(",
"src",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"%%0%dd\"",
",",
"z",
")",
",",
"src",
")",
"\n",
"}"
] |
// Left pads an int to a given with, using "0".
// If the string begins with a negative "-" character, then
// padding is inserted between the "-" and the remaining characters.
|
[
"Left",
"pads",
"an",
"int",
"to",
"a",
"given",
"with",
"using",
"0",
".",
"If",
"the",
"string",
"begins",
"with",
"a",
"negative",
"-",
"character",
"then",
"padding",
"is",
"inserted",
"between",
"the",
"-",
"and",
"the",
"remaining",
"characters",
"."
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/pad.go#L197-L202
|
test
|
justinfx/gofileseq
|
ranges/ranges.go
|
NewInclusiveRange
|
func NewInclusiveRange(start, end, step int) *InclusiveRange {
if step == 0 {
if start <= end {
step = 1
} else {
step = -1
}
}
r := &InclusiveRange{
start: start,
end: end,
step: step,
}
return r
}
|
go
|
func NewInclusiveRange(start, end, step int) *InclusiveRange {
if step == 0 {
if start <= end {
step = 1
} else {
step = -1
}
}
r := &InclusiveRange{
start: start,
end: end,
step: step,
}
return r
}
|
[
"func",
"NewInclusiveRange",
"(",
"start",
",",
"end",
",",
"step",
"int",
")",
"*",
"InclusiveRange",
"{",
"if",
"step",
"==",
"0",
"{",
"if",
"start",
"<=",
"end",
"{",
"step",
"=",
"1",
"\n",
"}",
"else",
"{",
"step",
"=",
"-",
"1",
"\n",
"}",
"\n",
"}",
"\n",
"r",
":=",
"&",
"InclusiveRange",
"{",
"start",
":",
"start",
",",
"end",
":",
"end",
",",
"step",
":",
"step",
",",
"}",
"\n",
"return",
"r",
"\n",
"}"
] |
// NewInclusiveRange creates a new InclusiveRange instance
|
[
"NewInclusiveRange",
"creates",
"a",
"new",
"InclusiveRange",
"instance"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L59-L75
|
test
|
justinfx/gofileseq
|
ranges/ranges.go
|
String
|
func (r *InclusiveRange) String() string {
var buf strings.Builder
// Always for a single value
buf.WriteString(strconv.Itoa(r.Start()))
// If we have a range, express the end value
if r.End() != r.Start() {
buf.WriteString(`-`)
buf.WriteString(strconv.Itoa(r.End()))
// Express the stepping, if its not 1
step := r.Step()
if step > 1 || step < -1 {
buf.WriteString(`x`)
buf.WriteString(strconv.Itoa(r.Step()))
}
}
return buf.String()
}
|
go
|
func (r *InclusiveRange) String() string {
var buf strings.Builder
// Always for a single value
buf.WriteString(strconv.Itoa(r.Start()))
// If we have a range, express the end value
if r.End() != r.Start() {
buf.WriteString(`-`)
buf.WriteString(strconv.Itoa(r.End()))
// Express the stepping, if its not 1
step := r.Step()
if step > 1 || step < -1 {
buf.WriteString(`x`)
buf.WriteString(strconv.Itoa(r.Step()))
}
}
return buf.String()
}
|
[
"func",
"(",
"r",
"*",
"InclusiveRange",
")",
"String",
"(",
")",
"string",
"{",
"var",
"buf",
"strings",
".",
"Builder",
"\n",
"buf",
".",
"WriteString",
"(",
"strconv",
".",
"Itoa",
"(",
"r",
".",
"Start",
"(",
")",
")",
")",
"\n",
"if",
"r",
".",
"End",
"(",
")",
"!=",
"r",
".",
"Start",
"(",
")",
"{",
"buf",
".",
"WriteString",
"(",
"`-`",
")",
"\n",
"buf",
".",
"WriteString",
"(",
"strconv",
".",
"Itoa",
"(",
"r",
".",
"End",
"(",
")",
")",
")",
"\n",
"step",
":=",
"r",
".",
"Step",
"(",
")",
"\n",
"if",
"step",
">",
"1",
"||",
"step",
"<",
"-",
"1",
"{",
"buf",
".",
"WriteString",
"(",
"`x`",
")",
"\n",
"buf",
".",
"WriteString",
"(",
"strconv",
".",
"Itoa",
"(",
"r",
".",
"Step",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}"
] |
// String returns a formatted string representation
// of the integer range
|
[
"String",
"returns",
"a",
"formatted",
"string",
"representation",
"of",
"the",
"integer",
"range"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L79-L98
|
test
|
justinfx/gofileseq
|
ranges/ranges.go
|
End
|
func (r *InclusiveRange) End() int {
if r.isEndCached {
return r.cachedEnd
}
r.isEndCached = true
// If we aren't stepping, or we don't have
// a full range, then just use the end value
if r.step == 1 || r.step == -1 || r.start == r.end {
r.cachedEnd = r.end
return r.cachedEnd
}
// If the step is in the wrong direction,
// compared to the range direction, then
// just use the start as the end.
if (r.end < r.start) && r.step < (r.end-r.start) {
r.cachedEnd = r.start
return r.cachedEnd
} else if (r.end > r.start) && r.step > (r.end-r.start) {
r.cachedEnd = r.start
return r.cachedEnd
}
// Calculate the end, taking into account the stepping
r.cachedEnd = r.closestInRange(r.end, r.start, r.end, r.step)
return r.cachedEnd
}
|
go
|
func (r *InclusiveRange) End() int {
if r.isEndCached {
return r.cachedEnd
}
r.isEndCached = true
// If we aren't stepping, or we don't have
// a full range, then just use the end value
if r.step == 1 || r.step == -1 || r.start == r.end {
r.cachedEnd = r.end
return r.cachedEnd
}
// If the step is in the wrong direction,
// compared to the range direction, then
// just use the start as the end.
if (r.end < r.start) && r.step < (r.end-r.start) {
r.cachedEnd = r.start
return r.cachedEnd
} else if (r.end > r.start) && r.step > (r.end-r.start) {
r.cachedEnd = r.start
return r.cachedEnd
}
// Calculate the end, taking into account the stepping
r.cachedEnd = r.closestInRange(r.end, r.start, r.end, r.step)
return r.cachedEnd
}
|
[
"func",
"(",
"r",
"*",
"InclusiveRange",
")",
"End",
"(",
")",
"int",
"{",
"if",
"r",
".",
"isEndCached",
"{",
"return",
"r",
".",
"cachedEnd",
"\n",
"}",
"\n",
"r",
".",
"isEndCached",
"=",
"true",
"\n",
"if",
"r",
".",
"step",
"==",
"1",
"||",
"r",
".",
"step",
"==",
"-",
"1",
"||",
"r",
".",
"start",
"==",
"r",
".",
"end",
"{",
"r",
".",
"cachedEnd",
"=",
"r",
".",
"end",
"\n",
"return",
"r",
".",
"cachedEnd",
"\n",
"}",
"\n",
"if",
"(",
"r",
".",
"end",
"<",
"r",
".",
"start",
")",
"&&",
"r",
".",
"step",
"<",
"(",
"r",
".",
"end",
"-",
"r",
".",
"start",
")",
"{",
"r",
".",
"cachedEnd",
"=",
"r",
".",
"start",
"\n",
"return",
"r",
".",
"cachedEnd",
"\n",
"}",
"else",
"if",
"(",
"r",
".",
"end",
">",
"r",
".",
"start",
")",
"&&",
"r",
".",
"step",
">",
"(",
"r",
".",
"end",
"-",
"r",
".",
"start",
")",
"{",
"r",
".",
"cachedEnd",
"=",
"r",
".",
"start",
"\n",
"return",
"r",
".",
"cachedEnd",
"\n",
"}",
"\n",
"r",
".",
"cachedEnd",
"=",
"r",
".",
"closestInRange",
"(",
"r",
".",
"end",
",",
"r",
".",
"start",
",",
"r",
".",
"end",
",",
"r",
".",
"step",
")",
"\n",
"return",
"r",
".",
"cachedEnd",
"\n",
"}"
] |
// End returns the end of the range. This value may
// be different from the end value given when the
// range was first initialized, since it takes into
// account the stepping value. The end value may be
// shifted to the closest valid value within the
// stepped range.
|
[
"End",
"returns",
"the",
"end",
"of",
"the",
"range",
".",
"This",
"value",
"may",
"be",
"different",
"from",
"the",
"end",
"value",
"given",
"when",
"the",
"range",
"was",
"first",
"initialized",
"since",
"it",
"takes",
"into",
"account",
"the",
"stepping",
"value",
".",
"The",
"end",
"value",
"may",
"be",
"shifted",
"to",
"the",
"closest",
"valid",
"value",
"within",
"the",
"stepped",
"range",
"."
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L111-L140
|
test
|
justinfx/gofileseq
|
ranges/ranges.go
|
Len
|
func (r *InclusiveRange) Len() int {
if r.isLenCached {
return r.cachedLen
}
// Offset by one to include the end value
diff := math.Abs(float64(r.end-r.start)) + 1
r.cachedLen = int(math.Ceil(diff / math.Abs(float64(r.step))))
r.isLenCached = true
return r.cachedLen
}
|
go
|
func (r *InclusiveRange) Len() int {
if r.isLenCached {
return r.cachedLen
}
// Offset by one to include the end value
diff := math.Abs(float64(r.end-r.start)) + 1
r.cachedLen = int(math.Ceil(diff / math.Abs(float64(r.step))))
r.isLenCached = true
return r.cachedLen
}
|
[
"func",
"(",
"r",
"*",
"InclusiveRange",
")",
"Len",
"(",
")",
"int",
"{",
"if",
"r",
".",
"isLenCached",
"{",
"return",
"r",
".",
"cachedLen",
"\n",
"}",
"\n",
"diff",
":=",
"math",
".",
"Abs",
"(",
"float64",
"(",
"r",
".",
"end",
"-",
"r",
".",
"start",
")",
")",
"+",
"1",
"\n",
"r",
".",
"cachedLen",
"=",
"int",
"(",
"math",
".",
"Ceil",
"(",
"diff",
"/",
"math",
".",
"Abs",
"(",
"float64",
"(",
"r",
".",
"step",
")",
")",
")",
")",
"\n",
"r",
".",
"isLenCached",
"=",
"true",
"\n",
"return",
"r",
".",
"cachedLen",
"\n",
"}"
] |
// Len returns the number of values in the range
|
[
"Len",
"returns",
"the",
"number",
"of",
"values",
"in",
"the",
"range"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L148-L158
|
test
|
justinfx/gofileseq
|
ranges/ranges.go
|
Min
|
func (r *InclusiveRange) Min() int {
start := r.Start()
end := r.End()
if start < end {
return start
}
return end
}
|
go
|
func (r *InclusiveRange) Min() int {
start := r.Start()
end := r.End()
if start < end {
return start
}
return end
}
|
[
"func",
"(",
"r",
"*",
"InclusiveRange",
")",
"Min",
"(",
")",
"int",
"{",
"start",
":=",
"r",
".",
"Start",
"(",
")",
"\n",
"end",
":=",
"r",
".",
"End",
"(",
")",
"\n",
"if",
"start",
"<",
"end",
"{",
"return",
"start",
"\n",
"}",
"\n",
"return",
"end",
"\n",
"}"
] |
// Min returns the smallest value in the range
|
[
"Min",
"returns",
"the",
"smallest",
"value",
"in",
"the",
"range"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L161-L168
|
test
|
justinfx/gofileseq
|
ranges/ranges.go
|
Max
|
func (r *InclusiveRange) Max() int {
start := r.Start()
end := r.End()
if start > end {
return start
}
return end
}
|
go
|
func (r *InclusiveRange) Max() int {
start := r.Start()
end := r.End()
if start > end {
return start
}
return end
}
|
[
"func",
"(",
"r",
"*",
"InclusiveRange",
")",
"Max",
"(",
")",
"int",
"{",
"start",
":=",
"r",
".",
"Start",
"(",
")",
"\n",
"end",
":=",
"r",
".",
"End",
"(",
")",
"\n",
"if",
"start",
">",
"end",
"{",
"return",
"start",
"\n",
"}",
"\n",
"return",
"end",
"\n",
"}"
] |
// Max returns the highest value in the range
|
[
"Max",
"returns",
"the",
"highest",
"value",
"in",
"the",
"range"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L171-L178
|
test
|
justinfx/gofileseq
|
ranges/ranges.go
|
Contains
|
func (r *InclusiveRange) Contains(value int) bool {
// If we attempt to find the closest value, given
// the start of the range and the step, we can check
// if it is still the same number. If it hasn't changed,
// then it is in the range.
closest := r.closestInRange(value, r.start, r.End(), r.step)
return closest == value
}
|
go
|
func (r *InclusiveRange) Contains(value int) bool {
// If we attempt to find the closest value, given
// the start of the range and the step, we can check
// if it is still the same number. If it hasn't changed,
// then it is in the range.
closest := r.closestInRange(value, r.start, r.End(), r.step)
return closest == value
}
|
[
"func",
"(",
"r",
"*",
"InclusiveRange",
")",
"Contains",
"(",
"value",
"int",
")",
"bool",
"{",
"closest",
":=",
"r",
".",
"closestInRange",
"(",
"value",
",",
"r",
".",
"start",
",",
"r",
".",
"End",
"(",
")",
",",
"r",
".",
"step",
")",
"\n",
"return",
"closest",
"==",
"value",
"\n",
"}"
] |
// Contains returns true if the given value is a valid
// value within the value range.
|
[
"Contains",
"returns",
"true",
"if",
"the",
"given",
"value",
"is",
"a",
"valid",
"value",
"within",
"the",
"value",
"range",
"."
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L182-L189
|
test
|
justinfx/gofileseq
|
ranges/ranges.go
|
closestInRange
|
func (*InclusiveRange) closestInRange(value, start, end, step int) int {
// Possibly clamp the value if it is outside the range
if end >= start {
if value < start {
return start
} else if value > end {
return end
}
} else {
if value > start {
return start
} else if value < end {
return end
}
}
// No calculation needed if there is no stepping
if step == 1 || step == -1 {
return value
}
// Modified the value so that it is a properly stepped
// increment within the range
return (((value - start) / step) * step) + start
}
|
go
|
func (*InclusiveRange) closestInRange(value, start, end, step int) int {
// Possibly clamp the value if it is outside the range
if end >= start {
if value < start {
return start
} else if value > end {
return end
}
} else {
if value > start {
return start
} else if value < end {
return end
}
}
// No calculation needed if there is no stepping
if step == 1 || step == -1 {
return value
}
// Modified the value so that it is a properly stepped
// increment within the range
return (((value - start) / step) * step) + start
}
|
[
"func",
"(",
"*",
"InclusiveRange",
")",
"closestInRange",
"(",
"value",
",",
"start",
",",
"end",
",",
"step",
"int",
")",
"int",
"{",
"if",
"end",
">=",
"start",
"{",
"if",
"value",
"<",
"start",
"{",
"return",
"start",
"\n",
"}",
"else",
"if",
"value",
">",
"end",
"{",
"return",
"end",
"\n",
"}",
"\n",
"}",
"else",
"{",
"if",
"value",
">",
"start",
"{",
"return",
"start",
"\n",
"}",
"else",
"if",
"value",
"<",
"end",
"{",
"return",
"end",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"step",
"==",
"1",
"||",
"step",
"==",
"-",
"1",
"{",
"return",
"value",
"\n",
"}",
"\n",
"return",
"(",
"(",
"(",
"value",
"-",
"start",
")",
"/",
"step",
")",
"*",
"step",
")",
"+",
"start",
"\n",
"}"
] |
// closestInRange finds the closest valid value within the range,
// to a given value. Values outside the range are clipped to either
// the range min or max.
|
[
"closestInRange",
"finds",
"the",
"closest",
"valid",
"value",
"within",
"the",
"range",
"to",
"a",
"given",
"value",
".",
"Values",
"outside",
"the",
"range",
"are",
"clipped",
"to",
"either",
"the",
"range",
"min",
"or",
"max",
"."
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L194-L219
|
test
|
justinfx/gofileseq
|
ranges/ranges.go
|
Index
|
func (f *InclusiveRange) Index(value int) int {
closest := f.closestInRange(value, f.start, f.End(), f.step)
if closest != value {
return -1
}
idx := (value - f.start) / f.step
if idx < 0 {
idx *= -1
}
return idx
}
|
go
|
func (f *InclusiveRange) Index(value int) int {
closest := f.closestInRange(value, f.start, f.End(), f.step)
if closest != value {
return -1
}
idx := (value - f.start) / f.step
if idx < 0 {
idx *= -1
}
return idx
}
|
[
"func",
"(",
"f",
"*",
"InclusiveRange",
")",
"Index",
"(",
"value",
"int",
")",
"int",
"{",
"closest",
":=",
"f",
".",
"closestInRange",
"(",
"value",
",",
"f",
".",
"start",
",",
"f",
".",
"End",
"(",
")",
",",
"f",
".",
"step",
")",
"\n",
"if",
"closest",
"!=",
"value",
"{",
"return",
"-",
"1",
"\n",
"}",
"\n",
"idx",
":=",
"(",
"value",
"-",
"f",
".",
"start",
")",
"/",
"f",
".",
"step",
"\n",
"if",
"idx",
"<",
"0",
"{",
"idx",
"*=",
"-",
"1",
"\n",
"}",
"\n",
"return",
"idx",
"\n",
"}"
] |
// Index returns the 0-based index of the first occurrence
// given value, within the range.
// If the value does not exist in the range, a
// value of -1 will be returned
|
[
"Index",
"returns",
"the",
"0",
"-",
"based",
"index",
"of",
"the",
"first",
"occurrence",
"given",
"value",
"within",
"the",
"range",
".",
"If",
"the",
"value",
"does",
"not",
"exist",
"in",
"the",
"range",
"a",
"value",
"of",
"-",
"1",
"will",
"be",
"returned"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L250-L260
|
test
|
justinfx/gofileseq
|
ranges/ranges.go
|
String
|
func (l *InclusiveRanges) String() string {
var buf strings.Builder
for i, b := range l.blocks {
if i > 0 {
buf.WriteString(`,`)
}
buf.WriteString(b.String())
}
return buf.String()
}
|
go
|
func (l *InclusiveRanges) String() string {
var buf strings.Builder
for i, b := range l.blocks {
if i > 0 {
buf.WriteString(`,`)
}
buf.WriteString(b.String())
}
return buf.String()
}
|
[
"func",
"(",
"l",
"*",
"InclusiveRanges",
")",
"String",
"(",
")",
"string",
"{",
"var",
"buf",
"strings",
".",
"Builder",
"\n",
"for",
"i",
",",
"b",
":=",
"range",
"l",
".",
"blocks",
"{",
"if",
"i",
">",
"0",
"{",
"buf",
".",
"WriteString",
"(",
"`,`",
")",
"\n",
"}",
"\n",
"buf",
".",
"WriteString",
"(",
"b",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}"
] |
// String returns the formatted representation of
// the combination of all internal InclusiveRange instances
|
[
"String",
"returns",
"the",
"formatted",
"representation",
"of",
"the",
"combination",
"of",
"all",
"internal",
"InclusiveRange",
"instances"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L310-L319
|
test
|
justinfx/gofileseq
|
ranges/ranges.go
|
Len
|
func (l *InclusiveRanges) Len() int {
var totalLen int
for _, b := range l.blocks {
totalLen += b.Len()
}
return totalLen
}
|
go
|
func (l *InclusiveRanges) Len() int {
var totalLen int
for _, b := range l.blocks {
totalLen += b.Len()
}
return totalLen
}
|
[
"func",
"(",
"l",
"*",
"InclusiveRanges",
")",
"Len",
"(",
")",
"int",
"{",
"var",
"totalLen",
"int",
"\n",
"for",
"_",
",",
"b",
":=",
"range",
"l",
".",
"blocks",
"{",
"totalLen",
"+=",
"b",
".",
"Len",
"(",
")",
"\n",
"}",
"\n",
"return",
"totalLen",
"\n",
"}"
] |
// Len returns the total number of values across all ranges
|
[
"Len",
"returns",
"the",
"total",
"number",
"of",
"values",
"across",
"all",
"ranges"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L322-L328
|
test
|
justinfx/gofileseq
|
ranges/ranges.go
|
Start
|
func (l *InclusiveRanges) Start() int {
for _, b := range l.blocks {
return b.Start()
}
return 0
}
|
go
|
func (l *InclusiveRanges) Start() int {
for _, b := range l.blocks {
return b.Start()
}
return 0
}
|
[
"func",
"(",
"l",
"*",
"InclusiveRanges",
")",
"Start",
"(",
")",
"int",
"{",
"for",
"_",
",",
"b",
":=",
"range",
"l",
".",
"blocks",
"{",
"return",
"b",
".",
"Start",
"(",
")",
"\n",
"}",
"\n",
"return",
"0",
"\n",
"}"
] |
// Start returns the first value of the first range
|
[
"Start",
"returns",
"the",
"first",
"value",
"of",
"the",
"first",
"range"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L331-L336
|
test
|
justinfx/gofileseq
|
ranges/ranges.go
|
End
|
func (l *InclusiveRanges) End() int {
if l.blocks == nil {
return 0
}
return l.blocks[len(l.blocks)-1].End()
}
|
go
|
func (l *InclusiveRanges) End() int {
if l.blocks == nil {
return 0
}
return l.blocks[len(l.blocks)-1].End()
}
|
[
"func",
"(",
"l",
"*",
"InclusiveRanges",
")",
"End",
"(",
")",
"int",
"{",
"if",
"l",
".",
"blocks",
"==",
"nil",
"{",
"return",
"0",
"\n",
"}",
"\n",
"return",
"l",
".",
"blocks",
"[",
"len",
"(",
"l",
".",
"blocks",
")",
"-",
"1",
"]",
".",
"End",
"(",
")",
"\n",
"}"
] |
// End returns the last value of the last range
|
[
"End",
"returns",
"the",
"last",
"value",
"of",
"the",
"last",
"range"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L339-L344
|
test
|
justinfx/gofileseq
|
ranges/ranges.go
|
Min
|
func (l *InclusiveRanges) Min() int {
val := l.Start()
for _, aRange := range l.blocks {
next := aRange.Min()
if next < val {
val = next
}
}
return val
}
|
go
|
func (l *InclusiveRanges) Min() int {
val := l.Start()
for _, aRange := range l.blocks {
next := aRange.Min()
if next < val {
val = next
}
}
return val
}
|
[
"func",
"(",
"l",
"*",
"InclusiveRanges",
")",
"Min",
"(",
")",
"int",
"{",
"val",
":=",
"l",
".",
"Start",
"(",
")",
"\n",
"for",
"_",
",",
"aRange",
":=",
"range",
"l",
".",
"blocks",
"{",
"next",
":=",
"aRange",
".",
"Min",
"(",
")",
"\n",
"if",
"next",
"<",
"val",
"{",
"val",
"=",
"next",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"val",
"\n",
"}"
] |
// Min returns the smallest value in the total range
|
[
"Min",
"returns",
"the",
"smallest",
"value",
"in",
"the",
"total",
"range"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L347-L356
|
test
|
justinfx/gofileseq
|
ranges/ranges.go
|
Max
|
func (l *InclusiveRanges) Max() int {
val := l.End()
for _, aRange := range l.blocks {
next := aRange.Max()
if next > val {
val = next
}
}
return val
}
|
go
|
func (l *InclusiveRanges) Max() int {
val := l.End()
for _, aRange := range l.blocks {
next := aRange.Max()
if next > val {
val = next
}
}
return val
}
|
[
"func",
"(",
"l",
"*",
"InclusiveRanges",
")",
"Max",
"(",
")",
"int",
"{",
"val",
":=",
"l",
".",
"End",
"(",
")",
"\n",
"for",
"_",
",",
"aRange",
":=",
"range",
"l",
".",
"blocks",
"{",
"next",
":=",
"aRange",
".",
"Max",
"(",
")",
"\n",
"if",
"next",
">",
"val",
"{",
"val",
"=",
"next",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"val",
"\n",
"}"
] |
// Max returns the highest value in the total range
|
[
"Max",
"returns",
"the",
"highest",
"value",
"in",
"the",
"total",
"range"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L359-L368
|
test
|
justinfx/gofileseq
|
ranges/ranges.go
|
numRanges
|
func (l *InclusiveRanges) numRanges() int {
if l.blocks == nil {
return 0
}
return len(l.blocks)
}
|
go
|
func (l *InclusiveRanges) numRanges() int {
if l.blocks == nil {
return 0
}
return len(l.blocks)
}
|
[
"func",
"(",
"l",
"*",
"InclusiveRanges",
")",
"numRanges",
"(",
")",
"int",
"{",
"if",
"l",
".",
"blocks",
"==",
"nil",
"{",
"return",
"0",
"\n",
"}",
"\n",
"return",
"len",
"(",
"l",
".",
"blocks",
")",
"\n",
"}"
] |
// NumRanges returns the number of discreet sets
// of ranges that were appended.
|
[
"NumRanges",
"returns",
"the",
"number",
"of",
"discreet",
"sets",
"of",
"ranges",
"that",
"were",
"appended",
"."
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L372-L377
|
test
|
justinfx/gofileseq
|
ranges/ranges.go
|
rangeAt
|
func (l *InclusiveRanges) rangeAt(idx int) *InclusiveRange {
if idx < 0 || idx >= l.numRanges() {
return nil
}
return l.blocks[idx]
}
|
go
|
func (l *InclusiveRanges) rangeAt(idx int) *InclusiveRange {
if idx < 0 || idx >= l.numRanges() {
return nil
}
return l.blocks[idx]
}
|
[
"func",
"(",
"l",
"*",
"InclusiveRanges",
")",
"rangeAt",
"(",
"idx",
"int",
")",
"*",
"InclusiveRange",
"{",
"if",
"idx",
"<",
"0",
"||",
"idx",
">=",
"l",
".",
"numRanges",
"(",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"l",
".",
"blocks",
"[",
"idx",
"]",
"\n",
"}"
] |
// rangeAt returns the underlying InclusiveRange instance
// that was appended, at a given index
|
[
"rangeAt",
"returns",
"the",
"underlying",
"InclusiveRange",
"instance",
"that",
"was",
"appended",
"at",
"a",
"given",
"index"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L381-L386
|
test
|
justinfx/gofileseq
|
ranges/ranges.go
|
Append
|
func (l *InclusiveRanges) Append(start, end, step int) {
block := NewInclusiveRange(start, end, step)
l.blocks = append(l.blocks, block)
}
|
go
|
func (l *InclusiveRanges) Append(start, end, step int) {
block := NewInclusiveRange(start, end, step)
l.blocks = append(l.blocks, block)
}
|
[
"func",
"(",
"l",
"*",
"InclusiveRanges",
")",
"Append",
"(",
"start",
",",
"end",
",",
"step",
"int",
")",
"{",
"block",
":=",
"NewInclusiveRange",
"(",
"start",
",",
"end",
",",
"step",
")",
"\n",
"l",
".",
"blocks",
"=",
"append",
"(",
"l",
".",
"blocks",
",",
"block",
")",
"\n",
"}"
] |
// Append creates and adds another range of values
// to the total range list.
|
[
"Append",
"creates",
"and",
"adds",
"another",
"range",
"of",
"values",
"to",
"the",
"total",
"range",
"list",
"."
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L390-L393
|
test
|
justinfx/gofileseq
|
ranges/ranges.go
|
AppendUnique
|
func (l *InclusiveRanges) AppendUnique(start, end, step int) {
if step == 0 {
return
}
subStart := start
subEnd := start
subStep := step
last := start
pending := 0 // Track unique value count
// Handle loop test for both increasing
// and decreasing ranges
var pred func() bool
if start <= end {
if step < 0 {
step *= -1
}
pred = func() bool { return subEnd <= end }
} else {
if step > 0 {
step *= -1
}
pred = func() bool { return subEnd >= end }
}
// Short-circuit if this is the first range being added
if len(l.blocks) == 0 {
l.Append(start, end, step)
return
}
// TODO: More intelligent fast-paths for easy-to-identify
// overlapping ranges. Such as when the existing range is:
// 1-100x1 and we are appending 50-150x1. Should be easy
// enough to just know we can Append(101,150,1)
for ; pred(); subEnd += step {
if !l.Contains(subEnd) {
// Is a unique value in the range
last = subEnd
if pending == 0 {
subStart = last
}
pending++
continue
}
if pending == 0 {
// Nothing to add yet
continue
}
// Current value is already in range.
// Add previous values
l.Append(subStart, last, subStep)
subStart = subEnd + step
pending = 0
}
// Flush the remaining values
if pending > 0 {
l.Append(subStart, last, subStep)
}
}
|
go
|
func (l *InclusiveRanges) AppendUnique(start, end, step int) {
if step == 0 {
return
}
subStart := start
subEnd := start
subStep := step
last := start
pending := 0 // Track unique value count
// Handle loop test for both increasing
// and decreasing ranges
var pred func() bool
if start <= end {
if step < 0 {
step *= -1
}
pred = func() bool { return subEnd <= end }
} else {
if step > 0 {
step *= -1
}
pred = func() bool { return subEnd >= end }
}
// Short-circuit if this is the first range being added
if len(l.blocks) == 0 {
l.Append(start, end, step)
return
}
// TODO: More intelligent fast-paths for easy-to-identify
// overlapping ranges. Such as when the existing range is:
// 1-100x1 and we are appending 50-150x1. Should be easy
// enough to just know we can Append(101,150,1)
for ; pred(); subEnd += step {
if !l.Contains(subEnd) {
// Is a unique value in the range
last = subEnd
if pending == 0 {
subStart = last
}
pending++
continue
}
if pending == 0 {
// Nothing to add yet
continue
}
// Current value is already in range.
// Add previous values
l.Append(subStart, last, subStep)
subStart = subEnd + step
pending = 0
}
// Flush the remaining values
if pending > 0 {
l.Append(subStart, last, subStep)
}
}
|
[
"func",
"(",
"l",
"*",
"InclusiveRanges",
")",
"AppendUnique",
"(",
"start",
",",
"end",
",",
"step",
"int",
")",
"{",
"if",
"step",
"==",
"0",
"{",
"return",
"\n",
"}",
"\n",
"subStart",
":=",
"start",
"\n",
"subEnd",
":=",
"start",
"\n",
"subStep",
":=",
"step",
"\n",
"last",
":=",
"start",
"\n",
"pending",
":=",
"0",
"\n",
"var",
"pred",
"func",
"(",
")",
"bool",
"\n",
"if",
"start",
"<=",
"end",
"{",
"if",
"step",
"<",
"0",
"{",
"step",
"*=",
"-",
"1",
"\n",
"}",
"\n",
"pred",
"=",
"func",
"(",
")",
"bool",
"{",
"return",
"subEnd",
"<=",
"end",
"}",
"\n",
"}",
"else",
"{",
"if",
"step",
">",
"0",
"{",
"step",
"*=",
"-",
"1",
"\n",
"}",
"\n",
"pred",
"=",
"func",
"(",
")",
"bool",
"{",
"return",
"subEnd",
">=",
"end",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"l",
".",
"blocks",
")",
"==",
"0",
"{",
"l",
".",
"Append",
"(",
"start",
",",
"end",
",",
"step",
")",
"\n",
"return",
"\n",
"}",
"\n",
"for",
";",
"pred",
"(",
")",
";",
"subEnd",
"+=",
"step",
"{",
"if",
"!",
"l",
".",
"Contains",
"(",
"subEnd",
")",
"{",
"last",
"=",
"subEnd",
"\n",
"if",
"pending",
"==",
"0",
"{",
"subStart",
"=",
"last",
"\n",
"}",
"\n",
"pending",
"++",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"pending",
"==",
"0",
"{",
"continue",
"\n",
"}",
"\n",
"l",
".",
"Append",
"(",
"subStart",
",",
"last",
",",
"subStep",
")",
"\n",
"subStart",
"=",
"subEnd",
"+",
"step",
"\n",
"pending",
"=",
"0",
"\n",
"}",
"\n",
"if",
"pending",
">",
"0",
"{",
"l",
".",
"Append",
"(",
"subStart",
",",
"last",
",",
"subStep",
")",
"\n",
"}",
"\n",
"}"
] |
// AppendUnique creates and adds another range of values
// to the total range list. Only unique values from the
// given range are appended to the total range.
|
[
"AppendUnique",
"creates",
"and",
"adds",
"another",
"range",
"of",
"values",
"to",
"the",
"total",
"range",
"list",
".",
"Only",
"unique",
"values",
"from",
"the",
"given",
"range",
"are",
"appended",
"to",
"the",
"total",
"range",
"."
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L398-L462
|
test
|
justinfx/gofileseq
|
ranges/ranges.go
|
Contains
|
func (l *InclusiveRanges) Contains(value int) bool {
for _, b := range l.blocks {
if b.Contains(value) {
return true
}
}
return false
}
|
go
|
func (l *InclusiveRanges) Contains(value int) bool {
for _, b := range l.blocks {
if b.Contains(value) {
return true
}
}
return false
}
|
[
"func",
"(",
"l",
"*",
"InclusiveRanges",
")",
"Contains",
"(",
"value",
"int",
")",
"bool",
"{",
"for",
"_",
",",
"b",
":=",
"range",
"l",
".",
"blocks",
"{",
"if",
"b",
".",
"Contains",
"(",
"value",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// Contains returns true if a given value is a valid
// value within the total range.
|
[
"Contains",
"returns",
"true",
"if",
"a",
"given",
"value",
"is",
"a",
"valid",
"value",
"within",
"the",
"total",
"range",
"."
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L466-L473
|
test
|
justinfx/gofileseq
|
ranges/ranges.go
|
Index
|
func (l *InclusiveRanges) Index(value int) int {
var idx, n int
for _, b := range l.blocks {
// If the value is within the current block
// then return the local index, offset by the
// number of previous values we have tracked
if idx = b.Index(value); idx >= 0 {
return idx + n
}
// Update the offset for the values we have seen
n += b.Len()
}
// The previous loop ended in error
return -1
}
|
go
|
func (l *InclusiveRanges) Index(value int) int {
var idx, n int
for _, b := range l.blocks {
// If the value is within the current block
// then return the local index, offset by the
// number of previous values we have tracked
if idx = b.Index(value); idx >= 0 {
return idx + n
}
// Update the offset for the values we have seen
n += b.Len()
}
// The previous loop ended in error
return -1
}
|
[
"func",
"(",
"l",
"*",
"InclusiveRanges",
")",
"Index",
"(",
"value",
"int",
")",
"int",
"{",
"var",
"idx",
",",
"n",
"int",
"\n",
"for",
"_",
",",
"b",
":=",
"range",
"l",
".",
"blocks",
"{",
"if",
"idx",
"=",
"b",
".",
"Index",
"(",
"value",
")",
";",
"idx",
">=",
"0",
"{",
"return",
"idx",
"+",
"n",
"\n",
"}",
"\n",
"n",
"+=",
"b",
".",
"Len",
"(",
")",
"\n",
"}",
"\n",
"return",
"-",
"1",
"\n",
"}"
] |
// Index returns the 0-based index of the first occurrence
// of the given value, within the range.
// If the value does not exist in the range, a
// value of -1 will be returned.
|
[
"Index",
"returns",
"the",
"0",
"-",
"based",
"index",
"of",
"the",
"first",
"occurrence",
"of",
"the",
"given",
"value",
"within",
"the",
"range",
".",
"If",
"the",
"value",
"does",
"not",
"exist",
"in",
"the",
"range",
"a",
"value",
"of",
"-",
"1",
"will",
"be",
"returned",
"."
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/ranges/ranges.go#L511-L527
|
test
|
justinfx/gofileseq
|
sequence.go
|
FrameRange
|
func (s *FileSequence) FrameRange() string {
if s.frameSet == nil {
return ""
}
return s.frameSet.FrameRange()
}
|
go
|
func (s *FileSequence) FrameRange() string {
if s.frameSet == nil {
return ""
}
return s.frameSet.FrameRange()
}
|
[
"func",
"(",
"s",
"*",
"FileSequence",
")",
"FrameRange",
"(",
")",
"string",
"{",
"if",
"s",
".",
"frameSet",
"==",
"nil",
"{",
"return",
"\"\"",
"\n",
"}",
"\n",
"return",
"s",
".",
"frameSet",
".",
"FrameRange",
"(",
")",
"\n",
"}"
] |
// FrameRange returns the string frame range component,
// parsed from the sequence. If no frame range was parsed,
// then this method will return an empty string.
|
[
"FrameRange",
"returns",
"the",
"string",
"frame",
"range",
"component",
"parsed",
"from",
"the",
"sequence",
".",
"If",
"no",
"frame",
"range",
"was",
"parsed",
"then",
"this",
"method",
"will",
"return",
"an",
"empty",
"string",
"."
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/sequence.go#L296-L301
|
test
|
justinfx/gofileseq
|
sequence.go
|
FrameRangePadded
|
func (s *FileSequence) FrameRangePadded() string {
if s.frameSet == nil {
return ""
}
return s.frameSet.FrameRangePadded(s.zfill)
}
|
go
|
func (s *FileSequence) FrameRangePadded() string {
if s.frameSet == nil {
return ""
}
return s.frameSet.FrameRangePadded(s.zfill)
}
|
[
"func",
"(",
"s",
"*",
"FileSequence",
")",
"FrameRangePadded",
"(",
")",
"string",
"{",
"if",
"s",
".",
"frameSet",
"==",
"nil",
"{",
"return",
"\"\"",
"\n",
"}",
"\n",
"return",
"s",
".",
"frameSet",
".",
"FrameRangePadded",
"(",
"s",
".",
"zfill",
")",
"\n",
"}"
] |
// FrameRangePadded returns the string frame range component,
// parsed from the sequence, and padded out by the pad characters.
// If no frame range was parsed, then this method will return an empty string.
|
[
"FrameRangePadded",
"returns",
"the",
"string",
"frame",
"range",
"component",
"parsed",
"from",
"the",
"sequence",
"and",
"padded",
"out",
"by",
"the",
"pad",
"characters",
".",
"If",
"no",
"frame",
"range",
"was",
"parsed",
"then",
"this",
"method",
"will",
"return",
"an",
"empty",
"string",
"."
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/sequence.go#L306-L311
|
test
|
justinfx/gofileseq
|
sequence.go
|
Index
|
func (s *FileSequence) Index(idx int) string {
if s.frameSet == nil {
return s.String()
}
frame, err := s.frameSet.Frame(idx)
if err != nil {
return ""
}
path, err := s.Frame(frame)
if err != nil {
return ""
}
return path
}
|
go
|
func (s *FileSequence) Index(idx int) string {
if s.frameSet == nil {
return s.String()
}
frame, err := s.frameSet.Frame(idx)
if err != nil {
return ""
}
path, err := s.Frame(frame)
if err != nil {
return ""
}
return path
}
|
[
"func",
"(",
"s",
"*",
"FileSequence",
")",
"Index",
"(",
"idx",
"int",
")",
"string",
"{",
"if",
"s",
".",
"frameSet",
"==",
"nil",
"{",
"return",
"s",
".",
"String",
"(",
")",
"\n",
"}",
"\n",
"frame",
",",
"err",
":=",
"s",
".",
"frameSet",
".",
"Frame",
"(",
"idx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
"\n",
"}",
"\n",
"path",
",",
"err",
":=",
"s",
".",
"Frame",
"(",
"frame",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
"\n",
"}",
"\n",
"return",
"path",
"\n",
"}"
] |
// Index returns the path to the file at the given index
// in the sequence. If a frame range was not parsed from
// the sequence, this will always returns the original path.
// If the index is not valid, this will return an empty string.
|
[
"Index",
"returns",
"the",
"path",
"to",
"the",
"file",
"at",
"the",
"given",
"index",
"in",
"the",
"sequence",
".",
"If",
"a",
"frame",
"range",
"was",
"not",
"parsed",
"from",
"the",
"sequence",
"this",
"will",
"always",
"returns",
"the",
"original",
"path",
".",
"If",
"the",
"index",
"is",
"not",
"valid",
"this",
"will",
"return",
"an",
"empty",
"string",
"."
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/sequence.go#L413-L426
|
test
|
justinfx/gofileseq
|
sequence.go
|
SetDirname
|
func (s *FileSequence) SetDirname(dir string) {
if !strings.HasSuffix(dir, string(filepath.Separator)) {
dir = dir + string(filepath.Separator)
}
s.dir = dir
}
|
go
|
func (s *FileSequence) SetDirname(dir string) {
if !strings.HasSuffix(dir, string(filepath.Separator)) {
dir = dir + string(filepath.Separator)
}
s.dir = dir
}
|
[
"func",
"(",
"s",
"*",
"FileSequence",
")",
"SetDirname",
"(",
"dir",
"string",
")",
"{",
"if",
"!",
"strings",
".",
"HasSuffix",
"(",
"dir",
",",
"string",
"(",
"filepath",
".",
"Separator",
")",
")",
"{",
"dir",
"=",
"dir",
"+",
"string",
"(",
"filepath",
".",
"Separator",
")",
"\n",
"}",
"\n",
"s",
".",
"dir",
"=",
"dir",
"\n",
"}"
] |
// Set a new dirname for the sequence
|
[
"Set",
"a",
"new",
"dirname",
"for",
"the",
"sequence"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/sequence.go#L429-L434
|
test
|
justinfx/gofileseq
|
sequence.go
|
SetPadding
|
func (s *FileSequence) SetPadding(padChars string) {
s.padChar = padChars
s.zfill = s.padMapper.PaddingCharsSize(padChars)
}
|
go
|
func (s *FileSequence) SetPadding(padChars string) {
s.padChar = padChars
s.zfill = s.padMapper.PaddingCharsSize(padChars)
}
|
[
"func",
"(",
"s",
"*",
"FileSequence",
")",
"SetPadding",
"(",
"padChars",
"string",
")",
"{",
"s",
".",
"padChar",
"=",
"padChars",
"\n",
"s",
".",
"zfill",
"=",
"s",
".",
"padMapper",
".",
"PaddingCharsSize",
"(",
"padChars",
")",
"\n",
"}"
] |
// Set a new padding characters for the sequence
|
[
"Set",
"a",
"new",
"padding",
"characters",
"for",
"the",
"sequence"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/sequence.go#L442-L445
|
test
|
justinfx/gofileseq
|
sequence.go
|
SetPaddingStyle
|
func (s *FileSequence) SetPaddingStyle(style PadStyle) {
s.padMapper = padders[style]
s.SetPadding(s.padMapper.PaddingChars(s.ZFill()))
}
|
go
|
func (s *FileSequence) SetPaddingStyle(style PadStyle) {
s.padMapper = padders[style]
s.SetPadding(s.padMapper.PaddingChars(s.ZFill()))
}
|
[
"func",
"(",
"s",
"*",
"FileSequence",
")",
"SetPaddingStyle",
"(",
"style",
"PadStyle",
")",
"{",
"s",
".",
"padMapper",
"=",
"padders",
"[",
"style",
"]",
"\n",
"s",
".",
"SetPadding",
"(",
"s",
".",
"padMapper",
".",
"PaddingChars",
"(",
"s",
".",
"ZFill",
"(",
")",
")",
")",
"\n",
"}"
] |
// Set a new padding style for mapping between characters and
// their numeric width
|
[
"Set",
"a",
"new",
"padding",
"style",
"for",
"mapping",
"between",
"characters",
"and",
"their",
"numeric",
"width"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/sequence.go#L449-L452
|
test
|
justinfx/gofileseq
|
sequence.go
|
SetExt
|
func (s *FileSequence) SetExt(ext string) {
if !strings.HasPrefix(ext, ".") {
ext = "." + ext
}
s.ext = ext
}
|
go
|
func (s *FileSequence) SetExt(ext string) {
if !strings.HasPrefix(ext, ".") {
ext = "." + ext
}
s.ext = ext
}
|
[
"func",
"(",
"s",
"*",
"FileSequence",
")",
"SetExt",
"(",
"ext",
"string",
")",
"{",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"ext",
",",
"\".\"",
")",
"{",
"ext",
"=",
"\".\"",
"+",
"ext",
"\n",
"}",
"\n",
"s",
".",
"ext",
"=",
"ext",
"\n",
"}"
] |
// Set a new ext for the sequence
|
[
"Set",
"a",
"new",
"ext",
"for",
"the",
"sequence"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/sequence.go#L455-L460
|
test
|
justinfx/gofileseq
|
sequence.go
|
SetFrameRange
|
func (s *FileSequence) SetFrameRange(frameRange string) error {
frameSet, err := NewFrameSet(frameRange)
if err != nil {
return err
}
s.frameSet = frameSet
return nil
}
|
go
|
func (s *FileSequence) SetFrameRange(frameRange string) error {
frameSet, err := NewFrameSet(frameRange)
if err != nil {
return err
}
s.frameSet = frameSet
return nil
}
|
[
"func",
"(",
"s",
"*",
"FileSequence",
")",
"SetFrameRange",
"(",
"frameRange",
"string",
")",
"error",
"{",
"frameSet",
",",
"err",
":=",
"NewFrameSet",
"(",
"frameRange",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"s",
".",
"frameSet",
"=",
"frameSet",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Set a new FrameSet, by way of providing a string frame range.
// If the frame range cannot be parsed, an error will be returned.
|
[
"Set",
"a",
"new",
"FrameSet",
"by",
"way",
"of",
"providing",
"a",
"string",
"frame",
"range",
".",
"If",
"the",
"frame",
"range",
"cannot",
"be",
"parsed",
"an",
"error",
"will",
"be",
"returned",
"."
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/sequence.go#L469-L476
|
test
|
justinfx/gofileseq
|
sequence.go
|
Len
|
func (s *FileSequence) Len() int {
if s.frameSet == nil {
return 1
}
return s.frameSet.Len()
}
|
go
|
func (s *FileSequence) Len() int {
if s.frameSet == nil {
return 1
}
return s.frameSet.Len()
}
|
[
"func",
"(",
"s",
"*",
"FileSequence",
")",
"Len",
"(",
")",
"int",
"{",
"if",
"s",
".",
"frameSet",
"==",
"nil",
"{",
"return",
"1",
"\n",
"}",
"\n",
"return",
"s",
".",
"frameSet",
".",
"Len",
"(",
")",
"\n",
"}"
] |
// Len returns the number of frames in the FrameSet.
// If a frame range was not parsed, this will always return 1
|
[
"Len",
"returns",
"the",
"number",
"of",
"frames",
"in",
"the",
"FrameSet",
".",
"If",
"a",
"frame",
"range",
"was",
"not",
"parsed",
"this",
"will",
"always",
"return",
"1"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/sequence.go#L480-L485
|
test
|
justinfx/gofileseq
|
sequence.go
|
String
|
func (s *FileSequence) String() string {
var fs string
if s.frameSet != nil {
fs = s.frameSet.String()
}
buf := bytes.NewBufferString(s.dir)
buf.WriteString(s.basename)
buf.WriteString(fs)
buf.WriteString(s.padChar)
buf.WriteString(s.ext)
return buf.String()
}
|
go
|
func (s *FileSequence) String() string {
var fs string
if s.frameSet != nil {
fs = s.frameSet.String()
}
buf := bytes.NewBufferString(s.dir)
buf.WriteString(s.basename)
buf.WriteString(fs)
buf.WriteString(s.padChar)
buf.WriteString(s.ext)
return buf.String()
}
|
[
"func",
"(",
"s",
"*",
"FileSequence",
")",
"String",
"(",
")",
"string",
"{",
"var",
"fs",
"string",
"\n",
"if",
"s",
".",
"frameSet",
"!=",
"nil",
"{",
"fs",
"=",
"s",
".",
"frameSet",
".",
"String",
"(",
")",
"\n",
"}",
"\n",
"buf",
":=",
"bytes",
".",
"NewBufferString",
"(",
"s",
".",
"dir",
")",
"\n",
"buf",
".",
"WriteString",
"(",
"s",
".",
"basename",
")",
"\n",
"buf",
".",
"WriteString",
"(",
"fs",
")",
"\n",
"buf",
".",
"WriteString",
"(",
"s",
".",
"padChar",
")",
"\n",
"buf",
".",
"WriteString",
"(",
"s",
".",
"ext",
")",
"\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}"
] |
// String returns the formatted sequence
|
[
"String",
"returns",
"the",
"formatted",
"sequence"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/sequence.go#L488-L499
|
test
|
justinfx/gofileseq
|
sequence.go
|
Copy
|
func (s *FileSequence) Copy() *FileSequence {
seq, _ := NewFileSequence(s.String())
return seq
}
|
go
|
func (s *FileSequence) Copy() *FileSequence {
seq, _ := NewFileSequence(s.String())
return seq
}
|
[
"func",
"(",
"s",
"*",
"FileSequence",
")",
"Copy",
"(",
")",
"*",
"FileSequence",
"{",
"seq",
",",
"_",
":=",
"NewFileSequence",
"(",
"s",
".",
"String",
"(",
")",
")",
"\n",
"return",
"seq",
"\n",
"}"
] |
// Copy returns a copy of the FileSequence
|
[
"Copy",
"returns",
"a",
"copy",
"of",
"the",
"FileSequence"
] |
2555f296b4493d1825f5f6fab4aa0ff51a8306cd
|
https://github.com/justinfx/gofileseq/blob/2555f296b4493d1825f5f6fab4aa0ff51a8306cd/sequence.go#L502-L505
|
test
|
achiku/soapc
|
client.go
|
NewClient
|
func NewClient(url string, tls bool, header interface{}) *Client {
return &Client{
url: url,
tls: tls,
header: header,
}
}
|
go
|
func NewClient(url string, tls bool, header interface{}) *Client {
return &Client{
url: url,
tls: tls,
header: header,
}
}
|
[
"func",
"NewClient",
"(",
"url",
"string",
",",
"tls",
"bool",
",",
"header",
"interface",
"{",
"}",
")",
"*",
"Client",
"{",
"return",
"&",
"Client",
"{",
"url",
":",
"url",
",",
"tls",
":",
"tls",
",",
"header",
":",
"header",
",",
"}",
"\n",
"}"
] |
// NewClient return SOAP client
|
[
"NewClient",
"return",
"SOAP",
"client"
] |
cfbdfe6e4caffe57a9cba89996e8b1cedb512be0
|
https://github.com/achiku/soapc/blob/cfbdfe6e4caffe57a9cba89996e8b1cedb512be0/client.go#L50-L56
|
test
|
achiku/soapc
|
client.go
|
UnmarshalXML
|
func (h *Header) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
var (
token xml.Token
err error
)
Loop:
for {
if token, err = d.Token(); err != nil {
return err
}
if token == nil {
break
}
switch se := token.(type) {
case xml.StartElement:
if err = d.DecodeElement(h.Content, &se); err != nil {
return err
}
case xml.EndElement:
break Loop
}
}
return nil
}
|
go
|
func (h *Header) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
var (
token xml.Token
err error
)
Loop:
for {
if token, err = d.Token(); err != nil {
return err
}
if token == nil {
break
}
switch se := token.(type) {
case xml.StartElement:
if err = d.DecodeElement(h.Content, &se); err != nil {
return err
}
case xml.EndElement:
break Loop
}
}
return nil
}
|
[
"func",
"(",
"h",
"*",
"Header",
")",
"UnmarshalXML",
"(",
"d",
"*",
"xml",
".",
"Decoder",
",",
"start",
"xml",
".",
"StartElement",
")",
"error",
"{",
"var",
"(",
"token",
"xml",
".",
"Token",
"\n",
"err",
"error",
"\n",
")",
"\n",
"Loop",
":",
"for",
"{",
"if",
"token",
",",
"err",
"=",
"d",
".",
"Token",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"token",
"==",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"switch",
"se",
":=",
"token",
".",
"(",
"type",
")",
"{",
"case",
"xml",
".",
"StartElement",
":",
"if",
"err",
"=",
"d",
".",
"DecodeElement",
"(",
"h",
".",
"Content",
",",
"&",
"se",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"case",
"xml",
".",
"EndElement",
":",
"break",
"Loop",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// UnmarshalXML unmarshal SOAPHeader
|
[
"UnmarshalXML",
"unmarshal",
"SOAPHeader"
] |
cfbdfe6e4caffe57a9cba89996e8b1cedb512be0
|
https://github.com/achiku/soapc/blob/cfbdfe6e4caffe57a9cba89996e8b1cedb512be0/client.go#L72-L95
|
test
|
achiku/soapc
|
client.go
|
UnmarshalXML
|
func (b *Body) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
if b.Content == nil {
return xml.UnmarshalError("Content must be a pointer to a struct")
}
var (
token xml.Token
err error
consumed bool
)
Loop:
for {
if token, err = d.Token(); err != nil {
return err
}
if token == nil {
break
}
envelopeNameSpace := "http://schemas.xmlsoap.org/soap/envelope/"
switch se := token.(type) {
case xml.StartElement:
if consumed {
return xml.UnmarshalError(
"Found multiple elements inside SOAP body; not wrapped-document/literal WS-I compliant")
} else if se.Name.Space == envelopeNameSpace && se.Name.Local == "Fault" {
b.Fault = &Fault{}
b.Content = nil
err = d.DecodeElement(b.Fault, &se)
if err != nil {
return err
}
consumed = true
} else {
if err = d.DecodeElement(b.Content, &se); err != nil {
return err
}
consumed = true
}
case xml.EndElement:
break Loop
}
}
return nil
}
|
go
|
func (b *Body) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
if b.Content == nil {
return xml.UnmarshalError("Content must be a pointer to a struct")
}
var (
token xml.Token
err error
consumed bool
)
Loop:
for {
if token, err = d.Token(); err != nil {
return err
}
if token == nil {
break
}
envelopeNameSpace := "http://schemas.xmlsoap.org/soap/envelope/"
switch se := token.(type) {
case xml.StartElement:
if consumed {
return xml.UnmarshalError(
"Found multiple elements inside SOAP body; not wrapped-document/literal WS-I compliant")
} else if se.Name.Space == envelopeNameSpace && se.Name.Local == "Fault" {
b.Fault = &Fault{}
b.Content = nil
err = d.DecodeElement(b.Fault, &se)
if err != nil {
return err
}
consumed = true
} else {
if err = d.DecodeElement(b.Content, &se); err != nil {
return err
}
consumed = true
}
case xml.EndElement:
break Loop
}
}
return nil
}
|
[
"func",
"(",
"b",
"*",
"Body",
")",
"UnmarshalXML",
"(",
"d",
"*",
"xml",
".",
"Decoder",
",",
"start",
"xml",
".",
"StartElement",
")",
"error",
"{",
"if",
"b",
".",
"Content",
"==",
"nil",
"{",
"return",
"xml",
".",
"UnmarshalError",
"(",
"\"Content must be a pointer to a struct\"",
")",
"\n",
"}",
"\n",
"var",
"(",
"token",
"xml",
".",
"Token",
"\n",
"err",
"error",
"\n",
"consumed",
"bool",
"\n",
")",
"\n",
"Loop",
":",
"for",
"{",
"if",
"token",
",",
"err",
"=",
"d",
".",
"Token",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"token",
"==",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"envelopeNameSpace",
":=",
"\"http://schemas.xmlsoap.org/soap/envelope/\"",
"\n",
"switch",
"se",
":=",
"token",
".",
"(",
"type",
")",
"{",
"case",
"xml",
".",
"StartElement",
":",
"if",
"consumed",
"{",
"return",
"xml",
".",
"UnmarshalError",
"(",
"\"Found multiple elements inside SOAP body; not wrapped-document/literal WS-I compliant\"",
")",
"\n",
"}",
"else",
"if",
"se",
".",
"Name",
".",
"Space",
"==",
"envelopeNameSpace",
"&&",
"se",
".",
"Name",
".",
"Local",
"==",
"\"Fault\"",
"{",
"b",
".",
"Fault",
"=",
"&",
"Fault",
"{",
"}",
"\n",
"b",
".",
"Content",
"=",
"nil",
"\n",
"err",
"=",
"d",
".",
"DecodeElement",
"(",
"b",
".",
"Fault",
",",
"&",
"se",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"consumed",
"=",
"true",
"\n",
"}",
"else",
"{",
"if",
"err",
"=",
"d",
".",
"DecodeElement",
"(",
"b",
".",
"Content",
",",
"&",
"se",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"consumed",
"=",
"true",
"\n",
"}",
"\n",
"case",
"xml",
".",
"EndElement",
":",
"break",
"Loop",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// UnmarshalXML unmarshal SOAPBody
|
[
"UnmarshalXML",
"unmarshal",
"SOAPBody"
] |
cfbdfe6e4caffe57a9cba89996e8b1cedb512be0
|
https://github.com/achiku/soapc/blob/cfbdfe6e4caffe57a9cba89996e8b1cedb512be0/client.go#L98-L140
|
test
|
achiku/soapc
|
client.go
|
Call
|
func (s *Client) Call(soapAction string, request, response, header interface{}) error {
var envelope Envelope
if s.header != nil {
envelope = Envelope{
Header: &Header{
Content: s.header,
},
Body: Body{
Content: request,
},
}
} else {
envelope = Envelope{
Body: Body{
Content: request,
},
}
}
buffer := new(bytes.Buffer)
encoder := xml.NewEncoder(buffer)
encoder.Indent(" ", " ")
if err := encoder.Encode(envelope); err != nil {
return errors.Wrap(err, "failed to encode envelope")
}
if err := encoder.Flush(); err != nil {
return errors.Wrap(err, "failed to flush encoder")
}
req, err := http.NewRequest("POST", s.url, buffer)
if err != nil {
return errors.Wrap(err, "failed to create POST request")
}
req.Header.Add("Content-Type", "text/xml; charset=\"utf-8\"")
req.Header.Set("SOAPAction", soapAction)
req.Header.Set("User-Agent", s.userAgent)
req.Close = true
tr := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: s.tls,
},
Dial: dialTimeout,
}
client := &http.Client{Transport: tr}
res, err := client.Do(req)
if err != nil {
return errors.Wrap(err, "failed to send SOAP request")
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
soapFault, err := ioutil.ReadAll(res.Body)
if err != nil {
return errors.Wrap(err, "failed to read SOAP fault response body")
}
msg := fmt.Sprintf("HTTP Status Code: %d, SOAP Fault: \n%s", res.StatusCode, string(soapFault))
return errors.New(msg)
}
rawbody, err := ioutil.ReadAll(res.Body)
if err != nil {
return errors.Wrap(err, "failed to read SOAP body")
}
if len(rawbody) == 0 {
return nil
}
respEnvelope := Envelope{}
respEnvelope.Body = Body{Content: response}
if header != nil {
respEnvelope.Header = &Header{Content: header}
}
if err = xml.Unmarshal(rawbody, &respEnvelope); err != nil {
return errors.Wrap(err, "failed to unmarshal response SOAP Envelope")
}
return nil
}
|
go
|
func (s *Client) Call(soapAction string, request, response, header interface{}) error {
var envelope Envelope
if s.header != nil {
envelope = Envelope{
Header: &Header{
Content: s.header,
},
Body: Body{
Content: request,
},
}
} else {
envelope = Envelope{
Body: Body{
Content: request,
},
}
}
buffer := new(bytes.Buffer)
encoder := xml.NewEncoder(buffer)
encoder.Indent(" ", " ")
if err := encoder.Encode(envelope); err != nil {
return errors.Wrap(err, "failed to encode envelope")
}
if err := encoder.Flush(); err != nil {
return errors.Wrap(err, "failed to flush encoder")
}
req, err := http.NewRequest("POST", s.url, buffer)
if err != nil {
return errors.Wrap(err, "failed to create POST request")
}
req.Header.Add("Content-Type", "text/xml; charset=\"utf-8\"")
req.Header.Set("SOAPAction", soapAction)
req.Header.Set("User-Agent", s.userAgent)
req.Close = true
tr := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: s.tls,
},
Dial: dialTimeout,
}
client := &http.Client{Transport: tr}
res, err := client.Do(req)
if err != nil {
return errors.Wrap(err, "failed to send SOAP request")
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
soapFault, err := ioutil.ReadAll(res.Body)
if err != nil {
return errors.Wrap(err, "failed to read SOAP fault response body")
}
msg := fmt.Sprintf("HTTP Status Code: %d, SOAP Fault: \n%s", res.StatusCode, string(soapFault))
return errors.New(msg)
}
rawbody, err := ioutil.ReadAll(res.Body)
if err != nil {
return errors.Wrap(err, "failed to read SOAP body")
}
if len(rawbody) == 0 {
return nil
}
respEnvelope := Envelope{}
respEnvelope.Body = Body{Content: response}
if header != nil {
respEnvelope.Header = &Header{Content: header}
}
if err = xml.Unmarshal(rawbody, &respEnvelope); err != nil {
return errors.Wrap(err, "failed to unmarshal response SOAP Envelope")
}
return nil
}
|
[
"func",
"(",
"s",
"*",
"Client",
")",
"Call",
"(",
"soapAction",
"string",
",",
"request",
",",
"response",
",",
"header",
"interface",
"{",
"}",
")",
"error",
"{",
"var",
"envelope",
"Envelope",
"\n",
"if",
"s",
".",
"header",
"!=",
"nil",
"{",
"envelope",
"=",
"Envelope",
"{",
"Header",
":",
"&",
"Header",
"{",
"Content",
":",
"s",
".",
"header",
",",
"}",
",",
"Body",
":",
"Body",
"{",
"Content",
":",
"request",
",",
"}",
",",
"}",
"\n",
"}",
"else",
"{",
"envelope",
"=",
"Envelope",
"{",
"Body",
":",
"Body",
"{",
"Content",
":",
"request",
",",
"}",
",",
"}",
"\n",
"}",
"\n",
"buffer",
":=",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"\n",
"encoder",
":=",
"xml",
".",
"NewEncoder",
"(",
"buffer",
")",
"\n",
"encoder",
".",
"Indent",
"(",
"\" \"",
",",
"\" \"",
")",
"\n",
"if",
"err",
":=",
"encoder",
".",
"Encode",
"(",
"envelope",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to encode envelope\"",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"encoder",
".",
"Flush",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to flush encoder\"",
")",
"\n",
"}",
"\n",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"\"POST\"",
",",
"s",
".",
"url",
",",
"buffer",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to create POST request\"",
")",
"\n",
"}",
"\n",
"req",
".",
"Header",
".",
"Add",
"(",
"\"Content-Type\"",
",",
"\"text/xml; charset=\\\"utf-8\\\"\"",
")",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"req",
".",
"Header",
".",
"Set",
"(",
"\"SOAPAction\"",
",",
"soapAction",
")",
"\n",
"req",
".",
"Header",
".",
"Set",
"(",
"\"User-Agent\"",
",",
"s",
".",
"userAgent",
")",
"\n",
"req",
".",
"Close",
"=",
"true",
"\n",
"tr",
":=",
"&",
"http",
".",
"Transport",
"{",
"TLSClientConfig",
":",
"&",
"tls",
".",
"Config",
"{",
"InsecureSkipVerify",
":",
"s",
".",
"tls",
",",
"}",
",",
"Dial",
":",
"dialTimeout",
",",
"}",
"\n",
"client",
":=",
"&",
"http",
".",
"Client",
"{",
"Transport",
":",
"tr",
"}",
"\n",
"res",
",",
"err",
":=",
"client",
".",
"Do",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to send SOAP request\"",
")",
"\n",
"}",
"\n",
"defer",
"res",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"if",
"res",
".",
"StatusCode",
"!=",
"http",
".",
"StatusOK",
"{",
"soapFault",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"res",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to read SOAP fault response body\"",
")",
"\n",
"}",
"\n",
"msg",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"HTTP Status Code: %d, SOAP Fault: \\n%s\"",
",",
"\\n",
",",
"res",
".",
"StatusCode",
")",
"\n",
"string",
"(",
"soapFault",
")",
"\n",
"}",
"\n",
"return",
"errors",
".",
"New",
"(",
"msg",
")",
"\n",
"rawbody",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"res",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"failed to read SOAP body\"",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"rawbody",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"respEnvelope",
":=",
"Envelope",
"{",
"}",
"\n",
"respEnvelope",
".",
"Body",
"=",
"Body",
"{",
"Content",
":",
"response",
"}",
"\n",
"}"
] |
// Call SOAP client API call
|
[
"Call",
"SOAP",
"client",
"API",
"call"
] |
cfbdfe6e4caffe57a9cba89996e8b1cedb512be0
|
https://github.com/achiku/soapc/blob/cfbdfe6e4caffe57a9cba89996e8b1cedb512be0/client.go#L143-L219
|
test
|
go-openapi/loads
|
spec.go
|
JSONDoc
|
func JSONDoc(path string) (json.RawMessage, error) {
data, err := swag.LoadFromFileOrHTTP(path)
if err != nil {
return nil, err
}
return json.RawMessage(data), nil
}
|
go
|
func JSONDoc(path string) (json.RawMessage, error) {
data, err := swag.LoadFromFileOrHTTP(path)
if err != nil {
return nil, err
}
return json.RawMessage(data), nil
}
|
[
"func",
"JSONDoc",
"(",
"path",
"string",
")",
"(",
"json",
".",
"RawMessage",
",",
"error",
")",
"{",
"data",
",",
"err",
":=",
"swag",
".",
"LoadFromFileOrHTTP",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"json",
".",
"RawMessage",
"(",
"data",
")",
",",
"nil",
"\n",
"}"
] |
// JSONDoc loads a json document from either a file or a remote url
|
[
"JSONDoc",
"loads",
"a",
"json",
"document",
"from",
"either",
"a",
"file",
"or",
"a",
"remote",
"url"
] |
74628589c3b94e3526a842d24f46589980f5ab22
|
https://github.com/go-openapi/loads/blob/74628589c3b94e3526a842d24f46589980f5ab22/spec.go#L30-L36
|
test
|
go-openapi/loads
|
spec.go
|
AddLoader
|
func AddLoader(predicate DocMatcher, load DocLoader) {
prev := loaders
loaders = &loader{
Match: predicate,
Fn: load,
Next: prev,
}
spec.PathLoader = loaders.Fn
}
|
go
|
func AddLoader(predicate DocMatcher, load DocLoader) {
prev := loaders
loaders = &loader{
Match: predicate,
Fn: load,
Next: prev,
}
spec.PathLoader = loaders.Fn
}
|
[
"func",
"AddLoader",
"(",
"predicate",
"DocMatcher",
",",
"load",
"DocLoader",
")",
"{",
"prev",
":=",
"loaders",
"\n",
"loaders",
"=",
"&",
"loader",
"{",
"Match",
":",
"predicate",
",",
"Fn",
":",
"load",
",",
"Next",
":",
"prev",
",",
"}",
"\n",
"spec",
".",
"PathLoader",
"=",
"loaders",
".",
"Fn",
"\n",
"}"
] |
// AddLoader for a document
|
[
"AddLoader",
"for",
"a",
"document"
] |
74628589c3b94e3526a842d24f46589980f5ab22
|
https://github.com/go-openapi/loads/blob/74628589c3b94e3526a842d24f46589980f5ab22/spec.go#L61-L69
|
test
|
go-openapi/loads
|
spec.go
|
JSONSpec
|
func JSONSpec(path string) (*Document, error) {
data, err := JSONDoc(path)
if err != nil {
return nil, err
}
// convert to json
return Analyzed(data, "")
}
|
go
|
func JSONSpec(path string) (*Document, error) {
data, err := JSONDoc(path)
if err != nil {
return nil, err
}
// convert to json
return Analyzed(data, "")
}
|
[
"func",
"JSONSpec",
"(",
"path",
"string",
")",
"(",
"*",
"Document",
",",
"error",
")",
"{",
"data",
",",
"err",
":=",
"JSONDoc",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"Analyzed",
"(",
"data",
",",
"\"\"",
")",
"\n",
"}"
] |
// JSONSpec loads a spec from a json document
|
[
"JSONSpec",
"loads",
"a",
"spec",
"from",
"a",
"json",
"document"
] |
74628589c3b94e3526a842d24f46589980f5ab22
|
https://github.com/go-openapi/loads/blob/74628589c3b94e3526a842d24f46589980f5ab22/spec.go#L78-L85
|
test
|
go-openapi/loads
|
spec.go
|
Embedded
|
func Embedded(orig, flat json.RawMessage) (*Document, error) {
var origSpec, flatSpec spec.Swagger
if err := json.Unmarshal(orig, &origSpec); err != nil {
return nil, err
}
if err := json.Unmarshal(flat, &flatSpec); err != nil {
return nil, err
}
return &Document{
raw: orig,
origSpec: &origSpec,
spec: &flatSpec,
}, nil
}
|
go
|
func Embedded(orig, flat json.RawMessage) (*Document, error) {
var origSpec, flatSpec spec.Swagger
if err := json.Unmarshal(orig, &origSpec); err != nil {
return nil, err
}
if err := json.Unmarshal(flat, &flatSpec); err != nil {
return nil, err
}
return &Document{
raw: orig,
origSpec: &origSpec,
spec: &flatSpec,
}, nil
}
|
[
"func",
"Embedded",
"(",
"orig",
",",
"flat",
"json",
".",
"RawMessage",
")",
"(",
"*",
"Document",
",",
"error",
")",
"{",
"var",
"origSpec",
",",
"flatSpec",
"spec",
".",
"Swagger",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"orig",
",",
"&",
"origSpec",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"flat",
",",
"&",
"flatSpec",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"Document",
"{",
"raw",
":",
"orig",
",",
"origSpec",
":",
"&",
"origSpec",
",",
"spec",
":",
"&",
"flatSpec",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// Embedded returns a Document based on embedded specs. No analysis is required
|
[
"Embedded",
"returns",
"a",
"Document",
"based",
"on",
"embedded",
"specs",
".",
"No",
"analysis",
"is",
"required"
] |
74628589c3b94e3526a842d24f46589980f5ab22
|
https://github.com/go-openapi/loads/blob/74628589c3b94e3526a842d24f46589980f5ab22/spec.go#L99-L112
|
test
|
go-openapi/loads
|
spec.go
|
Spec
|
func Spec(path string) (*Document, error) {
specURL, err := url.Parse(path)
if err != nil {
return nil, err
}
var lastErr error
for l := loaders.Next; l != nil; l = l.Next {
if loaders.Match(specURL.Path) {
b, err2 := loaders.Fn(path)
if err2 != nil {
lastErr = err2
continue
}
doc, err3 := Analyzed(b, "")
if err3 != nil {
return nil, err3
}
if doc != nil {
doc.specFilePath = path
}
return doc, nil
}
}
if lastErr != nil {
return nil, lastErr
}
b, err := defaultLoader.Fn(path)
if err != nil {
return nil, err
}
document, err := Analyzed(b, "")
if document != nil {
document.specFilePath = path
}
return document, err
}
|
go
|
func Spec(path string) (*Document, error) {
specURL, err := url.Parse(path)
if err != nil {
return nil, err
}
var lastErr error
for l := loaders.Next; l != nil; l = l.Next {
if loaders.Match(specURL.Path) {
b, err2 := loaders.Fn(path)
if err2 != nil {
lastErr = err2
continue
}
doc, err3 := Analyzed(b, "")
if err3 != nil {
return nil, err3
}
if doc != nil {
doc.specFilePath = path
}
return doc, nil
}
}
if lastErr != nil {
return nil, lastErr
}
b, err := defaultLoader.Fn(path)
if err != nil {
return nil, err
}
document, err := Analyzed(b, "")
if document != nil {
document.specFilePath = path
}
return document, err
}
|
[
"func",
"Spec",
"(",
"path",
"string",
")",
"(",
"*",
"Document",
",",
"error",
")",
"{",
"specURL",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"var",
"lastErr",
"error",
"\n",
"for",
"l",
":=",
"loaders",
".",
"Next",
";",
"l",
"!=",
"nil",
";",
"l",
"=",
"l",
".",
"Next",
"{",
"if",
"loaders",
".",
"Match",
"(",
"specURL",
".",
"Path",
")",
"{",
"b",
",",
"err2",
":=",
"loaders",
".",
"Fn",
"(",
"path",
")",
"\n",
"if",
"err2",
"!=",
"nil",
"{",
"lastErr",
"=",
"err2",
"\n",
"continue",
"\n",
"}",
"\n",
"doc",
",",
"err3",
":=",
"Analyzed",
"(",
"b",
",",
"\"\"",
")",
"\n",
"if",
"err3",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err3",
"\n",
"}",
"\n",
"if",
"doc",
"!=",
"nil",
"{",
"doc",
".",
"specFilePath",
"=",
"path",
"\n",
"}",
"\n",
"return",
"doc",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"lastErr",
"!=",
"nil",
"{",
"return",
"nil",
",",
"lastErr",
"\n",
"}",
"\n",
"b",
",",
"err",
":=",
"defaultLoader",
".",
"Fn",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"document",
",",
"err",
":=",
"Analyzed",
"(",
"b",
",",
"\"\"",
")",
"\n",
"if",
"document",
"!=",
"nil",
"{",
"document",
".",
"specFilePath",
"=",
"path",
"\n",
"}",
"\n",
"return",
"document",
",",
"err",
"\n",
"}"
] |
// Spec loads a new spec document
|
[
"Spec",
"loads",
"a",
"new",
"spec",
"document"
] |
74628589c3b94e3526a842d24f46589980f5ab22
|
https://github.com/go-openapi/loads/blob/74628589c3b94e3526a842d24f46589980f5ab22/spec.go#L115-L152
|
test
|
go-openapi/loads
|
spec.go
|
Analyzed
|
func Analyzed(data json.RawMessage, version string) (*Document, error) {
if version == "" {
version = "2.0"
}
if version != "2.0" {
return nil, fmt.Errorf("spec version %q is not supported", version)
}
raw := data
trimmed := bytes.TrimSpace(data)
if len(trimmed) > 0 {
if trimmed[0] != '{' && trimmed[0] != '[' {
yml, err := swag.BytesToYAMLDoc(trimmed)
if err != nil {
return nil, fmt.Errorf("analyzed: %v", err)
}
d, err := swag.YAMLToJSON(yml)
if err != nil {
return nil, fmt.Errorf("analyzed: %v", err)
}
raw = d
}
}
swspec := new(spec.Swagger)
if err := json.Unmarshal(raw, swspec); err != nil {
return nil, err
}
origsqspec, err := cloneSpec(swspec)
if err != nil {
return nil, err
}
d := &Document{
Analyzer: analysis.New(swspec),
schema: spec.MustLoadSwagger20Schema(),
spec: swspec,
raw: raw,
origSpec: origsqspec,
}
return d, nil
}
|
go
|
func Analyzed(data json.RawMessage, version string) (*Document, error) {
if version == "" {
version = "2.0"
}
if version != "2.0" {
return nil, fmt.Errorf("spec version %q is not supported", version)
}
raw := data
trimmed := bytes.TrimSpace(data)
if len(trimmed) > 0 {
if trimmed[0] != '{' && trimmed[0] != '[' {
yml, err := swag.BytesToYAMLDoc(trimmed)
if err != nil {
return nil, fmt.Errorf("analyzed: %v", err)
}
d, err := swag.YAMLToJSON(yml)
if err != nil {
return nil, fmt.Errorf("analyzed: %v", err)
}
raw = d
}
}
swspec := new(spec.Swagger)
if err := json.Unmarshal(raw, swspec); err != nil {
return nil, err
}
origsqspec, err := cloneSpec(swspec)
if err != nil {
return nil, err
}
d := &Document{
Analyzer: analysis.New(swspec),
schema: spec.MustLoadSwagger20Schema(),
spec: swspec,
raw: raw,
origSpec: origsqspec,
}
return d, nil
}
|
[
"func",
"Analyzed",
"(",
"data",
"json",
".",
"RawMessage",
",",
"version",
"string",
")",
"(",
"*",
"Document",
",",
"error",
")",
"{",
"if",
"version",
"==",
"\"\"",
"{",
"version",
"=",
"\"2.0\"",
"\n",
"}",
"\n",
"if",
"version",
"!=",
"\"2.0\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"spec version %q is not supported\"",
",",
"version",
")",
"\n",
"}",
"\n",
"raw",
":=",
"data",
"\n",
"trimmed",
":=",
"bytes",
".",
"TrimSpace",
"(",
"data",
")",
"\n",
"if",
"len",
"(",
"trimmed",
")",
">",
"0",
"{",
"if",
"trimmed",
"[",
"0",
"]",
"!=",
"'{'",
"&&",
"trimmed",
"[",
"0",
"]",
"!=",
"'['",
"{",
"yml",
",",
"err",
":=",
"swag",
".",
"BytesToYAMLDoc",
"(",
"trimmed",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"analyzed: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"d",
",",
"err",
":=",
"swag",
".",
"YAMLToJSON",
"(",
"yml",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"analyzed: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"raw",
"=",
"d",
"\n",
"}",
"\n",
"}",
"\n",
"swspec",
":=",
"new",
"(",
"spec",
".",
"Swagger",
")",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"raw",
",",
"swspec",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"origsqspec",
",",
"err",
":=",
"cloneSpec",
"(",
"swspec",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"d",
":=",
"&",
"Document",
"{",
"Analyzer",
":",
"analysis",
".",
"New",
"(",
"swspec",
")",
",",
"schema",
":",
"spec",
".",
"MustLoadSwagger20Schema",
"(",
")",
",",
"spec",
":",
"swspec",
",",
"raw",
":",
"raw",
",",
"origSpec",
":",
"origsqspec",
",",
"}",
"\n",
"return",
"d",
",",
"nil",
"\n",
"}"
] |
// Analyzed creates a new analyzed spec document
|
[
"Analyzed",
"creates",
"a",
"new",
"analyzed",
"spec",
"document"
] |
74628589c3b94e3526a842d24f46589980f5ab22
|
https://github.com/go-openapi/loads/blob/74628589c3b94e3526a842d24f46589980f5ab22/spec.go#L155-L197
|
test
|
go-openapi/loads
|
spec.go
|
Expanded
|
func (d *Document) Expanded(options ...*spec.ExpandOptions) (*Document, error) {
swspec := new(spec.Swagger)
if err := json.Unmarshal(d.raw, swspec); err != nil {
return nil, err
}
var expandOptions *spec.ExpandOptions
if len(options) > 0 {
expandOptions = options[0]
} else {
expandOptions = &spec.ExpandOptions{
RelativeBase: d.specFilePath,
}
}
if err := spec.ExpandSpec(swspec, expandOptions); err != nil {
return nil, err
}
dd := &Document{
Analyzer: analysis.New(swspec),
spec: swspec,
specFilePath: d.specFilePath,
schema: spec.MustLoadSwagger20Schema(),
raw: d.raw,
origSpec: d.origSpec,
}
return dd, nil
}
|
go
|
func (d *Document) Expanded(options ...*spec.ExpandOptions) (*Document, error) {
swspec := new(spec.Swagger)
if err := json.Unmarshal(d.raw, swspec); err != nil {
return nil, err
}
var expandOptions *spec.ExpandOptions
if len(options) > 0 {
expandOptions = options[0]
} else {
expandOptions = &spec.ExpandOptions{
RelativeBase: d.specFilePath,
}
}
if err := spec.ExpandSpec(swspec, expandOptions); err != nil {
return nil, err
}
dd := &Document{
Analyzer: analysis.New(swspec),
spec: swspec,
specFilePath: d.specFilePath,
schema: spec.MustLoadSwagger20Schema(),
raw: d.raw,
origSpec: d.origSpec,
}
return dd, nil
}
|
[
"func",
"(",
"d",
"*",
"Document",
")",
"Expanded",
"(",
"options",
"...",
"*",
"spec",
".",
"ExpandOptions",
")",
"(",
"*",
"Document",
",",
"error",
")",
"{",
"swspec",
":=",
"new",
"(",
"spec",
".",
"Swagger",
")",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"d",
".",
"raw",
",",
"swspec",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"var",
"expandOptions",
"*",
"spec",
".",
"ExpandOptions",
"\n",
"if",
"len",
"(",
"options",
")",
">",
"0",
"{",
"expandOptions",
"=",
"options",
"[",
"0",
"]",
"\n",
"}",
"else",
"{",
"expandOptions",
"=",
"&",
"spec",
".",
"ExpandOptions",
"{",
"RelativeBase",
":",
"d",
".",
"specFilePath",
",",
"}",
"\n",
"}",
"\n",
"if",
"err",
":=",
"spec",
".",
"ExpandSpec",
"(",
"swspec",
",",
"expandOptions",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"dd",
":=",
"&",
"Document",
"{",
"Analyzer",
":",
"analysis",
".",
"New",
"(",
"swspec",
")",
",",
"spec",
":",
"swspec",
",",
"specFilePath",
":",
"d",
".",
"specFilePath",
",",
"schema",
":",
"spec",
".",
"MustLoadSwagger20Schema",
"(",
")",
",",
"raw",
":",
"d",
".",
"raw",
",",
"origSpec",
":",
"d",
".",
"origSpec",
",",
"}",
"\n",
"return",
"dd",
",",
"nil",
"\n",
"}"
] |
// Expanded expands the ref fields in the spec document and returns a new spec document
|
[
"Expanded",
"expands",
"the",
"ref",
"fields",
"in",
"the",
"spec",
"document",
"and",
"returns",
"a",
"new",
"spec",
"document"
] |
74628589c3b94e3526a842d24f46589980f5ab22
|
https://github.com/go-openapi/loads/blob/74628589c3b94e3526a842d24f46589980f5ab22/spec.go#L200-L228
|
test
|
go-openapi/loads
|
spec.go
|
ResetDefinitions
|
func (d *Document) ResetDefinitions() *Document {
defs := make(map[string]spec.Schema, len(d.origSpec.Definitions))
for k, v := range d.origSpec.Definitions {
defs[k] = v
}
d.spec.Definitions = defs
return d
}
|
go
|
func (d *Document) ResetDefinitions() *Document {
defs := make(map[string]spec.Schema, len(d.origSpec.Definitions))
for k, v := range d.origSpec.Definitions {
defs[k] = v
}
d.spec.Definitions = defs
return d
}
|
[
"func",
"(",
"d",
"*",
"Document",
")",
"ResetDefinitions",
"(",
")",
"*",
"Document",
"{",
"defs",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"spec",
".",
"Schema",
",",
"len",
"(",
"d",
".",
"origSpec",
".",
"Definitions",
")",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"d",
".",
"origSpec",
".",
"Definitions",
"{",
"defs",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"d",
".",
"spec",
".",
"Definitions",
"=",
"defs",
"\n",
"return",
"d",
"\n",
"}"
] |
// ResetDefinitions gives a shallow copy with the models reset
|
[
"ResetDefinitions",
"gives",
"a",
"shallow",
"copy",
"with",
"the",
"models",
"reset"
] |
74628589c3b94e3526a842d24f46589980f5ab22
|
https://github.com/go-openapi/loads/blob/74628589c3b94e3526a842d24f46589980f5ab22/spec.go#L266-L274
|
test
|
go-openapi/loads
|
spec.go
|
Pristine
|
func (d *Document) Pristine() *Document {
dd, _ := Analyzed(d.Raw(), d.Version())
return dd
}
|
go
|
func (d *Document) Pristine() *Document {
dd, _ := Analyzed(d.Raw(), d.Version())
return dd
}
|
[
"func",
"(",
"d",
"*",
"Document",
")",
"Pristine",
"(",
")",
"*",
"Document",
"{",
"dd",
",",
"_",
":=",
"Analyzed",
"(",
"d",
".",
"Raw",
"(",
")",
",",
"d",
".",
"Version",
"(",
")",
")",
"\n",
"return",
"dd",
"\n",
"}"
] |
// Pristine creates a new pristine document instance based on the input data
|
[
"Pristine",
"creates",
"a",
"new",
"pristine",
"document",
"instance",
"based",
"on",
"the",
"input",
"data"
] |
74628589c3b94e3526a842d24f46589980f5ab22
|
https://github.com/go-openapi/loads/blob/74628589c3b94e3526a842d24f46589980f5ab22/spec.go#L277-L280
|
test
|
abh/geoip
|
geoip.go
|
OpenDb
|
func OpenDb(files []string, flag int) (*GeoIP, error) {
if len(files) == 0 {
files = []string{
"/usr/share/GeoIP/GeoIP.dat", // Linux default
"/usr/share/local/GeoIP/GeoIP.dat", // source install?
"/usr/local/share/GeoIP/GeoIP.dat", // FreeBSD
"/opt/local/share/GeoIP/GeoIP.dat", // MacPorts
"/usr/share/GeoIP/GeoIP.dat", // ArchLinux
}
}
g := &GeoIP{}
runtime.SetFinalizer(g, (*GeoIP).free)
var err error
for _, file := range files {
// libgeoip prints errors if it can't open the file, so check first
if _, err := os.Stat(file); err != nil {
if os.IsExist(err) {
log.Println(err)
}
continue
}
cbase := C.CString(file)
defer C.free(unsafe.Pointer(cbase))
g.db, err = C.GeoIP_open(cbase, C.int(flag))
if g.db != nil && err != nil {
break
}
}
if err != nil {
return nil, fmt.Errorf("Error opening GeoIP database (%s): %s", files, err)
}
if g.db == nil {
return nil, fmt.Errorf("Didn't open GeoIP database (%s)", files)
}
C.GeoIP_set_charset(g.db, C.GEOIP_CHARSET_UTF8)
return g, nil
}
|
go
|
func OpenDb(files []string, flag int) (*GeoIP, error) {
if len(files) == 0 {
files = []string{
"/usr/share/GeoIP/GeoIP.dat", // Linux default
"/usr/share/local/GeoIP/GeoIP.dat", // source install?
"/usr/local/share/GeoIP/GeoIP.dat", // FreeBSD
"/opt/local/share/GeoIP/GeoIP.dat", // MacPorts
"/usr/share/GeoIP/GeoIP.dat", // ArchLinux
}
}
g := &GeoIP{}
runtime.SetFinalizer(g, (*GeoIP).free)
var err error
for _, file := range files {
// libgeoip prints errors if it can't open the file, so check first
if _, err := os.Stat(file); err != nil {
if os.IsExist(err) {
log.Println(err)
}
continue
}
cbase := C.CString(file)
defer C.free(unsafe.Pointer(cbase))
g.db, err = C.GeoIP_open(cbase, C.int(flag))
if g.db != nil && err != nil {
break
}
}
if err != nil {
return nil, fmt.Errorf("Error opening GeoIP database (%s): %s", files, err)
}
if g.db == nil {
return nil, fmt.Errorf("Didn't open GeoIP database (%s)", files)
}
C.GeoIP_set_charset(g.db, C.GEOIP_CHARSET_UTF8)
return g, nil
}
|
[
"func",
"OpenDb",
"(",
"files",
"[",
"]",
"string",
",",
"flag",
"int",
")",
"(",
"*",
"GeoIP",
",",
"error",
")",
"{",
"if",
"len",
"(",
"files",
")",
"==",
"0",
"{",
"files",
"=",
"[",
"]",
"string",
"{",
"\"/usr/share/GeoIP/GeoIP.dat\"",
",",
"\"/usr/share/local/GeoIP/GeoIP.dat\"",
",",
"\"/usr/local/share/GeoIP/GeoIP.dat\"",
",",
"\"/opt/local/share/GeoIP/GeoIP.dat\"",
",",
"\"/usr/share/GeoIP/GeoIP.dat\"",
",",
"}",
"\n",
"}",
"\n",
"g",
":=",
"&",
"GeoIP",
"{",
"}",
"\n",
"runtime",
".",
"SetFinalizer",
"(",
"g",
",",
"(",
"*",
"GeoIP",
")",
".",
"free",
")",
"\n",
"var",
"err",
"error",
"\n",
"for",
"_",
",",
"file",
":=",
"range",
"files",
"{",
"if",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"file",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"os",
".",
"IsExist",
"(",
"err",
")",
"{",
"log",
".",
"Println",
"(",
"err",
")",
"\n",
"}",
"\n",
"continue",
"\n",
"}",
"\n",
"cbase",
":=",
"C",
".",
"CString",
"(",
"file",
")",
"\n",
"defer",
"C",
".",
"free",
"(",
"unsafe",
".",
"Pointer",
"(",
"cbase",
")",
")",
"\n",
"g",
".",
"db",
",",
"err",
"=",
"C",
".",
"GeoIP_open",
"(",
"cbase",
",",
"C",
".",
"int",
"(",
"flag",
")",
")",
"\n",
"if",
"g",
".",
"db",
"!=",
"nil",
"&&",
"err",
"!=",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Error opening GeoIP database (%s): %s\"",
",",
"files",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"g",
".",
"db",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Didn't open GeoIP database (%s)\"",
",",
"files",
")",
"\n",
"}",
"\n",
"C",
".",
"GeoIP_set_charset",
"(",
"g",
".",
"db",
",",
"C",
".",
"GEOIP_CHARSET_UTF8",
")",
"\n",
"return",
"g",
",",
"nil",
"\n",
"}"
] |
// Opens a GeoIP database by filename with specified GeoIPOptions flag.
// All formats supported by libgeoip are supported though there are only
// functions to access some of the databases in this API.
// If you don't pass a filename, it will try opening the database from
// a list of common paths.
|
[
"Opens",
"a",
"GeoIP",
"database",
"by",
"filename",
"with",
"specified",
"GeoIPOptions",
"flag",
".",
"All",
"formats",
"supported",
"by",
"libgeoip",
"are",
"supported",
"though",
"there",
"are",
"only",
"functions",
"to",
"access",
"some",
"of",
"the",
"databases",
"in",
"this",
"API",
".",
"If",
"you",
"don",
"t",
"pass",
"a",
"filename",
"it",
"will",
"try",
"opening",
"the",
"database",
"from",
"a",
"list",
"of",
"common",
"paths",
"."
] |
07cea4480daa3f28edd2856f2a0490fbe83842eb
|
https://github.com/abh/geoip/blob/07cea4480daa3f28edd2856f2a0490fbe83842eb/geoip.go#L58-L102
|
test
|
abh/geoip
|
geoip.go
|
GetOrg
|
func (gi *GeoIP) GetOrg(ip string) string {
name, _ := gi.GetName(ip)
return name
}
|
go
|
func (gi *GeoIP) GetOrg(ip string) string {
name, _ := gi.GetName(ip)
return name
}
|
[
"func",
"(",
"gi",
"*",
"GeoIP",
")",
"GetOrg",
"(",
"ip",
"string",
")",
"string",
"{",
"name",
",",
"_",
":=",
"gi",
".",
"GetName",
"(",
"ip",
")",
"\n",
"return",
"name",
"\n",
"}"
] |
// Takes an IPv4 address string and returns the organization name for that IP.
// Requires the GeoIP organization database.
|
[
"Takes",
"an",
"IPv4",
"address",
"string",
"and",
"returns",
"the",
"organization",
"name",
"for",
"that",
"IP",
".",
"Requires",
"the",
"GeoIP",
"organization",
"database",
"."
] |
07cea4480daa3f28edd2856f2a0490fbe83842eb
|
https://github.com/abh/geoip/blob/07cea4480daa3f28edd2856f2a0490fbe83842eb/geoip.go#L144-L147
|
test
|
abh/geoip
|
geoip.go
|
GetRegion
|
func (gi *GeoIP) GetRegion(ip string) (string, string) {
if gi.db == nil {
return "", ""
}
cip := C.CString(ip)
defer C.free(unsafe.Pointer(cip))
gi.mu.Lock()
region := C.GeoIP_region_by_addr(gi.db, cip)
gi.mu.Unlock()
if region == nil {
return "", ""
}
countryCode := C.GoString(®ion.country_code[0])
regionCode := C.GoString(®ion.region[0])
defer C.free(unsafe.Pointer(region))
return countryCode, regionCode
}
|
go
|
func (gi *GeoIP) GetRegion(ip string) (string, string) {
if gi.db == nil {
return "", ""
}
cip := C.CString(ip)
defer C.free(unsafe.Pointer(cip))
gi.mu.Lock()
region := C.GeoIP_region_by_addr(gi.db, cip)
gi.mu.Unlock()
if region == nil {
return "", ""
}
countryCode := C.GoString(®ion.country_code[0])
regionCode := C.GoString(®ion.region[0])
defer C.free(unsafe.Pointer(region))
return countryCode, regionCode
}
|
[
"func",
"(",
"gi",
"*",
"GeoIP",
")",
"GetRegion",
"(",
"ip",
"string",
")",
"(",
"string",
",",
"string",
")",
"{",
"if",
"gi",
".",
"db",
"==",
"nil",
"{",
"return",
"\"\"",
",",
"\"\"",
"\n",
"}",
"\n",
"cip",
":=",
"C",
".",
"CString",
"(",
"ip",
")",
"\n",
"defer",
"C",
".",
"free",
"(",
"unsafe",
".",
"Pointer",
"(",
"cip",
")",
")",
"\n",
"gi",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"region",
":=",
"C",
".",
"GeoIP_region_by_addr",
"(",
"gi",
".",
"db",
",",
"cip",
")",
"\n",
"gi",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"region",
"==",
"nil",
"{",
"return",
"\"\"",
",",
"\"\"",
"\n",
"}",
"\n",
"countryCode",
":=",
"C",
".",
"GoString",
"(",
"&",
"region",
".",
"country_code",
"[",
"0",
"]",
")",
"\n",
"regionCode",
":=",
"C",
".",
"GoString",
"(",
"&",
"region",
".",
"region",
"[",
"0",
"]",
")",
"\n",
"defer",
"C",
".",
"free",
"(",
"unsafe",
".",
"Pointer",
"(",
"region",
")",
")",
"\n",
"return",
"countryCode",
",",
"regionCode",
"\n",
"}"
] |
// Returns the country code and region code for an IP address. Requires
// the GeoIP Region database.
|
[
"Returns",
"the",
"country",
"code",
"and",
"region",
"code",
"for",
"an",
"IP",
"address",
".",
"Requires",
"the",
"GeoIP",
"Region",
"database",
"."
] |
07cea4480daa3f28edd2856f2a0490fbe83842eb
|
https://github.com/abh/geoip/blob/07cea4480daa3f28edd2856f2a0490fbe83842eb/geoip.go#L234-L255
|
test
|
abh/geoip
|
geoip.go
|
GetRegionName
|
func GetRegionName(countryCode, regionCode string) string {
cc := C.CString(countryCode)
defer C.free(unsafe.Pointer(cc))
rc := C.CString(regionCode)
defer C.free(unsafe.Pointer(rc))
region := C.GeoIP_region_name_by_code(cc, rc)
if region == nil {
return ""
}
// it's a static string constant, don't free this
regionName := C.GoString(region)
return regionName
}
|
go
|
func GetRegionName(countryCode, regionCode string) string {
cc := C.CString(countryCode)
defer C.free(unsafe.Pointer(cc))
rc := C.CString(regionCode)
defer C.free(unsafe.Pointer(rc))
region := C.GeoIP_region_name_by_code(cc, rc)
if region == nil {
return ""
}
// it's a static string constant, don't free this
regionName := C.GoString(region)
return regionName
}
|
[
"func",
"GetRegionName",
"(",
"countryCode",
",",
"regionCode",
"string",
")",
"string",
"{",
"cc",
":=",
"C",
".",
"CString",
"(",
"countryCode",
")",
"\n",
"defer",
"C",
".",
"free",
"(",
"unsafe",
".",
"Pointer",
"(",
"cc",
")",
")",
"\n",
"rc",
":=",
"C",
".",
"CString",
"(",
"regionCode",
")",
"\n",
"defer",
"C",
".",
"free",
"(",
"unsafe",
".",
"Pointer",
"(",
"rc",
")",
")",
"\n",
"region",
":=",
"C",
".",
"GeoIP_region_name_by_code",
"(",
"cc",
",",
"rc",
")",
"\n",
"if",
"region",
"==",
"nil",
"{",
"return",
"\"\"",
"\n",
"}",
"\n",
"regionName",
":=",
"C",
".",
"GoString",
"(",
"region",
")",
"\n",
"return",
"regionName",
"\n",
"}"
] |
// Returns the region name given a country code and region code
|
[
"Returns",
"the",
"region",
"name",
"given",
"a",
"country",
"code",
"and",
"region",
"code"
] |
07cea4480daa3f28edd2856f2a0490fbe83842eb
|
https://github.com/abh/geoip/blob/07cea4480daa3f28edd2856f2a0490fbe83842eb/geoip.go#L258-L275
|
test
|
abh/geoip
|
geoip.go
|
GetCountry
|
func (gi *GeoIP) GetCountry(ip string) (cc string, netmask int) {
if gi.db == nil {
return
}
gi.mu.Lock()
defer gi.mu.Unlock()
cip := C.CString(ip)
defer C.free(unsafe.Pointer(cip))
ccountry := C.GeoIP_country_code_by_addr(gi.db, cip)
if ccountry != nil {
cc = C.GoString(ccountry)
netmask = int(C.GeoIP_last_netmask(gi.db))
return
}
return
}
|
go
|
func (gi *GeoIP) GetCountry(ip string) (cc string, netmask int) {
if gi.db == nil {
return
}
gi.mu.Lock()
defer gi.mu.Unlock()
cip := C.CString(ip)
defer C.free(unsafe.Pointer(cip))
ccountry := C.GeoIP_country_code_by_addr(gi.db, cip)
if ccountry != nil {
cc = C.GoString(ccountry)
netmask = int(C.GeoIP_last_netmask(gi.db))
return
}
return
}
|
[
"func",
"(",
"gi",
"*",
"GeoIP",
")",
"GetCountry",
"(",
"ip",
"string",
")",
"(",
"cc",
"string",
",",
"netmask",
"int",
")",
"{",
"if",
"gi",
".",
"db",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"gi",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"gi",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"cip",
":=",
"C",
".",
"CString",
"(",
"ip",
")",
"\n",
"defer",
"C",
".",
"free",
"(",
"unsafe",
".",
"Pointer",
"(",
"cip",
")",
")",
"\n",
"ccountry",
":=",
"C",
".",
"GeoIP_country_code_by_addr",
"(",
"gi",
".",
"db",
",",
"cip",
")",
"\n",
"if",
"ccountry",
"!=",
"nil",
"{",
"cc",
"=",
"C",
".",
"GoString",
"(",
"ccountry",
")",
"\n",
"netmask",
"=",
"int",
"(",
"C",
".",
"GeoIP_last_netmask",
"(",
"gi",
".",
"db",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Takes an IPv4 address string and returns the country code for that IP
// and the netmask for that IP range.
|
[
"Takes",
"an",
"IPv4",
"address",
"string",
"and",
"returns",
"the",
"country",
"code",
"for",
"that",
"IP",
"and",
"the",
"netmask",
"for",
"that",
"IP",
"range",
"."
] |
07cea4480daa3f28edd2856f2a0490fbe83842eb
|
https://github.com/abh/geoip/blob/07cea4480daa3f28edd2856f2a0490fbe83842eb/geoip.go#L301-L319
|
test
|
siddontang/go-log
|
log/filehandler.go
|
NewRotatingFileHandler
|
func NewRotatingFileHandler(fileName string, maxBytes int, backupCount int) (*RotatingFileHandler, error) {
dir := path.Dir(fileName)
os.MkdirAll(dir, 0777)
h := new(RotatingFileHandler)
if maxBytes <= 0 {
return nil, fmt.Errorf("invalid max bytes")
}
h.fileName = fileName
h.maxBytes = maxBytes
h.backupCount = backupCount
var err error
h.fd, err = os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
return nil, err
}
f, err := h.fd.Stat()
if err != nil {
return nil, err
}
h.curBytes = int(f.Size())
return h, nil
}
|
go
|
func NewRotatingFileHandler(fileName string, maxBytes int, backupCount int) (*RotatingFileHandler, error) {
dir := path.Dir(fileName)
os.MkdirAll(dir, 0777)
h := new(RotatingFileHandler)
if maxBytes <= 0 {
return nil, fmt.Errorf("invalid max bytes")
}
h.fileName = fileName
h.maxBytes = maxBytes
h.backupCount = backupCount
var err error
h.fd, err = os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
return nil, err
}
f, err := h.fd.Stat()
if err != nil {
return nil, err
}
h.curBytes = int(f.Size())
return h, nil
}
|
[
"func",
"NewRotatingFileHandler",
"(",
"fileName",
"string",
",",
"maxBytes",
"int",
",",
"backupCount",
"int",
")",
"(",
"*",
"RotatingFileHandler",
",",
"error",
")",
"{",
"dir",
":=",
"path",
".",
"Dir",
"(",
"fileName",
")",
"\n",
"os",
".",
"MkdirAll",
"(",
"dir",
",",
"0777",
")",
"\n",
"h",
":=",
"new",
"(",
"RotatingFileHandler",
")",
"\n",
"if",
"maxBytes",
"<=",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"invalid max bytes\"",
")",
"\n",
"}",
"\n",
"h",
".",
"fileName",
"=",
"fileName",
"\n",
"h",
".",
"maxBytes",
"=",
"maxBytes",
"\n",
"h",
".",
"backupCount",
"=",
"backupCount",
"\n",
"var",
"err",
"error",
"\n",
"h",
".",
"fd",
",",
"err",
"=",
"os",
".",
"OpenFile",
"(",
"fileName",
",",
"os",
".",
"O_CREATE",
"|",
"os",
".",
"O_WRONLY",
"|",
"os",
".",
"O_APPEND",
",",
"0666",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"f",
",",
"err",
":=",
"h",
".",
"fd",
".",
"Stat",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"h",
".",
"curBytes",
"=",
"int",
"(",
"f",
".",
"Size",
"(",
")",
")",
"\n",
"return",
"h",
",",
"nil",
"\n",
"}"
] |
// NewRotatingFileHandler creates a RotatingFileHandler
|
[
"NewRotatingFileHandler",
"creates",
"a",
"RotatingFileHandler"
] |
1e957dd83bed18c84716181da7b80d4af48eaefe
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/filehandler.go#L56-L83
|
test
|
siddontang/go-log
|
log/filehandler.go
|
Close
|
func (h *RotatingFileHandler) Close() error {
if h.fd != nil {
return h.fd.Close()
}
return nil
}
|
go
|
func (h *RotatingFileHandler) Close() error {
if h.fd != nil {
return h.fd.Close()
}
return nil
}
|
[
"func",
"(",
"h",
"*",
"RotatingFileHandler",
")",
"Close",
"(",
")",
"error",
"{",
"if",
"h",
".",
"fd",
"!=",
"nil",
"{",
"return",
"h",
".",
"fd",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Close implements Handler interface
|
[
"Close",
"implements",
"Handler",
"interface"
] |
1e957dd83bed18c84716181da7b80d4af48eaefe
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/filehandler.go#L94-L99
|
test
|
siddontang/go-log
|
log/logger.go
|
String
|
func (l Level) String() string {
switch l {
case LevelTrace:
return "trace"
case LevelDebug:
return "debug"
case LevelInfo:
return "info"
case LevelWarn:
return "warn"
case LevelError:
return "error"
case LevelFatal:
return "fatal"
}
// return default info
return "info"
}
|
go
|
func (l Level) String() string {
switch l {
case LevelTrace:
return "trace"
case LevelDebug:
return "debug"
case LevelInfo:
return "info"
case LevelWarn:
return "warn"
case LevelError:
return "error"
case LevelFatal:
return "fatal"
}
// return default info
return "info"
}
|
[
"func",
"(",
"l",
"Level",
")",
"String",
"(",
")",
"string",
"{",
"switch",
"l",
"{",
"case",
"LevelTrace",
":",
"return",
"\"trace\"",
"\n",
"case",
"LevelDebug",
":",
"return",
"\"debug\"",
"\n",
"case",
"LevelInfo",
":",
"return",
"\"info\"",
"\n",
"case",
"LevelWarn",
":",
"return",
"\"warn\"",
"\n",
"case",
"LevelError",
":",
"return",
"\"error\"",
"\n",
"case",
"LevelFatal",
":",
"return",
"\"fatal\"",
"\n",
"}",
"\n",
"return",
"\"info\"",
"\n",
"}"
] |
// String returns level String
|
[
"String",
"returns",
"level",
"String"
] |
1e957dd83bed18c84716181da7b80d4af48eaefe
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L42-L59
|
test
|
siddontang/go-log
|
log/logger.go
|
New
|
func New(handler Handler, flag int) *Logger {
var l = new(Logger)
l.level = LevelInfo
l.handler = handler
l.flag = flag
l.bufs = sync.Pool{
New: func() interface{} {
return make([]byte, 0, 1024)
},
}
return l
}
|
go
|
func New(handler Handler, flag int) *Logger {
var l = new(Logger)
l.level = LevelInfo
l.handler = handler
l.flag = flag
l.bufs = sync.Pool{
New: func() interface{} {
return make([]byte, 0, 1024)
},
}
return l
}
|
[
"func",
"New",
"(",
"handler",
"Handler",
",",
"flag",
"int",
")",
"*",
"Logger",
"{",
"var",
"l",
"=",
"new",
"(",
"Logger",
")",
"\n",
"l",
".",
"level",
"=",
"LevelInfo",
"\n",
"l",
".",
"handler",
"=",
"handler",
"\n",
"l",
".",
"flag",
"=",
"flag",
"\n",
"l",
".",
"bufs",
"=",
"sync",
".",
"Pool",
"{",
"New",
":",
"func",
"(",
")",
"interface",
"{",
"}",
"{",
"return",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"1024",
")",
"\n",
"}",
",",
"}",
"\n",
"return",
"l",
"\n",
"}"
] |
// New creates a logger with specified handler and flag
|
[
"New",
"creates",
"a",
"logger",
"with",
"specified",
"handler",
"and",
"flag"
] |
1e957dd83bed18c84716181da7b80d4af48eaefe
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L76-L91
|
test
|
siddontang/go-log
|
log/logger.go
|
Close
|
func (l *Logger) Close() {
l.hLock.Lock()
defer l.hLock.Unlock()
l.handler.Close()
}
|
go
|
func (l *Logger) Close() {
l.hLock.Lock()
defer l.hLock.Unlock()
l.handler.Close()
}
|
[
"func",
"(",
"l",
"*",
"Logger",
")",
"Close",
"(",
")",
"{",
"l",
".",
"hLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"l",
".",
"hLock",
".",
"Unlock",
"(",
")",
"\n",
"l",
".",
"handler",
".",
"Close",
"(",
")",
"\n",
"}"
] |
// Close closes the logger
|
[
"Close",
"closes",
"the",
"logger"
] |
1e957dd83bed18c84716181da7b80d4af48eaefe
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L104-L108
|
test
|
siddontang/go-log
|
log/logger.go
|
SetLevelByName
|
func (l *Logger) SetLevelByName(name string) {
level := LevelInfo
switch strings.ToLower(name) {
case "trace":
level = LevelTrace
case "debug":
level = LevelDebug
case "warn", "warning":
level = LevelWarn
case "error":
level = LevelError
case "fatal":
level = LevelFatal
default:
level = LevelInfo
}
l.SetLevel(level)
}
|
go
|
func (l *Logger) SetLevelByName(name string) {
level := LevelInfo
switch strings.ToLower(name) {
case "trace":
level = LevelTrace
case "debug":
level = LevelDebug
case "warn", "warning":
level = LevelWarn
case "error":
level = LevelError
case "fatal":
level = LevelFatal
default:
level = LevelInfo
}
l.SetLevel(level)
}
|
[
"func",
"(",
"l",
"*",
"Logger",
")",
"SetLevelByName",
"(",
"name",
"string",
")",
"{",
"level",
":=",
"LevelInfo",
"\n",
"switch",
"strings",
".",
"ToLower",
"(",
"name",
")",
"{",
"case",
"\"trace\"",
":",
"level",
"=",
"LevelTrace",
"\n",
"case",
"\"debug\"",
":",
"level",
"=",
"LevelDebug",
"\n",
"case",
"\"warn\"",
",",
"\"warning\"",
":",
"level",
"=",
"LevelWarn",
"\n",
"case",
"\"error\"",
":",
"level",
"=",
"LevelError",
"\n",
"case",
"\"fatal\"",
":",
"level",
"=",
"LevelFatal",
"\n",
"default",
":",
"level",
"=",
"LevelInfo",
"\n",
"}",
"\n",
"l",
".",
"SetLevel",
"(",
"level",
")",
"\n",
"}"
] |
// SetLevelByName sets log level by name
|
[
"SetLevelByName",
"sets",
"log",
"level",
"by",
"name"
] |
1e957dd83bed18c84716181da7b80d4af48eaefe
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L116-L134
|
test
|
siddontang/go-log
|
log/logger.go
|
Output
|
func (l *Logger) Output(callDepth int, level Level, msg string) {
if l.level > level {
return
}
buf := l.bufs.Get().([]byte)
buf = buf[0:0]
defer l.bufs.Put(buf)
if l.flag&Ltime > 0 {
now := time.Now().Format(timeFormat)
buf = append(buf, '[')
buf = append(buf, now...)
buf = append(buf, "] "...)
}
if l.flag&Llevel > 0 {
buf = append(buf, '[')
buf = append(buf, level.String()...)
buf = append(buf, "] "...)
}
if l.flag&Lfile > 0 {
_, file, line, ok := runtime.Caller(callDepth)
if !ok {
file = "???"
line = 0
} else {
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
file = file[i+1:]
break
}
}
}
buf = append(buf, file...)
buf = append(buf, ':')
buf = strconv.AppendInt(buf, int64(line), 10)
buf = append(buf, ' ')
}
buf = append(buf, msg...)
if len(msg) == 0 || msg[len(msg)-1] != '\n' {
buf = append(buf, '\n')
}
l.hLock.Lock()
l.handler.Write(buf)
l.hLock.Unlock()
}
|
go
|
func (l *Logger) Output(callDepth int, level Level, msg string) {
if l.level > level {
return
}
buf := l.bufs.Get().([]byte)
buf = buf[0:0]
defer l.bufs.Put(buf)
if l.flag&Ltime > 0 {
now := time.Now().Format(timeFormat)
buf = append(buf, '[')
buf = append(buf, now...)
buf = append(buf, "] "...)
}
if l.flag&Llevel > 0 {
buf = append(buf, '[')
buf = append(buf, level.String()...)
buf = append(buf, "] "...)
}
if l.flag&Lfile > 0 {
_, file, line, ok := runtime.Caller(callDepth)
if !ok {
file = "???"
line = 0
} else {
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
file = file[i+1:]
break
}
}
}
buf = append(buf, file...)
buf = append(buf, ':')
buf = strconv.AppendInt(buf, int64(line), 10)
buf = append(buf, ' ')
}
buf = append(buf, msg...)
if len(msg) == 0 || msg[len(msg)-1] != '\n' {
buf = append(buf, '\n')
}
l.hLock.Lock()
l.handler.Write(buf)
l.hLock.Unlock()
}
|
[
"func",
"(",
"l",
"*",
"Logger",
")",
"Output",
"(",
"callDepth",
"int",
",",
"level",
"Level",
",",
"msg",
"string",
")",
"{",
"if",
"l",
".",
"level",
">",
"level",
"{",
"return",
"\n",
"}",
"\n",
"buf",
":=",
"l",
".",
"bufs",
".",
"Get",
"(",
")",
".",
"(",
"[",
"]",
"byte",
")",
"\n",
"buf",
"=",
"buf",
"[",
"0",
":",
"0",
"]",
"\n",
"defer",
"l",
".",
"bufs",
".",
"Put",
"(",
"buf",
")",
"\n",
"if",
"l",
".",
"flag",
"&",
"Ltime",
">",
"0",
"{",
"now",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Format",
"(",
"timeFormat",
")",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"'['",
")",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"now",
"...",
")",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"\"] \"",
"...",
")",
"\n",
"}",
"\n",
"if",
"l",
".",
"flag",
"&",
"Llevel",
">",
"0",
"{",
"buf",
"=",
"append",
"(",
"buf",
",",
"'['",
")",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"level",
".",
"String",
"(",
")",
"...",
")",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"\"] \"",
"...",
")",
"\n",
"}",
"\n",
"if",
"l",
".",
"flag",
"&",
"Lfile",
">",
"0",
"{",
"_",
",",
"file",
",",
"line",
",",
"ok",
":=",
"runtime",
".",
"Caller",
"(",
"callDepth",
")",
"\n",
"if",
"!",
"ok",
"{",
"file",
"=",
"\"???\"",
"\n",
"line",
"=",
"0",
"\n",
"}",
"else",
"{",
"for",
"i",
":=",
"len",
"(",
"file",
")",
"-",
"1",
";",
"i",
">",
"0",
";",
"i",
"--",
"{",
"if",
"file",
"[",
"i",
"]",
"==",
"'/'",
"{",
"file",
"=",
"file",
"[",
"i",
"+",
"1",
":",
"]",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"file",
"...",
")",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"':'",
")",
"\n",
"buf",
"=",
"strconv",
".",
"AppendInt",
"(",
"buf",
",",
"int64",
"(",
"line",
")",
",",
"10",
")",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"' '",
")",
"\n",
"}",
"\n",
"buf",
"=",
"append",
"(",
"buf",
",",
"msg",
"...",
")",
"\n",
"if",
"len",
"(",
"msg",
")",
"==",
"0",
"||",
"msg",
"[",
"len",
"(",
"msg",
")",
"-",
"1",
"]",
"!=",
"'\\n'",
"{",
"buf",
"=",
"append",
"(",
"buf",
",",
"'\\n'",
")",
"\n",
"}",
"\n",
"l",
".",
"hLock",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"handler",
".",
"Write",
"(",
"buf",
")",
"\n",
"l",
".",
"hLock",
".",
"Unlock",
"(",
")",
"\n",
"}"
] |
// Output records the log with special callstack depth and log level.
|
[
"Output",
"records",
"the",
"log",
"with",
"special",
"callstack",
"depth",
"and",
"log",
"level",
"."
] |
1e957dd83bed18c84716181da7b80d4af48eaefe
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L137-L188
|
test
|
siddontang/go-log
|
log/logger.go
|
OutputJson
|
func (l *Logger) OutputJson(callDepth int, level Level, body interface{}) {
if l.level > level {
return
}
buf := l.bufs.Get().([]byte)
buf = buf[0:0]
defer l.bufs.Put(buf)
type JsonLog struct {
Time string `json:"log_time"`
Level string `json:"log_level"`
File string `json:"log_file"`
Line string `json:"log_line"`
Body interface{} `json:"log_body"`
}
var jsonlog JsonLog
if l.flag&Ltime > 0 {
now := time.Now().Format(timeFormat)
jsonlog.Time = now
}
if l.flag&Llevel > 0 {
jsonlog.Level = level.String()
}
if l.flag&Lfile > 0 {
_, file, line, ok := runtime.Caller(callDepth)
if !ok {
file = "???"
line = 0
} else {
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
file = file[i+1:]
break
}
}
}
jsonlog.File = file
jsonlog.Line = string(strconv.AppendInt(buf, int64(line), 10))
}
jsonlog.Body = body
msg, _ := json.Marshal(jsonlog)
msg = append(msg, '\n')
l.hLock.Lock()
l.handler.Write(msg)
l.hLock.Unlock()
}
|
go
|
func (l *Logger) OutputJson(callDepth int, level Level, body interface{}) {
if l.level > level {
return
}
buf := l.bufs.Get().([]byte)
buf = buf[0:0]
defer l.bufs.Put(buf)
type JsonLog struct {
Time string `json:"log_time"`
Level string `json:"log_level"`
File string `json:"log_file"`
Line string `json:"log_line"`
Body interface{} `json:"log_body"`
}
var jsonlog JsonLog
if l.flag&Ltime > 0 {
now := time.Now().Format(timeFormat)
jsonlog.Time = now
}
if l.flag&Llevel > 0 {
jsonlog.Level = level.String()
}
if l.flag&Lfile > 0 {
_, file, line, ok := runtime.Caller(callDepth)
if !ok {
file = "???"
line = 0
} else {
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
file = file[i+1:]
break
}
}
}
jsonlog.File = file
jsonlog.Line = string(strconv.AppendInt(buf, int64(line), 10))
}
jsonlog.Body = body
msg, _ := json.Marshal(jsonlog)
msg = append(msg, '\n')
l.hLock.Lock()
l.handler.Write(msg)
l.hLock.Unlock()
}
|
[
"func",
"(",
"l",
"*",
"Logger",
")",
"OutputJson",
"(",
"callDepth",
"int",
",",
"level",
"Level",
",",
"body",
"interface",
"{",
"}",
")",
"{",
"if",
"l",
".",
"level",
">",
"level",
"{",
"return",
"\n",
"}",
"\n",
"buf",
":=",
"l",
".",
"bufs",
".",
"Get",
"(",
")",
".",
"(",
"[",
"]",
"byte",
")",
"\n",
"buf",
"=",
"buf",
"[",
"0",
":",
"0",
"]",
"\n",
"defer",
"l",
".",
"bufs",
".",
"Put",
"(",
"buf",
")",
"\n",
"type",
"JsonLog",
"struct",
"{",
"Time",
"string",
"`json:\"log_time\"`",
"\n",
"Level",
"string",
"`json:\"log_level\"`",
"\n",
"File",
"string",
"`json:\"log_file\"`",
"\n",
"Line",
"string",
"`json:\"log_line\"`",
"\n",
"Body",
"interface",
"{",
"}",
"`json:\"log_body\"`",
"\n",
"}",
"\n",
"var",
"jsonlog",
"JsonLog",
"\n",
"if",
"l",
".",
"flag",
"&",
"Ltime",
">",
"0",
"{",
"now",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Format",
"(",
"timeFormat",
")",
"\n",
"jsonlog",
".",
"Time",
"=",
"now",
"\n",
"}",
"\n",
"if",
"l",
".",
"flag",
"&",
"Llevel",
">",
"0",
"{",
"jsonlog",
".",
"Level",
"=",
"level",
".",
"String",
"(",
")",
"\n",
"}",
"\n",
"if",
"l",
".",
"flag",
"&",
"Lfile",
">",
"0",
"{",
"_",
",",
"file",
",",
"line",
",",
"ok",
":=",
"runtime",
".",
"Caller",
"(",
"callDepth",
")",
"\n",
"if",
"!",
"ok",
"{",
"file",
"=",
"\"???\"",
"\n",
"line",
"=",
"0",
"\n",
"}",
"else",
"{",
"for",
"i",
":=",
"len",
"(",
"file",
")",
"-",
"1",
";",
"i",
">",
"0",
";",
"i",
"--",
"{",
"if",
"file",
"[",
"i",
"]",
"==",
"'/'",
"{",
"file",
"=",
"file",
"[",
"i",
"+",
"1",
":",
"]",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"jsonlog",
".",
"File",
"=",
"file",
"\n",
"jsonlog",
".",
"Line",
"=",
"string",
"(",
"strconv",
".",
"AppendInt",
"(",
"buf",
",",
"int64",
"(",
"line",
")",
",",
"10",
")",
")",
"\n",
"}",
"\n",
"jsonlog",
".",
"Body",
"=",
"body",
"\n",
"msg",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"jsonlog",
")",
"\n",
"msg",
"=",
"append",
"(",
"msg",
",",
"'\\n'",
")",
"\n",
"l",
".",
"hLock",
".",
"Lock",
"(",
")",
"\n",
"l",
".",
"handler",
".",
"Write",
"(",
"msg",
")",
"\n",
"l",
".",
"hLock",
".",
"Unlock",
"(",
")",
"\n",
"}"
] |
// Output json format records the log with special callstack depth and log level.
|
[
"Output",
"json",
"format",
"records",
"the",
"log",
"with",
"special",
"callstack",
"depth",
"and",
"log",
"level",
"."
] |
1e957dd83bed18c84716181da7b80d4af48eaefe
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L191-L244
|
test
|
siddontang/go-log
|
log/logger.go
|
Print
|
func (l *Logger) Print(args ...interface{}) {
l.Output(2, LevelTrace, fmt.Sprint(args...))
}
|
go
|
func (l *Logger) Print(args ...interface{}) {
l.Output(2, LevelTrace, fmt.Sprint(args...))
}
|
[
"func",
"(",
"l",
"*",
"Logger",
")",
"Print",
"(",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"Output",
"(",
"2",
",",
"LevelTrace",
",",
"fmt",
".",
"Sprint",
"(",
"args",
"...",
")",
")",
"\n",
"}"
] |
// Print records the log with trace level
|
[
"Print",
"records",
"the",
"log",
"with",
"trace",
"level"
] |
1e957dd83bed18c84716181da7b80d4af48eaefe
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L286-L288
|
test
|
siddontang/go-log
|
log/logger.go
|
Println
|
func (l *Logger) Println(args ...interface{}) {
l.Output(2, LevelTrace, fmt.Sprintln(args...))
}
|
go
|
func (l *Logger) Println(args ...interface{}) {
l.Output(2, LevelTrace, fmt.Sprintln(args...))
}
|
[
"func",
"(",
"l",
"*",
"Logger",
")",
"Println",
"(",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"Output",
"(",
"2",
",",
"LevelTrace",
",",
"fmt",
".",
"Sprintln",
"(",
"args",
"...",
")",
")",
"\n",
"}"
] |
// Println records the log with trace level
|
[
"Println",
"records",
"the",
"log",
"with",
"trace",
"level"
] |
1e957dd83bed18c84716181da7b80d4af48eaefe
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L296-L298
|
test
|
siddontang/go-log
|
log/logger.go
|
Debug
|
func (l *Logger) Debug(args ...interface{}) {
l.Output(2, LevelDebug, fmt.Sprint(args...))
}
|
go
|
func (l *Logger) Debug(args ...interface{}) {
l.Output(2, LevelDebug, fmt.Sprint(args...))
}
|
[
"func",
"(",
"l",
"*",
"Logger",
")",
"Debug",
"(",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"Output",
"(",
"2",
",",
"LevelDebug",
",",
"fmt",
".",
"Sprint",
"(",
"args",
"...",
")",
")",
"\n",
"}"
] |
// Debug records the log with debug level
|
[
"Debug",
"records",
"the",
"log",
"with",
"debug",
"level"
] |
1e957dd83bed18c84716181da7b80d4af48eaefe
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L301-L303
|
test
|
siddontang/go-log
|
log/logger.go
|
Debugln
|
func (l *Logger) Debugln(args ...interface{}) {
l.Output(2, LevelDebug, fmt.Sprintln(args...))
}
|
go
|
func (l *Logger) Debugln(args ...interface{}) {
l.Output(2, LevelDebug, fmt.Sprintln(args...))
}
|
[
"func",
"(",
"l",
"*",
"Logger",
")",
"Debugln",
"(",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"Output",
"(",
"2",
",",
"LevelDebug",
",",
"fmt",
".",
"Sprintln",
"(",
"args",
"...",
")",
")",
"\n",
"}"
] |
// Debugln records the log with debug level
|
[
"Debugln",
"records",
"the",
"log",
"with",
"debug",
"level"
] |
1e957dd83bed18c84716181da7b80d4af48eaefe
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L311-L313
|
test
|
siddontang/go-log
|
log/logger.go
|
Error
|
func (l *Logger) Error(args ...interface{}) {
l.Output(2, LevelError, fmt.Sprint(args...))
}
|
go
|
func (l *Logger) Error(args ...interface{}) {
l.Output(2, LevelError, fmt.Sprint(args...))
}
|
[
"func",
"(",
"l",
"*",
"Logger",
")",
"Error",
"(",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"Output",
"(",
"2",
",",
"LevelError",
",",
"fmt",
".",
"Sprint",
"(",
"args",
"...",
")",
")",
"\n",
"}"
] |
// Error records the log with error level
|
[
"Error",
"records",
"the",
"log",
"with",
"error",
"level"
] |
1e957dd83bed18c84716181da7b80d4af48eaefe
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L316-L318
|
test
|
siddontang/go-log
|
log/logger.go
|
Errorln
|
func (l *Logger) Errorln(args ...interface{}) {
l.Output(2, LevelError, fmt.Sprintln(args...))
}
|
go
|
func (l *Logger) Errorln(args ...interface{}) {
l.Output(2, LevelError, fmt.Sprintln(args...))
}
|
[
"func",
"(",
"l",
"*",
"Logger",
")",
"Errorln",
"(",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"Output",
"(",
"2",
",",
"LevelError",
",",
"fmt",
".",
"Sprintln",
"(",
"args",
"...",
")",
")",
"\n",
"}"
] |
// Errorln records the log with error level
|
[
"Errorln",
"records",
"the",
"log",
"with",
"error",
"level"
] |
1e957dd83bed18c84716181da7b80d4af48eaefe
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L326-L328
|
test
|
siddontang/go-log
|
log/logger.go
|
Info
|
func (l *Logger) Info(args ...interface{}) {
l.Output(2, LevelInfo, fmt.Sprint(args...))
}
|
go
|
func (l *Logger) Info(args ...interface{}) {
l.Output(2, LevelInfo, fmt.Sprint(args...))
}
|
[
"func",
"(",
"l",
"*",
"Logger",
")",
"Info",
"(",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"Output",
"(",
"2",
",",
"LevelInfo",
",",
"fmt",
".",
"Sprint",
"(",
"args",
"...",
")",
")",
"\n",
"}"
] |
// Info records the log with info level
|
[
"Info",
"records",
"the",
"log",
"with",
"info",
"level"
] |
1e957dd83bed18c84716181da7b80d4af48eaefe
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L331-L333
|
test
|
siddontang/go-log
|
log/logger.go
|
Infoln
|
func (l *Logger) Infoln(args ...interface{}) {
l.Output(2, LevelInfo, fmt.Sprintln(args...))
}
|
go
|
func (l *Logger) Infoln(args ...interface{}) {
l.Output(2, LevelInfo, fmt.Sprintln(args...))
}
|
[
"func",
"(",
"l",
"*",
"Logger",
")",
"Infoln",
"(",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"Output",
"(",
"2",
",",
"LevelInfo",
",",
"fmt",
".",
"Sprintln",
"(",
"args",
"...",
")",
")",
"\n",
"}"
] |
// Infoln records the log with info level
|
[
"Infoln",
"records",
"the",
"log",
"with",
"info",
"level"
] |
1e957dd83bed18c84716181da7b80d4af48eaefe
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L341-L343
|
test
|
siddontang/go-log
|
log/logger.go
|
Warn
|
func (l *Logger) Warn(args ...interface{}) {
l.Output(2, LevelWarn, fmt.Sprint(args...))
}
|
go
|
func (l *Logger) Warn(args ...interface{}) {
l.Output(2, LevelWarn, fmt.Sprint(args...))
}
|
[
"func",
"(",
"l",
"*",
"Logger",
")",
"Warn",
"(",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"Output",
"(",
"2",
",",
"LevelWarn",
",",
"fmt",
".",
"Sprint",
"(",
"args",
"...",
")",
")",
"\n",
"}"
] |
// Warn records the log with warn level
|
[
"Warn",
"records",
"the",
"log",
"with",
"warn",
"level"
] |
1e957dd83bed18c84716181da7b80d4af48eaefe
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L346-L348
|
test
|
siddontang/go-log
|
log/logger.go
|
Warnln
|
func (l *Logger) Warnln(args ...interface{}) {
l.Output(2, LevelWarn, fmt.Sprintln(args...))
}
|
go
|
func (l *Logger) Warnln(args ...interface{}) {
l.Output(2, LevelWarn, fmt.Sprintln(args...))
}
|
[
"func",
"(",
"l",
"*",
"Logger",
")",
"Warnln",
"(",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"l",
".",
"Output",
"(",
"2",
",",
"LevelWarn",
",",
"fmt",
".",
"Sprintln",
"(",
"args",
"...",
")",
")",
"\n",
"}"
] |
// Warnln records the log with warn level
|
[
"Warnln",
"records",
"the",
"log",
"with",
"warn",
"level"
] |
1e957dd83bed18c84716181da7b80d4af48eaefe
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/logger.go#L356-L358
|
test
|
siddontang/go-log
|
log/handler.go
|
NewStreamHandler
|
func NewStreamHandler(w io.Writer) (*StreamHandler, error) {
h := new(StreamHandler)
h.w = w
return h, nil
}
|
go
|
func NewStreamHandler(w io.Writer) (*StreamHandler, error) {
h := new(StreamHandler)
h.w = w
return h, nil
}
|
[
"func",
"NewStreamHandler",
"(",
"w",
"io",
".",
"Writer",
")",
"(",
"*",
"StreamHandler",
",",
"error",
")",
"{",
"h",
":=",
"new",
"(",
"StreamHandler",
")",
"\n",
"h",
".",
"w",
"=",
"w",
"\n",
"return",
"h",
",",
"nil",
"\n",
"}"
] |
// NewStreamHandler creates a StreamHandler
|
[
"NewStreamHandler",
"creates",
"a",
"StreamHandler"
] |
1e957dd83bed18c84716181da7b80d4af48eaefe
|
https://github.com/siddontang/go-log/blob/1e957dd83bed18c84716181da7b80d4af48eaefe/log/handler.go#L19-L25
|
test
|
willf/pad
|
pad.go
|
Right
|
func Right(str string, length int, pad string) string {
return str + times(pad, length-len(str))
}
|
go
|
func Right(str string, length int, pad string) string {
return str + times(pad, length-len(str))
}
|
[
"func",
"Right",
"(",
"str",
"string",
",",
"length",
"int",
",",
"pad",
"string",
")",
"string",
"{",
"return",
"str",
"+",
"times",
"(",
"pad",
",",
"length",
"-",
"len",
"(",
"str",
")",
")",
"\n",
"}"
] |
// Right right-pads the string with pad up to len runes
|
[
"Right",
"right",
"-",
"pads",
"the",
"string",
"with",
"pad",
"up",
"to",
"len",
"runes"
] |
eccfe5d84172e4f9dfd83fac9ed3a5f0eafbc2b4
|
https://github.com/willf/pad/blob/eccfe5d84172e4f9dfd83fac9ed3a5f0eafbc2b4/pad.go#L24-L26
|
test
|
rightscale/rsc
|
ss/ss.go
|
New
|
func New(h string, a rsapi.Authenticator) *API {
api := rsapi.New(h, a)
api.Metadata = GenMetadata
return &API{API: api}
}
|
go
|
func New(h string, a rsapi.Authenticator) *API {
api := rsapi.New(h, a)
api.Metadata = GenMetadata
return &API{API: api}
}
|
[
"func",
"New",
"(",
"h",
"string",
",",
"a",
"rsapi",
".",
"Authenticator",
")",
"*",
"API",
"{",
"api",
":=",
"rsapi",
".",
"New",
"(",
"h",
",",
"a",
")",
"\n",
"api",
".",
"Metadata",
"=",
"GenMetadata",
"\n",
"return",
"&",
"API",
"{",
"API",
":",
"api",
"}",
"\n",
"}"
] |
// New returns a Self-Service API client.
|
[
"New",
"returns",
"a",
"Self",
"-",
"Service",
"API",
"client",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ss.go#L37-L41
|
test
|
rightscale/rsc
|
ss/ss.go
|
setupMetadata
|
func setupMetadata() (result map[string]*metadata.Resource) {
result = make(map[string]*metadata.Resource)
for n, r := range ssd.GenMetadata {
result[n] = r
for _, a := range r.Actions {
for _, p := range a.PathPatterns {
// remove "/api/designer" prefix
p.Regexp = removePrefixes(p.Regexp, 2)
}
}
}
for n, r := range ssc.GenMetadata {
result[n] = r
for _, a := range r.Actions {
for _, p := range a.PathPatterns {
// remove "/api/catalog" prefix
p.Regexp = removePrefixes(p.Regexp, 2)
}
}
}
for n, r := range ssm.GenMetadata {
result[n] = r
for _, a := range r.Actions {
for _, p := range a.PathPatterns {
// remove "/api/manager" prefix
p.Regexp = removePrefixes(p.Regexp, 2)
}
}
}
return
}
|
go
|
func setupMetadata() (result map[string]*metadata.Resource) {
result = make(map[string]*metadata.Resource)
for n, r := range ssd.GenMetadata {
result[n] = r
for _, a := range r.Actions {
for _, p := range a.PathPatterns {
// remove "/api/designer" prefix
p.Regexp = removePrefixes(p.Regexp, 2)
}
}
}
for n, r := range ssc.GenMetadata {
result[n] = r
for _, a := range r.Actions {
for _, p := range a.PathPatterns {
// remove "/api/catalog" prefix
p.Regexp = removePrefixes(p.Regexp, 2)
}
}
}
for n, r := range ssm.GenMetadata {
result[n] = r
for _, a := range r.Actions {
for _, p := range a.PathPatterns {
// remove "/api/manager" prefix
p.Regexp = removePrefixes(p.Regexp, 2)
}
}
}
return
}
|
[
"func",
"setupMetadata",
"(",
")",
"(",
"result",
"map",
"[",
"string",
"]",
"*",
"metadata",
".",
"Resource",
")",
"{",
"result",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"metadata",
".",
"Resource",
")",
"\n",
"for",
"n",
",",
"r",
":=",
"range",
"ssd",
".",
"GenMetadata",
"{",
"result",
"[",
"n",
"]",
"=",
"r",
"\n",
"for",
"_",
",",
"a",
":=",
"range",
"r",
".",
"Actions",
"{",
"for",
"_",
",",
"p",
":=",
"range",
"a",
".",
"PathPatterns",
"{",
"p",
".",
"Regexp",
"=",
"removePrefixes",
"(",
"p",
".",
"Regexp",
",",
"2",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"n",
",",
"r",
":=",
"range",
"ssc",
".",
"GenMetadata",
"{",
"result",
"[",
"n",
"]",
"=",
"r",
"\n",
"for",
"_",
",",
"a",
":=",
"range",
"r",
".",
"Actions",
"{",
"for",
"_",
",",
"p",
":=",
"range",
"a",
".",
"PathPatterns",
"{",
"p",
".",
"Regexp",
"=",
"removePrefixes",
"(",
"p",
".",
"Regexp",
",",
"2",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"n",
",",
"r",
":=",
"range",
"ssm",
".",
"GenMetadata",
"{",
"result",
"[",
"n",
"]",
"=",
"r",
"\n",
"for",
"_",
",",
"a",
":=",
"range",
"r",
".",
"Actions",
"{",
"for",
"_",
",",
"p",
":=",
"range",
"a",
".",
"PathPatterns",
"{",
"p",
".",
"Regexp",
"=",
"removePrefixes",
"(",
"p",
".",
"Regexp",
",",
"2",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Initialize GenMetadata from each SS API generated metadata
|
[
"Initialize",
"GenMetadata",
"from",
"each",
"SS",
"API",
"generated",
"metadata"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ss.go#L84-L114
|
test
|
rightscale/rsc
|
gen/api15gen/param_analyzer.go
|
recordTypes
|
func (p *ParamAnalyzer) recordTypes(root gen.DataType) {
if o, ok := root.(*gen.ObjectDataType); ok {
if _, found := p.ParamTypes[o.TypeName]; !found {
p.ParamTypes[o.TypeName] = o
for _, f := range o.Fields {
p.recordTypes(f.Type)
}
}
} else if a, ok := root.(*gen.ArrayDataType); ok {
p.recordTypes(a.ElemType.Type)
}
}
|
go
|
func (p *ParamAnalyzer) recordTypes(root gen.DataType) {
if o, ok := root.(*gen.ObjectDataType); ok {
if _, found := p.ParamTypes[o.TypeName]; !found {
p.ParamTypes[o.TypeName] = o
for _, f := range o.Fields {
p.recordTypes(f.Type)
}
}
} else if a, ok := root.(*gen.ArrayDataType); ok {
p.recordTypes(a.ElemType.Type)
}
}
|
[
"func",
"(",
"p",
"*",
"ParamAnalyzer",
")",
"recordTypes",
"(",
"root",
"gen",
".",
"DataType",
")",
"{",
"if",
"o",
",",
"ok",
":=",
"root",
".",
"(",
"*",
"gen",
".",
"ObjectDataType",
")",
";",
"ok",
"{",
"if",
"_",
",",
"found",
":=",
"p",
".",
"ParamTypes",
"[",
"o",
".",
"TypeName",
"]",
";",
"!",
"found",
"{",
"p",
".",
"ParamTypes",
"[",
"o",
".",
"TypeName",
"]",
"=",
"o",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"o",
".",
"Fields",
"{",
"p",
".",
"recordTypes",
"(",
"f",
".",
"Type",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"if",
"a",
",",
"ok",
":=",
"root",
".",
"(",
"*",
"gen",
".",
"ArrayDataType",
")",
";",
"ok",
"{",
"p",
".",
"recordTypes",
"(",
"a",
".",
"ElemType",
".",
"Type",
")",
"\n",
"}",
"\n",
"}"
] |
// Recursively record all type declarations
|
[
"Recursively",
"record",
"all",
"type",
"declarations"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/api15gen/param_analyzer.go#L222-L233
|
test
|
rightscale/rsc
|
gen/api15gen/param_analyzer.go
|
appendSorted
|
func appendSorted(params []*gen.ActionParam, param *gen.ActionParam) []*gen.ActionParam {
params = append(params, param)
sort.Sort(gen.ByName(params))
return params
}
|
go
|
func appendSorted(params []*gen.ActionParam, param *gen.ActionParam) []*gen.ActionParam {
params = append(params, param)
sort.Sort(gen.ByName(params))
return params
}
|
[
"func",
"appendSorted",
"(",
"params",
"[",
"]",
"*",
"gen",
".",
"ActionParam",
",",
"param",
"*",
"gen",
".",
"ActionParam",
")",
"[",
"]",
"*",
"gen",
".",
"ActionParam",
"{",
"params",
"=",
"append",
"(",
"params",
",",
"param",
")",
"\n",
"sort",
".",
"Sort",
"(",
"gen",
".",
"ByName",
"(",
"params",
")",
")",
"\n",
"return",
"params",
"\n",
"}"
] |
// Sort action params by name
|
[
"Sort",
"action",
"params",
"by",
"name"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/api15gen/param_analyzer.go#L236-L240
|
test
|
rightscale/rsc
|
gen/api15gen/param_analyzer.go
|
parseDataType
|
func (p *ParamAnalyzer) parseDataType(path string, child *gen.ActionParam) gen.DataType {
param := p.rawParams[path].(map[string]interface{})
class := "String"
if c, ok := param["class"].(string); ok {
class = c
}
var res gen.DataType
switch class {
case "Integer":
i := gen.BasicDataType("int")
res = &i
case "String":
s := gen.BasicDataType("string")
res = &s
case "Array":
if child != nil {
res = &gen.ArrayDataType{child}
} else {
s := gen.BasicDataType("string")
p := p.newParam(fmt.Sprintf("%s[item]", path),
map[string]interface{}{}, &s)
res = &gen.ArrayDataType{p}
}
case "SourceUpload":
res = new(gen.SourceUploadDataType)
case "FileUpload", "Tempfile":
res = &gen.UploadDataType{TypeName: "FileUpload"}
case "Enumerable":
res = new(gen.EnumerableDataType)
case "Hash":
if current, ok := p.parsed[path]; ok {
res = current.Type
o := res.(*gen.ObjectDataType)
o.Fields = appendSorted(o.Fields, child)
} else {
oname := p.typeName(path)
res = &gen.ObjectDataType{oname, []*gen.ActionParam{child}}
}
}
return res
}
|
go
|
func (p *ParamAnalyzer) parseDataType(path string, child *gen.ActionParam) gen.DataType {
param := p.rawParams[path].(map[string]interface{})
class := "String"
if c, ok := param["class"].(string); ok {
class = c
}
var res gen.DataType
switch class {
case "Integer":
i := gen.BasicDataType("int")
res = &i
case "String":
s := gen.BasicDataType("string")
res = &s
case "Array":
if child != nil {
res = &gen.ArrayDataType{child}
} else {
s := gen.BasicDataType("string")
p := p.newParam(fmt.Sprintf("%s[item]", path),
map[string]interface{}{}, &s)
res = &gen.ArrayDataType{p}
}
case "SourceUpload":
res = new(gen.SourceUploadDataType)
case "FileUpload", "Tempfile":
res = &gen.UploadDataType{TypeName: "FileUpload"}
case "Enumerable":
res = new(gen.EnumerableDataType)
case "Hash":
if current, ok := p.parsed[path]; ok {
res = current.Type
o := res.(*gen.ObjectDataType)
o.Fields = appendSorted(o.Fields, child)
} else {
oname := p.typeName(path)
res = &gen.ObjectDataType{oname, []*gen.ActionParam{child}}
}
}
return res
}
|
[
"func",
"(",
"p",
"*",
"ParamAnalyzer",
")",
"parseDataType",
"(",
"path",
"string",
",",
"child",
"*",
"gen",
".",
"ActionParam",
")",
"gen",
".",
"DataType",
"{",
"param",
":=",
"p",
".",
"rawParams",
"[",
"path",
"]",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"class",
":=",
"\"String\"",
"\n",
"if",
"c",
",",
"ok",
":=",
"param",
"[",
"\"class\"",
"]",
".",
"(",
"string",
")",
";",
"ok",
"{",
"class",
"=",
"c",
"\n",
"}",
"\n",
"var",
"res",
"gen",
".",
"DataType",
"\n",
"switch",
"class",
"{",
"case",
"\"Integer\"",
":",
"i",
":=",
"gen",
".",
"BasicDataType",
"(",
"\"int\"",
")",
"\n",
"res",
"=",
"&",
"i",
"\n",
"case",
"\"String\"",
":",
"s",
":=",
"gen",
".",
"BasicDataType",
"(",
"\"string\"",
")",
"\n",
"res",
"=",
"&",
"s",
"\n",
"case",
"\"Array\"",
":",
"if",
"child",
"!=",
"nil",
"{",
"res",
"=",
"&",
"gen",
".",
"ArrayDataType",
"{",
"child",
"}",
"\n",
"}",
"else",
"{",
"s",
":=",
"gen",
".",
"BasicDataType",
"(",
"\"string\"",
")",
"\n",
"p",
":=",
"p",
".",
"newParam",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"%s[item]\"",
",",
"path",
")",
",",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"}",
",",
"&",
"s",
")",
"\n",
"res",
"=",
"&",
"gen",
".",
"ArrayDataType",
"{",
"p",
"}",
"\n",
"}",
"\n",
"case",
"\"SourceUpload\"",
":",
"res",
"=",
"new",
"(",
"gen",
".",
"SourceUploadDataType",
")",
"\n",
"case",
"\"FileUpload\"",
",",
"\"Tempfile\"",
":",
"res",
"=",
"&",
"gen",
".",
"UploadDataType",
"{",
"TypeName",
":",
"\"FileUpload\"",
"}",
"\n",
"case",
"\"Enumerable\"",
":",
"res",
"=",
"new",
"(",
"gen",
".",
"EnumerableDataType",
")",
"\n",
"case",
"\"Hash\"",
":",
"if",
"current",
",",
"ok",
":=",
"p",
".",
"parsed",
"[",
"path",
"]",
";",
"ok",
"{",
"res",
"=",
"current",
".",
"Type",
"\n",
"o",
":=",
"res",
".",
"(",
"*",
"gen",
".",
"ObjectDataType",
")",
"\n",
"o",
".",
"Fields",
"=",
"appendSorted",
"(",
"o",
".",
"Fields",
",",
"child",
")",
"\n",
"}",
"else",
"{",
"oname",
":=",
"p",
".",
"typeName",
"(",
"path",
")",
"\n",
"res",
"=",
"&",
"gen",
".",
"ObjectDataType",
"{",
"oname",
",",
"[",
"]",
"*",
"gen",
".",
"ActionParam",
"{",
"child",
"}",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"res",
"\n",
"}"
] |
// Parse data type in context
|
[
"Parse",
"data",
"type",
"in",
"context"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/api15gen/param_analyzer.go#L243-L283
|
test
|
rightscale/rsc
|
gen/api15gen/param_analyzer.go
|
parseParam
|
func (p *ParamAnalyzer) parseParam(path string, param map[string]interface{}, child *gen.ActionParam) *gen.ActionParam {
dType := p.parseDataType(path, child)
return p.newParam(path, param, dType)
}
|
go
|
func (p *ParamAnalyzer) parseParam(path string, param map[string]interface{}, child *gen.ActionParam) *gen.ActionParam {
dType := p.parseDataType(path, child)
return p.newParam(path, param, dType)
}
|
[
"func",
"(",
"p",
"*",
"ParamAnalyzer",
")",
"parseParam",
"(",
"path",
"string",
",",
"param",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"child",
"*",
"gen",
".",
"ActionParam",
")",
"*",
"gen",
".",
"ActionParam",
"{",
"dType",
":=",
"p",
".",
"parseDataType",
"(",
"path",
",",
"child",
")",
"\n",
"return",
"p",
".",
"newParam",
"(",
"path",
",",
"param",
",",
"dType",
")",
"\n",
"}"
] |
// Build action param struct from json data
|
[
"Build",
"action",
"param",
"struct",
"from",
"json",
"data"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/api15gen/param_analyzer.go#L295-L298
|
test
|
rightscale/rsc
|
gen/api15gen/param_analyzer.go
|
newParam
|
func (p *ParamAnalyzer) newParam(path string, param map[string]interface{}, dType gen.DataType) *gen.ActionParam {
var description, regexp string
var mandatory, nonBlank bool
var validValues []interface{}
if d, ok := param["description"]; ok {
description = d.(string)
}
if m, ok := param["mandatory"]; ok {
mandatory = m.(bool)
}
if n, ok := param["non_blank"]; ok {
nonBlank = n.(bool)
}
if r, ok := param["regexp"]; ok {
regexp = r.(string)
}
if v, ok := param["valid_values"]; ok {
validValues = v.([]interface{})
}
native := nativeNameFromPath(path)
isLeaf := false
if _, ok := dType.(*gen.EnumerableDataType); ok {
isLeaf = true
} else {
for _, l := range p.leafParamNames {
if path == l {
isLeaf = true
break
}
}
}
queryName := path
if _, ok := dType.(*gen.ArrayDataType); ok {
queryName += "[]"
}
actionParam := &gen.ActionParam{
Name: native,
QueryName: queryName,
Description: removeBlankLines(description),
VarName: parseParamName(native),
Type: dType,
Mandatory: mandatory,
NonBlank: nonBlank,
Regexp: regexp,
ValidValues: validValues,
}
if isLeaf {
p.LeafParams = append(p.LeafParams, actionParam)
}
return actionParam
}
|
go
|
func (p *ParamAnalyzer) newParam(path string, param map[string]interface{}, dType gen.DataType) *gen.ActionParam {
var description, regexp string
var mandatory, nonBlank bool
var validValues []interface{}
if d, ok := param["description"]; ok {
description = d.(string)
}
if m, ok := param["mandatory"]; ok {
mandatory = m.(bool)
}
if n, ok := param["non_blank"]; ok {
nonBlank = n.(bool)
}
if r, ok := param["regexp"]; ok {
regexp = r.(string)
}
if v, ok := param["valid_values"]; ok {
validValues = v.([]interface{})
}
native := nativeNameFromPath(path)
isLeaf := false
if _, ok := dType.(*gen.EnumerableDataType); ok {
isLeaf = true
} else {
for _, l := range p.leafParamNames {
if path == l {
isLeaf = true
break
}
}
}
queryName := path
if _, ok := dType.(*gen.ArrayDataType); ok {
queryName += "[]"
}
actionParam := &gen.ActionParam{
Name: native,
QueryName: queryName,
Description: removeBlankLines(description),
VarName: parseParamName(native),
Type: dType,
Mandatory: mandatory,
NonBlank: nonBlank,
Regexp: regexp,
ValidValues: validValues,
}
if isLeaf {
p.LeafParams = append(p.LeafParams, actionParam)
}
return actionParam
}
|
[
"func",
"(",
"p",
"*",
"ParamAnalyzer",
")",
"newParam",
"(",
"path",
"string",
",",
"param",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"dType",
"gen",
".",
"DataType",
")",
"*",
"gen",
".",
"ActionParam",
"{",
"var",
"description",
",",
"regexp",
"string",
"\n",
"var",
"mandatory",
",",
"nonBlank",
"bool",
"\n",
"var",
"validValues",
"[",
"]",
"interface",
"{",
"}",
"\n",
"if",
"d",
",",
"ok",
":=",
"param",
"[",
"\"description\"",
"]",
";",
"ok",
"{",
"description",
"=",
"d",
".",
"(",
"string",
")",
"\n",
"}",
"\n",
"if",
"m",
",",
"ok",
":=",
"param",
"[",
"\"mandatory\"",
"]",
";",
"ok",
"{",
"mandatory",
"=",
"m",
".",
"(",
"bool",
")",
"\n",
"}",
"\n",
"if",
"n",
",",
"ok",
":=",
"param",
"[",
"\"non_blank\"",
"]",
";",
"ok",
"{",
"nonBlank",
"=",
"n",
".",
"(",
"bool",
")",
"\n",
"}",
"\n",
"if",
"r",
",",
"ok",
":=",
"param",
"[",
"\"regexp\"",
"]",
";",
"ok",
"{",
"regexp",
"=",
"r",
".",
"(",
"string",
")",
"\n",
"}",
"\n",
"if",
"v",
",",
"ok",
":=",
"param",
"[",
"\"valid_values\"",
"]",
";",
"ok",
"{",
"validValues",
"=",
"v",
".",
"(",
"[",
"]",
"interface",
"{",
"}",
")",
"\n",
"}",
"\n",
"native",
":=",
"nativeNameFromPath",
"(",
"path",
")",
"\n",
"isLeaf",
":=",
"false",
"\n",
"if",
"_",
",",
"ok",
":=",
"dType",
".",
"(",
"*",
"gen",
".",
"EnumerableDataType",
")",
";",
"ok",
"{",
"isLeaf",
"=",
"true",
"\n",
"}",
"else",
"{",
"for",
"_",
",",
"l",
":=",
"range",
"p",
".",
"leafParamNames",
"{",
"if",
"path",
"==",
"l",
"{",
"isLeaf",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"queryName",
":=",
"path",
"\n",
"if",
"_",
",",
"ok",
":=",
"dType",
".",
"(",
"*",
"gen",
".",
"ArrayDataType",
")",
";",
"ok",
"{",
"queryName",
"+=",
"\"[]\"",
"\n",
"}",
"\n",
"actionParam",
":=",
"&",
"gen",
".",
"ActionParam",
"{",
"Name",
":",
"native",
",",
"QueryName",
":",
"queryName",
",",
"Description",
":",
"removeBlankLines",
"(",
"description",
")",
",",
"VarName",
":",
"parseParamName",
"(",
"native",
")",
",",
"Type",
":",
"dType",
",",
"Mandatory",
":",
"mandatory",
",",
"NonBlank",
":",
"nonBlank",
",",
"Regexp",
":",
"regexp",
",",
"ValidValues",
":",
"validValues",
",",
"}",
"\n",
"if",
"isLeaf",
"{",
"p",
".",
"LeafParams",
"=",
"append",
"(",
"p",
".",
"LeafParams",
",",
"actionParam",
")",
"\n",
"}",
"\n",
"return",
"actionParam",
"\n",
"}"
] |
// New parameter from raw values
|
[
"New",
"parameter",
"from",
"raw",
"values"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/api15gen/param_analyzer.go#L301-L351
|
test
|
rightscale/rsc
|
gen/praxisgen/helpers.go
|
toGoReturnTypeName
|
func toGoReturnTypeName(name string, slice bool) string {
slicePrefix := ""
if slice {
slicePrefix = "[]"
}
return fmt.Sprintf("%s*%s", slicePrefix, toGoTypeName(name))
}
|
go
|
func toGoReturnTypeName(name string, slice bool) string {
slicePrefix := ""
if slice {
slicePrefix = "[]"
}
return fmt.Sprintf("%s*%s", slicePrefix, toGoTypeName(name))
}
|
[
"func",
"toGoReturnTypeName",
"(",
"name",
"string",
",",
"slice",
"bool",
")",
"string",
"{",
"slicePrefix",
":=",
"\"\"",
"\n",
"if",
"slice",
"{",
"slicePrefix",
"=",
"\"[]\"",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%s*%s\"",
",",
"slicePrefix",
",",
"toGoTypeName",
"(",
"name",
")",
")",
"\n",
"}"
] |
// Produce action return type name
|
[
"Produce",
"action",
"return",
"type",
"name"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/praxisgen/helpers.go#L26-L32
|
test
|
rightscale/rsc
|
gen/praxisgen/helpers.go
|
toGoTypeName
|
func toGoTypeName(name string) string {
switch name {
case "String", "Symbol":
return "string"
case "Integer":
return "int"
case "Boolean":
return "bool"
case "Struct", "Collection":
panic("Uh oh, trying to infer a go type name for a unnamed struct or collection (" + name + ")")
default:
if strings.Contains(name, "::") {
elems := strings.Split(name, "::")
return strings.Join(elems[2:len(elems)], "")
}
return name
}
}
|
go
|
func toGoTypeName(name string) string {
switch name {
case "String", "Symbol":
return "string"
case "Integer":
return "int"
case "Boolean":
return "bool"
case "Struct", "Collection":
panic("Uh oh, trying to infer a go type name for a unnamed struct or collection (" + name + ")")
default:
if strings.Contains(name, "::") {
elems := strings.Split(name, "::")
return strings.Join(elems[2:len(elems)], "")
}
return name
}
}
|
[
"func",
"toGoTypeName",
"(",
"name",
"string",
")",
"string",
"{",
"switch",
"name",
"{",
"case",
"\"String\"",
",",
"\"Symbol\"",
":",
"return",
"\"string\"",
"\n",
"case",
"\"Integer\"",
":",
"return",
"\"int\"",
"\n",
"case",
"\"Boolean\"",
":",
"return",
"\"bool\"",
"\n",
"case",
"\"Struct\"",
",",
"\"Collection\"",
":",
"panic",
"(",
"\"Uh oh, trying to infer a go type name for a unnamed struct or collection (\"",
"+",
"name",
"+",
"\")\"",
")",
"\n",
"default",
":",
"if",
"strings",
".",
"Contains",
"(",
"name",
",",
"\"::\"",
")",
"{",
"elems",
":=",
"strings",
".",
"Split",
"(",
"name",
",",
"\"::\"",
")",
"\n",
"return",
"strings",
".",
"Join",
"(",
"elems",
"[",
"2",
":",
"len",
"(",
"elems",
")",
"]",
",",
"\"\"",
")",
"\n",
"}",
"\n",
"return",
"name",
"\n",
"}",
"\n",
"}"
] |
// Produce go type name from given ruby type name
|
[
"Produce",
"go",
"type",
"name",
"from",
"given",
"ruby",
"type",
"name"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/praxisgen/helpers.go#L35-L53
|
test
|
rightscale/rsc
|
gen/praxisgen/helpers.go
|
prettify
|
func prettify(o interface{}) string {
s, err := json.MarshalIndent(o, "", " ")
if err != nil {
return fmt.Sprintf("%+v", o)
}
return string(s)
}
|
go
|
func prettify(o interface{}) string {
s, err := json.MarshalIndent(o, "", " ")
if err != nil {
return fmt.Sprintf("%+v", o)
}
return string(s)
}
|
[
"func",
"prettify",
"(",
"o",
"interface",
"{",
"}",
")",
"string",
"{",
"s",
",",
"err",
":=",
"json",
".",
"MarshalIndent",
"(",
"o",
",",
"\"\"",
",",
"\" \"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%+v\"",
",",
"o",
")",
"\n",
"}",
"\n",
"return",
"string",
"(",
"s",
")",
"\n",
"}"
] |
// Return dumpable representation of given object
|
[
"Return",
"dumpable",
"representation",
"of",
"given",
"object"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/praxisgen/helpers.go#L68-L74
|
test
|
rightscale/rsc
|
gen/praxisgen/helpers.go
|
isBuiltInType
|
func isBuiltInType(name string) bool {
for _, n := range BuiltInTypes {
if name == n {
return true
}
}
return false
}
|
go
|
func isBuiltInType(name string) bool {
for _, n := range BuiltInTypes {
if name == n {
return true
}
}
return false
}
|
[
"func",
"isBuiltInType",
"(",
"name",
"string",
")",
"bool",
"{",
"for",
"_",
",",
"n",
":=",
"range",
"BuiltInTypes",
"{",
"if",
"name",
"==",
"n",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// Returns true if given name is the name of a built-in type
|
[
"Returns",
"true",
"if",
"given",
"name",
"is",
"the",
"name",
"of",
"a",
"built",
"-",
"in",
"type"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/praxisgen/helpers.go#L91-L98
|
test
|
rightscale/rsc
|
metadata/action.go
|
MatchHref
|
func (a *Action) MatchHref(href string) bool {
hrefs := []string{href, href + "/"}
for _, pattern := range a.PathPatterns {
for _, href := range hrefs {
indices := pattern.Regexp.FindStringIndex(href)
// it is only an exact match if the pattern matches from the beginning to the length of the string
if indices != nil && indices[0] == 0 && indices[1] == len(href) {
return true
}
}
}
return false
}
|
go
|
func (a *Action) MatchHref(href string) bool {
hrefs := []string{href, href + "/"}
for _, pattern := range a.PathPatterns {
for _, href := range hrefs {
indices := pattern.Regexp.FindStringIndex(href)
// it is only an exact match if the pattern matches from the beginning to the length of the string
if indices != nil && indices[0] == 0 && indices[1] == len(href) {
return true
}
}
}
return false
}
|
[
"func",
"(",
"a",
"*",
"Action",
")",
"MatchHref",
"(",
"href",
"string",
")",
"bool",
"{",
"hrefs",
":=",
"[",
"]",
"string",
"{",
"href",
",",
"href",
"+",
"\"/\"",
"}",
"\n",
"for",
"_",
",",
"pattern",
":=",
"range",
"a",
".",
"PathPatterns",
"{",
"for",
"_",
",",
"href",
":=",
"range",
"hrefs",
"{",
"indices",
":=",
"pattern",
".",
"Regexp",
".",
"FindStringIndex",
"(",
"href",
")",
"\n",
"if",
"indices",
"!=",
"nil",
"&&",
"indices",
"[",
"0",
"]",
"==",
"0",
"&&",
"indices",
"[",
"1",
"]",
"==",
"len",
"(",
"href",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// MatchHref returns true if the given href matches one of the action's href patterns exactly
|
[
"MatchHref",
"returns",
"true",
"if",
"the",
"given",
"href",
"matches",
"one",
"of",
"the",
"action",
"s",
"href",
"patterns",
"exactly"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/metadata/action.go#L36-L48
|
test
|
rightscale/rsc
|
metadata/action.go
|
Substitute
|
func (p *PathPattern) Substitute(vars []*PathVariable) (string, []string) {
values := make([]interface{}, len(p.Variables))
var missing []string
var used []string
for i, n := range p.Variables {
for _, v := range vars {
if v.Name == n {
values[i] = v.Value
used = append(used, n)
break
}
}
if values[i] == nil {
missing = append(missing, n)
}
}
if len(missing) > 0 {
return "", missing
}
return fmt.Sprintf(p.Pattern, values...), used
}
|
go
|
func (p *PathPattern) Substitute(vars []*PathVariable) (string, []string) {
values := make([]interface{}, len(p.Variables))
var missing []string
var used []string
for i, n := range p.Variables {
for _, v := range vars {
if v.Name == n {
values[i] = v.Value
used = append(used, n)
break
}
}
if values[i] == nil {
missing = append(missing, n)
}
}
if len(missing) > 0 {
return "", missing
}
return fmt.Sprintf(p.Pattern, values...), used
}
|
[
"func",
"(",
"p",
"*",
"PathPattern",
")",
"Substitute",
"(",
"vars",
"[",
"]",
"*",
"PathVariable",
")",
"(",
"string",
",",
"[",
"]",
"string",
")",
"{",
"values",
":=",
"make",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"len",
"(",
"p",
".",
"Variables",
")",
")",
"\n",
"var",
"missing",
"[",
"]",
"string",
"\n",
"var",
"used",
"[",
"]",
"string",
"\n",
"for",
"i",
",",
"n",
":=",
"range",
"p",
".",
"Variables",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"vars",
"{",
"if",
"v",
".",
"Name",
"==",
"n",
"{",
"values",
"[",
"i",
"]",
"=",
"v",
".",
"Value",
"\n",
"used",
"=",
"append",
"(",
"used",
",",
"n",
")",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"values",
"[",
"i",
"]",
"==",
"nil",
"{",
"missing",
"=",
"append",
"(",
"missing",
",",
"n",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"missing",
")",
">",
"0",
"{",
"return",
"\"\"",
",",
"missing",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"p",
".",
"Pattern",
",",
"values",
"...",
")",
",",
"used",
"\n",
"}"
] |
// Substitute attemps to substitute the path pattern variables with the given values.
// - If the substitution succeeds, it returns the resulting path and the list of variable names
// that were used to build it.
// - If the substitution fails, it returns an empty string and the list of variable names that are
// missing from the list of given values.
|
[
"Substitute",
"attemps",
"to",
"substitute",
"the",
"path",
"pattern",
"variables",
"with",
"the",
"given",
"values",
".",
"-",
"If",
"the",
"substitution",
"succeeds",
"it",
"returns",
"the",
"resulting",
"path",
"and",
"the",
"list",
"of",
"variable",
"names",
"that",
"were",
"used",
"to",
"build",
"it",
".",
"-",
"If",
"the",
"substitution",
"fails",
"it",
"returns",
"an",
"empty",
"string",
"and",
"the",
"list",
"of",
"variable",
"names",
"that",
"are",
"missing",
"from",
"the",
"list",
"of",
"given",
"values",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/metadata/action.go#L133-L153
|
test
|
rightscale/rsc
|
rsapi/http.go
|
MarshalJSON
|
func (f *FileUpload) MarshalJSON() ([]byte, error) {
b, err := ioutil.ReadAll(f.Reader)
if err != nil {
return nil, err
}
return json.Marshal(string(b))
}
|
go
|
func (f *FileUpload) MarshalJSON() ([]byte, error) {
b, err := ioutil.ReadAll(f.Reader)
if err != nil {
return nil, err
}
return json.Marshal(string(b))
}
|
[
"func",
"(",
"f",
"*",
"FileUpload",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"b",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"f",
".",
"Reader",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"json",
".",
"Marshal",
"(",
"string",
"(",
"b",
")",
")",
"\n",
"}"
] |
// MarshalJSON just inserts the contents of the file from disk inline into the json
|
[
"MarshalJSON",
"just",
"inserts",
"the",
"contents",
"of",
"the",
"file",
"from",
"disk",
"inline",
"into",
"the",
"json"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/http.go#L26-L32
|
test
|
rightscale/rsc
|
rsapi/http.go
|
writeMultipartParams
|
func writeMultipartParams(w *multipart.Writer, payload APIParams, prefix string) error {
for k, v := range payload {
fieldName := k
if prefix != "" {
fieldName = fmt.Sprintf("%s[%s]", prefix, k)
}
// Add more types as needed. These two cover both CM15 and SS.
switch v.(type) {
case string:
err := w.WriteField(fieldName, v.(string))
if err != nil {
return err
}
case APIParams:
err := writeMultipartParams(w, v.(APIParams), fieldName)
if err != nil {
return err
}
default:
return fmt.Errorf("Unknown type for multipart form section %s: %#v", fieldName, v)
}
}
return nil
}
|
go
|
func writeMultipartParams(w *multipart.Writer, payload APIParams, prefix string) error {
for k, v := range payload {
fieldName := k
if prefix != "" {
fieldName = fmt.Sprintf("%s[%s]", prefix, k)
}
// Add more types as needed. These two cover both CM15 and SS.
switch v.(type) {
case string:
err := w.WriteField(fieldName, v.(string))
if err != nil {
return err
}
case APIParams:
err := writeMultipartParams(w, v.(APIParams), fieldName)
if err != nil {
return err
}
default:
return fmt.Errorf("Unknown type for multipart form section %s: %#v", fieldName, v)
}
}
return nil
}
|
[
"func",
"writeMultipartParams",
"(",
"w",
"*",
"multipart",
".",
"Writer",
",",
"payload",
"APIParams",
",",
"prefix",
"string",
")",
"error",
"{",
"for",
"k",
",",
"v",
":=",
"range",
"payload",
"{",
"fieldName",
":=",
"k",
"\n",
"if",
"prefix",
"!=",
"\"\"",
"{",
"fieldName",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%s[%s]\"",
",",
"prefix",
",",
"k",
")",
"\n",
"}",
"\n",
"switch",
"v",
".",
"(",
"type",
")",
"{",
"case",
"string",
":",
"err",
":=",
"w",
".",
"WriteField",
"(",
"fieldName",
",",
"v",
".",
"(",
"string",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"case",
"APIParams",
":",
"err",
":=",
"writeMultipartParams",
"(",
"w",
",",
"v",
".",
"(",
"APIParams",
")",
",",
"fieldName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"default",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Unknown type for multipart form section %s: %#v\"",
",",
"fieldName",
",",
"v",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Handle payload params. Each payload param gets its own multipart
// form section with the section name being the variable name and
// section contents being the variable contents. Handle recursion as well.
|
[
"Handle",
"payload",
"params",
".",
"Each",
"payload",
"param",
"gets",
"its",
"own",
"multipart",
"form",
"section",
"with",
"the",
"section",
"name",
"being",
"the",
"variable",
"name",
"and",
"section",
"contents",
"being",
"the",
"variable",
"contents",
".",
"Handle",
"recursion",
"as",
"well",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/http.go#L74-L97
|
test
|
rightscale/rsc
|
rsapi/http.go
|
PerformRequest
|
func (a *API) PerformRequest(req *http.Request) (*http.Response, error) {
// Sign last so auth headers don't get printed or logged
if a.Auth != nil {
if err := a.Auth.Sign(req); err != nil {
return nil, err
}
}
resp, err := a.Client.Do(req)
if err != nil {
return nil, err
}
return resp, err
}
|
go
|
func (a *API) PerformRequest(req *http.Request) (*http.Response, error) {
// Sign last so auth headers don't get printed or logged
if a.Auth != nil {
if err := a.Auth.Sign(req); err != nil {
return nil, err
}
}
resp, err := a.Client.Do(req)
if err != nil {
return nil, err
}
return resp, err
}
|
[
"func",
"(",
"a",
"*",
"API",
")",
"PerformRequest",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"if",
"a",
".",
"Auth",
"!=",
"nil",
"{",
"if",
"err",
":=",
"a",
".",
"Auth",
".",
"Sign",
"(",
"req",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"resp",
",",
"err",
":=",
"a",
".",
"Client",
".",
"Do",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"resp",
",",
"err",
"\n",
"}"
] |
// PerformRequest logs the request, dumping its content if required then makes the request and logs
// and dumps the corresponding response.
|
[
"PerformRequest",
"logs",
"the",
"request",
"dumping",
"its",
"content",
"if",
"required",
"then",
"makes",
"the",
"request",
"and",
"logs",
"and",
"dumps",
"the",
"corresponding",
"response",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/http.go#L217-L230
|
test
|
rightscale/rsc
|
rsapi/http.go
|
PerformRequestWithContext
|
func (a *API) PerformRequestWithContext(ctx context.Context, req *http.Request) (*http.Response, error) {
// Sign last so auth headers don't get printed or logged
if a.Auth != nil {
if err := a.Auth.Sign(req); err != nil {
return nil, err
}
}
resp, err := a.Client.DoWithContext(ctx, req)
if err != nil {
return nil, err
}
return resp, err
}
|
go
|
func (a *API) PerformRequestWithContext(ctx context.Context, req *http.Request) (*http.Response, error) {
// Sign last so auth headers don't get printed or logged
if a.Auth != nil {
if err := a.Auth.Sign(req); err != nil {
return nil, err
}
}
resp, err := a.Client.DoWithContext(ctx, req)
if err != nil {
return nil, err
}
return resp, err
}
|
[
"func",
"(",
"a",
"*",
"API",
")",
"PerformRequestWithContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"if",
"a",
".",
"Auth",
"!=",
"nil",
"{",
"if",
"err",
":=",
"a",
".",
"Auth",
".",
"Sign",
"(",
"req",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"resp",
",",
"err",
":=",
"a",
".",
"Client",
".",
"DoWithContext",
"(",
"ctx",
",",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"resp",
",",
"err",
"\n",
"}"
] |
// PerformRequestWithContext performs everything the PerformRequest does but is also context-aware.
|
[
"PerformRequestWithContext",
"performs",
"everything",
"the",
"PerformRequest",
"does",
"but",
"is",
"also",
"context",
"-",
"aware",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/http.go#L233-L246
|
test
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.