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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
k0kubun/pp | pp.go | Print | func Print(a ...interface{}) (n int, err error) {
return fmt.Fprint(out, formatAll(a)...)
} | go | func Print(a ...interface{}) (n int, err error) {
return fmt.Fprint(out, formatAll(a)...)
} | [
"func",
"Print",
"(",
"a",
"...",
"interface",
"{",
"}",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"return",
"fmt",
".",
"Fprint",
"(",
"out",
",",
"formatAll",
"(",
"a",
")",
"...",
")",
"\n",
"}"
] | // Print prints given arguments. | [
"Print",
"prints",
"given",
"arguments",
"."
] | ea9763a91366a414dccd02c8019a6dafe54829db | https://github.com/k0kubun/pp/blob/ea9763a91366a414dccd02c8019a6dafe54829db/pp.go#L32-L34 | train |
k0kubun/pp | pp.go | Printf | func Printf(format string, a ...interface{}) (n int, err error) {
return fmt.Fprintf(out, format, formatAll(a)...)
} | go | func Printf(format string, a ...interface{}) (n int, err error) {
return fmt.Fprintf(out, format, formatAll(a)...)
} | [
"func",
"Printf",
"(",
"format",
"string",
",",
"a",
"...",
"interface",
"{",
"}",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"return",
"fmt",
".",
"Fprintf",
"(",
"out",
",",
"format",
",",
"formatAll",
"(",
"a",
")",
"...",
")",
"\n",... | // Printf prints a given format. | [
"Printf",
"prints",
"a",
"given",
"format",
"."
] | ea9763a91366a414dccd02c8019a6dafe54829db | https://github.com/k0kubun/pp/blob/ea9763a91366a414dccd02c8019a6dafe54829db/pp.go#L37-L39 | train |
k0kubun/pp | pp.go | Println | func Println(a ...interface{}) (n int, err error) {
return fmt.Fprintln(out, formatAll(a)...)
} | go | func Println(a ...interface{}) (n int, err error) {
return fmt.Fprintln(out, formatAll(a)...)
} | [
"func",
"Println",
"(",
"a",
"...",
"interface",
"{",
"}",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"return",
"fmt",
".",
"Fprintln",
"(",
"out",
",",
"formatAll",
"(",
"a",
")",
"...",
")",
"\n",
"}"
] | // Println prints given arguments with newline. | [
"Println",
"prints",
"given",
"arguments",
"with",
"newline",
"."
] | ea9763a91366a414dccd02c8019a6dafe54829db | https://github.com/k0kubun/pp/blob/ea9763a91366a414dccd02c8019a6dafe54829db/pp.go#L42-L44 | train |
k0kubun/pp | pp.go | Sprintf | func Sprintf(format string, a ...interface{}) string {
return fmt.Sprintf(format, formatAll(a)...)
} | go | func Sprintf(format string, a ...interface{}) string {
return fmt.Sprintf(format, formatAll(a)...)
} | [
"func",
"Sprintf",
"(",
"format",
"string",
",",
"a",
"...",
"interface",
"{",
"}",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"format",
",",
"formatAll",
"(",
"a",
")",
"...",
")",
"\n",
"}"
] | // Sprintf formats with pretty print and returns the result as string. | [
"Sprintf",
"formats",
"with",
"pretty",
"print",
"and",
"returns",
"the",
"result",
"as",
"string",
"."
] | ea9763a91366a414dccd02c8019a6dafe54829db | https://github.com/k0kubun/pp/blob/ea9763a91366a414dccd02c8019a6dafe54829db/pp.go#L52-L54 | train |
k0kubun/pp | pp.go | Fprint | func Fprint(w io.Writer, a ...interface{}) (n int, err error) {
return fmt.Fprint(w, formatAll(a)...)
} | go | func Fprint(w io.Writer, a ...interface{}) (n int, err error) {
return fmt.Fprint(w, formatAll(a)...)
} | [
"func",
"Fprint",
"(",
"w",
"io",
".",
"Writer",
",",
"a",
"...",
"interface",
"{",
"}",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"return",
"fmt",
".",
"Fprint",
"(",
"w",
",",
"formatAll",
"(",
"a",
")",
"...",
")",
"\n",
"}"
] | // Fprint prints given arguments to a given writer. | [
"Fprint",
"prints",
"given",
"arguments",
"to",
"a",
"given",
"writer",
"."
] | ea9763a91366a414dccd02c8019a6dafe54829db | https://github.com/k0kubun/pp/blob/ea9763a91366a414dccd02c8019a6dafe54829db/pp.go#L62-L64 | train |
k0kubun/pp | pp.go | Fatalf | func Fatalf(format string, a ...interface{}) {
fmt.Fprintf(out, format, formatAll(a)...)
os.Exit(1)
} | go | func Fatalf(format string, a ...interface{}) {
fmt.Fprintf(out, format, formatAll(a)...)
os.Exit(1)
} | [
"func",
"Fatalf",
"(",
"format",
"string",
",",
"a",
"...",
"interface",
"{",
"}",
")",
"{",
"fmt",
".",
"Fprintf",
"(",
"out",
",",
"format",
",",
"formatAll",
"(",
"a",
")",
"...",
")",
"\n",
"os",
".",
"Exit",
"(",
"1",
")",
"\n",
"}"
] | // Fatalf prints a given format and finishes execution with exit status 1. | [
"Fatalf",
"prints",
"a",
"given",
"format",
"and",
"finishes",
"execution",
"with",
"exit",
"status",
"1",
"."
] | ea9763a91366a414dccd02c8019a6dafe54829db | https://github.com/k0kubun/pp/blob/ea9763a91366a414dccd02c8019a6dafe54829db/pp.go#L88-L91 | train |
alecthomas/log4go | wrapper.go | Crashf | func Crashf(format string, args ...interface{}) {
Global.intLogf(CRITICAL, format, args...)
Global.Close() // so that hopefully the messages get logged
panic(fmt.Sprintf(format, args...))
} | go | func Crashf(format string, args ...interface{}) {
Global.intLogf(CRITICAL, format, args...)
Global.Close() // so that hopefully the messages get logged
panic(fmt.Sprintf(format, args...))
} | [
"func",
"Crashf",
"(",
"format",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"Global",
".",
"intLogf",
"(",
"CRITICAL",
",",
"format",
",",
"args",
"...",
")",
"\n",
"Global",
".",
"Close",
"(",
")",
"// so that hopefully the messages ge... | // Logs the given message and crashes the program | [
"Logs",
"the",
"given",
"message",
"and",
"crashes",
"the",
"program"
] | d146e6b86faab5f7e4d135cc63b749d74bf0d4a6 | https://github.com/alecthomas/log4go/blob/d146e6b86faab5f7e4d135cc63b749d74bf0d4a6/wrapper.go#L43-L47 | train |
alecthomas/log4go | log4go.go | Warn | func (log Logger) Warn(arg0 interface{}, args ...interface{}) error {
const (
lvl = WARNING
)
var msg string
switch first := arg0.(type) {
case string:
// Use the string as a format string
msg = fmt.Sprintf(first, args...)
case func() string:
// Log the closure (no other arguments used)
msg = first()
default:
// Build a format string so that it will be similar to Sprint
msg = fmt.Sprintf(fmt.Sprint(first)+strings.Repeat(" %v", len(args)), args...)
}
log.intLogf(lvl, msg)
return errors.New(msg)
} | go | func (log Logger) Warn(arg0 interface{}, args ...interface{}) error {
const (
lvl = WARNING
)
var msg string
switch first := arg0.(type) {
case string:
// Use the string as a format string
msg = fmt.Sprintf(first, args...)
case func() string:
// Log the closure (no other arguments used)
msg = first()
default:
// Build a format string so that it will be similar to Sprint
msg = fmt.Sprintf(fmt.Sprint(first)+strings.Repeat(" %v", len(args)), args...)
}
log.intLogf(lvl, msg)
return errors.New(msg)
} | [
"func",
"(",
"log",
"Logger",
")",
"Warn",
"(",
"arg0",
"interface",
"{",
"}",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"const",
"(",
"lvl",
"=",
"WARNING",
"\n",
")",
"\n",
"var",
"msg",
"string",
"\n",
"switch",
"first",
":="... | // Warn logs a message at the warning log level and returns the formatted error.
// At the warning level and higher, there is no performance benefit if the
// message is not actually logged, because all formats are processed and all
// closures are executed to format the error message.
// See Debug for further explanation of the arguments. | [
"Warn",
"logs",
"a",
"message",
"at",
"the",
"warning",
"log",
"level",
"and",
"returns",
"the",
"formatted",
"error",
".",
"At",
"the",
"warning",
"level",
"and",
"higher",
"there",
"is",
"no",
"performance",
"benefit",
"if",
"the",
"message",
"is",
"not"... | d146e6b86faab5f7e4d135cc63b749d74bf0d4a6 | https://github.com/alecthomas/log4go/blob/d146e6b86faab5f7e4d135cc63b749d74bf0d4a6/log4go.go#L420-L438 | train |
alecthomas/log4go | filelog.go | SetRotateMaxBackup | func (w *FileLogWriter) SetRotateMaxBackup(maxbackup int) *FileLogWriter {
w.maxbackup = maxbackup
return w
} | go | func (w *FileLogWriter) SetRotateMaxBackup(maxbackup int) *FileLogWriter {
w.maxbackup = maxbackup
return w
} | [
"func",
"(",
"w",
"*",
"FileLogWriter",
")",
"SetRotateMaxBackup",
"(",
"maxbackup",
"int",
")",
"*",
"FileLogWriter",
"{",
"w",
".",
"maxbackup",
"=",
"maxbackup",
"\n",
"return",
"w",
"\n",
"}"
] | // Set max backup files. Must be called before the first log message
// is written. | [
"Set",
"max",
"backup",
"files",
".",
"Must",
"be",
"called",
"before",
"the",
"first",
"log",
"message",
"is",
"written",
"."
] | d146e6b86faab5f7e4d135cc63b749d74bf0d4a6 | https://github.com/alecthomas/log4go/blob/d146e6b86faab5f7e4d135cc63b749d74bf0d4a6/filelog.go#L240-L243 | train |
alecthomas/log4go | pattlog.go | NewFormatLogWriter | func NewFormatLogWriter(out io.Writer, format string) FormatLogWriter {
records := make(FormatLogWriter, LogBufferLength)
go records.run(out, format)
return records
} | go | func NewFormatLogWriter(out io.Writer, format string) FormatLogWriter {
records := make(FormatLogWriter, LogBufferLength)
go records.run(out, format)
return records
} | [
"func",
"NewFormatLogWriter",
"(",
"out",
"io",
".",
"Writer",
",",
"format",
"string",
")",
"FormatLogWriter",
"{",
"records",
":=",
"make",
"(",
"FormatLogWriter",
",",
"LogBufferLength",
")",
"\n",
"go",
"records",
".",
"run",
"(",
"out",
",",
"format",
... | // This creates a new FormatLogWriter | [
"This",
"creates",
"a",
"new",
"FormatLogWriter"
] | d146e6b86faab5f7e4d135cc63b749d74bf0d4a6 | https://github.com/alecthomas/log4go/blob/d146e6b86faab5f7e4d135cc63b749d74bf0d4a6/pattlog.go#L116-L120 | train |
alecthomas/log4go | termlog.go | Close | func (c *ConsoleLogWriter) Close() {
close(c.w)
time.Sleep(50 * time.Millisecond) // Try to give console I/O time to complete
} | go | func (c *ConsoleLogWriter) Close() {
close(c.w)
time.Sleep(50 * time.Millisecond) // Try to give console I/O time to complete
} | [
"func",
"(",
"c",
"*",
"ConsoleLogWriter",
")",
"Close",
"(",
")",
"{",
"close",
"(",
"c",
".",
"w",
")",
"\n",
"time",
".",
"Sleep",
"(",
"50",
"*",
"time",
".",
"Millisecond",
")",
"// Try to give console I/O time to complete",
"\n",
"}"
] | // Close stops the logger from sending messages to standard output. Attempts to
// send log messages to this logger after a Close have undefined behavior. | [
"Close",
"stops",
"the",
"logger",
"from",
"sending",
"messages",
"to",
"standard",
"output",
".",
"Attempts",
"to",
"send",
"log",
"messages",
"to",
"this",
"logger",
"after",
"a",
"Close",
"have",
"undefined",
"behavior",
"."
] | d146e6b86faab5f7e4d135cc63b749d74bf0d4a6 | https://github.com/alecthomas/log4go/blob/d146e6b86faab5f7e4d135cc63b749d74bf0d4a6/termlog.go#L46-L49 | train |
rook/operator-kit | sample-operator/pkg/client/clientset/versioned/typed/myproject/v1alpha1/fake/fake_sample.go | Get | func (c *FakeSamples) Get(name string, options v1.GetOptions) (result *v1alpha1.Sample, err error) {
obj, err := c.Fake.
Invokes(testing.NewGetAction(samplesResource, c.ns, name), &v1alpha1.Sample{})
if obj == nil {
return nil, err
}
return obj.(*v1alpha1.Sample), err
} | go | func (c *FakeSamples) Get(name string, options v1.GetOptions) (result *v1alpha1.Sample, err error) {
obj, err := c.Fake.
Invokes(testing.NewGetAction(samplesResource, c.ns, name), &v1alpha1.Sample{})
if obj == nil {
return nil, err
}
return obj.(*v1alpha1.Sample), err
} | [
"func",
"(",
"c",
"*",
"FakeSamples",
")",
"Get",
"(",
"name",
"string",
",",
"options",
"v1",
".",
"GetOptions",
")",
"(",
"result",
"*",
"v1alpha1",
".",
"Sample",
",",
"err",
"error",
")",
"{",
"obj",
",",
"err",
":=",
"c",
".",
"Fake",
".",
"... | // Get takes name of the sample, and returns the corresponding sample object, and an error if there is any. | [
"Get",
"takes",
"name",
"of",
"the",
"sample",
"and",
"returns",
"the",
"corresponding",
"sample",
"object",
"and",
"an",
"error",
"if",
"there",
"is",
"any",
"."
] | e7b2e1264fff5f1dc9d506089af2399621b5a0c1 | https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/sample-operator/pkg/client/clientset/versioned/typed/myproject/v1alpha1/fake/fake_sample.go#L42-L50 | train |
rook/operator-kit | sample-operator/pkg/client/clientset/versioned/typed/myproject/v1alpha1/fake/fake_sample.go | List | func (c *FakeSamples) List(opts v1.ListOptions) (result *v1alpha1.SampleList, err error) {
obj, err := c.Fake.
Invokes(testing.NewListAction(samplesResource, samplesKind, c.ns, opts), &v1alpha1.SampleList{})
if obj == nil {
return nil, err
}
label, _, _ := testing.ExtractFromListOptions(opts)
if label == nil {
label = labels.Everything()
}
list := &v1alpha1.SampleList{ListMeta: obj.(*v1alpha1.SampleList).ListMeta}
for _, item := range obj.(*v1alpha1.SampleList).Items {
if label.Matches(labels.Set(item.Labels)) {
list.Items = append(list.Items, item)
}
}
return list, err
} | go | func (c *FakeSamples) List(opts v1.ListOptions) (result *v1alpha1.SampleList, err error) {
obj, err := c.Fake.
Invokes(testing.NewListAction(samplesResource, samplesKind, c.ns, opts), &v1alpha1.SampleList{})
if obj == nil {
return nil, err
}
label, _, _ := testing.ExtractFromListOptions(opts)
if label == nil {
label = labels.Everything()
}
list := &v1alpha1.SampleList{ListMeta: obj.(*v1alpha1.SampleList).ListMeta}
for _, item := range obj.(*v1alpha1.SampleList).Items {
if label.Matches(labels.Set(item.Labels)) {
list.Items = append(list.Items, item)
}
}
return list, err
} | [
"func",
"(",
"c",
"*",
"FakeSamples",
")",
"List",
"(",
"opts",
"v1",
".",
"ListOptions",
")",
"(",
"result",
"*",
"v1alpha1",
".",
"SampleList",
",",
"err",
"error",
")",
"{",
"obj",
",",
"err",
":=",
"c",
".",
"Fake",
".",
"Invokes",
"(",
"testin... | // List takes label and field selectors, and returns the list of Samples that match those selectors. | [
"List",
"takes",
"label",
"and",
"field",
"selectors",
"and",
"returns",
"the",
"list",
"of",
"Samples",
"that",
"match",
"those",
"selectors",
"."
] | e7b2e1264fff5f1dc9d506089af2399621b5a0c1 | https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/sample-operator/pkg/client/clientset/versioned/typed/myproject/v1alpha1/fake/fake_sample.go#L53-L72 | train |
rook/operator-kit | sample-operator/pkg/client/clientset/versioned/typed/myproject/v1alpha1/fake/fake_sample.go | Watch | func (c *FakeSamples) Watch(opts v1.ListOptions) (watch.Interface, error) {
return c.Fake.
InvokesWatch(testing.NewWatchAction(samplesResource, c.ns, opts))
} | go | func (c *FakeSamples) Watch(opts v1.ListOptions) (watch.Interface, error) {
return c.Fake.
InvokesWatch(testing.NewWatchAction(samplesResource, c.ns, opts))
} | [
"func",
"(",
"c",
"*",
"FakeSamples",
")",
"Watch",
"(",
"opts",
"v1",
".",
"ListOptions",
")",
"(",
"watch",
".",
"Interface",
",",
"error",
")",
"{",
"return",
"c",
".",
"Fake",
".",
"InvokesWatch",
"(",
"testing",
".",
"NewWatchAction",
"(",
"sample... | // Watch returns a watch.Interface that watches the requested samples. | [
"Watch",
"returns",
"a",
"watch",
".",
"Interface",
"that",
"watches",
"the",
"requested",
"samples",
"."
] | e7b2e1264fff5f1dc9d506089af2399621b5a0c1 | https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/sample-operator/pkg/client/clientset/versioned/typed/myproject/v1alpha1/fake/fake_sample.go#L75-L79 | train |
rook/operator-kit | sample-operator/pkg/client/clientset/versioned/typed/myproject/v1alpha1/fake/fake_sample.go | Delete | func (c *FakeSamples) Delete(name string, options *v1.DeleteOptions) error {
_, err := c.Fake.
Invokes(testing.NewDeleteAction(samplesResource, c.ns, name), &v1alpha1.Sample{})
return err
} | go | func (c *FakeSamples) Delete(name string, options *v1.DeleteOptions) error {
_, err := c.Fake.
Invokes(testing.NewDeleteAction(samplesResource, c.ns, name), &v1alpha1.Sample{})
return err
} | [
"func",
"(",
"c",
"*",
"FakeSamples",
")",
"Delete",
"(",
"name",
"string",
",",
"options",
"*",
"v1",
".",
"DeleteOptions",
")",
"error",
"{",
"_",
",",
"err",
":=",
"c",
".",
"Fake",
".",
"Invokes",
"(",
"testing",
".",
"NewDeleteAction",
"(",
"sam... | // Delete takes name of the sample and deletes it. Returns an error if one occurs. | [
"Delete",
"takes",
"name",
"of",
"the",
"sample",
"and",
"deletes",
"it",
".",
"Returns",
"an",
"error",
"if",
"one",
"occurs",
"."
] | e7b2e1264fff5f1dc9d506089af2399621b5a0c1 | https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/sample-operator/pkg/client/clientset/versioned/typed/myproject/v1alpha1/fake/fake_sample.go#L104-L109 | train |
rook/operator-kit | sample-operator/pkg/client/clientset/versioned/typed/myproject/v1alpha1/fake/fake_sample.go | Patch | func (c *FakeSamples) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Sample, err error) {
obj, err := c.Fake.
Invokes(testing.NewPatchSubresourceAction(samplesResource, c.ns, name, data, subresources...), &v1alpha1.Sample{})
if obj == nil {
return nil, err
}
return obj.(*v1alpha1.Sample), err
} | go | func (c *FakeSamples) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Sample, err error) {
obj, err := c.Fake.
Invokes(testing.NewPatchSubresourceAction(samplesResource, c.ns, name, data, subresources...), &v1alpha1.Sample{})
if obj == nil {
return nil, err
}
return obj.(*v1alpha1.Sample), err
} | [
"func",
"(",
"c",
"*",
"FakeSamples",
")",
"Patch",
"(",
"name",
"string",
",",
"pt",
"types",
".",
"PatchType",
",",
"data",
"[",
"]",
"byte",
",",
"subresources",
"...",
"string",
")",
"(",
"result",
"*",
"v1alpha1",
".",
"Sample",
",",
"err",
"err... | // Patch applies the patch and returns the patched sample. | [
"Patch",
"applies",
"the",
"patch",
"and",
"returns",
"the",
"patched",
"sample",
"."
] | e7b2e1264fff5f1dc9d506089af2399621b5a0c1 | https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/sample-operator/pkg/client/clientset/versioned/typed/myproject/v1alpha1/fake/fake_sample.go#L120-L128 | train |
rook/operator-kit | sample-operator/pkg/client/clientset/versioned/typed/myproject/v1alpha1/sample.go | newSamples | func newSamples(c *MyprojectV1alpha1Client, namespace string) *samples {
return &samples{
client: c.RESTClient(),
ns: namespace,
}
} | go | func newSamples(c *MyprojectV1alpha1Client, namespace string) *samples {
return &samples{
client: c.RESTClient(),
ns: namespace,
}
} | [
"func",
"newSamples",
"(",
"c",
"*",
"MyprojectV1alpha1Client",
",",
"namespace",
"string",
")",
"*",
"samples",
"{",
"return",
"&",
"samples",
"{",
"client",
":",
"c",
".",
"RESTClient",
"(",
")",
",",
"ns",
":",
"namespace",
",",
"}",
"\n",
"}"
] | // newSamples returns a Samples | [
"newSamples",
"returns",
"a",
"Samples"
] | e7b2e1264fff5f1dc9d506089af2399621b5a0c1 | https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/sample-operator/pkg/client/clientset/versioned/typed/myproject/v1alpha1/sample.go#L56-L61 | train |
rook/operator-kit | sample-operator/pkg/apis/myproject/v1alpha1/zz_generated.deepcopy.go | DeepCopy | func (in *Sample) DeepCopy() *Sample {
if in == nil {
return nil
}
out := new(Sample)
in.DeepCopyInto(out)
return out
} | go | func (in *Sample) DeepCopy() *Sample {
if in == nil {
return nil
}
out := new(Sample)
in.DeepCopyInto(out)
return out
} | [
"func",
"(",
"in",
"*",
"Sample",
")",
"DeepCopy",
"(",
")",
"*",
"Sample",
"{",
"if",
"in",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"out",
":=",
"new",
"(",
"Sample",
")",
"\n",
"in",
".",
"DeepCopyInto",
"(",
"out",
")",
"\n",
"re... | // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Sample. | [
"DeepCopy",
"is",
"an",
"autogenerated",
"deepcopy",
"function",
"copying",
"the",
"receiver",
"creating",
"a",
"new",
"Sample",
"."
] | e7b2e1264fff5f1dc9d506089af2399621b5a0c1 | https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/sample-operator/pkg/apis/myproject/v1alpha1/zz_generated.deepcopy.go#L37-L44 | train |
rook/operator-kit | sample-operator/pkg/apis/myproject/v1alpha1/zz_generated.deepcopy.go | DeepCopy | func (in *SampleList) DeepCopy() *SampleList {
if in == nil {
return nil
}
out := new(SampleList)
in.DeepCopyInto(out)
return out
} | go | func (in *SampleList) DeepCopy() *SampleList {
if in == nil {
return nil
}
out := new(SampleList)
in.DeepCopyInto(out)
return out
} | [
"func",
"(",
"in",
"*",
"SampleList",
")",
"DeepCopy",
"(",
")",
"*",
"SampleList",
"{",
"if",
"in",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"out",
":=",
"new",
"(",
"SampleList",
")",
"\n",
"in",
".",
"DeepCopyInto",
"(",
"out",
")",
... | // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SampleList. | [
"DeepCopy",
"is",
"an",
"autogenerated",
"deepcopy",
"function",
"copying",
"the",
"receiver",
"creating",
"a",
"new",
"SampleList",
"."
] | e7b2e1264fff5f1dc9d506089af2399621b5a0c1 | https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/sample-operator/pkg/apis/myproject/v1alpha1/zz_generated.deepcopy.go#L70-L77 | train |
rook/operator-kit | sample-operator/pkg/apis/myproject/v1alpha1/zz_generated.deepcopy.go | DeepCopy | func (in *SampleSpec) DeepCopy() *SampleSpec {
if in == nil {
return nil
}
out := new(SampleSpec)
in.DeepCopyInto(out)
return out
} | go | func (in *SampleSpec) DeepCopy() *SampleSpec {
if in == nil {
return nil
}
out := new(SampleSpec)
in.DeepCopyInto(out)
return out
} | [
"func",
"(",
"in",
"*",
"SampleSpec",
")",
"DeepCopy",
"(",
")",
"*",
"SampleSpec",
"{",
"if",
"in",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"out",
":=",
"new",
"(",
"SampleSpec",
")",
"\n",
"in",
".",
"DeepCopyInto",
"(",
"out",
")",
... | // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SampleSpec. | [
"DeepCopy",
"is",
"an",
"autogenerated",
"deepcopy",
"function",
"copying",
"the",
"receiver",
"creating",
"a",
"new",
"SampleSpec",
"."
] | e7b2e1264fff5f1dc9d506089af2399621b5a0c1 | https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/sample-operator/pkg/apis/myproject/v1alpha1/zz_generated.deepcopy.go#L94-L101 | train |
rook/operator-kit | sample-operator/pkg/client/clientset/versioned/fake/clientset_generated.go | MyprojectV1alpha1 | func (c *Clientset) MyprojectV1alpha1() myprojectv1alpha1.MyprojectV1alpha1Interface {
return &fakemyprojectv1alpha1.FakeMyprojectV1alpha1{Fake: &c.Fake}
} | go | func (c *Clientset) MyprojectV1alpha1() myprojectv1alpha1.MyprojectV1alpha1Interface {
return &fakemyprojectv1alpha1.FakeMyprojectV1alpha1{Fake: &c.Fake}
} | [
"func",
"(",
"c",
"*",
"Clientset",
")",
"MyprojectV1alpha1",
"(",
")",
"myprojectv1alpha1",
".",
"MyprojectV1alpha1Interface",
"{",
"return",
"&",
"fakemyprojectv1alpha1",
".",
"FakeMyprojectV1alpha1",
"{",
"Fake",
":",
"&",
"c",
".",
"Fake",
"}",
"\n",
"}"
] | // MyprojectV1alpha1 retrieves the MyprojectV1alpha1Client | [
"MyprojectV1alpha1",
"retrieves",
"the",
"MyprojectV1alpha1Client"
] | e7b2e1264fff5f1dc9d506089af2399621b5a0c1 | https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/sample-operator/pkg/client/clientset/versioned/fake/clientset_generated.go#L75-L77 | train |
rook/operator-kit | sample-operator/pkg/client/clientset/versioned/fake/clientset_generated.go | Myproject | func (c *Clientset) Myproject() myprojectv1alpha1.MyprojectV1alpha1Interface {
return &fakemyprojectv1alpha1.FakeMyprojectV1alpha1{Fake: &c.Fake}
} | go | func (c *Clientset) Myproject() myprojectv1alpha1.MyprojectV1alpha1Interface {
return &fakemyprojectv1alpha1.FakeMyprojectV1alpha1{Fake: &c.Fake}
} | [
"func",
"(",
"c",
"*",
"Clientset",
")",
"Myproject",
"(",
")",
"myprojectv1alpha1",
".",
"MyprojectV1alpha1Interface",
"{",
"return",
"&",
"fakemyprojectv1alpha1",
".",
"FakeMyprojectV1alpha1",
"{",
"Fake",
":",
"&",
"c",
".",
"Fake",
"}",
"\n",
"}"
] | // Myproject retrieves the MyprojectV1alpha1Client | [
"Myproject",
"retrieves",
"the",
"MyprojectV1alpha1Client"
] | e7b2e1264fff5f1dc9d506089af2399621b5a0c1 | https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/sample-operator/pkg/client/clientset/versioned/fake/clientset_generated.go#L80-L82 | train |
rook/operator-kit | sample-operator/pkg/client/listers/myproject/v1alpha1/sample.go | List | func (s *sampleLister) List(selector labels.Selector) (ret []*v1alpha1.Sample, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*v1alpha1.Sample))
})
return ret, err
} | go | func (s *sampleLister) List(selector labels.Selector) (ret []*v1alpha1.Sample, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*v1alpha1.Sample))
})
return ret, err
} | [
"func",
"(",
"s",
"*",
"sampleLister",
")",
"List",
"(",
"selector",
"labels",
".",
"Selector",
")",
"(",
"ret",
"[",
"]",
"*",
"v1alpha1",
".",
"Sample",
",",
"err",
"error",
")",
"{",
"err",
"=",
"cache",
".",
"ListAll",
"(",
"s",
".",
"indexer",... | // List lists all Samples in the indexer. | [
"List",
"lists",
"all",
"Samples",
"in",
"the",
"indexer",
"."
] | e7b2e1264fff5f1dc9d506089af2399621b5a0c1 | https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/sample-operator/pkg/client/listers/myproject/v1alpha1/sample.go#L48-L53 | train |
rook/operator-kit | sample-operator/pkg/client/listers/myproject/v1alpha1/sample.go | Samples | func (s *sampleLister) Samples(namespace string) SampleNamespaceLister {
return sampleNamespaceLister{indexer: s.indexer, namespace: namespace}
} | go | func (s *sampleLister) Samples(namespace string) SampleNamespaceLister {
return sampleNamespaceLister{indexer: s.indexer, namespace: namespace}
} | [
"func",
"(",
"s",
"*",
"sampleLister",
")",
"Samples",
"(",
"namespace",
"string",
")",
"SampleNamespaceLister",
"{",
"return",
"sampleNamespaceLister",
"{",
"indexer",
":",
"s",
".",
"indexer",
",",
"namespace",
":",
"namespace",
"}",
"\n",
"}"
] | // Samples returns an object that can list and get Samples. | [
"Samples",
"returns",
"an",
"object",
"that",
"can",
"list",
"and",
"get",
"Samples",
"."
] | e7b2e1264fff5f1dc9d506089af2399621b5a0c1 | https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/sample-operator/pkg/client/listers/myproject/v1alpha1/sample.go#L56-L58 | train |
rook/operator-kit | sample-operator/pkg/client/listers/myproject/v1alpha1/sample.go | List | func (s sampleNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Sample, err error) {
err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {
ret = append(ret, m.(*v1alpha1.Sample))
})
return ret, err
} | go | func (s sampleNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Sample, err error) {
err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {
ret = append(ret, m.(*v1alpha1.Sample))
})
return ret, err
} | [
"func",
"(",
"s",
"sampleNamespaceLister",
")",
"List",
"(",
"selector",
"labels",
".",
"Selector",
")",
"(",
"ret",
"[",
"]",
"*",
"v1alpha1",
".",
"Sample",
",",
"err",
"error",
")",
"{",
"err",
"=",
"cache",
".",
"ListAllByNamespace",
"(",
"s",
".",... | // List lists all Samples in the indexer for a given namespace. | [
"List",
"lists",
"all",
"Samples",
"in",
"the",
"indexer",
"for",
"a",
"given",
"namespace",
"."
] | e7b2e1264fff5f1dc9d506089af2399621b5a0c1 | https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/sample-operator/pkg/client/listers/myproject/v1alpha1/sample.go#L77-L82 | train |
rook/operator-kit | sample-operator/controller.go | newSampleController | func newSampleController(context *opkit.Context, sampleClientset sampleclient.MyprojectV1alpha1Interface) *SampleController {
return &SampleController{
context: context,
sampleClientset: sampleClientset,
}
} | go | func newSampleController(context *opkit.Context, sampleClientset sampleclient.MyprojectV1alpha1Interface) *SampleController {
return &SampleController{
context: context,
sampleClientset: sampleClientset,
}
} | [
"func",
"newSampleController",
"(",
"context",
"*",
"opkit",
".",
"Context",
",",
"sampleClientset",
"sampleclient",
".",
"MyprojectV1alpha1Interface",
")",
"*",
"SampleController",
"{",
"return",
"&",
"SampleController",
"{",
"context",
":",
"context",
",",
"sample... | // newSampleController create controller for watching sample custom resources created | [
"newSampleController",
"create",
"controller",
"for",
"watching",
"sample",
"custom",
"resources",
"created"
] | e7b2e1264fff5f1dc9d506089af2399621b5a0c1 | https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/sample-operator/controller.go#L36-L41 | train |
rook/operator-kit | sample-operator/controller.go | StartWatch | func (c *SampleController) StartWatch(namespace string, stopCh chan struct{}) error {
resourceHandlers := cache.ResourceEventHandlerFuncs{
AddFunc: c.onAdd,
UpdateFunc: c.onUpdate,
DeleteFunc: c.onDelete,
}
restClient := c.sampleClientset.RESTClient()
watcher := opkit.NewWatcher(sample.SampleResource, namespace, resourceHandlers, restClient)
go watcher.Watch(&sample.Sample{}, stopCh)
return nil
} | go | func (c *SampleController) StartWatch(namespace string, stopCh chan struct{}) error {
resourceHandlers := cache.ResourceEventHandlerFuncs{
AddFunc: c.onAdd,
UpdateFunc: c.onUpdate,
DeleteFunc: c.onDelete,
}
restClient := c.sampleClientset.RESTClient()
watcher := opkit.NewWatcher(sample.SampleResource, namespace, resourceHandlers, restClient)
go watcher.Watch(&sample.Sample{}, stopCh)
return nil
} | [
"func",
"(",
"c",
"*",
"SampleController",
")",
"StartWatch",
"(",
"namespace",
"string",
",",
"stopCh",
"chan",
"struct",
"{",
"}",
")",
"error",
"{",
"resourceHandlers",
":=",
"cache",
".",
"ResourceEventHandlerFuncs",
"{",
"AddFunc",
":",
"c",
".",
"onAdd... | // Watch watches for instances of Sample custom resources and acts on them | [
"Watch",
"watches",
"for",
"instances",
"of",
"Sample",
"custom",
"resources",
"and",
"acts",
"on",
"them"
] | e7b2e1264fff5f1dc9d506089af2399621b5a0c1 | https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/sample-operator/controller.go#L44-L55 | train |
rook/operator-kit | sample-operator/pkg/client/clientset/versioned/typed/myproject/v1alpha1/myproject_client.go | NewForConfigOrDie | func NewForConfigOrDie(c *rest.Config) *MyprojectV1alpha1Client {
client, err := NewForConfig(c)
if err != nil {
panic(err)
}
return client
} | go | func NewForConfigOrDie(c *rest.Config) *MyprojectV1alpha1Client {
client, err := NewForConfig(c)
if err != nil {
panic(err)
}
return client
} | [
"func",
"NewForConfigOrDie",
"(",
"c",
"*",
"rest",
".",
"Config",
")",
"*",
"MyprojectV1alpha1Client",
"{",
"client",
",",
"err",
":=",
"NewForConfig",
"(",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"r... | // NewForConfigOrDie creates a new MyprojectV1alpha1Client for the given config and
// panics if there is an error in the config. | [
"NewForConfigOrDie",
"creates",
"a",
"new",
"MyprojectV1alpha1Client",
"for",
"the",
"given",
"config",
"and",
"panics",
"if",
"there",
"is",
"an",
"error",
"in",
"the",
"config",
"."
] | e7b2e1264fff5f1dc9d506089af2399621b5a0c1 | https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/sample-operator/pkg/client/clientset/versioned/typed/myproject/v1alpha1/myproject_client.go#L57-L63 | train |
rook/operator-kit | watcher.go | NewWatcher | func NewWatcher(resource CustomResource, namespace string, handlers cache.ResourceEventHandlerFuncs, client rest.Interface) *ResourceWatcher {
return &ResourceWatcher{
resource: resource,
namespace: namespace,
resourceEventHandlers: handlers,
client: client,
}
} | go | func NewWatcher(resource CustomResource, namespace string, handlers cache.ResourceEventHandlerFuncs, client rest.Interface) *ResourceWatcher {
return &ResourceWatcher{
resource: resource,
namespace: namespace,
resourceEventHandlers: handlers,
client: client,
}
} | [
"func",
"NewWatcher",
"(",
"resource",
"CustomResource",
",",
"namespace",
"string",
",",
"handlers",
"cache",
".",
"ResourceEventHandlerFuncs",
",",
"client",
"rest",
".",
"Interface",
")",
"*",
"ResourceWatcher",
"{",
"return",
"&",
"ResourceWatcher",
"{",
"reso... | // NewWatcher creates an instance of a custom resource watcher for the given resource | [
"NewWatcher",
"creates",
"an",
"instance",
"of",
"a",
"custom",
"resource",
"watcher",
"for",
"the",
"given",
"resource"
] | e7b2e1264fff5f1dc9d506089af2399621b5a0c1 | https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/watcher.go#L44-L51 | train |
rook/operator-kit | resource.go | CreateCustomResources | func CreateCustomResources(context Context, resources []CustomResource) error {
var lastErr error
for _, resource := range resources {
if err := createCRD(context, resource); err != nil {
lastErr = err
}
}
for _, resource := range resources {
if err := waitForCRDInit(context, resource); err != nil {
lastErr = err
}
}
return lastErr
} | go | func CreateCustomResources(context Context, resources []CustomResource) error {
var lastErr error
for _, resource := range resources {
if err := createCRD(context, resource); err != nil {
lastErr = err
}
}
for _, resource := range resources {
if err := waitForCRDInit(context, resource); err != nil {
lastErr = err
}
}
return lastErr
} | [
"func",
"CreateCustomResources",
"(",
"context",
"Context",
",",
"resources",
"[",
"]",
"CustomResource",
")",
"error",
"{",
"var",
"lastErr",
"error",
"\n",
"for",
"_",
",",
"resource",
":=",
"range",
"resources",
"{",
"if",
"err",
":=",
"createCRD",
"(",
... | // CreateCustomResources creates the given custom resources and waits for them to initialize
// The resource is of kind CRD if the Kubernetes server is 1.7.0 and above.
// The resource is of kind TPR if the Kubernetes server is below 1.7.0. | [
"CreateCustomResources",
"creates",
"the",
"given",
"custom",
"resources",
"and",
"waits",
"for",
"them",
"to",
"initialize",
"The",
"resource",
"is",
"of",
"kind",
"CRD",
"if",
"the",
"Kubernetes",
"server",
"is",
"1",
".",
"7",
".",
"0",
"and",
"above",
... | e7b2e1264fff5f1dc9d506089af2399621b5a0c1 | https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/resource.go#L70-L86 | train |
rook/operator-kit | client.go | NewHTTPClient | func NewHTTPClient(group, version string, schemeBuilder runtime.SchemeBuilder) (rest.Interface, *runtime.Scheme, error) {
config, err := rest.InClusterConfig()
if err != nil {
return nil, nil, err
}
return NewHTTPClientFromConfig(group, version, schemeBuilder, config)
} | go | func NewHTTPClient(group, version string, schemeBuilder runtime.SchemeBuilder) (rest.Interface, *runtime.Scheme, error) {
config, err := rest.InClusterConfig()
if err != nil {
return nil, nil, err
}
return NewHTTPClientFromConfig(group, version, schemeBuilder, config)
} | [
"func",
"NewHTTPClient",
"(",
"group",
",",
"version",
"string",
",",
"schemeBuilder",
"runtime",
".",
"SchemeBuilder",
")",
"(",
"rest",
".",
"Interface",
",",
"*",
"runtime",
".",
"Scheme",
",",
"error",
")",
"{",
"config",
",",
"err",
":=",
"rest",
".... | // NewHTTPClient creates a Kubernetes client to interact with API extensions for Custom Resources | [
"NewHTTPClient",
"creates",
"a",
"Kubernetes",
"client",
"to",
"interact",
"with",
"API",
"extensions",
"for",
"Custom",
"Resources"
] | e7b2e1264fff5f1dc9d506089af2399621b5a0c1 | https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/client.go#L32-L39 | train |
rook/operator-kit | sample-operator/pkg/client/informers/externalversions/myproject/v1alpha1/sample.go | NewSampleInformer | func NewSampleInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {
return NewFilteredSampleInformer(client, namespace, resyncPeriod, indexers, nil)
} | go | func NewSampleInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {
return NewFilteredSampleInformer(client, namespace, resyncPeriod, indexers, nil)
} | [
"func",
"NewSampleInformer",
"(",
"client",
"versioned",
".",
"Interface",
",",
"namespace",
"string",
",",
"resyncPeriod",
"time",
".",
"Duration",
",",
"indexers",
"cache",
".",
"Indexers",
")",
"cache",
".",
"SharedIndexInformer",
"{",
"return",
"NewFilteredSam... | // NewSampleInformer constructs a new informer for Sample type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server. | [
"NewSampleInformer",
"constructs",
"a",
"new",
"informer",
"for",
"Sample",
"type",
".",
"Always",
"prefer",
"using",
"an",
"informer",
"factory",
"to",
"get",
"a",
"shared",
"informer",
"instead",
"of",
"getting",
"an",
"independent",
"one",
".",
"This",
"red... | e7b2e1264fff5f1dc9d506089af2399621b5a0c1 | https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/sample-operator/pkg/client/informers/externalversions/myproject/v1alpha1/sample.go#L50-L52 | train |
rook/operator-kit | sample-operator/pkg/client/informers/externalversions/myproject/v1alpha1/sample.go | NewFilteredSampleInformer | func NewFilteredSampleInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {
return cache.NewSharedIndexInformer(
&cache.ListWatch{
ListFunc: func(options v1.ListOptions) (runtime.Object, error) {
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.MyprojectV1alpha1().Samples(namespace).List(options)
},
WatchFunc: func(options v1.ListOptions) (watch.Interface, error) {
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.MyprojectV1alpha1().Samples(namespace).Watch(options)
},
},
&myprojectv1alpha1.Sample{},
resyncPeriod,
indexers,
)
} | go | func NewFilteredSampleInformer(client versioned.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {
return cache.NewSharedIndexInformer(
&cache.ListWatch{
ListFunc: func(options v1.ListOptions) (runtime.Object, error) {
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.MyprojectV1alpha1().Samples(namespace).List(options)
},
WatchFunc: func(options v1.ListOptions) (watch.Interface, error) {
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.MyprojectV1alpha1().Samples(namespace).Watch(options)
},
},
&myprojectv1alpha1.Sample{},
resyncPeriod,
indexers,
)
} | [
"func",
"NewFilteredSampleInformer",
"(",
"client",
"versioned",
".",
"Interface",
",",
"namespace",
"string",
",",
"resyncPeriod",
"time",
".",
"Duration",
",",
"indexers",
"cache",
".",
"Indexers",
",",
"tweakListOptions",
"internalinterfaces",
".",
"TweakListOption... | // NewFilteredSampleInformer constructs a new informer for Sample type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server. | [
"NewFilteredSampleInformer",
"constructs",
"a",
"new",
"informer",
"for",
"Sample",
"type",
".",
"Always",
"prefer",
"using",
"an",
"informer",
"factory",
"to",
"get",
"a",
"shared",
"informer",
"instead",
"of",
"getting",
"an",
"independent",
"one",
".",
"This"... | e7b2e1264fff5f1dc9d506089af2399621b5a0c1 | https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/sample-operator/pkg/client/informers/externalversions/myproject/v1alpha1/sample.go#L57-L77 | train |
rook/operator-kit | sample-operator/pkg/client/informers/externalversions/myproject/v1alpha1/interface.go | Samples | func (v *version) Samples() SampleInformer {
return &sampleInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}
} | go | func (v *version) Samples() SampleInformer {
return &sampleInformer{factory: v.factory, namespace: v.namespace, tweakListOptions: v.tweakListOptions}
} | [
"func",
"(",
"v",
"*",
"version",
")",
"Samples",
"(",
")",
"SampleInformer",
"{",
"return",
"&",
"sampleInformer",
"{",
"factory",
":",
"v",
".",
"factory",
",",
"namespace",
":",
"v",
".",
"namespace",
",",
"tweakListOptions",
":",
"v",
".",
"tweakList... | // Samples returns a SampleInformer. | [
"Samples",
"returns",
"a",
"SampleInformer",
"."
] | e7b2e1264fff5f1dc9d506089af2399621b5a0c1 | https://github.com/rook/operator-kit/blob/e7b2e1264fff5f1dc9d506089af2399621b5a0c1/sample-operator/pkg/client/informers/externalversions/myproject/v1alpha1/interface.go#L43-L45 | train |
mcuadros/go-syslog | internal/syslogparser/rfc5424/rfc5424.go | parseYear | func parseYear(buff []byte, cursor *int, l int) (int, error) {
yearLen := 4
if *cursor+yearLen > l {
return 0, syslogparser.ErrEOL
}
// XXX : we do not check for a valid year (ie. 1999, 2013 etc)
// XXX : we only checks the format is correct
sub := string(buff[*cursor : *cursor+yearLen])
*cursor += yearLen
year, err := strconv.Atoi(sub)
if err != nil {
return 0, ErrYearInvalid
}
return year, nil
} | go | func parseYear(buff []byte, cursor *int, l int) (int, error) {
yearLen := 4
if *cursor+yearLen > l {
return 0, syslogparser.ErrEOL
}
// XXX : we do not check for a valid year (ie. 1999, 2013 etc)
// XXX : we only checks the format is correct
sub := string(buff[*cursor : *cursor+yearLen])
*cursor += yearLen
year, err := strconv.Atoi(sub)
if err != nil {
return 0, ErrYearInvalid
}
return year, nil
} | [
"func",
"parseYear",
"(",
"buff",
"[",
"]",
"byte",
",",
"cursor",
"*",
"int",
",",
"l",
"int",
")",
"(",
"int",
",",
"error",
")",
"{",
"yearLen",
":=",
"4",
"\n\n",
"if",
"*",
"cursor",
"+",
"yearLen",
">",
"l",
"{",
"return",
"0",
",",
"sysl... | // DATE-FULLYEAR = 4DIGIT | [
"DATE",
"-",
"FULLYEAR",
"=",
"4DIGIT"
] | a127d826d6c27489d377b3c080bd256d8f8093a6 | https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/internal/syslogparser/rfc5424/rfc5424.go#L307-L326 | train |
mcuadros/go-syslog | internal/syslogparser/rfc5424/rfc5424.go | parseMonth | func parseMonth(buff []byte, cursor *int, l int) (int, error) {
return syslogparser.Parse2Digits(buff, cursor, l, 1, 12, ErrMonthInvalid)
} | go | func parseMonth(buff []byte, cursor *int, l int) (int, error) {
return syslogparser.Parse2Digits(buff, cursor, l, 1, 12, ErrMonthInvalid)
} | [
"func",
"parseMonth",
"(",
"buff",
"[",
"]",
"byte",
",",
"cursor",
"*",
"int",
",",
"l",
"int",
")",
"(",
"int",
",",
"error",
")",
"{",
"return",
"syslogparser",
".",
"Parse2Digits",
"(",
"buff",
",",
"cursor",
",",
"l",
",",
"1",
",",
"12",
",... | // DATE-MONTH = 2DIGIT ; 01-12 | [
"DATE",
"-",
"MONTH",
"=",
"2DIGIT",
";",
"01",
"-",
"12"
] | a127d826d6c27489d377b3c080bd256d8f8093a6 | https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/internal/syslogparser/rfc5424/rfc5424.go#L329-L331 | train |
mcuadros/go-syslog | internal/syslogparser/rfc5424/rfc5424.go | parseFullTime | func parseFullTime(buff []byte, cursor *int, l int) (fullTime, error) {
var loc = new(time.Location)
var ft fullTime
pt, err := parsePartialTime(buff, cursor, l)
if err != nil {
return ft, err
}
loc, err = parseTimeOffset(buff, cursor, l)
if err != nil {
return ft, err
}
ft = fullTime{
pt: pt,
loc: loc,
}
return ft, nil
} | go | func parseFullTime(buff []byte, cursor *int, l int) (fullTime, error) {
var loc = new(time.Location)
var ft fullTime
pt, err := parsePartialTime(buff, cursor, l)
if err != nil {
return ft, err
}
loc, err = parseTimeOffset(buff, cursor, l)
if err != nil {
return ft, err
}
ft = fullTime{
pt: pt,
loc: loc,
}
return ft, nil
} | [
"func",
"parseFullTime",
"(",
"buff",
"[",
"]",
"byte",
",",
"cursor",
"*",
"int",
",",
"l",
"int",
")",
"(",
"fullTime",
",",
"error",
")",
"{",
"var",
"loc",
"=",
"new",
"(",
"time",
".",
"Location",
")",
"\n",
"var",
"ft",
"fullTime",
"\n\n",
... | // FULL-TIME = PARTIAL-TIME TIME-OFFSET | [
"FULL",
"-",
"TIME",
"=",
"PARTIAL",
"-",
"TIME",
"TIME",
"-",
"OFFSET"
] | a127d826d6c27489d377b3c080bd256d8f8093a6 | https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/internal/syslogparser/rfc5424/rfc5424.go#L343-L363 | train |
mcuadros/go-syslog | internal/syslogparser/rfc5424/rfc5424.go | parseHour | func parseHour(buff []byte, cursor *int, l int) (int, error) {
return syslogparser.Parse2Digits(buff, cursor, l, 0, 23, ErrHourInvalid)
} | go | func parseHour(buff []byte, cursor *int, l int) (int, error) {
return syslogparser.Parse2Digits(buff, cursor, l, 0, 23, ErrHourInvalid)
} | [
"func",
"parseHour",
"(",
"buff",
"[",
"]",
"byte",
",",
"cursor",
"*",
"int",
",",
"l",
"int",
")",
"(",
"int",
",",
"error",
")",
"{",
"return",
"syslogparser",
".",
"Parse2Digits",
"(",
"buff",
",",
"cursor",
",",
"l",
",",
"0",
",",
"23",
","... | // TIME-HOUR = 2DIGIT ; 00-23 | [
"TIME",
"-",
"HOUR",
"=",
"2DIGIT",
";",
"00",
"-",
"23"
] | a127d826d6c27489d377b3c080bd256d8f8093a6 | https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/internal/syslogparser/rfc5424/rfc5424.go#L411-L413 | train |
mcuadros/go-syslog | internal/syslogparser/rfc5424/rfc5424.go | parseMinute | func parseMinute(buff []byte, cursor *int, l int) (int, error) {
return syslogparser.Parse2Digits(buff, cursor, l, 0, 59, ErrMinuteInvalid)
} | go | func parseMinute(buff []byte, cursor *int, l int) (int, error) {
return syslogparser.Parse2Digits(buff, cursor, l, 0, 59, ErrMinuteInvalid)
} | [
"func",
"parseMinute",
"(",
"buff",
"[",
"]",
"byte",
",",
"cursor",
"*",
"int",
",",
"l",
"int",
")",
"(",
"int",
",",
"error",
")",
"{",
"return",
"syslogparser",
".",
"Parse2Digits",
"(",
"buff",
",",
"cursor",
",",
"l",
",",
"0",
",",
"59",
"... | // TIME-MINUTE = 2DIGIT ; 00-59 | [
"TIME",
"-",
"MINUTE",
"=",
"2DIGIT",
";",
"00",
"-",
"59"
] | a127d826d6c27489d377b3c080bd256d8f8093a6 | https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/internal/syslogparser/rfc5424/rfc5424.go#L416-L418 | train |
mcuadros/go-syslog | internal/syslogparser/rfc5424/rfc5424.go | parseSecond | func parseSecond(buff []byte, cursor *int, l int) (int, error) {
return syslogparser.Parse2Digits(buff, cursor, l, 0, 59, ErrSecondInvalid)
} | go | func parseSecond(buff []byte, cursor *int, l int) (int, error) {
return syslogparser.Parse2Digits(buff, cursor, l, 0, 59, ErrSecondInvalid)
} | [
"func",
"parseSecond",
"(",
"buff",
"[",
"]",
"byte",
",",
"cursor",
"*",
"int",
",",
"l",
"int",
")",
"(",
"int",
",",
"error",
")",
"{",
"return",
"syslogparser",
".",
"Parse2Digits",
"(",
"buff",
",",
"cursor",
",",
"l",
",",
"0",
",",
"59",
"... | // TIME-SECOND = 2DIGIT ; 00-59 | [
"TIME",
"-",
"SECOND",
"=",
"2DIGIT",
";",
"00",
"-",
"59"
] | a127d826d6c27489d377b3c080bd256d8f8093a6 | https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/internal/syslogparser/rfc5424/rfc5424.go#L421-L423 | train |
mcuadros/go-syslog | handler.go | NewChannelHandler | func NewChannelHandler(channel LogPartsChannel) *ChannelHandler {
handler := new(ChannelHandler)
handler.SetChannel(channel)
return handler
} | go | func NewChannelHandler(channel LogPartsChannel) *ChannelHandler {
handler := new(ChannelHandler)
handler.SetChannel(channel)
return handler
} | [
"func",
"NewChannelHandler",
"(",
"channel",
"LogPartsChannel",
")",
"*",
"ChannelHandler",
"{",
"handler",
":=",
"new",
"(",
"ChannelHandler",
")",
"\n",
"handler",
".",
"SetChannel",
"(",
"channel",
")",
"\n\n",
"return",
"handler",
"\n",
"}"
] | //NewChannelHandler returns a new ChannelHandler | [
"NewChannelHandler",
"returns",
"a",
"new",
"ChannelHandler"
] | a127d826d6c27489d377b3c080bd256d8f8093a6 | https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/handler.go#L20-L25 | train |
mcuadros/go-syslog | handler.go | Handle | func (h *ChannelHandler) Handle(logParts format.LogParts, messageLength int64, err error) {
h.channel <- logParts
} | go | func (h *ChannelHandler) Handle(logParts format.LogParts, messageLength int64, err error) {
h.channel <- logParts
} | [
"func",
"(",
"h",
"*",
"ChannelHandler",
")",
"Handle",
"(",
"logParts",
"format",
".",
"LogParts",
",",
"messageLength",
"int64",
",",
"err",
"error",
")",
"{",
"h",
".",
"channel",
"<-",
"logParts",
"\n",
"}"
] | //Syslog entry receiver | [
"Syslog",
"entry",
"receiver"
] | a127d826d6c27489d377b3c080bd256d8f8093a6 | https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/handler.go#L33-L35 | train |
mcuadros/go-syslog | server.go | NewServer | func NewServer() *Server {
return &Server{tlsPeerNameFunc: defaultTlsPeerName, datagramPool: sync.Pool{
New: func() interface{} {
return make([]byte, 65536)
},
}}
} | go | func NewServer() *Server {
return &Server{tlsPeerNameFunc: defaultTlsPeerName, datagramPool: sync.Pool{
New: func() interface{} {
return make([]byte, 65536)
},
}}
} | [
"func",
"NewServer",
"(",
")",
"*",
"Server",
"{",
"return",
"&",
"Server",
"{",
"tlsPeerNameFunc",
":",
"defaultTlsPeerName",
",",
"datagramPool",
":",
"sync",
".",
"Pool",
"{",
"New",
":",
"func",
"(",
")",
"interface",
"{",
"}",
"{",
"return",
"make",... | //NewServer returns a new Server | [
"NewServer",
"returns",
"a",
"new",
"Server"
] | a127d826d6c27489d377b3c080bd256d8f8093a6 | https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/server.go#L46-L52 | train |
mcuadros/go-syslog | server.go | defaultTlsPeerName | func defaultTlsPeerName(tlsConn *tls.Conn) (tlsPeer string, ok bool) {
state := tlsConn.ConnectionState()
if len(state.PeerCertificates) <= 0 {
return "", false
}
cn := state.PeerCertificates[0].Subject.CommonName
return cn, true
} | go | func defaultTlsPeerName(tlsConn *tls.Conn) (tlsPeer string, ok bool) {
state := tlsConn.ConnectionState()
if len(state.PeerCertificates) <= 0 {
return "", false
}
cn := state.PeerCertificates[0].Subject.CommonName
return cn, true
} | [
"func",
"defaultTlsPeerName",
"(",
"tlsConn",
"*",
"tls",
".",
"Conn",
")",
"(",
"tlsPeer",
"string",
",",
"ok",
"bool",
")",
"{",
"state",
":=",
"tlsConn",
".",
"ConnectionState",
"(",
")",
"\n",
"if",
"len",
"(",
"state",
".",
"PeerCertificates",
")",
... | // Default TLS peer name function - returns the CN of the certificate | [
"Default",
"TLS",
"peer",
"name",
"function",
"-",
"returns",
"the",
"CN",
"of",
"the",
"certificate"
] | a127d826d6c27489d377b3c080bd256d8f8093a6 | https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/server.go#L75-L82 | train |
mcuadros/go-syslog | server.go | ListenUDP | func (s *Server) ListenUDP(addr string) error {
udpAddr, err := net.ResolveUDPAddr("udp", addr)
if err != nil {
return err
}
connection, err := net.ListenUDP("udp", udpAddr)
if err != nil {
return err
}
connection.SetReadBuffer(datagramReadBufferSize)
s.connections = append(s.connections, connection)
return nil
} | go | func (s *Server) ListenUDP(addr string) error {
udpAddr, err := net.ResolveUDPAddr("udp", addr)
if err != nil {
return err
}
connection, err := net.ListenUDP("udp", udpAddr)
if err != nil {
return err
}
connection.SetReadBuffer(datagramReadBufferSize)
s.connections = append(s.connections, connection)
return nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"ListenUDP",
"(",
"addr",
"string",
")",
"error",
"{",
"udpAddr",
",",
"err",
":=",
"net",
".",
"ResolveUDPAddr",
"(",
"\"",
"\"",
",",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
... | //Configure the server for listen on an UDP addr | [
"Configure",
"the",
"server",
"for",
"listen",
"on",
"an",
"UDP",
"addr"
] | a127d826d6c27489d377b3c080bd256d8f8093a6 | https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/server.go#L85-L99 | train |
mcuadros/go-syslog | server.go | ListenUnixgram | func (s *Server) ListenUnixgram(addr string) error {
unixAddr, err := net.ResolveUnixAddr("unixgram", addr)
if err != nil {
return err
}
connection, err := net.ListenUnixgram("unixgram", unixAddr)
if err != nil {
return err
}
connection.SetReadBuffer(datagramReadBufferSize)
s.connections = append(s.connections, connection)
return nil
} | go | func (s *Server) ListenUnixgram(addr string) error {
unixAddr, err := net.ResolveUnixAddr("unixgram", addr)
if err != nil {
return err
}
connection, err := net.ListenUnixgram("unixgram", unixAddr)
if err != nil {
return err
}
connection.SetReadBuffer(datagramReadBufferSize)
s.connections = append(s.connections, connection)
return nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"ListenUnixgram",
"(",
"addr",
"string",
")",
"error",
"{",
"unixAddr",
",",
"err",
":=",
"net",
".",
"ResolveUnixAddr",
"(",
"\"",
"\"",
",",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
... | //Configure the server for listen on an unix socket | [
"Configure",
"the",
"server",
"for",
"listen",
"on",
"an",
"unix",
"socket"
] | a127d826d6c27489d377b3c080bd256d8f8093a6 | https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/server.go#L102-L116 | train |
mcuadros/go-syslog | server.go | ListenTCP | func (s *Server) ListenTCP(addr string) error {
tcpAddr, err := net.ResolveTCPAddr("tcp", addr)
if err != nil {
return err
}
listener, err := net.ListenTCP("tcp", tcpAddr)
if err != nil {
return err
}
s.doneTcp = make(chan bool)
s.listeners = append(s.listeners, listener)
return nil
} | go | func (s *Server) ListenTCP(addr string) error {
tcpAddr, err := net.ResolveTCPAddr("tcp", addr)
if err != nil {
return err
}
listener, err := net.ListenTCP("tcp", tcpAddr)
if err != nil {
return err
}
s.doneTcp = make(chan bool)
s.listeners = append(s.listeners, listener)
return nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"ListenTCP",
"(",
"addr",
"string",
")",
"error",
"{",
"tcpAddr",
",",
"err",
":=",
"net",
".",
"ResolveTCPAddr",
"(",
"\"",
"\"",
",",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
... | //Configure the server for listen on a TCP addr | [
"Configure",
"the",
"server",
"for",
"listen",
"on",
"a",
"TCP",
"addr"
] | a127d826d6c27489d377b3c080bd256d8f8093a6 | https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/server.go#L119-L133 | train |
mcuadros/go-syslog | server.go | ListenTCPTLS | func (s *Server) ListenTCPTLS(addr string, config *tls.Config) error {
listener, err := tls.Listen("tcp", addr, config)
if err != nil {
return err
}
s.doneTcp = make(chan bool)
s.listeners = append(s.listeners, listener)
return nil
} | go | func (s *Server) ListenTCPTLS(addr string, config *tls.Config) error {
listener, err := tls.Listen("tcp", addr, config)
if err != nil {
return err
}
s.doneTcp = make(chan bool)
s.listeners = append(s.listeners, listener)
return nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"ListenTCPTLS",
"(",
"addr",
"string",
",",
"config",
"*",
"tls",
".",
"Config",
")",
"error",
"{",
"listener",
",",
"err",
":=",
"tls",
".",
"Listen",
"(",
"\"",
"\"",
",",
"addr",
",",
"config",
")",
"\n",
... | //Configure the server for listen on a TCP addr for TLS | [
"Configure",
"the",
"server",
"for",
"listen",
"on",
"a",
"TCP",
"addr",
"for",
"TLS"
] | a127d826d6c27489d377b3c080bd256d8f8093a6 | https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/server.go#L136-L145 | train |
mcuadros/go-syslog | server.go | Boot | func (s *Server) Boot() error {
if s.format == nil {
return errors.New("please set a valid format")
}
if s.handler == nil {
return errors.New("please set a valid handler")
}
for _, listener := range s.listeners {
s.goAcceptConnection(listener)
}
if len(s.connections) > 0 {
s.goParseDatagrams()
}
for _, connection := range s.connections {
s.goReceiveDatagrams(connection)
}
return nil
} | go | func (s *Server) Boot() error {
if s.format == nil {
return errors.New("please set a valid format")
}
if s.handler == nil {
return errors.New("please set a valid handler")
}
for _, listener := range s.listeners {
s.goAcceptConnection(listener)
}
if len(s.connections) > 0 {
s.goParseDatagrams()
}
for _, connection := range s.connections {
s.goReceiveDatagrams(connection)
}
return nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"Boot",
"(",
")",
"error",
"{",
"if",
"s",
".",
"format",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"s",
".",
"handler",
"==",
"nil",
"{",
"return",
... | //Starts the server, all the go routines goes to live | [
"Starts",
"the",
"server",
"all",
"the",
"go",
"routines",
"goes",
"to",
"live"
] | a127d826d6c27489d377b3c080bd256d8f8093a6 | https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/server.go#L148-L170 | train |
mcuadros/go-syslog | server.go | Kill | func (s *Server) Kill() error {
for _, connection := range s.connections {
err := connection.Close()
if err != nil {
return err
}
}
for _, listener := range s.listeners {
err := listener.Close()
if err != nil {
return err
}
}
// Only need to close channel once to broadcast to all waiting
if s.doneTcp != nil {
close(s.doneTcp)
}
if s.datagramChannel != nil {
close(s.datagramChannel)
}
return nil
} | go | func (s *Server) Kill() error {
for _, connection := range s.connections {
err := connection.Close()
if err != nil {
return err
}
}
for _, listener := range s.listeners {
err := listener.Close()
if err != nil {
return err
}
}
// Only need to close channel once to broadcast to all waiting
if s.doneTcp != nil {
close(s.doneTcp)
}
if s.datagramChannel != nil {
close(s.datagramChannel)
}
return nil
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"Kill",
"(",
")",
"error",
"{",
"for",
"_",
",",
"connection",
":=",
"range",
"s",
".",
"connections",
"{",
"err",
":=",
"connection",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"e... | //Kill the server | [
"Kill",
"the",
"server"
] | a127d826d6c27489d377b3c080bd256d8f8093a6 | https://github.com/mcuadros/go-syslog/blob/a127d826d6c27489d377b3c080bd256d8f8093a6/server.go#L279-L301 | train |
cavaliercoder/grab | client.go | NewClient | func NewClient() *Client {
return &Client{
UserAgent: "grab",
HTTPClient: &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
},
},
}
} | go | func NewClient() *Client {
return &Client{
UserAgent: "grab",
HTTPClient: &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
},
},
}
} | [
"func",
"NewClient",
"(",
")",
"*",
"Client",
"{",
"return",
"&",
"Client",
"{",
"UserAgent",
":",
"\"",
"\"",
",",
"HTTPClient",
":",
"&",
"http",
".",
"Client",
"{",
"Transport",
":",
"&",
"http",
".",
"Transport",
"{",
"Proxy",
":",
"http",
".",
... | // NewClient returns a new file download Client, using default configuration. | [
"NewClient",
"returns",
"a",
"new",
"file",
"download",
"Client",
"using",
"default",
"configuration",
"."
] | a224b4097c01f213344b657c2886cd429d891812 | https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/client.go#L37-L46 | train |
cavaliercoder/grab | client.go | DoChannel | func (c *Client) DoChannel(reqch <-chan *Request, respch chan<- *Response) {
// TODO: enable cancelling of batch jobs
for req := range reqch {
resp := c.Do(req)
respch <- resp
<-resp.Done
}
} | go | func (c *Client) DoChannel(reqch <-chan *Request, respch chan<- *Response) {
// TODO: enable cancelling of batch jobs
for req := range reqch {
resp := c.Do(req)
respch <- resp
<-resp.Done
}
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"DoChannel",
"(",
"reqch",
"<-",
"chan",
"*",
"Request",
",",
"respch",
"chan",
"<-",
"*",
"Response",
")",
"{",
"// TODO: enable cancelling of batch jobs",
"for",
"req",
":=",
"range",
"reqch",
"{",
"resp",
":=",
"c",... | // DoChannel executes all requests sent through the given Request channel, one
// at a time, until it is closed by another goroutine. The caller is blocked
// until the Request channel is closed and all transfers have completed. All
// responses are sent through the given Response channel as soon as they are
// received from the remote servers and can be used to track the progress of
// each download.
//
// Slow Response receivers will cause a worker to block and therefore delay the
// start of the transfer for an already initiated connection - potentially
// causing a server timeout. It is the caller's responsibility to ensure a
// sufficient buffer size is used for the Response channel to prevent this.
//
// If an error occurs during any of the file transfers it will be accessible via
// the associated Response.Err function. | [
"DoChannel",
"executes",
"all",
"requests",
"sent",
"through",
"the",
"given",
"Request",
"channel",
"one",
"at",
"a",
"time",
"until",
"it",
"is",
"closed",
"by",
"another",
"goroutine",
".",
"The",
"caller",
"is",
"blocked",
"until",
"the",
"Request",
"cha... | a224b4097c01f213344b657c2886cd429d891812 | https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/client.go#L106-L113 | train |
cavaliercoder/grab | client.go | DoBatch | func (c *Client) DoBatch(workers int, requests ...*Request) <-chan *Response {
if workers < 1 {
workers = len(requests)
}
reqch := make(chan *Request, len(requests))
respch := make(chan *Response, len(requests))
wg := sync.WaitGroup{}
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
c.DoChannel(reqch, respch)
wg.Done()
}()
}
// queue requests
go func() {
for _, req := range requests {
reqch <- req
}
close(reqch)
wg.Wait()
close(respch)
}()
return respch
} | go | func (c *Client) DoBatch(workers int, requests ...*Request) <-chan *Response {
if workers < 1 {
workers = len(requests)
}
reqch := make(chan *Request, len(requests))
respch := make(chan *Response, len(requests))
wg := sync.WaitGroup{}
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
c.DoChannel(reqch, respch)
wg.Done()
}()
}
// queue requests
go func() {
for _, req := range requests {
reqch <- req
}
close(reqch)
wg.Wait()
close(respch)
}()
return respch
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"DoBatch",
"(",
"workers",
"int",
",",
"requests",
"...",
"*",
"Request",
")",
"<-",
"chan",
"*",
"Response",
"{",
"if",
"workers",
"<",
"1",
"{",
"workers",
"=",
"len",
"(",
"requests",
")",
"\n",
"}",
"\n",
... | // DoBatch executes all the given requests using the given number of concurrent
// workers. Control is passed back to the caller as soon as the workers are
// initiated.
//
// If the requested number of workers is less than one, a worker will be created
// for every request. I.e. all requests will be executed concurrently.
//
// If an error occurs during any of the file transfers it will be accessible via
// call to the associated Response.Err.
//
// The returned Response channel is closed only after all of the given Requests
// have completed, successfully or otherwise. | [
"DoBatch",
"executes",
"all",
"the",
"given",
"requests",
"using",
"the",
"given",
"number",
"of",
"concurrent",
"workers",
".",
"Control",
"is",
"passed",
"back",
"to",
"the",
"caller",
"as",
"soon",
"as",
"the",
"workers",
"are",
"initiated",
".",
"If",
... | a224b4097c01f213344b657c2886cd429d891812 | https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/client.go#L127-L152 | train |
cavaliercoder/grab | client.go | run | func (c *Client) run(resp *Response, f stateFunc) {
for {
select {
case <-resp.ctx.Done():
if resp.IsComplete() {
return
}
resp.err = resp.ctx.Err()
f = c.closeResponse
default:
// keep working
}
if f = f(resp); f == nil {
return
}
}
} | go | func (c *Client) run(resp *Response, f stateFunc) {
for {
select {
case <-resp.ctx.Done():
if resp.IsComplete() {
return
}
resp.err = resp.ctx.Err()
f = c.closeResponse
default:
// keep working
}
if f = f(resp); f == nil {
return
}
}
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"run",
"(",
"resp",
"*",
"Response",
",",
"f",
"stateFunc",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"<-",
"resp",
".",
"ctx",
".",
"Done",
"(",
")",
":",
"if",
"resp",
".",
"IsComplete",
"(",
")",
"{",... | // run calls the given stateFunc function and all subsequent returned stateFuncs
// until a stateFunc returns nil or the Response.ctx is canceled. Each stateFunc
// should mutate the state of the given Response until it has completed
// downloading or failed. | [
"run",
"calls",
"the",
"given",
"stateFunc",
"function",
"and",
"all",
"subsequent",
"returned",
"stateFuncs",
"until",
"a",
"stateFunc",
"returns",
"nil",
"or",
"the",
"Response",
".",
"ctx",
"is",
"canceled",
".",
"Each",
"stateFunc",
"should",
"mutate",
"th... | a224b4097c01f213344b657c2886cd429d891812 | https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/client.go#L162-L179 | train |
cavaliercoder/grab | client.go | statFileInfo | func (c *Client) statFileInfo(resp *Response) stateFunc {
if resp.Filename == "" {
return c.headRequest
}
fi, err := os.Stat(resp.Filename)
if err != nil {
if os.IsNotExist(err) {
return c.headRequest
}
resp.err = err
return c.closeResponse
}
if fi.IsDir() {
resp.Filename = ""
return c.headRequest
}
resp.fi = fi
return c.validateLocal
} | go | func (c *Client) statFileInfo(resp *Response) stateFunc {
if resp.Filename == "" {
return c.headRequest
}
fi, err := os.Stat(resp.Filename)
if err != nil {
if os.IsNotExist(err) {
return c.headRequest
}
resp.err = err
return c.closeResponse
}
if fi.IsDir() {
resp.Filename = ""
return c.headRequest
}
resp.fi = fi
return c.validateLocal
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"statFileInfo",
"(",
"resp",
"*",
"Response",
")",
"stateFunc",
"{",
"if",
"resp",
".",
"Filename",
"==",
"\"",
"\"",
"{",
"return",
"c",
".",
"headRequest",
"\n",
"}",
"\n",
"fi",
",",
"err",
":=",
"os",
".",
... | // statFileInfo retrieves FileInfo for any local file matching
// Response.Filename.
//
// If the file does not exist, is a directory, or its name is unknown the next
// stateFunc is headRequest.
//
// If the file exists, Response.fi is set and the next stateFunc is
// validateLocal.
//
// If an error occurs, the next stateFunc is closeResponse. | [
"statFileInfo",
"retrieves",
"FileInfo",
"for",
"any",
"local",
"file",
"matching",
"Response",
".",
"Filename",
".",
"If",
"the",
"file",
"does",
"not",
"exist",
"is",
"a",
"directory",
"or",
"its",
"name",
"is",
"unknown",
"the",
"next",
"stateFunc",
"is",... | a224b4097c01f213344b657c2886cd429d891812 | https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/client.go#L191-L209 | train |
cavaliercoder/grab | client.go | validateLocal | func (c *Client) validateLocal(resp *Response) stateFunc {
if resp.Request.SkipExisting {
resp.err = ErrFileExists
return c.closeResponse
}
// determine expected file size
size := resp.Request.Size
if size == 0 && resp.HTTPResponse != nil {
size = resp.HTTPResponse.ContentLength
}
if size == 0 {
return c.headRequest
}
if size == resp.fi.Size() {
resp.DidResume = true
resp.bytesResumed = resp.fi.Size()
return c.checksumFile
}
if resp.Request.NoResume {
return c.getRequest
}
if size < resp.fi.Size() {
resp.err = ErrBadLength
return c.closeResponse
}
if resp.CanResume {
resp.Request.HTTPRequest.Header.Set(
"Range",
fmt.Sprintf("bytes=%d-", resp.fi.Size()))
resp.DidResume = true
resp.bytesResumed = resp.fi.Size()
return c.getRequest
}
return c.headRequest
} | go | func (c *Client) validateLocal(resp *Response) stateFunc {
if resp.Request.SkipExisting {
resp.err = ErrFileExists
return c.closeResponse
}
// determine expected file size
size := resp.Request.Size
if size == 0 && resp.HTTPResponse != nil {
size = resp.HTTPResponse.ContentLength
}
if size == 0 {
return c.headRequest
}
if size == resp.fi.Size() {
resp.DidResume = true
resp.bytesResumed = resp.fi.Size()
return c.checksumFile
}
if resp.Request.NoResume {
return c.getRequest
}
if size < resp.fi.Size() {
resp.err = ErrBadLength
return c.closeResponse
}
if resp.CanResume {
resp.Request.HTTPRequest.Header.Set(
"Range",
fmt.Sprintf("bytes=%d-", resp.fi.Size()))
resp.DidResume = true
resp.bytesResumed = resp.fi.Size()
return c.getRequest
}
return c.headRequest
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"validateLocal",
"(",
"resp",
"*",
"Response",
")",
"stateFunc",
"{",
"if",
"resp",
".",
"Request",
".",
"SkipExisting",
"{",
"resp",
".",
"err",
"=",
"ErrFileExists",
"\n",
"return",
"c",
".",
"closeResponse",
"\n",... | // validateLocal compares a local copy of the downloaded file to the remote
// file.
//
// An error is returned if the local file is larger than the remote file, or
// Request.SkipExisting is true.
//
// If the existing file matches the length of the remote file, the next
// stateFunc is checksumFile.
//
// If the local file is smaller than the remote file and the remote server is
// known to support ranged requests, the next stateFunc is getRequest. | [
"validateLocal",
"compares",
"a",
"local",
"copy",
"of",
"the",
"downloaded",
"file",
"to",
"the",
"remote",
"file",
".",
"An",
"error",
"is",
"returned",
"if",
"the",
"local",
"file",
"is",
"larger",
"than",
"the",
"remote",
"file",
"or",
"Request",
".",
... | a224b4097c01f213344b657c2886cd429d891812 | https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/client.go#L222-L261 | train |
cavaliercoder/grab | client.go | doHTTPRequest | func (c *Client) doHTTPRequest(req *http.Request) (*http.Response, error) {
if c.UserAgent != "" && req.Header.Get("User-Agent") == "" {
req.Header.Set("User-Agent", c.UserAgent)
}
return c.HTTPClient.Do(req)
} | go | func (c *Client) doHTTPRequest(req *http.Request) (*http.Response, error) {
if c.UserAgent != "" && req.Header.Get("User-Agent") == "" {
req.Header.Set("User-Agent", c.UserAgent)
}
return c.HTTPClient.Do(req)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"doHTTPRequest",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"if",
"c",
".",
"UserAgent",
"!=",
"\"",
"\"",
"&&",
"req",
".",
"Header",
".",
"Get",... | // doHTTPRequest sends a HTTP Request and returns the response | [
"doHTTPRequest",
"sends",
"a",
"HTTP",
"Request",
"and",
"returns",
"the",
"response"
] | a224b4097c01f213344b657c2886cd429d891812 | https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/client.go#L293-L298 | train |
cavaliercoder/grab | client.go | openWriter | func (c *Client) openWriter(resp *Response) stateFunc {
if !resp.Request.NoCreateDirectories {
resp.err = mkdirp(resp.Filename)
if resp.err != nil {
return c.closeResponse
}
}
// compute write flags
flag := os.O_CREATE | os.O_WRONLY
if resp.fi != nil {
if resp.DidResume {
flag = os.O_APPEND | os.O_WRONLY
} else {
flag = os.O_TRUNC | os.O_WRONLY
}
}
// open file
f, err := os.OpenFile(resp.Filename, flag, 0644)
if err != nil {
resp.err = err
return c.closeResponse
}
resp.writer = f
// seek to start or end
whence := os.SEEK_SET
if resp.bytesResumed > 0 {
whence = os.SEEK_END
}
_, resp.err = f.Seek(0, whence)
if resp.err != nil {
return c.closeResponse
}
// init transfer
if resp.bufferSize < 1 {
resp.bufferSize = 32 * 1024
}
b := make([]byte, resp.bufferSize)
resp.transfer = newTransfer(
resp.Request.Context(),
resp.Request.RateLimiter,
resp.writer,
resp.HTTPResponse.Body,
b)
// next step is copyFile, but this will be called later in another goroutine
return nil
} | go | func (c *Client) openWriter(resp *Response) stateFunc {
if !resp.Request.NoCreateDirectories {
resp.err = mkdirp(resp.Filename)
if resp.err != nil {
return c.closeResponse
}
}
// compute write flags
flag := os.O_CREATE | os.O_WRONLY
if resp.fi != nil {
if resp.DidResume {
flag = os.O_APPEND | os.O_WRONLY
} else {
flag = os.O_TRUNC | os.O_WRONLY
}
}
// open file
f, err := os.OpenFile(resp.Filename, flag, 0644)
if err != nil {
resp.err = err
return c.closeResponse
}
resp.writer = f
// seek to start or end
whence := os.SEEK_SET
if resp.bytesResumed > 0 {
whence = os.SEEK_END
}
_, resp.err = f.Seek(0, whence)
if resp.err != nil {
return c.closeResponse
}
// init transfer
if resp.bufferSize < 1 {
resp.bufferSize = 32 * 1024
}
b := make([]byte, resp.bufferSize)
resp.transfer = newTransfer(
resp.Request.Context(),
resp.Request.RateLimiter,
resp.writer,
resp.HTTPResponse.Body,
b)
// next step is copyFile, but this will be called later in another goroutine
return nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"openWriter",
"(",
"resp",
"*",
"Response",
")",
"stateFunc",
"{",
"if",
"!",
"resp",
".",
"Request",
".",
"NoCreateDirectories",
"{",
"resp",
".",
"err",
"=",
"mkdirp",
"(",
"resp",
".",
"Filename",
")",
"\n",
"... | // openWriter opens the destination file for writing and seeks to the location
// from whence the file transfer will resume.
//
// Requires that Response.Filename and resp.DidResume are already be set. | [
"openWriter",
"opens",
"the",
"destination",
"file",
"for",
"writing",
"and",
"seeks",
"to",
"the",
"location",
"from",
"whence",
"the",
"file",
"transfer",
"will",
"resume",
".",
"Requires",
"that",
"Response",
".",
"Filename",
"and",
"resp",
".",
"DidResume"... | a224b4097c01f213344b657c2886cd429d891812 | https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/client.go#L387-L437 | train |
cavaliercoder/grab | client.go | closeResponse | func (c *Client) closeResponse(resp *Response) stateFunc {
if resp.IsComplete() {
panic("response already closed")
}
resp.fi = nil
closeWriter(resp)
resp.closeResponseBody()
resp.End = time.Now()
close(resp.Done)
if resp.cancel != nil {
resp.cancel()
}
return nil
} | go | func (c *Client) closeResponse(resp *Response) stateFunc {
if resp.IsComplete() {
panic("response already closed")
}
resp.fi = nil
closeWriter(resp)
resp.closeResponseBody()
resp.End = time.Now()
close(resp.Done)
if resp.cancel != nil {
resp.cancel()
}
return nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"closeResponse",
"(",
"resp",
"*",
"Response",
")",
"stateFunc",
"{",
"if",
"resp",
".",
"IsComplete",
"(",
")",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"resp",
".",
"fi",
"=",
"nil",
"\n",
"cl... | // close finalizes the Response | [
"close",
"finalizes",
"the",
"Response"
] | a224b4097c01f213344b657c2886cd429d891812 | https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/client.go#L489-L505 | train |
cavaliercoder/grab | response.go | Progress | func (c *Response) Progress() float64 {
if c.Size == 0 {
return 0
}
return float64(c.BytesComplete()) / float64(c.Size)
} | go | func (c *Response) Progress() float64 {
if c.Size == 0 {
return 0
}
return float64(c.BytesComplete()) / float64(c.Size)
} | [
"func",
"(",
"c",
"*",
"Response",
")",
"Progress",
"(",
")",
"float64",
"{",
"if",
"c",
".",
"Size",
"==",
"0",
"{",
"return",
"0",
"\n",
"}",
"\n",
"return",
"float64",
"(",
"c",
".",
"BytesComplete",
"(",
")",
")",
"/",
"float64",
"(",
"c",
... | // Progress returns the ratio of total bytes that have been downloaded. Multiply
// the returned value by 100 to return the percentage completed. | [
"Progress",
"returns",
"the",
"ratio",
"of",
"total",
"bytes",
"that",
"have",
"been",
"downloaded",
".",
"Multiply",
"the",
"returned",
"value",
"by",
"100",
"to",
"return",
"the",
"percentage",
"completed",
"."
] | a224b4097c01f213344b657c2886cd429d891812 | https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/response.go#L141-L146 | train |
cavaliercoder/grab | response.go | Duration | func (c *Response) Duration() time.Duration {
if c.IsComplete() {
return c.End.Sub(c.Start)
}
return time.Now().Sub(c.Start)
} | go | func (c *Response) Duration() time.Duration {
if c.IsComplete() {
return c.End.Sub(c.Start)
}
return time.Now().Sub(c.Start)
} | [
"func",
"(",
"c",
"*",
"Response",
")",
"Duration",
"(",
")",
"time",
".",
"Duration",
"{",
"if",
"c",
".",
"IsComplete",
"(",
")",
"{",
"return",
"c",
".",
"End",
".",
"Sub",
"(",
"c",
".",
"Start",
")",
"\n",
"}",
"\n\n",
"return",
"time",
".... | // Duration returns the duration of a file transfer. If the transfer is in
// process, the duration will be between now and the start of the transfer. If
// the transfer is complete, the duration will be between the start and end of
// the completed transfer process. | [
"Duration",
"returns",
"the",
"duration",
"of",
"a",
"file",
"transfer",
".",
"If",
"the",
"transfer",
"is",
"in",
"process",
"the",
"duration",
"will",
"be",
"between",
"now",
"and",
"the",
"start",
"of",
"the",
"transfer",
".",
"If",
"the",
"transfer",
... | a224b4097c01f213344b657c2886cd429d891812 | https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/response.go#L152-L158 | train |
cavaliercoder/grab | response.go | ETA | func (c *Response) ETA() time.Time {
if c.IsComplete() {
return c.End
}
bt := c.BytesComplete()
bps := c.transfer.BPS()
if bps == 0 {
return time.Time{}
}
secs := float64(c.Size-bt) / bps
return time.Now().Add(time.Duration(secs) * time.Second)
} | go | func (c *Response) ETA() time.Time {
if c.IsComplete() {
return c.End
}
bt := c.BytesComplete()
bps := c.transfer.BPS()
if bps == 0 {
return time.Time{}
}
secs := float64(c.Size-bt) / bps
return time.Now().Add(time.Duration(secs) * time.Second)
} | [
"func",
"(",
"c",
"*",
"Response",
")",
"ETA",
"(",
")",
"time",
".",
"Time",
"{",
"if",
"c",
".",
"IsComplete",
"(",
")",
"{",
"return",
"c",
".",
"End",
"\n",
"}",
"\n",
"bt",
":=",
"c",
".",
"BytesComplete",
"(",
")",
"\n",
"bps",
":=",
"c... | // ETA returns the estimated time at which the the download will complete, given
// the current BytesPerSecond. If the transfer has already completed, the actual
// end time will be returned. | [
"ETA",
"returns",
"the",
"estimated",
"time",
"at",
"which",
"the",
"the",
"download",
"will",
"complete",
"given",
"the",
"current",
"BytesPerSecond",
".",
"If",
"the",
"transfer",
"has",
"already",
"completed",
"the",
"actual",
"end",
"time",
"will",
"be",
... | a224b4097c01f213344b657c2886cd429d891812 | https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/response.go#L163-L174 | train |
cavaliercoder/grab | bps/bps.go | Watch | func Watch(ctx context.Context, g Gauge, f SampleFunc, interval time.Duration) {
g.Sample(time.Now(), f())
t := time.NewTicker(interval)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case now := <-t.C:
g.Sample(now, f())
}
}
} | go | func Watch(ctx context.Context, g Gauge, f SampleFunc, interval time.Duration) {
g.Sample(time.Now(), f())
t := time.NewTicker(interval)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case now := <-t.C:
g.Sample(now, f())
}
}
} | [
"func",
"Watch",
"(",
"ctx",
"context",
".",
"Context",
",",
"g",
"Gauge",
",",
"f",
"SampleFunc",
",",
"interval",
"time",
".",
"Duration",
")",
"{",
"g",
".",
"Sample",
"(",
"time",
".",
"Now",
"(",
")",
",",
"f",
"(",
")",
")",
"\n",
"t",
":... | // Watch will periodically call the given SampleFunc to sample the progress of
// a monitored stream and update the given gauge. SampleFunc should return the
// total number of bytes transferred by the stream since it started.
//
// Watch is a blocking call and should typically be called in a new goroutine.
// To prevent the goroutine from leaking, make sure to cancel the given context
// once the stream is completed or canceled. | [
"Watch",
"will",
"periodically",
"call",
"the",
"given",
"SampleFunc",
"to",
"sample",
"the",
"progress",
"of",
"a",
"monitored",
"stream",
"and",
"update",
"the",
"given",
"gauge",
".",
"SampleFunc",
"should",
"return",
"the",
"total",
"number",
"of",
"bytes"... | a224b4097c01f213344b657c2886cd429d891812 | https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/bps/bps.go#L42-L54 | train |
cavaliercoder/grab | util.go | setLastModified | func setLastModified(resp *http.Response, filename string) error {
// https://tools.ietf.org/html/rfc7232#section-2.2
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified
header := resp.Header.Get("Last-Modified")
if header == "" {
return nil
}
lastmod, err := time.Parse(http.TimeFormat, header)
if err != nil {
return nil
}
return os.Chtimes(filename, lastmod, lastmod)
} | go | func setLastModified(resp *http.Response, filename string) error {
// https://tools.ietf.org/html/rfc7232#section-2.2
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified
header := resp.Header.Get("Last-Modified")
if header == "" {
return nil
}
lastmod, err := time.Parse(http.TimeFormat, header)
if err != nil {
return nil
}
return os.Chtimes(filename, lastmod, lastmod)
} | [
"func",
"setLastModified",
"(",
"resp",
"*",
"http",
".",
"Response",
",",
"filename",
"string",
")",
"error",
"{",
"// https://tools.ietf.org/html/rfc7232#section-2.2",
"// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified",
"header",
":=",
"resp",
".",
... | // setLastModified sets the last modified timestamp of a local file according to
// the Last-Modified header returned by a remote server. | [
"setLastModified",
"sets",
"the",
"last",
"modified",
"timestamp",
"of",
"a",
"local",
"file",
"according",
"to",
"the",
"Last",
"-",
"Modified",
"header",
"returned",
"by",
"a",
"remote",
"server",
"."
] | a224b4097c01f213344b657c2886cd429d891812 | https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/util.go#L18-L30 | train |
cavaliercoder/grab | util.go | mkdirp | func mkdirp(path string) error {
dir := filepath.Dir(path)
if fi, err := os.Stat(dir); err != nil {
if !os.IsNotExist(err) {
return fmt.Errorf("error checking destination directory: %v", err)
}
if err := os.MkdirAll(dir, 0755); err != nil {
return fmt.Errorf("error creating destination directory: %v", err)
}
} else if !fi.IsDir() {
panic("destination path is not directory")
}
return nil
} | go | func mkdirp(path string) error {
dir := filepath.Dir(path)
if fi, err := os.Stat(dir); err != nil {
if !os.IsNotExist(err) {
return fmt.Errorf("error checking destination directory: %v", err)
}
if err := os.MkdirAll(dir, 0755); err != nil {
return fmt.Errorf("error creating destination directory: %v", err)
}
} else if !fi.IsDir() {
panic("destination path is not directory")
}
return nil
} | [
"func",
"mkdirp",
"(",
"path",
"string",
")",
"error",
"{",
"dir",
":=",
"filepath",
".",
"Dir",
"(",
"path",
")",
"\n",
"if",
"fi",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"dir",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"!",
"os",
".",
"Is... | // mkdirp creates all missing parent directories for the destination file path. | [
"mkdirp",
"creates",
"all",
"missing",
"parent",
"directories",
"for",
"the",
"destination",
"file",
"path",
"."
] | a224b4097c01f213344b657c2886cd429d891812 | https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/util.go#L33-L46 | train |
cavaliercoder/grab | util.go | guessFilename | func guessFilename(resp *http.Response) (string, error) {
filename := resp.Request.URL.Path
if cd := resp.Header.Get("Content-Disposition"); cd != "" {
if _, params, err := mime.ParseMediaType(cd); err == nil {
filename = params["filename"]
}
}
// sanitize
if filename == "" || strings.HasSuffix(filename, "/") || strings.Contains(filename, "\x00") {
return "", ErrNoFilename
}
filename = filepath.Base(path.Clean("/" + filename))
if filename == "" || filename == "." || filename == "/" {
return "", ErrNoFilename
}
return filename, nil
} | go | func guessFilename(resp *http.Response) (string, error) {
filename := resp.Request.URL.Path
if cd := resp.Header.Get("Content-Disposition"); cd != "" {
if _, params, err := mime.ParseMediaType(cd); err == nil {
filename = params["filename"]
}
}
// sanitize
if filename == "" || strings.HasSuffix(filename, "/") || strings.Contains(filename, "\x00") {
return "", ErrNoFilename
}
filename = filepath.Base(path.Clean("/" + filename))
if filename == "" || filename == "." || filename == "/" {
return "", ErrNoFilename
}
return filename, nil
} | [
"func",
"guessFilename",
"(",
"resp",
"*",
"http",
".",
"Response",
")",
"(",
"string",
",",
"error",
")",
"{",
"filename",
":=",
"resp",
".",
"Request",
".",
"URL",
".",
"Path",
"\n",
"if",
"cd",
":=",
"resp",
".",
"Header",
".",
"Get",
"(",
"\"",... | // guessFilename returns a filename for the given http.Response. If none can be
// determined ErrNoFilename is returned. | [
"guessFilename",
"returns",
"a",
"filename",
"for",
"the",
"given",
"http",
".",
"Response",
".",
"If",
"none",
"can",
"be",
"determined",
"ErrNoFilename",
"is",
"returned",
"."
] | a224b4097c01f213344b657c2886cd429d891812 | https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/util.go#L50-L69 | train |
cavaliercoder/grab | util.go | checksum | func checksum(ctx context.Context, filename string, h hash.Hash) (b []byte, err error) {
var f *os.File
f, err = os.Open(filename)
if err != nil {
return
}
defer func() {
err = f.Close()
}()
t := newTransfer(ctx, nil, h, f, nil)
if _, err = t.copy(); err != nil {
return
}
b = h.Sum(nil)
return
} | go | func checksum(ctx context.Context, filename string, h hash.Hash) (b []byte, err error) {
var f *os.File
f, err = os.Open(filename)
if err != nil {
return
}
defer func() {
err = f.Close()
}()
t := newTransfer(ctx, nil, h, f, nil)
if _, err = t.copy(); err != nil {
return
}
b = h.Sum(nil)
return
} | [
"func",
"checksum",
"(",
"ctx",
"context",
".",
"Context",
",",
"filename",
"string",
",",
"h",
"hash",
".",
"Hash",
")",
"(",
"b",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"var",
"f",
"*",
"os",
".",
"File",
"\n",
"f",
",",
"err",
"=",... | // checksum returns a hash of the given file, using the given hash algorithm. | [
"checksum",
"returns",
"a",
"hash",
"of",
"the",
"given",
"file",
"using",
"the",
"given",
"hash",
"algorithm",
"."
] | a224b4097c01f213344b657c2886cd429d891812 | https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/util.go#L72-L89 | train |
cavaliercoder/grab | grabui/console_client.go | refresh | func (c *ConsoleClient) refresh() {
// clear lines for incomplete downloads
if c.inProgress > 0 {
fmt.Printf("\033[%dA\033[K", c.inProgress)
}
// print newly completed downloads
for i, resp := range c.responses {
if resp != nil && resp.IsComplete() {
if resp.Err() != nil {
c.failed++
fmt.Fprintf(os.Stderr, "Error downloading %s: %v\n",
resp.Request.URL(),
resp.Err())
} else {
c.succeeded++
fmt.Printf("Finished %s %s / %s (%d%%)\n",
resp.Filename,
byteString(resp.BytesComplete()),
byteString(resp.Size),
int(100*resp.Progress()))
}
c.responses[i] = nil
}
}
// print progress for incomplete downloads
c.inProgress = 0
for _, resp := range c.responses {
if resp != nil {
fmt.Printf("Downloading %s %s / %s (%d%%) - %s ETA: %s \033[K\n",
resp.Filename,
byteString(resp.BytesComplete()),
byteString(resp.Size),
int(100*resp.Progress()),
bpsString(resp.BytesPerSecond()),
etaString(resp.ETA()))
c.inProgress++
}
}
} | go | func (c *ConsoleClient) refresh() {
// clear lines for incomplete downloads
if c.inProgress > 0 {
fmt.Printf("\033[%dA\033[K", c.inProgress)
}
// print newly completed downloads
for i, resp := range c.responses {
if resp != nil && resp.IsComplete() {
if resp.Err() != nil {
c.failed++
fmt.Fprintf(os.Stderr, "Error downloading %s: %v\n",
resp.Request.URL(),
resp.Err())
} else {
c.succeeded++
fmt.Printf("Finished %s %s / %s (%d%%)\n",
resp.Filename,
byteString(resp.BytesComplete()),
byteString(resp.Size),
int(100*resp.Progress()))
}
c.responses[i] = nil
}
}
// print progress for incomplete downloads
c.inProgress = 0
for _, resp := range c.responses {
if resp != nil {
fmt.Printf("Downloading %s %s / %s (%d%%) - %s ETA: %s \033[K\n",
resp.Filename,
byteString(resp.BytesComplete()),
byteString(resp.Size),
int(100*resp.Progress()),
bpsString(resp.BytesPerSecond()),
etaString(resp.ETA()))
c.inProgress++
}
}
} | [
"func",
"(",
"c",
"*",
"ConsoleClient",
")",
"refresh",
"(",
")",
"{",
"// clear lines for incomplete downloads",
"if",
"c",
".",
"inProgress",
">",
"0",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\033",
"\\033",
"\"",
",",
"c",
".",
"inProgress",
")",
"\n"... | // refresh prints the progress of all downloads to the terminal | [
"refresh",
"prints",
"the",
"progress",
"of",
"all",
"downloads",
"to",
"the",
"terminal"
] | a224b4097c01f213344b657c2886cd429d891812 | https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/grabui/console_client.go#L86-L126 | train |
cavaliercoder/grab | request.go | NewRequest | func NewRequest(dst, urlStr string) (*Request, error) {
if dst == "" {
dst = "."
}
req, err := http.NewRequest("GET", urlStr, nil)
if err != nil {
return nil, err
}
return &Request{
HTTPRequest: req,
Filename: dst,
}, nil
} | go | func NewRequest(dst, urlStr string) (*Request, error) {
if dst == "" {
dst = "."
}
req, err := http.NewRequest("GET", urlStr, nil)
if err != nil {
return nil, err
}
return &Request{
HTTPRequest: req,
Filename: dst,
}, nil
} | [
"func",
"NewRequest",
"(",
"dst",
",",
"urlStr",
"string",
")",
"(",
"*",
"Request",
",",
"error",
")",
"{",
"if",
"dst",
"==",
"\"",
"\"",
"{",
"dst",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"... | // NewRequest returns a new file transfer Request suitable for use with
// Client.Do. | [
"NewRequest",
"returns",
"a",
"new",
"file",
"transfer",
"Request",
"suitable",
"for",
"use",
"with",
"Client",
".",
"Do",
"."
] | a224b4097c01f213344b657c2886cd429d891812 | https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/request.go#L108-L120 | train |
cavaliercoder/grab | request.go | WithContext | func (r *Request) WithContext(ctx context.Context) *Request {
if ctx == nil {
panic("nil context")
}
r2 := new(Request)
*r2 = *r
r2.ctx = ctx
r2.HTTPRequest = r2.HTTPRequest.WithContext(ctx)
return r2
} | go | func (r *Request) WithContext(ctx context.Context) *Request {
if ctx == nil {
panic("nil context")
}
r2 := new(Request)
*r2 = *r
r2.ctx = ctx
r2.HTTPRequest = r2.HTTPRequest.WithContext(ctx)
return r2
} | [
"func",
"(",
"r",
"*",
"Request",
")",
"WithContext",
"(",
"ctx",
"context",
".",
"Context",
")",
"*",
"Request",
"{",
"if",
"ctx",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"r2",
":=",
"new",
"(",
"Request",
")",
"\n",
... | // WithContext returns a shallow copy of r with its context changed
// to ctx. The provided ctx must be non-nil. | [
"WithContext",
"returns",
"a",
"shallow",
"copy",
"of",
"r",
"with",
"its",
"context",
"changed",
"to",
"ctx",
".",
"The",
"provided",
"ctx",
"must",
"be",
"non",
"-",
"nil",
"."
] | a224b4097c01f213344b657c2886cd429d891812 | https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/request.go#L139-L148 | train |
cavaliercoder/grab | request.go | SetChecksum | func (r *Request) SetChecksum(h hash.Hash, sum []byte, deleteOnError bool) {
r.hash = h
r.checksum = sum
r.deleteOnError = deleteOnError
} | go | func (r *Request) SetChecksum(h hash.Hash, sum []byte, deleteOnError bool) {
r.hash = h
r.checksum = sum
r.deleteOnError = deleteOnError
} | [
"func",
"(",
"r",
"*",
"Request",
")",
"SetChecksum",
"(",
"h",
"hash",
".",
"Hash",
",",
"sum",
"[",
"]",
"byte",
",",
"deleteOnError",
"bool",
")",
"{",
"r",
".",
"hash",
"=",
"h",
"\n",
"r",
".",
"checksum",
"=",
"sum",
"\n",
"r",
".",
"dele... | // SetChecksum sets the desired hashing algorithm and checksum value to validate
// a downloaded file. Once the download is complete, the given hashing algorithm
// will be used to compute the actual checksum of the downloaded file. If the
// checksums do not match, an error will be returned by the associated
// Response.Err method.
//
// If deleteOnError is true, the downloaded file will be deleted automatically
// if it fails checksum validation.
//
// To prevent corruption of the computed checksum, the given hash must not be
// used by any other request or goroutines.
//
// To disable checksum validation, call SetChecksum with a nil hash. | [
"SetChecksum",
"sets",
"the",
"desired",
"hashing",
"algorithm",
"and",
"checksum",
"value",
"to",
"validate",
"a",
"downloaded",
"file",
".",
"Once",
"the",
"download",
"is",
"complete",
"the",
"given",
"hashing",
"algorithm",
"will",
"be",
"used",
"to",
"com... | a224b4097c01f213344b657c2886cd429d891812 | https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/request.go#L168-L172 | train |
cavaliercoder/grab | transfer.go | copy | func (c *transfer) copy() (written int64, err error) {
// maintain a bps gauge in another goroutine
ctx, cancel := context.WithCancel(c.ctx)
defer cancel()
go bps.Watch(ctx, c.gauge, c.N, time.Second)
// start the transfer
if c.b == nil {
c.b = make([]byte, 32*1024)
}
for {
select {
case <-c.ctx.Done():
err = c.ctx.Err()
return
default:
// keep working
}
nr, er := c.r.Read(c.b)
if nr > 0 {
nw, ew := c.w.Write(c.b[0:nr])
if nw > 0 {
written += int64(nw)
atomic.StoreInt64(&c.n, written)
}
if ew != nil {
err = ew
break
}
if nr != nw {
err = io.ErrShortWrite
break
}
// wait for rate limiter
if c.lim != nil {
err = c.lim.WaitN(c.ctx, nr)
if err != nil {
return
}
}
}
if er != nil {
if er != io.EOF {
err = er
}
break
}
}
return written, err
} | go | func (c *transfer) copy() (written int64, err error) {
// maintain a bps gauge in another goroutine
ctx, cancel := context.WithCancel(c.ctx)
defer cancel()
go bps.Watch(ctx, c.gauge, c.N, time.Second)
// start the transfer
if c.b == nil {
c.b = make([]byte, 32*1024)
}
for {
select {
case <-c.ctx.Done():
err = c.ctx.Err()
return
default:
// keep working
}
nr, er := c.r.Read(c.b)
if nr > 0 {
nw, ew := c.w.Write(c.b[0:nr])
if nw > 0 {
written += int64(nw)
atomic.StoreInt64(&c.n, written)
}
if ew != nil {
err = ew
break
}
if nr != nw {
err = io.ErrShortWrite
break
}
// wait for rate limiter
if c.lim != nil {
err = c.lim.WaitN(c.ctx, nr)
if err != nil {
return
}
}
}
if er != nil {
if er != io.EOF {
err = er
}
break
}
}
return written, err
} | [
"func",
"(",
"c",
"*",
"transfer",
")",
"copy",
"(",
")",
"(",
"written",
"int64",
",",
"err",
"error",
")",
"{",
"// maintain a bps gauge in another goroutine",
"ctx",
",",
"cancel",
":=",
"context",
".",
"WithCancel",
"(",
"c",
".",
"ctx",
")",
"\n",
"... | // copy behaves similarly to io.CopyBuffer except that it checks for cancelation
// of the given context.Context, reports progress in a thread-safe manner and
// tracks the transfer rate. | [
"copy",
"behaves",
"similarly",
"to",
"io",
".",
"CopyBuffer",
"except",
"that",
"it",
"checks",
"for",
"cancelation",
"of",
"the",
"given",
"context",
".",
"Context",
"reports",
"progress",
"in",
"a",
"thread",
"-",
"safe",
"manner",
"and",
"tracks",
"the",... | a224b4097c01f213344b657c2886cd429d891812 | https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/transfer.go#L36-L85 | train |
cavaliercoder/grab | transfer.go | N | func (c *transfer) N() (n int64) {
if c == nil {
return 0
}
n = atomic.LoadInt64(&c.n)
return
} | go | func (c *transfer) N() (n int64) {
if c == nil {
return 0
}
n = atomic.LoadInt64(&c.n)
return
} | [
"func",
"(",
"c",
"*",
"transfer",
")",
"N",
"(",
")",
"(",
"n",
"int64",
")",
"{",
"if",
"c",
"==",
"nil",
"{",
"return",
"0",
"\n",
"}",
"\n",
"n",
"=",
"atomic",
".",
"LoadInt64",
"(",
"&",
"c",
".",
"n",
")",
"\n",
"return",
"\n",
"}"
] | // N returns the number of bytes transferred. | [
"N",
"returns",
"the",
"number",
"of",
"bytes",
"transferred",
"."
] | a224b4097c01f213344b657c2886cd429d891812 | https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/transfer.go#L88-L94 | train |
cavaliercoder/grab | transfer.go | BPS | func (c *transfer) BPS() (bps float64) {
if c == nil || c.gauge == nil {
return 0
}
return c.gauge.BPS()
} | go | func (c *transfer) BPS() (bps float64) {
if c == nil || c.gauge == nil {
return 0
}
return c.gauge.BPS()
} | [
"func",
"(",
"c",
"*",
"transfer",
")",
"BPS",
"(",
")",
"(",
"bps",
"float64",
")",
"{",
"if",
"c",
"==",
"nil",
"||",
"c",
".",
"gauge",
"==",
"nil",
"{",
"return",
"0",
"\n",
"}",
"\n",
"return",
"c",
".",
"gauge",
".",
"BPS",
"(",
")",
... | // BPS returns the current bytes per second transfer rate using a simple moving
// average. | [
"BPS",
"returns",
"the",
"current",
"bytes",
"per",
"second",
"transfer",
"rate",
"using",
"a",
"simple",
"moving",
"average",
"."
] | a224b4097c01f213344b657c2886cd429d891812 | https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/transfer.go#L98-L103 | train |
cavaliercoder/grab | grab.go | GetBatch | func GetBatch(workers int, dst string, urlStrs ...string) (<-chan *Response, error) {
fi, err := os.Stat(dst)
if err != nil {
return nil, err
}
if !fi.IsDir() {
return nil, fmt.Errorf("destination is not a directory")
}
reqs := make([]*Request, len(urlStrs))
for i := 0; i < len(urlStrs); i++ {
req, err := NewRequest(dst, urlStrs[i])
if err != nil {
return nil, err
}
reqs[i] = req
}
ch := DefaultClient.DoBatch(workers, reqs...)
return ch, nil
} | go | func GetBatch(workers int, dst string, urlStrs ...string) (<-chan *Response, error) {
fi, err := os.Stat(dst)
if err != nil {
return nil, err
}
if !fi.IsDir() {
return nil, fmt.Errorf("destination is not a directory")
}
reqs := make([]*Request, len(urlStrs))
for i := 0; i < len(urlStrs); i++ {
req, err := NewRequest(dst, urlStrs[i])
if err != nil {
return nil, err
}
reqs[i] = req
}
ch := DefaultClient.DoBatch(workers, reqs...)
return ch, nil
} | [
"func",
"GetBatch",
"(",
"workers",
"int",
",",
"dst",
"string",
",",
"urlStrs",
"...",
"string",
")",
"(",
"<-",
"chan",
"*",
"Response",
",",
"error",
")",
"{",
"fi",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"dst",
")",
"\n",
"if",
"err",
"!="... | // GetBatch sends multiple HTTP requests and downloads the content of the
// requested URLs to the given destination directory using the given number of
// concurrent worker goroutines.
//
// The Response for each requested URL is sent through the returned Response
// channel, as soon as a worker receives a response from the remote server. The
// Response can then be used to track the progress of the download while it is
// in progress.
//
// The returned Response channel will be closed by Grab, only once all downloads
// have completed or failed.
//
// If an error occurs during any download, it will be available via call to the
// associated Response.Err.
//
// For control over HTTP client headers, redirect policy, and other settings,
// create a Client instead. | [
"GetBatch",
"sends",
"multiple",
"HTTP",
"requests",
"and",
"downloads",
"the",
"content",
"of",
"the",
"requested",
"URLs",
"to",
"the",
"given",
"destination",
"directory",
"using",
"the",
"given",
"number",
"of",
"concurrent",
"worker",
"goroutines",
".",
"Th... | a224b4097c01f213344b657c2886cd429d891812 | https://github.com/cavaliercoder/grab/blob/a224b4097c01f213344b657c2886cd429d891812/grab.go#L44-L64 | train |
opentracing-contrib/go-stdlib | nethttp/server.go | OperationNameFunc | func OperationNameFunc(f func(r *http.Request) string) MWOption {
return func(options *mwOptions) {
options.opNameFunc = f
}
} | go | func OperationNameFunc(f func(r *http.Request) string) MWOption {
return func(options *mwOptions) {
options.opNameFunc = f
}
} | [
"func",
"OperationNameFunc",
"(",
"f",
"func",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"string",
")",
"MWOption",
"{",
"return",
"func",
"(",
"options",
"*",
"mwOptions",
")",
"{",
"options",
".",
"opNameFunc",
"=",
"f",
"\n",
"}",
"\n",
"}"
] | // OperationNameFunc returns a MWOption that uses given function f
// to generate operation name for each server-side span. | [
"OperationNameFunc",
"returns",
"a",
"MWOption",
"that",
"uses",
"given",
"function",
"f",
"to",
"generate",
"operation",
"name",
"for",
"each",
"server",
"-",
"side",
"span",
"."
] | 3020fec0e66bdb65fd42cb346cb65d58deb92e0d | https://github.com/opentracing-contrib/go-stdlib/blob/3020fec0e66bdb65fd42cb346cb65d58deb92e0d/nethttp/server.go#L26-L30 | train |
opentracing-contrib/go-stdlib | nethttp/server.go | MWSpanFilter | func MWSpanFilter(f func(r *http.Request) bool) MWOption {
return func(options *mwOptions) {
options.spanFilter = f
}
} | go | func MWSpanFilter(f func(r *http.Request) bool) MWOption {
return func(options *mwOptions) {
options.spanFilter = f
}
} | [
"func",
"MWSpanFilter",
"(",
"f",
"func",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"bool",
")",
"MWOption",
"{",
"return",
"func",
"(",
"options",
"*",
"mwOptions",
")",
"{",
"options",
".",
"spanFilter",
"=",
"f",
"\n",
"}",
"\n",
"}"
] | // MWSpanFilter returns a MWOption that filters requests from creating a span
// for the server-side span.
// Span won't be created if it returns false. | [
"MWSpanFilter",
"returns",
"a",
"MWOption",
"that",
"filters",
"requests",
"from",
"creating",
"a",
"span",
"for",
"the",
"server",
"-",
"side",
"span",
".",
"Span",
"won",
"t",
"be",
"created",
"if",
"it",
"returns",
"false",
"."
] | 3020fec0e66bdb65fd42cb346cb65d58deb92e0d | https://github.com/opentracing-contrib/go-stdlib/blob/3020fec0e66bdb65fd42cb346cb65d58deb92e0d/nethttp/server.go#L43-L47 | train |
opentracing-contrib/go-stdlib | nethttp/server.go | MWSpanObserver | func MWSpanObserver(f func(span opentracing.Span, r *http.Request)) MWOption {
return func(options *mwOptions) {
options.spanObserver = f
}
} | go | func MWSpanObserver(f func(span opentracing.Span, r *http.Request)) MWOption {
return func(options *mwOptions) {
options.spanObserver = f
}
} | [
"func",
"MWSpanObserver",
"(",
"f",
"func",
"(",
"span",
"opentracing",
".",
"Span",
",",
"r",
"*",
"http",
".",
"Request",
")",
")",
"MWOption",
"{",
"return",
"func",
"(",
"options",
"*",
"mwOptions",
")",
"{",
"options",
".",
"spanObserver",
"=",
"f... | // MWSpanObserver returns a MWOption that observe the span
// for the server-side span. | [
"MWSpanObserver",
"returns",
"a",
"MWOption",
"that",
"observe",
"the",
"span",
"for",
"the",
"server",
"-",
"side",
"span",
"."
] | 3020fec0e66bdb65fd42cb346cb65d58deb92e0d | https://github.com/opentracing-contrib/go-stdlib/blob/3020fec0e66bdb65fd42cb346cb65d58deb92e0d/nethttp/server.go#L51-L55 | train |
opentracing-contrib/go-stdlib | nethttp/server.go | MWURLTagFunc | func MWURLTagFunc(f func(u *url.URL) string) MWOption {
return func(options *mwOptions) {
options.urlTagFunc = f
}
} | go | func MWURLTagFunc(f func(u *url.URL) string) MWOption {
return func(options *mwOptions) {
options.urlTagFunc = f
}
} | [
"func",
"MWURLTagFunc",
"(",
"f",
"func",
"(",
"u",
"*",
"url",
".",
"URL",
")",
"string",
")",
"MWOption",
"{",
"return",
"func",
"(",
"options",
"*",
"mwOptions",
")",
"{",
"options",
".",
"urlTagFunc",
"=",
"f",
"\n",
"}",
"\n",
"}"
] | // MWURLTagFunc returns a MWOption that uses given function f
// to set the span's http.url tag. Can be used to change the default
// http.url tag, eg to redact sensitive information. | [
"MWURLTagFunc",
"returns",
"a",
"MWOption",
"that",
"uses",
"given",
"function",
"f",
"to",
"set",
"the",
"span",
"s",
"http",
".",
"url",
"tag",
".",
"Can",
"be",
"used",
"to",
"change",
"the",
"default",
"http",
".",
"url",
"tag",
"eg",
"to",
"redact... | 3020fec0e66bdb65fd42cb346cb65d58deb92e0d | https://github.com/opentracing-contrib/go-stdlib/blob/3020fec0e66bdb65fd42cb346cb65d58deb92e0d/nethttp/server.go#L60-L64 | train |
opentracing-contrib/go-stdlib | nethttp/client.go | ClientSpanObserver | func ClientSpanObserver(f func(span opentracing.Span, r *http.Request)) ClientOption {
return func(options *clientOptions) {
options.spanObserver = f
}
} | go | func ClientSpanObserver(f func(span opentracing.Span, r *http.Request)) ClientOption {
return func(options *clientOptions) {
options.spanObserver = f
}
} | [
"func",
"ClientSpanObserver",
"(",
"f",
"func",
"(",
"span",
"opentracing",
".",
"Span",
",",
"r",
"*",
"http",
".",
"Request",
")",
")",
"ClientOption",
"{",
"return",
"func",
"(",
"options",
"*",
"clientOptions",
")",
"{",
"options",
".",
"spanObserver",... | // ClientSpanObserver returns a ClientOption that observes the span
// for the client-side span. | [
"ClientSpanObserver",
"returns",
"a",
"ClientOption",
"that",
"observes",
"the",
"span",
"for",
"the",
"client",
"-",
"side",
"span",
"."
] | 3020fec0e66bdb65fd42cb346cb65d58deb92e0d | https://github.com/opentracing-contrib/go-stdlib/blob/3020fec0e66bdb65fd42cb346cb65d58deb92e0d/nethttp/client.go#L69-L73 | train |
opentracing-contrib/go-stdlib | nethttp/client.go | TracerFromRequest | func TracerFromRequest(req *http.Request) *Tracer {
tr, ok := req.Context().Value(keyTracer).(*Tracer)
if !ok {
return nil
}
return tr
} | go | func TracerFromRequest(req *http.Request) *Tracer {
tr, ok := req.Context().Value(keyTracer).(*Tracer)
if !ok {
return nil
}
return tr
} | [
"func",
"TracerFromRequest",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"*",
"Tracer",
"{",
"tr",
",",
"ok",
":=",
"req",
".",
"Context",
"(",
")",
".",
"Value",
"(",
"keyTracer",
")",
".",
"(",
"*",
"Tracer",
")",
"\n",
"if",
"!",
"ok",
"{",
... | // TracerFromRequest retrieves the Tracer from the request. If the request does
// not have a Tracer it will return nil. | [
"TracerFromRequest",
"retrieves",
"the",
"Tracer",
"from",
"the",
"request",
".",
"If",
"the",
"request",
"does",
"not",
"have",
"a",
"Tracer",
"it",
"will",
"return",
"nil",
"."
] | 3020fec0e66bdb65fd42cb346cb65d58deb92e0d | https://github.com/opentracing-contrib/go-stdlib/blob/3020fec0e66bdb65fd42cb346cb65d58deb92e0d/nethttp/client.go#L129-L135 | train |
bitrise-io/bitrise | cli/trigger_check.go | getWorkflowIDByParamsInCompatibleMode | func getWorkflowIDByParamsInCompatibleMode(triggerMap models.TriggerMapModel, params RunAndTriggerParamsModel, isPullRequestMode bool) (string, error) {
if params.TriggerPattern != "" {
params = migratePatternToParams(params, isPullRequestMode)
}
return getWorkflowIDByParams(triggerMap, params)
} | go | func getWorkflowIDByParamsInCompatibleMode(triggerMap models.TriggerMapModel, params RunAndTriggerParamsModel, isPullRequestMode bool) (string, error) {
if params.TriggerPattern != "" {
params = migratePatternToParams(params, isPullRequestMode)
}
return getWorkflowIDByParams(triggerMap, params)
} | [
"func",
"getWorkflowIDByParamsInCompatibleMode",
"(",
"triggerMap",
"models",
".",
"TriggerMapModel",
",",
"params",
"RunAndTriggerParamsModel",
",",
"isPullRequestMode",
"bool",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"params",
".",
"TriggerPattern",
"!=",
... | // migrates deprecated params.TriggerPattern to params.PushBranch or params.PRSourceBranch based on isPullRequestMode
// and returns the triggered workflow id | [
"migrates",
"deprecated",
"params",
".",
"TriggerPattern",
"to",
"params",
".",
"PushBranch",
"or",
"params",
".",
"PRSourceBranch",
"based",
"on",
"isPullRequestMode",
"and",
"returns",
"the",
"triggered",
"workflow",
"id"
] | 2ec917b478fe766c026ba3e78954db0f6b3954d4 | https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/cli/trigger_check.go#L77-L83 | train |
bitrise-io/bitrise | tools/timeoutcmd/timeoutcmd.go | New | func New(dir, name string, args ...string) Command {
c := Command{
cmd: exec.Command(name, args...),
}
c.cmd.Dir = dir
return c
} | go | func New(dir, name string, args ...string) Command {
c := Command{
cmd: exec.Command(name, args...),
}
c.cmd.Dir = dir
return c
} | [
"func",
"New",
"(",
"dir",
",",
"name",
"string",
",",
"args",
"...",
"string",
")",
"Command",
"{",
"c",
":=",
"Command",
"{",
"cmd",
":",
"exec",
".",
"Command",
"(",
"name",
",",
"args",
"...",
")",
",",
"}",
"\n",
"c",
".",
"cmd",
".",
"Dir... | // New creates a command model. | [
"New",
"creates",
"a",
"command",
"model",
"."
] | 2ec917b478fe766c026ba3e78954db0f6b3954d4 | https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/timeoutcmd/timeoutcmd.go#L22-L28 | train |
bitrise-io/bitrise | tools/timeoutcmd/timeoutcmd.go | AppendEnv | func (c *Command) AppendEnv(env string) {
if c.cmd.Env != nil {
c.cmd.Env = append(c.cmd.Env, env)
return
}
c.cmd.Env = append(os.Environ(), env)
} | go | func (c *Command) AppendEnv(env string) {
if c.cmd.Env != nil {
c.cmd.Env = append(c.cmd.Env, env)
return
}
c.cmd.Env = append(os.Environ(), env)
} | [
"func",
"(",
"c",
"*",
"Command",
")",
"AppendEnv",
"(",
"env",
"string",
")",
"{",
"if",
"c",
".",
"cmd",
".",
"Env",
"!=",
"nil",
"{",
"c",
".",
"cmd",
".",
"Env",
"=",
"append",
"(",
"c",
".",
"cmd",
".",
"Env",
",",
"env",
")",
"\n",
"r... | // AppendEnv appends and env to the command's env list. | [
"AppendEnv",
"appends",
"and",
"env",
"to",
"the",
"command",
"s",
"env",
"list",
"."
] | 2ec917b478fe766c026ba3e78954db0f6b3954d4 | https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/timeoutcmd/timeoutcmd.go#L36-L42 | train |
bitrise-io/bitrise | tools/timeoutcmd/timeoutcmd.go | SetStandardIO | func (c *Command) SetStandardIO(in io.Reader, out, err io.Writer) {
c.cmd.Stdin, c.cmd.Stdout, c.cmd.Stderr = in, out, err
} | go | func (c *Command) SetStandardIO(in io.Reader, out, err io.Writer) {
c.cmd.Stdin, c.cmd.Stdout, c.cmd.Stderr = in, out, err
} | [
"func",
"(",
"c",
"*",
"Command",
")",
"SetStandardIO",
"(",
"in",
"io",
".",
"Reader",
",",
"out",
",",
"err",
"io",
".",
"Writer",
")",
"{",
"c",
".",
"cmd",
".",
"Stdin",
",",
"c",
".",
"cmd",
".",
"Stdout",
",",
"c",
".",
"cmd",
".",
"Std... | // SetStandardIO sets the input and outputs of the command. | [
"SetStandardIO",
"sets",
"the",
"input",
"and",
"outputs",
"of",
"the",
"command",
"."
] | 2ec917b478fe766c026ba3e78954db0f6b3954d4 | https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/timeoutcmd/timeoutcmd.go#L45-L47 | train |
bitrise-io/bitrise | tools/timeoutcmd/timeoutcmd.go | Start | func (c *Command) Start() error {
// setting up notification for signals so we can have
// separated logic to end the process
interruptChan := make(chan os.Signal)
signal.Notify(interruptChan, os.Interrupt, os.Kill)
var interrupted bool
go func() {
<-interruptChan
interrupted = true
}()
// start the process
if err := c.cmd.Start(); err != nil {
return err
}
// Wait for the process to finish
done := make(chan error, 1)
go func() {
done <- c.cmd.Wait()
}()
// or kill it after a timeout (whichever happens first)
var timeoutChan <-chan time.Time
if c.timeout > 0 {
timeoutChan = time.After(c.timeout)
}
// exiting the method for the two supported cases: finish/error or timeout
select {
case <-timeoutChan:
if err := c.cmd.Process.Kill(); err != nil {
log.Warnf("Failed to kill process: %s", err)
}
return fmt.Errorf("timed out")
case err := <-done:
if interrupted {
os.Exit(ExitStatus(err))
}
return err
}
} | go | func (c *Command) Start() error {
// setting up notification for signals so we can have
// separated logic to end the process
interruptChan := make(chan os.Signal)
signal.Notify(interruptChan, os.Interrupt, os.Kill)
var interrupted bool
go func() {
<-interruptChan
interrupted = true
}()
// start the process
if err := c.cmd.Start(); err != nil {
return err
}
// Wait for the process to finish
done := make(chan error, 1)
go func() {
done <- c.cmd.Wait()
}()
// or kill it after a timeout (whichever happens first)
var timeoutChan <-chan time.Time
if c.timeout > 0 {
timeoutChan = time.After(c.timeout)
}
// exiting the method for the two supported cases: finish/error or timeout
select {
case <-timeoutChan:
if err := c.cmd.Process.Kill(); err != nil {
log.Warnf("Failed to kill process: %s", err)
}
return fmt.Errorf("timed out")
case err := <-done:
if interrupted {
os.Exit(ExitStatus(err))
}
return err
}
} | [
"func",
"(",
"c",
"*",
"Command",
")",
"Start",
"(",
")",
"error",
"{",
"// setting up notification for signals so we can have",
"// separated logic to end the process",
"interruptChan",
":=",
"make",
"(",
"chan",
"os",
".",
"Signal",
")",
"\n",
"signal",
".",
"Noti... | // Start starts the command run. | [
"Start",
"starts",
"the",
"command",
"run",
"."
] | 2ec917b478fe766c026ba3e78954db0f6b3954d4 | https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/timeoutcmd/timeoutcmd.go#L50-L91 | train |
bitrise-io/bitrise | tools/timeoutcmd/timeoutcmd.go | ExitStatus | func ExitStatus(err error) int {
if err == nil {
return 0
}
code := 1
if exiterr, ok := err.(*exec.ExitError); ok {
if waitStatus, ok := exiterr.Sys().(syscall.WaitStatus); ok {
code = waitStatus.ExitStatus()
}
}
return code
} | go | func ExitStatus(err error) int {
if err == nil {
return 0
}
code := 1
if exiterr, ok := err.(*exec.ExitError); ok {
if waitStatus, ok := exiterr.Sys().(syscall.WaitStatus); ok {
code = waitStatus.ExitStatus()
}
}
return code
} | [
"func",
"ExitStatus",
"(",
"err",
"error",
")",
"int",
"{",
"if",
"err",
"==",
"nil",
"{",
"return",
"0",
"\n",
"}",
"\n\n",
"code",
":=",
"1",
"\n",
"if",
"exiterr",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"exec",
".",
"ExitError",
")",
";",
"o... | // ExitStatus returns the error's exit status
// if the error is an exec.ExitError
// if the error is nil it return 0
// otherwise returns 1. | [
"ExitStatus",
"returns",
"the",
"error",
"s",
"exit",
"status",
"if",
"the",
"error",
"is",
"an",
"exec",
".",
"ExitError",
"if",
"the",
"error",
"is",
"nil",
"it",
"return",
"0",
"otherwise",
"returns",
"1",
"."
] | 2ec917b478fe766c026ba3e78954db0f6b3954d4 | https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/timeoutcmd/timeoutcmd.go#L97-L109 | train |
bitrise-io/bitrise | tools/filterwriter/range.go | allRanges | func allRanges(b, pattern []byte) (ranges []matchRange) {
i := 0
for {
sub := b[i:len(b)]
idx := bytes.Index(sub, pattern)
if idx == -1 {
return
}
ranges = append(ranges, matchRange{first: idx + i, last: idx + i + len(pattern)})
i += idx + 1
if i > len(b)-1 {
return
}
}
} | go | func allRanges(b, pattern []byte) (ranges []matchRange) {
i := 0
for {
sub := b[i:len(b)]
idx := bytes.Index(sub, pattern)
if idx == -1 {
return
}
ranges = append(ranges, matchRange{first: idx + i, last: idx + i + len(pattern)})
i += idx + 1
if i > len(b)-1 {
return
}
}
} | [
"func",
"allRanges",
"(",
"b",
",",
"pattern",
"[",
"]",
"byte",
")",
"(",
"ranges",
"[",
"]",
"matchRange",
")",
"{",
"i",
":=",
"0",
"\n",
"for",
"{",
"sub",
":=",
"b",
"[",
"i",
":",
"len",
"(",
"b",
")",
"]",
"\n",
"idx",
":=",
"bytes",
... | // allRanges returns every indexes of instance of pattern in b, or nil if pattern is not present in b. | [
"allRanges",
"returns",
"every",
"indexes",
"of",
"instance",
"of",
"pattern",
"in",
"b",
"or",
"nil",
"if",
"pattern",
"is",
"not",
"present",
"in",
"b",
"."
] | 2ec917b478fe766c026ba3e78954db0f6b3954d4 | https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/filterwriter/range.go#L11-L27 | train |
bitrise-io/bitrise | tools/filterwriter/range.go | mergeAllRanges | func mergeAllRanges(r []matchRange) []matchRange {
sort.Slice(r, func(i, j int) bool { return r[i].first < r[j].first })
for i := 0; i < len(r)-1; i++ {
for i+1 < len(r) && r[i+1].first <= r[i].last {
if r[i+1].last > r[i].last {
r[i].last = r[i+1].last
}
r = append(r[:i+1], r[i+2:]...)
}
}
return r
} | go | func mergeAllRanges(r []matchRange) []matchRange {
sort.Slice(r, func(i, j int) bool { return r[i].first < r[j].first })
for i := 0; i < len(r)-1; i++ {
for i+1 < len(r) && r[i+1].first <= r[i].last {
if r[i+1].last > r[i].last {
r[i].last = r[i+1].last
}
r = append(r[:i+1], r[i+2:]...)
}
}
return r
} | [
"func",
"mergeAllRanges",
"(",
"r",
"[",
"]",
"matchRange",
")",
"[",
"]",
"matchRange",
"{",
"sort",
".",
"Slice",
"(",
"r",
",",
"func",
"(",
"i",
",",
"j",
"int",
")",
"bool",
"{",
"return",
"r",
"[",
"i",
"]",
".",
"first",
"<",
"r",
"[",
... | // mergeAllRanges merges every overlapping ranges in r. | [
"mergeAllRanges",
"merges",
"every",
"overlapping",
"ranges",
"in",
"r",
"."
] | 2ec917b478fe766c026ba3e78954db0f6b3954d4 | https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/filterwriter/range.go#L30-L41 | train |
bitrise-io/bitrise | tools/filterwriter/filterwriter.go | Write | func (w *Writer) Write(p []byte) (int, error) {
defer func() {
w.mux.Unlock()
}()
w.mux.Lock()
// previous bytes may not ended with newline
data := append(w.chunk, p...)
lastLines, chunk := splitAfterNewline(data)
w.chunk = chunk
if len(chunk) > 0 {
// we have remaining bytes, do not swallow them
if w.timer != nil {
w.timer.Stop()
w.timer.C = nil
}
w.timer = time.AfterFunc(100*time.Millisecond, func() {
if _, err := w.Flush(); err != nil {
log.Errorf("Failed to print last lines: %s", err)
}
})
}
if len(lastLines) == 0 {
// it is necessary to return the count of incoming bytes
return len(p), nil
}
for _, line := range lastLines {
lines := append(w.store, line)
matchMap, partialMatchIndexes := w.matchSecrets(lines)
var linesToPrint [][]byte
linesToPrint, w.store = w.matchLines(lines, partialMatchIndexes)
if linesToPrint == nil {
continue
}
redactedLines := w.redact(linesToPrint, matchMap)
redactedBytes := bytes.Join(redactedLines, nil)
if c, err := w.writer.Write(redactedBytes); err != nil {
return c, err
}
}
// it is necessary to return the count of incoming bytes
// to let the exec.Command work properly
return len(p), nil
} | go | func (w *Writer) Write(p []byte) (int, error) {
defer func() {
w.mux.Unlock()
}()
w.mux.Lock()
// previous bytes may not ended with newline
data := append(w.chunk, p...)
lastLines, chunk := splitAfterNewline(data)
w.chunk = chunk
if len(chunk) > 0 {
// we have remaining bytes, do not swallow them
if w.timer != nil {
w.timer.Stop()
w.timer.C = nil
}
w.timer = time.AfterFunc(100*time.Millisecond, func() {
if _, err := w.Flush(); err != nil {
log.Errorf("Failed to print last lines: %s", err)
}
})
}
if len(lastLines) == 0 {
// it is necessary to return the count of incoming bytes
return len(p), nil
}
for _, line := range lastLines {
lines := append(w.store, line)
matchMap, partialMatchIndexes := w.matchSecrets(lines)
var linesToPrint [][]byte
linesToPrint, w.store = w.matchLines(lines, partialMatchIndexes)
if linesToPrint == nil {
continue
}
redactedLines := w.redact(linesToPrint, matchMap)
redactedBytes := bytes.Join(redactedLines, nil)
if c, err := w.writer.Write(redactedBytes); err != nil {
return c, err
}
}
// it is necessary to return the count of incoming bytes
// to let the exec.Command work properly
return len(p), nil
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"Write",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"w",
".",
"mux",
".",
"Unlock",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"w",
".",
"mux",
".",... | // Write implements io.Writer interface.
// Splits p into lines, the lines are matched against the secrets,
// this determines which lines can be redacted and written into the buffer.
// There are may lines which needs to be stored, since they are partial matching to a secret.
// Since we do not know which is the last call of Write we need to call Flush
// on buffer to write the remaining lines. | [
"Write",
"implements",
"io",
".",
"Writer",
"interface",
".",
"Splits",
"p",
"into",
"lines",
"the",
"lines",
"are",
"matched",
"against",
"the",
"secrets",
"this",
"determines",
"which",
"lines",
"can",
"be",
"redacted",
"and",
"written",
"into",
"the",
"bu... | 2ec917b478fe766c026ba3e78954db0f6b3954d4 | https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/filterwriter/filterwriter.go#L43-L92 | train |
bitrise-io/bitrise | tools/filterwriter/filterwriter.go | Flush | func (w *Writer) Flush() (int, error) {
defer func() {
w.mux.Unlock()
}()
w.mux.Lock()
if len(w.chunk) > 0 {
// lines are containing newline, chunk may not
chunk := w.chunk
w.chunk = nil
w.store = append(w.store, chunk)
}
// we only need to care about the full matches in the remaining lines
// (no more lines were come, why care about the partial matches?)
matchMap, _ := w.matchSecrets(w.store)
redactedLines := w.redact(w.store, matchMap)
w.store = nil
return w.writer.Write(bytes.Join(redactedLines, nil))
} | go | func (w *Writer) Flush() (int, error) {
defer func() {
w.mux.Unlock()
}()
w.mux.Lock()
if len(w.chunk) > 0 {
// lines are containing newline, chunk may not
chunk := w.chunk
w.chunk = nil
w.store = append(w.store, chunk)
}
// we only need to care about the full matches in the remaining lines
// (no more lines were come, why care about the partial matches?)
matchMap, _ := w.matchSecrets(w.store)
redactedLines := w.redact(w.store, matchMap)
w.store = nil
return w.writer.Write(bytes.Join(redactedLines, nil))
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"Flush",
"(",
")",
"(",
"int",
",",
"error",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"w",
".",
"mux",
".",
"Unlock",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"w",
".",
"mux",
".",
"Lock",
"(",
")",
"\n\... | // Flush writes the remaining bytes. | [
"Flush",
"writes",
"the",
"remaining",
"bytes",
"."
] | 2ec917b478fe766c026ba3e78954db0f6b3954d4 | https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/filterwriter/filterwriter.go#L95-L115 | train |
bitrise-io/bitrise | tools/filterwriter/filterwriter.go | linesToKeepRange | func (w *Writer) linesToKeepRange(partialMatchIndexes map[int]bool) int {
first := -1
for lineIdx := range partialMatchIndexes {
if first == -1 {
first = lineIdx
continue
}
if first > lineIdx {
first = lineIdx
}
}
return first
} | go | func (w *Writer) linesToKeepRange(partialMatchIndexes map[int]bool) int {
first := -1
for lineIdx := range partialMatchIndexes {
if first == -1 {
first = lineIdx
continue
}
if first > lineIdx {
first = lineIdx
}
}
return first
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"linesToKeepRange",
"(",
"partialMatchIndexes",
"map",
"[",
"int",
"]",
"bool",
")",
"int",
"{",
"first",
":=",
"-",
"1",
"\n\n",
"for",
"lineIdx",
":=",
"range",
"partialMatchIndexes",
"{",
"if",
"first",
"==",
"-",... | // linesToKeepRange returns the first line index needs to be observed
// since they contain partially matching secrets. | [
"linesToKeepRange",
"returns",
"the",
"first",
"line",
"index",
"needs",
"to",
"be",
"observed",
"since",
"they",
"contain",
"partially",
"matching",
"secrets",
"."
] | 2ec917b478fe766c026ba3e78954db0f6b3954d4 | https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/filterwriter/filterwriter.go#L190-L205 | train |
bitrise-io/bitrise | tools/filterwriter/filterwriter.go | matchLines | func (w *Writer) matchLines(lines [][]byte, partialMatchIndexes map[int]bool) ([][]byte, [][]byte) {
first := w.linesToKeepRange(partialMatchIndexes)
switch first {
case -1:
// no lines needs to be kept
return lines, nil
case 0:
// partial match is always longer then the lines
return nil, lines
default:
return lines[:first], lines[first:]
}
} | go | func (w *Writer) matchLines(lines [][]byte, partialMatchIndexes map[int]bool) ([][]byte, [][]byte) {
first := w.linesToKeepRange(partialMatchIndexes)
switch first {
case -1:
// no lines needs to be kept
return lines, nil
case 0:
// partial match is always longer then the lines
return nil, lines
default:
return lines[:first], lines[first:]
}
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"matchLines",
"(",
"lines",
"[",
"]",
"[",
"]",
"byte",
",",
"partialMatchIndexes",
"map",
"[",
"int",
"]",
"bool",
")",
"(",
"[",
"]",
"[",
"]",
"byte",
",",
"[",
"]",
"[",
"]",
"byte",
")",
"{",
"first",
... | // matchLines return which lines can be printed and which should be kept for further observing. | [
"matchLines",
"return",
"which",
"lines",
"can",
"be",
"printed",
"and",
"which",
"should",
"be",
"kept",
"for",
"further",
"observing",
"."
] | 2ec917b478fe766c026ba3e78954db0f6b3954d4 | https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/filterwriter/filterwriter.go#L208-L220 | train |
bitrise-io/bitrise | tools/filterwriter/filterwriter.go | secretLinesToRedact | func (w *Writer) secretLinesToRedact(lineIdxToRedact int, matchMap map[int][]int) [][]byte {
// which line is which secrets first matching line
secretIdxsByLine := make(map[int][]int)
for secretIdx, lineIndexes := range matchMap {
for _, lineIdx := range lineIndexes {
secretIdxsByLine[lineIdx] = append(secretIdxsByLine[lineIdx], secretIdx)
}
}
var secretChunks [][]byte
for firstMatchingLineIdx, secretIndexes := range secretIdxsByLine {
if lineIdxToRedact < firstMatchingLineIdx {
continue
}
for _, secretIdx := range secretIndexes {
secret := w.secrets[secretIdx]
if lineIdxToRedact > firstMatchingLineIdx+len(secret)-1 {
continue
}
secretLineIdx := lineIdxToRedact - firstMatchingLineIdx
secretChunks = append(secretChunks, secret[secretLineIdx])
}
}
sort.Slice(secretChunks, func(i, j int) bool { return len(secretChunks[i]) < len(secretChunks[j]) })
return secretChunks
} | go | func (w *Writer) secretLinesToRedact(lineIdxToRedact int, matchMap map[int][]int) [][]byte {
// which line is which secrets first matching line
secretIdxsByLine := make(map[int][]int)
for secretIdx, lineIndexes := range matchMap {
for _, lineIdx := range lineIndexes {
secretIdxsByLine[lineIdx] = append(secretIdxsByLine[lineIdx], secretIdx)
}
}
var secretChunks [][]byte
for firstMatchingLineIdx, secretIndexes := range secretIdxsByLine {
if lineIdxToRedact < firstMatchingLineIdx {
continue
}
for _, secretIdx := range secretIndexes {
secret := w.secrets[secretIdx]
if lineIdxToRedact > firstMatchingLineIdx+len(secret)-1 {
continue
}
secretLineIdx := lineIdxToRedact - firstMatchingLineIdx
secretChunks = append(secretChunks, secret[secretLineIdx])
}
}
sort.Slice(secretChunks, func(i, j int) bool { return len(secretChunks[i]) < len(secretChunks[j]) })
return secretChunks
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"secretLinesToRedact",
"(",
"lineIdxToRedact",
"int",
",",
"matchMap",
"map",
"[",
"int",
"]",
"[",
"]",
"int",
")",
"[",
"]",
"[",
"]",
"byte",
"{",
"// which line is which secrets first matching line",
"secretIdxsByLine",
... | // secretLinesToRedact returns which secret lines should be redacted | [
"secretLinesToRedact",
"returns",
"which",
"secret",
"lines",
"should",
"be",
"redacted"
] | 2ec917b478fe766c026ba3e78954db0f6b3954d4 | https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/filterwriter/filterwriter.go#L223-L252 | train |
bitrise-io/bitrise | tools/filterwriter/filterwriter.go | redact | func redact(line []byte, ranges []matchRange) []byte {
var offset int // the offset of ranges generated by replacing x bytes by the RedactStr
for _, r := range ranges {
length := r.last - r.first
first := r.first + offset
last := first + length
toRedact := line[first:last]
redactStr := RedactStr
if bytes.HasSuffix(toRedact, []byte("\n")) {
// if string to redact ends with newline redact message should also
redactStr += "\n"
}
newLine := append([]byte{}, line[:first]...)
newLine = append(newLine, redactStr...)
newLine = append(newLine, line[last:]...)
offset += len(redactStr) - length
line = newLine
}
return line
} | go | func redact(line []byte, ranges []matchRange) []byte {
var offset int // the offset of ranges generated by replacing x bytes by the RedactStr
for _, r := range ranges {
length := r.last - r.first
first := r.first + offset
last := first + length
toRedact := line[first:last]
redactStr := RedactStr
if bytes.HasSuffix(toRedact, []byte("\n")) {
// if string to redact ends with newline redact message should also
redactStr += "\n"
}
newLine := append([]byte{}, line[:first]...)
newLine = append(newLine, redactStr...)
newLine = append(newLine, line[last:]...)
offset += len(redactStr) - length
line = newLine
}
return line
} | [
"func",
"redact",
"(",
"line",
"[",
"]",
"byte",
",",
"ranges",
"[",
"]",
"matchRange",
")",
"[",
"]",
"byte",
"{",
"var",
"offset",
"int",
"// the offset of ranges generated by replacing x bytes by the RedactStr",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"r... | // redact hides the given ranges in the given line. | [
"redact",
"hides",
"the",
"given",
"ranges",
"in",
"the",
"given",
"line",
"."
] | 2ec917b478fe766c026ba3e78954db0f6b3954d4 | https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/filterwriter/filterwriter.go#L255-L278 | train |
bitrise-io/bitrise | tools/filterwriter/filterwriter.go | redact | func (w *Writer) redact(lines [][]byte, matchMap map[int][]int) [][]byte {
secretIdxsByLine := map[int][]int{}
for secretIdx, lineIndexes := range matchMap {
for _, lineIdx := range lineIndexes {
secretIdxsByLine[lineIdx] = append(secretIdxsByLine[lineIdx], secretIdx)
}
}
for i, line := range lines {
linesToRedact := w.secretLinesToRedact(i, matchMap)
if linesToRedact == nil {
continue
}
var ranges []matchRange
for _, lineToRedact := range linesToRedact {
ranges = append(ranges, allRanges(line, lineToRedact)...)
}
lines[i] = redact(line, mergeAllRanges(ranges))
}
return lines
} | go | func (w *Writer) redact(lines [][]byte, matchMap map[int][]int) [][]byte {
secretIdxsByLine := map[int][]int{}
for secretIdx, lineIndexes := range matchMap {
for _, lineIdx := range lineIndexes {
secretIdxsByLine[lineIdx] = append(secretIdxsByLine[lineIdx], secretIdx)
}
}
for i, line := range lines {
linesToRedact := w.secretLinesToRedact(i, matchMap)
if linesToRedact == nil {
continue
}
var ranges []matchRange
for _, lineToRedact := range linesToRedact {
ranges = append(ranges, allRanges(line, lineToRedact)...)
}
lines[i] = redact(line, mergeAllRanges(ranges))
}
return lines
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"redact",
"(",
"lines",
"[",
"]",
"[",
"]",
"byte",
",",
"matchMap",
"map",
"[",
"int",
"]",
"[",
"]",
"int",
")",
"[",
"]",
"[",
"]",
"byte",
"{",
"secretIdxsByLine",
":=",
"map",
"[",
"int",
"]",
"[",
"... | // redact hides the given secrets in the given lines. | [
"redact",
"hides",
"the",
"given",
"secrets",
"in",
"the",
"given",
"lines",
"."
] | 2ec917b478fe766c026ba3e78954db0f6b3954d4 | https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/filterwriter/filterwriter.go#L281-L304 | train |
bitrise-io/bitrise | tools/filterwriter/filterwriter.go | secretsByteList | func secretsByteList(secrets []string) [][][]byte {
var s [][][]byte
for _, secret := range secrets {
lines, lastLine := splitAfterNewline([]byte(secret))
if lines == nil && lastLine == nil {
continue
}
var secretLines [][]byte
if lines != nil {
secretLines = append(secretLines, lines...)
}
if lastLine != nil {
secretLines = append(secretLines, lastLine)
}
s = append(s, secretLines)
}
return s
} | go | func secretsByteList(secrets []string) [][][]byte {
var s [][][]byte
for _, secret := range secrets {
lines, lastLine := splitAfterNewline([]byte(secret))
if lines == nil && lastLine == nil {
continue
}
var secretLines [][]byte
if lines != nil {
secretLines = append(secretLines, lines...)
}
if lastLine != nil {
secretLines = append(secretLines, lastLine)
}
s = append(s, secretLines)
}
return s
} | [
"func",
"secretsByteList",
"(",
"secrets",
"[",
"]",
"string",
")",
"[",
"]",
"[",
"]",
"[",
"]",
"byte",
"{",
"var",
"s",
"[",
"]",
"[",
"]",
"[",
"]",
"byte",
"\n",
"for",
"_",
",",
"secret",
":=",
"range",
"secrets",
"{",
"lines",
",",
"last... | // secretsByteList returns the list of secret byte lines. | [
"secretsByteList",
"returns",
"the",
"list",
"of",
"secret",
"byte",
"lines",
"."
] | 2ec917b478fe766c026ba3e78954db0f6b3954d4 | https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/filterwriter/filterwriter.go#L307-L325 | train |
bitrise-io/bitrise | tools/filterwriter/filterwriter.go | splitAfterNewline | func splitAfterNewline(p []byte) ([][]byte, []byte) {
chunk := p
var lines [][]byte
for len(chunk) > 0 {
idx := bytes.Index(chunk, newLine)
if idx == -1 {
return lines, chunk
}
lines = append(lines, chunk[:idx+1])
if idx == len(chunk)-1 {
chunk = nil
break
}
chunk = chunk[idx+1:]
}
return lines, chunk
} | go | func splitAfterNewline(p []byte) ([][]byte, []byte) {
chunk := p
var lines [][]byte
for len(chunk) > 0 {
idx := bytes.Index(chunk, newLine)
if idx == -1 {
return lines, chunk
}
lines = append(lines, chunk[:idx+1])
if idx == len(chunk)-1 {
chunk = nil
break
}
chunk = chunk[idx+1:]
}
return lines, chunk
} | [
"func",
"splitAfterNewline",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"[",
"]",
"byte",
",",
"[",
"]",
"byte",
")",
"{",
"chunk",
":=",
"p",
"\n",
"var",
"lines",
"[",
"]",
"[",
"]",
"byte",
"\n\n",
"for",
"len",
"(",
"chunk",
")",
">"... | // splitAfterNewline splits p after "\n", the split is assigned to lines
// if last line has no "\n" it is assigned to the chunk.
// If p is nil both lines and chunk is set to nil. | [
"splitAfterNewline",
"splits",
"p",
"after",
"\\",
"n",
"the",
"split",
"is",
"assigned",
"to",
"lines",
"if",
"last",
"line",
"has",
"no",
"\\",
"n",
"it",
"is",
"assigned",
"to",
"the",
"chunk",
".",
"If",
"p",
"is",
"nil",
"both",
"lines",
"and",
... | 2ec917b478fe766c026ba3e78954db0f6b3954d4 | https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/filterwriter/filterwriter.go#L330-L351 | train |
bitrise-io/bitrise | plugins/install.go | isSourceURIChanged | func isSourceURIChanged(installed, new string) bool {
if urlsForOrg := func(org string) []string {
return []string{
"https://github.com/" + org + "/bitrise-plugins-init.git",
"https://github.com/" + org + "/bitrise-plugins-step.git",
"https://github.com/" + org + "/bitrise-plugins-analytics.git",
}
}; (installed == new) || (sliceutil.IsStringInSlice(installed, urlsForOrg("bitrise-core")) &&
sliceutil.IsStringInSlice(new, urlsForOrg("bitrise-io"))) {
return false
}
return true
} | go | func isSourceURIChanged(installed, new string) bool {
if urlsForOrg := func(org string) []string {
return []string{
"https://github.com/" + org + "/bitrise-plugins-init.git",
"https://github.com/" + org + "/bitrise-plugins-step.git",
"https://github.com/" + org + "/bitrise-plugins-analytics.git",
}
}; (installed == new) || (sliceutil.IsStringInSlice(installed, urlsForOrg("bitrise-core")) &&
sliceutil.IsStringInSlice(new, urlsForOrg("bitrise-io"))) {
return false
}
return true
} | [
"func",
"isSourceURIChanged",
"(",
"installed",
",",
"new",
"string",
")",
"bool",
"{",
"if",
"urlsForOrg",
":=",
"func",
"(",
"org",
"string",
")",
"[",
"]",
"string",
"{",
"return",
"[",
"]",
"string",
"{",
"\"",
"\"",
"+",
"org",
"+",
"\"",
"\"",
... | // plugins from bitrise-core to bitrise-io GitHub org have been moved
// so it is better to not to detect this as a different plugin source | [
"plugins",
"from",
"bitrise",
"-",
"core",
"to",
"bitrise",
"-",
"io",
"GitHub",
"org",
"have",
"been",
"moved",
"so",
"it",
"is",
"better",
"to",
"not",
"to",
"detect",
"this",
"as",
"a",
"different",
"plugin",
"source"
] | 2ec917b478fe766c026ba3e78954db0f6b3954d4 | https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/plugins/install.go#L103-L115 | train |
bitrise-io/bitrise | tools/tools.go | EnvmanRun | func EnvmanRun(envstorePth, workDirPth string, cmdArgs []string, timeout time.Duration, secrets []envmanModels.EnvironmentItemModel) (int, error) {
logLevel := log.GetLevel().String()
args := []string{"--loglevel", logLevel, "--path", envstorePth, "run"}
args = append(args, cmdArgs...)
var outWriter io.Writer
var errWriter io.Writer
if !configs.IsSecretFiltering {
outWriter = os.Stdout
errWriter = os.Stderr
} else {
var secretValues []string
for _, secret := range secrets {
key, value, err := secret.GetKeyValuePair()
if err != nil || len(value) < 1 || IsBuiltInFlagTypeKey(key) {
continue
}
secretValues = append(secretValues, value)
}
outWriter = filterwriter.New(secretValues, os.Stdout)
errWriter = outWriter
}
cmd := timeoutcmd.New(workDirPth, "envman", args...)
cmd.SetStandardIO(os.Stdin, outWriter, errWriter)
cmd.SetTimeout(timeout)
cmd.AppendEnv("PWD=" + workDirPth)
err := cmd.Start()
// flush the writer anyway if the process is finished
if configs.IsSecretFiltering {
_, ferr := (outWriter.(*filterwriter.Writer)).Flush()
if ferr != nil {
return 1, ferr
}
}
return timeoutcmd.ExitStatus(err), err
} | go | func EnvmanRun(envstorePth, workDirPth string, cmdArgs []string, timeout time.Duration, secrets []envmanModels.EnvironmentItemModel) (int, error) {
logLevel := log.GetLevel().String()
args := []string{"--loglevel", logLevel, "--path", envstorePth, "run"}
args = append(args, cmdArgs...)
var outWriter io.Writer
var errWriter io.Writer
if !configs.IsSecretFiltering {
outWriter = os.Stdout
errWriter = os.Stderr
} else {
var secretValues []string
for _, secret := range secrets {
key, value, err := secret.GetKeyValuePair()
if err != nil || len(value) < 1 || IsBuiltInFlagTypeKey(key) {
continue
}
secretValues = append(secretValues, value)
}
outWriter = filterwriter.New(secretValues, os.Stdout)
errWriter = outWriter
}
cmd := timeoutcmd.New(workDirPth, "envman", args...)
cmd.SetStandardIO(os.Stdin, outWriter, errWriter)
cmd.SetTimeout(timeout)
cmd.AppendEnv("PWD=" + workDirPth)
err := cmd.Start()
// flush the writer anyway if the process is finished
if configs.IsSecretFiltering {
_, ferr := (outWriter.(*filterwriter.Writer)).Flush()
if ferr != nil {
return 1, ferr
}
}
return timeoutcmd.ExitStatus(err), err
} | [
"func",
"EnvmanRun",
"(",
"envstorePth",
",",
"workDirPth",
"string",
",",
"cmdArgs",
"[",
"]",
"string",
",",
"timeout",
"time",
".",
"Duration",
",",
"secrets",
"[",
"]",
"envmanModels",
".",
"EnvironmentItemModel",
")",
"(",
"int",
",",
"error",
")",
"{... | // EnvmanRun runs a command through envman. | [
"EnvmanRun",
"runs",
"a",
"command",
"through",
"envman",
"."
] | 2ec917b478fe766c026ba3e78954db0f6b3954d4 | https://github.com/bitrise-io/bitrise/blob/2ec917b478fe766c026ba3e78954db0f6b3954d4/tools/tools.go#L342-L383 | train |
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.