// Returns true if the user is the work item creator or space collaborator
432659
func authorizeWorkitemEditor(ctx context.Context, db application.DB, spaceID uuid.UUID, creatorID string, editorID string) (bool, error) {
	if editorID == creatorID {
		return true, nil
	}
	authorized, err := authz.Authorize(ctx, spaceID.String())
	if err != nil {
		return false, errors.NewUnauthorizedError(err.Error())
	}
	return authorized, nil
}
1182816
func (ctr *rowConstructor) SpaceBegin(widget_count int) (bounds rect.Rect) {
	layout := ctr.win.layout
	panelLayout(ctr.win.ctx, ctr.win, ctr.height, widget_count, 0)
	layout.Row.Type = layoutStaticFree

	layout.Row.Ratio = nil
	layout.Row.ItemWidth = 0
	layout.Row.ItemRatio = 0.0
	layout.Row.ItemOffset = 0
	layout.Row.Filled = 0

	style := ctr.win.style()
	spacing := style.Spacing
	padding := style.Padding

	bounds.W = layout.Width - 2*padding.X
	bounds.H = layout.Row.Height - spacing.Y

	return bounds
}
1167436
func (c *Controller) processNextWorkItem() bool {
	pvKey, quit := c.queue.Get()
	if quit {
		return false
	}
	defer c.queue.Done(pvKey)

	pvName := pvKey.(string)

	err := c.processPV(pvName)
	if err == nil {
		c.queue.Forget(pvKey)
		return true
	}

	utilruntime.HandleError(fmt.Errorf("PV %v failed with : %v", pvKey, err))
	c.queue.AddRateLimited(pvKey)

	return true
}
225626
func WorkspaceFor(source string) (*Workspace, error) {
	gopaths := envOr("GOPATH", build.Default.GOPATH)
	// We use absolute paths so that in particular on Windows the case gets normalized
	sourcePath, err := filepath.Abs(source)
	if err != nil {
		sourcePath = source
	}
	if os.Getenv("GO111MODULE") != "on" { // GOPATH mode
		for _, gp := range filepath.SplitList(gopaths) {
			gopath, err := filepath.Abs(gp)
			if err != nil {
				gopath = gp
			}
			if filepath.HasPrefix(sourcePath, gopath) {
				return &Workspace{
					gopath:       gopaths,
					isModuleMode: false,
					Path:         gopath,
				}, nil
			}
		}
	}
	if os.Getenv("GO111MODULE") != "off" { // Module mode
		root, _ := findModuleRoot(sourcePath, "", false)
		if root != "" {
			return &Workspace{
				gopath:       gopaths,
				isModuleMode: true,
				Path:         root,
			}, nil
		}
	}
	return nil, fmt.Errorf(`Go source file "%s" not in Go workspace, adjust GOPATH %s or use modules`, source, gopaths)
}
141919
func ConvertWorkItem(request *http.Request, wit workitem.WorkItemType, wi workitem.WorkItem, additional ...WorkItemConvertFunc) (*app.WorkItem, error) {
	// construct default values from input WI
	relatedURL := rest.AbsoluteURL(request, app.WorkitemHref(wi.ID))
	labelsRelated := relatedURL + "/labels"
	workItemLinksRelated := relatedURL + "/links"

	op := &app.WorkItem{
		ID:   &wi.ID,
		Type: APIStringTypeWorkItem,
		Attributes: map[string]interface{}{
			workitem.SystemVersion: wi.Version,
			workitem.SystemNumber:  wi.Number,
		},
		Relationships: &app.WorkItemRelationships{
			BaseType: &app.RelationBaseType{
				Data: &app.BaseTypeData{
					ID:   wi.Type,
					Type: APIStringTypeWorkItemType,
				},
				Links: &app.GenericLinks{
					Self: ptr.String(rest.AbsoluteURL(request, app.WorkitemtypeHref(wi.Type))),
				},
			},
			Space: app.NewSpaceRelation(wi.SpaceID, rest.AbsoluteURL(request, app.SpaceHref(wi.SpaceID.String()))),
			WorkItemLinks: &app.RelationGeneric{
				Links: &app.GenericLinks{
					Related: &workItemLinksRelated,
				},
			},
		},
		Links: &app.GenericLinksForWorkItem{
			Self:    &relatedURL,
			Related: &relatedURL,
		},
	}

	// Move fields into Relationships or Attributes as needed
	// TODO(kwk): Loop based on WorkItemType and match against Field.Type instead of directly to field value
	for name, val := range wi.Fields {
		switch name {
		case workitem.SystemAssignees:
			if val != nil {
				userID := val.([]interface{})
				op.Relationships.Assignees = &app.RelationGenericList{
					Data: ConvertUsersSimple(request, userID),
				}
			}
		case workitem.SystemLabels:
			if val != nil {
				labelIDs := val.([]interface{})
				op.Relationships.Labels = &app.RelationGenericList{
					Data: ConvertLabelsSimple(request, labelIDs),
					Links: &app.GenericLinks{
						Related: &labelsRelated,
					},
				}
			}
		case workitem.SystemBoardcolumns:
			if val != nil {
				columnIDs := val.([]interface{})
				op.Relationships.Boardcolumns = &app.RelationGenericList{
					Data: ConvertBoardColumnsSimple(request, columnIDs),
				}
			}
		case workitem.SystemCreator:
			if val != nil {
				userID := val.(string)
				data, links := ConvertUserSimple(request, userID)
				op.Relationships.Creator = &app.RelationGeneric{
					Data:  data,
					Links: links,
				}
			}
		case workitem.SystemIteration:
			if val != nil {
				valStr := val.(string)
				data, links := ConvertIterationSimple(request, valStr)
				op.Relationships.Iteration = &app.RelationGeneric{
					Data:  data,
					Links: links,
				}
			}
		case workitem.SystemArea:
			if val != nil {
				valStr := val.(string)
				data, links := ConvertAreaSimple(request, valStr)
				op.Relationships.Area = &app.RelationGeneric{
					Data:  data,
					Links: links,
				}
			}

		case workitem.SystemTitle:
			// 'HTML escape' the title to prevent script injection
			op.Attributes[name] = html.EscapeString(val.(string))
		case workitem.SystemDescription:
			description := rendering.NewMarkupContentFromValue(val)
			if description != nil {
				op.Attributes[name] = (*description).Content
				op.Attributes[workitem.SystemDescriptionMarkup] = (*description).Markup
				op.Attributes[workitem.SystemDescriptionRendered] = rendering.RenderMarkupToHTML((*description).Content, (*description).Markup)
			}
		case workitem.SystemCodebase:
			if val != nil {
				op.Attributes[name] = val
				// TODO: Following format is TBD and hence commented out
				cb := val.(codebase.Content)
				editURL := rest.AbsoluteURL(request, app.CodebaseHref(cb.CodebaseID)+"/edit")
				op.Links.EditCodebase = &editURL
			}
		default:
			op.Attributes[name] = val
		}
	}
	if op.Relationships.Assignees == nil {
		op.Relationships.Assignees = &app.RelationGenericList{Data: nil}
	}
	if op.Relationships.Iteration == nil {
		op.Relationships.Iteration = &app.RelationGeneric{Data: nil}
	}
	if op.Relationships.Area == nil {
		op.Relationships.Area = &app.RelationGeneric{Data: nil}
	}
	// Always include Comments Link, but optionally use workItemIncludeCommentsAndTotal
	workItemIncludeComments(request, &wi, op)
	workItemIncludeChildren(request, &wi, op)
	workItemIncludeEvents(request, &wi, op)
	for _, add := range additional {
		if err := add(request, &wi, op); err != nil {
			return nil, errs.Wrap(err, "failed to run additional conversion function")
		}
	}
	return op, nil
}
662333
func NewWorkItemCreated(workitemID string, revisionID uuid.UUID) Message {
	return Message{
		MessageID:   uuid.NewV4(),
		MessageType: "workitem.create",
		TargetID:    workitemID,
		Custom:      map[string]interface{}{"revision_id": revisionID},
	}
}
387300
func NewJiraRemoteWorkItem(item TrackerItem) (AttributeAccessor, error) {
	var j map[string]interface{}
	err := json.Unmarshal([]byte(item.Item), &j)
	if err != nil {
		return nil, errors.WithStack(err)
	}
	j = Flatten(j)
	return JiraRemoteWorkItem{issue: j}, nil
}
1026505
func isGeneratorJobImage(image *dockerv10.DockerImage) bool {
	if image == nil || image.Config == nil {
		return false
	}
	// Has the job annotation
	if image.Config.Labels[labelGenerateJob] == "true" {
		return true
	}
	return false
}
490442
func workItemIncludeHasChildren(ctx context.Context, appl application.Application, childLinks ...link.WorkItemLinkList) WorkItemConvertFunc {
	// TODO: Wrap ctx in a Timeout context?
	return func(request *http.Request, wi *workitem.WorkItem, wi2 *app.WorkItem) error {
		var hasChildren bool
		// If we already have information about children inside the child links
		// we can use that before querying the DB.
		if len(childLinks) == 1 {
			for _, l := range childLinks[0] {
				if l.LinkTypeID == link.SystemWorkItemLinkTypeParentChildID && l.SourceID == wi.ID {
					hasChildren = true
				}
			}
		}
		if !hasChildren {
			var err error
			repo := appl.WorkItemLinks()
			if repo != nil {
				hasChildren, err = appl.WorkItemLinks().WorkItemHasChildren(ctx, wi.ID)
				log.Info(ctx, map[string]interface{}{"wi_id": wi.ID}, "Work item has children: %t", hasChildren)
				if err != nil {
					log.Error(ctx, map[string]interface{}{
						"wi_id": wi.ID,
						"err":   err,
					}, "unable to find out if work item has children: %s", wi.ID)
					// enforce to have no children
					hasChildren = false
					return errs.Wrapf(err, "failed to determine if work item %s has children", wi.ID)
				}
			}
		}
		if wi2.Relationships.Children == nil {
			wi2.Relationships.Children = &app.RelationGeneric{}
		}
		wi2.Relationships.Children.Meta = map[string]interface{}{
			"hasChildren": hasChildren,
		}
		return nil
	}
}
789966
func NewWorker(sm *source.Manager, vm *storage.VendorCollectionManager, rm *storage.RecordCollectionManager) *Worker {
	return &Worker{
		sm: sm,
		vm: vm,
		rm: rm,
	}
}
80159
func (c *DiscoveryController) processNextWorkItem() bool {
	key, quit := c.queue.Get()
	if quit {
		return false
	}
	defer c.queue.Done(key)

	err := c.syncFn(key.(schema.GroupVersion))
	if err == nil {
		c.queue.Forget(key)
		return true
	}

	utilruntime.HandleError(fmt.Errorf("%v failed with: %v", key, err))
	c.queue.AddRateLimited(key)

	return true
}
792885
func (m *Manager) isDirectOwnerOfOrgs(globalIDs []string, username string) (ownedOrgs []string, err error) {
	var orgs []Organization
	err = m.collection.Find(bson.M{"globalid": bson.M{"$in": globalIDs}, "owners": username}).Select(bson.M{"globalid": 1}).All(&orgs)
	ownedOrgs = make([]string, len(orgs))
	for i, org := range orgs {
		ownedOrgs[i] = org.Globalid
	}
	return
}
1235745
func (c *WorkitemController) Delete(ctx *app.DeleteWorkitemContext) error {
	currentUserIdentityID, err := login.ContextIdentity(ctx)
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, errors.NewUnauthorizedError(err.Error()))
	}

	var wi *workitem.WorkItem
	err = application.Transactional(c.db, func(appl application.Application) error {
		wi, err = appl.WorkItems().LoadByID(ctx, ctx.WiID)
		if err != nil {
			return errs.Wrap(err, fmt.Sprintf("Fail to load work item with id %v", ctx.WiID))
		}
		return nil
	})
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, err)
	}

	// Check if user is space owner or workitem creator. Only space owner or workitem creator are allowed to delete the workitem.
	creator := wi.Fields[workitem.SystemCreator]
	if creator == nil {
		return jsonapi.JSONErrorResponse(ctx, errors.NewInternalError(ctx, errs.New("work item doesn't have creator")))
	}
	creatorIDStr, ok := creator.(string)
	if !ok {
		return jsonapi.JSONErrorResponse(ctx, errs.Errorf("failed to convert user to string: %+v (%[1]T)", creator))
	}
	creatorID, err := uuid.FromString(creatorIDStr)
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, err)
	}
	err = c.WorkitemCreatorOrSpaceOwner(ctx, wi.SpaceID, creatorID, *currentUserIdentityID)
	if err != nil {
		forbidden, _ := errors.IsForbiddenError(err)
		if forbidden {
			return jsonapi.JSONErrorResponse(ctx, errors.NewForbiddenError("user is not authorized to delete the workitem"))

		}
		return jsonapi.JSONErrorResponse(ctx, err)
	}
	err = application.Transactional(c.db, func(appl application.Application) error {
		if err := appl.WorkItemLinks().DeleteRelatedLinks(ctx, ctx.WiID, *currentUserIdentityID); err != nil {
			return errs.Wrapf(err, "failed to delete work item links related to work item %s", ctx.WiID)
		}
		if err := appl.WorkItems().Delete(ctx, ctx.WiID, *currentUserIdentityID); err != nil {
			return errs.Wrapf(err, "error deleting work item %s", ctx.WiID)
		}
		return nil
	})
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, err)
	}
	return ctx.OK([]byte{})
}
1139491
func (d *stiDocker) GetImageWorkdir(name string) (string, error) {
	resp, err := d.InspectImage(name)
	if err != nil {
		return "", err
	}
	workdir := resp.Config.WorkingDir
	if len(workdir) == 0 {
		// This is a default destination used by UploadToContainer when the WORKDIR
		// is not set or it is empty. To show user where the injections will end up,
		// we set this to "/".
		workdir = "/"
	}
	return workdir, nil
}
981511
func (c *Controller) processNextWorkItem() bool {
	pvcKey, quit := c.queue.Get()
	if quit {
		return false
	}
	defer c.queue.Done(pvcKey)

	pvcNamespace, pvcName, err := cache.SplitMetaNamespaceKey(pvcKey.(string))
	if err != nil {
		utilruntime.HandleError(fmt.Errorf("Error parsing PVC key %q: %v", pvcKey, err))
		return true
	}

	err = c.processPVC(pvcNamespace, pvcName)
	if err == nil {
		c.queue.Forget(pvcKey)
		return true
	}

	utilruntime.HandleError(fmt.Errorf("PVC %v failed with : %v", pvcKey, err))
	c.queue.AddRateLimited(pvcKey)

	return true
}
864087
func (ctrl *PersistentVolumeController) volumeWorker() {
	workFunc := func() bool {
		keyObj, quit := ctrl.volumeQueue.Get()
		if quit {
			return true
		}
		defer ctrl.volumeQueue.Done(keyObj)
		key := keyObj.(string)
		klog.V(5).Infof("volumeWorker[%s]", key)

		_, name, err := cache.SplitMetaNamespaceKey(key)
		if err != nil {
			klog.V(4).Infof("error getting name of volume %q to get volume from informer: %v", key, err)
			return false
		}
		volume, err := ctrl.volumeLister.Get(name)
		if err == nil {
			// The volume still exists in informer cache, the event must have
			// been add/update/sync
			ctrl.updateVolume(volume)
			return false
		}
		if !errors.IsNotFound(err) {
			klog.V(2).Infof("error getting volume %q from informer: %v", key, err)
			return false
		}

		// The volume is not in informer cache, the event must have been
		// "delete"
		volumeObj, found, err := ctrl.volumes.store.GetByKey(key)
		if err != nil {
			klog.V(2).Infof("error getting volume %q from cache: %v", key, err)
			return false
		}
		if !found {
			// The controller has already processed the delete event and
			// deleted the volume from its cache
			klog.V(2).Infof("deletion of volume %q was already processed", key)
			return false
		}
		volume, ok := volumeObj.(*v1.PersistentVolume)
		if !ok {
			klog.Errorf("expected volume, got %+v", volumeObj)
			return false
		}
		ctrl.deleteVolume(volume)
		return false
	}
	for {
		if quit := workFunc(); quit {
			klog.Infof("volume worker queue shutting down")
			return
		}
	}
}
130515
func (actor Actor) GrantSpaceManagerByUsername(orgGUID string, spaceGUID string, username string) (Warnings, error) {
	if actor.Config.UAAGrantType() == string(uaaconst.GrantTypeClientCredentials) {
		return actor.grantSpaceManagerByClientCredentials(orgGUID, spaceGUID, username)
	}

	return actor.grantSpaceManagerByUsername(orgGUID, spaceGUID, username)
}