repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L104-L106
go
train
// typeName returns the type of the given object.
func typeName(item mo.Reference) string
// typeName returns the type of the given object. func typeName(item mo.Reference) string
{ return reflect.TypeOf(item).Elem().Name() }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L109-L115
go
train
// valuePrefix returns the value name prefix of a given object
func valuePrefix(typeName string) string
// valuePrefix returns the value name prefix of a given object func valuePrefix(typeName string) string
{ if v, ok := refValueMap[typeName]; ok { return v } return strings.ToLower(typeName) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L119-L132
go
train
// newReference returns a new MOR, where Type defaults to type of the given item // and Value defaults to a unique id for the given type.
func (r *Registry) newReference(item mo.Reference) types.ManagedObjectReference
// newReference returns a new MOR, where Type defaults to type of the given item // and Value defaults to a unique id for the given type. func (r *Registry) newReference(item mo.Reference) types.ManagedObjectReference
{ ref := item.Reference() if ref.Type == "" { ref.Type = typeName(item) } if ref.Value == "" { n := atomic.AddInt64(&r.counter, 1) ref.Value = fmt.Sprintf("%s-%d", valuePrefix(ref.Type), n) } return ref }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L140-L144
go
train
// AddHandler adds a RegisterObject handler to the Registry.
func (r *Registry) AddHandler(h RegisterObject)
// AddHandler adds a RegisterObject handler to the Registry. func (r *Registry) AddHandler(h RegisterObject)
{ r.m.Lock() r.handlers[h.Reference()] = h r.m.Unlock() }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L148-L153
go
train
// NewEntity sets Entity().Self with a new, unique Value. // Useful for creating object instances from templates.
func (r *Registry) NewEntity(item mo.Entity) mo.Entity
// NewEntity sets Entity().Self with a new, unique Value. // Useful for creating object instances from templates. func (r *Registry) NewEntity(item mo.Entity) mo.Entity
{ e := item.Entity() e.Self.Value = "" e.Self = r.newReference(item) return item }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L156-L166
go
train
// PutEntity sets item.Parent to that of parent.Self before adding item to the Registry.
func (r *Registry) PutEntity(parent mo.Entity, item mo.Entity) mo.Entity
// PutEntity sets item.Parent to that of parent.Self before adding item to the Registry. func (r *Registry) PutEntity(parent mo.Entity, item mo.Entity) mo.Entity
{ e := item.Entity() if parent != nil { e.Parent = &parent.Entity().Self } r.Put(item) return item }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L169-L174
go
train
// Get returns the object for the given reference.
func (r *Registry) Get(ref types.ManagedObjectReference) mo.Reference
// Get returns the object for the given reference. func (r *Registry) Get(ref types.ManagedObjectReference) mo.Reference
{ r.m.Lock() defer r.m.Unlock() return r.objects[ref] }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L177-L188
go
train
// Any returns the first instance of entity type specified by kind.
func (r *Registry) Any(kind string) mo.Entity
// Any returns the first instance of entity type specified by kind. func (r *Registry) Any(kind string) mo.Entity
{ r.m.Lock() defer r.m.Unlock() for ref, val := range r.objects { if ref.Type == kind { return val.(mo.Entity) } } return nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L192-L206
go
train
// All returns all entities of type specified by kind. // If kind is empty - all entities will be returned.
func (r *Registry) All(kind string) []mo.Entity
// All returns all entities of type specified by kind. // If kind is empty - all entities will be returned. func (r *Registry) All(kind string) []mo.Entity
{ r.m.Lock() defer r.m.Unlock() var entities []mo.Entity for ref, val := range r.objects { if kind == "" || ref.Type == kind { if e, ok := val.(mo.Entity); ok { entities = append(entities, e) } } } return entities }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L209-L220
go
train
// applyHandlers calls the given func for each r.handlers
func (r *Registry) applyHandlers(f func(o RegisterObject))
// applyHandlers calls the given func for each r.handlers func (r *Registry) applyHandlers(f func(o RegisterObject))
{ r.m.Lock() handlers := make([]RegisterObject, 0, len(r.handlers)) for _, handler := range r.handlers { handlers = append(handlers, handler) } r.m.Unlock() for i := range handlers { f(handlers[i]) } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L223-L247
go
train
// Put adds a new object to Registry, generating a ManagedObjectReference if not already set.
func (r *Registry) Put(item mo.Reference) mo.Reference
// Put adds a new object to Registry, generating a ManagedObjectReference if not already set. func (r *Registry) Put(item mo.Reference) mo.Reference
{ r.m.Lock() ref := item.Reference() if ref.Type == "" || ref.Value == "" { ref = r.newReference(item) r.setReference(item, ref) } if me, ok := item.(mo.Entity); ok { me.Entity().ConfigStatus = types.ManagedEntityStatusGreen me.Entity().OverallStatus = types.ManagedEntityStatusGreen me.Entity().EffectiveRole = []int32{-1} // Admin } r.objects[ref] = item r.m.Unlock() r.applyHandlers(func(o RegisterObject) { o.PutObject(item) }) return item }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L250-L260
go
train
// Remove removes an object from the Registry.
func (r *Registry) Remove(item types.ManagedObjectReference)
// Remove removes an object from the Registry. func (r *Registry) Remove(item types.ManagedObjectReference)
{ r.applyHandlers(func(o RegisterObject) { o.RemoveObject(item) }) r.m.Lock() delete(r.objects, item) delete(r.handlers, item) delete(r.locks, item) r.m.Unlock() }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L266-L284
go
train
// Update dispatches object property changes to RegisterObject handlers, // such as any PropertyCollector instances with in-progress WaitForUpdates calls. // The changes are also applied to the given object via mo.ApplyPropertyChange, // so there is no need to set object fields directly.
func (r *Registry) Update(obj mo.Reference, changes []types.PropertyChange)
// Update dispatches object property changes to RegisterObject handlers, // such as any PropertyCollector instances with in-progress WaitForUpdates calls. // The changes are also applied to the given object via mo.ApplyPropertyChange, // so there is no need to set object fields directly. func (r *Registry) Update(obj mo.Reference, changes []types.PropertyChange)
{ for i := range changes { if changes[i].Op == "" { changes[i].Op = types.PropertyChangeOpAssign } if changes[i].Val != nil { rval := reflect.ValueOf(changes[i].Val) changes[i].Val = wrapValue(rval, rval.Type()) } } val := getManagedObject(obj).Addr().Interface().(mo.Reference) mo.ApplyPropertyChange(val, changes) r.applyHandlers(func(o RegisterObject) { o.UpdateObject(val, changes) }) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L289-L299
go
train
// getEntityParent traverses up the inventory and returns the first object of type kind. // If no object of type kind is found, the method will panic when it reaches the // inventory root Folder where the Parent field is nil.
func (r *Registry) getEntityParent(item mo.Entity, kind string) mo.Entity
// getEntityParent traverses up the inventory and returns the first object of type kind. // If no object of type kind is found, the method will panic when it reaches the // inventory root Folder where the Parent field is nil. func (r *Registry) getEntityParent(item mo.Entity, kind string) mo.Entity
{ for { parent := item.Entity().Parent item = r.Get(*parent).(mo.Entity) if item.Reference().Type == kind { return item } } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L302-L304
go
train
// getEntityDatacenter returns the Datacenter containing the given item
func (r *Registry) getEntityDatacenter(item mo.Entity) *Datacenter
// getEntityDatacenter returns the Datacenter containing the given item func (r *Registry) getEntityDatacenter(item mo.Entity) *Datacenter
{ return r.getEntityParent(item, "Datacenter").(*Datacenter) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L332-L345
go
train
// getEntityComputeResource returns the ComputeResource parent for the given item. // A ResourcePool for example may have N Parents of type ResourcePool, but the top // most Parent pool is always a ComputeResource child.
func (r *Registry) getEntityComputeResource(item mo.Entity) mo.Entity
// getEntityComputeResource returns the ComputeResource parent for the given item. // A ResourcePool for example may have N Parents of type ResourcePool, but the top // most Parent pool is always a ComputeResource child. func (r *Registry) getEntityComputeResource(item mo.Entity) mo.Entity
{ for { parent := item.Entity().Parent item = r.Get(*parent).(mo.Entity) switch item.Reference().Type { case "ComputeResource": return item case "ClusterComputeResource": return item } } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L351-L361
go
train
// FindByName returns the first mo.Entity of the given refs whose Name field is equal to the given name. // If there is no match, nil is returned. // This method is useful for cases where objects are required to have a unique name, such as Datastore with // a HostStorageSystem or HostSystem within a ClusterComputeResource.
func (r *Registry) FindByName(name string, refs []types.ManagedObjectReference) mo.Entity
// FindByName returns the first mo.Entity of the given refs whose Name field is equal to the given name. // If there is no match, nil is returned. // This method is useful for cases where objects are required to have a unique name, such as Datastore with // a HostStorageSystem or HostSystem within a ClusterComputeResource. func (r *Registry) FindByName(name string, refs []types.ManagedObjectReference) mo.Entity
{ for _, ref := range refs { if e, ok := r.Get(ref).(mo.Entity); ok { if name == e.Entity().Name { return e } } } return nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L364-L374
go
train
// FindReference returns the 1st match found in refs, or nil if not found.
func FindReference(refs []types.ManagedObjectReference, match ...types.ManagedObjectReference) *types.ManagedObjectReference
// FindReference returns the 1st match found in refs, or nil if not found. func FindReference(refs []types.ManagedObjectReference, match ...types.ManagedObjectReference) *types.ManagedObjectReference
{ for _, ref := range refs { for _, m := range match { if ref == m { return &ref } } } return nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L377-L381
go
train
// AppendReference appends the given refs to field.
func (r *Registry) AppendReference(obj mo.Reference, field *[]types.ManagedObjectReference, ref ...types.ManagedObjectReference)
// AppendReference appends the given refs to field. func (r *Registry) AppendReference(obj mo.Reference, field *[]types.ManagedObjectReference, ref ...types.ManagedObjectReference)
{ r.WithLock(obj, func() { *field = append(*field, ref...) }) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L384-L390
go
train
// AddReference appends ref to field if not already in the given field.
func (r *Registry) AddReference(obj mo.Reference, field *[]types.ManagedObjectReference, ref types.ManagedObjectReference)
// AddReference appends ref to field if not already in the given field. func (r *Registry) AddReference(obj mo.Reference, field *[]types.ManagedObjectReference, ref types.ManagedObjectReference)
{ r.WithLock(obj, func() { if FindReference(*field, ref) == nil { *field = append(*field, ref) } }) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L393-L400
go
train
// RemoveReference removes ref from the given field.
func RemoveReference(field *[]types.ManagedObjectReference, ref types.ManagedObjectReference)
// RemoveReference removes ref from the given field. func RemoveReference(field *[]types.ManagedObjectReference, ref types.ManagedObjectReference)
{ for i, r := range *field { if r == ref { *field = append((*field)[:i], (*field)[i+1:]...) break } } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L403-L407
go
train
// RemoveReference removes ref from the given field.
func (r *Registry) RemoveReference(obj mo.Reference, field *[]types.ManagedObjectReference, ref types.ManagedObjectReference)
// RemoveReference removes ref from the given field. func (r *Registry) RemoveReference(obj mo.Reference, field *[]types.ManagedObjectReference, ref types.ManagedObjectReference)
{ r.WithLock(obj, func() { RemoveReference(field, ref) }) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L435-L437
go
train
// SearchIndex returns the SearchIndex singleton
func (r *Registry) SearchIndex() *SearchIndex
// SearchIndex returns the SearchIndex singleton func (r *Registry) SearchIndex() *SearchIndex
{ return r.Get(r.content().SearchIndex.Reference()).(*SearchIndex) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L440-L442
go
train
// EventManager returns the EventManager singleton
func (r *Registry) EventManager() *EventManager
// EventManager returns the EventManager singleton func (r *Registry) EventManager() *EventManager
{ return r.Get(r.content().EventManager.Reference()).(*EventManager) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L445-L447
go
train
// FileManager returns the FileManager singleton
func (r *Registry) FileManager() *FileManager
// FileManager returns the FileManager singleton func (r *Registry) FileManager() *FileManager
{ return r.Get(r.content().FileManager.Reference()).(*FileManager) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L450-L452
go
train
// VirtualDiskManager returns the VirtualDiskManager singleton
func (r *Registry) VirtualDiskManager() *VirtualDiskManager
// VirtualDiskManager returns the VirtualDiskManager singleton func (r *Registry) VirtualDiskManager() *VirtualDiskManager
{ return r.Get(r.content().VirtualDiskManager.Reference()).(*VirtualDiskManager) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L455-L457
go
train
// ViewManager returns the ViewManager singleton
func (r *Registry) ViewManager() *ViewManager
// ViewManager returns the ViewManager singleton func (r *Registry) ViewManager() *ViewManager
{ return r.Get(r.content().ViewManager.Reference()).(*ViewManager) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L460-L462
go
train
// UserDirectory returns the UserDirectory singleton
func (r *Registry) UserDirectory() *UserDirectory
// UserDirectory returns the UserDirectory singleton func (r *Registry) UserDirectory() *UserDirectory
{ return r.Get(r.content().UserDirectory.Reference()).(*UserDirectory) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L465-L467
go
train
// SessionManager returns the SessionManager singleton
func (r *Registry) SessionManager() *SessionManager
// SessionManager returns the SessionManager singleton func (r *Registry) SessionManager() *SessionManager
{ return r.Get(r.content().SessionManager.Reference()).(*SessionManager) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L470-L472
go
train
// OptionManager returns the OptionManager singleton
func (r *Registry) OptionManager() *OptionManager
// OptionManager returns the OptionManager singleton func (r *Registry) OptionManager() *OptionManager
{ return r.Get(r.content().Setting.Reference()).(*OptionManager) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L475-L477
go
train
// CustomFieldsManager returns CustomFieldsManager singleton
func (r *Registry) CustomFieldsManager() *CustomFieldsManager
// CustomFieldsManager returns CustomFieldsManager singleton func (r *Registry) CustomFieldsManager() *CustomFieldsManager
{ return r.Get(r.content().CustomFieldsManager.Reference()).(*CustomFieldsManager) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/registry.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/registry.go#L526-L533
go
train
// WithLock holds a lock for the given object while then given function is run.
func (r *Registry) WithLock(obj mo.Reference, f func())
// WithLock holds a lock for the given object while then given function is run. func (r *Registry) WithLock(obj mo.Reference, f func())
{ if enableLocker { mu := r.locker(obj) mu.Lock() defer mu.Unlock() } f() }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/mo/type_info.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/mo/type_info.go#L164-L238
go
train
// assignValue assigns a value 'pv' to the struct pointed to by 'val', given a // slice of field indices. It recurses into the struct until it finds the field // specified by the indices. It creates new values for pointer types where // needed.
func assignValue(val reflect.Value, fi []int, pv reflect.Value)
// assignValue assigns a value 'pv' to the struct pointed to by 'val', given a // slice of field indices. It recurses into the struct until it finds the field // specified by the indices. It creates new values for pointer types where // needed. func assignValue(val reflect.Value, fi []int, pv reflect.Value)
{ // Create new value if necessary. if val.Kind() == reflect.Ptr { if val.IsNil() { val.Set(reflect.New(val.Type().Elem())) } val = val.Elem() } rv := val.Field(fi[0]) fi = fi[1:] if len(fi) == 0 { if pv == nilValue { pv = reflect.Zero(rv.Type()) rv.Set(pv) return } rt := rv.Type() pt := pv.Type() // If type is a pointer, create new instance of type. if rt.Kind() == reflect.Ptr { rv.Set(reflect.New(rt.Elem())) rv = rv.Elem() rt = rv.Type() } // If the target type is a slice, but the source is not, deference any ArrayOfXYZ type if rt.Kind() == reflect.Slice && pt.Kind() != reflect.Slice { if pt.Kind() == reflect.Ptr { pv = pv.Elem() pt = pt.Elem() } m := arrayOfRegexp.FindStringSubmatch(pt.Name()) if len(m) > 0 { pv = pv.FieldByName(m[1]) // ArrayOfXYZ type has single field named XYZ pt = pv.Type() if !pv.IsValid() { panic(fmt.Sprintf("expected %s type to have field %s", m[0], m[1])) } } } // If type is an interface, check if pv implements it. if rt.Kind() == reflect.Interface && !pt.Implements(rt) { // Check if pointer to pv implements it. if reflect.PtrTo(pt).Implements(rt) { npv := reflect.New(pt) npv.Elem().Set(pv) pv = npv pt = pv.Type() } else { panic(fmt.Sprintf("type %s doesn't implement %s", pt.Name(), rt.Name())) } } else if rt.Kind() == reflect.Struct && pt.Kind() == reflect.Ptr { pv = pv.Elem() pt = pv.Type() } if pt.AssignableTo(rt) { rv.Set(pv) } else if rt.ConvertibleTo(pt) { rv.Set(pv.Convert(rt)) } else { panic(fmt.Sprintf("cannot assign %q (%s) to %q (%s)", rt.Name(), rt.Kind(), pt.Name(), pt.Kind())) } return } assignValue(rv, fi, pv) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
vim25/mo/type_info.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/vim25/mo/type_info.go#L245-L258
go
train
// LoadObjectFromContent loads properties from the 'PropSet' field in the // specified ObjectContent value into the value it represents, which is // returned as a reflect.Value.
func (t *typeInfo) LoadFromObjectContent(o types.ObjectContent) (reflect.Value, error)
// LoadObjectFromContent loads properties from the 'PropSet' field in the // specified ObjectContent value into the value it represents, which is // returned as a reflect.Value. func (t *typeInfo) LoadFromObjectContent(o types.ObjectContent) (reflect.Value, error)
{ v := reflect.New(t.typ) assignValue(v, t.self, reflect.ValueOf(o.Obj)) for _, p := range o.PropSet { rv, ok := t.props[p.Name] if !ok { continue } assignValue(v, rv, reflect.ValueOf(p.Val)) } return v, nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/simulator.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L88-L98
go
train
// New returns an initialized simulator Service instance
func New(instance *ServiceInstance) *Service
// New returns an initialized simulator Service instance func New(instance *ServiceInstance) *Service
{ s := &Service{ readAll: ioutil.ReadAll, sm: Map.SessionManager(), sdk: make(map[string]*Registry), } s.client, _ = vim25.NewClient(context.Background(), s) return s }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/simulator.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L111-L120
go
train
// Fault wraps the given message and fault in a soap.Fault
func Fault(msg string, fault types.BaseMethodFault) *soap.Fault
// Fault wraps the given message and fault in a soap.Fault func Fault(msg string, fault types.BaseMethodFault) *soap.Fault
{ f := &soap.Fault{ Code: "ServerFaultCode", String: msg, } f.Detail.Fault = fault return f }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/simulator.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L212-L242
go
train
// RoundTrip implements the soap.RoundTripper interface in process. // Rather than encode/decode SOAP over HTTP, this implementation uses reflection.
func (s *Service) RoundTrip(ctx context.Context, request, response soap.HasFault) error
// RoundTrip implements the soap.RoundTripper interface in process. // Rather than encode/decode SOAP over HTTP, this implementation uses reflection. func (s *Service) RoundTrip(ctx context.Context, request, response soap.HasFault) error
{ field := func(r soap.HasFault, name string) reflect.Value { return reflect.ValueOf(r).Elem().FieldByName(name) } // Every struct passed to soap.RoundTrip has "Req" and "Res" fields req := field(request, "Req") // Every request has a "This" field. this := req.Elem().FieldByName("This") method := &Method{ Name: req.Elem().Type().Name(), This: this.Interface().(types.ManagedObjectReference), Body: req.Interface(), } res := s.call(&Context{ Map: Map, Context: ctx, Session: internalContext.Session, }, method) if err := res.Fault(); err != nil { return soap.WrapSoapFault(err) } field(response, "Res").Set(field(res, "Res")) return nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/simulator.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L271-L284
go
train
// MarshalXML renames the start element from "Fault" to "${Type}Fault"
func (d *faultDetail) MarshalXML(e *xml.Encoder, start xml.StartElement) error
// MarshalXML renames the start element from "Fault" to "${Type}Fault" func (d *faultDetail) MarshalXML(e *xml.Encoder, start xml.StartElement) error
{ kind := reflect.TypeOf(d.Fault).Elem().Name() start.Name.Local = kind + "Fault" start.Attr = append(start.Attr, xml.Attr{ Name: xml.Name{Local: "xmlns"}, Value: "urn:" + vim25.Namespace, }, xml.Attr{ Name: xml.Name{Local: "xsi:type"}, Value: kind, }) return e.EncodeElement(d.Fault, start) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/simulator.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L317-L363
go
train
// About generates some info about the simulator.
func (s *Service) About(w http.ResponseWriter, r *http.Request)
// About generates some info about the simulator. func (s *Service) About(w http.ResponseWriter, r *http.Request)
{ var about struct { Methods []string Types []string } seen := make(map[string]bool) f := reflect.TypeOf((*soap.HasFault)(nil)).Elem() for _, obj := range Map.objects { kind := obj.Reference().Type if seen[kind] { continue } seen[kind] = true about.Types = append(about.Types, kind) t := reflect.TypeOf(obj) for i := 0; i < t.NumMethod(); i++ { m := t.Method(i) if seen[m.Name] { continue } seen[m.Name] = true in := m.Type.NumIn() if in < 2 || in > 3 { // at least 2 params (receiver and request), optionally a 3rd param (context) continue } if m.Type.NumOut() != 1 || m.Type.Out(0) != f { // all methods return soap.HasFault continue } about.Methods = append(about.Methods, strings.Replace(m.Name, "Task", "_Task", 1)) } } sort.Strings(about.Methods) sort.Strings(about.Types) w.Header().Set("Content-Type", "application/json") enc := json.NewEncoder(w) enc.SetIndent("", " ") _ = enc.Encode(&about) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/simulator.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L366-L373
go
train
// Handle registers the handler for the given pattern with Service.ServeMux.
func (s *Service) Handle(pattern string, handler http.Handler)
// Handle registers the handler for the given pattern with Service.ServeMux. func (s *Service) Handle(pattern string, handler http.Handler)
{ s.ServeMux.Handle(pattern, handler) // Not ideal, but avoids having to add yet another registration mechanism // so we can optionally use vapi/simulator internally. if m, ok := handler.(tagManager); ok { s.sdk[vim25.Path].tagManager = m } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/simulator.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L376-L383
go
train
// RegisterSDK adds an HTTP handler for the Registry's Path and Namespace.
func (s *Service) RegisterSDK(r *Registry)
// RegisterSDK adds an HTTP handler for the Registry's Path and Namespace. func (s *Service) RegisterSDK(r *Registry)
{ if s.ServeMux == nil { s.ServeMux = http.NewServeMux() } s.sdk[r.Path] = r s.ServeMux.HandleFunc(r.Path, s.ServeSDK) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/simulator.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L386-L476
go
train
// ServeSDK implements the http.Handler interface
func (s *Service) ServeSDK(w http.ResponseWriter, r *http.Request)
// ServeSDK implements the http.Handler interface func (s *Service) ServeSDK(w http.ResponseWriter, r *http.Request)
{ if r.Method != http.MethodPost { w.WriteHeader(http.StatusMethodNotAllowed) return } body, err := s.readAll(r.Body) _ = r.Body.Close() if err != nil { log.Printf("error reading body: %s", err) w.WriteHeader(http.StatusBadRequest) return } if Trace { fmt.Fprintf(os.Stderr, "Request: %s\n", string(body)) } ctx := &Context{ req: r, res: w, svc: s, Map: s.sdk[r.URL.Path], Context: context.Background(), } ctx.Map.WithLock(s.sm, ctx.mapSession) var res soap.HasFault var soapBody interface{} method, err := UnmarshalBody(ctx.Map.typeFunc, body) if err != nil { res = serverFault(err.Error()) } else { ctx.Header = method.Header if method.Name == "Fetch" { // Redirect any Fetch method calls to the PropertyCollector singleton method.This = ctx.Map.content().PropertyCollector } res = s.call(ctx, method) } if f := res.Fault(); f != nil { w.WriteHeader(http.StatusInternalServerError) // the generated method/*Body structs use the '*soap.Fault' type, // so we need our own Body type to use the modified '*soapFault' type. soapBody = struct { Fault *soapFault }{ &soapFault{ Code: f.Code, String: f.String, Detail: struct { Fault *faultDetail }{&faultDetail{f.Detail.Fault}}, }, } } else { w.WriteHeader(http.StatusOK) soapBody = &response{ctx.Map.Namespace, res} } var out bytes.Buffer fmt.Fprint(&out, xml.Header) e := xml.NewEncoder(&out) err = e.Encode(&soapEnvelope{ Enc: "http://schemas.xmlsoap.org/soap/encoding/", Env: "http://schemas.xmlsoap.org/soap/envelope/", XSD: "http://www.w3.org/2001/XMLSchema", XSI: "http://www.w3.org/2001/XMLSchema-instance", Body: soapBody, }) if err == nil { err = e.Flush() } if err != nil { log.Printf("error encoding %s response: %s", method.Name, err) return } if Trace { fmt.Fprintf(os.Stderr, "Response: %s\n", out.String()) } _, _ = w.Write(out.Bytes()) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/simulator.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L500-L540
go
train
// ServeDatastore handler for Datastore access via /folder path.
func (s *Service) ServeDatastore(w http.ResponseWriter, r *http.Request)
// ServeDatastore handler for Datastore access via /folder path. func (s *Service) ServeDatastore(w http.ResponseWriter, r *http.Request)
{ ds, ferr := s.findDatastore(r.URL.Query()) if ferr != nil { log.Printf("failed to locate datastore with query params: %s", r.URL.RawQuery) w.WriteHeader(http.StatusNotFound) return } r.URL.Path = strings.TrimPrefix(r.URL.Path, folderPrefix) p := path.Join(ds.Info.GetDatastoreInfo().Url, r.URL.Path) switch r.Method { case http.MethodPost: _, err := os.Stat(p) if err == nil { // File exists w.WriteHeader(http.StatusConflict) return } // File does not exist, fallthrough to create via PUT logic fallthrough case http.MethodPut: dir := path.Dir(p) _ = os.MkdirAll(dir, 0700) f, err := os.Create(p) if err != nil { log.Printf("failed to %s '%s': %s", r.Method, p, err) w.WriteHeader(http.StatusInternalServerError) return } defer f.Close() _, _ = io.Copy(f, r.Body) default: fs := http.FileServer(http.Dir(ds.Info.GetDatastoreInfo().Url)) fs.ServeHTTP(w, r) } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/simulator.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L543-L558
go
train
// ServiceVersions handler for the /sdk/vimServiceVersions.xml path.
func (*Service) ServiceVersions(w http.ResponseWriter, r *http.Request)
// ServiceVersions handler for the /sdk/vimServiceVersions.xml path. func (*Service) ServiceVersions(w http.ResponseWriter, r *http.Request)
{ // pyvmomi depends on this const versions = xml.Header + `<namespaces version="1.0"> <namespace> <name>urn:vim25</name> <version>6.5</version> <priorVersions> <version>6.0</version> <version>5.5</version> </priorVersions> </namespace> </namespaces> ` fmt.Fprint(w, versions) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/simulator.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L561-L589
go
train
// defaultIP returns addr.IP if specified, otherwise attempts to find a non-loopback ipv4 IP
func defaultIP(addr *net.TCPAddr) string
// defaultIP returns addr.IP if specified, otherwise attempts to find a non-loopback ipv4 IP func defaultIP(addr *net.TCPAddr) string
{ if !addr.IP.IsUnspecified() { return addr.IP.String() } nics, err := net.Interfaces() if err != nil { return addr.IP.String() } for _, nic := range nics { if nic.Name == "docker0" || strings.HasPrefix(nic.Name, "vmnet") { continue } addrs, aerr := nic.Addrs() if aerr != nil { continue } for _, addr := range addrs { if ip, ok := addr.(*net.IPNet); ok && !ip.IP.IsLoopback() { if ip.IP.To4() != nil { return ip.IP.String() } } } } return addr.IP.String() }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/simulator.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L592-L645
go
train
// NewServer returns an http Server instance for the given service
func (s *Service) NewServer() *Server
// NewServer returns an http Server instance for the given service func (s *Service) NewServer() *Server
{ s.RegisterSDK(Map) mux := s.ServeMux vim := Map.Path + "/vimService" s.sdk[vim] = s.sdk[vim25.Path] mux.HandleFunc(vim, s.ServeSDK) mux.HandleFunc(Map.Path+"/vimServiceVersions.xml", s.ServiceVersions) mux.HandleFunc(folderPrefix, s.ServeDatastore) mux.HandleFunc(nfcPrefix, ServeNFC) mux.HandleFunc("/about", s.About) ts := internal.NewUnstartedServer(mux, s.Listen) addr := ts.Listener.Addr().(*net.TCPAddr) port := strconv.Itoa(addr.Port) u := &url.URL{ Scheme: "http", Host: net.JoinHostPort(defaultIP(addr), port), Path: Map.Path, } if s.TLS != nil { u.Scheme += "s" } // Redirect clients to this http server, rather than HostSystem.Name Map.SessionManager().ServiceHostName = u.Host // Add vcsim config to OptionManager for use by SDK handlers (see lookup/simulator for example) m := Map.OptionManager() m.Setting = append(m.Setting, &types.OptionValue{ Key: "vcsim.server.url", Value: u.String(), }, ) u.User = url.UserPassword("user", "pass") if s.TLS != nil { ts.TLS = s.TLS ts.TLS.ClientAuth = tls.RequestClientCert // Used by SessionManager.LoginExtensionByCertificate Map.SessionManager().TLSCert = func() string { return base64.StdEncoding.EncodeToString(ts.TLS.Certificates[0].Certificate[0]) } ts.StartTLS() } else { ts.Start() } return &Server{ Server: ts, URL: u, } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/simulator.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L649-L653
go
train
// Certificate returns the TLS certificate for the Server if started with TLS enabled. // This method will panic if TLS is not enabled for the server.
func (s *Server) Certificate() *x509.Certificate
// Certificate returns the TLS certificate for the Server if started with TLS enabled. // This method will panic if TLS is not enabled for the server. func (s *Server) Certificate() *x509.Certificate
{ // By default httptest.StartTLS uses http/internal.LocalhostCert, which we can access here: cert, _ := x509.ParseCertificate(s.TLS.Certificates[0].Certificate[0]) return cert }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/simulator.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L656-L660
go
train
// CertificateInfo returns Server.Certificate() as object.HostCertificateInfo
func (s *Server) CertificateInfo() *object.HostCertificateInfo
// CertificateInfo returns Server.Certificate() as object.HostCertificateInfo func (s *Server) CertificateInfo() *object.HostCertificateInfo
{ info := new(object.HostCertificateInfo) info.FromCertificate(s.Certificate()) return info }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/simulator.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L664-L678
go
train
// CertificateFile returns a file name, where the file contains the PEM encoded Server.Certificate. // The temporary file is removed when Server.Close() is called.
func (s *Server) CertificateFile() (string, error)
// CertificateFile returns a file name, where the file contains the PEM encoded Server.Certificate. // The temporary file is removed when Server.Close() is called. func (s *Server) CertificateFile() (string, error)
{ if s.caFile != "" { return s.caFile, nil } f, err := ioutil.TempFile("", "vcsim-") if err != nil { return "", err } defer f.Close() s.caFile = f.Name() cert := s.Certificate() return s.caFile, pem.Encode(f, &pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/simulator.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L681-L706
go
train
// proxy tunnels SDK requests
func (s *Server) proxy(w http.ResponseWriter, r *http.Request)
// proxy tunnels SDK requests func (s *Server) proxy(w http.ResponseWriter, r *http.Request)
{ if r.Method != http.MethodConnect { http.Error(w, "", http.StatusMethodNotAllowed) return } dst, err := net.Dial("tcp", s.URL.Host) if err != nil { http.Error(w, err.Error(), http.StatusBadGateway) return } w.WriteHeader(http.StatusOK) src, _, err := w.(http.Hijacker).Hijack() if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } go io.Copy(src, dst) go func() { _, _ = io.Copy(dst, src) _ = dst.Close() _ = src.Close() }() }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/simulator.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L709-L732
go
train
// StartTunnel runs an HTTP proxy for tunneling SDK requests that require TLS client certificate authentication.
func (s *Server) StartTunnel() error
// StartTunnel runs an HTTP proxy for tunneling SDK requests that require TLS client certificate authentication. func (s *Server) StartTunnel() error
{ tunnel := &http.Server{ Addr: fmt.Sprintf("%s:%d", s.URL.Hostname(), s.Tunnel), Handler: http.HandlerFunc(s.proxy), } l, err := net.Listen("tcp", tunnel.Addr) if err != nil { return err } if s.Tunnel == 0 { s.Tunnel = l.Addr().(*net.TCPAddr).Port } // Set client proxy port (defaults to vCenter host port 80 in real life) q := s.URL.Query() q.Set("GOVMOMI_TUNNEL_PROXY_PORT", strconv.Itoa(s.Tunnel)) s.URL.RawQuery = q.Encode() go tunnel.Serve(l) return nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/simulator.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L736-L741
go
train
// Close shuts down the server and blocks until all outstanding // requests on this server have completed.
func (s *Server) Close()
// Close shuts down the server and blocks until all outstanding // requests on this server have completed. func (s *Server) Close()
{ s.Server.Close() if s.caFile != "" { _ = os.Remove(s.caFile) } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/simulator.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/simulator.go#L786-L838
go
train
// UnmarshalBody extracts the Body from a soap.Envelope and unmarshals to the corresponding govmomi type
func UnmarshalBody(typeFunc func(string) (reflect.Type, bool), data []byte) (*Method, error)
// UnmarshalBody extracts the Body from a soap.Envelope and unmarshals to the corresponding govmomi type func UnmarshalBody(typeFunc func(string) (reflect.Type, bool), data []byte) (*Method, error)
{ body := &Element{typeFunc: typeFunc} req := soap.Envelope{ Header: &soap.Header{ Security: new(Element), }, Body: body, } err := xml.Unmarshal(data, &req) if err != nil { return nil, fmt.Errorf("xml.Unmarshal: %s", err) } var start xml.StartElement var ok bool decoder := body.decoder() for { tok, derr := decoder.Token() if derr != nil { return nil, fmt.Errorf("decoding: %s", derr) } if start, ok = tok.(xml.StartElement); ok { break } } if !ok { return nil, fmt.Errorf("decoding: method token not found") } kind := start.Name.Local rtype, ok := typeFunc(kind) if !ok { return nil, fmt.Errorf("no vmomi type defined for '%s'", kind) } val := reflect.New(rtype).Interface() err = decoder.DecodeElement(val, &start) if err != nil { return nil, fmt.Errorf("decoding %s: %s", kind, err) } method := &Method{Name: kind, Header: *req.Header, Body: val} field := reflect.ValueOf(val).Elem().FieldByName("This") method.This = field.Interface().(types.ManagedObjectReference) return method, nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
govc/host/autostart/info.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/govc/host/autostart/info.go#L86-L108
go
train
// vmPaths resolves the paths for the VMs in the result.
func (r *infoResult) vmPaths() (map[string]string, error)
// vmPaths resolves the paths for the VMs in the result. func (r *infoResult) vmPaths() (map[string]string, error)
{ ctx := context.TODO() paths := make(map[string]string) for _, info := range r.mhas.Config.PowerInfo { mes, err := mo.Ancestors(ctx, r.client, r.client.ServiceContent.PropertyCollector, info.Key) if err != nil { return nil, err } path := "" for _, me := range mes { // Skip root entity in building inventory path. if me.Parent == nil { continue } path += "/" + me.Name } paths[info.Key.Value] = path } return paths, nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/custom_fields_manager.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/custom_fields_manager.go#L41-L71
go
train
// Iterates through all entities of passed field type; // Removes found field from their custom field properties.
func entitiesFieldRemove(field types.CustomFieldDef)
// Iterates through all entities of passed field type; // Removes found field from their custom field properties. func entitiesFieldRemove(field types.CustomFieldDef)
{ entities := Map.All(field.ManagedObjectType) for _, e := range entities { entity := e.Entity() Map.WithLock(entity, func() { aFields := entity.AvailableField for i, aField := range aFields { if aField.Key == field.Key { entity.AvailableField = append(aFields[:i], aFields[i+1:]...) break } } values := e.Entity().Value for i, value := range values { if value.(*types.CustomFieldStringValue).Key == field.Key { entity.Value = append(values[:i], values[i+1:]...) break } } cValues := e.Entity().CustomValue for i, cValue := range cValues { if cValue.(*types.CustomFieldStringValue).Key == field.Key { entity.CustomValue = append(cValues[:i], cValues[i+1:]...) break } } }) } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
simulator/custom_fields_manager.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/simulator/custom_fields_manager.go#L75-L89
go
train
// Iterates through all entities of passed field type; // Renames found field in entity's AvailableField property.
func entitiesFieldRename(field types.CustomFieldDef)
// Iterates through all entities of passed field type; // Renames found field in entity's AvailableField property. func entitiesFieldRename(field types.CustomFieldDef)
{ entities := Map.All(field.ManagedObjectType) for _, e := range entities { entity := e.Entity() Map.WithLock(entity, func() { aFields := entity.AvailableField for i, aField := range aFields { if aField.Key == field.Key { aFields[i].Name = field.Name break } } }) } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/hgfs/archive.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/archive.go#L56-L69
go
train
// Stat implements FileHandler.Stat
func (*ArchiveHandler) Stat(u *url.URL) (os.FileInfo, error)
// Stat implements FileHandler.Stat func (*ArchiveHandler) Stat(u *url.URL) (os.FileInfo, error)
{ switch u.Query().Get("format") { case "", "tar", "tgz": // ok default: log.Printf("unknown archive format: %q", u) return nil, vix.Error(vix.InvalidArg) } return &archive{ name: u.Path, size: math.MaxInt64, }, nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/hgfs/archive.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/archive.go#L72-L81
go
train
// Open implements FileHandler.Open
func (h *ArchiveHandler) Open(u *url.URL, mode int32) (File, error)
// Open implements FileHandler.Open func (h *ArchiveHandler) Open(u *url.URL, mode int32) (File, error)
{ switch mode { case OpenModeReadOnly: return h.newArchiveFromGuest(u) case OpenModeWriteOnly: return h.newArchiveToGuest(u) default: return nil, os.ErrNotExist } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/hgfs/archive.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/archive.go#L131-L165
go
train
// newArchiveFromGuest returns an hgfs.File implementation to read a directory as a gzip'd tar.
func (h *ArchiveHandler) newArchiveFromGuest(u *url.URL) (File, error)
// newArchiveFromGuest returns an hgfs.File implementation to read a directory as a gzip'd tar. func (h *ArchiveHandler) newArchiveFromGuest(u *url.URL) (File, error)
{ r, w := io.Pipe() a := &archive{ name: u.Path, done: r.Close, Reader: r, Writer: w, } var z io.Writer = w var c io.Closer = ioutil.NopCloser(nil) switch u.Query().Get("format") { case "tgz": gz := gzip.NewWriter(w) z = gz c = gz } tw := tar.NewWriter(z) go func() { err := h.Write(u, tw) _ = tw.Close() _ = c.Close() if gzipTrailer { _, _ = w.Write(gzipHeader) } _ = w.CloseWithError(err) }() return a, nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/hgfs/archive.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/archive.go#L168-L225
go
train
// newArchiveToGuest returns an hgfs.File implementation to expand a gzip'd tar into a directory.
func (h *ArchiveHandler) newArchiveToGuest(u *url.URL) (File, error)
// newArchiveToGuest returns an hgfs.File implementation to expand a gzip'd tar into a directory. func (h *ArchiveHandler) newArchiveToGuest(u *url.URL) (File, error)
{ r, w := io.Pipe() buf := bufio.NewReader(r) a := &archive{ name: u.Path, Reader: buf, Writer: w, } var cerr error var wg sync.WaitGroup a.done = func() error { _ = w.Close() // We need to wait for unpack to finish to complete its work // and to propagate the error if any to Close. wg.Wait() return cerr } wg.Add(1) go func() { defer wg.Done() c := func() error { // Drain the pipe of tar trailer data (two null blocks) if cerr == nil { _, _ = io.Copy(ioutil.Discard, a.Reader) } return nil } header, _ := buf.Peek(len(gzipHeader)) if bytes.Equal(header, gzipHeader) { gz, err := gzip.NewReader(a.Reader) if err != nil { _ = r.CloseWithError(err) cerr = err return } c = gz.Close a.Reader = gz } tr := tar.NewReader(a.Reader) cerr = h.Read(u, tr) _ = c() _ = r.CloseWithError(cerr) }() return a, nil }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/hgfs/archive.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/archive.go#L232-L273
go
train
// archiveRead writes the contents of the given tar.Reader to the given directory.
func archiveRead(u *url.URL, tr *tar.Reader) error
// archiveRead writes the contents of the given tar.Reader to the given directory. func archiveRead(u *url.URL, tr *tar.Reader) error
{ for { header, err := tr.Next() if err != nil { if err == io.EOF { return nil } return err } name := filepath.Join(u.Path, header.Name) mode := os.FileMode(header.Mode) switch header.Typeflag { case tar.TypeDir: err = os.MkdirAll(name, mode) case tar.TypeReg: _ = os.MkdirAll(filepath.Dir(name), 0750) var f *os.File f, err = os.OpenFile(name, os.O_CREATE|os.O_RDWR|os.O_TRUNC, mode) if err == nil { _, cerr := io.Copy(f, tr) err = f.Close() if cerr != nil { err = cerr } } case tar.TypeSymlink: err = os.Symlink(header.Linkname, name) } // TODO: Uid/Gid may not be meaningful here without some mapping. // The other option to consider would be making use of the guest auth user ID. // os.Lchown(name, header.Uid, header.Gid) if err != nil { return err } } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
toolbox/hgfs/archive.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/toolbox/hgfs/archive.go#L276-L342
go
train
// archiveWrite writes the contents of the given source directory to the given tar.Writer.
func archiveWrite(u *url.URL, tw *tar.Writer) error
// archiveWrite writes the contents of the given source directory to the given tar.Writer. func archiveWrite(u *url.URL, tw *tar.Writer) error
{ info, err := os.Stat(u.Path) if err != nil { return err } // Note that the VMX will trim any trailing slash. For example: // "/foo/bar/?prefix=bar/" will end up here as "/foo/bar/?prefix=bar" // Escape to avoid this: "/for/bar/?prefix=bar%2F" prefix := u.Query().Get("prefix") dir := u.Path f := func(file string, fi os.FileInfo, err error) error { if err != nil { return filepath.SkipDir } name := strings.TrimPrefix(file, dir) name = strings.TrimPrefix(name, "/") if name == "" { return nil // this is u.Path itself (which may or may not have a trailing "/") } if prefix != "" { name = prefix + name } header, _ := tar.FileInfoHeader(fi, name) header.Name = name if header.Typeflag == tar.TypeDir { header.Name += "/" } var f *os.File if header.Typeflag == tar.TypeReg && fi.Size() != 0 { f, err = os.Open(filepath.Clean(file)) if err != nil { if os.IsPermission(err) { return nil } return err } } _ = tw.WriteHeader(header) if f != nil { _, err = io.Copy(tw, f) _ = f.Close() } return err } if info.IsDir() { return filepath.Walk(u.Path, f) } dir = filepath.Dir(dir) return f(u.Path, info, nil) }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
property/filter.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/property/filter.go#L33-L41
go
train
// Keys returns the Filter map keys as a []string
func (f Filter) Keys() []string
// Keys returns the Filter map keys as a []string func (f Filter) Keys() []string
{ keys := make([]string, 0, len(f)) for key := range f { keys = append(keys, key) } return keys }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
property/filter.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/property/filter.go#L44-L115
go
train
// MatchProperty returns true if a Filter entry matches the given prop.
func (f Filter) MatchProperty(prop types.DynamicProperty) bool
// MatchProperty returns true if a Filter entry matches the given prop. func (f Filter) MatchProperty(prop types.DynamicProperty) bool
{ match, ok := f[prop.Name] if !ok { return false } if match == prop.Val { return true } ptype := reflect.TypeOf(prop.Val) if strings.HasPrefix(ptype.Name(), "ArrayOf") { pval := reflect.ValueOf(prop.Val).Field(0) for i := 0; i < pval.Len(); i++ { prop.Val = pval.Index(i).Interface() if f.MatchProperty(prop) { return true } } return false } if reflect.TypeOf(match) != ptype { s, ok := match.(string) if !ok { return false } // convert if we can switch prop.Val.(type) { case bool: match, _ = strconv.ParseBool(s) case int16: x, _ := strconv.ParseInt(s, 10, 16) match = int16(x) case int32: x, _ := strconv.ParseInt(s, 10, 32) match = int32(x) case int64: match, _ = strconv.ParseInt(s, 10, 64) case float32: x, _ := strconv.ParseFloat(s, 32) match = float32(x) case float64: match, _ = strconv.ParseFloat(s, 64) case fmt.Stringer: prop.Val = prop.Val.(fmt.Stringer).String() default: if ptype.Kind() != reflect.String { return false } // An enum type we can convert to a string type prop.Val = reflect.ValueOf(prop.Val).String() } } switch pval := prop.Val.(type) { case string: s := match.(string) if s == "*" { return true // TODO: path.Match fails if s contains a '/' } m, _ := path.Match(s, pval) return m default: return reflect.DeepEqual(match, pval) } }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
property/filter.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/property/filter.go#L118-L126
go
train
// MatchPropertyList returns true if all given props match the Filter.
func (f Filter) MatchPropertyList(props []types.DynamicProperty) bool
// MatchPropertyList returns true if all given props match the Filter. func (f Filter) MatchPropertyList(props []types.DynamicProperty) bool
{ for _, p := range props { if !f.MatchProperty(p) { return false } } return len(f) == len(props) // false if a property such as VM "guest" is unset }
vmware/govmomi
fc3f0e9d2275df0e497a80917807a7c72d3c35bc
property/filter.go
https://github.com/vmware/govmomi/blob/fc3f0e9d2275df0e497a80917807a7c72d3c35bc/property/filter.go#L129-L139
go
train
// MatchObjectContent returns a list of ObjectContent.Obj where the ObjectContent.PropSet matches the Filter.
func (f Filter) MatchObjectContent(objects []types.ObjectContent) []types.ManagedObjectReference
// MatchObjectContent returns a list of ObjectContent.Obj where the ObjectContent.PropSet matches the Filter. func (f Filter) MatchObjectContent(objects []types.ObjectContent) []types.ManagedObjectReference
{ var refs []types.ManagedObjectReference for _, o := range objects { if f.MatchPropertyList(o.PropSet) { refs = append(refs, o.Obj) } } return refs }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L79-L81
go
train
// Lint lints src.
func (l *Linter) Lint(filename string, src []byte) ([]Problem, error)
// Lint lints src. func (l *Linter) Lint(filename string, src []byte) ([]Problem, error)
{ return l.LintFiles(map[string][]byte{filename: src}) }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L85-L116
go
train
// LintFiles lints a set of files of a single package. // The argument is a map of filename to source.
func (l *Linter) LintFiles(files map[string][]byte) ([]Problem, error)
// LintFiles lints a set of files of a single package. // The argument is a map of filename to source. func (l *Linter) LintFiles(files map[string][]byte) ([]Problem, error)
{ pkg := &pkg{ fset: token.NewFileSet(), files: make(map[string]*file), } var pkgName string for filename, src := range files { if isGenerated(src) { continue // See issue #239 } f, err := parser.ParseFile(pkg.fset, filename, src, parser.ParseComments) if err != nil { return nil, err } if pkgName == "" { pkgName = f.Name.Name } else if f.Name.Name != pkgName { return nil, fmt.Errorf("%s is in package %s, not %s", filename, f.Name.Name, pkgName) } pkg.files[filename] = &file{ pkg: pkg, f: f, fset: pkg.fset, src: src, filename: filename, } } if len(pkg.files) == 0 { return nil, nil } return pkg.lint(), nil }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L125-L134
go
train
// isGenerated reports whether the source file is generated code // according the rules from https://golang.org/s/generatedcode.
func isGenerated(src []byte) bool
// isGenerated reports whether the source file is generated code // according the rules from https://golang.org/s/generatedcode. func isGenerated(src []byte) bool
{ sc := bufio.NewScanner(bytes.NewReader(src)) for sc.Scan() { b := sc.Bytes() if bytes.HasPrefix(b, genHdr) && bytes.HasSuffix(b, genFtr) && len(b) >= len(genHdr)+len(genFtr) { return true } } return false }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L222-L228
go
train
// The variadic arguments may start with link and category types, // and must end with a format string and any arguments. // It returns the new Problem.
func (f *file) errorf(n ast.Node, confidence float64, args ...interface{}) *Problem
// The variadic arguments may start with link and category types, // and must end with a format string and any arguments. // It returns the new Problem. func (f *file) errorf(n ast.Node, confidence float64, args ...interface{}) *Problem
{ pos := f.fset.Position(n.Pos()) if pos.Filename == "" { pos.Filename = f.filename } return f.pkg.errorfAt(pos, confidence, args...) }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L308-L325
go
train
// scopeOf returns the tightest scope encompassing id.
func (p *pkg) scopeOf(id *ast.Ident) *types.Scope
// scopeOf returns the tightest scope encompassing id. func (p *pkg) scopeOf(id *ast.Ident) *types.Scope
{ var scope *types.Scope if obj := p.typesInfo.ObjectOf(id); obj != nil { scope = obj.Parent() } if scope == p.typesPkg.Scope() { // We were given a top-level identifier. // Use the file-level scope instead of the package-level scope. pos := id.Pos() for _, f := range p.files { if f.f.Pos() <= pos && pos < f.f.End() { scope = p.typesInfo.Scopes[f.f] break } } } return scope }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L380-L429
go
train
// lintPackageComment checks package comments. It complains if // there is no package comment, or if it is not of the right form. // This has a notable false positive in that a package comment // could rightfully appear in a different file of the same package, // but that's not easy to fix since this linter is file-oriented.
func (f *file) lintPackageComment()
// lintPackageComment checks package comments. It complains if // there is no package comment, or if it is not of the right form. // This has a notable false positive in that a package comment // could rightfully appear in a different file of the same package, // but that's not easy to fix since this linter is file-oriented. func (f *file) lintPackageComment()
{ if f.isTest() { return } const ref = styleGuideBase + "#package-comments" prefix := "Package " + f.f.Name.Name + " " // Look for a detached package comment. // First, scan for the last comment that occurs before the "package" keyword. var lastCG *ast.CommentGroup for _, cg := range f.f.Comments { if cg.Pos() > f.f.Package { // Gone past "package" keyword. break } lastCG = cg } if lastCG != nil && strings.HasPrefix(lastCG.Text(), prefix) { endPos := f.fset.Position(lastCG.End()) pkgPos := f.fset.Position(f.f.Package) if endPos.Line+1 < pkgPos.Line { // There isn't a great place to anchor this error; // the start of the blank lines between the doc and the package statement // is at least pointing at the location of the problem. pos := token.Position{ Filename: endPos.Filename, // Offset not set; it is non-trivial, and doesn't appear to be needed. Line: endPos.Line + 1, Column: 1, } f.pkg.errorfAt(pos, 0.9, link(ref), category("comments"), "package comment is detached; there should be no blank lines between it and the package statement") return } } if f.f.Doc == nil { f.errorf(f.f, 0.2, link(ref), category("comments"), "should have a package comment, unless it's in another file for this package") return } s := f.f.Doc.Text() if ts := strings.TrimLeft(s, " \t"); ts != s { f.errorf(f.f.Doc, 1, link(ref), category("comments"), "package comment should not have leading space") s = ts } // Only non-main packages need to keep to this form. if !f.pkg.main && !strings.HasPrefix(s, prefix) { f.errorf(f.f.Doc, 1, link(ref), category("comments"), `package comment should be of the form "%s..."`, prefix) } }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L433-L461
go
train
// lintBlankImports complains if a non-main package has blank imports that are // not documented.
func (f *file) lintBlankImports()
// lintBlankImports complains if a non-main package has blank imports that are // not documented. func (f *file) lintBlankImports()
{ // In package main and in tests, we don't complain about blank imports. if f.pkg.main || f.isTest() { return } // The first element of each contiguous group of blank imports should have // an explanatory comment of some kind. for i, imp := range f.f.Imports { pos := f.fset.Position(imp.Pos()) if !isBlank(imp.Name) { continue // Ignore non-blank imports. } if i > 0 { prev := f.f.Imports[i-1] prevPos := f.fset.Position(prev.Pos()) if isBlank(prev.Name) && prevPos.Line+1 == pos.Line { continue // A subsequent blank in a group. } } // This is the first blank import of a group. if imp.Doc == nil && imp.Comment == nil { ref := "" f.errorf(imp, 1, link(ref), category("imports"), "a blank import should be only in a main or test package, or have a comment justifying it") } } }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L464-L472
go
train
// lintImports examines import blocks.
func (f *file) lintImports()
// lintImports examines import blocks. func (f *file) lintImports()
{ for i, is := range f.f.Imports { _ = i if is.Name != nil && is.Name.Name == "." && !f.isTest() { f.errorf(is, 1, link(styleGuideBase+"#import-dot"), category("imports"), "should not use dot imports") } } }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L484-L528
go
train
// lintExported examines the exported names. // It complains if any required doc comments are missing, // or if they are not of the right form. The exact rules are in // lintFuncDoc, lintTypeDoc and lintValueSpecDoc; this function // also tracks the GenDecl structure being traversed to permit // doc comments for constants to be on top of the const block. // It also complains if the names stutter when combined with // the package name.
func (f *file) lintExported()
// lintExported examines the exported names. // It complains if any required doc comments are missing, // or if they are not of the right form. The exact rules are in // lintFuncDoc, lintTypeDoc and lintValueSpecDoc; this function // also tracks the GenDecl structure being traversed to permit // doc comments for constants to be on top of the const block. // It also complains if the names stutter when combined with // the package name. func (f *file) lintExported()
{ if f.isTest() { return } var lastGen *ast.GenDecl // last GenDecl entered. // Set of GenDecls that have already had missing comments flagged. genDeclMissingComments := make(map[*ast.GenDecl]bool) f.walk(func(node ast.Node) bool { switch v := node.(type) { case *ast.GenDecl: if v.Tok == token.IMPORT { return false } // token.CONST, token.TYPE or token.VAR lastGen = v return true case *ast.FuncDecl: f.lintFuncDoc(v) if v.Recv == nil { // Only check for stutter on functions, not methods. // Method names are not used package-qualified. f.checkStutter(v.Name, "func") } // Don't proceed inside funcs. return false case *ast.TypeSpec: // inside a GenDecl, which usually has the doc doc := v.Doc if doc == nil { doc = lastGen.Doc } f.lintTypeDoc(v, doc) f.checkStutter(v.Name, "type") // Don't proceed inside types. return false case *ast.ValueSpec: f.lintValueSpecDoc(v, lastGen, genDeclMissingComments) return false } return true }) }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L557-L698
go
train
// lintNames examines all names in the file. // It complains if any use underscores or incorrect known initialisms.
func (f *file) lintNames()
// lintNames examines all names in the file. // It complains if any use underscores or incorrect known initialisms. func (f *file) lintNames()
{ // Package names need slightly different handling than other names. if strings.Contains(f.f.Name.Name, "_") && !strings.HasSuffix(f.f.Name.Name, "_test") { f.errorf(f.f, 1, link("http://golang.org/doc/effective_go.html#package-names"), category("naming"), "don't use an underscore in package name") } if anyCapsRE.MatchString(f.f.Name.Name) { f.errorf(f.f, 1, link("http://golang.org/doc/effective_go.html#package-names"), category("mixed-caps"), "don't use MixedCaps in package name; %s should be %s", f.f.Name.Name, strings.ToLower(f.f.Name.Name)) } check := func(id *ast.Ident, thing string) { if id.Name == "_" { return } if knownNameExceptions[id.Name] { return } // Handle two common styles from other languages that don't belong in Go. if len(id.Name) >= 5 && allCapsRE.MatchString(id.Name) && strings.Contains(id.Name, "_") { capCount := 0 for _, c := range id.Name { if 'A' <= c && c <= 'Z' { capCount++ } } if capCount >= 2 { f.errorf(id, 0.8, link(styleGuideBase+"#mixed-caps"), category("naming"), "don't use ALL_CAPS in Go names; use CamelCase") return } } if thing == "const" || (thing == "var" && isInTopLevel(f.f, id)) { if len(id.Name) > 2 && id.Name[0] == 'k' && id.Name[1] >= 'A' && id.Name[1] <= 'Z' { should := string(id.Name[1]+'a'-'A') + id.Name[2:] f.errorf(id, 0.8, link(styleGuideBase+"#mixed-caps"), category("naming"), "don't use leading k in Go names; %s %s should be %s", thing, id.Name, should) } } should := lintName(id.Name) if id.Name == should { return } if len(id.Name) > 2 && strings.Contains(id.Name[1:], "_") { f.errorf(id, 0.9, link("http://golang.org/doc/effective_go.html#mixed-caps"), category("naming"), "don't use underscores in Go names; %s %s should be %s", thing, id.Name, should) return } f.errorf(id, 0.8, link(styleGuideBase+"#initialisms"), category("naming"), "%s %s should be %s", thing, id.Name, should) } checkList := func(fl *ast.FieldList, thing string) { if fl == nil { return } for _, f := range fl.List { for _, id := range f.Names { check(id, thing) } } } f.walk(func(node ast.Node) bool { switch v := node.(type) { case *ast.AssignStmt: if v.Tok == token.ASSIGN { return true } for _, exp := range v.Lhs { if id, ok := exp.(*ast.Ident); ok { check(id, "var") } } case *ast.FuncDecl: if f.isTest() && (strings.HasPrefix(v.Name.Name, "Example") || strings.HasPrefix(v.Name.Name, "Test") || strings.HasPrefix(v.Name.Name, "Benchmark")) { return true } thing := "func" if v.Recv != nil { thing = "method" } // Exclude naming warnings for functions that are exported to C but // not exported in the Go API. // See https://github.com/golang/lint/issues/144. if ast.IsExported(v.Name.Name) || !isCgoExported(v) { check(v.Name, thing) } checkList(v.Type.Params, thing+" parameter") checkList(v.Type.Results, thing+" result") case *ast.GenDecl: if v.Tok == token.IMPORT { return true } var thing string switch v.Tok { case token.CONST: thing = "const" case token.TYPE: thing = "type" case token.VAR: thing = "var" } for _, spec := range v.Specs { switch s := spec.(type) { case *ast.TypeSpec: check(s.Name, thing) case *ast.ValueSpec: for _, id := range s.Names { check(id, thing) } } } case *ast.InterfaceType: // Do not check interface method names. // They are often constrainted by the method names of concrete types. for _, x := range v.Methods.List { ft, ok := x.Type.(*ast.FuncType) if !ok { // might be an embedded interface name continue } checkList(ft.Params, "interface method parameter") checkList(ft.Results, "interface method result") } case *ast.RangeStmt: if v.Tok == token.ASSIGN { return true } if id, ok := v.Key.(*ast.Ident); ok { check(id, "range var") } if id, ok := v.Value.(*ast.Ident); ok { check(id, "range var") } case *ast.StructType: for _, f := range v.Fields.List { for _, id := range f.Names { check(id, "struct field") } } } return true }) }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L815-L835
go
train
// lintTypeDoc examines the doc comment on a type. // It complains if they are missing from an exported type, // or if they are not of the standard form.
func (f *file) lintTypeDoc(t *ast.TypeSpec, doc *ast.CommentGroup)
// lintTypeDoc examines the doc comment on a type. // It complains if they are missing from an exported type, // or if they are not of the standard form. func (f *file) lintTypeDoc(t *ast.TypeSpec, doc *ast.CommentGroup)
{ if !ast.IsExported(t.Name.Name) { return } if doc == nil { f.errorf(t, 1, link(docCommentsLink), category("comments"), "exported type %v should have comment or be unexported", t.Name) return } s := doc.Text() articles := [...]string{"A", "An", "The"} for _, a := range articles { if strings.HasPrefix(s, a+" ") { s = s[len(a)+1:] break } } if !strings.HasPrefix(s, t.Name.Name+" ") { f.errorf(doc, 1, link(docCommentsLink), category("comments"), `comment on exported type %v should be of the form "%v ..." (with optional leading article)`, t.Name, t.Name) } }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L848-L883
go
train
// lintFuncDoc examines doc comments on functions and methods. // It complains if they are missing, or not of the right form. // It has specific exclusions for well-known methods (see commonMethods above).
func (f *file) lintFuncDoc(fn *ast.FuncDecl)
// lintFuncDoc examines doc comments on functions and methods. // It complains if they are missing, or not of the right form. // It has specific exclusions for well-known methods (see commonMethods above). func (f *file) lintFuncDoc(fn *ast.FuncDecl)
{ if !ast.IsExported(fn.Name.Name) { // func is unexported return } kind := "function" name := fn.Name.Name if fn.Recv != nil && len(fn.Recv.List) > 0 { // method kind = "method" recv := receiverType(fn) if !ast.IsExported(recv) { // receiver is unexported return } if commonMethods[name] { return } switch name { case "Len", "Less", "Swap": if f.pkg.sortable[recv] { return } } name = recv + "." + name } if fn.Doc == nil { f.errorf(fn, 1, link(docCommentsLink), category("comments"), "exported %s %s should have comment or be unexported", kind, name) return } s := fn.Doc.Text() prefix := fn.Name.Name + " " if !strings.HasPrefix(s, prefix) { f.errorf(fn.Doc, 1, link(docCommentsLink), category("comments"), `comment on exported %s %s should be of the form "%s..."`, kind, name, prefix) } }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L888-L936
go
train
// lintValueSpecDoc examines package-global variables and constants. // It complains if they are not individually declared, // or if they are not suitably documented in the right form (unless they are in a block that is commented).
func (f *file) lintValueSpecDoc(vs *ast.ValueSpec, gd *ast.GenDecl, genDeclMissingComments map[*ast.GenDecl]bool)
// lintValueSpecDoc examines package-global variables and constants. // It complains if they are not individually declared, // or if they are not suitably documented in the right form (unless they are in a block that is commented). func (f *file) lintValueSpecDoc(vs *ast.ValueSpec, gd *ast.GenDecl, genDeclMissingComments map[*ast.GenDecl]bool)
{ kind := "var" if gd.Tok == token.CONST { kind = "const" } if len(vs.Names) > 1 { // Check that none are exported except for the first. for _, n := range vs.Names[1:] { if ast.IsExported(n.Name) { f.errorf(vs, 1, category("comments"), "exported %s %s should have its own declaration", kind, n.Name) return } } } // Only one name. name := vs.Names[0].Name if !ast.IsExported(name) { return } if vs.Doc == nil && gd.Doc == nil { if genDeclMissingComments[gd] { return } block := "" if kind == "const" && gd.Lparen.IsValid() { block = " (or a comment on this block)" } f.errorf(vs, 1, link(docCommentsLink), category("comments"), "exported %s %s should have comment%s or be unexported", kind, name, block) genDeclMissingComments[gd] = true return } // If this GenDecl has parens and a comment, we don't check its comment form. if gd.Lparen.IsValid() && gd.Doc != nil { return } // The relevant text to check will be on either vs.Doc or gd.Doc. // Use vs.Doc preferentially. doc := vs.Doc if doc == nil { doc = gd.Doc } prefix := name + " " if !strings.HasPrefix(doc.Text(), prefix) { f.errorf(doc, 1, link(docCommentsLink), category("comments"), `comment on exported %s %s should be of the form "%s..."`, kind, name, prefix) } }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L982-L1050
go
train
// lintVarDecls examines variable declarations. It complains about declarations with // redundant LHS types that can be inferred from the RHS.
func (f *file) lintVarDecls()
// lintVarDecls examines variable declarations. It complains about declarations with // redundant LHS types that can be inferred from the RHS. func (f *file) lintVarDecls()
{ var lastGen *ast.GenDecl // last GenDecl entered. f.walk(func(node ast.Node) bool { switch v := node.(type) { case *ast.GenDecl: if v.Tok != token.CONST && v.Tok != token.VAR { return false } lastGen = v return true case *ast.ValueSpec: if lastGen.Tok == token.CONST { return false } if len(v.Names) > 1 || v.Type == nil || len(v.Values) == 0 { return false } rhs := v.Values[0] // An underscore var appears in a common idiom for compile-time interface satisfaction, // as in "var _ Interface = (*Concrete)(nil)". if isIdent(v.Names[0], "_") { return false } // If the RHS is a zero value, suggest dropping it. zero := false if lit, ok := rhs.(*ast.BasicLit); ok { zero = zeroLiteral[lit.Value] } else if isIdent(rhs, "nil") { zero = true } if zero { f.errorf(rhs, 0.9, category("zero-value"), "should drop = %s from declaration of var %s; it is the zero value", f.render(rhs), v.Names[0]) return false } lhsTyp := f.pkg.typeOf(v.Type) rhsTyp := f.pkg.typeOf(rhs) if !validType(lhsTyp) || !validType(rhsTyp) { // Type checking failed (often due to missing imports). return false } if !types.Identical(lhsTyp, rhsTyp) { // Assignment to a different type is not redundant. return false } // The next three conditions are for suppressing the warning in situations // where we were unable to typecheck. // If the LHS type is an interface, don't warn, since it is probably a // concrete type on the RHS. Note that our feeble lexical check here // will only pick up interface{} and other literal interface types; // that covers most of the cases we care to exclude right now. if _, ok := v.Type.(*ast.InterfaceType); ok { return false } // If the RHS is an untyped const, only warn if the LHS type is its default type. if defType, ok := f.isUntypedConst(rhs); ok && !isIdent(v.Type, defType) { return false } f.errorf(v.Type, 0.8, category("type-inference"), "should omit type %s from declaration of var %s; it will be inferred from the right-hand side", f.render(v.Type), v.Names[0]) return false } return true }) }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1059-L1100
go
train
// lintElses examines else blocks. It complains about any else block whose if block ends in a return.
func (f *file) lintElses()
// lintElses examines else blocks. It complains about any else block whose if block ends in a return. func (f *file) lintElses()
{ // We don't want to flag if { } else if { } else { } constructions. // They will appear as an IfStmt whose Else field is also an IfStmt. // Record such a node so we ignore it when we visit it. ignore := make(map[*ast.IfStmt]bool) f.walk(func(node ast.Node) bool { ifStmt, ok := node.(*ast.IfStmt) if !ok || ifStmt.Else == nil { return true } if elseif, ok := ifStmt.Else.(*ast.IfStmt); ok { ignore[elseif] = true return true } if ignore[ifStmt] { return true } if _, ok := ifStmt.Else.(*ast.BlockStmt); !ok { // only care about elses without conditions return true } if len(ifStmt.Body.List) == 0 { return true } shortDecl := false // does the if statement have a ":=" initialization statement? if ifStmt.Init != nil { if as, ok := ifStmt.Init.(*ast.AssignStmt); ok && as.Tok == token.DEFINE { shortDecl = true } } lastStmt := ifStmt.Body.List[len(ifStmt.Body.List)-1] if _, ok := lastStmt.(*ast.ReturnStmt); ok { extra := "" if shortDecl { extra = " (move short variable declaration to its own line if necessary)" } f.errorf(ifStmt.Else, 1, link(styleGuideBase+"#indent-error-flow"), category("indent"), "if block ends with a return statement, so drop this else and outdent its block"+extra) } return true }) }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1103-L1131
go
train
// lintRanges examines range clauses. It complains about redundant constructions.
func (f *file) lintRanges()
// lintRanges examines range clauses. It complains about redundant constructions. func (f *file) lintRanges()
{ f.walk(func(node ast.Node) bool { rs, ok := node.(*ast.RangeStmt) if !ok { return true } if isIdent(rs.Key, "_") && (rs.Value == nil || isIdent(rs.Value, "_")) { p := f.errorf(rs.Key, 1, category("range-loop"), "should omit values from range; this loop is equivalent to `for range ...`") newRS := *rs // shallow copy newRS.Value = nil newRS.Key = nil p.ReplacementLine = f.firstLineOf(&newRS, rs) return true } if isIdent(rs.Value, "_") { p := f.errorf(rs.Value, 1, category("range-loop"), "should omit 2nd value from range; this loop is equivalent to `for %s %s range ...`", f.render(rs.Key), rs.Tok) newRS := *rs // shallow copy newRS.Value = nil p.ReplacementLine = f.firstLineOf(&newRS, rs) } return true }) }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1134-L1172
go
train
// lintErrorf examines errors.New and testing.Error calls. It complains if its only argument is an fmt.Sprintf invocation.
func (f *file) lintErrorf()
// lintErrorf examines errors.New and testing.Error calls. It complains if its only argument is an fmt.Sprintf invocation. func (f *file) lintErrorf()
{ f.walk(func(node ast.Node) bool { ce, ok := node.(*ast.CallExpr) if !ok || len(ce.Args) != 1 { return true } isErrorsNew := isPkgDot(ce.Fun, "errors", "New") var isTestingError bool se, ok := ce.Fun.(*ast.SelectorExpr) if ok && se.Sel.Name == "Error" { if typ := f.pkg.typeOf(se.X); typ != nil { isTestingError = typ.String() == "*testing.T" } } if !isErrorsNew && !isTestingError { return true } if !f.imports("errors") { return true } arg := ce.Args[0] ce, ok = arg.(*ast.CallExpr) if !ok || !isPkgDot(ce.Fun, "fmt", "Sprintf") { return true } errorfPrefix := "fmt" if isTestingError { errorfPrefix = f.render(se.X) } p := f.errorf(node, 1, category("errors"), "should replace %s(fmt.Sprintf(...)) with %s.Errorf(...)", f.render(se), errorfPrefix) m := f.srcLineWithMatch(ce, `^(.*)`+f.render(se)+`\(fmt\.Sprintf\((.*)\)\)(.*)$`) if m != nil { p.ReplacementLine = m[1] + errorfPrefix + ".Errorf(" + m[2] + ")" + m[3] } return true }) }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1175-L1204
go
train
// lintErrors examines global error vars. It complains if they aren't named in the standard way.
func (f *file) lintErrors()
// lintErrors examines global error vars. It complains if they aren't named in the standard way. func (f *file) lintErrors()
{ for _, decl := range f.f.Decls { gd, ok := decl.(*ast.GenDecl) if !ok || gd.Tok != token.VAR { continue } for _, spec := range gd.Specs { spec := spec.(*ast.ValueSpec) if len(spec.Names) != 1 || len(spec.Values) != 1 { continue } ce, ok := spec.Values[0].(*ast.CallExpr) if !ok { continue } if !isPkgDot(ce.Fun, "errors", "New") && !isPkgDot(ce.Fun, "fmt", "Errorf") { continue } id := spec.Names[0] prefix := "err" if id.IsExported() { prefix = "Err" } if !strings.HasPrefix(id.Name, prefix) { f.errorf(id, 0.9, category("naming"), "error var %s should have name of the form %sFoo", id.Name, prefix) } } } }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1230-L1259
go
train
// lintErrorStrings examines error strings. // It complains if they are capitalized or end in punctuation or a newline.
func (f *file) lintErrorStrings()
// lintErrorStrings examines error strings. // It complains if they are capitalized or end in punctuation or a newline. func (f *file) lintErrorStrings()
{ f.walk(func(node ast.Node) bool { ce, ok := node.(*ast.CallExpr) if !ok { return true } if !isPkgDot(ce.Fun, "errors", "New") && !isPkgDot(ce.Fun, "fmt", "Errorf") { return true } if len(ce.Args) < 1 { return true } str, ok := ce.Args[0].(*ast.BasicLit) if !ok || str.Kind != token.STRING { return true } s, _ := strconv.Unquote(str.Value) // can assume well-formed Go if s == "" { return true } clean, conf := lintErrorString(s) if clean { return true } f.errorf(str, conf, link(styleGuideBase+"#error-strings"), category("errors"), "error strings should not be capitalized or end with punctuation or a newline") return true }) }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1263-L1292
go
train
// lintReceiverNames examines receiver names. It complains about inconsistent // names used for the same type and names such as "this".
func (f *file) lintReceiverNames()
// lintReceiverNames examines receiver names. It complains about inconsistent // names used for the same type and names such as "this". func (f *file) lintReceiverNames()
{ typeReceiver := map[string]string{} f.walk(func(n ast.Node) bool { fn, ok := n.(*ast.FuncDecl) if !ok || fn.Recv == nil || len(fn.Recv.List) == 0 { return true } names := fn.Recv.List[0].Names if len(names) < 1 { return true } name := names[0].Name const ref = styleGuideBase + "#receiver-names" if name == "_" { f.errorf(n, 1, link(ref), category("naming"), `receiver name should not be an underscore, omit the name if it is unused`) return true } if name == "this" || name == "self" { f.errorf(n, 1, link(ref), category("naming"), `receiver name should be a reflection of its identity; don't use generic names such as "this" or "self"`) return true } recv := receiverType(fn) if prev, ok := typeReceiver[recv]; ok && prev != name { f.errorf(n, 1, link(ref), category("naming"), "receiver name %s should be consistent with previous receiver name %s for %s", name, prev, recv) return true } typeReceiver[recv] = name return true }) }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1296-L1320
go
train
// lintIncDec examines statements that increment or decrement a variable. // It complains if they don't use x++ or x--.
func (f *file) lintIncDec()
// lintIncDec examines statements that increment or decrement a variable. // It complains if they don't use x++ or x--. func (f *file) lintIncDec()
{ f.walk(func(n ast.Node) bool { as, ok := n.(*ast.AssignStmt) if !ok { return true } if len(as.Lhs) != 1 { return true } if !isOne(as.Rhs[0]) { return true } var suffix string switch as.Tok { case token.ADD_ASSIGN: suffix = "++" case token.SUB_ASSIGN: suffix = "--" default: return true } f.errorf(as, 0.8, category("unary-op"), "should replace %s with %s%s", f.render(as), f.render(as.Lhs[0]), suffix) return true }) }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1324-L1347
go
train
// lintErrorReturn examines function declarations that return an error. // It complains if the error isn't the last parameter.
func (f *file) lintErrorReturn()
// lintErrorReturn examines function declarations that return an error. // It complains if the error isn't the last parameter. func (f *file) lintErrorReturn()
{ f.walk(func(n ast.Node) bool { fn, ok := n.(*ast.FuncDecl) if !ok || fn.Type.Results == nil { return true } ret := fn.Type.Results.List if len(ret) <= 1 { return true } if isIdent(ret[len(ret)-1].Type, "error") { return true } // An error return parameter should be the last parameter. // Flag any error parameters found before the last. for _, r := range ret[:len(ret)-1] { if isIdent(r.Type, "error") { f.errorf(fn, 0.9, category("arg-order"), "error should be the last type when returning multiple items") break // only flag one } } return true }) }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1351-L1384
go
train
// lintUnexportedReturn examines exported function declarations. // It complains if any return an unexported type.
func (f *file) lintUnexportedReturn()
// lintUnexportedReturn examines exported function declarations. // It complains if any return an unexported type. func (f *file) lintUnexportedReturn()
{ f.walk(func(n ast.Node) bool { fn, ok := n.(*ast.FuncDecl) if !ok { return true } if fn.Type.Results == nil { return false } if !fn.Name.IsExported() { return false } thing := "func" if fn.Recv != nil && len(fn.Recv.List) > 0 { thing = "method" if !ast.IsExported(receiverType(fn)) { // Don't report exported methods of unexported types, // such as private implementations of sort.Interface. return false } } for _, ret := range fn.Type.Results.List { typ := f.pkg.typeOf(ret.Type) if exportedType(typ) { continue } f.errorf(ret.Type, 0.8, category("unexported-type-in-api"), "exported %s %s returns unexported type %s, which can be annoying to use", thing, fn.Name.Name, typ) break // only flag one } return false }) }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1389-L1403
go
train
// exportedType reports whether typ is an exported type. // It is imprecise, and will err on the side of returning true, // such as for composite types.
func exportedType(typ types.Type) bool
// exportedType reports whether typ is an exported type. // It is imprecise, and will err on the side of returning true, // such as for composite types. func exportedType(typ types.Type) bool
{ switch T := typ.(type) { case *types.Named: // Builtin types have no package. return T.Obj().Pkg() == nil || T.Obj().Exported() case *types.Map: return exportedType(T.Key()) && exportedType(T.Elem()) case interface { Elem() types.Type }: // array, slice, pointer, chan return exportedType(T.Elem()) } // Be conservative about other types, such as struct, interface, etc. return true }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1451-L1460
go
train
// lintContextKeyTypes checks for call expressions to context.WithValue with // basic types used for the key argument. // See: https://golang.org/issue/17293
func (f *file) lintContextKeyTypes()
// lintContextKeyTypes checks for call expressions to context.WithValue with // basic types used for the key argument. // See: https://golang.org/issue/17293 func (f *file) lintContextKeyTypes()
{ f.walk(func(node ast.Node) bool { switch node := node.(type) { case *ast.CallExpr: f.checkContextKeyType(node) } return true }) }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1464-L1486
go
train
// checkContextKeyType reports an error if the call expression calls // context.WithValue with a key argument of basic type.
func (f *file) checkContextKeyType(x *ast.CallExpr)
// checkContextKeyType reports an error if the call expression calls // context.WithValue with a key argument of basic type. func (f *file) checkContextKeyType(x *ast.CallExpr)
{ sel, ok := x.Fun.(*ast.SelectorExpr) if !ok { return } pkg, ok := sel.X.(*ast.Ident) if !ok || pkg.Name != "context" { return } if sel.Sel.Name != "WithValue" { return } // key is second argument to context.WithValue if len(x.Args) != 3 { return } key := f.pkg.typesInfo.Types[x.Args[1]] if ktyp, ok := key.Type.(*types.Basic); ok && ktyp.Kind() != types.Invalid { f.errorf(x, 1.0, category("context"), fmt.Sprintf("should not use basic type %s as key in context.WithValue", key.Type)) } }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1491-L1507
go
train
// lintContextArgs examines function declarations that contain an // argument with a type of context.Context // It complains if that argument isn't the first parameter.
func (f *file) lintContextArgs()
// lintContextArgs examines function declarations that contain an // argument with a type of context.Context // It complains if that argument isn't the first parameter. func (f *file) lintContextArgs()
{ f.walk(func(n ast.Node) bool { fn, ok := n.(*ast.FuncDecl) if !ok || len(fn.Type.Params.List) <= 1 { return true } // A context.Context should be the first parameter of a function. // Flag any that show up after the first. for _, arg := range fn.Type.Params.List[1:] { if isPkgDot(arg.Type, "context", "Context") { f.errorf(fn, 0.9, link("https://golang.org/pkg/context/"), category("arg-order"), "context.Context should be the first parameter of a function") break // only flag one } } return true }) }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1511-L1529
go
train
// containsComments returns whether the interval [start, end) contains any // comments without "// MATCH " prefix.
func (f *file) containsComments(start, end token.Pos) bool
// containsComments returns whether the interval [start, end) contains any // comments without "// MATCH " prefix. func (f *file) containsComments(start, end token.Pos) bool
{ for _, cgroup := range f.f.Comments { comments := cgroup.List if comments[0].Slash >= end { // All comments starting with this group are after end pos. return false } if comments[len(comments)-1].Slash < start { // Comments group ends before start pos. continue } for _, c := range comments { if start <= c.Slash && c.Slash < end && !strings.HasPrefix(c.Text, "// MATCH ") { return true } } } return false }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1533-L1544
go
train
// receiverType returns the named type of the method receiver, sans "*", // or "invalid-type" if fn.Recv is ill formed.
func receiverType(fn *ast.FuncDecl) string
// receiverType returns the named type of the method receiver, sans "*", // or "invalid-type" if fn.Recv is ill formed. func receiverType(fn *ast.FuncDecl) string
{ switch e := fn.Recv.List[0].Type.(type) { case *ast.Ident: return e.Name case *ast.StarExpr: if id, ok := e.X.(*ast.Ident); ok { return id.Name } } // The parser accepts much more than just the legal forms. return "invalid-type" }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1622-L1637
go
train
// isUntypedConst reports whether expr is an untyped constant, // and indicates what its default type is. // scope may be nil.
func (f *file) isUntypedConst(expr ast.Expr) (defType string, ok bool)
// isUntypedConst reports whether expr is an untyped constant, // and indicates what its default type is. // scope may be nil. func (f *file) isUntypedConst(expr ast.Expr) (defType string, ok bool)
{ // Re-evaluate expr outside of its context to see if it's untyped. // (An expr evaluated within, for example, an assignment context will get the type of the LHS.) exprStr := f.render(expr) tv, err := types.Eval(f.fset, f.pkg.typesPkg, expr.Pos(), exprStr) if err != nil { return "", false } if b, ok := tv.Type.(*types.Basic); ok { if dt, ok := basicTypeKinds[b.Kind()]; ok { return dt, true } } return "", false }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1641-L1647
go
train
// firstLineOf renders the given node and returns its first line. // It will also match the indentation of another node.
func (f *file) firstLineOf(node, match ast.Node) string
// firstLineOf renders the given node and returns its first line. // It will also match the indentation of another node. func (f *file) firstLineOf(node, match ast.Node) string
{ line := f.render(node) if i := strings.Index(line, "\n"); i >= 0 { line = line[:i] } return f.indentOf(match) + line }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1669-L1680
go
train
// imports returns true if the current file imports the specified package path.
func (f *file) imports(importPath string) bool
// imports returns true if the current file imports the specified package path. func (f *file) imports(importPath string) bool
{ all := astutil.Imports(f.fset, f.f) for _, p := range all { for _, i := range p { uq, err := strconv.Unquote(i.Path.Value) if err == nil && importPath == uq { return true } } } return false }
golang/lint
959b441ac422379a43da2230f62be024250818b0
lint.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/lint.go#L1683-L1693
go
train
// srcLine returns the complete line at p, including the terminating newline.
func srcLine(src []byte, p token.Position) string
// srcLine returns the complete line at p, including the terminating newline. func srcLine(src []byte, p token.Position) string
{ // Run to end of line in both directions if not at line start/end. lo, hi := p.Offset, p.Offset+1 for lo > 0 && src[lo-1] != '\n' { lo-- } for hi < len(src) && src[hi-1] != '\n' { hi++ } return string(src[lo:hi]) }
golang/lint
959b441ac422379a43da2230f62be024250818b0
golint/import.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/golint/import.go#L65-L80
go
train
// importPaths returns the import paths to use for the given command line.
func importPaths(args []string) []string
// importPaths returns the import paths to use for the given command line. func importPaths(args []string) []string
{ args = importPathsNoDotExpansion(args) var out []string for _, a := range args { if strings.Contains(a, "...") { if build.IsLocalImport(a) { out = append(out, allPackagesInFS(a)...) } else { out = append(out, allPackages(a)...) } continue } out = append(out, a) } return out }