_id
stringlengths
2
7
title
stringlengths
1
118
partition
stringclasses
3 values
text
stringlengths
52
85.5k
language
stringclasses
1 value
meta_information
dict
q17600
RootTypeSpec
train
func RootTypeSpec(s TypeSpec) TypeSpec { if t, ok := s.(*TypedefSpec); ok { return t.root } return s }
go
{ "resource": "" }
q17601
Link
train
func (r typeSpecReference) Link(scope Scope) (TypeSpec, error) { src := ast.TypeReference(r) t, err := scope.LookupType(src.Name) if err == nil { return t.Link(scope) } mname, iname := splitInclude(src.Name) if len(mname) == 0 { return nil, referenceError{ Target: src.Name, Line: src.Line, ScopeName: scope.GetName(), Reason: err, } } includedScope, err := getIncludedScope(scope, mname) if err != nil { return nil, referenceError{ Target: src.Name, Line: src.Line, ScopeName: scope.GetName(), Reason: err, } } t, err = typeSpecReference{Name: iname}.Link(includedScope) if err != nil { return nil, referenceError{ Target: src.Name, Line: src.Line, ScopeName: scope.GetName(), Reason: err, } } return t, nil }
go
{ "resource": "" }
q17602
ForEachTypeReference
train
func (r typeSpecReference) ForEachTypeReference(func(TypeSpec) error) error { panic(fmt.Sprintf( "ForEachTypeReference() called on unresolved TypeSpec reference %v."+ "Make sure you called Link().", r, )) }
go
{ "resource": "" }
q17603
compileTypeReference
train
func compileTypeReference(typ ast.Type) (TypeSpec, error) { if typ == nil { return nil, nil } switch t := typ.(type) { case ast.BaseType: return compileBaseType(t) case ast.MapType: return compileMapType(t) case ast.ListType: return compileListType(t) case ast.SetType: return compileSetType(t) case ast.TypeReference: return typeSpecReference(t), nil default: panic(fmt.Sprintf("unknown type %v", typ)) } }
go
{ "resource": "" }
q17604
NewServer
train
func NewServer(p protocol.Protocol, h Handler) Server { return Server{p: p, h: h} }
go
{ "resource": "" }
q17605
Handle
train
func (s Server) Handle(data []byte) ([]byte, error) { request, err := s.p.DecodeEnveloped(bytes.NewReader(data)) if err != nil { return nil, err } response := wire.Envelope{ Name: request.Name, SeqID: request.SeqID, Type: wire.Reply, } response.Value, err = s.h.Handle(request.Name, request.Value) if err != nil { response.Type = wire.Exception switch err.(type) { case ErrUnknownMethod: response.Value, err = tappExc(err, exception.ExceptionTypeUnknownMethod) default: response.Value, err = tappExc(err, exception.ExceptionTypeInternalError) } if err != nil { return nil, err } } var buff bytes.Buffer if err := s.p.EncodeEnveloped(response, &buff); err != nil { return nil, err } return buff.Bytes(), nil }
go
{ "resource": "" }
q17606
tappExc
train
func tappExc(err error, typ exception.ExceptionType) (wire.Value, error) { return (&exception.TApplicationException{ Message: ptr.String(err.Error()), Type: &typ, }).ToWire() }
go
{ "resource": "" }
q17607
Name
train
func (mh MultiHandle) Name() string { names := make([]string, 0, len(mh)) for _, h := range mh { names = append(names, h.Name()) } return fmt.Sprintf("MultiHandle{%v}", strings.Join(names, ", ")) }
go
{ "resource": "" }
q17608
Close
train
func (mh MultiHandle) Close() error { return concurrent.Range(mh, func(_ int, h Handle) error { return h.Close() }) }
go
{ "resource": "" }
q17609
ServiceGenerator
train
func (mh MultiHandle) ServiceGenerator() ServiceGenerator { msg := make(MultiServiceGenerator, 0, len(mh)) for _, h := range mh { if sg := h.ServiceGenerator(); sg != nil { msg = append(msg, sg) } } return msg }
go
{ "resource": "" }
q17610
Handle
train
func (msg MultiServiceGenerator) Handle() Handle { mh := make(MultiHandle, len(msg)) for i, sg := range msg { mh[i] = sg.Handle() } return mh }
go
{ "resource": "" }
q17611
Generate
train
func (msg MultiServiceGenerator) Generate(req *api.GenerateServiceRequest) (*api.GenerateServiceResponse, error) { var ( lock sync.Mutex files = make(map[string][]byte) usedPaths = make(map[string]string) // path -> plugin name ) err := concurrent.Range(msg, func(_ int, sg ServiceGenerator) error { res, err := sg.Generate(req) if err != nil { return err } lock.Lock() defer lock.Unlock() pluginName := sg.Handle().Name() for path, contents := range res.Files { if takenBy, taken := usedPaths[path]; taken { return fmt.Errorf("plugin conflict: cannot write file %q for plugin %q: "+ "plugin %q already wrote to that file", path, pluginName, takenBy) } usedPaths[path] = pluginName files[path] = contents } return nil }) return &api.GenerateServiceResponse{Files: files}, err }
go
{ "resource": "" }
q17612
NewTransportHandle
train
func NewTransportHandle(name string, t envelope.Transport) (Handle, error) { client := api.NewPluginClient(multiplex.NewClient( "Plugin", envelope.NewClient(_proto, t), )) handshake, err := client.Handshake(&api.HandshakeRequest{}) if err != nil { return nil, errHandshakeFailed{Name: name, Reason: err} } if handshake.Name != name { return nil, errHandshakeFailed{ Name: name, Reason: errNameMismatch{Want: name, Got: handshake.Name}, } } if handshake.APIVersion != api.APIVersion { return nil, errHandshakeFailed{ Name: name, Reason: errAPIVersionMismatch{Want: api.APIVersion, Got: handshake.APIVersion}, } } features := make(map[api.Feature]struct{}, len(handshake.Features)) for _, feature := range handshake.Features { features[feature] = struct{}{} } return &transportHandle{ name: name, Transport: t, Client: client, Running: atomic.NewBool(true), Features: features, }, nil }
go
{ "resource": "" }
q17613
Service
train
func Service(g Generator, s *compile.ServiceSpec) (map[string]*bytes.Buffer, error) { files := make(map[string]*bytes.Buffer) for _, functionName := range sortStringKeys(s.Functions) { fileName := fmt.Sprintf("%s_%s.go", strings.ToLower(s.Name), strings.ToLower(functionName)) function := s.Functions[functionName] if err := ServiceFunction(g, s, function); err != nil { return nil, fmt.Errorf( "could not generate types for %s.%s: %v", s.Name, functionName, err) } buff := new(bytes.Buffer) if err := g.Write(buff, token.NewFileSet()); err != nil { return nil, fmt.Errorf("could not write %s.%s: %v", s.Name, functionName, err) } // TODO check for conflicts files[fileName] = buff } return files, nil }
go
{ "resource": "" }
q17614
ServiceFunction
train
func ServiceFunction(g Generator, s *compile.ServiceSpec, f *compile.FunctionSpec) error { argsName := functionNamePrefix(s, f) + "Args" argsGen := fieldGroupGenerator{ Namespace: NewNamespace(), Name: argsName, Fields: compile.FieldGroup(f.ArgsSpec), Doc: fmt.Sprintf( "%v represents the arguments for the %v.%v function.\n\n"+ "The arguments for %v are sent and received over the wire as this struct.", argsName, s.Name, f.Name, f.Name, ), } if err := argsGen.Generate(g); err != nil { return wrapGenerateError(fmt.Sprintf("%s.%s", s.Name, f.Name), err) } if err := functionArgsEnveloper(g, s, f); err != nil { return wrapGenerateError(fmt.Sprintf("%s.%s", s.Name, f.Name), err) } if err := functionHelper(g, s, f); err != nil { return wrapGenerateError(fmt.Sprintf("%s.%s", s.Name, f.Name), err) } if f.ResultSpec == nil { return nil } resultFields := make(compile.FieldGroup, 0, len(f.ResultSpec.Exceptions)+1) if f.ResultSpec.ReturnType != nil { resultFields = append(resultFields, &compile.FieldSpec{ ID: 0, Name: "success", Type: f.ResultSpec.ReturnType, Doc: fmt.Sprintf("Value returned by %v after a successful execution.", f.Name), }) } resultFields = append(resultFields, f.ResultSpec.Exceptions...) resultName := functionNamePrefix(s, f) + "Result" resultDoc := fmt.Sprintf( "%v represents the result of a %v.%v function call.\n\n"+ "The result of a %v execution is sent and received over the wire as this struct.", resultName, s.Name, f.Name, f.Name, ) if f.ResultSpec.ReturnType != nil { resultDoc += fmt.Sprintf("\n\nSuccess is set only if the function did not throw an exception.") } resultGen := fieldGroupGenerator{ Namespace: NewNamespace(), Name: resultName, Fields: resultFields, IsUnion: true, AllowEmptyUnion: f.ResultSpec.ReturnType == nil, Doc: resultDoc, } if err := resultGen.Generate(g); err != nil { return wrapGenerateError(fmt.Sprintf("%s.%s", s.Name, f.Name), err) } if err := functionResponseEnveloper(g, s, f); err != nil { return wrapGenerateError(fmt.Sprintf("%s.%s", s.Name, f.Name), err) } // TODO(abg): If we receive unknown exceptions over the wire, we need to // throw a generic error. return nil }
go
{ "resource": "" }
q17615
functionParams
train
func functionParams(g Generator, f *compile.FunctionSpec) (string, error) { return g.TextTemplate( ` <- $params := newNamespace -> <- range .ArgsSpec> <- if .Required> <$params.NewName .Name> <typeReference .Type>, <- else> <$params.NewName .Name> <typeReferencePtr .Type>, <- end -> <end> `, f) }
go
{ "resource": "" }
q17616
functionNewArgs
train
func functionNewArgs(g Generator, s *compile.ServiceSpec, f *compile.FunctionSpec) (string, error) { return g.TextTemplate( ` <- $f := .Function -> <- $prefix := namePrefix .Service $f -> <- $params := newNamespace -> func( <- range $f.ArgsSpec> <- if .Required> <$params.NewName .Name> <typeReference .Type>, <- else> <$params.NewName .Name> <typeReferencePtr .Type>, <- end -> <end> ) *<$prefix>Args { return &<$prefix>Args{ <range $f.ArgsSpec> <- if .Required -> <goCase .Name>: <$params.Rotate .Name>, <- else -> <goCase .Name>: <$params.Rotate .Name>, <- end> <end> } } `, struct { Service *compile.ServiceSpec Function *compile.FunctionSpec }{ Service: s, Function: f, }, TemplateFunc("namePrefix", functionNamePrefix)) }
go
{ "resource": "" }
q17617
BorrowWriter
train
func BorrowWriter(w io.Writer) *Writer { writer := writerPool.Get().(*Writer) writer.writer = w return writer }
go
{ "resource": "" }
q17618
WriteValue
train
func (bw *Writer) WriteValue(v wire.Value) error { switch v.Type() { case wire.TBool: if v.GetBool() { return bw.writeByte(1) } return bw.writeByte(0) case wire.TI8: return bw.writeByte(byte(v.GetI8())) case wire.TDouble: value := math.Float64bits(v.GetDouble()) return bw.writeInt64(int64(value)) case wire.TI16: return bw.writeInt16(v.GetI16()) case wire.TI32: return bw.writeInt32(v.GetI32()) case wire.TI64: return bw.writeInt64(v.GetI64()) case wire.TBinary: b := v.GetBinary() if err := bw.writeInt32(int32(len(b))); err != nil { return err } return bw.write(b) case wire.TStruct: return bw.writeStruct(v.GetStruct()) case wire.TMap: return bw.writeMap(v.GetMap()) case wire.TSet: return bw.writeSet(v.GetSet()) case wire.TList: return bw.writeList(v.GetList()) default: return fmt.Errorf("unknown ttype %v", v.Type()) } }
go
{ "resource": "" }
q17619
Info
train
func (c *Constant) Info() DefinitionInfo { return DefinitionInfo{Name: c.Name, Line: c.Line} }
go
{ "resource": "" }
q17620
Info
train
func (t *Typedef) Info() DefinitionInfo { return DefinitionInfo{Name: t.Name, Line: t.Line} }
go
{ "resource": "" }
q17621
Info
train
func (e *Enum) Info() DefinitionInfo { return DefinitionInfo{Name: e.Name, Line: e.Line} }
go
{ "resource": "" }
q17622
Info
train
func (s *Struct) Info() DefinitionInfo { return DefinitionInfo{Name: s.Name, Line: s.Line} }
go
{ "resource": "" }
q17623
Info
train
func (s *Service) Info() DefinitionInfo { return DefinitionInfo{Name: s.Name, Line: s.Line} }
go
{ "resource": "" }
q17624
curryGenerator
train
func curryGenerator(f interface{}, g Generator) interface{} { typ := reflect.TypeOf(f) if typ.NumIn() > 0 && typ.In(0) == _typeOfGenerator { return curry.One(f, g) } return f }
go
{ "resource": "" }
q17625
NewGenerator
train
func NewGenerator(o *GeneratorOptions) Generator { // TODO(abg): Determine package name from `namespace go` directive. namespace := NewNamespace() return &generator{ PackageName: o.PackageName, ImportPath: o.ImportPath, Namespace: namespace, importer: newImporter(namespace.Child()), mangler: newMangler(), thriftImporter: o.Importer, fset: token.NewFileSet(), noZap: o.NoZap, } }
go
{ "resource": "" }
q17626
checkNoZap
train
func checkNoZap(g Generator) bool { if gen, ok := g.(*generator); ok { return gen.noZap } return false }
go
{ "resource": "" }
q17627
TextTemplate
train
func (g *generator) TextTemplate(s string, data interface{}, opts ...TemplateOption) (string, error) { templateFuncs := template.FuncMap{ "formatDoc": formatDoc, "goCase": goCase, "goName": goName, "import": g.Import, "isHashable": isHashable, "setUsesMap": setUsesMap, "isPrimitiveType": isPrimitiveType, "isStructType": isStructType, "newNamespace": g.Namespace.Child, "newVar": g.Namespace.Child().NewName, "typeName": curryGenerator(typeName, g), "typeReference": curryGenerator(typeReference, g), "typeReferencePtr": curryGenerator(typeReferencePtr, g), "fromWire": curryGenerator(g.w.FromWire, g), "fromWirePtr": curryGenerator(g.w.FromWirePtr, g), "toWire": curryGenerator(g.w.ToWire, g), "toWirePtr": curryGenerator(g.w.ToWirePtr, g), "typeCode": curryGenerator(TypeCode, g), "equals": curryGenerator(g.e.Equals, g), "equalsPtr": curryGenerator(g.e.EqualsPtr, g), "zapEncodeBegin": curryGenerator(g.z.zapEncodeBegin, g), "zapEncodeEnd": g.z.zapEncodeEnd, "zapEncoder": curryGenerator(g.z.zapEncoder, g), "zapMarshaler": curryGenerator(g.z.zapMarshaler, g), "zapMarshalerPtr": curryGenerator(g.z.zapMarshalerPtr, g), } tmpl := template.New("thriftrw").Delims("<", ">").Funcs(templateFuncs) for _, opt := range opts { tmpl = opt(g, tmpl) } tmpl, err := tmpl.Parse(s) if err != nil { return "", err } buff := bytes.Buffer{} if err := tmpl.Execute(&buff, data); err != nil { return "", err } return buff.String(), nil }
go
{ "resource": "" }
q17628
appendDecl
train
func (g *generator) appendDecl(decl ast.Decl) { g.decls = append(g.decls, decl) }
go
{ "resource": "" }
q17629
Generate
train
func Generate(m *compile.Module, o *Options) error { if !filepath.IsAbs(o.ThriftRoot) { return fmt.Errorf( "ThriftRoot must be an absolute path: %q is not absolute", o.ThriftRoot) } if !filepath.IsAbs(o.OutputDir) { return fmt.Errorf( "OutputDir must be an absolute path: %q is not absolute", o.OutputDir) } importer := thriftPackageImporter{ ImportPrefix: o.PackagePrefix, ThriftRoot: o.ThriftRoot, } // Mapping of filenames relative to OutputDir to their contents. files := make(map[string][]byte) genBuilder := newGenerateServiceBuilder(importer) generate := func(m *compile.Module) error { moduleFiles, err := generateModule(m, importer, genBuilder, o) if err != nil { return generateError{Name: m.ThriftPath, Reason: err} } if err := mergeFiles(files, moduleFiles); err != nil { return generateError{Name: m.ThriftPath, Reason: err} } return nil } // Note that we call generate directly on only those modules that we need // to generate code for. If the user used --no-recurse, we're not going to // generate code for included modules. if o.NoRecurse { if err := generate(m); err != nil { return err } } else { if err := m.Walk(generate); err != nil { return err } } plug := o.Plugin if plug == nil { plug = plugin.EmptyHandle } if sgen := plug.ServiceGenerator(); sgen != nil { res, err := sgen.Generate(genBuilder.Build()) if err != nil { return err } if err := mergeFiles(files, res.Files); err != nil { return err } } for relPath, contents := range files { fullPath := filepath.Join(o.OutputDir, relPath) directory := filepath.Dir(fullPath) if err := os.MkdirAll(directory, 0755); err != nil { return fmt.Errorf("could not create directory %q: %v", directory, err) } if err := ioutil.WriteFile(fullPath, contents, 0644); err != nil { return fmt.Errorf("failed to write %q: %v", fullPath, err) } } return nil }
go
{ "resource": "" }
q17630
Visit
train
func (f VisitorFunc) Visit(w Walker, n Node) Visitor { f(w, n) return f }
go
{ "resource": "" }
q17631
Handle
train
func (f *Flag) Handle() (Handle, error) { transport, err := process.NewClient(f.Command) if err != nil { return nil, fmt.Errorf("failed to open plugin %q: %v", f.Name, err) } handle, err := NewTransportHandle(f.Name, transport) if err != nil { return nil, multierr.Combine( fmt.Errorf("failed to open plugin %q: %v", f.Name, err), transport.Close(), ) } return handle, nil }
go
{ "resource": "" }
q17632
UnmarshalFlag
train
func (f *Flag) UnmarshalFlag(value string) error { tokens, err := shlex.Split(value, true /* posix */) if err != nil { return fmt.Errorf("invalid plugin %q: %v", value, err) } if len(tokens) < 1 { return fmt.Errorf("invalid plugin %q: please provide a name", value) } f.Name = tokens[0] exe := _pluginExecPrefix + f.Name path, err := exec.LookPath(exe) if err != nil { return fmt.Errorf("invalid plugin %q: could not find executable %q: %v", value, exe, err) } cmd := exec.Command(path, tokens[1:]...) cmd.Stderr = os.Stderr // connect stderr so that plugins can log f.Command = cmd return nil }
go
{ "resource": "" }
q17633
Handle
train
func (fs Flags) Handle() (MultiHandle, error) { var ( lock sync.Mutex multi MultiHandle ) err := concurrent.Range(fs, func(_ int, f Flag) error { h, err := f.Handle() if err != nil { return err } lock.Lock() defer lock.Unlock() multi = append(multi, h) return nil }) if err == nil { return multi, nil } return nil, multierr.Append(err, multi.Close()) }
go
{ "resource": "" }
q17634
ToWirePtr
train
func (w *WireGenerator) ToWirePtr(g Generator, spec compile.TypeSpec, varName string) (string, error) { switch spec.(type) { case *compile.BoolSpec, *compile.I8Spec, *compile.I16Spec, *compile.I32Spec, *compile.I64Spec, *compile.DoubleSpec, *compile.StringSpec: return w.ToWire(g, spec, fmt.Sprintf("*(%s)", varName)) default: // Everything else is either a reference type or has a ToWire method // on it that does automatic dereferencing. return w.ToWire(g, spec, varName) } }
go
{ "resource": "" }
q17635
FromWirePtr
train
func (w *WireGenerator) FromWirePtr(g Generator, spec compile.TypeSpec, lhs string, value string) (string, error) { if !isPrimitiveType(spec) { // Everything else can be assigned to directly. out, err := w.FromWire(g, spec, value) if err != nil { return "", err } return fmt.Sprintf("%s, err = %s", lhs, out), err } return g.TextTemplate( ` <- $x := newVar "x" -> var <$x> <typeReference .Spec> <$x>, err = <fromWire .Spec .Value> <.LHS> = &<$x -> `, struct { Spec compile.TypeSpec LHS string Value string }{Spec: spec, LHS: lhs, Value: value}, ) }
go
{ "resource": "" }
q17636
TypeCode
train
func TypeCode(g Generator, spec compile.TypeSpec) string { wire := g.Import("go.uber.org/thriftrw/wire") spec = compile.RootTypeSpec(spec) switch spec.(type) { case *compile.BoolSpec: return fmt.Sprintf("%s.TBool", wire) case *compile.I8Spec: return fmt.Sprintf("%s.TI8", wire) case *compile.I16Spec: return fmt.Sprintf("%s.TI16", wire) case *compile.I32Spec: return fmt.Sprintf("%s.TI32", wire) case *compile.I64Spec: return fmt.Sprintf("%s.TI64", wire) case *compile.DoubleSpec: return fmt.Sprintf("%s.TDouble", wire) case *compile.StringSpec, *compile.BinarySpec: return fmt.Sprintf("%s.TBinary", wire) case *compile.MapSpec: return fmt.Sprintf("%s.TMap", wire) case *compile.ListSpec: return fmt.Sprintf("%s.TList", wire) case *compile.SetSpec: return fmt.Sprintf("%s.TSet", wire) case *compile.EnumSpec: return fmt.Sprintf("%s.TI32", wire) case *compile.StructSpec: return fmt.Sprintf("%s.TStruct", wire) default: panic(fmt.Sprintf("unknown type spec %v (type %T)", spec, spec)) } }
go
{ "resource": "" }
q17637
isRequired
train
func (r fieldRequiredness) isRequired(src *ast.Field) (bool, error) { switch r { case explicitRequiredness: if src.Requiredness == ast.Unspecified { return false, requirednessRequiredError{ FieldName: src.Name, Line: src.Line, } } case noRequiredFields: if src.Requiredness == ast.Required { return false, cannotBeRequiredError{ FieldName: src.Name, Line: src.Line, } } default: // do nothing } // A field is considered required only if it was marked required AND it // does not have a default value. return (src.Requiredness == ast.Required && src.Default == nil), nil }
go
{ "resource": "" }
q17638
compileField
train
func compileField(src *ast.Field, options fieldOptions) (*FieldSpec, error) { if src.ID < 1 || src.ID > math.MaxInt16 { return nil, fieldIDOutOfBoundsError{ID: src.ID, Name: src.Name} } required, err := options.requiredness.isRequired(src) if err != nil { return nil, err } if options.disallowDefaultValue && src.Default != nil { return nil, defaultValueNotAllowedError{ FieldName: src.Name, Line: src.Line, } } annotations, err := compileAnnotations(src.Annotations) if err != nil { return nil, compileError{ Target: src.Name, Line: src.Line, Reason: err, } } typ, err := compileTypeReference(src.Type) if err != nil { return nil, compileError{ Target: src.Name, Line: src.Line, Reason: err, } } return &FieldSpec{ // TODO(abg): perform bounds check on field ID ID: int16(src.ID), Name: src.Name, Type: typ, Doc: src.Doc, Required: required, Default: compileConstantValue(src.Default), Annotations: annotations, }, nil }
go
{ "resource": "" }
q17639
Link
train
func (f *FieldSpec) Link(scope Scope) (err error) { if f.Type, err = f.Type.Link(scope); err != nil { return err } if f.Default != nil { f.Default, err = f.Default.Link(scope, f.Type) } return err }
go
{ "resource": "" }
q17640
compileFields
train
func compileFields(src []*ast.Field, options fieldOptions) (FieldGroup, error) { fieldsNS := newNamespace(caseInsensitive) usedIDs := make(map[int16]string) fields := make([]*FieldSpec, 0, len(src)) for _, astField := range src { if err := fieldsNS.claim(astField.Name, astField.Line); err != nil { return nil, compileError{ Target: astField.Name, Line: astField.Line, Reason: err, } } field, err := compileField(astField, options) if err != nil { return nil, compileError{ Target: astField.Name, Line: astField.Line, Reason: err, } } if conflictingField, ok := usedIDs[field.ID]; ok { return nil, compileError{ Target: astField.Name, Line: astField.Line, Reason: fieldIDConflictError{ ID: field.ID, Name: conflictingField, }, } } fields = append(fields, field) usedIDs[field.ID] = field.Name } return FieldGroup(fields), nil }
go
{ "resource": "" }
q17641
FindByName
train
func (fg FieldGroup) FindByName(name string) (*FieldSpec, error) { for _, field := range fg { if field.Name == name { return field, nil } } return nil, fmt.Errorf("unknown field %v", name) }
go
{ "resource": "" }
q17642
Link
train
func (fg FieldGroup) Link(scope Scope) error { for _, field := range fg { if err := field.Link(scope); err != nil { return err } } return nil }
go
{ "resource": "" }
q17643
ForEachTypeReference
train
func (fg FieldGroup) ForEachTypeReference(f func(TypeSpec) error) error { for _, field := range fg { if err := f(field.Type); err != nil { return err } } return nil }
go
{ "resource": "" }
q17644
LookupType
train
func (m *Module) LookupType(name string) (TypeSpec, error) { if t, ok := m.Types[name]; ok { return t, nil } return nil, lookupError{Name: name} }
go
{ "resource": "" }
q17645
LookupConstant
train
func (m *Module) LookupConstant(name string) (*Constant, error) { if c, ok := m.Constants[name]; ok { return c, nil } return nil, lookupError{Name: name} }
go
{ "resource": "" }
q17646
LookupService
train
func (m *Module) LookupService(name string) (*ServiceSpec, error) { if s, ok := m.Services[name]; ok { return s, nil } return nil, lookupError{Name: name} }
go
{ "resource": "" }
q17647
LookupInclude
train
func (m *Module) LookupInclude(name string) (Scope, error) { if s, ok := m.Includes[name]; ok { return s.Module, nil } return nil, lookupError{Name: name} }
go
{ "resource": "" }
q17648
Walk
train
func (m *Module) Walk(f func(*Module) error) error { visited := make(map[string]struct{}) toVisit := make([]*Module, 0, 100) toVisit = append(toVisit, m) for len(toVisit) > 0 { m := toVisit[0] toVisit = toVisit[1:] if _, ok := visited[m.ThriftPath]; ok { continue } visited[m.ThriftPath] = struct{}{} for _, inc := range m.Includes { toVisit = append(toVisit, inc.Module) } if err := f(m); err != nil { return err } } return nil }
go
{ "resource": "" }
q17649
compileConstantValue
train
func compileConstantValue(v ast.ConstantValue) ConstantValue { if v == nil { return nil } // TODO(abg): Support typedefs switch src := v.(type) { case ast.ConstantReference: return constantReference(src) case ast.ConstantMap: return compileConstantMap(src) case ast.ConstantList: return compileConstantList(src) case ast.ConstantBoolean: return ConstantBool(src) case ast.ConstantInteger: return ConstantInt(src) case ast.ConstantString: return ConstantString(src) case ast.ConstantDouble: return ConstantDouble(src) default: panic(fmt.Sprintf("unknown constant value of type %T: %v", src, src)) } }
go
{ "resource": "" }
q17650
Link
train
func (c ConstantBool) Link(scope Scope, t TypeSpec) (ConstantValue, error) { if _, ok := RootTypeSpec(t).(*BoolSpec); !ok { return nil, constantValueCastError{Value: c, Type: t} } return c, nil }
go
{ "resource": "" }
q17651
Link
train
func (c ConstantInt) Link(scope Scope, t TypeSpec) (ConstantValue, error) { rt := RootTypeSpec(t) switch spec := rt.(type) { case *I8Spec, *I16Spec, *I32Spec, *I64Spec: // TODO bounds checks? return c, nil case *DoubleSpec: return ConstantDouble(float64(c)).Link(scope, t) case *BoolSpec: switch v := int64(c); v { case 0, 1: return ConstantBool(v == 1).Link(scope, t) default: return nil, constantValueCastError{ Value: c, Type: t, Reason: errors.New("the value must be 0 or 1"), } } case *EnumSpec: for _, item := range spec.Items { if item.Value == int32(c) { return EnumItemReference{Enum: spec, Item: &item}, nil } } return nil, constantValueCastError{ Value: c, Type: t, Reason: fmt.Errorf( "%v is not a valid value for enum %q", int32(c), spec.ThriftName()), } } return nil, constantValueCastError{Value: c, Type: t} // TODO: AST for constants will need to track positions for us to // include them in the error messages. }
go
{ "resource": "" }
q17652
Link
train
func (c ConstantString) Link(scope Scope, t TypeSpec) (ConstantValue, error) { // TODO(abg): Are binary literals a thing? if _, ok := RootTypeSpec(t).(*StringSpec); !ok { return nil, constantValueCastError{Value: c, Type: t} } return c, nil }
go
{ "resource": "" }
q17653
Link
train
func (c ConstantDouble) Link(scope Scope, t TypeSpec) (ConstantValue, error) { if _, ok := RootTypeSpec(t).(*DoubleSpec); !ok { return nil, constantValueCastError{Value: c, Type: t} } return c, nil }
go
{ "resource": "" }
q17654
buildConstantStruct
train
func buildConstantStruct(c ConstantMap) (*ConstantStruct, error) { fields := make(map[string]ConstantValue, len(c)) for _, pair := range c { s, isString := pair.Key.(ConstantString) if !isString { return nil, fmt.Errorf( "%v is not a string: all keys must be strings", pair.Key) } fields[string(s)] = pair.Value } return &ConstantStruct{Fields: fields}, nil }
go
{ "resource": "" }
q17655
Link
train
func (c *ConstantStruct) Link(scope Scope, t TypeSpec) (ConstantValue, error) { s, ok := RootTypeSpec(t).(*StructSpec) if !ok { return nil, constantValueCastError{Value: c, Type: t} } for _, field := range s.Fields { f, ok := c.Fields[field.Name] if !ok { if field.Default == nil { if field.Required { return nil, constantValueCastError{ Value: c, Type: t, Reason: fmt.Errorf("%q is a required field", field.Name), } } continue } f = field.Default c.Fields[field.Name] = f } f, err := f.Link(scope, field.Type) if err != nil { return nil, constantValueCastError{ Value: c, Type: t, Reason: constantStructFieldCastError{ FieldName: field.Name, Reason: err, }, } } c.Fields[field.Name] = f } return c, nil }
go
{ "resource": "" }
q17656
Link
train
func (c ConstantMap) Link(scope Scope, t TypeSpec) (ConstantValue, error) { rt := RootTypeSpec(t) if _, isStruct := rt.(*StructSpec); isStruct { cs, err := buildConstantStruct(c) if err != nil { return nil, constantValueCastError{ Value: c, Type: t, Reason: err, } } return cs.Link(scope, t) } m, ok := rt.(*MapSpec) if !ok { return nil, constantValueCastError{Value: c, Type: t} } items := make([]ConstantValuePair, len(c)) for i, item := range c { key, err := item.Key.Link(scope, m.KeySpec) if err != nil { return nil, err } value, err := item.Value.Link(scope, m.ValueSpec) if err != nil { return nil, err } // TODO(abg): Duplicate key check items[i] = ConstantValuePair{Key: key, Value: value} } return ConstantMap(items), nil }
go
{ "resource": "" }
q17657
Link
train
func (c ConstantSet) Link(scope Scope, t TypeSpec) (ConstantValue, error) { s, ok := RootTypeSpec(t).(*SetSpec) if !ok { return nil, constantValueCastError{Value: c, Type: t} } // TODO(abg): Track whether things are linked so that we don't re-link here // TODO(abg): Fail for duplicates values := make([]ConstantValue, len(c)) for i, v := range c { value, err := v.Link(scope, s.ValueSpec) if err != nil { return nil, err } values[i] = value } return ConstantSet(values), nil }
go
{ "resource": "" }
q17658
Link
train
func (c ConstantList) Link(scope Scope, t TypeSpec) (ConstantValue, error) { rt := RootTypeSpec(t) if _, isSet := rt.(*SetSpec); isSet { return ConstantSet(c).Link(scope, t) } l, ok := rt.(*ListSpec) if !ok { return nil, constantValueCastError{Value: c, Type: t} } values := make([]ConstantValue, len(c)) for i, v := range c { value, err := v.Link(scope, l.ValueSpec) if err != nil { return nil, err } values[i] = value } return ConstantList(values), nil }
go
{ "resource": "" }
q17659
Link
train
func (c ConstReference) Link(scope Scope, t TypeSpec) (ConstantValue, error) { if t == c.Target.Type { return c, nil } return c.Target.Value.Link(scope, t) }
go
{ "resource": "" }
q17660
Link
train
func (e EnumItemReference) Link(scope Scope, t TypeSpec) (ConstantValue, error) { if RootTypeSpec(t) != e.Enum { return nil, constantValueCastError{Value: e, Type: t} } return e, nil }
go
{ "resource": "" }
q17661
Link
train
func (r constantReference) Link(scope Scope, t TypeSpec) (ConstantValue, error) { src := ast.ConstantReference(r) c, err := scope.LookupConstant(src.Name) if err == nil { if err := c.Link(scope); err != nil { return nil, err } return ConstReference{Target: c}.Link(scope, t) } mname, iname := splitInclude(src.Name) if len(mname) == 0 { return nil, referenceError{ Target: src.Name, Line: src.Line, ScopeName: scope.GetName(), Reason: err, } } if enum, ok := lookupEnum(scope, mname); ok { if item, ok := enum.LookupItem(iname); ok { return EnumItemReference{ Enum: enum, Item: item, }, nil } return nil, referenceError{ Target: src.Name, Line: src.Line, ScopeName: scope.GetName(), Reason: unrecognizedEnumItemError{ EnumName: mname, ItemName: iname, }, } } includedScope, err := getIncludedScope(scope, mname) if err != nil { return nil, referenceError{ Target: src.Name, Line: src.Line, ScopeName: scope.GetName(), Reason: err, } } value, err := constantReference{Name: iname}.Link(includedScope, t) if err != nil { return nil, referenceError{ Target: src.Name, Line: src.Line, ScopeName: scope.GetName(), Reason: err, } } return value, nil }
go
{ "resource": "" }
q17662
lookupEnum
train
func lookupEnum(scope Scope, name string) (*EnumSpec, bool) { t, err := scope.LookupType(name) if err != nil { return nil, false } if enum, ok := t.(*EnumSpec); ok { return enum, true } return nil, false }
go
{ "resource": "" }
q17663
NewClient
train
func NewClient(cmd *exec.Cmd) (*Client, error) { stdout, err := cmd.StdoutPipe() if err != nil { return nil, fmt.Errorf("failed to create stdout pipe to %q: %v", cmd.Path, err) } stdin, err := cmd.StdinPipe() if err != nil { return nil, fmt.Errorf("failed to create stdin pipe to %q: %v", cmd.Path, err) } if err := cmd.Start(); err != nil { return nil, fmt.Errorf("failed to start %q: %v", cmd.Path, err) } return &Client{ stdout: stdout, stdin: stdin, running: atomic.NewBool(true), client: frame.NewClient(stdin, stdout), cmd: cmd, }, nil }
go
{ "resource": "" }
q17664
Send
train
func (c *Client) Send(data []byte) ([]byte, error) { if !c.running.Load() { panic(fmt.Sprintf("process.Client for %q has been closed", c.cmd.Path)) } return c.client.Send(data) }
go
{ "resource": "" }
q17665
Close
train
func (c *Client) Close() error { if !c.running.Swap(false) { return nil // already stopped } var errors []error if err := c.stdout.Close(); err != nil { errors = append(errors, fmt.Errorf("failed to detach stdout from %q: %v", c.cmd.Path, err)) } if err := c.stdin.Close(); err != nil { errors = append(errors, fmt.Errorf("failed to detach stdin from %q: %v", c.cmd.Path, err)) } if err := c.cmd.Wait(); err != nil { errors = append(errors, fmt.Errorf("%q failed with: %v", c.cmd.Path, err)) } return multierr.Combine(errors...) }
go
{ "resource": "" }
q17666
Equals
train
func (v *Plugin_Goodbye_Args) Equals(rhs *Plugin_Goodbye_Args) bool { if v == nil { return rhs == nil } else if rhs == nil { return false } return true }
go
{ "resource": "" }
q17667
Equals
train
func (v *Plugin_Goodbye_Result) Equals(rhs *Plugin_Goodbye_Result) bool { if v == nil { return rhs == nil } else if rhs == nil { return false } return true }
go
{ "resource": "" }
q17668
LineNumber
train
func LineNumber(n Node) int { if nl, ok := n.(nodeWithLine); ok { return nl.lineNumber() } return 0 }
go
{ "resource": "" }
q17669
Read
train
func (r *Reader) Read() ([]byte, error) { r.Lock() defer r.Unlock() if _, err := io.ReadFull(r.r, r.buff[:]); err != nil { return nil, err } length := int64(binary.BigEndian.Uint32(r.buff[:])) if length < _fastPathFrameSize { return r.readFastPath(length) } var buff bytes.Buffer _, err := io.CopyN(&buff, r.r, length) if err != nil { return nil, err } return buff.Bytes(), nil }
go
{ "resource": "" }
q17670
Close
train
func (r *Reader) Close() error { if r.closed.Swap(true) { return nil // already closed } if c, ok := r.r.(io.Closer); ok { return c.Close() } return nil }
go
{ "resource": "" }
q17671
unsafeStringToBytes
train
func unsafeStringToBytes(s string) []byte { sh := (*reflect.StringHeader)(unsafe.Pointer(&s)) sliceHeader := reflect.SliceHeader{ Data: sh.Data, Len: sh.Len, Cap: sh.Len, } return *(*[]byte)(unsafe.Pointer(&sliceHeader)) }
go
{ "resource": "" }
q17672
typedef
train
func typedef(g Generator, spec *compile.TypedefSpec) error { err := g.DeclareFromTemplate( ` <$fmt := import "fmt"> <$wire := import "go.uber.org/thriftrw/wire"> <$typedefType := typeReference .> <formatDoc .Doc>type <typeName .> <typeName .Target> <$v := newVar "v"> <$x := newVar "x"> <- if isPrimitiveType .> // <typeName .>Ptr returns a pointer to a <$typedefType> func (<$v> <typeName .>) Ptr() *<$typedefType>{ return &<$v> } <- end> // ToWire translates <typeName .> into a Thrift-level intermediate // representation. This intermediate representation may be serialized // into bytes using a ThriftRW protocol implementation. func (<$v> <$typedefType>) ToWire() (<$wire>.Value, error) { <$x> := (<typeReference .Target>)(<$v>) return <toWire .Target $x> } // String returns a readable string representation of <typeName .>. func (<$v> <$typedefType>) String() string { <$x> := (<typeReference .Target>)(<$v>) return <$fmt>.Sprint(<$x>) } <$w := newVar "w"> // FromWire deserializes <typeName .> from its Thrift-level // representation. The Thrift-level representation may be obtained // from a ThriftRW protocol implementation. func (<$v> *<typeName .>) FromWire(<$w> <$wire>.Value) error { <if isStructType . -> return (<typeReference .Target>)(<$v>).FromWire(<$w>) <- else -> <$x>, err := <fromWire .Target $w> *<$v> = (<$typedefType>)(<$x>) return err <- end> } <$lhs := newVar "lhs"> <$rhs := newVar "rhs"> // Equals returns true if this <typeName .> is equal to the provided // <typeName .>. func (<$lhs> <$typedefType>) Equals(<$rhs> <$typedefType>) bool { <- $lhsCast := printf "(%v)(%v)" (typeReference .Target) $lhs -> <- $rhsCast := printf "(%v)(%v)" (typeReference .Target) $rhs -> return <equals .Target $lhsCast $rhsCast> } <if not (checkNoZap) -> </* We want the behavior of the underlying type for typedefs: in the case that they are objects or arrays, we need to cast to the underlying object or array; else, zapMarshaler in zap.go will take care of it. */> <if (eq (zapEncoder .Target) "Object") -> <$zapcore := import "go.uber.org/zap/zapcore"> <$enc := newVar "enc"> func (<$v> <$typedefType>) MarshalLogObject(<$enc> <$zapcore>.ObjectEncoder) error { return (<zapMarshaler . $v>).MarshalLogObject(<$enc>) } <- end> <if (eq (zapEncoder .Target) "Array") -> <$zapcore := import "go.uber.org/zap/zapcore"> <$enc := newVar "enc"> func (<$v> <$typedefType>) MarshalLogArray(<$enc> <$zapcore>.ArrayEncoder) error { return (<zapMarshaler . $v>).MarshalLogArray(<$enc>) } <- end> <- end> `, spec, TemplateFunc("checkNoZap", checkNoZap), ) return wrapGenerateError(spec.Name, err) }
go
{ "resource": "" }
q17673
EncodeResponse
train
func (r EnvelopeV0Responder) EncodeResponse(v wire.Value, t wire.EnvelopeType, w io.Writer) error { writer := binary.BorrowWriter(w) err := writer.WriteLegacyEnveloped(wire.Envelope{ Name: r.Name, Type: t, SeqID: r.SeqID, Value: v, }) binary.ReturnWriter(writer) return err }
go
{ "resource": "" }
q17674
visited
train
func (f typeCycleFinder) visited(s TypeSpec) bool { for _, t := range f { if t == s { return true } } return false }
go
{ "resource": "" }
q17675
cloneWithPart
train
func (f typeCycleFinder) cloneWithPart(s TypeSpec) typeCycleFinder { newf := make(typeCycleFinder, 0, len(f)+1) newf = append(newf, f...) newf = append(newf, s) return newf }
go
{ "resource": "" }
q17676
newImporter
train
func newImporter(ns Namespace) importer { return importer{ ns: ns, imports: make(map[string]*ast.ImportSpec), } }
go
{ "resource": "" }
q17677
AddImportSpec
train
func (i importer) AddImportSpec(spec *ast.ImportSpec) error { path := spec.Path.Value name := filepath.Base(path) if spec.Name != nil { name = spec.Name.Name } if err := i.ns.Reserve(name); err != nil { return err } i.imports[path] = spec return nil }
go
{ "resource": "" }
q17678
Import
train
func (i importer) Import(path string) string { if imp, ok := i.imports[path]; ok { if imp.Name != nil { return imp.Name.Name } return filepath.Base(path) } name := i.ns.NewName(goast.DeterminePackageName(path)) astImport := &ast.ImportSpec{ Name: ast.NewIdent(name), Path: stringLiteral(path), } i.imports[path] = astImport return name }
go
{ "resource": "" }
q17679
importDecl
train
func (i importer) importDecl() ast.Decl { imports := i.imports if imports == nil || len(imports) == 0 { return nil } specs := make([]ast.Spec, 0, len(imports)) for _, iname := range sortStringKeys(imports) { imp := imports[iname] specs = append(specs, imp) } decl := &ast.GenDecl{Tok: token.IMPORT, Specs: specs} if len(specs) > 1 { // Just need a non-zero value for Lparen to get the parens added. decl.Lparen = token.Pos(1) } return decl }
go
{ "resource": "" }
q17680
Write
train
func Write(p protocol.Protocol, w io.Writer, seqID int32, e Enveloper) error { body, err := e.ToWire() if err != nil { return err } return p.EncodeEnveloped(wire.Envelope{ SeqID: seqID, Name: e.MethodName(), Type: e.EnvelopeType(), Value: body, }, w) }
go
{ "resource": "" }
q17681
ReadReply
train
func ReadReply(p protocol.Protocol, r io.ReaderAt) (_ wire.Value, seqID int32, _ error) { envelope, err := p.DecodeEnveloped(r) if err != nil { return wire.Value{}, 0, err } switch { case envelope.Type == wire.Reply: return envelope.Value, envelope.SeqID, nil case envelope.Type != wire.Exception: return envelope.Value, envelope.SeqID, fmt.Errorf("unknown envelope type for reply, got %v", envelope.Type) } // Decode the exception payload. ex := &exception.TApplicationException{} if err := ex.FromWire(envelope.Value); err != nil { return envelope.Value, envelope.SeqID, fmt.Errorf("failed to decode exception: %v", err) } return envelope.Value, envelope.SeqID, ex }
go
{ "resource": "" }
q17682
compileMapType
train
func compileMapType(src ast.MapType) (*MapSpec, error) { annots, err := compileAnnotations(src.Annotations) if err != nil { return nil, err } keySpec, err := compileTypeReference(src.KeyType) if err != nil { return nil, err } valueSpec, err := compileTypeReference(src.ValueType) if err != nil { return nil, err } return &MapSpec{ KeySpec: keySpec, ValueSpec: valueSpec, Annotations: annots, }, nil }
go
{ "resource": "" }
q17683
Link
train
func (m *MapSpec) Link(scope Scope) (TypeSpec, error) { if m.linked() { return m, nil } var err error m.KeySpec, err = m.KeySpec.Link(scope) if err != nil { return m, err } m.ValueSpec, err = m.ValueSpec.Link(scope) if err != nil { return m, err } return m, nil }
go
{ "resource": "" }
q17684
ThriftName
train
func (m *MapSpec) ThriftName() string { return fmt.Sprintf( "map<%s, %s>", m.KeySpec.ThriftName(), m.ValueSpec.ThriftName(), ) }
go
{ "resource": "" }
q17685
ForEachTypeReference
train
func (m *MapSpec) ForEachTypeReference(f func(TypeSpec) error) error { if err := f(m.KeySpec); err != nil { return err } return f(m.ValueSpec) }
go
{ "resource": "" }
q17686
compileListType
train
func compileListType(src ast.ListType) (*ListSpec, error) { annots, err := compileAnnotations(src.Annotations) if err != nil { return nil, err } valueSpec, err := compileTypeReference(src.ValueType) if err != nil { return nil, err } return &ListSpec{ ValueSpec: valueSpec, Annotations: annots, }, nil }
go
{ "resource": "" }
q17687
Link
train
func (l *ListSpec) Link(scope Scope) (TypeSpec, error) { if l.linked() { return l, nil } var err error l.ValueSpec, err = l.ValueSpec.Link(scope) return l, err }
go
{ "resource": "" }
q17688
ForEachTypeReference
train
func (l *ListSpec) ForEachTypeReference(f func(TypeSpec) error) error { return f(l.ValueSpec) }
go
{ "resource": "" }
q17689
compileSetType
train
func compileSetType(src ast.SetType) (*SetSpec, error) { annots, err := compileAnnotations(src.Annotations) if err != nil { return nil, err } valueSpec, err := compileTypeReference(src.ValueType) if err != nil { return nil, err } return &SetSpec{ ValueSpec: valueSpec, Annotations: annots, }, nil }
go
{ "resource": "" }
q17690
Link
train
func (s *SetSpec) Link(scope Scope) (TypeSpec, error) { if s.linked() { return s, nil } var err error s.ValueSpec, err = s.ValueSpec.Link(scope) return s, err }
go
{ "resource": "" }
q17691
ForEachTypeReference
train
func (s *SetSpec) ForEachTypeReference(f func(TypeSpec) error) error { return f(s.ValueSpec) }
go
{ "resource": "" }
q17692
compileStruct
train
func compileStruct(file string, src *ast.Struct, requiredness fieldRequiredness) (*StructSpec, error) { opts := fieldOptions{requiredness: requiredness} if src.Type == ast.UnionType { opts.requiredness = noRequiredFields opts.disallowDefaultValue = true } fields, err := compileFields(src.Fields, opts) if err != nil { return nil, compileError{ Target: src.Name, Line: src.Line, Reason: err, } } annotations, err := compileAnnotations(src.Annotations) if err != nil { return nil, compileError{ Target: src.Name, Line: src.Line, Reason: err, } } return &StructSpec{ Name: src.Name, File: file, Type: src.Type, Fields: fields, Doc: src.Doc, Annotations: annotations, }, nil }
go
{ "resource": "" }
q17693
Link
train
func (s *StructSpec) Link(scope Scope) (TypeSpec, error) { if s.linked() { return s, nil } err := s.Fields.Link(scope) return s, err }
go
{ "resource": "" }
q17694
ForEachTypeReference
train
func (s *StructSpec) ForEachTypeReference(f func(TypeSpec) error) error { return s.Fields.ForEachTypeReference(f) }
go
{ "resource": "" }
q17695
verifyAncestry
train
func verifyAncestry(m *compile.Module, root string) error { return m.Walk(func(m *compile.Module) error { path, err := filepath.Rel(root, m.ThriftPath) if err != nil { return fmt.Errorf( "could not resolve path for %q: %v", m.ThriftPath, err) } if strings.HasPrefix(path, "..") { return fmt.Errorf( "%q is not contained in the %q directory tree", m.ThriftPath, root) } return nil }) }
go
{ "resource": "" }
q17696
findCommonAncestor
train
func findCommonAncestor(m *compile.Module) (string, error) { var result []string var lastString string err := m.Walk(func(m *compile.Module) error { thriftPath := m.ThriftPath if !filepath.IsAbs(thriftPath) { return fmt.Errorf( "ThriftPath must be absolute: %q is not absolute", thriftPath) } thriftDir := filepath.Dir(thriftPath) // Split("/foo/bar", "/") = ["", "foo", "bar"] parts := strings.Split(thriftDir, string(filepath.Separator)) if result == nil { result = parts lastString = thriftPath return nil } result = commonPrefix(result, parts) if len(result) == 1 && result[0] == "" { return fmt.Errorf( "%q does not share an ancestor with %q", thriftPath, lastString) } lastString = thriftPath return nil }) if err != nil { return "", err } return strings.Join(result, string(filepath.Separator)), nil }
go
{ "resource": "" }
q17697
commonPrefix
train
func commonPrefix(l, r []string) []string { var i int for i = 0; i < len(l) && i < len(r); i++ { if l[i] != r[i] { break } } return l[:i] }
go
{ "resource": "" }
q17698
determinePackagePrefix
train
func determinePackagePrefix(dir string) (string, error) { gopathList := os.Getenv("GOPATH") if gopathList == "" { return "", errors.New("$GOPATH is not set") } for _, gopath := range filepath.SplitList(gopathList) { packagePath, err := filepath.Rel(filepath.Join(gopath, "src"), dir) if err != nil { return "", err } // The match is valid only if it's within the directory tree. if !strings.HasPrefix(packagePath, "..") { return packagePath, nil } } return "", fmt.Errorf("directory %q is not inside $GOPATH/src", dir) }
go
{ "resource": "" }
q17699
Parse
train
func Parse(v string) (r Version, err error) { parts := semVerRegex.FindStringSubmatch(v) if parts == nil { return r, fmt.Errorf(`cannot parse as semantic version: %q`, v) } if r.Major, err = parseUint(parts[1]); err != nil { return r, err } if r.Minor, err = parseUint(parts[2]); err != nil { return r, err } if r.Patch, err = parseUint(parts[3]); err != nil { return r, err } if parts[4] != "" { r.Pre = strings.Split(parts[4], ".") } r.Meta = parts[5] return r, nil }
go
{ "resource": "" }