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().Effect...
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 m...
{ 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.ApplyPropertyC...
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 ClusterComputeResou...
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 ClusterComputeResou...
{ 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...
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{ ...
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 := ...
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...
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) swi...
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 } ...
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...
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 { htt...
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 ...
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 { ...
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 ...
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 ...
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...
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(...
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(file...
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(f...
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.Mat...
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 pk...
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 && ...
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-ori...
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-ori...
{ 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...
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 !isBla...
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 consta...
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 consta...
{ 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...
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 anyCaps...
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(...
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] { ...
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, genDeclMissingCommen...
{ 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) ...
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 ...
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 || ...
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 := ...
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 { ...
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 { co...
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 ...
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-name...
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: ...
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. /...
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)) {...
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()) } ...
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 kty...
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, "contex...
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 {...
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.Ty...
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 }