// ConvertLinkFromModel converts a work item from model to REST representation
765310
func ConvertLinkFromModel(request *http.Request, t link.WorkItemLink) app.WorkItemLinkSingle {
	linkSelfURL := rest.AbsoluteURL(request, app.WorkItemLinkHref(t.ID.String()))
	linkTypeRelatedURL := rest.AbsoluteURL(request, app.WorkItemLinkTypeHref(t.LinkTypeID.String()))

	sourceRelatedURL := rest.AbsoluteURL(request, app.WorkitemHref(t.SourceID.String()))
	targetRelatedURL := rest.AbsoluteURL(request, app.WorkitemHref(t.TargetID.String()))

	var converted = app.WorkItemLinkSingle{
		Data: &app.WorkItemLinkData{
			Type: link.EndpointWorkItemLinks,
			ID:   &t.ID,
			Attributes: &app.WorkItemLinkAttributes{
				CreatedAt: &t.CreatedAt,
				UpdatedAt: &t.UpdatedAt,
				Version:   &t.Version,
			},
			Links: &app.GenericLinks{
				Self: &linkSelfURL,
			},
			Relationships: &app.WorkItemLinkRelationships{
				LinkType: &app.RelationWorkItemLinkType{
					Data: &app.RelationWorkItemLinkTypeData{
						Type: link.EndpointWorkItemLinkTypes,
						ID:   t.LinkTypeID,
					},
					Links: &app.GenericLinks{
						Self: &linkTypeRelatedURL,
					},
				},
				Source: &app.RelationWorkItem{
					Data: &app.RelationWorkItemData{
						Type: link.EndpointWorkItems,
						ID:   t.SourceID,
					},
					Links: &app.GenericLinks{
						Related: &sourceRelatedURL,
					},
				},
				Target: &app.RelationWorkItem{
					Data: &app.RelationWorkItemData{
						Type: link.EndpointWorkItems,
						ID:   t.TargetID,
					},
					Links: &app.GenericLinks{
						Related: &targetRelatedURL,
					},
				},
			},
		},
	}
	return converted
}
136355
func (obj *GenericDimension) GetLinkedObjectsRaw(ctx context.Context) (json.RawMessage, error) {
	result := &struct {
		Items json.RawMessage	`json:"qItems"`
	} {}
	err := obj.rpc(ctx, "GetLinkedObjects", result)
	return result.Items, err 
}
1331167
func getWorkItemsOfLinks(ctx context.Context, appl application.Application, req *http.Request, linksDataArr []*app.WorkItemLinkData) ([]*app.WorkItem, error) {
	// Build our "set" of distinct work item IDs
	idMap := map[uuid.UUID]struct{}{}
	idArr := []uuid.UUID{}
	for _, linkData := range linksDataArr {
		src := linkData.Relationships.Source.Data.ID
		tgt := linkData.Relationships.Target.Data.ID
		if _, ok := idMap[src]; !ok {
			idMap[src] = struct{}{}
			idArr = append(idArr, src)
		}
		if _, ok := idMap[tgt]; !ok {
			idMap[tgt] = struct{}{}
			idArr = append(idArr, tgt)
		}
	}

	// Fetch all work items specified in the array
	res := []*app.WorkItem{}
	for _, id := range idArr {
		wi, err := appl.WorkItems().LoadByID(ctx, id)
		if err != nil {
			return nil, errs.WithStack(err)
		}
		wit, err := appl.WorkItemTypes().Load(ctx, wi.Type)
		if err != nil {
			return nil, errs.Wrapf(err, "failed to load work item type: %s", wi.Type)
		}
		converted, err := ConvertWorkItem(req, *wit, *wi)
		if err != nil {
			return nil, errs.WithStack(err)
		}
		res = append(res, converted)
	}
	return res, nil
}
953373
func (n *Node) ResolveLink(path []string) (*node.Link, []string, error) {
	obj, rest, err := n.Resolve(path)
	if err != nil {
		return nil, nil, err
	}

	lnk, ok := obj.(*node.Link)
	if !ok {
		return nil, rest, ErrNonLink
	}

	return lnk, rest, nil
}
410491
func (m *linkMechanismManager) UpdateLink(context *LinkManagerContext) (err error) {
	link := new(LinkManagerContext)

	update := func(fn func() error) error {
		return m.BaseMechanismManager.Update(
			LinkModel, link, fn,
		)
	}

	pre := func(port LinkPort) error {
		linkContext, err := m.linkContext(port)
		if err != nil {
			return err
		}

		err = m.do(func(llmech LinkMechanism) error {
			return llmech.UpdateLinkPreCommit(linkContext)
		})

		if err != nil {
			log.ErrorLog("link/UPDATE_LINK_PRECOMMIT",
				"Failed to update link configuration: ", err)
		}

		return err
	}

	post := func(port LinkPort) error {
		linkContext, err := m.linkContext(port)
		if err != nil {
			return err
		}

		err = m.do(func(llmech LinkMechanism) error {
			return llmech.UpdateLinkPostCommit(linkContext)
		})

		if err != nil {
			log.ErrorLog("link/UPDATE_LINK_POSTCOMMIT",
				"Failed to update link configuration: ", err)
		}

		return err
	}

	m.lock.RLock()
	defer m.lock.RUnlock()

	return update(func() error {
		_, err := m.Driver()
		if err != nil && len(link.Ports) != 0 {
			log.ErrorLog("link/UPDATE_LINK",
				"Driver not found, but ports need to be updated")
			return ErrLinkNotInitialized
		}

		for _, port := range context.Ports {
			port = link.Port(port.Port)
			blank := LinkPort{}

			// Skip blank ports
			if port == blank {
				continue
			}

			// Update pre-commit
			if err := pre(port); err != nil {
				log.ErrorLog("link/UPDATE_LINK",
					"Link layer delete pre-commit failed: ", err)
				return err
			}
		}

		// Set new link layer driver
		err = m.SetDriver(context.Driver)
		if err != nil {
			return err
		}

		// Update driver configuration
		link.Driver = context.Driver

		for _, port := range context.Ports {
			// Update  post-commit
			if err := post(port); err != nil {
				log.ErrorLog("link/UPDATE_LINK",
					"Link layer update pre-commit failed: ", err)
				return err
			}

			// Update link layer port configuration
			link.SetPort(port)
		}

		return nil
	})
}
1142522
func (f *CustomUplinkFunctions) convert(fields map[string]interface{}, port uint8) (map[string]interface{}, error) {
	if f.Converter == "" {
		return fields, nil
	}

	env := map[string]interface{}{
		"fields": fields,
		"port":   port,
	}

	code := fmt.Sprintf(`
		%s;
		Converter(fields, port)
	`, f.Converter)

	value, err := functions.RunCode("Converter", code, env, timeOut, f.Logger)
	if err != nil {
		return nil, err
	}

	m, ok := value.(map[string]interface{})
	if !ok {
		return nil, errors.NewErrInvalidArgument("Converter", "does not return an object")
	}

	return m, nil
}
1308660
func (r *GormWorkItemLinkRepository) ListChildLinks(ctx context.Context, linkTypeID uuid.UUID, parentIDs ...uuid.UUID) (WorkItemLinkList, error) {
	defer goa.MeasureSince([]string{"goa", "db", "workitemlink", "list", "children", "ids"}, time.Now())

	var results WorkItemLinkList
	db := r.db.Model(&WorkItemLink{}).Where("source_id IN (?) AND link_type_id = ?", parentIDs, linkTypeID).Scan(&results)
	if db.Error != nil {
		log.Error(ctx, map[string]interface{}{
			"err": db.Error,
		}, "failed to find children for work items: %+v", parentIDs)
		return nil, errors.NewInternalError(ctx, errs.Wrapf(db.Error, "failed to find children for work items: %+v", parentIDs))
	}

	return results, nil
}
1374801
func ConvertWorkItemLinkTypeToModel(appLinkType app.WorkItemLinkTypeSingle) (*link.WorkItemLinkType, error) {
	modelLinkType := link.WorkItemLinkType{}
	if appLinkType.Data == nil {
		return nil, errors.NewBadParameterError("data", nil).Expected("not <nil>")
	}
	if appLinkType.Data.Attributes == nil {
		return nil, errors.NewBadParameterError("data.attributes", nil).Expected("not <nil>")
	}
	if appLinkType.Data.Relationships == nil {
		return nil, errors.NewBadParameterError("data.relationships", nil).Expected("not <nil>")
	}

	attrs := appLinkType.Data.Attributes
	rel := appLinkType.Data.Relationships

	if appLinkType.Data.ID != nil {
		modelLinkType.ID = *appLinkType.Data.ID
	}

	if attrs != nil {
		// If the name is not nil, it MUST NOT be empty
		if attrs.Name != nil {
			if *attrs.Name == "" {
				return nil, errors.NewBadParameterError("data.attributes.name", *attrs.Name)
			}
			modelLinkType.Name = *attrs.Name
		}

		modelLinkType.Description = attrs.Description
		modelLinkType.ForwardDescription = attrs.ForwardDescription
		modelLinkType.ReverseDescription = attrs.ReverseDescription

		if attrs.Version != nil {
			modelLinkType.Version = *attrs.Version
		}

		// If the forwardName is not nil, it MUST NOT be empty
		if attrs.ForwardName != nil {
			if *attrs.ForwardName == "" {
				return nil, errors.NewBadParameterError("data.attributes.forward_name", *attrs.ForwardName)
			}
			modelLinkType.ForwardName = *attrs.ForwardName
		}

		// If the ReverseName is not nil, it MUST NOT be empty
		if attrs.ReverseName != nil {
			if *attrs.ReverseName == "" {
				return nil, errors.NewBadParameterError("data.attributes.reverse_name", *attrs.ReverseName)
			}
			modelLinkType.ReverseName = *attrs.ReverseName
		}

		if attrs.Topology != nil {
			modelLinkType.Topology = link.Topology(*attrs.Topology)
			if err := modelLinkType.Topology.CheckValid(); err != nil {
				return nil, err
			}
		}
	}

	if rel != nil && rel.SpaceTemplate != nil && rel.SpaceTemplate.Data != nil {
		modelLinkType.SpaceTemplateID = rel.SpaceTemplate.Data.ID
	}

	return &modelLinkType, nil
}
263464
func convertTermObj(o map[string]interface{}) termsObj {
	if len(o) == 0 {
		return nil
	}

	terms := make(termsObj, len(o))
	for k, v := range o {
		terms[k] = Expr(v)
	}

	return terms
}
1059355
func ModelInfoFromParams(info params.ModelInfo, now time.Time) (ModelInfo, error) {
	ownerTag, err := names.ParseUserTag(info.OwnerTag)
	if err != nil {
		return ModelInfo{}, errors.Trace(err)
	}
	cloudTag, err := names.ParseCloudTag(info.CloudTag)
	if err != nil {
		return ModelInfo{}, errors.Trace(err)
	}
	modelInfo := ModelInfo{
		ShortName:      info.Name,
		Name:           jujuclient.JoinOwnerModelName(ownerTag, info.Name),
		Type:           model.ModelType(info.Type),
		UUID:           info.UUID,
		ControllerUUID: info.ControllerUUID,
		IsController:   info.IsController,
		Owner:          ownerTag.Id(),
		Life:           string(info.Life),
		Cloud:          cloudTag.Id(),
		CloudRegion:    info.CloudRegion,
	}
	if info.AgentVersion != nil {
		modelInfo.AgentVersion = info.AgentVersion.String()
	}
	// Although this may be more performance intensive, we have to use reflection
	// since structs containing map[string]interface {} cannot be compared, i.e
	// cannot use simple '==' here.
	if !reflect.DeepEqual(info.Status, params.EntityStatus{}) {
		modelInfo.Status = &ModelStatus{
			Current: info.Status.Status,
			Message: info.Status.Info,
			Since:   FriendlyDuration(info.Status.Since, now),
		}
	}
	if info.Migration != nil {
		status := modelInfo.Status
		if status == nil {
			status = &ModelStatus{}
			modelInfo.Status = status
		}
		status.Migration = info.Migration.Status
		status.MigrationStart = FriendlyDuration(info.Migration.Start, now)
		status.MigrationEnd = FriendlyDuration(info.Migration.End, now)
	}

	if info.ProviderType != "" {
		modelInfo.ProviderType = info.ProviderType

	}
	if len(info.Users) != 0 {
		modelInfo.Users = ModelUserInfoFromParams(info.Users, now)
	}
	if len(info.Machines) != 0 {
		modelInfo.Machines = ModelMachineInfoFromParams(info.Machines)
	}
	if info.SLA != nil {
		modelInfo.SLA = ModelSLAFromParams(info.SLA)
		modelInfo.SLAOwner = ModelSLAOwnerFromParams(info.SLA)
	}

	if info.CloudCredentialTag != "" {
		credTag, err := names.ParseCloudCredentialTag(info.CloudCredentialTag)
		if err != nil {
			return ModelInfo{}, errors.Trace(err)
		}
		modelInfo.Credential = &ModelCredential{
			Name:  credTag.Name(),
			Owner: credTag.Owner().Id(),
			Cloud: credTag.Cloud().Id(),
		}
	}

	return modelInfo, nil
}
87047
func ConvertWorkItemStorageToModel(wiType *WorkItemType, wi *WorkItemStorage) (*WorkItem, error) {
	result, err := wiType.ConvertWorkItemStorageToModel(*wi)
	if err != nil {
		return nil, errors.NewConversionError(err.Error())
	}
	if _, ok := wiType.Fields[SystemCreatedAt]; ok {
		result.Fields[SystemCreatedAt] = wi.CreatedAt
	}
	if _, ok := wiType.Fields[SystemUpdatedAt]; ok {
		result.Fields[SystemUpdatedAt] = wi.UpdatedAt
	}
	if _, ok := wiType.Fields[SystemOrder]; ok {
		result.Fields[SystemOrder] = wi.ExecutionOrder
	}
	if _, ok := wiType.Fields[SystemNumber]; ok {
		result.Fields[SystemNumber] = wi.Number
	}
	return result, nil

}
1214246
func (b *Browser) Readlink(link string) (target string, err error) {
	defer translateGitError(&err)
	fi, err := b.Lstat(link)
	if err != nil {
		return "", err
	}
	// If it's not a symlink, error right away.
	if fi.Mode()&os.ModeSymlink == 0 {
		return "", errors.New("not a symlink")
	}

	return b.readLink(link)
}
781206
func ConvertCodebase(request *http.Request, codebase codebase.Codebase, options ...CodebaseConvertFunc) *app.Codebase {
	relatedURL := rest.AbsoluteURL(request, app.CodebaseHref(codebase.ID))
	spaceRelatedURL := rest.AbsoluteURL(request, app.SpaceHref(codebase.SpaceID))
	workspacesRelatedURL := rest.AbsoluteURL(request, app.CodebaseHref(codebase.ID)+"/workspaces")

	result := &app.Codebase{
		Type: APIStringTypeCodebase,
		ID:   &codebase.ID,
		Attributes: &app.CodebaseAttributes{
			CreatedAt:         &codebase.CreatedAt,
			Type:              &codebase.Type,
			URL:               &codebase.URL,
			StackID:           codebase.StackID,
			LastUsedWorkspace: &codebase.LastUsedWorkspace,
			CveScan:           &codebase.CVEScan,
		},
		Relationships: &app.CodebaseRelations{
			Space: &app.RelationGeneric{
				Data: &app.GenericData{
					Type: ptr.String(APIStringTypeSpace),
					ID:   ptr.String(codebase.SpaceID.String()),
				},
				Links: &app.GenericLinks{
					Self:    &spaceRelatedURL,
					Related: &spaceRelatedURL,
				},
			},
			Workspaces: &app.RelationGeneric{
				Links: &app.GenericLinks{
					Self:    &workspacesRelatedURL,
					Related: &workspacesRelatedURL,
				},
			},
		},
		Links: &app.CodebaseLinks{
			Self:    &relatedURL,
			Related: &relatedURL,
			// Deprecated: use 'Workspaces' links instead
			Edit: ptr.String(rest.AbsoluteURL(request, app.CodebaseHref(codebase.ID)+"/edit")),
		},
	}
	for _, option := range options {
		option(request, codebase, result)
	}
	return result
}
320332
func newWorkItemLinkContext(ctx context.Context, service *goa.Service, appl application.Application, db application.DB, request *http.Request, responseWriter http.ResponseWriter, linkFunc hrefLinkFunc, currentUserIdentityID *uuid.UUID) *workItemLinkContext {
	return &workItemLinkContext{
		Request:               request,
		ResponseWriter:        responseWriter,
		Application:           appl,
		Context:               ctx,
		Service:               service,
		CurrentUserIdentityID: currentUserIdentityID,
		DB:       db,
		LinkFunc: linkFunc,
	}
}
565583
func NewWorkItemRelationshipsLinksController(service *goa.Service, db application.DB, config WorkItemRelationshipsLinksControllerConfig) *WorkItemRelationshipsLinksController {
	return &WorkItemRelationshipsLinksController{
		Controller: service.NewController("WorkItemRelationshipsLinksController"),
		db:         db,
		config:     config,
	}
}
24122
func convertToModel(entry Entry) (cves *models.CveDetail, err error) {
	refs := []models.Reference{}
	for _, r := range entry.References {
		ref := models.Reference{
			Source: r.Source,
			Link:   r.Link.Href,
		}
		refs = append(refs, ref)
	}

	// uncomment if you needed
	// cpes := []models.Cpe{}
	// for _, c := range entry.Products {
	// cpeBase, err := fetcher.ParseCpeURI(c)
	// if err != nil {
	// return nil, err
	// }
	// cpes = append(cpes, models.Cpe{
	// CpeBase: *cpeBase,
	// })
	// }

	cwes := []models.Cwe{}
	for _, cwe := range entry.Cwes {
		cwes = append(cwes, models.Cwe{
			CweID: cwe.ID,
		})
	}

	score := fetcher.StringToFloat(entry.Cvss.Score)

	vectorString := ""
	if entry.Cvss.AccessVector != "" {
		vectorString = fmt.Sprintf("AV:%c/AC:%c/Au:%c/C:%c/I:%c/A:%c",
			entry.Cvss.AccessVector[0],
			entry.Cvss.AccessComplexity[0],
			entry.Cvss.Authentication[0],
			entry.Cvss.ConfidentialityImpact[0],
			entry.Cvss.IntegrityImpact[0],
			entry.Cvss.AvailabilityImpact[0],
		)
	}

	return &models.CveDetail{
		CveID: entry.CveID,
		NvdXML: &models.NvdXML{
			CveID:   entry.CveID,
			Summary: entry.Summary,
			Cvss2: models.Cvss2{
				BaseScore:             score,
				Severity:              cvss2ScoreToSeverity(score),
				VectorString:          vectorString,
				AccessVector:          entry.Cvss.AccessVector,
				AccessComplexity:      entry.Cvss.AccessComplexity,
				Authentication:        entry.Cvss.Authentication,
				ConfidentialityImpact: entry.Cvss.ConfidentialityImpact,
				IntegrityImpact:       entry.Cvss.IntegrityImpact,
				AvailabilityImpact:    entry.Cvss.AvailabilityImpact,
			},
			Cwes:             cwes,
			PublishedDate:    entry.PublishedDate,
			LastModifiedDate: entry.LastModifiedDate,

			// Cpes:       cpes,
			References: refs,
		},
	}, nil
}
1244807
func (rs *ResultSpec) Link(scope Scope) (err error) {
	if rs.ReturnType != nil {
		rs.ReturnType, err = rs.ReturnType.Link(scope)
		if err != nil {
			return err
		}
	}

	if err := rs.Exceptions.Link(scope); err != nil {
		return err
	}

	// verify that everything listed under throws is an exception.
	for _, exception := range rs.Exceptions {
		spec, ok := exception.Type.(*StructSpec)
		if !ok || spec.Type != ast.ExceptionType {
			return notAnExceptionError{
				FieldName: exception.ThriftName(),
				TypeName:  spec.ThriftName(),
			}
		}
	}

	return nil
}