repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
openzipkin/zipkin-go
model/traceid.go
UnmarshalJSON
func (t *TraceID) UnmarshalJSON(traceID []byte) error { if len(traceID) < 3 { return ErrValidTraceIDRequired } // A valid JSON string is encoded wrapped in double quotes. We need to trim // these before converting the hex payload. tID, err := TraceIDFromHex(string(traceID[1 : len(traceID)-1])) if err != nil { return err } *t = tID return nil }
go
func (t *TraceID) UnmarshalJSON(traceID []byte) error { if len(traceID) < 3 { return ErrValidTraceIDRequired } // A valid JSON string is encoded wrapped in double quotes. We need to trim // these before converting the hex payload. tID, err := TraceIDFromHex(string(traceID[1 : len(traceID)-1])) if err != nil { return err } *t = tID return nil }
[ "func", "(", "t", "*", "TraceID", ")", "UnmarshalJSON", "(", "traceID", "[", "]", "byte", ")", "error", "{", "if", "len", "(", "traceID", ")", "<", "3", "{", "return", "ErrValidTraceIDRequired", "\n", "}", "\n", "tID", ",", "err", ":=", "TraceIDFromHex...
// UnmarshalJSON custom JSON deserializer to retrieve the traceID from the hex // encoded representation.
[ "UnmarshalJSON", "custom", "JSON", "deserializer", "to", "retrieve", "the", "traceID", "from", "the", "hex", "encoded", "representation", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/model/traceid.go#L63-L75
train
openzipkin/zipkin-go
middleware/http/transport.go
RoundTripper
func RoundTripper(rt http.RoundTripper) TransportOption { return func(t *transport) { if rt != nil { t.rt = rt } } }
go
func RoundTripper(rt http.RoundTripper) TransportOption { return func(t *transport) { if rt != nil { t.rt = rt } } }
[ "func", "RoundTripper", "(", "rt", "http", ".", "RoundTripper", ")", "TransportOption", "{", "return", "func", "(", "t", "*", "transport", ")", "{", "if", "rt", "!=", "nil", "{", "t", ".", "rt", "=", "rt", "\n", "}", "\n", "}", "\n", "}" ]
// RoundTripper adds the Transport RoundTripper to wrap.
[ "RoundTripper", "adds", "the", "Transport", "RoundTripper", "to", "wrap", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/middleware/http/transport.go#L54-L60
train
openzipkin/zipkin-go
middleware/http/transport.go
TransportTags
func TransportTags(tags map[string]string) TransportOption { return func(t *transport) { t.defaultTags = tags } }
go
func TransportTags(tags map[string]string) TransportOption { return func(t *transport) { t.defaultTags = tags } }
[ "func", "TransportTags", "(", "tags", "map", "[", "string", "]", "string", ")", "TransportOption", "{", "return", "func", "(", "t", "*", "transport", ")", "{", "t", ".", "defaultTags", "=", "tags", "\n", "}", "\n", "}" ]
// TransportTags adds default Tags to inject into transport spans.
[ "TransportTags", "adds", "default", "Tags", "to", "inject", "into", "transport", "spans", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/middleware/http/transport.go#L63-L67
train
openzipkin/zipkin-go
middleware/http/transport.go
NewTransport
func NewTransport(tracer *zipkin.Tracer, options ...TransportOption) (http.RoundTripper, error) { if tracer == nil { return nil, ErrValidTracerRequired } t := &transport{ tracer: tracer, rt: http.DefaultTransport, httpTrace: false, errHandler: defaultErrHandler, } for _, option := range options { option(t) } return t, nil }
go
func NewTransport(tracer *zipkin.Tracer, options ...TransportOption) (http.RoundTripper, error) { if tracer == nil { return nil, ErrValidTracerRequired } t := &transport{ tracer: tracer, rt: http.DefaultTransport, httpTrace: false, errHandler: defaultErrHandler, } for _, option := range options { option(t) } return t, nil }
[ "func", "NewTransport", "(", "tracer", "*", "zipkin", ".", "Tracer", ",", "options", "...", "TransportOption", ")", "(", "http", ".", "RoundTripper", ",", "error", ")", "{", "if", "tracer", "==", "nil", "{", "return", "nil", ",", "ErrValidTracerRequired", ...
// NewTransport returns a new Zipkin instrumented http RoundTripper which can be // used with a standard library http Client.
[ "NewTransport", "returns", "a", "new", "Zipkin", "instrumented", "http", "RoundTripper", "which", "can", "be", "used", "with", "a", "standard", "library", "http", "Client", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/middleware/http/transport.go#L85-L102
train
openzipkin/zipkin-go
middleware/http/transport.go
RoundTrip
func (t *transport) RoundTrip(req *http.Request) (res *http.Response, err error) { sp, _ := t.tracer.StartSpanFromContext( req.Context(), req.URL.Scheme+"/"+req.Method, zipkin.Kind(model.Client), ) for k, v := range t.defaultTags { sp.Tag(k, v) } if t.httpTrace { sptr := spanTrace{ Span: sp, } sptr.c = &httptrace.ClientTrace{ GetConn: sptr.getConn, GotConn: sptr.gotConn, PutIdleConn: sptr.putIdleConn, GotFirstResponseByte: sptr.gotFirstResponseByte, Got100Continue: sptr.got100Continue, DNSStart: sptr.dnsStart, DNSDone: sptr.dnsDone, ConnectStart: sptr.connectStart, ConnectDone: sptr.connectDone, TLSHandshakeStart: sptr.tlsHandshakeStart, TLSHandshakeDone: sptr.tlsHandshakeDone, WroteHeaders: sptr.wroteHeaders, Wait100Continue: sptr.wait100Continue, WroteRequest: sptr.wroteRequest, } req = req.WithContext( httptrace.WithClientTrace(req.Context(), sptr.c), ) } zipkin.TagHTTPMethod.Set(sp, req.Method) zipkin.TagHTTPPath.Set(sp, req.URL.Path) _ = b3.InjectHTTP(req)(sp.Context()) res, err = t.rt.RoundTrip(req) if err != nil { t.errHandler(sp, err, 0) sp.Finish() return } if res.ContentLength > 0 { zipkin.TagHTTPResponseSize.Set(sp, strconv.FormatInt(res.ContentLength, 10)) } if res.StatusCode < 200 || res.StatusCode > 299 { statusCode := strconv.FormatInt(int64(res.StatusCode), 10) zipkin.TagHTTPStatusCode.Set(sp, statusCode) if res.StatusCode > 399 { t.errHandler(sp, nil, res.StatusCode) } } sp.Finish() return }
go
func (t *transport) RoundTrip(req *http.Request) (res *http.Response, err error) { sp, _ := t.tracer.StartSpanFromContext( req.Context(), req.URL.Scheme+"/"+req.Method, zipkin.Kind(model.Client), ) for k, v := range t.defaultTags { sp.Tag(k, v) } if t.httpTrace { sptr := spanTrace{ Span: sp, } sptr.c = &httptrace.ClientTrace{ GetConn: sptr.getConn, GotConn: sptr.gotConn, PutIdleConn: sptr.putIdleConn, GotFirstResponseByte: sptr.gotFirstResponseByte, Got100Continue: sptr.got100Continue, DNSStart: sptr.dnsStart, DNSDone: sptr.dnsDone, ConnectStart: sptr.connectStart, ConnectDone: sptr.connectDone, TLSHandshakeStart: sptr.tlsHandshakeStart, TLSHandshakeDone: sptr.tlsHandshakeDone, WroteHeaders: sptr.wroteHeaders, Wait100Continue: sptr.wait100Continue, WroteRequest: sptr.wroteRequest, } req = req.WithContext( httptrace.WithClientTrace(req.Context(), sptr.c), ) } zipkin.TagHTTPMethod.Set(sp, req.Method) zipkin.TagHTTPPath.Set(sp, req.URL.Path) _ = b3.InjectHTTP(req)(sp.Context()) res, err = t.rt.RoundTrip(req) if err != nil { t.errHandler(sp, err, 0) sp.Finish() return } if res.ContentLength > 0 { zipkin.TagHTTPResponseSize.Set(sp, strconv.FormatInt(res.ContentLength, 10)) } if res.StatusCode < 200 || res.StatusCode > 299 { statusCode := strconv.FormatInt(int64(res.StatusCode), 10) zipkin.TagHTTPStatusCode.Set(sp, statusCode) if res.StatusCode > 399 { t.errHandler(sp, nil, res.StatusCode) } } sp.Finish() return }
[ "func", "(", "t", "*", "transport", ")", "RoundTrip", "(", "req", "*", "http", ".", "Request", ")", "(", "res", "*", "http", ".", "Response", ",", "err", "error", ")", "{", "sp", ",", "_", ":=", "t", ".", "tracer", ".", "StartSpanFromContext", "(",...
// RoundTrip satisfies the RoundTripper interface.
[ "RoundTrip", "satisfies", "the", "RoundTripper", "interface", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/middleware/http/transport.go#L105-L164
train
openzipkin/zipkin-go
propagation/b3/spancontext.go
ParseHeaders
func ParseHeaders( hdrTraceID, hdrSpanID, hdrParentSpanID, hdrSampled, hdrFlags string, ) (*model.SpanContext, error) { var ( err error spanID uint64 requiredCount int sc = &model.SpanContext{} ) // correct values for an existing sampled header are "0" and "1". // For legacy support and being lenient to other tracing implementations we // allow "true" and "false" as inputs for interop purposes. switch strings.ToLower(hdrSampled) { case "0", "false": sampled := false sc.Sampled = &sampled case "1", "true": sampled := true sc.Sampled = &sampled case "": // sc.Sampled = nil default: return nil, ErrInvalidSampledHeader } // The only accepted value for Flags is "1". This will set Debug to true. All // other values and omission of header will be ignored. if hdrFlags == "1" { sc.Debug = true sc.Sampled = nil } if hdrTraceID != "" { requiredCount++ if sc.TraceID, err = model.TraceIDFromHex(hdrTraceID); err != nil { return nil, ErrInvalidTraceIDHeader } } if hdrSpanID != "" { requiredCount++ if spanID, err = strconv.ParseUint(hdrSpanID, 16, 64); err != nil { return nil, ErrInvalidSpanIDHeader } sc.ID = model.ID(spanID) } if requiredCount != 0 && requiredCount != 2 { return nil, ErrInvalidScope } if hdrParentSpanID != "" { if requiredCount == 0 { return nil, ErrInvalidScopeParent } if spanID, err = strconv.ParseUint(hdrParentSpanID, 16, 64); err != nil { return nil, ErrInvalidParentSpanIDHeader } parentSpanID := model.ID(spanID) sc.ParentID = &parentSpanID } return sc, nil }
go
func ParseHeaders( hdrTraceID, hdrSpanID, hdrParentSpanID, hdrSampled, hdrFlags string, ) (*model.SpanContext, error) { var ( err error spanID uint64 requiredCount int sc = &model.SpanContext{} ) // correct values for an existing sampled header are "0" and "1". // For legacy support and being lenient to other tracing implementations we // allow "true" and "false" as inputs for interop purposes. switch strings.ToLower(hdrSampled) { case "0", "false": sampled := false sc.Sampled = &sampled case "1", "true": sampled := true sc.Sampled = &sampled case "": // sc.Sampled = nil default: return nil, ErrInvalidSampledHeader } // The only accepted value for Flags is "1". This will set Debug to true. All // other values and omission of header will be ignored. if hdrFlags == "1" { sc.Debug = true sc.Sampled = nil } if hdrTraceID != "" { requiredCount++ if sc.TraceID, err = model.TraceIDFromHex(hdrTraceID); err != nil { return nil, ErrInvalidTraceIDHeader } } if hdrSpanID != "" { requiredCount++ if spanID, err = strconv.ParseUint(hdrSpanID, 16, 64); err != nil { return nil, ErrInvalidSpanIDHeader } sc.ID = model.ID(spanID) } if requiredCount != 0 && requiredCount != 2 { return nil, ErrInvalidScope } if hdrParentSpanID != "" { if requiredCount == 0 { return nil, ErrInvalidScopeParent } if spanID, err = strconv.ParseUint(hdrParentSpanID, 16, 64); err != nil { return nil, ErrInvalidParentSpanIDHeader } parentSpanID := model.ID(spanID) sc.ParentID = &parentSpanID } return sc, nil }
[ "func", "ParseHeaders", "(", "hdrTraceID", ",", "hdrSpanID", ",", "hdrParentSpanID", ",", "hdrSampled", ",", "hdrFlags", "string", ",", ")", "(", "*", "model", ".", "SpanContext", ",", "error", ")", "{", "var", "(", "err", "error", "\n", "spanID", "uint64"...
// ParseHeaders takes values found from B3 Headers and tries to reconstruct a // SpanContext.
[ "ParseHeaders", "takes", "values", "found", "from", "B3", "Headers", "and", "tries", "to", "reconstruct", "a", "SpanContext", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/propagation/b3/spancontext.go#L26-L90
train
openzipkin/zipkin-go
reporter/serializer.go
Serialize
func (JSONSerializer) Serialize(spans []*model.SpanModel) ([]byte, error) { return json.Marshal(spans) }
go
func (JSONSerializer) Serialize(spans []*model.SpanModel) ([]byte, error) { return json.Marshal(spans) }
[ "func", "(", "JSONSerializer", ")", "Serialize", "(", "spans", "[", "]", "*", "model", ".", "SpanModel", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "json", ".", "Marshal", "(", "spans", ")", "\n", "}" ]
// Serialize takes an array of Zipkin SpanModel objects and returns a JSON // encoding of it.
[ "Serialize", "takes", "an", "array", "of", "Zipkin", "SpanModel", "objects", "and", "returns", "a", "JSON", "encoding", "of", "it", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/reporter/serializer.go#L35-L37
train
openzipkin/zipkin-go
middleware/http/client.go
WithClient
func WithClient(client *http.Client) ClientOption { return func(c *Client) { if client == nil { client = &http.Client{} } c.Client = client } }
go
func WithClient(client *http.Client) ClientOption { return func(c *Client) { if client == nil { client = &http.Client{} } c.Client = client } }
[ "func", "WithClient", "(", "client", "*", "http", ".", "Client", ")", "ClientOption", "{", "return", "func", "(", "c", "*", "Client", ")", "{", "if", "client", "==", "nil", "{", "client", "=", "&", "http", ".", "Client", "{", "}", "\n", "}", "\n", ...
// WithClient allows one to add a custom configured http.Client to use.
[ "WithClient", "allows", "one", "to", "add", "a", "custom", "configured", "http", ".", "Client", "to", "use", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/middleware/http/client.go#L43-L50
train
openzipkin/zipkin-go
middleware/http/client.go
ClientTags
func ClientTags(tags map[string]string) ClientOption { return func(c *Client) { c.defaultTags = tags } }
go
func ClientTags(tags map[string]string) ClientOption { return func(c *Client) { c.defaultTags = tags } }
[ "func", "ClientTags", "(", "tags", "map", "[", "string", "]", "string", ")", "ClientOption", "{", "return", "func", "(", "c", "*", "Client", ")", "{", "c", ".", "defaultTags", "=", "tags", "\n", "}", "\n", "}" ]
// ClientTags adds default Tags to inject into client application spans.
[ "ClientTags", "adds", "default", "Tags", "to", "inject", "into", "client", "application", "spans", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/middleware/http/client.go#L60-L64
train
openzipkin/zipkin-go
middleware/http/client.go
NewClient
func NewClient(tracer *zipkin.Tracer, options ...ClientOption) (*Client, error) { if tracer == nil { return nil, ErrValidTracerRequired } c := &Client{tracer: tracer, Client: &http.Client{}} for _, option := range options { option(c) } c.transportOptions = append( c.transportOptions, // the following Client settings override provided transport settings. RoundTripper(c.Client.Transport), TransportTrace(c.httpTrace), ) transport, err := NewTransport(tracer, c.transportOptions...) if err != nil { return nil, err } c.Client.Transport = transport return c, nil }
go
func NewClient(tracer *zipkin.Tracer, options ...ClientOption) (*Client, error) { if tracer == nil { return nil, ErrValidTracerRequired } c := &Client{tracer: tracer, Client: &http.Client{}} for _, option := range options { option(c) } c.transportOptions = append( c.transportOptions, // the following Client settings override provided transport settings. RoundTripper(c.Client.Transport), TransportTrace(c.httpTrace), ) transport, err := NewTransport(tracer, c.transportOptions...) if err != nil { return nil, err } c.Client.Transport = transport return c, nil }
[ "func", "NewClient", "(", "tracer", "*", "zipkin", ".", "Tracer", ",", "options", "...", "ClientOption", ")", "(", "*", "Client", ",", "error", ")", "{", "if", "tracer", "==", "nil", "{", "return", "nil", ",", "ErrValidTracerRequired", "\n", "}", "\n", ...
// NewClient returns an HTTP Client adding Zipkin instrumentation around an // embedded standard Go http.Client.
[ "NewClient", "returns", "an", "HTTP", "Client", "adding", "Zipkin", "instrumentation", "around", "an", "embedded", "standard", "Go", "http", ".", "Client", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/middleware/http/client.go#L76-L99
train
openzipkin/zipkin-go
middleware/http/client.go
DoWithAppSpan
func (c *Client) DoWithAppSpan(req *http.Request, name string) (res *http.Response, err error) { var parentContext model.SpanContext if span := zipkin.SpanFromContext(req.Context()); span != nil { parentContext = span.Context() } appSpan := c.tracer.StartSpan(name, zipkin.Parent(parentContext)) zipkin.TagHTTPMethod.Set(appSpan, req.Method) zipkin.TagHTTPPath.Set(appSpan, req.URL.Path) res, err = c.Client.Do( req.WithContext(zipkin.NewContext(req.Context(), appSpan)), ) if err != nil { zipkin.TagError.Set(appSpan, err.Error()) appSpan.Finish() return } if c.httpTrace { appSpan.Annotate(time.Now(), "wr") } if res.ContentLength > 0 { zipkin.TagHTTPResponseSize.Set(appSpan, strconv.FormatInt(res.ContentLength, 10)) } if res.StatusCode < 200 || res.StatusCode > 299 { statusCode := strconv.FormatInt(int64(res.StatusCode), 10) zipkin.TagHTTPStatusCode.Set(appSpan, statusCode) if res.StatusCode > 399 { zipkin.TagError.Set(appSpan, statusCode) } } res.Body = &spanCloser{ ReadCloser: res.Body, sp: appSpan, traceEnabled: c.httpTrace, } return }
go
func (c *Client) DoWithAppSpan(req *http.Request, name string) (res *http.Response, err error) { var parentContext model.SpanContext if span := zipkin.SpanFromContext(req.Context()); span != nil { parentContext = span.Context() } appSpan := c.tracer.StartSpan(name, zipkin.Parent(parentContext)) zipkin.TagHTTPMethod.Set(appSpan, req.Method) zipkin.TagHTTPPath.Set(appSpan, req.URL.Path) res, err = c.Client.Do( req.WithContext(zipkin.NewContext(req.Context(), appSpan)), ) if err != nil { zipkin.TagError.Set(appSpan, err.Error()) appSpan.Finish() return } if c.httpTrace { appSpan.Annotate(time.Now(), "wr") } if res.ContentLength > 0 { zipkin.TagHTTPResponseSize.Set(appSpan, strconv.FormatInt(res.ContentLength, 10)) } if res.StatusCode < 200 || res.StatusCode > 299 { statusCode := strconv.FormatInt(int64(res.StatusCode), 10) zipkin.TagHTTPStatusCode.Set(appSpan, statusCode) if res.StatusCode > 399 { zipkin.TagError.Set(appSpan, statusCode) } } res.Body = &spanCloser{ ReadCloser: res.Body, sp: appSpan, traceEnabled: c.httpTrace, } return }
[ "func", "(", "c", "*", "Client", ")", "DoWithAppSpan", "(", "req", "*", "http", ".", "Request", ",", "name", "string", ")", "(", "res", "*", "http", ".", "Response", ",", "err", "error", ")", "{", "var", "parentContext", "model", ".", "SpanContext", ...
// DoWithAppSpan wraps http.Client's Do with tracing using an application span.
[ "DoWithAppSpan", "wraps", "http", ".", "Client", "s", "Do", "with", "tracing", "using", "an", "application", "span", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/middleware/http/client.go#L102-L144
train
openzipkin/zipkin-go
model/annotation.go
MarshalJSON
func (a *Annotation) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { Timestamp int64 `json:"timestamp"` Value string `json:"value"` }{ Timestamp: a.Timestamp.Round(time.Microsecond).UnixNano() / 1e3, Value: a.Value, }) }
go
func (a *Annotation) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { Timestamp int64 `json:"timestamp"` Value string `json:"value"` }{ Timestamp: a.Timestamp.Round(time.Microsecond).UnixNano() / 1e3, Value: a.Value, }) }
[ "func", "(", "a", "*", "Annotation", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "json", ".", "Marshal", "(", "&", "struct", "{", "Timestamp", "int64", "`json:\"timestamp\"`", "\n", "Value", "string", "`json:\"v...
// MarshalJSON implements custom JSON encoding
[ "MarshalJSON", "implements", "custom", "JSON", "encoding" ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/model/annotation.go#L33-L41
train
openzipkin/zipkin-go
model/annotation.go
UnmarshalJSON
func (a *Annotation) UnmarshalJSON(b []byte) error { type Alias Annotation annotation := &struct { TimeStamp uint64 `json:"timestamp"` *Alias }{ Alias: (*Alias)(a), } if err := json.Unmarshal(b, &annotation); err != nil { return err } if annotation.TimeStamp < 1 { return ErrValidTimestampRequired } a.Timestamp = time.Unix(0, int64(annotation.TimeStamp)*1e3) return nil }
go
func (a *Annotation) UnmarshalJSON(b []byte) error { type Alias Annotation annotation := &struct { TimeStamp uint64 `json:"timestamp"` *Alias }{ Alias: (*Alias)(a), } if err := json.Unmarshal(b, &annotation); err != nil { return err } if annotation.TimeStamp < 1 { return ErrValidTimestampRequired } a.Timestamp = time.Unix(0, int64(annotation.TimeStamp)*1e3) return nil }
[ "func", "(", "a", "*", "Annotation", ")", "UnmarshalJSON", "(", "b", "[", "]", "byte", ")", "error", "{", "type", "Alias", "Annotation", "\n", "annotation", ":=", "&", "struct", "{", "TimeStamp", "uint64", "`json:\"timestamp\"`", "\n", "*", "Alias", "\n", ...
// UnmarshalJSON implements custom JSON decoding
[ "UnmarshalJSON", "implements", "custom", "JSON", "decoding" ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/model/annotation.go#L44-L60
train
openzipkin/zipkin-go
propagation/b3/http.go
ExtractHTTP
func ExtractHTTP(r *http.Request) propagation.Extractor { return func() (*model.SpanContext, error) { var ( traceIDHeader = r.Header.Get(TraceID) spanIDHeader = r.Header.Get(SpanID) parentSpanIDHeader = r.Header.Get(ParentSpanID) sampledHeader = r.Header.Get(Sampled) flagsHeader = r.Header.Get(Flags) ) return ParseHeaders( traceIDHeader, spanIDHeader, parentSpanIDHeader, sampledHeader, flagsHeader, ) } }
go
func ExtractHTTP(r *http.Request) propagation.Extractor { return func() (*model.SpanContext, error) { var ( traceIDHeader = r.Header.Get(TraceID) spanIDHeader = r.Header.Get(SpanID) parentSpanIDHeader = r.Header.Get(ParentSpanID) sampledHeader = r.Header.Get(Sampled) flagsHeader = r.Header.Get(Flags) ) return ParseHeaders( traceIDHeader, spanIDHeader, parentSpanIDHeader, sampledHeader, flagsHeader, ) } }
[ "func", "ExtractHTTP", "(", "r", "*", "http", ".", "Request", ")", "propagation", ".", "Extractor", "{", "return", "func", "(", ")", "(", "*", "model", ".", "SpanContext", ",", "error", ")", "{", "var", "(", "traceIDHeader", "=", "r", ".", "Header", ...
// ExtractHTTP will extract a span.Context from the HTTP Request if found in // B3 header format.
[ "ExtractHTTP", "will", "extract", "a", "span", ".", "Context", "from", "the", "HTTP", "Request", "if", "found", "in", "B3", "header", "format", "." ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/propagation/b3/http.go#L26-L41
train
openzipkin/zipkin-go
propagation/b3/http.go
InjectHTTP
func InjectHTTP(r *http.Request) propagation.Injector { return func(sc model.SpanContext) error { if (model.SpanContext{}) == sc { return ErrEmptyContext } if sc.Debug { r.Header.Set(Flags, "1") } else if sc.Sampled != nil { // Debug is encoded as X-B3-Flags: 1. Since Debug implies Sampled, // so don't also send "X-B3-Sampled: 1". if *sc.Sampled { r.Header.Set(Sampled, "1") } else { r.Header.Set(Sampled, "0") } } if !sc.TraceID.Empty() && sc.ID > 0 { r.Header.Set(TraceID, sc.TraceID.String()) r.Header.Set(SpanID, sc.ID.String()) if sc.ParentID != nil { r.Header.Set(ParentSpanID, sc.ParentID.String()) } } return nil } }
go
func InjectHTTP(r *http.Request) propagation.Injector { return func(sc model.SpanContext) error { if (model.SpanContext{}) == sc { return ErrEmptyContext } if sc.Debug { r.Header.Set(Flags, "1") } else if sc.Sampled != nil { // Debug is encoded as X-B3-Flags: 1. Since Debug implies Sampled, // so don't also send "X-B3-Sampled: 1". if *sc.Sampled { r.Header.Set(Sampled, "1") } else { r.Header.Set(Sampled, "0") } } if !sc.TraceID.Empty() && sc.ID > 0 { r.Header.Set(TraceID, sc.TraceID.String()) r.Header.Set(SpanID, sc.ID.String()) if sc.ParentID != nil { r.Header.Set(ParentSpanID, sc.ParentID.String()) } } return nil } }
[ "func", "InjectHTTP", "(", "r", "*", "http", ".", "Request", ")", "propagation", ".", "Injector", "{", "return", "func", "(", "sc", "model", ".", "SpanContext", ")", "error", "{", "if", "(", "model", ".", "SpanContext", "{", "}", ")", "==", "sc", "{"...
// InjectHTTP will inject a span.Context into a HTTP Request
[ "InjectHTTP", "will", "inject", "a", "span", ".", "Context", "into", "a", "HTTP", "Request" ]
a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962
https://github.com/openzipkin/zipkin-go/blob/a9beb3b3ee82f8d9336022a1c2ed7c1f4f5d6962/propagation/b3/http.go#L44-L72
train
mholt/archiver
rar.go
Unarchive
func (r *Rar) Unarchive(source, destination string) error { if !fileExists(destination) && r.MkdirAll { err := mkdir(destination, 0755) if err != nil { return fmt.Errorf("preparing destination: %v", err) } } // if the files in the archive do not all share a common // root, then make sure we extract to a single subfolder // rather than potentially littering the destination... if r.ImplicitTopLevelFolder { var err error destination, err = r.addTopLevelFolder(source, destination) if err != nil { return fmt.Errorf("scanning source archive: %v", err) } } err := r.OpenFile(source) if err != nil { return fmt.Errorf("opening rar archive for reading: %v", err) } defer r.Close() for { err := r.unrarNext(destination) if err == io.EOF { break } if err != nil { if r.ContinueOnError { log.Printf("[ERROR] Reading file in rar archive: %v", err) continue } return fmt.Errorf("reading file in rar archive: %v", err) } } return nil }
go
func (r *Rar) Unarchive(source, destination string) error { if !fileExists(destination) && r.MkdirAll { err := mkdir(destination, 0755) if err != nil { return fmt.Errorf("preparing destination: %v", err) } } // if the files in the archive do not all share a common // root, then make sure we extract to a single subfolder // rather than potentially littering the destination... if r.ImplicitTopLevelFolder { var err error destination, err = r.addTopLevelFolder(source, destination) if err != nil { return fmt.Errorf("scanning source archive: %v", err) } } err := r.OpenFile(source) if err != nil { return fmt.Errorf("opening rar archive for reading: %v", err) } defer r.Close() for { err := r.unrarNext(destination) if err == io.EOF { break } if err != nil { if r.ContinueOnError { log.Printf("[ERROR] Reading file in rar archive: %v", err) continue } return fmt.Errorf("reading file in rar archive: %v", err) } } return nil }
[ "func", "(", "r", "*", "Rar", ")", "Unarchive", "(", "source", ",", "destination", "string", ")", "error", "{", "if", "!", "fileExists", "(", "destination", ")", "&&", "r", ".", "MkdirAll", "{", "err", ":=", "mkdir", "(", "destination", ",", "0755", ...
// Unarchive unpacks the .rar file at source to destination. // Destination will be treated as a folder name. It supports // multi-volume archives.
[ "Unarchive", "unpacks", "the", ".", "rar", "file", "at", "source", "to", "destination", ".", "Destination", "will", "be", "treated", "as", "a", "folder", "name", ".", "It", "supports", "multi", "-", "volume", "archives", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/rar.go#L66-L106
train
mholt/archiver
rar.go
Extract
func (r *Rar) Extract(source, target, destination string) error { // target refers to a path inside the archive, which should be clean also target = path.Clean(target) // if the target ends up being a directory, then // we will continue walking and extracting files // until we are no longer within that directory var targetDirPath string return r.Walk(source, func(f File) error { th, ok := f.Header.(*rardecode.FileHeader) if !ok { return fmt.Errorf("expected header to be *rardecode.FileHeader but was %T", f.Header) } // importantly, cleaning the path strips tailing slash, // which must be appended to folders within the archive name := path.Clean(th.Name) if f.IsDir() && target == name { targetDirPath = path.Dir(name) } if within(target, th.Name) { // either this is the exact file we want, or is // in the directory we want to extract // build the filename we will extract to end, err := filepath.Rel(targetDirPath, th.Name) if err != nil { return fmt.Errorf("relativizing paths: %v", err) } joined := filepath.Join(destination, end) err = r.unrarFile(f, joined) if err != nil { return fmt.Errorf("extracting file %s: %v", th.Name, err) } // if our target was not a directory, stop walk if targetDirPath == "" { return ErrStopWalk } } else if targetDirPath != "" { // finished walking the entire directory return ErrStopWalk } return nil }) }
go
func (r *Rar) Extract(source, target, destination string) error { // target refers to a path inside the archive, which should be clean also target = path.Clean(target) // if the target ends up being a directory, then // we will continue walking and extracting files // until we are no longer within that directory var targetDirPath string return r.Walk(source, func(f File) error { th, ok := f.Header.(*rardecode.FileHeader) if !ok { return fmt.Errorf("expected header to be *rardecode.FileHeader but was %T", f.Header) } // importantly, cleaning the path strips tailing slash, // which must be appended to folders within the archive name := path.Clean(th.Name) if f.IsDir() && target == name { targetDirPath = path.Dir(name) } if within(target, th.Name) { // either this is the exact file we want, or is // in the directory we want to extract // build the filename we will extract to end, err := filepath.Rel(targetDirPath, th.Name) if err != nil { return fmt.Errorf("relativizing paths: %v", err) } joined := filepath.Join(destination, end) err = r.unrarFile(f, joined) if err != nil { return fmt.Errorf("extracting file %s: %v", th.Name, err) } // if our target was not a directory, stop walk if targetDirPath == "" { return ErrStopWalk } } else if targetDirPath != "" { // finished walking the entire directory return ErrStopWalk } return nil }) }
[ "func", "(", "r", "*", "Rar", ")", "Extract", "(", "source", ",", "target", ",", "destination", "string", ")", "error", "{", "target", "=", "path", ".", "Clean", "(", "target", ")", "\n", "var", "targetDirPath", "string", "\n", "return", "r", ".", "W...
// Extract extracts a single file from the rar archive. // If the target is a directory, the entire folder will // be extracted into destination.
[ "Extract", "extracts", "a", "single", "file", "from", "the", "rar", "archive", ".", "If", "the", "target", "is", "a", "directory", "the", "entire", "folder", "will", "be", "extracted", "into", "destination", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/rar.go#L304-L353
train
mholt/archiver
tarxz.go
Archive
func (txz *TarXz) Archive(sources []string, destination string) error { err := txz.CheckExt(destination) if err != nil { return fmt.Errorf("output %s", err.Error()) } txz.wrapWriter() return txz.Tar.Archive(sources, destination) }
go
func (txz *TarXz) Archive(sources []string, destination string) error { err := txz.CheckExt(destination) if err != nil { return fmt.Errorf("output %s", err.Error()) } txz.wrapWriter() return txz.Tar.Archive(sources, destination) }
[ "func", "(", "txz", "*", "TarXz", ")", "Archive", "(", "sources", "[", "]", "string", ",", "destination", "string", ")", "error", "{", "err", ":=", "txz", ".", "CheckExt", "(", "destination", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt",...
// Archive creates a compressed tar file at destination // containing the files listed in sources. The destination // must end with ".tar.xz" or ".txz". File paths can be // those of regular files or directories; directories will // be recursively added.
[ "Archive", "creates", "a", "compressed", "tar", "file", "at", "destination", "containing", "the", "files", "listed", "in", "sources", ".", "The", "destination", "must", "end", "with", ".", "tar", ".", "xz", "or", ".", "txz", ".", "File", "paths", "can", ...
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/tarxz.go#L33-L40
train
mholt/archiver
tar.go
Archive
func (t *Tar) Archive(sources []string, destination string) error { err := t.CheckExt(destination) if t.writerWrapFn == nil && err != nil { return fmt.Errorf("checking extension: %v", err) } if !t.OverwriteExisting && fileExists(destination) { return fmt.Errorf("file already exists: %s", destination) } // make the folder to contain the resulting archive // if it does not already exist destDir := filepath.Dir(destination) if t.MkdirAll && !fileExists(destDir) { err := mkdir(destDir, 0755) if err != nil { return fmt.Errorf("making folder for destination: %v", err) } } out, err := os.Create(destination) if err != nil { return fmt.Errorf("creating %s: %v", destination, err) } defer out.Close() err = t.Create(out) if err != nil { return fmt.Errorf("creating tar: %v", err) } defer t.Close() var topLevelFolder string if t.ImplicitTopLevelFolder && multipleTopLevels(sources) { topLevelFolder = folderNameFromFileName(destination) } for _, source := range sources { err := t.writeWalk(source, topLevelFolder, destination) if err != nil { return fmt.Errorf("walking %s: %v", source, err) } } return nil }
go
func (t *Tar) Archive(sources []string, destination string) error { err := t.CheckExt(destination) if t.writerWrapFn == nil && err != nil { return fmt.Errorf("checking extension: %v", err) } if !t.OverwriteExisting && fileExists(destination) { return fmt.Errorf("file already exists: %s", destination) } // make the folder to contain the resulting archive // if it does not already exist destDir := filepath.Dir(destination) if t.MkdirAll && !fileExists(destDir) { err := mkdir(destDir, 0755) if err != nil { return fmt.Errorf("making folder for destination: %v", err) } } out, err := os.Create(destination) if err != nil { return fmt.Errorf("creating %s: %v", destination, err) } defer out.Close() err = t.Create(out) if err != nil { return fmt.Errorf("creating tar: %v", err) } defer t.Close() var topLevelFolder string if t.ImplicitTopLevelFolder && multipleTopLevels(sources) { topLevelFolder = folderNameFromFileName(destination) } for _, source := range sources { err := t.writeWalk(source, topLevelFolder, destination) if err != nil { return fmt.Errorf("walking %s: %v", source, err) } } return nil }
[ "func", "(", "t", "*", "Tar", ")", "Archive", "(", "sources", "[", "]", "string", ",", "destination", "string", ")", "error", "{", "err", ":=", "t", ".", "CheckExt", "(", "destination", ")", "\n", "if", "t", ".", "writerWrapFn", "==", "nil", "&&", ...
// Archive creates a tarball file at destination containing // the files listed in sources. The destination must end with // ".tar". File paths can be those of regular files or // directories; directories will be recursively added.
[ "Archive", "creates", "a", "tarball", "file", "at", "destination", "containing", "the", "files", "listed", "in", "sources", ".", "The", "destination", "must", "end", "with", ".", "tar", ".", "File", "paths", "can", "be", "those", "of", "regular", "files", ...
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/tar.go#L68-L112
train
mholt/archiver
tar.go
Unarchive
func (t *Tar) Unarchive(source, destination string) error { if !fileExists(destination) && t.MkdirAll { err := mkdir(destination, 0755) if err != nil { return fmt.Errorf("preparing destination: %v", err) } } // if the files in the archive do not all share a common // root, then make sure we extract to a single subfolder // rather than potentially littering the destination... if t.ImplicitTopLevelFolder { var err error destination, err = t.addTopLevelFolder(source, destination) if err != nil { return fmt.Errorf("scanning source archive: %v", err) } } file, err := os.Open(source) if err != nil { return fmt.Errorf("opening source archive: %v", err) } defer file.Close() err = t.Open(file, 0) if err != nil { return fmt.Errorf("opening tar archive for reading: %v", err) } defer t.Close() for { err := t.untarNext(destination) if err == io.EOF { break } if err != nil { if t.ContinueOnError { log.Printf("[ERROR] Reading file in tar archive: %v", err) continue } return fmt.Errorf("reading file in tar archive: %v", err) } } return nil }
go
func (t *Tar) Unarchive(source, destination string) error { if !fileExists(destination) && t.MkdirAll { err := mkdir(destination, 0755) if err != nil { return fmt.Errorf("preparing destination: %v", err) } } // if the files in the archive do not all share a common // root, then make sure we extract to a single subfolder // rather than potentially littering the destination... if t.ImplicitTopLevelFolder { var err error destination, err = t.addTopLevelFolder(source, destination) if err != nil { return fmt.Errorf("scanning source archive: %v", err) } } file, err := os.Open(source) if err != nil { return fmt.Errorf("opening source archive: %v", err) } defer file.Close() err = t.Open(file, 0) if err != nil { return fmt.Errorf("opening tar archive for reading: %v", err) } defer t.Close() for { err := t.untarNext(destination) if err == io.EOF { break } if err != nil { if t.ContinueOnError { log.Printf("[ERROR] Reading file in tar archive: %v", err) continue } return fmt.Errorf("reading file in tar archive: %v", err) } } return nil }
[ "func", "(", "t", "*", "Tar", ")", "Unarchive", "(", "source", ",", "destination", "string", ")", "error", "{", "if", "!", "fileExists", "(", "destination", ")", "&&", "t", ".", "MkdirAll", "{", "err", ":=", "mkdir", "(", "destination", ",", "0755", ...
// Unarchive unpacks the .tar file at source to destination. // Destination will be treated as a folder name.
[ "Unarchive", "unpacks", "the", ".", "tar", "file", "at", "source", "to", "destination", ".", "Destination", "will", "be", "treated", "as", "a", "folder", "name", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/tar.go#L116-L162
train
mholt/archiver
tar.go
Create
func (t *Tar) Create(out io.Writer) error { if t.tw != nil { return fmt.Errorf("tar archive is already created for writing") } // wrapping writers allows us to output // compressed tarballs, for example if t.writerWrapFn != nil { var err error out, err = t.writerWrapFn(out) if err != nil { return fmt.Errorf("wrapping writer: %v", err) } } t.tw = tar.NewWriter(out) return nil }
go
func (t *Tar) Create(out io.Writer) error { if t.tw != nil { return fmt.Errorf("tar archive is already created for writing") } // wrapping writers allows us to output // compressed tarballs, for example if t.writerWrapFn != nil { var err error out, err = t.writerWrapFn(out) if err != nil { return fmt.Errorf("wrapping writer: %v", err) } } t.tw = tar.NewWriter(out) return nil }
[ "func", "(", "t", "*", "Tar", ")", "Create", "(", "out", "io", ".", "Writer", ")", "error", "{", "if", "t", ".", "tw", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"tar archive is already created for writing\"", ")", "\n", "}", "\n", "if", ...
// Create opens t for writing a tar archive to out.
[ "Create", "opens", "t", "for", "writing", "a", "tar", "archive", "to", "out", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/tar.go#L312-L329
train
mholt/archiver
tar.go
Write
func (t *Tar) Write(f File) error { if t.tw == nil { return fmt.Errorf("tar archive was not created for writing first") } if f.FileInfo == nil { return fmt.Errorf("no file info") } if f.FileInfo.Name() == "" { return fmt.Errorf("missing file name") } var linkTarget string if isSymlink(f) { var err error linkTarget, err = os.Readlink(f.Name()) if err != nil { return fmt.Errorf("%s: readlink: %v", f.Name(), err) } } hdr, err := tar.FileInfoHeader(f, filepath.ToSlash(linkTarget)) if err != nil { return fmt.Errorf("%s: making header: %v", f.Name(), err) } err = t.tw.WriteHeader(hdr) if err != nil { return fmt.Errorf("%s: writing header: %v", hdr.Name, err) } if f.IsDir() { return nil // directories have no contents } if hdr.Typeflag == tar.TypeReg { if f.ReadCloser == nil { return fmt.Errorf("%s: no way to read file contents", f.Name()) } _, err := io.Copy(t.tw, f) if err != nil { return fmt.Errorf("%s: copying contents: %v", f.Name(), err) } } return nil }
go
func (t *Tar) Write(f File) error { if t.tw == nil { return fmt.Errorf("tar archive was not created for writing first") } if f.FileInfo == nil { return fmt.Errorf("no file info") } if f.FileInfo.Name() == "" { return fmt.Errorf("missing file name") } var linkTarget string if isSymlink(f) { var err error linkTarget, err = os.Readlink(f.Name()) if err != nil { return fmt.Errorf("%s: readlink: %v", f.Name(), err) } } hdr, err := tar.FileInfoHeader(f, filepath.ToSlash(linkTarget)) if err != nil { return fmt.Errorf("%s: making header: %v", f.Name(), err) } err = t.tw.WriteHeader(hdr) if err != nil { return fmt.Errorf("%s: writing header: %v", hdr.Name, err) } if f.IsDir() { return nil // directories have no contents } if hdr.Typeflag == tar.TypeReg { if f.ReadCloser == nil { return fmt.Errorf("%s: no way to read file contents", f.Name()) } _, err := io.Copy(t.tw, f) if err != nil { return fmt.Errorf("%s: copying contents: %v", f.Name(), err) } } return nil }
[ "func", "(", "t", "*", "Tar", ")", "Write", "(", "f", "File", ")", "error", "{", "if", "t", ".", "tw", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"tar archive was not created for writing first\"", ")", "\n", "}", "\n", "if", "f", ".", "...
// Write writes f to t, which must have been opened for writing first.
[ "Write", "writes", "f", "to", "t", "which", "must", "have", "been", "opened", "for", "writing", "first", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/tar.go#L332-L377
train
mholt/archiver
tar.go
hasTarHeader
func hasTarHeader(buf []byte) bool { if len(buf) < tarBlockSize { return false } b := buf[148:156] b = bytes.Trim(b, " \x00") // clean up all spaces and null bytes if len(b) == 0 { return false // unknown format } hdrSum, err := strconv.ParseUint(string(b), 8, 64) if err != nil { return false } // According to the go official archive/tar, Sun tar uses signed byte // values so this calcs both signed and unsigned var usum uint64 var sum int64 for i, c := range buf { if 148 <= i && i < 156 { c = ' ' // checksum field itself is counted as branks } usum += uint64(uint8(c)) sum += int64(int8(c)) } if hdrSum != usum && int64(hdrSum) != sum { return false // invalid checksum } return true }
go
func hasTarHeader(buf []byte) bool { if len(buf) < tarBlockSize { return false } b := buf[148:156] b = bytes.Trim(b, " \x00") // clean up all spaces and null bytes if len(b) == 0 { return false // unknown format } hdrSum, err := strconv.ParseUint(string(b), 8, 64) if err != nil { return false } // According to the go official archive/tar, Sun tar uses signed byte // values so this calcs both signed and unsigned var usum uint64 var sum int64 for i, c := range buf { if 148 <= i && i < 156 { c = ' ' // checksum field itself is counted as branks } usum += uint64(uint8(c)) sum += int64(int8(c)) } if hdrSum != usum && int64(hdrSum) != sum { return false // invalid checksum } return true }
[ "func", "hasTarHeader", "(", "buf", "[", "]", "byte", ")", "bool", "{", "if", "len", "(", "buf", ")", "<", "tarBlockSize", "{", "return", "false", "\n", "}", "\n", "b", ":=", "buf", "[", "148", ":", "156", "]", "\n", "b", "=", "bytes", ".", "Tr...
// hasTarHeader checks passed bytes has a valid tar header or not. buf must // contain at least 512 bytes and if not, it always returns false.
[ "hasTarHeader", "checks", "passed", "bytes", "has", "a", "valid", "tar", "header", "or", "not", ".", "buf", "must", "contain", "at", "least", "512", "bytes", "and", "if", "not", "it", "always", "returns", "false", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/tar.go#L558-L590
train
mholt/archiver
tarlz4.go
Archive
func (tlz4 *TarLz4) Archive(sources []string, destination string) error { err := tlz4.CheckExt(destination) if err != nil { return fmt.Errorf("output %s", err.Error()) } tlz4.wrapWriter() return tlz4.Tar.Archive(sources, destination) }
go
func (tlz4 *TarLz4) Archive(sources []string, destination string) error { err := tlz4.CheckExt(destination) if err != nil { return fmt.Errorf("output %s", err.Error()) } tlz4.wrapWriter() return tlz4.Tar.Archive(sources, destination) }
[ "func", "(", "tlz4", "*", "TarLz4", ")", "Archive", "(", "sources", "[", "]", "string", ",", "destination", "string", ")", "error", "{", "err", ":=", "tlz4", ".", "CheckExt", "(", "destination", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fm...
// Archive creates a compressed tar file at destination // containing the files listed in sources. The destination // must end with ".tar.lz4" or ".tlz4". File paths can be // those of regular files or directories; directories will // be recursively added.
[ "Archive", "creates", "a", "compressed", "tar", "file", "at", "destination", "containing", "the", "files", "listed", "in", "sources", ".", "The", "destination", "must", "end", "with", ".", "tar", ".", "lz4", "or", ".", "tlz4", ".", "File", "paths", "can", ...
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/tarlz4.go#L38-L45
train
mholt/archiver
tarlz4.go
Create
func (tlz4 *TarLz4) Create(out io.Writer) error { tlz4.wrapWriter() return tlz4.Tar.Create(out) }
go
func (tlz4 *TarLz4) Create(out io.Writer) error { tlz4.wrapWriter() return tlz4.Tar.Create(out) }
[ "func", "(", "tlz4", "*", "TarLz4", ")", "Create", "(", "out", "io", ".", "Writer", ")", "error", "{", "tlz4", ".", "wrapWriter", "(", ")", "\n", "return", "tlz4", ".", "Tar", ".", "Create", "(", "out", ")", "\n", "}" ]
// Create opens tlz4 for writing a compressed // tar archive to out.
[ "Create", "opens", "tlz4", "for", "writing", "a", "compressed", "tar", "archive", "to", "out", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/tarlz4.go#L63-L66
train
mholt/archiver
tarsz.go
Archive
func (tsz *TarSz) Archive(sources []string, destination string) error { err := tsz.CheckExt(destination) if err != nil { return fmt.Errorf("output %s", err.Error()) } tsz.wrapWriter() return tsz.Tar.Archive(sources, destination) }
go
func (tsz *TarSz) Archive(sources []string, destination string) error { err := tsz.CheckExt(destination) if err != nil { return fmt.Errorf("output %s", err.Error()) } tsz.wrapWriter() return tsz.Tar.Archive(sources, destination) }
[ "func", "(", "tsz", "*", "TarSz", ")", "Archive", "(", "sources", "[", "]", "string", ",", "destination", "string", ")", "error", "{", "err", ":=", "tsz", ".", "CheckExt", "(", "destination", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt",...
// Archive creates a compressed tar file at destination // containing the files listed in sources. The destination // must end with ".tar.sz" or ".tsz". File paths can be // those of regular files or directories; directories will // be recursively added.
[ "Archive", "creates", "a", "compressed", "tar", "file", "at", "destination", "containing", "the", "files", "listed", "in", "sources", ".", "The", "destination", "must", "end", "with", ".", "tar", ".", "sz", "or", ".", "tsz", ".", "File", "paths", "can", ...
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/tarsz.go#L32-L39
train
mholt/archiver
tarsz.go
Create
func (tsz *TarSz) Create(out io.Writer) error { tsz.wrapWriter() return tsz.Tar.Create(out) }
go
func (tsz *TarSz) Create(out io.Writer) error { tsz.wrapWriter() return tsz.Tar.Create(out) }
[ "func", "(", "tsz", "*", "TarSz", ")", "Create", "(", "out", "io", ".", "Writer", ")", "error", "{", "tsz", ".", "wrapWriter", "(", ")", "\n", "return", "tsz", ".", "Tar", ".", "Create", "(", "out", ")", "\n", "}" ]
// Create opens tsz for writing a compressed // tar archive to out.
[ "Create", "opens", "tsz", "for", "writing", "a", "compressed", "tar", "archive", "to", "out", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/tarsz.go#L57-L60
train
mholt/archiver
targz.go
Archive
func (tgz *TarGz) Archive(sources []string, destination string) error { err := tgz.CheckExt(destination) if err != nil { return fmt.Errorf("output %s", err.Error()) } tgz.wrapWriter() return tgz.Tar.Archive(sources, destination) }
go
func (tgz *TarGz) Archive(sources []string, destination string) error { err := tgz.CheckExt(destination) if err != nil { return fmt.Errorf("output %s", err.Error()) } tgz.wrapWriter() return tgz.Tar.Archive(sources, destination) }
[ "func", "(", "tgz", "*", "TarGz", ")", "Archive", "(", "sources", "[", "]", "string", ",", "destination", "string", ")", "error", "{", "err", ":=", "tgz", ".", "CheckExt", "(", "destination", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt",...
// Archive creates a compressed tar file at destination // containing the files listed in sources. The destination // must end with ".tar.gz" or ".tgz". File paths can be // those of regular files or directories; directories will // be recursively added.
[ "Archive", "creates", "a", "compressed", "tar", "file", "at", "destination", "containing", "the", "files", "listed", "in", "sources", ".", "The", "destination", "must", "end", "with", ".", "tar", ".", "gz", "or", ".", "tgz", ".", "File", "paths", "can", ...
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/targz.go#L34-L41
train
mholt/archiver
tarbz2.go
Archive
func (tbz2 *TarBz2) Archive(sources []string, destination string) error { err := tbz2.CheckExt(destination) if err != nil { return fmt.Errorf("output %s", err.Error()) } tbz2.wrapWriter() return tbz2.Tar.Archive(sources, destination) }
go
func (tbz2 *TarBz2) Archive(sources []string, destination string) error { err := tbz2.CheckExt(destination) if err != nil { return fmt.Errorf("output %s", err.Error()) } tbz2.wrapWriter() return tbz2.Tar.Archive(sources, destination) }
[ "func", "(", "tbz2", "*", "TarBz2", ")", "Archive", "(", "sources", "[", "]", "string", ",", "destination", "string", ")", "error", "{", "err", ":=", "tbz2", ".", "CheckExt", "(", "destination", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fm...
// Archive creates a compressed tar file at destination // containing the files listed in sources. The destination // must end with ".tar.bz2" or ".tbz2". File paths can be // those of regular files or directories; directories will // be recursively added.
[ "Archive", "creates", "a", "compressed", "tar", "file", "at", "destination", "containing", "the", "files", "listed", "in", "sources", ".", "The", "destination", "must", "end", "with", ".", "tar", ".", "bz2", "or", ".", "tbz2", ".", "File", "paths", "can", ...
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/tarbz2.go#L34-L41
train
mholt/archiver
tarbz2.go
Create
func (tbz2 *TarBz2) Create(out io.Writer) error { tbz2.wrapWriter() return tbz2.Tar.Create(out) }
go
func (tbz2 *TarBz2) Create(out io.Writer) error { tbz2.wrapWriter() return tbz2.Tar.Create(out) }
[ "func", "(", "tbz2", "*", "TarBz2", ")", "Create", "(", "out", "io", ".", "Writer", ")", "error", "{", "tbz2", ".", "wrapWriter", "(", ")", "\n", "return", "tbz2", ".", "Tar", ".", "Create", "(", "out", ")", "\n", "}" ]
// Create opens tbz2 for writing a compressed // tar archive to out.
[ "Create", "opens", "tbz2", "for", "writing", "a", "compressed", "tar", "archive", "to", "out", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/tarbz2.go#L59-L62
train
mholt/archiver
zip.go
Unarchive
func (z *Zip) Unarchive(source, destination string) error { if !fileExists(destination) && z.MkdirAll { err := mkdir(destination, 0755) if err != nil { return fmt.Errorf("preparing destination: %v", err) } } file, err := os.Open(source) if err != nil { return fmt.Errorf("opening source file: %v", err) } defer file.Close() fileInfo, err := file.Stat() if err != nil { return fmt.Errorf("statting source file: %v", err) } err = z.Open(file, fileInfo.Size()) if err != nil { return fmt.Errorf("opening zip archive for reading: %v", err) } defer z.Close() // if the files in the archive do not all share a common // root, then make sure we extract to a single subfolder // rather than potentially littering the destination... if z.ImplicitTopLevelFolder { files := make([]string, len(z.zr.File)) for i := range z.zr.File { files[i] = z.zr.File[i].Name } if multipleTopLevels(files) { destination = filepath.Join(destination, folderNameFromFileName(source)) } } for { err := z.extractNext(destination) if err == io.EOF { break } if err != nil { if z.ContinueOnError { log.Printf("[ERROR] Reading file in zip archive: %v", err) continue } return fmt.Errorf("reading file in zip archive: %v", err) } } return nil }
go
func (z *Zip) Unarchive(source, destination string) error { if !fileExists(destination) && z.MkdirAll { err := mkdir(destination, 0755) if err != nil { return fmt.Errorf("preparing destination: %v", err) } } file, err := os.Open(source) if err != nil { return fmt.Errorf("opening source file: %v", err) } defer file.Close() fileInfo, err := file.Stat() if err != nil { return fmt.Errorf("statting source file: %v", err) } err = z.Open(file, fileInfo.Size()) if err != nil { return fmt.Errorf("opening zip archive for reading: %v", err) } defer z.Close() // if the files in the archive do not all share a common // root, then make sure we extract to a single subfolder // rather than potentially littering the destination... if z.ImplicitTopLevelFolder { files := make([]string, len(z.zr.File)) for i := range z.zr.File { files[i] = z.zr.File[i].Name } if multipleTopLevels(files) { destination = filepath.Join(destination, folderNameFromFileName(source)) } } for { err := z.extractNext(destination) if err == io.EOF { break } if err != nil { if z.ContinueOnError { log.Printf("[ERROR] Reading file in zip archive: %v", err) continue } return fmt.Errorf("reading file in zip archive: %v", err) } } return nil }
[ "func", "(", "z", "*", "Zip", ")", "Unarchive", "(", "source", ",", "destination", "string", ")", "error", "{", "if", "!", "fileExists", "(", "destination", ")", "&&", "z", ".", "MkdirAll", "{", "err", ":=", "mkdir", "(", "destination", ",", "0755", ...
// Unarchive unpacks the .zip file at source to destination. // Destination will be treated as a folder name.
[ "Unarchive", "unpacks", "the", ".", "zip", "file", "at", "source", "to", "destination", ".", "Destination", "will", "be", "treated", "as", "a", "folder", "name", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/zip.go#L124-L177
train
mholt/archiver
zip.go
Create
func (z *Zip) Create(out io.Writer) error { if z.zw != nil { return fmt.Errorf("zip archive is already created for writing") } z.zw = zip.NewWriter(out) if z.CompressionLevel != flate.DefaultCompression { z.zw.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) { return flate.NewWriter(out, z.CompressionLevel) }) } return nil }
go
func (z *Zip) Create(out io.Writer) error { if z.zw != nil { return fmt.Errorf("zip archive is already created for writing") } z.zw = zip.NewWriter(out) if z.CompressionLevel != flate.DefaultCompression { z.zw.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) { return flate.NewWriter(out, z.CompressionLevel) }) } return nil }
[ "func", "(", "z", "*", "Zip", ")", "Create", "(", "out", "io", ".", "Writer", ")", "error", "{", "if", "z", ".", "zw", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"zip archive is already created for writing\"", ")", "\n", "}", "\n", "z", ...
// Create opens z for writing a ZIP archive to out.
[ "Create", "opens", "z", "for", "writing", "a", "ZIP", "archive", "to", "out", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/zip.go#L285-L296
train
mholt/archiver
zip.go
Write
func (z *Zip) Write(f File) error { if z.zw == nil { return fmt.Errorf("zip archive was not created for writing first") } if f.FileInfo == nil { return fmt.Errorf("no file info") } if f.FileInfo.Name() == "" { return fmt.Errorf("missing file name") } header, err := zip.FileInfoHeader(f) if err != nil { return fmt.Errorf("%s: getting header: %v", f.Name(), err) } if f.IsDir() { header.Name += "/" // required - strangely no mention of this in zip spec? but is in godoc... header.Method = zip.Store } else { ext := strings.ToLower(path.Ext(header.Name)) if _, ok := compressedFormats[ext]; ok && z.SelectiveCompression { header.Method = zip.Store } else { header.Method = zip.Deflate } } writer, err := z.zw.CreateHeader(header) if err != nil { return fmt.Errorf("%s: making header: %v", f.Name(), err) } return z.writeFile(f, writer) }
go
func (z *Zip) Write(f File) error { if z.zw == nil { return fmt.Errorf("zip archive was not created for writing first") } if f.FileInfo == nil { return fmt.Errorf("no file info") } if f.FileInfo.Name() == "" { return fmt.Errorf("missing file name") } header, err := zip.FileInfoHeader(f) if err != nil { return fmt.Errorf("%s: getting header: %v", f.Name(), err) } if f.IsDir() { header.Name += "/" // required - strangely no mention of this in zip spec? but is in godoc... header.Method = zip.Store } else { ext := strings.ToLower(path.Ext(header.Name)) if _, ok := compressedFormats[ext]; ok && z.SelectiveCompression { header.Method = zip.Store } else { header.Method = zip.Deflate } } writer, err := z.zw.CreateHeader(header) if err != nil { return fmt.Errorf("%s: making header: %v", f.Name(), err) } return z.writeFile(f, writer) }
[ "func", "(", "z", "*", "Zip", ")", "Write", "(", "f", "File", ")", "error", "{", "if", "z", ".", "zw", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"zip archive was not created for writing first\"", ")", "\n", "}", "\n", "if", "f", ".", "...
// Write writes f to z, which must have been opened for writing first.
[ "Write", "writes", "f", "to", "z", "which", "must", "have", "been", "opened", "for", "writing", "first", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/zip.go#L299-L333
train
mholt/archiver
zip.go
Open
func (z *Zip) Open(in io.Reader, size int64) error { inRdrAt, ok := in.(io.ReaderAt) if !ok { return fmt.Errorf("reader must be io.ReaderAt") } if z.zr != nil { return fmt.Errorf("zip archive is already open for reading") } var err error z.zr, err = zip.NewReader(inRdrAt, size) if err != nil { return fmt.Errorf("creating reader: %v", err) } z.ridx = 0 return nil }
go
func (z *Zip) Open(in io.Reader, size int64) error { inRdrAt, ok := in.(io.ReaderAt) if !ok { return fmt.Errorf("reader must be io.ReaderAt") } if z.zr != nil { return fmt.Errorf("zip archive is already open for reading") } var err error z.zr, err = zip.NewReader(inRdrAt, size) if err != nil { return fmt.Errorf("creating reader: %v", err) } z.ridx = 0 return nil }
[ "func", "(", "z", "*", "Zip", ")", "Open", "(", "in", "io", ".", "Reader", ",", "size", "int64", ")", "error", "{", "inRdrAt", ",", "ok", ":=", "in", ".", "(", "io", ".", "ReaderAt", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Err...
// Open opens z for reading an archive from in, // which is expected to have the given size and // which must be an io.ReaderAt.
[ "Open", "opens", "z", "for", "reading", "an", "archive", "from", "in", "which", "is", "expected", "to", "have", "the", "given", "size", "and", "which", "must", "be", "an", "io", ".", "ReaderAt", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/zip.go#L366-L381
train
mholt/archiver
zip.go
Read
func (z *Zip) Read() (File, error) { if z.zr == nil { return File{}, fmt.Errorf("zip archive is not open") } if z.ridx >= len(z.zr.File) { return File{}, io.EOF } // access the file and increment counter so that // if there is an error processing this file, the // caller can still iterate to the next file zf := z.zr.File[z.ridx] z.ridx++ file := File{ FileInfo: zf.FileInfo(), Header: zf.FileHeader, } rc, err := zf.Open() if err != nil { return file, fmt.Errorf("%s: open compressed file: %v", zf.Name, err) } file.ReadCloser = rc return file, nil }
go
func (z *Zip) Read() (File, error) { if z.zr == nil { return File{}, fmt.Errorf("zip archive is not open") } if z.ridx >= len(z.zr.File) { return File{}, io.EOF } // access the file and increment counter so that // if there is an error processing this file, the // caller can still iterate to the next file zf := z.zr.File[z.ridx] z.ridx++ file := File{ FileInfo: zf.FileInfo(), Header: zf.FileHeader, } rc, err := zf.Open() if err != nil { return file, fmt.Errorf("%s: open compressed file: %v", zf.Name, err) } file.ReadCloser = rc return file, nil }
[ "func", "(", "z", "*", "Zip", ")", "Read", "(", ")", "(", "File", ",", "error", ")", "{", "if", "z", ".", "zr", "==", "nil", "{", "return", "File", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"zip archive is not open\"", ")", "\n", "}", "\n", "...
// Read reads the next file from z, which must have // already been opened for reading. If there are no // more files, the error is io.EOF. The File must // be closed when finished reading from it.
[ "Read", "reads", "the", "next", "file", "from", "z", "which", "must", "have", "already", "been", "opened", "for", "reading", ".", "If", "there", "are", "no", "more", "files", "the", "error", "is", "io", ".", "EOF", ".", "The", "File", "must", "be", "...
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/zip.go#L387-L413
train
mholt/archiver
zip.go
Extract
func (z *Zip) Extract(source, target, destination string) error { // target refers to a path inside the archive, which should be clean also target = path.Clean(target) // if the target ends up being a directory, then // we will continue walking and extracting files // until we are no longer within that directory var targetDirPath string return z.Walk(source, func(f File) error { zfh, ok := f.Header.(zip.FileHeader) if !ok { return fmt.Errorf("expected header to be zip.FileHeader but was %T", f.Header) } // importantly, cleaning the path strips tailing slash, // which must be appended to folders within the archive name := path.Clean(zfh.Name) if f.IsDir() && target == name { targetDirPath = path.Dir(name) } if within(target, zfh.Name) { // either this is the exact file we want, or is // in the directory we want to extract // build the filename we will extract to end, err := filepath.Rel(targetDirPath, zfh.Name) if err != nil { return fmt.Errorf("relativizing paths: %v", err) } joined := filepath.Join(destination, end) err = z.extractFile(f, joined) if err != nil { return fmt.Errorf("extracting file %s: %v", zfh.Name, err) } // if our target was not a directory, stop walk if targetDirPath == "" { return ErrStopWalk } } else if targetDirPath != "" { // finished walking the entire directory return ErrStopWalk } return nil }) }
go
func (z *Zip) Extract(source, target, destination string) error { // target refers to a path inside the archive, which should be clean also target = path.Clean(target) // if the target ends up being a directory, then // we will continue walking and extracting files // until we are no longer within that directory var targetDirPath string return z.Walk(source, func(f File) error { zfh, ok := f.Header.(zip.FileHeader) if !ok { return fmt.Errorf("expected header to be zip.FileHeader but was %T", f.Header) } // importantly, cleaning the path strips tailing slash, // which must be appended to folders within the archive name := path.Clean(zfh.Name) if f.IsDir() && target == name { targetDirPath = path.Dir(name) } if within(target, zfh.Name) { // either this is the exact file we want, or is // in the directory we want to extract // build the filename we will extract to end, err := filepath.Rel(targetDirPath, zfh.Name) if err != nil { return fmt.Errorf("relativizing paths: %v", err) } joined := filepath.Join(destination, end) err = z.extractFile(f, joined) if err != nil { return fmt.Errorf("extracting file %s: %v", zfh.Name, err) } // if our target was not a directory, stop walk if targetDirPath == "" { return ErrStopWalk } } else if targetDirPath != "" { // finished walking the entire directory return ErrStopWalk } return nil }) }
[ "func", "(", "z", "*", "Zip", ")", "Extract", "(", "source", ",", "target", ",", "destination", "string", ")", "error", "{", "target", "=", "path", ".", "Clean", "(", "target", ")", "\n", "var", "targetDirPath", "string", "\n", "return", "z", ".", "W...
// Extract extracts a single file from the zip archive. // If the target is a directory, the entire folder will // be extracted into destination.
[ "Extract", "extracts", "a", "single", "file", "from", "the", "zip", "archive", ".", "If", "the", "target", "is", "a", "directory", "the", "entire", "folder", "will", "be", "extracted", "into", "destination", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/zip.go#L471-L520
train
mholt/archiver
zip.go
NewZip
func NewZip() *Zip { return &Zip{ CompressionLevel: flate.DefaultCompression, MkdirAll: true, SelectiveCompression: true, } }
go
func NewZip() *Zip { return &Zip{ CompressionLevel: flate.DefaultCompression, MkdirAll: true, SelectiveCompression: true, } }
[ "func", "NewZip", "(", ")", "*", "Zip", "{", "return", "&", "Zip", "{", "CompressionLevel", ":", "flate", ".", "DefaultCompression", ",", "MkdirAll", ":", "true", ",", "SelectiveCompression", ":", "true", ",", "}", "\n", "}" ]
// NewZip returns a new, default instance ready to be customized and used.
[ "NewZip", "returns", "a", "new", "default", "instance", "ready", "to", "be", "customized", "and", "used", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/zip.go#L545-L551
train
mholt/archiver
archiver.go
Archive
func Archive(sources []string, destination string) error { aIface, err := ByExtension(destination) if err != nil { return err } a, ok := aIface.(Archiver) if !ok { return fmt.Errorf("format specified by destination filename is not an archive format: %s (%T)", destination, aIface) } return a.Archive(sources, destination) }
go
func Archive(sources []string, destination string) error { aIface, err := ByExtension(destination) if err != nil { return err } a, ok := aIface.(Archiver) if !ok { return fmt.Errorf("format specified by destination filename is not an archive format: %s (%T)", destination, aIface) } return a.Archive(sources, destination) }
[ "func", "Archive", "(", "sources", "[", "]", "string", ",", "destination", "string", ")", "error", "{", "aIface", ",", "err", ":=", "ByExtension", "(", "destination", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "a", ",...
// Archive creates an archive of the source files to a new file at destination. // The archive format is chosen implicitly by file extension.
[ "Archive", "creates", "an", "archive", "of", "the", "source", "files", "to", "a", "new", "file", "at", "destination", ".", "The", "archive", "format", "is", "chosen", "implicitly", "by", "file", "extension", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/archiver.go#L186-L196
train
mholt/archiver
archiver.go
Unarchive
func Unarchive(source, destination string) error { uaIface, err := ByExtension(source) if err != nil { return err } u, ok := uaIface.(Unarchiver) if !ok { return fmt.Errorf("format specified by source filename is not an archive format: %s (%T)", source, uaIface) } return u.Unarchive(source, destination) }
go
func Unarchive(source, destination string) error { uaIface, err := ByExtension(source) if err != nil { return err } u, ok := uaIface.(Unarchiver) if !ok { return fmt.Errorf("format specified by source filename is not an archive format: %s (%T)", source, uaIface) } return u.Unarchive(source, destination) }
[ "func", "Unarchive", "(", "source", ",", "destination", "string", ")", "error", "{", "uaIface", ",", "err", ":=", "ByExtension", "(", "source", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "u", ",", "ok", ":=", "uaIface...
// Unarchive unarchives the given archive file into the destination folder. // The archive format is selected implicitly.
[ "Unarchive", "unarchives", "the", "given", "archive", "file", "into", "the", "destination", "folder", ".", "The", "archive", "format", "is", "selected", "implicitly", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/archiver.go#L200-L210
train
mholt/archiver
archiver.go
Walk
func Walk(archive string, walkFn WalkFunc) error { wIface, err := ByExtension(archive) if err != nil { return err } w, ok := wIface.(Walker) if !ok { return fmt.Errorf("format specified by archive filename is not a walker format: %s (%T)", archive, wIface) } return w.Walk(archive, walkFn) }
go
func Walk(archive string, walkFn WalkFunc) error { wIface, err := ByExtension(archive) if err != nil { return err } w, ok := wIface.(Walker) if !ok { return fmt.Errorf("format specified by archive filename is not a walker format: %s (%T)", archive, wIface) } return w.Walk(archive, walkFn) }
[ "func", "Walk", "(", "archive", "string", ",", "walkFn", "WalkFunc", ")", "error", "{", "wIface", ",", "err", ":=", "ByExtension", "(", "archive", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "w", ",", "ok", ":=", "wI...
// Walk calls walkFn for each file within the given archive file. // The archive format is chosen implicitly.
[ "Walk", "calls", "walkFn", "for", "each", "file", "within", "the", "given", "archive", "file", ".", "The", "archive", "format", "is", "chosen", "implicitly", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/archiver.go#L214-L224
train
mholt/archiver
archiver.go
Extract
func Extract(source, target, destination string) error { eIface, err := ByExtension(source) if err != nil { return err } e, ok := eIface.(Extractor) if !ok { return fmt.Errorf("format specified by source filename is not an extractor format: %s (%T)", source, eIface) } return e.Extract(source, target, destination) }
go
func Extract(source, target, destination string) error { eIface, err := ByExtension(source) if err != nil { return err } e, ok := eIface.(Extractor) if !ok { return fmt.Errorf("format specified by source filename is not an extractor format: %s (%T)", source, eIface) } return e.Extract(source, target, destination) }
[ "func", "Extract", "(", "source", ",", "target", ",", "destination", "string", ")", "error", "{", "eIface", ",", "err", ":=", "ByExtension", "(", "source", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "e", ",", "ok", ...
// Extract extracts a single file from the given source archive. If the target // is a directory, the entire folder will be extracted into destination. The // archive format is chosen implicitly.
[ "Extract", "extracts", "a", "single", "file", "from", "the", "given", "source", "archive", ".", "If", "the", "target", "is", "a", "directory", "the", "entire", "folder", "will", "be", "extracted", "into", "destination", ".", "The", "archive", "format", "is",...
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/archiver.go#L229-L239
train
mholt/archiver
archiver.go
CompressFile
func CompressFile(source, destination string) error { cIface, err := ByExtension(destination) if err != nil { return err } c, ok := cIface.(Compressor) if !ok { return fmt.Errorf("format specified by destination filename is not a recognized compression algorithm: %s", destination) } return FileCompressor{Compressor: c}.CompressFile(source, destination) }
go
func CompressFile(source, destination string) error { cIface, err := ByExtension(destination) if err != nil { return err } c, ok := cIface.(Compressor) if !ok { return fmt.Errorf("format specified by destination filename is not a recognized compression algorithm: %s", destination) } return FileCompressor{Compressor: c}.CompressFile(source, destination) }
[ "func", "CompressFile", "(", "source", ",", "destination", "string", ")", "error", "{", "cIface", ",", "err", ":=", "ByExtension", "(", "destination", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "c", ",", "ok", ":=", "...
// CompressFile is a convenience function to simply compress a file. // The compression algorithm is selected implicitly based on the // destination's extension.
[ "CompressFile", "is", "a", "convenience", "function", "to", "simply", "compress", "a", "file", ".", "The", "compression", "algorithm", "is", "selected", "implicitly", "based", "on", "the", "destination", "s", "extension", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/archiver.go#L244-L254
train
mholt/archiver
archiver.go
DecompressFile
func DecompressFile(source, destination string) error { cIface, err := ByExtension(source) if err != nil { return err } c, ok := cIface.(Decompressor) if !ok { return fmt.Errorf("format specified by source filename is not a recognized compression algorithm: %s", source) } return FileCompressor{Decompressor: c}.DecompressFile(source, destination) }
go
func DecompressFile(source, destination string) error { cIface, err := ByExtension(source) if err != nil { return err } c, ok := cIface.(Decompressor) if !ok { return fmt.Errorf("format specified by source filename is not a recognized compression algorithm: %s", source) } return FileCompressor{Decompressor: c}.DecompressFile(source, destination) }
[ "func", "DecompressFile", "(", "source", ",", "destination", "string", ")", "error", "{", "cIface", ",", "err", ":=", "ByExtension", "(", "source", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "c", ",", "ok", ":=", "cIf...
// DecompressFile is a convenience function to simply compress a file. // The compression algorithm is selected implicitly based on the // source's extension.
[ "DecompressFile", "is", "a", "convenience", "function", "to", "simply", "compress", "a", "file", ".", "The", "compression", "algorithm", "is", "selected", "implicitly", "based", "on", "the", "source", "s", "extension", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/archiver.go#L259-L269
train
mholt/archiver
archiver.go
within
func within(parent, sub string) bool { rel, err := filepath.Rel(parent, sub) if err != nil { return false } return !strings.Contains(rel, "..") }
go
func within(parent, sub string) bool { rel, err := filepath.Rel(parent, sub) if err != nil { return false } return !strings.Contains(rel, "..") }
[ "func", "within", "(", "parent", ",", "sub", "string", ")", "bool", "{", "rel", ",", "err", ":=", "filepath", ".", "Rel", "(", "parent", ",", "sub", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "return", "!", "str...
// within returns true if sub is within or equal to parent.
[ "within", "returns", "true", "if", "sub", "is", "within", "or", "equal", "to", "parent", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/archiver.go#L355-L361
train
mholt/archiver
archiver.go
multipleTopLevels
func multipleTopLevels(paths []string) bool { if len(paths) < 2 { return false } var lastTop string for _, p := range paths { p = strings.TrimPrefix(strings.Replace(p, `\`, "/", -1), "/") for { next := path.Dir(p) if next == "." { break } p = next } if lastTop == "" { lastTop = p } if p != lastTop { return true } } return false }
go
func multipleTopLevels(paths []string) bool { if len(paths) < 2 { return false } var lastTop string for _, p := range paths { p = strings.TrimPrefix(strings.Replace(p, `\`, "/", -1), "/") for { next := path.Dir(p) if next == "." { break } p = next } if lastTop == "" { lastTop = p } if p != lastTop { return true } } return false }
[ "func", "multipleTopLevels", "(", "paths", "[", "]", "string", ")", "bool", "{", "if", "len", "(", "paths", ")", "<", "2", "{", "return", "false", "\n", "}", "\n", "var", "lastTop", "string", "\n", "for", "_", ",", "p", ":=", "range", "paths", "{",...
// multipleTopLevels returns true if the paths do not // share a common top-level folder.
[ "multipleTopLevels", "returns", "true", "if", "the", "paths", "do", "not", "share", "a", "common", "top", "-", "level", "folder", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/archiver.go#L365-L387
train
mholt/archiver
archiver.go
folderNameFromFileName
func folderNameFromFileName(filename string) string { base := filepath.Base(filename) firstDot := strings.Index(base, ".") if firstDot > -1 { return base[:firstDot] } return base }
go
func folderNameFromFileName(filename string) string { base := filepath.Base(filename) firstDot := strings.Index(base, ".") if firstDot > -1 { return base[:firstDot] } return base }
[ "func", "folderNameFromFileName", "(", "filename", "string", ")", "string", "{", "base", ":=", "filepath", ".", "Base", "(", "filename", ")", "\n", "firstDot", ":=", "strings", ".", "Index", "(", "base", ",", "\".\"", ")", "\n", "if", "firstDot", ">", "-...
// folderNameFromFileName returns a name for a folder // that is suitable based on the filename, which will // be stripped of its extensions.
[ "folderNameFromFileName", "returns", "a", "name", "for", "a", "folder", "that", "is", "suitable", "based", "on", "the", "filename", "which", "will", "be", "stripped", "of", "its", "extensions", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/archiver.go#L392-L399
train
mholt/archiver
archiver.go
makeNameInArchive
func makeNameInArchive(sourceInfo os.FileInfo, source, baseDir, fpath string) (string, error) { name := filepath.Base(fpath) // start with the file or dir name if sourceInfo.IsDir() { // preserve internal directory structure; that's the path components // between the source directory's leaf and this file's leaf dir, err := filepath.Rel(filepath.Dir(source), filepath.Dir(fpath)) if err != nil { return "", err } // prepend the internal directory structure to the leaf name, // and convert path separators to forward slashes as per spec name = path.Join(filepath.ToSlash(dir), name) } return path.Join(baseDir, name), nil // prepend the base directory }
go
func makeNameInArchive(sourceInfo os.FileInfo, source, baseDir, fpath string) (string, error) { name := filepath.Base(fpath) // start with the file or dir name if sourceInfo.IsDir() { // preserve internal directory structure; that's the path components // between the source directory's leaf and this file's leaf dir, err := filepath.Rel(filepath.Dir(source), filepath.Dir(fpath)) if err != nil { return "", err } // prepend the internal directory structure to the leaf name, // and convert path separators to forward slashes as per spec name = path.Join(filepath.ToSlash(dir), name) } return path.Join(baseDir, name), nil // prepend the base directory }
[ "func", "makeNameInArchive", "(", "sourceInfo", "os", ".", "FileInfo", ",", "source", ",", "baseDir", ",", "fpath", "string", ")", "(", "string", ",", "error", ")", "{", "name", ":=", "filepath", ".", "Base", "(", "fpath", ")", "\n", "if", "sourceInfo", ...
// makeNameInArchive returns the filename for the file given by fpath to be used within // the archive. sourceInfo is the FileInfo obtained by calling os.Stat on source, and baseDir // is an optional base directory that becomes the root of the archive. fpath should be the // unaltered file path of the file given to a filepath.WalkFunc.
[ "makeNameInArchive", "returns", "the", "filename", "for", "the", "file", "given", "by", "fpath", "to", "be", "used", "within", "the", "archive", ".", "sourceInfo", "is", "the", "FileInfo", "obtained", "by", "calling", "os", ".", "Stat", "on", "source", "and"...
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/archiver.go#L405-L419
train
mholt/archiver
archiver.go
NameInArchive
func NameInArchive(sourceInfo os.FileInfo, source, fpath string) (string, error) { return makeNameInArchive(sourceInfo, source, "", fpath) }
go
func NameInArchive(sourceInfo os.FileInfo, source, fpath string) (string, error) { return makeNameInArchive(sourceInfo, source, "", fpath) }
[ "func", "NameInArchive", "(", "sourceInfo", "os", ".", "FileInfo", ",", "source", ",", "fpath", "string", ")", "(", "string", ",", "error", ")", "{", "return", "makeNameInArchive", "(", "sourceInfo", ",", "source", ",", "\"\"", ",", "fpath", ")", "\n", "...
// NameInArchive returns a name for the file at fpath suitable for // the inside of an archive. The source and its associated sourceInfo // is the path where walking a directory started, and if no directory // was walked, source may == fpath. The returned name is essentially // the components of the path between source and fpath, preserving // the internal directory structure.
[ "NameInArchive", "returns", "a", "name", "for", "the", "file", "at", "fpath", "suitable", "for", "the", "inside", "of", "an", "archive", ".", "The", "source", "and", "its", "associated", "sourceInfo", "is", "the", "path", "where", "walking", "a", "directory"...
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/archiver.go#L427-L429
train
mholt/archiver
archiver.go
ByExtension
func ByExtension(filename string) (interface{}, error) { var ec interface{} for _, c := range extCheckers { if err := c.CheckExt(filename); err == nil { ec = c break } } switch ec.(type) { case *Rar: return NewRar(), nil case *Tar: return NewTar(), nil case *TarBz2: return NewTarBz2(), nil case *TarGz: return NewTarGz(), nil case *TarLz4: return NewTarLz4(), nil case *TarSz: return NewTarSz(), nil case *TarXz: return NewTarXz(), nil case *Zip: return NewZip(), nil case *Gz: return NewGz(), nil case *Bz2: return NewBz2(), nil case *Lz4: return NewLz4(), nil case *Snappy: return NewSnappy(), nil case *Xz: return NewXz(), nil } return nil, fmt.Errorf("format unrecognized by filename: %s", filename) }
go
func ByExtension(filename string) (interface{}, error) { var ec interface{} for _, c := range extCheckers { if err := c.CheckExt(filename); err == nil { ec = c break } } switch ec.(type) { case *Rar: return NewRar(), nil case *Tar: return NewTar(), nil case *TarBz2: return NewTarBz2(), nil case *TarGz: return NewTarGz(), nil case *TarLz4: return NewTarLz4(), nil case *TarSz: return NewTarSz(), nil case *TarXz: return NewTarXz(), nil case *Zip: return NewZip(), nil case *Gz: return NewGz(), nil case *Bz2: return NewBz2(), nil case *Lz4: return NewLz4(), nil case *Snappy: return NewSnappy(), nil case *Xz: return NewXz(), nil } return nil, fmt.Errorf("format unrecognized by filename: %s", filename) }
[ "func", "ByExtension", "(", "filename", "string", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "var", "ec", "interface", "{", "}", "\n", "for", "_", ",", "c", ":=", "range", "extCheckers", "{", "if", "err", ":=", "c", ".", "CheckExt", "...
// ByExtension returns an archiver and unarchiver, or compressor // and decompressor, based on the extension of the filename.
[ "ByExtension", "returns", "an", "archiver", "and", "unarchiver", "or", "compressor", "and", "decompressor", "based", "on", "the", "extension", "of", "the", "filename", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/archiver.go#L433-L470
train
mholt/archiver
archiver.go
ByHeader
func ByHeader(input io.ReadSeeker) (Unarchiver, error) { var matcher Matcher for _, m := range matchers { ok, err := m.Match(input) if err != nil { return nil, fmt.Errorf("matching on format %s: %v", m, err) } if ok { matcher = m break } } switch matcher.(type) { case *Zip: return NewZip(), nil case *Tar: return NewTar(), nil case *Rar: return NewRar(), nil } return nil, ErrFormatNotRecognized }
go
func ByHeader(input io.ReadSeeker) (Unarchiver, error) { var matcher Matcher for _, m := range matchers { ok, err := m.Match(input) if err != nil { return nil, fmt.Errorf("matching on format %s: %v", m, err) } if ok { matcher = m break } } switch matcher.(type) { case *Zip: return NewZip(), nil case *Tar: return NewTar(), nil case *Rar: return NewRar(), nil } return nil, ErrFormatNotRecognized }
[ "func", "ByHeader", "(", "input", "io", ".", "ReadSeeker", ")", "(", "Unarchiver", ",", "error", ")", "{", "var", "matcher", "Matcher", "\n", "for", "_", ",", "m", ":=", "range", "matchers", "{", "ok", ",", "err", ":=", "m", ".", "Match", "(", "inp...
// ByHeader returns the unarchiver value that matches the input's // file header. It does not affect the current read position. // If the file's header is not a recognized archive format, then // ErrFormatNotRecognized will be returned.
[ "ByHeader", "returns", "the", "unarchiver", "value", "that", "matches", "the", "input", "s", "file", "header", ".", "It", "does", "not", "affect", "the", "current", "read", "position", ".", "If", "the", "file", "s", "header", "is", "not", "a", "recognized"...
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/archiver.go#L476-L497
train
mholt/archiver
filecompressor.go
CompressFile
func (fc FileCompressor) CompressFile(source, destination string) error { if err := fc.CheckExt(destination); err != nil { return err } if fc.Compressor == nil { return fmt.Errorf("no compressor specified") } if !fc.OverwriteExisting && fileExists(destination) { return fmt.Errorf("file exists: %s", destination) } in, err := os.Open(source) if err != nil { return err } defer in.Close() out, err := os.Create(destination) if err != nil { return err } defer out.Close() return fc.Compress(in, out) }
go
func (fc FileCompressor) CompressFile(source, destination string) error { if err := fc.CheckExt(destination); err != nil { return err } if fc.Compressor == nil { return fmt.Errorf("no compressor specified") } if !fc.OverwriteExisting && fileExists(destination) { return fmt.Errorf("file exists: %s", destination) } in, err := os.Open(source) if err != nil { return err } defer in.Close() out, err := os.Create(destination) if err != nil { return err } defer out.Close() return fc.Compress(in, out) }
[ "func", "(", "fc", "FileCompressor", ")", "CompressFile", "(", "source", ",", "destination", "string", ")", "error", "{", "if", "err", ":=", "fc", ".", "CheckExt", "(", "destination", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n",...
// CompressFile reads the source file and compresses it to destination. // The destination must have a matching extension.
[ "CompressFile", "reads", "the", "source", "file", "and", "compresses", "it", "to", "destination", ".", "The", "destination", "must", "have", "a", "matching", "extension", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/filecompressor.go#L19-L43
train
mholt/archiver
filecompressor.go
DecompressFile
func (fc FileCompressor) DecompressFile(source, destination string) error { if fc.Decompressor == nil { return fmt.Errorf("no decompressor specified") } if !fc.OverwriteExisting && fileExists(destination) { return fmt.Errorf("file exists: %s", destination) } in, err := os.Open(source) if err != nil { return err } defer in.Close() out, err := os.Create(destination) if err != nil { return err } defer out.Close() return fc.Decompress(in, out) }
go
func (fc FileCompressor) DecompressFile(source, destination string) error { if fc.Decompressor == nil { return fmt.Errorf("no decompressor specified") } if !fc.OverwriteExisting && fileExists(destination) { return fmt.Errorf("file exists: %s", destination) } in, err := os.Open(source) if err != nil { return err } defer in.Close() out, err := os.Create(destination) if err != nil { return err } defer out.Close() return fc.Decompress(in, out) }
[ "func", "(", "fc", "FileCompressor", ")", "DecompressFile", "(", "source", ",", "destination", "string", ")", "error", "{", "if", "fc", ".", "Decompressor", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"no decompressor specified\"", ")", "\n", "}...
// DecompressFile reads the source file and decompresses it to destination.
[ "DecompressFile", "reads", "the", "source", "file", "and", "decompresses", "it", "to", "destination", "." ]
5e4ca701b6014549de7fa8734b3c7c5caf98af9e
https://github.com/mholt/archiver/blob/5e4ca701b6014549de7fa8734b3c7c5caf98af9e/filecompressor.go#L46-L67
train
GeertJohan/go.rice
config.go
FindBox
func (c *Config) FindBox(boxName string) (*Box, error) { return findBox(boxName, c.LocateOrder) }
go
func (c *Config) FindBox(boxName string) (*Box, error) { return findBox(boxName, c.LocateOrder) }
[ "func", "(", "c", "*", "Config", ")", "FindBox", "(", "boxName", "string", ")", "(", "*", "Box", ",", "error", ")", "{", "return", "findBox", "(", "boxName", ",", "c", ".", "LocateOrder", ")", "\n", "}" ]
// FindBox searches for boxes using the LocateOrder of the config.
[ "FindBox", "searches", "for", "boxes", "using", "the", "LocateOrder", "of", "the", "config", "." ]
c880e3cd4dd81db36b423e83dc0aeea4dca93774
https://github.com/GeertJohan/go.rice/blob/c880e3cd4dd81db36b423e83dc0aeea4dca93774/config.go#L26-L28
train
GeertJohan/go.rice
config.go
MustFindBox
func (c *Config) MustFindBox(boxName string) *Box { box, err := findBox(boxName, c.LocateOrder) if err != nil { panic(err) } return box }
go
func (c *Config) MustFindBox(boxName string) *Box { box, err := findBox(boxName, c.LocateOrder) if err != nil { panic(err) } return box }
[ "func", "(", "c", "*", "Config", ")", "MustFindBox", "(", "boxName", "string", ")", "*", "Box", "{", "box", ",", "err", ":=", "findBox", "(", "boxName", ",", "c", ".", "LocateOrder", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ...
// MustFindBox searches for boxes using the LocateOrder of the config, like // FindBox does. It does not return an error, instead it panics when an error // occurs.
[ "MustFindBox", "searches", "for", "boxes", "using", "the", "LocateOrder", "of", "the", "config", "like", "FindBox", "does", ".", "It", "does", "not", "return", "an", "error", "instead", "it", "panics", "when", "an", "error", "occurs", "." ]
c880e3cd4dd81db36b423e83dc0aeea4dca93774
https://github.com/GeertJohan/go.rice/blob/c880e3cd4dd81db36b423e83dc0aeea4dca93774/config.go#L33-L39
train
GeertJohan/go.rice
embedded/embedded.go
Link
func (e *EmbeddedBox) Link() { for _, ed := range e.Dirs { ed.ChildDirs = make([]*EmbeddedDir, 0) ed.ChildFiles = make([]*EmbeddedFile, 0) } for path, ed := range e.Dirs { // skip for root, it'll create a recursion if path == "" { continue } parentDirpath, _ := filepath.Split(path) if strings.HasSuffix(parentDirpath, "/") { parentDirpath = parentDirpath[:len(parentDirpath)-1] } parentDir := e.Dirs[parentDirpath] if parentDir == nil { panic("parentDir `" + parentDirpath + "` is missing in embedded box") } parentDir.ChildDirs = append(parentDir.ChildDirs, ed) } for path, ef := range e.Files { dirpath, _ := filepath.Split(path) if strings.HasSuffix(dirpath, "/") { dirpath = dirpath[:len(dirpath)-1] } dir := e.Dirs[dirpath] if dir == nil { panic("dir `" + dirpath + "` is missing in embedded box") } dir.ChildFiles = append(dir.ChildFiles, ef) } }
go
func (e *EmbeddedBox) Link() { for _, ed := range e.Dirs { ed.ChildDirs = make([]*EmbeddedDir, 0) ed.ChildFiles = make([]*EmbeddedFile, 0) } for path, ed := range e.Dirs { // skip for root, it'll create a recursion if path == "" { continue } parentDirpath, _ := filepath.Split(path) if strings.HasSuffix(parentDirpath, "/") { parentDirpath = parentDirpath[:len(parentDirpath)-1] } parentDir := e.Dirs[parentDirpath] if parentDir == nil { panic("parentDir `" + parentDirpath + "` is missing in embedded box") } parentDir.ChildDirs = append(parentDir.ChildDirs, ed) } for path, ef := range e.Files { dirpath, _ := filepath.Split(path) if strings.HasSuffix(dirpath, "/") { dirpath = dirpath[:len(dirpath)-1] } dir := e.Dirs[dirpath] if dir == nil { panic("dir `" + dirpath + "` is missing in embedded box") } dir.ChildFiles = append(dir.ChildFiles, ef) } }
[ "func", "(", "e", "*", "EmbeddedBox", ")", "Link", "(", ")", "{", "for", "_", ",", "ed", ":=", "range", "e", ".", "Dirs", "{", "ed", ".", "ChildDirs", "=", "make", "(", "[", "]", "*", "EmbeddedDir", ",", "0", ")", "\n", "ed", ".", "ChildFiles",...
// Link creates the ChildDirs and ChildFiles links in all EmbeddedDir's
[ "Link", "creates", "the", "ChildDirs", "and", "ChildFiles", "links", "in", "all", "EmbeddedDir", "s" ]
c880e3cd4dd81db36b423e83dc0aeea4dca93774
https://github.com/GeertJohan/go.rice/blob/c880e3cd4dd81db36b423e83dc0aeea4dca93774/embedded/embedded.go#L26-L57
train
GeertJohan/go.rice
embedded/embedded.go
RegisterEmbeddedBox
func RegisterEmbeddedBox(name string, box *EmbeddedBox) { if _, exists := EmbeddedBoxes[name]; exists { panic(fmt.Sprintf("EmbeddedBox with name `%s` exists already", name)) } EmbeddedBoxes[name] = box }
go
func RegisterEmbeddedBox(name string, box *EmbeddedBox) { if _, exists := EmbeddedBoxes[name]; exists { panic(fmt.Sprintf("EmbeddedBox with name `%s` exists already", name)) } EmbeddedBoxes[name] = box }
[ "func", "RegisterEmbeddedBox", "(", "name", "string", ",", "box", "*", "EmbeddedBox", ")", "{", "if", "_", ",", "exists", ":=", "EmbeddedBoxes", "[", "name", "]", ";", "exists", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"EmbeddedBox with name `%s` exi...
// RegisterEmbeddedBox registers an EmbeddedBox
[ "RegisterEmbeddedBox", "registers", "an", "EmbeddedBox" ]
c880e3cd4dd81db36b423e83dc0aeea4dca93774
https://github.com/GeertJohan/go.rice/blob/c880e3cd4dd81db36b423e83dc0aeea4dca93774/embedded/embedded.go#L78-L83
train
GeertJohan/go.rice
box.go
MustFindBox
func MustFindBox(name string) *Box { box, err := findBox(name, defaultLocateOrder) if err != nil { panic(err) } return box }
go
func MustFindBox(name string) *Box { box, err := findBox(name, defaultLocateOrder) if err != nil { panic(err) } return box }
[ "func", "MustFindBox", "(", "name", "string", ")", "*", "Box", "{", "box", ",", "err", ":=", "findBox", "(", "name", ",", "defaultLocateOrder", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "box", "\...
// MustFindBox returns a Box instance for given name, like FindBox does. // It does not return an error, instead it panics when an error occurs.
[ "MustFindBox", "returns", "a", "Box", "instance", "for", "given", "name", "like", "FindBox", "does", ".", "It", "does", "not", "return", "an", "error", "instead", "it", "panics", "when", "an", "error", "occurs", "." ]
c880e3cd4dd81db36b423e83dc0aeea4dca93774
https://github.com/GeertJohan/go.rice/blob/c880e3cd4dd81db36b423e83dc0aeea4dca93774/box.go#L107-L113
train
GeertJohan/go.rice
box.go
String
func (b *Box) String(name string) (string, error) { // check if box is embedded, optimized fast path if b.IsEmbedded() { // find file in embed ef := b.embed.Files[name] if ef == nil { return "", os.ErrNotExist } // return as string return ef.Content, nil } bts, err := b.Bytes(name) if err != nil { return "", err } return string(bts), nil }
go
func (b *Box) String(name string) (string, error) { // check if box is embedded, optimized fast path if b.IsEmbedded() { // find file in embed ef := b.embed.Files[name] if ef == nil { return "", os.ErrNotExist } // return as string return ef.Content, nil } bts, err := b.Bytes(name) if err != nil { return "", err } return string(bts), nil }
[ "func", "(", "b", "*", "Box", ")", "String", "(", "name", "string", ")", "(", "string", ",", "error", ")", "{", "if", "b", ".", "IsEmbedded", "(", ")", "{", "ef", ":=", "b", ".", "embed", ".", "Files", "[", "name", "]", "\n", "if", "ef", "=="...
// String returns the content of the file with given name as string.
[ "String", "returns", "the", "content", "of", "the", "file", "with", "given", "name", "as", "string", "." ]
c880e3cd4dd81db36b423e83dc0aeea4dca93774
https://github.com/GeertJohan/go.rice/blob/c880e3cd4dd81db36b423e83dc0aeea4dca93774/box.go#L305-L322
train
GeertJohan/go.rice
box.go
MustString
func (b *Box) MustString(name string) string { str, err := b.String(name) if err != nil { panic(err) } return str }
go
func (b *Box) MustString(name string) string { str, err := b.String(name) if err != nil { panic(err) } return str }
[ "func", "(", "b", "*", "Box", ")", "MustString", "(", "name", "string", ")", "string", "{", "str", ",", "err", ":=", "b", ".", "String", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return",...
// MustString returns the content of the file with given name as string. // panic's on error.
[ "MustString", "returns", "the", "content", "of", "the", "file", "with", "given", "name", "as", "string", ".", "panic", "s", "on", "error", "." ]
c880e3cd4dd81db36b423e83dc0aeea4dca93774
https://github.com/GeertJohan/go.rice/blob/c880e3cd4dd81db36b423e83dc0aeea4dca93774/box.go#L326-L332
train
GeertJohan/go.rice
virtual.go
newVirtualFile
func newVirtualFile(ef *embedded.EmbeddedFile) *virtualFile { vf := &virtualFile{ EmbeddedFile: ef, offset: 0, closed: false, } return vf }
go
func newVirtualFile(ef *embedded.EmbeddedFile) *virtualFile { vf := &virtualFile{ EmbeddedFile: ef, offset: 0, closed: false, } return vf }
[ "func", "newVirtualFile", "(", "ef", "*", "embedded", ".", "EmbeddedFile", ")", "*", "virtualFile", "{", "vf", ":=", "&", "virtualFile", "{", "EmbeddedFile", ":", "ef", ",", "offset", ":", "0", ",", "closed", ":", "false", ",", "}", "\n", "return", "vf...
// create a new virtualFile for given EmbeddedFile
[ "create", "a", "new", "virtualFile", "for", "given", "EmbeddedFile" ]
c880e3cd4dd81db36b423e83dc0aeea4dca93774
https://github.com/GeertJohan/go.rice/blob/c880e3cd4dd81db36b423e83dc0aeea4dca93774/virtual.go#L25-L32
train
GeertJohan/go.rice
virtual.go
newVirtualDir
func newVirtualDir(ed *embedded.EmbeddedDir) *virtualDir { vd := &virtualDir{ EmbeddedDir: ed, offset: 0, closed: false, } return vd }
go
func newVirtualDir(ed *embedded.EmbeddedDir) *virtualDir { vd := &virtualDir{ EmbeddedDir: ed, offset: 0, closed: false, } return vd }
[ "func", "newVirtualDir", "(", "ed", "*", "embedded", ".", "EmbeddedDir", ")", "*", "virtualDir", "{", "vd", ":=", "&", "virtualDir", "{", "EmbeddedDir", ":", "ed", ",", "offset", ":", "0", ",", "closed", ":", "false", ",", "}", "\n", "return", "vd", ...
// create a new virtualDir for given EmbeddedDir
[ "create", "a", "new", "virtualDir", "for", "given", "EmbeddedDir" ]
c880e3cd4dd81db36b423e83dc0aeea4dca93774
https://github.com/GeertJohan/go.rice/blob/c880e3cd4dd81db36b423e83dc0aeea4dca93774/virtual.go#L150-L157
train
GeertJohan/go.rice
rice/util.go
generated
func generated(filename string) bool { return filepath.Base(filename) == boxFilename || strings.HasSuffix(filename, "."+boxFilename) || strings.HasSuffix(filename, sysoBoxSuffix) }
go
func generated(filename string) bool { return filepath.Base(filename) == boxFilename || strings.HasSuffix(filename, "."+boxFilename) || strings.HasSuffix(filename, sysoBoxSuffix) }
[ "func", "generated", "(", "filename", "string", ")", "bool", "{", "return", "filepath", ".", "Base", "(", "filename", ")", "==", "boxFilename", "||", "strings", ".", "HasSuffix", "(", "filename", ",", "\".\"", "+", "boxFilename", ")", "||", "strings", ".",...
// generated tests if a filename was generated by rice
[ "generated", "tests", "if", "a", "filename", "was", "generated", "by", "rice" ]
c880e3cd4dd81db36b423e83dc0aeea4dca93774
https://github.com/GeertJohan/go.rice/blob/c880e3cd4dd81db36b423e83dc0aeea4dca93774/rice/util.go#L11-L15
train
GeertJohan/go.rice
rice/util.go
randomString
func randomString(length int) string { rand.Seed(time.Now().UnixNano()) k := make([]rune, length) for i := 0; i < length; i++ { c := rand.Intn(35) if c < 10 { c += 48 // numbers (0-9) (0+48 == 48 == '0', 9+48 == 57 == '9') } else { c += 87 // lower case alphabets (a-z) (10+87 == 97 == 'a', 35+87 == 122 = 'z') } k[i] = rune(c) } return string(k) }
go
func randomString(length int) string { rand.Seed(time.Now().UnixNano()) k := make([]rune, length) for i := 0; i < length; i++ { c := rand.Intn(35) if c < 10 { c += 48 // numbers (0-9) (0+48 == 48 == '0', 9+48 == 57 == '9') } else { c += 87 // lower case alphabets (a-z) (10+87 == 97 == 'a', 35+87 == 122 = 'z') } k[i] = rune(c) } return string(k) }
[ "func", "randomString", "(", "length", "int", ")", "string", "{", "rand", ".", "Seed", "(", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ")", "\n", "k", ":=", "make", "(", "[", "]", "rune", ",", "length", ")", "\n", "for", "i", ":="...
// randomString generates a pseudo-random alpha-numeric string with given length.
[ "randomString", "generates", "a", "pseudo", "-", "random", "alpha", "-", "numeric", "string", "with", "given", "length", "." ]
c880e3cd4dd81db36b423e83dc0aeea4dca93774
https://github.com/GeertJohan/go.rice/blob/c880e3cd4dd81db36b423e83dc0aeea4dca93774/rice/util.go#L18-L31
train
bwmarrin/discordgo
ratelimit.go
NewRatelimiter
func NewRatelimiter() *RateLimiter { return &RateLimiter{ buckets: make(map[string]*Bucket), global: new(int64), customRateLimits: []*customRateLimit{ &customRateLimit{ suffix: "//reactions//", requests: 1, reset: 200 * time.Millisecond, }, }, } }
go
func NewRatelimiter() *RateLimiter { return &RateLimiter{ buckets: make(map[string]*Bucket), global: new(int64), customRateLimits: []*customRateLimit{ &customRateLimit{ suffix: "//reactions//", requests: 1, reset: 200 * time.Millisecond, }, }, } }
[ "func", "NewRatelimiter", "(", ")", "*", "RateLimiter", "{", "return", "&", "RateLimiter", "{", "buckets", ":", "make", "(", "map", "[", "string", "]", "*", "Bucket", ")", ",", "global", ":", "new", "(", "int64", ")", ",", "customRateLimits", ":", "[",...
// NewRatelimiter returns a new RateLimiter
[ "NewRatelimiter", "returns", "a", "new", "RateLimiter" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/ratelimit.go#L29-L42
train
bwmarrin/discordgo
ratelimit.go
GetBucket
func (r *RateLimiter) GetBucket(key string) *Bucket { r.Lock() defer r.Unlock() if bucket, ok := r.buckets[key]; ok { return bucket } b := &Bucket{ Remaining: 1, Key: key, global: r.global, } // Check if there is a custom ratelimit set for this bucket ID. for _, rl := range r.customRateLimits { if strings.HasSuffix(b.Key, rl.suffix) { b.customRateLimit = rl break } } r.buckets[key] = b return b }
go
func (r *RateLimiter) GetBucket(key string) *Bucket { r.Lock() defer r.Unlock() if bucket, ok := r.buckets[key]; ok { return bucket } b := &Bucket{ Remaining: 1, Key: key, global: r.global, } // Check if there is a custom ratelimit set for this bucket ID. for _, rl := range r.customRateLimits { if strings.HasSuffix(b.Key, rl.suffix) { b.customRateLimit = rl break } } r.buckets[key] = b return b }
[ "func", "(", "r", "*", "RateLimiter", ")", "GetBucket", "(", "key", "string", ")", "*", "Bucket", "{", "r", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "Unlock", "(", ")", "\n", "if", "bucket", ",", "ok", ":=", "r", ".", "buckets", "[", "ke...
// GetBucket retrieves or creates a bucket
[ "GetBucket", "retrieves", "or", "creates", "a", "bucket" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/ratelimit.go#L45-L69
train
bwmarrin/discordgo
ratelimit.go
GetWaitTime
func (r *RateLimiter) GetWaitTime(b *Bucket, minRemaining int) time.Duration { // If we ran out of calls and the reset time is still ahead of us // then we need to take it easy and relax a little if b.Remaining < minRemaining && b.reset.After(time.Now()) { return b.reset.Sub(time.Now()) } // Check for global ratelimits sleepTo := time.Unix(0, atomic.LoadInt64(r.global)) if now := time.Now(); now.Before(sleepTo) { return sleepTo.Sub(now) } return 0 }
go
func (r *RateLimiter) GetWaitTime(b *Bucket, minRemaining int) time.Duration { // If we ran out of calls and the reset time is still ahead of us // then we need to take it easy and relax a little if b.Remaining < minRemaining && b.reset.After(time.Now()) { return b.reset.Sub(time.Now()) } // Check for global ratelimits sleepTo := time.Unix(0, atomic.LoadInt64(r.global)) if now := time.Now(); now.Before(sleepTo) { return sleepTo.Sub(now) } return 0 }
[ "func", "(", "r", "*", "RateLimiter", ")", "GetWaitTime", "(", "b", "*", "Bucket", ",", "minRemaining", "int", ")", "time", ".", "Duration", "{", "if", "b", ".", "Remaining", "<", "minRemaining", "&&", "b", ".", "reset", ".", "After", "(", "time", "....
// GetWaitTime returns the duration you should wait for a Bucket
[ "GetWaitTime", "returns", "the", "duration", "you", "should", "wait", "for", "a", "Bucket" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/ratelimit.go#L72-L86
train
bwmarrin/discordgo
ratelimit.go
LockBucket
func (r *RateLimiter) LockBucket(bucketID string) *Bucket { return r.LockBucketObject(r.GetBucket(bucketID)) }
go
func (r *RateLimiter) LockBucket(bucketID string) *Bucket { return r.LockBucketObject(r.GetBucket(bucketID)) }
[ "func", "(", "r", "*", "RateLimiter", ")", "LockBucket", "(", "bucketID", "string", ")", "*", "Bucket", "{", "return", "r", ".", "LockBucketObject", "(", "r", ".", "GetBucket", "(", "bucketID", ")", ")", "\n", "}" ]
// LockBucket Locks until a request can be made
[ "LockBucket", "Locks", "until", "a", "request", "can", "be", "made" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/ratelimit.go#L89-L91
train
bwmarrin/discordgo
ratelimit.go
LockBucketObject
func (r *RateLimiter) LockBucketObject(b *Bucket) *Bucket { b.Lock() if wait := r.GetWaitTime(b, 1); wait > 0 { time.Sleep(wait) } b.Remaining-- return b }
go
func (r *RateLimiter) LockBucketObject(b *Bucket) *Bucket { b.Lock() if wait := r.GetWaitTime(b, 1); wait > 0 { time.Sleep(wait) } b.Remaining-- return b }
[ "func", "(", "r", "*", "RateLimiter", ")", "LockBucketObject", "(", "b", "*", "Bucket", ")", "*", "Bucket", "{", "b", ".", "Lock", "(", ")", "\n", "if", "wait", ":=", "r", ".", "GetWaitTime", "(", "b", ",", "1", ")", ";", "wait", ">", "0", "{",...
// LockBucketObject Locks an already resolved bucket until a request can be made
[ "LockBucketObject", "Locks", "an", "already", "resolved", "bucket", "until", "a", "request", "can", "be", "made" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/ratelimit.go#L94-L103
train
bwmarrin/discordgo
ratelimit.go
Release
func (b *Bucket) Release(headers http.Header) error { defer b.Unlock() // Check if the bucket uses a custom ratelimiter if rl := b.customRateLimit; rl != nil { if time.Now().Sub(b.lastReset) >= rl.reset { b.Remaining = rl.requests - 1 b.lastReset = time.Now() } if b.Remaining < 1 { b.reset = time.Now().Add(rl.reset) } return nil } if headers == nil { return nil } remaining := headers.Get("X-RateLimit-Remaining") reset := headers.Get("X-RateLimit-Reset") global := headers.Get("X-RateLimit-Global") retryAfter := headers.Get("Retry-After") // Update global and per bucket reset time if the proper headers are available // If global is set, then it will block all buckets until after Retry-After // If Retry-After without global is provided it will use that for the new reset // time since it's more accurate than X-RateLimit-Reset. // If Retry-After after is not proided, it will update the reset time from X-RateLimit-Reset if retryAfter != "" { parsedAfter, err := strconv.ParseInt(retryAfter, 10, 64) if err != nil { return err } resetAt := time.Now().Add(time.Duration(parsedAfter) * time.Millisecond) // Lock either this single bucket or all buckets if global != "" { atomic.StoreInt64(b.global, resetAt.UnixNano()) } else { b.reset = resetAt } } else if reset != "" { // Calculate the reset time by using the date header returned from discord discordTime, err := http.ParseTime(headers.Get("Date")) if err != nil { return err } unix, err := strconv.ParseInt(reset, 10, 64) if err != nil { return err } // Calculate the time until reset and add it to the current local time // some extra time is added because without it i still encountered 429's. // The added amount is the lowest amount that gave no 429's // in 1k requests delta := time.Unix(unix, 0).Sub(discordTime) + time.Millisecond*250 b.reset = time.Now().Add(delta) } // Udpate remaining if header is present if remaining != "" { parsedRemaining, err := strconv.ParseInt(remaining, 10, 32) if err != nil { return err } b.Remaining = int(parsedRemaining) } return nil }
go
func (b *Bucket) Release(headers http.Header) error { defer b.Unlock() // Check if the bucket uses a custom ratelimiter if rl := b.customRateLimit; rl != nil { if time.Now().Sub(b.lastReset) >= rl.reset { b.Remaining = rl.requests - 1 b.lastReset = time.Now() } if b.Remaining < 1 { b.reset = time.Now().Add(rl.reset) } return nil } if headers == nil { return nil } remaining := headers.Get("X-RateLimit-Remaining") reset := headers.Get("X-RateLimit-Reset") global := headers.Get("X-RateLimit-Global") retryAfter := headers.Get("Retry-After") // Update global and per bucket reset time if the proper headers are available // If global is set, then it will block all buckets until after Retry-After // If Retry-After without global is provided it will use that for the new reset // time since it's more accurate than X-RateLimit-Reset. // If Retry-After after is not proided, it will update the reset time from X-RateLimit-Reset if retryAfter != "" { parsedAfter, err := strconv.ParseInt(retryAfter, 10, 64) if err != nil { return err } resetAt := time.Now().Add(time.Duration(parsedAfter) * time.Millisecond) // Lock either this single bucket or all buckets if global != "" { atomic.StoreInt64(b.global, resetAt.UnixNano()) } else { b.reset = resetAt } } else if reset != "" { // Calculate the reset time by using the date header returned from discord discordTime, err := http.ParseTime(headers.Get("Date")) if err != nil { return err } unix, err := strconv.ParseInt(reset, 10, 64) if err != nil { return err } // Calculate the time until reset and add it to the current local time // some extra time is added because without it i still encountered 429's. // The added amount is the lowest amount that gave no 429's // in 1k requests delta := time.Unix(unix, 0).Sub(discordTime) + time.Millisecond*250 b.reset = time.Now().Add(delta) } // Udpate remaining if header is present if remaining != "" { parsedRemaining, err := strconv.ParseInt(remaining, 10, 32) if err != nil { return err } b.Remaining = int(parsedRemaining) } return nil }
[ "func", "(", "b", "*", "Bucket", ")", "Release", "(", "headers", "http", ".", "Header", ")", "error", "{", "defer", "b", ".", "Unlock", "(", ")", "\n", "if", "rl", ":=", "b", ".", "customRateLimit", ";", "rl", "!=", "nil", "{", "if", "time", ".",...
// Release unlocks the bucket and reads the headers to update the buckets ratelimit info // and locks up the whole thing in case if there's a global ratelimit.
[ "Release", "unlocks", "the", "bucket", "and", "reads", "the", "headers", "to", "update", "the", "buckets", "ratelimit", "info", "and", "locks", "up", "the", "whole", "thing", "in", "case", "if", "there", "s", "a", "global", "ratelimit", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/ratelimit.go#L121-L194
train
bwmarrin/discordgo
state.go
NewState
func NewState() *State { return &State{ Ready: Ready{ PrivateChannels: []*Channel{}, Guilds: []*Guild{}, }, TrackChannels: true, TrackEmojis: true, TrackMembers: true, TrackRoles: true, TrackVoice: true, TrackPresences: true, guildMap: make(map[string]*Guild), channelMap: make(map[string]*Channel), memberMap: make(map[string]map[string]*Member), } }
go
func NewState() *State { return &State{ Ready: Ready{ PrivateChannels: []*Channel{}, Guilds: []*Guild{}, }, TrackChannels: true, TrackEmojis: true, TrackMembers: true, TrackRoles: true, TrackVoice: true, TrackPresences: true, guildMap: make(map[string]*Guild), channelMap: make(map[string]*Channel), memberMap: make(map[string]map[string]*Member), } }
[ "func", "NewState", "(", ")", "*", "State", "{", "return", "&", "State", "{", "Ready", ":", "Ready", "{", "PrivateChannels", ":", "[", "]", "*", "Channel", "{", "}", ",", "Guilds", ":", "[", "]", "*", "Guild", "{", "}", ",", "}", ",", "TrackChann...
// NewState creates an empty state.
[ "NewState", "creates", "an", "empty", "state", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L50-L66
train
bwmarrin/discordgo
state.go
GuildAdd
func (s *State) GuildAdd(guild *Guild) error { if s == nil { return ErrNilState } s.Lock() defer s.Unlock() // Update the channels to point to the right guild, adding them to the channelMap as we go for _, c := range guild.Channels { s.channelMap[c.ID] = c } // If this guild contains a new member slice, we must regenerate the member map so the pointers stay valid if guild.Members != nil { s.createMemberMap(guild) } else if _, ok := s.memberMap[guild.ID]; !ok { // Even if we have no new member slice, we still initialize the member map for this guild if it doesn't exist s.memberMap[guild.ID] = make(map[string]*Member) } if g, ok := s.guildMap[guild.ID]; ok { // We are about to replace `g` in the state with `guild`, but first we need to // make sure we preserve any fields that the `guild` doesn't contain from `g`. if guild.MemberCount == 0 { guild.MemberCount = g.MemberCount } if guild.Roles == nil { guild.Roles = g.Roles } if guild.Emojis == nil { guild.Emojis = g.Emojis } if guild.Members == nil { guild.Members = g.Members } if guild.Presences == nil { guild.Presences = g.Presences } if guild.Channels == nil { guild.Channels = g.Channels } if guild.VoiceStates == nil { guild.VoiceStates = g.VoiceStates } *g = *guild return nil } s.Guilds = append(s.Guilds, guild) s.guildMap[guild.ID] = guild return nil }
go
func (s *State) GuildAdd(guild *Guild) error { if s == nil { return ErrNilState } s.Lock() defer s.Unlock() // Update the channels to point to the right guild, adding them to the channelMap as we go for _, c := range guild.Channels { s.channelMap[c.ID] = c } // If this guild contains a new member slice, we must regenerate the member map so the pointers stay valid if guild.Members != nil { s.createMemberMap(guild) } else if _, ok := s.memberMap[guild.ID]; !ok { // Even if we have no new member slice, we still initialize the member map for this guild if it doesn't exist s.memberMap[guild.ID] = make(map[string]*Member) } if g, ok := s.guildMap[guild.ID]; ok { // We are about to replace `g` in the state with `guild`, but first we need to // make sure we preserve any fields that the `guild` doesn't contain from `g`. if guild.MemberCount == 0 { guild.MemberCount = g.MemberCount } if guild.Roles == nil { guild.Roles = g.Roles } if guild.Emojis == nil { guild.Emojis = g.Emojis } if guild.Members == nil { guild.Members = g.Members } if guild.Presences == nil { guild.Presences = g.Presences } if guild.Channels == nil { guild.Channels = g.Channels } if guild.VoiceStates == nil { guild.VoiceStates = g.VoiceStates } *g = *guild return nil } s.Guilds = append(s.Guilds, guild) s.guildMap[guild.ID] = guild return nil }
[ "func", "(", "s", "*", "State", ")", "GuildAdd", "(", "guild", "*", "Guild", ")", "error", "{", "if", "s", "==", "nil", "{", "return", "ErrNilState", "\n", "}", "\n", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n"...
// GuildAdd adds a guild to the current world state, or // updates it if it already exists.
[ "GuildAdd", "adds", "a", "guild", "to", "the", "current", "world", "state", "or", "updates", "it", "if", "it", "already", "exists", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L78-L131
train
bwmarrin/discordgo
state.go
GuildRemove
func (s *State) GuildRemove(guild *Guild) error { if s == nil { return ErrNilState } _, err := s.Guild(guild.ID) if err != nil { return err } s.Lock() defer s.Unlock() delete(s.guildMap, guild.ID) for i, g := range s.Guilds { if g.ID == guild.ID { s.Guilds = append(s.Guilds[:i], s.Guilds[i+1:]...) return nil } } return nil }
go
func (s *State) GuildRemove(guild *Guild) error { if s == nil { return ErrNilState } _, err := s.Guild(guild.ID) if err != nil { return err } s.Lock() defer s.Unlock() delete(s.guildMap, guild.ID) for i, g := range s.Guilds { if g.ID == guild.ID { s.Guilds = append(s.Guilds[:i], s.Guilds[i+1:]...) return nil } } return nil }
[ "func", "(", "s", "*", "State", ")", "GuildRemove", "(", "guild", "*", "Guild", ")", "error", "{", "if", "s", "==", "nil", "{", "return", "ErrNilState", "\n", "}", "\n", "_", ",", "err", ":=", "s", ".", "Guild", "(", "guild", ".", "ID", ")", "\...
// GuildRemove removes a guild from current world state.
[ "GuildRemove", "removes", "a", "guild", "from", "current", "world", "state", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L134-L157
train
bwmarrin/discordgo
state.go
Guild
func (s *State) Guild(guildID string) (*Guild, error) { if s == nil { return nil, ErrNilState } s.RLock() defer s.RUnlock() if g, ok := s.guildMap[guildID]; ok { return g, nil } return nil, ErrStateNotFound }
go
func (s *State) Guild(guildID string) (*Guild, error) { if s == nil { return nil, ErrNilState } s.RLock() defer s.RUnlock() if g, ok := s.guildMap[guildID]; ok { return g, nil } return nil, ErrStateNotFound }
[ "func", "(", "s", "*", "State", ")", "Guild", "(", "guildID", "string", ")", "(", "*", "Guild", ",", "error", ")", "{", "if", "s", "==", "nil", "{", "return", "nil", ",", "ErrNilState", "\n", "}", "\n", "s", ".", "RLock", "(", ")", "\n", "defer...
// Guild gets a guild by ID. // Useful for querying if @me is in a guild: // _, err := discordgo.Session.State.Guild(guildID) // isInGuild := err == nil
[ "Guild", "gets", "a", "guild", "by", "ID", ".", "Useful", "for", "querying", "if" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L163-L176
train
bwmarrin/discordgo
state.go
PresenceAdd
func (s *State) PresenceAdd(guildID string, presence *Presence) error { if s == nil { return ErrNilState } guild, err := s.Guild(guildID) if err != nil { return err } s.Lock() defer s.Unlock() for i, p := range guild.Presences { if p.User.ID == presence.User.ID { //guild.Presences[i] = presence //Update status guild.Presences[i].Game = presence.Game guild.Presences[i].Roles = presence.Roles if presence.Status != "" { guild.Presences[i].Status = presence.Status } if presence.Nick != "" { guild.Presences[i].Nick = presence.Nick } //Update the optionally sent user information //ID Is a mandatory field so you should not need to check if it is empty guild.Presences[i].User.ID = presence.User.ID if presence.User.Avatar != "" { guild.Presences[i].User.Avatar = presence.User.Avatar } if presence.User.Discriminator != "" { guild.Presences[i].User.Discriminator = presence.User.Discriminator } if presence.User.Email != "" { guild.Presences[i].User.Email = presence.User.Email } if presence.User.Token != "" { guild.Presences[i].User.Token = presence.User.Token } if presence.User.Username != "" { guild.Presences[i].User.Username = presence.User.Username } return nil } } guild.Presences = append(guild.Presences, presence) return nil }
go
func (s *State) PresenceAdd(guildID string, presence *Presence) error { if s == nil { return ErrNilState } guild, err := s.Guild(guildID) if err != nil { return err } s.Lock() defer s.Unlock() for i, p := range guild.Presences { if p.User.ID == presence.User.ID { //guild.Presences[i] = presence //Update status guild.Presences[i].Game = presence.Game guild.Presences[i].Roles = presence.Roles if presence.Status != "" { guild.Presences[i].Status = presence.Status } if presence.Nick != "" { guild.Presences[i].Nick = presence.Nick } //Update the optionally sent user information //ID Is a mandatory field so you should not need to check if it is empty guild.Presences[i].User.ID = presence.User.ID if presence.User.Avatar != "" { guild.Presences[i].User.Avatar = presence.User.Avatar } if presence.User.Discriminator != "" { guild.Presences[i].User.Discriminator = presence.User.Discriminator } if presence.User.Email != "" { guild.Presences[i].User.Email = presence.User.Email } if presence.User.Token != "" { guild.Presences[i].User.Token = presence.User.Token } if presence.User.Username != "" { guild.Presences[i].User.Username = presence.User.Username } return nil } } guild.Presences = append(guild.Presences, presence) return nil }
[ "func", "(", "s", "*", "State", ")", "PresenceAdd", "(", "guildID", "string", ",", "presence", "*", "Presence", ")", "error", "{", "if", "s", "==", "nil", "{", "return", "ErrNilState", "\n", "}", "\n", "guild", ",", "err", ":=", "s", ".", "Guild", ...
// PresenceAdd adds a presence to the current world state, or // updates it if it already exists.
[ "PresenceAdd", "adds", "a", "presence", "to", "the", "current", "world", "state", "or", "updates", "it", "if", "it", "already", "exists", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L180-L233
train
bwmarrin/discordgo
state.go
PresenceRemove
func (s *State) PresenceRemove(guildID string, presence *Presence) error { if s == nil { return ErrNilState } guild, err := s.Guild(guildID) if err != nil { return err } s.Lock() defer s.Unlock() for i, p := range guild.Presences { if p.User.ID == presence.User.ID { guild.Presences = append(guild.Presences[:i], guild.Presences[i+1:]...) return nil } } return ErrStateNotFound }
go
func (s *State) PresenceRemove(guildID string, presence *Presence) error { if s == nil { return ErrNilState } guild, err := s.Guild(guildID) if err != nil { return err } s.Lock() defer s.Unlock() for i, p := range guild.Presences { if p.User.ID == presence.User.ID { guild.Presences = append(guild.Presences[:i], guild.Presences[i+1:]...) return nil } } return ErrStateNotFound }
[ "func", "(", "s", "*", "State", ")", "PresenceRemove", "(", "guildID", "string", ",", "presence", "*", "Presence", ")", "error", "{", "if", "s", "==", "nil", "{", "return", "ErrNilState", "\n", "}", "\n", "guild", ",", "err", ":=", "s", ".", "Guild",...
// PresenceRemove removes a presence from the current world state.
[ "PresenceRemove", "removes", "a", "presence", "from", "the", "current", "world", "state", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L236-L257
train
bwmarrin/discordgo
state.go
Presence
func (s *State) Presence(guildID, userID string) (*Presence, error) { if s == nil { return nil, ErrNilState } guild, err := s.Guild(guildID) if err != nil { return nil, err } for _, p := range guild.Presences { if p.User.ID == userID { return p, nil } } return nil, ErrStateNotFound }
go
func (s *State) Presence(guildID, userID string) (*Presence, error) { if s == nil { return nil, ErrNilState } guild, err := s.Guild(guildID) if err != nil { return nil, err } for _, p := range guild.Presences { if p.User.ID == userID { return p, nil } } return nil, ErrStateNotFound }
[ "func", "(", "s", "*", "State", ")", "Presence", "(", "guildID", ",", "userID", "string", ")", "(", "*", "Presence", ",", "error", ")", "{", "if", "s", "==", "nil", "{", "return", "nil", ",", "ErrNilState", "\n", "}", "\n", "guild", ",", "err", "...
// Presence gets a presence by ID from a guild.
[ "Presence", "gets", "a", "presence", "by", "ID", "from", "a", "guild", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L260-L277
train
bwmarrin/discordgo
state.go
MemberRemove
func (s *State) MemberRemove(member *Member) error { if s == nil { return ErrNilState } guild, err := s.Guild(member.GuildID) if err != nil { return err } s.Lock() defer s.Unlock() members, ok := s.memberMap[member.GuildID] if !ok { return ErrStateNotFound } _, ok = members[member.User.ID] if !ok { return ErrStateNotFound } delete(members, member.User.ID) for i, m := range guild.Members { if m.User.ID == member.User.ID { guild.Members = append(guild.Members[:i], guild.Members[i+1:]...) return nil } } return ErrStateNotFound }
go
func (s *State) MemberRemove(member *Member) error { if s == nil { return ErrNilState } guild, err := s.Guild(member.GuildID) if err != nil { return err } s.Lock() defer s.Unlock() members, ok := s.memberMap[member.GuildID] if !ok { return ErrStateNotFound } _, ok = members[member.User.ID] if !ok { return ErrStateNotFound } delete(members, member.User.ID) for i, m := range guild.Members { if m.User.ID == member.User.ID { guild.Members = append(guild.Members[:i], guild.Members[i+1:]...) return nil } } return ErrStateNotFound }
[ "func", "(", "s", "*", "State", ")", "MemberRemove", "(", "member", "*", "Member", ")", "error", "{", "if", "s", "==", "nil", "{", "return", "ErrNilState", "\n", "}", "\n", "guild", ",", "err", ":=", "s", ".", "Guild", "(", "member", ".", "GuildID"...
// MemberRemove removes a member from current world state.
[ "MemberRemove", "removes", "a", "member", "from", "current", "world", "state", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L318-L350
train
bwmarrin/discordgo
state.go
Member
func (s *State) Member(guildID, userID string) (*Member, error) { if s == nil { return nil, ErrNilState } s.RLock() defer s.RUnlock() members, ok := s.memberMap[guildID] if !ok { return nil, ErrStateNotFound } m, ok := members[userID] if ok { return m, nil } return nil, ErrStateNotFound }
go
func (s *State) Member(guildID, userID string) (*Member, error) { if s == nil { return nil, ErrNilState } s.RLock() defer s.RUnlock() members, ok := s.memberMap[guildID] if !ok { return nil, ErrStateNotFound } m, ok := members[userID] if ok { return m, nil } return nil, ErrStateNotFound }
[ "func", "(", "s", "*", "State", ")", "Member", "(", "guildID", ",", "userID", "string", ")", "(", "*", "Member", ",", "error", ")", "{", "if", "s", "==", "nil", "{", "return", "nil", ",", "ErrNilState", "\n", "}", "\n", "s", ".", "RLock", "(", ...
// Member gets a member by ID from a guild.
[ "Member", "gets", "a", "member", "by", "ID", "from", "a", "guild", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L353-L372
train
bwmarrin/discordgo
state.go
RoleAdd
func (s *State) RoleAdd(guildID string, role *Role) error { if s == nil { return ErrNilState } guild, err := s.Guild(guildID) if err != nil { return err } s.Lock() defer s.Unlock() for i, r := range guild.Roles { if r.ID == role.ID { guild.Roles[i] = role return nil } } guild.Roles = append(guild.Roles, role) return nil }
go
func (s *State) RoleAdd(guildID string, role *Role) error { if s == nil { return ErrNilState } guild, err := s.Guild(guildID) if err != nil { return err } s.Lock() defer s.Unlock() for i, r := range guild.Roles { if r.ID == role.ID { guild.Roles[i] = role return nil } } guild.Roles = append(guild.Roles, role) return nil }
[ "func", "(", "s", "*", "State", ")", "RoleAdd", "(", "guildID", "string", ",", "role", "*", "Role", ")", "error", "{", "if", "s", "==", "nil", "{", "return", "ErrNilState", "\n", "}", "\n", "guild", ",", "err", ":=", "s", ".", "Guild", "(", "guil...
// RoleAdd adds a role to the current world state, or // updates it if it already exists.
[ "RoleAdd", "adds", "a", "role", "to", "the", "current", "world", "state", "or", "updates", "it", "if", "it", "already", "exists", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L376-L398
train
bwmarrin/discordgo
state.go
RoleRemove
func (s *State) RoleRemove(guildID, roleID string) error { if s == nil { return ErrNilState } guild, err := s.Guild(guildID) if err != nil { return err } s.Lock() defer s.Unlock() for i, r := range guild.Roles { if r.ID == roleID { guild.Roles = append(guild.Roles[:i], guild.Roles[i+1:]...) return nil } } return ErrStateNotFound }
go
func (s *State) RoleRemove(guildID, roleID string) error { if s == nil { return ErrNilState } guild, err := s.Guild(guildID) if err != nil { return err } s.Lock() defer s.Unlock() for i, r := range guild.Roles { if r.ID == roleID { guild.Roles = append(guild.Roles[:i], guild.Roles[i+1:]...) return nil } } return ErrStateNotFound }
[ "func", "(", "s", "*", "State", ")", "RoleRemove", "(", "guildID", ",", "roleID", "string", ")", "error", "{", "if", "s", "==", "nil", "{", "return", "ErrNilState", "\n", "}", "\n", "guild", ",", "err", ":=", "s", ".", "Guild", "(", "guildID", ")",...
// RoleRemove removes a role from current world state by ID.
[ "RoleRemove", "removes", "a", "role", "from", "current", "world", "state", "by", "ID", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L401-L422
train
bwmarrin/discordgo
state.go
Role
func (s *State) Role(guildID, roleID string) (*Role, error) { if s == nil { return nil, ErrNilState } guild, err := s.Guild(guildID) if err != nil { return nil, err } s.RLock() defer s.RUnlock() for _, r := range guild.Roles { if r.ID == roleID { return r, nil } } return nil, ErrStateNotFound }
go
func (s *State) Role(guildID, roleID string) (*Role, error) { if s == nil { return nil, ErrNilState } guild, err := s.Guild(guildID) if err != nil { return nil, err } s.RLock() defer s.RUnlock() for _, r := range guild.Roles { if r.ID == roleID { return r, nil } } return nil, ErrStateNotFound }
[ "func", "(", "s", "*", "State", ")", "Role", "(", "guildID", ",", "roleID", "string", ")", "(", "*", "Role", ",", "error", ")", "{", "if", "s", "==", "nil", "{", "return", "nil", ",", "ErrNilState", "\n", "}", "\n", "guild", ",", "err", ":=", "...
// Role gets a role by ID from a guild.
[ "Role", "gets", "a", "role", "by", "ID", "from", "a", "guild", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L425-L445
train
bwmarrin/discordgo
state.go
ChannelAdd
func (s *State) ChannelAdd(channel *Channel) error { if s == nil { return ErrNilState } s.Lock() defer s.Unlock() // If the channel exists, replace it if c, ok := s.channelMap[channel.ID]; ok { if channel.Messages == nil { channel.Messages = c.Messages } if channel.PermissionOverwrites == nil { channel.PermissionOverwrites = c.PermissionOverwrites } *c = *channel return nil } if channel.Type == ChannelTypeDM || channel.Type == ChannelTypeGroupDM { s.PrivateChannels = append(s.PrivateChannels, channel) } else { guild, ok := s.guildMap[channel.GuildID] if !ok { return ErrStateNotFound } guild.Channels = append(guild.Channels, channel) } s.channelMap[channel.ID] = channel return nil }
go
func (s *State) ChannelAdd(channel *Channel) error { if s == nil { return ErrNilState } s.Lock() defer s.Unlock() // If the channel exists, replace it if c, ok := s.channelMap[channel.ID]; ok { if channel.Messages == nil { channel.Messages = c.Messages } if channel.PermissionOverwrites == nil { channel.PermissionOverwrites = c.PermissionOverwrites } *c = *channel return nil } if channel.Type == ChannelTypeDM || channel.Type == ChannelTypeGroupDM { s.PrivateChannels = append(s.PrivateChannels, channel) } else { guild, ok := s.guildMap[channel.GuildID] if !ok { return ErrStateNotFound } guild.Channels = append(guild.Channels, channel) } s.channelMap[channel.ID] = channel return nil }
[ "func", "(", "s", "*", "State", ")", "ChannelAdd", "(", "channel", "*", "Channel", ")", "error", "{", "if", "s", "==", "nil", "{", "return", "ErrNilState", "\n", "}", "\n", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", ...
// ChannelAdd adds a channel to the current world state, or // updates it if it already exists. // Channels may exist either as PrivateChannels or inside // a guild.
[ "ChannelAdd", "adds", "a", "channel", "to", "the", "current", "world", "state", "or", "updates", "it", "if", "it", "already", "exists", ".", "Channels", "may", "exist", "either", "as", "PrivateChannels", "or", "inside", "a", "guild", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L451-L486
train
bwmarrin/discordgo
state.go
ChannelRemove
func (s *State) ChannelRemove(channel *Channel) error { if s == nil { return ErrNilState } _, err := s.Channel(channel.ID) if err != nil { return err } if channel.Type == ChannelTypeDM || channel.Type == ChannelTypeGroupDM { s.Lock() defer s.Unlock() for i, c := range s.PrivateChannels { if c.ID == channel.ID { s.PrivateChannels = append(s.PrivateChannels[:i], s.PrivateChannels[i+1:]...) break } } } else { guild, err := s.Guild(channel.GuildID) if err != nil { return err } s.Lock() defer s.Unlock() for i, c := range guild.Channels { if c.ID == channel.ID { guild.Channels = append(guild.Channels[:i], guild.Channels[i+1:]...) break } } } delete(s.channelMap, channel.ID) return nil }
go
func (s *State) ChannelRemove(channel *Channel) error { if s == nil { return ErrNilState } _, err := s.Channel(channel.ID) if err != nil { return err } if channel.Type == ChannelTypeDM || channel.Type == ChannelTypeGroupDM { s.Lock() defer s.Unlock() for i, c := range s.PrivateChannels { if c.ID == channel.ID { s.PrivateChannels = append(s.PrivateChannels[:i], s.PrivateChannels[i+1:]...) break } } } else { guild, err := s.Guild(channel.GuildID) if err != nil { return err } s.Lock() defer s.Unlock() for i, c := range guild.Channels { if c.ID == channel.ID { guild.Channels = append(guild.Channels[:i], guild.Channels[i+1:]...) break } } } delete(s.channelMap, channel.ID) return nil }
[ "func", "(", "s", "*", "State", ")", "ChannelRemove", "(", "channel", "*", "Channel", ")", "error", "{", "if", "s", "==", "nil", "{", "return", "ErrNilState", "\n", "}", "\n", "_", ",", "err", ":=", "s", ".", "Channel", "(", "channel", ".", "ID", ...
// ChannelRemove removes a channel from current world state.
[ "ChannelRemove", "removes", "a", "channel", "from", "current", "world", "state", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L489-L529
train
bwmarrin/discordgo
state.go
Channel
func (s *State) Channel(channelID string) (*Channel, error) { if s == nil { return nil, ErrNilState } s.RLock() defer s.RUnlock() if c, ok := s.channelMap[channelID]; ok { return c, nil } return nil, ErrStateNotFound }
go
func (s *State) Channel(channelID string) (*Channel, error) { if s == nil { return nil, ErrNilState } s.RLock() defer s.RUnlock() if c, ok := s.channelMap[channelID]; ok { return c, nil } return nil, ErrStateNotFound }
[ "func", "(", "s", "*", "State", ")", "Channel", "(", "channelID", "string", ")", "(", "*", "Channel", ",", "error", ")", "{", "if", "s", "==", "nil", "{", "return", "nil", ",", "ErrNilState", "\n", "}", "\n", "s", ".", "RLock", "(", ")", "\n", ...
// Channel gets a channel by ID, it will look in all guilds and private channels.
[ "Channel", "gets", "a", "channel", "by", "ID", "it", "will", "look", "in", "all", "guilds", "and", "private", "channels", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L544-L557
train
bwmarrin/discordgo
state.go
Emoji
func (s *State) Emoji(guildID, emojiID string) (*Emoji, error) { if s == nil { return nil, ErrNilState } guild, err := s.Guild(guildID) if err != nil { return nil, err } s.RLock() defer s.RUnlock() for _, e := range guild.Emojis { if e.ID == emojiID { return e, nil } } return nil, ErrStateNotFound }
go
func (s *State) Emoji(guildID, emojiID string) (*Emoji, error) { if s == nil { return nil, ErrNilState } guild, err := s.Guild(guildID) if err != nil { return nil, err } s.RLock() defer s.RUnlock() for _, e := range guild.Emojis { if e.ID == emojiID { return e, nil } } return nil, ErrStateNotFound }
[ "func", "(", "s", "*", "State", ")", "Emoji", "(", "guildID", ",", "emojiID", "string", ")", "(", "*", "Emoji", ",", "error", ")", "{", "if", "s", "==", "nil", "{", "return", "nil", ",", "ErrNilState", "\n", "}", "\n", "guild", ",", "err", ":=", ...
// Emoji returns an emoji for a guild and emoji id.
[ "Emoji", "returns", "an", "emoji", "for", "a", "guild", "and", "emoji", "id", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L560-L580
train
bwmarrin/discordgo
state.go
EmojiAdd
func (s *State) EmojiAdd(guildID string, emoji *Emoji) error { if s == nil { return ErrNilState } guild, err := s.Guild(guildID) if err != nil { return err } s.Lock() defer s.Unlock() for i, e := range guild.Emojis { if e.ID == emoji.ID { guild.Emojis[i] = emoji return nil } } guild.Emojis = append(guild.Emojis, emoji) return nil }
go
func (s *State) EmojiAdd(guildID string, emoji *Emoji) error { if s == nil { return ErrNilState } guild, err := s.Guild(guildID) if err != nil { return err } s.Lock() defer s.Unlock() for i, e := range guild.Emojis { if e.ID == emoji.ID { guild.Emojis[i] = emoji return nil } } guild.Emojis = append(guild.Emojis, emoji) return nil }
[ "func", "(", "s", "*", "State", ")", "EmojiAdd", "(", "guildID", "string", ",", "emoji", "*", "Emoji", ")", "error", "{", "if", "s", "==", "nil", "{", "return", "ErrNilState", "\n", "}", "\n", "guild", ",", "err", ":=", "s", ".", "Guild", "(", "g...
// EmojiAdd adds an emoji to the current world state.
[ "EmojiAdd", "adds", "an", "emoji", "to", "the", "current", "world", "state", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L583-L605
train
bwmarrin/discordgo
state.go
EmojisAdd
func (s *State) EmojisAdd(guildID string, emojis []*Emoji) error { for _, e := range emojis { if err := s.EmojiAdd(guildID, e); err != nil { return err } } return nil }
go
func (s *State) EmojisAdd(guildID string, emojis []*Emoji) error { for _, e := range emojis { if err := s.EmojiAdd(guildID, e); err != nil { return err } } return nil }
[ "func", "(", "s", "*", "State", ")", "EmojisAdd", "(", "guildID", "string", ",", "emojis", "[", "]", "*", "Emoji", ")", "error", "{", "for", "_", ",", "e", ":=", "range", "emojis", "{", "if", "err", ":=", "s", ".", "EmojiAdd", "(", "guildID", ","...
// EmojisAdd adds multiple emojis to the world state.
[ "EmojisAdd", "adds", "multiple", "emojis", "to", "the", "world", "state", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L608-L615
train
bwmarrin/discordgo
state.go
MessageAdd
func (s *State) MessageAdd(message *Message) error { if s == nil { return ErrNilState } c, err := s.Channel(message.ChannelID) if err != nil { return err } s.Lock() defer s.Unlock() // If the message exists, merge in the new message contents. for _, m := range c.Messages { if m.ID == message.ID { if message.Content != "" { m.Content = message.Content } if message.EditedTimestamp != "" { m.EditedTimestamp = message.EditedTimestamp } if message.Mentions != nil { m.Mentions = message.Mentions } if message.Embeds != nil { m.Embeds = message.Embeds } if message.Attachments != nil { m.Attachments = message.Attachments } if message.Timestamp != "" { m.Timestamp = message.Timestamp } if message.Author != nil { m.Author = message.Author } return nil } } c.Messages = append(c.Messages, message) if len(c.Messages) > s.MaxMessageCount { c.Messages = c.Messages[len(c.Messages)-s.MaxMessageCount:] } return nil }
go
func (s *State) MessageAdd(message *Message) error { if s == nil { return ErrNilState } c, err := s.Channel(message.ChannelID) if err != nil { return err } s.Lock() defer s.Unlock() // If the message exists, merge in the new message contents. for _, m := range c.Messages { if m.ID == message.ID { if message.Content != "" { m.Content = message.Content } if message.EditedTimestamp != "" { m.EditedTimestamp = message.EditedTimestamp } if message.Mentions != nil { m.Mentions = message.Mentions } if message.Embeds != nil { m.Embeds = message.Embeds } if message.Attachments != nil { m.Attachments = message.Attachments } if message.Timestamp != "" { m.Timestamp = message.Timestamp } if message.Author != nil { m.Author = message.Author } return nil } } c.Messages = append(c.Messages, message) if len(c.Messages) > s.MaxMessageCount { c.Messages = c.Messages[len(c.Messages)-s.MaxMessageCount:] } return nil }
[ "func", "(", "s", "*", "State", ")", "MessageAdd", "(", "message", "*", "Message", ")", "error", "{", "if", "s", "==", "nil", "{", "return", "ErrNilState", "\n", "}", "\n", "c", ",", "err", ":=", "s", ".", "Channel", "(", "message", ".", "ChannelID...
// MessageAdd adds a message to the current world state, or updates it if it exists. // If the channel cannot be found, the message is discarded. // Messages are kept in state up to s.MaxMessageCount per channel.
[ "MessageAdd", "adds", "a", "message", "to", "the", "current", "world", "state", "or", "updates", "it", "if", "it", "exists", ".", "If", "the", "channel", "cannot", "be", "found", "the", "message", "is", "discarded", ".", "Messages", "are", "kept", "in", ...
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L620-L668
train
bwmarrin/discordgo
state.go
MessageRemove
func (s *State) MessageRemove(message *Message) error { if s == nil { return ErrNilState } return s.messageRemoveByID(message.ChannelID, message.ID) }
go
func (s *State) MessageRemove(message *Message) error { if s == nil { return ErrNilState } return s.messageRemoveByID(message.ChannelID, message.ID) }
[ "func", "(", "s", "*", "State", ")", "MessageRemove", "(", "message", "*", "Message", ")", "error", "{", "if", "s", "==", "nil", "{", "return", "ErrNilState", "\n", "}", "\n", "return", "s", ".", "messageRemoveByID", "(", "message", ".", "ChannelID", "...
// MessageRemove removes a message from the world state.
[ "MessageRemove", "removes", "a", "message", "from", "the", "world", "state", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L671-L677
train
bwmarrin/discordgo
state.go
messageRemoveByID
func (s *State) messageRemoveByID(channelID, messageID string) error { c, err := s.Channel(channelID) if err != nil { return err } s.Lock() defer s.Unlock() for i, m := range c.Messages { if m.ID == messageID { c.Messages = append(c.Messages[:i], c.Messages[i+1:]...) return nil } } return ErrStateNotFound }
go
func (s *State) messageRemoveByID(channelID, messageID string) error { c, err := s.Channel(channelID) if err != nil { return err } s.Lock() defer s.Unlock() for i, m := range c.Messages { if m.ID == messageID { c.Messages = append(c.Messages[:i], c.Messages[i+1:]...) return nil } } return ErrStateNotFound }
[ "func", "(", "s", "*", "State", ")", "messageRemoveByID", "(", "channelID", ",", "messageID", "string", ")", "error", "{", "c", ",", "err", ":=", "s", ".", "Channel", "(", "channelID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", ...
// messageRemoveByID removes a message by channelID and messageID from the world state.
[ "messageRemoveByID", "removes", "a", "message", "by", "channelID", "and", "messageID", "from", "the", "world", "state", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L680-L697
train
bwmarrin/discordgo
state.go
Message
func (s *State) Message(channelID, messageID string) (*Message, error) { if s == nil { return nil, ErrNilState } c, err := s.Channel(channelID) if err != nil { return nil, err } s.RLock() defer s.RUnlock() for _, m := range c.Messages { if m.ID == messageID { return m, nil } } return nil, ErrStateNotFound }
go
func (s *State) Message(channelID, messageID string) (*Message, error) { if s == nil { return nil, ErrNilState } c, err := s.Channel(channelID) if err != nil { return nil, err } s.RLock() defer s.RUnlock() for _, m := range c.Messages { if m.ID == messageID { return m, nil } } return nil, ErrStateNotFound }
[ "func", "(", "s", "*", "State", ")", "Message", "(", "channelID", ",", "messageID", "string", ")", "(", "*", "Message", ",", "error", ")", "{", "if", "s", "==", "nil", "{", "return", "nil", ",", "ErrNilState", "\n", "}", "\n", "c", ",", "err", ":...
// Message gets a message by channel and message ID.
[ "Message", "gets", "a", "message", "by", "channel", "and", "message", "ID", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L731-L751
train
bwmarrin/discordgo
state.go
onReady
func (s *State) onReady(se *Session, r *Ready) (err error) { if s == nil { return ErrNilState } s.Lock() defer s.Unlock() // We must track at least the current user for Voice, even // if state is disabled, store the bare essentials. if !se.StateEnabled { ready := Ready{ Version: r.Version, SessionID: r.SessionID, User: r.User, } s.Ready = ready return nil } s.Ready = *r for _, g := range s.Guilds { s.guildMap[g.ID] = g s.createMemberMap(g) for _, c := range g.Channels { s.channelMap[c.ID] = c } } for _, c := range s.PrivateChannels { s.channelMap[c.ID] = c } return nil }
go
func (s *State) onReady(se *Session, r *Ready) (err error) { if s == nil { return ErrNilState } s.Lock() defer s.Unlock() // We must track at least the current user for Voice, even // if state is disabled, store the bare essentials. if !se.StateEnabled { ready := Ready{ Version: r.Version, SessionID: r.SessionID, User: r.User, } s.Ready = ready return nil } s.Ready = *r for _, g := range s.Guilds { s.guildMap[g.ID] = g s.createMemberMap(g) for _, c := range g.Channels { s.channelMap[c.ID] = c } } for _, c := range s.PrivateChannels { s.channelMap[c.ID] = c } return nil }
[ "func", "(", "s", "*", "State", ")", "onReady", "(", "se", "*", "Session", ",", "r", "*", "Ready", ")", "(", "err", "error", ")", "{", "if", "s", "==", "nil", "{", "return", "ErrNilState", "\n", "}", "\n", "s", ".", "Lock", "(", ")", "\n", "d...
// OnReady takes a Ready event and updates all internal state.
[ "OnReady", "takes", "a", "Ready", "event", "and", "updates", "all", "internal", "state", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L754-L792
train
bwmarrin/discordgo
state.go
UserColor
func (s *State) UserColor(userID, channelID string) int { if s == nil { return 0 } channel, err := s.Channel(channelID) if err != nil { return 0 } guild, err := s.Guild(channel.GuildID) if err != nil { return 0 } member, err := s.Member(guild.ID, userID) if err != nil { return 0 } roles := Roles(guild.Roles) sort.Sort(roles) for _, role := range roles { for _, roleID := range member.Roles { if role.ID == roleID { if role.Color != 0 { return role.Color } } } } return 0 }
go
func (s *State) UserColor(userID, channelID string) int { if s == nil { return 0 } channel, err := s.Channel(channelID) if err != nil { return 0 } guild, err := s.Guild(channel.GuildID) if err != nil { return 0 } member, err := s.Member(guild.ID, userID) if err != nil { return 0 } roles := Roles(guild.Roles) sort.Sort(roles) for _, role := range roles { for _, roleID := range member.Roles { if role.ID == roleID { if role.Color != 0 { return role.Color } } } } return 0 }
[ "func", "(", "s", "*", "State", ")", "UserColor", "(", "userID", ",", "channelID", "string", ")", "int", "{", "if", "s", "==", "nil", "{", "return", "0", "\n", "}", "\n", "channel", ",", "err", ":=", "s", ".", "Channel", "(", "channelID", ")", "\...
// UserColor returns the color of a user in a channel. // While colors are defined at a Guild level, determining for a channel is more useful in message handlers. // 0 is returned in cases of error, which is the color of @everyone. // userID : The ID of the user to calculate the color for. // channelID : The ID of the channel to calculate the color for.
[ "UserColor", "returns", "the", "color", "of", "a", "user", "in", "a", "channel", ".", "While", "colors", "are", "defined", "at", "a", "Guild", "level", "determining", "for", "a", "channel", "is", "more", "useful", "in", "message", "handlers", ".", "0", "...
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/state.go#L981-L1015
train
bwmarrin/discordgo
voice.go
ChangeChannel
func (v *VoiceConnection) ChangeChannel(channelID string, mute, deaf bool) (err error) { v.log(LogInformational, "called") data := voiceChannelJoinOp{4, voiceChannelJoinData{&v.GuildID, &channelID, mute, deaf}} v.wsMutex.Lock() err = v.session.wsConn.WriteJSON(data) v.wsMutex.Unlock() if err != nil { return } v.ChannelID = channelID v.deaf = deaf v.mute = mute v.speaking = false return }
go
func (v *VoiceConnection) ChangeChannel(channelID string, mute, deaf bool) (err error) { v.log(LogInformational, "called") data := voiceChannelJoinOp{4, voiceChannelJoinData{&v.GuildID, &channelID, mute, deaf}} v.wsMutex.Lock() err = v.session.wsConn.WriteJSON(data) v.wsMutex.Unlock() if err != nil { return } v.ChannelID = channelID v.deaf = deaf v.mute = mute v.speaking = false return }
[ "func", "(", "v", "*", "VoiceConnection", ")", "ChangeChannel", "(", "channelID", "string", ",", "mute", ",", "deaf", "bool", ")", "(", "err", "error", ")", "{", "v", ".", "log", "(", "LogInformational", ",", "\"called\"", ")", "\n", "data", ":=", "voi...
// ChangeChannel sends Discord a request to change channels within a Guild // !!! NOTE !!! This function may be removed in favour of just using ChannelVoiceJoin
[ "ChangeChannel", "sends", "Discord", "a", "request", "to", "change", "channels", "within", "a", "Guild", "!!!", "NOTE", "!!!", "This", "function", "may", "be", "removed", "in", "favour", "of", "just", "using", "ChannelVoiceJoin" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/voice.go#L118-L135
train
bwmarrin/discordgo
voice.go
Disconnect
func (v *VoiceConnection) Disconnect() (err error) { // Send a OP4 with a nil channel to disconnect if v.sessionID != "" { data := voiceChannelJoinOp{4, voiceChannelJoinData{&v.GuildID, nil, true, true}} v.session.wsMutex.Lock() err = v.session.wsConn.WriteJSON(data) v.session.wsMutex.Unlock() v.sessionID = "" } // Close websocket and udp connections v.Close() v.log(LogInformational, "Deleting VoiceConnection %s", v.GuildID) v.session.Lock() delete(v.session.VoiceConnections, v.GuildID) v.session.Unlock() return }
go
func (v *VoiceConnection) Disconnect() (err error) { // Send a OP4 with a nil channel to disconnect if v.sessionID != "" { data := voiceChannelJoinOp{4, voiceChannelJoinData{&v.GuildID, nil, true, true}} v.session.wsMutex.Lock() err = v.session.wsConn.WriteJSON(data) v.session.wsMutex.Unlock() v.sessionID = "" } // Close websocket and udp connections v.Close() v.log(LogInformational, "Deleting VoiceConnection %s", v.GuildID) v.session.Lock() delete(v.session.VoiceConnections, v.GuildID) v.session.Unlock() return }
[ "func", "(", "v", "*", "VoiceConnection", ")", "Disconnect", "(", ")", "(", "err", "error", ")", "{", "if", "v", ".", "sessionID", "!=", "\"\"", "{", "data", ":=", "voiceChannelJoinOp", "{", "4", ",", "voiceChannelJoinData", "{", "&", "v", ".", "GuildI...
// Disconnect disconnects from this voice channel and closes the websocket // and udp connections to Discord.
[ "Disconnect", "disconnects", "from", "this", "voice", "channel", "and", "closes", "the", "websocket", "and", "udp", "connections", "to", "Discord", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/voice.go#L139-L160
train
bwmarrin/discordgo
voice.go
Close
func (v *VoiceConnection) Close() { v.log(LogInformational, "called") v.Lock() defer v.Unlock() v.Ready = false v.speaking = false if v.close != nil { v.log(LogInformational, "closing v.close") close(v.close) v.close = nil } if v.udpConn != nil { v.log(LogInformational, "closing udp") err := v.udpConn.Close() if err != nil { v.log(LogError, "error closing udp connection, %s", err) } v.udpConn = nil } if v.wsConn != nil { v.log(LogInformational, "sending close frame") // To cleanly close a connection, a client should send a close // frame and wait for the server to close the connection. v.wsMutex.Lock() err := v.wsConn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")) v.wsMutex.Unlock() if err != nil { v.log(LogError, "error closing websocket, %s", err) } // TODO: Wait for Discord to actually close the connection. time.Sleep(1 * time.Second) v.log(LogInformational, "closing websocket") err = v.wsConn.Close() if err != nil { v.log(LogError, "error closing websocket, %s", err) } v.wsConn = nil } }
go
func (v *VoiceConnection) Close() { v.log(LogInformational, "called") v.Lock() defer v.Unlock() v.Ready = false v.speaking = false if v.close != nil { v.log(LogInformational, "closing v.close") close(v.close) v.close = nil } if v.udpConn != nil { v.log(LogInformational, "closing udp") err := v.udpConn.Close() if err != nil { v.log(LogError, "error closing udp connection, %s", err) } v.udpConn = nil } if v.wsConn != nil { v.log(LogInformational, "sending close frame") // To cleanly close a connection, a client should send a close // frame and wait for the server to close the connection. v.wsMutex.Lock() err := v.wsConn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")) v.wsMutex.Unlock() if err != nil { v.log(LogError, "error closing websocket, %s", err) } // TODO: Wait for Discord to actually close the connection. time.Sleep(1 * time.Second) v.log(LogInformational, "closing websocket") err = v.wsConn.Close() if err != nil { v.log(LogError, "error closing websocket, %s", err) } v.wsConn = nil } }
[ "func", "(", "v", "*", "VoiceConnection", ")", "Close", "(", ")", "{", "v", ".", "log", "(", "LogInformational", ",", "\"called\"", ")", "\n", "v", ".", "Lock", "(", ")", "\n", "defer", "v", ".", "Unlock", "(", ")", "\n", "v", ".", "Ready", "=", ...
// Close closes the voice ws and udp connections
[ "Close", "closes", "the", "voice", "ws", "and", "udp", "connections" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/voice.go#L163-L211
train
bwmarrin/discordgo
voice.go
AddHandler
func (v *VoiceConnection) AddHandler(h VoiceSpeakingUpdateHandler) { v.Lock() defer v.Unlock() v.voiceSpeakingUpdateHandlers = append(v.voiceSpeakingUpdateHandlers, h) }
go
func (v *VoiceConnection) AddHandler(h VoiceSpeakingUpdateHandler) { v.Lock() defer v.Unlock() v.voiceSpeakingUpdateHandlers = append(v.voiceSpeakingUpdateHandlers, h) }
[ "func", "(", "v", "*", "VoiceConnection", ")", "AddHandler", "(", "h", "VoiceSpeakingUpdateHandler", ")", "{", "v", ".", "Lock", "(", ")", "\n", "defer", "v", ".", "Unlock", "(", ")", "\n", "v", ".", "voiceSpeakingUpdateHandlers", "=", "append", "(", "v"...
// AddHandler adds a Handler for VoiceSpeakingUpdate events.
[ "AddHandler", "adds", "a", "Handler", "for", "VoiceSpeakingUpdate", "events", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/voice.go#L214-L219
train
bwmarrin/discordgo
voice.go
waitUntilConnected
func (v *VoiceConnection) waitUntilConnected() error { v.log(LogInformational, "called") i := 0 for { v.RLock() ready := v.Ready v.RUnlock() if ready { return nil } if i > 10 { return fmt.Errorf("timeout waiting for voice") } time.Sleep(1 * time.Second) i++ } }
go
func (v *VoiceConnection) waitUntilConnected() error { v.log(LogInformational, "called") i := 0 for { v.RLock() ready := v.Ready v.RUnlock() if ready { return nil } if i > 10 { return fmt.Errorf("timeout waiting for voice") } time.Sleep(1 * time.Second) i++ } }
[ "func", "(", "v", "*", "VoiceConnection", ")", "waitUntilConnected", "(", ")", "error", "{", "v", ".", "log", "(", "LogInformational", ",", "\"called\"", ")", "\n", "i", ":=", "0", "\n", "for", "{", "v", ".", "RLock", "(", ")", "\n", "ready", ":=", ...
// WaitUntilConnected waits for the Voice Connection to // become ready, if it does not become ready it returns an err
[ "WaitUntilConnected", "waits", "for", "the", "Voice", "Connection", "to", "become", "ready", "if", "it", "does", "not", "become", "ready", "it", "returns", "an", "err" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/voice.go#L250-L270
train
bwmarrin/discordgo
voice.go
open
func (v *VoiceConnection) open() (err error) { v.log(LogInformational, "called") v.Lock() defer v.Unlock() // Don't open a websocket if one is already open if v.wsConn != nil { v.log(LogWarning, "refusing to overwrite non-nil websocket") return } // TODO temp? loop to wait for the SessionID i := 0 for { if v.sessionID != "" { break } if i > 20 { // only loop for up to 1 second total return fmt.Errorf("did not receive voice Session ID in time") } time.Sleep(50 * time.Millisecond) i++ } // Connect to VoiceConnection Websocket vg := "wss://" + strings.TrimSuffix(v.endpoint, ":80") v.log(LogInformational, "connecting to voice endpoint %s", vg) v.wsConn, _, err = websocket.DefaultDialer.Dial(vg, nil) if err != nil { v.log(LogWarning, "error connecting to voice endpoint %s, %s", vg, err) v.log(LogDebug, "voice struct: %#v\n", v) return } type voiceHandshakeData struct { ServerID string `json:"server_id"` UserID string `json:"user_id"` SessionID string `json:"session_id"` Token string `json:"token"` } type voiceHandshakeOp struct { Op int `json:"op"` // Always 0 Data voiceHandshakeData `json:"d"` } data := voiceHandshakeOp{0, voiceHandshakeData{v.GuildID, v.UserID, v.sessionID, v.token}} err = v.wsConn.WriteJSON(data) if err != nil { v.log(LogWarning, "error sending init packet, %s", err) return } v.close = make(chan struct{}) go v.wsListen(v.wsConn, v.close) // add loop/check for Ready bool here? // then return false if not ready? // but then wsListen will also err. return }
go
func (v *VoiceConnection) open() (err error) { v.log(LogInformational, "called") v.Lock() defer v.Unlock() // Don't open a websocket if one is already open if v.wsConn != nil { v.log(LogWarning, "refusing to overwrite non-nil websocket") return } // TODO temp? loop to wait for the SessionID i := 0 for { if v.sessionID != "" { break } if i > 20 { // only loop for up to 1 second total return fmt.Errorf("did not receive voice Session ID in time") } time.Sleep(50 * time.Millisecond) i++ } // Connect to VoiceConnection Websocket vg := "wss://" + strings.TrimSuffix(v.endpoint, ":80") v.log(LogInformational, "connecting to voice endpoint %s", vg) v.wsConn, _, err = websocket.DefaultDialer.Dial(vg, nil) if err != nil { v.log(LogWarning, "error connecting to voice endpoint %s, %s", vg, err) v.log(LogDebug, "voice struct: %#v\n", v) return } type voiceHandshakeData struct { ServerID string `json:"server_id"` UserID string `json:"user_id"` SessionID string `json:"session_id"` Token string `json:"token"` } type voiceHandshakeOp struct { Op int `json:"op"` // Always 0 Data voiceHandshakeData `json:"d"` } data := voiceHandshakeOp{0, voiceHandshakeData{v.GuildID, v.UserID, v.sessionID, v.token}} err = v.wsConn.WriteJSON(data) if err != nil { v.log(LogWarning, "error sending init packet, %s", err) return } v.close = make(chan struct{}) go v.wsListen(v.wsConn, v.close) // add loop/check for Ready bool here? // then return false if not ready? // but then wsListen will also err. return }
[ "func", "(", "v", "*", "VoiceConnection", ")", "open", "(", ")", "(", "err", "error", ")", "{", "v", ".", "log", "(", "LogInformational", ",", "\"called\"", ")", "\n", "v", ".", "Lock", "(", ")", "\n", "defer", "v", ".", "Unlock", "(", ")", "\n",...
// Open opens a voice connection. This should be called // after VoiceChannelJoin is used and the data VOICE websocket events // are captured.
[ "Open", "opens", "a", "voice", "connection", ".", "This", "should", "be", "called", "after", "VoiceChannelJoin", "is", "used", "and", "the", "data", "VOICE", "websocket", "events", "are", "captured", "." ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/voice.go#L275-L337
train
bwmarrin/discordgo
voice.go
wsListen
func (v *VoiceConnection) wsListen(wsConn *websocket.Conn, close <-chan struct{}) { v.log(LogInformational, "called") for { _, message, err := v.wsConn.ReadMessage() if err != nil { // Detect if we have been closed manually. If a Close() has already // happened, the websocket we are listening on will be different to the // current session. v.RLock() sameConnection := v.wsConn == wsConn v.RUnlock() if sameConnection { v.log(LogError, "voice endpoint %s websocket closed unexpectantly, %s", v.endpoint, err) // Start reconnect goroutine then exit. go v.reconnect() } return } // Pass received message to voice event handler select { case <-close: return default: go v.onEvent(message) } } }
go
func (v *VoiceConnection) wsListen(wsConn *websocket.Conn, close <-chan struct{}) { v.log(LogInformational, "called") for { _, message, err := v.wsConn.ReadMessage() if err != nil { // Detect if we have been closed manually. If a Close() has already // happened, the websocket we are listening on will be different to the // current session. v.RLock() sameConnection := v.wsConn == wsConn v.RUnlock() if sameConnection { v.log(LogError, "voice endpoint %s websocket closed unexpectantly, %s", v.endpoint, err) // Start reconnect goroutine then exit. go v.reconnect() } return } // Pass received message to voice event handler select { case <-close: return default: go v.onEvent(message) } } }
[ "func", "(", "v", "*", "VoiceConnection", ")", "wsListen", "(", "wsConn", "*", "websocket", ".", "Conn", ",", "close", "<-", "chan", "struct", "{", "}", ")", "{", "v", ".", "log", "(", "LogInformational", ",", "\"called\"", ")", "\n", "for", "{", "_"...
// wsListen listens on the voice websocket for messages and passes them // to the voice event handler. This is automatically called by the Open func
[ "wsListen", "listens", "on", "the", "voice", "websocket", "for", "messages", "and", "passes", "them", "to", "the", "voice", "event", "handler", ".", "This", "is", "automatically", "called", "by", "the", "Open", "func" ]
8325a6bf6dd6c91ed4040a1617b07287b8fb0eba
https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/voice.go#L341-L372
train