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
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
oklog/ulid
ulid.go
MustParse
func MustParse(ulid string) ULID { id, err := Parse(ulid) if err != nil { panic(err) } return id }
go
func MustParse(ulid string) ULID { id, err := Parse(ulid) if err != nil { panic(err) } return id }
[ "func", "MustParse", "(", "ulid", "string", ")", "ULID", "{", "id", ",", "err", ":=", "Parse", "(", "ulid", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "id", "\n", "}" ]
// MustParse is a convenience function equivalent to Parse that panics on failure // instead of returning an error.
[ "MustParse", "is", "a", "convenience", "function", "equivalent", "to", "Parse", "that", "panics", "on", "failure", "instead", "of", "returning", "an", "error", "." ]
bacfb41fdd06edf5294635d18ec387dee671a964
https://github.com/oklog/ulid/blob/bacfb41fdd06edf5294635d18ec387dee671a964/ulid.go#L219-L225
train
oklog/ulid
ulid.go
MustParseStrict
func MustParseStrict(ulid string) ULID { id, err := ParseStrict(ulid) if err != nil { panic(err) } return id }
go
func MustParseStrict(ulid string) ULID { id, err := ParseStrict(ulid) if err != nil { panic(err) } return id }
[ "func", "MustParseStrict", "(", "ulid", "string", ")", "ULID", "{", "id", ",", "err", ":=", "ParseStrict", "(", "ulid", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "id", "\n", "}" ]
// MustParseStrict is a convenience function equivalent to ParseStrict that // panics on failure instead of returning an error.
[ "MustParseStrict", "is", "a", "convenience", "function", "equivalent", "to", "ParseStrict", "that", "panics", "on", "failure", "instead", "of", "returning", "an", "error", "." ]
bacfb41fdd06edf5294635d18ec387dee671a964
https://github.com/oklog/ulid/blob/bacfb41fdd06edf5294635d18ec387dee671a964/ulid.go#L229-L235
train
oklog/ulid
ulid.go
MarshalBinary
func (id ULID) MarshalBinary() ([]byte, error) { ulid := make([]byte, len(id)) return ulid, id.MarshalBinaryTo(ulid) }
go
func (id ULID) MarshalBinary() ([]byte, error) { ulid := make([]byte, len(id)) return ulid, id.MarshalBinaryTo(ulid) }
[ "func", "(", "id", "ULID", ")", "MarshalBinary", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "ulid", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "id", ")", ")", "\n", "return", "ulid", ",", "id", ".", "MarshalBinaryTo", "(", "ulid", ")", "\n", "}" ]
// MarshalBinary implements the encoding.BinaryMarshaler interface by // returning the ULID as a byte slice.
[ "MarshalBinary", "implements", "the", "encoding", ".", "BinaryMarshaler", "interface", "by", "returning", "the", "ULID", "as", "a", "byte", "slice", "." ]
bacfb41fdd06edf5294635d18ec387dee671a964
https://github.com/oklog/ulid/blob/bacfb41fdd06edf5294635d18ec387dee671a964/ulid.go#L248-L251
train
oklog/ulid
ulid.go
UnmarshalBinary
func (id *ULID) UnmarshalBinary(data []byte) error { if len(data) != len(*id) { return ErrDataSize } copy((*id)[:], data) return nil }
go
func (id *ULID) UnmarshalBinary(data []byte) error { if len(data) != len(*id) { return ErrDataSize } copy((*id)[:], data) return nil }
[ "func", "(", "id", "*", "ULID", ")", "UnmarshalBinary", "(", "data", "[", "]", "byte", ")", "error", "{", "if", "len", "(", "data", ")", "!=", "len", "(", "*", "id", ")", "{", "return", "ErrDataSize", "\n", "}", "\n\n", "copy", "(", "(", "*", "id", ")", "[", ":", "]", ",", "data", ")", "\n", "return", "nil", "\n", "}" ]
// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface by // copying the passed data and converting it to an ULID. ErrDataSize is // returned if the data length is different from ULID length.
[ "UnmarshalBinary", "implements", "the", "encoding", ".", "BinaryUnmarshaler", "interface", "by", "copying", "the", "passed", "data", "and", "converting", "it", "to", "an", "ULID", ".", "ErrDataSize", "is", "returned", "if", "the", "data", "length", "is", "different", "from", "ULID", "length", "." ]
bacfb41fdd06edf5294635d18ec387dee671a964
https://github.com/oklog/ulid/blob/bacfb41fdd06edf5294635d18ec387dee671a964/ulid.go#L267-L274
train
oklog/ulid
ulid.go
MarshalText
func (id ULID) MarshalText() ([]byte, error) { ulid := make([]byte, EncodedSize) return ulid, id.MarshalTextTo(ulid) }
go
func (id ULID) MarshalText() ([]byte, error) { ulid := make([]byte, EncodedSize) return ulid, id.MarshalTextTo(ulid) }
[ "func", "(", "id", "ULID", ")", "MarshalText", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "ulid", ":=", "make", "(", "[", "]", "byte", ",", "EncodedSize", ")", "\n", "return", "ulid", ",", "id", ".", "MarshalTextTo", "(", "ulid", ")", "\n", "}" ]
// MarshalText implements the encoding.TextMarshaler interface by // returning the string encoded ULID.
[ "MarshalText", "implements", "the", "encoding", ".", "TextMarshaler", "interface", "by", "returning", "the", "string", "encoded", "ULID", "." ]
bacfb41fdd06edf5294635d18ec387dee671a964
https://github.com/oklog/ulid/blob/bacfb41fdd06edf5294635d18ec387dee671a964/ulid.go#L281-L284
train
oklog/ulid
ulid.go
Time
func (id ULID) Time() uint64 { return uint64(id[5]) | uint64(id[4])<<8 | uint64(id[3])<<16 | uint64(id[2])<<24 | uint64(id[1])<<32 | uint64(id[0])<<40 }
go
func (id ULID) Time() uint64 { return uint64(id[5]) | uint64(id[4])<<8 | uint64(id[3])<<16 | uint64(id[2])<<24 | uint64(id[1])<<32 | uint64(id[0])<<40 }
[ "func", "(", "id", "ULID", ")", "Time", "(", ")", "uint64", "{", "return", "uint64", "(", "id", "[", "5", "]", ")", "|", "uint64", "(", "id", "[", "4", "]", ")", "<<", "8", "|", "uint64", "(", "id", "[", "3", "]", ")", "<<", "16", "|", "uint64", "(", "id", "[", "2", "]", ")", "<<", "24", "|", "uint64", "(", "id", "[", "1", "]", ")", "<<", "32", "|", "uint64", "(", "id", "[", "0", "]", ")", "<<", "40", "\n", "}" ]
// Time returns the Unix time in milliseconds encoded in the ULID. // Use the top level Time function to convert the returned value to // a time.Time.
[ "Time", "returns", "the", "Unix", "time", "in", "milliseconds", "encoded", "in", "the", "ULID", ".", "Use", "the", "top", "level", "Time", "function", "to", "convert", "the", "returned", "value", "to", "a", "time", ".", "Time", "." ]
bacfb41fdd06edf5294635d18ec387dee671a964
https://github.com/oklog/ulid/blob/bacfb41fdd06edf5294635d18ec387dee671a964/ulid.go#L375-L379
train
oklog/ulid
ulid.go
Timestamp
func Timestamp(t time.Time) uint64 { return uint64(t.Unix())*1000 + uint64(t.Nanosecond()/int(time.Millisecond)) }
go
func Timestamp(t time.Time) uint64 { return uint64(t.Unix())*1000 + uint64(t.Nanosecond()/int(time.Millisecond)) }
[ "func", "Timestamp", "(", "t", "time", ".", "Time", ")", "uint64", "{", "return", "uint64", "(", "t", ".", "Unix", "(", ")", ")", "*", "1000", "+", "uint64", "(", "t", ".", "Nanosecond", "(", ")", "/", "int", "(", "time", ".", "Millisecond", ")", ")", "\n", "}" ]
// Timestamp converts a time.Time to Unix milliseconds. // // Because of the way ULID stores time, times from the year // 10889 produces undefined results.
[ "Timestamp", "converts", "a", "time", ".", "Time", "to", "Unix", "milliseconds", ".", "Because", "of", "the", "way", "ULID", "stores", "time", "times", "from", "the", "year", "10889", "produces", "undefined", "results", "." ]
bacfb41fdd06edf5294635d18ec387dee671a964
https://github.com/oklog/ulid/blob/bacfb41fdd06edf5294635d18ec387dee671a964/ulid.go#L398-L401
train
oklog/ulid
ulid.go
Time
func Time(ms uint64) time.Time { s := int64(ms / 1e3) ns := int64((ms % 1e3) * 1e6) return time.Unix(s, ns) }
go
func Time(ms uint64) time.Time { s := int64(ms / 1e3) ns := int64((ms % 1e3) * 1e6) return time.Unix(s, ns) }
[ "func", "Time", "(", "ms", "uint64", ")", "time", ".", "Time", "{", "s", ":=", "int64", "(", "ms", "/", "1e3", ")", "\n", "ns", ":=", "int64", "(", "(", "ms", "%", "1e3", ")", "*", "1e6", ")", "\n", "return", "time", ".", "Unix", "(", "s", ",", "ns", ")", "\n", "}" ]
// Time converts Unix milliseconds in the format // returned by the Timestamp function to a time.Time.
[ "Time", "converts", "Unix", "milliseconds", "in", "the", "format", "returned", "by", "the", "Timestamp", "function", "to", "a", "time", ".", "Time", "." ]
bacfb41fdd06edf5294635d18ec387dee671a964
https://github.com/oklog/ulid/blob/bacfb41fdd06edf5294635d18ec387dee671a964/ulid.go#L405-L409
train
oklog/ulid
ulid.go
SetTime
func (id *ULID) SetTime(ms uint64) error { if ms > maxTime { return ErrBigTime } (*id)[0] = byte(ms >> 40) (*id)[1] = byte(ms >> 32) (*id)[2] = byte(ms >> 24) (*id)[3] = byte(ms >> 16) (*id)[4] = byte(ms >> 8) (*id)[5] = byte(ms) return nil }
go
func (id *ULID) SetTime(ms uint64) error { if ms > maxTime { return ErrBigTime } (*id)[0] = byte(ms >> 40) (*id)[1] = byte(ms >> 32) (*id)[2] = byte(ms >> 24) (*id)[3] = byte(ms >> 16) (*id)[4] = byte(ms >> 8) (*id)[5] = byte(ms) return nil }
[ "func", "(", "id", "*", "ULID", ")", "SetTime", "(", "ms", "uint64", ")", "error", "{", "if", "ms", ">", "maxTime", "{", "return", "ErrBigTime", "\n", "}", "\n\n", "(", "*", "id", ")", "[", "0", "]", "=", "byte", "(", "ms", ">>", "40", ")", "\n", "(", "*", "id", ")", "[", "1", "]", "=", "byte", "(", "ms", ">>", "32", ")", "\n", "(", "*", "id", ")", "[", "2", "]", "=", "byte", "(", "ms", ">>", "24", ")", "\n", "(", "*", "id", ")", "[", "3", "]", "=", "byte", "(", "ms", ">>", "16", ")", "\n", "(", "*", "id", ")", "[", "4", "]", "=", "byte", "(", "ms", ">>", "8", ")", "\n", "(", "*", "id", ")", "[", "5", "]", "=", "byte", "(", "ms", ")", "\n\n", "return", "nil", "\n", "}" ]
// SetTime sets the time component of the ULID to the given Unix time // in milliseconds.
[ "SetTime", "sets", "the", "time", "component", "of", "the", "ULID", "to", "the", "given", "Unix", "time", "in", "milliseconds", "." ]
bacfb41fdd06edf5294635d18ec387dee671a964
https://github.com/oklog/ulid/blob/bacfb41fdd06edf5294635d18ec387dee671a964/ulid.go#L413-L426
train
oklog/ulid
ulid.go
Entropy
func (id ULID) Entropy() []byte { e := make([]byte, 10) copy(e, id[6:]) return e }
go
func (id ULID) Entropy() []byte { e := make([]byte, 10) copy(e, id[6:]) return e }
[ "func", "(", "id", "ULID", ")", "Entropy", "(", ")", "[", "]", "byte", "{", "e", ":=", "make", "(", "[", "]", "byte", ",", "10", ")", "\n", "copy", "(", "e", ",", "id", "[", "6", ":", "]", ")", "\n", "return", "e", "\n", "}" ]
// Entropy returns the entropy from the ULID.
[ "Entropy", "returns", "the", "entropy", "from", "the", "ULID", "." ]
bacfb41fdd06edf5294635d18ec387dee671a964
https://github.com/oklog/ulid/blob/bacfb41fdd06edf5294635d18ec387dee671a964/ulid.go#L429-L433
train
oklog/ulid
ulid.go
Scan
func (id *ULID) Scan(src interface{}) error { switch x := src.(type) { case nil: return nil case string: return id.UnmarshalText([]byte(x)) case []byte: return id.UnmarshalBinary(x) } return ErrScanValue }
go
func (id *ULID) Scan(src interface{}) error { switch x := src.(type) { case nil: return nil case string: return id.UnmarshalText([]byte(x)) case []byte: return id.UnmarshalBinary(x) } return ErrScanValue }
[ "func", "(", "id", "*", "ULID", ")", "Scan", "(", "src", "interface", "{", "}", ")", "error", "{", "switch", "x", ":=", "src", ".", "(", "type", ")", "{", "case", "nil", ":", "return", "nil", "\n", "case", "string", ":", "return", "id", ".", "UnmarshalText", "(", "[", "]", "byte", "(", "x", ")", ")", "\n", "case", "[", "]", "byte", ":", "return", "id", ".", "UnmarshalBinary", "(", "x", ")", "\n", "}", "\n\n", "return", "ErrScanValue", "\n", "}" ]
// Scan implements the sql.Scanner interface. It supports scanning // a string or byte slice.
[ "Scan", "implements", "the", "sql", ".", "Scanner", "interface", ".", "It", "supports", "scanning", "a", "string", "or", "byte", "slice", "." ]
bacfb41fdd06edf5294635d18ec387dee671a964
https://github.com/oklog/ulid/blob/bacfb41fdd06edf5294635d18ec387dee671a964/ulid.go#L454-L465
train
oklog/ulid
ulid.go
MonotonicRead
func (m *MonotonicEntropy) MonotonicRead(ms uint64, entropy []byte) (err error) { if !m.entropy.IsZero() && m.ms == ms { err = m.increment() m.entropy.AppendTo(entropy) } else if _, err = io.ReadFull(m.Reader, entropy); err == nil { m.ms = ms m.entropy.SetBytes(entropy) } return err }
go
func (m *MonotonicEntropy) MonotonicRead(ms uint64, entropy []byte) (err error) { if !m.entropy.IsZero() && m.ms == ms { err = m.increment() m.entropy.AppendTo(entropy) } else if _, err = io.ReadFull(m.Reader, entropy); err == nil { m.ms = ms m.entropy.SetBytes(entropy) } return err }
[ "func", "(", "m", "*", "MonotonicEntropy", ")", "MonotonicRead", "(", "ms", "uint64", ",", "entropy", "[", "]", "byte", ")", "(", "err", "error", ")", "{", "if", "!", "m", ".", "entropy", ".", "IsZero", "(", ")", "&&", "m", ".", "ms", "==", "ms", "{", "err", "=", "m", ".", "increment", "(", ")", "\n", "m", ".", "entropy", ".", "AppendTo", "(", "entropy", ")", "\n", "}", "else", "if", "_", ",", "err", "=", "io", ".", "ReadFull", "(", "m", ".", "Reader", ",", "entropy", ")", ";", "err", "==", "nil", "{", "m", ".", "ms", "=", "ms", "\n", "m", ".", "entropy", ".", "SetBytes", "(", "entropy", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// MonotonicRead implements the MonotonicReader interface.
[ "MonotonicRead", "implements", "the", "MonotonicReader", "interface", "." ]
bacfb41fdd06edf5294635d18ec387dee671a964
https://github.com/oklog/ulid/blob/bacfb41fdd06edf5294635d18ec387dee671a964/ulid.go#L528-L537
train
olekukonko/tablewriter
table.go
NewWriter
func NewWriter(writer io.Writer) *Table { t := &Table{ out: writer, rows: [][]string{}, lines: [][][]string{}, cs: make(map[int]int), rs: make(map[int]int), headers: [][]string{}, footers: [][]string{}, caption: false, captionText: "Table caption.", autoFmt: true, autoWrap: true, reflowText: true, mW: MAX_ROW_WIDTH, pCenter: CENTER, pRow: ROW, pColumn: COLUMN, tColumn: -1, tRow: -1, hAlign: ALIGN_DEFAULT, fAlign: ALIGN_DEFAULT, align: ALIGN_DEFAULT, newLine: NEWLINE, rowLine: false, hdrLine: true, borders: Border{Left: true, Right: true, Bottom: true, Top: true}, colSize: -1, headerParams: []string{}, columnsParams: []string{}, footerParams: []string{}, columnsAlign: []int{}} return t }
go
func NewWriter(writer io.Writer) *Table { t := &Table{ out: writer, rows: [][]string{}, lines: [][][]string{}, cs: make(map[int]int), rs: make(map[int]int), headers: [][]string{}, footers: [][]string{}, caption: false, captionText: "Table caption.", autoFmt: true, autoWrap: true, reflowText: true, mW: MAX_ROW_WIDTH, pCenter: CENTER, pRow: ROW, pColumn: COLUMN, tColumn: -1, tRow: -1, hAlign: ALIGN_DEFAULT, fAlign: ALIGN_DEFAULT, align: ALIGN_DEFAULT, newLine: NEWLINE, rowLine: false, hdrLine: true, borders: Border{Left: true, Right: true, Bottom: true, Top: true}, colSize: -1, headerParams: []string{}, columnsParams: []string{}, footerParams: []string{}, columnsAlign: []int{}} return t }
[ "func", "NewWriter", "(", "writer", "io", ".", "Writer", ")", "*", "Table", "{", "t", ":=", "&", "Table", "{", "out", ":", "writer", ",", "rows", ":", "[", "]", "[", "]", "string", "{", "}", ",", "lines", ":", "[", "]", "[", "]", "[", "]", "string", "{", "}", ",", "cs", ":", "make", "(", "map", "[", "int", "]", "int", ")", ",", "rs", ":", "make", "(", "map", "[", "int", "]", "int", ")", ",", "headers", ":", "[", "]", "[", "]", "string", "{", "}", ",", "footers", ":", "[", "]", "[", "]", "string", "{", "}", ",", "caption", ":", "false", ",", "captionText", ":", "\"", "\"", ",", "autoFmt", ":", "true", ",", "autoWrap", ":", "true", ",", "reflowText", ":", "true", ",", "mW", ":", "MAX_ROW_WIDTH", ",", "pCenter", ":", "CENTER", ",", "pRow", ":", "ROW", ",", "pColumn", ":", "COLUMN", ",", "tColumn", ":", "-", "1", ",", "tRow", ":", "-", "1", ",", "hAlign", ":", "ALIGN_DEFAULT", ",", "fAlign", ":", "ALIGN_DEFAULT", ",", "align", ":", "ALIGN_DEFAULT", ",", "newLine", ":", "NEWLINE", ",", "rowLine", ":", "false", ",", "hdrLine", ":", "true", ",", "borders", ":", "Border", "{", "Left", ":", "true", ",", "Right", ":", "true", ",", "Bottom", ":", "true", ",", "Top", ":", "true", "}", ",", "colSize", ":", "-", "1", ",", "headerParams", ":", "[", "]", "string", "{", "}", ",", "columnsParams", ":", "[", "]", "string", "{", "}", ",", "footerParams", ":", "[", "]", "string", "{", "}", ",", "columnsAlign", ":", "[", "]", "int", "{", "}", "}", "\n", "return", "t", "\n", "}" ]
// Start New Table // Take io.Writer Directly
[ "Start", "New", "Table", "Take", "io", ".", "Writer", "Directly" ]
7e037d187b0c13d81ccf0dd1c6b990c2759e6597
https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L86-L119
train
olekukonko/tablewriter
table.go
Render
func (t *Table) Render() { if t.borders.Top { t.printLine(true) } t.printHeading() if t.autoMergeCells { t.printRowsMergeCells() } else { t.printRows() } if !t.rowLine && t.borders.Bottom { t.printLine(true) } t.printFooter() if t.caption { t.printCaption() } }
go
func (t *Table) Render() { if t.borders.Top { t.printLine(true) } t.printHeading() if t.autoMergeCells { t.printRowsMergeCells() } else { t.printRows() } if !t.rowLine && t.borders.Bottom { t.printLine(true) } t.printFooter() if t.caption { t.printCaption() } }
[ "func", "(", "t", "*", "Table", ")", "Render", "(", ")", "{", "if", "t", ".", "borders", ".", "Top", "{", "t", ".", "printLine", "(", "true", ")", "\n", "}", "\n", "t", ".", "printHeading", "(", ")", "\n", "if", "t", ".", "autoMergeCells", "{", "t", ".", "printRowsMergeCells", "(", ")", "\n", "}", "else", "{", "t", ".", "printRows", "(", ")", "\n", "}", "\n", "if", "!", "t", ".", "rowLine", "&&", "t", ".", "borders", ".", "Bottom", "{", "t", ".", "printLine", "(", "true", ")", "\n", "}", "\n", "t", ".", "printFooter", "(", ")", "\n\n", "if", "t", ".", "caption", "{", "t", ".", "printCaption", "(", ")", "\n", "}", "\n", "}" ]
// Render table output
[ "Render", "table", "output" ]
7e037d187b0c13d81ccf0dd1c6b990c2759e6597
https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L122-L140
train
olekukonko/tablewriter
table.go
SetHeader
func (t *Table) SetHeader(keys []string) { t.colSize = len(keys) for i, v := range keys { lines := t.parseDimension(v, i, headerRowIdx) t.headers = append(t.headers, lines) } }
go
func (t *Table) SetHeader(keys []string) { t.colSize = len(keys) for i, v := range keys { lines := t.parseDimension(v, i, headerRowIdx) t.headers = append(t.headers, lines) } }
[ "func", "(", "t", "*", "Table", ")", "SetHeader", "(", "keys", "[", "]", "string", ")", "{", "t", ".", "colSize", "=", "len", "(", "keys", ")", "\n", "for", "i", ",", "v", ":=", "range", "keys", "{", "lines", ":=", "t", ".", "parseDimension", "(", "v", ",", "i", ",", "headerRowIdx", ")", "\n", "t", ".", "headers", "=", "append", "(", "t", ".", "headers", ",", "lines", ")", "\n", "}", "\n", "}" ]
// Set table header
[ "Set", "table", "header" ]
7e037d187b0c13d81ccf0dd1c6b990c2759e6597
https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L148-L154
train
olekukonko/tablewriter
table.go
SetFooter
func (t *Table) SetFooter(keys []string) { //t.colSize = len(keys) for i, v := range keys { lines := t.parseDimension(v, i, footerRowIdx) t.footers = append(t.footers, lines) } }
go
func (t *Table) SetFooter(keys []string) { //t.colSize = len(keys) for i, v := range keys { lines := t.parseDimension(v, i, footerRowIdx) t.footers = append(t.footers, lines) } }
[ "func", "(", "t", "*", "Table", ")", "SetFooter", "(", "keys", "[", "]", "string", ")", "{", "//t.colSize = len(keys)", "for", "i", ",", "v", ":=", "range", "keys", "{", "lines", ":=", "t", ".", "parseDimension", "(", "v", ",", "i", ",", "footerRowIdx", ")", "\n", "t", ".", "footers", "=", "append", "(", "t", ".", "footers", ",", "lines", ")", "\n", "}", "\n", "}" ]
// Set table Footer
[ "Set", "table", "Footer" ]
7e037d187b0c13d81ccf0dd1c6b990c2759e6597
https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L157-L163
train
olekukonko/tablewriter
table.go
SetCaption
func (t *Table) SetCaption(caption bool, captionText ...string) { t.caption = caption if len(captionText) == 1 { t.captionText = captionText[0] } }
go
func (t *Table) SetCaption(caption bool, captionText ...string) { t.caption = caption if len(captionText) == 1 { t.captionText = captionText[0] } }
[ "func", "(", "t", "*", "Table", ")", "SetCaption", "(", "caption", "bool", ",", "captionText", "...", "string", ")", "{", "t", ".", "caption", "=", "caption", "\n", "if", "len", "(", "captionText", ")", "==", "1", "{", "t", ".", "captionText", "=", "captionText", "[", "0", "]", "\n", "}", "\n", "}" ]
// Set table Caption
[ "Set", "table", "Caption" ]
7e037d187b0c13d81ccf0dd1c6b990c2759e6597
https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L166-L171
train
olekukonko/tablewriter
table.go
SetColMinWidth
func (t *Table) SetColMinWidth(column int, width int) { t.cs[column] = width }
go
func (t *Table) SetColMinWidth(column int, width int) { t.cs[column] = width }
[ "func", "(", "t", "*", "Table", ")", "SetColMinWidth", "(", "column", "int", ",", "width", "int", ")", "{", "t", ".", "cs", "[", "column", "]", "=", "width", "\n", "}" ]
// Set the minimal width for a column
[ "Set", "the", "minimal", "width", "for", "a", "column" ]
7e037d187b0c13d81ccf0dd1c6b990c2759e6597
https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L194-L196
train
olekukonko/tablewriter
table.go
Append
func (t *Table) Append(row []string) { rowSize := len(t.headers) if rowSize > t.colSize { t.colSize = rowSize } n := len(t.lines) line := [][]string{} for i, v := range row { // Detect string width // Detect String height // Break strings into words out := t.parseDimension(v, i, n) // Append broken words line = append(line, out) } t.lines = append(t.lines, line) }
go
func (t *Table) Append(row []string) { rowSize := len(t.headers) if rowSize > t.colSize { t.colSize = rowSize } n := len(t.lines) line := [][]string{} for i, v := range row { // Detect string width // Detect String height // Break strings into words out := t.parseDimension(v, i, n) // Append broken words line = append(line, out) } t.lines = append(t.lines, line) }
[ "func", "(", "t", "*", "Table", ")", "Append", "(", "row", "[", "]", "string", ")", "{", "rowSize", ":=", "len", "(", "t", ".", "headers", ")", "\n", "if", "rowSize", ">", "t", ".", "colSize", "{", "t", ".", "colSize", "=", "rowSize", "\n", "}", "\n\n", "n", ":=", "len", "(", "t", ".", "lines", ")", "\n", "line", ":=", "[", "]", "[", "]", "string", "{", "}", "\n", "for", "i", ",", "v", ":=", "range", "row", "{", "// Detect string width", "// Detect String height", "// Break strings into words", "out", ":=", "t", ".", "parseDimension", "(", "v", ",", "i", ",", "n", ")", "\n\n", "// Append broken words", "line", "=", "append", "(", "line", ",", "out", ")", "\n", "}", "\n", "t", ".", "lines", "=", "append", "(", "t", ".", "lines", ",", "line", ")", "\n", "}" ]
// Append row to table
[ "Append", "row", "to", "table" ]
7e037d187b0c13d81ccf0dd1c6b990c2759e6597
https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L278-L297
train
olekukonko/tablewriter
table.go
AppendBulk
func (t *Table) AppendBulk(rows [][]string) { for _, row := range rows { t.Append(row) } }
go
func (t *Table) AppendBulk(rows [][]string) { for _, row := range rows { t.Append(row) } }
[ "func", "(", "t", "*", "Table", ")", "AppendBulk", "(", "rows", "[", "]", "[", "]", "string", ")", "{", "for", "_", ",", "row", ":=", "range", "rows", "{", "t", ".", "Append", "(", "row", ")", "\n", "}", "\n", "}" ]
// Allow Support for Bulk Append // Eliminates repeated for loops
[ "Allow", "Support", "for", "Bulk", "Append", "Eliminates", "repeated", "for", "loops" ]
7e037d187b0c13d81ccf0dd1c6b990c2759e6597
https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L301-L305
train
olekukonko/tablewriter
table.go
center
func (t *Table) center(i int) string { if i == -1 && !t.borders.Left { return t.pRow } if i == len(t.cs)-1 && !t.borders.Right { return t.pRow } return t.pCenter }
go
func (t *Table) center(i int) string { if i == -1 && !t.borders.Left { return t.pRow } if i == len(t.cs)-1 && !t.borders.Right { return t.pRow } return t.pCenter }
[ "func", "(", "t", "*", "Table", ")", "center", "(", "i", "int", ")", "string", "{", "if", "i", "==", "-", "1", "&&", "!", "t", ".", "borders", ".", "Left", "{", "return", "t", ".", "pRow", "\n", "}", "\n\n", "if", "i", "==", "len", "(", "t", ".", "cs", ")", "-", "1", "&&", "!", "t", ".", "borders", ".", "Right", "{", "return", "t", ".", "pRow", "\n", "}", "\n\n", "return", "t", ".", "pCenter", "\n", "}" ]
// Center based on position and border.
[ "Center", "based", "on", "position", "and", "border", "." ]
7e037d187b0c13d81ccf0dd1c6b990c2759e6597
https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L323-L333
train
olekukonko/tablewriter
table.go
printLine
func (t *Table) printLine(nl bool) { fmt.Fprint(t.out, t.center(-1)) for i := 0; i < len(t.cs); i++ { v := t.cs[i] fmt.Fprintf(t.out, "%s%s%s%s", t.pRow, strings.Repeat(string(t.pRow), v), t.pRow, t.center(i)) } if nl { fmt.Fprint(t.out, t.newLine) } }
go
func (t *Table) printLine(nl bool) { fmt.Fprint(t.out, t.center(-1)) for i := 0; i < len(t.cs); i++ { v := t.cs[i] fmt.Fprintf(t.out, "%s%s%s%s", t.pRow, strings.Repeat(string(t.pRow), v), t.pRow, t.center(i)) } if nl { fmt.Fprint(t.out, t.newLine) } }
[ "func", "(", "t", "*", "Table", ")", "printLine", "(", "nl", "bool", ")", "{", "fmt", ".", "Fprint", "(", "t", ".", "out", ",", "t", ".", "center", "(", "-", "1", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "t", ".", "cs", ")", ";", "i", "++", "{", "v", ":=", "t", ".", "cs", "[", "i", "]", "\n", "fmt", ".", "Fprintf", "(", "t", ".", "out", ",", "\"", "\"", ",", "t", ".", "pRow", ",", "strings", ".", "Repeat", "(", "string", "(", "t", ".", "pRow", ")", ",", "v", ")", ",", "t", ".", "pRow", ",", "t", ".", "center", "(", "i", ")", ")", "\n", "}", "\n", "if", "nl", "{", "fmt", ".", "Fprint", "(", "t", ".", "out", ",", "t", ".", "newLine", ")", "\n", "}", "\n", "}" ]
// Print line based on row width
[ "Print", "line", "based", "on", "row", "width" ]
7e037d187b0c13d81ccf0dd1c6b990c2759e6597
https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L336-L349
train
olekukonko/tablewriter
table.go
printLineOptionalCellSeparators
func (t *Table) printLineOptionalCellSeparators(nl bool, displayCellSeparator []bool) { fmt.Fprint(t.out, t.pCenter) for i := 0; i < len(t.cs); i++ { v := t.cs[i] if i > len(displayCellSeparator) || displayCellSeparator[i] { // Display the cell separator fmt.Fprintf(t.out, "%s%s%s%s", t.pRow, strings.Repeat(string(t.pRow), v), t.pRow, t.pCenter) } else { // Don't display the cell separator for this cell fmt.Fprintf(t.out, "%s%s", strings.Repeat(" ", v+2), t.pCenter) } } if nl { fmt.Fprint(t.out, t.newLine) } }
go
func (t *Table) printLineOptionalCellSeparators(nl bool, displayCellSeparator []bool) { fmt.Fprint(t.out, t.pCenter) for i := 0; i < len(t.cs); i++ { v := t.cs[i] if i > len(displayCellSeparator) || displayCellSeparator[i] { // Display the cell separator fmt.Fprintf(t.out, "%s%s%s%s", t.pRow, strings.Repeat(string(t.pRow), v), t.pRow, t.pCenter) } else { // Don't display the cell separator for this cell fmt.Fprintf(t.out, "%s%s", strings.Repeat(" ", v+2), t.pCenter) } } if nl { fmt.Fprint(t.out, t.newLine) } }
[ "func", "(", "t", "*", "Table", ")", "printLineOptionalCellSeparators", "(", "nl", "bool", ",", "displayCellSeparator", "[", "]", "bool", ")", "{", "fmt", ".", "Fprint", "(", "t", ".", "out", ",", "t", ".", "pCenter", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "t", ".", "cs", ")", ";", "i", "++", "{", "v", ":=", "t", ".", "cs", "[", "i", "]", "\n", "if", "i", ">", "len", "(", "displayCellSeparator", ")", "||", "displayCellSeparator", "[", "i", "]", "{", "// Display the cell separator", "fmt", ".", "Fprintf", "(", "t", ".", "out", ",", "\"", "\"", ",", "t", ".", "pRow", ",", "strings", ".", "Repeat", "(", "string", "(", "t", ".", "pRow", ")", ",", "v", ")", ",", "t", ".", "pRow", ",", "t", ".", "pCenter", ")", "\n", "}", "else", "{", "// Don't display the cell separator for this cell", "fmt", ".", "Fprintf", "(", "t", ".", "out", ",", "\"", "\"", ",", "strings", ".", "Repeat", "(", "\"", "\"", ",", "v", "+", "2", ")", ",", "t", ".", "pCenter", ")", "\n", "}", "\n", "}", "\n", "if", "nl", "{", "fmt", ".", "Fprint", "(", "t", ".", "out", ",", "t", ".", "newLine", ")", "\n", "}", "\n", "}" ]
// Print line based on row width with our without cell separator
[ "Print", "line", "based", "on", "row", "width", "with", "our", "without", "cell", "separator" ]
7e037d187b0c13d81ccf0dd1c6b990c2759e6597
https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L352-L373
train
olekukonko/tablewriter
table.go
pad
func pad(align int) func(string, string, int) string { padFunc := Pad switch align { case ALIGN_LEFT: padFunc = PadRight case ALIGN_RIGHT: padFunc = PadLeft } return padFunc }
go
func pad(align int) func(string, string, int) string { padFunc := Pad switch align { case ALIGN_LEFT: padFunc = PadRight case ALIGN_RIGHT: padFunc = PadLeft } return padFunc }
[ "func", "pad", "(", "align", "int", ")", "func", "(", "string", ",", "string", ",", "int", ")", "string", "{", "padFunc", ":=", "Pad", "\n", "switch", "align", "{", "case", "ALIGN_LEFT", ":", "padFunc", "=", "PadRight", "\n", "case", "ALIGN_RIGHT", ":", "padFunc", "=", "PadLeft", "\n", "}", "\n", "return", "padFunc", "\n", "}" ]
// Return the PadRight function if align is left, PadLeft if align is right, // and Pad by default
[ "Return", "the", "PadRight", "function", "if", "align", "is", "left", "PadLeft", "if", "align", "is", "right", "and", "Pad", "by", "default" ]
7e037d187b0c13d81ccf0dd1c6b990c2759e6597
https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L377-L386
train
olekukonko/tablewriter
table.go
printCaption
func (t Table) printCaption() { width := t.getTableWidth() paragraph, _ := WrapString(t.captionText, width) for linecount := 0; linecount < len(paragraph); linecount++ { fmt.Fprintln(t.out, paragraph[linecount]) } }
go
func (t Table) printCaption() { width := t.getTableWidth() paragraph, _ := WrapString(t.captionText, width) for linecount := 0; linecount < len(paragraph); linecount++ { fmt.Fprintln(t.out, paragraph[linecount]) } }
[ "func", "(", "t", "Table", ")", "printCaption", "(", ")", "{", "width", ":=", "t", ".", "getTableWidth", "(", ")", "\n", "paragraph", ",", "_", ":=", "WrapString", "(", "t", ".", "captionText", ",", "width", ")", "\n", "for", "linecount", ":=", "0", ";", "linecount", "<", "len", "(", "paragraph", ")", ";", "linecount", "++", "{", "fmt", ".", "Fprintln", "(", "t", ".", "out", ",", "paragraph", "[", "linecount", "]", ")", "\n", "}", "\n", "}" ]
// Print caption text
[ "Print", "caption", "text" ]
7e037d187b0c13d81ccf0dd1c6b990c2759e6597
https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L580-L586
train
olekukonko/tablewriter
table.go
getTableWidth
func (t Table) getTableWidth() int { var chars int for _, v := range t.cs { chars += v } // Add chars, spaces, seperators to calculate the total width of the table. // ncols := t.colSize // spaces := ncols * 2 // seps := ncols + 1 return (chars + (3 * t.colSize) + 2) }
go
func (t Table) getTableWidth() int { var chars int for _, v := range t.cs { chars += v } // Add chars, spaces, seperators to calculate the total width of the table. // ncols := t.colSize // spaces := ncols * 2 // seps := ncols + 1 return (chars + (3 * t.colSize) + 2) }
[ "func", "(", "t", "Table", ")", "getTableWidth", "(", ")", "int", "{", "var", "chars", "int", "\n", "for", "_", ",", "v", ":=", "range", "t", ".", "cs", "{", "chars", "+=", "v", "\n", "}", "\n\n", "// Add chars, spaces, seperators to calculate the total width of the table.", "// ncols := t.colSize", "// spaces := ncols * 2", "// seps := ncols + 1", "return", "(", "chars", "+", "(", "3", "*", "t", ".", "colSize", ")", "+", "2", ")", "\n", "}" ]
// Calculate the total number of characters in a row
[ "Calculate", "the", "total", "number", "of", "characters", "in", "a", "row" ]
7e037d187b0c13d81ccf0dd1c6b990c2759e6597
https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L589-L601
train
olekukonko/tablewriter
table.go
printRow
func (t *Table) printRow(columns [][]string, rowIdx int) { // Get Maximum Height max := t.rs[rowIdx] total := len(columns) // TODO Fix uneven col size // if total < t.colSize { // for n := t.colSize - total; n < t.colSize ; n++ { // columns = append(columns, []string{SPACE}) // t.cs[n] = t.mW // } //} // Pad Each Height pads := []int{} // Checking for ANSI escape sequences for columns is_esc_seq := false if len(t.columnsParams) > 0 { is_esc_seq = true } t.fillAlignment(total) for i, line := range columns { length := len(line) pad := max - length pads = append(pads, pad) for n := 0; n < pad; n++ { columns[i] = append(columns[i], " ") } } //fmt.Println(max, "\n") for x := 0; x < max; x++ { for y := 0; y < total; y++ { // Check if border is set fmt.Fprint(t.out, ConditionString((!t.borders.Left && y == 0), SPACE, t.pColumn)) fmt.Fprintf(t.out, SPACE) str := columns[y][x] // Embedding escape sequence with column value if is_esc_seq { str = format(str, t.columnsParams[y]) } // This would print alignment // Default alignment would use multiple configuration switch t.columnsAlign[y] { case ALIGN_CENTER: // fmt.Fprintf(t.out, "%s", Pad(str, SPACE, t.cs[y])) case ALIGN_RIGHT: fmt.Fprintf(t.out, "%s", PadLeft(str, SPACE, t.cs[y])) case ALIGN_LEFT: fmt.Fprintf(t.out, "%s", PadRight(str, SPACE, t.cs[y])) default: if decimal.MatchString(strings.TrimSpace(str)) || percent.MatchString(strings.TrimSpace(str)) { fmt.Fprintf(t.out, "%s", PadLeft(str, SPACE, t.cs[y])) } else { fmt.Fprintf(t.out, "%s", PadRight(str, SPACE, t.cs[y])) // TODO Custom alignment per column //if max == 1 || pads[y] > 0 { // fmt.Fprintf(t.out, "%s", Pad(str, SPACE, t.cs[y])) //} else { // fmt.Fprintf(t.out, "%s", PadRight(str, SPACE, t.cs[y])) //} } } fmt.Fprintf(t.out, SPACE) } // Check if border is set // Replace with space if not set fmt.Fprint(t.out, ConditionString(t.borders.Left, t.pColumn, SPACE)) fmt.Fprint(t.out, t.newLine) } if t.rowLine { t.printLine(true) } }
go
func (t *Table) printRow(columns [][]string, rowIdx int) { // Get Maximum Height max := t.rs[rowIdx] total := len(columns) // TODO Fix uneven col size // if total < t.colSize { // for n := t.colSize - total; n < t.colSize ; n++ { // columns = append(columns, []string{SPACE}) // t.cs[n] = t.mW // } //} // Pad Each Height pads := []int{} // Checking for ANSI escape sequences for columns is_esc_seq := false if len(t.columnsParams) > 0 { is_esc_seq = true } t.fillAlignment(total) for i, line := range columns { length := len(line) pad := max - length pads = append(pads, pad) for n := 0; n < pad; n++ { columns[i] = append(columns[i], " ") } } //fmt.Println(max, "\n") for x := 0; x < max; x++ { for y := 0; y < total; y++ { // Check if border is set fmt.Fprint(t.out, ConditionString((!t.borders.Left && y == 0), SPACE, t.pColumn)) fmt.Fprintf(t.out, SPACE) str := columns[y][x] // Embedding escape sequence with column value if is_esc_seq { str = format(str, t.columnsParams[y]) } // This would print alignment // Default alignment would use multiple configuration switch t.columnsAlign[y] { case ALIGN_CENTER: // fmt.Fprintf(t.out, "%s", Pad(str, SPACE, t.cs[y])) case ALIGN_RIGHT: fmt.Fprintf(t.out, "%s", PadLeft(str, SPACE, t.cs[y])) case ALIGN_LEFT: fmt.Fprintf(t.out, "%s", PadRight(str, SPACE, t.cs[y])) default: if decimal.MatchString(strings.TrimSpace(str)) || percent.MatchString(strings.TrimSpace(str)) { fmt.Fprintf(t.out, "%s", PadLeft(str, SPACE, t.cs[y])) } else { fmt.Fprintf(t.out, "%s", PadRight(str, SPACE, t.cs[y])) // TODO Custom alignment per column //if max == 1 || pads[y] > 0 { // fmt.Fprintf(t.out, "%s", Pad(str, SPACE, t.cs[y])) //} else { // fmt.Fprintf(t.out, "%s", PadRight(str, SPACE, t.cs[y])) //} } } fmt.Fprintf(t.out, SPACE) } // Check if border is set // Replace with space if not set fmt.Fprint(t.out, ConditionString(t.borders.Left, t.pColumn, SPACE)) fmt.Fprint(t.out, t.newLine) } if t.rowLine { t.printLine(true) } }
[ "func", "(", "t", "*", "Table", ")", "printRow", "(", "columns", "[", "]", "[", "]", "string", ",", "rowIdx", "int", ")", "{", "// Get Maximum Height", "max", ":=", "t", ".", "rs", "[", "rowIdx", "]", "\n", "total", ":=", "len", "(", "columns", ")", "\n\n", "// TODO Fix uneven col size", "// if total < t.colSize {", "//\tfor n := t.colSize - total; n < t.colSize ; n++ {", "//\t\tcolumns = append(columns, []string{SPACE})", "//\t\tt.cs[n] = t.mW", "//\t}", "//}", "// Pad Each Height", "pads", ":=", "[", "]", "int", "{", "}", "\n\n", "// Checking for ANSI escape sequences for columns", "is_esc_seq", ":=", "false", "\n", "if", "len", "(", "t", ".", "columnsParams", ")", ">", "0", "{", "is_esc_seq", "=", "true", "\n", "}", "\n", "t", ".", "fillAlignment", "(", "total", ")", "\n\n", "for", "i", ",", "line", ":=", "range", "columns", "{", "length", ":=", "len", "(", "line", ")", "\n", "pad", ":=", "max", "-", "length", "\n", "pads", "=", "append", "(", "pads", ",", "pad", ")", "\n", "for", "n", ":=", "0", ";", "n", "<", "pad", ";", "n", "++", "{", "columns", "[", "i", "]", "=", "append", "(", "columns", "[", "i", "]", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "//fmt.Println(max, \"\\n\")", "for", "x", ":=", "0", ";", "x", "<", "max", ";", "x", "++", "{", "for", "y", ":=", "0", ";", "y", "<", "total", ";", "y", "++", "{", "// Check if border is set", "fmt", ".", "Fprint", "(", "t", ".", "out", ",", "ConditionString", "(", "(", "!", "t", ".", "borders", ".", "Left", "&&", "y", "==", "0", ")", ",", "SPACE", ",", "t", ".", "pColumn", ")", ")", "\n\n", "fmt", ".", "Fprintf", "(", "t", ".", "out", ",", "SPACE", ")", "\n", "str", ":=", "columns", "[", "y", "]", "[", "x", "]", "\n\n", "// Embedding escape sequence with column value", "if", "is_esc_seq", "{", "str", "=", "format", "(", "str", ",", "t", ".", "columnsParams", "[", "y", "]", ")", "\n", "}", "\n\n", "// This would print alignment", "// Default alignment would use multiple configuration", "switch", "t", ".", "columnsAlign", "[", "y", "]", "{", "case", "ALIGN_CENTER", ":", "//", "fmt", ".", "Fprintf", "(", "t", ".", "out", ",", "\"", "\"", ",", "Pad", "(", "str", ",", "SPACE", ",", "t", ".", "cs", "[", "y", "]", ")", ")", "\n", "case", "ALIGN_RIGHT", ":", "fmt", ".", "Fprintf", "(", "t", ".", "out", ",", "\"", "\"", ",", "PadLeft", "(", "str", ",", "SPACE", ",", "t", ".", "cs", "[", "y", "]", ")", ")", "\n", "case", "ALIGN_LEFT", ":", "fmt", ".", "Fprintf", "(", "t", ".", "out", ",", "\"", "\"", ",", "PadRight", "(", "str", ",", "SPACE", ",", "t", ".", "cs", "[", "y", "]", ")", ")", "\n", "default", ":", "if", "decimal", ".", "MatchString", "(", "strings", ".", "TrimSpace", "(", "str", ")", ")", "||", "percent", ".", "MatchString", "(", "strings", ".", "TrimSpace", "(", "str", ")", ")", "{", "fmt", ".", "Fprintf", "(", "t", ".", "out", ",", "\"", "\"", ",", "PadLeft", "(", "str", ",", "SPACE", ",", "t", ".", "cs", "[", "y", "]", ")", ")", "\n", "}", "else", "{", "fmt", ".", "Fprintf", "(", "t", ".", "out", ",", "\"", "\"", ",", "PadRight", "(", "str", ",", "SPACE", ",", "t", ".", "cs", "[", "y", "]", ")", ")", "\n\n", "// TODO Custom alignment per column", "//if max == 1 || pads[y] > 0 {", "//\tfmt.Fprintf(t.out, \"%s\", Pad(str, SPACE, t.cs[y]))", "//} else {", "//\tfmt.Fprintf(t.out, \"%s\", PadRight(str, SPACE, t.cs[y]))", "//}", "}", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "t", ".", "out", ",", "SPACE", ")", "\n", "}", "\n", "// Check if border is set", "// Replace with space if not set", "fmt", ".", "Fprint", "(", "t", ".", "out", ",", "ConditionString", "(", "t", ".", "borders", ".", "Left", ",", "t", ".", "pColumn", ",", "SPACE", ")", ")", "\n", "fmt", ".", "Fprint", "(", "t", ".", "out", ",", "t", ".", "newLine", ")", "\n", "}", "\n\n", "if", "t", ".", "rowLine", "{", "t", ".", "printLine", "(", "true", ")", "\n", "}", "\n", "}" ]
// Print Row Information // Adjust column alignment based on type
[ "Print", "Row", "Information", "Adjust", "column", "alignment", "based", "on", "type" ]
7e037d187b0c13d81ccf0dd1c6b990c2759e6597
https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L621-L702
train
olekukonko/tablewriter
table.go
printRowsMergeCells
func (t *Table) printRowsMergeCells() { var previousLine []string var displayCellBorder []bool var tmpWriter bytes.Buffer for i, lines := range t.lines { // We store the display of the current line in a tmp writer, as we need to know which border needs to be print above previousLine, displayCellBorder = t.printRowMergeCells(&tmpWriter, lines, i, previousLine) if i > 0 { //We don't need to print borders above first line if t.rowLine { t.printLineOptionalCellSeparators(true, displayCellBorder) } } tmpWriter.WriteTo(t.out) } //Print the end of the table if t.rowLine { t.printLine(true) } }
go
func (t *Table) printRowsMergeCells() { var previousLine []string var displayCellBorder []bool var tmpWriter bytes.Buffer for i, lines := range t.lines { // We store the display of the current line in a tmp writer, as we need to know which border needs to be print above previousLine, displayCellBorder = t.printRowMergeCells(&tmpWriter, lines, i, previousLine) if i > 0 { //We don't need to print borders above first line if t.rowLine { t.printLineOptionalCellSeparators(true, displayCellBorder) } } tmpWriter.WriteTo(t.out) } //Print the end of the table if t.rowLine { t.printLine(true) } }
[ "func", "(", "t", "*", "Table", ")", "printRowsMergeCells", "(", ")", "{", "var", "previousLine", "[", "]", "string", "\n", "var", "displayCellBorder", "[", "]", "bool", "\n", "var", "tmpWriter", "bytes", ".", "Buffer", "\n", "for", "i", ",", "lines", ":=", "range", "t", ".", "lines", "{", "// We store the display of the current line in a tmp writer, as we need to know which border needs to be print above", "previousLine", ",", "displayCellBorder", "=", "t", ".", "printRowMergeCells", "(", "&", "tmpWriter", ",", "lines", ",", "i", ",", "previousLine", ")", "\n", "if", "i", ">", "0", "{", "//We don't need to print borders above first line", "if", "t", ".", "rowLine", "{", "t", ".", "printLineOptionalCellSeparators", "(", "true", ",", "displayCellBorder", ")", "\n", "}", "\n", "}", "\n", "tmpWriter", ".", "WriteTo", "(", "t", ".", "out", ")", "\n", "}", "\n", "//Print the end of the table", "if", "t", ".", "rowLine", "{", "t", ".", "printLine", "(", "true", ")", "\n", "}", "\n", "}" ]
// Print the rows of the table and merge the cells that are identical
[ "Print", "the", "rows", "of", "the", "table", "and", "merge", "the", "cells", "that", "are", "identical" ]
7e037d187b0c13d81ccf0dd1c6b990c2759e6597
https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table.go#L705-L723
train
olekukonko/tablewriter
csv.go
NewCSV
func NewCSV(writer io.Writer, fileName string, hasHeader bool) (*Table, error) { file, err := os.Open(fileName) if err != nil { return &Table{}, err } defer file.Close() csvReader := csv.NewReader(file) t, err := NewCSVReader(writer, csvReader, hasHeader) return t, err }
go
func NewCSV(writer io.Writer, fileName string, hasHeader bool) (*Table, error) { file, err := os.Open(fileName) if err != nil { return &Table{}, err } defer file.Close() csvReader := csv.NewReader(file) t, err := NewCSVReader(writer, csvReader, hasHeader) return t, err }
[ "func", "NewCSV", "(", "writer", "io", ".", "Writer", ",", "fileName", "string", ",", "hasHeader", "bool", ")", "(", "*", "Table", ",", "error", ")", "{", "file", ",", "err", ":=", "os", ".", "Open", "(", "fileName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "Table", "{", "}", ",", "err", "\n", "}", "\n", "defer", "file", ".", "Close", "(", ")", "\n", "csvReader", ":=", "csv", ".", "NewReader", "(", "file", ")", "\n", "t", ",", "err", ":=", "NewCSVReader", "(", "writer", ",", "csvReader", ",", "hasHeader", ")", "\n", "return", "t", ",", "err", "\n", "}" ]
// Start A new table by importing from a CSV file // Takes io.Writer and csv File name
[ "Start", "A", "new", "table", "by", "importing", "from", "a", "CSV", "file", "Takes", "io", ".", "Writer", "and", "csv", "File", "name" ]
7e037d187b0c13d81ccf0dd1c6b990c2759e6597
https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/csv.go#L18-L27
train
olekukonko/tablewriter
table_with_color.go
format
func format(s string, codes interface{}) string { var seq string switch v := codes.(type) { case string: seq = v case []int: seq = makeSequence(v) default: return s } if len(seq) == 0 { return s } return startFormat(seq) + s + stopFormat() }
go
func format(s string, codes interface{}) string { var seq string switch v := codes.(type) { case string: seq = v case []int: seq = makeSequence(v) default: return s } if len(seq) == 0 { return s } return startFormat(seq) + s + stopFormat() }
[ "func", "format", "(", "s", "string", ",", "codes", "interface", "{", "}", ")", "string", "{", "var", "seq", "string", "\n\n", "switch", "v", ":=", "codes", ".", "(", "type", ")", "{", "case", "string", ":", "seq", "=", "v", "\n", "case", "[", "]", "int", ":", "seq", "=", "makeSequence", "(", "v", ")", "\n", "default", ":", "return", "s", "\n", "}", "\n\n", "if", "len", "(", "seq", ")", "==", "0", "{", "return", "s", "\n", "}", "\n", "return", "startFormat", "(", "seq", ")", "+", "s", "+", "stopFormat", "(", ")", "\n", "}" ]
// Adding ANSI escape sequences before and after string
[ "Adding", "ANSI", "escape", "sequences", "before", "and", "after", "string" ]
7e037d187b0c13d81ccf0dd1c6b990c2759e6597
https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/table_with_color.go#L83-L100
train
olekukonko/tablewriter
util.go
ConditionString
func ConditionString(cond bool, valid, inValid string) string { if cond { return valid } return inValid }
go
func ConditionString(cond bool, valid, inValid string) string { if cond { return valid } return inValid }
[ "func", "ConditionString", "(", "cond", "bool", ",", "valid", ",", "inValid", "string", ")", "string", "{", "if", "cond", "{", "return", "valid", "\n", "}", "\n", "return", "inValid", "\n", "}" ]
// Simple Condition for string // Returns value based on condition
[ "Simple", "Condition", "for", "string", "Returns", "value", "based", "on", "condition" ]
7e037d187b0c13d81ccf0dd1c6b990c2759e6597
https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/util.go#L26-L31
train
olekukonko/tablewriter
util.go
Title
func Title(name string) string { origLen := len(name) rs := []rune(name) for i, r := range rs { switch r { case '_': rs[i] = ' ' case '.': // ignore floating number 0.0 if (i != 0 && !isNumOrSpace(rs[i-1])) || (i != len(rs)-1 && !isNumOrSpace(rs[i+1])) { rs[i] = ' ' } } } name = string(rs) name = strings.TrimSpace(name) if len(name) == 0 && origLen > 0 { // Keep at least one character. This is important to preserve // empty lines in multi-line headers/footers. name = " " } return strings.ToUpper(name) }
go
func Title(name string) string { origLen := len(name) rs := []rune(name) for i, r := range rs { switch r { case '_': rs[i] = ' ' case '.': // ignore floating number 0.0 if (i != 0 && !isNumOrSpace(rs[i-1])) || (i != len(rs)-1 && !isNumOrSpace(rs[i+1])) { rs[i] = ' ' } } } name = string(rs) name = strings.TrimSpace(name) if len(name) == 0 && origLen > 0 { // Keep at least one character. This is important to preserve // empty lines in multi-line headers/footers. name = " " } return strings.ToUpper(name) }
[ "func", "Title", "(", "name", "string", ")", "string", "{", "origLen", ":=", "len", "(", "name", ")", "\n", "rs", ":=", "[", "]", "rune", "(", "name", ")", "\n", "for", "i", ",", "r", ":=", "range", "rs", "{", "switch", "r", "{", "case", "'_'", ":", "rs", "[", "i", "]", "=", "' '", "\n", "case", "'.'", ":", "// ignore floating number 0.0", "if", "(", "i", "!=", "0", "&&", "!", "isNumOrSpace", "(", "rs", "[", "i", "-", "1", "]", ")", ")", "||", "(", "i", "!=", "len", "(", "rs", ")", "-", "1", "&&", "!", "isNumOrSpace", "(", "rs", "[", "i", "+", "1", "]", ")", ")", "{", "rs", "[", "i", "]", "=", "' '", "\n", "}", "\n", "}", "\n", "}", "\n", "name", "=", "string", "(", "rs", ")", "\n", "name", "=", "strings", ".", "TrimSpace", "(", "name", ")", "\n", "if", "len", "(", "name", ")", "==", "0", "&&", "origLen", ">", "0", "{", "// Keep at least one character. This is important to preserve", "// empty lines in multi-line headers/footers.", "name", "=", "\"", "\"", "\n", "}", "\n", "return", "strings", ".", "ToUpper", "(", "name", ")", "\n", "}" ]
// Format Table Header // Replace _ , . and spaces
[ "Format", "Table", "Header", "Replace", "_", ".", "and", "spaces" ]
7e037d187b0c13d81ccf0dd1c6b990c2759e6597
https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/util.go#L39-L61
train
olekukonko/tablewriter
util.go
Pad
func Pad(s, pad string, width int) string { gap := width - DisplayWidth(s) if gap > 0 { gapLeft := int(math.Ceil(float64(gap / 2))) gapRight := gap - gapLeft return strings.Repeat(string(pad), gapLeft) + s + strings.Repeat(string(pad), gapRight) } return s }
go
func Pad(s, pad string, width int) string { gap := width - DisplayWidth(s) if gap > 0 { gapLeft := int(math.Ceil(float64(gap / 2))) gapRight := gap - gapLeft return strings.Repeat(string(pad), gapLeft) + s + strings.Repeat(string(pad), gapRight) } return s }
[ "func", "Pad", "(", "s", ",", "pad", "string", ",", "width", "int", ")", "string", "{", "gap", ":=", "width", "-", "DisplayWidth", "(", "s", ")", "\n", "if", "gap", ">", "0", "{", "gapLeft", ":=", "int", "(", "math", ".", "Ceil", "(", "float64", "(", "gap", "/", "2", ")", ")", ")", "\n", "gapRight", ":=", "gap", "-", "gapLeft", "\n", "return", "strings", ".", "Repeat", "(", "string", "(", "pad", ")", ",", "gapLeft", ")", "+", "s", "+", "strings", ".", "Repeat", "(", "string", "(", "pad", ")", ",", "gapRight", ")", "\n", "}", "\n", "return", "s", "\n", "}" ]
// Pad String // Attempts to place string in the center
[ "Pad", "String", "Attempts", "to", "place", "string", "in", "the", "center" ]
7e037d187b0c13d81ccf0dd1c6b990c2759e6597
https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/util.go#L65-L73
train
olekukonko/tablewriter
util.go
PadRight
func PadRight(s, pad string, width int) string { gap := width - DisplayWidth(s) if gap > 0 { return s + strings.Repeat(string(pad), gap) } return s }
go
func PadRight(s, pad string, width int) string { gap := width - DisplayWidth(s) if gap > 0 { return s + strings.Repeat(string(pad), gap) } return s }
[ "func", "PadRight", "(", "s", ",", "pad", "string", ",", "width", "int", ")", "string", "{", "gap", ":=", "width", "-", "DisplayWidth", "(", "s", ")", "\n", "if", "gap", ">", "0", "{", "return", "s", "+", "strings", ".", "Repeat", "(", "string", "(", "pad", ")", ",", "gap", ")", "\n", "}", "\n", "return", "s", "\n", "}" ]
// Pad String Right position // This would place string at the left side of the screen
[ "Pad", "String", "Right", "position", "This", "would", "place", "string", "at", "the", "left", "side", "of", "the", "screen" ]
7e037d187b0c13d81ccf0dd1c6b990c2759e6597
https://github.com/olekukonko/tablewriter/blob/7e037d187b0c13d81ccf0dd1c6b990c2759e6597/util.go#L77-L83
train
openzipkin/zipkin-go
propagation/b3/grpc.go
ExtractGRPC
func ExtractGRPC(md *metadata.MD) propagation.Extractor { return func() (*model.SpanContext, error) { var ( traceIDHeader = GetGRPCHeader(md, TraceID) spanIDHeader = GetGRPCHeader(md, SpanID) parentSpanIDHeader = GetGRPCHeader(md, ParentSpanID) sampledHeader = GetGRPCHeader(md, Sampled) flagsHeader = GetGRPCHeader(md, Flags) ) return ParseHeaders( traceIDHeader, spanIDHeader, parentSpanIDHeader, sampledHeader, flagsHeader, ) } }
go
func ExtractGRPC(md *metadata.MD) propagation.Extractor { return func() (*model.SpanContext, error) { var ( traceIDHeader = GetGRPCHeader(md, TraceID) spanIDHeader = GetGRPCHeader(md, SpanID) parentSpanIDHeader = GetGRPCHeader(md, ParentSpanID) sampledHeader = GetGRPCHeader(md, Sampled) flagsHeader = GetGRPCHeader(md, Flags) ) return ParseHeaders( traceIDHeader, spanIDHeader, parentSpanIDHeader, sampledHeader, flagsHeader, ) } }
[ "func", "ExtractGRPC", "(", "md", "*", "metadata", ".", "MD", ")", "propagation", ".", "Extractor", "{", "return", "func", "(", ")", "(", "*", "model", ".", "SpanContext", ",", "error", ")", "{", "var", "(", "traceIDHeader", "=", "GetGRPCHeader", "(", "md", ",", "TraceID", ")", "\n", "spanIDHeader", "=", "GetGRPCHeader", "(", "md", ",", "SpanID", ")", "\n", "parentSpanIDHeader", "=", "GetGRPCHeader", "(", "md", ",", "ParentSpanID", ")", "\n", "sampledHeader", "=", "GetGRPCHeader", "(", "md", ",", "Sampled", ")", "\n", "flagsHeader", "=", "GetGRPCHeader", "(", "md", ",", "Flags", ")", "\n", ")", "\n\n", "return", "ParseHeaders", "(", "traceIDHeader", ",", "spanIDHeader", ",", "parentSpanIDHeader", ",", "sampledHeader", ",", "flagsHeader", ",", ")", "\n", "}", "\n", "}" ]
// ExtractGRPC will extract a span.Context from the gRPC Request metadata if // found in B3 header format.
[ "ExtractGRPC", "will", "extract", "a", "span", ".", "Context", "from", "the", "gRPC", "Request", "metadata", "if", "found", "in", "B3", "header", "format", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/propagation/b3/grpc.go#L26-L41
train
openzipkin/zipkin-go
propagation/b3/grpc.go
InjectGRPC
func InjectGRPC(md *metadata.MD) propagation.Injector { return func(sc model.SpanContext) error { if (model.SpanContext{}) == sc { return ErrEmptyContext } if sc.Debug { setGRPCHeader(md, Flags, "1") } else if sc.Sampled != nil { // Debug is encoded as X-B3-Flags: 1. Since Debug implies Sampled, // we don't send "X-B3-Sampled" if Debug is set. if *sc.Sampled { setGRPCHeader(md, Sampled, "1") } else { setGRPCHeader(md, Sampled, "0") } } if !sc.TraceID.Empty() && sc.ID > 0 { // set identifiers setGRPCHeader(md, TraceID, sc.TraceID.String()) setGRPCHeader(md, SpanID, sc.ID.String()) if sc.ParentID != nil { setGRPCHeader(md, ParentSpanID, sc.ParentID.String()) } } return nil } }
go
func InjectGRPC(md *metadata.MD) propagation.Injector { return func(sc model.SpanContext) error { if (model.SpanContext{}) == sc { return ErrEmptyContext } if sc.Debug { setGRPCHeader(md, Flags, "1") } else if sc.Sampled != nil { // Debug is encoded as X-B3-Flags: 1. Since Debug implies Sampled, // we don't send "X-B3-Sampled" if Debug is set. if *sc.Sampled { setGRPCHeader(md, Sampled, "1") } else { setGRPCHeader(md, Sampled, "0") } } if !sc.TraceID.Empty() && sc.ID > 0 { // set identifiers setGRPCHeader(md, TraceID, sc.TraceID.String()) setGRPCHeader(md, SpanID, sc.ID.String()) if sc.ParentID != nil { setGRPCHeader(md, ParentSpanID, sc.ParentID.String()) } } return nil } }
[ "func", "InjectGRPC", "(", "md", "*", "metadata", ".", "MD", ")", "propagation", ".", "Injector", "{", "return", "func", "(", "sc", "model", ".", "SpanContext", ")", "error", "{", "if", "(", "model", ".", "SpanContext", "{", "}", ")", "==", "sc", "{", "return", "ErrEmptyContext", "\n", "}", "\n\n", "if", "sc", ".", "Debug", "{", "setGRPCHeader", "(", "md", ",", "Flags", ",", "\"", "\"", ")", "\n", "}", "else", "if", "sc", ".", "Sampled", "!=", "nil", "{", "// Debug is encoded as X-B3-Flags: 1. Since Debug implies Sampled,", "// we don't send \"X-B3-Sampled\" if Debug is set.", "if", "*", "sc", ".", "Sampled", "{", "setGRPCHeader", "(", "md", ",", "Sampled", ",", "\"", "\"", ")", "\n", "}", "else", "{", "setGRPCHeader", "(", "md", ",", "Sampled", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "if", "!", "sc", ".", "TraceID", ".", "Empty", "(", ")", "&&", "sc", ".", "ID", ">", "0", "{", "// set identifiers", "setGRPCHeader", "(", "md", ",", "TraceID", ",", "sc", ".", "TraceID", ".", "String", "(", ")", ")", "\n", "setGRPCHeader", "(", "md", ",", "SpanID", ",", "sc", ".", "ID", ".", "String", "(", ")", ")", "\n", "if", "sc", ".", "ParentID", "!=", "nil", "{", "setGRPCHeader", "(", "md", ",", "ParentSpanID", ",", "sc", ".", "ParentID", ".", "String", "(", ")", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}", "\n", "}" ]
// InjectGRPC will inject a span.Context into gRPC metadata.
[ "InjectGRPC", "will", "inject", "a", "span", ".", "Context", "into", "gRPC", "metadata", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/propagation/b3/grpc.go#L44-L73
train
openzipkin/zipkin-go
propagation/b3/grpc.go
GetGRPCHeader
func GetGRPCHeader(md *metadata.MD, key string) string { v := (*md)[key] if len(v) < 1 { return "" } return v[len(v)-1] }
go
func GetGRPCHeader(md *metadata.MD, key string) string { v := (*md)[key] if len(v) < 1 { return "" } return v[len(v)-1] }
[ "func", "GetGRPCHeader", "(", "md", "*", "metadata", ".", "MD", ",", "key", "string", ")", "string", "{", "v", ":=", "(", "*", "md", ")", "[", "key", "]", "\n", "if", "len", "(", "v", ")", "<", "1", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "v", "[", "len", "(", "v", ")", "-", "1", "]", "\n", "}" ]
// GetGRPCHeader retrieves the last value found for a particular key. If key is // not found it returns an empty string.
[ "GetGRPCHeader", "retrieves", "the", "last", "value", "found", "for", "a", "particular", "key", ".", "If", "key", "is", "not", "found", "it", "returns", "an", "empty", "string", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/propagation/b3/grpc.go#L77-L83
train
openzipkin/zipkin-go
reporter/recorder/recorder.go
Send
func (r *ReporterRecorder) Send(span model.SpanModel) { r.mtx.Lock() r.spans = append(r.spans, span) r.mtx.Unlock() }
go
func (r *ReporterRecorder) Send(span model.SpanModel) { r.mtx.Lock() r.spans = append(r.spans, span) r.mtx.Unlock() }
[ "func", "(", "r", "*", "ReporterRecorder", ")", "Send", "(", "span", "model", ".", "SpanModel", ")", "{", "r", ".", "mtx", ".", "Lock", "(", ")", "\n", "r", ".", "spans", "=", "append", "(", "r", ".", "spans", ",", "span", ")", "\n", "r", ".", "mtx", ".", "Unlock", "(", ")", "\n", "}" ]
// Send adds the provided span to the span list held by the recorder.
[ "Send", "adds", "the", "provided", "span", "to", "the", "span", "list", "held", "by", "the", "recorder", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/reporter/recorder/recorder.go#L38-L42
train
openzipkin/zipkin-go
reporter/recorder/recorder.go
Flush
func (r *ReporterRecorder) Flush() []model.SpanModel { r.mtx.Lock() spans := r.spans r.spans = nil r.mtx.Unlock() return spans }
go
func (r *ReporterRecorder) Flush() []model.SpanModel { r.mtx.Lock() spans := r.spans r.spans = nil r.mtx.Unlock() return spans }
[ "func", "(", "r", "*", "ReporterRecorder", ")", "Flush", "(", ")", "[", "]", "model", ".", "SpanModel", "{", "r", ".", "mtx", ".", "Lock", "(", ")", "\n", "spans", ":=", "r", ".", "spans", "\n", "r", ".", "spans", "=", "nil", "\n", "r", ".", "mtx", ".", "Unlock", "(", ")", "\n", "return", "spans", "\n", "}" ]
// Flush returns all recorded spans and clears its internal span storage
[ "Flush", "returns", "all", "recorded", "spans", "and", "clears", "its", "internal", "span", "storage" ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/reporter/recorder/recorder.go#L45-L51
train
openzipkin/zipkin-go
tracer_options.go
WithLocalEndpoint
func WithLocalEndpoint(e *model.Endpoint) TracerOption { return func(o *Tracer) error { if e == nil { o.localEndpoint = nil return nil } ep := *e o.localEndpoint = &ep return nil } }
go
func WithLocalEndpoint(e *model.Endpoint) TracerOption { return func(o *Tracer) error { if e == nil { o.localEndpoint = nil return nil } ep := *e o.localEndpoint = &ep return nil } }
[ "func", "WithLocalEndpoint", "(", "e", "*", "model", ".", "Endpoint", ")", "TracerOption", "{", "return", "func", "(", "o", "*", "Tracer", ")", "error", "{", "if", "e", "==", "nil", "{", "o", ".", "localEndpoint", "=", "nil", "\n", "return", "nil", "\n", "}", "\n", "ep", ":=", "*", "e", "\n", "o", ".", "localEndpoint", "=", "&", "ep", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// WithLocalEndpoint sets the local endpoint of the tracer.
[ "WithLocalEndpoint", "sets", "the", "local", "endpoint", "of", "the", "tracer", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tracer_options.go#L45-L55
train
openzipkin/zipkin-go
tracer_options.go
WithExtractFailurePolicy
func WithExtractFailurePolicy(p ExtractFailurePolicy) TracerOption { return func(o *Tracer) error { if p < 0 || p > ExtractFailurePolicyTagAndRestart { return ErrInvalidExtractFailurePolicy } o.extractFailurePolicy = p return nil } }
go
func WithExtractFailurePolicy(p ExtractFailurePolicy) TracerOption { return func(o *Tracer) error { if p < 0 || p > ExtractFailurePolicyTagAndRestart { return ErrInvalidExtractFailurePolicy } o.extractFailurePolicy = p return nil } }
[ "func", "WithExtractFailurePolicy", "(", "p", "ExtractFailurePolicy", ")", "TracerOption", "{", "return", "func", "(", "o", "*", "Tracer", ")", "error", "{", "if", "p", "<", "0", "||", "p", ">", "ExtractFailurePolicyTagAndRestart", "{", "return", "ErrInvalidExtractFailurePolicy", "\n", "}", "\n", "o", ".", "extractFailurePolicy", "=", "p", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// WithExtractFailurePolicy allows one to set the ExtractFailurePolicy.
[ "WithExtractFailurePolicy", "allows", "one", "to", "set", "the", "ExtractFailurePolicy", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tracer_options.go#L58-L66
train
openzipkin/zipkin-go
tracer_options.go
WithNoopSpan
func WithNoopSpan(unsampledNoop bool) TracerOption { return func(o *Tracer) error { o.unsampledNoop = unsampledNoop return nil } }
go
func WithNoopSpan(unsampledNoop bool) TracerOption { return func(o *Tracer) error { o.unsampledNoop = unsampledNoop return nil } }
[ "func", "WithNoopSpan", "(", "unsampledNoop", "bool", ")", "TracerOption", "{", "return", "func", "(", "o", "*", "Tracer", ")", "error", "{", "o", ".", "unsampledNoop", "=", "unsampledNoop", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// WithNoopSpan if set to true will switch to a NoopSpan implementation // if the trace is not sampled.
[ "WithNoopSpan", "if", "set", "to", "true", "will", "switch", "to", "a", "NoopSpan", "implementation", "if", "the", "trace", "is", "not", "sampled", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tracer_options.go#L70-L75
train
openzipkin/zipkin-go
tracer_options.go
WithSampler
func WithSampler(sampler Sampler) TracerOption { return func(o *Tracer) error { o.sampler = sampler return nil } }
go
func WithSampler(sampler Sampler) TracerOption { return func(o *Tracer) error { o.sampler = sampler return nil } }
[ "func", "WithSampler", "(", "sampler", "Sampler", ")", "TracerOption", "{", "return", "func", "(", "o", "*", "Tracer", ")", "error", "{", "o", ".", "sampler", "=", "sampler", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// WithSampler allows one to set a Sampler function
[ "WithSampler", "allows", "one", "to", "set", "a", "Sampler", "function" ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tracer_options.go#L89-L94
train
openzipkin/zipkin-go
tracer_options.go
WithTraceID128Bit
func WithTraceID128Bit(val bool) TracerOption { return func(o *Tracer) error { if val { o.generate = idgenerator.NewRandom128() } else { o.generate = idgenerator.NewRandom64() } return nil } }
go
func WithTraceID128Bit(val bool) TracerOption { return func(o *Tracer) error { if val { o.generate = idgenerator.NewRandom128() } else { o.generate = idgenerator.NewRandom64() } return nil } }
[ "func", "WithTraceID128Bit", "(", "val", "bool", ")", "TracerOption", "{", "return", "func", "(", "o", "*", "Tracer", ")", "error", "{", "if", "val", "{", "o", ".", "generate", "=", "idgenerator", ".", "NewRandom128", "(", ")", "\n", "}", "else", "{", "o", ".", "generate", "=", "idgenerator", ".", "NewRandom64", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// WithTraceID128Bit if set to true will instruct the Tracer to start traces // with 128 bit TraceID's. If set to false the Tracer will start traces with // 64 bits.
[ "WithTraceID128Bit", "if", "set", "to", "true", "will", "instruct", "the", "Tracer", "to", "start", "traces", "with", "128", "bit", "TraceID", "s", ".", "If", "set", "to", "false", "the", "Tracer", "will", "start", "traces", "with", "64", "bits", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tracer_options.go#L99-L108
train
openzipkin/zipkin-go
tracer_options.go
WithIDGenerator
func WithIDGenerator(generator idgenerator.IDGenerator) TracerOption { return func(o *Tracer) error { o.generate = generator return nil } }
go
func WithIDGenerator(generator idgenerator.IDGenerator) TracerOption { return func(o *Tracer) error { o.generate = generator return nil } }
[ "func", "WithIDGenerator", "(", "generator", "idgenerator", ".", "IDGenerator", ")", "TracerOption", "{", "return", "func", "(", "o", "*", "Tracer", ")", "error", "{", "o", ".", "generate", "=", "generator", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// WithIDGenerator allows one to set a custom ID Generator
[ "WithIDGenerator", "allows", "one", "to", "set", "a", "custom", "ID", "Generator" ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tracer_options.go#L111-L116
train
openzipkin/zipkin-go
tracer_options.go
WithTags
func WithTags(tags map[string]string) TracerOption { return func(o *Tracer) error { for k, v := range tags { o.defaultTags[k] = v } return nil } }
go
func WithTags(tags map[string]string) TracerOption { return func(o *Tracer) error { for k, v := range tags { o.defaultTags[k] = v } return nil } }
[ "func", "WithTags", "(", "tags", "map", "[", "string", "]", "string", ")", "TracerOption", "{", "return", "func", "(", "o", "*", "Tracer", ")", "error", "{", "for", "k", ",", "v", ":=", "range", "tags", "{", "o", ".", "defaultTags", "[", "k", "]", "=", "v", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// WithTags allows one to set default tags to be added to each created span
[ "WithTags", "allows", "one", "to", "set", "default", "tags", "to", "be", "added", "to", "each", "created", "span" ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tracer_options.go#L119-L126
train
openzipkin/zipkin-go
tracer_options.go
WithNoopTracer
func WithNoopTracer(tracerNoop bool) TracerOption { return func(o *Tracer) error { if tracerNoop { o.noop = 1 } else { o.noop = 0 } return nil } }
go
func WithNoopTracer(tracerNoop bool) TracerOption { return func(o *Tracer) error { if tracerNoop { o.noop = 1 } else { o.noop = 0 } return nil } }
[ "func", "WithNoopTracer", "(", "tracerNoop", "bool", ")", "TracerOption", "{", "return", "func", "(", "o", "*", "Tracer", ")", "error", "{", "if", "tracerNoop", "{", "o", ".", "noop", "=", "1", "\n", "}", "else", "{", "o", ".", "noop", "=", "0", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// WithNoopTracer allows one to start the Tracer as Noop implementation.
[ "WithNoopTracer", "allows", "one", "to", "start", "the", "Tracer", "as", "Noop", "implementation", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tracer_options.go#L129-L138
train
openzipkin/zipkin-go
middleware/grpc/client.go
NewClientHandler
func NewClientHandler(tracer *zipkin.Tracer, options ...ClientOption) stats.Handler { c := &clientHandler{ tracer: tracer, } for _, option := range options { option(c) } return c }
go
func NewClientHandler(tracer *zipkin.Tracer, options ...ClientOption) stats.Handler { c := &clientHandler{ tracer: tracer, } for _, option := range options { option(c) } return c }
[ "func", "NewClientHandler", "(", "tracer", "*", "zipkin", ".", "Tracer", ",", "options", "...", "ClientOption", ")", "stats", ".", "Handler", "{", "c", ":=", "&", "clientHandler", "{", "tracer", ":", "tracer", ",", "}", "\n", "for", "_", ",", "option", ":=", "range", "options", "{", "option", "(", "c", ")", "\n", "}", "\n", "return", "c", "\n", "}" ]
// NewClientHandler returns a stats.Handler which can be used with grpc.WithStatsHandler to add // tracing to a gRPC client. The gRPC method name is used as the span name and by default the only // tags are the gRPC status code if the call fails.
[ "NewClientHandler", "returns", "a", "stats", ".", "Handler", "which", "can", "be", "used", "with", "grpc", ".", "WithStatsHandler", "to", "add", "tracing", "to", "a", "gRPC", "client", ".", "The", "gRPC", "method", "name", "is", "used", "as", "the", "span", "name", "and", "by", "default", "the", "only", "tags", "are", "the", "gRPC", "status", "code", "if", "the", "call", "fails", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/middleware/grpc/client.go#L47-L55
train
openzipkin/zipkin-go
reporter/log/log.go
NewReporter
func NewReporter(l *log.Logger) reporter.Reporter { if l == nil { // use standard type of log setup l = log.New(os.Stderr, "", log.LstdFlags) } return &logReporter{ logger: l, } }
go
func NewReporter(l *log.Logger) reporter.Reporter { if l == nil { // use standard type of log setup l = log.New(os.Stderr, "", log.LstdFlags) } return &logReporter{ logger: l, } }
[ "func", "NewReporter", "(", "l", "*", "log", ".", "Logger", ")", "reporter", ".", "Reporter", "{", "if", "l", "==", "nil", "{", "// use standard type of log setup", "l", "=", "log", ".", "New", "(", "os", ".", "Stderr", ",", "\"", "\"", ",", "log", ".", "LstdFlags", ")", "\n", "}", "\n", "return", "&", "logReporter", "{", "logger", ":", "l", ",", "}", "\n", "}" ]
// NewReporter returns a new log reporter.
[ "NewReporter", "returns", "a", "new", "log", "reporter", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/reporter/log/log.go#L37-L45
train
openzipkin/zipkin-go
reporter/log/log.go
Send
func (r *logReporter) Send(s model.SpanModel) { if b, err := json.MarshalIndent(s, "", " "); err == nil { r.logger.Printf("%s:\n%s\n\n", time.Now(), string(b)) } }
go
func (r *logReporter) Send(s model.SpanModel) { if b, err := json.MarshalIndent(s, "", " "); err == nil { r.logger.Printf("%s:\n%s\n\n", time.Now(), string(b)) } }
[ "func", "(", "r", "*", "logReporter", ")", "Send", "(", "s", "model", ".", "SpanModel", ")", "{", "if", "b", ",", "err", ":=", "json", ".", "MarshalIndent", "(", "s", ",", "\"", "\"", ",", "\"", "\"", ")", ";", "err", "==", "nil", "{", "r", ".", "logger", ".", "Printf", "(", "\"", "\\n", "\\n", "\\n", "\"", ",", "time", ".", "Now", "(", ")", ",", "string", "(", "b", ")", ")", "\n", "}", "\n", "}" ]
// Send outputs a span to the Go logger.
[ "Send", "outputs", "a", "span", "to", "the", "Go", "logger", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/reporter/log/log.go#L48-L52
train
openzipkin/zipkin-go
context.go
NewContext
func NewContext(ctx context.Context, s Span) context.Context { return context.WithValue(ctx, spanKey, s) }
go
func NewContext(ctx context.Context, s Span) context.Context { return context.WithValue(ctx, spanKey, s) }
[ "func", "NewContext", "(", "ctx", "context", ".", "Context", ",", "s", "Span", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "ctx", ",", "spanKey", ",", "s", ")", "\n", "}" ]
// NewContext stores a Zipkin Span into Go's context propagation mechanism.
[ "NewContext", "stores", "a", "Zipkin", "Span", "into", "Go", "s", "context", "propagation", "mechanism", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/context.go#L46-L48
train
openzipkin/zipkin-go
reporter/http/http.go
Timeout
func Timeout(duration time.Duration) ReporterOption { return func(r *httpReporter) { r.client.Timeout = duration } }
go
func Timeout(duration time.Duration) ReporterOption { return func(r *httpReporter) { r.client.Timeout = duration } }
[ "func", "Timeout", "(", "duration", "time", ".", "Duration", ")", "ReporterOption", "{", "return", "func", "(", "r", "*", "httpReporter", ")", "{", "r", ".", "client", ".", "Timeout", "=", "duration", "}", "\n", "}" ]
// Timeout sets maximum timeout for http request.
[ "Timeout", "sets", "maximum", "timeout", "for", "http", "request", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/reporter/http/http.go#L173-L175
train
openzipkin/zipkin-go
reporter/http/http.go
BatchInterval
func BatchInterval(d time.Duration) ReporterOption { return func(r *httpReporter) { r.batchInterval = d } }
go
func BatchInterval(d time.Duration) ReporterOption { return func(r *httpReporter) { r.batchInterval = d } }
[ "func", "BatchInterval", "(", "d", "time", ".", "Duration", ")", "ReporterOption", "{", "return", "func", "(", "r", "*", "httpReporter", ")", "{", "r", ".", "batchInterval", "=", "d", "}", "\n", "}" ]
// BatchInterval sets the maximum duration we will buffer traces before // emitting them to the collector. The default batch interval is 1 second.
[ "BatchInterval", "sets", "the", "maximum", "duration", "we", "will", "buffer", "traces", "before", "emitting", "them", "to", "the", "collector", ".", "The", "default", "batch", "interval", "is", "1", "second", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/reporter/http/http.go#L191-L193
train
openzipkin/zipkin-go
reporter/http/http.go
Client
func Client(client *http.Client) ReporterOption { return func(r *httpReporter) { r.client = client } }
go
func Client(client *http.Client) ReporterOption { return func(r *httpReporter) { r.client = client } }
[ "func", "Client", "(", "client", "*", "http", ".", "Client", ")", "ReporterOption", "{", "return", "func", "(", "r", "*", "httpReporter", ")", "{", "r", ".", "client", "=", "client", "}", "\n", "}" ]
// Client sets a custom http client to use.
[ "Client", "sets", "a", "custom", "http", "client", "to", "use", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/reporter/http/http.go#L196-L198
train
openzipkin/zipkin-go
middleware/http/server.go
NewServerMiddleware
func NewServerMiddleware(t *zipkin.Tracer, options ...ServerOption) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { h := &handler{ tracer: t, next: next, } for _, option := range options { option(h) } return h } }
go
func NewServerMiddleware(t *zipkin.Tracer, options ...ServerOption) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { h := &handler{ tracer: t, next: next, } for _, option := range options { option(h) } return h } }
[ "func", "NewServerMiddleware", "(", "t", "*", "zipkin", ".", "Tracer", ",", "options", "...", "ServerOption", ")", "func", "(", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "func", "(", "next", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "h", ":=", "&", "handler", "{", "tracer", ":", "t", ",", "next", ":", "next", ",", "}", "\n", "for", "_", ",", "option", ":=", "range", "options", "{", "option", "(", "h", ")", "\n", "}", "\n", "return", "h", "\n", "}", "\n", "}" ]
// NewServerMiddleware returns a http.Handler middleware with Zipkin tracing.
[ "NewServerMiddleware", "returns", "a", "http", ".", "Handler", "middleware", "with", "Zipkin", "tracing", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/middleware/http/server.go#L74-L85
train
openzipkin/zipkin-go
proto/v2/decode_proto.go
ParseSpans
func ParseSpans(protoBlob []byte, debugWasSet bool) (zss []*zipkinmodel.SpanModel, err error) { var listOfSpans ListOfSpans if err := proto.Unmarshal(protoBlob, &listOfSpans); err != nil { return nil, err } for _, zps := range listOfSpans.Spans { zms, err := protoSpanToModelSpan(zps, debugWasSet) if err != nil { return zss, err } zss = append(zss, zms) } return zss, nil }
go
func ParseSpans(protoBlob []byte, debugWasSet bool) (zss []*zipkinmodel.SpanModel, err error) { var listOfSpans ListOfSpans if err := proto.Unmarshal(protoBlob, &listOfSpans); err != nil { return nil, err } for _, zps := range listOfSpans.Spans { zms, err := protoSpanToModelSpan(zps, debugWasSet) if err != nil { return zss, err } zss = append(zss, zms) } return zss, nil }
[ "func", "ParseSpans", "(", "protoBlob", "[", "]", "byte", ",", "debugWasSet", "bool", ")", "(", "zss", "[", "]", "*", "zipkinmodel", ".", "SpanModel", ",", "err", "error", ")", "{", "var", "listOfSpans", "ListOfSpans", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "protoBlob", ",", "&", "listOfSpans", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "for", "_", ",", "zps", ":=", "range", "listOfSpans", ".", "Spans", "{", "zms", ",", "err", ":=", "protoSpanToModelSpan", "(", "zps", ",", "debugWasSet", ")", "\n", "if", "err", "!=", "nil", "{", "return", "zss", ",", "err", "\n", "}", "\n", "zss", "=", "append", "(", "zss", ",", "zms", ")", "\n", "}", "\n", "return", "zss", ",", "nil", "\n", "}" ]
// ParseSpans parses zipkinmodel.SpanModel values from data serialized by Protobuf3. // debugWasSet is a boolean that toggles the Debug field of each Span. Its value // is usually retrieved from the transport headers when the "X-B3-Flags" header has a value of 1.
[ "ParseSpans", "parses", "zipkinmodel", ".", "SpanModel", "values", "from", "data", "serialized", "by", "Protobuf3", ".", "debugWasSet", "is", "a", "boolean", "that", "toggles", "the", "Debug", "field", "of", "each", "Span", ".", "Its", "value", "is", "usually", "retrieved", "from", "the", "transport", "headers", "when", "the", "X", "-", "B3", "-", "Flags", "header", "has", "a", "value", "of", "1", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/proto/v2/decode_proto.go#L35-L48
train
openzipkin/zipkin-go
proto/v2/encode_proto.go
Serialize
func (SpanSerializer) Serialize(sms []*zipkinmodel.SpanModel) (protoBlob []byte, err error) { var listOfSpans ListOfSpans for _, sm := range sms { sp, err := modelSpanToProtoSpan(sm) if err != nil { return nil, err } listOfSpans.Spans = append(listOfSpans.Spans, sp) } return proto.Marshal(&listOfSpans) }
go
func (SpanSerializer) Serialize(sms []*zipkinmodel.SpanModel) (protoBlob []byte, err error) { var listOfSpans ListOfSpans for _, sm := range sms { sp, err := modelSpanToProtoSpan(sm) if err != nil { return nil, err } listOfSpans.Spans = append(listOfSpans.Spans, sp) } return proto.Marshal(&listOfSpans) }
[ "func", "(", "SpanSerializer", ")", "Serialize", "(", "sms", "[", "]", "*", "zipkinmodel", ".", "SpanModel", ")", "(", "protoBlob", "[", "]", "byte", ",", "err", "error", ")", "{", "var", "listOfSpans", "ListOfSpans", "\n\n", "for", "_", ",", "sm", ":=", "range", "sms", "{", "sp", ",", "err", ":=", "modelSpanToProtoSpan", "(", "sm", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "listOfSpans", ".", "Spans", "=", "append", "(", "listOfSpans", ".", "Spans", ",", "sp", ")", "\n", "}", "\n\n", "return", "proto", ".", "Marshal", "(", "&", "listOfSpans", ")", "\n", "}" ]
// Serialize takes an array of zipkin SpanModel objects and serializes it to a protobuf blob.
[ "Serialize", "takes", "an", "array", "of", "zipkin", "SpanModel", "objects", "and", "serializes", "it", "to", "a", "protobuf", "blob", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/proto/v2/encode_proto.go#L32-L44
train
openzipkin/zipkin-go
model/span.go
MarshalJSON
func (s SpanModel) MarshalJSON() ([]byte, error) { type Alias SpanModel var timestamp int64 if !s.Timestamp.IsZero() { if s.Timestamp.Unix() < 1 { // Zipkin does not allow Timestamps before Unix epoch return nil, ErrValidTimestampRequired } timestamp = s.Timestamp.Round(time.Microsecond).UnixNano() / 1e3 } if s.Duration < time.Microsecond { if s.Duration < 0 { // negative duration is not allowed and signals a timing logic error return nil, ErrValidDurationRequired } else if s.Duration > 0 { // sub microsecond durations are reported as 1 microsecond s.Duration = 1 * time.Microsecond } } else { // Duration will be rounded to nearest microsecond representation. // // NOTE: Duration.Round() is not available in Go 1.8 which we still support. // To handle microsecond resolution rounding we'll add 500 nanoseconds to // the duration. When truncated to microseconds in the call to marshal, it // will be naturally rounded. See TestSpanDurationRounding in span_test.go s.Duration += 500 * time.Nanosecond } if s.LocalEndpoint.Empty() { s.LocalEndpoint = nil } if s.RemoteEndpoint.Empty() { s.RemoteEndpoint = nil } return json.Marshal(&struct { T int64 `json:"timestamp,omitempty"` D int64 `json:"duration,omitempty"` Alias }{ T: timestamp, D: s.Duration.Nanoseconds() / 1e3, Alias: (Alias)(s), }) }
go
func (s SpanModel) MarshalJSON() ([]byte, error) { type Alias SpanModel var timestamp int64 if !s.Timestamp.IsZero() { if s.Timestamp.Unix() < 1 { // Zipkin does not allow Timestamps before Unix epoch return nil, ErrValidTimestampRequired } timestamp = s.Timestamp.Round(time.Microsecond).UnixNano() / 1e3 } if s.Duration < time.Microsecond { if s.Duration < 0 { // negative duration is not allowed and signals a timing logic error return nil, ErrValidDurationRequired } else if s.Duration > 0 { // sub microsecond durations are reported as 1 microsecond s.Duration = 1 * time.Microsecond } } else { // Duration will be rounded to nearest microsecond representation. // // NOTE: Duration.Round() is not available in Go 1.8 which we still support. // To handle microsecond resolution rounding we'll add 500 nanoseconds to // the duration. When truncated to microseconds in the call to marshal, it // will be naturally rounded. See TestSpanDurationRounding in span_test.go s.Duration += 500 * time.Nanosecond } if s.LocalEndpoint.Empty() { s.LocalEndpoint = nil } if s.RemoteEndpoint.Empty() { s.RemoteEndpoint = nil } return json.Marshal(&struct { T int64 `json:"timestamp,omitempty"` D int64 `json:"duration,omitempty"` Alias }{ T: timestamp, D: s.Duration.Nanoseconds() / 1e3, Alias: (Alias)(s), }) }
[ "func", "(", "s", "SpanModel", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "type", "Alias", "SpanModel", "\n\n", "var", "timestamp", "int64", "\n", "if", "!", "s", ".", "Timestamp", ".", "IsZero", "(", ")", "{", "if", "s", ".", "Timestamp", ".", "Unix", "(", ")", "<", "1", "{", "// Zipkin does not allow Timestamps before Unix epoch", "return", "nil", ",", "ErrValidTimestampRequired", "\n", "}", "\n", "timestamp", "=", "s", ".", "Timestamp", ".", "Round", "(", "time", ".", "Microsecond", ")", ".", "UnixNano", "(", ")", "/", "1e3", "\n", "}", "\n\n", "if", "s", ".", "Duration", "<", "time", ".", "Microsecond", "{", "if", "s", ".", "Duration", "<", "0", "{", "// negative duration is not allowed and signals a timing logic error", "return", "nil", ",", "ErrValidDurationRequired", "\n", "}", "else", "if", "s", ".", "Duration", ">", "0", "{", "// sub microsecond durations are reported as 1 microsecond", "s", ".", "Duration", "=", "1", "*", "time", ".", "Microsecond", "\n", "}", "\n", "}", "else", "{", "// Duration will be rounded to nearest microsecond representation.", "//", "// NOTE: Duration.Round() is not available in Go 1.8 which we still support.", "// To handle microsecond resolution rounding we'll add 500 nanoseconds to", "// the duration. When truncated to microseconds in the call to marshal, it", "// will be naturally rounded. See TestSpanDurationRounding in span_test.go", "s", ".", "Duration", "+=", "500", "*", "time", ".", "Nanosecond", "\n", "}", "\n\n", "if", "s", ".", "LocalEndpoint", ".", "Empty", "(", ")", "{", "s", ".", "LocalEndpoint", "=", "nil", "\n", "}", "\n\n", "if", "s", ".", "RemoteEndpoint", ".", "Empty", "(", ")", "{", "s", ".", "RemoteEndpoint", "=", "nil", "\n", "}", "\n\n", "return", "json", ".", "Marshal", "(", "&", "struct", "{", "T", "int64", "`json:\"timestamp,omitempty\"`", "\n", "D", "int64", "`json:\"duration,omitempty\"`", "\n", "Alias", "\n", "}", "{", "T", ":", "timestamp", ",", "D", ":", "s", ".", "Duration", ".", "Nanoseconds", "(", ")", "/", "1e3", ",", "Alias", ":", "(", "Alias", ")", "(", "s", ")", ",", "}", ")", "\n", "}" ]
// MarshalJSON exports our Model into the correct format for the Zipkin V2 API.
[ "MarshalJSON", "exports", "our", "Model", "into", "the", "correct", "format", "for", "the", "Zipkin", "V2", "API", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/model/span.go#L60-L107
train
openzipkin/zipkin-go
model/span.go
UnmarshalJSON
func (s *SpanModel) UnmarshalJSON(b []byte) error { type Alias SpanModel span := &struct { T uint64 `json:"timestamp,omitempty"` D uint64 `json:"duration,omitempty"` *Alias }{ Alias: (*Alias)(s), } if err := json.Unmarshal(b, &span); err != nil { return err } if s.ID < 1 { return ErrValidIDRequired } if span.T > 0 { s.Timestamp = time.Unix(0, int64(span.T)*1e3) } s.Duration = time.Duration(span.D*1e3) * time.Nanosecond if s.LocalEndpoint.Empty() { s.LocalEndpoint = nil } if s.RemoteEndpoint.Empty() { s.RemoteEndpoint = nil } return nil }
go
func (s *SpanModel) UnmarshalJSON(b []byte) error { type Alias SpanModel span := &struct { T uint64 `json:"timestamp,omitempty"` D uint64 `json:"duration,omitempty"` *Alias }{ Alias: (*Alias)(s), } if err := json.Unmarshal(b, &span); err != nil { return err } if s.ID < 1 { return ErrValidIDRequired } if span.T > 0 { s.Timestamp = time.Unix(0, int64(span.T)*1e3) } s.Duration = time.Duration(span.D*1e3) * time.Nanosecond if s.LocalEndpoint.Empty() { s.LocalEndpoint = nil } if s.RemoteEndpoint.Empty() { s.RemoteEndpoint = nil } return nil }
[ "func", "(", "s", "*", "SpanModel", ")", "UnmarshalJSON", "(", "b", "[", "]", "byte", ")", "error", "{", "type", "Alias", "SpanModel", "\n", "span", ":=", "&", "struct", "{", "T", "uint64", "`json:\"timestamp,omitempty\"`", "\n", "D", "uint64", "`json:\"duration,omitempty\"`", "\n", "*", "Alias", "\n", "}", "{", "Alias", ":", "(", "*", "Alias", ")", "(", "s", ")", ",", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "b", ",", "&", "span", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "s", ".", "ID", "<", "1", "{", "return", "ErrValidIDRequired", "\n", "}", "\n", "if", "span", ".", "T", ">", "0", "{", "s", ".", "Timestamp", "=", "time", ".", "Unix", "(", "0", ",", "int64", "(", "span", ".", "T", ")", "*", "1e3", ")", "\n", "}", "\n", "s", ".", "Duration", "=", "time", ".", "Duration", "(", "span", ".", "D", "*", "1e3", ")", "*", "time", ".", "Nanosecond", "\n", "if", "s", ".", "LocalEndpoint", ".", "Empty", "(", ")", "{", "s", ".", "LocalEndpoint", "=", "nil", "\n", "}", "\n\n", "if", "s", ".", "RemoteEndpoint", ".", "Empty", "(", ")", "{", "s", ".", "RemoteEndpoint", "=", "nil", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON imports our Model from a Zipkin V2 API compatible span // representation.
[ "UnmarshalJSON", "imports", "our", "Model", "from", "a", "Zipkin", "V2", "API", "compatible", "span", "representation", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/model/span.go#L111-L138
train
openzipkin/zipkin-go
tags.go
Set
func (t Tag) Set(s Span, value string) { s.Tag(string(t), value) }
go
func (t Tag) Set(s Span, value string) { s.Tag(string(t), value) }
[ "func", "(", "t", "Tag", ")", "Set", "(", "s", "Span", ",", "value", "string", ")", "{", "s", ".", "Tag", "(", "string", "(", "t", ")", ",", "value", ")", "\n", "}" ]
// Set a standard Tag with a payload on provided Span.
[ "Set", "a", "standard", "Tag", "with", "a", "payload", "on", "provided", "Span", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tags.go#L35-L37
train
openzipkin/zipkin-go
sample.go
NewModuloSampler
func NewModuloSampler(mod uint64) Sampler { if mod < 2 { return AlwaysSample } return func(id uint64) bool { return (id % mod) == 0 } }
go
func NewModuloSampler(mod uint64) Sampler { if mod < 2 { return AlwaysSample } return func(id uint64) bool { return (id % mod) == 0 } }
[ "func", "NewModuloSampler", "(", "mod", "uint64", ")", "Sampler", "{", "if", "mod", "<", "2", "{", "return", "AlwaysSample", "\n", "}", "\n", "return", "func", "(", "id", "uint64", ")", "bool", "{", "return", "(", "id", "%", "mod", ")", "==", "0", "\n", "}", "\n", "}" ]
// NewModuloSampler provides a generic type Sampler.
[ "NewModuloSampler", "provides", "a", "generic", "type", "Sampler", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/sample.go#L40-L47
train
openzipkin/zipkin-go
tracer.go
NewTracer
func NewTracer(rep reporter.Reporter, opts ...TracerOption) (*Tracer, error) { // set default tracer options t := &Tracer{ defaultTags: make(map[string]string), extractFailurePolicy: ExtractFailurePolicyRestart, sampler: AlwaysSample, generate: idgenerator.NewRandom64(), reporter: rep, localEndpoint: nil, noop: 0, sharedSpans: true, unsampledNoop: false, } // if no reporter was provided we default to noop implementation. if t.reporter == nil { t.reporter = reporter.NewNoopReporter() t.noop = 1 } // process functional options for _, opt := range opts { if err := opt(t); err != nil { return nil, err } } return t, nil }
go
func NewTracer(rep reporter.Reporter, opts ...TracerOption) (*Tracer, error) { // set default tracer options t := &Tracer{ defaultTags: make(map[string]string), extractFailurePolicy: ExtractFailurePolicyRestart, sampler: AlwaysSample, generate: idgenerator.NewRandom64(), reporter: rep, localEndpoint: nil, noop: 0, sharedSpans: true, unsampledNoop: false, } // if no reporter was provided we default to noop implementation. if t.reporter == nil { t.reporter = reporter.NewNoopReporter() t.noop = 1 } // process functional options for _, opt := range opts { if err := opt(t); err != nil { return nil, err } } return t, nil }
[ "func", "NewTracer", "(", "rep", "reporter", ".", "Reporter", ",", "opts", "...", "TracerOption", ")", "(", "*", "Tracer", ",", "error", ")", "{", "// set default tracer options", "t", ":=", "&", "Tracer", "{", "defaultTags", ":", "make", "(", "map", "[", "string", "]", "string", ")", ",", "extractFailurePolicy", ":", "ExtractFailurePolicyRestart", ",", "sampler", ":", "AlwaysSample", ",", "generate", ":", "idgenerator", ".", "NewRandom64", "(", ")", ",", "reporter", ":", "rep", ",", "localEndpoint", ":", "nil", ",", "noop", ":", "0", ",", "sharedSpans", ":", "true", ",", "unsampledNoop", ":", "false", ",", "}", "\n\n", "// if no reporter was provided we default to noop implementation.", "if", "t", ".", "reporter", "==", "nil", "{", "t", ".", "reporter", "=", "reporter", ".", "NewNoopReporter", "(", ")", "\n", "t", ".", "noop", "=", "1", "\n", "}", "\n\n", "// process functional options", "for", "_", ",", "opt", ":=", "range", "opts", "{", "if", "err", ":=", "opt", "(", "t", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "t", ",", "nil", "\n", "}" ]
// NewTracer returns a new Zipkin Tracer.
[ "NewTracer", "returns", "a", "new", "Zipkin", "Tracer", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tracer.go#L43-L71
train
openzipkin/zipkin-go
tracer.go
StartSpanFromContext
func (t *Tracer) StartSpanFromContext(ctx context.Context, name string, options ...SpanOption) (Span, context.Context) { if parentSpan := SpanFromContext(ctx); parentSpan != nil { options = append(options, Parent(parentSpan.Context())) } span := t.StartSpan(name, options...) return span, NewContext(ctx, span) }
go
func (t *Tracer) StartSpanFromContext(ctx context.Context, name string, options ...SpanOption) (Span, context.Context) { if parentSpan := SpanFromContext(ctx); parentSpan != nil { options = append(options, Parent(parentSpan.Context())) } span := t.StartSpan(name, options...) return span, NewContext(ctx, span) }
[ "func", "(", "t", "*", "Tracer", ")", "StartSpanFromContext", "(", "ctx", "context", ".", "Context", ",", "name", "string", ",", "options", "...", "SpanOption", ")", "(", "Span", ",", "context", ".", "Context", ")", "{", "if", "parentSpan", ":=", "SpanFromContext", "(", "ctx", ")", ";", "parentSpan", "!=", "nil", "{", "options", "=", "append", "(", "options", ",", "Parent", "(", "parentSpan", ".", "Context", "(", ")", ")", ")", "\n", "}", "\n", "span", ":=", "t", ".", "StartSpan", "(", "name", ",", "options", "...", ")", "\n", "return", "span", ",", "NewContext", "(", "ctx", ",", "span", ")", "\n", "}" ]
// StartSpanFromContext creates and starts a span using the span found in // context as parent. If no parent span is found a root span is created.
[ "StartSpanFromContext", "creates", "and", "starts", "a", "span", "using", "the", "span", "found", "in", "context", "as", "parent", ".", "If", "no", "parent", "span", "is", "found", "a", "root", "span", "is", "created", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tracer.go#L75-L81
train
openzipkin/zipkin-go
tracer.go
StartSpan
func (t *Tracer) StartSpan(name string, options ...SpanOption) Span { if atomic.LoadInt32(&t.noop) == 1 { return &noopSpan{} } s := &spanImpl{ SpanModel: model.SpanModel{ Kind: model.Undetermined, Name: name, LocalEndpoint: t.localEndpoint, Annotations: make([]model.Annotation, 0), Tags: make(map[string]string), }, flushOnFinish: true, tracer: t, } // add default tracer tags to span for k, v := range t.defaultTags { s.Tag(k, v) } // handle provided functional options for _, option := range options { option(t, s) } if s.TraceID.Empty() { // create root span s.SpanContext.TraceID = t.generate.TraceID() s.SpanContext.ID = t.generate.SpanID(s.SpanContext.TraceID) } else { // valid parent context found if t.sharedSpans && s.Kind == model.Server { // join span s.Shared = true } else { // regular child span parentID := s.SpanContext.ID s.SpanContext.ParentID = &parentID s.SpanContext.ID = t.generate.SpanID(model.TraceID{}) } } if !s.SpanContext.Debug && s.Sampled == nil { // deferred sampled context found, invoke sampler sampled := t.sampler(s.SpanContext.TraceID.Low) s.SpanContext.Sampled = &sampled if sampled { s.mustCollect = 1 } } else { if s.SpanContext.Debug || *s.Sampled { s.mustCollect = 1 } } if t.unsampledNoop && s.mustCollect == 0 { // trace not being sampled and noop requested return &noopSpan{ SpanContext: s.SpanContext, } } // add start time if s.Timestamp.IsZero() { s.Timestamp = time.Now() } return s }
go
func (t *Tracer) StartSpan(name string, options ...SpanOption) Span { if atomic.LoadInt32(&t.noop) == 1 { return &noopSpan{} } s := &spanImpl{ SpanModel: model.SpanModel{ Kind: model.Undetermined, Name: name, LocalEndpoint: t.localEndpoint, Annotations: make([]model.Annotation, 0), Tags: make(map[string]string), }, flushOnFinish: true, tracer: t, } // add default tracer tags to span for k, v := range t.defaultTags { s.Tag(k, v) } // handle provided functional options for _, option := range options { option(t, s) } if s.TraceID.Empty() { // create root span s.SpanContext.TraceID = t.generate.TraceID() s.SpanContext.ID = t.generate.SpanID(s.SpanContext.TraceID) } else { // valid parent context found if t.sharedSpans && s.Kind == model.Server { // join span s.Shared = true } else { // regular child span parentID := s.SpanContext.ID s.SpanContext.ParentID = &parentID s.SpanContext.ID = t.generate.SpanID(model.TraceID{}) } } if !s.SpanContext.Debug && s.Sampled == nil { // deferred sampled context found, invoke sampler sampled := t.sampler(s.SpanContext.TraceID.Low) s.SpanContext.Sampled = &sampled if sampled { s.mustCollect = 1 } } else { if s.SpanContext.Debug || *s.Sampled { s.mustCollect = 1 } } if t.unsampledNoop && s.mustCollect == 0 { // trace not being sampled and noop requested return &noopSpan{ SpanContext: s.SpanContext, } } // add start time if s.Timestamp.IsZero() { s.Timestamp = time.Now() } return s }
[ "func", "(", "t", "*", "Tracer", ")", "StartSpan", "(", "name", "string", ",", "options", "...", "SpanOption", ")", "Span", "{", "if", "atomic", ".", "LoadInt32", "(", "&", "t", ".", "noop", ")", "==", "1", "{", "return", "&", "noopSpan", "{", "}", "\n", "}", "\n", "s", ":=", "&", "spanImpl", "{", "SpanModel", ":", "model", ".", "SpanModel", "{", "Kind", ":", "model", ".", "Undetermined", ",", "Name", ":", "name", ",", "LocalEndpoint", ":", "t", ".", "localEndpoint", ",", "Annotations", ":", "make", "(", "[", "]", "model", ".", "Annotation", ",", "0", ")", ",", "Tags", ":", "make", "(", "map", "[", "string", "]", "string", ")", ",", "}", ",", "flushOnFinish", ":", "true", ",", "tracer", ":", "t", ",", "}", "\n\n", "// add default tracer tags to span", "for", "k", ",", "v", ":=", "range", "t", ".", "defaultTags", "{", "s", ".", "Tag", "(", "k", ",", "v", ")", "\n", "}", "\n\n", "// handle provided functional options", "for", "_", ",", "option", ":=", "range", "options", "{", "option", "(", "t", ",", "s", ")", "\n", "}", "\n\n", "if", "s", ".", "TraceID", ".", "Empty", "(", ")", "{", "// create root span", "s", ".", "SpanContext", ".", "TraceID", "=", "t", ".", "generate", ".", "TraceID", "(", ")", "\n", "s", ".", "SpanContext", ".", "ID", "=", "t", ".", "generate", ".", "SpanID", "(", "s", ".", "SpanContext", ".", "TraceID", ")", "\n", "}", "else", "{", "// valid parent context found", "if", "t", ".", "sharedSpans", "&&", "s", ".", "Kind", "==", "model", ".", "Server", "{", "// join span", "s", ".", "Shared", "=", "true", "\n", "}", "else", "{", "// regular child span", "parentID", ":=", "s", ".", "SpanContext", ".", "ID", "\n", "s", ".", "SpanContext", ".", "ParentID", "=", "&", "parentID", "\n", "s", ".", "SpanContext", ".", "ID", "=", "t", ".", "generate", ".", "SpanID", "(", "model", ".", "TraceID", "{", "}", ")", "\n", "}", "\n", "}", "\n\n", "if", "!", "s", ".", "SpanContext", ".", "Debug", "&&", "s", ".", "Sampled", "==", "nil", "{", "// deferred sampled context found, invoke sampler", "sampled", ":=", "t", ".", "sampler", "(", "s", ".", "SpanContext", ".", "TraceID", ".", "Low", ")", "\n", "s", ".", "SpanContext", ".", "Sampled", "=", "&", "sampled", "\n", "if", "sampled", "{", "s", ".", "mustCollect", "=", "1", "\n", "}", "\n", "}", "else", "{", "if", "s", ".", "SpanContext", ".", "Debug", "||", "*", "s", ".", "Sampled", "{", "s", ".", "mustCollect", "=", "1", "\n", "}", "\n", "}", "\n\n", "if", "t", ".", "unsampledNoop", "&&", "s", ".", "mustCollect", "==", "0", "{", "// trace not being sampled and noop requested", "return", "&", "noopSpan", "{", "SpanContext", ":", "s", ".", "SpanContext", ",", "}", "\n", "}", "\n\n", "// add start time", "if", "s", ".", "Timestamp", ".", "IsZero", "(", ")", "{", "s", ".", "Timestamp", "=", "time", ".", "Now", "(", ")", "\n", "}", "\n\n", "return", "s", "\n", "}" ]
// StartSpan creates and starts a span.
[ "StartSpan", "creates", "and", "starts", "a", "span", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tracer.go#L84-L153
train
openzipkin/zipkin-go
tracer.go
Extract
func (t *Tracer) Extract(extractor propagation.Extractor) (sc model.SpanContext) { if atomic.LoadInt32(&t.noop) == 1 { return } psc, err := extractor() if psc != nil { sc = *psc } sc.Err = err return }
go
func (t *Tracer) Extract(extractor propagation.Extractor) (sc model.SpanContext) { if atomic.LoadInt32(&t.noop) == 1 { return } psc, err := extractor() if psc != nil { sc = *psc } sc.Err = err return }
[ "func", "(", "t", "*", "Tracer", ")", "Extract", "(", "extractor", "propagation", ".", "Extractor", ")", "(", "sc", "model", ".", "SpanContext", ")", "{", "if", "atomic", ".", "LoadInt32", "(", "&", "t", ".", "noop", ")", "==", "1", "{", "return", "\n", "}", "\n", "psc", ",", "err", ":=", "extractor", "(", ")", "\n", "if", "psc", "!=", "nil", "{", "sc", "=", "*", "psc", "\n", "}", "\n", "sc", ".", "Err", "=", "err", "\n", "return", "\n", "}" ]
// Extract extracts a SpanContext using the provided Extractor function.
[ "Extract", "extracts", "a", "SpanContext", "using", "the", "provided", "Extractor", "function", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tracer.go#L156-L166
train
openzipkin/zipkin-go
tracer.go
SetNoop
func (t *Tracer) SetNoop(noop bool) { if noop { atomic.CompareAndSwapInt32(&t.noop, 0, 1) } else { atomic.CompareAndSwapInt32(&t.noop, 1, 0) } }
go
func (t *Tracer) SetNoop(noop bool) { if noop { atomic.CompareAndSwapInt32(&t.noop, 0, 1) } else { atomic.CompareAndSwapInt32(&t.noop, 1, 0) } }
[ "func", "(", "t", "*", "Tracer", ")", "SetNoop", "(", "noop", "bool", ")", "{", "if", "noop", "{", "atomic", ".", "CompareAndSwapInt32", "(", "&", "t", ".", "noop", ",", "0", ",", "1", ")", "\n", "}", "else", "{", "atomic", ".", "CompareAndSwapInt32", "(", "&", "t", ".", "noop", ",", "1", ",", "0", ")", "\n", "}", "\n", "}" ]
// SetNoop allows for killswitch behavior. If set to true the tracer will return // noopSpans and all data is dropped. This allows operators to stop tracing in // risk scenarios. Set back to false to resume tracing.
[ "SetNoop", "allows", "for", "killswitch", "behavior", ".", "If", "set", "to", "true", "the", "tracer", "will", "return", "noopSpans", "and", "all", "data", "is", "dropped", ".", "This", "allows", "operators", "to", "stop", "tracing", "in", "risk", "scenarios", ".", "Set", "back", "to", "false", "to", "resume", "tracing", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tracer.go#L171-L177
train
openzipkin/zipkin-go
tracer.go
LocalEndpoint
func (t *Tracer) LocalEndpoint() *model.Endpoint { if t.localEndpoint == nil { return nil } ep := *t.localEndpoint return &ep }
go
func (t *Tracer) LocalEndpoint() *model.Endpoint { if t.localEndpoint == nil { return nil } ep := *t.localEndpoint return &ep }
[ "func", "(", "t", "*", "Tracer", ")", "LocalEndpoint", "(", ")", "*", "model", ".", "Endpoint", "{", "if", "t", ".", "localEndpoint", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "ep", ":=", "*", "t", ".", "localEndpoint", "\n", "return", "&", "ep", "\n", "}" ]
// LocalEndpoint returns a copy of the currently set local endpoint of the // tracer instance.
[ "LocalEndpoint", "returns", "a", "copy", "of", "the", "currently", "set", "local", "endpoint", "of", "the", "tracer", "instance", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/tracer.go#L181-L187
train
openzipkin/zipkin-go
endpoint.go
NewEndpoint
func NewEndpoint(serviceName string, hostPort string) (*model.Endpoint, error) { e := &model.Endpoint{ ServiceName: serviceName, } if hostPort == "" || hostPort == ":0" { if serviceName == "" { // if all properties are empty we should not have an Endpoint object. return nil, nil } return e, nil } if strings.IndexByte(hostPort, ':') < 0 { hostPort += ":0" } host, port, err := net.SplitHostPort(hostPort) if err != nil { return nil, err } p, err := strconv.ParseUint(port, 10, 16) if err != nil { return nil, err } e.Port = uint16(p) addrs, err := net.LookupIP(host) if err != nil { return nil, err } for i := range addrs { addr := addrs[i].To4() if addr == nil { // IPv6 - 16 bytes if e.IPv6 == nil { e.IPv6 = addrs[i].To16() } } else { // IPv4 - 4 bytes if e.IPv4 == nil { e.IPv4 = addr } } if e.IPv4 != nil && e.IPv6 != nil { // Both IPv4 & IPv6 have been set, done... break } } return e, nil }
go
func NewEndpoint(serviceName string, hostPort string) (*model.Endpoint, error) { e := &model.Endpoint{ ServiceName: serviceName, } if hostPort == "" || hostPort == ":0" { if serviceName == "" { // if all properties are empty we should not have an Endpoint object. return nil, nil } return e, nil } if strings.IndexByte(hostPort, ':') < 0 { hostPort += ":0" } host, port, err := net.SplitHostPort(hostPort) if err != nil { return nil, err } p, err := strconv.ParseUint(port, 10, 16) if err != nil { return nil, err } e.Port = uint16(p) addrs, err := net.LookupIP(host) if err != nil { return nil, err } for i := range addrs { addr := addrs[i].To4() if addr == nil { // IPv6 - 16 bytes if e.IPv6 == nil { e.IPv6 = addrs[i].To16() } } else { // IPv4 - 4 bytes if e.IPv4 == nil { e.IPv4 = addr } } if e.IPv4 != nil && e.IPv6 != nil { // Both IPv4 & IPv6 have been set, done... break } } return e, nil }
[ "func", "NewEndpoint", "(", "serviceName", "string", ",", "hostPort", "string", ")", "(", "*", "model", ".", "Endpoint", ",", "error", ")", "{", "e", ":=", "&", "model", ".", "Endpoint", "{", "ServiceName", ":", "serviceName", ",", "}", "\n\n", "if", "hostPort", "==", "\"", "\"", "||", "hostPort", "==", "\"", "\"", "{", "if", "serviceName", "==", "\"", "\"", "{", "// if all properties are empty we should not have an Endpoint object.", "return", "nil", ",", "nil", "\n", "}", "\n", "return", "e", ",", "nil", "\n", "}", "\n\n", "if", "strings", ".", "IndexByte", "(", "hostPort", ",", "':'", ")", "<", "0", "{", "hostPort", "+=", "\"", "\"", "\n", "}", "\n\n", "host", ",", "port", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "hostPort", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "p", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "port", ",", "10", ",", "16", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "e", ".", "Port", "=", "uint16", "(", "p", ")", "\n\n", "addrs", ",", "err", ":=", "net", ".", "LookupIP", "(", "host", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "for", "i", ":=", "range", "addrs", "{", "addr", ":=", "addrs", "[", "i", "]", ".", "To4", "(", ")", "\n", "if", "addr", "==", "nil", "{", "// IPv6 - 16 bytes", "if", "e", ".", "IPv6", "==", "nil", "{", "e", ".", "IPv6", "=", "addrs", "[", "i", "]", ".", "To16", "(", ")", "\n", "}", "\n", "}", "else", "{", "// IPv4 - 4 bytes", "if", "e", ".", "IPv4", "==", "nil", "{", "e", ".", "IPv4", "=", "addr", "\n", "}", "\n", "}", "\n", "if", "e", ".", "IPv4", "!=", "nil", "&&", "e", ".", "IPv6", "!=", "nil", "{", "// Both IPv4 & IPv6 have been set, done...", "break", "\n", "}", "\n", "}", "\n\n", "return", "e", ",", "nil", "\n", "}" ]
// NewEndpoint creates a new endpoint given the provided serviceName and // hostPort.
[ "NewEndpoint", "creates", "a", "new", "endpoint", "given", "the", "provided", "serviceName", "and", "hostPort", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/endpoint.go#L27-L80
train
openzipkin/zipkin-go
reporter/kafka/kafka.go
Producer
func Producer(p sarama.AsyncProducer) ReporterOption { return func(c *kafkaReporter) { c.producer = p } }
go
func Producer(p sarama.AsyncProducer) ReporterOption { return func(c *kafkaReporter) { c.producer = p } }
[ "func", "Producer", "(", "p", "sarama", ".", "AsyncProducer", ")", "ReporterOption", "{", "return", "func", "(", "c", "*", "kafkaReporter", ")", "{", "c", ".", "producer", "=", "p", "\n", "}", "\n", "}" ]
// Producer sets the producer used to produce to Kafka.
[ "Producer", "sets", "the", "producer", "used", "to", "produce", "to", "Kafka", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/reporter/kafka/kafka.go#L56-L60
train
openzipkin/zipkin-go
middleware/grpc/server.go
NewServerHandler
func NewServerHandler(tracer *zipkin.Tracer, options ...ServerOption) stats.Handler { c := &serverHandler{ tracer: tracer, } for _, option := range options { option(c) } return c }
go
func NewServerHandler(tracer *zipkin.Tracer, options ...ServerOption) stats.Handler { c := &serverHandler{ tracer: tracer, } for _, option := range options { option(c) } return c }
[ "func", "NewServerHandler", "(", "tracer", "*", "zipkin", ".", "Tracer", ",", "options", "...", "ServerOption", ")", "stats", ".", "Handler", "{", "c", ":=", "&", "serverHandler", "{", "tracer", ":", "tracer", ",", "}", "\n", "for", "_", ",", "option", ":=", "range", "options", "{", "option", "(", "c", ")", "\n", "}", "\n", "return", "c", "\n", "}" ]
// NewServerHandler returns a stats.Handler which can be used with grpc.WithStatsHandler to add // tracing to a gRPC server. The gRPC method name is used as the span name and by default the only // tags are the gRPC status code if the call fails. Use ServerTags to add additional tags that // should be applied to all spans.
[ "NewServerHandler", "returns", "a", "stats", ".", "Handler", "which", "can", "be", "used", "with", "grpc", ".", "WithStatsHandler", "to", "add", "tracing", "to", "a", "gRPC", "server", ".", "The", "gRPC", "method", "name", "is", "used", "as", "the", "span", "name", "and", "by", "default", "the", "only", "tags", "are", "the", "gRPC", "status", "code", "if", "the", "call", "fails", ".", "Use", "ServerTags", "to", "add", "additional", "tags", "that", "should", "be", "applied", "to", "all", "spans", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/middleware/grpc/server.go#L46-L54
train
openzipkin/zipkin-go
span_options.go
Kind
func Kind(kind model.Kind) SpanOption { return func(t *Tracer, s *spanImpl) { s.Kind = kind } }
go
func Kind(kind model.Kind) SpanOption { return func(t *Tracer, s *spanImpl) { s.Kind = kind } }
[ "func", "Kind", "(", "kind", "model", ".", "Kind", ")", "SpanOption", "{", "return", "func", "(", "t", "*", "Tracer", ",", "s", "*", "spanImpl", ")", "{", "s", ".", "Kind", "=", "kind", "\n", "}", "\n", "}" ]
// Kind sets the kind of the span being created..
[ "Kind", "sets", "the", "kind", "of", "the", "span", "being", "created", ".." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/span_options.go#L28-L32
train
openzipkin/zipkin-go
span_options.go
Parent
func Parent(sc model.SpanContext) SpanOption { return func(t *Tracer, s *spanImpl) { if sc.Err != nil { // encountered an extraction error switch t.extractFailurePolicy { case ExtractFailurePolicyRestart: case ExtractFailurePolicyError: panic(s.SpanContext.Err) case ExtractFailurePolicyTagAndRestart: s.Tags["error.extract"] = sc.Err.Error() default: panic(ErrInvalidExtractFailurePolicy) } /* don't use provided SpanContext, but restart trace */ return } s.SpanContext = sc } }
go
func Parent(sc model.SpanContext) SpanOption { return func(t *Tracer, s *spanImpl) { if sc.Err != nil { // encountered an extraction error switch t.extractFailurePolicy { case ExtractFailurePolicyRestart: case ExtractFailurePolicyError: panic(s.SpanContext.Err) case ExtractFailurePolicyTagAndRestart: s.Tags["error.extract"] = sc.Err.Error() default: panic(ErrInvalidExtractFailurePolicy) } /* don't use provided SpanContext, but restart trace */ return } s.SpanContext = sc } }
[ "func", "Parent", "(", "sc", "model", ".", "SpanContext", ")", "SpanOption", "{", "return", "func", "(", "t", "*", "Tracer", ",", "s", "*", "spanImpl", ")", "{", "if", "sc", ".", "Err", "!=", "nil", "{", "// encountered an extraction error", "switch", "t", ".", "extractFailurePolicy", "{", "case", "ExtractFailurePolicyRestart", ":", "case", "ExtractFailurePolicyError", ":", "panic", "(", "s", ".", "SpanContext", ".", "Err", ")", "\n", "case", "ExtractFailurePolicyTagAndRestart", ":", "s", ".", "Tags", "[", "\"", "\"", "]", "=", "sc", ".", "Err", ".", "Error", "(", ")", "\n", "default", ":", "panic", "(", "ErrInvalidExtractFailurePolicy", ")", "\n", "}", "\n", "/* don't use provided SpanContext, but restart trace */", "return", "\n", "}", "\n", "s", ".", "SpanContext", "=", "sc", "\n", "}", "\n", "}" ]
// Parent will use provided SpanContext as parent to the span being created.
[ "Parent", "will", "use", "provided", "SpanContext", "as", "parent", "to", "the", "span", "being", "created", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/span_options.go#L35-L53
train
openzipkin/zipkin-go
span_options.go
StartTime
func StartTime(start time.Time) SpanOption { return func(t *Tracer, s *spanImpl) { s.Timestamp = start } }
go
func StartTime(start time.Time) SpanOption { return func(t *Tracer, s *spanImpl) { s.Timestamp = start } }
[ "func", "StartTime", "(", "start", "time", ".", "Time", ")", "SpanOption", "{", "return", "func", "(", "t", "*", "Tracer", ",", "s", "*", "spanImpl", ")", "{", "s", ".", "Timestamp", "=", "start", "\n", "}", "\n", "}" ]
// StartTime uses a given start time for the span being created.
[ "StartTime", "uses", "a", "given", "start", "time", "for", "the", "span", "being", "created", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/span_options.go#L56-L60
train
openzipkin/zipkin-go
span_options.go
RemoteEndpoint
func RemoteEndpoint(e *model.Endpoint) SpanOption { return func(t *Tracer, s *spanImpl) { s.RemoteEndpoint = e } }
go
func RemoteEndpoint(e *model.Endpoint) SpanOption { return func(t *Tracer, s *spanImpl) { s.RemoteEndpoint = e } }
[ "func", "RemoteEndpoint", "(", "e", "*", "model", ".", "Endpoint", ")", "SpanOption", "{", "return", "func", "(", "t", "*", "Tracer", ",", "s", "*", "spanImpl", ")", "{", "s", ".", "RemoteEndpoint", "=", "e", "\n", "}", "\n", "}" ]
// RemoteEndpoint sets the remote endpoint of the span being created.
[ "RemoteEndpoint", "sets", "the", "remote", "endpoint", "of", "the", "span", "being", "created", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/span_options.go#L63-L67
train
openzipkin/zipkin-go
span_options.go
Tags
func Tags(tags map[string]string) SpanOption { return func(t *Tracer, s *spanImpl) { for k, v := range tags { s.Tags[k] = v } } }
go
func Tags(tags map[string]string) SpanOption { return func(t *Tracer, s *spanImpl) { for k, v := range tags { s.Tags[k] = v } } }
[ "func", "Tags", "(", "tags", "map", "[", "string", "]", "string", ")", "SpanOption", "{", "return", "func", "(", "t", "*", "Tracer", ",", "s", "*", "spanImpl", ")", "{", "for", "k", ",", "v", ":=", "range", "tags", "{", "s", ".", "Tags", "[", "k", "]", "=", "v", "\n", "}", "\n", "}", "\n", "}" ]
// Tags sets initial tags for the span being created. If default tracer tags // are present they will be overwritten on key collisions.
[ "Tags", "sets", "initial", "tags", "for", "the", "span", "being", "created", ".", "If", "default", "tracer", "tags", "are", "present", "they", "will", "be", "overwritten", "on", "key", "collisions", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/span_options.go#L71-L77
train
openzipkin/zipkin-go
model/traceid.go
String
func (t TraceID) String() string { if t.High == 0 { return fmt.Sprintf("%016x", t.Low) } return fmt.Sprintf("%016x%016x", t.High, t.Low) }
go
func (t TraceID) String() string { if t.High == 0 { return fmt.Sprintf("%016x", t.Low) } return fmt.Sprintf("%016x%016x", t.High, t.Low) }
[ "func", "(", "t", "TraceID", ")", "String", "(", ")", "string", "{", "if", "t", ".", "High", "==", "0", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "t", ".", "Low", ")", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "t", ".", "High", ",", "t", ".", "Low", ")", "\n", "}" ]
// String outputs the 128-bit traceID as hex string.
[ "String", "outputs", "the", "128", "-", "bit", "traceID", "as", "hex", "string", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/model/traceid.go#L35-L40
train
openzipkin/zipkin-go
model/traceid.go
TraceIDFromHex
func TraceIDFromHex(h string) (t TraceID, err error) { if len(h) > 16 { if t.High, err = strconv.ParseUint(h[0:len(h)-16], 16, 64); err != nil { return } t.Low, err = strconv.ParseUint(h[len(h)-16:], 16, 64) return } t.Low, err = strconv.ParseUint(h, 16, 64) return }
go
func TraceIDFromHex(h string) (t TraceID, err error) { if len(h) > 16 { if t.High, err = strconv.ParseUint(h[0:len(h)-16], 16, 64); err != nil { return } t.Low, err = strconv.ParseUint(h[len(h)-16:], 16, 64) return } t.Low, err = strconv.ParseUint(h, 16, 64) return }
[ "func", "TraceIDFromHex", "(", "h", "string", ")", "(", "t", "TraceID", ",", "err", "error", ")", "{", "if", "len", "(", "h", ")", ">", "16", "{", "if", "t", ".", "High", ",", "err", "=", "strconv", ".", "ParseUint", "(", "h", "[", "0", ":", "len", "(", "h", ")", "-", "16", "]", ",", "16", ",", "64", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "t", ".", "Low", ",", "err", "=", "strconv", ".", "ParseUint", "(", "h", "[", "len", "(", "h", ")", "-", "16", ":", "]", ",", "16", ",", "64", ")", "\n", "return", "\n", "}", "\n", "t", ".", "Low", ",", "err", "=", "strconv", ".", "ParseUint", "(", "h", ",", "16", ",", "64", ")", "\n", "return", "\n", "}" ]
// TraceIDFromHex returns the TraceID from a hex string.
[ "TraceIDFromHex", "returns", "the", "TraceID", "from", "a", "hex", "string", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/model/traceid.go#L43-L53
train
openzipkin/zipkin-go
model/traceid.go
MarshalJSON
func (t TraceID) MarshalJSON() ([]byte, error) { return []byte(fmt.Sprintf("%q", t.String())), nil }
go
func (t TraceID) MarshalJSON() ([]byte, error) { return []byte(fmt.Sprintf("%q", t.String())), nil }
[ "func", "(", "t", "TraceID", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "[", "]", "byte", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "t", ".", "String", "(", ")", ")", ")", ",", "nil", "\n", "}" ]
// MarshalJSON custom JSON serializer to export the TraceID in the required // zero padded hex representation.
[ "MarshalJSON", "custom", "JSON", "serializer", "to", "export", "the", "TraceID", "in", "the", "required", "zero", "padded", "hex", "representation", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/model/traceid.go#L57-L59
train
openzipkin/zipkin-go
model/traceid.go
UnmarshalJSON
func (t *TraceID) UnmarshalJSON(traceID []byte) error { if len(traceID) < 3 { return ErrValidTraceIDRequired } // A valid JSON string is encoded wrapped in double quotes. We need to trim // these before converting the hex payload. tID, err := TraceIDFromHex(string(traceID[1 : len(traceID)-1])) if err != nil { return err } *t = tID return nil }
go
func (t *TraceID) UnmarshalJSON(traceID []byte) error { if len(traceID) < 3 { return ErrValidTraceIDRequired } // A valid JSON string is encoded wrapped in double quotes. We need to trim // these before converting the hex payload. tID, err := TraceIDFromHex(string(traceID[1 : len(traceID)-1])) if err != nil { return err } *t = tID return nil }
[ "func", "(", "t", "*", "TraceID", ")", "UnmarshalJSON", "(", "traceID", "[", "]", "byte", ")", "error", "{", "if", "len", "(", "traceID", ")", "<", "3", "{", "return", "ErrValidTraceIDRequired", "\n", "}", "\n", "// A valid JSON string is encoded wrapped in double quotes. We need to trim", "// these before converting the hex payload.", "tID", ",", "err", ":=", "TraceIDFromHex", "(", "string", "(", "traceID", "[", "1", ":", "len", "(", "traceID", ")", "-", "1", "]", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "*", "t", "=", "tID", "\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON custom JSON deserializer to retrieve the traceID from the hex // encoded representation.
[ "UnmarshalJSON", "custom", "JSON", "deserializer", "to", "retrieve", "the", "traceID", "from", "the", "hex", "encoded", "representation", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/model/traceid.go#L63-L75
train
openzipkin/zipkin-go
middleware/http/transport.go
RoundTripper
func RoundTripper(rt http.RoundTripper) TransportOption { return func(t *transport) { if rt != nil { t.rt = rt } } }
go
func RoundTripper(rt http.RoundTripper) TransportOption { return func(t *transport) { if rt != nil { t.rt = rt } } }
[ "func", "RoundTripper", "(", "rt", "http", ".", "RoundTripper", ")", "TransportOption", "{", "return", "func", "(", "t", "*", "transport", ")", "{", "if", "rt", "!=", "nil", "{", "t", ".", "rt", "=", "rt", "\n", "}", "\n", "}", "\n", "}" ]
// RoundTripper adds the Transport RoundTripper to wrap.
[ "RoundTripper", "adds", "the", "Transport", "RoundTripper", "to", "wrap", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/middleware/http/transport.go#L54-L60
train
openzipkin/zipkin-go
middleware/http/transport.go
TransportTags
func TransportTags(tags map[string]string) TransportOption { return func(t *transport) { t.defaultTags = tags } }
go
func TransportTags(tags map[string]string) TransportOption { return func(t *transport) { t.defaultTags = tags } }
[ "func", "TransportTags", "(", "tags", "map", "[", "string", "]", "string", ")", "TransportOption", "{", "return", "func", "(", "t", "*", "transport", ")", "{", "t", ".", "defaultTags", "=", "tags", "\n", "}", "\n", "}" ]
// TransportTags adds default Tags to inject into transport spans.
[ "TransportTags", "adds", "default", "Tags", "to", "inject", "into", "transport", "spans", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/middleware/http/transport.go#L63-L67
train
openzipkin/zipkin-go
middleware/http/transport.go
NewTransport
func NewTransport(tracer *zipkin.Tracer, options ...TransportOption) (http.RoundTripper, error) { if tracer == nil { return nil, ErrValidTracerRequired } t := &transport{ tracer: tracer, rt: http.DefaultTransport, httpTrace: false, errHandler: defaultErrHandler, } for _, option := range options { option(t) } return t, nil }
go
func NewTransport(tracer *zipkin.Tracer, options ...TransportOption) (http.RoundTripper, error) { if tracer == nil { return nil, ErrValidTracerRequired } t := &transport{ tracer: tracer, rt: http.DefaultTransport, httpTrace: false, errHandler: defaultErrHandler, } for _, option := range options { option(t) } return t, nil }
[ "func", "NewTransport", "(", "tracer", "*", "zipkin", ".", "Tracer", ",", "options", "...", "TransportOption", ")", "(", "http", ".", "RoundTripper", ",", "error", ")", "{", "if", "tracer", "==", "nil", "{", "return", "nil", ",", "ErrValidTracerRequired", "\n", "}", "\n\n", "t", ":=", "&", "transport", "{", "tracer", ":", "tracer", ",", "rt", ":", "http", ".", "DefaultTransport", ",", "httpTrace", ":", "false", ",", "errHandler", ":", "defaultErrHandler", ",", "}", "\n\n", "for", "_", ",", "option", ":=", "range", "options", "{", "option", "(", "t", ")", "\n", "}", "\n\n", "return", "t", ",", "nil", "\n", "}" ]
// NewTransport returns a new Zipkin instrumented http RoundTripper which can be // used with a standard library http Client.
[ "NewTransport", "returns", "a", "new", "Zipkin", "instrumented", "http", "RoundTripper", "which", "can", "be", "used", "with", "a", "standard", "library", "http", "Client", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/middleware/http/transport.go#L85-L102
train
openzipkin/zipkin-go
middleware/http/transport.go
RoundTrip
func (t *transport) RoundTrip(req *http.Request) (res *http.Response, err error) { sp, _ := t.tracer.StartSpanFromContext( req.Context(), req.URL.Scheme+"/"+req.Method, zipkin.Kind(model.Client), ) for k, v := range t.defaultTags { sp.Tag(k, v) } if t.httpTrace { sptr := spanTrace{ Span: sp, } sptr.c = &httptrace.ClientTrace{ GetConn: sptr.getConn, GotConn: sptr.gotConn, PutIdleConn: sptr.putIdleConn, GotFirstResponseByte: sptr.gotFirstResponseByte, Got100Continue: sptr.got100Continue, DNSStart: sptr.dnsStart, DNSDone: sptr.dnsDone, ConnectStart: sptr.connectStart, ConnectDone: sptr.connectDone, TLSHandshakeStart: sptr.tlsHandshakeStart, TLSHandshakeDone: sptr.tlsHandshakeDone, WroteHeaders: sptr.wroteHeaders, Wait100Continue: sptr.wait100Continue, WroteRequest: sptr.wroteRequest, } req = req.WithContext( httptrace.WithClientTrace(req.Context(), sptr.c), ) } zipkin.TagHTTPMethod.Set(sp, req.Method) zipkin.TagHTTPPath.Set(sp, req.URL.Path) _ = b3.InjectHTTP(req)(sp.Context()) res, err = t.rt.RoundTrip(req) if err != nil { t.errHandler(sp, err, 0) sp.Finish() return } if res.ContentLength > 0 { zipkin.TagHTTPResponseSize.Set(sp, strconv.FormatInt(res.ContentLength, 10)) } if res.StatusCode < 200 || res.StatusCode > 299 { statusCode := strconv.FormatInt(int64(res.StatusCode), 10) zipkin.TagHTTPStatusCode.Set(sp, statusCode) if res.StatusCode > 399 { t.errHandler(sp, nil, res.StatusCode) } } sp.Finish() return }
go
func (t *transport) RoundTrip(req *http.Request) (res *http.Response, err error) { sp, _ := t.tracer.StartSpanFromContext( req.Context(), req.URL.Scheme+"/"+req.Method, zipkin.Kind(model.Client), ) for k, v := range t.defaultTags { sp.Tag(k, v) } if t.httpTrace { sptr := spanTrace{ Span: sp, } sptr.c = &httptrace.ClientTrace{ GetConn: sptr.getConn, GotConn: sptr.gotConn, PutIdleConn: sptr.putIdleConn, GotFirstResponseByte: sptr.gotFirstResponseByte, Got100Continue: sptr.got100Continue, DNSStart: sptr.dnsStart, DNSDone: sptr.dnsDone, ConnectStart: sptr.connectStart, ConnectDone: sptr.connectDone, TLSHandshakeStart: sptr.tlsHandshakeStart, TLSHandshakeDone: sptr.tlsHandshakeDone, WroteHeaders: sptr.wroteHeaders, Wait100Continue: sptr.wait100Continue, WroteRequest: sptr.wroteRequest, } req = req.WithContext( httptrace.WithClientTrace(req.Context(), sptr.c), ) } zipkin.TagHTTPMethod.Set(sp, req.Method) zipkin.TagHTTPPath.Set(sp, req.URL.Path) _ = b3.InjectHTTP(req)(sp.Context()) res, err = t.rt.RoundTrip(req) if err != nil { t.errHandler(sp, err, 0) sp.Finish() return } if res.ContentLength > 0 { zipkin.TagHTTPResponseSize.Set(sp, strconv.FormatInt(res.ContentLength, 10)) } if res.StatusCode < 200 || res.StatusCode > 299 { statusCode := strconv.FormatInt(int64(res.StatusCode), 10) zipkin.TagHTTPStatusCode.Set(sp, statusCode) if res.StatusCode > 399 { t.errHandler(sp, nil, res.StatusCode) } } sp.Finish() return }
[ "func", "(", "t", "*", "transport", ")", "RoundTrip", "(", "req", "*", "http", ".", "Request", ")", "(", "res", "*", "http", ".", "Response", ",", "err", "error", ")", "{", "sp", ",", "_", ":=", "t", ".", "tracer", ".", "StartSpanFromContext", "(", "req", ".", "Context", "(", ")", ",", "req", ".", "URL", ".", "Scheme", "+", "\"", "\"", "+", "req", ".", "Method", ",", "zipkin", ".", "Kind", "(", "model", ".", "Client", ")", ",", ")", "\n\n", "for", "k", ",", "v", ":=", "range", "t", ".", "defaultTags", "{", "sp", ".", "Tag", "(", "k", ",", "v", ")", "\n", "}", "\n\n", "if", "t", ".", "httpTrace", "{", "sptr", ":=", "spanTrace", "{", "Span", ":", "sp", ",", "}", "\n", "sptr", ".", "c", "=", "&", "httptrace", ".", "ClientTrace", "{", "GetConn", ":", "sptr", ".", "getConn", ",", "GotConn", ":", "sptr", ".", "gotConn", ",", "PutIdleConn", ":", "sptr", ".", "putIdleConn", ",", "GotFirstResponseByte", ":", "sptr", ".", "gotFirstResponseByte", ",", "Got100Continue", ":", "sptr", ".", "got100Continue", ",", "DNSStart", ":", "sptr", ".", "dnsStart", ",", "DNSDone", ":", "sptr", ".", "dnsDone", ",", "ConnectStart", ":", "sptr", ".", "connectStart", ",", "ConnectDone", ":", "sptr", ".", "connectDone", ",", "TLSHandshakeStart", ":", "sptr", ".", "tlsHandshakeStart", ",", "TLSHandshakeDone", ":", "sptr", ".", "tlsHandshakeDone", ",", "WroteHeaders", ":", "sptr", ".", "wroteHeaders", ",", "Wait100Continue", ":", "sptr", ".", "wait100Continue", ",", "WroteRequest", ":", "sptr", ".", "wroteRequest", ",", "}", "\n\n", "req", "=", "req", ".", "WithContext", "(", "httptrace", ".", "WithClientTrace", "(", "req", ".", "Context", "(", ")", ",", "sptr", ".", "c", ")", ",", ")", "\n", "}", "\n\n", "zipkin", ".", "TagHTTPMethod", ".", "Set", "(", "sp", ",", "req", ".", "Method", ")", "\n", "zipkin", ".", "TagHTTPPath", ".", "Set", "(", "sp", ",", "req", ".", "URL", ".", "Path", ")", "\n\n", "_", "=", "b3", ".", "InjectHTTP", "(", "req", ")", "(", "sp", ".", "Context", "(", ")", ")", "\n\n", "res", ",", "err", "=", "t", ".", "rt", ".", "RoundTrip", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "t", ".", "errHandler", "(", "sp", ",", "err", ",", "0", ")", "\n", "sp", ".", "Finish", "(", ")", "\n", "return", "\n", "}", "\n\n", "if", "res", ".", "ContentLength", ">", "0", "{", "zipkin", ".", "TagHTTPResponseSize", ".", "Set", "(", "sp", ",", "strconv", ".", "FormatInt", "(", "res", ".", "ContentLength", ",", "10", ")", ")", "\n", "}", "\n", "if", "res", ".", "StatusCode", "<", "200", "||", "res", ".", "StatusCode", ">", "299", "{", "statusCode", ":=", "strconv", ".", "FormatInt", "(", "int64", "(", "res", ".", "StatusCode", ")", ",", "10", ")", "\n", "zipkin", ".", "TagHTTPStatusCode", ".", "Set", "(", "sp", ",", "statusCode", ")", "\n", "if", "res", ".", "StatusCode", ">", "399", "{", "t", ".", "errHandler", "(", "sp", ",", "nil", ",", "res", ".", "StatusCode", ")", "\n", "}", "\n", "}", "\n", "sp", ".", "Finish", "(", ")", "\n", "return", "\n", "}" ]
// RoundTrip satisfies the RoundTripper interface.
[ "RoundTrip", "satisfies", "the", "RoundTripper", "interface", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/middleware/http/transport.go#L105-L164
train
openzipkin/zipkin-go
propagation/b3/spancontext.go
ParseHeaders
func ParseHeaders( hdrTraceID, hdrSpanID, hdrParentSpanID, hdrSampled, hdrFlags string, ) (*model.SpanContext, error) { var ( err error spanID uint64 requiredCount int sc = &model.SpanContext{} ) // correct values for an existing sampled header are "0" and "1". // For legacy support and being lenient to other tracing implementations we // allow "true" and "false" as inputs for interop purposes. switch strings.ToLower(hdrSampled) { case "0", "false": sampled := false sc.Sampled = &sampled case "1", "true": sampled := true sc.Sampled = &sampled case "": // sc.Sampled = nil default: return nil, ErrInvalidSampledHeader } // The only accepted value for Flags is "1". This will set Debug to true. All // other values and omission of header will be ignored. if hdrFlags == "1" { sc.Debug = true sc.Sampled = nil } if hdrTraceID != "" { requiredCount++ if sc.TraceID, err = model.TraceIDFromHex(hdrTraceID); err != nil { return nil, ErrInvalidTraceIDHeader } } if hdrSpanID != "" { requiredCount++ if spanID, err = strconv.ParseUint(hdrSpanID, 16, 64); err != nil { return nil, ErrInvalidSpanIDHeader } sc.ID = model.ID(spanID) } if requiredCount != 0 && requiredCount != 2 { return nil, ErrInvalidScope } if hdrParentSpanID != "" { if requiredCount == 0 { return nil, ErrInvalidScopeParent } if spanID, err = strconv.ParseUint(hdrParentSpanID, 16, 64); err != nil { return nil, ErrInvalidParentSpanIDHeader } parentSpanID := model.ID(spanID) sc.ParentID = &parentSpanID } return sc, nil }
go
func ParseHeaders( hdrTraceID, hdrSpanID, hdrParentSpanID, hdrSampled, hdrFlags string, ) (*model.SpanContext, error) { var ( err error spanID uint64 requiredCount int sc = &model.SpanContext{} ) // correct values for an existing sampled header are "0" and "1". // For legacy support and being lenient to other tracing implementations we // allow "true" and "false" as inputs for interop purposes. switch strings.ToLower(hdrSampled) { case "0", "false": sampled := false sc.Sampled = &sampled case "1", "true": sampled := true sc.Sampled = &sampled case "": // sc.Sampled = nil default: return nil, ErrInvalidSampledHeader } // The only accepted value for Flags is "1". This will set Debug to true. All // other values and omission of header will be ignored. if hdrFlags == "1" { sc.Debug = true sc.Sampled = nil } if hdrTraceID != "" { requiredCount++ if sc.TraceID, err = model.TraceIDFromHex(hdrTraceID); err != nil { return nil, ErrInvalidTraceIDHeader } } if hdrSpanID != "" { requiredCount++ if spanID, err = strconv.ParseUint(hdrSpanID, 16, 64); err != nil { return nil, ErrInvalidSpanIDHeader } sc.ID = model.ID(spanID) } if requiredCount != 0 && requiredCount != 2 { return nil, ErrInvalidScope } if hdrParentSpanID != "" { if requiredCount == 0 { return nil, ErrInvalidScopeParent } if spanID, err = strconv.ParseUint(hdrParentSpanID, 16, 64); err != nil { return nil, ErrInvalidParentSpanIDHeader } parentSpanID := model.ID(spanID) sc.ParentID = &parentSpanID } return sc, nil }
[ "func", "ParseHeaders", "(", "hdrTraceID", ",", "hdrSpanID", ",", "hdrParentSpanID", ",", "hdrSampled", ",", "hdrFlags", "string", ",", ")", "(", "*", "model", ".", "SpanContext", ",", "error", ")", "{", "var", "(", "err", "error", "\n", "spanID", "uint64", "\n", "requiredCount", "int", "\n", "sc", "=", "&", "model", ".", "SpanContext", "{", "}", "\n", ")", "\n\n", "// correct values for an existing sampled header are \"0\" and \"1\".", "// For legacy support and being lenient to other tracing implementations we", "// allow \"true\" and \"false\" as inputs for interop purposes.", "switch", "strings", ".", "ToLower", "(", "hdrSampled", ")", "{", "case", "\"", "\"", ",", "\"", "\"", ":", "sampled", ":=", "false", "\n", "sc", ".", "Sampled", "=", "&", "sampled", "\n", "case", "\"", "\"", ",", "\"", "\"", ":", "sampled", ":=", "true", "\n", "sc", ".", "Sampled", "=", "&", "sampled", "\n", "case", "\"", "\"", ":", "// sc.Sampled = nil", "default", ":", "return", "nil", ",", "ErrInvalidSampledHeader", "\n", "}", "\n\n", "// The only accepted value for Flags is \"1\". This will set Debug to true. All", "// other values and omission of header will be ignored.", "if", "hdrFlags", "==", "\"", "\"", "{", "sc", ".", "Debug", "=", "true", "\n", "sc", ".", "Sampled", "=", "nil", "\n", "}", "\n\n", "if", "hdrTraceID", "!=", "\"", "\"", "{", "requiredCount", "++", "\n", "if", "sc", ".", "TraceID", ",", "err", "=", "model", ".", "TraceIDFromHex", "(", "hdrTraceID", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "ErrInvalidTraceIDHeader", "\n", "}", "\n", "}", "\n\n", "if", "hdrSpanID", "!=", "\"", "\"", "{", "requiredCount", "++", "\n", "if", "spanID", ",", "err", "=", "strconv", ".", "ParseUint", "(", "hdrSpanID", ",", "16", ",", "64", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "ErrInvalidSpanIDHeader", "\n", "}", "\n", "sc", ".", "ID", "=", "model", ".", "ID", "(", "spanID", ")", "\n", "}", "\n\n", "if", "requiredCount", "!=", "0", "&&", "requiredCount", "!=", "2", "{", "return", "nil", ",", "ErrInvalidScope", "\n", "}", "\n\n", "if", "hdrParentSpanID", "!=", "\"", "\"", "{", "if", "requiredCount", "==", "0", "{", "return", "nil", ",", "ErrInvalidScopeParent", "\n", "}", "\n", "if", "spanID", ",", "err", "=", "strconv", ".", "ParseUint", "(", "hdrParentSpanID", ",", "16", ",", "64", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "ErrInvalidParentSpanIDHeader", "\n", "}", "\n", "parentSpanID", ":=", "model", ".", "ID", "(", "spanID", ")", "\n", "sc", ".", "ParentID", "=", "&", "parentSpanID", "\n", "}", "\n\n", "return", "sc", ",", "nil", "\n", "}" ]
// ParseHeaders takes values found from B3 Headers and tries to reconstruct a // SpanContext.
[ "ParseHeaders", "takes", "values", "found", "from", "B3", "Headers", "and", "tries", "to", "reconstruct", "a", "SpanContext", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/propagation/b3/spancontext.go#L26-L90
train
openzipkin/zipkin-go
reporter/serializer.go
Serialize
func (JSONSerializer) Serialize(spans []*model.SpanModel) ([]byte, error) { return json.Marshal(spans) }
go
func (JSONSerializer) Serialize(spans []*model.SpanModel) ([]byte, error) { return json.Marshal(spans) }
[ "func", "(", "JSONSerializer", ")", "Serialize", "(", "spans", "[", "]", "*", "model", ".", "SpanModel", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "json", ".", "Marshal", "(", "spans", ")", "\n", "}" ]
// Serialize takes an array of Zipkin SpanModel objects and returns a JSON // encoding of it.
[ "Serialize", "takes", "an", "array", "of", "Zipkin", "SpanModel", "objects", "and", "returns", "a", "JSON", "encoding", "of", "it", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/reporter/serializer.go#L35-L37
train
openzipkin/zipkin-go
middleware/http/client.go
WithClient
func WithClient(client *http.Client) ClientOption { return func(c *Client) { if client == nil { client = &http.Client{} } c.Client = client } }
go
func WithClient(client *http.Client) ClientOption { return func(c *Client) { if client == nil { client = &http.Client{} } c.Client = client } }
[ "func", "WithClient", "(", "client", "*", "http", ".", "Client", ")", "ClientOption", "{", "return", "func", "(", "c", "*", "Client", ")", "{", "if", "client", "==", "nil", "{", "client", "=", "&", "http", ".", "Client", "{", "}", "\n", "}", "\n", "c", ".", "Client", "=", "client", "\n", "}", "\n", "}" ]
// WithClient allows one to add a custom configured http.Client to use.
[ "WithClient", "allows", "one", "to", "add", "a", "custom", "configured", "http", ".", "Client", "to", "use", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/middleware/http/client.go#L43-L50
train
openzipkin/zipkin-go
middleware/http/client.go
ClientTags
func ClientTags(tags map[string]string) ClientOption { return func(c *Client) { c.defaultTags = tags } }
go
func ClientTags(tags map[string]string) ClientOption { return func(c *Client) { c.defaultTags = tags } }
[ "func", "ClientTags", "(", "tags", "map", "[", "string", "]", "string", ")", "ClientOption", "{", "return", "func", "(", "c", "*", "Client", ")", "{", "c", ".", "defaultTags", "=", "tags", "\n", "}", "\n", "}" ]
// ClientTags adds default Tags to inject into client application spans.
[ "ClientTags", "adds", "default", "Tags", "to", "inject", "into", "client", "application", "spans", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/middleware/http/client.go#L60-L64
train
openzipkin/zipkin-go
middleware/http/client.go
NewClient
func NewClient(tracer *zipkin.Tracer, options ...ClientOption) (*Client, error) { if tracer == nil { return nil, ErrValidTracerRequired } c := &Client{tracer: tracer, Client: &http.Client{}} for _, option := range options { option(c) } c.transportOptions = append( c.transportOptions, // the following Client settings override provided transport settings. RoundTripper(c.Client.Transport), TransportTrace(c.httpTrace), ) transport, err := NewTransport(tracer, c.transportOptions...) if err != nil { return nil, err } c.Client.Transport = transport return c, nil }
go
func NewClient(tracer *zipkin.Tracer, options ...ClientOption) (*Client, error) { if tracer == nil { return nil, ErrValidTracerRequired } c := &Client{tracer: tracer, Client: &http.Client{}} for _, option := range options { option(c) } c.transportOptions = append( c.transportOptions, // the following Client settings override provided transport settings. RoundTripper(c.Client.Transport), TransportTrace(c.httpTrace), ) transport, err := NewTransport(tracer, c.transportOptions...) if err != nil { return nil, err } c.Client.Transport = transport return c, nil }
[ "func", "NewClient", "(", "tracer", "*", "zipkin", ".", "Tracer", ",", "options", "...", "ClientOption", ")", "(", "*", "Client", ",", "error", ")", "{", "if", "tracer", "==", "nil", "{", "return", "nil", ",", "ErrValidTracerRequired", "\n", "}", "\n\n", "c", ":=", "&", "Client", "{", "tracer", ":", "tracer", ",", "Client", ":", "&", "http", ".", "Client", "{", "}", "}", "\n", "for", "_", ",", "option", ":=", "range", "options", "{", "option", "(", "c", ")", "\n", "}", "\n\n", "c", ".", "transportOptions", "=", "append", "(", "c", ".", "transportOptions", ",", "// the following Client settings override provided transport settings.", "RoundTripper", "(", "c", ".", "Client", ".", "Transport", ")", ",", "TransportTrace", "(", "c", ".", "httpTrace", ")", ",", ")", "\n", "transport", ",", "err", ":=", "NewTransport", "(", "tracer", ",", "c", ".", "transportOptions", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "c", ".", "Client", ".", "Transport", "=", "transport", "\n\n", "return", "c", ",", "nil", "\n", "}" ]
// NewClient returns an HTTP Client adding Zipkin instrumentation around an // embedded standard Go http.Client.
[ "NewClient", "returns", "an", "HTTP", "Client", "adding", "Zipkin", "instrumentation", "around", "an", "embedded", "standard", "Go", "http", ".", "Client", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/middleware/http/client.go#L76-L99
train
openzipkin/zipkin-go
middleware/http/client.go
DoWithAppSpan
func (c *Client) DoWithAppSpan(req *http.Request, name string) (res *http.Response, err error) { var parentContext model.SpanContext if span := zipkin.SpanFromContext(req.Context()); span != nil { parentContext = span.Context() } appSpan := c.tracer.StartSpan(name, zipkin.Parent(parentContext)) zipkin.TagHTTPMethod.Set(appSpan, req.Method) zipkin.TagHTTPPath.Set(appSpan, req.URL.Path) res, err = c.Client.Do( req.WithContext(zipkin.NewContext(req.Context(), appSpan)), ) if err != nil { zipkin.TagError.Set(appSpan, err.Error()) appSpan.Finish() return } if c.httpTrace { appSpan.Annotate(time.Now(), "wr") } if res.ContentLength > 0 { zipkin.TagHTTPResponseSize.Set(appSpan, strconv.FormatInt(res.ContentLength, 10)) } if res.StatusCode < 200 || res.StatusCode > 299 { statusCode := strconv.FormatInt(int64(res.StatusCode), 10) zipkin.TagHTTPStatusCode.Set(appSpan, statusCode) if res.StatusCode > 399 { zipkin.TagError.Set(appSpan, statusCode) } } res.Body = &spanCloser{ ReadCloser: res.Body, sp: appSpan, traceEnabled: c.httpTrace, } return }
go
func (c *Client) DoWithAppSpan(req *http.Request, name string) (res *http.Response, err error) { var parentContext model.SpanContext if span := zipkin.SpanFromContext(req.Context()); span != nil { parentContext = span.Context() } appSpan := c.tracer.StartSpan(name, zipkin.Parent(parentContext)) zipkin.TagHTTPMethod.Set(appSpan, req.Method) zipkin.TagHTTPPath.Set(appSpan, req.URL.Path) res, err = c.Client.Do( req.WithContext(zipkin.NewContext(req.Context(), appSpan)), ) if err != nil { zipkin.TagError.Set(appSpan, err.Error()) appSpan.Finish() return } if c.httpTrace { appSpan.Annotate(time.Now(), "wr") } if res.ContentLength > 0 { zipkin.TagHTTPResponseSize.Set(appSpan, strconv.FormatInt(res.ContentLength, 10)) } if res.StatusCode < 200 || res.StatusCode > 299 { statusCode := strconv.FormatInt(int64(res.StatusCode), 10) zipkin.TagHTTPStatusCode.Set(appSpan, statusCode) if res.StatusCode > 399 { zipkin.TagError.Set(appSpan, statusCode) } } res.Body = &spanCloser{ ReadCloser: res.Body, sp: appSpan, traceEnabled: c.httpTrace, } return }
[ "func", "(", "c", "*", "Client", ")", "DoWithAppSpan", "(", "req", "*", "http", ".", "Request", ",", "name", "string", ")", "(", "res", "*", "http", ".", "Response", ",", "err", "error", ")", "{", "var", "parentContext", "model", ".", "SpanContext", "\n\n", "if", "span", ":=", "zipkin", ".", "SpanFromContext", "(", "req", ".", "Context", "(", ")", ")", ";", "span", "!=", "nil", "{", "parentContext", "=", "span", ".", "Context", "(", ")", "\n", "}", "\n\n", "appSpan", ":=", "c", ".", "tracer", ".", "StartSpan", "(", "name", ",", "zipkin", ".", "Parent", "(", "parentContext", ")", ")", "\n\n", "zipkin", ".", "TagHTTPMethod", ".", "Set", "(", "appSpan", ",", "req", ".", "Method", ")", "\n", "zipkin", ".", "TagHTTPPath", ".", "Set", "(", "appSpan", ",", "req", ".", "URL", ".", "Path", ")", "\n\n", "res", ",", "err", "=", "c", ".", "Client", ".", "Do", "(", "req", ".", "WithContext", "(", "zipkin", ".", "NewContext", "(", "req", ".", "Context", "(", ")", ",", "appSpan", ")", ")", ",", ")", "\n", "if", "err", "!=", "nil", "{", "zipkin", ".", "TagError", ".", "Set", "(", "appSpan", ",", "err", ".", "Error", "(", ")", ")", "\n", "appSpan", ".", "Finish", "(", ")", "\n", "return", "\n", "}", "\n\n", "if", "c", ".", "httpTrace", "{", "appSpan", ".", "Annotate", "(", "time", ".", "Now", "(", ")", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "res", ".", "ContentLength", ">", "0", "{", "zipkin", ".", "TagHTTPResponseSize", ".", "Set", "(", "appSpan", ",", "strconv", ".", "FormatInt", "(", "res", ".", "ContentLength", ",", "10", ")", ")", "\n", "}", "\n", "if", "res", ".", "StatusCode", "<", "200", "||", "res", ".", "StatusCode", ">", "299", "{", "statusCode", ":=", "strconv", ".", "FormatInt", "(", "int64", "(", "res", ".", "StatusCode", ")", ",", "10", ")", "\n", "zipkin", ".", "TagHTTPStatusCode", ".", "Set", "(", "appSpan", ",", "statusCode", ")", "\n", "if", "res", ".", "StatusCode", ">", "399", "{", "zipkin", ".", "TagError", ".", "Set", "(", "appSpan", ",", "statusCode", ")", "\n", "}", "\n", "}", "\n\n", "res", ".", "Body", "=", "&", "spanCloser", "{", "ReadCloser", ":", "res", ".", "Body", ",", "sp", ":", "appSpan", ",", "traceEnabled", ":", "c", ".", "httpTrace", ",", "}", "\n", "return", "\n", "}" ]
// DoWithAppSpan wraps http.Client's Do with tracing using an application span.
[ "DoWithAppSpan", "wraps", "http", ".", "Client", "s", "Do", "with", "tracing", "using", "an", "application", "span", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/middleware/http/client.go#L102-L144
train
openzipkin/zipkin-go
model/annotation.go
MarshalJSON
func (a *Annotation) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { Timestamp int64 `json:"timestamp"` Value string `json:"value"` }{ Timestamp: a.Timestamp.Round(time.Microsecond).UnixNano() / 1e3, Value: a.Value, }) }
go
func (a *Annotation) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { Timestamp int64 `json:"timestamp"` Value string `json:"value"` }{ Timestamp: a.Timestamp.Round(time.Microsecond).UnixNano() / 1e3, Value: a.Value, }) }
[ "func", "(", "a", "*", "Annotation", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "json", ".", "Marshal", "(", "&", "struct", "{", "Timestamp", "int64", "`json:\"timestamp\"`", "\n", "Value", "string", "`json:\"value\"`", "\n", "}", "{", "Timestamp", ":", "a", ".", "Timestamp", ".", "Round", "(", "time", ".", "Microsecond", ")", ".", "UnixNano", "(", ")", "/", "1e3", ",", "Value", ":", "a", ".", "Value", ",", "}", ")", "\n", "}" ]
// MarshalJSON implements custom JSON encoding
[ "MarshalJSON", "implements", "custom", "JSON", "encoding" ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/model/annotation.go#L33-L41
train
openzipkin/zipkin-go
model/annotation.go
UnmarshalJSON
func (a *Annotation) UnmarshalJSON(b []byte) error { type Alias Annotation annotation := &struct { TimeStamp uint64 `json:"timestamp"` *Alias }{ Alias: (*Alias)(a), } if err := json.Unmarshal(b, &annotation); err != nil { return err } if annotation.TimeStamp < 1 { return ErrValidTimestampRequired } a.Timestamp = time.Unix(0, int64(annotation.TimeStamp)*1e3) return nil }
go
func (a *Annotation) UnmarshalJSON(b []byte) error { type Alias Annotation annotation := &struct { TimeStamp uint64 `json:"timestamp"` *Alias }{ Alias: (*Alias)(a), } if err := json.Unmarshal(b, &annotation); err != nil { return err } if annotation.TimeStamp < 1 { return ErrValidTimestampRequired } a.Timestamp = time.Unix(0, int64(annotation.TimeStamp)*1e3) return nil }
[ "func", "(", "a", "*", "Annotation", ")", "UnmarshalJSON", "(", "b", "[", "]", "byte", ")", "error", "{", "type", "Alias", "Annotation", "\n", "annotation", ":=", "&", "struct", "{", "TimeStamp", "uint64", "`json:\"timestamp\"`", "\n", "*", "Alias", "\n", "}", "{", "Alias", ":", "(", "*", "Alias", ")", "(", "a", ")", ",", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "b", ",", "&", "annotation", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "annotation", ".", "TimeStamp", "<", "1", "{", "return", "ErrValidTimestampRequired", "\n", "}", "\n", "a", ".", "Timestamp", "=", "time", ".", "Unix", "(", "0", ",", "int64", "(", "annotation", ".", "TimeStamp", ")", "*", "1e3", ")", "\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON implements custom JSON decoding
[ "UnmarshalJSON", "implements", "custom", "JSON", "decoding" ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/model/annotation.go#L44-L60
train
openzipkin/zipkin-go
propagation/b3/http.go
ExtractHTTP
func ExtractHTTP(r *http.Request) propagation.Extractor { return func() (*model.SpanContext, error) { var ( traceIDHeader = r.Header.Get(TraceID) spanIDHeader = r.Header.Get(SpanID) parentSpanIDHeader = r.Header.Get(ParentSpanID) sampledHeader = r.Header.Get(Sampled) flagsHeader = r.Header.Get(Flags) ) return ParseHeaders( traceIDHeader, spanIDHeader, parentSpanIDHeader, sampledHeader, flagsHeader, ) } }
go
func ExtractHTTP(r *http.Request) propagation.Extractor { return func() (*model.SpanContext, error) { var ( traceIDHeader = r.Header.Get(TraceID) spanIDHeader = r.Header.Get(SpanID) parentSpanIDHeader = r.Header.Get(ParentSpanID) sampledHeader = r.Header.Get(Sampled) flagsHeader = r.Header.Get(Flags) ) return ParseHeaders( traceIDHeader, spanIDHeader, parentSpanIDHeader, sampledHeader, flagsHeader, ) } }
[ "func", "ExtractHTTP", "(", "r", "*", "http", ".", "Request", ")", "propagation", ".", "Extractor", "{", "return", "func", "(", ")", "(", "*", "model", ".", "SpanContext", ",", "error", ")", "{", "var", "(", "traceIDHeader", "=", "r", ".", "Header", ".", "Get", "(", "TraceID", ")", "\n", "spanIDHeader", "=", "r", ".", "Header", ".", "Get", "(", "SpanID", ")", "\n", "parentSpanIDHeader", "=", "r", ".", "Header", ".", "Get", "(", "ParentSpanID", ")", "\n", "sampledHeader", "=", "r", ".", "Header", ".", "Get", "(", "Sampled", ")", "\n", "flagsHeader", "=", "r", ".", "Header", ".", "Get", "(", "Flags", ")", "\n", ")", "\n\n", "return", "ParseHeaders", "(", "traceIDHeader", ",", "spanIDHeader", ",", "parentSpanIDHeader", ",", "sampledHeader", ",", "flagsHeader", ",", ")", "\n", "}", "\n", "}" ]
// ExtractHTTP will extract a span.Context from the HTTP Request if found in // B3 header format.
[ "ExtractHTTP", "will", "extract", "a", "span", ".", "Context", "from", "the", "HTTP", "Request", "if", "found", "in", "B3", "header", "format", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/propagation/b3/http.go#L26-L41
train
openzipkin/zipkin-go
propagation/b3/http.go
InjectHTTP
func InjectHTTP(r *http.Request) propagation.Injector { return func(sc model.SpanContext) error { if (model.SpanContext{}) == sc { return ErrEmptyContext } if sc.Debug { r.Header.Set(Flags, "1") } else if sc.Sampled != nil { // Debug is encoded as X-B3-Flags: 1. Since Debug implies Sampled, // so don't also send "X-B3-Sampled: 1". if *sc.Sampled { r.Header.Set(Sampled, "1") } else { r.Header.Set(Sampled, "0") } } if !sc.TraceID.Empty() && sc.ID > 0 { r.Header.Set(TraceID, sc.TraceID.String()) r.Header.Set(SpanID, sc.ID.String()) if sc.ParentID != nil { r.Header.Set(ParentSpanID, sc.ParentID.String()) } } return nil } }
go
func InjectHTTP(r *http.Request) propagation.Injector { return func(sc model.SpanContext) error { if (model.SpanContext{}) == sc { return ErrEmptyContext } if sc.Debug { r.Header.Set(Flags, "1") } else if sc.Sampled != nil { // Debug is encoded as X-B3-Flags: 1. Since Debug implies Sampled, // so don't also send "X-B3-Sampled: 1". if *sc.Sampled { r.Header.Set(Sampled, "1") } else { r.Header.Set(Sampled, "0") } } if !sc.TraceID.Empty() && sc.ID > 0 { r.Header.Set(TraceID, sc.TraceID.String()) r.Header.Set(SpanID, sc.ID.String()) if sc.ParentID != nil { r.Header.Set(ParentSpanID, sc.ParentID.String()) } } return nil } }
[ "func", "InjectHTTP", "(", "r", "*", "http", ".", "Request", ")", "propagation", ".", "Injector", "{", "return", "func", "(", "sc", "model", ".", "SpanContext", ")", "error", "{", "if", "(", "model", ".", "SpanContext", "{", "}", ")", "==", "sc", "{", "return", "ErrEmptyContext", "\n", "}", "\n\n", "if", "sc", ".", "Debug", "{", "r", ".", "Header", ".", "Set", "(", "Flags", ",", "\"", "\"", ")", "\n", "}", "else", "if", "sc", ".", "Sampled", "!=", "nil", "{", "// Debug is encoded as X-B3-Flags: 1. Since Debug implies Sampled,", "// so don't also send \"X-B3-Sampled: 1\".", "if", "*", "sc", ".", "Sampled", "{", "r", ".", "Header", ".", "Set", "(", "Sampled", ",", "\"", "\"", ")", "\n", "}", "else", "{", "r", ".", "Header", ".", "Set", "(", "Sampled", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "if", "!", "sc", ".", "TraceID", ".", "Empty", "(", ")", "&&", "sc", ".", "ID", ">", "0", "{", "r", ".", "Header", ".", "Set", "(", "TraceID", ",", "sc", ".", "TraceID", ".", "String", "(", ")", ")", "\n", "r", ".", "Header", ".", "Set", "(", "SpanID", ",", "sc", ".", "ID", ".", "String", "(", ")", ")", "\n", "if", "sc", ".", "ParentID", "!=", "nil", "{", "r", ".", "Header", ".", "Set", "(", "ParentSpanID", ",", "sc", ".", "ParentID", ".", "String", "(", ")", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}", "\n", "}" ]
// InjectHTTP will inject a span.Context into a HTTP Request
[ "InjectHTTP", "will", "inject", "a", "span", ".", "Context", "into", "a", "HTTP", "Request" ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/propagation/b3/http.go#L44-L72
train
mholt/archiver
rar.go
Unarchive
func (r *Rar) Unarchive(source, destination string) error { if !fileExists(destination) && r.MkdirAll { err := mkdir(destination, 0755) if err != nil { return fmt.Errorf("preparing destination: %v", err) } } // if the files in the archive do not all share a common // root, then make sure we extract to a single subfolder // rather than potentially littering the destination... if r.ImplicitTopLevelFolder { var err error destination, err = r.addTopLevelFolder(source, destination) if err != nil { return fmt.Errorf("scanning source archive: %v", err) } } err := r.OpenFile(source) if err != nil { return fmt.Errorf("opening rar archive for reading: %v", err) } defer r.Close() for { err := r.unrarNext(destination) if err == io.EOF { break } if err != nil { if r.ContinueOnError { log.Printf("[ERROR] Reading file in rar archive: %v", err) continue } return fmt.Errorf("reading file in rar archive: %v", err) } } return nil }
go
func (r *Rar) Unarchive(source, destination string) error { if !fileExists(destination) && r.MkdirAll { err := mkdir(destination, 0755) if err != nil { return fmt.Errorf("preparing destination: %v", err) } } // if the files in the archive do not all share a common // root, then make sure we extract to a single subfolder // rather than potentially littering the destination... if r.ImplicitTopLevelFolder { var err error destination, err = r.addTopLevelFolder(source, destination) if err != nil { return fmt.Errorf("scanning source archive: %v", err) } } err := r.OpenFile(source) if err != nil { return fmt.Errorf("opening rar archive for reading: %v", err) } defer r.Close() for { err := r.unrarNext(destination) if err == io.EOF { break } if err != nil { if r.ContinueOnError { log.Printf("[ERROR] Reading file in rar archive: %v", err) continue } return fmt.Errorf("reading file in rar archive: %v", err) } } return nil }
[ "func", "(", "r", "*", "Rar", ")", "Unarchive", "(", "source", ",", "destination", "string", ")", "error", "{", "if", "!", "fileExists", "(", "destination", ")", "&&", "r", ".", "MkdirAll", "{", "err", ":=", "mkdir", "(", "destination", ",", "0755", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "// if the files in the archive do not all share a common", "// root, then make sure we extract to a single subfolder", "// rather than potentially littering the destination...", "if", "r", ".", "ImplicitTopLevelFolder", "{", "var", "err", "error", "\n", "destination", ",", "err", "=", "r", ".", "addTopLevelFolder", "(", "source", ",", "destination", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "err", ":=", "r", ".", "OpenFile", "(", "source", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "defer", "r", ".", "Close", "(", ")", "\n\n", "for", "{", "err", ":=", "r", ".", "unrarNext", "(", "destination", ")", "\n", "if", "err", "==", "io", ".", "EOF", "{", "break", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "if", "r", ".", "ContinueOnError", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Unarchive unpacks the .rar file at source to destination. // Destination will be treated as a folder name. It supports // multi-volume archives.
[ "Unarchive", "unpacks", "the", ".", "rar", "file", "at", "source", "to", "destination", ".", "Destination", "will", "be", "treated", "as", "a", "folder", "name", ".", "It", "supports", "multi", "-", "volume", "archives", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/rar.go#L66-L106
train
mholt/archiver
rar.go
Extract
func (r *Rar) Extract(source, target, destination string) error { // target refers to a path inside the archive, which should be clean also target = path.Clean(target) // if the target ends up being a directory, then // we will continue walking and extracting files // until we are no longer within that directory var targetDirPath string return r.Walk(source, func(f File) error { th, ok := f.Header.(*rardecode.FileHeader) if !ok { return fmt.Errorf("expected header to be *rardecode.FileHeader but was %T", f.Header) } // importantly, cleaning the path strips tailing slash, // which must be appended to folders within the archive name := path.Clean(th.Name) if f.IsDir() && target == name { targetDirPath = path.Dir(name) } if within(target, th.Name) { // either this is the exact file we want, or is // in the directory we want to extract // build the filename we will extract to end, err := filepath.Rel(targetDirPath, th.Name) if err != nil { return fmt.Errorf("relativizing paths: %v", err) } joined := filepath.Join(destination, end) err = r.unrarFile(f, joined) if err != nil { return fmt.Errorf("extracting file %s: %v", th.Name, err) } // if our target was not a directory, stop walk if targetDirPath == "" { return ErrStopWalk } } else if targetDirPath != "" { // finished walking the entire directory return ErrStopWalk } return nil }) }
go
func (r *Rar) Extract(source, target, destination string) error { // target refers to a path inside the archive, which should be clean also target = path.Clean(target) // if the target ends up being a directory, then // we will continue walking and extracting files // until we are no longer within that directory var targetDirPath string return r.Walk(source, func(f File) error { th, ok := f.Header.(*rardecode.FileHeader) if !ok { return fmt.Errorf("expected header to be *rardecode.FileHeader but was %T", f.Header) } // importantly, cleaning the path strips tailing slash, // which must be appended to folders within the archive name := path.Clean(th.Name) if f.IsDir() && target == name { targetDirPath = path.Dir(name) } if within(target, th.Name) { // either this is the exact file we want, or is // in the directory we want to extract // build the filename we will extract to end, err := filepath.Rel(targetDirPath, th.Name) if err != nil { return fmt.Errorf("relativizing paths: %v", err) } joined := filepath.Join(destination, end) err = r.unrarFile(f, joined) if err != nil { return fmt.Errorf("extracting file %s: %v", th.Name, err) } // if our target was not a directory, stop walk if targetDirPath == "" { return ErrStopWalk } } else if targetDirPath != "" { // finished walking the entire directory return ErrStopWalk } return nil }) }
[ "func", "(", "r", "*", "Rar", ")", "Extract", "(", "source", ",", "target", ",", "destination", "string", ")", "error", "{", "// target refers to a path inside the archive, which should be clean also", "target", "=", "path", ".", "Clean", "(", "target", ")", "\n\n", "// if the target ends up being a directory, then", "// we will continue walking and extracting files", "// until we are no longer within that directory", "var", "targetDirPath", "string", "\n\n", "return", "r", ".", "Walk", "(", "source", ",", "func", "(", "f", "File", ")", "error", "{", "th", ",", "ok", ":=", "f", ".", "Header", ".", "(", "*", "rardecode", ".", "FileHeader", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "f", ".", "Header", ")", "\n", "}", "\n\n", "// importantly, cleaning the path strips tailing slash,", "// which must be appended to folders within the archive", "name", ":=", "path", ".", "Clean", "(", "th", ".", "Name", ")", "\n", "if", "f", ".", "IsDir", "(", ")", "&&", "target", "==", "name", "{", "targetDirPath", "=", "path", ".", "Dir", "(", "name", ")", "\n", "}", "\n\n", "if", "within", "(", "target", ",", "th", ".", "Name", ")", "{", "// either this is the exact file we want, or is", "// in the directory we want to extract", "// build the filename we will extract to", "end", ",", "err", ":=", "filepath", ".", "Rel", "(", "targetDirPath", ",", "th", ".", "Name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "joined", ":=", "filepath", ".", "Join", "(", "destination", ",", "end", ")", "\n\n", "err", "=", "r", ".", "unrarFile", "(", "f", ",", "joined", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "th", ".", "Name", ",", "err", ")", "\n", "}", "\n\n", "// if our target was not a directory, stop walk", "if", "targetDirPath", "==", "\"", "\"", "{", "return", "ErrStopWalk", "\n", "}", "\n", "}", "else", "if", "targetDirPath", "!=", "\"", "\"", "{", "// finished walking the entire directory", "return", "ErrStopWalk", "\n", "}", "\n\n", "return", "nil", "\n", "}", ")", "\n", "}" ]
// Extract extracts a single file from the rar archive. // If the target is a directory, the entire folder will // be extracted into destination.
[ "Extract", "extracts", "a", "single", "file", "from", "the", "rar", "archive", ".", "If", "the", "target", "is", "a", "directory", "the", "entire", "folder", "will", "be", "extracted", "into", "destination", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/rar.go#L304-L353
train
mholt/archiver
tarxz.go
Archive
func (txz *TarXz) Archive(sources []string, destination string) error { err := txz.CheckExt(destination) if err != nil { return fmt.Errorf("output %s", err.Error()) } txz.wrapWriter() return txz.Tar.Archive(sources, destination) }
go
func (txz *TarXz) Archive(sources []string, destination string) error { err := txz.CheckExt(destination) if err != nil { return fmt.Errorf("output %s", err.Error()) } txz.wrapWriter() return txz.Tar.Archive(sources, destination) }
[ "func", "(", "txz", "*", "TarXz", ")", "Archive", "(", "sources", "[", "]", "string", ",", "destination", "string", ")", "error", "{", "err", ":=", "txz", ".", "CheckExt", "(", "destination", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "txz", ".", "wrapWriter", "(", ")", "\n", "return", "txz", ".", "Tar", ".", "Archive", "(", "sources", ",", "destination", ")", "\n", "}" ]
// Archive creates a compressed tar file at destination // containing the files listed in sources. The destination // must end with ".tar.xz" or ".txz". File paths can be // those of regular files or directories; directories will // be recursively added.
[ "Archive", "creates", "a", "compressed", "tar", "file", "at", "destination", "containing", "the", "files", "listed", "in", "sources", ".", "The", "destination", "must", "end", "with", ".", "tar", ".", "xz", "or", ".", "txz", ".", "File", "paths", "can", "be", "those", "of", "regular", "files", "or", "directories", ";", "directories", "will", "be", "recursively", "added", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/tarxz.go#L33-L40
train
mholt/archiver
tar.go
Archive
func (t *Tar) Archive(sources []string, destination string) error { err := t.CheckExt(destination) if t.writerWrapFn == nil && err != nil { return fmt.Errorf("checking extension: %v", err) } if !t.OverwriteExisting && fileExists(destination) { return fmt.Errorf("file already exists: %s", destination) } // make the folder to contain the resulting archive // if it does not already exist destDir := filepath.Dir(destination) if t.MkdirAll && !fileExists(destDir) { err := mkdir(destDir, 0755) if err != nil { return fmt.Errorf("making folder for destination: %v", err) } } out, err := os.Create(destination) if err != nil { return fmt.Errorf("creating %s: %v", destination, err) } defer out.Close() err = t.Create(out) if err != nil { return fmt.Errorf("creating tar: %v", err) } defer t.Close() var topLevelFolder string if t.ImplicitTopLevelFolder && multipleTopLevels(sources) { topLevelFolder = folderNameFromFileName(destination) } for _, source := range sources { err := t.writeWalk(source, topLevelFolder, destination) if err != nil { return fmt.Errorf("walking %s: %v", source, err) } } return nil }
go
func (t *Tar) Archive(sources []string, destination string) error { err := t.CheckExt(destination) if t.writerWrapFn == nil && err != nil { return fmt.Errorf("checking extension: %v", err) } if !t.OverwriteExisting && fileExists(destination) { return fmt.Errorf("file already exists: %s", destination) } // make the folder to contain the resulting archive // if it does not already exist destDir := filepath.Dir(destination) if t.MkdirAll && !fileExists(destDir) { err := mkdir(destDir, 0755) if err != nil { return fmt.Errorf("making folder for destination: %v", err) } } out, err := os.Create(destination) if err != nil { return fmt.Errorf("creating %s: %v", destination, err) } defer out.Close() err = t.Create(out) if err != nil { return fmt.Errorf("creating tar: %v", err) } defer t.Close() var topLevelFolder string if t.ImplicitTopLevelFolder && multipleTopLevels(sources) { topLevelFolder = folderNameFromFileName(destination) } for _, source := range sources { err := t.writeWalk(source, topLevelFolder, destination) if err != nil { return fmt.Errorf("walking %s: %v", source, err) } } return nil }
[ "func", "(", "t", "*", "Tar", ")", "Archive", "(", "sources", "[", "]", "string", ",", "destination", "string", ")", "error", "{", "err", ":=", "t", ".", "CheckExt", "(", "destination", ")", "\n", "if", "t", ".", "writerWrapFn", "==", "nil", "&&", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "!", "t", ".", "OverwriteExisting", "&&", "fileExists", "(", "destination", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "destination", ")", "\n", "}", "\n\n", "// make the folder to contain the resulting archive", "// if it does not already exist", "destDir", ":=", "filepath", ".", "Dir", "(", "destination", ")", "\n", "if", "t", ".", "MkdirAll", "&&", "!", "fileExists", "(", "destDir", ")", "{", "err", ":=", "mkdir", "(", "destDir", ",", "0755", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "out", ",", "err", ":=", "os", ".", "Create", "(", "destination", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "destination", ",", "err", ")", "\n", "}", "\n", "defer", "out", ".", "Close", "(", ")", "\n\n", "err", "=", "t", ".", "Create", "(", "out", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "defer", "t", ".", "Close", "(", ")", "\n\n", "var", "topLevelFolder", "string", "\n", "if", "t", ".", "ImplicitTopLevelFolder", "&&", "multipleTopLevels", "(", "sources", ")", "{", "topLevelFolder", "=", "folderNameFromFileName", "(", "destination", ")", "\n", "}", "\n\n", "for", "_", ",", "source", ":=", "range", "sources", "{", "err", ":=", "t", ".", "writeWalk", "(", "source", ",", "topLevelFolder", ",", "destination", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "source", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Archive creates a tarball file at destination containing // the files listed in sources. The destination must end with // ".tar". File paths can be those of regular files or // directories; directories will be recursively added.
[ "Archive", "creates", "a", "tarball", "file", "at", "destination", "containing", "the", "files", "listed", "in", "sources", ".", "The", "destination", "must", "end", "with", ".", "tar", ".", "File", "paths", "can", "be", "those", "of", "regular", "files", "or", "directories", ";", "directories", "will", "be", "recursively", "added", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/tar.go#L68-L112
train
mholt/archiver
tar.go
Unarchive
func (t *Tar) Unarchive(source, destination string) error { if !fileExists(destination) && t.MkdirAll { err := mkdir(destination, 0755) if err != nil { return fmt.Errorf("preparing destination: %v", err) } } // if the files in the archive do not all share a common // root, then make sure we extract to a single subfolder // rather than potentially littering the destination... if t.ImplicitTopLevelFolder { var err error destination, err = t.addTopLevelFolder(source, destination) if err != nil { return fmt.Errorf("scanning source archive: %v", err) } } file, err := os.Open(source) if err != nil { return fmt.Errorf("opening source archive: %v", err) } defer file.Close() err = t.Open(file, 0) if err != nil { return fmt.Errorf("opening tar archive for reading: %v", err) } defer t.Close() for { err := t.untarNext(destination) if err == io.EOF { break } if err != nil { if t.ContinueOnError { log.Printf("[ERROR] Reading file in tar archive: %v", err) continue } return fmt.Errorf("reading file in tar archive: %v", err) } } return nil }
go
func (t *Tar) Unarchive(source, destination string) error { if !fileExists(destination) && t.MkdirAll { err := mkdir(destination, 0755) if err != nil { return fmt.Errorf("preparing destination: %v", err) } } // if the files in the archive do not all share a common // root, then make sure we extract to a single subfolder // rather than potentially littering the destination... if t.ImplicitTopLevelFolder { var err error destination, err = t.addTopLevelFolder(source, destination) if err != nil { return fmt.Errorf("scanning source archive: %v", err) } } file, err := os.Open(source) if err != nil { return fmt.Errorf("opening source archive: %v", err) } defer file.Close() err = t.Open(file, 0) if err != nil { return fmt.Errorf("opening tar archive for reading: %v", err) } defer t.Close() for { err := t.untarNext(destination) if err == io.EOF { break } if err != nil { if t.ContinueOnError { log.Printf("[ERROR] Reading file in tar archive: %v", err) continue } return fmt.Errorf("reading file in tar archive: %v", err) } } return nil }
[ "func", "(", "t", "*", "Tar", ")", "Unarchive", "(", "source", ",", "destination", "string", ")", "error", "{", "if", "!", "fileExists", "(", "destination", ")", "&&", "t", ".", "MkdirAll", "{", "err", ":=", "mkdir", "(", "destination", ",", "0755", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "// if the files in the archive do not all share a common", "// root, then make sure we extract to a single subfolder", "// rather than potentially littering the destination...", "if", "t", ".", "ImplicitTopLevelFolder", "{", "var", "err", "error", "\n", "destination", ",", "err", "=", "t", ".", "addTopLevelFolder", "(", "source", ",", "destination", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "file", ",", "err", ":=", "os", ".", "Open", "(", "source", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "defer", "file", ".", "Close", "(", ")", "\n\n", "err", "=", "t", ".", "Open", "(", "file", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "defer", "t", ".", "Close", "(", ")", "\n\n", "for", "{", "err", ":=", "t", ".", "untarNext", "(", "destination", ")", "\n", "if", "err", "==", "io", ".", "EOF", "{", "break", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "if", "t", ".", "ContinueOnError", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Unarchive unpacks the .tar file at source to destination. // Destination will be treated as a folder name.
[ "Unarchive", "unpacks", "the", ".", "tar", "file", "at", "source", "to", "destination", ".", "Destination", "will", "be", "treated", "as", "a", "folder", "name", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/tar.go#L116-L162
train
mholt/archiver
tar.go
Create
func (t *Tar) Create(out io.Writer) error { if t.tw != nil { return fmt.Errorf("tar archive is already created for writing") } // wrapping writers allows us to output // compressed tarballs, for example if t.writerWrapFn != nil { var err error out, err = t.writerWrapFn(out) if err != nil { return fmt.Errorf("wrapping writer: %v", err) } } t.tw = tar.NewWriter(out) return nil }
go
func (t *Tar) Create(out io.Writer) error { if t.tw != nil { return fmt.Errorf("tar archive is already created for writing") } // wrapping writers allows us to output // compressed tarballs, for example if t.writerWrapFn != nil { var err error out, err = t.writerWrapFn(out) if err != nil { return fmt.Errorf("wrapping writer: %v", err) } } t.tw = tar.NewWriter(out) return nil }
[ "func", "(", "t", "*", "Tar", ")", "Create", "(", "out", "io", ".", "Writer", ")", "error", "{", "if", "t", ".", "tw", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// wrapping writers allows us to output", "// compressed tarballs, for example", "if", "t", ".", "writerWrapFn", "!=", "nil", "{", "var", "err", "error", "\n", "out", ",", "err", "=", "t", ".", "writerWrapFn", "(", "out", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "t", ".", "tw", "=", "tar", ".", "NewWriter", "(", "out", ")", "\n", "return", "nil", "\n", "}" ]
// Create opens t for writing a tar archive to out.
[ "Create", "opens", "t", "for", "writing", "a", "tar", "archive", "to", "out", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/tar.go#L312-L329
train
mholt/archiver
tar.go
Write
func (t *Tar) Write(f File) error { if t.tw == nil { return fmt.Errorf("tar archive was not created for writing first") } if f.FileInfo == nil { return fmt.Errorf("no file info") } if f.FileInfo.Name() == "" { return fmt.Errorf("missing file name") } var linkTarget string if isSymlink(f) { var err error linkTarget, err = os.Readlink(f.Name()) if err != nil { return fmt.Errorf("%s: readlink: %v", f.Name(), err) } } hdr, err := tar.FileInfoHeader(f, filepath.ToSlash(linkTarget)) if err != nil { return fmt.Errorf("%s: making header: %v", f.Name(), err) } err = t.tw.WriteHeader(hdr) if err != nil { return fmt.Errorf("%s: writing header: %v", hdr.Name, err) } if f.IsDir() { return nil // directories have no contents } if hdr.Typeflag == tar.TypeReg { if f.ReadCloser == nil { return fmt.Errorf("%s: no way to read file contents", f.Name()) } _, err := io.Copy(t.tw, f) if err != nil { return fmt.Errorf("%s: copying contents: %v", f.Name(), err) } } return nil }
go
func (t *Tar) Write(f File) error { if t.tw == nil { return fmt.Errorf("tar archive was not created for writing first") } if f.FileInfo == nil { return fmt.Errorf("no file info") } if f.FileInfo.Name() == "" { return fmt.Errorf("missing file name") } var linkTarget string if isSymlink(f) { var err error linkTarget, err = os.Readlink(f.Name()) if err != nil { return fmt.Errorf("%s: readlink: %v", f.Name(), err) } } hdr, err := tar.FileInfoHeader(f, filepath.ToSlash(linkTarget)) if err != nil { return fmt.Errorf("%s: making header: %v", f.Name(), err) } err = t.tw.WriteHeader(hdr) if err != nil { return fmt.Errorf("%s: writing header: %v", hdr.Name, err) } if f.IsDir() { return nil // directories have no contents } if hdr.Typeflag == tar.TypeReg { if f.ReadCloser == nil { return fmt.Errorf("%s: no way to read file contents", f.Name()) } _, err := io.Copy(t.tw, f) if err != nil { return fmt.Errorf("%s: copying contents: %v", f.Name(), err) } } return nil }
[ "func", "(", "t", "*", "Tar", ")", "Write", "(", "f", "File", ")", "error", "{", "if", "t", ".", "tw", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "f", ".", "FileInfo", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "f", ".", "FileInfo", ".", "Name", "(", ")", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var", "linkTarget", "string", "\n", "if", "isSymlink", "(", "f", ")", "{", "var", "err", "error", "\n", "linkTarget", ",", "err", "=", "os", ".", "Readlink", "(", "f", ".", "Name", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "f", ".", "Name", "(", ")", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "hdr", ",", "err", ":=", "tar", ".", "FileInfoHeader", "(", "f", ",", "filepath", ".", "ToSlash", "(", "linkTarget", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "f", ".", "Name", "(", ")", ",", "err", ")", "\n", "}", "\n\n", "err", "=", "t", ".", "tw", ".", "WriteHeader", "(", "hdr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hdr", ".", "Name", ",", "err", ")", "\n", "}", "\n\n", "if", "f", ".", "IsDir", "(", ")", "{", "return", "nil", "// directories have no contents", "\n", "}", "\n\n", "if", "hdr", ".", "Typeflag", "==", "tar", ".", "TypeReg", "{", "if", "f", ".", "ReadCloser", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "f", ".", "Name", "(", ")", ")", "\n", "}", "\n", "_", ",", "err", ":=", "io", ".", "Copy", "(", "t", ".", "tw", ",", "f", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "f", ".", "Name", "(", ")", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Write writes f to t, which must have been opened for writing first.
[ "Write", "writes", "f", "to", "t", "which", "must", "have", "been", "opened", "for", "writing", "first", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/tar.go#L332-L377
train