id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
13,100
fabric8-services/fabric8-wit
controller/deployments_osioclient.go
GetSpaceByID
func (osioclient *OSIOClient) GetSpaceByID(ctx context.Context, spaceID uuid.UUID) (*app.Space, error) { guid := goauuid.UUID(spaceID) urlpath := witclient.ShowSpacePath(guid) resp, err := osioclient.wc.ShowSpace(goasupport.ForwardContextRequestID(ctx), urlpath, nil, nil) if err != nil { return nil, errs.Wrapf(err, "could not connect to %s", urlpath) } respBody, err := osioclient.responseReader.ReadResponse(resp) status := resp.StatusCode if status == http.StatusNotFound { return nil, nil } else if status != http.StatusOK { log.Error(nil, map[string]interface{}{ "err": err, "space_id": spaceID, "path": urlpath, "http_status": status, }, "failed to get user space from WIT service due to HTTP error %s", status) return nil, errs.Errorf("failed to GET %s due to status code %d", urlpath, status) } var respType app.SpaceSingle err = json.Unmarshal(respBody, &respType) if err != nil { log.Error(nil, map[string]interface{}{ "err": err, "space_id": spaceID, "path": urlpath, "response": respBody, }, "unable to unmarshal user space from WIT service") return nil, errs.Wrap(err, "could not unmarshal SpaceSingle JSON") } return respType.Data, nil }
go
func (osioclient *OSIOClient) GetSpaceByID(ctx context.Context, spaceID uuid.UUID) (*app.Space, error) { guid := goauuid.UUID(spaceID) urlpath := witclient.ShowSpacePath(guid) resp, err := osioclient.wc.ShowSpace(goasupport.ForwardContextRequestID(ctx), urlpath, nil, nil) if err != nil { return nil, errs.Wrapf(err, "could not connect to %s", urlpath) } respBody, err := osioclient.responseReader.ReadResponse(resp) status := resp.StatusCode if status == http.StatusNotFound { return nil, nil } else if status != http.StatusOK { log.Error(nil, map[string]interface{}{ "err": err, "space_id": spaceID, "path": urlpath, "http_status": status, }, "failed to get user space from WIT service due to HTTP error %s", status) return nil, errs.Errorf("failed to GET %s due to status code %d", urlpath, status) } var respType app.SpaceSingle err = json.Unmarshal(respBody, &respType) if err != nil { log.Error(nil, map[string]interface{}{ "err": err, "space_id": spaceID, "path": urlpath, "response": respBody, }, "unable to unmarshal user space from WIT service") return nil, errs.Wrap(err, "could not unmarshal SpaceSingle JSON") } return respType.Data, nil }
[ "func", "(", "osioclient", "*", "OSIOClient", ")", "GetSpaceByID", "(", "ctx", "context", ".", "Context", ",", "spaceID", "uuid", ".", "UUID", ")", "(", "*", "app", ".", "Space", ",", "error", ")", "{", "guid", ":=", "goauuid", ".", "UUID", "(", "spa...
// GetSpaceByID - fetch space given UUID
[ "GetSpaceByID", "-", "fetch", "space", "given", "UUID" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/deployments_osioclient.go#L140-L175
13,101
fabric8-services/fabric8-wit
remoteworkitem/remoteworkitem.go
Convert
func (converter ListConverter) Convert(value interface{}, item AttributeAccessor) (interface{}, error) { if value == nil { return make([]string, 0), nil } result := make([]string, 1) result[0] = value.(string) return result, nil }
go
func (converter ListConverter) Convert(value interface{}, item AttributeAccessor) (interface{}, error) { if value == nil { return make([]string, 0), nil } result := make([]string, 1) result[0] = value.(string) return result, nil }
[ "func", "(", "converter", "ListConverter", ")", "Convert", "(", "value", "interface", "{", "}", ",", "item", "AttributeAccessor", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "value", "==", "nil", "{", "return", "make", "(", "[", "]",...
// Convert converts the given value to a list containing this single value as string
[ "Convert", "converts", "the", "given", "value", "to", "a", "list", "containing", "this", "single", "value", "as", "string" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/remoteworkitem/remoteworkitem.go#L125-L132
13,102
fabric8-services/fabric8-wit
remoteworkitem/remoteworkitem.go
Convert
func (converter PatternToListConverter) Convert(value interface{}, item AttributeAccessor) (interface{}, error) { result := []string{} i := 0 for { key := AttributeExpression(strings.Replace(converter.pattern, "?", strconv.Itoa(i), 1)) if v := item.Get(key); v != nil { result = append(result, v.(string)) } else { break } i++ } return result, nil }
go
func (converter PatternToListConverter) Convert(value interface{}, item AttributeAccessor) (interface{}, error) { result := []string{} i := 0 for { key := AttributeExpression(strings.Replace(converter.pattern, "?", strconv.Itoa(i), 1)) if v := item.Get(key); v != nil { result = append(result, v.(string)) } else { break } i++ } return result, nil }
[ "func", "(", "converter", "PatternToListConverter", ")", "Convert", "(", "value", "interface", "{", "}", ",", "item", "AttributeAccessor", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "result", ":=", "[", "]", "string", "{", "}", "\n", "i", ...
// Convert converts all fields from the given item that match this RegexpConverter's pattern, and returns an array of matching values as string
[ "Convert", "converts", "all", "fields", "from", "the", "given", "item", "that", "match", "this", "RegexpConverter", "s", "pattern", "and", "returns", "an", "array", "of", "matching", "values", "as", "string" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/remoteworkitem/remoteworkitem.go#L135-L148
13,103
fabric8-services/fabric8-wit
remoteworkitem/remoteworkitem.go
Convert
func (converter MarkupConverter) Convert(value interface{}, item AttributeAccessor) (interface{}, error) { // return a 'nil' result if the supplied 'value' was nil if value == nil { return nil, nil } switch value.(type) { case string: return rendering.NewMarkupContent(value.(string), converter.markup), nil default: return nil, errors.Errorf("Unexpected type of value to convert: %T", value) } }
go
func (converter MarkupConverter) Convert(value interface{}, item AttributeAccessor) (interface{}, error) { // return a 'nil' result if the supplied 'value' was nil if value == nil { return nil, nil } switch value.(type) { case string: return rendering.NewMarkupContent(value.(string), converter.markup), nil default: return nil, errors.Errorf("Unexpected type of value to convert: %T", value) } }
[ "func", "(", "converter", "MarkupConverter", ")", "Convert", "(", "value", "interface", "{", "}", ",", "item", "AttributeAccessor", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "// return a 'nil' result if the supplied 'value' was nil", "if", "value", ...
// Convert returns the given `value` if the `item` is not nil`, otherwise returns `nil`
[ "Convert", "returns", "the", "given", "value", "if", "the", "item", "is", "not", "nil", "otherwise", "returns", "nil" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/remoteworkitem/remoteworkitem.go#L151-L162
13,104
fabric8-services/fabric8-wit
remoteworkitem/remoteworkitem.go
NewJiraRemoteWorkItem
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 }
go
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 }
[ "func", "NewJiraRemoteWorkItem", "(", "item", "TrackerItem", ")", "(", "AttributeAccessor", ",", "error", ")", "{", "var", "j", "map", "[", "string", "]", "interface", "{", "}", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "...
// NewJiraRemoteWorkItem creates a new Decoded AttributeAccessor for a GitHub Issue
[ "NewJiraRemoteWorkItem", "creates", "a", "new", "Decoded", "AttributeAccessor", "for", "a", "GitHub", "Issue" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/remoteworkitem/remoteworkitem.go#L242-L250
13,105
fabric8-services/fabric8-wit
remoteworkitem/remoteworkitem.go
Map
func Map(remoteItem AttributeAccessor, mapping RemoteWorkItemMap) (RemoteWorkItem, error) { remoteWorkItem := RemoteWorkItem{Fields: make(map[string]interface{})} for from, to := range mapping { originalValue := remoteItem.Get(from.Expression) convertedValue, err := from.AttributeConverter.Convert(originalValue, remoteItem) if err == nil { remoteWorkItem.Fields[to] = convertedValue } } return remoteWorkItem, nil }
go
func Map(remoteItem AttributeAccessor, mapping RemoteWorkItemMap) (RemoteWorkItem, error) { remoteWorkItem := RemoteWorkItem{Fields: make(map[string]interface{})} for from, to := range mapping { originalValue := remoteItem.Get(from.Expression) convertedValue, err := from.AttributeConverter.Convert(originalValue, remoteItem) if err == nil { remoteWorkItem.Fields[to] = convertedValue } } return remoteWorkItem, nil }
[ "func", "Map", "(", "remoteItem", "AttributeAccessor", ",", "mapping", "RemoteWorkItemMap", ")", "(", "RemoteWorkItem", ",", "error", ")", "{", "remoteWorkItem", ":=", "RemoteWorkItem", "{", "Fields", ":", "make", "(", "map", "[", "string", "]", "interface", "...
// Map maps the remote WorkItem to a local RemoteWorkItem
[ "Map", "maps", "the", "remote", "WorkItem", "to", "a", "local", "RemoteWorkItem" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/remoteworkitem/remoteworkitem.go#L258-L268
13,106
fabric8-services/fabric8-wit
goasupport/jsonapi_errors_stringer/generator.go
Generate
func Generate() ([]string, error) { var ( ver string outDir string ) set := flag.NewFlagSet("app", flag.PanicOnError) set.String("design", "", "") // Consume design argument so Parse doesn't complain set.StringVar(&ver, "version", "", "") set.StringVar(&outDir, "out", "", "") set.Parse(os.Args[2:]) // First check compatibility if err := codegen.CheckVersion(ver); err != nil { return nil, err } return writeFunctions(design.Design, outDir) }
go
func Generate() ([]string, error) { var ( ver string outDir string ) set := flag.NewFlagSet("app", flag.PanicOnError) set.String("design", "", "") // Consume design argument so Parse doesn't complain set.StringVar(&ver, "version", "", "") set.StringVar(&outDir, "out", "", "") set.Parse(os.Args[2:]) // First check compatibility if err := codegen.CheckVersion(ver); err != nil { return nil, err } return writeFunctions(design.Design, outDir) }
[ "func", "Generate", "(", ")", "(", "[", "]", "string", ",", "error", ")", "{", "var", "(", "ver", "string", "\n", "outDir", "string", "\n", ")", "\n", "set", ":=", "flag", ".", "NewFlagSet", "(", "\"", "\"", ",", "flag", ".", "PanicOnError", ")", ...
// Generate adds method to support conditional queries
[ "Generate", "adds", "method", "to", "support", "conditional", "queries" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/goasupport/jsonapi_errors_stringer/generator.go#L14-L29
13,107
fabric8-services/fabric8-wit
configuration/http_option.go
WithRoundTripper
func WithRoundTripper(r http.RoundTripper) HTTPClientOption { return func(client *http.Client) { client.Transport = r } }
go
func WithRoundTripper(r http.RoundTripper) HTTPClientOption { return func(client *http.Client) { client.Transport = r } }
[ "func", "WithRoundTripper", "(", "r", "http", ".", "RoundTripper", ")", "HTTPClientOption", "{", "return", "func", "(", "client", "*", "http", ".", "Client", ")", "{", "client", ".", "Transport", "=", "r", "\n", "}", "\n", "}" ]
// WithRoundTripper configures the client's transport with the given round-tripper
[ "WithRoundTripper", "configures", "the", "client", "s", "transport", "with", "the", "given", "round", "-", "tripper" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/configuration/http_option.go#L11-L15
13,108
fabric8-services/fabric8-wit
space/space.go
Equal
func (p Space) Equal(u convert.Equaler) bool { other, ok := u.(Space) if !ok { return false } if !p.Lifecycle.Equal(other.Lifecycle) { return false } if p.ID != other.ID { return false } if p.Version != other.Version { return false } if p.Name != other.Name { return false } if !uuid.Equal(p.SpaceTemplateID, other.SpaceTemplateID) { return false } if p.Description != other.Description { return false } if !uuid.Equal(p.OwnerID, other.OwnerID) { return false } return true }
go
func (p Space) Equal(u convert.Equaler) bool { other, ok := u.(Space) if !ok { return false } if !p.Lifecycle.Equal(other.Lifecycle) { return false } if p.ID != other.ID { return false } if p.Version != other.Version { return false } if p.Name != other.Name { return false } if !uuid.Equal(p.SpaceTemplateID, other.SpaceTemplateID) { return false } if p.Description != other.Description { return false } if !uuid.Equal(p.OwnerID, other.OwnerID) { return false } return true }
[ "func", "(", "p", "Space", ")", "Equal", "(", "u", "convert", ".", "Equaler", ")", "bool", "{", "other", ",", "ok", ":=", "u", ".", "(", "Space", ")", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n", "if", "!", "p", ".", "Lifec...
// Equal returns true if two Space objects are equal; otherwise false is returned.
[ "Equal", "returns", "true", "if", "two", "Space", "objects", "are", "equal", ";", "otherwise", "false", "is", "returned", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/space/space.go#L49-L76
13,109
fabric8-services/fabric8-wit
space/space.go
NewRepository
func NewRepository(db *gorm.DB) *GormRepository { return &GormRepository{ db: db, winr: numbersequence.NewWorkItemNumberSequenceRepository(db), } }
go
func NewRepository(db *gorm.DB) *GormRepository { return &GormRepository{ db: db, winr: numbersequence.NewWorkItemNumberSequenceRepository(db), } }
[ "func", "NewRepository", "(", "db", "*", "gorm", ".", "DB", ")", "*", "GormRepository", "{", "return", "&", "GormRepository", "{", "db", ":", "db", ",", "winr", ":", "numbersequence", ".", "NewWorkItemNumberSequenceRepository", "(", "db", ")", ",", "}", "\...
// NewRepository creates a new space repo
[ "NewRepository", "creates", "a", "new", "space", "repo" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/space/space.go#L121-L126
13,110
fabric8-services/fabric8-wit
space/space.go
LoadMany
func (r *GormRepository) LoadMany(ctx context.Context, IDs []uuid.UUID) ([]Space, error) { defer goa.MeasureSince([]string{"goa", "db", "space", "loadMany"}, time.Now()) // no need to run the query if the list of IDs is empty :) var result []Space if len(IDs) == 0 { return result, nil } strIDs := make([]string, len(IDs)) for i, ID := range IDs { strIDs[i] = fmt.Sprintf("'%s'", ID.String()) } db := r.db.Model(Space{}).Select("distinct *").Where(fmt.Sprintf("ID in (%s)", strings.Join(strIDs, ", "))) rows, err := db.Rows() defer closeable.Close(ctx, rows) if err != nil { log.Error(ctx, map[string]interface{}{ "err": err.Error(), }, "unable to load multiple spaces by their IDs") return nil, errors.NewInternalError(ctx, err) } // scan the results for rows.Next() { s := Space{} err := db.ScanRows(rows, &s) if err != nil { log.Error(ctx, map[string]interface{}{ "err": err.Error(), }, "unable to load space") return nil, errors.NewInternalError(ctx, err) } result = append(result, s) } log.Debug(ctx, map[string]interface{}{ "count": len(result), "spaces": result, }, "loaded multiple spaces by their IDs") return result, nil }
go
func (r *GormRepository) LoadMany(ctx context.Context, IDs []uuid.UUID) ([]Space, error) { defer goa.MeasureSince([]string{"goa", "db", "space", "loadMany"}, time.Now()) // no need to run the query if the list of IDs is empty :) var result []Space if len(IDs) == 0 { return result, nil } strIDs := make([]string, len(IDs)) for i, ID := range IDs { strIDs[i] = fmt.Sprintf("'%s'", ID.String()) } db := r.db.Model(Space{}).Select("distinct *").Where(fmt.Sprintf("ID in (%s)", strings.Join(strIDs, ", "))) rows, err := db.Rows() defer closeable.Close(ctx, rows) if err != nil { log.Error(ctx, map[string]interface{}{ "err": err.Error(), }, "unable to load multiple spaces by their IDs") return nil, errors.NewInternalError(ctx, err) } // scan the results for rows.Next() { s := Space{} err := db.ScanRows(rows, &s) if err != nil { log.Error(ctx, map[string]interface{}{ "err": err.Error(), }, "unable to load space") return nil, errors.NewInternalError(ctx, err) } result = append(result, s) } log.Debug(ctx, map[string]interface{}{ "count": len(result), "spaces": result, }, "loaded multiple spaces by their IDs") return result, nil }
[ "func", "(", "r", "*", "GormRepository", ")", "LoadMany", "(", "ctx", "context", ".", "Context", ",", "IDs", "[", "]", "uuid", ".", "UUID", ")", "(", "[", "]", "Space", ",", "error", ")", "{", "defer", "goa", ".", "MeasureSince", "(", "[", "]", "...
// LoadMany returns the spaces for the given IDs // returns NotFoundError or InternalError
[ "LoadMany", "returns", "the", "spaces", "for", "the", "given", "IDs", "returns", "NotFoundError", "or", "InternalError" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/space/space.go#L158-L196
13,111
fabric8-services/fabric8-wit
space/space.go
Save
func (r *GormRepository) Save(ctx context.Context, p *Space) (*Space, error) { defer goa.MeasureSince([]string{"goa", "db", "space", "save"}, time.Now()) pr := Space{} tx := r.db.Where("id=?", p.ID).First(&pr) oldVersion := p.Version p.Version++ if tx.RecordNotFound() { // treating this as a not found error: the fact that we're using number internal is implementation detail return nil, errors.NewNotFoundError("space", p.ID.String()) } if err := tx.Error; err != nil { log.Error(ctx, map[string]interface{}{ "err": tx.Error, "space_id": p.ID, }, "unable to find the space by ID") return nil, errors.NewInternalError(ctx, err) } tx = tx.Where("Version = ?", oldVersion).Save(p) if err := tx.Error; err != nil { if gormsupport.IsCheckViolation(tx.Error, "spaces_name_check") { return nil, errors.NewBadParameterError("Name", p.Name).Expected("not empty") } if gormsupport.IsUniqueViolation(tx.Error, "spaces_name_idx") { return nil, errors.NewBadParameterError("Name", p.Name).Expected("unique") } log.Error(ctx, map[string]interface{}{ "err": err, "version": oldVersion, "space_id": p.ID, }, "unable to find the space by version") return nil, errors.NewInternalError(ctx, err) } if tx.RowsAffected == 0 { return nil, errors.NewVersionConflictError("version conflict") } log.Info(ctx, map[string]interface{}{ "space_id": p.ID, }, "space updated successfully") return p, nil }
go
func (r *GormRepository) Save(ctx context.Context, p *Space) (*Space, error) { defer goa.MeasureSince([]string{"goa", "db", "space", "save"}, time.Now()) pr := Space{} tx := r.db.Where("id=?", p.ID).First(&pr) oldVersion := p.Version p.Version++ if tx.RecordNotFound() { // treating this as a not found error: the fact that we're using number internal is implementation detail return nil, errors.NewNotFoundError("space", p.ID.String()) } if err := tx.Error; err != nil { log.Error(ctx, map[string]interface{}{ "err": tx.Error, "space_id": p.ID, }, "unable to find the space by ID") return nil, errors.NewInternalError(ctx, err) } tx = tx.Where("Version = ?", oldVersion).Save(p) if err := tx.Error; err != nil { if gormsupport.IsCheckViolation(tx.Error, "spaces_name_check") { return nil, errors.NewBadParameterError("Name", p.Name).Expected("not empty") } if gormsupport.IsUniqueViolation(tx.Error, "spaces_name_idx") { return nil, errors.NewBadParameterError("Name", p.Name).Expected("unique") } log.Error(ctx, map[string]interface{}{ "err": err, "version": oldVersion, "space_id": p.ID, }, "unable to find the space by version") return nil, errors.NewInternalError(ctx, err) } if tx.RowsAffected == 0 { return nil, errors.NewVersionConflictError("version conflict") } log.Info(ctx, map[string]interface{}{ "space_id": p.ID, }, "space updated successfully") return p, nil }
[ "func", "(", "r", "*", "GormRepository", ")", "Save", "(", "ctx", "context", ".", "Context", ",", "p", "*", "Space", ")", "(", "*", "Space", ",", "error", ")", "{", "defer", "goa", ".", "MeasureSince", "(", "[", "]", "string", "{", "\"", "\"", ",...
// Save updates the given space in the db. Version must be the same as the one in the stored version // returns NotFoundError, BadParameterError, VersionConflictError or InternalError
[ "Save", "updates", "the", "given", "space", "in", "the", "db", ".", "Version", "must", "be", "the", "same", "as", "the", "one", "in", "the", "stored", "version", "returns", "NotFoundError", "BadParameterError", "VersionConflictError", "or", "InternalError" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/space/space.go#L235-L275
13,112
fabric8-services/fabric8-wit
space/space.go
Create
func (r *GormRepository) Create(ctx context.Context, space *Space) (*Space, error) { defer goa.MeasureSince([]string{"goa", "db", "space", "create"}, time.Now()) // We might want to create a space with a specific ID, e.g. space.SystemSpace if space.ID == uuid.Nil { space.ID = uuid.NewV4() } // Check if the used space template can create spaces spaceTemplateRepo := spacetemplate.NewRepository(r.db) templ, err := spaceTemplateRepo.Load(ctx, space.SpaceTemplateID) if err != nil { return nil, errors.NewNotFoundError("space template", space.SpaceTemplateID.String()) } if !templ.CanConstruct { return nil, errors.NewForbiddenError(fmt.Sprintf("space template %q (ID: %s) cannot create spaces", templ.Name, templ.ID)) } tx := r.db.Create(space) if err := tx.Error; err != nil { if gormsupport.IsCheckViolation(tx.Error, "spaces_name_check") { return nil, errors.NewBadParameterError("Name", space.Name).Expected("not empty") } if gormsupport.IsUniqueViolation(tx.Error, "spaces_name_idx") { log.Error(ctx, map[string]interface{}{ "err": err, "space_name": space.Name, }, "unable to create space because a space with the same name already exists for this user") return nil, errors.NewDataConflictError(fmt.Sprintf("space already exists ( for this user ) : %s ", space.Name)) } return nil, errors.NewInternalError(ctx, err) } log.Debug(ctx, map[string]interface{}{ "space_id": space.ID, }, "Space created") return space, nil }
go
func (r *GormRepository) Create(ctx context.Context, space *Space) (*Space, error) { defer goa.MeasureSince([]string{"goa", "db", "space", "create"}, time.Now()) // We might want to create a space with a specific ID, e.g. space.SystemSpace if space.ID == uuid.Nil { space.ID = uuid.NewV4() } // Check if the used space template can create spaces spaceTemplateRepo := spacetemplate.NewRepository(r.db) templ, err := spaceTemplateRepo.Load(ctx, space.SpaceTemplateID) if err != nil { return nil, errors.NewNotFoundError("space template", space.SpaceTemplateID.String()) } if !templ.CanConstruct { return nil, errors.NewForbiddenError(fmt.Sprintf("space template %q (ID: %s) cannot create spaces", templ.Name, templ.ID)) } tx := r.db.Create(space) if err := tx.Error; err != nil { if gormsupport.IsCheckViolation(tx.Error, "spaces_name_check") { return nil, errors.NewBadParameterError("Name", space.Name).Expected("not empty") } if gormsupport.IsUniqueViolation(tx.Error, "spaces_name_idx") { log.Error(ctx, map[string]interface{}{ "err": err, "space_name": space.Name, }, "unable to create space because a space with the same name already exists for this user") return nil, errors.NewDataConflictError(fmt.Sprintf("space already exists ( for this user ) : %s ", space.Name)) } return nil, errors.NewInternalError(ctx, err) } log.Debug(ctx, map[string]interface{}{ "space_id": space.ID, }, "Space created") return space, nil }
[ "func", "(", "r", "*", "GormRepository", ")", "Create", "(", "ctx", "context", ".", "Context", ",", "space", "*", "Space", ")", "(", "*", "Space", ",", "error", ")", "{", "defer", "goa", ".", "MeasureSince", "(", "[", "]", "string", "{", "\"", "\""...
// Create creates a new Space in the db // returns BadParameterError or InternalError
[ "Create", "creates", "a", "new", "Space", "in", "the", "db", "returns", "BadParameterError", "or", "InternalError" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/space/space.go#L279-L314
13,113
fabric8-services/fabric8-wit
numbersequence/human_friendly_number.go
Equal
func (n HumanFriendlyNumber) Equal(u convert.Equaler) bool { other, ok := u.(HumanFriendlyNumber) if !ok { return false } if n.Number != other.Number { return false } if n.spaceID != other.spaceID { return false } if n.tableName != other.tableName { return false } return true }
go
func (n HumanFriendlyNumber) Equal(u convert.Equaler) bool { other, ok := u.(HumanFriendlyNumber) if !ok { return false } if n.Number != other.Number { return false } if n.spaceID != other.spaceID { return false } if n.tableName != other.tableName { return false } return true }
[ "func", "(", "n", "HumanFriendlyNumber", ")", "Equal", "(", "u", "convert", ".", "Equaler", ")", "bool", "{", "other", ",", "ok", ":=", "u", ".", "(", "HumanFriendlyNumber", ")", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n", "if", ...
// Equal implements convert.Equaler
[ "Equal", "implements", "convert", ".", "Equaler" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/numbersequence/human_friendly_number.go#L43-L58
13,114
fabric8-services/fabric8-wit
workitem/event/event.go
FilterByRevisionID
func (l List) FilterByRevisionID(revisionID uuid.UUID) List { res := List{} for _, x := range l { if x.RevisionID == revisionID { res = append(res, x) } } return res }
go
func (l List) FilterByRevisionID(revisionID uuid.UUID) List { res := List{} for _, x := range l { if x.RevisionID == revisionID { res = append(res, x) } } return res }
[ "func", "(", "l", "List", ")", "FilterByRevisionID", "(", "revisionID", "uuid", ".", "UUID", ")", "List", "{", "res", ":=", "List", "{", "}", "\n", "for", "_", ",", "x", ":=", "range", "l", "{", "if", "x", ".", "RevisionID", "==", "revisionID", "{"...
// FilterByRevisionID returns a new list with just the events inside that match // the given revision ID.
[ "FilterByRevisionID", "returns", "a", "new", "list", "with", "just", "the", "events", "inside", "that", "match", "the", "given", "revision", "ID", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/workitem/event/event.go#L36-L44
13,115
fabric8-services/fabric8-wit
convert/equaler.go
Equal
func (d DummyEqualer) Equal(u Equaler) bool { _, ok := u.(DummyEqualer) return ok }
go
func (d DummyEqualer) Equal(u Equaler) bool { _, ok := u.(DummyEqualer) return ok }
[ "func", "(", "d", "DummyEqualer", ")", "Equal", "(", "u", "Equaler", ")", "bool", "{", "_", ",", "ok", ":=", "u", ".", "(", "DummyEqualer", ")", "\n", "return", "ok", "\n", "}" ]
// Equal implements Equaler
[ "Equal", "implements", "Equaler" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/convert/equaler.go#L57-L60
13,116
fabric8-services/fabric8-wit
convert/equaler.go
EqualValue
func (d DummyEqualer) EqualValue(u Equaler) bool { _, ok := u.(DummyEqualer) return ok }
go
func (d DummyEqualer) EqualValue(u Equaler) bool { _, ok := u.(DummyEqualer) return ok }
[ "func", "(", "d", "DummyEqualer", ")", "EqualValue", "(", "u", "Equaler", ")", "bool", "{", "_", ",", "ok", ":=", "u", ".", "(", "DummyEqualer", ")", "\n", "return", "ok", "\n", "}" ]
// EqualValue implements Equaler
[ "EqualValue", "implements", "Equaler" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/convert/equaler.go#L63-L66
13,117
fabric8-services/fabric8-wit
workitem/table_join.go
Validate
func (j TableJoin) Validate(db *gorm.DB) error { dialect := db.Dialect() dialect.SetDB(db.CommonDB()) if j.Active { for _, f := range j.HandledFields { var allowed bool for _, allowedColumn := range j.AllowedColumns { if allowedColumn == f { allowed = true } } if !allowed { if !dialect.HasColumn(j.TableName, f) { return errs.Errorf(`table "%s" has no column "%s"`, j.TableName, f) } } } } return nil }
go
func (j TableJoin) Validate(db *gorm.DB) error { dialect := db.Dialect() dialect.SetDB(db.CommonDB()) if j.Active { for _, f := range j.HandledFields { var allowed bool for _, allowedColumn := range j.AllowedColumns { if allowedColumn == f { allowed = true } } if !allowed { if !dialect.HasColumn(j.TableName, f) { return errs.Errorf(`table "%s" has no column "%s"`, j.TableName, f) } } } } return nil }
[ "func", "(", "j", "TableJoin", ")", "Validate", "(", "db", "*", "gorm", ".", "DB", ")", "error", "{", "dialect", ":=", "db", ".", "Dialect", "(", ")", "\n", "dialect", ".", "SetDB", "(", "db", ".", "CommonDB", "(", ")", ")", "\n", "if", "j", "....
// Validate returns nil if the join is active and all the fields handled by this // join do exist in the joined table; otherwise an error is returned.
[ "Validate", "returns", "nil", "if", "the", "join", "is", "active", "and", "all", "the", "fields", "handled", "by", "this", "join", "do", "exist", "in", "the", "joined", "table", ";", "otherwise", "an", "error", "is", "returned", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/workitem/table_join.go#L75-L94
13,118
fabric8-services/fabric8-wit
workitem/table_join.go
JoinOnJSONField
func JoinOnJSONField(jsonField, foreignCol string) string { return fmt.Sprintf(`%[1]s @> concat('{"%[2]s": "', %[3]s, '"}')::jsonb`, Column(WorkItemStorage{}.TableName(), "fields"), jsonField, foreignCol) }
go
func JoinOnJSONField(jsonField, foreignCol string) string { return fmt.Sprintf(`%[1]s @> concat('{"%[2]s": "', %[3]s, '"}')::jsonb`, Column(WorkItemStorage{}.TableName(), "fields"), jsonField, foreignCol) }
[ "func", "JoinOnJSONField", "(", "jsonField", ",", "foreignCol", "string", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "`%[1]s @> concat('{\"%[2]s\": \"', %[3]s, '\"}')::jsonb`", ",", "Column", "(", "WorkItemStorage", "{", "}", ".", "TableName", "(", ")...
// JoinOnJSONField returns the ON part of an SQL JOIN for the given fields
[ "JoinOnJSONField", "returns", "the", "ON", "part", "of", "an", "SQL", "JOIN", "for", "the", "given", "fields" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/workitem/table_join.go#L97-L99
13,119
fabric8-services/fabric8-wit
workitem/table_join.go
GetJoinExpression
func (j TableJoin) GetJoinExpression() string { return fmt.Sprintf(`LEFT JOIN %s "%s" ON %s`, j.TableName, j.TableAlias, j.On) }
go
func (j TableJoin) GetJoinExpression() string { return fmt.Sprintf(`LEFT JOIN %s "%s" ON %s`, j.TableName, j.TableAlias, j.On) }
[ "func", "(", "j", "TableJoin", ")", "GetJoinExpression", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "`LEFT JOIN %s \"%s\" ON %s`", ",", "j", ".", "TableName", ",", "j", ".", "TableAlias", ",", "j", ".", "On", ")", "\n", "}" ]
// GetJoinExpression returns the SQL JOIN expression for this table join.
[ "GetJoinExpression", "returns", "the", "SQL", "JOIN", "expression", "for", "this", "table", "join", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/workitem/table_join.go#L102-L104
13,120
fabric8-services/fabric8-wit
workitem/table_join.go
HandlesFieldName
func (j *TableJoin) HandlesFieldName(fieldName string) bool { for _, t := range j.PrefixActivators { if strings.HasPrefix(fieldName, t) { return true } } return false }
go
func (j *TableJoin) HandlesFieldName(fieldName string) bool { for _, t := range j.PrefixActivators { if strings.HasPrefix(fieldName, t) { return true } } return false }
[ "func", "(", "j", "*", "TableJoin", ")", "HandlesFieldName", "(", "fieldName", "string", ")", "bool", "{", "for", "_", ",", "t", ":=", "range", "j", ".", "PrefixActivators", "{", "if", "strings", ".", "HasPrefix", "(", "fieldName", ",", "t", ")", "{", ...
// HandlesFieldName returns true if the given field name should be handled by // this table join.
[ "HandlesFieldName", "returns", "true", "if", "the", "given", "field", "name", "should", "be", "handled", "by", "this", "table", "join", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/workitem/table_join.go#L108-L115
13,121
fabric8-services/fabric8-wit
workitem/table_join.go
TranslateFieldName
func (j *TableJoin) TranslateFieldName(fieldName string) (string, error) { if !j.HandlesFieldName(fieldName) { return "", errs.Errorf(`field name "%s" not handled by this table join`, fieldName) } // Ensure this join is active j.Active = true var prefix string for _, t := range j.PrefixActivators { if strings.HasPrefix(fieldName, t) { prefix = t break } } col := strings.TrimPrefix(fieldName, prefix) col = strings.TrimSpace(col) if col == "" { return "", errs.Errorf(`field name "%s" contains an empty column name after prefix "%s"`, fieldName, prefix) } if strings.Contains(col, "'") { // beware of injection, it's a reasonable restriction for field names, // make sure it's not allowed when creating wi types return "", errs.Errorf(`single quote not allowed in field name: "%s"`, col) } // now we have the final column name // Check if this field should be handled by another one table join delegator := j for prefix, dele := range j.DelegateTo { if strings.HasPrefix(fieldName, prefix) { if dele == nil { return "", errs.Errorf(`delegated join "%s" for field "%s" must not point to nil`, prefix, fieldName) } delegator = dele // ensure the other join is active (just to be safe) if it // wasn't activated yet. delegator.Active = true break } } // if no columns are explicitly allowed, then this column is allowed by // default. columnIsAllowed := (delegator.AllowedColumns == nil || len(delegator.AllowedColumns) == 0) for _, c := range delegator.AllowedColumns { if c == col { columnIsAllowed = true break } } // check if a column is explicitly disallowed for _, c := range delegator.DisallowedColumns { if c == col { columnIsAllowed = false break } } if !columnIsAllowed { return "", errs.Errorf("column is not allowed: %s", col) } // Remember what foreign columns where queried for. Later we can use // Validate() to see if those columns do exist or not. delegator.HandledFields = append(delegator.HandledFields, col) return Column(delegator.TableAlias, col), nil }
go
func (j *TableJoin) TranslateFieldName(fieldName string) (string, error) { if !j.HandlesFieldName(fieldName) { return "", errs.Errorf(`field name "%s" not handled by this table join`, fieldName) } // Ensure this join is active j.Active = true var prefix string for _, t := range j.PrefixActivators { if strings.HasPrefix(fieldName, t) { prefix = t break } } col := strings.TrimPrefix(fieldName, prefix) col = strings.TrimSpace(col) if col == "" { return "", errs.Errorf(`field name "%s" contains an empty column name after prefix "%s"`, fieldName, prefix) } if strings.Contains(col, "'") { // beware of injection, it's a reasonable restriction for field names, // make sure it's not allowed when creating wi types return "", errs.Errorf(`single quote not allowed in field name: "%s"`, col) } // now we have the final column name // Check if this field should be handled by another one table join delegator := j for prefix, dele := range j.DelegateTo { if strings.HasPrefix(fieldName, prefix) { if dele == nil { return "", errs.Errorf(`delegated join "%s" for field "%s" must not point to nil`, prefix, fieldName) } delegator = dele // ensure the other join is active (just to be safe) if it // wasn't activated yet. delegator.Active = true break } } // if no columns are explicitly allowed, then this column is allowed by // default. columnIsAllowed := (delegator.AllowedColumns == nil || len(delegator.AllowedColumns) == 0) for _, c := range delegator.AllowedColumns { if c == col { columnIsAllowed = true break } } // check if a column is explicitly disallowed for _, c := range delegator.DisallowedColumns { if c == col { columnIsAllowed = false break } } if !columnIsAllowed { return "", errs.Errorf("column is not allowed: %s", col) } // Remember what foreign columns where queried for. Later we can use // Validate() to see if those columns do exist or not. delegator.HandledFields = append(delegator.HandledFields, col) return Column(delegator.TableAlias, col), nil }
[ "func", "(", "j", "*", "TableJoin", ")", "TranslateFieldName", "(", "fieldName", "string", ")", "(", "string", ",", "error", ")", "{", "if", "!", "j", ".", "HandlesFieldName", "(", "fieldName", ")", "{", "return", "\"", "\"", ",", "errs", ".", "Errorf"...
// TranslateFieldName returns a non-empty string if the given field name has the // prefix specified by the table join and if the field is allowed to be queried; // otherwise it returns an empty string.
[ "TranslateFieldName", "returns", "a", "non", "-", "empty", "string", "if", "the", "given", "field", "name", "has", "the", "prefix", "specified", "by", "the", "table", "join", "and", "if", "the", "field", "is", "allowed", "to", "be", "queried", ";", "otherw...
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/workitem/table_join.go#L120-L188
13,122
fabric8-services/fabric8-wit
workitem/table_join.go
ActivateRequiredJoins
func (joins *TableJoinMap) ActivateRequiredJoins() error { for k, join := range *joins { if !join.Active { continue } for _, name := range join.ActivateOtherJoins { other, exists := (*joins)[name] if !exists { return errs.Errorf(`join "%s" not found for "%s" join`, name, k) } // Check if dependend join is already active if other.Active { continue } other.Active = true if err := joins.ActivateRequiredJoins(); err != nil { return errs.Wrapf(err, `failed to activate required joins for "%s" join`, k) } } } return nil }
go
func (joins *TableJoinMap) ActivateRequiredJoins() error { for k, join := range *joins { if !join.Active { continue } for _, name := range join.ActivateOtherJoins { other, exists := (*joins)[name] if !exists { return errs.Errorf(`join "%s" not found for "%s" join`, name, k) } // Check if dependend join is already active if other.Active { continue } other.Active = true if err := joins.ActivateRequiredJoins(); err != nil { return errs.Wrapf(err, `failed to activate required joins for "%s" join`, k) } } } return nil }
[ "func", "(", "joins", "*", "TableJoinMap", ")", "ActivateRequiredJoins", "(", ")", "error", "{", "for", "k", ",", "join", ":=", "range", "*", "joins", "{", "if", "!", "join", ".", "Active", "{", "continue", "\n", "}", "\n\n", "for", "_", ",", "name",...
// ActivateRequiredJoins recursively walks over all given joins potentially // multiple times and activates all other required joins.
[ "ActivateRequiredJoins", "recursively", "walks", "over", "all", "given", "joins", "potentially", "multiple", "times", "and", "activates", "all", "other", "required", "joins", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/workitem/table_join.go#L195-L219
13,123
fabric8-services/fabric8-wit
workitem/table_join.go
GetOrderdActivatedJoins
func (joins *TableJoinMap) GetOrderdActivatedJoins() ([]*TableJoin, error) { if err := joins.ActivateRequiredJoins(); err != nil { return nil, errs.Wrap(err, "failed to get activate required joins") } orderer := activationOrderer{ m: *joins, alreadyVisited: map[*TableJoin]struct{}{}, } for name := range *joins { if err := orderer.visitDepthFirst(name); err != nil { return nil, errs.Wrapf(err, `failed to visit "%s" join`, name) } } return orderer.orderedActivatedJoins, nil }
go
func (joins *TableJoinMap) GetOrderdActivatedJoins() ([]*TableJoin, error) { if err := joins.ActivateRequiredJoins(); err != nil { return nil, errs.Wrap(err, "failed to get activate required joins") } orderer := activationOrderer{ m: *joins, alreadyVisited: map[*TableJoin]struct{}{}, } for name := range *joins { if err := orderer.visitDepthFirst(name); err != nil { return nil, errs.Wrapf(err, `failed to visit "%s" join`, name) } } return orderer.orderedActivatedJoins, nil }
[ "func", "(", "joins", "*", "TableJoinMap", ")", "GetOrderdActivatedJoins", "(", ")", "(", "[", "]", "*", "TableJoin", ",", "error", ")", "{", "if", "err", ":=", "joins", ".", "ActivateRequiredJoins", "(", ")", ";", "err", "!=", "nil", "{", "return", "n...
// GetOrderdActivatedJoins returns a slice of activated joins in a proper order, // beginning with the join that activates no other join, and ending with the // join that activates another join but isn't activated by another join itself.
[ "GetOrderdActivatedJoins", "returns", "a", "slice", "of", "activated", "joins", "in", "a", "proper", "order", "beginning", "with", "the", "join", "that", "activates", "no", "other", "join", "and", "ending", "with", "the", "join", "that", "activates", "another", ...
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/workitem/table_join.go#L224-L240
13,124
fabric8-services/fabric8-wit
workitem/typegroup_repository.go
Load
func (r *GormWorkItemTypeGroupRepository) Load(ctx context.Context, groupID uuid.UUID) (*WorkItemTypeGroup, error) { defer goa.MeasureSince([]string{"goa", "db", "workitemtypegroup", "load"}, time.Now()) log.Debug(ctx, map[string]interface{}{"witg_id": groupID}, "loading work item type group ") res := WorkItemTypeGroup{} db := r.db.Model(&res).Where("id=?", groupID).First(&res) if db.RecordNotFound() { log.Error(ctx, map[string]interface{}{"witg_id": groupID}, "work item type group not found") return nil, errors.NewNotFoundError("work item type group", groupID.String()) } if err := db.Error; err != nil { return nil, errors.NewInternalError(ctx, err) } typeList, err := r.loadTypeList(ctx, res.ID) if err != nil { return nil, errs.WithStack(err) } res.TypeList = typeList return &res, nil }
go
func (r *GormWorkItemTypeGroupRepository) Load(ctx context.Context, groupID uuid.UUID) (*WorkItemTypeGroup, error) { defer goa.MeasureSince([]string{"goa", "db", "workitemtypegroup", "load"}, time.Now()) log.Debug(ctx, map[string]interface{}{"witg_id": groupID}, "loading work item type group ") res := WorkItemTypeGroup{} db := r.db.Model(&res).Where("id=?", groupID).First(&res) if db.RecordNotFound() { log.Error(ctx, map[string]interface{}{"witg_id": groupID}, "work item type group not found") return nil, errors.NewNotFoundError("work item type group", groupID.String()) } if err := db.Error; err != nil { return nil, errors.NewInternalError(ctx, err) } typeList, err := r.loadTypeList(ctx, res.ID) if err != nil { return nil, errs.WithStack(err) } res.TypeList = typeList return &res, nil }
[ "func", "(", "r", "*", "GormWorkItemTypeGroupRepository", ")", "Load", "(", "ctx", "context", ".", "Context", ",", "groupID", "uuid", ".", "UUID", ")", "(", "*", "WorkItemTypeGroup", ",", "error", ")", "{", "defer", "goa", ".", "MeasureSince", "(", "[", ...
// Load returns the work item type group for the given id
[ "Load", "returns", "the", "work", "item", "type", "group", "for", "the", "given", "id" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/workitem/typegroup_repository.go#L40-L58
13,125
fabric8-services/fabric8-wit
workitem/typegroup_repository.go
loadTypeList
func (r *GormWorkItemTypeGroupRepository) loadTypeList(ctx context.Context, groupID uuid.UUID) ([]uuid.UUID, error) { members := []typeGroupMember{} db := r.db.Model(&members).Where("type_group_id=?", groupID).Order("position ASC").Find(&members) if db.RecordNotFound() { log.Error(ctx, map[string]interface{}{"witg_id": groupID}, "work item type group members not found") return nil, errors.NewNotFoundError("work item type group members of group", groupID.String()) } if err := db.Error; err != nil { return nil, errors.NewInternalError(ctx, err) } res := make([]uuid.UUID, len(members)) for i, member := range members { res[i] = member.WorkItemTypeID } return res, nil }
go
func (r *GormWorkItemTypeGroupRepository) loadTypeList(ctx context.Context, groupID uuid.UUID) ([]uuid.UUID, error) { members := []typeGroupMember{} db := r.db.Model(&members).Where("type_group_id=?", groupID).Order("position ASC").Find(&members) if db.RecordNotFound() { log.Error(ctx, map[string]interface{}{"witg_id": groupID}, "work item type group members not found") return nil, errors.NewNotFoundError("work item type group members of group", groupID.String()) } if err := db.Error; err != nil { return nil, errors.NewInternalError(ctx, err) } res := make([]uuid.UUID, len(members)) for i, member := range members { res[i] = member.WorkItemTypeID } return res, nil }
[ "func", "(", "r", "*", "GormWorkItemTypeGroupRepository", ")", "loadTypeList", "(", "ctx", "context", ".", "Context", ",", "groupID", "uuid", ".", "UUID", ")", "(", "[", "]", "uuid", ".", "UUID", ",", "error", ")", "{", "members", ":=", "[", "]", "type...
// loadTypeList loads all work item type associated with the given group and
[ "loadTypeList", "loads", "all", "work", "item", "type", "associated", "with", "the", "given", "group", "and" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/workitem/typegroup_repository.go#L61-L76
13,126
fabric8-services/fabric8-wit
workitem/typegroup_repository.go
List
func (r *GormWorkItemTypeGroupRepository) List(ctx context.Context, spaceTemplateID uuid.UUID) ([]*WorkItemTypeGroup, error) { defer goa.MeasureSince([]string{"goa", "db", "workitemtypegroup", "list"}, time.Now()) log.Debug(ctx, map[string]interface{}{"space_template_id": spaceTemplateID}, "loading work item type groups for space template") // check space template exists if err := spacetemplate.NewRepository(r.db).CheckExists(ctx, spaceTemplateID); err != nil { return nil, errors.NewNotFoundError("space template", spaceTemplateID.String()) } res := []*WorkItemTypeGroup{} db := r.db.Model(&res).Where("space_template_id=?", spaceTemplateID).Order("position ASC").Find(&res) if db.RecordNotFound() { log.Error(ctx, map[string]interface{}{"space_template_id": spaceTemplateID}, "work item type groups not found") return nil, errors.NewNotFoundError("work item type groups for space template", spaceTemplateID.String()) } if err := db.Error; err != nil { return nil, errors.NewInternalError(ctx, err) } for _, group := range res { typeList, err := r.loadTypeList(ctx, group.ID) if err != nil { return nil, errs.WithStack(err) } group.TypeList = typeList } return res, nil }
go
func (r *GormWorkItemTypeGroupRepository) List(ctx context.Context, spaceTemplateID uuid.UUID) ([]*WorkItemTypeGroup, error) { defer goa.MeasureSince([]string{"goa", "db", "workitemtypegroup", "list"}, time.Now()) log.Debug(ctx, map[string]interface{}{"space_template_id": spaceTemplateID}, "loading work item type groups for space template") // check space template exists if err := spacetemplate.NewRepository(r.db).CheckExists(ctx, spaceTemplateID); err != nil { return nil, errors.NewNotFoundError("space template", spaceTemplateID.String()) } res := []*WorkItemTypeGroup{} db := r.db.Model(&res).Where("space_template_id=?", spaceTemplateID).Order("position ASC").Find(&res) if db.RecordNotFound() { log.Error(ctx, map[string]interface{}{"space_template_id": spaceTemplateID}, "work item type groups not found") return nil, errors.NewNotFoundError("work item type groups for space template", spaceTemplateID.String()) } if err := db.Error; err != nil { return nil, errors.NewInternalError(ctx, err) } for _, group := range res { typeList, err := r.loadTypeList(ctx, group.ID) if err != nil { return nil, errs.WithStack(err) } group.TypeList = typeList } return res, nil }
[ "func", "(", "r", "*", "GormWorkItemTypeGroupRepository", ")", "List", "(", "ctx", "context", ".", "Context", ",", "spaceTemplateID", "uuid", ".", "UUID", ")", "(", "[", "]", "*", "WorkItemTypeGroup", ",", "error", ")", "{", "defer", "goa", ".", "MeasureSi...
// List returns all work item type groups for the given space template ID // ordered by their position value.
[ "List", "returns", "all", "work", "item", "type", "groups", "for", "the", "given", "space", "template", "ID", "ordered", "by", "their", "position", "value", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/workitem/typegroup_repository.go#L80-L106
13,127
fabric8-services/fabric8-wit
workitem/typegroup_repository.go
Create
func (r *GormWorkItemTypeGroupRepository) Create(ctx context.Context, g WorkItemTypeGroup) (*WorkItemTypeGroup, error) { defer goa.MeasureSince([]string{"goa", "db", "workitemtypegroup", "create"}, time.Now()) if len(g.TypeList) <= 0 { return nil, errors.NewBadParameterError("type_list", g.TypeList).Expected("not empty") } if g.ID == uuid.Nil { g.ID = uuid.NewV4() } db := r.db.Create(&g) if db.Error != nil { return nil, errors.NewInternalError(ctx, db.Error) } log.Debug(ctx, map[string]interface{}{"witg_id": g.ID}, "created work item type group") // Create entries for each member in the type list for idx, ID := range g.TypeList { member := typeGroupMember{ TypeGroupID: g.ID, WorkItemTypeID: ID, Position: idx, } db = db.Create(&member) if db.Error != nil { return nil, errors.NewInternalError(ctx, db.Error) } } return &g, nil }
go
func (r *GormWorkItemTypeGroupRepository) Create(ctx context.Context, g WorkItemTypeGroup) (*WorkItemTypeGroup, error) { defer goa.MeasureSince([]string{"goa", "db", "workitemtypegroup", "create"}, time.Now()) if len(g.TypeList) <= 0 { return nil, errors.NewBadParameterError("type_list", g.TypeList).Expected("not empty") } if g.ID == uuid.Nil { g.ID = uuid.NewV4() } db := r.db.Create(&g) if db.Error != nil { return nil, errors.NewInternalError(ctx, db.Error) } log.Debug(ctx, map[string]interface{}{"witg_id": g.ID}, "created work item type group") // Create entries for each member in the type list for idx, ID := range g.TypeList { member := typeGroupMember{ TypeGroupID: g.ID, WorkItemTypeID: ID, Position: idx, } db = db.Create(&member) if db.Error != nil { return nil, errors.NewInternalError(ctx, db.Error) } } return &g, nil }
[ "func", "(", "r", "*", "GormWorkItemTypeGroupRepository", ")", "Create", "(", "ctx", "context", ".", "Context", ",", "g", "WorkItemTypeGroup", ")", "(", "*", "WorkItemTypeGroup", ",", "error", ")", "{", "defer", "goa", ".", "MeasureSince", "(", "[", "]", "...
// Create creates a new work item type group in the repository
[ "Create", "creates", "a", "new", "work", "item", "type", "group", "in", "the", "repository" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/workitem/typegroup_repository.go#L116-L142
13,128
fabric8-services/fabric8-wit
log/log.go
InitializeLogger
func InitializeLogger(logJSON bool, lvl string) { logger = logrus.New() logLevel, err := logrus.ParseLevel(lvl) if err != nil { logrus.Warnf("unable to parse log level configuration error: %q", err) logLevel = logrus.ErrorLevel // reset to ERROR } logrus.SetLevel(logLevel) logger.Level = logLevel if logJSON { customFormatter := new(logrus.JSONFormatter) customFormatter.TimestampFormat = "2006-01-02 15:04:05" logrus.SetFormatter(customFormatter) customFormatter.DisableTimestamp = false logger.Formatter = customFormatter } else { customFormatter := new(logrus.TextFormatter) customFormatter.FullTimestamp = true customFormatter.TimestampFormat = "2006-01-02 15:04:05" logrus.SetFormatter(customFormatter) logger.Formatter = customFormatter } logger.Out = os.Stdout }
go
func InitializeLogger(logJSON bool, lvl string) { logger = logrus.New() logLevel, err := logrus.ParseLevel(lvl) if err != nil { logrus.Warnf("unable to parse log level configuration error: %q", err) logLevel = logrus.ErrorLevel // reset to ERROR } logrus.SetLevel(logLevel) logger.Level = logLevel if logJSON { customFormatter := new(logrus.JSONFormatter) customFormatter.TimestampFormat = "2006-01-02 15:04:05" logrus.SetFormatter(customFormatter) customFormatter.DisableTimestamp = false logger.Formatter = customFormatter } else { customFormatter := new(logrus.TextFormatter) customFormatter.FullTimestamp = true customFormatter.TimestampFormat = "2006-01-02 15:04:05" logrus.SetFormatter(customFormatter) logger.Formatter = customFormatter } logger.Out = os.Stdout }
[ "func", "InitializeLogger", "(", "logJSON", "bool", ",", "lvl", "string", ")", "{", "logger", "=", "logrus", ".", "New", "(", ")", "\n\n", "logLevel", ",", "err", ":=", "logrus", ".", "ParseLevel", "(", "lvl", ")", "\n", "if", "err", "!=", "nil", "{"...
// InitializeLogger creates a default logger with the given ouput format and log level
[ "InitializeLogger", "creates", "a", "default", "logger", "with", "the", "given", "ouput", "format", "and", "log", "level" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/log/log.go#L28-L55
13,129
fabric8-services/fabric8-wit
log/log.go
extractCallerDetails
func extractCallerDetails() (file string, line int, pkg string, function string, err error) { if pc, file, line, ok := runtime.Caller(2); ok { fName := runtime.FuncForPC(pc).Name() parts := strings.Split(fName, ".") pl := len(parts) pName := "" if parts[pl-2][0] == '(' { pName = strings.Join(parts[0:pl-2], ".") } else { pName = strings.Join(parts[0:pl-1], ".") } pName = strings.Replace(pName, defaultPackageName, "", -1) return file, line, pName, fName, nil } return "", 0, "", "", errors.New("unable to extract the caller details") }
go
func extractCallerDetails() (file string, line int, pkg string, function string, err error) { if pc, file, line, ok := runtime.Caller(2); ok { fName := runtime.FuncForPC(pc).Name() parts := strings.Split(fName, ".") pl := len(parts) pName := "" if parts[pl-2][0] == '(' { pName = strings.Join(parts[0:pl-2], ".") } else { pName = strings.Join(parts[0:pl-1], ".") } pName = strings.Replace(pName, defaultPackageName, "", -1) return file, line, pName, fName, nil } return "", 0, "", "", errors.New("unable to extract the caller details") }
[ "func", "extractCallerDetails", "(", ")", "(", "file", "string", ",", "line", "int", ",", "pkg", "string", ",", "function", "string", ",", "err", "error", ")", "{", "if", "pc", ",", "file", ",", "line", ",", "ok", ":=", "runtime", ".", "Caller", "(",...
// extractCallerDetails gets information about the file, line and function that // called a certain logging method such as Error, Info, Debug, Warn and Panic.
[ "extractCallerDetails", "gets", "information", "about", "the", "file", "line", "and", "function", "that", "called", "a", "certain", "logging", "method", "such", "as", "Error", "Info", "Debug", "Warn", "and", "Panic", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/log/log.go#L254-L274
13,130
fabric8-services/fabric8-wit
remoteworkitem/flatten.go
Flatten
func Flatten(source map[string]interface{}) map[string]interface{} { target := make(map[string]interface{}) flatten(target, source, nil) return target }
go
func Flatten(source map[string]interface{}) map[string]interface{} { target := make(map[string]interface{}) flatten(target, source, nil) return target }
[ "func", "Flatten", "(", "source", "map", "[", "string", "]", "interface", "{", "}", ")", "map", "[", "string", "]", "interface", "{", "}", "{", "target", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "flatten", "("...
// Flatten Takes the nested map and returns a non nested one with dot delimited keys
[ "Flatten", "Takes", "the", "nested", "map", "and", "returns", "a", "non", "nested", "one", "with", "dot", "delimited", "keys" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/remoteworkitem/flatten.go#L9-L13
13,131
fabric8-services/fabric8-wit
controller/space_template.go
NewSpaceTemplateController
func NewSpaceTemplateController(service *goa.Service, db application.DB, config SpaceTemplateControllerConfiguration) *SpaceTemplateController { return &SpaceTemplateController{Controller: service.NewController("SpaceTemplateController"), db: db, config: config} }
go
func NewSpaceTemplateController(service *goa.Service, db application.DB, config SpaceTemplateControllerConfiguration) *SpaceTemplateController { return &SpaceTemplateController{Controller: service.NewController("SpaceTemplateController"), db: db, config: config} }
[ "func", "NewSpaceTemplateController", "(", "service", "*", "goa", ".", "Service", ",", "db", "application", ".", "DB", ",", "config", "SpaceTemplateControllerConfiguration", ")", "*", "SpaceTemplateController", "{", "return", "&", "SpaceTemplateController", "{", "Cont...
// NewSpaceTemplateController creates a space_template controller.
[ "NewSpaceTemplateController", "creates", "a", "space_template", "controller", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/space_template.go#L33-L35
13,132
fabric8-services/fabric8-wit
controller/space_template.go
ConvertSpaceTemplates
func ConvertSpaceTemplates(appl application.Application, request *http.Request, spaceTemplates []spacetemplate.SpaceTemplate, additional ...SpaceTemplateConvertFunc) []*app.SpaceTemplate { var is = []*app.SpaceTemplate{} for _, i := range spaceTemplates { is = append(is, ConvertSpaceTemplate(appl, request, i, additional...)) } return is }
go
func ConvertSpaceTemplates(appl application.Application, request *http.Request, spaceTemplates []spacetemplate.SpaceTemplate, additional ...SpaceTemplateConvertFunc) []*app.SpaceTemplate { var is = []*app.SpaceTemplate{} for _, i := range spaceTemplates { is = append(is, ConvertSpaceTemplate(appl, request, i, additional...)) } return is }
[ "func", "ConvertSpaceTemplates", "(", "appl", "application", ".", "Application", ",", "request", "*", "http", ".", "Request", ",", "spaceTemplates", "[", "]", "spacetemplate", ".", "SpaceTemplate", ",", "additional", "...", "SpaceTemplateConvertFunc", ")", "[", "]...
// ConvertSpaceTemplates converts between internal and external REST representation
[ "ConvertSpaceTemplates", "converts", "between", "internal", "and", "external", "REST", "representation" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/space_template.go#L87-L93
13,133
fabric8-services/fabric8-wit
controller/space_template.go
ConvertSpaceTemplate
func ConvertSpaceTemplate(appl application.Application, request *http.Request, st spacetemplate.SpaceTemplate, additional ...SpaceTemplateConvertFunc) *app.SpaceTemplate { // template := base64.StdEncoding.EncodeToString([]byte(st.Template)) i := &app.SpaceTemplate{ Type: APISpaceTemplates, ID: &st.ID, Attributes: &app.SpaceTemplateAttributes{ Name: &st.Name, CreatedAt: &st.CreatedAt, UpdatedAt: &st.UpdatedAt, Version: &st.Version, Description: st.Description, CanConstruct: &st.CanConstruct, // Template: &template, }, Relationships: &app.SpaceTemplateRelationships{ Workitemtypes: &app.RelationGeneric{ Links: &app.GenericLinks{ Related: ptr.String(rest.AbsoluteURL(request, app.SpaceTemplateHref(st.ID)+"/workitemtypes")), }, }, Workitemlinktypes: &app.RelationGeneric{ Links: &app.GenericLinks{ Related: ptr.String(rest.AbsoluteURL(request, app.SpaceTemplateHref(st.ID)+"/workitemlinktypes")), }, }, Workitemtypegroups: &app.RelationGeneric{ Links: &app.GenericLinks{ Related: ptr.String(rest.AbsoluteURL(request, app.SpaceTemplateHref(st.ID)+"/workitemtypegroups")), }, }, Workitemboards: &app.RelationGeneric{ Links: &app.GenericLinks{ Related: ptr.String(rest.AbsoluteURL(request, app.SpaceTemplateHref(st.ID)+"/workitemboards")), }, }, }, Links: &app.GenericLinks{ Self: ptr.String(rest.AbsoluteURL(request, app.SpaceTemplateHref(st.ID))), }, } for _, add := range additional { add(appl, request, &st, i) } return i }
go
func ConvertSpaceTemplate(appl application.Application, request *http.Request, st spacetemplate.SpaceTemplate, additional ...SpaceTemplateConvertFunc) *app.SpaceTemplate { // template := base64.StdEncoding.EncodeToString([]byte(st.Template)) i := &app.SpaceTemplate{ Type: APISpaceTemplates, ID: &st.ID, Attributes: &app.SpaceTemplateAttributes{ Name: &st.Name, CreatedAt: &st.CreatedAt, UpdatedAt: &st.UpdatedAt, Version: &st.Version, Description: st.Description, CanConstruct: &st.CanConstruct, // Template: &template, }, Relationships: &app.SpaceTemplateRelationships{ Workitemtypes: &app.RelationGeneric{ Links: &app.GenericLinks{ Related: ptr.String(rest.AbsoluteURL(request, app.SpaceTemplateHref(st.ID)+"/workitemtypes")), }, }, Workitemlinktypes: &app.RelationGeneric{ Links: &app.GenericLinks{ Related: ptr.String(rest.AbsoluteURL(request, app.SpaceTemplateHref(st.ID)+"/workitemlinktypes")), }, }, Workitemtypegroups: &app.RelationGeneric{ Links: &app.GenericLinks{ Related: ptr.String(rest.AbsoluteURL(request, app.SpaceTemplateHref(st.ID)+"/workitemtypegroups")), }, }, Workitemboards: &app.RelationGeneric{ Links: &app.GenericLinks{ Related: ptr.String(rest.AbsoluteURL(request, app.SpaceTemplateHref(st.ID)+"/workitemboards")), }, }, }, Links: &app.GenericLinks{ Self: ptr.String(rest.AbsoluteURL(request, app.SpaceTemplateHref(st.ID))), }, } for _, add := range additional { add(appl, request, &st, i) } return i }
[ "func", "ConvertSpaceTemplate", "(", "appl", "application", ".", "Application", ",", "request", "*", "http", ".", "Request", ",", "st", "spacetemplate", ".", "SpaceTemplate", ",", "additional", "...", "SpaceTemplateConvertFunc", ")", "*", "app", ".", "SpaceTemplat...
// ConvertSpaceTemplate converts between internal and external REST representation
[ "ConvertSpaceTemplate", "converts", "between", "internal", "and", "external", "REST", "representation" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/space_template.go#L96-L142
13,134
fabric8-services/fabric8-wit
workitem/event/event_repository.go
NewEventRepository
func NewEventRepository(db *gorm.DB) *GormEventRepository { return &GormEventRepository{ db: db, workItemRepo: workitem.NewWorkItemRepository(db), wiRevisionRepo: workitem.NewRevisionRepository(db), workItemTypeRepo: workitem.NewWorkItemTypeRepository(db), identityRepo: account.NewIdentityRepository(db), } }
go
func NewEventRepository(db *gorm.DB) *GormEventRepository { return &GormEventRepository{ db: db, workItemRepo: workitem.NewWorkItemRepository(db), wiRevisionRepo: workitem.NewRevisionRepository(db), workItemTypeRepo: workitem.NewWorkItemTypeRepository(db), identityRepo: account.NewIdentityRepository(db), } }
[ "func", "NewEventRepository", "(", "db", "*", "gorm", ".", "DB", ")", "*", "GormEventRepository", "{", "return", "&", "GormEventRepository", "{", "db", ":", "db", ",", "workItemRepo", ":", "workitem", ".", "NewWorkItemRepository", "(", "db", ")", ",", "wiRev...
// NewEventRepository creates a work item event repository based on gorm
[ "NewEventRepository", "creates", "a", "work", "item", "event", "repository", "based", "on", "gorm" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/workitem/event/event_repository.go#L29-L37
13,135
fabric8-services/fabric8-wit
controller/work_item_boards.go
NewWorkItemBoardsController
func NewWorkItemBoardsController(service *goa.Service, db application.DB) *WorkItemBoardsController { return &WorkItemBoardsController{ Controller: service.NewController("WorkItemBoardsController"), db: db, } }
go
func NewWorkItemBoardsController(service *goa.Service, db application.DB) *WorkItemBoardsController { return &WorkItemBoardsController{ Controller: service.NewController("WorkItemBoardsController"), db: db, } }
[ "func", "NewWorkItemBoardsController", "(", "service", "*", "goa", ".", "Service", ",", "db", "application", ".", "DB", ")", "*", "WorkItemBoardsController", "{", "return", "&", "WorkItemBoardsController", "{", "Controller", ":", "service", ".", "NewController", "...
// NewWorkItemBoardsController creates a work_item_boards controller.
[ "NewWorkItemBoardsController", "creates", "a", "work_item_boards", "controller", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/work_item_boards.go#L20-L25
13,136
fabric8-services/fabric8-wit
controller/workitem.go
NewWorkitemController
func NewWorkitemController(service *goa.Service, db application.DB, config WorkItemControllerConfig) *WorkitemController { return NewNotifyingWorkitemController(service, db, &notification.DevNullChannel{}, config) }
go
func NewWorkitemController(service *goa.Service, db application.DB, config WorkItemControllerConfig) *WorkitemController { return NewNotifyingWorkitemController(service, db, &notification.DevNullChannel{}, config) }
[ "func", "NewWorkitemController", "(", "service", "*", "goa", ".", "Service", ",", "db", "application", ".", "DB", ",", "config", "WorkItemControllerConfig", ")", "*", "WorkitemController", "{", "return", "NewNotifyingWorkitemController", "(", "service", ",", "db", ...
// NewWorkitemController creates a workitem controller.
[ "NewWorkitemController", "creates", "a", "workitem", "controller", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/workitem.go#L61-L63
13,137
fabric8-services/fabric8-wit
controller/workitem.go
WorkitemCreatorOrSpaceOwner
func (c *WorkitemController) WorkitemCreatorOrSpaceOwner(ctx context.Context, spaceID uuid.UUID, creatorID uuid.UUID, editorID uuid.UUID) error { // check if workitem editor is same as workitem creator if editorID == creatorID { return nil } space, err := c.db.Spaces().Load(ctx, spaceID) if err != nil { return errors.NewNotFoundError("space", spaceID.String()) } // check if workitem editor is same as space owner if space != nil && editorID == space.OwnerID { return nil } return errors.NewForbiddenError("user is not a workitem creator or space owner") }
go
func (c *WorkitemController) WorkitemCreatorOrSpaceOwner(ctx context.Context, spaceID uuid.UUID, creatorID uuid.UUID, editorID uuid.UUID) error { // check if workitem editor is same as workitem creator if editorID == creatorID { return nil } space, err := c.db.Spaces().Load(ctx, spaceID) if err != nil { return errors.NewNotFoundError("space", spaceID.String()) } // check if workitem editor is same as space owner if space != nil && editorID == space.OwnerID { return nil } return errors.NewForbiddenError("user is not a workitem creator or space owner") }
[ "func", "(", "c", "*", "WorkitemController", ")", "WorkitemCreatorOrSpaceOwner", "(", "ctx", "context", ".", "Context", ",", "spaceID", "uuid", ".", "UUID", ",", "creatorID", "uuid", ".", "UUID", ",", "editorID", "uuid", ".", "UUID", ")", "error", "{", "//...
// WorkitemCreatorOrSpaceOwner checks if the modifier is space owner or workitem creator
[ "WorkitemCreatorOrSpaceOwner", "checks", "if", "the", "modifier", "is", "space", "owner", "or", "workitem", "creator" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/workitem.go#L79-L93
13,138
fabric8-services/fabric8-wit
controller/workitem.go
authorizeWorkitemEditor
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 }
go
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 }
[ "func", "authorizeWorkitemEditor", "(", "ctx", "context", ".", "Context", ",", "db", "application", ".", "DB", ",", "spaceID", "uuid", ".", "UUID", ",", "creatorID", "string", ",", "editorID", "string", ")", "(", "bool", ",", "error", ")", "{", "if", "ed...
// Returns true if the user is the work item creator or space collaborator
[ "Returns", "true", "if", "the", "user", "is", "the", "work", "item", "creator", "or", "space", "collaborator" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/workitem.go#L96-L105
13,139
fabric8-services/fabric8-wit
controller/workitem.go
Show
func (c *WorkitemController) Show(ctx *app.ShowWorkitemContext) error { var wi *workitem.WorkItem var wit *workitem.WorkItemType err := application.Transactional(c.db, func(appl application.Application) error { var err 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)) } wit, err = appl.WorkItemTypes().Load(ctx.Context, wi.Type) if err != nil { return errs.Wrapf(err, "failed to load work item type: %s", wi.Type) } return nil }) if err != nil { return jsonapi.JSONErrorResponse(ctx, err) } return ctx.ConditionalRequest(*wi, c.config.GetCacheControlWorkItem, func() error { comments := workItemIncludeCommentsAndTotal(ctx, c.db, ctx.WiID) hasChildren := workItemIncludeHasChildren(ctx, c.db) wi2, err := ConvertWorkItem(ctx.Request, *wit, *wi, comments, hasChildren) if err != nil { return jsonapi.JSONErrorResponse(ctx, err) } resp := &app.WorkItemSingle{ Data: wi2, } return ctx.OK(resp) }) }
go
func (c *WorkitemController) Show(ctx *app.ShowWorkitemContext) error { var wi *workitem.WorkItem var wit *workitem.WorkItemType err := application.Transactional(c.db, func(appl application.Application) error { var err 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)) } wit, err = appl.WorkItemTypes().Load(ctx.Context, wi.Type) if err != nil { return errs.Wrapf(err, "failed to load work item type: %s", wi.Type) } return nil }) if err != nil { return jsonapi.JSONErrorResponse(ctx, err) } return ctx.ConditionalRequest(*wi, c.config.GetCacheControlWorkItem, func() error { comments := workItemIncludeCommentsAndTotal(ctx, c.db, ctx.WiID) hasChildren := workItemIncludeHasChildren(ctx, c.db) wi2, err := ConvertWorkItem(ctx.Request, *wit, *wi, comments, hasChildren) if err != nil { return jsonapi.JSONErrorResponse(ctx, err) } resp := &app.WorkItemSingle{ Data: wi2, } return ctx.OK(resp) }) }
[ "func", "(", "c", "*", "WorkitemController", ")", "Show", "(", "ctx", "*", "app", ".", "ShowWorkitemContext", ")", "error", "{", "var", "wi", "*", "workitem", ".", "WorkItem", "\n", "var", "wit", "*", "workitem", ".", "WorkItemType", "\n", "err", ":=", ...
// Show does GET workitem
[ "Show", "does", "GET", "workitem" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/workitem.go#L212-L242
13,140
fabric8-services/fabric8-wit
controller/workitem.go
Delete
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{}) }
go
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{}) }
[ "func", "(", "c", "*", "WorkitemController", ")", "Delete", "(", "ctx", "*", "app", ".", "DeleteWorkitemContext", ")", "error", "{", "currentUserIdentityID", ",", "err", ":=", "login", ".", "ContextIdentity", "(", "ctx", ")", "\n", "if", "err", "!=", "nil"...
// Delete does DELETE workitem
[ "Delete", "does", "DELETE", "workitem" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/workitem.go#L245-L298
13,141
fabric8-services/fabric8-wit
controller/workitem.go
updatedAt
func updatedAt(wi workitem.WorkItem) time.Time { var t time.Time if ua, ok := wi.Fields[workitem.SystemUpdatedAt]; ok { t = ua.(time.Time) } return t.Truncate(time.Second) }
go
func updatedAt(wi workitem.WorkItem) time.Time { var t time.Time if ua, ok := wi.Fields[workitem.SystemUpdatedAt]; ok { t = ua.(time.Time) } return t.Truncate(time.Second) }
[ "func", "updatedAt", "(", "wi", "workitem", ".", "WorkItem", ")", "time", ".", "Time", "{", "var", "t", "time", ".", "Time", "\n", "if", "ua", ",", "ok", ":=", "wi", ".", "Fields", "[", "workitem", ".", "SystemUpdatedAt", "]", ";", "ok", "{", "t", ...
// Time is default value if no UpdatedAt field is found
[ "Time", "is", "default", "value", "if", "no", "UpdatedAt", "field", "is", "found" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/workitem.go#L301-L307
13,142
fabric8-services/fabric8-wit
controller/workitem.go
setupCodebase
func setupCodebase(appl application.Application, cb *codebase.Content, spaceID uuid.UUID) error { if cb.CodebaseID == "" { newCodeBase := codebase.Codebase{ SpaceID: spaceID, Type: "git", URL: cb.Repository, StackID: ptr.String("java-centos"), //TODO: Think of making stackID dynamic value (from analyzer) } existingCB, err := appl.Codebases().LoadByRepo(context.Background(), spaceID, cb.Repository) if existingCB != nil { cb.CodebaseID = existingCB.ID.String() return nil } err = appl.Codebases().Create(context.Background(), &newCodeBase) if err != nil { return errors.NewInternalError(context.Background(), err) } cb.CodebaseID = newCodeBase.ID.String() } return nil }
go
func setupCodebase(appl application.Application, cb *codebase.Content, spaceID uuid.UUID) error { if cb.CodebaseID == "" { newCodeBase := codebase.Codebase{ SpaceID: spaceID, Type: "git", URL: cb.Repository, StackID: ptr.String("java-centos"), //TODO: Think of making stackID dynamic value (from analyzer) } existingCB, err := appl.Codebases().LoadByRepo(context.Background(), spaceID, cb.Repository) if existingCB != nil { cb.CodebaseID = existingCB.ID.String() return nil } err = appl.Codebases().Create(context.Background(), &newCodeBase) if err != nil { return errors.NewInternalError(context.Background(), err) } cb.CodebaseID = newCodeBase.ID.String() } return nil }
[ "func", "setupCodebase", "(", "appl", "application", ".", "Application", ",", "cb", "*", "codebase", ".", "Content", ",", "spaceID", "uuid", ".", "UUID", ")", "error", "{", "if", "cb", ".", "CodebaseID", "==", "\"", "\"", "{", "newCodeBase", ":=", "codeb...
// setupCodebase is the link between CodebaseContent & Codebase // setupCodebase creates a codebase and saves it's ID in CodebaseContent // for future use
[ "setupCodebase", "is", "the", "link", "between", "CodebaseContent", "&", "Codebase", "setupCodebase", "creates", "a", "codebase", "and", "saves", "it", "s", "ID", "in", "CodebaseContent", "for", "future", "use" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/workitem.go#L534-L555
13,143
fabric8-services/fabric8-wit
controller/workitem.go
checkNumberCache
func checkNumberCache(idNumberMap map[string]string, entryID string) (string, bool) { for key, value := range idNumberMap { if key == entryID { return value, true } } return "", false }
go
func checkNumberCache(idNumberMap map[string]string, entryID string) (string, bool) { for key, value := range idNumberMap { if key == entryID { return value, true } } return "", false }
[ "func", "checkNumberCache", "(", "idNumberMap", "map", "[", "string", "]", "string", ",", "entryID", "string", ")", "(", "string", ",", "bool", ")", "{", "for", "key", ",", "value", ":=", "range", "idNumberMap", "{", "if", "key", "==", "entryID", "{", ...
// checkNumberCache looks the given ID up and returns the value
[ "checkNumberCache", "looks", "the", "given", "ID", "up", "and", "returns", "the", "value" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/workitem.go#L753-L760
13,144
fabric8-services/fabric8-wit
controller/workitem.go
resolveNumberByWorkItemID
func resolveNumberByWorkItemID(ctx context.Context, db application.DB, workItemID uuid.UUID) (string, error) { var numberInt int err := application.Transactional(db, func(appl application.Application) error { thisWorkItem, err := appl.WorkItems().LoadByID(ctx, workItemID) if err != nil { log.Error(ctx, map[string]interface{}{ "err": err, "workItemID": workItemID, }, "error retrieving number for workItemID") return errs.Wrapf(err, "error retrieving number for workItemID: %s", workItemID.String()) } number := thisWorkItem.Fields[workitem.SystemNumber] var ok bool numberInt, ok = number.(int) if !ok { return errs.Errorf("error converting number for workItemID: %s", workItemID.String()) } return nil }) return strconv.Itoa(numberInt), err }
go
func resolveNumberByWorkItemID(ctx context.Context, db application.DB, workItemID uuid.UUID) (string, error) { var numberInt int err := application.Transactional(db, func(appl application.Application) error { thisWorkItem, err := appl.WorkItems().LoadByID(ctx, workItemID) if err != nil { log.Error(ctx, map[string]interface{}{ "err": err, "workItemID": workItemID, }, "error retrieving number for workItemID") return errs.Wrapf(err, "error retrieving number for workItemID: %s", workItemID.String()) } number := thisWorkItem.Fields[workitem.SystemNumber] var ok bool numberInt, ok = number.(int) if !ok { return errs.Errorf("error converting number for workItemID: %s", workItemID.String()) } return nil }) return strconv.Itoa(numberInt), err }
[ "func", "resolveNumberByWorkItemID", "(", "ctx", "context", ".", "Context", ",", "db", "application", ".", "DB", ",", "workItemID", "uuid", ".", "UUID", ")", "(", "string", ",", "error", ")", "{", "var", "numberInt", "int", "\n", "err", ":=", "application"...
// resolveNumberByWorkItemID retrieves the work item number for a work item ID
[ "resolveNumberByWorkItemID", "retrieves", "the", "work", "item", "number", "for", "a", "work", "item", "ID" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/workitem.go#L763-L783
13,145
fabric8-services/fabric8-wit
controller/workitem.go
extractWorkItemTypeFields
func extractWorkItemTypeFields(wit workitem.WorkItemType) ([]string, []string, error) { fieldLabels := []string{} fieldKeys := []string{} for fieldKey, fieldDefinition := range wit.Fields { // extract the label and key fieldLabels = append(fieldLabels, fieldDefinition.Label) fieldKeys = append(fieldKeys, fieldKey) } return fieldLabels, fieldKeys, nil }
go
func extractWorkItemTypeFields(wit workitem.WorkItemType) ([]string, []string, error) { fieldLabels := []string{} fieldKeys := []string{} for fieldKey, fieldDefinition := range wit.Fields { // extract the label and key fieldLabels = append(fieldLabels, fieldDefinition.Label) fieldKeys = append(fieldKeys, fieldKey) } return fieldLabels, fieldKeys, nil }
[ "func", "extractWorkItemTypeFields", "(", "wit", "workitem", ".", "WorkItemType", ")", "(", "[", "]", "string", ",", "[", "]", "string", ",", "error", ")", "{", "fieldLabels", ":=", "[", "]", "string", "{", "}", "\n", "fieldKeys", ":=", "[", "]", "stri...
// extractWorkItemTypeFields extracts the field information for a wit; it returns slices for // field labels and field keys
[ "extractWorkItemTypeFields", "extracts", "the", "field", "information", "for", "a", "wit", ";", "it", "returns", "slices", "for", "field", "labels", "and", "field", "keys" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/workitem.go#L787-L796
13,146
fabric8-services/fabric8-wit
controller/workitem.go
convertWorkItemFieldValues
func convertWorkItemFieldValues(ctx context.Context, app application.Application, uuidStringCache *map[string]string, wit workitem.WorkItemType, wi workitem.WorkItem) (map[string]string, error) { fieldMap := make(map[string]string) for fieldKey, fieldDefinition := range wit.Fields { // convert the value to a string for the CSV fieldValueGeneric := wi.Fields[fieldKey] fieldType := fieldDefinition.Type fieldValueStrSlice, err := fieldType.ConvertToStringSlice(fieldValueGeneric) if err != nil { return nil, errs.Wrapf(err, "failed to convert type value to string for field key: %s", fieldKey) } var convertedValue string // now retrieve and, if needed, resolve the id value. switch fieldType.(type) { case workitem.ListType: var converted string kind := fieldType.(workitem.ListType).ComponentType.Kind delim := "" for _, elem := range fieldValueStrSlice { elemConvertedValue, err := convertValueToString(ctx, app, uuidStringCache, fieldValueGeneric, []string{elem}, fieldKey, kind) if err != nil { return nil, errs.Wrapf(err, "failed to convert compound type value to string for field key: %s", fieldKey) } converted = converted + delim + elemConvertedValue delim = "\n" } convertedValue = converted case workitem.EnumType: kind := fieldType.(workitem.EnumType).BaseType.Kind convertedValue, err = convertValueToString(ctx, app, uuidStringCache, fieldValueGeneric, fieldValueStrSlice, fieldKey, kind) default: // all other Kinds don't need compound resolving. kind := fieldType.GetKind() convertedValue, err = convertValueToString(ctx, app, uuidStringCache, fieldValueGeneric, fieldValueStrSlice, fieldKey, kind) } if err != nil { return nil, errs.Wrapf(err, "failed to resolve type value to string for field key: %s", fieldKey) } fieldMap[fieldKey] = convertedValue } return fieldMap, nil }
go
func convertWorkItemFieldValues(ctx context.Context, app application.Application, uuidStringCache *map[string]string, wit workitem.WorkItemType, wi workitem.WorkItem) (map[string]string, error) { fieldMap := make(map[string]string) for fieldKey, fieldDefinition := range wit.Fields { // convert the value to a string for the CSV fieldValueGeneric := wi.Fields[fieldKey] fieldType := fieldDefinition.Type fieldValueStrSlice, err := fieldType.ConvertToStringSlice(fieldValueGeneric) if err != nil { return nil, errs.Wrapf(err, "failed to convert type value to string for field key: %s", fieldKey) } var convertedValue string // now retrieve and, if needed, resolve the id value. switch fieldType.(type) { case workitem.ListType: var converted string kind := fieldType.(workitem.ListType).ComponentType.Kind delim := "" for _, elem := range fieldValueStrSlice { elemConvertedValue, err := convertValueToString(ctx, app, uuidStringCache, fieldValueGeneric, []string{elem}, fieldKey, kind) if err != nil { return nil, errs.Wrapf(err, "failed to convert compound type value to string for field key: %s", fieldKey) } converted = converted + delim + elemConvertedValue delim = "\n" } convertedValue = converted case workitem.EnumType: kind := fieldType.(workitem.EnumType).BaseType.Kind convertedValue, err = convertValueToString(ctx, app, uuidStringCache, fieldValueGeneric, fieldValueStrSlice, fieldKey, kind) default: // all other Kinds don't need compound resolving. kind := fieldType.GetKind() convertedValue, err = convertValueToString(ctx, app, uuidStringCache, fieldValueGeneric, fieldValueStrSlice, fieldKey, kind) } if err != nil { return nil, errs.Wrapf(err, "failed to resolve type value to string for field key: %s", fieldKey) } fieldMap[fieldKey] = convertedValue } return fieldMap, nil }
[ "func", "convertWorkItemFieldValues", "(", "ctx", "context", ".", "Context", ",", "app", "application", ".", "Application", ",", "uuidStringCache", "*", "map", "[", "string", "]", "string", ",", "wit", "workitem", ".", "WorkItemType", ",", "wi", "workitem", "....
// convertWorkItemFieldValues extracts and converts the wi field values; it returns a map // that maps field keys to converted field values
[ "convertWorkItemFieldValues", "extracts", "and", "converts", "the", "wi", "field", "values", ";", "it", "returns", "a", "map", "that", "maps", "field", "keys", "to", "converted", "field", "values" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/workitem.go#L800-L840
13,147
fabric8-services/fabric8-wit
controller/workitem.go
workItemIncludeHasChildren
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 } }
go
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 } }
[ "func", "workItemIncludeHasChildren", "(", "ctx", "context", ".", "Context", ",", "appl", "application", ".", "Application", ",", "childLinks", "...", "link", ".", "WorkItemLinkList", ")", "WorkItemConvertFunc", "{", "// TODO: Wrap ctx in a Timeout context?", "return", ...
// workItemIncludeHasChildren adds meta information about existing children
[ "workItemIncludeHasChildren", "adds", "meta", "information", "about", "existing", "children" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/workitem.go#L1080-L1118
13,148
fabric8-services/fabric8-wit
controller/workitem.go
includeParentWorkItem
func includeParentWorkItem(ctx context.Context, ancestors link.AncestorList, childLinks link.WorkItemLinkList) WorkItemConvertFunc { return func(request *http.Request, wi *workitem.WorkItem, wi2 *app.WorkItem) error { var parentID *uuid.UUID // If we have an ancestry we can lookup the parent in no time. if ancestors != nil && len(ancestors) != 0 { p := ancestors.GetParentOf(wi.ID) if p != nil { parentID = &p.ID } } // If no parent ID was found in the ancestor list, see if the child // link list contains information to use. if parentID == nil && childLinks != nil && len(childLinks) != 0 { p := childLinks.GetParentIDOf(wi.ID, link.SystemWorkItemLinkTypeParentChildID) if p != uuid.Nil { parentID = &p } } if wi2.Relationships.Parent == nil { wi2.Relationships.Parent = &app.RelationKindUUID{} } if parentID != nil { if wi2.Relationships.Parent.Data == nil { wi2.Relationships.Parent.Data = &app.DataKindUUID{} } wi2.Relationships.Parent.Data.ID = *parentID wi2.Relationships.Parent.Data.Type = APIStringTypeWorkItem } return nil } }
go
func includeParentWorkItem(ctx context.Context, ancestors link.AncestorList, childLinks link.WorkItemLinkList) WorkItemConvertFunc { return func(request *http.Request, wi *workitem.WorkItem, wi2 *app.WorkItem) error { var parentID *uuid.UUID // If we have an ancestry we can lookup the parent in no time. if ancestors != nil && len(ancestors) != 0 { p := ancestors.GetParentOf(wi.ID) if p != nil { parentID = &p.ID } } // If no parent ID was found in the ancestor list, see if the child // link list contains information to use. if parentID == nil && childLinks != nil && len(childLinks) != 0 { p := childLinks.GetParentIDOf(wi.ID, link.SystemWorkItemLinkTypeParentChildID) if p != uuid.Nil { parentID = &p } } if wi2.Relationships.Parent == nil { wi2.Relationships.Parent = &app.RelationKindUUID{} } if parentID != nil { if wi2.Relationships.Parent.Data == nil { wi2.Relationships.Parent.Data = &app.DataKindUUID{} } wi2.Relationships.Parent.Data.ID = *parentID wi2.Relationships.Parent.Data.Type = APIStringTypeWorkItem } return nil } }
[ "func", "includeParentWorkItem", "(", "ctx", "context", ".", "Context", ",", "ancestors", "link", ".", "AncestorList", ",", "childLinks", "link", ".", "WorkItemLinkList", ")", "WorkItemConvertFunc", "{", "return", "func", "(", "request", "*", "http", ".", "Reque...
// includeParentWorkItem adds the parent of given WI to relationships & included object
[ "includeParentWorkItem", "adds", "the", "parent", "of", "given", "WI", "to", "relationships", "&", "included", "object" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/workitem.go#L1121-L1151
13,149
fabric8-services/fabric8-wit
controller/workitem.go
ListChildren
func (c *WorkitemController) ListChildren(ctx *app.ListChildrenWorkitemContext) error { offset, limit := computePagingLimits(ctx.PageOffset, ctx.PageLimit) var result []workitem.WorkItem var count int var wits []workitem.WorkItemType err := application.Transactional(c.db, func(appl application.Application) error { var err error result, count, err = appl.WorkItemLinks().ListWorkItemChildren(ctx, ctx.WiID, &offset, &limit) if err != nil { return errs.Wrap(err, "unable to list work item children") } wits, err = loadWorkItemTypesFromArr(ctx.Context, appl, result) if err != nil { return errs.Wrap(err, "failed to load the work item types") } return nil }) if err != nil { return jsonapi.JSONErrorResponse(ctx, err) } return ctx.ConditionalEntities(result, c.config.GetCacheControlWorkItems, func() error { var response app.WorkItemList application.Transactional(c.db, func(appl application.Application) error { hasChildren := workItemIncludeHasChildren(ctx, appl) converted, err := ConvertWorkItems(ctx.Request, wits, result, hasChildren) if err != nil { return errs.WithStack(err) } response = app.WorkItemList{ Links: &app.PagingLinks{}, Meta: &app.WorkItemListResponseMeta{TotalCount: count}, Data: converted, } return nil }) setPagingLinks(response.Links, buildAbsoluteURL(ctx.Request), len(result), offset, limit, count) return ctx.OK(&response) }) }
go
func (c *WorkitemController) ListChildren(ctx *app.ListChildrenWorkitemContext) error { offset, limit := computePagingLimits(ctx.PageOffset, ctx.PageLimit) var result []workitem.WorkItem var count int var wits []workitem.WorkItemType err := application.Transactional(c.db, func(appl application.Application) error { var err error result, count, err = appl.WorkItemLinks().ListWorkItemChildren(ctx, ctx.WiID, &offset, &limit) if err != nil { return errs.Wrap(err, "unable to list work item children") } wits, err = loadWorkItemTypesFromArr(ctx.Context, appl, result) if err != nil { return errs.Wrap(err, "failed to load the work item types") } return nil }) if err != nil { return jsonapi.JSONErrorResponse(ctx, err) } return ctx.ConditionalEntities(result, c.config.GetCacheControlWorkItems, func() error { var response app.WorkItemList application.Transactional(c.db, func(appl application.Application) error { hasChildren := workItemIncludeHasChildren(ctx, appl) converted, err := ConvertWorkItems(ctx.Request, wits, result, hasChildren) if err != nil { return errs.WithStack(err) } response = app.WorkItemList{ Links: &app.PagingLinks{}, Meta: &app.WorkItemListResponseMeta{TotalCount: count}, Data: converted, } return nil }) setPagingLinks(response.Links, buildAbsoluteURL(ctx.Request), len(result), offset, limit, count) return ctx.OK(&response) }) }
[ "func", "(", "c", "*", "WorkitemController", ")", "ListChildren", "(", "ctx", "*", "app", ".", "ListChildrenWorkitemContext", ")", "error", "{", "offset", ",", "limit", ":=", "computePagingLimits", "(", "ctx", ".", "PageOffset", ",", "ctx", ".", "PageLimit", ...
// ListChildren runs the list action.
[ "ListChildren", "runs", "the", "list", "action", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/workitem.go#L1154-L1192
13,150
fabric8-services/fabric8-wit
controller/work_item_relationships_links.go
NewWorkItemRelationshipsLinksController
func NewWorkItemRelationshipsLinksController(service *goa.Service, db application.DB, config WorkItemRelationshipsLinksControllerConfig) *WorkItemRelationshipsLinksController { return &WorkItemRelationshipsLinksController{ Controller: service.NewController("WorkItemRelationshipsLinksController"), db: db, config: config, } }
go
func NewWorkItemRelationshipsLinksController(service *goa.Service, db application.DB, config WorkItemRelationshipsLinksControllerConfig) *WorkItemRelationshipsLinksController { return &WorkItemRelationshipsLinksController{ Controller: service.NewController("WorkItemRelationshipsLinksController"), db: db, config: config, } }
[ "func", "NewWorkItemRelationshipsLinksController", "(", "service", "*", "goa", ".", "Service", ",", "db", "application", ".", "DB", ",", "config", "WorkItemRelationshipsLinksControllerConfig", ")", "*", "WorkItemRelationshipsLinksController", "{", "return", "&", "WorkItem...
// NewWorkItemRelationshipsLinksController creates a work-item-relationships-links controller.
[ "NewWorkItemRelationshipsLinksController", "creates", "a", "work", "-", "item", "-", "relationships", "-", "links", "controller", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/work_item_relationships_links.go#L24-L30
13,151
fabric8-services/fabric8-wit
criteria/expression_or.go
Or
func Or(left Expression, right Expression) Expression { return reparent(&OrExpression{binaryExpression{expression{}, left, right}}) }
go
func Or(left Expression, right Expression) Expression { return reparent(&OrExpression{binaryExpression{expression{}, left, right}}) }
[ "func", "Or", "(", "left", "Expression", ",", "right", "Expression", ")", "Expression", "{", "return", "reparent", "(", "&", "OrExpression", "{", "binaryExpression", "{", "expression", "{", "}", ",", "left", ",", "right", "}", "}", ")", "\n", "}" ]
// Or constructs an OrExpression
[ "Or", "constructs", "an", "OrExpression" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/criteria/expression_or.go#L18-L20
13,152
fabric8-services/fabric8-wit
workitem/workitem_revision_repository.go
Create
func (r *GormRevisionRepository) Create(ctx context.Context, modifierID uuid.UUID, revisionType RevisionType, workitem WorkItemStorage) (Revision, error) { log.Debug(nil, map[string]interface{}{ "modifier_id": modifierID, "revision_type": revisionType, }, "Storing a revision after operation on work item.") tx := r.db workitemRevision := Revision{ ModifierIdentity: modifierID, Time: time.Now(), Type: revisionType, WorkItemID: workitem.ID, WorkItemTypeID: workitem.Type, WorkItemVersion: workitem.Version, WorkItemFields: workitem.Fields, } // do not store fields when the work item is deleted if workitemRevision.Type == RevisionTypeDelete { workitemRevision.WorkItemFields = Fields{} } if err := tx.Create(&workitemRevision).Error; err != nil { return Revision{}, errors.NewInternalError(ctx, errs.Wrap(err, "failed to create new work item revision")) } log.Debug(ctx, map[string]interface{}{"wi_id": workitem.ID}, "Work item revision occurrence created") return workitemRevision, nil }
go
func (r *GormRevisionRepository) Create(ctx context.Context, modifierID uuid.UUID, revisionType RevisionType, workitem WorkItemStorage) (Revision, error) { log.Debug(nil, map[string]interface{}{ "modifier_id": modifierID, "revision_type": revisionType, }, "Storing a revision after operation on work item.") tx := r.db workitemRevision := Revision{ ModifierIdentity: modifierID, Time: time.Now(), Type: revisionType, WorkItemID: workitem.ID, WorkItemTypeID: workitem.Type, WorkItemVersion: workitem.Version, WorkItemFields: workitem.Fields, } // do not store fields when the work item is deleted if workitemRevision.Type == RevisionTypeDelete { workitemRevision.WorkItemFields = Fields{} } if err := tx.Create(&workitemRevision).Error; err != nil { return Revision{}, errors.NewInternalError(ctx, errs.Wrap(err, "failed to create new work item revision")) } log.Debug(ctx, map[string]interface{}{"wi_id": workitem.ID}, "Work item revision occurrence created") return workitemRevision, nil }
[ "func", "(", "r", "*", "GormRevisionRepository", ")", "Create", "(", "ctx", "context", ".", "Context", ",", "modifierID", "uuid", ".", "UUID", ",", "revisionType", "RevisionType", ",", "workitem", "WorkItemStorage", ")", "(", "Revision", ",", "error", ")", "...
// Create stores a new revision for the given work item.
[ "Create", "stores", "a", "new", "revision", "for", "the", "given", "work", "item", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/workitem/workitem_revision_repository.go#L35-L59
13,153
fabric8-services/fabric8-wit
workitem/workitem_revision_repository.go
List
func (r *GormRevisionRepository) List(ctx context.Context, workitemID uuid.UUID) ([]Revision, error) { log.Debug(nil, map[string]interface{}{}, "List all revisions for work item with ID=%v", workitemID) var revisions []Revision if err := r.db.Where("work_item_id = ?", workitemID).Order("revision_time asc").Find(&revisions).Error; err != nil { return nil, errors.NewInternalError(ctx, errs.Wrap(err, "failed to retrieve work item revisions")) } return revisions, nil }
go
func (r *GormRevisionRepository) List(ctx context.Context, workitemID uuid.UUID) ([]Revision, error) { log.Debug(nil, map[string]interface{}{}, "List all revisions for work item with ID=%v", workitemID) var revisions []Revision if err := r.db.Where("work_item_id = ?", workitemID).Order("revision_time asc").Find(&revisions).Error; err != nil { return nil, errors.NewInternalError(ctx, errs.Wrap(err, "failed to retrieve work item revisions")) } return revisions, nil }
[ "func", "(", "r", "*", "GormRevisionRepository", ")", "List", "(", "ctx", "context", ".", "Context", ",", "workitemID", "uuid", ".", "UUID", ")", "(", "[", "]", "Revision", ",", "error", ")", "{", "log", ".", "Debug", "(", "nil", ",", "map", "[", "...
// List retrieves all revisions for a given work item
[ "List", "retrieves", "all", "revisions", "for", "a", "given", "work", "item" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/workitem/workitem_revision_repository.go#L62-L69
13,154
fabric8-services/fabric8-wit
controller/space_tracker_queries.go
NewSpaceTrackerQueriesController
func NewSpaceTrackerQueriesController(service *goa.Service, db application.DB, config SpaceTrackerQueriesControllerConfig) *SpaceTrackerQueriesController { return &SpaceTrackerQueriesController{ Controller: service.NewController("SpaceTrackerQueriesController"), db: db, config: config, } }
go
func NewSpaceTrackerQueriesController(service *goa.Service, db application.DB, config SpaceTrackerQueriesControllerConfig) *SpaceTrackerQueriesController { return &SpaceTrackerQueriesController{ Controller: service.NewController("SpaceTrackerQueriesController"), db: db, config: config, } }
[ "func", "NewSpaceTrackerQueriesController", "(", "service", "*", "goa", ".", "Service", ",", "db", "application", ".", "DB", ",", "config", "SpaceTrackerQueriesControllerConfig", ")", "*", "SpaceTrackerQueriesController", "{", "return", "&", "SpaceTrackerQueriesController...
// NewSpaceTrackerQueriesController creates a space_tracker_queries controller.
[ "NewSpaceTrackerQueriesController", "creates", "a", "space_tracker_queries", "controller", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/space_tracker_queries.go#L24-L30
13,155
fabric8-services/fabric8-wit
kubernetes/deployments_kubeclient.go
NewKubeClient
func NewKubeClient(config *KubeClientConfig) (KubeClientInterface, error) { // Use default implementation if no KubernetesGetter is specified if config.KubeRESTAPIGetter == nil { config.KubeRESTAPIGetter = &defaultGetter{} } // Use default implementation if no OpenShiftGetter is specified if config.OpenShiftRESTAPIGetter == nil { config.OpenShiftRESTAPIGetter = &defaultGetter{} } kubeAPI, err := config.GetKubeRESTAPI(config) if err != nil { return nil, err } osAPI, err := config.GetOpenShiftRESTAPI(config) if err != nil { return nil, err } // Use default implementation if no MetricsGetter is specified if config.MetricsGetter == nil { config.MetricsGetter = &defaultGetter{} } envMap := config.GetEnvironmentMapping() kubeClient := &kubeClient{ config: config, envMap: envMap, BaseURLProvider: config, KubeRESTAPI: kubeAPI, OpenShiftRESTAPI: osAPI, metricsMap: make(map[string]Metrics), rulesMap: make(map[string]*accessRules), MetricsGetter: config.MetricsGetter, } return kubeClient, nil }
go
func NewKubeClient(config *KubeClientConfig) (KubeClientInterface, error) { // Use default implementation if no KubernetesGetter is specified if config.KubeRESTAPIGetter == nil { config.KubeRESTAPIGetter = &defaultGetter{} } // Use default implementation if no OpenShiftGetter is specified if config.OpenShiftRESTAPIGetter == nil { config.OpenShiftRESTAPIGetter = &defaultGetter{} } kubeAPI, err := config.GetKubeRESTAPI(config) if err != nil { return nil, err } osAPI, err := config.GetOpenShiftRESTAPI(config) if err != nil { return nil, err } // Use default implementation if no MetricsGetter is specified if config.MetricsGetter == nil { config.MetricsGetter = &defaultGetter{} } envMap := config.GetEnvironmentMapping() kubeClient := &kubeClient{ config: config, envMap: envMap, BaseURLProvider: config, KubeRESTAPI: kubeAPI, OpenShiftRESTAPI: osAPI, metricsMap: make(map[string]Metrics), rulesMap: make(map[string]*accessRules), MetricsGetter: config.MetricsGetter, } return kubeClient, nil }
[ "func", "NewKubeClient", "(", "config", "*", "KubeClientConfig", ")", "(", "KubeClientInterface", ",", "error", ")", "{", "// Use default implementation if no KubernetesGetter is specified", "if", "config", ".", "KubeRESTAPIGetter", "==", "nil", "{", "config", ".", "Kub...
// NewKubeClient creates a KubeClientInterface given a configuration. The returned // KubeClientInterface must be closed using the Close method, when no longer needed.
[ "NewKubeClient", "creates", "a", "KubeClientInterface", "given", "a", "configuration", ".", "The", "returned", "KubeClientInterface", "must", "be", "closed", "using", "the", "Close", "method", "when", "no", "longer", "needed", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/kubernetes/deployments_kubeclient.go#L172-L207
13,156
fabric8-services/fabric8-wit
kubernetes/deployments_kubeclient.go
GetSpace
func (kc *kubeClient) GetSpace(spaceName string) (*app.SimpleSpace, error) { // Get BuildConfigs within the user namespace that have a matching 'space' label // This is similar to how pipelines are displayed in fabric8-ui // https://github.com/fabric8-ui/fabric8-ui/blob/master/src/app/space/create/pipelines/pipelines.component.ts buildconfigs, err := kc.getBuildConfigsForSpace(spaceName) if err != nil { return nil, err } // Get all applications in this space using BuildConfig names apps := []*app.SimpleApp{} for _, bc := range buildconfigs { appn, err := kc.GetApplication(spaceName, bc) if err != nil { return nil, err } apps = append(apps, appn) } result := &app.SimpleSpace{ Type: "space", Attributes: &app.SimpleSpaceAttributes{ Name: spaceName, Applications: apps, }, } return result, nil }
go
func (kc *kubeClient) GetSpace(spaceName string) (*app.SimpleSpace, error) { // Get BuildConfigs within the user namespace that have a matching 'space' label // This is similar to how pipelines are displayed in fabric8-ui // https://github.com/fabric8-ui/fabric8-ui/blob/master/src/app/space/create/pipelines/pipelines.component.ts buildconfigs, err := kc.getBuildConfigsForSpace(spaceName) if err != nil { return nil, err } // Get all applications in this space using BuildConfig names apps := []*app.SimpleApp{} for _, bc := range buildconfigs { appn, err := kc.GetApplication(spaceName, bc) if err != nil { return nil, err } apps = append(apps, appn) } result := &app.SimpleSpace{ Type: "space", Attributes: &app.SimpleSpaceAttributes{ Name: spaceName, Applications: apps, }, } return result, nil }
[ "func", "(", "kc", "*", "kubeClient", ")", "GetSpace", "(", "spaceName", "string", ")", "(", "*", "app", ".", "SimpleSpace", ",", "error", ")", "{", "// Get BuildConfigs within the user namespace that have a matching 'space' label", "// This is similar to how pipelines are ...
// GetSpace returns a space matching the provided name, containing all applications that belong to it
[ "GetSpace", "returns", "a", "space", "matching", "the", "provided", "name", "containing", "all", "applications", "that", "belong", "to", "it" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/kubernetes/deployments_kubeclient.go#L289-L317
13,157
fabric8-services/fabric8-wit
kubernetes/deployments_kubeclient.go
GetApplication
func (kc *kubeClient) GetApplication(spaceName string, appName string) (*app.SimpleApp, error) { // Get all deployments of this app for each environment in this space deployments := []*app.SimpleDeployment{} for envName := range kc.envMap { // Only look for the application in environments where the user can deploy applications if kc.CanDeploy(envName) { deployment, err := kc.GetDeployment(spaceName, appName, envName) if err != nil { return nil, err } else if deployment != nil { deployments = append(deployments, deployment) } } } result := &app.SimpleApp{ Type: "application", Attributes: &app.SimpleAppAttributes{ Name: appName, Deployments: deployments, }, ID: appName, } return result, nil }
go
func (kc *kubeClient) GetApplication(spaceName string, appName string) (*app.SimpleApp, error) { // Get all deployments of this app for each environment in this space deployments := []*app.SimpleDeployment{} for envName := range kc.envMap { // Only look for the application in environments where the user can deploy applications if kc.CanDeploy(envName) { deployment, err := kc.GetDeployment(spaceName, appName, envName) if err != nil { return nil, err } else if deployment != nil { deployments = append(deployments, deployment) } } } result := &app.SimpleApp{ Type: "application", Attributes: &app.SimpleAppAttributes{ Name: appName, Deployments: deployments, }, ID: appName, } return result, nil }
[ "func", "(", "kc", "*", "kubeClient", ")", "GetApplication", "(", "spaceName", "string", ",", "appName", "string", ")", "(", "*", "app", ".", "SimpleApp", ",", "error", ")", "{", "// Get all deployments of this app for each environment in this space", "deployments", ...
// GetApplication retrieves an application with the given space and application names, with the status // of that application's deployment in each environment
[ "GetApplication", "retrieves", "an", "application", "with", "the", "given", "space", "and", "application", "names", "with", "the", "status", "of", "that", "application", "s", "deployment", "in", "each", "environment" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/kubernetes/deployments_kubeclient.go#L321-L345
13,158
fabric8-services/fabric8-wit
kubernetes/deployments_kubeclient.go
ScaleDeployment
func (kc *kubeClient) ScaleDeployment(spaceName string, appName string, envName string, deployNumber int) (*int, error) { envNS, err := kc.getDeployableEnvironmentNamespace(envName) if err != nil { return nil, err } // Deployment Config name does not always match the application name, look up // DC name using available metadata dcName, err := kc.getDeploymentConfigNameForApp(envNS, appName, spaceName) if err != nil { return nil, err } // Look up the Scale for the DeploymentConfig corresponding to the application name in the provided environment scale, err := kc.GetDeploymentConfigScale(envNS, dcName) if err != nil { return nil, err } spec, ok := scale["spec"].(map[string]interface{}) if !ok { log.Error(nil, map[string]interface{}{ "err": err, "space_name": spaceName, "application_name": appName, "environment_name": envName, }, "invalid deployment config returned from endpoint") return nil, errs.New("invalid deployment config returned from endpoint: missing 'spec'") } replicas, pres := spec["replicas"] oldReplicas := 0 // replicas property may be missing from spec if set to 0 if pres { oldReplicasFlt, ok := replicas.(float64) if !ok { return nil, errs.New("invalid deployment config returned from endpoint: 'replicas' is not a number") } oldReplicas = int(oldReplicasFlt) } spec["replicas"] = deployNumber _, err = kc.SetDeploymentConfigScale(envNS, dcName, scale) if err != nil { return nil, err } log.Info(nil, map[string]interface{}{ "space_name": spaceName, "application_name": appName, "environment_name": envName, "old_replica_count": oldReplicas, "new_replica_count": deployNumber, }, "scaled deployment to %d replicas", deployNumber) return &oldReplicas, nil }
go
func (kc *kubeClient) ScaleDeployment(spaceName string, appName string, envName string, deployNumber int) (*int, error) { envNS, err := kc.getDeployableEnvironmentNamespace(envName) if err != nil { return nil, err } // Deployment Config name does not always match the application name, look up // DC name using available metadata dcName, err := kc.getDeploymentConfigNameForApp(envNS, appName, spaceName) if err != nil { return nil, err } // Look up the Scale for the DeploymentConfig corresponding to the application name in the provided environment scale, err := kc.GetDeploymentConfigScale(envNS, dcName) if err != nil { return nil, err } spec, ok := scale["spec"].(map[string]interface{}) if !ok { log.Error(nil, map[string]interface{}{ "err": err, "space_name": spaceName, "application_name": appName, "environment_name": envName, }, "invalid deployment config returned from endpoint") return nil, errs.New("invalid deployment config returned from endpoint: missing 'spec'") } replicas, pres := spec["replicas"] oldReplicas := 0 // replicas property may be missing from spec if set to 0 if pres { oldReplicasFlt, ok := replicas.(float64) if !ok { return nil, errs.New("invalid deployment config returned from endpoint: 'replicas' is not a number") } oldReplicas = int(oldReplicasFlt) } spec["replicas"] = deployNumber _, err = kc.SetDeploymentConfigScale(envNS, dcName, scale) if err != nil { return nil, err } log.Info(nil, map[string]interface{}{ "space_name": spaceName, "application_name": appName, "environment_name": envName, "old_replica_count": oldReplicas, "new_replica_count": deployNumber, }, "scaled deployment to %d replicas", deployNumber) return &oldReplicas, nil }
[ "func", "(", "kc", "*", "kubeClient", ")", "ScaleDeployment", "(", "spaceName", "string", ",", "appName", "string", ",", "envName", "string", ",", "deployNumber", "int", ")", "(", "*", "int", ",", "error", ")", "{", "envNS", ",", "err", ":=", "kc", "."...
// ScaleDeployment adjusts the desired number of replicas for a specified application, returning the // previous number of desired replicas
[ "ScaleDeployment", "adjusts", "the", "desired", "number", "of", "replicas", "for", "a", "specified", "application", "returning", "the", "previous", "number", "of", "desired", "replicas" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/kubernetes/deployments_kubeclient.go#L349-L404
13,159
fabric8-services/fabric8-wit
kubernetes/deployments_kubeclient.go
GetDeployment
func (kc *kubeClient) GetDeployment(spaceName string, appName string, envName string) (*app.SimpleDeployment, error) { envNS, err := kc.getDeployableEnvironmentNamespace(envName) if err != nil { return nil, err } // Get the UID for the current deployment of the app deploy, err := kc.getCurrentDeployment(spaceName, appName, envNS) if err != nil { return nil, err } else if deploy == nil || deploy.current == nil { return nil, nil } // Get all pods created by this deployment pods, err := kc.getPods(envNS, deploy.current) if err != nil { return nil, err } // Get the quota for all pods in the deployment podsQuota, err := kc.getPodsQuota(pods) if err != nil { return nil, err } // Get the status of each pod in the deployment podStats, total := kc.getPodStatus(pods) // Get related URLs for the deployment appURL, err := kc.getApplicationURL(envNS, deploy) if err != nil { return nil, err } consoleURL, err := kc.GetConsoleURL(envNS) if err != nil { return nil, err } logURL, err := kc.GetLoggingURL(envNS, deploy.current.Name) if err != nil { return nil, err } var links *app.GenericLinksForDeployment if consoleURL != nil || appURL != nil || logURL != nil { links = &app.GenericLinksForDeployment{ Console: consoleURL, Logs: logURL, Application: appURL, } } verString := string(deploy.appVersion) result := &app.SimpleDeployment{ Type: "deployment", Attributes: &app.SimpleDeploymentAttributes{ Name: envName, Version: &verString, Pods: podStats, PodTotal: &total, PodsQuota: podsQuota, }, ID: envName, Links: links, } return result, nil }
go
func (kc *kubeClient) GetDeployment(spaceName string, appName string, envName string) (*app.SimpleDeployment, error) { envNS, err := kc.getDeployableEnvironmentNamespace(envName) if err != nil { return nil, err } // Get the UID for the current deployment of the app deploy, err := kc.getCurrentDeployment(spaceName, appName, envNS) if err != nil { return nil, err } else if deploy == nil || deploy.current == nil { return nil, nil } // Get all pods created by this deployment pods, err := kc.getPods(envNS, deploy.current) if err != nil { return nil, err } // Get the quota for all pods in the deployment podsQuota, err := kc.getPodsQuota(pods) if err != nil { return nil, err } // Get the status of each pod in the deployment podStats, total := kc.getPodStatus(pods) // Get related URLs for the deployment appURL, err := kc.getApplicationURL(envNS, deploy) if err != nil { return nil, err } consoleURL, err := kc.GetConsoleURL(envNS) if err != nil { return nil, err } logURL, err := kc.GetLoggingURL(envNS, deploy.current.Name) if err != nil { return nil, err } var links *app.GenericLinksForDeployment if consoleURL != nil || appURL != nil || logURL != nil { links = &app.GenericLinksForDeployment{ Console: consoleURL, Logs: logURL, Application: appURL, } } verString := string(deploy.appVersion) result := &app.SimpleDeployment{ Type: "deployment", Attributes: &app.SimpleDeploymentAttributes{ Name: envName, Version: &verString, Pods: podStats, PodTotal: &total, PodsQuota: podsQuota, }, ID: envName, Links: links, } return result, nil }
[ "func", "(", "kc", "*", "kubeClient", ")", "GetDeployment", "(", "spaceName", "string", ",", "appName", "string", ",", "envName", "string", ")", "(", "*", "app", ".", "SimpleDeployment", ",", "error", ")", "{", "envNS", ",", "err", ":=", "kc", ".", "ge...
// GetDeployment returns information about the current deployment of an application within a // particular environment. The application must exist within the provided space.
[ "GetDeployment", "returns", "information", "about", "the", "current", "deployment", "of", "an", "application", "within", "a", "particular", "environment", ".", "The", "application", "must", "exist", "within", "the", "provided", "space", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/kubernetes/deployments_kubeclient.go#L433-L500
13,160
fabric8-services/fabric8-wit
kubernetes/deployments_kubeclient.go
GetDeploymentStats
func (kc *kubeClient) GetDeploymentStats(spaceName string, appName string, envName string, startTime time.Time) (*app.SimpleDeploymentStats, error) { envNS, err := kc.getDeployableEnvironmentNamespace(envName) if err != nil { return nil, err } // Get the UID for the current deployment of the app deploy, err := kc.getCurrentDeployment(spaceName, appName, envNS) if err != nil { return nil, err } else if deploy == nil || deploy.current == nil { return nil, nil } // Get pods belonging to current deployment pods, err := kc.getPods(envNS, deploy.current) if err != nil { return nil, err } mc, err := kc.GetMetricsClient(envNS) if err != nil { return nil, err } // Gather the statistics we need about the current deployment cpuUsage, err := mc.GetCPUMetrics(pods, envNS, startTime) if err != nil { return nil, err } memoryUsage, err := mc.GetMemoryMetrics(pods, envNS, startTime) if err != nil { return nil, err } netTxUsage, err := mc.GetNetworkSentMetrics(pods, envNS, startTime) if err != nil { return nil, err } netRxUsage, err := mc.GetNetworkRecvMetrics(pods, envNS, startTime) if err != nil { return nil, err } result := &app.SimpleDeploymentStats{ Type: "deploymentstats", Attributes: &app.SimpleDeploymentStatsAttributes{ Cores: cpuUsage, Memory: memoryUsage, NetTx: netTxUsage, NetRx: netRxUsage, }, } return result, nil }
go
func (kc *kubeClient) GetDeploymentStats(spaceName string, appName string, envName string, startTime time.Time) (*app.SimpleDeploymentStats, error) { envNS, err := kc.getDeployableEnvironmentNamespace(envName) if err != nil { return nil, err } // Get the UID for the current deployment of the app deploy, err := kc.getCurrentDeployment(spaceName, appName, envNS) if err != nil { return nil, err } else if deploy == nil || deploy.current == nil { return nil, nil } // Get pods belonging to current deployment pods, err := kc.getPods(envNS, deploy.current) if err != nil { return nil, err } mc, err := kc.GetMetricsClient(envNS) if err != nil { return nil, err } // Gather the statistics we need about the current deployment cpuUsage, err := mc.GetCPUMetrics(pods, envNS, startTime) if err != nil { return nil, err } memoryUsage, err := mc.GetMemoryMetrics(pods, envNS, startTime) if err != nil { return nil, err } netTxUsage, err := mc.GetNetworkSentMetrics(pods, envNS, startTime) if err != nil { return nil, err } netRxUsage, err := mc.GetNetworkRecvMetrics(pods, envNS, startTime) if err != nil { return nil, err } result := &app.SimpleDeploymentStats{ Type: "deploymentstats", Attributes: &app.SimpleDeploymentStatsAttributes{ Cores: cpuUsage, Memory: memoryUsage, NetTx: netTxUsage, NetRx: netRxUsage, }, } return result, nil }
[ "func", "(", "kc", "*", "kubeClient", ")", "GetDeploymentStats", "(", "spaceName", "string", ",", "appName", "string", ",", "envName", "string", ",", "startTime", "time", ".", "Time", ")", "(", "*", "app", ".", "SimpleDeploymentStats", ",", "error", ")", "...
// GetDeploymentStats returns performance metrics of an application for a period of 1 minute // beyond the specified start time, which are then aggregated into a single data point.
[ "GetDeploymentStats", "returns", "performance", "metrics", "of", "an", "application", "for", "a", "period", "of", "1", "minute", "beyond", "the", "specified", "start", "time", "which", "are", "then", "aggregated", "into", "a", "single", "data", "point", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/kubernetes/deployments_kubeclient.go#L504-L558
13,161
fabric8-services/fabric8-wit
kubernetes/deployments_kubeclient.go
GetDeploymentStatSeries
func (kc *kubeClient) GetDeploymentStatSeries(spaceName string, appName string, envName string, startTime time.Time, endTime time.Time, limit int) (*app.SimpleDeploymentStatSeries, error) { envNS, err := kc.getDeployableEnvironmentNamespace(envName) if err != nil { return nil, err } // Get the UID for the current deployment of the app deploy, err := kc.getCurrentDeployment(spaceName, appName, envNS) if err != nil { return nil, err } else if deploy == nil || deploy.current == nil { return nil, nil } // Get pods belonging to current deployment pods, err := kc.getPods(envNS, deploy.current) if err != nil { return nil, err } mc, err := kc.GetMetricsClient(envNS) if err != nil { return nil, err } // Get CPU, memory and network metrics for pods in deployment cpuMetrics, err := mc.GetCPUMetricsRange(pods, envNS, startTime, endTime, limit) if err != nil { return nil, err } memoryMetrics, err := mc.GetMemoryMetricsRange(pods, envNS, startTime, endTime, limit) if err != nil { return nil, err } netTxMetrics, err := mc.GetNetworkSentMetricsRange(pods, envNS, startTime, endTime, limit) if err != nil { return nil, err } netRxMetrics, err := mc.GetNetworkRecvMetricsRange(pods, envNS, startTime, endTime, limit) if err != nil { return nil, err } // Get the earliest and latest timestamps minTime, maxTime := getTimestampEndpoints(cpuMetrics, memoryMetrics) result := &app.SimpleDeploymentStatSeries{ Cores: cpuMetrics, Memory: memoryMetrics, NetTx: netTxMetrics, NetRx: netRxMetrics, Start: minTime, End: maxTime, } return result, nil }
go
func (kc *kubeClient) GetDeploymentStatSeries(spaceName string, appName string, envName string, startTime time.Time, endTime time.Time, limit int) (*app.SimpleDeploymentStatSeries, error) { envNS, err := kc.getDeployableEnvironmentNamespace(envName) if err != nil { return nil, err } // Get the UID for the current deployment of the app deploy, err := kc.getCurrentDeployment(spaceName, appName, envNS) if err != nil { return nil, err } else if deploy == nil || deploy.current == nil { return nil, nil } // Get pods belonging to current deployment pods, err := kc.getPods(envNS, deploy.current) if err != nil { return nil, err } mc, err := kc.GetMetricsClient(envNS) if err != nil { return nil, err } // Get CPU, memory and network metrics for pods in deployment cpuMetrics, err := mc.GetCPUMetricsRange(pods, envNS, startTime, endTime, limit) if err != nil { return nil, err } memoryMetrics, err := mc.GetMemoryMetricsRange(pods, envNS, startTime, endTime, limit) if err != nil { return nil, err } netTxMetrics, err := mc.GetNetworkSentMetricsRange(pods, envNS, startTime, endTime, limit) if err != nil { return nil, err } netRxMetrics, err := mc.GetNetworkRecvMetricsRange(pods, envNS, startTime, endTime, limit) if err != nil { return nil, err } // Get the earliest and latest timestamps minTime, maxTime := getTimestampEndpoints(cpuMetrics, memoryMetrics) result := &app.SimpleDeploymentStatSeries{ Cores: cpuMetrics, Memory: memoryMetrics, NetTx: netTxMetrics, NetRx: netRxMetrics, Start: minTime, End: maxTime, } return result, nil }
[ "func", "(", "kc", "*", "kubeClient", ")", "GetDeploymentStatSeries", "(", "spaceName", "string", ",", "appName", "string", ",", "envName", "string", ",", "startTime", "time", ".", "Time", ",", "endTime", "time", ".", "Time", ",", "limit", "int", ")", "(",...
// GetDeploymentStatSeries returns performance metrics of an application as a time series bounded by // the provided time range in startTime and endTime. If there are more data points than the // limit argument, only the newest datapoints within that limit are returned.
[ "GetDeploymentStatSeries", "returns", "performance", "metrics", "of", "an", "application", "as", "a", "time", "series", "bounded", "by", "the", "provided", "time", "range", "in", "startTime", "and", "endTime", ".", "If", "there", "are", "more", "data", "points",...
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/kubernetes/deployments_kubeclient.go#L563-L619
13,162
fabric8-services/fabric8-wit
kubernetes/deployments_kubeclient.go
GetEnvironments
func (kc *kubeClient) GetEnvironments() ([]*app.SimpleEnvironment, error) { envs := []*app.SimpleEnvironment{} for envName := range kc.envMap { // Only return environments where the user can deploy applications if kc.CanDeploy(envName) { env, err := kc.GetEnvironment(envName) if err != nil { return nil, err } envs = append(envs, env) } } return envs, nil }
go
func (kc *kubeClient) GetEnvironments() ([]*app.SimpleEnvironment, error) { envs := []*app.SimpleEnvironment{} for envName := range kc.envMap { // Only return environments where the user can deploy applications if kc.CanDeploy(envName) { env, err := kc.GetEnvironment(envName) if err != nil { return nil, err } envs = append(envs, env) } } return envs, nil }
[ "func", "(", "kc", "*", "kubeClient", ")", "GetEnvironments", "(", ")", "(", "[", "]", "*", "app", ".", "SimpleEnvironment", ",", "error", ")", "{", "envs", ":=", "[", "]", "*", "app", ".", "SimpleEnvironment", "{", "}", "\n", "for", "envName", ":=",...
// GetEnvironments retrieves information on all environments in the cluster // for the current user
[ "GetEnvironments", "retrieves", "information", "on", "all", "environments", "in", "the", "cluster", "for", "the", "current", "user" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/kubernetes/deployments_kubeclient.go#L675-L688
13,163
fabric8-services/fabric8-wit
kubernetes/deployments_kubeclient.go
GetEnvironment
func (kc *kubeClient) GetEnvironment(envName string) (*app.SimpleEnvironment, error) { envNS, err := kc.getDeployableEnvironmentNamespace(envName) if err != nil { return nil, err } envStats, err := kc.getResourceQuota(envNS) if err != nil { return nil, err } env := &app.SimpleEnvironment{ Type: "environment", Attributes: &app.SimpleEnvironmentAttributes{ Name: &envName, Quota: envStats, }, } return env, nil }
go
func (kc *kubeClient) GetEnvironment(envName string) (*app.SimpleEnvironment, error) { envNS, err := kc.getDeployableEnvironmentNamespace(envName) if err != nil { return nil, err } envStats, err := kc.getResourceQuota(envNS) if err != nil { return nil, err } env := &app.SimpleEnvironment{ Type: "environment", Attributes: &app.SimpleEnvironmentAttributes{ Name: &envName, Quota: envStats, }, } return env, nil }
[ "func", "(", "kc", "*", "kubeClient", ")", "GetEnvironment", "(", "envName", "string", ")", "(", "*", "app", ".", "SimpleEnvironment", ",", "error", ")", "{", "envNS", ",", "err", ":=", "kc", ".", "getDeployableEnvironmentNamespace", "(", "envName", ")", "...
// GetEnvironment returns information on an environment with the provided name
[ "GetEnvironment", "returns", "information", "on", "an", "environment", "with", "the", "provided", "name" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/kubernetes/deployments_kubeclient.go#L691-L710
13,164
fabric8-services/fabric8-wit
kubernetes/deployments_kubeclient.go
getDeployableEnvironmentNamespace
func (kc *kubeClient) getDeployableEnvironmentNamespace(envName string) (string, error) { envNS, pres := kc.envMap[envName] if !pres || !kc.CanDeploy(envName) { return "", errs.Errorf("unknown environment: %s", envName) } return envNS, nil }
go
func (kc *kubeClient) getDeployableEnvironmentNamespace(envName string) (string, error) { envNS, pres := kc.envMap[envName] if !pres || !kc.CanDeploy(envName) { return "", errs.Errorf("unknown environment: %s", envName) } return envNS, nil }
[ "func", "(", "kc", "*", "kubeClient", ")", "getDeployableEnvironmentNamespace", "(", "envName", "string", ")", "(", "string", ",", "error", ")", "{", "envNS", ",", "pres", ":=", "kc", ".", "envMap", "[", "envName", "]", "\n", "if", "!", "pres", "||", "...
// getDeployableEnvironmentNamespace finds a namespace with the corresponding environment name. // Differs from getEnvironmentNamespace in that the environment must be one where the user can deploy // applications
[ "getDeployableEnvironmentNamespace", "finds", "a", "namespace", "with", "the", "corresponding", "environment", "name", ".", "Differs", "from", "getEnvironmentNamespace", "in", "that", "the", "environment", "must", "be", "one", "where", "the", "user", "can", "deploy", ...
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/kubernetes/deployments_kubeclient.go#L779-L785
13,165
fabric8-services/fabric8-wit
kubernetes/deployments_kubeclient.go
getEnvironmentNamespace
func (kc *kubeClient) getEnvironmentNamespace(envName string) (string, error) { envNS, pres := kc.envMap[envName] if !pres { return "", errs.Errorf("unknown environment: %s", envName) } return envNS, nil }
go
func (kc *kubeClient) getEnvironmentNamespace(envName string) (string, error) { envNS, pres := kc.envMap[envName] if !pres { return "", errs.Errorf("unknown environment: %s", envName) } return envNS, nil }
[ "func", "(", "kc", "*", "kubeClient", ")", "getEnvironmentNamespace", "(", "envName", "string", ")", "(", "string", ",", "error", ")", "{", "envNS", ",", "pres", ":=", "kc", ".", "envMap", "[", "envName", "]", "\n", "if", "!", "pres", "{", "return", ...
// getEnvironmentNamespace finds a namespace with the corresponding environment name
[ "getEnvironmentNamespace", "finds", "a", "namespace", "with", "the", "corresponding", "environment", "name" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/kubernetes/deployments_kubeclient.go#L788-L794
13,166
fabric8-services/fabric8-wit
kubernetes/deployments_kubeclient.go
convertError
func convertError(err error, format string, args ...interface{}) error { message := format if len(args) > 0 { message = fmt.Sprintf(format, args...) } cause := errs.Cause(err) if statusError, ok := cause.(*kubeErrors.StatusError); ok { message = fmt.Sprintf("%s: %s", message, statusError.Error()) // Pass through certain HTTP statuses to our API response if kubeErrors.IsBadRequest(statusError) { return errors.NewBadParameterErrorFromString(message) } else if kubeErrors.IsNotFound(statusError) { return errors.NewNotFoundErrorFromString(message) } } return errors.NewInternalError(nil /* unused */, errs.Wrap(err, message)) }
go
func convertError(err error, format string, args ...interface{}) error { message := format if len(args) > 0 { message = fmt.Sprintf(format, args...) } cause := errs.Cause(err) if statusError, ok := cause.(*kubeErrors.StatusError); ok { message = fmt.Sprintf("%s: %s", message, statusError.Error()) // Pass through certain HTTP statuses to our API response if kubeErrors.IsBadRequest(statusError) { return errors.NewBadParameterErrorFromString(message) } else if kubeErrors.IsNotFound(statusError) { return errors.NewNotFoundErrorFromString(message) } } return errors.NewInternalError(nil /* unused */, errs.Wrap(err, message)) }
[ "func", "convertError", "(", "err", "error", ",", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "error", "{", "message", ":=", "format", "\n", "if", "len", "(", "args", ")", ">", "0", "{", "message", "=", "fmt", ".", "Sprintf", ...
// convertError converts a Kubernetes API error into an error suitable to be // passed to jsonapi.ErrorToJSONAPIError. The format and args arguments are used // to construct an error message, in a similar fashion to fmt.Sprintf.
[ "convertError", "converts", "a", "Kubernetes", "API", "error", "into", "an", "error", "suitable", "to", "be", "passed", "to", "jsonapi", ".", "ErrorToJSONAPIError", ".", "The", "format", "and", "args", "arguments", "are", "used", "to", "construct", "an", "erro...
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/kubernetes/deployments_kubeclient.go#L2331-L2348
13,167
fabric8-services/fabric8-wit
account/init_tenant.go
NewInitTenant
func NewInitTenant(config tenantConfig) func(context.Context) error { return func(ctx context.Context) error { return InitTenant(ctx, config) } }
go
func NewInitTenant(config tenantConfig) func(context.Context) error { return func(ctx context.Context) error { return InitTenant(ctx, config) } }
[ "func", "NewInitTenant", "(", "config", "tenantConfig", ")", "func", "(", "context", ".", "Context", ")", "error", "{", "return", "func", "(", "ctx", "context", ".", "Context", ")", "error", "{", "return", "InitTenant", "(", "ctx", ",", "config", ")", "\...
// NewInitTenant creates a new tenant service in oso
[ "NewInitTenant", "creates", "a", "new", "tenant", "service", "in", "oso" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/account/init_tenant.go#L24-L28
13,168
fabric8-services/fabric8-wit
account/init_tenant.go
NewUpdateTenant
func NewUpdateTenant(config tenantConfig) func(context.Context) error { return func(ctx context.Context) error { return UpdateTenant(ctx, config) } }
go
func NewUpdateTenant(config tenantConfig) func(context.Context) error { return func(ctx context.Context) error { return UpdateTenant(ctx, config) } }
[ "func", "NewUpdateTenant", "(", "config", "tenantConfig", ")", "func", "(", "context", ".", "Context", ")", "error", "{", "return", "func", "(", "ctx", "context", ".", "Context", ")", "error", "{", "return", "UpdateTenant", "(", "ctx", ",", "config", ")", ...
// NewUpdateTenant creates a new tenant service in oso
[ "NewUpdateTenant", "creates", "a", "new", "tenant", "service", "in", "oso" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/account/init_tenant.go#L31-L35
13,169
fabric8-services/fabric8-wit
account/init_tenant.go
NewCleanTenant
func NewCleanTenant(config tenantConfig) func(context.Context, bool) error { return func(ctx context.Context, remove bool) error { return CleanTenant(ctx, config, remove) } }
go
func NewCleanTenant(config tenantConfig) func(context.Context, bool) error { return func(ctx context.Context, remove bool) error { return CleanTenant(ctx, config, remove) } }
[ "func", "NewCleanTenant", "(", "config", "tenantConfig", ")", "func", "(", "context", ".", "Context", ",", "bool", ")", "error", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "remove", "bool", ")", "error", "{", "return", "CleanTenant"...
// NewCleanTenant creates a new tenant service in oso
[ "NewCleanTenant", "creates", "a", "new", "tenant", "service", "in", "oso" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/account/init_tenant.go#L38-L42
13,170
fabric8-services/fabric8-wit
account/init_tenant.go
NewShowTenant
func NewShowTenant(config tenantConfig) CodebaseInitTenantProvider { return func(ctx context.Context) (*tenant.TenantSingle, error) { return ShowTenant(ctx, config) } }
go
func NewShowTenant(config tenantConfig) CodebaseInitTenantProvider { return func(ctx context.Context) (*tenant.TenantSingle, error) { return ShowTenant(ctx, config) } }
[ "func", "NewShowTenant", "(", "config", "tenantConfig", ")", "CodebaseInitTenantProvider", "{", "return", "func", "(", "ctx", "context", ".", "Context", ")", "(", "*", "tenant", ".", "TenantSingle", ",", "error", ")", "{", "return", "ShowTenant", "(", "ctx", ...
// NewShowTenant view an existing tenant in oso
[ "NewShowTenant", "view", "an", "existing", "tenant", "in", "oso" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/account/init_tenant.go#L48-L52
13,171
fabric8-services/fabric8-wit
account/init_tenant.go
InitTenant
func InitTenant(ctx context.Context, config tenantConfig) error { c, err := createClient(ctx, config) if err != nil { return err } // Ignore response for now res, err := c.SetupTenant(goasupport.ForwardContextRequestID(ctx), tenant.SetupTenantPath()) defer rest.CloseResponse(res) return err }
go
func InitTenant(ctx context.Context, config tenantConfig) error { c, err := createClient(ctx, config) if err != nil { return err } // Ignore response for now res, err := c.SetupTenant(goasupport.ForwardContextRequestID(ctx), tenant.SetupTenantPath()) defer rest.CloseResponse(res) return err }
[ "func", "InitTenant", "(", "ctx", "context", ".", "Context", ",", "config", "tenantConfig", ")", "error", "{", "c", ",", "err", ":=", "createClient", "(", "ctx", ",", "config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n...
// InitTenant creates a new tenant service in oso
[ "InitTenant", "creates", "a", "new", "tenant", "service", "in", "oso" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/account/init_tenant.go#L55-L67
13,172
fabric8-services/fabric8-wit
account/init_tenant.go
UpdateTenant
func UpdateTenant(ctx context.Context, config tenantConfig) error { c, err := createClient(ctx, config) if err != nil { return err } // Ignore response for now res, err := c.UpdateTenant(goasupport.ForwardContextRequestID(ctx), tenant.UpdateTenantPath()) defer rest.CloseResponse(res) return err }
go
func UpdateTenant(ctx context.Context, config tenantConfig) error { c, err := createClient(ctx, config) if err != nil { return err } // Ignore response for now res, err := c.UpdateTenant(goasupport.ForwardContextRequestID(ctx), tenant.UpdateTenantPath()) defer rest.CloseResponse(res) return err }
[ "func", "UpdateTenant", "(", "ctx", "context", ".", "Context", ",", "config", "tenantConfig", ")", "error", "{", "c", ",", "err", ":=", "createClient", "(", "ctx", ",", "config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "...
// UpdateTenant updates excisting tenant in oso
[ "UpdateTenant", "updates", "excisting", "tenant", "in", "oso" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/account/init_tenant.go#L70-L82
13,173
fabric8-services/fabric8-wit
account/init_tenant.go
CleanTenant
func CleanTenant(ctx context.Context, config tenantConfig, remove bool, options ...configuration.HTTPClientOption) error { c, err := createClient(ctx, config, options...) if err != nil { return err } res, err := c.CleanTenant(goasupport.ForwardContextRequestID(ctx), tenant.CleanTenantPath(), &remove) if err != nil { return err } defer rest.CloseResponse(res) // operation failed for some reason if res.StatusCode < 200 || res.StatusCode >= 300 { jsonErr, err := c.DecodeJSONAPIErrors(res) if err == nil && len(jsonErr.Errors) > 0 { return errors.FromStatusCode(res.StatusCode, jsonErr.Errors[0].Detail) } // if failed to decode the response body into a JSON-API error, or if the JSON-API error was empty return errors.FromStatusCode(res.StatusCode, "unknown error") } // operation succeeded return nil }
go
func CleanTenant(ctx context.Context, config tenantConfig, remove bool, options ...configuration.HTTPClientOption) error { c, err := createClient(ctx, config, options...) if err != nil { return err } res, err := c.CleanTenant(goasupport.ForwardContextRequestID(ctx), tenant.CleanTenantPath(), &remove) if err != nil { return err } defer rest.CloseResponse(res) // operation failed for some reason if res.StatusCode < 200 || res.StatusCode >= 300 { jsonErr, err := c.DecodeJSONAPIErrors(res) if err == nil && len(jsonErr.Errors) > 0 { return errors.FromStatusCode(res.StatusCode, jsonErr.Errors[0].Detail) } // if failed to decode the response body into a JSON-API error, or if the JSON-API error was empty return errors.FromStatusCode(res.StatusCode, "unknown error") } // operation succeeded return nil }
[ "func", "CleanTenant", "(", "ctx", "context", ".", "Context", ",", "config", "tenantConfig", ",", "remove", "bool", ",", "options", "...", "configuration", ".", "HTTPClientOption", ")", "error", "{", "c", ",", "err", ":=", "createClient", "(", "ctx", ",", ...
// CleanTenant cleans out a tenant in oso.
[ "CleanTenant", "cleans", "out", "a", "tenant", "in", "oso", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/account/init_tenant.go#L85-L109
13,174
fabric8-services/fabric8-wit
account/init_tenant.go
ShowTenant
func ShowTenant(ctx context.Context, config tenantConfig, options ...configuration.HTTPClientOption) (*tenant.TenantSingle, error) { c, err := createClient(ctx, config, options...) if err != nil { return nil, err } res, err := c.ShowTenant(goasupport.ForwardContextRequestID(ctx), tenant.ShowTenantPath()) if err != nil { return nil, err } defer rest.CloseResponse(res) switch res.StatusCode { case http.StatusOK: tenant, err := c.DecodeTenantSingle(res) if err != nil { return nil, errors.NewInternalError(ctx, err) } return tenant, nil case http.StatusNotFound: jsonErr, err := c.DecodeJSONAPIErrors(res) if err == nil { if len(jsonErr.Errors) > 0 { log.Error(ctx, map[string]interface{}{ "error_msg": jsonErr.Errors[0].Detail, }, "failed to retrieve tenant") return nil, errors.NewNotFoundError("tenants", *jsonErr.Errors[0].ID) } } else { log.Error(ctx, map[string]interface{}{"error_msg": err}, "failed to parse JSON-API error response") } } return nil, errors.NewInternalError(ctx, fmt.Errorf("Unknown response: '%v' (%d)", res.Status, res.StatusCode)) }
go
func ShowTenant(ctx context.Context, config tenantConfig, options ...configuration.HTTPClientOption) (*tenant.TenantSingle, error) { c, err := createClient(ctx, config, options...) if err != nil { return nil, err } res, err := c.ShowTenant(goasupport.ForwardContextRequestID(ctx), tenant.ShowTenantPath()) if err != nil { return nil, err } defer rest.CloseResponse(res) switch res.StatusCode { case http.StatusOK: tenant, err := c.DecodeTenantSingle(res) if err != nil { return nil, errors.NewInternalError(ctx, err) } return tenant, nil case http.StatusNotFound: jsonErr, err := c.DecodeJSONAPIErrors(res) if err == nil { if len(jsonErr.Errors) > 0 { log.Error(ctx, map[string]interface{}{ "error_msg": jsonErr.Errors[0].Detail, }, "failed to retrieve tenant") return nil, errors.NewNotFoundError("tenants", *jsonErr.Errors[0].ID) } } else { log.Error(ctx, map[string]interface{}{"error_msg": err}, "failed to parse JSON-API error response") } } return nil, errors.NewInternalError(ctx, fmt.Errorf("Unknown response: '%v' (%d)", res.Status, res.StatusCode)) }
[ "func", "ShowTenant", "(", "ctx", "context", ".", "Context", ",", "config", "tenantConfig", ",", "options", "...", "configuration", ".", "HTTPClientOption", ")", "(", "*", "tenant", ".", "TenantSingle", ",", "error", ")", "{", "c", ",", "err", ":=", "creat...
// ShowTenant fetches the current tenant state.
[ "ShowTenant", "fetches", "the", "current", "tenant", "state", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/account/init_tenant.go#L112-L144
13,175
fabric8-services/fabric8-wit
account/init_tenant.go
createClient
func createClient(ctx context.Context, config tenantConfig, options ...configuration.HTTPClientOption) (*tenant.Client, error) { u, err := url.Parse(config.GetTenantServiceURL()) if err != nil { return nil, err } httpClient := http.DefaultClient // apply options for _, opt := range options { opt(httpClient) } c := tenant.New(goaclient.HTTPClientDoer(httpClient)) c.Host = u.Host c.Scheme = u.Scheme c.SetJWTSigner(goasupport.NewForwardSigner(ctx)) return c, nil }
go
func createClient(ctx context.Context, config tenantConfig, options ...configuration.HTTPClientOption) (*tenant.Client, error) { u, err := url.Parse(config.GetTenantServiceURL()) if err != nil { return nil, err } httpClient := http.DefaultClient // apply options for _, opt := range options { opt(httpClient) } c := tenant.New(goaclient.HTTPClientDoer(httpClient)) c.Host = u.Host c.Scheme = u.Scheme c.SetJWTSigner(goasupport.NewForwardSigner(ctx)) return c, nil }
[ "func", "createClient", "(", "ctx", "context", ".", "Context", ",", "config", "tenantConfig", ",", "options", "...", "configuration", ".", "HTTPClientOption", ")", "(", "*", "tenant", ".", "Client", ",", "error", ")", "{", "u", ",", "err", ":=", "url", "...
// createClient creates a client to the tenant service with the given configuration and options for the underlying HTTP client
[ "createClient", "creates", "a", "client", "to", "the", "tenant", "service", "with", "the", "given", "configuration", "and", "options", "for", "the", "underlying", "HTTP", "client" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/account/init_tenant.go#L147-L162
13,176
fabric8-services/fabric8-wit
criteria/expression_child.go
Child
func Child(left Expression, right Expression) Expression { return reparent(&ChildExpression{binaryExpression{expression{}, left, right}}) }
go
func Child(left Expression, right Expression) Expression { return reparent(&ChildExpression{binaryExpression{expression{}, left, right}}) }
[ "func", "Child", "(", "left", "Expression", ",", "right", "Expression", ")", "Expression", "{", "return", "reparent", "(", "&", "ChildExpression", "{", "binaryExpression", "{", "expression", "{", "}", ",", "left", ",", "right", "}", "}", ")", "\n", "}" ]
// Child constructs a ChildExpression
[ "Child", "constructs", "a", "ChildExpression" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/criteria/expression_child.go#L18-L20
13,177
fabric8-services/fabric8-wit
controller/label.go
NewLabelController
func NewLabelController(service *goa.Service, db application.DB, config LabelControllerConfiguration) *LabelController { return &LabelController{ Controller: service.NewController("LabelController"), db: db, config: config} }
go
func NewLabelController(service *goa.Service, db application.DB, config LabelControllerConfiguration) *LabelController { return &LabelController{ Controller: service.NewController("LabelController"), db: db, config: config} }
[ "func", "NewLabelController", "(", "service", "*", "goa", ".", "Service", ",", "db", "application", ".", "DB", ",", "config", "LabelControllerConfiguration", ")", "*", "LabelController", "{", "return", "&", "LabelController", "{", "Controller", ":", "service", "...
// NewLabelController creates a label controller.
[ "NewLabelController", "creates", "a", "label", "controller", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/label.go#L34-L39
13,178
fabric8-services/fabric8-wit
controller/label.go
Show
func (c *LabelController) Show(ctx *app.ShowLabelContext) error { var lbl *label.Label err := application.Transactional(c.db, func(appl application.Application) error { var err error lbl, err = appl.Labels().Load(ctx, ctx.LabelID) return err }) if err != nil { return jsonapi.JSONErrorResponse(ctx, err) } return ctx.OK(&app.LabelSingle{ Data: ConvertLabel(ctx.Request, *lbl), }) }
go
func (c *LabelController) Show(ctx *app.ShowLabelContext) error { var lbl *label.Label err := application.Transactional(c.db, func(appl application.Application) error { var err error lbl, err = appl.Labels().Load(ctx, ctx.LabelID) return err }) if err != nil { return jsonapi.JSONErrorResponse(ctx, err) } return ctx.OK(&app.LabelSingle{ Data: ConvertLabel(ctx.Request, *lbl), }) }
[ "func", "(", "c", "*", "LabelController", ")", "Show", "(", "ctx", "*", "app", ".", "ShowLabelContext", ")", "error", "{", "var", "lbl", "*", "label", ".", "Label", "\n", "err", ":=", "application", ".", "Transactional", "(", "c", ".", "db", ",", "fu...
// Show retrieve a single label
[ "Show", "retrieve", "a", "single", "label" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/label.go#L42-L55
13,179
fabric8-services/fabric8-wit
controller/label.go
ConvertLabel
func ConvertLabel(request *http.Request, lbl label.Label) *app.Label { labelType := label.APIStringTypeLabels spaceID := lbl.SpaceID.String() relatedURL := rest.AbsoluteURL(request, app.LabelHref(spaceID, lbl.ID)) spaceRelatedURL := rest.AbsoluteURL(request, app.SpaceHref(spaceID)) l := &app.Label{ Type: labelType, ID: &lbl.ID, Attributes: &app.LabelAttributes{ TextColor: &lbl.TextColor, BackgroundColor: &lbl.BackgroundColor, BorderColor: &lbl.BorderColor, Name: &lbl.Name, CreatedAt: &lbl.CreatedAt, UpdatedAt: &lbl.UpdatedAt, Version: &lbl.Version, }, Relationships: &app.LabelRelations{ Space: &app.RelationGeneric{ Data: &app.GenericData{ Type: &space.SpaceType, ID: &spaceID, }, Links: &app.GenericLinks{ Self: &spaceRelatedURL, Related: &spaceRelatedURL, }, }, }, Links: &app.GenericLinks{ Self: &relatedURL, Related: &relatedURL, }, } return l }
go
func ConvertLabel(request *http.Request, lbl label.Label) *app.Label { labelType := label.APIStringTypeLabels spaceID := lbl.SpaceID.String() relatedURL := rest.AbsoluteURL(request, app.LabelHref(spaceID, lbl.ID)) spaceRelatedURL := rest.AbsoluteURL(request, app.SpaceHref(spaceID)) l := &app.Label{ Type: labelType, ID: &lbl.ID, Attributes: &app.LabelAttributes{ TextColor: &lbl.TextColor, BackgroundColor: &lbl.BackgroundColor, BorderColor: &lbl.BorderColor, Name: &lbl.Name, CreatedAt: &lbl.CreatedAt, UpdatedAt: &lbl.UpdatedAt, Version: &lbl.Version, }, Relationships: &app.LabelRelations{ Space: &app.RelationGeneric{ Data: &app.GenericData{ Type: &space.SpaceType, ID: &spaceID, }, Links: &app.GenericLinks{ Self: &spaceRelatedURL, Related: &spaceRelatedURL, }, }, }, Links: &app.GenericLinks{ Self: &relatedURL, Related: &relatedURL, }, } return l }
[ "func", "ConvertLabel", "(", "request", "*", "http", ".", "Request", ",", "lbl", "label", ".", "Label", ")", "*", "app", ".", "Label", "{", "labelType", ":=", "label", ".", "APIStringTypeLabels", "\n", "spaceID", ":=", "lbl", ".", "SpaceID", ".", "String...
// ConvertLabel converts from internal to external REST representation
[ "ConvertLabel", "converts", "from", "internal", "to", "external", "REST", "representation" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/label.go#L93-L129
13,180
fabric8-services/fabric8-wit
controller/label.go
ConvertLabels
func ConvertLabels(appl application.Application, request *http.Request, labels []label.Label) []*app.Label { var ls = []*app.Label{} for _, i := range labels { ls = append(ls, ConvertLabel(request, i)) } return ls }
go
func ConvertLabels(appl application.Application, request *http.Request, labels []label.Label) []*app.Label { var ls = []*app.Label{} for _, i := range labels { ls = append(ls, ConvertLabel(request, i)) } return ls }
[ "func", "ConvertLabels", "(", "appl", "application", ".", "Application", ",", "request", "*", "http", ".", "Request", ",", "labels", "[", "]", "label", ".", "Label", ")", "[", "]", "*", "app", ".", "Label", "{", "var", "ls", "=", "[", "]", "*", "ap...
// ConvertLabels from internal to external REST representation
[ "ConvertLabels", "from", "internal", "to", "external", "REST", "representation" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/label.go#L149-L155
13,181
fabric8-services/fabric8-wit
controller/label.go
ConvertLabelsSimple
func ConvertLabelsSimple(request *http.Request, labelIDs []interface{}) []*app.GenericData { ops := make([]*app.GenericData, 0, len(labelIDs)) for _, labelID := range labelIDs { ops = append(ops, ConvertLabelSimple(request, labelID)) } return ops }
go
func ConvertLabelsSimple(request *http.Request, labelIDs []interface{}) []*app.GenericData { ops := make([]*app.GenericData, 0, len(labelIDs)) for _, labelID := range labelIDs { ops = append(ops, ConvertLabelSimple(request, labelID)) } return ops }
[ "func", "ConvertLabelsSimple", "(", "request", "*", "http", ".", "Request", ",", "labelIDs", "[", "]", "interface", "{", "}", ")", "[", "]", "*", "app", ".", "GenericData", "{", "ops", ":=", "make", "(", "[", "]", "*", "app", ".", "GenericData", ",",...
// ConvertLabelsSimple converts an array of Label IDs into a Generic Relationship List
[ "ConvertLabelsSimple", "converts", "an", "array", "of", "Label", "IDs", "into", "a", "Generic", "Relationship", "List" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/label.go#L158-L164
13,182
fabric8-services/fabric8-wit
controller/label.go
ConvertLabelSimple
func ConvertLabelSimple(request *http.Request, labelID interface{}) *app.GenericData { i := fmt.Sprint(labelID) return &app.GenericData{ Type: ptr.String(label.APIStringTypeLabels), ID: &i, } }
go
func ConvertLabelSimple(request *http.Request, labelID interface{}) *app.GenericData { i := fmt.Sprint(labelID) return &app.GenericData{ Type: ptr.String(label.APIStringTypeLabels), ID: &i, } }
[ "func", "ConvertLabelSimple", "(", "request", "*", "http", ".", "Request", ",", "labelID", "interface", "{", "}", ")", "*", "app", ".", "GenericData", "{", "i", ":=", "fmt", ".", "Sprint", "(", "labelID", ")", "\n", "return", "&", "app", ".", "GenericD...
// ConvertLabelSimple converts a Label ID into a Generic Relationship
[ "ConvertLabelSimple", "converts", "a", "Label", "ID", "into", "a", "Generic", "Relationship" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/label.go#L167-L173
13,183
fabric8-services/fabric8-wit
controller/work_item_comments.go
NewWorkItemCommentsController
func NewWorkItemCommentsController(service *goa.Service, db application.DB, config WorkItemCommentsControllerConfiguration) *WorkItemCommentsController { return NewNotifyingWorkItemCommentsController(service, db, &notification.DevNullChannel{}, config) }
go
func NewWorkItemCommentsController(service *goa.Service, db application.DB, config WorkItemCommentsControllerConfiguration) *WorkItemCommentsController { return NewNotifyingWorkItemCommentsController(service, db, &notification.DevNullChannel{}, config) }
[ "func", "NewWorkItemCommentsController", "(", "service", "*", "goa", ".", "Service", ",", "db", "application", ".", "DB", ",", "config", "WorkItemCommentsControllerConfiguration", ")", "*", "WorkItemCommentsController", "{", "return", "NewNotifyingWorkItemCommentsController...
// NewWorkItemCommentsController creates a work-item-relationships-comments controller.
[ "NewWorkItemCommentsController", "creates", "a", "work", "-", "item", "-", "relationships", "-", "comments", "controller", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/work_item_comments.go#L36-L38
13,184
fabric8-services/fabric8-wit
controller/work_item_comments.go
NewNotifyingWorkItemCommentsController
func NewNotifyingWorkItemCommentsController(service *goa.Service, db application.DB, notificationChannel notification.Channel, config WorkItemCommentsControllerConfiguration) *WorkItemCommentsController { n := notificationChannel if n == nil { n = &notification.DevNullChannel{} } return &WorkItemCommentsController{ Controller: service.NewController("WorkItemRelationshipsCommentsController"), db: db, notification: n, config: config, } }
go
func NewNotifyingWorkItemCommentsController(service *goa.Service, db application.DB, notificationChannel notification.Channel, config WorkItemCommentsControllerConfiguration) *WorkItemCommentsController { n := notificationChannel if n == nil { n = &notification.DevNullChannel{} } return &WorkItemCommentsController{ Controller: service.NewController("WorkItemRelationshipsCommentsController"), db: db, notification: n, config: config, } }
[ "func", "NewNotifyingWorkItemCommentsController", "(", "service", "*", "goa", ".", "Service", ",", "db", "application", ".", "DB", ",", "notificationChannel", "notification", ".", "Channel", ",", "config", "WorkItemCommentsControllerConfiguration", ")", "*", "WorkItemCo...
// NewNotifyingWorkItemCommentsController creates a work-item-relationships-comments controller.
[ "NewNotifyingWorkItemCommentsController", "creates", "a", "work", "-", "item", "-", "relationships", "-", "comments", "controller", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/work_item_comments.go#L41-L52
13,185
fabric8-services/fabric8-wit
controller/work_item_comments.go
CreateCommentsRelation
func CreateCommentsRelation(request *http.Request, wi *workitem.WorkItem) *app.RelationGeneric { return &app.RelationGeneric{ Links: CreateCommentsRelationLinks(request, wi), } }
go
func CreateCommentsRelation(request *http.Request, wi *workitem.WorkItem) *app.RelationGeneric { return &app.RelationGeneric{ Links: CreateCommentsRelationLinks(request, wi), } }
[ "func", "CreateCommentsRelation", "(", "request", "*", "http", ".", "Request", ",", "wi", "*", "workitem", ".", "WorkItem", ")", "*", "app", ".", "RelationGeneric", "{", "return", "&", "app", ".", "RelationGeneric", "{", "Links", ":", "CreateCommentsRelationLi...
// CreateCommentsRelation returns a RelationGeneric object representing the relation for a workitem to comment relation
[ "CreateCommentsRelation", "returns", "a", "RelationGeneric", "object", "representing", "the", "relation", "for", "a", "workitem", "to", "comment", "relation" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/work_item_comments.go#L196-L200
13,186
fabric8-services/fabric8-wit
controller/work_item_comments.go
CreateCommentsRelationLinks
func CreateCommentsRelationLinks(request *http.Request, wi *workitem.WorkItem) *app.GenericLinks { commentsSelf := rest.AbsoluteURL(request, app.WorkitemHref(wi.ID)) + "/relationships/comments" commentsRelated := rest.AbsoluteURL(request, app.WorkitemHref(wi.ID)) + "/comments" return &app.GenericLinks{ Self: &commentsSelf, Related: &commentsRelated, } }
go
func CreateCommentsRelationLinks(request *http.Request, wi *workitem.WorkItem) *app.GenericLinks { commentsSelf := rest.AbsoluteURL(request, app.WorkitemHref(wi.ID)) + "/relationships/comments" commentsRelated := rest.AbsoluteURL(request, app.WorkitemHref(wi.ID)) + "/comments" return &app.GenericLinks{ Self: &commentsSelf, Related: &commentsRelated, } }
[ "func", "CreateCommentsRelationLinks", "(", "request", "*", "http", ".", "Request", ",", "wi", "*", "workitem", ".", "WorkItem", ")", "*", "app", ".", "GenericLinks", "{", "commentsSelf", ":=", "rest", ".", "AbsoluteURL", "(", "request", ",", "app", ".", "...
// CreateCommentsRelationLinks returns a RelationGeneric object representing the links for a workitem to comment relation
[ "CreateCommentsRelationLinks", "returns", "a", "RelationGeneric", "object", "representing", "the", "links", "for", "a", "workitem", "to", "comment", "relation" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/work_item_comments.go#L203-L210
13,187
fabric8-services/fabric8-wit
comment/comment_repository.go
NewRepository
func NewRepository(db *gorm.DB) Repository { return &GormCommentRepository{db: db, revisionRepository: &GormCommentRevisionRepository{db}} }
go
func NewRepository(db *gorm.DB) Repository { return &GormCommentRepository{db: db, revisionRepository: &GormCommentRevisionRepository{db}} }
[ "func", "NewRepository", "(", "db", "*", "gorm", ".", "DB", ")", "Repository", "{", "return", "&", "GormCommentRepository", "{", "db", ":", "db", ",", "revisionRepository", ":", "&", "GormCommentRevisionRepository", "{", "db", "}", "}", "\n", "}" ]
// NewRepository creates a new storage type.
[ "NewRepository", "creates", "a", "new", "storage", "type", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/comment/comment_repository.go#L32-L34
13,188
fabric8-services/fabric8-wit
comment/comment_repository.go
Save
func (m *GormCommentRepository) Save(ctx context.Context, comment *Comment, modifierID uuid.UUID) error { c := Comment{} tx := m.db.Where("id=?", comment.ID).First(&c) if tx.RecordNotFound() { log.Error(ctx, map[string]interface{}{ "comment_id": comment.ID, }, "comment not found!") // treating this as a not found error: the fact that we're using number internal is implementation detail return errors.NewNotFoundError("comment", comment.ID.String()) } if err := tx.Error; err != nil { log.Error(ctx, map[string]interface{}{ "comment_id": comment.ID, "err": err, }, "comment search operation failed!") return errors.NewInternalError(ctx, err) } // make sure no comment is created with an empty 'markup' value if comment.Markup == "" { comment.Markup = rendering.SystemMarkupDefault } tx = tx.Save(comment) if err := tx.Error; err != nil { log.Error(ctx, map[string]interface{}{ "comment_id": comment.ID, "err": err, }, "unable to save the comment!") return errors.NewInternalError(ctx, err) } // save a revision of the updated comment if err := m.revisionRepository.Create(ctx, modifierID, RevisionTypeUpdate, *comment); err != nil { return errs.Wrapf(err, "error while saving work item") } log.Debug(ctx, map[string]interface{}{ "comment_id": comment.ID, }, "Comment updated!") return nil }
go
func (m *GormCommentRepository) Save(ctx context.Context, comment *Comment, modifierID uuid.UUID) error { c := Comment{} tx := m.db.Where("id=?", comment.ID).First(&c) if tx.RecordNotFound() { log.Error(ctx, map[string]interface{}{ "comment_id": comment.ID, }, "comment not found!") // treating this as a not found error: the fact that we're using number internal is implementation detail return errors.NewNotFoundError("comment", comment.ID.String()) } if err := tx.Error; err != nil { log.Error(ctx, map[string]interface{}{ "comment_id": comment.ID, "err": err, }, "comment search operation failed!") return errors.NewInternalError(ctx, err) } // make sure no comment is created with an empty 'markup' value if comment.Markup == "" { comment.Markup = rendering.SystemMarkupDefault } tx = tx.Save(comment) if err := tx.Error; err != nil { log.Error(ctx, map[string]interface{}{ "comment_id": comment.ID, "err": err, }, "unable to save the comment!") return errors.NewInternalError(ctx, err) } // save a revision of the updated comment if err := m.revisionRepository.Create(ctx, modifierID, RevisionTypeUpdate, *comment); err != nil { return errs.Wrapf(err, "error while saving work item") } log.Debug(ctx, map[string]interface{}{ "comment_id": comment.ID, }, "Comment updated!") return nil }
[ "func", "(", "m", "*", "GormCommentRepository", ")", "Save", "(", "ctx", "context", ".", "Context", ",", "comment", "*", "Comment", ",", "modifierID", "uuid", ".", "UUID", ")", "error", "{", "c", ":=", "Comment", "{", "}", "\n", "tx", ":=", "m", ".",...
// Save a single comment
[ "Save", "a", "single", "comment" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/comment/comment_repository.go#L69-L109
13,189
fabric8-services/fabric8-wit
comment/comment_repository.go
Delete
func (m *GormCommentRepository) Delete(ctx context.Context, commentID uuid.UUID, suppressorID uuid.UUID) error { if commentID == uuid.Nil { return errors.NewNotFoundError("comment", commentID.String()) } // fetch the id and parent id of the comment to delete, to store them in the new revision. c := Comment{} tx := m.db.Select("id, parent_id, parent_comment_id").Where("id = ?", commentID).Find(&c) if tx.RowsAffected != 1 { return errors.NewNotFoundError("comment", commentID.String()) } if err := tx.Error; err != nil { return errors.NewInternalError(ctx, err) } m.db.Delete(c) // save a revision of the deleted comment if err := m.revisionRepository.Create(ctx, suppressorID, RevisionTypeDelete, c); err != nil { return errs.Wrapf(err, "error while deleting work item") } return nil }
go
func (m *GormCommentRepository) Delete(ctx context.Context, commentID uuid.UUID, suppressorID uuid.UUID) error { if commentID == uuid.Nil { return errors.NewNotFoundError("comment", commentID.String()) } // fetch the id and parent id of the comment to delete, to store them in the new revision. c := Comment{} tx := m.db.Select("id, parent_id, parent_comment_id").Where("id = ?", commentID).Find(&c) if tx.RowsAffected != 1 { return errors.NewNotFoundError("comment", commentID.String()) } if err := tx.Error; err != nil { return errors.NewInternalError(ctx, err) } m.db.Delete(c) // save a revision of the deleted comment if err := m.revisionRepository.Create(ctx, suppressorID, RevisionTypeDelete, c); err != nil { return errs.Wrapf(err, "error while deleting work item") } return nil }
[ "func", "(", "m", "*", "GormCommentRepository", ")", "Delete", "(", "ctx", "context", ".", "Context", ",", "commentID", "uuid", ".", "UUID", ",", "suppressorID", "uuid", ".", "UUID", ")", "error", "{", "if", "commentID", "==", "uuid", ".", "Nil", "{", ...
// Delete a single comment
[ "Delete", "a", "single", "comment" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/comment/comment_repository.go#L112-L131
13,190
fabric8-services/fabric8-wit
comment/comment_repository.go
List
func (m *GormCommentRepository) List(ctx context.Context, parentID uuid.UUID, start *int, limit *int) ([]Comment, uint64, error) { defer goa.MeasureSince([]string{"goa", "db", "comment", "query"}, time.Now()) db := m.db.Model(&Comment{}).Where("parent_id = ?", parentID) orgDB := db if start != nil { if *start < 0 { return nil, 0, errors.NewBadParameterError("start", *start) } db = db.Offset(*start) } if limit != nil { if *limit <= 0 { return nil, 0, errors.NewBadParameterError("limit", *limit) } db = db.Limit(*limit) } db = db.Select("count(*) over () as cnt2 , *").Order("created_at desc") rows, err := db.Rows() defer closeable.Close(ctx, rows) if err != nil { return nil, 0, err } result := []Comment{} columns, err := rows.Columns() if err != nil { return nil, 0, errors.NewInternalError(ctx, err) } // need to set up a result for Scan() in order to extract total count. var count uint64 var ignore interface{} columnValues := make([]interface{}, len(columns)) for index := range columnValues { columnValues[index] = &ignore } columnValues[0] = &count first := true for rows.Next() { value := &Comment{} db.ScanRows(rows, value) if first { first = false if err = rows.Scan(columnValues...); err != nil { return nil, 0, errors.NewInternalError(ctx, err) } } result = append(result, *value) } if first { // means 0 rows were returned from the first query (maybe because of offset outside of total count), // need to do a count(*) to find out total orgDB := orgDB.Select("count(*)") rows2, err := orgDB.Rows() defer closeable.Close(ctx, rows2) if err != nil { return nil, 0, err } rows2.Next() // count(*) will always return a row rows2.Scan(&count) } return result, count, nil }
go
func (m *GormCommentRepository) List(ctx context.Context, parentID uuid.UUID, start *int, limit *int) ([]Comment, uint64, error) { defer goa.MeasureSince([]string{"goa", "db", "comment", "query"}, time.Now()) db := m.db.Model(&Comment{}).Where("parent_id = ?", parentID) orgDB := db if start != nil { if *start < 0 { return nil, 0, errors.NewBadParameterError("start", *start) } db = db.Offset(*start) } if limit != nil { if *limit <= 0 { return nil, 0, errors.NewBadParameterError("limit", *limit) } db = db.Limit(*limit) } db = db.Select("count(*) over () as cnt2 , *").Order("created_at desc") rows, err := db.Rows() defer closeable.Close(ctx, rows) if err != nil { return nil, 0, err } result := []Comment{} columns, err := rows.Columns() if err != nil { return nil, 0, errors.NewInternalError(ctx, err) } // need to set up a result for Scan() in order to extract total count. var count uint64 var ignore interface{} columnValues := make([]interface{}, len(columns)) for index := range columnValues { columnValues[index] = &ignore } columnValues[0] = &count first := true for rows.Next() { value := &Comment{} db.ScanRows(rows, value) if first { first = false if err = rows.Scan(columnValues...); err != nil { return nil, 0, errors.NewInternalError(ctx, err) } } result = append(result, *value) } if first { // means 0 rows were returned from the first query (maybe because of offset outside of total count), // need to do a count(*) to find out total orgDB := orgDB.Select("count(*)") rows2, err := orgDB.Rows() defer closeable.Close(ctx, rows2) if err != nil { return nil, 0, err } rows2.Next() // count(*) will always return a row rows2.Scan(&count) } return result, count, nil }
[ "func", "(", "m", "*", "GormCommentRepository", ")", "List", "(", "ctx", "context", ".", "Context", ",", "parentID", "uuid", ".", "UUID", ",", "start", "*", "int", ",", "limit", "*", "int", ")", "(", "[", "]", "Comment", ",", "uint64", ",", "error", ...
// List all comments related to a single item
[ "List", "all", "comments", "related", "to", "a", "single", "item" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/comment/comment_repository.go#L134-L200
13,191
fabric8-services/fabric8-wit
comment/comment_repository.go
Count
func (m *GormCommentRepository) Count(ctx context.Context, parentID uuid.UUID) (int, error) { defer goa.MeasureSince([]string{"goa", "db", "comment", "query"}, time.Now()) var count int m.db.Model(&Comment{}).Where("parent_id = ?", parentID).Count(&count) return count, nil }
go
func (m *GormCommentRepository) Count(ctx context.Context, parentID uuid.UUID) (int, error) { defer goa.MeasureSince([]string{"goa", "db", "comment", "query"}, time.Now()) var count int m.db.Model(&Comment{}).Where("parent_id = ?", parentID).Count(&count) return count, nil }
[ "func", "(", "m", "*", "GormCommentRepository", ")", "Count", "(", "ctx", "context", ".", "Context", ",", "parentID", "uuid", ".", "UUID", ")", "(", "int", ",", "error", ")", "{", "defer", "goa", ".", "MeasureSince", "(", "[", "]", "string", "{", "\"...
// Count all comments related to a single item
[ "Count", "all", "comments", "related", "to", "a", "single", "item" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/comment/comment_repository.go#L203-L210
13,192
fabric8-services/fabric8-wit
controller/query.go
NewQueryController
func NewQueryController(service *goa.Service, db application.DB, config QueryControllerConfiguration) *QueryController { return &QueryController{ Controller: service.NewController("QueryController"), db: db, config: config, } }
go
func NewQueryController(service *goa.Service, db application.DB, config QueryControllerConfiguration) *QueryController { return &QueryController{ Controller: service.NewController("QueryController"), db: db, config: config, } }
[ "func", "NewQueryController", "(", "service", "*", "goa", ".", "Service", ",", "db", "application", ".", "DB", ",", "config", "QueryControllerConfiguration", ")", "*", "QueryController", "{", "return", "&", "QueryController", "{", "Controller", ":", "service", "...
// NewQueryController creates a query controller.
[ "NewQueryController", "creates", "a", "query", "controller", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/query.go#L37-L43
13,193
fabric8-services/fabric8-wit
controller/query.go
ConvertQuery
func ConvertQuery(request *http.Request, q query.Query) *app.Query { spaceID := q.SpaceID.String() relatedURL := rest.AbsoluteURL(request, app.QueryHref(spaceID, q.ID)) creatorID := q.Creator.String() relatedCreatorLink := rest.AbsoluteURL(request, fmt.Sprintf("%s/%s", usersEndpoint, creatorID)) spaceRelatedURL := rest.AbsoluteURL(request, app.SpaceHref(spaceID)) appQuery := &app.Query{ Type: query.APIStringTypeQuery, ID: &q.ID, Attributes: &app.QueryAttributes{ Title: q.Title, Fields: q.Fields, CreatedAt: &q.CreatedAt, Version: &q.Version, }, Links: &app.GenericLinks{ Self: &relatedURL, Related: &relatedURL, }, Relationships: &app.QueryRelations{ Creator: &app.RelationGeneric{ Data: &app.GenericData{ Type: ptr.String(APIStringTypeUser), ID: &creatorID, Links: &app.GenericLinks{ Related: &relatedCreatorLink, }, }, }, Space: &app.RelationGeneric{ Data: &app.GenericData{ Type: &space.SpaceType, ID: &spaceID, }, Links: &app.GenericLinks{ Self: &spaceRelatedURL, Related: &spaceRelatedURL, }, }, }, } return appQuery }
go
func ConvertQuery(request *http.Request, q query.Query) *app.Query { spaceID := q.SpaceID.String() relatedURL := rest.AbsoluteURL(request, app.QueryHref(spaceID, q.ID)) creatorID := q.Creator.String() relatedCreatorLink := rest.AbsoluteURL(request, fmt.Sprintf("%s/%s", usersEndpoint, creatorID)) spaceRelatedURL := rest.AbsoluteURL(request, app.SpaceHref(spaceID)) appQuery := &app.Query{ Type: query.APIStringTypeQuery, ID: &q.ID, Attributes: &app.QueryAttributes{ Title: q.Title, Fields: q.Fields, CreatedAt: &q.CreatedAt, Version: &q.Version, }, Links: &app.GenericLinks{ Self: &relatedURL, Related: &relatedURL, }, Relationships: &app.QueryRelations{ Creator: &app.RelationGeneric{ Data: &app.GenericData{ Type: ptr.String(APIStringTypeUser), ID: &creatorID, Links: &app.GenericLinks{ Related: &relatedCreatorLink, }, }, }, Space: &app.RelationGeneric{ Data: &app.GenericData{ Type: &space.SpaceType, ID: &spaceID, }, Links: &app.GenericLinks{ Self: &spaceRelatedURL, Related: &spaceRelatedURL, }, }, }, } return appQuery }
[ "func", "ConvertQuery", "(", "request", "*", "http", ".", "Request", ",", "q", "query", ".", "Query", ")", "*", "app", ".", "Query", "{", "spaceID", ":=", "q", ".", "SpaceID", ".", "String", "(", ")", "\n", "relatedURL", ":=", "rest", ".", "AbsoluteU...
// ConvertQuery converts from internal to external REST representation
[ "ConvertQuery", "converts", "from", "internal", "to", "external", "REST", "representation" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/query.go#L77-L119
13,194
fabric8-services/fabric8-wit
controller/query.go
ConvertQueries
func ConvertQueries(request *http.Request, queries []query.Query) []*app.Query { var ls = []*app.Query{} for _, q := range queries { ls = append(ls, ConvertQuery(request, q)) } return ls }
go
func ConvertQueries(request *http.Request, queries []query.Query) []*app.Query { var ls = []*app.Query{} for _, q := range queries { ls = append(ls, ConvertQuery(request, q)) } return ls }
[ "func", "ConvertQueries", "(", "request", "*", "http", ".", "Request", ",", "queries", "[", "]", "query", ".", "Query", ")", "[", "]", "*", "app", ".", "Query", "{", "var", "ls", "=", "[", "]", "*", "app", ".", "Query", "{", "}", "\n", "for", "...
// ConvertQueries from internal to external REST representation
[ "ConvertQueries", "from", "internal", "to", "external", "REST", "representation" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/controller/query.go#L122-L128
13,195
fabric8-services/fabric8-wit
account/identity.go
Lookup
func (m *GormIdentityRepository) Lookup(ctx context.Context, username, profileURL, providerType string) (*Identity, error) { if username == "" || profileURL == "" || providerType == "" { return nil, errs.New("Cannot lookup identity with empty username, profile URL or provider type") } log.Debug(nil, nil, "Looking for identity of user with profile URL=%s\n", profileURL) // bind the assignee to an existing identity, or create a new one identity, err := m.First(IdentityFilterByProfileURL(profileURL)) if err != nil { return nil, errs.Wrapf(err, "failed to lookup identity by profileURL '%s'", profileURL) } if identity == nil { // create the identity if it does not exist yet log.Debug(nil, nil, "Creating an identity for username '%s' with profile '%s' on '%s'\n", username, profileURL, providerType) identity = &Identity{ ProviderType: providerType, Username: username, ProfileURL: &profileURL, } err = m.Create(context.Background(), identity) if err != nil { return nil, errs.Wrap(err, "failed to create identity during lookup") } } else { // use existing identity log.Debug(nil, nil, "Using existing identity with ID: %v", identity.ID.String()) } log.Debug(nil, nil, "Found identity of user with profile URL=%s: %s", profileURL, identity.ID) return identity, nil }
go
func (m *GormIdentityRepository) Lookup(ctx context.Context, username, profileURL, providerType string) (*Identity, error) { if username == "" || profileURL == "" || providerType == "" { return nil, errs.New("Cannot lookup identity with empty username, profile URL or provider type") } log.Debug(nil, nil, "Looking for identity of user with profile URL=%s\n", profileURL) // bind the assignee to an existing identity, or create a new one identity, err := m.First(IdentityFilterByProfileURL(profileURL)) if err != nil { return nil, errs.Wrapf(err, "failed to lookup identity by profileURL '%s'", profileURL) } if identity == nil { // create the identity if it does not exist yet log.Debug(nil, nil, "Creating an identity for username '%s' with profile '%s' on '%s'\n", username, profileURL, providerType) identity = &Identity{ ProviderType: providerType, Username: username, ProfileURL: &profileURL, } err = m.Create(context.Background(), identity) if err != nil { return nil, errs.Wrap(err, "failed to create identity during lookup") } } else { // use existing identity log.Debug(nil, nil, "Using existing identity with ID: %v", identity.ID.String()) } log.Debug(nil, nil, "Found identity of user with profile URL=%s: %s", profileURL, identity.ID) return identity, nil }
[ "func", "(", "m", "*", "GormIdentityRepository", ")", "Lookup", "(", "ctx", "context", ".", "Context", ",", "username", ",", "profileURL", ",", "providerType", "string", ")", "(", "*", "Identity", ",", "error", ")", "{", "if", "username", "==", "\"", "\"...
// Lookup looks for an existing identity with the given `profileURL` or creates a new one
[ "Lookup", "looks", "for", "an", "existing", "identity", "with", "the", "given", "profileURL", "or", "creates", "a", "new", "one" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/account/identity.go#L139-L167
13,196
fabric8-services/fabric8-wit
account/identity.go
First
func (m *GormIdentityRepository) First(funcs ...func(*gorm.DB) *gorm.DB) (*Identity, error) { defer goa.MeasureSince([]string{"goa", "db", "identity", "first"}, time.Now()) var objs []*Identity log.Debug(nil, nil, "Looking for identity matching: %v", funcs) err := m.db.Scopes(funcs...).Table(m.TableName()).First(&objs).Error if err != nil && err != gorm.ErrRecordNotFound { return nil, errs.WithStack(err) } if len(objs) != 0 && objs[0] != nil { log.Debug(nil, map[string]interface{}{ "identity_list": objs, }, "Found matching identity: %v", *objs[0]) return objs[0], nil } log.Debug(nil, map[string]interface{}{ "identity_list": objs, }, "No matching identity found") return nil, nil }
go
func (m *GormIdentityRepository) First(funcs ...func(*gorm.DB) *gorm.DB) (*Identity, error) { defer goa.MeasureSince([]string{"goa", "db", "identity", "first"}, time.Now()) var objs []*Identity log.Debug(nil, nil, "Looking for identity matching: %v", funcs) err := m.db.Scopes(funcs...).Table(m.TableName()).First(&objs).Error if err != nil && err != gorm.ErrRecordNotFound { return nil, errs.WithStack(err) } if len(objs) != 0 && objs[0] != nil { log.Debug(nil, map[string]interface{}{ "identity_list": objs, }, "Found matching identity: %v", *objs[0]) return objs[0], nil } log.Debug(nil, map[string]interface{}{ "identity_list": objs, }, "No matching identity found") return nil, nil }
[ "func", "(", "m", "*", "GormIdentityRepository", ")", "First", "(", "funcs", "...", "func", "(", "*", "gorm", ".", "DB", ")", "*", "gorm", ".", "DB", ")", "(", "*", "Identity", ",", "error", ")", "{", "defer", "goa", ".", "MeasureSince", "(", "[", ...
// First returns the first Identity element that matches the given criteria
[ "First", "returns", "the", "first", "Identity", "element", "that", "matches", "the", "given", "criteria" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/account/identity.go#L223-L242
13,197
fabric8-services/fabric8-wit
account/identity.go
IdentityFilterByUserID
func IdentityFilterByUserID(userID uuid.UUID) func(db *gorm.DB) *gorm.DB { return func(db *gorm.DB) *gorm.DB { return db.Where("user_id = ?", userID) } }
go
func IdentityFilterByUserID(userID uuid.UUID) func(db *gorm.DB) *gorm.DB { return func(db *gorm.DB) *gorm.DB { return db.Where("user_id = ?", userID) } }
[ "func", "IdentityFilterByUserID", "(", "userID", "uuid", ".", "UUID", ")", "func", "(", "db", "*", "gorm", ".", "DB", ")", "*", "gorm", ".", "DB", "{", "return", "func", "(", "db", "*", "gorm", ".", "DB", ")", "*", "gorm", ".", "DB", "{", "return...
// IdentityFilterByUserID is a gorm filter for a Belongs To relationship.
[ "IdentityFilterByUserID", "is", "a", "gorm", "filter", "for", "a", "Belongs", "To", "relationship", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/account/identity.go#L245-L249
13,198
fabric8-services/fabric8-wit
account/identity.go
IdentityFilterByProfileURL
func IdentityFilterByProfileURL(profileURL string) func(db *gorm.DB) *gorm.DB { return func(db *gorm.DB) *gorm.DB { return db.Where("profile_url = ?", profileURL).Limit(1) } }
go
func IdentityFilterByProfileURL(profileURL string) func(db *gorm.DB) *gorm.DB { return func(db *gorm.DB) *gorm.DB { return db.Where("profile_url = ?", profileURL).Limit(1) } }
[ "func", "IdentityFilterByProfileURL", "(", "profileURL", "string", ")", "func", "(", "db", "*", "gorm", ".", "DB", ")", "*", "gorm", ".", "DB", "{", "return", "func", "(", "db", "*", "gorm", ".", "DB", ")", "*", "gorm", ".", "DB", "{", "return", "d...
// IdentityFilterByProfileURL is a gorm filter by 'profile_url'
[ "IdentityFilterByProfileURL", "is", "a", "gorm", "filter", "by", "profile_url" ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/account/identity.go#L259-L263
13,199
fabric8-services/fabric8-wit
account/identity.go
IdentityFilterByID
func IdentityFilterByID(identityID uuid.UUID) func(db *gorm.DB) *gorm.DB { return func(db *gorm.DB) *gorm.DB { return db.Where("id = ?", identityID) } }
go
func IdentityFilterByID(identityID uuid.UUID) func(db *gorm.DB) *gorm.DB { return func(db *gorm.DB) *gorm.DB { return db.Where("id = ?", identityID) } }
[ "func", "IdentityFilterByID", "(", "identityID", "uuid", ".", "UUID", ")", "func", "(", "db", "*", "gorm", ".", "DB", ")", "*", "gorm", ".", "DB", "{", "return", "func", "(", "db", "*", "gorm", ".", "DB", ")", "*", "gorm", ".", "DB", "{", "return...
// IdentityFilterByID is a gorm filter for Identity ID.
[ "IdentityFilterByID", "is", "a", "gorm", "filter", "for", "Identity", "ID", "." ]
54759c80c42ff2cf29b352e0f6c9330ce4ad7fce
https://github.com/fabric8-services/fabric8-wit/blob/54759c80c42ff2cf29b352e0f6c9330ce4ad7fce/account/identity.go#L266-L270