id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
1,500
rakyll/gom
internal/driver/interactive.go
setGranularityToggle
func setGranularityToggle(o string, fl *flags) { t, f := newBool(true), newBool(false) fl.flagFunctions = f fl.flagFiles = f fl.flagLines = f fl.flagAddresses = f switch o { case "functions": fl.flagFunctions = t case "files": fl.flagFiles = t case "lines": fl.flagLines = t case "addresses": fl.flagAddresses = t default: panic(fmt.Errorf("unexpected option %s", o)) } }
go
func setGranularityToggle(o string, fl *flags) { t, f := newBool(true), newBool(false) fl.flagFunctions = f fl.flagFiles = f fl.flagLines = f fl.flagAddresses = f switch o { case "functions": fl.flagFunctions = t case "files": fl.flagFiles = t case "lines": fl.flagLines = t case "addresses": fl.flagAddresses = t default: panic(fmt.Errorf("unexpected option %s", o)) } }
[ "func", "setGranularityToggle", "(", "o", "string", ",", "fl", "*", "flags", ")", "{", "t", ",", "f", ":=", "newBool", "(", "true", ")", ",", "newBool", "(", "false", ")", "\n", "fl", ".", "flagFunctions", "=", "f", "\n", "fl", ".", "flagFiles", "=", "f", "\n", "fl", ".", "flagLines", "=", "f", "\n", "fl", ".", "flagAddresses", "=", "f", "\n", "switch", "o", "{", "case", "\"", "\"", ":", "fl", ".", "flagFunctions", "=", "t", "\n", "case", "\"", "\"", ":", "fl", ".", "flagFiles", "=", "t", "\n", "case", "\"", "\"", ":", "fl", ".", "flagLines", "=", "t", "\n", "case", "\"", "\"", ":", "fl", ".", "flagAddresses", "=", "t", "\n", "default", ":", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "o", ")", ")", "\n", "}", "\n", "}" ]
// setGranularityToggle manages the set of granularity options. These // operate as a toggle; turning one on turns the others off.
[ "setGranularityToggle", "manages", "the", "set", "of", "granularity", "options", ".", "These", "operate", "as", "a", "toggle", ";", "turning", "one", "on", "turns", "the", "others", "off", "." ]
183a9e70f4777aa03d377d21a0ed023a6afac141
https://github.com/rakyll/gom/blob/183a9e70f4777aa03d377d21a0ed023a6afac141/internal/driver/interactive.go#L474-L492
1,501
rakyll/gom
internal/svg/svg.go
Massage
func Massage(in bytes.Buffer) string { svg := string(in.Bytes()) // Work around for dot bug which misses quoting some ampersands, // resulting on unparsable SVG. svg = strings.Replace(svg, "&;", "&amp;;", -1) //Dot's SVG output is // // <svg width="___" height="___" // viewBox="___" xmlns=...> // <g id="graph0" transform="..."> // ... // </g> // </svg> // // Change it to // // <svg width="100%" height="100%" // xmlns=...> // <script>...</script> // <g id="viewport" transform="translate(0,0)"> // <g id="graph0" transform="..."> // ... // </g> // </g> // </svg> if loc := viewBox.FindStringIndex(svg); loc != nil { svg = svg[:loc[0]] + `<svg width="100%" height="100%"` + svg[loc[1]:] } if loc := graphId.FindStringIndex(svg); loc != nil { svg = svg[:loc[0]] + `<script type="text/ecmascript"><![CDATA[` + svgPanJS + `]]></script>` + `<g id="viewport" transform="scale(0.5,0.5) translate(0,0)">` + svg[loc[0]:] } if loc := svgClose.FindStringIndex(svg); loc != nil { svg = svg[:loc[0]] + `</g>` + svg[loc[0]:] } return svg }
go
func Massage(in bytes.Buffer) string { svg := string(in.Bytes()) // Work around for dot bug which misses quoting some ampersands, // resulting on unparsable SVG. svg = strings.Replace(svg, "&;", "&amp;;", -1) //Dot's SVG output is // // <svg width="___" height="___" // viewBox="___" xmlns=...> // <g id="graph0" transform="..."> // ... // </g> // </svg> // // Change it to // // <svg width="100%" height="100%" // xmlns=...> // <script>...</script> // <g id="viewport" transform="translate(0,0)"> // <g id="graph0" transform="..."> // ... // </g> // </g> // </svg> if loc := viewBox.FindStringIndex(svg); loc != nil { svg = svg[:loc[0]] + `<svg width="100%" height="100%"` + svg[loc[1]:] } if loc := graphId.FindStringIndex(svg); loc != nil { svg = svg[:loc[0]] + `<script type="text/ecmascript"><![CDATA[` + svgPanJS + `]]></script>` + `<g id="viewport" transform="scale(0.5,0.5) translate(0,0)">` + svg[loc[0]:] } if loc := svgClose.FindStringIndex(svg); loc != nil { svg = svg[:loc[0]] + `</g>` + svg[loc[0]:] } return svg }
[ "func", "Massage", "(", "in", "bytes", ".", "Buffer", ")", "string", "{", "svg", ":=", "string", "(", "in", ".", "Bytes", "(", ")", ")", "\n\n", "// Work around for dot bug which misses quoting some ampersands,", "// resulting on unparsable SVG.", "svg", "=", "strings", ".", "Replace", "(", "svg", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n\n", "//Dot's SVG output is", "//", "// <svg width=\"___\" height=\"___\"", "// viewBox=\"___\" xmlns=...>", "// <g id=\"graph0\" transform=\"...\">", "// ...", "// </g>", "// </svg>", "//", "// Change it to", "//", "// <svg width=\"100%\" height=\"100%\"", "// xmlns=...>", "// <script>...</script>", "// <g id=\"viewport\" transform=\"translate(0,0)\">", "// <g id=\"graph0\" transform=\"...\">", "// ...", "// </g>", "// </g>", "// </svg>", "if", "loc", ":=", "viewBox", ".", "FindStringIndex", "(", "svg", ")", ";", "loc", "!=", "nil", "{", "svg", "=", "svg", "[", ":", "loc", "[", "0", "]", "]", "+", "`<svg width=\"100%\" height=\"100%\"`", "+", "svg", "[", "loc", "[", "1", "]", ":", "]", "\n", "}", "\n\n", "if", "loc", ":=", "graphId", ".", "FindStringIndex", "(", "svg", ")", ";", "loc", "!=", "nil", "{", "svg", "=", "svg", "[", ":", "loc", "[", "0", "]", "]", "+", "`<script type=\"text/ecmascript\"><![CDATA[`", "+", "svgPanJS", "+", "`]]></script>`", "+", "`<g id=\"viewport\" transform=\"scale(0.5,0.5) translate(0,0)\">`", "+", "svg", "[", "loc", "[", "0", "]", ":", "]", "\n", "}", "\n\n", "if", "loc", ":=", "svgClose", ".", "FindStringIndex", "(", "svg", ")", ";", "loc", "!=", "nil", "{", "svg", "=", "svg", "[", ":", "loc", "[", "0", "]", "]", "+", "`</g>`", "+", "svg", "[", "loc", "[", "0", "]", ":", "]", "\n", "}", "\n\n", "return", "svg", "\n", "}" ]
// Massage enhances the SVG output from DOT to provide better // panning inside a web browser. It uses the SVGPan library, which is // included directly.
[ "Massage", "enhances", "the", "SVG", "output", "from", "DOT", "to", "provide", "better", "panning", "inside", "a", "web", "browser", ".", "It", "uses", "the", "SVGPan", "library", "which", "is", "included", "directly", "." ]
183a9e70f4777aa03d377d21a0ed023a6afac141
https://github.com/rakyll/gom/blob/183a9e70f4777aa03d377d21a0ed023a6afac141/internal/svg/svg.go#L23-L71
1,502
rakyll/gom
internal/profile/profile.go
setMain
func (p *Profile) setMain() { for i := 0; i < len(p.Mapping); i++ { file := strings.TrimSpace(strings.Replace(p.Mapping[i].File, "(deleted)", "", -1)) if len(file) == 0 { continue } if len(libRx.FindStringSubmatch(file)) > 0 { continue } if strings.HasPrefix(file, "[") { continue } // Swap what we guess is main to position 0. tmp := p.Mapping[i] p.Mapping[i] = p.Mapping[0] p.Mapping[0] = tmp break } }
go
func (p *Profile) setMain() { for i := 0; i < len(p.Mapping); i++ { file := strings.TrimSpace(strings.Replace(p.Mapping[i].File, "(deleted)", "", -1)) if len(file) == 0 { continue } if len(libRx.FindStringSubmatch(file)) > 0 { continue } if strings.HasPrefix(file, "[") { continue } // Swap what we guess is main to position 0. tmp := p.Mapping[i] p.Mapping[i] = p.Mapping[0] p.Mapping[0] = tmp break } }
[ "func", "(", "p", "*", "Profile", ")", "setMain", "(", ")", "{", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "p", ".", "Mapping", ")", ";", "i", "++", "{", "file", ":=", "strings", ".", "TrimSpace", "(", "strings", ".", "Replace", "(", "p", ".", "Mapping", "[", "i", "]", ".", "File", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", ")", "\n", "if", "len", "(", "file", ")", "==", "0", "{", "continue", "\n", "}", "\n", "if", "len", "(", "libRx", ".", "FindStringSubmatch", "(", "file", ")", ")", ">", "0", "{", "continue", "\n", "}", "\n", "if", "strings", ".", "HasPrefix", "(", "file", ",", "\"", "\"", ")", "{", "continue", "\n", "}", "\n", "// Swap what we guess is main to position 0.", "tmp", ":=", "p", ".", "Mapping", "[", "i", "]", "\n", "p", ".", "Mapping", "[", "i", "]", "=", "p", ".", "Mapping", "[", "0", "]", "\n", "p", ".", "Mapping", "[", "0", "]", "=", "tmp", "\n", "break", "\n", "}", "\n", "}" ]
// setMain scans Mapping entries and guesses which entry is main // because legacy profiles don't obey the convention of putting main // first.
[ "setMain", "scans", "Mapping", "entries", "and", "guesses", "which", "entry", "is", "main", "because", "legacy", "profiles", "don", "t", "obey", "the", "convention", "of", "putting", "main", "first", "." ]
183a9e70f4777aa03d377d21a0ed023a6afac141
https://github.com/rakyll/gom/blob/183a9e70f4777aa03d377d21a0ed023a6afac141/internal/profile/profile.go#L194-L212
1,503
rakyll/gom
internal/profile/filter.go
matchesName
func (loc *Location) matchesName(re *regexp.Regexp) bool { for _, ln := range loc.Line { if fn := ln.Function; fn != nil { if re.MatchString(fn.Name) { return true } if re.MatchString(fn.Filename) { return true } } } return false }
go
func (loc *Location) matchesName(re *regexp.Regexp) bool { for _, ln := range loc.Line { if fn := ln.Function; fn != nil { if re.MatchString(fn.Name) { return true } if re.MatchString(fn.Filename) { return true } } } return false }
[ "func", "(", "loc", "*", "Location", ")", "matchesName", "(", "re", "*", "regexp", ".", "Regexp", ")", "bool", "{", "for", "_", ",", "ln", ":=", "range", "loc", ".", "Line", "{", "if", "fn", ":=", "ln", ".", "Function", ";", "fn", "!=", "nil", "{", "if", "re", ".", "MatchString", "(", "fn", ".", "Name", ")", "{", "return", "true", "\n", "}", "\n", "if", "re", ".", "MatchString", "(", "fn", ".", "Filename", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// matchesName returns whether the function name or file in the // location matches the regular expression.
[ "matchesName", "returns", "whether", "the", "function", "name", "or", "file", "in", "the", "location", "matches", "the", "regular", "expression", "." ]
183a9e70f4777aa03d377d21a0ed023a6afac141
https://github.com/rakyll/gom/blob/183a9e70f4777aa03d377d21a0ed023a6afac141/internal/profile/filter.go#L60-L72
1,504
rakyll/gom
internal/profile/filter.go
unmatchedLines
func (loc *Location) unmatchedLines(re *regexp.Regexp) []Line { var lines []Line for _, ln := range loc.Line { if fn := ln.Function; fn != nil { if re.MatchString(fn.Name) { continue } if re.MatchString(fn.Filename) { continue } } lines = append(lines, ln) } return lines }
go
func (loc *Location) unmatchedLines(re *regexp.Regexp) []Line { var lines []Line for _, ln := range loc.Line { if fn := ln.Function; fn != nil { if re.MatchString(fn.Name) { continue } if re.MatchString(fn.Filename) { continue } } lines = append(lines, ln) } return lines }
[ "func", "(", "loc", "*", "Location", ")", "unmatchedLines", "(", "re", "*", "regexp", ".", "Regexp", ")", "[", "]", "Line", "{", "var", "lines", "[", "]", "Line", "\n", "for", "_", ",", "ln", ":=", "range", "loc", ".", "Line", "{", "if", "fn", ":=", "ln", ".", "Function", ";", "fn", "!=", "nil", "{", "if", "re", ".", "MatchString", "(", "fn", ".", "Name", ")", "{", "continue", "\n", "}", "\n", "if", "re", ".", "MatchString", "(", "fn", ".", "Filename", ")", "{", "continue", "\n", "}", "\n", "}", "\n", "lines", "=", "append", "(", "lines", ",", "ln", ")", "\n", "}", "\n", "return", "lines", "\n", "}" ]
// unmatchedLines returns the lines in the location that do not match // the regular expression.
[ "unmatchedLines", "returns", "the", "lines", "in", "the", "location", "that", "do", "not", "match", "the", "regular", "expression", "." ]
183a9e70f4777aa03d377d21a0ed023a6afac141
https://github.com/rakyll/gom/blob/183a9e70f4777aa03d377d21a0ed023a6afac141/internal/profile/filter.go#L76-L90
1,505
rakyll/gom
internal/symbolizer/symbolizer.go
Symbolize
func Symbolize(mode string, prof *profile.Profile, obj plugin.ObjTool, ui plugin.UI) error { force := false // Disable some mechanisms based on mode string. for _, o := range strings.Split(strings.ToLower(mode), ":") { switch o { case "force": force = true default: } } if len(prof.Mapping) == 0 { return fmt.Errorf("no known mappings") } mt, err := newMapping(prof, obj, ui, force) if err != nil { return err } defer mt.close() functions := make(map[profile.Function]*profile.Function) for _, l := range mt.prof.Location { m := l.Mapping segment := mt.segments[m] if segment == nil { // Nothing to do continue } stack, err := segment.SourceLine(l.Address) if err != nil || len(stack) == 0 { // No answers from addr2line continue } l.Line = make([]profile.Line, len(stack)) for i, frame := range stack { if frame.Func != "" { m.HasFunctions = true } if frame.File != "" { m.HasFilenames = true } if frame.Line != 0 { m.HasLineNumbers = true } f := &profile.Function{ Name: frame.Func, SystemName: frame.Func, Filename: frame.File, } if fp := functions[*f]; fp != nil { f = fp } else { functions[*f] = f f.ID = uint64(len(mt.prof.Function)) + 1 mt.prof.Function = append(mt.prof.Function, f) } l.Line[i] = profile.Line{ Function: f, Line: int64(frame.Line), } } if len(stack) > 0 { m.HasInlineFrames = true } } return nil }
go
func Symbolize(mode string, prof *profile.Profile, obj plugin.ObjTool, ui plugin.UI) error { force := false // Disable some mechanisms based on mode string. for _, o := range strings.Split(strings.ToLower(mode), ":") { switch o { case "force": force = true default: } } if len(prof.Mapping) == 0 { return fmt.Errorf("no known mappings") } mt, err := newMapping(prof, obj, ui, force) if err != nil { return err } defer mt.close() functions := make(map[profile.Function]*profile.Function) for _, l := range mt.prof.Location { m := l.Mapping segment := mt.segments[m] if segment == nil { // Nothing to do continue } stack, err := segment.SourceLine(l.Address) if err != nil || len(stack) == 0 { // No answers from addr2line continue } l.Line = make([]profile.Line, len(stack)) for i, frame := range stack { if frame.Func != "" { m.HasFunctions = true } if frame.File != "" { m.HasFilenames = true } if frame.Line != 0 { m.HasLineNumbers = true } f := &profile.Function{ Name: frame.Func, SystemName: frame.Func, Filename: frame.File, } if fp := functions[*f]; fp != nil { f = fp } else { functions[*f] = f f.ID = uint64(len(mt.prof.Function)) + 1 mt.prof.Function = append(mt.prof.Function, f) } l.Line[i] = profile.Line{ Function: f, Line: int64(frame.Line), } } if len(stack) > 0 { m.HasInlineFrames = true } } return nil }
[ "func", "Symbolize", "(", "mode", "string", ",", "prof", "*", "profile", ".", "Profile", ",", "obj", "plugin", ".", "ObjTool", ",", "ui", "plugin", ".", "UI", ")", "error", "{", "force", ":=", "false", "\n", "// Disable some mechanisms based on mode string.", "for", "_", ",", "o", ":=", "range", "strings", ".", "Split", "(", "strings", ".", "ToLower", "(", "mode", ")", ",", "\"", "\"", ")", "{", "switch", "o", "{", "case", "\"", "\"", ":", "force", "=", "true", "\n", "default", ":", "}", "\n", "}", "\n\n", "if", "len", "(", "prof", ".", "Mapping", ")", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "mt", ",", "err", ":=", "newMapping", "(", "prof", ",", "obj", ",", "ui", ",", "force", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "mt", ".", "close", "(", ")", "\n\n", "functions", ":=", "make", "(", "map", "[", "profile", ".", "Function", "]", "*", "profile", ".", "Function", ")", "\n", "for", "_", ",", "l", ":=", "range", "mt", ".", "prof", ".", "Location", "{", "m", ":=", "l", ".", "Mapping", "\n", "segment", ":=", "mt", ".", "segments", "[", "m", "]", "\n", "if", "segment", "==", "nil", "{", "// Nothing to do", "continue", "\n", "}", "\n\n", "stack", ",", "err", ":=", "segment", ".", "SourceLine", "(", "l", ".", "Address", ")", "\n", "if", "err", "!=", "nil", "||", "len", "(", "stack", ")", "==", "0", "{", "// No answers from addr2line", "continue", "\n", "}", "\n\n", "l", ".", "Line", "=", "make", "(", "[", "]", "profile", ".", "Line", ",", "len", "(", "stack", ")", ")", "\n", "for", "i", ",", "frame", ":=", "range", "stack", "{", "if", "frame", ".", "Func", "!=", "\"", "\"", "{", "m", ".", "HasFunctions", "=", "true", "\n", "}", "\n", "if", "frame", ".", "File", "!=", "\"", "\"", "{", "m", ".", "HasFilenames", "=", "true", "\n", "}", "\n", "if", "frame", ".", "Line", "!=", "0", "{", "m", ".", "HasLineNumbers", "=", "true", "\n", "}", "\n", "f", ":=", "&", "profile", ".", "Function", "{", "Name", ":", "frame", ".", "Func", ",", "SystemName", ":", "frame", ".", "Func", ",", "Filename", ":", "frame", ".", "File", ",", "}", "\n", "if", "fp", ":=", "functions", "[", "*", "f", "]", ";", "fp", "!=", "nil", "{", "f", "=", "fp", "\n", "}", "else", "{", "functions", "[", "*", "f", "]", "=", "f", "\n", "f", ".", "ID", "=", "uint64", "(", "len", "(", "mt", ".", "prof", ".", "Function", ")", ")", "+", "1", "\n", "mt", ".", "prof", ".", "Function", "=", "append", "(", "mt", ".", "prof", ".", "Function", ",", "f", ")", "\n", "}", "\n", "l", ".", "Line", "[", "i", "]", "=", "profile", ".", "Line", "{", "Function", ":", "f", ",", "Line", ":", "int64", "(", "frame", ".", "Line", ")", ",", "}", "\n", "}", "\n\n", "if", "len", "(", "stack", ")", ">", "0", "{", "m", ".", "HasInlineFrames", "=", "true", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Symbolize adds symbol and line number information to all locations // in a profile. mode enables some options to control // symbolization. Currently only recognizes "force", which causes it // to overwrite any existing data.
[ "Symbolize", "adds", "symbol", "and", "line", "number", "information", "to", "all", "locations", "in", "a", "profile", ".", "mode", "enables", "some", "options", "to", "control", "symbolization", ".", "Currently", "only", "recognizes", "force", "which", "causes", "it", "to", "overwrite", "any", "existing", "data", "." ]
183a9e70f4777aa03d377d21a0ed023a6afac141
https://github.com/rakyll/gom/blob/183a9e70f4777aa03d377d21a0ed023a6afac141/internal/symbolizer/symbolizer.go#L24-L94
1,506
rakyll/gom
internal/report/source.go
printFunctionHeader
func printFunctionHeader(w io.Writer, name, path string, flatSum, cumSum int64, rpt *Report) { fmt.Fprintf(w, `<h1>%s</h1>%s <pre onClick="pprof_toggle_asm()"> Total: %10s %10s (flat, cum) %s `, template.HTMLEscapeString(name), template.HTMLEscapeString(path), rpt.formatValue(flatSum), rpt.formatValue(cumSum), percentage(cumSum, rpt.total)) }
go
func printFunctionHeader(w io.Writer, name, path string, flatSum, cumSum int64, rpt *Report) { fmt.Fprintf(w, `<h1>%s</h1>%s <pre onClick="pprof_toggle_asm()"> Total: %10s %10s (flat, cum) %s `, template.HTMLEscapeString(name), template.HTMLEscapeString(path), rpt.formatValue(flatSum), rpt.formatValue(cumSum), percentage(cumSum, rpt.total)) }
[ "func", "printFunctionHeader", "(", "w", "io", ".", "Writer", ",", "name", ",", "path", "string", ",", "flatSum", ",", "cumSum", "int64", ",", "rpt", "*", "Report", ")", "{", "fmt", ".", "Fprintf", "(", "w", ",", "`<h1>%s</h1>%s\n<pre onClick=\"pprof_toggle_asm()\">\n Total: %10s %10s (flat, cum) %s\n`", ",", "template", ".", "HTMLEscapeString", "(", "name", ")", ",", "template", ".", "HTMLEscapeString", "(", "path", ")", ",", "rpt", ".", "formatValue", "(", "flatSum", ")", ",", "rpt", ".", "formatValue", "(", "cumSum", ")", ",", "percentage", "(", "cumSum", ",", "rpt", ".", "total", ")", ")", "\n", "}" ]
// printFunctionHeader prints a function header for a weblist report.
[ "printFunctionHeader", "prints", "a", "function", "header", "for", "a", "weblist", "report", "." ]
183a9e70f4777aa03d377d21a0ed023a6afac141
https://github.com/rakyll/gom/blob/183a9e70f4777aa03d377d21a0ed023a6afac141/internal/report/source.go#L258-L266
1,507
rakyll/gom
internal/report/source.go
getFunctionSource
func getFunctionSource(fun, file string, fns nodes, start, end int) (nodes, string, error) { f, file, err := adjustSourcePath(file) if err != nil { return nil, file, err } lineNodes := make(map[int]nodes) // Collect source coordinates from profile. const margin = 5 // Lines before first/after last sample. if start == 0 { if fns[0].info.startLine != 0 { start = fns[0].info.startLine } else { start = fns[0].info.lineno - margin } } else { start -= margin } if end == 0 { end = fns[0].info.lineno } end += margin for _, n := range fns { lineno := n.info.lineno nodeStart := n.info.startLine if nodeStart == 0 { nodeStart = lineno - margin } nodeEnd := lineno + margin if nodeStart < start { start = nodeStart } else if nodeEnd > end { end = nodeEnd } lineNodes[lineno] = append(lineNodes[lineno], n) } var src nodes buf := bufio.NewReader(f) lineno := 1 for { line, err := buf.ReadString('\n') if err != nil { if err != io.EOF { return nil, file, err } if line == "" { // end was at or past EOF; that's okay break } } if lineno >= start { flat, cum := sumNodes(lineNodes[lineno]) src = append(src, &node{ info: nodeInfo{ name: strings.TrimRight(line, "\n"), lineno: lineno, }, flat: flat, cum: cum, }) } lineno++ if lineno > end { break } } return src, file, nil }
go
func getFunctionSource(fun, file string, fns nodes, start, end int) (nodes, string, error) { f, file, err := adjustSourcePath(file) if err != nil { return nil, file, err } lineNodes := make(map[int]nodes) // Collect source coordinates from profile. const margin = 5 // Lines before first/after last sample. if start == 0 { if fns[0].info.startLine != 0 { start = fns[0].info.startLine } else { start = fns[0].info.lineno - margin } } else { start -= margin } if end == 0 { end = fns[0].info.lineno } end += margin for _, n := range fns { lineno := n.info.lineno nodeStart := n.info.startLine if nodeStart == 0 { nodeStart = lineno - margin } nodeEnd := lineno + margin if nodeStart < start { start = nodeStart } else if nodeEnd > end { end = nodeEnd } lineNodes[lineno] = append(lineNodes[lineno], n) } var src nodes buf := bufio.NewReader(f) lineno := 1 for { line, err := buf.ReadString('\n') if err != nil { if err != io.EOF { return nil, file, err } if line == "" { // end was at or past EOF; that's okay break } } if lineno >= start { flat, cum := sumNodes(lineNodes[lineno]) src = append(src, &node{ info: nodeInfo{ name: strings.TrimRight(line, "\n"), lineno: lineno, }, flat: flat, cum: cum, }) } lineno++ if lineno > end { break } } return src, file, nil }
[ "func", "getFunctionSource", "(", "fun", ",", "file", "string", ",", "fns", "nodes", ",", "start", ",", "end", "int", ")", "(", "nodes", ",", "string", ",", "error", ")", "{", "f", ",", "file", ",", "err", ":=", "adjustSourcePath", "(", "file", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "file", ",", "err", "\n", "}", "\n\n", "lineNodes", ":=", "make", "(", "map", "[", "int", "]", "nodes", ")", "\n\n", "// Collect source coordinates from profile.", "const", "margin", "=", "5", "// Lines before first/after last sample.", "\n", "if", "start", "==", "0", "{", "if", "fns", "[", "0", "]", ".", "info", ".", "startLine", "!=", "0", "{", "start", "=", "fns", "[", "0", "]", ".", "info", ".", "startLine", "\n", "}", "else", "{", "start", "=", "fns", "[", "0", "]", ".", "info", ".", "lineno", "-", "margin", "\n", "}", "\n", "}", "else", "{", "start", "-=", "margin", "\n", "}", "\n", "if", "end", "==", "0", "{", "end", "=", "fns", "[", "0", "]", ".", "info", ".", "lineno", "\n", "}", "\n", "end", "+=", "margin", "\n", "for", "_", ",", "n", ":=", "range", "fns", "{", "lineno", ":=", "n", ".", "info", ".", "lineno", "\n", "nodeStart", ":=", "n", ".", "info", ".", "startLine", "\n", "if", "nodeStart", "==", "0", "{", "nodeStart", "=", "lineno", "-", "margin", "\n", "}", "\n", "nodeEnd", ":=", "lineno", "+", "margin", "\n", "if", "nodeStart", "<", "start", "{", "start", "=", "nodeStart", "\n", "}", "else", "if", "nodeEnd", ">", "end", "{", "end", "=", "nodeEnd", "\n", "}", "\n", "lineNodes", "[", "lineno", "]", "=", "append", "(", "lineNodes", "[", "lineno", "]", ",", "n", ")", "\n", "}", "\n\n", "var", "src", "nodes", "\n", "buf", ":=", "bufio", ".", "NewReader", "(", "f", ")", "\n", "lineno", ":=", "1", "\n", "for", "{", "line", ",", "err", ":=", "buf", ".", "ReadString", "(", "'\\n'", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "!=", "io", ".", "EOF", "{", "return", "nil", ",", "file", ",", "err", "\n", "}", "\n", "if", "line", "==", "\"", "\"", "{", "// end was at or past EOF; that's okay", "break", "\n", "}", "\n", "}", "\n", "if", "lineno", ">=", "start", "{", "flat", ",", "cum", ":=", "sumNodes", "(", "lineNodes", "[", "lineno", "]", ")", "\n\n", "src", "=", "append", "(", "src", ",", "&", "node", "{", "info", ":", "nodeInfo", "{", "name", ":", "strings", ".", "TrimRight", "(", "line", ",", "\"", "\\n", "\"", ")", ",", "lineno", ":", "lineno", ",", "}", ",", "flat", ":", "flat", ",", "cum", ":", "cum", ",", "}", ")", "\n", "}", "\n", "lineno", "++", "\n", "if", "lineno", ">", "end", "{", "break", "\n", "}", "\n", "}", "\n", "return", "src", ",", "file", ",", "nil", "\n", "}" ]
// getFunctionSource collects the sources of a function from a source // file and annotates it with the samples in fns. Returns the sources // as nodes, using the info.name field to hold the source code.
[ "getFunctionSource", "collects", "the", "sources", "of", "a", "function", "from", "a", "source", "file", "and", "annotates", "it", "with", "the", "samples", "in", "fns", ".", "Returns", "the", "sources", "as", "nodes", "using", "the", "info", ".", "name", "field", "to", "hold", "the", "source", "code", "." ]
183a9e70f4777aa03d377d21a0ed023a6afac141
https://github.com/rakyll/gom/blob/183a9e70f4777aa03d377d21a0ed023a6afac141/internal/report/source.go#L317-L387
1,508
rakyll/gom
internal/report/source.go
adjustSourcePath
func adjustSourcePath(path string) (*os.File, string, error) { path = trimPath(path) f, err := os.Open(path) if err == nil { return f, path, nil } if dir, wderr := os.Getwd(); wderr == nil { for { parent := filepath.Dir(dir) if parent == dir { break } if f, err := os.Open(filepath.Join(parent, path)); err == nil { return f, filepath.Join(parent, path), nil } dir = parent } } return nil, path, err }
go
func adjustSourcePath(path string) (*os.File, string, error) { path = trimPath(path) f, err := os.Open(path) if err == nil { return f, path, nil } if dir, wderr := os.Getwd(); wderr == nil { for { parent := filepath.Dir(dir) if parent == dir { break } if f, err := os.Open(filepath.Join(parent, path)); err == nil { return f, filepath.Join(parent, path), nil } dir = parent } } return nil, path, err }
[ "func", "adjustSourcePath", "(", "path", "string", ")", "(", "*", "os", ".", "File", ",", "string", ",", "error", ")", "{", "path", "=", "trimPath", "(", "path", ")", "\n", "f", ",", "err", ":=", "os", ".", "Open", "(", "path", ")", "\n", "if", "err", "==", "nil", "{", "return", "f", ",", "path", ",", "nil", "\n", "}", "\n\n", "if", "dir", ",", "wderr", ":=", "os", ".", "Getwd", "(", ")", ";", "wderr", "==", "nil", "{", "for", "{", "parent", ":=", "filepath", ".", "Dir", "(", "dir", ")", "\n", "if", "parent", "==", "dir", "{", "break", "\n", "}", "\n", "if", "f", ",", "err", ":=", "os", ".", "Open", "(", "filepath", ".", "Join", "(", "parent", ",", "path", ")", ")", ";", "err", "==", "nil", "{", "return", "f", ",", "filepath", ".", "Join", "(", "parent", ",", "path", ")", ",", "nil", "\n", "}", "\n\n", "dir", "=", "parent", "\n", "}", "\n", "}", "\n\n", "return", "nil", ",", "path", ",", "err", "\n", "}" ]
// adjustSourcePath adjusts the pathe for a source file by trimmming // known prefixes and searching for the file on all parents of the // current working dir.
[ "adjustSourcePath", "adjusts", "the", "pathe", "for", "a", "source", "file", "by", "trimmming", "known", "prefixes", "and", "searching", "for", "the", "file", "on", "all", "parents", "of", "the", "current", "working", "dir", "." ]
183a9e70f4777aa03d377d21a0ed023a6afac141
https://github.com/rakyll/gom/blob/183a9e70f4777aa03d377d21a0ed023a6afac141/internal/report/source.go#L414-L436
1,509
rakyll/gom
internal/report/source.go
trimPath
func trimPath(path string) string { basePaths := []string{ "/proc/self/cwd/./", "/proc/self/cwd/", } sPath := filepath.ToSlash(path) for _, base := range basePaths { if strings.HasPrefix(sPath, base) { return filepath.FromSlash(sPath[len(base):]) } } return path }
go
func trimPath(path string) string { basePaths := []string{ "/proc/self/cwd/./", "/proc/self/cwd/", } sPath := filepath.ToSlash(path) for _, base := range basePaths { if strings.HasPrefix(sPath, base) { return filepath.FromSlash(sPath[len(base):]) } } return path }
[ "func", "trimPath", "(", "path", "string", ")", "string", "{", "basePaths", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "}", "\n\n", "sPath", ":=", "filepath", ".", "ToSlash", "(", "path", ")", "\n\n", "for", "_", ",", "base", ":=", "range", "basePaths", "{", "if", "strings", ".", "HasPrefix", "(", "sPath", ",", "base", ")", "{", "return", "filepath", ".", "FromSlash", "(", "sPath", "[", "len", "(", "base", ")", ":", "]", ")", "\n", "}", "\n", "}", "\n", "return", "path", "\n", "}" ]
// trimPath cleans up a path by removing prefixes that are commonly // found on profiles.
[ "trimPath", "cleans", "up", "a", "path", "by", "removing", "prefixes", "that", "are", "commonly", "found", "on", "profiles", "." ]
183a9e70f4777aa03d377d21a0ed023a6afac141
https://github.com/rakyll/gom/blob/183a9e70f4777aa03d377d21a0ed023a6afac141/internal/report/source.go#L440-L454
1,510
rakyll/gom
internal/profile/prune.go
Prune
func (p *Profile) Prune(dropRx, keepRx *regexp.Regexp) { prune := make(map[uint64]bool) pruneBeneath := make(map[uint64]bool) for _, loc := range p.Location { var i int for i = len(loc.Line) - 1; i >= 0; i-- { if fn := loc.Line[i].Function; fn != nil && fn.Name != "" { funcName := fn.Name // Account for leading '.' on the PPC ELF v1 ABI. if funcName[0] == '.' { funcName = funcName[1:] } if dropRx.MatchString(funcName) { if keepRx == nil || !keepRx.MatchString(funcName) { break } } } } if i >= 0 { // Found matching entry to prune. pruneBeneath[loc.ID] = true // Remove the matching location. if i == len(loc.Line)-1 { // Matched the top entry: prune the whole location. prune[loc.ID] = true } else { loc.Line = loc.Line[i+1:] } } } // Prune locs from each Sample for _, sample := range p.Sample { // Scan from the root to the leaves to find the prune location. // Do not prune frames before the first user frame, to avoid // pruning everything. foundUser := false for i := len(sample.Location) - 1; i >= 0; i-- { id := sample.Location[i].ID if !prune[id] && !pruneBeneath[id] { foundUser = true continue } if !foundUser { continue } if prune[id] { sample.Location = sample.Location[i+1:] break } if pruneBeneath[id] { sample.Location = sample.Location[i:] break } } } }
go
func (p *Profile) Prune(dropRx, keepRx *regexp.Regexp) { prune := make(map[uint64]bool) pruneBeneath := make(map[uint64]bool) for _, loc := range p.Location { var i int for i = len(loc.Line) - 1; i >= 0; i-- { if fn := loc.Line[i].Function; fn != nil && fn.Name != "" { funcName := fn.Name // Account for leading '.' on the PPC ELF v1 ABI. if funcName[0] == '.' { funcName = funcName[1:] } if dropRx.MatchString(funcName) { if keepRx == nil || !keepRx.MatchString(funcName) { break } } } } if i >= 0 { // Found matching entry to prune. pruneBeneath[loc.ID] = true // Remove the matching location. if i == len(loc.Line)-1 { // Matched the top entry: prune the whole location. prune[loc.ID] = true } else { loc.Line = loc.Line[i+1:] } } } // Prune locs from each Sample for _, sample := range p.Sample { // Scan from the root to the leaves to find the prune location. // Do not prune frames before the first user frame, to avoid // pruning everything. foundUser := false for i := len(sample.Location) - 1; i >= 0; i-- { id := sample.Location[i].ID if !prune[id] && !pruneBeneath[id] { foundUser = true continue } if !foundUser { continue } if prune[id] { sample.Location = sample.Location[i+1:] break } if pruneBeneath[id] { sample.Location = sample.Location[i:] break } } } }
[ "func", "(", "p", "*", "Profile", ")", "Prune", "(", "dropRx", ",", "keepRx", "*", "regexp", ".", "Regexp", ")", "{", "prune", ":=", "make", "(", "map", "[", "uint64", "]", "bool", ")", "\n", "pruneBeneath", ":=", "make", "(", "map", "[", "uint64", "]", "bool", ")", "\n\n", "for", "_", ",", "loc", ":=", "range", "p", ".", "Location", "{", "var", "i", "int", "\n", "for", "i", "=", "len", "(", "loc", ".", "Line", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "if", "fn", ":=", "loc", ".", "Line", "[", "i", "]", ".", "Function", ";", "fn", "!=", "nil", "&&", "fn", ".", "Name", "!=", "\"", "\"", "{", "funcName", ":=", "fn", ".", "Name", "\n", "// Account for leading '.' on the PPC ELF v1 ABI.", "if", "funcName", "[", "0", "]", "==", "'.'", "{", "funcName", "=", "funcName", "[", "1", ":", "]", "\n", "}", "\n", "if", "dropRx", ".", "MatchString", "(", "funcName", ")", "{", "if", "keepRx", "==", "nil", "||", "!", "keepRx", ".", "MatchString", "(", "funcName", ")", "{", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "i", ">=", "0", "{", "// Found matching entry to prune.", "pruneBeneath", "[", "loc", ".", "ID", "]", "=", "true", "\n\n", "// Remove the matching location.", "if", "i", "==", "len", "(", "loc", ".", "Line", ")", "-", "1", "{", "// Matched the top entry: prune the whole location.", "prune", "[", "loc", ".", "ID", "]", "=", "true", "\n", "}", "else", "{", "loc", ".", "Line", "=", "loc", ".", "Line", "[", "i", "+", "1", ":", "]", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Prune locs from each Sample", "for", "_", ",", "sample", ":=", "range", "p", ".", "Sample", "{", "// Scan from the root to the leaves to find the prune location.", "// Do not prune frames before the first user frame, to avoid", "// pruning everything.", "foundUser", ":=", "false", "\n", "for", "i", ":=", "len", "(", "sample", ".", "Location", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "id", ":=", "sample", ".", "Location", "[", "i", "]", ".", "ID", "\n", "if", "!", "prune", "[", "id", "]", "&&", "!", "pruneBeneath", "[", "id", "]", "{", "foundUser", "=", "true", "\n", "continue", "\n", "}", "\n", "if", "!", "foundUser", "{", "continue", "\n", "}", "\n", "if", "prune", "[", "id", "]", "{", "sample", ".", "Location", "=", "sample", ".", "Location", "[", "i", "+", "1", ":", "]", "\n", "break", "\n", "}", "\n", "if", "pruneBeneath", "[", "id", "]", "{", "sample", ".", "Location", "=", "sample", ".", "Location", "[", "i", ":", "]", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// Prune removes all nodes beneath a node matching dropRx, and not // matching keepRx. If the root node of a Sample matches, the sample // will have an empty stack.
[ "Prune", "removes", "all", "nodes", "beneath", "a", "node", "matching", "dropRx", "and", "not", "matching", "keepRx", ".", "If", "the", "root", "node", "of", "a", "Sample", "matches", "the", "sample", "will", "have", "an", "empty", "stack", "." ]
183a9e70f4777aa03d377d21a0ed023a6afac141
https://github.com/rakyll/gom/blob/183a9e70f4777aa03d377d21a0ed023a6afac141/internal/profile/prune.go#L17-L77
1,511
rakyll/gom
internal/driver/driver.go
adjustURL
func adjustURL(source string, sec int, ui plugin.UI) (adjusted, host string, duration time.Duration) { // If there is a local file with this name, just use it. if _, err := os.Stat(source); err == nil { return source, "", 0 } url, err := url.Parse(source) // Automatically add http:// to URLs of the form hostname:port/path. // url.Parse treats "hostname" as the Scheme. if err != nil || (url.Host == "" && url.Scheme != "" && url.Scheme != "file") { url, err = url.Parse("http://" + source) if err != nil { return source, url.Host, time.Duration(30) * time.Second } } if scheme := strings.ToLower(url.Scheme); scheme == "" || scheme == "file" { url.Scheme = "" return url.String(), "", 0 } values := url.Query() if urlSeconds := values.Get("seconds"); urlSeconds != "" { if us, err := strconv.ParseInt(urlSeconds, 10, 32); err == nil { if sec >= 0 { ui.PrintErr("Overriding -seconds for URL ", source) } sec = int(us) } } switch strings.ToLower(url.Path) { case "", "/": // Apply default /profilez. url.Path = "/profilez" case "/protoz": // Rewrite to /profilez?type=proto url.Path = "/profilez" values.Set("type", "proto") } if hasDuration(url.Path) { if sec > 0 { duration = time.Duration(sec) * time.Second values.Set("seconds", fmt.Sprintf("%d", sec)) } else { // Assume default duration: 30 seconds duration = 30 * time.Second } } url.RawQuery = values.Encode() return url.String(), url.Host, duration }
go
func adjustURL(source string, sec int, ui plugin.UI) (adjusted, host string, duration time.Duration) { // If there is a local file with this name, just use it. if _, err := os.Stat(source); err == nil { return source, "", 0 } url, err := url.Parse(source) // Automatically add http:// to URLs of the form hostname:port/path. // url.Parse treats "hostname" as the Scheme. if err != nil || (url.Host == "" && url.Scheme != "" && url.Scheme != "file") { url, err = url.Parse("http://" + source) if err != nil { return source, url.Host, time.Duration(30) * time.Second } } if scheme := strings.ToLower(url.Scheme); scheme == "" || scheme == "file" { url.Scheme = "" return url.String(), "", 0 } values := url.Query() if urlSeconds := values.Get("seconds"); urlSeconds != "" { if us, err := strconv.ParseInt(urlSeconds, 10, 32); err == nil { if sec >= 0 { ui.PrintErr("Overriding -seconds for URL ", source) } sec = int(us) } } switch strings.ToLower(url.Path) { case "", "/": // Apply default /profilez. url.Path = "/profilez" case "/protoz": // Rewrite to /profilez?type=proto url.Path = "/profilez" values.Set("type", "proto") } if hasDuration(url.Path) { if sec > 0 { duration = time.Duration(sec) * time.Second values.Set("seconds", fmt.Sprintf("%d", sec)) } else { // Assume default duration: 30 seconds duration = 30 * time.Second } } url.RawQuery = values.Encode() return url.String(), url.Host, duration }
[ "func", "adjustURL", "(", "source", "string", ",", "sec", "int", ",", "ui", "plugin", ".", "UI", ")", "(", "adjusted", ",", "host", "string", ",", "duration", "time", ".", "Duration", ")", "{", "// If there is a local file with this name, just use it.", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "source", ")", ";", "err", "==", "nil", "{", "return", "source", ",", "\"", "\"", ",", "0", "\n", "}", "\n\n", "url", ",", "err", ":=", "url", ".", "Parse", "(", "source", ")", "\n\n", "// Automatically add http:// to URLs of the form hostname:port/path.", "// url.Parse treats \"hostname\" as the Scheme.", "if", "err", "!=", "nil", "||", "(", "url", ".", "Host", "==", "\"", "\"", "&&", "url", ".", "Scheme", "!=", "\"", "\"", "&&", "url", ".", "Scheme", "!=", "\"", "\"", ")", "{", "url", ",", "err", "=", "url", ".", "Parse", "(", "\"", "\"", "+", "source", ")", "\n", "if", "err", "!=", "nil", "{", "return", "source", ",", "url", ".", "Host", ",", "time", ".", "Duration", "(", "30", ")", "*", "time", ".", "Second", "\n", "}", "\n", "}", "\n", "if", "scheme", ":=", "strings", ".", "ToLower", "(", "url", ".", "Scheme", ")", ";", "scheme", "==", "\"", "\"", "||", "scheme", "==", "\"", "\"", "{", "url", ".", "Scheme", "=", "\"", "\"", "\n", "return", "url", ".", "String", "(", ")", ",", "\"", "\"", ",", "0", "\n", "}", "\n\n", "values", ":=", "url", ".", "Query", "(", ")", "\n", "if", "urlSeconds", ":=", "values", ".", "Get", "(", "\"", "\"", ")", ";", "urlSeconds", "!=", "\"", "\"", "{", "if", "us", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "urlSeconds", ",", "10", ",", "32", ")", ";", "err", "==", "nil", "{", "if", "sec", ">=", "0", "{", "ui", ".", "PrintErr", "(", "\"", "\"", ",", "source", ")", "\n", "}", "\n", "sec", "=", "int", "(", "us", ")", "\n", "}", "\n", "}", "\n\n", "switch", "strings", ".", "ToLower", "(", "url", ".", "Path", ")", "{", "case", "\"", "\"", ",", "\"", "\"", ":", "// Apply default /profilez.", "url", ".", "Path", "=", "\"", "\"", "\n", "case", "\"", "\"", ":", "// Rewrite to /profilez?type=proto", "url", ".", "Path", "=", "\"", "\"", "\n", "values", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "hasDuration", "(", "url", ".", "Path", ")", "{", "if", "sec", ">", "0", "{", "duration", "=", "time", ".", "Duration", "(", "sec", ")", "*", "time", ".", "Second", "\n", "values", ".", "Set", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "sec", ")", ")", "\n", "}", "else", "{", "// Assume default duration: 30 seconds", "duration", "=", "30", "*", "time", ".", "Second", "\n", "}", "\n", "}", "\n", "url", ".", "RawQuery", "=", "values", ".", "Encode", "(", ")", "\n", "return", "url", ".", "String", "(", ")", ",", "url", ".", "Host", ",", "duration", "\n", "}" ]
// adjustURL updates the profile source URL based on heuristics. It // will append ?seconds=sec for CPU profiles if not already // specified. Returns the hostname if the profile is remote.
[ "adjustURL", "updates", "the", "profile", "source", "URL", "based", "on", "heuristics", ".", "It", "will", "append", "?seconds", "=", "sec", "for", "CPU", "profiles", "if", "not", "already", "specified", ".", "Returns", "the", "hostname", "if", "the", "profile", "is", "remote", "." ]
183a9e70f4777aa03d377d21a0ed023a6afac141
https://github.com/rakyll/gom/blob/183a9e70f4777aa03d377d21a0ed023a6afac141/internal/driver/driver.go#L129-L181
1,512
rakyll/gom
internal/driver/driver.go
preprocess
func preprocess(prof *profile.Profile, ui plugin.UI, f *flags) error { if *f.flagFocus != "" || *f.flagIgnore != "" || *f.flagHide != "" { focus, ignore, hide, err := compileFocusIgnore(*f.flagFocus, *f.flagIgnore, *f.flagHide) if err != nil { return err } fm, im, hm := prof.FilterSamplesByName(focus, ignore, hide) warnNoMatches(fm, *f.flagFocus, "Focus", ui) warnNoMatches(im, *f.flagIgnore, "Ignore", ui) warnNoMatches(hm, *f.flagHide, "Hide", ui) } if *f.flagTagFocus != "" || *f.flagTagIgnore != "" { focus, err := compileTagFilter(*f.flagTagFocus, ui) if err != nil { return err } ignore, err := compileTagFilter(*f.flagTagIgnore, ui) if err != nil { return err } fm, im := prof.FilterSamplesByTag(focus, ignore) warnNoMatches(fm, *f.flagTagFocus, "TagFocus", ui) warnNoMatches(im, *f.flagTagIgnore, "TagIgnore", ui) } return aggregate(prof, f) }
go
func preprocess(prof *profile.Profile, ui plugin.UI, f *flags) error { if *f.flagFocus != "" || *f.flagIgnore != "" || *f.flagHide != "" { focus, ignore, hide, err := compileFocusIgnore(*f.flagFocus, *f.flagIgnore, *f.flagHide) if err != nil { return err } fm, im, hm := prof.FilterSamplesByName(focus, ignore, hide) warnNoMatches(fm, *f.flagFocus, "Focus", ui) warnNoMatches(im, *f.flagIgnore, "Ignore", ui) warnNoMatches(hm, *f.flagHide, "Hide", ui) } if *f.flagTagFocus != "" || *f.flagTagIgnore != "" { focus, err := compileTagFilter(*f.flagTagFocus, ui) if err != nil { return err } ignore, err := compileTagFilter(*f.flagTagIgnore, ui) if err != nil { return err } fm, im := prof.FilterSamplesByTag(focus, ignore) warnNoMatches(fm, *f.flagTagFocus, "TagFocus", ui) warnNoMatches(im, *f.flagTagIgnore, "TagIgnore", ui) } return aggregate(prof, f) }
[ "func", "preprocess", "(", "prof", "*", "profile", ".", "Profile", ",", "ui", "plugin", ".", "UI", ",", "f", "*", "flags", ")", "error", "{", "if", "*", "f", ".", "flagFocus", "!=", "\"", "\"", "||", "*", "f", ".", "flagIgnore", "!=", "\"", "\"", "||", "*", "f", ".", "flagHide", "!=", "\"", "\"", "{", "focus", ",", "ignore", ",", "hide", ",", "err", ":=", "compileFocusIgnore", "(", "*", "f", ".", "flagFocus", ",", "*", "f", ".", "flagIgnore", ",", "*", "f", ".", "flagHide", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "fm", ",", "im", ",", "hm", ":=", "prof", ".", "FilterSamplesByName", "(", "focus", ",", "ignore", ",", "hide", ")", "\n\n", "warnNoMatches", "(", "fm", ",", "*", "f", ".", "flagFocus", ",", "\"", "\"", ",", "ui", ")", "\n", "warnNoMatches", "(", "im", ",", "*", "f", ".", "flagIgnore", ",", "\"", "\"", ",", "ui", ")", "\n", "warnNoMatches", "(", "hm", ",", "*", "f", ".", "flagHide", ",", "\"", "\"", ",", "ui", ")", "\n", "}", "\n\n", "if", "*", "f", ".", "flagTagFocus", "!=", "\"", "\"", "||", "*", "f", ".", "flagTagIgnore", "!=", "\"", "\"", "{", "focus", ",", "err", ":=", "compileTagFilter", "(", "*", "f", ".", "flagTagFocus", ",", "ui", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "ignore", ",", "err", ":=", "compileTagFilter", "(", "*", "f", ".", "flagTagIgnore", ",", "ui", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "fm", ",", "im", ":=", "prof", ".", "FilterSamplesByTag", "(", "focus", ",", "ignore", ")", "\n\n", "warnNoMatches", "(", "fm", ",", "*", "f", ".", "flagTagFocus", ",", "\"", "\"", ",", "ui", ")", "\n", "warnNoMatches", "(", "im", ",", "*", "f", ".", "flagTagIgnore", ",", "\"", "\"", ",", "ui", ")", "\n", "}", "\n\n", "return", "aggregate", "(", "prof", ",", "f", ")", "\n", "}" ]
// preprocess does filtering and aggregation of a profile based on the // requested options.
[ "preprocess", "does", "filtering", "and", "aggregation", "of", "a", "profile", "based", "on", "the", "requested", "options", "." ]
183a9e70f4777aa03d377d21a0ed023a6afac141
https://github.com/rakyll/gom/blob/183a9e70f4777aa03d377d21a0ed023a6afac141/internal/driver/driver.go#L194-L223
1,513
rakyll/gom
internal/driver/driver.go
String
func (f *flags) String(p *profile.Profile) string { var ret string if ix := *f.flagSampleIndex; ix != -1 { ret += fmt.Sprintf(" %-25s : %d (%s)\n", "sample_index", ix, p.SampleType[ix].Type) } if ix := *f.flagMean; ix { ret += boolFlagString("mean") } if *f.flagDisplayUnit != "minimum" { ret += stringFlagString("unit", *f.flagDisplayUnit) } switch { case *f.flagInteractive: ret += boolFlagString("interactive") } for name, fl := range f.flagCommands { if *fl { ret += boolFlagString(name) } } if *f.flagCum { ret += boolFlagString("cum") } if *f.flagCallTree { ret += boolFlagString("call_tree") } switch { case *f.flagAddresses: ret += boolFlagString("addresses") case *f.flagLines: ret += boolFlagString("lines") case *f.flagFiles: ret += boolFlagString("files") case *f.flagFunctions: ret += boolFlagString("functions") } if *f.flagNodeCount != -1 { ret += intFlagString("nodecount", *f.flagNodeCount) } ret += floatFlagString("nodefraction", *f.flagNodeFraction) ret += floatFlagString("edgefraction", *f.flagEdgeFraction) if *f.flagFocus != "" { ret += stringFlagString("focus", *f.flagFocus) } if *f.flagIgnore != "" { ret += stringFlagString("ignore", *f.flagIgnore) } if *f.flagHide != "" { ret += stringFlagString("hide", *f.flagHide) } if *f.flagTagFocus != "" { ret += stringFlagString("tagfocus", *f.flagTagFocus) } if *f.flagTagIgnore != "" { ret += stringFlagString("tagignore", *f.flagTagIgnore) } return ret }
go
func (f *flags) String(p *profile.Profile) string { var ret string if ix := *f.flagSampleIndex; ix != -1 { ret += fmt.Sprintf(" %-25s : %d (%s)\n", "sample_index", ix, p.SampleType[ix].Type) } if ix := *f.flagMean; ix { ret += boolFlagString("mean") } if *f.flagDisplayUnit != "minimum" { ret += stringFlagString("unit", *f.flagDisplayUnit) } switch { case *f.flagInteractive: ret += boolFlagString("interactive") } for name, fl := range f.flagCommands { if *fl { ret += boolFlagString(name) } } if *f.flagCum { ret += boolFlagString("cum") } if *f.flagCallTree { ret += boolFlagString("call_tree") } switch { case *f.flagAddresses: ret += boolFlagString("addresses") case *f.flagLines: ret += boolFlagString("lines") case *f.flagFiles: ret += boolFlagString("files") case *f.flagFunctions: ret += boolFlagString("functions") } if *f.flagNodeCount != -1 { ret += intFlagString("nodecount", *f.flagNodeCount) } ret += floatFlagString("nodefraction", *f.flagNodeFraction) ret += floatFlagString("edgefraction", *f.flagEdgeFraction) if *f.flagFocus != "" { ret += stringFlagString("focus", *f.flagFocus) } if *f.flagIgnore != "" { ret += stringFlagString("ignore", *f.flagIgnore) } if *f.flagHide != "" { ret += stringFlagString("hide", *f.flagHide) } if *f.flagTagFocus != "" { ret += stringFlagString("tagfocus", *f.flagTagFocus) } if *f.flagTagIgnore != "" { ret += stringFlagString("tagignore", *f.flagTagIgnore) } return ret }
[ "func", "(", "f", "*", "flags", ")", "String", "(", "p", "*", "profile", ".", "Profile", ")", "string", "{", "var", "ret", "string", "\n\n", "if", "ix", ":=", "*", "f", ".", "flagSampleIndex", ";", "ix", "!=", "-", "1", "{", "ret", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "\"", "\"", ",", "ix", ",", "p", ".", "SampleType", "[", "ix", "]", ".", "Type", ")", "\n", "}", "\n", "if", "ix", ":=", "*", "f", ".", "flagMean", ";", "ix", "{", "ret", "+=", "boolFlagString", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "*", "f", ".", "flagDisplayUnit", "!=", "\"", "\"", "{", "ret", "+=", "stringFlagString", "(", "\"", "\"", ",", "*", "f", ".", "flagDisplayUnit", ")", "\n", "}", "\n\n", "switch", "{", "case", "*", "f", ".", "flagInteractive", ":", "ret", "+=", "boolFlagString", "(", "\"", "\"", ")", "\n", "}", "\n", "for", "name", ",", "fl", ":=", "range", "f", ".", "flagCommands", "{", "if", "*", "fl", "{", "ret", "+=", "boolFlagString", "(", "name", ")", "\n", "}", "\n", "}", "\n\n", "if", "*", "f", ".", "flagCum", "{", "ret", "+=", "boolFlagString", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "*", "f", ".", "flagCallTree", "{", "ret", "+=", "boolFlagString", "(", "\"", "\"", ")", "\n", "}", "\n\n", "switch", "{", "case", "*", "f", ".", "flagAddresses", ":", "ret", "+=", "boolFlagString", "(", "\"", "\"", ")", "\n", "case", "*", "f", ".", "flagLines", ":", "ret", "+=", "boolFlagString", "(", "\"", "\"", ")", "\n", "case", "*", "f", ".", "flagFiles", ":", "ret", "+=", "boolFlagString", "(", "\"", "\"", ")", "\n", "case", "*", "f", ".", "flagFunctions", ":", "ret", "+=", "boolFlagString", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "*", "f", ".", "flagNodeCount", "!=", "-", "1", "{", "ret", "+=", "intFlagString", "(", "\"", "\"", ",", "*", "f", ".", "flagNodeCount", ")", "\n", "}", "\n\n", "ret", "+=", "floatFlagString", "(", "\"", "\"", ",", "*", "f", ".", "flagNodeFraction", ")", "\n", "ret", "+=", "floatFlagString", "(", "\"", "\"", ",", "*", "f", ".", "flagEdgeFraction", ")", "\n\n", "if", "*", "f", ".", "flagFocus", "!=", "\"", "\"", "{", "ret", "+=", "stringFlagString", "(", "\"", "\"", ",", "*", "f", ".", "flagFocus", ")", "\n", "}", "\n", "if", "*", "f", ".", "flagIgnore", "!=", "\"", "\"", "{", "ret", "+=", "stringFlagString", "(", "\"", "\"", ",", "*", "f", ".", "flagIgnore", ")", "\n", "}", "\n", "if", "*", "f", ".", "flagHide", "!=", "\"", "\"", "{", "ret", "+=", "stringFlagString", "(", "\"", "\"", ",", "*", "f", ".", "flagHide", ")", "\n", "}", "\n\n", "if", "*", "f", ".", "flagTagFocus", "!=", "\"", "\"", "{", "ret", "+=", "stringFlagString", "(", "\"", "\"", ",", "*", "f", ".", "flagTagFocus", ")", "\n", "}", "\n", "if", "*", "f", ".", "flagTagIgnore", "!=", "\"", "\"", "{", "ret", "+=", "stringFlagString", "(", "\"", "\"", ",", "*", "f", ".", "flagTagIgnore", ")", "\n", "}", "\n\n", "return", "ret", "\n", "}" ]
// String provides a printable representation for the current set of flags.
[ "String", "provides", "a", "printable", "representation", "for", "the", "current", "set", "of", "flags", "." ]
183a9e70f4777aa03d377d21a0ed023a6afac141
https://github.com/rakyll/gom/blob/183a9e70f4777aa03d377d21a0ed023a6afac141/internal/driver/driver.go#L494-L560
1,514
rakyll/gom
internal/driver/driver.go
parseOptions
func parseOptions(f *flags) (o *report.Options, p commands.PostProcessor, err error) { if *f.flagDivideBy == 0 { return nil, nil, fmt.Errorf("zero divisor specified") } o = &report.Options{ CumSort: *f.flagCum, CallTree: *f.flagCallTree, PrintAddresses: *f.flagAddresses, DropNegative: *f.flagDropNegative, Ratio: 1 / *f.flagDivideBy, NodeCount: *f.flagNodeCount, NodeFraction: *f.flagNodeFraction, EdgeFraction: *f.flagEdgeFraction, OutputUnit: *f.flagDisplayUnit, } for cmd, b := range f.flagCommands { if *b { pcmd := f.commands[cmd] o.OutputFormat = pcmd.Format return o, pcmd.PostProcess, nil } } for cmd, rx := range f.flagParamCommands { if *rx != "" { pcmd := f.commands[cmd] if o.Symbol, err = regexp.Compile(*rx); err != nil { return nil, nil, fmt.Errorf("parsing -%s regexp: %v", cmd, err) } o.OutputFormat = pcmd.Format return o, pcmd.PostProcess, nil } } return nil, nil, fmt.Errorf("no output format selected") }
go
func parseOptions(f *flags) (o *report.Options, p commands.PostProcessor, err error) { if *f.flagDivideBy == 0 { return nil, nil, fmt.Errorf("zero divisor specified") } o = &report.Options{ CumSort: *f.flagCum, CallTree: *f.flagCallTree, PrintAddresses: *f.flagAddresses, DropNegative: *f.flagDropNegative, Ratio: 1 / *f.flagDivideBy, NodeCount: *f.flagNodeCount, NodeFraction: *f.flagNodeFraction, EdgeFraction: *f.flagEdgeFraction, OutputUnit: *f.flagDisplayUnit, } for cmd, b := range f.flagCommands { if *b { pcmd := f.commands[cmd] o.OutputFormat = pcmd.Format return o, pcmd.PostProcess, nil } } for cmd, rx := range f.flagParamCommands { if *rx != "" { pcmd := f.commands[cmd] if o.Symbol, err = regexp.Compile(*rx); err != nil { return nil, nil, fmt.Errorf("parsing -%s regexp: %v", cmd, err) } o.OutputFormat = pcmd.Format return o, pcmd.PostProcess, nil } } return nil, nil, fmt.Errorf("no output format selected") }
[ "func", "parseOptions", "(", "f", "*", "flags", ")", "(", "o", "*", "report", ".", "Options", ",", "p", "commands", ".", "PostProcessor", ",", "err", "error", ")", "{", "if", "*", "f", ".", "flagDivideBy", "==", "0", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "o", "=", "&", "report", ".", "Options", "{", "CumSort", ":", "*", "f", ".", "flagCum", ",", "CallTree", ":", "*", "f", ".", "flagCallTree", ",", "PrintAddresses", ":", "*", "f", ".", "flagAddresses", ",", "DropNegative", ":", "*", "f", ".", "flagDropNegative", ",", "Ratio", ":", "1", "/", "*", "f", ".", "flagDivideBy", ",", "NodeCount", ":", "*", "f", ".", "flagNodeCount", ",", "NodeFraction", ":", "*", "f", ".", "flagNodeFraction", ",", "EdgeFraction", ":", "*", "f", ".", "flagEdgeFraction", ",", "OutputUnit", ":", "*", "f", ".", "flagDisplayUnit", ",", "}", "\n\n", "for", "cmd", ",", "b", ":=", "range", "f", ".", "flagCommands", "{", "if", "*", "b", "{", "pcmd", ":=", "f", ".", "commands", "[", "cmd", "]", "\n", "o", ".", "OutputFormat", "=", "pcmd", ".", "Format", "\n", "return", "o", ",", "pcmd", ".", "PostProcess", ",", "nil", "\n", "}", "\n", "}", "\n\n", "for", "cmd", ",", "rx", ":=", "range", "f", ".", "flagParamCommands", "{", "if", "*", "rx", "!=", "\"", "\"", "{", "pcmd", ":=", "f", ".", "commands", "[", "cmd", "]", "\n", "if", "o", ".", "Symbol", ",", "err", "=", "regexp", ".", "Compile", "(", "*", "rx", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "cmd", ",", "err", ")", "\n", "}", "\n", "o", ".", "OutputFormat", "=", "pcmd", ".", "Format", "\n", "return", "o", ",", "pcmd", ".", "PostProcess", ",", "nil", "\n", "}", "\n", "}", "\n\n", "return", "nil", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}" ]
// parseOptions parses the options into report.Options // Returns a function to postprocess the report after generation.
[ "parseOptions", "parses", "the", "options", "into", "report", ".", "Options", "Returns", "a", "function", "to", "postprocess", "the", "report", "after", "generation", "." ]
183a9e70f4777aa03d377d21a0ed023a6afac141
https://github.com/rakyll/gom/blob/183a9e70f4777aa03d377d21a0ed023a6afac141/internal/driver/driver.go#L924-L963
1,515
rakyll/gom
internal/profile/legacy_profile.go
ParseTracebacks
func ParseTracebacks(b []byte) (*Profile, error) { r := bytes.NewBuffer(b) p := &Profile{ PeriodType: &ValueType{Type: "trace", Unit: "count"}, Period: 1, SampleType: []*ValueType{ {Type: "trace", Unit: "count"}, }, } var sources []string var sloc []*Location locs := make(map[uint64]*Location) for { l, err := r.ReadString('\n') if err != nil { if err != io.EOF { return nil, err } if l == "" { break } } if sectionTrigger(l) == memoryMapSection { break } if s, addrs := extractHexAddresses(l); len(s) > 0 { for _, addr := range addrs { // Addresses from stack traces point to the next instruction after // each call. Adjust by -1 to land somewhere on the actual call // (except for the leaf, which is not a call). if len(sloc) > 0 { addr-- } loc := locs[addr] if locs[addr] == nil { loc = &Location{ Address: addr, } p.Location = append(p.Location, loc) locs[addr] = loc } sloc = append(sloc, loc) } sources = append(sources, s...) } else { if len(sources) > 0 || len(sloc) > 0 { addTracebackSample(sloc, sources, p) sloc, sources = nil, nil } } } // Add final sample to save any leftover data. if len(sources) > 0 || len(sloc) > 0 { addTracebackSample(sloc, sources, p) } if err := p.ParseMemoryMap(r); err != nil { return nil, err } return p, nil }
go
func ParseTracebacks(b []byte) (*Profile, error) { r := bytes.NewBuffer(b) p := &Profile{ PeriodType: &ValueType{Type: "trace", Unit: "count"}, Period: 1, SampleType: []*ValueType{ {Type: "trace", Unit: "count"}, }, } var sources []string var sloc []*Location locs := make(map[uint64]*Location) for { l, err := r.ReadString('\n') if err != nil { if err != io.EOF { return nil, err } if l == "" { break } } if sectionTrigger(l) == memoryMapSection { break } if s, addrs := extractHexAddresses(l); len(s) > 0 { for _, addr := range addrs { // Addresses from stack traces point to the next instruction after // each call. Adjust by -1 to land somewhere on the actual call // (except for the leaf, which is not a call). if len(sloc) > 0 { addr-- } loc := locs[addr] if locs[addr] == nil { loc = &Location{ Address: addr, } p.Location = append(p.Location, loc) locs[addr] = loc } sloc = append(sloc, loc) } sources = append(sources, s...) } else { if len(sources) > 0 || len(sloc) > 0 { addTracebackSample(sloc, sources, p) sloc, sources = nil, nil } } } // Add final sample to save any leftover data. if len(sources) > 0 || len(sloc) > 0 { addTracebackSample(sloc, sources, p) } if err := p.ParseMemoryMap(r); err != nil { return nil, err } return p, nil }
[ "func", "ParseTracebacks", "(", "b", "[", "]", "byte", ")", "(", "*", "Profile", ",", "error", ")", "{", "r", ":=", "bytes", ".", "NewBuffer", "(", "b", ")", "\n\n", "p", ":=", "&", "Profile", "{", "PeriodType", ":", "&", "ValueType", "{", "Type", ":", "\"", "\"", ",", "Unit", ":", "\"", "\"", "}", ",", "Period", ":", "1", ",", "SampleType", ":", "[", "]", "*", "ValueType", "{", "{", "Type", ":", "\"", "\"", ",", "Unit", ":", "\"", "\"", "}", ",", "}", ",", "}", "\n\n", "var", "sources", "[", "]", "string", "\n", "var", "sloc", "[", "]", "*", "Location", "\n\n", "locs", ":=", "make", "(", "map", "[", "uint64", "]", "*", "Location", ")", "\n", "for", "{", "l", ",", "err", ":=", "r", ".", "ReadString", "(", "'\\n'", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "!=", "io", ".", "EOF", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "l", "==", "\"", "\"", "{", "break", "\n", "}", "\n", "}", "\n", "if", "sectionTrigger", "(", "l", ")", "==", "memoryMapSection", "{", "break", "\n", "}", "\n", "if", "s", ",", "addrs", ":=", "extractHexAddresses", "(", "l", ")", ";", "len", "(", "s", ")", ">", "0", "{", "for", "_", ",", "addr", ":=", "range", "addrs", "{", "// Addresses from stack traces point to the next instruction after", "// each call. Adjust by -1 to land somewhere on the actual call", "// (except for the leaf, which is not a call).", "if", "len", "(", "sloc", ")", ">", "0", "{", "addr", "--", "\n", "}", "\n", "loc", ":=", "locs", "[", "addr", "]", "\n", "if", "locs", "[", "addr", "]", "==", "nil", "{", "loc", "=", "&", "Location", "{", "Address", ":", "addr", ",", "}", "\n", "p", ".", "Location", "=", "append", "(", "p", ".", "Location", ",", "loc", ")", "\n", "locs", "[", "addr", "]", "=", "loc", "\n", "}", "\n", "sloc", "=", "append", "(", "sloc", ",", "loc", ")", "\n", "}", "\n\n", "sources", "=", "append", "(", "sources", ",", "s", "...", ")", "\n", "}", "else", "{", "if", "len", "(", "sources", ")", ">", "0", "||", "len", "(", "sloc", ")", ">", "0", "{", "addTracebackSample", "(", "sloc", ",", "sources", ",", "p", ")", "\n", "sloc", ",", "sources", "=", "nil", ",", "nil", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Add final sample to save any leftover data.", "if", "len", "(", "sources", ")", ">", "0", "||", "len", "(", "sloc", ")", ">", "0", "{", "addTracebackSample", "(", "sloc", ",", "sources", ",", "p", ")", "\n", "}", "\n\n", "if", "err", ":=", "p", ".", "ParseMemoryMap", "(", "r", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "p", ",", "nil", "\n", "}" ]
// ParseTracebacks parses a set of tracebacks and returns a newly // populated profile. It will accept any text file and generate a // Profile out of it with any hex addresses it can identify, including // a process map if it can recognize one. Each sample will include a // tag "source" with the addresses recognized in string format.
[ "ParseTracebacks", "parses", "a", "set", "of", "tracebacks", "and", "returns", "a", "newly", "populated", "profile", ".", "It", "will", "accept", "any", "text", "file", "and", "generate", "a", "Profile", "out", "of", "it", "with", "any", "hex", "addresses", "it", "can", "identify", "including", "a", "process", "map", "if", "it", "can", "recognize", "one", ".", "Each", "sample", "will", "include", "a", "tag", "source", "with", "the", "addresses", "recognized", "in", "string", "format", "." ]
183a9e70f4777aa03d377d21a0ed023a6afac141
https://github.com/rakyll/gom/blob/183a9e70f4777aa03d377d21a0ed023a6afac141/internal/profile/legacy_profile.go#L263-L328
1,516
rakyll/gom
internal/profile/legacy_profile.go
extractHexAddresses
func extractHexAddresses(s string) ([]string, []uint64) { hexStrings := hexNumberRE.FindAllString(s, -1) var ids []uint64 for _, s := range hexStrings { if id, err := strconv.ParseUint(s, 0, 64); err == nil { ids = append(ids, id) } else { // Do not expect any parsing failures due to the regexp matching. panic("failed to parse hex value:" + s) } } return hexStrings, ids }
go
func extractHexAddresses(s string) ([]string, []uint64) { hexStrings := hexNumberRE.FindAllString(s, -1) var ids []uint64 for _, s := range hexStrings { if id, err := strconv.ParseUint(s, 0, 64); err == nil { ids = append(ids, id) } else { // Do not expect any parsing failures due to the regexp matching. panic("failed to parse hex value:" + s) } } return hexStrings, ids }
[ "func", "extractHexAddresses", "(", "s", "string", ")", "(", "[", "]", "string", ",", "[", "]", "uint64", ")", "{", "hexStrings", ":=", "hexNumberRE", ".", "FindAllString", "(", "s", ",", "-", "1", ")", "\n", "var", "ids", "[", "]", "uint64", "\n", "for", "_", ",", "s", ":=", "range", "hexStrings", "{", "if", "id", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "s", ",", "0", ",", "64", ")", ";", "err", "==", "nil", "{", "ids", "=", "append", "(", "ids", ",", "id", ")", "\n", "}", "else", "{", "// Do not expect any parsing failures due to the regexp matching.", "panic", "(", "\"", "\"", "+", "s", ")", "\n", "}", "\n", "}", "\n", "return", "hexStrings", ",", "ids", "\n", "}" ]
// extractHexAddresses extracts hex numbers from a string and returns // them, together with their numeric value, in a slice.
[ "extractHexAddresses", "extracts", "hex", "numbers", "from", "a", "string", "and", "returns", "them", "together", "with", "their", "numeric", "value", "in", "a", "slice", "." ]
183a9e70f4777aa03d377d21a0ed023a6afac141
https://github.com/rakyll/gom/blob/183a9e70f4777aa03d377d21a0ed023a6afac141/internal/profile/legacy_profile.go#L644-L656
1,517
rafaeljusto/redigomock
command.go
match
func match(commandName string, args []interface{}, cmd *Cmd) bool { if commandName != cmd.Name || len(args) != len(cmd.Args) { return false } for pos := range cmd.Args { if implementsFuzzy(cmd.Args[pos]) { if cmd.Args[pos].(FuzzyMatcher).Match(args[pos]) == false { return false } } else if reflect.DeepEqual(cmd.Args[pos], args[pos]) == false { return false } } return true }
go
func match(commandName string, args []interface{}, cmd *Cmd) bool { if commandName != cmd.Name || len(args) != len(cmd.Args) { return false } for pos := range cmd.Args { if implementsFuzzy(cmd.Args[pos]) { if cmd.Args[pos].(FuzzyMatcher).Match(args[pos]) == false { return false } } else if reflect.DeepEqual(cmd.Args[pos], args[pos]) == false { return false } } return true }
[ "func", "match", "(", "commandName", "string", ",", "args", "[", "]", "interface", "{", "}", ",", "cmd", "*", "Cmd", ")", "bool", "{", "if", "commandName", "!=", "cmd", ".", "Name", "||", "len", "(", "args", ")", "!=", "len", "(", "cmd", ".", "Args", ")", "{", "return", "false", "\n", "}", "\n\n", "for", "pos", ":=", "range", "cmd", ".", "Args", "{", "if", "implementsFuzzy", "(", "cmd", ".", "Args", "[", "pos", "]", ")", "{", "if", "cmd", ".", "Args", "[", "pos", "]", ".", "(", "FuzzyMatcher", ")", ".", "Match", "(", "args", "[", "pos", "]", ")", "==", "false", "{", "return", "false", "\n", "}", "\n", "}", "else", "if", "reflect", ".", "DeepEqual", "(", "cmd", ".", "Args", "[", "pos", "]", ",", "args", "[", "pos", "]", ")", "==", "false", "{", "return", "false", "\n", "}", "\n\n", "}", "\n", "return", "true", "\n", "}" ]
// match check if provided arguments can be matched with any registered // commands
[ "match", "check", "if", "provided", "arguments", "can", "be", "matched", "with", "any", "registered", "commands" ]
257e089e14a15ee7bf9e8e845fd1229b6bf80048
https://github.com/rafaeljusto/redigomock/blob/257e089e14a15ee7bf9e8e845fd1229b6bf80048/command.go#L54-L70
1,518
rafaeljusto/redigomock
command.go
Expect
func (c *Cmd) Expect(response interface{}) *Cmd { c.Responses = append(c.Responses, Response{response, nil}) return c }
go
func (c *Cmd) Expect(response interface{}) *Cmd { c.Responses = append(c.Responses, Response{response, nil}) return c }
[ "func", "(", "c", "*", "Cmd", ")", "Expect", "(", "response", "interface", "{", "}", ")", "*", "Cmd", "{", "c", ".", "Responses", "=", "append", "(", "c", ".", "Responses", ",", "Response", "{", "response", ",", "nil", "}", ")", "\n", "return", "c", "\n", "}" ]
// Expect sets a response for this command. Every time a Do or Receive method // is executed for a registered command this response or error will be // returned. Expect call returns a pointer to Cmd struct, so you can chain // Expect calls. Chained responses will be returned on subsequent calls // matching this commands arguments in FIFO order
[ "Expect", "sets", "a", "response", "for", "this", "command", ".", "Every", "time", "a", "Do", "or", "Receive", "method", "is", "executed", "for", "a", "registered", "command", "this", "response", "or", "error", "will", "be", "returned", ".", "Expect", "call", "returns", "a", "pointer", "to", "Cmd", "struct", "so", "you", "can", "chain", "Expect", "calls", ".", "Chained", "responses", "will", "be", "returned", "on", "subsequent", "calls", "matching", "this", "commands", "arguments", "in", "FIFO", "order" ]
257e089e14a15ee7bf9e8e845fd1229b6bf80048
https://github.com/rafaeljusto/redigomock/blob/257e089e14a15ee7bf9e8e845fd1229b6bf80048/command.go#L77-L80
1,519
rafaeljusto/redigomock
command.go
ExpectStringSlice
func (c *Cmd) ExpectStringSlice(resp ...string) *Cmd { response := []interface{}{} for _, r := range resp { response = append(response, []byte(r)) } c.Responses = append(c.Responses, Response{response, nil}) return c }
go
func (c *Cmd) ExpectStringSlice(resp ...string) *Cmd { response := []interface{}{} for _, r := range resp { response = append(response, []byte(r)) } c.Responses = append(c.Responses, Response{response, nil}) return c }
[ "func", "(", "c", "*", "Cmd", ")", "ExpectStringSlice", "(", "resp", "...", "string", ")", "*", "Cmd", "{", "response", ":=", "[", "]", "interface", "{", "}", "{", "}", "\n", "for", "_", ",", "r", ":=", "range", "resp", "{", "response", "=", "append", "(", "response", ",", "[", "]", "byte", "(", "r", ")", ")", "\n", "}", "\n", "c", ".", "Responses", "=", "append", "(", "c", ".", "Responses", ",", "Response", "{", "response", ",", "nil", "}", ")", "\n", "return", "c", "\n", "}" ]
// ExpectStringSlice makes it easier to expect a slice of strings, plays nicely // with redigo.Strings
[ "ExpectStringSlice", "makes", "it", "easier", "to", "expect", "a", "slice", "of", "strings", "plays", "nicely", "with", "redigo", ".", "Strings" ]
257e089e14a15ee7bf9e8e845fd1229b6bf80048
https://github.com/rafaeljusto/redigomock/blob/257e089e14a15ee7bf9e8e845fd1229b6bf80048/command.go#L114-L121
1,520
rafaeljusto/redigomock
command.go
hash
func (c Cmd) hash() cmdHash { output := c.Name for _, arg := range c.Args { output += fmt.Sprintf("%v", arg) } return cmdHash(output) }
go
func (c Cmd) hash() cmdHash { output := c.Name for _, arg := range c.Args { output += fmt.Sprintf("%v", arg) } return cmdHash(output) }
[ "func", "(", "c", "Cmd", ")", "hash", "(", ")", "cmdHash", "{", "output", ":=", "c", ".", "Name", "\n", "for", "_", ",", "arg", ":=", "range", "c", ".", "Args", "{", "output", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "arg", ")", "\n", "}", "\n", "return", "cmdHash", "(", "output", ")", "\n", "}" ]
// hash generates a unique identifier for the command
[ "hash", "generates", "a", "unique", "identifier", "for", "the", "command" ]
257e089e14a15ee7bf9e8e845fd1229b6bf80048
https://github.com/rafaeljusto/redigomock/blob/257e089e14a15ee7bf9e8e845fd1229b6bf80048/command.go#L124-L130
1,521
rafaeljusto/redigomock
redigomock.go
NewConn
func NewConn() *Conn { return &Conn{ ReceiveNow: make(chan bool), stats: make(map[cmdHash]int), } }
go
func NewConn() *Conn { return &Conn{ ReceiveNow: make(chan bool), stats: make(map[cmdHash]int), } }
[ "func", "NewConn", "(", ")", "*", "Conn", "{", "return", "&", "Conn", "{", "ReceiveNow", ":", "make", "(", "chan", "bool", ")", ",", "stats", ":", "make", "(", "map", "[", "cmdHash", "]", "int", ")", ",", "}", "\n", "}" ]
// NewConn returns a new mocked connection. Obviously as we are mocking we // don't need any Redis connection parameter
[ "NewConn", "returns", "a", "new", "mocked", "connection", ".", "Obviously", "as", "we", "are", "mocking", "we", "don", "t", "need", "any", "Redis", "connection", "parameter" ]
257e089e14a15ee7bf9e8e845fd1229b6bf80048
https://github.com/rafaeljusto/redigomock/blob/257e089e14a15ee7bf9e8e845fd1229b6bf80048/redigomock.go#L44-L49
1,522
rafaeljusto/redigomock
redigomock.go
Close
func (c *Conn) Close() error { if c.CloseMock == nil { return nil } return c.CloseMock() }
go
func (c *Conn) Close() error { if c.CloseMock == nil { return nil } return c.CloseMock() }
[ "func", "(", "c", "*", "Conn", ")", "Close", "(", ")", "error", "{", "if", "c", ".", "CloseMock", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "return", "c", ".", "CloseMock", "(", ")", "\n", "}" ]
// Close can be mocked using the Conn struct attributes
[ "Close", "can", "be", "mocked", "using", "the", "Conn", "struct", "attributes" ]
257e089e14a15ee7bf9e8e845fd1229b6bf80048
https://github.com/rafaeljusto/redigomock/blob/257e089e14a15ee7bf9e8e845fd1229b6bf80048/redigomock.go#L52-L58
1,523
rafaeljusto/redigomock
redigomock.go
Err
func (c *Conn) Err() error { if c.ErrMock == nil { return nil } return c.ErrMock() }
go
func (c *Conn) Err() error { if c.ErrMock == nil { return nil } return c.ErrMock() }
[ "func", "(", "c", "*", "Conn", ")", "Err", "(", ")", "error", "{", "if", "c", ".", "ErrMock", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "return", "c", ".", "ErrMock", "(", ")", "\n", "}" ]
// Err can be mocked using the Conn struct attributes
[ "Err", "can", "be", "mocked", "using", "the", "Conn", "struct", "attributes" ]
257e089e14a15ee7bf9e8e845fd1229b6bf80048
https://github.com/rafaeljusto/redigomock/blob/257e089e14a15ee7bf9e8e845fd1229b6bf80048/redigomock.go#L61-L67
1,524
rafaeljusto/redigomock
redigomock.go
Command
func (c *Conn) Command(commandName string, args ...interface{}) *Cmd { cmd := &Cmd{ Name: commandName, Args: args, } c.removeRelatedCommands(commandName, args) c.commands = append(c.commands, cmd) return cmd }
go
func (c *Conn) Command(commandName string, args ...interface{}) *Cmd { cmd := &Cmd{ Name: commandName, Args: args, } c.removeRelatedCommands(commandName, args) c.commands = append(c.commands, cmd) return cmd }
[ "func", "(", "c", "*", "Conn", ")", "Command", "(", "commandName", "string", ",", "args", "...", "interface", "{", "}", ")", "*", "Cmd", "{", "cmd", ":=", "&", "Cmd", "{", "Name", ":", "commandName", ",", "Args", ":", "args", ",", "}", "\n", "c", ".", "removeRelatedCommands", "(", "commandName", ",", "args", ")", "\n", "c", ".", "commands", "=", "append", "(", "c", ".", "commands", ",", "cmd", ")", "\n", "return", "cmd", "\n", "}" ]
// Command register a command in the mock system using the same arguments of // a Do or Send commands. It will return a registered command object where // you can set the response or error
[ "Command", "register", "a", "command", "in", "the", "mock", "system", "using", "the", "same", "arguments", "of", "a", "Do", "or", "Send", "commands", ".", "It", "will", "return", "a", "registered", "command", "object", "where", "you", "can", "set", "the", "response", "or", "error" ]
257e089e14a15ee7bf9e8e845fd1229b6bf80048
https://github.com/rafaeljusto/redigomock/blob/257e089e14a15ee7bf9e8e845fd1229b6bf80048/redigomock.go#L72-L80
1,525
rafaeljusto/redigomock
redigomock.go
GenericCommand
func (c *Conn) GenericCommand(commandName string) *Cmd { cmd := &Cmd{ Name: commandName, } c.removeRelatedCommands(commandName, nil) c.commands = append(c.commands, cmd) return cmd }
go
func (c *Conn) GenericCommand(commandName string) *Cmd { cmd := &Cmd{ Name: commandName, } c.removeRelatedCommands(commandName, nil) c.commands = append(c.commands, cmd) return cmd }
[ "func", "(", "c", "*", "Conn", ")", "GenericCommand", "(", "commandName", "string", ")", "*", "Cmd", "{", "cmd", ":=", "&", "Cmd", "{", "Name", ":", "commandName", ",", "}", "\n\n", "c", ".", "removeRelatedCommands", "(", "commandName", ",", "nil", ")", "\n", "c", ".", "commands", "=", "append", "(", "c", ".", "commands", ",", "cmd", ")", "\n", "return", "cmd", "\n", "}" ]
// GenericCommand register a command without arguments. If a command with // arguments doesn't match with any registered command, it will look for // generic commands before throwing an error
[ "GenericCommand", "register", "a", "command", "without", "arguments", ".", "If", "a", "command", "with", "arguments", "doesn", "t", "match", "with", "any", "registered", "command", "it", "will", "look", "for", "generic", "commands", "before", "throwing", "an", "error" ]
257e089e14a15ee7bf9e8e845fd1229b6bf80048
https://github.com/rafaeljusto/redigomock/blob/257e089e14a15ee7bf9e8e845fd1229b6bf80048/redigomock.go#L101-L109
1,526
rafaeljusto/redigomock
redigomock.go
find
func (c *Conn) find(commandName string, args []interface{}) *Cmd { for _, cmd := range c.commands { if match(commandName, args, cmd) { return cmd } } return nil }
go
func (c *Conn) find(commandName string, args []interface{}) *Cmd { for _, cmd := range c.commands { if match(commandName, args, cmd) { return cmd } } return nil }
[ "func", "(", "c", "*", "Conn", ")", "find", "(", "commandName", "string", ",", "args", "[", "]", "interface", "{", "}", ")", "*", "Cmd", "{", "for", "_", ",", "cmd", ":=", "range", "c", ".", "commands", "{", "if", "match", "(", "commandName", ",", "args", ",", "cmd", ")", "{", "return", "cmd", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// find will scan the registered commands, looking for the first command with // the same name and arguments. If the command is not found nil is returned
[ "find", "will", "scan", "the", "registered", "commands", "looking", "for", "the", "first", "command", "with", "the", "same", "name", "and", "arguments", ".", "If", "the", "command", "is", "not", "found", "nil", "is", "returned" ]
257e089e14a15ee7bf9e8e845fd1229b6bf80048
https://github.com/rafaeljusto/redigomock/blob/257e089e14a15ee7bf9e8e845fd1229b6bf80048/redigomock.go#L113-L120
1,527
rafaeljusto/redigomock
redigomock.go
removeRelatedCommands
func (c *Conn) removeRelatedCommands(commandName string, args []interface{}) { var unique []*Cmd for _, cmd := range c.commands { // new array will contain only commands that are not related to the given // one if !equal(commandName, args, cmd) { unique = append(unique, cmd) } } c.commands = unique }
go
func (c *Conn) removeRelatedCommands(commandName string, args []interface{}) { var unique []*Cmd for _, cmd := range c.commands { // new array will contain only commands that are not related to the given // one if !equal(commandName, args, cmd) { unique = append(unique, cmd) } } c.commands = unique }
[ "func", "(", "c", "*", "Conn", ")", "removeRelatedCommands", "(", "commandName", "string", ",", "args", "[", "]", "interface", "{", "}", ")", "{", "var", "unique", "[", "]", "*", "Cmd", "\n\n", "for", "_", ",", "cmd", ":=", "range", "c", ".", "commands", "{", "// new array will contain only commands that are not related to the given", "// one", "if", "!", "equal", "(", "commandName", ",", "args", ",", "cmd", ")", "{", "unique", "=", "append", "(", "unique", ",", "cmd", ")", "\n", "}", "\n", "}", "\n", "c", ".", "commands", "=", "unique", "\n", "}" ]
// removeRelatedCommands verify if a command is already registered, removing // any command already registered with the same name and arguments. This // should avoid duplicated mocked commands
[ "removeRelatedCommands", "verify", "if", "a", "command", "is", "already", "registered", "removing", "any", "command", "already", "registered", "with", "the", "same", "name", "and", "arguments", ".", "This", "should", "avoid", "duplicated", "mocked", "commands" ]
257e089e14a15ee7bf9e8e845fd1229b6bf80048
https://github.com/rafaeljusto/redigomock/blob/257e089e14a15ee7bf9e8e845fd1229b6bf80048/redigomock.go#L125-L136
1,528
rafaeljusto/redigomock
redigomock.go
Clear
func (c *Conn) Clear() { c.statsMut.Lock() defer c.statsMut.Unlock() c.commands = []*Cmd{} c.queue = []queueElement{} c.replies = []replyElement{} c.stats = make(map[cmdHash]int) }
go
func (c *Conn) Clear() { c.statsMut.Lock() defer c.statsMut.Unlock() c.commands = []*Cmd{} c.queue = []queueElement{} c.replies = []replyElement{} c.stats = make(map[cmdHash]int) }
[ "func", "(", "c", "*", "Conn", ")", "Clear", "(", ")", "{", "c", ".", "statsMut", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "statsMut", ".", "Unlock", "(", ")", "\n\n", "c", ".", "commands", "=", "[", "]", "*", "Cmd", "{", "}", "\n", "c", ".", "queue", "=", "[", "]", "queueElement", "{", "}", "\n", "c", ".", "replies", "=", "[", "]", "replyElement", "{", "}", "\n", "c", ".", "stats", "=", "make", "(", "map", "[", "cmdHash", "]", "int", ")", "\n", "}" ]
// Clear removes all registered commands. Useful for connection reuse in test // scenarios
[ "Clear", "removes", "all", "registered", "commands", ".", "Useful", "for", "connection", "reuse", "in", "test", "scenarios" ]
257e089e14a15ee7bf9e8e845fd1229b6bf80048
https://github.com/rafaeljusto/redigomock/blob/257e089e14a15ee7bf9e8e845fd1229b6bf80048/redigomock.go#L140-L148
1,529
rafaeljusto/redigomock
redigomock.go
DoWithTimeout
func (c *Conn) DoWithTimeout(readTimeout time.Duration, cmd string, args ...interface{}) (interface{}, error) { return c.Do(cmd, args...) }
go
func (c *Conn) DoWithTimeout(readTimeout time.Duration, cmd string, args ...interface{}) (interface{}, error) { return c.Do(cmd, args...) }
[ "func", "(", "c", "*", "Conn", ")", "DoWithTimeout", "(", "readTimeout", "time", ".", "Duration", ",", "cmd", "string", ",", "args", "...", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "return", "c", ".", "Do", "(", "cmd", ",", "args", "...", ")", "\n", "}" ]
// DoWithTimeout is a helper function for Do call to satisfy the ConnWithTimeout // interface.
[ "DoWithTimeout", "is", "a", "helper", "function", "for", "Do", "call", "to", "satisfy", "the", "ConnWithTimeout", "interface", "." ]
257e089e14a15ee7bf9e8e845fd1229b6bf80048
https://github.com/rafaeljusto/redigomock/blob/257e089e14a15ee7bf9e8e845fd1229b6bf80048/redigomock.go#L230-L232
1,530
rafaeljusto/redigomock
redigomock.go
Flush
func (c *Conn) Flush() error { if c.FlushMock != nil { return c.FlushMock() } if len(c.queue) > 0 { for _, cmd := range c.queue { reply, err := c.do(cmd.commandName, cmd.args...) c.replies = append(c.replies, replyElement{reply: reply, err: err}) } c.queue = []queueElement{} } return nil }
go
func (c *Conn) Flush() error { if c.FlushMock != nil { return c.FlushMock() } if len(c.queue) > 0 { for _, cmd := range c.queue { reply, err := c.do(cmd.commandName, cmd.args...) c.replies = append(c.replies, replyElement{reply: reply, err: err}) } c.queue = []queueElement{} } return nil }
[ "func", "(", "c", "*", "Conn", ")", "Flush", "(", ")", "error", "{", "if", "c", ".", "FlushMock", "!=", "nil", "{", "return", "c", ".", "FlushMock", "(", ")", "\n", "}", "\n\n", "if", "len", "(", "c", ".", "queue", ")", ">", "0", "{", "for", "_", ",", "cmd", ":=", "range", "c", ".", "queue", "{", "reply", ",", "err", ":=", "c", ".", "do", "(", "cmd", ".", "commandName", ",", "cmd", ".", "args", "...", ")", "\n", "c", ".", "replies", "=", "append", "(", "c", ".", "replies", ",", "replyElement", "{", "reply", ":", "reply", ",", "err", ":", "err", "}", ")", "\n", "}", "\n", "c", ".", "queue", "=", "[", "]", "queueElement", "{", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Flush can be mocked using the Conn struct attributes
[ "Flush", "can", "be", "mocked", "using", "the", "Conn", "struct", "attributes" ]
257e089e14a15ee7bf9e8e845fd1229b6bf80048
https://github.com/rafaeljusto/redigomock/blob/257e089e14a15ee7bf9e8e845fd1229b6bf80048/redigomock.go#L245-L259
1,531
rafaeljusto/redigomock
redigomock.go
AddSubscriptionMessage
func (c *Conn) AddSubscriptionMessage(msg interface{}) { resp := Response{} resp.Response = msg c.SubResponses = append(c.SubResponses, resp) }
go
func (c *Conn) AddSubscriptionMessage(msg interface{}) { resp := Response{} resp.Response = msg c.SubResponses = append(c.SubResponses, resp) }
[ "func", "(", "c", "*", "Conn", ")", "AddSubscriptionMessage", "(", "msg", "interface", "{", "}", ")", "{", "resp", ":=", "Response", "{", "}", "\n", "resp", ".", "Response", "=", "msg", "\n", "c", ".", "SubResponses", "=", "append", "(", "c", ".", "SubResponses", ",", "resp", ")", "\n", "}" ]
// AddSubscriptionMessage register a response to be returned by the receive // call.
[ "AddSubscriptionMessage", "register", "a", "response", "to", "be", "returned", "by", "the", "receive", "call", "." ]
257e089e14a15ee7bf9e8e845fd1229b6bf80048
https://github.com/rafaeljusto/redigomock/blob/257e089e14a15ee7bf9e8e845fd1229b6bf80048/redigomock.go#L263-L267
1,532
rafaeljusto/redigomock
redigomock.go
Receive
func (c *Conn) Receive() (reply interface{}, err error) { if c.ReceiveWait { <-c.ReceiveNow } if len(c.queue) == 0 && len(c.replies) == 0 { if len(c.SubResponses) > 0 { reply, err = c.SubResponses[0].Response, c.SubResponses[0].Error c.SubResponses = c.SubResponses[1:] return } return nil, fmt.Errorf("no more items") } if err := c.Flush(); err != nil { return nil, err } reply, err = c.replies[0].reply, c.replies[0].err c.replies = c.replies[1:] return }
go
func (c *Conn) Receive() (reply interface{}, err error) { if c.ReceiveWait { <-c.ReceiveNow } if len(c.queue) == 0 && len(c.replies) == 0 { if len(c.SubResponses) > 0 { reply, err = c.SubResponses[0].Response, c.SubResponses[0].Error c.SubResponses = c.SubResponses[1:] return } return nil, fmt.Errorf("no more items") } if err := c.Flush(); err != nil { return nil, err } reply, err = c.replies[0].reply, c.replies[0].err c.replies = c.replies[1:] return }
[ "func", "(", "c", "*", "Conn", ")", "Receive", "(", ")", "(", "reply", "interface", "{", "}", ",", "err", "error", ")", "{", "if", "c", ".", "ReceiveWait", "{", "<-", "c", ".", "ReceiveNow", "\n", "}", "\n\n", "if", "len", "(", "c", ".", "queue", ")", "==", "0", "&&", "len", "(", "c", ".", "replies", ")", "==", "0", "{", "if", "len", "(", "c", ".", "SubResponses", ")", ">", "0", "{", "reply", ",", "err", "=", "c", ".", "SubResponses", "[", "0", "]", ".", "Response", ",", "c", ".", "SubResponses", "[", "0", "]", ".", "Error", "\n", "c", ".", "SubResponses", "=", "c", ".", "SubResponses", "[", "1", ":", "]", "\n", "return", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "err", ":=", "c", ".", "Flush", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "reply", ",", "err", "=", "c", ".", "replies", "[", "0", "]", ".", "reply", ",", "c", ".", "replies", "[", "0", "]", ".", "err", "\n", "c", ".", "replies", "=", "c", ".", "replies", "[", "1", ":", "]", "\n", "return", "\n", "}" ]
// Receive will process the queue created by the Send method, only one item // of the queue is processed by Receive call. It will work as the Do method
[ "Receive", "will", "process", "the", "queue", "created", "by", "the", "Send", "method", "only", "one", "item", "of", "the", "queue", "is", "processed", "by", "Receive", "call", ".", "It", "will", "work", "as", "the", "Do", "method" ]
257e089e14a15ee7bf9e8e845fd1229b6bf80048
https://github.com/rafaeljusto/redigomock/blob/257e089e14a15ee7bf9e8e845fd1229b6bf80048/redigomock.go#L271-L292
1,533
rafaeljusto/redigomock
redigomock.go
Stats
func (c *Conn) Stats(cmd *Cmd) int { c.statsMut.RLock() defer c.statsMut.RUnlock() return c.stats[cmd.hash()] }
go
func (c *Conn) Stats(cmd *Cmd) int { c.statsMut.RLock() defer c.statsMut.RUnlock() return c.stats[cmd.hash()] }
[ "func", "(", "c", "*", "Conn", ")", "Stats", "(", "cmd", "*", "Cmd", ")", "int", "{", "c", ".", "statsMut", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "statsMut", ".", "RUnlock", "(", ")", "\n\n", "return", "c", ".", "stats", "[", "cmd", ".", "hash", "(", ")", "]", "\n", "}" ]
// Stats returns the number of times that a command was called in the current // connection
[ "Stats", "returns", "the", "number", "of", "times", "that", "a", "command", "was", "called", "in", "the", "current", "connection" ]
257e089e14a15ee7bf9e8e845fd1229b6bf80048
https://github.com/rafaeljusto/redigomock/blob/257e089e14a15ee7bf9e8e845fd1229b6bf80048/redigomock.go#L302-L307
1,534
rafaeljusto/redigomock
redigomock.go
ExpectationsWereMet
func (c *Conn) ExpectationsWereMet() error { errMsg := "" for _, err := range c.Errors { errMsg = fmt.Sprintf("%s%s\n", errMsg, err.Error()) } for _, cmd := range c.commands { if !cmd.Called { errMsg = fmt.Sprintf("%sCommand %s with arguments %#v expected but never called.\n", errMsg, cmd.Name, cmd.Args) } } if errMsg != "" { return fmt.Errorf("%s", errMsg) } return nil }
go
func (c *Conn) ExpectationsWereMet() error { errMsg := "" for _, err := range c.Errors { errMsg = fmt.Sprintf("%s%s\n", errMsg, err.Error()) } for _, cmd := range c.commands { if !cmd.Called { errMsg = fmt.Sprintf("%sCommand %s with arguments %#v expected but never called.\n", errMsg, cmd.Name, cmd.Args) } } if errMsg != "" { return fmt.Errorf("%s", errMsg) } return nil }
[ "func", "(", "c", "*", "Conn", ")", "ExpectationsWereMet", "(", ")", "error", "{", "errMsg", ":=", "\"", "\"", "\n", "for", "_", ",", "err", ":=", "range", "c", ".", "Errors", "{", "errMsg", "=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "errMsg", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "for", "_", ",", "cmd", ":=", "range", "c", ".", "commands", "{", "if", "!", "cmd", ".", "Called", "{", "errMsg", "=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "errMsg", ",", "cmd", ".", "Name", ",", "cmd", ".", "Args", ")", "\n", "}", "\n", "}", "\n\n", "if", "errMsg", "!=", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "errMsg", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// ExpectationsWereMet can guarantee that all commands that was set on unit tests // called or call of unregistered command can be caught here too
[ "ExpectationsWereMet", "can", "guarantee", "that", "all", "commands", "that", "was", "set", "on", "unit", "tests", "called", "or", "call", "of", "unregistered", "command", "can", "be", "caught", "here", "too" ]
257e089e14a15ee7bf9e8e845fd1229b6bf80048
https://github.com/rafaeljusto/redigomock/blob/257e089e14a15ee7bf9e8e845fd1229b6bf80048/redigomock.go#L311-L328
1,535
oxtoacart/bpool
sizedbufferpool.go
Get
func (bp *SizedBufferPool) Get() (b *bytes.Buffer) { select { case b = <-bp.c: // reuse existing buffer default: // create new buffer b = bytes.NewBuffer(make([]byte, 0, bp.a)) } return }
go
func (bp *SizedBufferPool) Get() (b *bytes.Buffer) { select { case b = <-bp.c: // reuse existing buffer default: // create new buffer b = bytes.NewBuffer(make([]byte, 0, bp.a)) } return }
[ "func", "(", "bp", "*", "SizedBufferPool", ")", "Get", "(", ")", "(", "b", "*", "bytes", ".", "Buffer", ")", "{", "select", "{", "case", "b", "=", "<-", "bp", ".", "c", ":", "// reuse existing buffer", "default", ":", "// create new buffer", "b", "=", "bytes", ".", "NewBuffer", "(", "make", "(", "[", "]", "byte", ",", "0", ",", "bp", ".", "a", ")", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Get gets a Buffer from the SizedBufferPool, or creates a new one if none are // available in the pool. Buffers have a pre-allocated capacity.
[ "Get", "gets", "a", "Buffer", "from", "the", "SizedBufferPool", "or", "creates", "a", "new", "one", "if", "none", "are", "available", "in", "the", "pool", ".", "Buffers", "have", "a", "pre", "-", "allocated", "capacity", "." ]
8c4636f812cc8920c26e2002b988c878b1fd6f5e
https://github.com/oxtoacart/bpool/blob/8c4636f812cc8920c26e2002b988c878b1fd6f5e/sizedbufferpool.go#L32-L41
1,536
oxtoacart/bpool
sizedbufferpool.go
Put
func (bp *SizedBufferPool) Put(b *bytes.Buffer) { b.Reset() // Release buffers over our maximum capacity and re-create a pre-sized // buffer to replace it. // Note that the cap(b.Bytes()) provides the capacity from the read off-set // only, but as we've called b.Reset() the full capacity of the underlying // byte slice is returned. if cap(b.Bytes()) > bp.a { b = bytes.NewBuffer(make([]byte, 0, bp.a)) } select { case bp.c <- b: default: // Discard the buffer if the pool is full. } }
go
func (bp *SizedBufferPool) Put(b *bytes.Buffer) { b.Reset() // Release buffers over our maximum capacity and re-create a pre-sized // buffer to replace it. // Note that the cap(b.Bytes()) provides the capacity from the read off-set // only, but as we've called b.Reset() the full capacity of the underlying // byte slice is returned. if cap(b.Bytes()) > bp.a { b = bytes.NewBuffer(make([]byte, 0, bp.a)) } select { case bp.c <- b: default: // Discard the buffer if the pool is full. } }
[ "func", "(", "bp", "*", "SizedBufferPool", ")", "Put", "(", "b", "*", "bytes", ".", "Buffer", ")", "{", "b", ".", "Reset", "(", ")", "\n\n", "// Release buffers over our maximum capacity and re-create a pre-sized", "// buffer to replace it.", "// Note that the cap(b.Bytes()) provides the capacity from the read off-set", "// only, but as we've called b.Reset() the full capacity of the underlying", "// byte slice is returned.", "if", "cap", "(", "b", ".", "Bytes", "(", ")", ")", ">", "bp", ".", "a", "{", "b", "=", "bytes", ".", "NewBuffer", "(", "make", "(", "[", "]", "byte", ",", "0", ",", "bp", ".", "a", ")", ")", "\n", "}", "\n\n", "select", "{", "case", "bp", ".", "c", "<-", "b", ":", "default", ":", "// Discard the buffer if the pool is full.", "}", "\n", "}" ]
// Put returns the given Buffer to the SizedBufferPool.
[ "Put", "returns", "the", "given", "Buffer", "to", "the", "SizedBufferPool", "." ]
8c4636f812cc8920c26e2002b988c878b1fd6f5e
https://github.com/oxtoacart/bpool/blob/8c4636f812cc8920c26e2002b988c878b1fd6f5e/sizedbufferpool.go#L44-L60
1,537
oxtoacart/bpool
bytepool.go
NewBytePool
func NewBytePool(maxSize int, width int) (bp *BytePool) { return &BytePool{ c: make(chan []byte, maxSize), w: width, } }
go
func NewBytePool(maxSize int, width int) (bp *BytePool) { return &BytePool{ c: make(chan []byte, maxSize), w: width, } }
[ "func", "NewBytePool", "(", "maxSize", "int", ",", "width", "int", ")", "(", "bp", "*", "BytePool", ")", "{", "return", "&", "BytePool", "{", "c", ":", "make", "(", "chan", "[", "]", "byte", ",", "maxSize", ")", ",", "w", ":", "width", ",", "}", "\n", "}" ]
// NewBytePool creates a new BytePool bounded to the given maxSize, with new // byte arrays sized based on width.
[ "NewBytePool", "creates", "a", "new", "BytePool", "bounded", "to", "the", "given", "maxSize", "with", "new", "byte", "arrays", "sized", "based", "on", "width", "." ]
8c4636f812cc8920c26e2002b988c878b1fd6f5e
https://github.com/oxtoacart/bpool/blob/8c4636f812cc8920c26e2002b988c878b1fd6f5e/bytepool.go#L12-L17
1,538
oxtoacart/bpool
bytepool.go
Put
func (bp *BytePool) Put(b []byte) { if cap(b) < bp.w { // someone tried to put back a too small buffer, discard it return } select { case bp.c <- b[:bp.w]: // buffer went back into pool default: // buffer didn't go back into pool, just discard } }
go
func (bp *BytePool) Put(b []byte) { if cap(b) < bp.w { // someone tried to put back a too small buffer, discard it return } select { case bp.c <- b[:bp.w]: // buffer went back into pool default: // buffer didn't go back into pool, just discard } }
[ "func", "(", "bp", "*", "BytePool", ")", "Put", "(", "b", "[", "]", "byte", ")", "{", "if", "cap", "(", "b", ")", "<", "bp", ".", "w", "{", "// someone tried to put back a too small buffer, discard it", "return", "\n", "}", "\n\n", "select", "{", "case", "bp", ".", "c", "<-", "b", "[", ":", "bp", ".", "w", "]", ":", "// buffer went back into pool", "default", ":", "// buffer didn't go back into pool, just discard", "}", "\n", "}" ]
// Put returns the given Buffer to the BytePool.
[ "Put", "returns", "the", "given", "Buffer", "to", "the", "BytePool", "." ]
8c4636f812cc8920c26e2002b988c878b1fd6f5e
https://github.com/oxtoacart/bpool/blob/8c4636f812cc8920c26e2002b988c878b1fd6f5e/bytepool.go#L33-L45
1,539
yvasiyarov/swagger
markup/markup_asciidoc.go
tableHeader
func (this *MarkupAsciiDoc) tableHeader(tableTitle string) string { retval := "\n" if tableTitle != "" { retval += fmt.Sprintf(".%s\n", tableTitle) } return retval + "[width=\"60%\",options=\"header\"]\n|==========\n" }
go
func (this *MarkupAsciiDoc) tableHeader(tableTitle string) string { retval := "\n" if tableTitle != "" { retval += fmt.Sprintf(".%s\n", tableTitle) } return retval + "[width=\"60%\",options=\"header\"]\n|==========\n" }
[ "func", "(", "this", "*", "MarkupAsciiDoc", ")", "tableHeader", "(", "tableTitle", "string", ")", "string", "{", "retval", ":=", "\"", "\\n", "\"", "\n", "if", "tableTitle", "!=", "\"", "\"", "{", "retval", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "tableTitle", ")", "\n", "}", "\n", "return", "retval", "+", "\"", "\\\"", "\\\"", "\\\"", "\\\"", "\\n", "\\n", "\"", "\n", "}" ]
// tableHeader starts a table
[ "tableHeader", "starts", "a", "table" ]
39eb437316e9318213bb9daf3fdc7f7bc5acde38
https://github.com/yvasiyarov/swagger/blob/39eb437316e9318213bb9daf3fdc7f7bc5acde38/markup/markup_asciidoc.go#L40-L46
1,540
yvasiyarov/swagger
markup/markup_asciidoc.go
tableHeaderRow
func (this *MarkupAsciiDoc) tableHeaderRow(args ...string) string { var retval string for _, arg := range args { retval += fmt.Sprintf("|%s ", arg) } return retval + "\n" }
go
func (this *MarkupAsciiDoc) tableHeaderRow(args ...string) string { var retval string for _, arg := range args { retval += fmt.Sprintf("|%s ", arg) } return retval + "\n" }
[ "func", "(", "this", "*", "MarkupAsciiDoc", ")", "tableHeaderRow", "(", "args", "...", "string", ")", "string", "{", "var", "retval", "string", "\n", "for", "_", ",", "arg", ":=", "range", "args", "{", "retval", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "arg", ")", "\n", "}", "\n", "return", "retval", "+", "\"", "\\n", "\"", "\n", "}" ]
// tableRow issues a table header row
[ "tableRow", "issues", "a", "table", "header", "row" ]
39eb437316e9318213bb9daf3fdc7f7bc5acde38
https://github.com/yvasiyarov/swagger/blob/39eb437316e9318213bb9daf3fdc7f7bc5acde38/markup/markup_asciidoc.go#L54-L60
1,541
yvasiyarov/swagger
parser/parser.go
isController
func isController(funcDeclaration *ast.FuncDecl, controllerClass string) bool { if len(controllerClass) == 0 { // Search every method return true } if funcDeclaration.Recv != nil && len(funcDeclaration.Recv.List) > 0 { if starExpression, ok := funcDeclaration.Recv.List[0].Type.(*ast.StarExpr); ok { receiverName := fmt.Sprint(starExpression.X) matched, err := regexp.MatchString(string(controllerClass), receiverName) if err != nil { log.Fatalf("The -controllerClass argument is not a valid regular expression: %v\n", err) } return matched } } return false }
go
func isController(funcDeclaration *ast.FuncDecl, controllerClass string) bool { if len(controllerClass) == 0 { // Search every method return true } if funcDeclaration.Recv != nil && len(funcDeclaration.Recv.List) > 0 { if starExpression, ok := funcDeclaration.Recv.List[0].Type.(*ast.StarExpr); ok { receiverName := fmt.Sprint(starExpression.X) matched, err := regexp.MatchString(string(controllerClass), receiverName) if err != nil { log.Fatalf("The -controllerClass argument is not a valid regular expression: %v\n", err) } return matched } } return false }
[ "func", "isController", "(", "funcDeclaration", "*", "ast", ".", "FuncDecl", ",", "controllerClass", "string", ")", "bool", "{", "if", "len", "(", "controllerClass", ")", "==", "0", "{", "// Search every method", "return", "true", "\n", "}", "\n", "if", "funcDeclaration", ".", "Recv", "!=", "nil", "&&", "len", "(", "funcDeclaration", ".", "Recv", ".", "List", ")", ">", "0", "{", "if", "starExpression", ",", "ok", ":=", "funcDeclaration", ".", "Recv", ".", "List", "[", "0", "]", ".", "Type", ".", "(", "*", "ast", ".", "StarExpr", ")", ";", "ok", "{", "receiverName", ":=", "fmt", ".", "Sprint", "(", "starExpression", ".", "X", ")", "\n", "matched", ",", "err", ":=", "regexp", ".", "MatchString", "(", "string", "(", "controllerClass", ")", ",", "receiverName", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\\n", "\"", ",", "err", ")", "\n", "}", "\n", "return", "matched", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// It must return true if funcDeclaration is controller. We will try to parse only comments before controllers
[ "It", "must", "return", "true", "if", "funcDeclaration", "is", "controller", ".", "We", "will", "try", "to", "parse", "only", "comments", "before", "controllers" ]
39eb437316e9318213bb9daf3fdc7f7bc5acde38
https://github.com/yvasiyarov/swagger/blob/39eb437316e9318213bb9daf3fdc7f7bc5acde38/parser/parser.go#L43-L59
1,542
yvasiyarov/swagger
parser/parser.go
ParseSubApiDescription
func (parser *Parser) ParseSubApiDescription(commentLine string) { if !strings.HasPrefix(commentLine, "@SubApi") { return } else { commentLine = strings.TrimSpace(commentLine[len("@SubApi"):]) } re := regexp.MustCompile(`([^\[]+)\[{1}([\w\_\-/]+)`) if matches := re.FindStringSubmatch(commentLine); len(matches) != 3 { log.Printf("Can not parse sub api description %s, skipped", commentLine) } else { found := false for _, ref := range parser.Listing.Apis { if ref.Path == matches[2] { found = true ref.Description = strings.TrimSpace(matches[1]) } } if !found { subApi := &ApiRef{Path: matches[2], Description: strings.TrimSpace(matches[1]), } parser.Listing.Apis = append(parser.Listing.Apis, subApi) } } }
go
func (parser *Parser) ParseSubApiDescription(commentLine string) { if !strings.HasPrefix(commentLine, "@SubApi") { return } else { commentLine = strings.TrimSpace(commentLine[len("@SubApi"):]) } re := regexp.MustCompile(`([^\[]+)\[{1}([\w\_\-/]+)`) if matches := re.FindStringSubmatch(commentLine); len(matches) != 3 { log.Printf("Can not parse sub api description %s, skipped", commentLine) } else { found := false for _, ref := range parser.Listing.Apis { if ref.Path == matches[2] { found = true ref.Description = strings.TrimSpace(matches[1]) } } if !found { subApi := &ApiRef{Path: matches[2], Description: strings.TrimSpace(matches[1]), } parser.Listing.Apis = append(parser.Listing.Apis, subApi) } } }
[ "func", "(", "parser", "*", "Parser", ")", "ParseSubApiDescription", "(", "commentLine", "string", ")", "{", "if", "!", "strings", ".", "HasPrefix", "(", "commentLine", ",", "\"", "\"", ")", "{", "return", "\n", "}", "else", "{", "commentLine", "=", "strings", ".", "TrimSpace", "(", "commentLine", "[", "len", "(", "\"", "\"", ")", ":", "]", ")", "\n", "}", "\n", "re", ":=", "regexp", ".", "MustCompile", "(", "`([^\\[]+)\\[{1}([\\w\\_\\-/]+)`", ")", "\n\n", "if", "matches", ":=", "re", ".", "FindStringSubmatch", "(", "commentLine", ")", ";", "len", "(", "matches", ")", "!=", "3", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "commentLine", ")", "\n", "}", "else", "{", "found", ":=", "false", "\n", "for", "_", ",", "ref", ":=", "range", "parser", ".", "Listing", ".", "Apis", "{", "if", "ref", ".", "Path", "==", "matches", "[", "2", "]", "{", "found", "=", "true", "\n", "ref", ".", "Description", "=", "strings", ".", "TrimSpace", "(", "matches", "[", "1", "]", ")", "\n", "}", "\n", "}", "\n", "if", "!", "found", "{", "subApi", ":=", "&", "ApiRef", "{", "Path", ":", "matches", "[", "2", "]", ",", "Description", ":", "strings", ".", "TrimSpace", "(", "matches", "[", "1", "]", ")", ",", "}", "\n", "parser", ".", "Listing", ".", "Apis", "=", "append", "(", "parser", ".", "Listing", ".", "Apis", ",", "subApi", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Parse sub api declaration // @SubApi Very fancy API [/fancy-api]
[ "Parse", "sub", "api", "declaration" ]
39eb437316e9318213bb9daf3fdc7f7bc5acde38
https://github.com/yvasiyarov/swagger/blob/39eb437316e9318213bb9daf3fdc7f7bc5acde38/parser/parser.go#L543-L568
1,543
yvasiyarov/swagger
markup/markup_markdown.go
tableHeaderRow
func (this *MarkupMarkDown) tableHeaderRow(args ...string) string { var retval string = "" var separator string = "" for _, arg := range args { retval += fmt.Sprintf("| %s ", arg) separator += "|-----" } return retval + "|\n" + separator + "|\n" }
go
func (this *MarkupMarkDown) tableHeaderRow(args ...string) string { var retval string = "" var separator string = "" for _, arg := range args { retval += fmt.Sprintf("| %s ", arg) separator += "|-----" } return retval + "|\n" + separator + "|\n" }
[ "func", "(", "this", "*", "MarkupMarkDown", ")", "tableHeaderRow", "(", "args", "...", "string", ")", "string", "{", "var", "retval", "string", "=", "\"", "\"", "\n", "var", "separator", "string", "=", "\"", "\"", "\n", "for", "_", ",", "arg", ":=", "range", "args", "{", "retval", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "arg", ")", "\n", "separator", "+=", "\"", "\"", "\n", "}", "\n", "return", "retval", "+", "\"", "\\n", "\"", "+", "separator", "+", "\"", "\\n", "\"", "\n", "}" ]
// tableHeaderRow issues a table header row
[ "tableHeaderRow", "issues", "a", "table", "header", "row" ]
39eb437316e9318213bb9daf3fdc7f7bc5acde38
https://github.com/yvasiyarov/swagger/blob/39eb437316e9318213bb9daf3fdc7f7bc5acde38/markup/markup_markdown.go#L45-L53
1,544
yvasiyarov/swagger
parser/model.go
ParseModel
func (m *Model) ParseModel(modelName string, currentPackage string, knownModelNames map[string]bool) (error, []*Model) { knownModelNames[modelName] = true //log.Printf("Before parse model |%s|, package: |%s|\n", modelName, currentPackage) astTypeSpec, modelPackage := m.parser.FindModelDefinition(modelName, currentPackage) modelNameParts := strings.Split(modelName, ".") m.Id = strings.Join(append(strings.Split(modelPackage, "/"), modelNameParts[len(modelNameParts)-1]), ".") var innerModelList []*Model if astTypeDef, ok := astTypeSpec.Type.(*ast.Ident); ok { typeDefTranslations[astTypeSpec.Name.String()] = astTypeDef.Name } else if astStructType, ok := astTypeSpec.Type.(*ast.StructType); ok { m.ParseFieldList(astStructType.Fields.List, modelPackage) usedTypes := make(map[string]bool) for _, property := range m.Properties { typeName := property.Type if typeName == "array" { if property.Items.Type != "" { typeName = property.Items.Type } else { typeName = property.Items.Ref } } if translation, ok := typeDefTranslations[typeName]; ok { typeName = translation } if IsBasicType(typeName) || m.parser.IsImplementMarshalInterface(typeName) { continue } if _, exists := knownModelNames[typeName]; exists { continue } usedTypes[typeName] = true } //log.Printf("Before parse inner model list: %#v\n (%s)", usedTypes, modelName) innerModelList = make([]*Model, 0, len(usedTypes)) for typeName, _ := range usedTypes { typeModel := NewModel(m.parser) if err, typeInnerModels := typeModel.ParseModel(typeName, modelPackage, knownModelNames); err != nil { //log.Printf("Parse Inner Model error %#v \n", err) return err, nil } else { for _, property := range m.Properties { if property.Type == "array" { if property.Items.Ref == typeName { property.Items.Ref = typeModel.Id } } else { if property.Type == typeName { property.Type = typeModel.Id } } } //log.Printf("Inner model %v parsed, parsing %s \n", typeName, modelName) if typeModel != nil { innerModelList = append(innerModelList, typeModel) } if typeInnerModels != nil && len(typeInnerModels) > 0 { innerModelList = append(innerModelList, typeInnerModels...) } //log.Printf("innerModelList: %#v\n, typeInnerModels: %#v, usedTypes: %#v \n", innerModelList, typeInnerModels, usedTypes) } } //log.Printf("After parse inner model list: %#v\n (%s)", usedTypes, modelName) // log.Fatalf("Inner model list: %#v\n", innerModelList) } //log.Printf("ParseModel finished %s \n", modelName) return nil, innerModelList }
go
func (m *Model) ParseModel(modelName string, currentPackage string, knownModelNames map[string]bool) (error, []*Model) { knownModelNames[modelName] = true //log.Printf("Before parse model |%s|, package: |%s|\n", modelName, currentPackage) astTypeSpec, modelPackage := m.parser.FindModelDefinition(modelName, currentPackage) modelNameParts := strings.Split(modelName, ".") m.Id = strings.Join(append(strings.Split(modelPackage, "/"), modelNameParts[len(modelNameParts)-1]), ".") var innerModelList []*Model if astTypeDef, ok := astTypeSpec.Type.(*ast.Ident); ok { typeDefTranslations[astTypeSpec.Name.String()] = astTypeDef.Name } else if astStructType, ok := astTypeSpec.Type.(*ast.StructType); ok { m.ParseFieldList(astStructType.Fields.List, modelPackage) usedTypes := make(map[string]bool) for _, property := range m.Properties { typeName := property.Type if typeName == "array" { if property.Items.Type != "" { typeName = property.Items.Type } else { typeName = property.Items.Ref } } if translation, ok := typeDefTranslations[typeName]; ok { typeName = translation } if IsBasicType(typeName) || m.parser.IsImplementMarshalInterface(typeName) { continue } if _, exists := knownModelNames[typeName]; exists { continue } usedTypes[typeName] = true } //log.Printf("Before parse inner model list: %#v\n (%s)", usedTypes, modelName) innerModelList = make([]*Model, 0, len(usedTypes)) for typeName, _ := range usedTypes { typeModel := NewModel(m.parser) if err, typeInnerModels := typeModel.ParseModel(typeName, modelPackage, knownModelNames); err != nil { //log.Printf("Parse Inner Model error %#v \n", err) return err, nil } else { for _, property := range m.Properties { if property.Type == "array" { if property.Items.Ref == typeName { property.Items.Ref = typeModel.Id } } else { if property.Type == typeName { property.Type = typeModel.Id } } } //log.Printf("Inner model %v parsed, parsing %s \n", typeName, modelName) if typeModel != nil { innerModelList = append(innerModelList, typeModel) } if typeInnerModels != nil && len(typeInnerModels) > 0 { innerModelList = append(innerModelList, typeInnerModels...) } //log.Printf("innerModelList: %#v\n, typeInnerModels: %#v, usedTypes: %#v \n", innerModelList, typeInnerModels, usedTypes) } } //log.Printf("After parse inner model list: %#v\n (%s)", usedTypes, modelName) // log.Fatalf("Inner model list: %#v\n", innerModelList) } //log.Printf("ParseModel finished %s \n", modelName) return nil, innerModelList }
[ "func", "(", "m", "*", "Model", ")", "ParseModel", "(", "modelName", "string", ",", "currentPackage", "string", ",", "knownModelNames", "map", "[", "string", "]", "bool", ")", "(", "error", ",", "[", "]", "*", "Model", ")", "{", "knownModelNames", "[", "modelName", "]", "=", "true", "\n", "//log.Printf(\"Before parse model |%s|, package: |%s|\\n\", modelName, currentPackage)", "astTypeSpec", ",", "modelPackage", ":=", "m", ".", "parser", ".", "FindModelDefinition", "(", "modelName", ",", "currentPackage", ")", "\n\n", "modelNameParts", ":=", "strings", ".", "Split", "(", "modelName", ",", "\"", "\"", ")", "\n", "m", ".", "Id", "=", "strings", ".", "Join", "(", "append", "(", "strings", ".", "Split", "(", "modelPackage", ",", "\"", "\"", ")", ",", "modelNameParts", "[", "len", "(", "modelNameParts", ")", "-", "1", "]", ")", ",", "\"", "\"", ")", "\n\n", "var", "innerModelList", "[", "]", "*", "Model", "\n", "if", "astTypeDef", ",", "ok", ":=", "astTypeSpec", ".", "Type", ".", "(", "*", "ast", ".", "Ident", ")", ";", "ok", "{", "typeDefTranslations", "[", "astTypeSpec", ".", "Name", ".", "String", "(", ")", "]", "=", "astTypeDef", ".", "Name", "\n", "}", "else", "if", "astStructType", ",", "ok", ":=", "astTypeSpec", ".", "Type", ".", "(", "*", "ast", ".", "StructType", ")", ";", "ok", "{", "m", ".", "ParseFieldList", "(", "astStructType", ".", "Fields", ".", "List", ",", "modelPackage", ")", "\n", "usedTypes", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n\n", "for", "_", ",", "property", ":=", "range", "m", ".", "Properties", "{", "typeName", ":=", "property", ".", "Type", "\n", "if", "typeName", "==", "\"", "\"", "{", "if", "property", ".", "Items", ".", "Type", "!=", "\"", "\"", "{", "typeName", "=", "property", ".", "Items", ".", "Type", "\n", "}", "else", "{", "typeName", "=", "property", ".", "Items", ".", "Ref", "\n", "}", "\n", "}", "\n", "if", "translation", ",", "ok", ":=", "typeDefTranslations", "[", "typeName", "]", ";", "ok", "{", "typeName", "=", "translation", "\n", "}", "\n", "if", "IsBasicType", "(", "typeName", ")", "||", "m", ".", "parser", ".", "IsImplementMarshalInterface", "(", "typeName", ")", "{", "continue", "\n", "}", "\n", "if", "_", ",", "exists", ":=", "knownModelNames", "[", "typeName", "]", ";", "exists", "{", "continue", "\n", "}", "\n\n", "usedTypes", "[", "typeName", "]", "=", "true", "\n", "}", "\n\n", "//log.Printf(\"Before parse inner model list: %#v\\n (%s)\", usedTypes, modelName)", "innerModelList", "=", "make", "(", "[", "]", "*", "Model", ",", "0", ",", "len", "(", "usedTypes", ")", ")", "\n\n", "for", "typeName", ",", "_", ":=", "range", "usedTypes", "{", "typeModel", ":=", "NewModel", "(", "m", ".", "parser", ")", "\n", "if", "err", ",", "typeInnerModels", ":=", "typeModel", ".", "ParseModel", "(", "typeName", ",", "modelPackage", ",", "knownModelNames", ")", ";", "err", "!=", "nil", "{", "//log.Printf(\"Parse Inner Model error %#v \\n\", err)", "return", "err", ",", "nil", "\n", "}", "else", "{", "for", "_", ",", "property", ":=", "range", "m", ".", "Properties", "{", "if", "property", ".", "Type", "==", "\"", "\"", "{", "if", "property", ".", "Items", ".", "Ref", "==", "typeName", "{", "property", ".", "Items", ".", "Ref", "=", "typeModel", ".", "Id", "\n", "}", "\n", "}", "else", "{", "if", "property", ".", "Type", "==", "typeName", "{", "property", ".", "Type", "=", "typeModel", ".", "Id", "\n", "}", "\n", "}", "\n", "}", "\n", "//log.Printf(\"Inner model %v parsed, parsing %s \\n\", typeName, modelName)", "if", "typeModel", "!=", "nil", "{", "innerModelList", "=", "append", "(", "innerModelList", ",", "typeModel", ")", "\n", "}", "\n", "if", "typeInnerModels", "!=", "nil", "&&", "len", "(", "typeInnerModels", ")", ">", "0", "{", "innerModelList", "=", "append", "(", "innerModelList", ",", "typeInnerModels", "...", ")", "\n", "}", "\n", "//log.Printf(\"innerModelList: %#v\\n, typeInnerModels: %#v, usedTypes: %#v \\n\", innerModelList, typeInnerModels, usedTypes)", "}", "\n", "}", "\n", "//log.Printf(\"After parse inner model list: %#v\\n (%s)\", usedTypes, modelName)", "// log.Fatalf(\"Inner model list: %#v\\n\", innerModelList)", "}", "\n\n", "//log.Printf(\"ParseModel finished %s \\n\", modelName)", "return", "nil", ",", "innerModelList", "\n", "}" ]
// modelName is something like package.subpackage.SomeModel or just "subpackage.SomeModel"
[ "modelName", "is", "something", "like", "package", ".", "subpackage", ".", "SomeModel", "or", "just", "subpackage", ".", "SomeModel" ]
39eb437316e9318213bb9daf3fdc7f7bc5acde38
https://github.com/yvasiyarov/swagger/blob/39eb437316e9318213bb9daf3fdc7f7bc5acde38/parser/model.go#L25-L100
1,545
yvasiyarov/swagger
utils/utils.go
GetGoVars
func GetGoVars() (string, string, error) { gopath := os.Getenv("GOPATH") if gopath == "" { return "", "", errors.New("Please set the $GOPATH environment variable") } goroot := filepath.Clean(runtime.GOROOT()) if goroot == "" { return "", "", errors.New("Please set $GOROOT environment variable") } return gopath, goroot, nil }
go
func GetGoVars() (string, string, error) { gopath := os.Getenv("GOPATH") if gopath == "" { return "", "", errors.New("Please set the $GOPATH environment variable") } goroot := filepath.Clean(runtime.GOROOT()) if goroot == "" { return "", "", errors.New("Please set $GOROOT environment variable") } return gopath, goroot, nil }
[ "func", "GetGoVars", "(", ")", "(", "string", ",", "string", ",", "error", ")", "{", "gopath", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", "\n", "if", "gopath", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "goroot", ":=", "filepath", ".", "Clean", "(", "runtime", ".", "GOROOT", "(", ")", ")", "\n", "if", "goroot", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "gopath", ",", "goroot", ",", "nil", "\n", "}" ]
// return gopath, goroot, err
[ "return", "gopath", "goroot", "err" ]
39eb437316e9318213bb9daf3fdc7f7bc5acde38
https://github.com/yvasiyarov/swagger/blob/39eb437316e9318213bb9daf3fdc7f7bc5acde38/utils/utils.go#L21-L33
1,546
hashicorp/consul-migrate
main.go
handleProgress
func handleProgress(ch <-chan *migrator.ProgressUpdate, doneCh <-chan struct{}) { var lastOp string var lastProgress float64 lastFlush := time.Now() for { select { case update := <-ch: switch { case lastOp != update.Op: lastProgress = update.Progress lastOp = update.Op fmt.Println(update.Op) fmt.Printf("%.2f%%\n", update.Progress) case update.Progress-lastProgress >= 5: fallthrough case time.Now().Sub(lastFlush) > time.Second: fallthrough case update.Progress == 100: lastFlush = time.Now() lastProgress = update.Progress fmt.Printf("%.2f%%\n", update.Progress) } case <-doneCh: return } } }
go
func handleProgress(ch <-chan *migrator.ProgressUpdate, doneCh <-chan struct{}) { var lastOp string var lastProgress float64 lastFlush := time.Now() for { select { case update := <-ch: switch { case lastOp != update.Op: lastProgress = update.Progress lastOp = update.Op fmt.Println(update.Op) fmt.Printf("%.2f%%\n", update.Progress) case update.Progress-lastProgress >= 5: fallthrough case time.Now().Sub(lastFlush) > time.Second: fallthrough case update.Progress == 100: lastFlush = time.Now() lastProgress = update.Progress fmt.Printf("%.2f%%\n", update.Progress) } case <-doneCh: return } } }
[ "func", "handleProgress", "(", "ch", "<-", "chan", "*", "migrator", ".", "ProgressUpdate", ",", "doneCh", "<-", "chan", "struct", "{", "}", ")", "{", "var", "lastOp", "string", "\n", "var", "lastProgress", "float64", "\n", "lastFlush", ":=", "time", ".", "Now", "(", ")", "\n", "for", "{", "select", "{", "case", "update", ":=", "<-", "ch", ":", "switch", "{", "case", "lastOp", "!=", "update", ".", "Op", ":", "lastProgress", "=", "update", ".", "Progress", "\n", "lastOp", "=", "update", ".", "Op", "\n", "fmt", ".", "Println", "(", "update", ".", "Op", ")", "\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "update", ".", "Progress", ")", "\n\n", "case", "update", ".", "Progress", "-", "lastProgress", ">=", "5", ":", "fallthrough", "\n\n", "case", "time", ".", "Now", "(", ")", ".", "Sub", "(", "lastFlush", ")", ">", "time", ".", "Second", ":", "fallthrough", "\n\n", "case", "update", ".", "Progress", "==", "100", ":", "lastFlush", "=", "time", ".", "Now", "(", ")", "\n", "lastProgress", "=", "update", ".", "Progress", "\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "update", ".", "Progress", ")", "\n", "}", "\n", "case", "<-", "doneCh", ":", "return", "\n", "}", "\n", "}", "\n", "}" ]
// handleProgress is used to dump progress information to the console while // a migration is in flight. This allows the user to monitor a migration.
[ "handleProgress", "is", "used", "to", "dump", "progress", "information", "to", "the", "console", "while", "a", "migration", "is", "in", "flight", ".", "This", "allows", "the", "user", "to", "monitor", "a", "migration", "." ]
678fb10cdeae25ab309e99e655148f0bf65f9710
https://github.com/hashicorp/consul-migrate/blob/678fb10cdeae25ab309e99e655148f0bf65f9710/main.go#L58-L87
1,547
hashicorp/consul-migrate
migrator/migrator.go
New
func New(dataDir string) (*Migrator, error) { // Check that the directory exists if _, err := os.Stat(dataDir); err != nil { return nil, err } // Create the struct m := &Migrator{ ProgressCh: make(chan *ProgressUpdate, 128), dataDir: dataDir, raftPath: filepath.Join(dataDir, raftDir), mdbPath: filepath.Join(dataDir, raftDir, mdbDir), mdbBackupPath: filepath.Join(dataDir, raftDir, mdbBackupDir), boltPath: filepath.Join(dataDir, raftDir, boltFile), boltTempPath: filepath.Join(dataDir, raftDir, boltTempFile), } return m, nil }
go
func New(dataDir string) (*Migrator, error) { // Check that the directory exists if _, err := os.Stat(dataDir); err != nil { return nil, err } // Create the struct m := &Migrator{ ProgressCh: make(chan *ProgressUpdate, 128), dataDir: dataDir, raftPath: filepath.Join(dataDir, raftDir), mdbPath: filepath.Join(dataDir, raftDir, mdbDir), mdbBackupPath: filepath.Join(dataDir, raftDir, mdbBackupDir), boltPath: filepath.Join(dataDir, raftDir, boltFile), boltTempPath: filepath.Join(dataDir, raftDir, boltTempFile), } return m, nil }
[ "func", "New", "(", "dataDir", "string", ")", "(", "*", "Migrator", ",", "error", ")", "{", "// Check that the directory exists", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "dataDir", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Create the struct", "m", ":=", "&", "Migrator", "{", "ProgressCh", ":", "make", "(", "chan", "*", "ProgressUpdate", ",", "128", ")", ",", "dataDir", ":", "dataDir", ",", "raftPath", ":", "filepath", ".", "Join", "(", "dataDir", ",", "raftDir", ")", ",", "mdbPath", ":", "filepath", ".", "Join", "(", "dataDir", ",", "raftDir", ",", "mdbDir", ")", ",", "mdbBackupPath", ":", "filepath", ".", "Join", "(", "dataDir", ",", "raftDir", ",", "mdbBackupDir", ")", ",", "boltPath", ":", "filepath", ".", "Join", "(", "dataDir", ",", "raftDir", ",", "boltFile", ")", ",", "boltTempPath", ":", "filepath", ".", "Join", "(", "dataDir", ",", "raftDir", ",", "boltTempFile", ")", ",", "}", "\n\n", "return", "m", ",", "nil", "\n", "}" ]
// New creates a new Migrator given the path to a Consul // data-dir. Returns the new Migrator and any error.
[ "New", "creates", "a", "new", "Migrator", "given", "the", "path", "to", "a", "Consul", "data", "-", "dir", ".", "Returns", "the", "new", "Migrator", "and", "any", "error", "." ]
678fb10cdeae25ab309e99e655148f0bf65f9710
https://github.com/hashicorp/consul-migrate/blob/678fb10cdeae25ab309e99e655148f0bf65f9710/migrator/migrator.go#L71-L90
1,548
hashicorp/consul-migrate
migrator/migrator.go
mdbConnect
func (m *Migrator) mdbConnect(dir string) error { // Calculate and set the max size size := maxLogSize32bit if runtime.GOARCH == "amd64" { size = maxLogSize64bit } // Open the connection mdb, err := raftmdb.NewMDBStoreWithSize(dir, size) if err != nil { return err } // Return the new environment m.mdbStore = mdb return nil }
go
func (m *Migrator) mdbConnect(dir string) error { // Calculate and set the max size size := maxLogSize32bit if runtime.GOARCH == "amd64" { size = maxLogSize64bit } // Open the connection mdb, err := raftmdb.NewMDBStoreWithSize(dir, size) if err != nil { return err } // Return the new environment m.mdbStore = mdb return nil }
[ "func", "(", "m", "*", "Migrator", ")", "mdbConnect", "(", "dir", "string", ")", "error", "{", "// Calculate and set the max size", "size", ":=", "maxLogSize32bit", "\n", "if", "runtime", ".", "GOARCH", "==", "\"", "\"", "{", "size", "=", "maxLogSize64bit", "\n", "}", "\n\n", "// Open the connection", "mdb", ",", "err", ":=", "raftmdb", ".", "NewMDBStoreWithSize", "(", "dir", ",", "size", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Return the new environment", "m", ".", "mdbStore", "=", "mdb", "\n", "return", "nil", "\n", "}" ]
// mdbConnect is used to open a handle on our LMDB raft backend. This // is enough to read all of the Consul data we need to migrate.
[ "mdbConnect", "is", "used", "to", "open", "a", "handle", "on", "our", "LMDB", "raft", "backend", ".", "This", "is", "enough", "to", "read", "all", "of", "the", "Consul", "data", "we", "need", "to", "migrate", "." ]
678fb10cdeae25ab309e99e655148f0bf65f9710
https://github.com/hashicorp/consul-migrate/blob/678fb10cdeae25ab309e99e655148f0bf65f9710/migrator/migrator.go#L94-L110
1,549
hashicorp/consul-migrate
migrator/migrator.go
boltConnect
func (m *Migrator) boltConnect(file string) error { // Connect to the new BoltStore store, err := raftboltdb.NewBoltStore(file) if err != nil { return err } m.boltStore = store return nil }
go
func (m *Migrator) boltConnect(file string) error { // Connect to the new BoltStore store, err := raftboltdb.NewBoltStore(file) if err != nil { return err } m.boltStore = store return nil }
[ "func", "(", "m", "*", "Migrator", ")", "boltConnect", "(", "file", "string", ")", "error", "{", "// Connect to the new BoltStore", "store", ",", "err", ":=", "raftboltdb", ".", "NewBoltStore", "(", "file", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "m", ".", "boltStore", "=", "store", "\n", "return", "nil", "\n", "}" ]
// boltConnect creates a new BoltStore to copy our data into. We can // use the BoltStore directly because it provides simple setter // methods, provided our keys and values are known.
[ "boltConnect", "creates", "a", "new", "BoltStore", "to", "copy", "our", "data", "into", ".", "We", "can", "use", "the", "BoltStore", "directly", "because", "it", "provides", "simple", "setter", "methods", "provided", "our", "keys", "and", "values", "are", "known", "." ]
678fb10cdeae25ab309e99e655148f0bf65f9710
https://github.com/hashicorp/consul-migrate/blob/678fb10cdeae25ab309e99e655148f0bf65f9710/migrator/migrator.go#L115-L124
1,550
hashicorp/consul-migrate
migrator/migrator.go
migrateStableStore
func (m *Migrator) migrateStableStore() error { op := "Migrating stable store" m.sendProgress(op, 0, 1) total := len(stableStoreKeys) for i, key := range stableStoreKeys { val, err := m.mdbStore.Get(key) if err != nil { if err.Error() != "not found" { return fmt.Errorf("Error getting key '%s': %s", string(key), err) } m.sendProgress(op, i+1, total) continue } if err := m.boltStore.Set(key, val); err != nil { return fmt.Errorf("Error storing key '%s': %s", string(key), err) } m.sendProgress(op, i+1, total) } return nil }
go
func (m *Migrator) migrateStableStore() error { op := "Migrating stable store" m.sendProgress(op, 0, 1) total := len(stableStoreKeys) for i, key := range stableStoreKeys { val, err := m.mdbStore.Get(key) if err != nil { if err.Error() != "not found" { return fmt.Errorf("Error getting key '%s': %s", string(key), err) } m.sendProgress(op, i+1, total) continue } if err := m.boltStore.Set(key, val); err != nil { return fmt.Errorf("Error storing key '%s': %s", string(key), err) } m.sendProgress(op, i+1, total) } return nil }
[ "func", "(", "m", "*", "Migrator", ")", "migrateStableStore", "(", ")", "error", "{", "op", ":=", "\"", "\"", "\n", "m", ".", "sendProgress", "(", "op", ",", "0", ",", "1", ")", "\n\n", "total", ":=", "len", "(", "stableStoreKeys", ")", "\n", "for", "i", ",", "key", ":=", "range", "stableStoreKeys", "{", "val", ",", "err", ":=", "m", ".", "mdbStore", ".", "Get", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", ".", "Error", "(", ")", "!=", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "string", "(", "key", ")", ",", "err", ")", "\n", "}", "\n", "m", ".", "sendProgress", "(", "op", ",", "i", "+", "1", ",", "total", ")", "\n", "continue", "\n", "}", "\n", "if", "err", ":=", "m", ".", "boltStore", ".", "Set", "(", "key", ",", "val", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "string", "(", "key", ")", ",", "err", ")", "\n", "}", "\n", "m", ".", "sendProgress", "(", "op", ",", "i", "+", "1", ",", "total", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// migrateStableStore copies values out of the origin StableStore // and writes them into the destination. There are only a handful // of keys we need, so we copy them explicitly.
[ "migrateStableStore", "copies", "values", "out", "of", "the", "origin", "StableStore", "and", "writes", "them", "into", "the", "destination", ".", "There", "are", "only", "a", "handful", "of", "keys", "we", "need", "so", "we", "copy", "them", "explicitly", "." ]
678fb10cdeae25ab309e99e655148f0bf65f9710
https://github.com/hashicorp/consul-migrate/blob/678fb10cdeae25ab309e99e655148f0bf65f9710/migrator/migrator.go#L129-L149
1,551
hashicorp/consul-migrate
migrator/migrator.go
migrateLogStore
func (m *Migrator) migrateLogStore() error { op := "Migrating log store" m.sendProgress(op, 0, 1) first, err := m.mdbStore.FirstIndex() if err != nil { return err } if first == 0 { return errFirstIndexZero } last, err := m.mdbStore.LastIndex() if err != nil { return err } if last == 0 { return errLastIndexZero } total := int(last - first) current := 0 for i := first; i <= last; i++ { log := &raft.Log{} if err := m.mdbStore.GetLog(i, log); err != nil { return err } if err := m.boltStore.StoreLog(log); err != nil { return err } current++ m.sendProgress(op, current, total) } return nil }
go
func (m *Migrator) migrateLogStore() error { op := "Migrating log store" m.sendProgress(op, 0, 1) first, err := m.mdbStore.FirstIndex() if err != nil { return err } if first == 0 { return errFirstIndexZero } last, err := m.mdbStore.LastIndex() if err != nil { return err } if last == 0 { return errLastIndexZero } total := int(last - first) current := 0 for i := first; i <= last; i++ { log := &raft.Log{} if err := m.mdbStore.GetLog(i, log); err != nil { return err } if err := m.boltStore.StoreLog(log); err != nil { return err } current++ m.sendProgress(op, current, total) } return nil }
[ "func", "(", "m", "*", "Migrator", ")", "migrateLogStore", "(", ")", "error", "{", "op", ":=", "\"", "\"", "\n", "m", ".", "sendProgress", "(", "op", ",", "0", ",", "1", ")", "\n\n", "first", ",", "err", ":=", "m", ".", "mdbStore", ".", "FirstIndex", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "first", "==", "0", "{", "return", "errFirstIndexZero", "\n", "}", "\n\n", "last", ",", "err", ":=", "m", ".", "mdbStore", ".", "LastIndex", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "last", "==", "0", "{", "return", "errLastIndexZero", "\n", "}", "\n", "total", ":=", "int", "(", "last", "-", "first", ")", "\n\n", "current", ":=", "0", "\n", "for", "i", ":=", "first", ";", "i", "<=", "last", ";", "i", "++", "{", "log", ":=", "&", "raft", ".", "Log", "{", "}", "\n", "if", "err", ":=", "m", ".", "mdbStore", ".", "GetLog", "(", "i", ",", "log", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "m", ".", "boltStore", ".", "StoreLog", "(", "log", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "current", "++", "\n", "m", ".", "sendProgress", "(", "op", ",", "current", ",", "total", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// migrateLogStore is like migrateStableStore, but iterates over // all of our Raft logs and copies them into the new BoltStore.
[ "migrateLogStore", "is", "like", "migrateStableStore", "but", "iterates", "over", "all", "of", "our", "Raft", "logs", "and", "copies", "them", "into", "the", "new", "BoltStore", "." ]
678fb10cdeae25ab309e99e655148f0bf65f9710
https://github.com/hashicorp/consul-migrate/blob/678fb10cdeae25ab309e99e655148f0bf65f9710/migrator/migrator.go#L153-L187
1,552
hashicorp/consul-migrate
migrator/migrator.go
activateBoltStore
func (m *Migrator) activateBoltStore() error { op := "Moving Bolt file into place" m.sendProgress(op, 0, 1) if err := os.Rename(m.boltTempPath, m.boltPath); err != nil { return err } m.sendProgress(op, 1, 1) return nil }
go
func (m *Migrator) activateBoltStore() error { op := "Moving Bolt file into place" m.sendProgress(op, 0, 1) if err := os.Rename(m.boltTempPath, m.boltPath); err != nil { return err } m.sendProgress(op, 1, 1) return nil }
[ "func", "(", "m", "*", "Migrator", ")", "activateBoltStore", "(", ")", "error", "{", "op", ":=", "\"", "\"", "\n", "m", ".", "sendProgress", "(", "op", ",", "0", ",", "1", ")", "\n\n", "if", "err", ":=", "os", ".", "Rename", "(", "m", ".", "boltTempPath", ",", "m", ".", "boltPath", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "m", ".", "sendProgress", "(", "op", ",", "1", ",", "1", ")", "\n", "return", "nil", "\n", "}" ]
// activateBoltStore wraps moving the Bolt file into place after // a data migration has finished successfully.
[ "activateBoltStore", "wraps", "moving", "the", "Bolt", "file", "into", "place", "after", "a", "data", "migration", "has", "finished", "successfully", "." ]
678fb10cdeae25ab309e99e655148f0bf65f9710
https://github.com/hashicorp/consul-migrate/blob/678fb10cdeae25ab309e99e655148f0bf65f9710/migrator/migrator.go#L191-L201
1,553
hashicorp/consul-migrate
migrator/migrator.go
archiveMDBStore
func (m *Migrator) archiveMDBStore() error { op := "Archiving LMDB data" m.sendProgress(op, 0, 1) if err := os.Rename(m.mdbPath, m.mdbBackupPath); err != nil { os.Remove(m.boltPath) return err } m.sendProgress(op, 1, 1) return nil }
go
func (m *Migrator) archiveMDBStore() error { op := "Archiving LMDB data" m.sendProgress(op, 0, 1) if err := os.Rename(m.mdbPath, m.mdbBackupPath); err != nil { os.Remove(m.boltPath) return err } m.sendProgress(op, 1, 1) return nil }
[ "func", "(", "m", "*", "Migrator", ")", "archiveMDBStore", "(", ")", "error", "{", "op", ":=", "\"", "\"", "\n", "m", ".", "sendProgress", "(", "op", ",", "0", ",", "1", ")", "\n\n", "if", "err", ":=", "os", ".", "Rename", "(", "m", ".", "mdbPath", ",", "m", ".", "mdbBackupPath", ")", ";", "err", "!=", "nil", "{", "os", ".", "Remove", "(", "m", ".", "boltPath", ")", "\n", "return", "err", "\n", "}", "\n\n", "m", ".", "sendProgress", "(", "op", ",", "1", ",", "1", ")", "\n", "return", "nil", "\n", "}" ]
// archiveMDBStore is used to move the LMDB data directory to a backup // location so that it is not used by Consul again.
[ "archiveMDBStore", "is", "used", "to", "move", "the", "LMDB", "data", "directory", "to", "a", "backup", "location", "so", "that", "it", "is", "not", "used", "by", "Consul", "again", "." ]
678fb10cdeae25ab309e99e655148f0bf65f9710
https://github.com/hashicorp/consul-migrate/blob/678fb10cdeae25ab309e99e655148f0bf65f9710/migrator/migrator.go#L205-L216
1,554
hashicorp/consul-migrate
migrator/migrator.go
Migrate
func (m *Migrator) Migrate() (bool, error) { // Check if we should attempt a migration if _, err := os.Stat(m.mdbPath); os.IsNotExist(err) { return false, nil } // Connect the stores if err := m.mdbConnect(m.raftPath); err != nil { return false, fmt.Errorf("Failed to connect MDB: %s", err) } defer m.mdbStore.Close() if err := m.boltConnect(m.boltTempPath); err != nil { return false, fmt.Errorf("Failed to connect BoltDB: %s", err) } defer m.boltStore.Close() // Ensure we clean up the temp file during failure cases defer os.Remove(m.boltTempPath) // Migrate the stable store if err := m.migrateStableStore(); err != nil { return false, fmt.Errorf("Failed to migrate stable store: %v", err) } // Migrate the log store if err := m.migrateLogStore(); err != nil { return false, fmt.Errorf("Failed to migrate log store: %v", err) } // Activate the new BoltDB file if err := m.activateBoltStore(); err != nil { return false, fmt.Errorf("Failed to activate Bolt store: %s", err) } // Move the old MDB dir to its backup location if err := m.archiveMDBStore(); err != nil { return false, fmt.Errorf("Failed to archive LMDB data: %s", err) } return true, nil }
go
func (m *Migrator) Migrate() (bool, error) { // Check if we should attempt a migration if _, err := os.Stat(m.mdbPath); os.IsNotExist(err) { return false, nil } // Connect the stores if err := m.mdbConnect(m.raftPath); err != nil { return false, fmt.Errorf("Failed to connect MDB: %s", err) } defer m.mdbStore.Close() if err := m.boltConnect(m.boltTempPath); err != nil { return false, fmt.Errorf("Failed to connect BoltDB: %s", err) } defer m.boltStore.Close() // Ensure we clean up the temp file during failure cases defer os.Remove(m.boltTempPath) // Migrate the stable store if err := m.migrateStableStore(); err != nil { return false, fmt.Errorf("Failed to migrate stable store: %v", err) } // Migrate the log store if err := m.migrateLogStore(); err != nil { return false, fmt.Errorf("Failed to migrate log store: %v", err) } // Activate the new BoltDB file if err := m.activateBoltStore(); err != nil { return false, fmt.Errorf("Failed to activate Bolt store: %s", err) } // Move the old MDB dir to its backup location if err := m.archiveMDBStore(); err != nil { return false, fmt.Errorf("Failed to archive LMDB data: %s", err) } return true, nil }
[ "func", "(", "m", "*", "Migrator", ")", "Migrate", "(", ")", "(", "bool", ",", "error", ")", "{", "// Check if we should attempt a migration", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "m", ".", "mdbPath", ")", ";", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "false", ",", "nil", "\n", "}", "\n\n", "// Connect the stores", "if", "err", ":=", "m", ".", "mdbConnect", "(", "m", ".", "raftPath", ")", ";", "err", "!=", "nil", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "defer", "m", ".", "mdbStore", ".", "Close", "(", ")", "\n\n", "if", "err", ":=", "m", ".", "boltConnect", "(", "m", ".", "boltTempPath", ")", ";", "err", "!=", "nil", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "defer", "m", ".", "boltStore", ".", "Close", "(", ")", "\n\n", "// Ensure we clean up the temp file during failure cases", "defer", "os", ".", "Remove", "(", "m", ".", "boltTempPath", ")", "\n\n", "// Migrate the stable store", "if", "err", ":=", "m", ".", "migrateStableStore", "(", ")", ";", "err", "!=", "nil", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Migrate the log store", "if", "err", ":=", "m", ".", "migrateLogStore", "(", ")", ";", "err", "!=", "nil", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Activate the new BoltDB file", "if", "err", ":=", "m", ".", "activateBoltStore", "(", ")", ";", "err", "!=", "nil", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Move the old MDB dir to its backup location", "if", "err", ":=", "m", ".", "archiveMDBStore", "(", ")", ";", "err", "!=", "nil", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "true", ",", "nil", "\n", "}" ]
// Migrate is the high-level function we call when we want to attempt // to migrate all of our LMDB data into BoltDB. If an error is // encountered, the BoltStore is nuked from disk, since it is useless. // The migration can be attempted again, as the LMDB data should // still be intact. Returns a bool indicating whether a migration // was completed, and any error.
[ "Migrate", "is", "the", "high", "-", "level", "function", "we", "call", "when", "we", "want", "to", "attempt", "to", "migrate", "all", "of", "our", "LMDB", "data", "into", "BoltDB", ".", "If", "an", "error", "is", "encountered", "the", "BoltStore", "is", "nuked", "from", "disk", "since", "it", "is", "useless", ".", "The", "migration", "can", "be", "attempted", "again", "as", "the", "LMDB", "data", "should", "still", "be", "intact", ".", "Returns", "a", "bool", "indicating", "whether", "a", "migration", "was", "completed", "and", "any", "error", "." ]
678fb10cdeae25ab309e99e655148f0bf65f9710
https://github.com/hashicorp/consul-migrate/blob/678fb10cdeae25ab309e99e655148f0bf65f9710/migrator/migrator.go#L224-L265
1,555
hashicorp/consul-migrate
migrator/migrator.go
sendProgress
func (m *Migrator) sendProgress(op string, done, total int) { update := ProgressUpdate{op, (float64(done) / float64(total)) * 100} select { case m.ProgressCh <- &update: default: } }
go
func (m *Migrator) sendProgress(op string, done, total int) { update := ProgressUpdate{op, (float64(done) / float64(total)) * 100} select { case m.ProgressCh <- &update: default: } }
[ "func", "(", "m", "*", "Migrator", ")", "sendProgress", "(", "op", "string", ",", "done", ",", "total", "int", ")", "{", "update", ":=", "ProgressUpdate", "{", "op", ",", "(", "float64", "(", "done", ")", "/", "float64", "(", "total", ")", ")", "*", "100", "}", "\n", "select", "{", "case", "m", ".", "ProgressCh", "<-", "&", "update", ":", "default", ":", "}", "\n", "}" ]
// sendProgress is used to send a progress update message to the progress // channel. Sending is a non-blocking operation. It is the responsibility // of the caller to ensure they drain the queue promptly to avoid missing // progress update messages.
[ "sendProgress", "is", "used", "to", "send", "a", "progress", "update", "message", "to", "the", "progress", "channel", ".", "Sending", "is", "a", "non", "-", "blocking", "operation", ".", "It", "is", "the", "responsibility", "of", "the", "caller", "to", "ensure", "they", "drain", "the", "queue", "promptly", "to", "avoid", "missing", "progress", "update", "messages", "." ]
678fb10cdeae25ab309e99e655148f0bf65f9710
https://github.com/hashicorp/consul-migrate/blob/678fb10cdeae25ab309e99e655148f0bf65f9710/migrator/migrator.go#L271-L277
1,556
shibukawa/configdir
config.go
CreateParentDir
func (c Config) CreateParentDir(fileName string) error { return os.MkdirAll(filepath.Dir(filepath.Join(c.Path, fileName)), 0755) }
go
func (c Config) CreateParentDir(fileName string) error { return os.MkdirAll(filepath.Dir(filepath.Join(c.Path, fileName)), 0755) }
[ "func", "(", "c", "Config", ")", "CreateParentDir", "(", "fileName", "string", ")", "error", "{", "return", "os", ".", "MkdirAll", "(", "filepath", ".", "Dir", "(", "filepath", ".", "Join", "(", "c", ".", "Path", ",", "fileName", ")", ")", ",", "0755", ")", "\n", "}" ]
// CreateParentDir creates the parent directory of fileName inside c. fileName // is a relative path inside c, containing zero or more path separators.
[ "CreateParentDir", "creates", "the", "parent", "directory", "of", "fileName", "inside", "c", ".", "fileName", "is", "a", "relative", "path", "inside", "c", "containing", "zero", "or", "more", "path", "separators", "." ]
e180dbdc8da04c4fa04272e875ce64949f38bd3e
https://github.com/shibukawa/configdir/blob/e180dbdc8da04c4fa04272e875ce64949f38bd3e/config.go#L66-L68
1,557
rakyll/portmidi
stream.go
NewInputStream
func NewInputStream(id DeviceID, bufferSize int64) (stream *Stream, err error) { var str *C.PmStream errCode := C.Pm_OpenInput( (*unsafe.Pointer)(unsafe.Pointer(&str)), C.PmDeviceID(id), nil, C.int32_t(bufferSize), nil, nil) if errCode != 0 { return nil, convertToError(errCode) } if info := Info(id); !info.IsInputAvailable { return nil, ErrInputUnavailable } return &Stream{deviceID: id, pmStream: str}, nil }
go
func NewInputStream(id DeviceID, bufferSize int64) (stream *Stream, err error) { var str *C.PmStream errCode := C.Pm_OpenInput( (*unsafe.Pointer)(unsafe.Pointer(&str)), C.PmDeviceID(id), nil, C.int32_t(bufferSize), nil, nil) if errCode != 0 { return nil, convertToError(errCode) } if info := Info(id); !info.IsInputAvailable { return nil, ErrInputUnavailable } return &Stream{deviceID: id, pmStream: str}, nil }
[ "func", "NewInputStream", "(", "id", "DeviceID", ",", "bufferSize", "int64", ")", "(", "stream", "*", "Stream", ",", "err", "error", ")", "{", "var", "str", "*", "C", ".", "PmStream", "\n", "errCode", ":=", "C", ".", "Pm_OpenInput", "(", "(", "*", "unsafe", ".", "Pointer", ")", "(", "unsafe", ".", "Pointer", "(", "&", "str", ")", ")", ",", "C", ".", "PmDeviceID", "(", "id", ")", ",", "nil", ",", "C", ".", "int32_t", "(", "bufferSize", ")", ",", "nil", ",", "nil", ")", "\n", "if", "errCode", "!=", "0", "{", "return", "nil", ",", "convertToError", "(", "errCode", ")", "\n", "}", "\n", "if", "info", ":=", "Info", "(", "id", ")", ";", "!", "info", ".", "IsInputAvailable", "{", "return", "nil", ",", "ErrInputUnavailable", "\n", "}", "\n", "return", "&", "Stream", "{", "deviceID", ":", "id", ",", "pmStream", ":", "str", "}", ",", "nil", "\n", "}" ]
// NewInputStream initializes a new input stream.
[ "NewInputStream", "initializes", "a", "new", "input", "stream", "." ]
1246dd47c56089ea2ae791266edb7f4c6b90c045
https://github.com/rakyll/portmidi/blob/1246dd47c56089ea2ae791266edb7f4c6b90c045/stream.go#L62-L74
1,558
rakyll/portmidi
stream.go
NewOutputStream
func NewOutputStream(id DeviceID, bufferSize int64, latency int64) (stream *Stream, err error) { var str *C.PmStream errCode := C.Pm_OpenOutput( (*unsafe.Pointer)(unsafe.Pointer(&str)), C.PmDeviceID(id), nil, C.int32_t(bufferSize), nil, nil, C.int32_t(latency)) if errCode != 0 { return nil, convertToError(errCode) } if info := Info(id); !info.IsOutputAvailable { return nil, ErrOutputUnavailable } return &Stream{deviceID: id, pmStream: str}, nil }
go
func NewOutputStream(id DeviceID, bufferSize int64, latency int64) (stream *Stream, err error) { var str *C.PmStream errCode := C.Pm_OpenOutput( (*unsafe.Pointer)(unsafe.Pointer(&str)), C.PmDeviceID(id), nil, C.int32_t(bufferSize), nil, nil, C.int32_t(latency)) if errCode != 0 { return nil, convertToError(errCode) } if info := Info(id); !info.IsOutputAvailable { return nil, ErrOutputUnavailable } return &Stream{deviceID: id, pmStream: str}, nil }
[ "func", "NewOutputStream", "(", "id", "DeviceID", ",", "bufferSize", "int64", ",", "latency", "int64", ")", "(", "stream", "*", "Stream", ",", "err", "error", ")", "{", "var", "str", "*", "C", ".", "PmStream", "\n", "errCode", ":=", "C", ".", "Pm_OpenOutput", "(", "(", "*", "unsafe", ".", "Pointer", ")", "(", "unsafe", ".", "Pointer", "(", "&", "str", ")", ")", ",", "C", ".", "PmDeviceID", "(", "id", ")", ",", "nil", ",", "C", ".", "int32_t", "(", "bufferSize", ")", ",", "nil", ",", "nil", ",", "C", ".", "int32_t", "(", "latency", ")", ")", "\n", "if", "errCode", "!=", "0", "{", "return", "nil", ",", "convertToError", "(", "errCode", ")", "\n", "}", "\n", "if", "info", ":=", "Info", "(", "id", ")", ";", "!", "info", ".", "IsOutputAvailable", "{", "return", "nil", ",", "ErrOutputUnavailable", "\n", "}", "\n", "return", "&", "Stream", "{", "deviceID", ":", "id", ",", "pmStream", ":", "str", "}", ",", "nil", "\n", "}" ]
// NewOutputStream initializes a new output stream.
[ "NewOutputStream", "initializes", "a", "new", "output", "stream", "." ]
1246dd47c56089ea2ae791266edb7f4c6b90c045
https://github.com/rakyll/portmidi/blob/1246dd47c56089ea2ae791266edb7f4c6b90c045/stream.go#L77-L89
1,559
rakyll/portmidi
stream.go
Close
func (s *Stream) Close() error { if s.pmStream == nil { return nil } return convertToError(C.Pm_Close(unsafe.Pointer(s.pmStream))) }
go
func (s *Stream) Close() error { if s.pmStream == nil { return nil } return convertToError(C.Pm_Close(unsafe.Pointer(s.pmStream))) }
[ "func", "(", "s", "*", "Stream", ")", "Close", "(", ")", "error", "{", "if", "s", ".", "pmStream", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "convertToError", "(", "C", ".", "Pm_Close", "(", "unsafe", ".", "Pointer", "(", "s", ".", "pmStream", ")", ")", ")", "\n", "}" ]
// Close closes the MIDI stream.
[ "Close", "closes", "the", "MIDI", "stream", "." ]
1246dd47c56089ea2ae791266edb7f4c6b90c045
https://github.com/rakyll/portmidi/blob/1246dd47c56089ea2ae791266edb7f4c6b90c045/stream.go#L92-L97
1,560
rakyll/portmidi
stream.go
Abort
func (s *Stream) Abort() error { if s.pmStream == nil { return nil } return convertToError(C.Pm_Abort(unsafe.Pointer(s.pmStream))) }
go
func (s *Stream) Abort() error { if s.pmStream == nil { return nil } return convertToError(C.Pm_Abort(unsafe.Pointer(s.pmStream))) }
[ "func", "(", "s", "*", "Stream", ")", "Abort", "(", ")", "error", "{", "if", "s", ".", "pmStream", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "convertToError", "(", "C", ".", "Pm_Abort", "(", "unsafe", ".", "Pointer", "(", "s", ".", "pmStream", ")", ")", ")", "\n", "}" ]
// Abort aborts the MIDI stream.
[ "Abort", "aborts", "the", "MIDI", "stream", "." ]
1246dd47c56089ea2ae791266edb7f4c6b90c045
https://github.com/rakyll/portmidi/blob/1246dd47c56089ea2ae791266edb7f4c6b90c045/stream.go#L100-L105
1,561
rakyll/portmidi
stream.go
Write
func (s *Stream) Write(events []Event) error { size := len(events) if size > maxEventBufferSize { return ErrMaxBuffer } buffer := make([]C.PmEvent, size) for i, evt := range events { var event C.PmEvent event.timestamp = C.PmTimestamp(evt.Timestamp) event.message = C.PmMessage((((evt.Data2 << 16) & 0xFF0000) | ((evt.Data1 << 8) & 0xFF00) | (evt.Status & 0xFF))) buffer[i] = event } return convertToError(C.Pm_Write(unsafe.Pointer(s.pmStream), &buffer[0], C.int32_t(size))) }
go
func (s *Stream) Write(events []Event) error { size := len(events) if size > maxEventBufferSize { return ErrMaxBuffer } buffer := make([]C.PmEvent, size) for i, evt := range events { var event C.PmEvent event.timestamp = C.PmTimestamp(evt.Timestamp) event.message = C.PmMessage((((evt.Data2 << 16) & 0xFF0000) | ((evt.Data1 << 8) & 0xFF00) | (evt.Status & 0xFF))) buffer[i] = event } return convertToError(C.Pm_Write(unsafe.Pointer(s.pmStream), &buffer[0], C.int32_t(size))) }
[ "func", "(", "s", "*", "Stream", ")", "Write", "(", "events", "[", "]", "Event", ")", "error", "{", "size", ":=", "len", "(", "events", ")", "\n", "if", "size", ">", "maxEventBufferSize", "{", "return", "ErrMaxBuffer", "\n", "}", "\n", "buffer", ":=", "make", "(", "[", "]", "C", ".", "PmEvent", ",", "size", ")", "\n", "for", "i", ",", "evt", ":=", "range", "events", "{", "var", "event", "C", ".", "PmEvent", "\n", "event", ".", "timestamp", "=", "C", ".", "PmTimestamp", "(", "evt", ".", "Timestamp", ")", "\n", "event", ".", "message", "=", "C", ".", "PmMessage", "(", "(", "(", "(", "evt", ".", "Data2", "<<", "16", ")", "&", "0xFF0000", ")", "|", "(", "(", "evt", ".", "Data1", "<<", "8", ")", "&", "0xFF00", ")", "|", "(", "evt", ".", "Status", "&", "0xFF", ")", ")", ")", "\n", "buffer", "[", "i", "]", "=", "event", "\n", "}", "\n", "return", "convertToError", "(", "C", ".", "Pm_Write", "(", "unsafe", ".", "Pointer", "(", "s", ".", "pmStream", ")", ",", "&", "buffer", "[", "0", "]", ",", "C", ".", "int32_t", "(", "size", ")", ")", ")", "\n", "}" ]
// Write writes a buffer of MIDI events to the output stream.
[ "Write", "writes", "a", "buffer", "of", "MIDI", "events", "to", "the", "output", "stream", "." ]
1246dd47c56089ea2ae791266edb7f4c6b90c045
https://github.com/rakyll/portmidi/blob/1246dd47c56089ea2ae791266edb7f4c6b90c045/stream.go#L108-L121
1,562
rakyll/portmidi
stream.go
WriteShort
func (s *Stream) WriteShort(status int64, data1 int64, data2 int64) error { evt := Event{ Timestamp: Timestamp(C.Pt_Time()), Status: status, Data1: data1, Data2: data2, } return s.Write([]Event{evt}) }
go
func (s *Stream) WriteShort(status int64, data1 int64, data2 int64) error { evt := Event{ Timestamp: Timestamp(C.Pt_Time()), Status: status, Data1: data1, Data2: data2, } return s.Write([]Event{evt}) }
[ "func", "(", "s", "*", "Stream", ")", "WriteShort", "(", "status", "int64", ",", "data1", "int64", ",", "data2", "int64", ")", "error", "{", "evt", ":=", "Event", "{", "Timestamp", ":", "Timestamp", "(", "C", ".", "Pt_Time", "(", ")", ")", ",", "Status", ":", "status", ",", "Data1", ":", "data1", ",", "Data2", ":", "data2", ",", "}", "\n", "return", "s", ".", "Write", "(", "[", "]", "Event", "{", "evt", "}", ")", "\n", "}" ]
// WriteShort writes a MIDI event of three bytes immediately to the output stream.
[ "WriteShort", "writes", "a", "MIDI", "event", "of", "three", "bytes", "immediately", "to", "the", "output", "stream", "." ]
1246dd47c56089ea2ae791266edb7f4c6b90c045
https://github.com/rakyll/portmidi/blob/1246dd47c56089ea2ae791266edb7f4c6b90c045/stream.go#L124-L132
1,563
rakyll/portmidi
stream.go
Read
func (s *Stream) Read(max int) (events []Event, err error) { if max > maxEventBufferSize { return nil, ErrMaxBuffer } if max < minEventBufferSize { return nil, ErrMinBuffer } buffer := make([]C.PmEvent, max) numEvents := C.Pm_Read(unsafe.Pointer(s.pmStream), &buffer[0], C.int32_t(max)) if numEvents < 0 { return nil, convertToError(C.PmError(numEvents)) } events = make([]Event, numEvents) for i := 0; i < int(numEvents); i++ { events[i] = Event{ Timestamp: Timestamp(buffer[i].timestamp), Status: int64(buffer[i].message) & 0xFF, Data1: (int64(buffer[i].message) >> 8) & 0xFF, Data2: (int64(buffer[i].message) >> 16) & 0xFF, } } return }
go
func (s *Stream) Read(max int) (events []Event, err error) { if max > maxEventBufferSize { return nil, ErrMaxBuffer } if max < minEventBufferSize { return nil, ErrMinBuffer } buffer := make([]C.PmEvent, max) numEvents := C.Pm_Read(unsafe.Pointer(s.pmStream), &buffer[0], C.int32_t(max)) if numEvents < 0 { return nil, convertToError(C.PmError(numEvents)) } events = make([]Event, numEvents) for i := 0; i < int(numEvents); i++ { events[i] = Event{ Timestamp: Timestamp(buffer[i].timestamp), Status: int64(buffer[i].message) & 0xFF, Data1: (int64(buffer[i].message) >> 8) & 0xFF, Data2: (int64(buffer[i].message) >> 16) & 0xFF, } } return }
[ "func", "(", "s", "*", "Stream", ")", "Read", "(", "max", "int", ")", "(", "events", "[", "]", "Event", ",", "err", "error", ")", "{", "if", "max", ">", "maxEventBufferSize", "{", "return", "nil", ",", "ErrMaxBuffer", "\n", "}", "\n", "if", "max", "<", "minEventBufferSize", "{", "return", "nil", ",", "ErrMinBuffer", "\n", "}", "\n", "buffer", ":=", "make", "(", "[", "]", "C", ".", "PmEvent", ",", "max", ")", "\n", "numEvents", ":=", "C", ".", "Pm_Read", "(", "unsafe", ".", "Pointer", "(", "s", ".", "pmStream", ")", ",", "&", "buffer", "[", "0", "]", ",", "C", ".", "int32_t", "(", "max", ")", ")", "\n", "if", "numEvents", "<", "0", "{", "return", "nil", ",", "convertToError", "(", "C", ".", "PmError", "(", "numEvents", ")", ")", "\n", "}", "\n", "events", "=", "make", "(", "[", "]", "Event", ",", "numEvents", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "int", "(", "numEvents", ")", ";", "i", "++", "{", "events", "[", "i", "]", "=", "Event", "{", "Timestamp", ":", "Timestamp", "(", "buffer", "[", "i", "]", ".", "timestamp", ")", ",", "Status", ":", "int64", "(", "buffer", "[", "i", "]", ".", "message", ")", "&", "0xFF", ",", "Data1", ":", "(", "int64", "(", "buffer", "[", "i", "]", ".", "message", ")", ">>", "8", ")", "&", "0xFF", ",", "Data2", ":", "(", "int64", "(", "buffer", "[", "i", "]", ".", "message", ")", ">>", "16", ")", "&", "0xFF", ",", "}", "\n", "}", "\n", "return", "\n", "}" ]
// Reads from the input stream, the max number events to be read are // determined by max.
[ "Reads", "from", "the", "input", "stream", "the", "max", "number", "events", "to", "be", "read", "are", "determined", "by", "max", "." ]
1246dd47c56089ea2ae791266edb7f4c6b90c045
https://github.com/rakyll/portmidi/blob/1246dd47c56089ea2ae791266edb7f4c6b90c045/stream.go#L161-L183
1,564
rakyll/portmidi
stream.go
Listen
func (s *Stream) Listen() <-chan Event { ch := make(chan Event) go func(s *Stream, ch chan Event) { for { // sleep for a while before the new polling tick, // otherwise operation is too intensive and blocking time.Sleep(10 * time.Millisecond) events, err := s.Read(1024) // Note: It's not very reasonable to push sliced data into // a channel, several perf penalities there are. // This function is added as a handy utility. if err != nil { continue } for i := range events { ch <- events[i] } } }(s, ch) return ch }
go
func (s *Stream) Listen() <-chan Event { ch := make(chan Event) go func(s *Stream, ch chan Event) { for { // sleep for a while before the new polling tick, // otherwise operation is too intensive and blocking time.Sleep(10 * time.Millisecond) events, err := s.Read(1024) // Note: It's not very reasonable to push sliced data into // a channel, several perf penalities there are. // This function is added as a handy utility. if err != nil { continue } for i := range events { ch <- events[i] } } }(s, ch) return ch }
[ "func", "(", "s", "*", "Stream", ")", "Listen", "(", ")", "<-", "chan", "Event", "{", "ch", ":=", "make", "(", "chan", "Event", ")", "\n", "go", "func", "(", "s", "*", "Stream", ",", "ch", "chan", "Event", ")", "{", "for", "{", "// sleep for a while before the new polling tick,", "// otherwise operation is too intensive and blocking", "time", ".", "Sleep", "(", "10", "*", "time", ".", "Millisecond", ")", "\n", "events", ",", "err", ":=", "s", ".", "Read", "(", "1024", ")", "\n", "// Note: It's not very reasonable to push sliced data into", "// a channel, several perf penalities there are.", "// This function is added as a handy utility.", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n", "for", "i", ":=", "range", "events", "{", "ch", "<-", "events", "[", "i", "]", "\n", "}", "\n", "}", "\n", "}", "(", "s", ",", "ch", ")", "\n", "return", "ch", "\n", "}" ]
// Listen input stream for MIDI events.
[ "Listen", "input", "stream", "for", "MIDI", "events", "." ]
1246dd47c56089ea2ae791266edb7f4c6b90c045
https://github.com/rakyll/portmidi/blob/1246dd47c56089ea2ae791266edb7f4c6b90c045/stream.go#L209-L229
1,565
rakyll/portmidi
stream.go
Poll
func (s *Stream) Poll() (bool, error) { poll := C.Pm_Poll(unsafe.Pointer(s.pmStream)) if poll < 0 { return false, convertToError(C.PmError(poll)) } return poll > 0, nil }
go
func (s *Stream) Poll() (bool, error) { poll := C.Pm_Poll(unsafe.Pointer(s.pmStream)) if poll < 0 { return false, convertToError(C.PmError(poll)) } return poll > 0, nil }
[ "func", "(", "s", "*", "Stream", ")", "Poll", "(", ")", "(", "bool", ",", "error", ")", "{", "poll", ":=", "C", ".", "Pm_Poll", "(", "unsafe", ".", "Pointer", "(", "s", ".", "pmStream", ")", ")", "\n", "if", "poll", "<", "0", "{", "return", "false", ",", "convertToError", "(", "C", ".", "PmError", "(", "poll", ")", ")", "\n", "}", "\n", "return", "poll", ">", "0", ",", "nil", "\n", "}" ]
// Poll reports whether there is input available in the stream.
[ "Poll", "reports", "whether", "there", "is", "input", "available", "in", "the", "stream", "." ]
1246dd47c56089ea2ae791266edb7f4c6b90c045
https://github.com/rakyll/portmidi/blob/1246dd47c56089ea2ae791266edb7f4c6b90c045/stream.go#L232-L238
1,566
rakyll/portmidi
portmidi.go
Initialize
func Initialize() error { if code := C.Pm_Initialize(); code != 0 { return convertToError(code) } C.Pt_Start(C.int(1), nil, nil) return nil }
go
func Initialize() error { if code := C.Pm_Initialize(); code != 0 { return convertToError(code) } C.Pt_Start(C.int(1), nil, nil) return nil }
[ "func", "Initialize", "(", ")", "error", "{", "if", "code", ":=", "C", ".", "Pm_Initialize", "(", ")", ";", "code", "!=", "0", "{", "return", "convertToError", "(", "code", ")", "\n", "}", "\n", "C", ".", "Pt_Start", "(", "C", ".", "int", "(", "1", ")", ",", "nil", ",", "nil", ")", "\n", "return", "nil", "\n", "}" ]
// Initialize initializes the portmidi. Needs to be called before // making any other call from the portmidi package. // Once portmidi package is no longer required, Terminate should be // called to free the underlying resources.
[ "Initialize", "initializes", "the", "portmidi", ".", "Needs", "to", "be", "called", "before", "making", "any", "other", "call", "from", "the", "portmidi", "package", ".", "Once", "portmidi", "package", "is", "no", "longer", "required", "Terminate", "should", "be", "called", "to", "free", "the", "underlying", "resources", "." ]
1246dd47c56089ea2ae791266edb7f4c6b90c045
https://github.com/rakyll/portmidi/blob/1246dd47c56089ea2ae791266edb7f4c6b90c045/portmidi.go#L48-L54
1,567
rakyll/portmidi
portmidi.go
Info
func Info(deviceID DeviceID) *DeviceInfo { info := C.Pm_GetDeviceInfo(C.PmDeviceID(deviceID)) if info == nil { return nil } return &DeviceInfo{ Interface: C.GoString(info.interf), Name: C.GoString(info.name), IsInputAvailable: info.input > 0, IsOutputAvailable: info.output > 0, IsOpened: info.opened > 0, } }
go
func Info(deviceID DeviceID) *DeviceInfo { info := C.Pm_GetDeviceInfo(C.PmDeviceID(deviceID)) if info == nil { return nil } return &DeviceInfo{ Interface: C.GoString(info.interf), Name: C.GoString(info.name), IsInputAvailable: info.input > 0, IsOutputAvailable: info.output > 0, IsOpened: info.opened > 0, } }
[ "func", "Info", "(", "deviceID", "DeviceID", ")", "*", "DeviceInfo", "{", "info", ":=", "C", ".", "Pm_GetDeviceInfo", "(", "C", ".", "PmDeviceID", "(", "deviceID", ")", ")", "\n", "if", "info", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "&", "DeviceInfo", "{", "Interface", ":", "C", ".", "GoString", "(", "info", ".", "interf", ")", ",", "Name", ":", "C", ".", "GoString", "(", "info", ".", "name", ")", ",", "IsInputAvailable", ":", "info", ".", "input", ">", "0", ",", "IsOutputAvailable", ":", "info", ".", "output", ">", "0", ",", "IsOpened", ":", "info", ".", "opened", ">", "0", ",", "}", "\n", "}" ]
// Info returns the device info for the device indentified with deviceID. // If deviceID is out of range, Info returns nil.
[ "Info", "returns", "the", "device", "info", "for", "the", "device", "indentified", "with", "deviceID", ".", "If", "deviceID", "is", "out", "of", "range", "Info", "returns", "nil", "." ]
1246dd47c56089ea2ae791266edb7f4c6b90c045
https://github.com/rakyll/portmidi/blob/1246dd47c56089ea2ae791266edb7f4c6b90c045/portmidi.go#L79-L91
1,568
rakyll/portmidi
portmidi.go
convertToError
func convertToError(code C.PmError) error { if code >= 0 { return nil } return errors.New(C.GoString(C.Pm_GetErrorText(code))) }
go
func convertToError(code C.PmError) error { if code >= 0 { return nil } return errors.New(C.GoString(C.Pm_GetErrorText(code))) }
[ "func", "convertToError", "(", "code", "C", ".", "PmError", ")", "error", "{", "if", "code", ">=", "0", "{", "return", "nil", "\n", "}", "\n", "return", "errors", ".", "New", "(", "C", ".", "GoString", "(", "C", ".", "Pm_GetErrorText", "(", "code", ")", ")", ")", "\n", "}" ]
// convertToError converts a portmidi error code to a Go error.
[ "convertToError", "converts", "a", "portmidi", "error", "code", "to", "a", "Go", "error", "." ]
1246dd47c56089ea2ae791266edb7f4c6b90c045
https://github.com/rakyll/portmidi/blob/1246dd47c56089ea2ae791266edb7f4c6b90c045/portmidi.go#L99-L104
1,569
ryszard/goskiplist
skiplist/skiplist.go
next
func (n *node) next() *node { if len(n.forward) == 0 { return nil } return n.forward[0] }
go
func (n *node) next() *node { if len(n.forward) == 0 { return nil } return n.forward[0] }
[ "func", "(", "n", "*", "node", ")", "next", "(", ")", "*", "node", "{", "if", "len", "(", "n", ".", "forward", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "return", "n", ".", "forward", "[", "0", "]", "\n", "}" ]
// next returns the next node in the skip list containing n.
[ "next", "returns", "the", "next", "node", "in", "the", "skip", "list", "containing", "n", "." ]
2dfbae5fcf46374f166f8969cb07e167f1be6273
https://github.com/ryszard/goskiplist/blob/2dfbae5fcf46374f166f8969cb07e167f1be6273/skiplist/skiplist.go#L41-L46
1,570
ryszard/goskiplist
skiplist/skiplist.go
Iterator
func (s *SkipList) Iterator() Iterator { return &iter{ current: s.header, list: s, } }
go
func (s *SkipList) Iterator() Iterator { return &iter{ current: s.header, list: s, } }
[ "func", "(", "s", "*", "SkipList", ")", "Iterator", "(", ")", "Iterator", "{", "return", "&", "iter", "{", "current", ":", "s", ".", "header", ",", "list", ":", "s", ",", "}", "\n", "}" ]
// Iterator returns an Iterator that will go through all elements s.
[ "Iterator", "returns", "an", "Iterator", "that", "will", "go", "through", "all", "elements", "s", "." ]
2dfbae5fcf46374f166f8969cb07e167f1be6273
https://github.com/ryszard/goskiplist/blob/2dfbae5fcf46374f166f8969cb07e167f1be6273/skiplist/skiplist.go#L267-L272
1,571
ryszard/goskiplist
skiplist/skiplist.go
Seek
func (s *SkipList) Seek(key interface{}) Iterator { current := s.getPath(s.header, nil, key) if current == nil { return nil } return &iter{ current: current, key: current.key, list: s, value: current.value, } }
go
func (s *SkipList) Seek(key interface{}) Iterator { current := s.getPath(s.header, nil, key) if current == nil { return nil } return &iter{ current: current, key: current.key, list: s, value: current.value, } }
[ "func", "(", "s", "*", "SkipList", ")", "Seek", "(", "key", "interface", "{", "}", ")", "Iterator", "{", "current", ":=", "s", ".", "getPath", "(", "s", ".", "header", ",", "nil", ",", "key", ")", "\n", "if", "current", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "return", "&", "iter", "{", "current", ":", "current", ",", "key", ":", "current", ".", "key", ",", "list", ":", "s", ",", "value", ":", "current", ".", "value", ",", "}", "\n", "}" ]
// Seek returns a bidirectional iterator starting with the first element whose // key is greater or equal to key; otherwise, a nil iterator is returned.
[ "Seek", "returns", "a", "bidirectional", "iterator", "starting", "with", "the", "first", "element", "whose", "key", "is", "greater", "or", "equal", "to", "key", ";", "otherwise", "a", "nil", "iterator", "is", "returned", "." ]
2dfbae5fcf46374f166f8969cb07e167f1be6273
https://github.com/ryszard/goskiplist/blob/2dfbae5fcf46374f166f8969cb07e167f1be6273/skiplist/skiplist.go#L276-L288
1,572
ryszard/goskiplist
skiplist/skiplist.go
SeekToFirst
func (s *SkipList) SeekToFirst() Iterator { if s.length == 0 { return nil } current := s.header.next() return &iter{ current: current, key: current.key, list: s, value: current.value, } }
go
func (s *SkipList) SeekToFirst() Iterator { if s.length == 0 { return nil } current := s.header.next() return &iter{ current: current, key: current.key, list: s, value: current.value, } }
[ "func", "(", "s", "*", "SkipList", ")", "SeekToFirst", "(", ")", "Iterator", "{", "if", "s", ".", "length", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "current", ":=", "s", ".", "header", ".", "next", "(", ")", "\n\n", "return", "&", "iter", "{", "current", ":", "current", ",", "key", ":", "current", ".", "key", ",", "list", ":", "s", ",", "value", ":", "current", ".", "value", ",", "}", "\n", "}" ]
// SeekToFirst returns a bidirectional iterator starting from the first element // in the list if the list is populated; otherwise, a nil iterator is returned.
[ "SeekToFirst", "returns", "a", "bidirectional", "iterator", "starting", "from", "the", "first", "element", "in", "the", "list", "if", "the", "list", "is", "populated", ";", "otherwise", "a", "nil", "iterator", "is", "returned", "." ]
2dfbae5fcf46374f166f8969cb07e167f1be6273
https://github.com/ryszard/goskiplist/blob/2dfbae5fcf46374f166f8969cb07e167f1be6273/skiplist/skiplist.go#L292-L305
1,573
ryszard/goskiplist
skiplist/skiplist.go
SeekToLast
func (s *SkipList) SeekToLast() Iterator { current := s.footer if current == nil { return nil } return &iter{ current: current, key: current.key, list: s, value: current.value, } }
go
func (s *SkipList) SeekToLast() Iterator { current := s.footer if current == nil { return nil } return &iter{ current: current, key: current.key, list: s, value: current.value, } }
[ "func", "(", "s", "*", "SkipList", ")", "SeekToLast", "(", ")", "Iterator", "{", "current", ":=", "s", ".", "footer", "\n", "if", "current", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "return", "&", "iter", "{", "current", ":", "current", ",", "key", ":", "current", ".", "key", ",", "list", ":", "s", ",", "value", ":", "current", ".", "value", ",", "}", "\n", "}" ]
// SeekToLast returns a bidirectional iterator starting from the last element // in the list if the list is populated; otherwise, a nil iterator is returned.
[ "SeekToLast", "returns", "a", "bidirectional", "iterator", "starting", "from", "the", "last", "element", "in", "the", "list", "if", "the", "list", "is", "populated", ";", "otherwise", "a", "nil", "iterator", "is", "returned", "." ]
2dfbae5fcf46374f166f8969cb07e167f1be6273
https://github.com/ryszard/goskiplist/blob/2dfbae5fcf46374f166f8969cb07e167f1be6273/skiplist/skiplist.go#L309-L321
1,574
ryszard/goskiplist
skiplist/skiplist.go
Range
func (s *SkipList) Range(from, to interface{}) Iterator { start := s.getPath(s.header, nil, from) return &rangeIterator{ iter: iter{ current: &node{ forward: []*node{start}, backward: start, }, list: s, }, upperLimit: to, lowerLimit: from, } }
go
func (s *SkipList) Range(from, to interface{}) Iterator { start := s.getPath(s.header, nil, from) return &rangeIterator{ iter: iter{ current: &node{ forward: []*node{start}, backward: start, }, list: s, }, upperLimit: to, lowerLimit: from, } }
[ "func", "(", "s", "*", "SkipList", ")", "Range", "(", "from", ",", "to", "interface", "{", "}", ")", "Iterator", "{", "start", ":=", "s", ".", "getPath", "(", "s", ".", "header", ",", "nil", ",", "from", ")", "\n", "return", "&", "rangeIterator", "{", "iter", ":", "iter", "{", "current", ":", "&", "node", "{", "forward", ":", "[", "]", "*", "node", "{", "start", "}", ",", "backward", ":", "start", ",", "}", ",", "list", ":", "s", ",", "}", ",", "upperLimit", ":", "to", ",", "lowerLimit", ":", "from", ",", "}", "\n", "}" ]
// Range returns an iterator that will go through all the // elements of the skip list that are greater or equal than from, but // less than to.
[ "Range", "returns", "an", "iterator", "that", "will", "go", "through", "all", "the", "elements", "of", "the", "skip", "list", "that", "are", "greater", "or", "equal", "than", "from", "but", "less", "than", "to", "." ]
2dfbae5fcf46374f166f8969cb07e167f1be6273
https://github.com/ryszard/goskiplist/blob/2dfbae5fcf46374f166f8969cb07e167f1be6273/skiplist/skiplist.go#L326-L339
1,575
ryszard/goskiplist
skiplist/skiplist.go
randomLevel
func (s SkipList) randomLevel() (n int) { for n = 0; n < s.effectiveMaxLevel() && rand.Float64() < p; n++ { } return }
go
func (s SkipList) randomLevel() (n int) { for n = 0; n < s.effectiveMaxLevel() && rand.Float64() < p; n++ { } return }
[ "func", "(", "s", "SkipList", ")", "randomLevel", "(", ")", "(", "n", "int", ")", "{", "for", "n", "=", "0", ";", "n", "<", "s", ".", "effectiveMaxLevel", "(", ")", "&&", "rand", ".", "Float64", "(", ")", "<", "p", ";", "n", "++", "{", "}", "\n", "return", "\n", "}" ]
// Returns a new random level.
[ "Returns", "a", "new", "random", "level", "." ]
2dfbae5fcf46374f166f8969cb07e167f1be6273
https://github.com/ryszard/goskiplist/blob/2dfbae5fcf46374f166f8969cb07e167f1be6273/skiplist/skiplist.go#L357-L361
1,576
ryszard/goskiplist
skiplist/skiplist.go
GetGreaterOrEqual
func (s *SkipList) GetGreaterOrEqual(min interface{}) (actualKey, value interface{}, ok bool) { candidate := s.getPath(s.header, nil, min) if candidate != nil { return candidate.key, candidate.value, true } return nil, nil, false }
go
func (s *SkipList) GetGreaterOrEqual(min interface{}) (actualKey, value interface{}, ok bool) { candidate := s.getPath(s.header, nil, min) if candidate != nil { return candidate.key, candidate.value, true } return nil, nil, false }
[ "func", "(", "s", "*", "SkipList", ")", "GetGreaterOrEqual", "(", "min", "interface", "{", "}", ")", "(", "actualKey", ",", "value", "interface", "{", "}", ",", "ok", "bool", ")", "{", "candidate", ":=", "s", ".", "getPath", "(", "s", ".", "header", ",", "nil", ",", "min", ")", "\n\n", "if", "candidate", "!=", "nil", "{", "return", "candidate", ".", "key", ",", "candidate", ".", "value", ",", "true", "\n", "}", "\n", "return", "nil", ",", "nil", ",", "false", "\n", "}" ]
// GetGreaterOrEqual finds the node whose key is greater than or equal // to min. It returns its value, its actual key, and whether such a // node is present in the skip list.
[ "GetGreaterOrEqual", "finds", "the", "node", "whose", "key", "is", "greater", "than", "or", "equal", "to", "min", ".", "It", "returns", "its", "value", "its", "actual", "key", "and", "whether", "such", "a", "node", "is", "present", "in", "the", "skip", "list", "." ]
2dfbae5fcf46374f166f8969cb07e167f1be6273
https://github.com/ryszard/goskiplist/blob/2dfbae5fcf46374f166f8969cb07e167f1be6273/skiplist/skiplist.go#L379-L386
1,577
ryszard/goskiplist
skiplist/skiplist.go
Set
func (s *SkipList) Set(key, value interface{}) { if key == nil { panic("goskiplist: nil keys are not supported") } // s.level starts from 0, so we need to allocate one. update := make([]*node, s.level()+1, s.effectiveMaxLevel()+1) candidate := s.getPath(s.header, update, key) if candidate != nil && candidate.key == key { candidate.value = value return } newLevel := s.randomLevel() if currentLevel := s.level(); newLevel > currentLevel { // there are no pointers for the higher levels in // update. Header should be there. Also add higher // level links to the header. for i := currentLevel + 1; i <= newLevel; i++ { update = append(update, s.header) s.header.forward = append(s.header.forward, nil) } } newNode := &node{ forward: make([]*node, newLevel+1, s.effectiveMaxLevel()+1), key: key, value: value, } if previous := update[0]; previous.key != nil { newNode.backward = previous } for i := 0; i <= newLevel; i++ { newNode.forward[i] = update[i].forward[i] update[i].forward[i] = newNode } s.length++ if newNode.forward[0] != nil { if newNode.forward[0].backward != newNode { newNode.forward[0].backward = newNode } } if s.footer == nil || s.lessThan(s.footer.key, key) { s.footer = newNode } }
go
func (s *SkipList) Set(key, value interface{}) { if key == nil { panic("goskiplist: nil keys are not supported") } // s.level starts from 0, so we need to allocate one. update := make([]*node, s.level()+1, s.effectiveMaxLevel()+1) candidate := s.getPath(s.header, update, key) if candidate != nil && candidate.key == key { candidate.value = value return } newLevel := s.randomLevel() if currentLevel := s.level(); newLevel > currentLevel { // there are no pointers for the higher levels in // update. Header should be there. Also add higher // level links to the header. for i := currentLevel + 1; i <= newLevel; i++ { update = append(update, s.header) s.header.forward = append(s.header.forward, nil) } } newNode := &node{ forward: make([]*node, newLevel+1, s.effectiveMaxLevel()+1), key: key, value: value, } if previous := update[0]; previous.key != nil { newNode.backward = previous } for i := 0; i <= newLevel; i++ { newNode.forward[i] = update[i].forward[i] update[i].forward[i] = newNode } s.length++ if newNode.forward[0] != nil { if newNode.forward[0].backward != newNode { newNode.forward[0].backward = newNode } } if s.footer == nil || s.lessThan(s.footer.key, key) { s.footer = newNode } }
[ "func", "(", "s", "*", "SkipList", ")", "Set", "(", "key", ",", "value", "interface", "{", "}", ")", "{", "if", "key", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "// s.level starts from 0, so we need to allocate one.", "update", ":=", "make", "(", "[", "]", "*", "node", ",", "s", ".", "level", "(", ")", "+", "1", ",", "s", ".", "effectiveMaxLevel", "(", ")", "+", "1", ")", "\n", "candidate", ":=", "s", ".", "getPath", "(", "s", ".", "header", ",", "update", ",", "key", ")", "\n\n", "if", "candidate", "!=", "nil", "&&", "candidate", ".", "key", "==", "key", "{", "candidate", ".", "value", "=", "value", "\n", "return", "\n", "}", "\n\n", "newLevel", ":=", "s", ".", "randomLevel", "(", ")", "\n\n", "if", "currentLevel", ":=", "s", ".", "level", "(", ")", ";", "newLevel", ">", "currentLevel", "{", "// there are no pointers for the higher levels in", "// update. Header should be there. Also add higher", "// level links to the header.", "for", "i", ":=", "currentLevel", "+", "1", ";", "i", "<=", "newLevel", ";", "i", "++", "{", "update", "=", "append", "(", "update", ",", "s", ".", "header", ")", "\n", "s", ".", "header", ".", "forward", "=", "append", "(", "s", ".", "header", ".", "forward", ",", "nil", ")", "\n", "}", "\n", "}", "\n\n", "newNode", ":=", "&", "node", "{", "forward", ":", "make", "(", "[", "]", "*", "node", ",", "newLevel", "+", "1", ",", "s", ".", "effectiveMaxLevel", "(", ")", "+", "1", ")", ",", "key", ":", "key", ",", "value", ":", "value", ",", "}", "\n\n", "if", "previous", ":=", "update", "[", "0", "]", ";", "previous", ".", "key", "!=", "nil", "{", "newNode", ".", "backward", "=", "previous", "\n", "}", "\n\n", "for", "i", ":=", "0", ";", "i", "<=", "newLevel", ";", "i", "++", "{", "newNode", ".", "forward", "[", "i", "]", "=", "update", "[", "i", "]", ".", "forward", "[", "i", "]", "\n", "update", "[", "i", "]", ".", "forward", "[", "i", "]", "=", "newNode", "\n", "}", "\n\n", "s", ".", "length", "++", "\n\n", "if", "newNode", ".", "forward", "[", "0", "]", "!=", "nil", "{", "if", "newNode", ".", "forward", "[", "0", "]", ".", "backward", "!=", "newNode", "{", "newNode", ".", "forward", "[", "0", "]", ".", "backward", "=", "newNode", "\n", "}", "\n", "}", "\n\n", "if", "s", ".", "footer", "==", "nil", "||", "s", ".", "lessThan", "(", "s", ".", "footer", ".", "key", ",", "key", ")", "{", "s", ".", "footer", "=", "newNode", "\n", "}", "\n", "}" ]
// Sets set the value associated with key in s.
[ "Sets", "set", "the", "value", "associated", "with", "key", "in", "s", "." ]
2dfbae5fcf46374f166f8969cb07e167f1be6273
https://github.com/ryszard/goskiplist/blob/2dfbae5fcf46374f166f8969cb07e167f1be6273/skiplist/skiplist.go#L408-L459
1,578
ryszard/goskiplist
skiplist/skiplist.go
Delete
func (s *SkipList) Delete(key interface{}) (value interface{}, ok bool) { if key == nil { panic("goskiplist: nil keys are not supported") } update := make([]*node, s.level()+1, s.effectiveMaxLevel()) candidate := s.getPath(s.header, update, key) if candidate == nil || candidate.key != key { return nil, false } previous := candidate.backward if s.footer == candidate { s.footer = previous } next := candidate.next() if next != nil { next.backward = previous } for i := 0; i <= s.level() && update[i].forward[i] == candidate; i++ { update[i].forward[i] = candidate.forward[i] } for s.level() > 0 && s.header.forward[s.level()] == nil { s.header.forward = s.header.forward[:s.level()] } s.length-- return candidate.value, true }
go
func (s *SkipList) Delete(key interface{}) (value interface{}, ok bool) { if key == nil { panic("goskiplist: nil keys are not supported") } update := make([]*node, s.level()+1, s.effectiveMaxLevel()) candidate := s.getPath(s.header, update, key) if candidate == nil || candidate.key != key { return nil, false } previous := candidate.backward if s.footer == candidate { s.footer = previous } next := candidate.next() if next != nil { next.backward = previous } for i := 0; i <= s.level() && update[i].forward[i] == candidate; i++ { update[i].forward[i] = candidate.forward[i] } for s.level() > 0 && s.header.forward[s.level()] == nil { s.header.forward = s.header.forward[:s.level()] } s.length-- return candidate.value, true }
[ "func", "(", "s", "*", "SkipList", ")", "Delete", "(", "key", "interface", "{", "}", ")", "(", "value", "interface", "{", "}", ",", "ok", "bool", ")", "{", "if", "key", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "update", ":=", "make", "(", "[", "]", "*", "node", ",", "s", ".", "level", "(", ")", "+", "1", ",", "s", ".", "effectiveMaxLevel", "(", ")", ")", "\n", "candidate", ":=", "s", ".", "getPath", "(", "s", ".", "header", ",", "update", ",", "key", ")", "\n\n", "if", "candidate", "==", "nil", "||", "candidate", ".", "key", "!=", "key", "{", "return", "nil", ",", "false", "\n", "}", "\n\n", "previous", ":=", "candidate", ".", "backward", "\n", "if", "s", ".", "footer", "==", "candidate", "{", "s", ".", "footer", "=", "previous", "\n", "}", "\n\n", "next", ":=", "candidate", ".", "next", "(", ")", "\n", "if", "next", "!=", "nil", "{", "next", ".", "backward", "=", "previous", "\n", "}", "\n\n", "for", "i", ":=", "0", ";", "i", "<=", "s", ".", "level", "(", ")", "&&", "update", "[", "i", "]", ".", "forward", "[", "i", "]", "==", "candidate", ";", "i", "++", "{", "update", "[", "i", "]", ".", "forward", "[", "i", "]", "=", "candidate", ".", "forward", "[", "i", "]", "\n", "}", "\n\n", "for", "s", ".", "level", "(", ")", ">", "0", "&&", "s", ".", "header", ".", "forward", "[", "s", ".", "level", "(", ")", "]", "==", "nil", "{", "s", ".", "header", ".", "forward", "=", "s", ".", "header", ".", "forward", "[", ":", "s", ".", "level", "(", ")", "]", "\n", "}", "\n", "s", ".", "length", "--", "\n\n", "return", "candidate", ".", "value", ",", "true", "\n", "}" ]
// Delete removes the node with the given key. // // It returns the old value and whether the node was present.
[ "Delete", "removes", "the", "node", "with", "the", "given", "key", ".", "It", "returns", "the", "old", "value", "and", "whether", "the", "node", "was", "present", "." ]
2dfbae5fcf46374f166f8969cb07e167f1be6273
https://github.com/ryszard/goskiplist/blob/2dfbae5fcf46374f166f8969cb07e167f1be6273/skiplist/skiplist.go#L464-L495
1,579
ryszard/goskiplist
skiplist/skiplist.go
NewCustomMap
func NewCustomMap(lessThan func(l, r interface{}) bool) *SkipList { return &SkipList{ lessThan: lessThan, header: &node{ forward: []*node{nil}, }, MaxLevel: DefaultMaxLevel, } }
go
func NewCustomMap(lessThan func(l, r interface{}) bool) *SkipList { return &SkipList{ lessThan: lessThan, header: &node{ forward: []*node{nil}, }, MaxLevel: DefaultMaxLevel, } }
[ "func", "NewCustomMap", "(", "lessThan", "func", "(", "l", ",", "r", "interface", "{", "}", ")", "bool", ")", "*", "SkipList", "{", "return", "&", "SkipList", "{", "lessThan", ":", "lessThan", ",", "header", ":", "&", "node", "{", "forward", ":", "[", "]", "*", "node", "{", "nil", "}", ",", "}", ",", "MaxLevel", ":", "DefaultMaxLevel", ",", "}", "\n", "}" ]
// NewCustomMap returns a new SkipList that will use lessThan as the // comparison function. lessThan should define a linear order on keys // you intend to use with the SkipList.
[ "NewCustomMap", "returns", "a", "new", "SkipList", "that", "will", "use", "lessThan", "as", "the", "comparison", "function", ".", "lessThan", "should", "define", "a", "linear", "order", "on", "keys", "you", "intend", "to", "use", "with", "the", "SkipList", "." ]
2dfbae5fcf46374f166f8969cb07e167f1be6273
https://github.com/ryszard/goskiplist/blob/2dfbae5fcf46374f166f8969cb07e167f1be6273/skiplist/skiplist.go#L500-L508
1,580
ryszard/goskiplist
skiplist/skiplist.go
New
func New() *SkipList { comparator := func(left, right interface{}) bool { return left.(Ordered).LessThan(right.(Ordered)) } return NewCustomMap(comparator) }
go
func New() *SkipList { comparator := func(left, right interface{}) bool { return left.(Ordered).LessThan(right.(Ordered)) } return NewCustomMap(comparator) }
[ "func", "New", "(", ")", "*", "SkipList", "{", "comparator", ":=", "func", "(", "left", ",", "right", "interface", "{", "}", ")", "bool", "{", "return", "left", ".", "(", "Ordered", ")", ".", "LessThan", "(", "right", ".", "(", "Ordered", ")", ")", "\n", "}", "\n", "return", "NewCustomMap", "(", "comparator", ")", "\n\n", "}" ]
// New returns a new SkipList. // // Its keys must implement the Ordered interface.
[ "New", "returns", "a", "new", "SkipList", ".", "Its", "keys", "must", "implement", "the", "Ordered", "interface", "." ]
2dfbae5fcf46374f166f8969cb07e167f1be6273
https://github.com/ryszard/goskiplist/blob/2dfbae5fcf46374f166f8969cb07e167f1be6273/skiplist/skiplist.go#L521-L527
1,581
ryszard/goskiplist
skiplist/skiplist.go
NewIntMap
func NewIntMap() *SkipList { return NewCustomMap(func(l, r interface{}) bool { return l.(int) < r.(int) }) }
go
func NewIntMap() *SkipList { return NewCustomMap(func(l, r interface{}) bool { return l.(int) < r.(int) }) }
[ "func", "NewIntMap", "(", ")", "*", "SkipList", "{", "return", "NewCustomMap", "(", "func", "(", "l", ",", "r", "interface", "{", "}", ")", "bool", "{", "return", "l", ".", "(", "int", ")", "<", "r", ".", "(", "int", ")", "\n", "}", ")", "\n", "}" ]
// NewIntKey returns a SkipList that accepts int keys.
[ "NewIntKey", "returns", "a", "SkipList", "that", "accepts", "int", "keys", "." ]
2dfbae5fcf46374f166f8969cb07e167f1be6273
https://github.com/ryszard/goskiplist/blob/2dfbae5fcf46374f166f8969cb07e167f1be6273/skiplist/skiplist.go#L530-L534
1,582
ryszard/goskiplist
skiplist/skiplist.go
NewStringMap
func NewStringMap() *SkipList { return NewCustomMap(func(l, r interface{}) bool { return l.(string) < r.(string) }) }
go
func NewStringMap() *SkipList { return NewCustomMap(func(l, r interface{}) bool { return l.(string) < r.(string) }) }
[ "func", "NewStringMap", "(", ")", "*", "SkipList", "{", "return", "NewCustomMap", "(", "func", "(", "l", ",", "r", "interface", "{", "}", ")", "bool", "{", "return", "l", ".", "(", "string", ")", "<", "r", ".", "(", "string", ")", "\n", "}", ")", "\n", "}" ]
// NewStringMap returns a SkipList that accepts string keys.
[ "NewStringMap", "returns", "a", "SkipList", "that", "accepts", "string", "keys", "." ]
2dfbae5fcf46374f166f8969cb07e167f1be6273
https://github.com/ryszard/goskiplist/blob/2dfbae5fcf46374f166f8969cb07e167f1be6273/skiplist/skiplist.go#L537-L541
1,583
ryszard/goskiplist
skiplist/skiplist.go
NewSet
func NewSet() *Set { comparator := func(left, right interface{}) bool { return left.(Ordered).LessThan(right.(Ordered)) } return NewCustomSet(comparator) }
go
func NewSet() *Set { comparator := func(left, right interface{}) bool { return left.(Ordered).LessThan(right.(Ordered)) } return NewCustomSet(comparator) }
[ "func", "NewSet", "(", ")", "*", "Set", "{", "comparator", ":=", "func", "(", "left", ",", "right", "interface", "{", "}", ")", "bool", "{", "return", "left", ".", "(", "Ordered", ")", ".", "LessThan", "(", "right", ".", "(", "Ordered", ")", ")", "\n", "}", "\n", "return", "NewCustomSet", "(", "comparator", ")", "\n", "}" ]
// NewSet returns a new Set.
[ "NewSet", "returns", "a", "new", "Set", "." ]
2dfbae5fcf46374f166f8969cb07e167f1be6273
https://github.com/ryszard/goskiplist/blob/2dfbae5fcf46374f166f8969cb07e167f1be6273/skiplist/skiplist.go#L560-L565
1,584
ryszard/goskiplist
skiplist/skiplist.go
NewCustomSet
func NewCustomSet(lessThan func(l, r interface{}) bool) *Set { return &Set{skiplist: SkipList{ lessThan: lessThan, header: &node{ forward: []*node{nil}, }, MaxLevel: DefaultMaxLevel, }} }
go
func NewCustomSet(lessThan func(l, r interface{}) bool) *Set { return &Set{skiplist: SkipList{ lessThan: lessThan, header: &node{ forward: []*node{nil}, }, MaxLevel: DefaultMaxLevel, }} }
[ "func", "NewCustomSet", "(", "lessThan", "func", "(", "l", ",", "r", "interface", "{", "}", ")", "bool", ")", "*", "Set", "{", "return", "&", "Set", "{", "skiplist", ":", "SkipList", "{", "lessThan", ":", "lessThan", ",", "header", ":", "&", "node", "{", "forward", ":", "[", "]", "*", "node", "{", "nil", "}", ",", "}", ",", "MaxLevel", ":", "DefaultMaxLevel", ",", "}", "}", "\n", "}" ]
// NewCustomSet returns a new Set that will use lessThan as the // comparison function. lessThan should define a linear order on // elements you intend to use with the Set.
[ "NewCustomSet", "returns", "a", "new", "Set", "that", "will", "use", "lessThan", "as", "the", "comparison", "function", ".", "lessThan", "should", "define", "a", "linear", "order", "on", "elements", "you", "intend", "to", "use", "with", "the", "Set", "." ]
2dfbae5fcf46374f166f8969cb07e167f1be6273
https://github.com/ryszard/goskiplist/blob/2dfbae5fcf46374f166f8969cb07e167f1be6273/skiplist/skiplist.go#L570-L578
1,585
ryszard/goskiplist
skiplist/skiplist.go
NewIntSet
func NewIntSet() *Set { return NewCustomSet(func(l, r interface{}) bool { return l.(int) < r.(int) }) }
go
func NewIntSet() *Set { return NewCustomSet(func(l, r interface{}) bool { return l.(int) < r.(int) }) }
[ "func", "NewIntSet", "(", ")", "*", "Set", "{", "return", "NewCustomSet", "(", "func", "(", "l", ",", "r", "interface", "{", "}", ")", "bool", "{", "return", "l", ".", "(", "int", ")", "<", "r", ".", "(", "int", ")", "\n", "}", ")", "\n", "}" ]
// NewIntSet returns a new Set that accepts int elements.
[ "NewIntSet", "returns", "a", "new", "Set", "that", "accepts", "int", "elements", "." ]
2dfbae5fcf46374f166f8969cb07e167f1be6273
https://github.com/ryszard/goskiplist/blob/2dfbae5fcf46374f166f8969cb07e167f1be6273/skiplist/skiplist.go#L581-L585
1,586
ryszard/goskiplist
skiplist/skiplist.go
NewStringSet
func NewStringSet() *Set { return NewCustomSet(func(l, r interface{}) bool { return l.(string) < r.(string) }) }
go
func NewStringSet() *Set { return NewCustomSet(func(l, r interface{}) bool { return l.(string) < r.(string) }) }
[ "func", "NewStringSet", "(", ")", "*", "Set", "{", "return", "NewCustomSet", "(", "func", "(", "l", ",", "r", "interface", "{", "}", ")", "bool", "{", "return", "l", ".", "(", "string", ")", "<", "r", ".", "(", "string", ")", "\n", "}", ")", "\n", "}" ]
// NewStringSet returns a new Set that accepts string elements.
[ "NewStringSet", "returns", "a", "new", "Set", "that", "accepts", "string", "elements", "." ]
2dfbae5fcf46374f166f8969cb07e167f1be6273
https://github.com/ryszard/goskiplist/blob/2dfbae5fcf46374f166f8969cb07e167f1be6273/skiplist/skiplist.go#L588-L592
1,587
ryszard/goskiplist
skiplist/skiplist.go
Remove
func (s *Set) Remove(key interface{}) (ok bool) { _, ok = s.skiplist.Delete(key) return ok }
go
func (s *Set) Remove(key interface{}) (ok bool) { _, ok = s.skiplist.Delete(key) return ok }
[ "func", "(", "s", "*", "Set", ")", "Remove", "(", "key", "interface", "{", "}", ")", "(", "ok", "bool", ")", "{", "_", ",", "ok", "=", "s", ".", "skiplist", ".", "Delete", "(", "key", ")", "\n", "return", "ok", "\n", "}" ]
// Remove tries to remove key from the set. It returns true if key was // present.
[ "Remove", "tries", "to", "remove", "key", "from", "the", "set", ".", "It", "returns", "true", "if", "key", "was", "present", "." ]
2dfbae5fcf46374f166f8969cb07e167f1be6273
https://github.com/ryszard/goskiplist/blob/2dfbae5fcf46374f166f8969cb07e167f1be6273/skiplist/skiplist.go#L601-L604
1,588
ryszard/goskiplist
skiplist/skiplist.go
Contains
func (s *Set) Contains(key interface{}) bool { _, ok := s.skiplist.Get(key) return ok }
go
func (s *Set) Contains(key interface{}) bool { _, ok := s.skiplist.Get(key) return ok }
[ "func", "(", "s", "*", "Set", ")", "Contains", "(", "key", "interface", "{", "}", ")", "bool", "{", "_", ",", "ok", ":=", "s", ".", "skiplist", ".", "Get", "(", "key", ")", "\n", "return", "ok", "\n", "}" ]
// Contains returns true if key is present in s.
[ "Contains", "returns", "true", "if", "key", "is", "present", "in", "s", "." ]
2dfbae5fcf46374f166f8969cb07e167f1be6273
https://github.com/ryszard/goskiplist/blob/2dfbae5fcf46374f166f8969cb07e167f1be6273/skiplist/skiplist.go#L612-L615
1,589
ryszard/goskiplist
skiplist/skiplist.go
Range
func (s *Set) Range(from, to interface{}) Iterator { return s.skiplist.Range(from, to) }
go
func (s *Set) Range(from, to interface{}) Iterator { return s.skiplist.Range(from, to) }
[ "func", "(", "s", "*", "Set", ")", "Range", "(", "from", ",", "to", "interface", "{", "}", ")", "Iterator", "{", "return", "s", ".", "skiplist", ".", "Range", "(", "from", ",", "to", ")", "\n", "}" ]
// Range returns an iterator that will go through all the elements of // the set that are greater or equal than from, but less than to.
[ "Range", "returns", "an", "iterator", "that", "will", "go", "through", "all", "the", "elements", "of", "the", "set", "that", "are", "greater", "or", "equal", "than", "from", "but", "less", "than", "to", "." ]
2dfbae5fcf46374f166f8969cb07e167f1be6273
https://github.com/ryszard/goskiplist/blob/2dfbae5fcf46374f166f8969cb07e167f1be6273/skiplist/skiplist.go#L623-L625
1,590
manifoldco/torus-cli
registry/org_invites.go
Approve
func (o *OrgInvitesClient) Approve(ctx context.Context, inviteID *identity.ID) (*envelope.OrgInvite, error) { invite := envelope.OrgInvite{} path := "/org-invites/" + inviteID.String() + "/approve" err := o.client.RoundTrip(ctx, "POST", path, nil, nil, &invite) return &invite, err }
go
func (o *OrgInvitesClient) Approve(ctx context.Context, inviteID *identity.ID) (*envelope.OrgInvite, error) { invite := envelope.OrgInvite{} path := "/org-invites/" + inviteID.String() + "/approve" err := o.client.RoundTrip(ctx, "POST", path, nil, nil, &invite) return &invite, err }
[ "func", "(", "o", "*", "OrgInvitesClient", ")", "Approve", "(", "ctx", "context", ".", "Context", ",", "inviteID", "*", "identity", ".", "ID", ")", "(", "*", "envelope", ".", "OrgInvite", ",", "error", ")", "{", "invite", ":=", "envelope", ".", "OrgInvite", "{", "}", "\n", "path", ":=", "\"", "\"", "+", "inviteID", ".", "String", "(", ")", "+", "\"", "\"", "\n", "err", ":=", "o", ".", "client", ".", "RoundTrip", "(", "ctx", ",", "\"", "\"", ",", "path", ",", "nil", ",", "nil", ",", "&", "invite", ")", "\n", "return", "&", "invite", ",", "err", "\n", "}" ]
// Approve sends an approval notification to the registry regarding a specific // invitation.
[ "Approve", "sends", "an", "approval", "notification", "to", "the", "registry", "regarding", "a", "specific", "invitation", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/registry/org_invites.go#L23-L28
1,591
manifoldco/torus-cli
registry/org_invites.go
List
func (o *OrgInvitesClient) List(ctx context.Context, orgID *identity.ID, states []string, email string) ([]envelope.OrgInvite, error) { v := &url.Values{} v.Set("org_id", orgID.String()) for _, state := range states { v.Add("state", state) } if email != "" { v.Add("email", email) } var invites []envelope.OrgInvite err := o.client.RoundTrip(ctx, "GET", "/org-invites", v, nil, &invites) return invites, err }
go
func (o *OrgInvitesClient) List(ctx context.Context, orgID *identity.ID, states []string, email string) ([]envelope.OrgInvite, error) { v := &url.Values{} v.Set("org_id", orgID.String()) for _, state := range states { v.Add("state", state) } if email != "" { v.Add("email", email) } var invites []envelope.OrgInvite err := o.client.RoundTrip(ctx, "GET", "/org-invites", v, nil, &invites) return invites, err }
[ "func", "(", "o", "*", "OrgInvitesClient", ")", "List", "(", "ctx", "context", ".", "Context", ",", "orgID", "*", "identity", ".", "ID", ",", "states", "[", "]", "string", ",", "email", "string", ")", "(", "[", "]", "envelope", ".", "OrgInvite", ",", "error", ")", "{", "v", ":=", "&", "url", ".", "Values", "{", "}", "\n", "v", ".", "Set", "(", "\"", "\"", ",", "orgID", ".", "String", "(", ")", ")", "\n\n", "for", "_", ",", "state", ":=", "range", "states", "{", "v", ".", "Add", "(", "\"", "\"", ",", "state", ")", "\n", "}", "\n\n", "if", "email", "!=", "\"", "\"", "{", "v", ".", "Add", "(", "\"", "\"", ",", "email", ")", "\n", "}", "\n\n", "var", "invites", "[", "]", "envelope", ".", "OrgInvite", "\n", "err", ":=", "o", ".", "client", ".", "RoundTrip", "(", "ctx", ",", "\"", "\"", ",", "\"", "\"", ",", "v", ",", "nil", ",", "&", "invites", ")", "\n", "return", "invites", ",", "err", "\n", "}" ]
// List lists all invites for a given org with the given states
[ "List", "lists", "all", "invites", "for", "a", "given", "org", "with", "the", "given", "states" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/registry/org_invites.go#L43-L58
1,592
manifoldco/torus-cli
registry/org_invites.go
Accept
func (o *OrgInvitesClient) Accept(ctx context.Context, org, email, code string) error { data := apitypes.InviteAccept{ Org: org, Email: email, Code: code, } return o.client.RoundTrip(ctx, "POST", "/org-invites/accept", nil, &data, nil) }
go
func (o *OrgInvitesClient) Accept(ctx context.Context, org, email, code string) error { data := apitypes.InviteAccept{ Org: org, Email: email, Code: code, } return o.client.RoundTrip(ctx, "POST", "/org-invites/accept", nil, &data, nil) }
[ "func", "(", "o", "*", "OrgInvitesClient", ")", "Accept", "(", "ctx", "context", ".", "Context", ",", "org", ",", "email", ",", "code", "string", ")", "error", "{", "data", ":=", "apitypes", ".", "InviteAccept", "{", "Org", ":", "org", ",", "Email", ":", "email", ",", "Code", ":", "code", ",", "}", "\n\n", "return", "o", ".", "client", ".", "RoundTrip", "(", "ctx", ",", "\"", "\"", ",", "\"", "\"", ",", "nil", ",", "&", "data", ",", "nil", ")", "\n", "}" ]
// Accept executes the accept invite request
[ "Accept", "executes", "the", "accept", "invite", "request" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/registry/org_invites.go#L61-L69
1,593
manifoldco/torus-cli
registry/org_invites.go
Send
func (o *OrgInvitesClient) Send(ctx context.Context, email string, orgID, inviterID identity.ID, teamIDs []identity.ID) error { now := time.Now() inviteBody := primitive.OrgInvite{ OrgID: &orgID, InviterID: &inviterID, PendingTeams: teamIDs, Email: email, Created: &now, // Null values below InviteeID: nil, ApproverID: nil, Accepted: nil, Approved: nil, } ID, err := identity.NewMutable(&inviteBody) if err != nil { return err } invite := envelope.OrgInvite{ ID: &ID, Version: 1, Body: &inviteBody, } return o.client.RoundTrip(ctx, "POST", "/org-invites", nil, &invite, nil) }
go
func (o *OrgInvitesClient) Send(ctx context.Context, email string, orgID, inviterID identity.ID, teamIDs []identity.ID) error { now := time.Now() inviteBody := primitive.OrgInvite{ OrgID: &orgID, InviterID: &inviterID, PendingTeams: teamIDs, Email: email, Created: &now, // Null values below InviteeID: nil, ApproverID: nil, Accepted: nil, Approved: nil, } ID, err := identity.NewMutable(&inviteBody) if err != nil { return err } invite := envelope.OrgInvite{ ID: &ID, Version: 1, Body: &inviteBody, } return o.client.RoundTrip(ctx, "POST", "/org-invites", nil, &invite, nil) }
[ "func", "(", "o", "*", "OrgInvitesClient", ")", "Send", "(", "ctx", "context", ".", "Context", ",", "email", "string", ",", "orgID", ",", "inviterID", "identity", ".", "ID", ",", "teamIDs", "[", "]", "identity", ".", "ID", ")", "error", "{", "now", ":=", "time", ".", "Now", "(", ")", "\n\n", "inviteBody", ":=", "primitive", ".", "OrgInvite", "{", "OrgID", ":", "&", "orgID", ",", "InviterID", ":", "&", "inviterID", ",", "PendingTeams", ":", "teamIDs", ",", "Email", ":", "email", ",", "Created", ":", "&", "now", ",", "// Null values below", "InviteeID", ":", "nil", ",", "ApproverID", ":", "nil", ",", "Accepted", ":", "nil", ",", "Approved", ":", "nil", ",", "}", "\n\n", "ID", ",", "err", ":=", "identity", ".", "NewMutable", "(", "&", "inviteBody", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "invite", ":=", "envelope", ".", "OrgInvite", "{", "ID", ":", "&", "ID", ",", "Version", ":", "1", ",", "Body", ":", "&", "inviteBody", ",", "}", "\n\n", "return", "o", ".", "client", ".", "RoundTrip", "(", "ctx", ",", "\"", "\"", ",", "\"", "\"", ",", "nil", ",", "&", "invite", ",", "nil", ")", "\n", "}" ]
// Send creates a new org invitation
[ "Send", "creates", "a", "new", "org", "invitation" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/registry/org_invites.go#L72-L100
1,594
manifoldco/torus-cli
registry/org_invites.go
Associate
func (o *OrgInvitesClient) Associate(ctx context.Context, org, email, code string) (*envelope.OrgInvite, error) { // Same payload as accept, re-use type data := apitypes.InviteAccept{ Org: org, Email: email, Code: code, } invite := envelope.OrgInvite{} err := o.client.RoundTrip(ctx, "POST", "/org-invites/associate", nil, &data, &invite) return &invite, err }
go
func (o *OrgInvitesClient) Associate(ctx context.Context, org, email, code string) (*envelope.OrgInvite, error) { // Same payload as accept, re-use type data := apitypes.InviteAccept{ Org: org, Email: email, Code: code, } invite := envelope.OrgInvite{} err := o.client.RoundTrip(ctx, "POST", "/org-invites/associate", nil, &data, &invite) return &invite, err }
[ "func", "(", "o", "*", "OrgInvitesClient", ")", "Associate", "(", "ctx", "context", ".", "Context", ",", "org", ",", "email", ",", "code", "string", ")", "(", "*", "envelope", ".", "OrgInvite", ",", "error", ")", "{", "// Same payload as accept, re-use type", "data", ":=", "apitypes", ".", "InviteAccept", "{", "Org", ":", "org", ",", "Email", ":", "email", ",", "Code", ":", "code", ",", "}", "\n\n", "invite", ":=", "envelope", ".", "OrgInvite", "{", "}", "\n", "err", ":=", "o", ".", "client", ".", "RoundTrip", "(", "ctx", ",", "\"", "\"", ",", "\"", "\"", ",", "nil", ",", "&", "data", ",", "&", "invite", ")", "\n", "return", "&", "invite", ",", "err", "\n", "}" ]
// Associate executes the associate invite request
[ "Associate", "executes", "the", "associate", "invite", "request" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/registry/org_invites.go#L103-L114
1,595
manifoldco/torus-cli
daemon/observer/observer.go
Notifier
func (n *Notifier) Notifier(total uint) *Notifier { notifier := &Notifier{ total: total, current: 0, transaction: nil, totalUpdates: n.totalUpdates, notifications: n.notifications, observerClosed: n.observerClosed, ctxDone: n.ctxDone, } n.totalUpdates <- total return notifier }
go
func (n *Notifier) Notifier(total uint) *Notifier { notifier := &Notifier{ total: total, current: 0, transaction: nil, totalUpdates: n.totalUpdates, notifications: n.notifications, observerClosed: n.observerClosed, ctxDone: n.ctxDone, } n.totalUpdates <- total return notifier }
[ "func", "(", "n", "*", "Notifier", ")", "Notifier", "(", "total", "uint", ")", "*", "Notifier", "{", "notifier", ":=", "&", "Notifier", "{", "total", ":", "total", ",", "current", ":", "0", ",", "transaction", ":", "nil", ",", "totalUpdates", ":", "n", ".", "totalUpdates", ",", "notifications", ":", "n", ".", "notifications", ",", "observerClosed", ":", "n", ".", "observerClosed", ",", "ctxDone", ":", "n", ".", "ctxDone", ",", "}", "\n\n", "n", ".", "totalUpdates", "<-", "total", "\n", "return", "notifier", "\n", "}" ]
// Notifier creates a child notifier to this Notifier
[ "Notifier", "creates", "a", "child", "notifier", "to", "this", "Notifier" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/daemon/observer/observer.go#L113-L126
1,596
manifoldco/torus-cli
daemon/observer/observer.go
Notify
func (n *Notifier) Notify(eventType EventType, message string, increment bool) { notif := &notification{ Type: eventType, Message: message, Increment: increment, } if increment { n.Lock() n.current++ n.Unlock() } n.RLock() current := n.current total := n.total n.RUnlock() if current > total { panic(fmt.Sprintf( "notifications exceed maximum %d/%d", current, total)) } select { case n.notifications <- notif: return case <-n.observerClosed: return case <-n.ctxDone: return } }
go
func (n *Notifier) Notify(eventType EventType, message string, increment bool) { notif := &notification{ Type: eventType, Message: message, Increment: increment, } if increment { n.Lock() n.current++ n.Unlock() } n.RLock() current := n.current total := n.total n.RUnlock() if current > total { panic(fmt.Sprintf( "notifications exceed maximum %d/%d", current, total)) } select { case n.notifications <- notif: return case <-n.observerClosed: return case <-n.ctxDone: return } }
[ "func", "(", "n", "*", "Notifier", ")", "Notify", "(", "eventType", "EventType", ",", "message", "string", ",", "increment", "bool", ")", "{", "notif", ":=", "&", "notification", "{", "Type", ":", "eventType", ",", "Message", ":", "message", ",", "Increment", ":", "increment", ",", "}", "\n\n", "if", "increment", "{", "n", ".", "Lock", "(", ")", "\n", "n", ".", "current", "++", "\n", "n", ".", "Unlock", "(", ")", "\n", "}", "\n\n", "n", ".", "RLock", "(", ")", "\n", "current", ":=", "n", ".", "current", "\n", "total", ":=", "n", ".", "total", "\n", "n", ".", "RUnlock", "(", ")", "\n\n", "if", "current", ">", "total", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "current", ",", "total", ")", ")", "\n", "}", "\n\n", "select", "{", "case", "n", ".", "notifications", "<-", "notif", ":", "return", "\n", "case", "<-", "n", ".", "observerClosed", ":", "return", "\n", "case", "<-", "n", ".", "ctxDone", ":", "return", "\n", "}", "\n", "}" ]
// Notify publishes an event to all SSE observers. This function panics when it // is called more often than it is supposed to have been called.
[ "Notify", "publishes", "an", "event", "to", "all", "SSE", "observers", ".", "This", "function", "panics", "when", "it", "is", "called", "more", "often", "than", "it", "is", "supposed", "to", "have", "been", "called", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/daemon/observer/observer.go#L130-L161
1,597
manifoldco/torus-cli
daemon/observer/observer.go
New
func New() *Observer { return &Observer{ notify: make(chan *event), closed: make(chan int), observers: make(map[chan []byte]bool), newObservers: make(chan chan []byte), closedObservers: make(chan chan []byte), } }
go
func New() *Observer { return &Observer{ notify: make(chan *event), closed: make(chan int), observers: make(map[chan []byte]bool), newObservers: make(chan chan []byte), closedObservers: make(chan chan []byte), } }
[ "func", "New", "(", ")", "*", "Observer", "{", "return", "&", "Observer", "{", "notify", ":", "make", "(", "chan", "*", "event", ")", ",", "closed", ":", "make", "(", "chan", "int", ")", ",", "observers", ":", "make", "(", "map", "[", "chan", "[", "]", "byte", "]", "bool", ")", ",", "newObservers", ":", "make", "(", "chan", "chan", "[", "]", "byte", ")", ",", "closedObservers", ":", "make", "(", "chan", "chan", "[", "]", "byte", ")", ",", "}", "\n", "}" ]
// New returns a new initialized Observer
[ "New", "returns", "a", "new", "initialized", "Observer" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/daemon/observer/observer.go#L164-L174
1,598
manifoldco/torus-cli
daemon/observer/observer.go
Notifier
func (o *Observer) Notifier(ctx context.Context, total uint) (*Notifier, error) { if ctx == nil { return nil, errors.New("Context must be provided") } id, ok := ctx.Value(CtxRequestID).(string) if !ok { return nil, errors.New("Missing 'id' property in Context") } totalUpdates := make(chan uint) notifications := make(chan *notification) t := &transaction{ requestID: id, total: total, current: 0, totalUpdates: totalUpdates, events: o.notify, notifications: notifications, observerClosed: o.closed, ctxDone: ctx.Done(), } t.start() n := &Notifier{ total: total, current: 0, transaction: t, totalUpdates: totalUpdates, notifications: notifications, observerClosed: t.observerClosed, ctxDone: t.ctxDone, } return n, nil }
go
func (o *Observer) Notifier(ctx context.Context, total uint) (*Notifier, error) { if ctx == nil { return nil, errors.New("Context must be provided") } id, ok := ctx.Value(CtxRequestID).(string) if !ok { return nil, errors.New("Missing 'id' property in Context") } totalUpdates := make(chan uint) notifications := make(chan *notification) t := &transaction{ requestID: id, total: total, current: 0, totalUpdates: totalUpdates, events: o.notify, notifications: notifications, observerClosed: o.closed, ctxDone: ctx.Done(), } t.start() n := &Notifier{ total: total, current: 0, transaction: t, totalUpdates: totalUpdates, notifications: notifications, observerClosed: t.observerClosed, ctxDone: t.ctxDone, } return n, nil }
[ "func", "(", "o", "*", "Observer", ")", "Notifier", "(", "ctx", "context", ".", "Context", ",", "total", "uint", ")", "(", "*", "Notifier", ",", "error", ")", "{", "if", "ctx", "==", "nil", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "id", ",", "ok", ":=", "ctx", ".", "Value", "(", "CtxRequestID", ")", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "totalUpdates", ":=", "make", "(", "chan", "uint", ")", "\n", "notifications", ":=", "make", "(", "chan", "*", "notification", ")", "\n\n", "t", ":=", "&", "transaction", "{", "requestID", ":", "id", ",", "total", ":", "total", ",", "current", ":", "0", ",", "totalUpdates", ":", "totalUpdates", ",", "events", ":", "o", ".", "notify", ",", "notifications", ":", "notifications", ",", "observerClosed", ":", "o", ".", "closed", ",", "ctxDone", ":", "ctx", ".", "Done", "(", ")", ",", "}", "\n\n", "t", ".", "start", "(", ")", "\n\n", "n", ":=", "&", "Notifier", "{", "total", ":", "total", ",", "current", ":", "0", ",", "transaction", ":", "t", ",", "totalUpdates", ":", "totalUpdates", ",", "notifications", ":", "notifications", ",", "observerClosed", ":", "t", ".", "observerClosed", ",", "ctxDone", ":", "t", ".", "ctxDone", ",", "}", "\n\n", "return", "n", ",", "nil", "\n", "}" ]
// Notifier creates a new transaction for sending notifications
[ "Notifier", "creates", "a", "new", "transaction", "for", "sending", "notifications" ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/daemon/observer/observer.go#L177-L215
1,599
manifoldco/torus-cli
daemon/observer/observer.go
ServeHTTP
func (o *Observer) ServeHTTP(rw http.ResponseWriter, r *http.Request) { rwf := rw.(http.Flusher) closed := rw.(http.CloseNotifier).CloseNotify() notify := make(chan []byte) o.newObservers <- notify defer func() { o.closedObservers <- notify }() rw.Header().Set("Content-Type", "text/event-stream") rw.Header().Set("Connection", "keep-alive") rwf.Flush() for { select { case evt := <-notify: // Write the event to the client. we ignore errors here, and // let the close channel tell us when to stop writing. rw.Write(evt) rwf.Flush() case <-closed: // client has disconnected. Exit. return case <-o.closed: // The Observer is shutting down. Exit. return } } }
go
func (o *Observer) ServeHTTP(rw http.ResponseWriter, r *http.Request) { rwf := rw.(http.Flusher) closed := rw.(http.CloseNotifier).CloseNotify() notify := make(chan []byte) o.newObservers <- notify defer func() { o.closedObservers <- notify }() rw.Header().Set("Content-Type", "text/event-stream") rw.Header().Set("Connection", "keep-alive") rwf.Flush() for { select { case evt := <-notify: // Write the event to the client. we ignore errors here, and // let the close channel tell us when to stop writing. rw.Write(evt) rwf.Flush() case <-closed: // client has disconnected. Exit. return case <-o.closed: // The Observer is shutting down. Exit. return } } }
[ "func", "(", "o", "*", "Observer", ")", "ServeHTTP", "(", "rw", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "rwf", ":=", "rw", ".", "(", "http", ".", "Flusher", ")", "\n", "closed", ":=", "rw", ".", "(", "http", ".", "CloseNotifier", ")", ".", "CloseNotify", "(", ")", "\n\n", "notify", ":=", "make", "(", "chan", "[", "]", "byte", ")", "\n", "o", ".", "newObservers", "<-", "notify", "\n\n", "defer", "func", "(", ")", "{", "o", ".", "closedObservers", "<-", "notify", "\n", "}", "(", ")", "\n\n", "rw", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "rw", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "rwf", ".", "Flush", "(", ")", "\n\n", "for", "{", "select", "{", "case", "evt", ":=", "<-", "notify", ":", "// Write the event to the client. we ignore errors here, and", "// let the close channel tell us when to stop writing.", "rw", ".", "Write", "(", "evt", ")", "\n", "rwf", ".", "Flush", "(", ")", "\n\n", "case", "<-", "closed", ":", "// client has disconnected. Exit.", "return", "\n", "case", "<-", "o", ".", "closed", ":", "// The Observer is shutting down. Exit.", "return", "\n", "}", "\n", "}", "\n", "}" ]
// ServeHTTP implements the http.Handler interface for providing server-sent // events of observed notifications.
[ "ServeHTTP", "implements", "the", "http", ".", "Handler", "interface", "for", "providing", "server", "-", "sent", "events", "of", "observed", "notifications", "." ]
137599f985e6f676c081ffb4230aaad52fb7d26c
https://github.com/manifoldco/torus-cli/blob/137599f985e6f676c081ffb4230aaad52fb7d26c/daemon/observer/observer.go#L219-L249