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
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
17,300
cloudfoundry-community/go-cfclient
appevents.go
ListAppEventsByQuery
func (c *Client) ListAppEventsByQuery(eventType string, queries []AppEventQuery) ([]AppEventEntity, error) { var events []AppEventEntity if eventType != AppCrash && eventType != AppStart && eventType != AppStop && eventType != AppUpdate && eventType != AppCreate && eventType != AppDelete && eventType != AppSSHAuth && eventType != AppSSHUnauth && eventType != AppRestage && eventType != AppMapRoute && eventType != AppUnmapRoute { return nil, errors.New("Unsupported app event type " + eventType) } var query = "/v2/events?q=type:" + eventType //adding the additional queries if queries != nil && len(queries) > 0 { for _, eventQuery := range queries { if eventQuery.Filter != FilterTimestamp && eventQuery.Filter != FilterActee { return nil, errors.New("Unsupported query filter type " + eventQuery.Filter) } if !stringInSlice(eventQuery.Operator, ValidOperators) { return nil, errors.New("Unsupported query operator type " + eventQuery.Operator) } query += "&q=" + eventQuery.Filter + eventQuery.Operator + eventQuery.Value } } for { eventResponse, err := c.getAppEventsResponse(query) if err != nil { return []AppEventEntity{}, err } for _, event := range eventResponse.Resources { events = append(events, event.Entity) } query = eventResponse.NextURL if query == "" { break } } return events, nil }
go
func (c *Client) ListAppEventsByQuery(eventType string, queries []AppEventQuery) ([]AppEventEntity, error) { var events []AppEventEntity if eventType != AppCrash && eventType != AppStart && eventType != AppStop && eventType != AppUpdate && eventType != AppCreate && eventType != AppDelete && eventType != AppSSHAuth && eventType != AppSSHUnauth && eventType != AppRestage && eventType != AppMapRoute && eventType != AppUnmapRoute { return nil, errors.New("Unsupported app event type " + eventType) } var query = "/v2/events?q=type:" + eventType //adding the additional queries if queries != nil && len(queries) > 0 { for _, eventQuery := range queries { if eventQuery.Filter != FilterTimestamp && eventQuery.Filter != FilterActee { return nil, errors.New("Unsupported query filter type " + eventQuery.Filter) } if !stringInSlice(eventQuery.Operator, ValidOperators) { return nil, errors.New("Unsupported query operator type " + eventQuery.Operator) } query += "&q=" + eventQuery.Filter + eventQuery.Operator + eventQuery.Value } } for { eventResponse, err := c.getAppEventsResponse(query) if err != nil { return []AppEventEntity{}, err } for _, event := range eventResponse.Resources { events = append(events, event.Entity) } query = eventResponse.NextURL if query == "" { break } } return events, nil }
[ "func", "(", "c", "*", "Client", ")", "ListAppEventsByQuery", "(", "eventType", "string", ",", "queries", "[", "]", "AppEventQuery", ")", "(", "[", "]", "AppEventEntity", ",", "error", ")", "{", "var", "events", "[", "]", "AppEventEntity", "\n\n", "if", "eventType", "!=", "AppCrash", "&&", "eventType", "!=", "AppStart", "&&", "eventType", "!=", "AppStop", "&&", "eventType", "!=", "AppUpdate", "&&", "eventType", "!=", "AppCreate", "&&", "eventType", "!=", "AppDelete", "&&", "eventType", "!=", "AppSSHAuth", "&&", "eventType", "!=", "AppSSHUnauth", "&&", "eventType", "!=", "AppRestage", "&&", "eventType", "!=", "AppMapRoute", "&&", "eventType", "!=", "AppUnmapRoute", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", "+", "eventType", ")", "\n", "}", "\n\n", "var", "query", "=", "\"", "\"", "+", "eventType", "\n", "//adding the additional queries", "if", "queries", "!=", "nil", "&&", "len", "(", "queries", ")", ">", "0", "{", "for", "_", ",", "eventQuery", ":=", "range", "queries", "{", "if", "eventQuery", ".", "Filter", "!=", "FilterTimestamp", "&&", "eventQuery", ".", "Filter", "!=", "FilterActee", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", "+", "eventQuery", ".", "Filter", ")", "\n", "}", "\n", "if", "!", "stringInSlice", "(", "eventQuery", ".", "Operator", ",", "ValidOperators", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", "+", "eventQuery", ".", "Operator", ")", "\n", "}", "\n", "query", "+=", "\"", "\"", "+", "eventQuery", ".", "Filter", "+", "eventQuery", ".", "Operator", "+", "eventQuery", ".", "Value", "\n", "}", "\n", "}", "\n\n", "for", "{", "eventResponse", ",", "err", ":=", "c", ".", "getAppEventsResponse", "(", "query", ")", "\n", "if", "err", "!=", "nil", "{", "return", "[", "]", "AppEventEntity", "{", "}", ",", "err", "\n", "}", "\n", "for", "_", ",", "event", ":=", "range", "eventResponse", ".", "Resources", "{", "events", "=", "append", "(", "events", ",", "event", ".", "Entity", ")", "\n", "}", "\n", "query", "=", "eventResponse", ".", "NextURL", "\n", "if", "query", "==", "\"", "\"", "{", "break", "\n", "}", "\n", "}", "\n\n", "return", "events", ",", "nil", "\n", "}" ]
// ListAppEventsByQuery returns all app events based on eventType and queries
[ "ListAppEventsByQuery", "returns", "all", "app", "events", "based", "on", "eventType", "and", "queries" ]
f136f9222381e2fea5099f62e4b751dcb660ff82
https://github.com/cloudfoundry-community/go-cfclient/blob/f136f9222381e2fea5099f62e4b751dcb660ff82/appevents.go#L115-L153
17,301
cloudfoundry-community/go-cfclient
service_keys.go
CreateServiceKey
func (c *Client) CreateServiceKey(csr CreateServiceKeyRequest) (ServiceKey, error) { var serviceKeyResource ServiceKeyResource buf := bytes.NewBuffer(nil) err := json.NewEncoder(buf).Encode(csr) if err != nil { return ServiceKey{}, err } req := c.NewRequestWithBody("POST", "/v2/service_keys", buf) resp, err := c.DoRequest(req) if err != nil { return ServiceKey{}, err } if resp.StatusCode != http.StatusCreated { return ServiceKey{}, fmt.Errorf("CF API returned with status code %d", resp.StatusCode) } body, err := ioutil.ReadAll(resp.Body) defer resp.Body.Close() if err != nil { return ServiceKey{}, err } err = json.Unmarshal(body, &serviceKeyResource) if err != nil { return ServiceKey{}, err } return serviceKeyResource.Entity, nil }
go
func (c *Client) CreateServiceKey(csr CreateServiceKeyRequest) (ServiceKey, error) { var serviceKeyResource ServiceKeyResource buf := bytes.NewBuffer(nil) err := json.NewEncoder(buf).Encode(csr) if err != nil { return ServiceKey{}, err } req := c.NewRequestWithBody("POST", "/v2/service_keys", buf) resp, err := c.DoRequest(req) if err != nil { return ServiceKey{}, err } if resp.StatusCode != http.StatusCreated { return ServiceKey{}, fmt.Errorf("CF API returned with status code %d", resp.StatusCode) } body, err := ioutil.ReadAll(resp.Body) defer resp.Body.Close() if err != nil { return ServiceKey{}, err } err = json.Unmarshal(body, &serviceKeyResource) if err != nil { return ServiceKey{}, err } return serviceKeyResource.Entity, nil }
[ "func", "(", "c", "*", "Client", ")", "CreateServiceKey", "(", "csr", "CreateServiceKeyRequest", ")", "(", "ServiceKey", ",", "error", ")", "{", "var", "serviceKeyResource", "ServiceKeyResource", "\n\n", "buf", ":=", "bytes", ".", "NewBuffer", "(", "nil", ")", "\n", "err", ":=", "json", ".", "NewEncoder", "(", "buf", ")", ".", "Encode", "(", "csr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ServiceKey", "{", "}", ",", "err", "\n", "}", "\n", "req", ":=", "c", ".", "NewRequestWithBody", "(", "\"", "\"", ",", "\"", "\"", ",", "buf", ")", "\n", "resp", ",", "err", ":=", "c", ".", "DoRequest", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ServiceKey", "{", "}", ",", "err", "\n", "}", "\n", "if", "resp", ".", "StatusCode", "!=", "http", ".", "StatusCreated", "{", "return", "ServiceKey", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "resp", ".", "StatusCode", ")", "\n", "}", "\n\n", "body", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "resp", ".", "Body", ")", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ServiceKey", "{", "}", ",", "err", "\n", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "body", ",", "&", "serviceKeyResource", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ServiceKey", "{", "}", ",", "err", "\n", "}", "\n\n", "return", "serviceKeyResource", ".", "Entity", ",", "nil", "\n", "}" ]
// CreateServiceKey creates a service key from the request. If a service key // exists already, it returns an error containing `CF-ServiceKeyNameTaken`
[ "CreateServiceKey", "creates", "a", "service", "key", "from", "the", "request", ".", "If", "a", "service", "key", "exists", "already", "it", "returns", "an", "error", "containing", "CF", "-", "ServiceKeyNameTaken" ]
f136f9222381e2fea5099f62e4b751dcb660ff82
https://github.com/cloudfoundry-community/go-cfclient/blob/f136f9222381e2fea5099f62e4b751dcb660ff82/service_keys.go#L131-L159
17,302
cloudfoundry-community/go-cfclient
secgroups.go
respBodyToSecGroup
func respBodyToSecGroup(body io.ReadCloser, c *Client) (*SecGroup, error) { //get the json from the response body bodyRaw, err := ioutil.ReadAll(body) if err != nil { return nil, errors.Wrap(err, "Could not read response body") } jStruct := SecGroupResource{} //make it a SecGroup err = json.Unmarshal(bodyRaw, &jStruct) if err != nil { return nil, errors.Wrap(err, "Could not unmarshal response body as json") } //pull a few extra fields from other places ret := jStruct.Entity ret.Guid = jStruct.Meta.Guid ret.CreatedAt = jStruct.Meta.CreatedAt ret.UpdatedAt = jStruct.Meta.UpdatedAt ret.c = c return &ret, nil }
go
func respBodyToSecGroup(body io.ReadCloser, c *Client) (*SecGroup, error) { //get the json from the response body bodyRaw, err := ioutil.ReadAll(body) if err != nil { return nil, errors.Wrap(err, "Could not read response body") } jStruct := SecGroupResource{} //make it a SecGroup err = json.Unmarshal(bodyRaw, &jStruct) if err != nil { return nil, errors.Wrap(err, "Could not unmarshal response body as json") } //pull a few extra fields from other places ret := jStruct.Entity ret.Guid = jStruct.Meta.Guid ret.CreatedAt = jStruct.Meta.CreatedAt ret.UpdatedAt = jStruct.Meta.UpdatedAt ret.c = c return &ret, nil }
[ "func", "respBodyToSecGroup", "(", "body", "io", ".", "ReadCloser", ",", "c", "*", "Client", ")", "(", "*", "SecGroup", ",", "error", ")", "{", "//get the json from the response body", "bodyRaw", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "jStruct", ":=", "SecGroupResource", "{", "}", "\n", "//make it a SecGroup", "err", "=", "json", ".", "Unmarshal", "(", "bodyRaw", ",", "&", "jStruct", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "//pull a few extra fields from other places", "ret", ":=", "jStruct", ".", "Entity", "\n", "ret", ".", "Guid", "=", "jStruct", ".", "Meta", ".", "Guid", "\n", "ret", ".", "CreatedAt", "=", "jStruct", ".", "Meta", ".", "CreatedAt", "\n", "ret", ".", "UpdatedAt", "=", "jStruct", ".", "Meta", ".", "UpdatedAt", "\n", "ret", ".", "c", "=", "c", "\n", "return", "&", "ret", ",", "nil", "\n", "}" ]
//Reads most security group response bodies into a SecGroup object
[ "Reads", "most", "security", "group", "response", "bodies", "into", "a", "SecGroup", "object" ]
f136f9222381e2fea5099f62e4b751dcb660ff82
https://github.com/cloudfoundry-community/go-cfclient/blob/f136f9222381e2fea5099f62e4b751dcb660ff82/secgroups.go#L456-L475
17,303
cloudfoundry-community/go-cfclient
secgroups.go
secGroupCreateHelper
func (c *Client) secGroupCreateHelper(url, method, name string, rules []SecGroupRule, spaceGuids []string) (*SecGroup, error) { reqRules := make([]map[string]interface{}, len(rules)) for i, rule := range rules { reqRules[i] = convertStructToMap(rule) protocol := strings.ToLower(reqRules[i]["protocol"].(string)) // if not icmp protocol need to remove the Code/Type fields if protocol != "icmp" { delete(reqRules[i], "code") delete(reqRules[i], "type") } } req := c.NewRequest(method, url) //set up request body inputs := map[string]interface{}{ "name": name, "rules": reqRules, } if spaceGuids != nil { inputs["space_guids"] = spaceGuids } req.obj = inputs //fire off the request and check for problems resp, err := c.DoRequest(req) if err != nil { return nil, err } if resp.StatusCode != 201 { // Both create and update should give 201 CREATED var response SecGroupCreateResponse bodyRaw, _ := ioutil.ReadAll(resp.Body) err = json.Unmarshal(bodyRaw, &response) if err != nil { return nil, errors.Wrap(err, "Error unmarshaling response") } return nil, fmt.Errorf(`Request failed CF API returned with status code %d ------------------------------- Error Code %s Code %d Description %s`, resp.StatusCode, response.ErrorCode, response.Code, response.Description) } //get the json from the response body return respBodyToSecGroup(resp.Body, c) }
go
func (c *Client) secGroupCreateHelper(url, method, name string, rules []SecGroupRule, spaceGuids []string) (*SecGroup, error) { reqRules := make([]map[string]interface{}, len(rules)) for i, rule := range rules { reqRules[i] = convertStructToMap(rule) protocol := strings.ToLower(reqRules[i]["protocol"].(string)) // if not icmp protocol need to remove the Code/Type fields if protocol != "icmp" { delete(reqRules[i], "code") delete(reqRules[i], "type") } } req := c.NewRequest(method, url) //set up request body inputs := map[string]interface{}{ "name": name, "rules": reqRules, } if spaceGuids != nil { inputs["space_guids"] = spaceGuids } req.obj = inputs //fire off the request and check for problems resp, err := c.DoRequest(req) if err != nil { return nil, err } if resp.StatusCode != 201 { // Both create and update should give 201 CREATED var response SecGroupCreateResponse bodyRaw, _ := ioutil.ReadAll(resp.Body) err = json.Unmarshal(bodyRaw, &response) if err != nil { return nil, errors.Wrap(err, "Error unmarshaling response") } return nil, fmt.Errorf(`Request failed CF API returned with status code %d ------------------------------- Error Code %s Code %d Description %s`, resp.StatusCode, response.ErrorCode, response.Code, response.Description) } //get the json from the response body return respBodyToSecGroup(resp.Body, c) }
[ "func", "(", "c", "*", "Client", ")", "secGroupCreateHelper", "(", "url", ",", "method", ",", "name", "string", ",", "rules", "[", "]", "SecGroupRule", ",", "spaceGuids", "[", "]", "string", ")", "(", "*", "SecGroup", ",", "error", ")", "{", "reqRules", ":=", "make", "(", "[", "]", "map", "[", "string", "]", "interface", "{", "}", ",", "len", "(", "rules", ")", ")", "\n\n", "for", "i", ",", "rule", ":=", "range", "rules", "{", "reqRules", "[", "i", "]", "=", "convertStructToMap", "(", "rule", ")", "\n", "protocol", ":=", "strings", ".", "ToLower", "(", "reqRules", "[", "i", "]", "[", "\"", "\"", "]", ".", "(", "string", ")", ")", "\n\n", "// if not icmp protocol need to remove the Code/Type fields", "if", "protocol", "!=", "\"", "\"", "{", "delete", "(", "reqRules", "[", "i", "]", ",", "\"", "\"", ")", "\n", "delete", "(", "reqRules", "[", "i", "]", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "req", ":=", "c", ".", "NewRequest", "(", "method", ",", "url", ")", "\n", "//set up request body", "inputs", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "name", ",", "\"", "\"", ":", "reqRules", ",", "}", "\n\n", "if", "spaceGuids", "!=", "nil", "{", "inputs", "[", "\"", "\"", "]", "=", "spaceGuids", "\n", "}", "\n", "req", ".", "obj", "=", "inputs", "\n", "//fire off the request and check for problems", "resp", ",", "err", ":=", "c", ".", "DoRequest", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "resp", ".", "StatusCode", "!=", "201", "{", "// Both create and update should give 201 CREATED", "var", "response", "SecGroupCreateResponse", "\n\n", "bodyRaw", ",", "_", ":=", "ioutil", ".", "ReadAll", "(", "resp", ".", "Body", ")", "\n\n", "err", "=", "json", ".", "Unmarshal", "(", "bodyRaw", ",", "&", "response", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "`Request failed CF API returned with status code %d\n-------------------------------\nError Code %s\nCode %d\nDescription %s`", ",", "resp", ".", "StatusCode", ",", "response", ".", "ErrorCode", ",", "response", ".", "Code", ",", "response", ".", "Description", ")", "\n", "}", "\n", "//get the json from the response body", "return", "respBodyToSecGroup", "(", "resp", ".", "Body", ",", "c", ")", "\n", "}" ]
//Create and Update secGroup pretty much do the same thing, so this function abstracts those out.
[ "Create", "and", "Update", "secGroup", "pretty", "much", "do", "the", "same", "thing", "so", "this", "function", "abstracts", "those", "out", "." ]
f136f9222381e2fea5099f62e4b751dcb660ff82
https://github.com/cloudfoundry-community/go-cfclient/blob/f136f9222381e2fea5099f62e4b751dcb660ff82/secgroups.go#L511-L560
17,304
cloudfoundry-community/go-cfclient
processes.go
ListAllProcessesByQuery
func (c *Client) ListAllProcessesByQuery(query url.Values) ([]Process, error) { var allProcesses []Process urlPath := "/v3/processes" for { resp, err := c.getProcessPage(urlPath, query) if err != nil { return nil, err } if resp.Pagination.TotalResults == 0 { return nil, nil } if allProcesses == nil { allProcesses = make([]Process, 0, resp.Pagination.TotalResults) } allProcesses = append(allProcesses, resp.Processes...) if resp.Pagination.Next == nil { return allProcesses, nil } var nextURL string if resp.Pagination.Next == nil { return allProcesses, nil } switch resp.Pagination.Next.(type) { case string: nextURL = resp.Pagination.Next.(string) case map[string]interface{}: m := resp.Pagination.Next.(map[string]interface{}) u, ok := m["href"] if ok { nextURL = u.(string) } default: return nil, fmt.Errorf("Unexpected type [%s] for next url", reflect.TypeOf(resp.Pagination.Next).String()) } if nextURL == "" { return allProcesses, nil } u, err := url.Parse(nextURL) if err != nil { return nil, err } urlPath = u.Path query, err = url.ParseQuery(u.RawQuery) if err != nil { return nil, err } } }
go
func (c *Client) ListAllProcessesByQuery(query url.Values) ([]Process, error) { var allProcesses []Process urlPath := "/v3/processes" for { resp, err := c.getProcessPage(urlPath, query) if err != nil { return nil, err } if resp.Pagination.TotalResults == 0 { return nil, nil } if allProcesses == nil { allProcesses = make([]Process, 0, resp.Pagination.TotalResults) } allProcesses = append(allProcesses, resp.Processes...) if resp.Pagination.Next == nil { return allProcesses, nil } var nextURL string if resp.Pagination.Next == nil { return allProcesses, nil } switch resp.Pagination.Next.(type) { case string: nextURL = resp.Pagination.Next.(string) case map[string]interface{}: m := resp.Pagination.Next.(map[string]interface{}) u, ok := m["href"] if ok { nextURL = u.(string) } default: return nil, fmt.Errorf("Unexpected type [%s] for next url", reflect.TypeOf(resp.Pagination.Next).String()) } if nextURL == "" { return allProcesses, nil } u, err := url.Parse(nextURL) if err != nil { return nil, err } urlPath = u.Path query, err = url.ParseQuery(u.RawQuery) if err != nil { return nil, err } } }
[ "func", "(", "c", "*", "Client", ")", "ListAllProcessesByQuery", "(", "query", "url", ".", "Values", ")", "(", "[", "]", "Process", ",", "error", ")", "{", "var", "allProcesses", "[", "]", "Process", "\n\n", "urlPath", ":=", "\"", "\"", "\n", "for", "{", "resp", ",", "err", ":=", "c", ".", "getProcessPage", "(", "urlPath", ",", "query", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "resp", ".", "Pagination", ".", "TotalResults", "==", "0", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "if", "allProcesses", "==", "nil", "{", "allProcesses", "=", "make", "(", "[", "]", "Process", ",", "0", ",", "resp", ".", "Pagination", ".", "TotalResults", ")", "\n", "}", "\n\n", "allProcesses", "=", "append", "(", "allProcesses", ",", "resp", ".", "Processes", "...", ")", "\n", "if", "resp", ".", "Pagination", ".", "Next", "==", "nil", "{", "return", "allProcesses", ",", "nil", "\n", "}", "\n\n", "var", "nextURL", "string", "\n\n", "if", "resp", ".", "Pagination", ".", "Next", "==", "nil", "{", "return", "allProcesses", ",", "nil", "\n", "}", "\n\n", "switch", "resp", ".", "Pagination", ".", "Next", ".", "(", "type", ")", "{", "case", "string", ":", "nextURL", "=", "resp", ".", "Pagination", ".", "Next", ".", "(", "string", ")", "\n", "case", "map", "[", "string", "]", "interface", "{", "}", ":", "m", ":=", "resp", ".", "Pagination", ".", "Next", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "u", ",", "ok", ":=", "m", "[", "\"", "\"", "]", "\n", "if", "ok", "{", "nextURL", "=", "u", ".", "(", "string", ")", "\n", "}", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "reflect", ".", "TypeOf", "(", "resp", ".", "Pagination", ".", "Next", ")", ".", "String", "(", ")", ")", "\n", "}", "\n\n", "if", "nextURL", "==", "\"", "\"", "{", "return", "allProcesses", ",", "nil", "\n", "}", "\n\n", "u", ",", "err", ":=", "url", ".", "Parse", "(", "nextURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "urlPath", "=", "u", ".", "Path", "\n", "query", ",", "err", "=", "url", ".", "ParseQuery", "(", "u", ".", "RawQuery", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "}" ]
// ListAllProcessesByQuery will call the v3 processes api
[ "ListAllProcessesByQuery", "will", "call", "the", "v3", "processes", "api" ]
f136f9222381e2fea5099f62e4b751dcb660ff82
https://github.com/cloudfoundry-community/go-cfclient/blob/f136f9222381e2fea5099f62e4b751dcb660ff82/processes.go#L49-L106
17,305
cloudfoundry-community/go-cfclient
apps.go
ListAppsByQueryWithLimits
func (c *Client) ListAppsByQueryWithLimits(query url.Values, totalPages int) ([]App, error) { return c.listApps("/v2/apps?"+query.Encode(), totalPages) }
go
func (c *Client) ListAppsByQueryWithLimits(query url.Values, totalPages int) ([]App, error) { return c.listApps("/v2/apps?"+query.Encode(), totalPages) }
[ "func", "(", "c", "*", "Client", ")", "ListAppsByQueryWithLimits", "(", "query", "url", ".", "Values", ",", "totalPages", "int", ")", "(", "[", "]", "App", ",", "error", ")", "{", "return", "c", ".", "listApps", "(", "\"", "\"", "+", "query", ".", "Encode", "(", ")", ",", "totalPages", ")", "\n", "}" ]
// ListAppsByQueryWithLimits queries totalPages app info. When totalPages is // less and equal than 0, it queries all app info // When there are no more than totalPages apps on server side, all apps info will be returned
[ "ListAppsByQueryWithLimits", "queries", "totalPages", "app", "info", ".", "When", "totalPages", "is", "less", "and", "equal", "than", "0", "it", "queries", "all", "app", "info", "When", "there", "are", "no", "more", "than", "totalPages", "apps", "on", "server", "side", "all", "apps", "info", "will", "be", "returned" ]
f136f9222381e2fea5099f62e4b751dcb660ff82
https://github.com/cloudfoundry-community/go-cfclient/blob/f136f9222381e2fea5099f62e4b751dcb660ff82/apps.go#L270-L272
17,306
cloudfoundry-community/go-cfclient
apps.go
GetAppByGuidNoInlineCall
func (c *Client) GetAppByGuidNoInlineCall(guid string) (App, error) { var appResource AppResource r := c.NewRequest("GET", "/v2/apps/"+guid) resp, err := c.DoRequest(r) if err != nil { return App{}, errors.Wrap(err, "Error requesting apps") } defer resp.Body.Close() resBody, err := ioutil.ReadAll(resp.Body) if err != nil { return App{}, errors.Wrap(err, "Error reading app response body") } err = json.Unmarshal(resBody, &appResource) if err != nil { return App{}, errors.Wrap(err, "Error unmarshalling app") } app := c.mergeAppResource(appResource) // If no Space Information no need to check org. if app.SpaceGuid != "" { //Getting Spaces Resource space, err := app.Space() if err != nil { errors.Wrap(err, "Unable to get the Space for the apps "+app.Name) } else { app.SpaceData.Entity = space } //Getting orgResource org, err := app.SpaceData.Entity.Org() if err != nil { errors.Wrap(err, "Unable to get the Org for the apps "+app.Name) } else { app.SpaceData.Entity.OrgData.Entity = org } } return app, nil }
go
func (c *Client) GetAppByGuidNoInlineCall(guid string) (App, error) { var appResource AppResource r := c.NewRequest("GET", "/v2/apps/"+guid) resp, err := c.DoRequest(r) if err != nil { return App{}, errors.Wrap(err, "Error requesting apps") } defer resp.Body.Close() resBody, err := ioutil.ReadAll(resp.Body) if err != nil { return App{}, errors.Wrap(err, "Error reading app response body") } err = json.Unmarshal(resBody, &appResource) if err != nil { return App{}, errors.Wrap(err, "Error unmarshalling app") } app := c.mergeAppResource(appResource) // If no Space Information no need to check org. if app.SpaceGuid != "" { //Getting Spaces Resource space, err := app.Space() if err != nil { errors.Wrap(err, "Unable to get the Space for the apps "+app.Name) } else { app.SpaceData.Entity = space } //Getting orgResource org, err := app.SpaceData.Entity.Org() if err != nil { errors.Wrap(err, "Unable to get the Org for the apps "+app.Name) } else { app.SpaceData.Entity.OrgData.Entity = org } } return app, nil }
[ "func", "(", "c", "*", "Client", ")", "GetAppByGuidNoInlineCall", "(", "guid", "string", ")", "(", "App", ",", "error", ")", "{", "var", "appResource", "AppResource", "\n", "r", ":=", "c", ".", "NewRequest", "(", "\"", "\"", ",", "\"", "\"", "+", "guid", ")", "\n", "resp", ",", "err", ":=", "c", ".", "DoRequest", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "App", "{", "}", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "resBody", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "resp", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "App", "{", "}", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "err", "=", "json", ".", "Unmarshal", "(", "resBody", ",", "&", "appResource", ")", "\n", "if", "err", "!=", "nil", "{", "return", "App", "{", "}", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "app", ":=", "c", ".", "mergeAppResource", "(", "appResource", ")", "\n\n", "// If no Space Information no need to check org.", "if", "app", ".", "SpaceGuid", "!=", "\"", "\"", "{", "//Getting Spaces Resource", "space", ",", "err", ":=", "app", ".", "Space", "(", ")", "\n", "if", "err", "!=", "nil", "{", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", "+", "app", ".", "Name", ")", "\n", "}", "else", "{", "app", ".", "SpaceData", ".", "Entity", "=", "space", "\n\n", "}", "\n\n", "//Getting orgResource", "org", ",", "err", ":=", "app", ".", "SpaceData", ".", "Entity", ".", "Org", "(", ")", "\n", "if", "err", "!=", "nil", "{", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", "+", "app", ".", "Name", ")", "\n", "}", "else", "{", "app", ".", "SpaceData", ".", "Entity", ".", "OrgData", ".", "Entity", "=", "org", "\n", "}", "\n", "}", "\n\n", "return", "app", ",", "nil", "\n", "}" ]
// GetAppByGuidNoInlineCall will fetch app info including space and orgs information // Without using inline-relations-depth=2 call
[ "GetAppByGuidNoInlineCall", "will", "fetch", "app", "info", "including", "space", "and", "orgs", "information", "Without", "using", "inline", "-", "relations", "-", "depth", "=", "2", "call" ]
f136f9222381e2fea5099f62e4b751dcb660ff82
https://github.com/cloudfoundry-community/go-cfclient/blob/f136f9222381e2fea5099f62e4b751dcb660ff82/apps.go#L280-L320
17,307
cloudfoundry-community/go-cfclient
apps.go
AppByName
func (c *Client) AppByName(appName, spaceGuid, orgGuid string) (app App, err error) { query := url.Values{} query.Add("q", fmt.Sprintf("organization_guid:%s", orgGuid)) query.Add("q", fmt.Sprintf("space_guid:%s", spaceGuid)) query.Add("q", fmt.Sprintf("name:%s", appName)) apps, err := c.ListAppsByQuery(query) if err != nil { return } if len(apps) == 0 { err = fmt.Errorf("No app found with name: `%s` in space with GUID `%s` and org with GUID `%s`", appName, spaceGuid, orgGuid) return } app = apps[0] return }
go
func (c *Client) AppByName(appName, spaceGuid, orgGuid string) (app App, err error) { query := url.Values{} query.Add("q", fmt.Sprintf("organization_guid:%s", orgGuid)) query.Add("q", fmt.Sprintf("space_guid:%s", spaceGuid)) query.Add("q", fmt.Sprintf("name:%s", appName)) apps, err := c.ListAppsByQuery(query) if err != nil { return } if len(apps) == 0 { err = fmt.Errorf("No app found with name: `%s` in space with GUID `%s` and org with GUID `%s`", appName, spaceGuid, orgGuid) return } app = apps[0] return }
[ "func", "(", "c", "*", "Client", ")", "AppByName", "(", "appName", ",", "spaceGuid", ",", "orgGuid", "string", ")", "(", "app", "App", ",", "err", "error", ")", "{", "query", ":=", "url", ".", "Values", "{", "}", "\n", "query", ".", "Add", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "orgGuid", ")", ")", "\n", "query", ".", "Add", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "spaceGuid", ")", ")", "\n", "query", ".", "Add", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "appName", ")", ")", "\n", "apps", ",", "err", ":=", "c", ".", "ListAppsByQuery", "(", "query", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "len", "(", "apps", ")", "==", "0", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "appName", ",", "spaceGuid", ",", "orgGuid", ")", "\n", "return", "\n", "}", "\n", "app", "=", "apps", "[", "0", "]", "\n", "return", "\n", "}" ]
//AppByName takes an appName, and GUIDs for a space and org, and performs // the API lookup with those query parameters set to return you the desired // App object.
[ "AppByName", "takes", "an", "appName", "and", "GUIDs", "for", "a", "space", "and", "org", "and", "performs", "the", "API", "lookup", "with", "those", "query", "parameters", "set", "to", "return", "you", "the", "desired", "App", "object", "." ]
f136f9222381e2fea5099f62e4b751dcb660ff82
https://github.com/cloudfoundry-community/go-cfclient/blob/f136f9222381e2fea5099f62e4b751dcb660ff82/apps.go#L478-L493
17,308
cloudfoundry-community/go-cfclient
apps.go
UploadAppBits
func (c *Client) UploadAppBits(file io.Reader, appGUID string) error { requestFile, err := ioutil.TempFile("", "requests") defer func() { requestFile.Close() os.Remove(requestFile.Name()) }() writer := multipart.NewWriter(requestFile) err = writer.WriteField("resources", "[]") if err != nil { return errors.Wrapf(err, "Error uploading app %s bits", appGUID) } part, err := writer.CreateFormFile("application", "application.zip") if err != nil { return errors.Wrapf(err, "Error uploading app %s bits", appGUID) } _, err = io.Copy(part, file) if err != nil { return errors.Wrapf(err, "Error uploading app %s bits, failed to copy all bytes", appGUID) } err = writer.Close() if err != nil { return errors.Wrapf(err, "Error uploading app %s bits, failed to close multipart writer", appGUID) } requestFile.Seek(0, 0) fileStats, err := requestFile.Stat() if err != nil { return errors.Wrapf(err, "Error uploading app %s bits, failed to get temp file stats", appGUID) } requestURL := fmt.Sprintf("/v2/apps/%s/bits", appGUID) r := c.NewRequestWithBody("PUT", requestURL, requestFile) req, err := r.toHTTP() if err != nil { return errors.Wrapf(err, "Error uploading app %s bits", appGUID) } req.ContentLength = fileStats.Size() contentType := fmt.Sprintf("multipart/form-data; boundary=%s", writer.Boundary()) req.Header.Set("Content-Type", contentType) resp, err := c.Do(req) if err != nil { return errors.Wrapf(err, "Error uploading app %s bits", appGUID) } if resp.StatusCode != http.StatusCreated { return errors.Wrapf(err, "Error uploading app %s bits, response code: %d", appGUID, resp.StatusCode) } return nil }
go
func (c *Client) UploadAppBits(file io.Reader, appGUID string) error { requestFile, err := ioutil.TempFile("", "requests") defer func() { requestFile.Close() os.Remove(requestFile.Name()) }() writer := multipart.NewWriter(requestFile) err = writer.WriteField("resources", "[]") if err != nil { return errors.Wrapf(err, "Error uploading app %s bits", appGUID) } part, err := writer.CreateFormFile("application", "application.zip") if err != nil { return errors.Wrapf(err, "Error uploading app %s bits", appGUID) } _, err = io.Copy(part, file) if err != nil { return errors.Wrapf(err, "Error uploading app %s bits, failed to copy all bytes", appGUID) } err = writer.Close() if err != nil { return errors.Wrapf(err, "Error uploading app %s bits, failed to close multipart writer", appGUID) } requestFile.Seek(0, 0) fileStats, err := requestFile.Stat() if err != nil { return errors.Wrapf(err, "Error uploading app %s bits, failed to get temp file stats", appGUID) } requestURL := fmt.Sprintf("/v2/apps/%s/bits", appGUID) r := c.NewRequestWithBody("PUT", requestURL, requestFile) req, err := r.toHTTP() if err != nil { return errors.Wrapf(err, "Error uploading app %s bits", appGUID) } req.ContentLength = fileStats.Size() contentType := fmt.Sprintf("multipart/form-data; boundary=%s", writer.Boundary()) req.Header.Set("Content-Type", contentType) resp, err := c.Do(req) if err != nil { return errors.Wrapf(err, "Error uploading app %s bits", appGUID) } if resp.StatusCode != http.StatusCreated { return errors.Wrapf(err, "Error uploading app %s bits, response code: %d", appGUID, resp.StatusCode) } return nil }
[ "func", "(", "c", "*", "Client", ")", "UploadAppBits", "(", "file", "io", ".", "Reader", ",", "appGUID", "string", ")", "error", "{", "requestFile", ",", "err", ":=", "ioutil", ".", "TempFile", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "defer", "func", "(", ")", "{", "requestFile", ".", "Close", "(", ")", "\n", "os", ".", "Remove", "(", "requestFile", ".", "Name", "(", ")", ")", "\n", "}", "(", ")", "\n\n", "writer", ":=", "multipart", ".", "NewWriter", "(", "requestFile", ")", "\n", "err", "=", "writer", ".", "WriteField", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "appGUID", ")", "\n", "}", "\n\n", "part", ",", "err", ":=", "writer", ".", "CreateFormFile", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "appGUID", ")", "\n", "}", "\n\n", "_", ",", "err", "=", "io", ".", "Copy", "(", "part", ",", "file", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "appGUID", ")", "\n", "}", "\n\n", "err", "=", "writer", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "appGUID", ")", "\n", "}", "\n\n", "requestFile", ".", "Seek", "(", "0", ",", "0", ")", "\n", "fileStats", ",", "err", ":=", "requestFile", ".", "Stat", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "appGUID", ")", "\n", "}", "\n\n", "requestURL", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "appGUID", ")", "\n", "r", ":=", "c", ".", "NewRequestWithBody", "(", "\"", "\"", ",", "requestURL", ",", "requestFile", ")", "\n", "req", ",", "err", ":=", "r", ".", "toHTTP", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "appGUID", ")", "\n", "}", "\n\n", "req", ".", "ContentLength", "=", "fileStats", ".", "Size", "(", ")", "\n", "contentType", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "writer", ".", "Boundary", "(", ")", ")", "\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "contentType", ")", "\n\n", "resp", ",", "err", ":=", "c", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "appGUID", ")", "\n", "}", "\n", "if", "resp", ".", "StatusCode", "!=", "http", ".", "StatusCreated", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "appGUID", ",", "resp", ".", "StatusCode", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// UploadAppBits uploads the application's contents
[ "UploadAppBits", "uploads", "the", "application", "s", "contents" ]
f136f9222381e2fea5099f62e4b751dcb660ff82
https://github.com/cloudfoundry-community/go-cfclient/blob/f136f9222381e2fea5099f62e4b751dcb660ff82/apps.go#L496-L551
17,309
cloudfoundry-community/go-cfclient
apps.go
GetAppBits
func (c *Client) GetAppBits(guid string) (io.ReadCloser, error) { requestURL := fmt.Sprintf("/v2/apps/%s/download", guid) req := c.NewRequest("GET", requestURL) resp, err := c.DoRequestWithoutRedirects(req) if err != nil { return nil, errors.Wrapf(err, "Error downloading app %s bits, API request failed", guid) } if isResponseRedirect(resp) { // directly download the bits from blobstore using a non cloud controller transport // some blobstores will return a 400 if an Authorization header is sent blobStoreLocation := resp.Header.Get("Location") tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: c.Config.SkipSslValidation}, } client := &http.Client{Transport: tr} resp, err = client.Get(blobStoreLocation) if err != nil { return nil, errors.Wrapf(err, "Error downloading app %s bits from blobstore", guid) } } else { return nil, errors.Wrapf(err, "Error downloading app %s bits, expected redirect to blobstore", guid) } return resp.Body, nil }
go
func (c *Client) GetAppBits(guid string) (io.ReadCloser, error) { requestURL := fmt.Sprintf("/v2/apps/%s/download", guid) req := c.NewRequest("GET", requestURL) resp, err := c.DoRequestWithoutRedirects(req) if err != nil { return nil, errors.Wrapf(err, "Error downloading app %s bits, API request failed", guid) } if isResponseRedirect(resp) { // directly download the bits from blobstore using a non cloud controller transport // some blobstores will return a 400 if an Authorization header is sent blobStoreLocation := resp.Header.Get("Location") tr := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: c.Config.SkipSslValidation}, } client := &http.Client{Transport: tr} resp, err = client.Get(blobStoreLocation) if err != nil { return nil, errors.Wrapf(err, "Error downloading app %s bits from blobstore", guid) } } else { return nil, errors.Wrapf(err, "Error downloading app %s bits, expected redirect to blobstore", guid) } return resp.Body, nil }
[ "func", "(", "c", "*", "Client", ")", "GetAppBits", "(", "guid", "string", ")", "(", "io", ".", "ReadCloser", ",", "error", ")", "{", "requestURL", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "guid", ")", "\n", "req", ":=", "c", ".", "NewRequest", "(", "\"", "\"", ",", "requestURL", ")", "\n", "resp", ",", "err", ":=", "c", ".", "DoRequestWithoutRedirects", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "guid", ")", "\n", "}", "\n", "if", "isResponseRedirect", "(", "resp", ")", "{", "// directly download the bits from blobstore using a non cloud controller transport", "// some blobstores will return a 400 if an Authorization header is sent", "blobStoreLocation", ":=", "resp", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "\n", "tr", ":=", "&", "http", ".", "Transport", "{", "TLSClientConfig", ":", "&", "tls", ".", "Config", "{", "InsecureSkipVerify", ":", "c", ".", "Config", ".", "SkipSslValidation", "}", ",", "}", "\n", "client", ":=", "&", "http", ".", "Client", "{", "Transport", ":", "tr", "}", "\n", "resp", ",", "err", "=", "client", ".", "Get", "(", "blobStoreLocation", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "guid", ")", "\n", "}", "\n", "}", "else", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "guid", ")", "\n", "}", "\n", "return", "resp", ".", "Body", ",", "nil", "\n", "}" ]
// GetAppBits downloads the application's bits as a tar file
[ "GetAppBits", "downloads", "the", "application", "s", "bits", "as", "a", "tar", "file" ]
f136f9222381e2fea5099f62e4b751dcb660ff82
https://github.com/cloudfoundry-community/go-cfclient/blob/f136f9222381e2fea5099f62e4b751dcb660ff82/apps.go#L554-L577
17,310
cloudfoundry-community/go-cfclient
apps.go
CreateApp
func (c *Client) CreateApp(req AppCreateRequest) (App, error) { var appResp AppResource buf := bytes.NewBuffer(nil) err := json.NewEncoder(buf).Encode(req) if err != nil { return App{}, err } r := c.NewRequestWithBody("POST", "/v2/apps", buf) resp, err := c.DoRequest(r) if err != nil { return App{}, errors.Wrapf(err, "Error creating app %s", req.Name) } if resp.StatusCode != http.StatusCreated { return App{}, errors.Wrapf(err, "Error creating app %s, response code: %d", req.Name, resp.StatusCode) } resBody, err := ioutil.ReadAll(resp.Body) defer resp.Body.Close() if err != nil { return App{}, errors.Wrapf(err, "Error reading app %s http response body", req.Name) } err = json.Unmarshal(resBody, &appResp) if err != nil { return App{}, errors.Wrapf(err, "Error deserializing app %s response", req.Name) } return c.mergeAppResource(appResp), nil }
go
func (c *Client) CreateApp(req AppCreateRequest) (App, error) { var appResp AppResource buf := bytes.NewBuffer(nil) err := json.NewEncoder(buf).Encode(req) if err != nil { return App{}, err } r := c.NewRequestWithBody("POST", "/v2/apps", buf) resp, err := c.DoRequest(r) if err != nil { return App{}, errors.Wrapf(err, "Error creating app %s", req.Name) } if resp.StatusCode != http.StatusCreated { return App{}, errors.Wrapf(err, "Error creating app %s, response code: %d", req.Name, resp.StatusCode) } resBody, err := ioutil.ReadAll(resp.Body) defer resp.Body.Close() if err != nil { return App{}, errors.Wrapf(err, "Error reading app %s http response body", req.Name) } err = json.Unmarshal(resBody, &appResp) if err != nil { return App{}, errors.Wrapf(err, "Error deserializing app %s response", req.Name) } return c.mergeAppResource(appResp), nil }
[ "func", "(", "c", "*", "Client", ")", "CreateApp", "(", "req", "AppCreateRequest", ")", "(", "App", ",", "error", ")", "{", "var", "appResp", "AppResource", "\n", "buf", ":=", "bytes", ".", "NewBuffer", "(", "nil", ")", "\n", "err", ":=", "json", ".", "NewEncoder", "(", "buf", ")", ".", "Encode", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "App", "{", "}", ",", "err", "\n", "}", "\n", "r", ":=", "c", ".", "NewRequestWithBody", "(", "\"", "\"", ",", "\"", "\"", ",", "buf", ")", "\n", "resp", ",", "err", ":=", "c", ".", "DoRequest", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "App", "{", "}", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "req", ".", "Name", ")", "\n", "}", "\n", "if", "resp", ".", "StatusCode", "!=", "http", ".", "StatusCreated", "{", "return", "App", "{", "}", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "req", ".", "Name", ",", "resp", ".", "StatusCode", ")", "\n", "}", "\n", "resBody", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "resp", ".", "Body", ")", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "App", "{", "}", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "req", ".", "Name", ")", "\n", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "resBody", ",", "&", "appResp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "App", "{", "}", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "req", ".", "Name", ")", "\n", "}", "\n", "return", "c", ".", "mergeAppResource", "(", "appResp", ")", ",", "nil", "\n", "}" ]
// CreateApp creates a new empty application that still needs it's // app bit uploaded and to be started
[ "CreateApp", "creates", "a", "new", "empty", "application", "that", "still", "needs", "it", "s", "app", "bit", "uploaded", "and", "to", "be", "started" ]
f136f9222381e2fea5099f62e4b751dcb660ff82
https://github.com/cloudfoundry-community/go-cfclient/blob/f136f9222381e2fea5099f62e4b751dcb660ff82/apps.go#L581-L606
17,311
cloudfoundry-community/go-cfclient
info.go
GetInfo
func (c *Client) GetInfo() (*Info, error) { r := c.NewRequest("GET", "/v2/info") resp, err := c.DoRequest(r) if err != nil { return nil, errors.Wrap(err, "Error requesting info") } defer resp.Body.Close() var i Info err = json.NewDecoder(resp.Body).Decode(&i) if err != nil { return nil, errors.Wrap(err, "Error unmarshalling info") } return &i, nil }
go
func (c *Client) GetInfo() (*Info, error) { r := c.NewRequest("GET", "/v2/info") resp, err := c.DoRequest(r) if err != nil { return nil, errors.Wrap(err, "Error requesting info") } defer resp.Body.Close() var i Info err = json.NewDecoder(resp.Body).Decode(&i) if err != nil { return nil, errors.Wrap(err, "Error unmarshalling info") } return &i, nil }
[ "func", "(", "c", "*", "Client", ")", "GetInfo", "(", ")", "(", "*", "Info", ",", "error", ")", "{", "r", ":=", "c", ".", "NewRequest", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "resp", ",", "err", ":=", "c", ".", "DoRequest", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "var", "i", "Info", "\n", "err", "=", "json", ".", "NewDecoder", "(", "resp", ".", "Body", ")", ".", "Decode", "(", "&", "i", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "&", "i", ",", "nil", "\n", "}" ]
// GetInfo retrieves Info from the Cloud Controller API
[ "GetInfo", "retrieves", "Info", "from", "the", "Cloud", "Controller", "API" ]
f136f9222381e2fea5099f62e4b751dcb660ff82
https://github.com/cloudfoundry-community/go-cfclient/blob/f136f9222381e2fea5099f62e4b751dcb660ff82/info.go#L30-L43
17,312
cloudfoundry-community/go-cfclient
error.go
NewCloudFoundryErrorFromV3Errors
func NewCloudFoundryErrorFromV3Errors(cfErrorsV3 CloudFoundryErrorsV3) CloudFoundryError { if len(cfErrorsV3.Errors) == 0 { return CloudFoundryError{ 0, "GO-Client-No-Errors", "No Errors in response from V3", } } return CloudFoundryError{ cfErrorsV3.Errors[0].Code, cfErrorsV3.Errors[0].Title, cfErrorsV3.Errors[0].Detail, } }
go
func NewCloudFoundryErrorFromV3Errors(cfErrorsV3 CloudFoundryErrorsV3) CloudFoundryError { if len(cfErrorsV3.Errors) == 0 { return CloudFoundryError{ 0, "GO-Client-No-Errors", "No Errors in response from V3", } } return CloudFoundryError{ cfErrorsV3.Errors[0].Code, cfErrorsV3.Errors[0].Title, cfErrorsV3.Errors[0].Detail, } }
[ "func", "NewCloudFoundryErrorFromV3Errors", "(", "cfErrorsV3", "CloudFoundryErrorsV3", ")", "CloudFoundryError", "{", "if", "len", "(", "cfErrorsV3", ".", "Errors", ")", "==", "0", "{", "return", "CloudFoundryError", "{", "0", ",", "\"", "\"", ",", "\"", "\"", ",", "}", "\n", "}", "\n\n", "return", "CloudFoundryError", "{", "cfErrorsV3", ".", "Errors", "[", "0", "]", ".", "Code", ",", "cfErrorsV3", ".", "Errors", "[", "0", "]", ".", "Title", ",", "cfErrorsV3", ".", "Errors", "[", "0", "]", ".", "Detail", ",", "}", "\n", "}" ]
// CF APIs v3 can return multiple errors, we take the first one and convert it into a V2 model
[ "CF", "APIs", "v3", "can", "return", "multiple", "errors", "we", "take", "the", "first", "one", "and", "convert", "it", "into", "a", "V2", "model" ]
f136f9222381e2fea5099f62e4b751dcb660ff82
https://github.com/cloudfoundry-community/go-cfclient/blob/f136f9222381e2fea5099f62e4b751dcb660ff82/error.go#L26-L40
17,313
cloudfoundry-community/go-cfclient
service_usage_events.go
ListServiceUsageEventsByQuery
func (c *Client) ListServiceUsageEventsByQuery(query url.Values) ([]ServiceUsageEvent, error) { var serviceUsageEvents []ServiceUsageEvent requestURL := fmt.Sprintf("/v2/service_usage_events?%s", query.Encode()) for { var serviceUsageEventsResponse ServiceUsageEventsResponse r := c.NewRequest("GET", requestURL) resp, err := c.DoRequest(r) if err != nil { return nil, errors.Wrap(err, "error requesting events") } defer resp.Body.Close() if err := json.NewDecoder(resp.Body).Decode(&serviceUsageEventsResponse); err != nil { return nil, errors.Wrap(err, "error unmarshaling events") } for _, e := range serviceUsageEventsResponse.Resources { e.Entity.GUID = e.Meta.Guid e.Entity.CreatedAt = e.Meta.CreatedAt e.Entity.c = c serviceUsageEvents = append(serviceUsageEvents, e.Entity) } requestURL = serviceUsageEventsResponse.NextURL if requestURL == "" { break } } return serviceUsageEvents, nil }
go
func (c *Client) ListServiceUsageEventsByQuery(query url.Values) ([]ServiceUsageEvent, error) { var serviceUsageEvents []ServiceUsageEvent requestURL := fmt.Sprintf("/v2/service_usage_events?%s", query.Encode()) for { var serviceUsageEventsResponse ServiceUsageEventsResponse r := c.NewRequest("GET", requestURL) resp, err := c.DoRequest(r) if err != nil { return nil, errors.Wrap(err, "error requesting events") } defer resp.Body.Close() if err := json.NewDecoder(resp.Body).Decode(&serviceUsageEventsResponse); err != nil { return nil, errors.Wrap(err, "error unmarshaling events") } for _, e := range serviceUsageEventsResponse.Resources { e.Entity.GUID = e.Meta.Guid e.Entity.CreatedAt = e.Meta.CreatedAt e.Entity.c = c serviceUsageEvents = append(serviceUsageEvents, e.Entity) } requestURL = serviceUsageEventsResponse.NextURL if requestURL == "" { break } } return serviceUsageEvents, nil }
[ "func", "(", "c", "*", "Client", ")", "ListServiceUsageEventsByQuery", "(", "query", "url", ".", "Values", ")", "(", "[", "]", "ServiceUsageEvent", ",", "error", ")", "{", "var", "serviceUsageEvents", "[", "]", "ServiceUsageEvent", "\n", "requestURL", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "query", ".", "Encode", "(", ")", ")", "\n", "for", "{", "var", "serviceUsageEventsResponse", "ServiceUsageEventsResponse", "\n", "r", ":=", "c", ".", "NewRequest", "(", "\"", "\"", ",", "requestURL", ")", "\n", "resp", ",", "err", ":=", "c", ".", "DoRequest", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "if", "err", ":=", "json", ".", "NewDecoder", "(", "resp", ".", "Body", ")", ".", "Decode", "(", "&", "serviceUsageEventsResponse", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "for", "_", ",", "e", ":=", "range", "serviceUsageEventsResponse", ".", "Resources", "{", "e", ".", "Entity", ".", "GUID", "=", "e", ".", "Meta", ".", "Guid", "\n", "e", ".", "Entity", ".", "CreatedAt", "=", "e", ".", "Meta", ".", "CreatedAt", "\n", "e", ".", "Entity", ".", "c", "=", "c", "\n", "serviceUsageEvents", "=", "append", "(", "serviceUsageEvents", ",", "e", ".", "Entity", ")", "\n", "}", "\n", "requestURL", "=", "serviceUsageEventsResponse", ".", "NextURL", "\n", "if", "requestURL", "==", "\"", "\"", "{", "break", "\n", "}", "\n", "}", "\n", "return", "serviceUsageEvents", ",", "nil", "\n", "}" ]
// ListServiceUsageEventsByQuery lists all events matching the provided query.
[ "ListServiceUsageEventsByQuery", "lists", "all", "events", "matching", "the", "provided", "query", "." ]
f136f9222381e2fea5099f62e4b751dcb660ff82
https://github.com/cloudfoundry-community/go-cfclient/blob/f136f9222381e2fea5099f62e4b751dcb660ff82/service_usage_events.go#L41-L67
17,314
cloudfoundry-community/go-cfclient
events.go
ListEventsByQuery
func (c *Client) ListEventsByQuery(query url.Values) ([]Event, error) { var events []Event requestURL := fmt.Sprintf("/v2/events?%s", query.Encode()) for { var eventResp EventsResponse r := c.NewRequest("GET", requestURL) resp, err := c.DoRequest(r) if err != nil { return nil, errors.Wrap(err, "error requesting events") } defer resp.Body.Close() if err := json.NewDecoder(resp.Body).Decode(&eventResp); err != nil { return nil, errors.Wrap(err, "error unmarshaling events") } for _, e := range eventResp.Resources { e.Entity.GUID = e.Meta.Guid e.Entity.CreatedAt = e.Meta.CreatedAt e.Entity.c = c events = append(events, e.Entity) } requestURL = eventResp.NextURL if requestURL == "" { break } } return events, nil }
go
func (c *Client) ListEventsByQuery(query url.Values) ([]Event, error) { var events []Event requestURL := fmt.Sprintf("/v2/events?%s", query.Encode()) for { var eventResp EventsResponse r := c.NewRequest("GET", requestURL) resp, err := c.DoRequest(r) if err != nil { return nil, errors.Wrap(err, "error requesting events") } defer resp.Body.Close() if err := json.NewDecoder(resp.Body).Decode(&eventResp); err != nil { return nil, errors.Wrap(err, "error unmarshaling events") } for _, e := range eventResp.Resources { e.Entity.GUID = e.Meta.Guid e.Entity.CreatedAt = e.Meta.CreatedAt e.Entity.c = c events = append(events, e.Entity) } requestURL = eventResp.NextURL if requestURL == "" { break } } return events, nil }
[ "func", "(", "c", "*", "Client", ")", "ListEventsByQuery", "(", "query", "url", ".", "Values", ")", "(", "[", "]", "Event", ",", "error", ")", "{", "var", "events", "[", "]", "Event", "\n", "requestURL", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "query", ".", "Encode", "(", ")", ")", "\n", "for", "{", "var", "eventResp", "EventsResponse", "\n", "r", ":=", "c", ".", "NewRequest", "(", "\"", "\"", ",", "requestURL", ")", "\n", "resp", ",", "err", ":=", "c", ".", "DoRequest", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "if", "err", ":=", "json", ".", "NewDecoder", "(", "resp", ".", "Body", ")", ".", "Decode", "(", "&", "eventResp", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "for", "_", ",", "e", ":=", "range", "eventResp", ".", "Resources", "{", "e", ".", "Entity", ".", "GUID", "=", "e", ".", "Meta", ".", "Guid", "\n", "e", ".", "Entity", ".", "CreatedAt", "=", "e", ".", "Meta", ".", "CreatedAt", "\n", "e", ".", "Entity", ".", "c", "=", "c", "\n", "events", "=", "append", "(", "events", ",", "e", ".", "Entity", ")", "\n", "}", "\n", "requestURL", "=", "eventResp", ".", "NextURL", "\n", "if", "requestURL", "==", "\"", "\"", "{", "break", "\n", "}", "\n", "}", "\n", "return", "events", ",", "nil", "\n", "}" ]
// ListEventsByQuery lists all events matching the provided query.
[ "ListEventsByQuery", "lists", "all", "events", "matching", "the", "provided", "query", "." ]
f136f9222381e2fea5099f62e4b751dcb660ff82
https://github.com/cloudfoundry-community/go-cfclient/blob/f136f9222381e2fea5099f62e4b751dcb660ff82/events.go#L43-L69
17,315
cloudfoundry-community/go-cfclient
events.go
TotalEventsByQuery
func (c *Client) TotalEventsByQuery(query url.Values) (int, error) { r := c.NewRequest("GET", fmt.Sprintf("/v2/events?%s", query.Encode())) resp, err := c.DoRequest(r) if err != nil { return 0, errors.Wrap(err, "error requesting events") } defer resp.Body.Close() var apiResp EventsResponse if err := json.NewDecoder(resp.Body).Decode(&apiResp); err != nil { return 0, errors.Wrap(err, "error unmarshaling events") } return apiResp.TotalResults, nil }
go
func (c *Client) TotalEventsByQuery(query url.Values) (int, error) { r := c.NewRequest("GET", fmt.Sprintf("/v2/events?%s", query.Encode())) resp, err := c.DoRequest(r) if err != nil { return 0, errors.Wrap(err, "error requesting events") } defer resp.Body.Close() var apiResp EventsResponse if err := json.NewDecoder(resp.Body).Decode(&apiResp); err != nil { return 0, errors.Wrap(err, "error unmarshaling events") } return apiResp.TotalResults, nil }
[ "func", "(", "c", "*", "Client", ")", "TotalEventsByQuery", "(", "query", "url", ".", "Values", ")", "(", "int", ",", "error", ")", "{", "r", ":=", "c", ".", "NewRequest", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "query", ".", "Encode", "(", ")", ")", ")", "\n", "resp", ",", "err", ":=", "c", ".", "DoRequest", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "var", "apiResp", "EventsResponse", "\n", "if", "err", ":=", "json", ".", "NewDecoder", "(", "resp", ".", "Body", ")", ".", "Decode", "(", "&", "apiResp", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "apiResp", ".", "TotalResults", ",", "nil", "\n", "}" ]
// TotalEventsByQuery returns the number of events matching the provided query.
[ "TotalEventsByQuery", "returns", "the", "number", "of", "events", "matching", "the", "provided", "query", "." ]
f136f9222381e2fea5099f62e4b751dcb660ff82
https://github.com/cloudfoundry-community/go-cfclient/blob/f136f9222381e2fea5099f62e4b751dcb660ff82/events.go#L77-L89
17,316
cloudfoundry-community/go-cfclient
tasks.go
CreateTask
func (c *Client) CreateTask(tr TaskRequest) (task Task, err error) { bodyReader, err := createReader(tr) if err != nil { return task, err } request := fmt.Sprintf("/v3/apps/%s/tasks", tr.DropletGUID) req := c.NewRequestWithBody("POST", request, bodyReader) resp, err := c.DoRequest(req) if err != nil { return task, errors.Wrap(err, "Error creating task") } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return task, errors.Wrap(err, "Error reading task after creation") } err = json.Unmarshal(body, &task) if err != nil { return task, errors.Wrap(err, "Error unmarshaling task") } return task, err }
go
func (c *Client) CreateTask(tr TaskRequest) (task Task, err error) { bodyReader, err := createReader(tr) if err != nil { return task, err } request := fmt.Sprintf("/v3/apps/%s/tasks", tr.DropletGUID) req := c.NewRequestWithBody("POST", request, bodyReader) resp, err := c.DoRequest(req) if err != nil { return task, errors.Wrap(err, "Error creating task") } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return task, errors.Wrap(err, "Error reading task after creation") } err = json.Unmarshal(body, &task) if err != nil { return task, errors.Wrap(err, "Error unmarshaling task") } return task, err }
[ "func", "(", "c", "*", "Client", ")", "CreateTask", "(", "tr", "TaskRequest", ")", "(", "task", "Task", ",", "err", "error", ")", "{", "bodyReader", ",", "err", ":=", "createReader", "(", "tr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "task", ",", "err", "\n", "}", "\n\n", "request", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "tr", ".", "DropletGUID", ")", "\n", "req", ":=", "c", ".", "NewRequestWithBody", "(", "\"", "\"", ",", "request", ",", "bodyReader", ")", "\n\n", "resp", ",", "err", ":=", "c", ".", "DoRequest", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "task", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n\n", "body", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "resp", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "task", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "err", "=", "json", ".", "Unmarshal", "(", "body", ",", "&", "task", ")", "\n", "if", "err", "!=", "nil", "{", "return", "task", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "task", ",", "err", "\n", "}" ]
// CreateTask creates a new task in CF system and returns its structure.
[ "CreateTask", "creates", "a", "new", "task", "in", "CF", "system", "and", "returns", "its", "structure", "." ]
f136f9222381e2fea5099f62e4b751dcb660ff82
https://github.com/cloudfoundry-community/go-cfclient/blob/f136f9222381e2fea5099f62e4b751dcb660ff82/tasks.go#L137-L162
17,317
cloudfoundry-community/go-cfclient
tasks.go
GetTaskByGuid
func (c *Client) GetTaskByGuid(guid string) (task Task, err error) { request := fmt.Sprintf("/v3/tasks/%s", guid) req := c.NewRequest("GET", request) resp, err := c.DoRequest(req) if err != nil { return task, errors.Wrap(err, "Error requesting task") } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return task, errors.Wrap(err, "Error reading task") } err = json.Unmarshal(body, &task) if err != nil { return task, errors.Wrap(err, "Error unmarshaling task") } return task, err }
go
func (c *Client) GetTaskByGuid(guid string) (task Task, err error) { request := fmt.Sprintf("/v3/tasks/%s", guid) req := c.NewRequest("GET", request) resp, err := c.DoRequest(req) if err != nil { return task, errors.Wrap(err, "Error requesting task") } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return task, errors.Wrap(err, "Error reading task") } err = json.Unmarshal(body, &task) if err != nil { return task, errors.Wrap(err, "Error unmarshaling task") } return task, err }
[ "func", "(", "c", "*", "Client", ")", "GetTaskByGuid", "(", "guid", "string", ")", "(", "task", "Task", ",", "err", "error", ")", "{", "request", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "guid", ")", "\n", "req", ":=", "c", ".", "NewRequest", "(", "\"", "\"", ",", "request", ")", "\n\n", "resp", ",", "err", ":=", "c", ".", "DoRequest", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "task", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n\n", "body", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "resp", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "task", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "err", "=", "json", ".", "Unmarshal", "(", "body", ",", "&", "task", ")", "\n", "if", "err", "!=", "nil", "{", "return", "task", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "task", ",", "err", "\n", "}" ]
// GetTaskByGuid returns a task structure by requesting it with the tasks GUID.
[ "GetTaskByGuid", "returns", "a", "task", "structure", "by", "requesting", "it", "with", "the", "tasks", "GUID", "." ]
f136f9222381e2fea5099f62e4b751dcb660ff82
https://github.com/cloudfoundry-community/go-cfclient/blob/f136f9222381e2fea5099f62e4b751dcb660ff82/tasks.go#L165-L185
17,318
cloudfoundry-community/go-cfclient
tasks.go
TerminateTask
func (c *Client) TerminateTask(guid string) error { req := c.NewRequest("PUT", fmt.Sprintf("/v3/tasks/%s/cancel", guid)) resp, err := c.DoRequest(req) if err != nil { return errors.Wrap(err, "Error terminating task") } defer resp.Body.Close() if resp.StatusCode != 202 { return errors.Wrapf(err, "Failed terminating task, response status code %d", resp.StatusCode) } return nil }
go
func (c *Client) TerminateTask(guid string) error { req := c.NewRequest("PUT", fmt.Sprintf("/v3/tasks/%s/cancel", guid)) resp, err := c.DoRequest(req) if err != nil { return errors.Wrap(err, "Error terminating task") } defer resp.Body.Close() if resp.StatusCode != 202 { return errors.Wrapf(err, "Failed terminating task, response status code %d", resp.StatusCode) } return nil }
[ "func", "(", "c", "*", "Client", ")", "TerminateTask", "(", "guid", "string", ")", "error", "{", "req", ":=", "c", ".", "NewRequest", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "guid", ")", ")", "\n", "resp", ",", "err", ":=", "c", ".", "DoRequest", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n\n", "if", "resp", ".", "StatusCode", "!=", "202", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "resp", ".", "StatusCode", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// TerminateTask cancels a task identified by its GUID.
[ "TerminateTask", "cancels", "a", "task", "identified", "by", "its", "GUID", "." ]
f136f9222381e2fea5099f62e4b751dcb660ff82
https://github.com/cloudfoundry-community/go-cfclient/blob/f136f9222381e2fea5099f62e4b751dcb660ff82/tasks.go#L192-L204
17,319
cloudfoundry-community/go-cfclient
client.go
DefaultConfig
func DefaultConfig() *Config { return &Config{ ApiAddress: "http://api.bosh-lite.com", Username: "admin", Password: "admin", Token: "", SkipSslValidation: false, HttpClient: http.DefaultClient, UserAgent: "Go-CF-client/1.1", } }
go
func DefaultConfig() *Config { return &Config{ ApiAddress: "http://api.bosh-lite.com", Username: "admin", Password: "admin", Token: "", SkipSslValidation: false, HttpClient: http.DefaultClient, UserAgent: "Go-CF-client/1.1", } }
[ "func", "DefaultConfig", "(", ")", "*", "Config", "{", "return", "&", "Config", "{", "ApiAddress", ":", "\"", "\"", ",", "Username", ":", "\"", "\"", ",", "Password", ":", "\"", "\"", ",", "Token", ":", "\"", "\"", ",", "SkipSslValidation", ":", "false", ",", "HttpClient", ":", "http", ".", "DefaultClient", ",", "UserAgent", ":", "\"", "\"", ",", "}", "\n", "}" ]
//DefaultConfig configuration for client //Keep LoginAdress for backward compatibility //Need to be remove in close future
[ "DefaultConfig", "configuration", "for", "client", "Keep", "LoginAdress", "for", "backward", "compatibility", "Need", "to", "be", "remove", "in", "close", "future" ]
f136f9222381e2fea5099f62e4b751dcb660ff82
https://github.com/cloudfoundry-community/go-cfclient/blob/f136f9222381e2fea5099f62e4b751dcb660ff82/client.go#L61-L71
17,320
cloudfoundry-community/go-cfclient
client.go
getUserTokenAuth
func getUserTokenAuth(ctx context.Context, config Config, endpoint *Endpoint) Config { authConfig := &oauth2.Config{ ClientID: "cf", Scopes: []string{""}, Endpoint: oauth2.Endpoint{ AuthURL: endpoint.AuthEndpoint + "/oauth/auth", TokenURL: endpoint.TokenEndpoint + "/oauth/token", }, } // Token is expected to have no "bearer" prefix token := &oauth2.Token{ AccessToken: config.Token, TokenType: "Bearer"} config.TokenSource = authConfig.TokenSource(ctx, token) config.HttpClient = oauth2.NewClient(ctx, config.TokenSource) return config }
go
func getUserTokenAuth(ctx context.Context, config Config, endpoint *Endpoint) Config { authConfig := &oauth2.Config{ ClientID: "cf", Scopes: []string{""}, Endpoint: oauth2.Endpoint{ AuthURL: endpoint.AuthEndpoint + "/oauth/auth", TokenURL: endpoint.TokenEndpoint + "/oauth/token", }, } // Token is expected to have no "bearer" prefix token := &oauth2.Token{ AccessToken: config.Token, TokenType: "Bearer"} config.TokenSource = authConfig.TokenSource(ctx, token) config.HttpClient = oauth2.NewClient(ctx, config.TokenSource) return config }
[ "func", "getUserTokenAuth", "(", "ctx", "context", ".", "Context", ",", "config", "Config", ",", "endpoint", "*", "Endpoint", ")", "Config", "{", "authConfig", ":=", "&", "oauth2", ".", "Config", "{", "ClientID", ":", "\"", "\"", ",", "Scopes", ":", "[", "]", "string", "{", "\"", "\"", "}", ",", "Endpoint", ":", "oauth2", ".", "Endpoint", "{", "AuthURL", ":", "endpoint", ".", "AuthEndpoint", "+", "\"", "\"", ",", "TokenURL", ":", "endpoint", ".", "TokenEndpoint", "+", "\"", "\"", ",", "}", ",", "}", "\n\n", "// Token is expected to have no \"bearer\" prefix", "token", ":=", "&", "oauth2", ".", "Token", "{", "AccessToken", ":", "config", ".", "Token", ",", "TokenType", ":", "\"", "\"", "}", "\n\n", "config", ".", "TokenSource", "=", "authConfig", ".", "TokenSource", "(", "ctx", ",", "token", ")", "\n", "config", ".", "HttpClient", "=", "oauth2", ".", "NewClient", "(", "ctx", ",", "config", ".", "TokenSource", ")", "\n\n", "return", "config", "\n", "}" ]
// getUserTokenAuth initializes client credentials from existing bearer token.
[ "getUserTokenAuth", "initializes", "client", "credentials", "from", "existing", "bearer", "token", "." ]
f136f9222381e2fea5099f62e4b751dcb660ff82
https://github.com/cloudfoundry-community/go-cfclient/blob/f136f9222381e2fea5099f62e4b751dcb660ff82/client.go#L190-L209
17,321
cloudfoundry-community/go-cfclient
client.go
NewRequest
func (c *Client) NewRequest(method, path string) *Request { r := &Request{ method: method, url: c.Config.ApiAddress + path, params: make(map[string][]string), } return r }
go
func (c *Client) NewRequest(method, path string) *Request { r := &Request{ method: method, url: c.Config.ApiAddress + path, params: make(map[string][]string), } return r }
[ "func", "(", "c", "*", "Client", ")", "NewRequest", "(", "method", ",", "path", "string", ")", "*", "Request", "{", "r", ":=", "&", "Request", "{", "method", ":", "method", ",", "url", ":", "c", ".", "Config", ".", "ApiAddress", "+", "path", ",", "params", ":", "make", "(", "map", "[", "string", "]", "[", "]", "string", ")", ",", "}", "\n", "return", "r", "\n", "}" ]
// NewRequest is used to create a new Request
[ "NewRequest", "is", "used", "to", "create", "a", "new", "Request" ]
f136f9222381e2fea5099f62e4b751dcb660ff82
https://github.com/cloudfoundry-community/go-cfclient/blob/f136f9222381e2fea5099f62e4b751dcb660ff82/client.go#L233-L240
17,322
cloudfoundry-community/go-cfclient
client.go
NewRequestWithBody
func (c *Client) NewRequestWithBody(method, path string, body io.Reader) *Request { r := c.NewRequest(method, path) // Set request body r.body = body return r }
go
func (c *Client) NewRequestWithBody(method, path string, body io.Reader) *Request { r := c.NewRequest(method, path) // Set request body r.body = body return r }
[ "func", "(", "c", "*", "Client", ")", "NewRequestWithBody", "(", "method", ",", "path", "string", ",", "body", "io", ".", "Reader", ")", "*", "Request", "{", "r", ":=", "c", ".", "NewRequest", "(", "method", ",", "path", ")", "\n\n", "// Set request body", "r", ".", "body", "=", "body", "\n\n", "return", "r", "\n", "}" ]
// NewRequestWithBody is used to create a new request with // arbigtrary body io.Reader.
[ "NewRequestWithBody", "is", "used", "to", "create", "a", "new", "request", "with", "arbigtrary", "body", "io", ".", "Reader", "." ]
f136f9222381e2fea5099f62e4b751dcb660ff82
https://github.com/cloudfoundry-community/go-cfclient/blob/f136f9222381e2fea5099f62e4b751dcb660ff82/client.go#L244-L251
17,323
cloudfoundry-community/go-cfclient
client.go
DoRequestWithoutRedirects
func (c *Client) DoRequestWithoutRedirects(r *Request) (*http.Response, error) { prevCheckRedirect := c.Config.HttpClient.CheckRedirect c.Config.HttpClient.CheckRedirect = func(httpReq *http.Request, via []*http.Request) error { return http.ErrUseLastResponse } defer func() { c.Config.HttpClient.CheckRedirect = prevCheckRedirect }() return c.DoRequest(r) }
go
func (c *Client) DoRequestWithoutRedirects(r *Request) (*http.Response, error) { prevCheckRedirect := c.Config.HttpClient.CheckRedirect c.Config.HttpClient.CheckRedirect = func(httpReq *http.Request, via []*http.Request) error { return http.ErrUseLastResponse } defer func() { c.Config.HttpClient.CheckRedirect = prevCheckRedirect }() return c.DoRequest(r) }
[ "func", "(", "c", "*", "Client", ")", "DoRequestWithoutRedirects", "(", "r", "*", "Request", ")", "(", "*", "http", ".", "Response", ",", "error", ")", "{", "prevCheckRedirect", ":=", "c", ".", "Config", ".", "HttpClient", ".", "CheckRedirect", "\n", "c", ".", "Config", ".", "HttpClient", ".", "CheckRedirect", "=", "func", "(", "httpReq", "*", "http", ".", "Request", ",", "via", "[", "]", "*", "http", ".", "Request", ")", "error", "{", "return", "http", ".", "ErrUseLastResponse", "\n", "}", "\n", "defer", "func", "(", ")", "{", "c", ".", "Config", ".", "HttpClient", ".", "CheckRedirect", "=", "prevCheckRedirect", "\n", "}", "(", ")", "\n", "return", "c", ".", "DoRequest", "(", "r", ")", "\n", "}" ]
// DoRequestWithoutRedirects executes the request without following redirects
[ "DoRequestWithoutRedirects", "executes", "the", "request", "without", "following", "redirects" ]
f136f9222381e2fea5099f62e4b751dcb660ff82
https://github.com/cloudfoundry-community/go-cfclient/blob/f136f9222381e2fea5099f62e4b751dcb660ff82/client.go#L263-L272
17,324
cloudfoundry-community/go-cfclient
service_plan_visibilities.go
CreateServicePlanVisibilityByUniqueId
func (c *Client) CreateServicePlanVisibilityByUniqueId(uniqueId string, organizationGuid string) (ServicePlanVisibility, error) { q := url.Values{} q.Set("q", fmt.Sprintf("unique_id:%s", uniqueId)) plans, err := c.ListServicePlansByQuery(q) if err != nil { return ServicePlanVisibility{}, errors.Wrap(err, fmt.Sprintf("Couldn't find a service plan with unique_id: %s", uniqueId)) } return c.CreateServicePlanVisibility(plans[0].Guid, organizationGuid) }
go
func (c *Client) CreateServicePlanVisibilityByUniqueId(uniqueId string, organizationGuid string) (ServicePlanVisibility, error) { q := url.Values{} q.Set("q", fmt.Sprintf("unique_id:%s", uniqueId)) plans, err := c.ListServicePlansByQuery(q) if err != nil { return ServicePlanVisibility{}, errors.Wrap(err, fmt.Sprintf("Couldn't find a service plan with unique_id: %s", uniqueId)) } return c.CreateServicePlanVisibility(plans[0].Guid, organizationGuid) }
[ "func", "(", "c", "*", "Client", ")", "CreateServicePlanVisibilityByUniqueId", "(", "uniqueId", "string", ",", "organizationGuid", "string", ")", "(", "ServicePlanVisibility", ",", "error", ")", "{", "q", ":=", "url", ".", "Values", "{", "}", "\n", "q", ".", "Set", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "uniqueId", ")", ")", "\n", "plans", ",", "err", ":=", "c", ".", "ListServicePlansByQuery", "(", "q", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ServicePlanVisibility", "{", "}", ",", "errors", ".", "Wrap", "(", "err", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "uniqueId", ")", ")", "\n", "}", "\n", "return", "c", ".", "CreateServicePlanVisibility", "(", "plans", "[", "0", "]", ".", "Guid", ",", "organizationGuid", ")", "\n", "}" ]
//a uniqueID is the id of the service in the catalog and not in cf internal db
[ "a", "uniqueID", "is", "the", "id", "of", "the", "service", "in", "the", "catalog", "and", "not", "in", "cf", "internal", "db" ]
f136f9222381e2fea5099f62e4b751dcb660ff82
https://github.com/cloudfoundry-community/go-cfclient/blob/f136f9222381e2fea5099f62e4b751dcb660ff82/service_plan_visibilities.go#L85-L93
17,325
cloudfoundry-community/go-cfclient
users.go
GetUserByGUID
func (c *Client) GetUserByGUID(guid string) (User, error) { var userRes UserResource r := c.NewRequest("GET", "/v2/users/"+guid) resp, err := c.DoRequest(r) if err != nil { return User{}, err } body, err := ioutil.ReadAll(resp.Body) defer resp.Body.Close() if err != nil { return User{}, err } err = json.Unmarshal(body, &userRes) if err != nil { return User{}, err } return c.mergeUserResource(userRes), nil }
go
func (c *Client) GetUserByGUID(guid string) (User, error) { var userRes UserResource r := c.NewRequest("GET", "/v2/users/"+guid) resp, err := c.DoRequest(r) if err != nil { return User{}, err } body, err := ioutil.ReadAll(resp.Body) defer resp.Body.Close() if err != nil { return User{}, err } err = json.Unmarshal(body, &userRes) if err != nil { return User{}, err } return c.mergeUserResource(userRes), nil }
[ "func", "(", "c", "*", "Client", ")", "GetUserByGUID", "(", "guid", "string", ")", "(", "User", ",", "error", ")", "{", "var", "userRes", "UserResource", "\n", "r", ":=", "c", ".", "NewRequest", "(", "\"", "\"", ",", "\"", "\"", "+", "guid", ")", "\n", "resp", ",", "err", ":=", "c", ".", "DoRequest", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "User", "{", "}", ",", "err", "\n", "}", "\n", "body", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "resp", ".", "Body", ")", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "User", "{", "}", ",", "err", "\n", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "body", ",", "&", "userRes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "User", "{", "}", ",", "err", "\n", "}", "\n", "return", "c", ".", "mergeUserResource", "(", "userRes", ")", ",", "nil", "\n", "}" ]
// GetUserByGUID retrieves the user with the provided guid.
[ "GetUserByGUID", "retrieves", "the", "user", "with", "the", "provided", "guid", "." ]
f136f9222381e2fea5099f62e4b751dcb660ff82
https://github.com/cloudfoundry-community/go-cfclient/blob/f136f9222381e2fea5099f62e4b751dcb660ff82/users.go#L52-L69
17,326
cloudfoundry-community/go-cfclient
app_usage_events.go
ListAppUsageEventsByQuery
func (c *Client) ListAppUsageEventsByQuery(query url.Values) ([]AppUsageEvent, error) { var appUsageEvents []AppUsageEvent requestURL := fmt.Sprintf("/v2/app_usage_events?%s", query.Encode()) for { var appUsageEventsResponse AppUsageEventsResponse r := c.NewRequest("GET", requestURL) resp, err := c.DoRequest(r) if err != nil { return nil, errors.Wrap(err, "error requesting events") } defer resp.Body.Close() if err := json.NewDecoder(resp.Body).Decode(&appUsageEventsResponse); err != nil { return nil, errors.Wrap(err, "error unmarshaling events") } for _, e := range appUsageEventsResponse.Resources { e.Entity.GUID = e.Meta.Guid e.Entity.CreatedAt = e.Meta.CreatedAt e.Entity.c = c appUsageEvents = append(appUsageEvents, e.Entity) } requestURL = appUsageEventsResponse.NextURL if requestURL == "" { break } } return appUsageEvents, nil }
go
func (c *Client) ListAppUsageEventsByQuery(query url.Values) ([]AppUsageEvent, error) { var appUsageEvents []AppUsageEvent requestURL := fmt.Sprintf("/v2/app_usage_events?%s", query.Encode()) for { var appUsageEventsResponse AppUsageEventsResponse r := c.NewRequest("GET", requestURL) resp, err := c.DoRequest(r) if err != nil { return nil, errors.Wrap(err, "error requesting events") } defer resp.Body.Close() if err := json.NewDecoder(resp.Body).Decode(&appUsageEventsResponse); err != nil { return nil, errors.Wrap(err, "error unmarshaling events") } for _, e := range appUsageEventsResponse.Resources { e.Entity.GUID = e.Meta.Guid e.Entity.CreatedAt = e.Meta.CreatedAt e.Entity.c = c appUsageEvents = append(appUsageEvents, e.Entity) } requestURL = appUsageEventsResponse.NextURL if requestURL == "" { break } } return appUsageEvents, nil }
[ "func", "(", "c", "*", "Client", ")", "ListAppUsageEventsByQuery", "(", "query", "url", ".", "Values", ")", "(", "[", "]", "AppUsageEvent", ",", "error", ")", "{", "var", "appUsageEvents", "[", "]", "AppUsageEvent", "\n", "requestURL", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "query", ".", "Encode", "(", ")", ")", "\n", "for", "{", "var", "appUsageEventsResponse", "AppUsageEventsResponse", "\n", "r", ":=", "c", ".", "NewRequest", "(", "\"", "\"", ",", "requestURL", ")", "\n", "resp", ",", "err", ":=", "c", ".", "DoRequest", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "if", "err", ":=", "json", ".", "NewDecoder", "(", "resp", ".", "Body", ")", ".", "Decode", "(", "&", "appUsageEventsResponse", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "for", "_", ",", "e", ":=", "range", "appUsageEventsResponse", ".", "Resources", "{", "e", ".", "Entity", ".", "GUID", "=", "e", ".", "Meta", ".", "Guid", "\n", "e", ".", "Entity", ".", "CreatedAt", "=", "e", ".", "Meta", ".", "CreatedAt", "\n", "e", ".", "Entity", ".", "c", "=", "c", "\n", "appUsageEvents", "=", "append", "(", "appUsageEvents", ",", "e", ".", "Entity", ")", "\n", "}", "\n", "requestURL", "=", "appUsageEventsResponse", ".", "NextURL", "\n", "if", "requestURL", "==", "\"", "\"", "{", "break", "\n", "}", "\n", "}", "\n", "return", "appUsageEvents", ",", "nil", "\n", "}" ]
// ListAppUsageEventsByQuery lists all events matching the provided query.
[ "ListAppUsageEventsByQuery", "lists", "all", "events", "matching", "the", "provided", "query", "." ]
f136f9222381e2fea5099f62e4b751dcb660ff82
https://github.com/cloudfoundry-community/go-cfclient/blob/f136f9222381e2fea5099f62e4b751dcb660ff82/app_usage_events.go#L49-L75
17,327
cloudfoundry-community/go-cfclient
routes.go
CreateRoute
func (c *Client) CreateRoute(routeRequest RouteRequest) (Route, error) { routesResource, err := c.createRoute("/v2/routes", routeRequest) if nil != err { return Route{}, err } return c.mergeRouteResource(routesResource), nil }
go
func (c *Client) CreateRoute(routeRequest RouteRequest) (Route, error) { routesResource, err := c.createRoute("/v2/routes", routeRequest) if nil != err { return Route{}, err } return c.mergeRouteResource(routesResource), nil }
[ "func", "(", "c", "*", "Client", ")", "CreateRoute", "(", "routeRequest", "RouteRequest", ")", "(", "Route", ",", "error", ")", "{", "routesResource", ",", "err", ":=", "c", ".", "createRoute", "(", "\"", "\"", ",", "routeRequest", ")", "\n", "if", "nil", "!=", "err", "{", "return", "Route", "{", "}", ",", "err", "\n", "}", "\n", "return", "c", ".", "mergeRouteResource", "(", "routesResource", ")", ",", "nil", "\n", "}" ]
// CreateRoute creates a regular http route
[ "CreateRoute", "creates", "a", "regular", "http", "route" ]
f136f9222381e2fea5099f62e4b751dcb660ff82
https://github.com/cloudfoundry-community/go-cfclient/blob/f136f9222381e2fea5099f62e4b751dcb660ff82/routes.go#L48-L54
17,328
cloudfoundry-community/go-cfclient
routes.go
BindRoute
func (c *Client) BindRoute(routeGUID, appGUID string) error { resp, err := c.DoRequest(c.NewRequest("PUT", fmt.Sprintf("/v2/routes/%s/apps/%s", routeGUID, appGUID))) if err != nil { return errors.Wrapf(err, "Error binding route %s to app %s", routeGUID, appGUID) } if resp.StatusCode != http.StatusCreated { return fmt.Errorf("Error binding route %s to app %s, response code: %d", routeGUID, appGUID, resp.StatusCode) } return nil }
go
func (c *Client) BindRoute(routeGUID, appGUID string) error { resp, err := c.DoRequest(c.NewRequest("PUT", fmt.Sprintf("/v2/routes/%s/apps/%s", routeGUID, appGUID))) if err != nil { return errors.Wrapf(err, "Error binding route %s to app %s", routeGUID, appGUID) } if resp.StatusCode != http.StatusCreated { return fmt.Errorf("Error binding route %s to app %s, response code: %d", routeGUID, appGUID, resp.StatusCode) } return nil }
[ "func", "(", "c", "*", "Client", ")", "BindRoute", "(", "routeGUID", ",", "appGUID", "string", ")", "error", "{", "resp", ",", "err", ":=", "c", ".", "DoRequest", "(", "c", ".", "NewRequest", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "routeGUID", ",", "appGUID", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "routeGUID", ",", "appGUID", ")", "\n", "}", "\n", "if", "resp", ".", "StatusCode", "!=", "http", ".", "StatusCreated", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "routeGUID", ",", "appGUID", ",", "resp", ".", "StatusCode", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// BindRoute associates the specified route with the application
[ "BindRoute", "associates", "the", "specified", "route", "with", "the", "application" ]
f136f9222381e2fea5099f62e4b751dcb660ff82
https://github.com/cloudfoundry-community/go-cfclient/blob/f136f9222381e2fea5099f62e4b751dcb660ff82/routes.go#L66-L75
17,329
bamiaux/rez
image.go
Check
func (d *Descriptor) Check() error { if d.Pack < 1 || d.Pack > 4 { return fmt.Errorf("invalid pack value %v", d.Pack) } for i := 0; i < d.Planes; i++ { h := d.GetHeight(i) if d.Interlaced && h%2 != 0 && h != d.Height { return fmt.Errorf("invalid interlaced input height %v", d.Height) } } return nil }
go
func (d *Descriptor) Check() error { if d.Pack < 1 || d.Pack > 4 { return fmt.Errorf("invalid pack value %v", d.Pack) } for i := 0; i < d.Planes; i++ { h := d.GetHeight(i) if d.Interlaced && h%2 != 0 && h != d.Height { return fmt.Errorf("invalid interlaced input height %v", d.Height) } } return nil }
[ "func", "(", "d", "*", "Descriptor", ")", "Check", "(", ")", "error", "{", "if", "d", ".", "Pack", "<", "1", "||", "d", ".", "Pack", ">", "4", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "d", ".", "Pack", ")", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "d", ".", "Planes", ";", "i", "++", "{", "h", ":=", "d", ".", "GetHeight", "(", "i", ")", "\n", "if", "d", ".", "Interlaced", "&&", "h", "%", "2", "!=", "0", "&&", "h", "!=", "d", ".", "Height", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "d", ".", "Height", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Check returns whether the descriptor is valid
[ "Check", "returns", "whether", "the", "descriptor", "is", "valid" ]
29f4463c688b986c11f166b12734f69b58b5555f
https://github.com/bamiaux/rez/blob/29f4463c688b986c11f166b12734f69b58b5555f/image.go#L84-L95
17,330
bamiaux/rez
image.go
GetWidth
func (d *Descriptor) GetWidth(plane int) int { if plane < 0 || plane+1 > maxPlanes { panic(fmt.Errorf("invalid plane %v", plane)) } if plane == 0 { return d.Width } switch d.Ratio { case Ratio410, Ratio411: return (d.Width + 3) >> 2 case Ratio420, Ratio422: return (d.Width + 1) >> 1 case Ratio440, Ratio444: return d.Width } panic(fmt.Errorf("invalid ratio %v", d.Ratio)) }
go
func (d *Descriptor) GetWidth(plane int) int { if plane < 0 || plane+1 > maxPlanes { panic(fmt.Errorf("invalid plane %v", plane)) } if plane == 0 { return d.Width } switch d.Ratio { case Ratio410, Ratio411: return (d.Width + 3) >> 2 case Ratio420, Ratio422: return (d.Width + 1) >> 1 case Ratio440, Ratio444: return d.Width } panic(fmt.Errorf("invalid ratio %v", d.Ratio)) }
[ "func", "(", "d", "*", "Descriptor", ")", "GetWidth", "(", "plane", "int", ")", "int", "{", "if", "plane", "<", "0", "||", "plane", "+", "1", ">", "maxPlanes", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "plane", ")", ")", "\n", "}", "\n", "if", "plane", "==", "0", "{", "return", "d", ".", "Width", "\n", "}", "\n", "switch", "d", ".", "Ratio", "{", "case", "Ratio410", ",", "Ratio411", ":", "return", "(", "d", ".", "Width", "+", "3", ")", ">>", "2", "\n", "case", "Ratio420", ",", "Ratio422", ":", "return", "(", "d", ".", "Width", "+", "1", ")", ">>", "1", "\n", "case", "Ratio440", ",", "Ratio444", ":", "return", "d", ".", "Width", "\n", "}", "\n", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "d", ".", "Ratio", ")", ")", "\n", "}" ]
// GetWidth returns the width in pixels for the input plane
[ "GetWidth", "returns", "the", "width", "in", "pixels", "for", "the", "input", "plane" ]
29f4463c688b986c11f166b12734f69b58b5555f
https://github.com/bamiaux/rez/blob/29f4463c688b986c11f166b12734f69b58b5555f/image.go#L98-L114
17,331
bamiaux/rez
image.go
GetHeight
func (d *Descriptor) GetHeight(plane int) int { if plane < 0 || plane+1 > maxPlanes { panic(fmt.Errorf("invalid plane %v", plane)) } if plane == 0 { return d.Height } switch d.Ratio { case Ratio411, Ratio422, Ratio444: return d.Height case Ratio410, Ratio420, Ratio440: h := (d.Height + 1) >> 1 if d.Interlaced && h&1 != 0 { h++ } return h } panic(fmt.Errorf("invalid ratio %v", d.Ratio)) }
go
func (d *Descriptor) GetHeight(plane int) int { if plane < 0 || plane+1 > maxPlanes { panic(fmt.Errorf("invalid plane %v", plane)) } if plane == 0 { return d.Height } switch d.Ratio { case Ratio411, Ratio422, Ratio444: return d.Height case Ratio410, Ratio420, Ratio440: h := (d.Height + 1) >> 1 if d.Interlaced && h&1 != 0 { h++ } return h } panic(fmt.Errorf("invalid ratio %v", d.Ratio)) }
[ "func", "(", "d", "*", "Descriptor", ")", "GetHeight", "(", "plane", "int", ")", "int", "{", "if", "plane", "<", "0", "||", "plane", "+", "1", ">", "maxPlanes", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "plane", ")", ")", "\n", "}", "\n", "if", "plane", "==", "0", "{", "return", "d", ".", "Height", "\n", "}", "\n", "switch", "d", ".", "Ratio", "{", "case", "Ratio411", ",", "Ratio422", ",", "Ratio444", ":", "return", "d", ".", "Height", "\n", "case", "Ratio410", ",", "Ratio420", ",", "Ratio440", ":", "h", ":=", "(", "d", ".", "Height", "+", "1", ")", ">>", "1", "\n", "if", "d", ".", "Interlaced", "&&", "h", "&", "1", "!=", "0", "{", "h", "++", "\n", "}", "\n", "return", "h", "\n", "}", "\n", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "d", ".", "Ratio", ")", ")", "\n", "}" ]
// GetHeight returns the height in pixels for the input plane
[ "GetHeight", "returns", "the", "height", "in", "pixels", "for", "the", "input", "plane" ]
29f4463c688b986c11f166b12734f69b58b5555f
https://github.com/bamiaux/rez/blob/29f4463c688b986c11f166b12734f69b58b5555f/image.go#L117-L135
17,332
bamiaux/rez
image.go
GetRatio
func GetRatio(value image.YCbCrSubsampleRatio) ChromaRatio { switch value { case image.YCbCrSubsampleRatio410: return Ratio410 case image.YCbCrSubsampleRatio411: return Ratio411 case image.YCbCrSubsampleRatio420: return Ratio420 case image.YCbCrSubsampleRatio422: return Ratio422 case image.YCbCrSubsampleRatio440: return Ratio440 case image.YCbCrSubsampleRatio444: return Ratio444 } return Ratio444 }
go
func GetRatio(value image.YCbCrSubsampleRatio) ChromaRatio { switch value { case image.YCbCrSubsampleRatio410: return Ratio410 case image.YCbCrSubsampleRatio411: return Ratio411 case image.YCbCrSubsampleRatio420: return Ratio420 case image.YCbCrSubsampleRatio422: return Ratio422 case image.YCbCrSubsampleRatio440: return Ratio440 case image.YCbCrSubsampleRatio444: return Ratio444 } return Ratio444 }
[ "func", "GetRatio", "(", "value", "image", ".", "YCbCrSubsampleRatio", ")", "ChromaRatio", "{", "switch", "value", "{", "case", "image", ".", "YCbCrSubsampleRatio410", ":", "return", "Ratio410", "\n", "case", "image", ".", "YCbCrSubsampleRatio411", ":", "return", "Ratio411", "\n", "case", "image", ".", "YCbCrSubsampleRatio420", ":", "return", "Ratio420", "\n", "case", "image", ".", "YCbCrSubsampleRatio422", ":", "return", "Ratio422", "\n", "case", "image", ".", "YCbCrSubsampleRatio440", ":", "return", "Ratio440", "\n", "case", "image", ".", "YCbCrSubsampleRatio444", ":", "return", "Ratio444", "\n", "}", "\n", "return", "Ratio444", "\n", "}" ]
// GetRatio returns a ChromaRatio from an image.YCbCrSubsampleRatio
[ "GetRatio", "returns", "a", "ChromaRatio", "from", "an", "image", ".", "YCbCrSubsampleRatio" ]
29f4463c688b986c11f166b12734f69b58b5555f
https://github.com/bamiaux/rez/blob/29f4463c688b986c11f166b12734f69b58b5555f/image.go#L300-L316
17,333
bamiaux/rez
image.go
PrepareConversion
func PrepareConversion(output, input image.Image) (*ConverterConfig, error) { src, _, err := inspect(input, false) if err != nil { return nil, err } dst, _, err := inspect(output, false) if err != nil { return nil, err } err = checkConversion(dst, src) if err != nil { return nil, err } return &ConverterConfig{ Input: *src, Output: *dst, }, nil }
go
func PrepareConversion(output, input image.Image) (*ConverterConfig, error) { src, _, err := inspect(input, false) if err != nil { return nil, err } dst, _, err := inspect(output, false) if err != nil { return nil, err } err = checkConversion(dst, src) if err != nil { return nil, err } return &ConverterConfig{ Input: *src, Output: *dst, }, nil }
[ "func", "PrepareConversion", "(", "output", ",", "input", "image", ".", "Image", ")", "(", "*", "ConverterConfig", ",", "error", ")", "{", "src", ",", "_", ",", "err", ":=", "inspect", "(", "input", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "dst", ",", "_", ",", "err", ":=", "inspect", "(", "output", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "err", "=", "checkConversion", "(", "dst", ",", "src", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "ConverterConfig", "{", "Input", ":", "*", "src", ",", "Output", ":", "*", "dst", ",", "}", ",", "nil", "\n", "}" ]
// PrepareConversion returns a ConverterConfig properly set for a conversion // from input images to output images // Returns an error if the conversion is not possible
[ "PrepareConversion", "returns", "a", "ConverterConfig", "properly", "set", "for", "a", "conversion", "from", "input", "images", "to", "output", "images", "Returns", "an", "error", "if", "the", "conversion", "is", "not", "possible" ]
29f4463c688b986c11f166b12734f69b58b5555f
https://github.com/bamiaux/rez/blob/29f4463c688b986c11f166b12734f69b58b5555f/image.go#L486-L503
17,334
bamiaux/rez
image.go
Psnr
func Psnr(a, b image.Image) ([]float64, error) { psnrs := []float64{} id, src, err := inspect(a, false) if err != nil { return nil, err } od, dst, err := inspect(b, false) if err != nil { return nil, err } if *id != *od { return nil, fmt.Errorf("unable to psnr different formats") } for i := 0; i < len(dst); i++ { psnrs = append(psnrs, psnrPlane(src[i].Data, dst[i].Data, src[i].Width*src[i].Pack, src[i].Height, src[i].Pitch, dst[i].Pitch)) } return psnrs, nil }
go
func Psnr(a, b image.Image) ([]float64, error) { psnrs := []float64{} id, src, err := inspect(a, false) if err != nil { return nil, err } od, dst, err := inspect(b, false) if err != nil { return nil, err } if *id != *od { return nil, fmt.Errorf("unable to psnr different formats") } for i := 0; i < len(dst); i++ { psnrs = append(psnrs, psnrPlane(src[i].Data, dst[i].Data, src[i].Width*src[i].Pack, src[i].Height, src[i].Pitch, dst[i].Pitch)) } return psnrs, nil }
[ "func", "Psnr", "(", "a", ",", "b", "image", ".", "Image", ")", "(", "[", "]", "float64", ",", "error", ")", "{", "psnrs", ":=", "[", "]", "float64", "{", "}", "\n", "id", ",", "src", ",", "err", ":=", "inspect", "(", "a", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "od", ",", "dst", ",", "err", ":=", "inspect", "(", "b", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "*", "id", "!=", "*", "od", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "dst", ")", ";", "i", "++", "{", "psnrs", "=", "append", "(", "psnrs", ",", "psnrPlane", "(", "src", "[", "i", "]", ".", "Data", ",", "dst", "[", "i", "]", ".", "Data", ",", "src", "[", "i", "]", ".", "Width", "*", "src", "[", "i", "]", ".", "Pack", ",", "src", "[", "i", "]", ".", "Height", ",", "src", "[", "i", "]", ".", "Pitch", ",", "dst", "[", "i", "]", ".", "Pitch", ")", ")", "\n", "}", "\n", "return", "psnrs", ",", "nil", "\n", "}" ]
// Psnr computes the PSNR between two input images // Only ycbcr is currently supported
[ "Psnr", "computes", "the", "PSNR", "between", "two", "input", "images", "Only", "ycbcr", "is", "currently", "supported" ]
29f4463c688b986c11f166b12734f69b58b5555f
https://github.com/bamiaux/rez/blob/29f4463c688b986c11f166b12734f69b58b5555f/image.go#L523-L540
17,335
bamiaux/rez
resize.go
NewResize
func NewResize(cfg *ResizerConfig, filter Filter) Resizer { ctx := context{ cfg: *cfg, } ctx.cfg.Depth = 8 // only 8-bit for now if ctx.cfg.Pack < 1 { ctx.cfg.Pack = 1 } ctx.kernels = []kernel{makeKernel(&ctx.cfg, filter, 0)} ctx.scaler = getHorizontalScaler(ctx.kernels[0].size, !cfg.DisableAsm) if cfg.Vertical { ctx.scaler = getVerticalScaler(ctx.kernels[0].size, !cfg.DisableAsm) if cfg.Interlaced { ctx.kernels = append(ctx.kernels, makeKernel(&ctx.cfg, filter, 1)) } } return &ctx }
go
func NewResize(cfg *ResizerConfig, filter Filter) Resizer { ctx := context{ cfg: *cfg, } ctx.cfg.Depth = 8 // only 8-bit for now if ctx.cfg.Pack < 1 { ctx.cfg.Pack = 1 } ctx.kernels = []kernel{makeKernel(&ctx.cfg, filter, 0)} ctx.scaler = getHorizontalScaler(ctx.kernels[0].size, !cfg.DisableAsm) if cfg.Vertical { ctx.scaler = getVerticalScaler(ctx.kernels[0].size, !cfg.DisableAsm) if cfg.Interlaced { ctx.kernels = append(ctx.kernels, makeKernel(&ctx.cfg, filter, 1)) } } return &ctx }
[ "func", "NewResize", "(", "cfg", "*", "ResizerConfig", ",", "filter", "Filter", ")", "Resizer", "{", "ctx", ":=", "context", "{", "cfg", ":", "*", "cfg", ",", "}", "\n", "ctx", ".", "cfg", ".", "Depth", "=", "8", "// only 8-bit for now", "\n", "if", "ctx", ".", "cfg", ".", "Pack", "<", "1", "{", "ctx", ".", "cfg", ".", "Pack", "=", "1", "\n", "}", "\n", "ctx", ".", "kernels", "=", "[", "]", "kernel", "{", "makeKernel", "(", "&", "ctx", ".", "cfg", ",", "filter", ",", "0", ")", "}", "\n", "ctx", ".", "scaler", "=", "getHorizontalScaler", "(", "ctx", ".", "kernels", "[", "0", "]", ".", "size", ",", "!", "cfg", ".", "DisableAsm", ")", "\n", "if", "cfg", ".", "Vertical", "{", "ctx", ".", "scaler", "=", "getVerticalScaler", "(", "ctx", ".", "kernels", "[", "0", "]", ".", "size", ",", "!", "cfg", ".", "DisableAsm", ")", "\n", "if", "cfg", ".", "Interlaced", "{", "ctx", ".", "kernels", "=", "append", "(", "ctx", ".", "kernels", ",", "makeKernel", "(", "&", "ctx", ".", "cfg", ",", "filter", ",", "1", ")", ")", "\n", "}", "\n", "}", "\n", "return", "&", "ctx", "\n", "}" ]
// NewResize returns a new resizer // cfg = resize configuration // filter = filter used for computing weights
[ "NewResize", "returns", "a", "new", "resizer", "cfg", "=", "resize", "configuration", "filter", "=", "filter", "used", "for", "computing", "weights" ]
29f4463c688b986c11f166b12734f69b58b5555f
https://github.com/bamiaux/rez/blob/29f4463c688b986c11f166b12734f69b58b5555f/resize.go#L80-L97
17,336
bamiaux/rez
fixedscalers.go
h8scale2Go
func h8scale2Go(dst, src []byte, cof, off []int16, taps, width, height, dp, sp int) { di := 0 si := 0 for y := 0; y < height; y++ { c := cof s := src[si:] d := dst[di:] for x, xoff := range off[:width] { pix := int(s[xoff+0])*int(c[0]) + int(s[xoff+1])*int(c[1]) d[x] = u8((pix + 1<<(Bits-1)) >> Bits) c = c[2:] } di += dp si += sp } }
go
func h8scale2Go(dst, src []byte, cof, off []int16, taps, width, height, dp, sp int) { di := 0 si := 0 for y := 0; y < height; y++ { c := cof s := src[si:] d := dst[di:] for x, xoff := range off[:width] { pix := int(s[xoff+0])*int(c[0]) + int(s[xoff+1])*int(c[1]) d[x] = u8((pix + 1<<(Bits-1)) >> Bits) c = c[2:] } di += dp si += sp } }
[ "func", "h8scale2Go", "(", "dst", ",", "src", "[", "]", "byte", ",", "cof", ",", "off", "[", "]", "int16", ",", "taps", ",", "width", ",", "height", ",", "dp", ",", "sp", "int", ")", "{", "di", ":=", "0", "\n", "si", ":=", "0", "\n", "for", "y", ":=", "0", ";", "y", "<", "height", ";", "y", "++", "{", "c", ":=", "cof", "\n", "s", ":=", "src", "[", "si", ":", "]", "\n", "d", ":=", "dst", "[", "di", ":", "]", "\n", "for", "x", ",", "xoff", ":=", "range", "off", "[", ":", "width", "]", "{", "pix", ":=", "int", "(", "s", "[", "xoff", "+", "0", "]", ")", "*", "int", "(", "c", "[", "0", "]", ")", "+", "int", "(", "s", "[", "xoff", "+", "1", "]", ")", "*", "int", "(", "c", "[", "1", "]", ")", "\n", "d", "[", "x", "]", "=", "u8", "(", "(", "pix", "+", "1", "<<", "(", "Bits", "-", "1", ")", ")", ">>", "Bits", ")", "\n", "c", "=", "c", "[", "2", ":", "]", "\n", "}", "\n", "di", "+=", "dp", "\n", "si", "+=", "sp", "\n", "}", "\n", "}" ]
// This file is auto-generated - do not modify
[ "This", "file", "is", "auto", "-", "generated", "-", "do", "not", "modify" ]
29f4463c688b986c11f166b12734f69b58b5555f
https://github.com/bamiaux/rez/blob/29f4463c688b986c11f166b12734f69b58b5555f/fixedscalers.go#L9-L26
17,337
bamiaux/rez
utils.go
DumpImage
func DumpImage(prefix string, img image.Image) error { _, src, err := inspect(img, false) if err != nil { return err } for i, p := range src { err = dumpPlane(prefix, &p, i) if err != nil { return err } } return nil }
go
func DumpImage(prefix string, img image.Image) error { _, src, err := inspect(img, false) if err != nil { return err } for i, p := range src { err = dumpPlane(prefix, &p, i) if err != nil { return err } } return nil }
[ "func", "DumpImage", "(", "prefix", "string", ",", "img", "image", ".", "Image", ")", "error", "{", "_", ",", "src", ",", "err", ":=", "inspect", "(", "img", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "i", ",", "p", ":=", "range", "src", "{", "err", "=", "dumpPlane", "(", "prefix", ",", "&", "p", ",", "i", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DumpImage dumps each img planes to disk using the input prefix
[ "DumpImage", "dumps", "each", "img", "planes", "to", "disk", "using", "the", "input", "prefix" ]
29f4463c688b986c11f166b12734f69b58b5555f
https://github.com/bamiaux/rez/blob/29f4463c688b986c11f166b12734f69b58b5555f/utils.go#L31-L43
17,338
weppos/publicsuffix-go
publicsuffix/publicsuffix.go
NewListFromString
func NewListFromString(src string, options *ParserOption) (*List, error) { l := NewList() _, err := l.LoadString(src, options) return l, err }
go
func NewListFromString(src string, options *ParserOption) (*List, error) { l := NewList() _, err := l.LoadString(src, options) return l, err }
[ "func", "NewListFromString", "(", "src", "string", ",", "options", "*", "ParserOption", ")", "(", "*", "List", ",", "error", ")", "{", "l", ":=", "NewList", "(", ")", "\n", "_", ",", "err", ":=", "l", ".", "LoadString", "(", "src", ",", "options", ")", "\n", "return", "l", ",", "err", "\n", "}" ]
// NewListFromString parses a string that represents a Public Suffix source // and returns a List initialized with the rules in the source.
[ "NewListFromString", "parses", "a", "string", "that", "represents", "a", "Public", "Suffix", "source", "and", "returns", "a", "List", "initialized", "with", "the", "rules", "in", "the", "source", "." ]
7c1d5dc5cdc2b05f1ea58e40ed9bdee01d9d0e4d
https://github.com/weppos/publicsuffix-go/blob/7c1d5dc5cdc2b05f1ea58e40ed9bdee01d9d0e4d/publicsuffix/publicsuffix.go#L94-L98
17,339
weppos/publicsuffix-go
publicsuffix/publicsuffix.go
NewListFromFile
func NewListFromFile(path string, options *ParserOption) (*List, error) { l := NewList() _, err := l.LoadFile(path, options) return l, err }
go
func NewListFromFile(path string, options *ParserOption) (*List, error) { l := NewList() _, err := l.LoadFile(path, options) return l, err }
[ "func", "NewListFromFile", "(", "path", "string", ",", "options", "*", "ParserOption", ")", "(", "*", "List", ",", "error", ")", "{", "l", ":=", "NewList", "(", ")", "\n", "_", ",", "err", ":=", "l", ".", "LoadFile", "(", "path", ",", "options", ")", "\n", "return", "l", ",", "err", "\n", "}" ]
// NewListFromFile parses a string that represents a Public Suffix source // and returns a List initialized with the rules in the source.
[ "NewListFromFile", "parses", "a", "string", "that", "represents", "a", "Public", "Suffix", "source", "and", "returns", "a", "List", "initialized", "with", "the", "rules", "in", "the", "source", "." ]
7c1d5dc5cdc2b05f1ea58e40ed9bdee01d9d0e4d
https://github.com/weppos/publicsuffix-go/blob/7c1d5dc5cdc2b05f1ea58e40ed9bdee01d9d0e4d/publicsuffix/publicsuffix.go#L102-L106
17,340
weppos/publicsuffix-go
publicsuffix/publicsuffix.go
Load
func (l *List) Load(r io.Reader, options *ParserOption) ([]Rule, error) { return l.parse(r, options) }
go
func (l *List) Load(r io.Reader, options *ParserOption) ([]Rule, error) { return l.parse(r, options) }
[ "func", "(", "l", "*", "List", ")", "Load", "(", "r", "io", ".", "Reader", ",", "options", "*", "ParserOption", ")", "(", "[", "]", "Rule", ",", "error", ")", "{", "return", "l", ".", "parse", "(", "r", ",", "options", ")", "\n", "}" ]
// Load parses and loads a set of rules from an io.Reader into the current list.
[ "Load", "parses", "and", "loads", "a", "set", "of", "rules", "from", "an", "io", ".", "Reader", "into", "the", "current", "list", "." ]
7c1d5dc5cdc2b05f1ea58e40ed9bdee01d9d0e4d
https://github.com/weppos/publicsuffix-go/blob/7c1d5dc5cdc2b05f1ea58e40ed9bdee01d9d0e4d/publicsuffix/publicsuffix.go#L109-L111
17,341
weppos/publicsuffix-go
publicsuffix/publicsuffix.go
LoadString
func (l *List) LoadString(src string, options *ParserOption) ([]Rule, error) { r := strings.NewReader(src) return l.parse(r, options) }
go
func (l *List) LoadString(src string, options *ParserOption) ([]Rule, error) { r := strings.NewReader(src) return l.parse(r, options) }
[ "func", "(", "l", "*", "List", ")", "LoadString", "(", "src", "string", ",", "options", "*", "ParserOption", ")", "(", "[", "]", "Rule", ",", "error", ")", "{", "r", ":=", "strings", ".", "NewReader", "(", "src", ")", "\n", "return", "l", ".", "parse", "(", "r", ",", "options", ")", "\n", "}" ]
// LoadString parses and loads a set of rules from a String into the current list.
[ "LoadString", "parses", "and", "loads", "a", "set", "of", "rules", "from", "a", "String", "into", "the", "current", "list", "." ]
7c1d5dc5cdc2b05f1ea58e40ed9bdee01d9d0e4d
https://github.com/weppos/publicsuffix-go/blob/7c1d5dc5cdc2b05f1ea58e40ed9bdee01d9d0e4d/publicsuffix/publicsuffix.go#L114-L117
17,342
weppos/publicsuffix-go
publicsuffix/publicsuffix.go
LoadFile
func (l *List) LoadFile(path string, options *ParserOption) ([]Rule, error) { f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() return l.parse(f, options) }
go
func (l *List) LoadFile(path string, options *ParserOption) ([]Rule, error) { f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() return l.parse(f, options) }
[ "func", "(", "l", "*", "List", ")", "LoadFile", "(", "path", "string", ",", "options", "*", "ParserOption", ")", "(", "[", "]", "Rule", ",", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "return", "l", ".", "parse", "(", "f", ",", "options", ")", "\n", "}" ]
// LoadFile parses and loads a set of rules from a File into the current list.
[ "LoadFile", "parses", "and", "loads", "a", "set", "of", "rules", "from", "a", "File", "into", "the", "current", "list", "." ]
7c1d5dc5cdc2b05f1ea58e40ed9bdee01d9d0e4d
https://github.com/weppos/publicsuffix-go/blob/7c1d5dc5cdc2b05f1ea58e40ed9bdee01d9d0e4d/publicsuffix/publicsuffix.go#L120-L127
17,343
weppos/publicsuffix-go
publicsuffix/publicsuffix.go
AddRule
func (l *List) AddRule(r *Rule) error { l.rules[r.Value] = r return nil }
go
func (l *List) AddRule(r *Rule) error { l.rules[r.Value] = r return nil }
[ "func", "(", "l", "*", "List", ")", "AddRule", "(", "r", "*", "Rule", ")", "error", "{", "l", ".", "rules", "[", "r", ".", "Value", "]", "=", "r", "\n", "return", "nil", "\n", "}" ]
// AddRule adds a new rule to the list. // // The exact position of the rule into the list is unpredictable. // The list may be optimized internally for lookups, therefore the algorithm // will decide the best position for the new rule.
[ "AddRule", "adds", "a", "new", "rule", "to", "the", "list", ".", "The", "exact", "position", "of", "the", "rule", "into", "the", "list", "is", "unpredictable", ".", "The", "list", "may", "be", "optimized", "internally", "for", "lookups", "therefore", "the", "algorithm", "will", "decide", "the", "best", "position", "for", "the", "new", "rule", "." ]
7c1d5dc5cdc2b05f1ea58e40ed9bdee01d9d0e4d
https://github.com/weppos/publicsuffix-go/blob/7c1d5dc5cdc2b05f1ea58e40ed9bdee01d9d0e4d/publicsuffix/publicsuffix.go#L134-L137
17,344
weppos/publicsuffix-go
publicsuffix/publicsuffix.go
Find
func (l *List) Find(name string, options *FindOptions) *Rule { if options == nil { options = DefaultFindOptions } part := name for { rule, ok := l.rules[part] if ok && rule.Match(name) && !(options.IgnorePrivate && rule.Private) { return rule } i := strings.IndexRune(part, '.') if i < 0 { return options.DefaultRule } part = part[i+1:] } return nil }
go
func (l *List) Find(name string, options *FindOptions) *Rule { if options == nil { options = DefaultFindOptions } part := name for { rule, ok := l.rules[part] if ok && rule.Match(name) && !(options.IgnorePrivate && rule.Private) { return rule } i := strings.IndexRune(part, '.') if i < 0 { return options.DefaultRule } part = part[i+1:] } return nil }
[ "func", "(", "l", "*", "List", ")", "Find", "(", "name", "string", ",", "options", "*", "FindOptions", ")", "*", "Rule", "{", "if", "options", "==", "nil", "{", "options", "=", "DefaultFindOptions", "\n", "}", "\n\n", "part", ":=", "name", "\n", "for", "{", "rule", ",", "ok", ":=", "l", ".", "rules", "[", "part", "]", "\n\n", "if", "ok", "&&", "rule", ".", "Match", "(", "name", ")", "&&", "!", "(", "options", ".", "IgnorePrivate", "&&", "rule", ".", "Private", ")", "{", "return", "rule", "\n", "}", "\n\n", "i", ":=", "strings", ".", "IndexRune", "(", "part", ",", "'.'", ")", "\n", "if", "i", "<", "0", "{", "return", "options", ".", "DefaultRule", "\n", "}", "\n\n", "part", "=", "part", "[", "i", "+", "1", ":", "]", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Find and returns the most appropriate rule for the domain name.
[ "Find", "and", "returns", "the", "most", "appropriate", "rule", "for", "the", "domain", "name", "." ]
7c1d5dc5cdc2b05f1ea58e40ed9bdee01d9d0e4d
https://github.com/weppos/publicsuffix-go/blob/7c1d5dc5cdc2b05f1ea58e40ed9bdee01d9d0e4d/publicsuffix/publicsuffix.go#L197-L219
17,345
weppos/publicsuffix-go
publicsuffix/publicsuffix.go
MustNewRule
func MustNewRule(content string) *Rule { rule, err := NewRule(content) if err != nil { panic(err) } return rule }
go
func MustNewRule(content string) *Rule { rule, err := NewRule(content) if err != nil { panic(err) } return rule }
[ "func", "MustNewRule", "(", "content", "string", ")", "*", "Rule", "{", "rule", ",", "err", ":=", "NewRule", "(", "content", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "rule", "\n", "}" ]
// MustNewRule is like NewRule, but panics if the content cannot be parsed.
[ "MustNewRule", "is", "like", "NewRule", "but", "panics", "if", "the", "content", "cannot", "be", "parsed", "." ]
7c1d5dc5cdc2b05f1ea58e40ed9bdee01d9d0e4d
https://github.com/weppos/publicsuffix-go/blob/7c1d5dc5cdc2b05f1ea58e40ed9bdee01d9d0e4d/publicsuffix/publicsuffix.go#L260-L266
17,346
weppos/publicsuffix-go
publicsuffix/publicsuffix.go
PublicSuffix
func (l cookiejarList) PublicSuffix(domain string) string { rule := l.List.Find(domain, nil) return rule.Decompose(domain)[1] }
go
func (l cookiejarList) PublicSuffix(domain string) string { rule := l.List.Find(domain, nil) return rule.Decompose(domain)[1] }
[ "func", "(", "l", "cookiejarList", ")", "PublicSuffix", "(", "domain", "string", ")", "string", "{", "rule", ":=", "l", ".", "List", ".", "Find", "(", "domain", ",", "nil", ")", "\n", "return", "rule", ".", "Decompose", "(", "domain", ")", "[", "1", "]", "\n", "}" ]
// PublicSuffix implements cookiejar.PublicSuffixList.
[ "PublicSuffix", "implements", "cookiejar", ".", "PublicSuffixList", "." ]
7c1d5dc5cdc2b05f1ea58e40ed9bdee01d9d0e4d
https://github.com/weppos/publicsuffix-go/blob/7c1d5dc5cdc2b05f1ea58e40ed9bdee01d9d0e4d/publicsuffix/publicsuffix.go#L530-L533
17,347
a8m/tree
node.go
Visit
func (node *Node) Visit(opts *Options) (dirs, files int) { // visited paths if path, err := filepath.Abs(node.path); err == nil { path = filepath.Clean(path) node.vpaths[path] = true } // stat fi, err := opts.Fs.Stat(node.path) if err != nil { node.err = err return } node.FileInfo = fi if !fi.IsDir() { return 0, 1 } // increase dirs only if it's a dir, but not the root. if node.depth != 0 { dirs++ } // DeepLevel option if opts.DeepLevel > 0 && opts.DeepLevel <= node.depth { return } names, err := opts.Fs.ReadDir(node.path) if err != nil { node.err = err return } node.nodes = make(Nodes, 0) for _, name := range names { // "all" option if !opts.All && strings.HasPrefix(name, ".") { continue } nnode := &Node{ path: filepath.Join(node.path, name), depth: node.depth + 1, vpaths: node.vpaths, } d, f := nnode.Visit(opts) if nnode.err == nil && !nnode.IsDir() { // "dirs only" option if opts.DirsOnly { continue } var rePrefix string if opts.IgnoreCase { rePrefix = "(?i)" } // Pattern matching if opts.Pattern != "" { re, err := regexp.Compile(rePrefix + opts.Pattern) if err == nil && !re.MatchString(name) { continue } } // IPattern matching if opts.IPattern != "" { re, err := regexp.Compile(rePrefix + opts.IPattern) if err == nil && re.MatchString(name) { continue } } } node.nodes = append(node.nodes, nnode) dirs, files = dirs+d, files+f } // Sorting if !opts.NoSort { node.sort(opts) } return }
go
func (node *Node) Visit(opts *Options) (dirs, files int) { // visited paths if path, err := filepath.Abs(node.path); err == nil { path = filepath.Clean(path) node.vpaths[path] = true } // stat fi, err := opts.Fs.Stat(node.path) if err != nil { node.err = err return } node.FileInfo = fi if !fi.IsDir() { return 0, 1 } // increase dirs only if it's a dir, but not the root. if node.depth != 0 { dirs++ } // DeepLevel option if opts.DeepLevel > 0 && opts.DeepLevel <= node.depth { return } names, err := opts.Fs.ReadDir(node.path) if err != nil { node.err = err return } node.nodes = make(Nodes, 0) for _, name := range names { // "all" option if !opts.All && strings.HasPrefix(name, ".") { continue } nnode := &Node{ path: filepath.Join(node.path, name), depth: node.depth + 1, vpaths: node.vpaths, } d, f := nnode.Visit(opts) if nnode.err == nil && !nnode.IsDir() { // "dirs only" option if opts.DirsOnly { continue } var rePrefix string if opts.IgnoreCase { rePrefix = "(?i)" } // Pattern matching if opts.Pattern != "" { re, err := regexp.Compile(rePrefix + opts.Pattern) if err == nil && !re.MatchString(name) { continue } } // IPattern matching if opts.IPattern != "" { re, err := regexp.Compile(rePrefix + opts.IPattern) if err == nil && re.MatchString(name) { continue } } } node.nodes = append(node.nodes, nnode) dirs, files = dirs+d, files+f } // Sorting if !opts.NoSort { node.sort(opts) } return }
[ "func", "(", "node", "*", "Node", ")", "Visit", "(", "opts", "*", "Options", ")", "(", "dirs", ",", "files", "int", ")", "{", "// visited paths", "if", "path", ",", "err", ":=", "filepath", ".", "Abs", "(", "node", ".", "path", ")", ";", "err", "==", "nil", "{", "path", "=", "filepath", ".", "Clean", "(", "path", ")", "\n", "node", ".", "vpaths", "[", "path", "]", "=", "true", "\n", "}", "\n", "// stat", "fi", ",", "err", ":=", "opts", ".", "Fs", ".", "Stat", "(", "node", ".", "path", ")", "\n", "if", "err", "!=", "nil", "{", "node", ".", "err", "=", "err", "\n", "return", "\n", "}", "\n", "node", ".", "FileInfo", "=", "fi", "\n", "if", "!", "fi", ".", "IsDir", "(", ")", "{", "return", "0", ",", "1", "\n", "}", "\n", "// increase dirs only if it's a dir, but not the root.", "if", "node", ".", "depth", "!=", "0", "{", "dirs", "++", "\n", "}", "\n", "// DeepLevel option", "if", "opts", ".", "DeepLevel", ">", "0", "&&", "opts", ".", "DeepLevel", "<=", "node", ".", "depth", "{", "return", "\n", "}", "\n", "names", ",", "err", ":=", "opts", ".", "Fs", ".", "ReadDir", "(", "node", ".", "path", ")", "\n", "if", "err", "!=", "nil", "{", "node", ".", "err", "=", "err", "\n", "return", "\n", "}", "\n", "node", ".", "nodes", "=", "make", "(", "Nodes", ",", "0", ")", "\n", "for", "_", ",", "name", ":=", "range", "names", "{", "// \"all\" option", "if", "!", "opts", ".", "All", "&&", "strings", ".", "HasPrefix", "(", "name", ",", "\"", "\"", ")", "{", "continue", "\n", "}", "\n", "nnode", ":=", "&", "Node", "{", "path", ":", "filepath", ".", "Join", "(", "node", ".", "path", ",", "name", ")", ",", "depth", ":", "node", ".", "depth", "+", "1", ",", "vpaths", ":", "node", ".", "vpaths", ",", "}", "\n", "d", ",", "f", ":=", "nnode", ".", "Visit", "(", "opts", ")", "\n", "if", "nnode", ".", "err", "==", "nil", "&&", "!", "nnode", ".", "IsDir", "(", ")", "{", "// \"dirs only\" option", "if", "opts", ".", "DirsOnly", "{", "continue", "\n", "}", "\n", "var", "rePrefix", "string", "\n", "if", "opts", ".", "IgnoreCase", "{", "rePrefix", "=", "\"", "\"", "\n", "}", "\n", "// Pattern matching", "if", "opts", ".", "Pattern", "!=", "\"", "\"", "{", "re", ",", "err", ":=", "regexp", ".", "Compile", "(", "rePrefix", "+", "opts", ".", "Pattern", ")", "\n", "if", "err", "==", "nil", "&&", "!", "re", ".", "MatchString", "(", "name", ")", "{", "continue", "\n", "}", "\n", "}", "\n", "// IPattern matching", "if", "opts", ".", "IPattern", "!=", "\"", "\"", "{", "re", ",", "err", ":=", "regexp", ".", "Compile", "(", "rePrefix", "+", "opts", ".", "IPattern", ")", "\n", "if", "err", "==", "nil", "&&", "re", ".", "MatchString", "(", "name", ")", "{", "continue", "\n", "}", "\n", "}", "\n", "}", "\n", "node", ".", "nodes", "=", "append", "(", "node", ".", "nodes", ",", "nnode", ")", "\n", "dirs", ",", "files", "=", "dirs", "+", "d", ",", "files", "+", "f", "\n", "}", "\n", "// Sorting", "if", "!", "opts", ".", "NoSort", "{", "node", ".", "sort", "(", "opts", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Visit all files under the given node.
[ "Visit", "all", "files", "under", "the", "given", "node", "." ]
6a0b80129de45f91880d18428b95fab29df91d7e
https://github.com/a8m/tree/blob/6a0b80129de45f91880d18428b95fab29df91d7e/node.go#L82-L155
17,348
a8m/tree
node.go
formatBytes
func formatBytes(i int64) (result string) { var n float64 sFmt, eFmt := "%.01f", "" switch { case i > EB: eFmt = "E" n = float64(i) / float64(EB) case i > PB: eFmt = "P" n = float64(i) / float64(PB) case i > TB: eFmt = "T" n = float64(i) / float64(TB) case i > GB: eFmt = "G" n = float64(i) / float64(GB) case i > MB: eFmt = "M" n = float64(i) / float64(MB) case i > KB: eFmt = "K" n = float64(i) / float64(KB) default: sFmt = "%.0f" n = float64(i) } if eFmt != "" && n >= 10 { sFmt = "%.0f" } result = fmt.Sprintf(sFmt+eFmt, n) result = strings.Trim(result, " ") return }
go
func formatBytes(i int64) (result string) { var n float64 sFmt, eFmt := "%.01f", "" switch { case i > EB: eFmt = "E" n = float64(i) / float64(EB) case i > PB: eFmt = "P" n = float64(i) / float64(PB) case i > TB: eFmt = "T" n = float64(i) / float64(TB) case i > GB: eFmt = "G" n = float64(i) / float64(GB) case i > MB: eFmt = "M" n = float64(i) / float64(MB) case i > KB: eFmt = "K" n = float64(i) / float64(KB) default: sFmt = "%.0f" n = float64(i) } if eFmt != "" && n >= 10 { sFmt = "%.0f" } result = fmt.Sprintf(sFmt+eFmt, n) result = strings.Trim(result, " ") return }
[ "func", "formatBytes", "(", "i", "int64", ")", "(", "result", "string", ")", "{", "var", "n", "float64", "\n", "sFmt", ",", "eFmt", ":=", "\"", "\"", ",", "\"", "\"", "\n", "switch", "{", "case", "i", ">", "EB", ":", "eFmt", "=", "\"", "\"", "\n", "n", "=", "float64", "(", "i", ")", "/", "float64", "(", "EB", ")", "\n", "case", "i", ">", "PB", ":", "eFmt", "=", "\"", "\"", "\n", "n", "=", "float64", "(", "i", ")", "/", "float64", "(", "PB", ")", "\n", "case", "i", ">", "TB", ":", "eFmt", "=", "\"", "\"", "\n", "n", "=", "float64", "(", "i", ")", "/", "float64", "(", "TB", ")", "\n", "case", "i", ">", "GB", ":", "eFmt", "=", "\"", "\"", "\n", "n", "=", "float64", "(", "i", ")", "/", "float64", "(", "GB", ")", "\n", "case", "i", ">", "MB", ":", "eFmt", "=", "\"", "\"", "\n", "n", "=", "float64", "(", "i", ")", "/", "float64", "(", "MB", ")", "\n", "case", "i", ">", "KB", ":", "eFmt", "=", "\"", "\"", "\n", "n", "=", "float64", "(", "i", ")", "/", "float64", "(", "KB", ")", "\n", "default", ":", "sFmt", "=", "\"", "\"", "\n", "n", "=", "float64", "(", "i", ")", "\n", "}", "\n", "if", "eFmt", "!=", "\"", "\"", "&&", "n", ">=", "10", "{", "sFmt", "=", "\"", "\"", "\n", "}", "\n", "result", "=", "fmt", ".", "Sprintf", "(", "sFmt", "+", "eFmt", ",", "n", ")", "\n", "result", "=", "strings", ".", "Trim", "(", "result", ",", "\"", "\"", ")", "\n", "return", "\n", "}" ]
// Convert bytes to human readable string. Like a 2 MB, 64.2 KB, 52 B
[ "Convert", "bytes", "to", "human", "readable", "string", ".", "Like", "a", "2", "MB", "64", ".", "2", "KB", "52", "B" ]
6a0b80129de45f91880d18428b95fab29df91d7e
https://github.com/a8m/tree/blob/6a0b80129de45f91880d18428b95fab29df91d7e/node.go#L367-L399
17,349
a8m/tree
color.go
contains
func contains(slice []string, str string) bool { for _, val := range slice { if val == strings.ToLower(str) { return true } } return false }
go
func contains(slice []string, str string) bool { for _, val := range slice { if val == strings.ToLower(str) { return true } } return false }
[ "func", "contains", "(", "slice", "[", "]", "string", ",", "str", "string", ")", "bool", "{", "for", "_", ",", "val", ":=", "range", "slice", "{", "if", "val", "==", "strings", ".", "ToLower", "(", "str", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// case-insensitive contains helper
[ "case", "-", "insensitive", "contains", "helper" ]
6a0b80129de45f91880d18428b95fab29df91d7e
https://github.com/a8m/tree/blob/6a0b80129de45f91880d18428b95fab29df91d7e/color.go#L65-L72
17,350
ghetzel/pivot
dal/record_loader.go
getIdentityFieldNameFromStruct
func getIdentityFieldNameFromStruct(instance interface{}, fallbackIdentityFieldName string) (string, string, error) { if err := validatePtrToStructType(instance); err != nil { return ``, ``, err } s := structs.New(instance) // find a field with an ",identity" tag and get its value for _, field := range s.Fields() { if tag := field.Tag(RecordStructTag); tag != `` { v := strings.Split(tag, `,`) if sliceutil.ContainsString(v[1:], `identity`) { if v[0] != `` { return field.Name(), v[0], nil } else { return field.Name(), field.Name(), nil } } } } if fallbackIdentityFieldName == `` { fallbackIdentityFieldName = DefaultStructIdentityFieldName } if _, ok := s.FieldOk(fallbackIdentityFieldName); ok { return fallbackIdentityFieldName, fallbackIdentityFieldName, nil } else if _, ok := s.FieldOk(DefaultStructIdentityFieldName); ok { return DefaultStructIdentityFieldName, DefaultStructIdentityFieldName, nil } return ``, ``, fmt.Errorf("No identity field could be found for type %T", instance) }
go
func getIdentityFieldNameFromStruct(instance interface{}, fallbackIdentityFieldName string) (string, string, error) { if err := validatePtrToStructType(instance); err != nil { return ``, ``, err } s := structs.New(instance) // find a field with an ",identity" tag and get its value for _, field := range s.Fields() { if tag := field.Tag(RecordStructTag); tag != `` { v := strings.Split(tag, `,`) if sliceutil.ContainsString(v[1:], `identity`) { if v[0] != `` { return field.Name(), v[0], nil } else { return field.Name(), field.Name(), nil } } } } if fallbackIdentityFieldName == `` { fallbackIdentityFieldName = DefaultStructIdentityFieldName } if _, ok := s.FieldOk(fallbackIdentityFieldName); ok { return fallbackIdentityFieldName, fallbackIdentityFieldName, nil } else if _, ok := s.FieldOk(DefaultStructIdentityFieldName); ok { return DefaultStructIdentityFieldName, DefaultStructIdentityFieldName, nil } return ``, ``, fmt.Errorf("No identity field could be found for type %T", instance) }
[ "func", "getIdentityFieldNameFromStruct", "(", "instance", "interface", "{", "}", ",", "fallbackIdentityFieldName", "string", ")", "(", "string", ",", "string", ",", "error", ")", "{", "if", "err", ":=", "validatePtrToStructType", "(", "instance", ")", ";", "err", "!=", "nil", "{", "return", "``", ",", "``", ",", "err", "\n", "}", "\n\n", "s", ":=", "structs", ".", "New", "(", "instance", ")", "\n\n", "// find a field with an \",identity\" tag and get its value", "for", "_", ",", "field", ":=", "range", "s", ".", "Fields", "(", ")", "{", "if", "tag", ":=", "field", ".", "Tag", "(", "RecordStructTag", ")", ";", "tag", "!=", "``", "{", "v", ":=", "strings", ".", "Split", "(", "tag", ",", "`,`", ")", "\n\n", "if", "sliceutil", ".", "ContainsString", "(", "v", "[", "1", ":", "]", ",", "`identity`", ")", "{", "if", "v", "[", "0", "]", "!=", "``", "{", "return", "field", ".", "Name", "(", ")", ",", "v", "[", "0", "]", ",", "nil", "\n", "}", "else", "{", "return", "field", ".", "Name", "(", ")", ",", "field", ".", "Name", "(", ")", ",", "nil", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "fallbackIdentityFieldName", "==", "``", "{", "fallbackIdentityFieldName", "=", "DefaultStructIdentityFieldName", "\n", "}", "\n\n", "if", "_", ",", "ok", ":=", "s", ".", "FieldOk", "(", "fallbackIdentityFieldName", ")", ";", "ok", "{", "return", "fallbackIdentityFieldName", ",", "fallbackIdentityFieldName", ",", "nil", "\n", "}", "else", "if", "_", ",", "ok", ":=", "s", ".", "FieldOk", "(", "DefaultStructIdentityFieldName", ")", ";", "ok", "{", "return", "DefaultStructIdentityFieldName", ",", "DefaultStructIdentityFieldName", ",", "nil", "\n", "}", "\n\n", "return", "``", ",", "``", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "instance", ")", "\n", "}" ]
// Retrieves the struct field name and key name that represents the identity field for a given struct.
[ "Retrieves", "the", "struct", "field", "name", "and", "key", "name", "that", "represents", "the", "identity", "field", "for", "a", "given", "struct", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/record_loader.go#L25-L58
17,351
ghetzel/pivot
dal/connection.go
Scheme
func (self *ConnectionString) Scheme() (string, string) { backend, protocol := stringutil.SplitPair(self.URI.Scheme, `+`) return backend, strings.Trim(protocol, `/`) }
go
func (self *ConnectionString) Scheme() (string, string) { backend, protocol := stringutil.SplitPair(self.URI.Scheme, `+`) return backend, strings.Trim(protocol, `/`) }
[ "func", "(", "self", "*", "ConnectionString", ")", "Scheme", "(", ")", "(", "string", ",", "string", ")", "{", "backend", ",", "protocol", ":=", "stringutil", ".", "SplitPair", "(", "self", ".", "URI", ".", "Scheme", ",", "`+`", ")", "\n", "return", "backend", ",", "strings", ".", "Trim", "(", "protocol", ",", "`/`", ")", "\n", "}" ]
// Returns the backend and protocol components of the string.
[ "Returns", "the", "backend", "and", "protocol", "components", "of", "the", "string", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/connection.go#L54-L57
17,352
ghetzel/pivot
dal/connection.go
Protocol
func (self *ConnectionString) Protocol(defaults ...string) string { if _, protocol := self.Scheme(); protocol != `` { return protocol } else if len(defaults) > 0 { return defaults[0] } else { return `` } }
go
func (self *ConnectionString) Protocol(defaults ...string) string { if _, protocol := self.Scheme(); protocol != `` { return protocol } else if len(defaults) > 0 { return defaults[0] } else { return `` } }
[ "func", "(", "self", "*", "ConnectionString", ")", "Protocol", "(", "defaults", "...", "string", ")", "string", "{", "if", "_", ",", "protocol", ":=", "self", ".", "Scheme", "(", ")", ";", "protocol", "!=", "``", "{", "return", "protocol", "\n", "}", "else", "if", "len", "(", "defaults", ")", ">", "0", "{", "return", "defaults", "[", "0", "]", "\n", "}", "else", "{", "return", "``", "\n", "}", "\n", "}" ]
// Returns the protocol component of the string.
[ "Returns", "the", "protocol", "component", "of", "the", "string", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/connection.go#L66-L75
17,353
ghetzel/pivot
dal/connection.go
Host
func (self *ConnectionString) Host(defaults ...string) string { if host := self.URI.Host; host != `` { return host } else if len(defaults) > 0 { return defaults[0] } else { return `` } }
go
func (self *ConnectionString) Host(defaults ...string) string { if host := self.URI.Host; host != `` { return host } else if len(defaults) > 0 { return defaults[0] } else { return `` } }
[ "func", "(", "self", "*", "ConnectionString", ")", "Host", "(", "defaults", "...", "string", ")", "string", "{", "if", "host", ":=", "self", ".", "URI", ".", "Host", ";", "host", "!=", "``", "{", "return", "host", "\n", "}", "else", "if", "len", "(", "defaults", ")", ">", "0", "{", "return", "defaults", "[", "0", "]", "\n", "}", "else", "{", "return", "``", "\n", "}", "\n", "}" ]
// Returns the host component of the string.
[ "Returns", "the", "host", "component", "of", "the", "string", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/connection.go#L78-L86
17,354
ghetzel/pivot
dal/connection.go
Dataset
func (self *ConnectionString) Dataset() string { dataset := self.URI.Path dataset = strings.TrimPrefix(dataset, `/`) dataset = strings.TrimSuffix(dataset, `/`) return dataset }
go
func (self *ConnectionString) Dataset() string { dataset := self.URI.Path dataset = strings.TrimPrefix(dataset, `/`) dataset = strings.TrimSuffix(dataset, `/`) return dataset }
[ "func", "(", "self", "*", "ConnectionString", ")", "Dataset", "(", ")", "string", "{", "dataset", ":=", "self", ".", "URI", ".", "Path", "\n", "dataset", "=", "strings", ".", "TrimPrefix", "(", "dataset", ",", "`/`", ")", "\n", "dataset", "=", "strings", ".", "TrimSuffix", "(", "dataset", ",", "`/`", ")", "\n", "return", "dataset", "\n", "}" ]
// Returns the dataset component of the string.
[ "Returns", "the", "dataset", "component", "of", "the", "string", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/connection.go#L89-L94
17,355
ghetzel/pivot
dal/connection.go
SetCredentials
func (self *ConnectionString) SetCredentials(username string, password string) { self.URI.User = url.UserPassword(username, password) }
go
func (self *ConnectionString) SetCredentials(username string, password string) { self.URI.User = url.UserPassword(username, password) }
[ "func", "(", "self", "*", "ConnectionString", ")", "SetCredentials", "(", "username", "string", ",", "password", "string", ")", "{", "self", ".", "URI", ".", "User", "=", "url", ".", "UserPassword", "(", "username", ",", "password", ")", "\n", "}" ]
// Explicitly set username and password on this connection string
[ "Explicitly", "set", "username", "and", "password", "on", "this", "connection", "string" ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/connection.go#L97-L99
17,356
ghetzel/pivot
dal/connection.go
LoadCredentialsFromNetrc
func (self *ConnectionString) LoadCredentialsFromNetrc(filename string) error { if u := self.URI.User; u == nil && filename != `` { filename = fileutil.MustExpandUser(filename) if fileutil.IsNonemptyFile(filename) { if netrcFile, err := netrc.Parse(filename); err == nil { if machine := netrcFile.Machine(self.URI.Hostname()); machine != nil { log.Debugf("Reading credentials from %v for host %v", filename, machine.Name) login := machine.Get(`login`) password := machine.Get(`password`) if login != `` || password != `` { self.URI.User = url.UserPassword(login, password) } } } else { return fmt.Errorf("netrc error: %v", err) } } } return nil }
go
func (self *ConnectionString) LoadCredentialsFromNetrc(filename string) error { if u := self.URI.User; u == nil && filename != `` { filename = fileutil.MustExpandUser(filename) if fileutil.IsNonemptyFile(filename) { if netrcFile, err := netrc.Parse(filename); err == nil { if machine := netrcFile.Machine(self.URI.Hostname()); machine != nil { log.Debugf("Reading credentials from %v for host %v", filename, machine.Name) login := machine.Get(`login`) password := machine.Get(`password`) if login != `` || password != `` { self.URI.User = url.UserPassword(login, password) } } } else { return fmt.Errorf("netrc error: %v", err) } } } return nil }
[ "func", "(", "self", "*", "ConnectionString", ")", "LoadCredentialsFromNetrc", "(", "filename", "string", ")", "error", "{", "if", "u", ":=", "self", ".", "URI", ".", "User", ";", "u", "==", "nil", "&&", "filename", "!=", "``", "{", "filename", "=", "fileutil", ".", "MustExpandUser", "(", "filename", ")", "\n\n", "if", "fileutil", ".", "IsNonemptyFile", "(", "filename", ")", "{", "if", "netrcFile", ",", "err", ":=", "netrc", ".", "Parse", "(", "filename", ")", ";", "err", "==", "nil", "{", "if", "machine", ":=", "netrcFile", ".", "Machine", "(", "self", ".", "URI", ".", "Hostname", "(", ")", ")", ";", "machine", "!=", "nil", "{", "log", ".", "Debugf", "(", "\"", "\"", ",", "filename", ",", "machine", ".", "Name", ")", "\n\n", "login", ":=", "machine", ".", "Get", "(", "`login`", ")", "\n", "password", ":=", "machine", ".", "Get", "(", "`password`", ")", "\n\n", "if", "login", "!=", "``", "||", "password", "!=", "``", "{", "self", ".", "URI", ".", "User", "=", "url", ".", "UserPassword", "(", "login", ",", "password", ")", "\n", "}", "\n", "}", "\n", "}", "else", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Reads a .netrc-style file and loads the appropriate credentials. The host component of // this connection string is matched with the netrc "machine" field.
[ "Reads", "a", ".", "netrc", "-", "style", "file", "and", "loads", "the", "appropriate", "credentials", ".", "The", "host", "component", "of", "this", "connection", "string", "is", "matched", "with", "the", "netrc", "machine", "field", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/connection.go#L103-L127
17,357
ghetzel/pivot
dal/collection.go
NewCollection
func NewCollection(name string) *Collection { return &Collection{ Name: name, Fields: make([]Field, 0), IdentityField: DefaultIdentityField, IdentityFieldType: DefaultIdentityFieldType, IdentityFieldValidator: ValidateNotEmpty, } }
go
func NewCollection(name string) *Collection { return &Collection{ Name: name, Fields: make([]Field, 0), IdentityField: DefaultIdentityField, IdentityFieldType: DefaultIdentityFieldType, IdentityFieldValidator: ValidateNotEmpty, } }
[ "func", "NewCollection", "(", "name", "string", ")", "*", "Collection", "{", "return", "&", "Collection", "{", "Name", ":", "name", ",", "Fields", ":", "make", "(", "[", "]", "Field", ",", "0", ")", ",", "IdentityField", ":", "DefaultIdentityField", ",", "IdentityFieldType", ":", "DefaultIdentityFieldType", ",", "IdentityFieldValidator", ":", "ValidateNotEmpty", ",", "}", "\n", "}" ]
// Create a new colllection definition with no fields.
[ "Create", "a", "new", "colllection", "definition", "with", "no", "fields", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/collection.go#L112-L120
17,358
ghetzel/pivot
dal/collection.go
TTL
func (self *Collection) TTL(record *Record) time.Duration { if self.TimeToLiveField != `` { if value := record.Get(self.TimeToLiveField); !typeutil.IsZero(value) { if expireAt := typeutil.V(value).Time(); !expireAt.IsZero() { return expireAt.Sub(time.Now()) } } } return 0 }
go
func (self *Collection) TTL(record *Record) time.Duration { if self.TimeToLiveField != `` { if value := record.Get(self.TimeToLiveField); !typeutil.IsZero(value) { if expireAt := typeutil.V(value).Time(); !expireAt.IsZero() { return expireAt.Sub(time.Now()) } } } return 0 }
[ "func", "(", "self", "*", "Collection", ")", "TTL", "(", "record", "*", "Record", ")", "time", ".", "Duration", "{", "if", "self", ".", "TimeToLiveField", "!=", "``", "{", "if", "value", ":=", "record", ".", "Get", "(", "self", ".", "TimeToLiveField", ")", ";", "!", "typeutil", ".", "IsZero", "(", "value", ")", "{", "if", "expireAt", ":=", "typeutil", ".", "V", "(", "value", ")", ".", "Time", "(", ")", ";", "!", "expireAt", ".", "IsZero", "(", ")", "{", "return", "expireAt", ".", "Sub", "(", "time", ".", "Now", "(", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "0", "\n", "}" ]
// Return the duration until the TimeToLiveField in given record expires within the current collection. // Collections with an empty TimeToLiveField, or records with a missing or zero-valued TimeToLiveField // will return 0. If the record has already expired, the returned duration will be a negative number.
[ "Return", "the", "duration", "until", "the", "TimeToLiveField", "in", "given", "record", "expires", "within", "the", "current", "collection", ".", "Collections", "with", "an", "empty", "TimeToLiveField", "or", "records", "with", "a", "missing", "or", "zero", "-", "valued", "TimeToLiveField", "will", "return", "0", ".", "If", "the", "record", "has", "already", "expired", "the", "returned", "duration", "will", "be", "a", "negative", "number", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/collection.go#L125-L135
17,359
ghetzel/pivot
dal/collection.go
IsExpired
func (self *Collection) IsExpired(record *Record) bool { if self.TTL(record) < 0 { return true } else { return false } }
go
func (self *Collection) IsExpired(record *Record) bool { if self.TTL(record) < 0 { return true } else { return false } }
[ "func", "(", "self", "*", "Collection", ")", "IsExpired", "(", "record", "*", "Record", ")", "bool", "{", "if", "self", ".", "TTL", "(", "record", ")", "<", "0", "{", "return", "true", "\n", "}", "else", "{", "return", "false", "\n", "}", "\n", "}" ]
// Expired records are those whose TTL duration is non-zero and negative.
[ "Expired", "records", "are", "those", "whose", "TTL", "duration", "is", "non", "-", "zero", "and", "negative", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/collection.go#L138-L144
17,360
ghetzel/pivot
dal/collection.go
GetIndexName
func (self *Collection) GetIndexName() string { if self.IndexName != `` { return self.IndexName } return self.Name }
go
func (self *Collection) GetIndexName() string { if self.IndexName != `` { return self.IndexName } return self.Name }
[ "func", "(", "self", "*", "Collection", ")", "GetIndexName", "(", ")", "string", "{", "if", "self", ".", "IndexName", "!=", "``", "{", "return", "self", ".", "IndexName", "\n", "}", "\n\n", "return", "self", ".", "Name", "\n", "}" ]
// Get the canonical name of the external index name.
[ "Get", "the", "canonical", "name", "of", "the", "external", "index", "name", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/collection.go#L147-L153
17,361
ghetzel/pivot
dal/collection.go
GetAggregatorName
func (self *Collection) GetAggregatorName() string { if self.IndexName != `` { return self.IndexName } return self.Name }
go
func (self *Collection) GetAggregatorName() string { if self.IndexName != `` { return self.IndexName } return self.Name }
[ "func", "(", "self", "*", "Collection", ")", "GetAggregatorName", "(", ")", "string", "{", "if", "self", ".", "IndexName", "!=", "``", "{", "return", "self", ".", "IndexName", "\n", "}", "\n\n", "return", "self", ".", "Name", "\n", "}" ]
// Get the canonical name of the dataset in an external aggregator service.
[ "Get", "the", "canonical", "name", "of", "the", "dataset", "in", "an", "external", "aggregator", "service", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/collection.go#L156-L162
17,362
ghetzel/pivot
dal/collection.go
SetIdentity
func (self *Collection) SetIdentity(name string, idtype Type, formatter FieldFormatterFunc, validator FieldValidatorFunc) *Collection { if name != `` { self.IdentityField = name } self.IdentityFieldType = idtype if formatter != nil { self.IdentityFieldFormatter = formatter } if validator != nil { self.IdentityFieldValidator = validator } return self }
go
func (self *Collection) SetIdentity(name string, idtype Type, formatter FieldFormatterFunc, validator FieldValidatorFunc) *Collection { if name != `` { self.IdentityField = name } self.IdentityFieldType = idtype if formatter != nil { self.IdentityFieldFormatter = formatter } if validator != nil { self.IdentityFieldValidator = validator } return self }
[ "func", "(", "self", "*", "Collection", ")", "SetIdentity", "(", "name", "string", ",", "idtype", "Type", ",", "formatter", "FieldFormatterFunc", ",", "validator", "FieldValidatorFunc", ")", "*", "Collection", "{", "if", "name", "!=", "``", "{", "self", ".", "IdentityField", "=", "name", "\n", "}", "\n\n", "self", ".", "IdentityFieldType", "=", "idtype", "\n\n", "if", "formatter", "!=", "nil", "{", "self", ".", "IdentityFieldFormatter", "=", "formatter", "\n", "}", "\n\n", "if", "validator", "!=", "nil", "{", "self", ".", "IdentityFieldValidator", "=", "validator", "\n", "}", "\n\n", "return", "self", "\n", "}" ]
// Configure the identity field of a collection in a single function call.
[ "Configure", "the", "identity", "field", "of", "a", "collection", "in", "a", "single", "function", "call", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/collection.go#L165-L181
17,363
ghetzel/pivot
dal/collection.go
AddFields
func (self *Collection) AddFields(fields ...Field) *Collection { self.Fields = append(self.Fields, fields...) return self }
go
func (self *Collection) AddFields(fields ...Field) *Collection { self.Fields = append(self.Fields, fields...) return self }
[ "func", "(", "self", "*", "Collection", ")", "AddFields", "(", "fields", "...", "Field", ")", "*", "Collection", "{", "self", ".", "Fields", "=", "append", "(", "self", ".", "Fields", ",", "fields", "...", ")", "\n", "return", "self", "\n", "}" ]
// Append a field definition to this collection.
[ "Append", "a", "field", "definition", "to", "this", "collection", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/collection.go#L184-L187
17,364
ghetzel/pivot
dal/collection.go
ApplyDefinition
func (self *Collection) ApplyDefinition(definition *Collection) error { if definition != nil { if v := definition.IdentityField; v != `` { self.IdentityField = v } if v := definition.IdentityFieldType; v != `` { self.IdentityFieldType = v } if fn := definition.IdentityFieldFormatter; fn != nil { self.IdentityFieldFormatter = fn } if fn := definition.IdentityFieldValidator; fn != nil { self.IdentityFieldValidator = fn } for i, field := range self.Fields { if defField, ok := definition.GetField(field.Name); ok { if field.Description == `` { self.Fields[i].Description = defField.Description } if field.Length == 0 && defField.Length != 0 { self.Fields[i].Length = defField.Length } if field.Precision == 0 && defField.Precision != 0 { self.Fields[i].Precision = defField.Precision } // unconditionally pull these over as they are either client-only fields or we know better // than the database on this one self.Fields[i].Required = defField.Required self.Fields[i].Type = defField.Type self.Fields[i].KeyType = defField.KeyType self.Fields[i].Subtype = defField.Subtype self.Fields[i].DefaultValue = defField.DefaultValue self.Fields[i].ValidateOnPopulate = defField.ValidateOnPopulate self.Fields[i].Validator = defField.Validator self.Fields[i].Formatter = defField.Formatter } else { return fmt.Errorf("Definition is missing field %q", field.Name) } } } return nil }
go
func (self *Collection) ApplyDefinition(definition *Collection) error { if definition != nil { if v := definition.IdentityField; v != `` { self.IdentityField = v } if v := definition.IdentityFieldType; v != `` { self.IdentityFieldType = v } if fn := definition.IdentityFieldFormatter; fn != nil { self.IdentityFieldFormatter = fn } if fn := definition.IdentityFieldValidator; fn != nil { self.IdentityFieldValidator = fn } for i, field := range self.Fields { if defField, ok := definition.GetField(field.Name); ok { if field.Description == `` { self.Fields[i].Description = defField.Description } if field.Length == 0 && defField.Length != 0 { self.Fields[i].Length = defField.Length } if field.Precision == 0 && defField.Precision != 0 { self.Fields[i].Precision = defField.Precision } // unconditionally pull these over as they are either client-only fields or we know better // than the database on this one self.Fields[i].Required = defField.Required self.Fields[i].Type = defField.Type self.Fields[i].KeyType = defField.KeyType self.Fields[i].Subtype = defField.Subtype self.Fields[i].DefaultValue = defField.DefaultValue self.Fields[i].ValidateOnPopulate = defField.ValidateOnPopulate self.Fields[i].Validator = defField.Validator self.Fields[i].Formatter = defField.Formatter } else { return fmt.Errorf("Definition is missing field %q", field.Name) } } } return nil }
[ "func", "(", "self", "*", "Collection", ")", "ApplyDefinition", "(", "definition", "*", "Collection", ")", "error", "{", "if", "definition", "!=", "nil", "{", "if", "v", ":=", "definition", ".", "IdentityField", ";", "v", "!=", "``", "{", "self", ".", "IdentityField", "=", "v", "\n", "}", "\n\n", "if", "v", ":=", "definition", ".", "IdentityFieldType", ";", "v", "!=", "``", "{", "self", ".", "IdentityFieldType", "=", "v", "\n", "}", "\n\n", "if", "fn", ":=", "definition", ".", "IdentityFieldFormatter", ";", "fn", "!=", "nil", "{", "self", ".", "IdentityFieldFormatter", "=", "fn", "\n", "}", "\n\n", "if", "fn", ":=", "definition", ".", "IdentityFieldValidator", ";", "fn", "!=", "nil", "{", "self", ".", "IdentityFieldValidator", "=", "fn", "\n", "}", "\n\n", "for", "i", ",", "field", ":=", "range", "self", ".", "Fields", "{", "if", "defField", ",", "ok", ":=", "definition", ".", "GetField", "(", "field", ".", "Name", ")", ";", "ok", "{", "if", "field", ".", "Description", "==", "``", "{", "self", ".", "Fields", "[", "i", "]", ".", "Description", "=", "defField", ".", "Description", "\n", "}", "\n\n", "if", "field", ".", "Length", "==", "0", "&&", "defField", ".", "Length", "!=", "0", "{", "self", ".", "Fields", "[", "i", "]", ".", "Length", "=", "defField", ".", "Length", "\n", "}", "\n\n", "if", "field", ".", "Precision", "==", "0", "&&", "defField", ".", "Precision", "!=", "0", "{", "self", ".", "Fields", "[", "i", "]", ".", "Precision", "=", "defField", ".", "Precision", "\n", "}", "\n\n", "// unconditionally pull these over as they are either client-only fields or we know better", "// than the database on this one", "self", ".", "Fields", "[", "i", "]", ".", "Required", "=", "defField", ".", "Required", "\n", "self", ".", "Fields", "[", "i", "]", ".", "Type", "=", "defField", ".", "Type", "\n", "self", ".", "Fields", "[", "i", "]", ".", "KeyType", "=", "defField", ".", "KeyType", "\n", "self", ".", "Fields", "[", "i", "]", ".", "Subtype", "=", "defField", ".", "Subtype", "\n", "self", ".", "Fields", "[", "i", "]", ".", "DefaultValue", "=", "defField", ".", "DefaultValue", "\n", "self", ".", "Fields", "[", "i", "]", ".", "ValidateOnPopulate", "=", "defField", ".", "ValidateOnPopulate", "\n", "self", ".", "Fields", "[", "i", "]", ".", "Validator", "=", "defField", ".", "Validator", "\n", "self", ".", "Fields", "[", "i", "]", ".", "Formatter", "=", "defField", ".", "Formatter", "\n", "}", "else", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "field", ".", "Name", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Copies certain collection and field properties from the definition object into this collection // instance. This is useful for collections that are created by parsing the schema as it exists on // the remote datastore, which will have some but not all of the information we need to work with the // data. Definition collections are the authoritative source for things like what the default value // should be, and which validators and formatters apply to a given field. // // This function converts this instance into a Collection definition by copying the relevant values // from given definition. //
[ "Copies", "certain", "collection", "and", "field", "properties", "from", "the", "definition", "object", "into", "this", "collection", "instance", ".", "This", "is", "useful", "for", "collections", "that", "are", "created", "by", "parsing", "the", "schema", "as", "it", "exists", "on", "the", "remote", "datastore", "which", "will", "have", "some", "but", "not", "all", "of", "the", "information", "we", "need", "to", "work", "with", "the", "data", ".", "Definition", "collections", "are", "the", "authoritative", "source", "for", "things", "like", "what", "the", "default", "value", "should", "be", "and", "which", "validators", "and", "formatters", "apply", "to", "a", "given", "field", ".", "This", "function", "converts", "this", "instance", "into", "a", "Collection", "definition", "by", "copying", "the", "relevant", "values", "from", "given", "definition", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/collection.go#L198-L247
17,365
ghetzel/pivot
dal/collection.go
GetField
func (self *Collection) GetField(name string) (Field, bool) { if name == self.GetIdentityFieldName() { return Field{ Name: name, Type: self.IdentityFieldType, Index: self.IdentityFieldIndex, Identity: true, Key: true, Required: true, }, true } else { for _, field := range self.Fields { if field.Name == name { return field, true } } } return Field{}, false }
go
func (self *Collection) GetField(name string) (Field, bool) { if name == self.GetIdentityFieldName() { return Field{ Name: name, Type: self.IdentityFieldType, Index: self.IdentityFieldIndex, Identity: true, Key: true, Required: true, }, true } else { for _, field := range self.Fields { if field.Name == name { return field, true } } } return Field{}, false }
[ "func", "(", "self", "*", "Collection", ")", "GetField", "(", "name", "string", ")", "(", "Field", ",", "bool", ")", "{", "if", "name", "==", "self", ".", "GetIdentityFieldName", "(", ")", "{", "return", "Field", "{", "Name", ":", "name", ",", "Type", ":", "self", ".", "IdentityFieldType", ",", "Index", ":", "self", ".", "IdentityFieldIndex", ",", "Identity", ":", "true", ",", "Key", ":", "true", ",", "Required", ":", "true", ",", "}", ",", "true", "\n", "}", "else", "{", "for", "_", ",", "field", ":=", "range", "self", ".", "Fields", "{", "if", "field", ".", "Name", "==", "name", "{", "return", "field", ",", "true", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "Field", "{", "}", ",", "false", "\n", "}" ]
// Retrieve a single field by name. The second return value will be false if the field does not // exist.
[ "Retrieve", "a", "single", "field", "by", "name", ".", "The", "second", "return", "value", "will", "be", "false", "if", "the", "field", "does", "not", "exist", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/collection.go#L371-L390
17,366
ghetzel/pivot
dal/collection.go
GetFieldByIndex
func (self *Collection) GetFieldByIndex(index int) (Field, bool) { if index == self.IdentityFieldIndex { return Field{ Name: self.GetIdentityFieldName(), Type: self.IdentityFieldType, Index: self.IdentityFieldIndex, Identity: true, Key: true, Required: true, }, true } else { for _, field := range self.Fields { if field.Index == index { return field, true } } } return Field{}, false }
go
func (self *Collection) GetFieldByIndex(index int) (Field, bool) { if index == self.IdentityFieldIndex { return Field{ Name: self.GetIdentityFieldName(), Type: self.IdentityFieldType, Index: self.IdentityFieldIndex, Identity: true, Key: true, Required: true, }, true } else { for _, field := range self.Fields { if field.Index == index { return field, true } } } return Field{}, false }
[ "func", "(", "self", "*", "Collection", ")", "GetFieldByIndex", "(", "index", "int", ")", "(", "Field", ",", "bool", ")", "{", "if", "index", "==", "self", ".", "IdentityFieldIndex", "{", "return", "Field", "{", "Name", ":", "self", ".", "GetIdentityFieldName", "(", ")", ",", "Type", ":", "self", ".", "IdentityFieldType", ",", "Index", ":", "self", ".", "IdentityFieldIndex", ",", "Identity", ":", "true", ",", "Key", ":", "true", ",", "Required", ":", "true", ",", "}", ",", "true", "\n", "}", "else", "{", "for", "_", ",", "field", ":=", "range", "self", ".", "Fields", "{", "if", "field", ".", "Index", "==", "index", "{", "return", "field", ",", "true", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "Field", "{", "}", ",", "false", "\n", "}" ]
// Retrieve a single field by its index value. The second return value will be false if a field // at that index does not exist.
[ "Retrieve", "a", "single", "field", "by", "its", "index", "value", ".", "The", "second", "return", "value", "will", "be", "false", "if", "a", "field", "at", "that", "index", "does", "not", "exist", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/collection.go#L394-L413
17,367
ghetzel/pivot
dal/collection.go
IsKeyField
func (self *Collection) IsKeyField(name string) bool { if field, ok := self.GetField(name); ok { return (field.Key && !field.Identity) } return false }
go
func (self *Collection) IsKeyField(name string) bool { if field, ok := self.GetField(name); ok { return (field.Key && !field.Identity) } return false }
[ "func", "(", "self", "*", "Collection", ")", "IsKeyField", "(", "name", "string", ")", "bool", "{", "if", "field", ",", "ok", ":=", "self", ".", "GetField", "(", "name", ")", ";", "ok", "{", "return", "(", "field", ".", "Key", "&&", "!", "field", ".", "Identity", ")", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// Return whether a given field name is a key on this Collection.
[ "Return", "whether", "a", "given", "field", "name", "is", "a", "key", "on", "this", "Collection", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/collection.go#L434-L440
17,368
ghetzel/pivot
dal/collection.go
KeyFields
func (self *Collection) KeyFields() []Field { keys := []Field{ Field{ Name: self.GetIdentityFieldName(), Type: self.IdentityFieldType, Identity: true, Key: true, Required: true, }, } // append additional key fields for _, field := range self.Fields { if field.Key { keys = append(keys, field) } } return keys }
go
func (self *Collection) KeyFields() []Field { keys := []Field{ Field{ Name: self.GetIdentityFieldName(), Type: self.IdentityFieldType, Identity: true, Key: true, Required: true, }, } // append additional key fields for _, field := range self.Fields { if field.Key { keys = append(keys, field) } } return keys }
[ "func", "(", "self", "*", "Collection", ")", "KeyFields", "(", ")", "[", "]", "Field", "{", "keys", ":=", "[", "]", "Field", "{", "Field", "{", "Name", ":", "self", ".", "GetIdentityFieldName", "(", ")", ",", "Type", ":", "self", ".", "IdentityFieldType", ",", "Identity", ":", "true", ",", "Key", ":", "true", ",", "Required", ":", "true", ",", "}", ",", "}", "\n\n", "// append additional key fields", "for", "_", ",", "field", ":=", "range", "self", ".", "Fields", "{", "if", "field", ".", "Key", "{", "keys", "=", "append", "(", "keys", ",", "field", ")", "\n", "}", "\n", "}", "\n\n", "return", "keys", "\n", "}" ]
// Retrieve all of the fields that comprise the primary key for this Collection. This will always include the identity // field at a minimum.
[ "Retrieve", "all", "of", "the", "fields", "that", "comprise", "the", "primary", "key", "for", "this", "Collection", ".", "This", "will", "always", "include", "the", "identity", "field", "at", "a", "minimum", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/collection.go#L444-L463
17,369
ghetzel/pivot
dal/collection.go
GetFirstNonIdentityKeyField
func (self *Collection) GetFirstNonIdentityKeyField() (Field, bool) { for _, field := range self.Fields { if field.Key && !field.Identity { return field, true } } return Field{}, false }
go
func (self *Collection) GetFirstNonIdentityKeyField() (Field, bool) { for _, field := range self.Fields { if field.Key && !field.Identity { return field, true } } return Field{}, false }
[ "func", "(", "self", "*", "Collection", ")", "GetFirstNonIdentityKeyField", "(", ")", "(", "Field", ",", "bool", ")", "{", "for", "_", ",", "field", ":=", "range", "self", ".", "Fields", "{", "if", "field", ".", "Key", "&&", "!", "field", ".", "Identity", "{", "return", "field", ",", "true", "\n", "}", "\n", "}", "\n\n", "return", "Field", "{", "}", ",", "false", "\n", "}" ]
// Retrieve the first non-indentity key field, sometimes referred to as the "range", "sort", or "cluster" key.
[ "Retrieve", "the", "first", "non", "-", "indentity", "key", "field", "sometimes", "referred", "to", "as", "the", "range", "sort", "or", "cluster", "key", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/collection.go#L471-L479
17,370
ghetzel/pivot
dal/collection.go
ConvertValue
func (self *Collection) ConvertValue(name string, value interface{}) interface{} { if field, ok := self.GetField(name); ok { if v, err := field.ConvertValue(value); err == nil { return v } } return value }
go
func (self *Collection) ConvertValue(name string, value interface{}) interface{} { if field, ok := self.GetField(name); ok { if v, err := field.ConvertValue(value); err == nil { return v } } return value }
[ "func", "(", "self", "*", "Collection", ")", "ConvertValue", "(", "name", "string", ",", "value", "interface", "{", "}", ")", "interface", "{", "}", "{", "if", "field", ",", "ok", ":=", "self", ".", "GetField", "(", "name", ")", ";", "ok", "{", "if", "v", ",", "err", ":=", "field", ".", "ConvertValue", "(", "value", ")", ";", "err", "==", "nil", "{", "return", "v", "\n", "}", "\n", "}", "\n\n", "return", "value", "\n", "}" ]
// Convert a given value according to the data type of a specific named field.
[ "Convert", "a", "given", "value", "according", "to", "the", "data", "type", "of", "a", "specific", "named", "field", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/collection.go#L482-L490
17,371
ghetzel/pivot
dal/collection.go
MapFromRecord
func (self *Collection) MapFromRecord(record *Record, fields ...string) (map[string]interface{}, error) { rv := make(map[string]interface{}) for _, field := range self.Fields { if len(fields) > 0 && !sliceutil.ContainsString(fields, field.Name) { continue } if dv := field.GetDefaultValue(); dv != nil { rv[field.Name] = dv } } if record != nil { if record.ID != nil { if id, err := self.formatAndValidateId(record.ID, RetrieveOperation, record); err == nil { rv[self.GetIdentityFieldName()] = id } else { return nil, err } } if len(self.Fields) > 0 { for _, field := range self.Fields { if v := record.Get(field.Name); v != nil { if len(fields) > 0 && !sliceutil.ContainsString(fields, field.Name) { continue } rv[field.Name] = v } } } else { for k, v := range record.Fields { rv[k] = v } } } return rv, nil }
go
func (self *Collection) MapFromRecord(record *Record, fields ...string) (map[string]interface{}, error) { rv := make(map[string]interface{}) for _, field := range self.Fields { if len(fields) > 0 && !sliceutil.ContainsString(fields, field.Name) { continue } if dv := field.GetDefaultValue(); dv != nil { rv[field.Name] = dv } } if record != nil { if record.ID != nil { if id, err := self.formatAndValidateId(record.ID, RetrieveOperation, record); err == nil { rv[self.GetIdentityFieldName()] = id } else { return nil, err } } if len(self.Fields) > 0 { for _, field := range self.Fields { if v := record.Get(field.Name); v != nil { if len(fields) > 0 && !sliceutil.ContainsString(fields, field.Name) { continue } rv[field.Name] = v } } } else { for k, v := range record.Fields { rv[k] = v } } } return rv, nil }
[ "func", "(", "self", "*", "Collection", ")", "MapFromRecord", "(", "record", "*", "Record", ",", "fields", "...", "string", ")", "(", "map", "[", "string", "]", "interface", "{", "}", ",", "error", ")", "{", "rv", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n\n", "for", "_", ",", "field", ":=", "range", "self", ".", "Fields", "{", "if", "len", "(", "fields", ")", ">", "0", "&&", "!", "sliceutil", ".", "ContainsString", "(", "fields", ",", "field", ".", "Name", ")", "{", "continue", "\n", "}", "\n\n", "if", "dv", ":=", "field", ".", "GetDefaultValue", "(", ")", ";", "dv", "!=", "nil", "{", "rv", "[", "field", ".", "Name", "]", "=", "dv", "\n", "}", "\n", "}", "\n\n", "if", "record", "!=", "nil", "{", "if", "record", ".", "ID", "!=", "nil", "{", "if", "id", ",", "err", ":=", "self", ".", "formatAndValidateId", "(", "record", ".", "ID", ",", "RetrieveOperation", ",", "record", ")", ";", "err", "==", "nil", "{", "rv", "[", "self", ".", "GetIdentityFieldName", "(", ")", "]", "=", "id", "\n", "}", "else", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "self", ".", "Fields", ")", ">", "0", "{", "for", "_", ",", "field", ":=", "range", "self", ".", "Fields", "{", "if", "v", ":=", "record", ".", "Get", "(", "field", ".", "Name", ")", ";", "v", "!=", "nil", "{", "if", "len", "(", "fields", ")", ">", "0", "&&", "!", "sliceutil", ".", "ContainsString", "(", "fields", ",", "field", ".", "Name", ")", "{", "continue", "\n", "}", "\n\n", "rv", "[", "field", ".", "Name", "]", "=", "v", "\n", "}", "\n", "}", "\n", "}", "else", "{", "for", "k", ",", "v", ":=", "range", "record", ".", "Fields", "{", "rv", "[", "k", "]", "=", "v", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "rv", ",", "nil", "\n", "}" ]
// Convert the given record into a map.
[ "Convert", "the", "given", "record", "into", "a", "map", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/collection.go#L690-L730
17,372
ghetzel/pivot
dal/collection.go
ValidateRecord
func (self *Collection) ValidateRecord(record *Record, op FieldOperation) error { switch op { case PersistOperation: // validate whole record (if specified) if self.PreSaveValidator != nil { if err := self.PreSaveValidator(record); err != nil { return err } } } return nil }
go
func (self *Collection) ValidateRecord(record *Record, op FieldOperation) error { switch op { case PersistOperation: // validate whole record (if specified) if self.PreSaveValidator != nil { if err := self.PreSaveValidator(record); err != nil { return err } } } return nil }
[ "func", "(", "self", "*", "Collection", ")", "ValidateRecord", "(", "record", "*", "Record", ",", "op", "FieldOperation", ")", "error", "{", "switch", "op", "{", "case", "PersistOperation", ":", "// validate whole record (if specified)", "if", "self", ".", "PreSaveValidator", "!=", "nil", "{", "if", "err", ":=", "self", ".", "PreSaveValidator", "(", "record", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Validate the given record against all Field and Collection validators.
[ "Validate", "the", "given", "record", "against", "all", "Field", "and", "Collection", "validators", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/collection.go#L733-L745
17,373
ghetzel/pivot
dal/collection.go
Check
func (self *Collection) Check() error { var merr error for i, field := range self.Fields { if field.Name == `` { merr = log.AppendError(merr, fmt.Errorf("collection[%s] field #%d cannot have an empty name", self.Name, i)) } if ParseFieldType(string(field.Type)) == `` { merr = log.AppendError(merr, fmt.Errorf("collection[%s] field[%s]: invalid type %q", self.Name, field.Name, field.Type)) } } return merr }
go
func (self *Collection) Check() error { var merr error for i, field := range self.Fields { if field.Name == `` { merr = log.AppendError(merr, fmt.Errorf("collection[%s] field #%d cannot have an empty name", self.Name, i)) } if ParseFieldType(string(field.Type)) == `` { merr = log.AppendError(merr, fmt.Errorf("collection[%s] field[%s]: invalid type %q", self.Name, field.Name, field.Type)) } } return merr }
[ "func", "(", "self", "*", "Collection", ")", "Check", "(", ")", "error", "{", "var", "merr", "error", "\n\n", "for", "i", ",", "field", ":=", "range", "self", ".", "Fields", "{", "if", "field", ".", "Name", "==", "``", "{", "merr", "=", "log", ".", "AppendError", "(", "merr", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "self", ".", "Name", ",", "i", ")", ")", "\n", "}", "\n\n", "if", "ParseFieldType", "(", "string", "(", "field", ".", "Type", ")", ")", "==", "``", "{", "merr", "=", "log", ".", "AppendError", "(", "merr", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "self", ".", "Name", ",", "field", ".", "Name", ",", "field", ".", "Type", ")", ")", "\n", "}", "\n", "}", "\n\n", "return", "merr", "\n", "}" ]
// Verifies that the schema passes some basic sanity checks.
[ "Verifies", "that", "the", "schema", "passes", "some", "basic", "sanity", "checks", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/collection.go#L748-L762
17,374
ghetzel/pivot
mapper/model.go
Get
func (self *Model) Get(id interface{}, into interface{}) error { if record, err := self.db.Retrieve(self.collection.Name, id); err == nil { return record.Populate(into, self.collection) } else { return err } }
go
func (self *Model) Get(id interface{}, into interface{}) error { if record, err := self.db.Retrieve(self.collection.Name, id); err == nil { return record.Populate(into, self.collection) } else { return err } }
[ "func", "(", "self", "*", "Model", ")", "Get", "(", "id", "interface", "{", "}", ",", "into", "interface", "{", "}", ")", "error", "{", "if", "record", ",", "err", ":=", "self", ".", "db", ".", "Retrieve", "(", "self", ".", "collection", ".", "Name", ",", "id", ")", ";", "err", "==", "nil", "{", "return", "record", ".", "Populate", "(", "into", ",", "self", ".", "collection", ")", "\n", "}", "else", "{", "return", "err", "\n", "}", "\n", "}" ]
// Retrieves an instance of the model identified by the given ID and populates the value pointed to // by the into parameter. Structs and dal.Record instances can be populated. //
[ "Retrieves", "an", "instance", "of", "the", "model", "identified", "by", "the", "given", "ID", "and", "populates", "the", "value", "pointed", "to", "by", "the", "into", "parameter", ".", "Structs", "and", "dal", ".", "Record", "instances", "can", "be", "populated", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/mapper/model.go#L123-L129
17,375
ghetzel/pivot
mapper/model.go
Exists
func (self *Model) Exists(id interface{}) bool { return self.db.Exists(self.collection.Name, id) }
go
func (self *Model) Exists(id interface{}) bool { return self.db.Exists(self.collection.Name, id) }
[ "func", "(", "self", "*", "Model", ")", "Exists", "(", "id", "interface", "{", "}", ")", "bool", "{", "return", "self", ".", "db", ".", "Exists", "(", "self", ".", "collection", ".", "Name", ",", "id", ")", "\n", "}" ]
// Tests whether a record exists for the given ID. //
[ "Tests", "whether", "a", "record", "exists", "for", "the", "given", "ID", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/mapper/model.go#L133-L135
17,376
ghetzel/pivot
mapper/model.go
Update
func (self *Model) Update(from interface{}) error { if record, err := self.collection.MakeRecord(from); err == nil { return self.db.Update(self.collection.Name, dal.NewRecordSet(record)) } else { return err } }
go
func (self *Model) Update(from interface{}) error { if record, err := self.collection.MakeRecord(from); err == nil { return self.db.Update(self.collection.Name, dal.NewRecordSet(record)) } else { return err } }
[ "func", "(", "self", "*", "Model", ")", "Update", "(", "from", "interface", "{", "}", ")", "error", "{", "if", "record", ",", "err", ":=", "self", ".", "collection", ".", "MakeRecord", "(", "from", ")", ";", "err", "==", "nil", "{", "return", "self", ".", "db", ".", "Update", "(", "self", ".", "collection", ".", "Name", ",", "dal", ".", "NewRecordSet", "(", "record", ")", ")", "\n", "}", "else", "{", "return", "err", "\n", "}", "\n", "}" ]
// Updates and saves an existing instance of the model from the given struct or dal.Record. //
[ "Updates", "and", "saves", "an", "existing", "instance", "of", "the", "model", "from", "the", "given", "struct", "or", "dal", ".", "Record", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/mapper/model.go#L139-L145
17,377
ghetzel/pivot
mapper/model.go
CreateOrUpdate
func (self *Model) CreateOrUpdate(id interface{}, from interface{}) error { if id == nil || !self.Exists(id) { return self.Create(from) } else { return self.Update(from) } }
go
func (self *Model) CreateOrUpdate(id interface{}, from interface{}) error { if id == nil || !self.Exists(id) { return self.Create(from) } else { return self.Update(from) } }
[ "func", "(", "self", "*", "Model", ")", "CreateOrUpdate", "(", "id", "interface", "{", "}", ",", "from", "interface", "{", "}", ")", "error", "{", "if", "id", "==", "nil", "||", "!", "self", ".", "Exists", "(", "id", ")", "{", "return", "self", ".", "Create", "(", "from", ")", "\n", "}", "else", "{", "return", "self", ".", "Update", "(", "from", ")", "\n", "}", "\n", "}" ]
// Creates or updates an instance of the model depending on whether it exists or not. //
[ "Creates", "or", "updates", "an", "instance", "of", "the", "model", "depending", "on", "whether", "it", "exists", "or", "not", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/mapper/model.go#L149-L155
17,378
ghetzel/pivot
mapper/model.go
Delete
func (self *Model) Delete(ids ...interface{}) error { return self.db.Delete(self.collection.Name, ids...) }
go
func (self *Model) Delete(ids ...interface{}) error { return self.db.Delete(self.collection.Name, ids...) }
[ "func", "(", "self", "*", "Model", ")", "Delete", "(", "ids", "...", "interface", "{", "}", ")", "error", "{", "return", "self", ".", "db", ".", "Delete", "(", "self", ".", "collection", ".", "Name", ",", "ids", "...", ")", "\n", "}" ]
// Delete instances of the model identified by the given IDs //
[ "Delete", "instances", "of", "the", "model", "identified", "by", "the", "given", "IDs" ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/mapper/model.go#L159-L161
17,379
ghetzel/pivot
mapper/model.go
DeleteQuery
func (self *Model) DeleteQuery(flt interface{}) error { if f, err := self.filterFromInterface(flt); err == nil { f.IdentityField = self.collection.IdentityField if search := self.db.WithSearch(self.collection, f); search != nil { return search.DeleteQuery(self.collection, f) } else { return fmt.Errorf("backend %T does not support searching", self.db) } } else { return err } }
go
func (self *Model) DeleteQuery(flt interface{}) error { if f, err := self.filterFromInterface(flt); err == nil { f.IdentityField = self.collection.IdentityField if search := self.db.WithSearch(self.collection, f); search != nil { return search.DeleteQuery(self.collection, f) } else { return fmt.Errorf("backend %T does not support searching", self.db) } } else { return err } }
[ "func", "(", "self", "*", "Model", ")", "DeleteQuery", "(", "flt", "interface", "{", "}", ")", "error", "{", "if", "f", ",", "err", ":=", "self", ".", "filterFromInterface", "(", "flt", ")", ";", "err", "==", "nil", "{", "f", ".", "IdentityField", "=", "self", ".", "collection", ".", "IdentityField", "\n\n", "if", "search", ":=", "self", ".", "db", ".", "WithSearch", "(", "self", ".", "collection", ",", "f", ")", ";", "search", "!=", "nil", "{", "return", "search", ".", "DeleteQuery", "(", "self", ".", "collection", ",", "f", ")", "\n", "}", "else", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "self", ".", "db", ")", "\n", "}", "\n", "}", "else", "{", "return", "err", "\n", "}", "\n", "}" ]
// Delete all records matching the given query.
[ "Delete", "all", "records", "matching", "the", "given", "query", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/mapper/model.go#L164-L176
17,380
ghetzel/pivot
mapper/model.go
Find
func (self *Model) Find(flt interface{}, into interface{}) error { if f, err := self.filterFromInterface(flt); err == nil { f.IdentityField = self.collection.IdentityField if search := self.db.WithSearch(self.collection, f); search != nil { // perform query if recordset, err := search.Query(self.collection, f); err == nil { return self.populateOutputParameter(f, recordset, into) } else { return err } } else { return fmt.Errorf("backend %T does not support searching", self.db) } } else { return err } }
go
func (self *Model) Find(flt interface{}, into interface{}) error { if f, err := self.filterFromInterface(flt); err == nil { f.IdentityField = self.collection.IdentityField if search := self.db.WithSearch(self.collection, f); search != nil { // perform query if recordset, err := search.Query(self.collection, f); err == nil { return self.populateOutputParameter(f, recordset, into) } else { return err } } else { return fmt.Errorf("backend %T does not support searching", self.db) } } else { return err } }
[ "func", "(", "self", "*", "Model", ")", "Find", "(", "flt", "interface", "{", "}", ",", "into", "interface", "{", "}", ")", "error", "{", "if", "f", ",", "err", ":=", "self", ".", "filterFromInterface", "(", "flt", ")", ";", "err", "==", "nil", "{", "f", ".", "IdentityField", "=", "self", ".", "collection", ".", "IdentityField", "\n\n", "if", "search", ":=", "self", ".", "db", ".", "WithSearch", "(", "self", ".", "collection", ",", "f", ")", ";", "search", "!=", "nil", "{", "// perform query", "if", "recordset", ",", "err", ":=", "search", ".", "Query", "(", "self", ".", "collection", ",", "f", ")", ";", "err", "==", "nil", "{", "return", "self", ".", "populateOutputParameter", "(", "f", ",", "recordset", ",", "into", ")", "\n", "}", "else", "{", "return", "err", "\n", "}", "\n", "}", "else", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "self", ".", "db", ")", "\n", "}", "\n", "}", "else", "{", "return", "err", "\n", "}", "\n", "}" ]
// Perform a query for instances of the model that match the given filter.Filter. // Results will be returned in the slice or array pointed to by the into parameter, or // if into points to a dal.RecordSet, the RecordSet resulting from the query will be returned // as-is. //
[ "Perform", "a", "query", "for", "instances", "of", "the", "model", "that", "match", "the", "given", "filter", ".", "Filter", ".", "Results", "will", "be", "returned", "in", "the", "slice", "or", "array", "pointed", "to", "by", "the", "into", "parameter", "or", "if", "into", "points", "to", "a", "dal", ".", "RecordSet", "the", "RecordSet", "resulting", "from", "the", "query", "will", "be", "returned", "as", "-", "is", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/mapper/model.go#L183-L200
17,381
ghetzel/pivot
mapper/model.go
FindFunc
func (self *Model) FindFunc(flt interface{}, destZeroValue interface{}, resultFn ResultFunc) error { if f, err := self.filterFromInterface(flt); err == nil { f.IdentityField = self.collection.IdentityField if search := self.db.WithSearch(self.collection, f); search != nil { _, err := search.Query(self.collection, f, func(record *dal.Record, err error, _ backends.IndexPage) error { if err == nil { if _, ok := destZeroValue.(*dal.Record); ok { resultFn(record, nil) } else if _, ok := destZeroValue.(dal.Record); ok { resultFn(*record, nil) } else { into := reflect.New(reflect.TypeOf(destZeroValue)).Interface() // populate that type with data from this record if err := record.Populate(into, self.collection); err == nil { resultFn(into, nil) } else { return err } } } else { resultFn(nil, err) } return nil }) return err } else { return fmt.Errorf("backend %T does not support searching", self.db) } } else { return err } }
go
func (self *Model) FindFunc(flt interface{}, destZeroValue interface{}, resultFn ResultFunc) error { if f, err := self.filterFromInterface(flt); err == nil { f.IdentityField = self.collection.IdentityField if search := self.db.WithSearch(self.collection, f); search != nil { _, err := search.Query(self.collection, f, func(record *dal.Record, err error, _ backends.IndexPage) error { if err == nil { if _, ok := destZeroValue.(*dal.Record); ok { resultFn(record, nil) } else if _, ok := destZeroValue.(dal.Record); ok { resultFn(*record, nil) } else { into := reflect.New(reflect.TypeOf(destZeroValue)).Interface() // populate that type with data from this record if err := record.Populate(into, self.collection); err == nil { resultFn(into, nil) } else { return err } } } else { resultFn(nil, err) } return nil }) return err } else { return fmt.Errorf("backend %T does not support searching", self.db) } } else { return err } }
[ "func", "(", "self", "*", "Model", ")", "FindFunc", "(", "flt", "interface", "{", "}", ",", "destZeroValue", "interface", "{", "}", ",", "resultFn", "ResultFunc", ")", "error", "{", "if", "f", ",", "err", ":=", "self", ".", "filterFromInterface", "(", "flt", ")", ";", "err", "==", "nil", "{", "f", ".", "IdentityField", "=", "self", ".", "collection", ".", "IdentityField", "\n\n", "if", "search", ":=", "self", ".", "db", ".", "WithSearch", "(", "self", ".", "collection", ",", "f", ")", ";", "search", "!=", "nil", "{", "_", ",", "err", ":=", "search", ".", "Query", "(", "self", ".", "collection", ",", "f", ",", "func", "(", "record", "*", "dal", ".", "Record", ",", "err", "error", ",", "_", "backends", ".", "IndexPage", ")", "error", "{", "if", "err", "==", "nil", "{", "if", "_", ",", "ok", ":=", "destZeroValue", ".", "(", "*", "dal", ".", "Record", ")", ";", "ok", "{", "resultFn", "(", "record", ",", "nil", ")", "\n", "}", "else", "if", "_", ",", "ok", ":=", "destZeroValue", ".", "(", "dal", ".", "Record", ")", ";", "ok", "{", "resultFn", "(", "*", "record", ",", "nil", ")", "\n", "}", "else", "{", "into", ":=", "reflect", ".", "New", "(", "reflect", ".", "TypeOf", "(", "destZeroValue", ")", ")", ".", "Interface", "(", ")", "\n\n", "// populate that type with data from this record", "if", "err", ":=", "record", ".", "Populate", "(", "into", ",", "self", ".", "collection", ")", ";", "err", "==", "nil", "{", "resultFn", "(", "into", ",", "nil", ")", "\n", "}", "else", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "else", "{", "resultFn", "(", "nil", ",", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}", ")", "\n\n", "return", "err", "\n", "}", "else", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "self", ".", "db", ")", "\n", "}", "\n", "}", "else", "{", "return", "err", "\n", "}", "\n", "}" ]
// Perform a query for instances of the model that match the given filter.Filter. // The given callback function will be called once per result. //
[ "Perform", "a", "query", "for", "instances", "of", "the", "model", "that", "match", "the", "given", "filter", ".", "Filter", ".", "The", "given", "callback", "function", "will", "be", "called", "once", "per", "result", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/mapper/model.go#L205-L240
17,382
ghetzel/pivot
dal/formatters.go
GenerateUUID
func GenerateUUID(value interface{}, _ FieldOperation) (interface{}, error) { if record, ok := value.(*Record); ok { value = record.ID } if typeutil.IsZero(value) { value = stringutil.UUID().String() } return value, nil }
go
func GenerateUUID(value interface{}, _ FieldOperation) (interface{}, error) { if record, ok := value.(*Record); ok { value = record.ID } if typeutil.IsZero(value) { value = stringutil.UUID().String() } return value, nil }
[ "func", "GenerateUUID", "(", "value", "interface", "{", "}", ",", "_", "FieldOperation", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "record", ",", "ok", ":=", "value", ".", "(", "*", "Record", ")", ";", "ok", "{", "value", "=", "record", ".", "ID", "\n", "}", "\n\n", "if", "typeutil", ".", "IsZero", "(", "value", ")", "{", "value", "=", "stringutil", ".", "UUID", "(", ")", ".", "String", "(", ")", "\n", "}", "\n\n", "return", "value", ",", "nil", "\n", "}" ]
// Generates a V4 UUID value if the existing value is empty.
[ "Generates", "a", "V4", "UUID", "value", "if", "the", "existing", "value", "is", "empty", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/formatters.go#L191-L201
17,383
ghetzel/pivot
dal/formatters.go
GenerateEncodedUUID
func GenerateEncodedUUID(encoder EncoderFunc) FieldFormatterFunc { return func(value interface{}, _ FieldOperation) (interface{}, error) { if record, ok := value.(*Record); ok { value = record.ID } if typeutil.IsZero(value) { if v, err := encoder(stringutil.UUID().Bytes()); err == nil { if typeutil.IsZero(v) { return value, fmt.Errorf("UUID encoder produced a zero-length result") } value = v } else { return value, err } } return value, nil } }
go
func GenerateEncodedUUID(encoder EncoderFunc) FieldFormatterFunc { return func(value interface{}, _ FieldOperation) (interface{}, error) { if record, ok := value.(*Record); ok { value = record.ID } if typeutil.IsZero(value) { if v, err := encoder(stringutil.UUID().Bytes()); err == nil { if typeutil.IsZero(v) { return value, fmt.Errorf("UUID encoder produced a zero-length result") } value = v } else { return value, err } } return value, nil } }
[ "func", "GenerateEncodedUUID", "(", "encoder", "EncoderFunc", ")", "FieldFormatterFunc", "{", "return", "func", "(", "value", "interface", "{", "}", ",", "_", "FieldOperation", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "record", ",", "ok", ":=", "value", ".", "(", "*", "Record", ")", ";", "ok", "{", "value", "=", "record", ".", "ID", "\n", "}", "\n\n", "if", "typeutil", ".", "IsZero", "(", "value", ")", "{", "if", "v", ",", "err", ":=", "encoder", "(", "stringutil", ".", "UUID", "(", ")", ".", "Bytes", "(", ")", ")", ";", "err", "==", "nil", "{", "if", "typeutil", ".", "IsZero", "(", "v", ")", "{", "return", "value", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "value", "=", "v", "\n", "}", "else", "{", "return", "value", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "value", ",", "nil", "\n", "}", "\n", "}" ]
// Same as GenerateUUID, but allows for a custom representation of the underlying bytes.
[ "Same", "as", "GenerateUUID", "but", "allows", "for", "a", "custom", "representation", "of", "the", "underlying", "bytes", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/formatters.go#L204-L224
17,384
ghetzel/pivot
dal/formatters.go
IfUnset
func IfUnset(onlyIf FieldFormatterFunc) FieldFormatterFunc { return func(value interface{}, op FieldOperation) (interface{}, error) { if onlyIf != nil { if typeutil.IsZero(value) { return onlyIf(value, op) } } return value, nil } }
go
func IfUnset(onlyIf FieldFormatterFunc) FieldFormatterFunc { return func(value interface{}, op FieldOperation) (interface{}, error) { if onlyIf != nil { if typeutil.IsZero(value) { return onlyIf(value, op) } } return value, nil } }
[ "func", "IfUnset", "(", "onlyIf", "FieldFormatterFunc", ")", "FieldFormatterFunc", "{", "return", "func", "(", "value", "interface", "{", "}", ",", "op", "FieldOperation", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "onlyIf", "!=", "nil", "{", "if", "typeutil", ".", "IsZero", "(", "value", ")", "{", "return", "onlyIf", "(", "value", ",", "op", ")", "\n", "}", "\n", "}", "\n\n", "return", "value", ",", "nil", "\n", "}", "\n", "}" ]
// Only evaluates the given formatter if the current value of the field is empty.
[ "Only", "evaluates", "the", "given", "formatter", "if", "the", "current", "value", "of", "the", "field", "is", "empty", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/formatters.go#L227-L237
17,385
ghetzel/pivot
dal/formatters.go
DeriveFromFields
func DeriveFromFields(format string, fields ...string) FieldFormatterFunc { return func(input interface{}, _ FieldOperation) (interface{}, error) { if record, ok := input.(*Record); ok { values := make([]interface{}, len(fields)) for i, field := range fields { values[i] = record.Get(field) } return fmt.Sprintf(format, values...), nil } else { return nil, fmt.Errorf("DeriveFromFields formatter requires a *dal.Record argument, got %T", input) } } }
go
func DeriveFromFields(format string, fields ...string) FieldFormatterFunc { return func(input interface{}, _ FieldOperation) (interface{}, error) { if record, ok := input.(*Record); ok { values := make([]interface{}, len(fields)) for i, field := range fields { values[i] = record.Get(field) } return fmt.Sprintf(format, values...), nil } else { return nil, fmt.Errorf("DeriveFromFields formatter requires a *dal.Record argument, got %T", input) } } }
[ "func", "DeriveFromFields", "(", "format", "string", ",", "fields", "...", "string", ")", "FieldFormatterFunc", "{", "return", "func", "(", "input", "interface", "{", "}", ",", "_", "FieldOperation", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "record", ",", "ok", ":=", "input", ".", "(", "*", "Record", ")", ";", "ok", "{", "values", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "len", "(", "fields", ")", ")", "\n\n", "for", "i", ",", "field", ":=", "range", "fields", "{", "values", "[", "i", "]", "=", "record", ".", "Get", "(", "field", ")", "\n", "}", "\n\n", "return", "fmt", ".", "Sprintf", "(", "format", ",", "values", "...", ")", ",", "nil", "\n", "}", "else", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "input", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Extracts values from the given Record and generates a deterministic output based on those values.
[ "Extracts", "values", "from", "the", "given", "Record", "and", "generates", "a", "deterministic", "output", "based", "on", "those", "values", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/formatters.go#L240-L254
17,386
ghetzel/pivot
dal/formatters.go
CurrentTime
func CurrentTime(value interface{}, op FieldOperation) (interface{}, error) { if op == PersistOperation { return time.Now(), nil } else { return value, nil } }
go
func CurrentTime(value interface{}, op FieldOperation) (interface{}, error) { if op == PersistOperation { return time.Now(), nil } else { return value, nil } }
[ "func", "CurrentTime", "(", "value", "interface", "{", "}", ",", "op", "FieldOperation", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "op", "==", "PersistOperation", "{", "return", "time", ".", "Now", "(", ")", ",", "nil", "\n", "}", "else", "{", "return", "value", ",", "nil", "\n", "}", "\n", "}" ]
// Returns the current time every time the field is persisted.
[ "Returns", "the", "current", "time", "every", "time", "the", "field", "is", "persisted", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/formatters.go#L257-L263
17,387
ghetzel/pivot
dal/formatters.go
CurrentTimeIfUnset
func CurrentTimeIfUnset(value interface{}, op FieldOperation) (interface{}, error) { return IfUnset(func(v interface{}, o FieldOperation) (interface{}, error) { if o == PersistOperation { return time.Now(), nil } else { return v, nil } })(value, op) }
go
func CurrentTimeIfUnset(value interface{}, op FieldOperation) (interface{}, error) { return IfUnset(func(v interface{}, o FieldOperation) (interface{}, error) { if o == PersistOperation { return time.Now(), nil } else { return v, nil } })(value, op) }
[ "func", "CurrentTimeIfUnset", "(", "value", "interface", "{", "}", ",", "op", "FieldOperation", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "return", "IfUnset", "(", "func", "(", "v", "interface", "{", "}", ",", "o", "FieldOperation", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "o", "==", "PersistOperation", "{", "return", "time", ".", "Now", "(", ")", ",", "nil", "\n", "}", "else", "{", "return", "v", ",", "nil", "\n", "}", "\n", "}", ")", "(", "value", ",", "op", ")", "\n", "}" ]
// Returns the current time when the field is persisted if the current value is empty.
[ "Returns", "the", "current", "time", "when", "the", "field", "is", "persisted", "if", "the", "current", "value", "is", "empty", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/formatters.go#L266-L274
17,388
ghetzel/pivot
dal/formatters.go
NowPlusDuration
func NowPlusDuration(duration time.Duration) FieldFormatterFunc { return func(value interface{}, op FieldOperation) (interface{}, error) { if op == PersistOperation { if duration != 0 { return time.Now().Add(duration), nil } } return value, nil } }
go
func NowPlusDuration(duration time.Duration) FieldFormatterFunc { return func(value interface{}, op FieldOperation) (interface{}, error) { if op == PersistOperation { if duration != 0 { return time.Now().Add(duration), nil } } return value, nil } }
[ "func", "NowPlusDuration", "(", "duration", "time", ".", "Duration", ")", "FieldFormatterFunc", "{", "return", "func", "(", "value", "interface", "{", "}", ",", "op", "FieldOperation", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "op", "==", "PersistOperation", "{", "if", "duration", "!=", "0", "{", "return", "time", ".", "Now", "(", ")", ".", "Add", "(", "duration", ")", ",", "nil", "\n", "}", "\n", "}", "\n\n", "return", "value", ",", "nil", "\n", "}", "\n", "}" ]
// Returns the current time with an added offset when the field is persisted.
[ "Returns", "the", "current", "time", "with", "an", "added", "offset", "when", "the", "field", "is", "persisted", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/formatters.go#L277-L287
17,389
ghetzel/pivot
dal/validators.go
ValidateMatchAll
func ValidateMatchAll(patterns ...string) FieldValidatorFunc { prx := make([]*regexp.Regexp, len(patterns)) for i, rxs := range patterns { prx[i] = regexp.MustCompile(rxs) } return func(value interface{}) error { for _, rx := range prx { if !rx.MatchString(typeutil.String(value)) { return fmt.Errorf("Value does not match pattern %q", rx.String()) } } return nil } }
go
func ValidateMatchAll(patterns ...string) FieldValidatorFunc { prx := make([]*regexp.Regexp, len(patterns)) for i, rxs := range patterns { prx[i] = regexp.MustCompile(rxs) } return func(value interface{}) error { for _, rx := range prx { if !rx.MatchString(typeutil.String(value)) { return fmt.Errorf("Value does not match pattern %q", rx.String()) } } return nil } }
[ "func", "ValidateMatchAll", "(", "patterns", "...", "string", ")", "FieldValidatorFunc", "{", "prx", ":=", "make", "(", "[", "]", "*", "regexp", ".", "Regexp", ",", "len", "(", "patterns", ")", ")", "\n\n", "for", "i", ",", "rxs", ":=", "range", "patterns", "{", "prx", "[", "i", "]", "=", "regexp", ".", "MustCompile", "(", "rxs", ")", "\n", "}", "\n\n", "return", "func", "(", "value", "interface", "{", "}", ")", "error", "{", "for", "_", ",", "rx", ":=", "range", "prx", "{", "if", "!", "rx", ".", "MatchString", "(", "typeutil", ".", "String", "(", "value", ")", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "rx", ".", "String", "(", ")", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}", "\n", "}" ]
// Validate that the given value matches all of the given regular expressions.
[ "Validate", "that", "the", "given", "value", "matches", "all", "of", "the", "given", "regular", "expressions", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/validators.go#L73-L89
17,390
ghetzel/pivot
dal/validators.go
ValidateAll
func ValidateAll(validators ...FieldValidatorFunc) FieldValidatorFunc { return func(value interface{}) error { for _, validator := range validators { if err := validator(value); err != nil { return err } } return nil } }
go
func ValidateAll(validators ...FieldValidatorFunc) FieldValidatorFunc { return func(value interface{}) error { for _, validator := range validators { if err := validator(value); err != nil { return err } } return nil } }
[ "func", "ValidateAll", "(", "validators", "...", "FieldValidatorFunc", ")", "FieldValidatorFunc", "{", "return", "func", "(", "value", "interface", "{", "}", ")", "error", "{", "for", "_", ",", "validator", ":=", "range", "validators", "{", "if", "err", ":=", "validator", "(", "value", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}", "\n", "}" ]
// Validate that all of the given validator functions pass.
[ "Validate", "that", "all", "of", "the", "given", "validator", "functions", "pass", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/validators.go#L111-L121
17,391
ghetzel/pivot
dal/validators.go
ValidateIsOneOf
func ValidateIsOneOf(choices ...interface{}) FieldValidatorFunc { return func(value interface{}) error { for _, choice := range choices { if ok, err := stringutil.RelaxedEqual(choice, value); err == nil && ok { return nil } } return fmt.Errorf("value must be one of: %+v", choices) } }
go
func ValidateIsOneOf(choices ...interface{}) FieldValidatorFunc { return func(value interface{}) error { for _, choice := range choices { if ok, err := stringutil.RelaxedEqual(choice, value); err == nil && ok { return nil } } return fmt.Errorf("value must be one of: %+v", choices) } }
[ "func", "ValidateIsOneOf", "(", "choices", "...", "interface", "{", "}", ")", "FieldValidatorFunc", "{", "return", "func", "(", "value", "interface", "{", "}", ")", "error", "{", "for", "_", ",", "choice", ":=", "range", "choices", "{", "if", "ok", ",", "err", ":=", "stringutil", ".", "RelaxedEqual", "(", "choice", ",", "value", ")", ";", "err", "==", "nil", "&&", "ok", "{", "return", "nil", "\n", "}", "\n", "}", "\n\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "choices", ")", "\n", "}", "\n", "}" ]
// Validate that the given value is among the given choices.
[ "Validate", "that", "the", "given", "value", "is", "among", "the", "given", "choices", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/validators.go#L124-L134
17,392
ghetzel/pivot
dal/validators.go
ValidateNotEmpty
func ValidateNotEmpty(value interface{}) error { if typeutil.IsEmpty(value) { return fmt.Errorf("expected non-empty value, got: %v", value) } return nil }
go
func ValidateNotEmpty(value interface{}) error { if typeutil.IsEmpty(value) { return fmt.Errorf("expected non-empty value, got: %v", value) } return nil }
[ "func", "ValidateNotEmpty", "(", "value", "interface", "{", "}", ")", "error", "{", "if", "typeutil", ".", "IsEmpty", "(", "value", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "value", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Validate that the given value is not a zero value, and if it's a string, that the string // does not contain only whitespace.
[ "Validate", "that", "the", "given", "value", "is", "not", "a", "zero", "value", "and", "if", "it", "s", "a", "string", "that", "the", "string", "does", "not", "contain", "only", "whitespace", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/validators.go#L147-L153
17,393
ghetzel/pivot
dal/validators.go
ValidatePositiveInteger
func ValidatePositiveInteger(value interface{}) error { if v, err := stringutil.ConvertToInteger(value); err == nil { if v <= 0 { return fmt.Errorf("expected value > 0, got: %v", v) } } else { return err } return nil }
go
func ValidatePositiveInteger(value interface{}) error { if v, err := stringutil.ConvertToInteger(value); err == nil { if v <= 0 { return fmt.Errorf("expected value > 0, got: %v", v) } } else { return err } return nil }
[ "func", "ValidatePositiveInteger", "(", "value", "interface", "{", "}", ")", "error", "{", "if", "v", ",", "err", ":=", "stringutil", ".", "ConvertToInteger", "(", "value", ")", ";", "err", "==", "nil", "{", "if", "v", "<=", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "v", ")", "\n", "}", "\n", "}", "else", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Validate that the given value is an integer > 0.
[ "Validate", "that", "the", "given", "value", "is", "an", "integer", ">", "0", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/validators.go#L156-L166
17,394
ghetzel/pivot
dal/validators.go
ValidateIsURL
func ValidateIsURL(value interface{}) error { if u, err := url.Parse(typeutil.String(value)); err == nil { if u.Scheme == `` || u.Host == `` || u.Path == `` { return fmt.Errorf("Invalid URL") } } else { return err } return nil }
go
func ValidateIsURL(value interface{}) error { if u, err := url.Parse(typeutil.String(value)); err == nil { if u.Scheme == `` || u.Host == `` || u.Path == `` { return fmt.Errorf("Invalid URL") } } else { return err } return nil }
[ "func", "ValidateIsURL", "(", "value", "interface", "{", "}", ")", "error", "{", "if", "u", ",", "err", ":=", "url", ".", "Parse", "(", "typeutil", ".", "String", "(", "value", ")", ")", ";", "err", "==", "nil", "{", "if", "u", ".", "Scheme", "==", "``", "||", "u", ".", "Host", "==", "``", "||", "u", ".", "Path", "==", "``", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "else", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Validate that the value is a URL with a non-empty scheme and host component.
[ "Validate", "that", "the", "value", "is", "a", "URL", "with", "a", "non", "-", "empty", "scheme", "and", "host", "component", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/validators.go#L182-L192
17,395
ghetzel/pivot
backends/redis.go
run
func (self *RedisBackend) run(cmd string, args ...interface{}) (interface{}, error) { if conn := self.pool.Get(); conn != nil { defer conn.Close() // debug := strings.Join(sliceutil.Stringify(args), ` `) // querylog.Debugf("[%v] %v %v", self, cmd, debug) return redis.DoWithTimeout(conn, self.cmdTimeout, cmd, args...) } else { return nil, fmt.Errorf("Failed to borrow Redis connection") } }
go
func (self *RedisBackend) run(cmd string, args ...interface{}) (interface{}, error) { if conn := self.pool.Get(); conn != nil { defer conn.Close() // debug := strings.Join(sliceutil.Stringify(args), ` `) // querylog.Debugf("[%v] %v %v", self, cmd, debug) return redis.DoWithTimeout(conn, self.cmdTimeout, cmd, args...) } else { return nil, fmt.Errorf("Failed to borrow Redis connection") } }
[ "func", "(", "self", "*", "RedisBackend", ")", "run", "(", "cmd", "string", ",", "args", "...", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "conn", ":=", "self", ".", "pool", ".", "Get", "(", ")", ";", "conn", "!=", "nil", "{", "defer", "conn", ".", "Close", "(", ")", "\n\n", "// debug := strings.Join(sliceutil.Stringify(args), ` `)", "// querylog.Debugf(\"[%v] %v %v\", self, cmd, debug)", "return", "redis", ".", "DoWithTimeout", "(", "conn", ",", "self", ".", "cmdTimeout", ",", "cmd", ",", "args", "...", ")", "\n", "}", "else", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// wraps the process of borrowing a connection from the pool and running a command
[ "wraps", "the", "process", "of", "borrowing", "a", "connection", "from", "the", "pool", "and", "running", "a", "command" ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/backends/redis.go#L461-L471
17,396
ghetzel/pivot
backends/sql-indexer.go
DeleteQuery
func (self *SqlBackend) DeleteQuery(collection *dal.Collection, f *filter.Filter) error { if tx, err := self.db.Begin(); err == nil { queryGen := self.makeQueryGen(collection) queryGen.Type = generators.SqlDeleteStatement // generate SQL if stmt, err := filter.Render(queryGen, collection.Name, f); err == nil { querylog.Debugf("[%v] %s %v", self, string(stmt[:]), queryGen.GetValues()) // execute SQL if _, err := tx.Exec(string(stmt[:]), queryGen.GetValues()...); err == nil { if err := tx.Commit(); err == nil { return nil } else { return err } } else { defer tx.Rollback() return err } } else { defer tx.Rollback() return err } } else { return err } }
go
func (self *SqlBackend) DeleteQuery(collection *dal.Collection, f *filter.Filter) error { if tx, err := self.db.Begin(); err == nil { queryGen := self.makeQueryGen(collection) queryGen.Type = generators.SqlDeleteStatement // generate SQL if stmt, err := filter.Render(queryGen, collection.Name, f); err == nil { querylog.Debugf("[%v] %s %v", self, string(stmt[:]), queryGen.GetValues()) // execute SQL if _, err := tx.Exec(string(stmt[:]), queryGen.GetValues()...); err == nil { if err := tx.Commit(); err == nil { return nil } else { return err } } else { defer tx.Rollback() return err } } else { defer tx.Rollback() return err } } else { return err } }
[ "func", "(", "self", "*", "SqlBackend", ")", "DeleteQuery", "(", "collection", "*", "dal", ".", "Collection", ",", "f", "*", "filter", ".", "Filter", ")", "error", "{", "if", "tx", ",", "err", ":=", "self", ".", "db", ".", "Begin", "(", ")", ";", "err", "==", "nil", "{", "queryGen", ":=", "self", ".", "makeQueryGen", "(", "collection", ")", "\n", "queryGen", ".", "Type", "=", "generators", ".", "SqlDeleteStatement", "\n\n", "// generate SQL", "if", "stmt", ",", "err", ":=", "filter", ".", "Render", "(", "queryGen", ",", "collection", ".", "Name", ",", "f", ")", ";", "err", "==", "nil", "{", "querylog", ".", "Debugf", "(", "\"", "\"", ",", "self", ",", "string", "(", "stmt", "[", ":", "]", ")", ",", "queryGen", ".", "GetValues", "(", ")", ")", "\n\n", "// execute SQL", "if", "_", ",", "err", ":=", "tx", ".", "Exec", "(", "string", "(", "stmt", "[", ":", "]", ")", ",", "queryGen", ".", "GetValues", "(", ")", "...", ")", ";", "err", "==", "nil", "{", "if", "err", ":=", "tx", ".", "Commit", "(", ")", ";", "err", "==", "nil", "{", "return", "nil", "\n", "}", "else", "{", "return", "err", "\n", "}", "\n", "}", "else", "{", "defer", "tx", ".", "Rollback", "(", ")", "\n", "return", "err", "\n", "}", "\n", "}", "else", "{", "defer", "tx", ".", "Rollback", "(", ")", "\n", "return", "err", "\n", "}", "\n", "}", "else", "{", "return", "err", "\n", "}", "\n", "}" ]
// DeleteQuery removes records using a filter
[ "DeleteQuery", "removes", "records", "using", "a", "filter" ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/backends/sql-indexer.go#L240-L267
17,397
ghetzel/pivot
dal/recordset.go
PopulateFromRecords
func (self *RecordSet) PopulateFromRecords(into interface{}, schema *Collection) error { vInto := reflect.ValueOf(into) // get value pointed to if we were given a pointer if vInto.Kind() == reflect.Ptr { vInto = vInto.Elem() } else { return fmt.Errorf("Output argument must be a pointer") } // we're going to fill arrays or slices switch vInto.Type().Kind() { case reflect.Array, reflect.Slice: indirectResult := true // get the type of the underlying slice element sliceType := vInto.Type().Elem() // get the type pointed to if sliceType.Kind() == reflect.Ptr { sliceType = sliceType.Elem() indirectResult = false } // for each resulting record... for _, record := range self.Records { // make a new zero-valued instance of the slice type elem := reflect.New(sliceType) // if we have a registered collection, use its if schema != nil && schema.HasRecordType() { elem = reflect.ValueOf(schema.NewInstance()) } // populate that type with data from this record if err := record.Populate(elem.Interface(), schema); err == nil { // if the slice elements are pointers, we can append the pointer we just created as-is // otherwise, we need to indirect the value and append a copy if indirectResult { vInto.Set(reflect.Append(vInto, reflect.Indirect(elem))) } else { vInto.Set(reflect.Append(vInto, elem)) } } else { return err } } return nil case reflect.Struct: if rs, ok := into.(*RecordSet); ok { *rs = *self return nil } } return fmt.Errorf("RecordSet can only populate records into slice or array, got %T", into) }
go
func (self *RecordSet) PopulateFromRecords(into interface{}, schema *Collection) error { vInto := reflect.ValueOf(into) // get value pointed to if we were given a pointer if vInto.Kind() == reflect.Ptr { vInto = vInto.Elem() } else { return fmt.Errorf("Output argument must be a pointer") } // we're going to fill arrays or slices switch vInto.Type().Kind() { case reflect.Array, reflect.Slice: indirectResult := true // get the type of the underlying slice element sliceType := vInto.Type().Elem() // get the type pointed to if sliceType.Kind() == reflect.Ptr { sliceType = sliceType.Elem() indirectResult = false } // for each resulting record... for _, record := range self.Records { // make a new zero-valued instance of the slice type elem := reflect.New(sliceType) // if we have a registered collection, use its if schema != nil && schema.HasRecordType() { elem = reflect.ValueOf(schema.NewInstance()) } // populate that type with data from this record if err := record.Populate(elem.Interface(), schema); err == nil { // if the slice elements are pointers, we can append the pointer we just created as-is // otherwise, we need to indirect the value and append a copy if indirectResult { vInto.Set(reflect.Append(vInto, reflect.Indirect(elem))) } else { vInto.Set(reflect.Append(vInto, elem)) } } else { return err } } return nil case reflect.Struct: if rs, ok := into.(*RecordSet); ok { *rs = *self return nil } } return fmt.Errorf("RecordSet can only populate records into slice or array, got %T", into) }
[ "func", "(", "self", "*", "RecordSet", ")", "PopulateFromRecords", "(", "into", "interface", "{", "}", ",", "schema", "*", "Collection", ")", "error", "{", "vInto", ":=", "reflect", ".", "ValueOf", "(", "into", ")", "\n\n", "// get value pointed to if we were given a pointer", "if", "vInto", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "vInto", "=", "vInto", ".", "Elem", "(", ")", "\n", "}", "else", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// we're going to fill arrays or slices", "switch", "vInto", ".", "Type", "(", ")", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Array", ",", "reflect", ".", "Slice", ":", "indirectResult", ":=", "true", "\n\n", "// get the type of the underlying slice element", "sliceType", ":=", "vInto", ".", "Type", "(", ")", ".", "Elem", "(", ")", "\n\n", "// get the type pointed to", "if", "sliceType", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "sliceType", "=", "sliceType", ".", "Elem", "(", ")", "\n", "indirectResult", "=", "false", "\n", "}", "\n\n", "// for each resulting record...", "for", "_", ",", "record", ":=", "range", "self", ".", "Records", "{", "// make a new zero-valued instance of the slice type", "elem", ":=", "reflect", ".", "New", "(", "sliceType", ")", "\n\n", "// if we have a registered collection, use its", "if", "schema", "!=", "nil", "&&", "schema", ".", "HasRecordType", "(", ")", "{", "elem", "=", "reflect", ".", "ValueOf", "(", "schema", ".", "NewInstance", "(", ")", ")", "\n", "}", "\n\n", "// populate that type with data from this record", "if", "err", ":=", "record", ".", "Populate", "(", "elem", ".", "Interface", "(", ")", ",", "schema", ")", ";", "err", "==", "nil", "{", "// if the slice elements are pointers, we can append the pointer we just created as-is", "// otherwise, we need to indirect the value and append a copy", "if", "indirectResult", "{", "vInto", ".", "Set", "(", "reflect", ".", "Append", "(", "vInto", ",", "reflect", ".", "Indirect", "(", "elem", ")", ")", ")", "\n", "}", "else", "{", "vInto", ".", "Set", "(", "reflect", ".", "Append", "(", "vInto", ",", "elem", ")", ")", "\n", "}", "\n", "}", "else", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "case", "reflect", ".", "Struct", ":", "if", "rs", ",", "ok", ":=", "into", ".", "(", "*", "RecordSet", ")", ";", "ok", "{", "*", "rs", "=", "*", "self", "\n", "return", "nil", "\n", "}", "\n", "}", "\n\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "into", ")", "\n", "}" ]
// Takes a slice of structs or maps and fills it with instances populated by the records in this RecordSet // in accordance with the types specified in the given collection definition, as well as which // fields are available in the given struct.
[ "Takes", "a", "slice", "of", "structs", "or", "maps", "and", "fills", "it", "with", "instances", "populated", "by", "the", "records", "in", "this", "RecordSet", "in", "accordance", "with", "the", "types", "specified", "in", "the", "given", "collection", "definition", "as", "well", "as", "which", "fields", "are", "available", "in", "the", "given", "struct", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/recordset.go#L80-L138
17,398
ghetzel/pivot
dal/record.go
Populate
func (self *Record) Populate(into interface{}, collection *Collection) error { // special case for what is essentially copying another record into this one if record, ok := into.(*Record); ok { return self.Copy(record, collection) } else { if err := validatePtrToStructType(into); err != nil { return err } // if the struct we got is a zero value, and we've been given a collection, // use it with NewInstance if collection != nil { if typeutil.IsZero(into) { into = collection.NewInstance() } } var idFieldName string var fallbackIdFieldName string // if a collection is specified, set the fallback identity field name to what the collection // knows the ID field is called. This is used for input structs that don't explicitly tag // a field with the ",identity" option if collection != nil { idFieldName = collection.GetIdentityFieldName() } // get the name of the identity field from the given struct if _, key, err := getIdentityFieldNameFromStruct(into, fallbackIdFieldName); err == nil && key != `` { idFieldName = key } else if err != nil { return err } else { return fmt.Errorf("Could not determine identity field name") } if data, err := self.toMap(collection, idFieldName); err == nil { return maputil.TaggedStructFromMap(data, into, RecordStructTag) } else { return err } } }
go
func (self *Record) Populate(into interface{}, collection *Collection) error { // special case for what is essentially copying another record into this one if record, ok := into.(*Record); ok { return self.Copy(record, collection) } else { if err := validatePtrToStructType(into); err != nil { return err } // if the struct we got is a zero value, and we've been given a collection, // use it with NewInstance if collection != nil { if typeutil.IsZero(into) { into = collection.NewInstance() } } var idFieldName string var fallbackIdFieldName string // if a collection is specified, set the fallback identity field name to what the collection // knows the ID field is called. This is used for input structs that don't explicitly tag // a field with the ",identity" option if collection != nil { idFieldName = collection.GetIdentityFieldName() } // get the name of the identity field from the given struct if _, key, err := getIdentityFieldNameFromStruct(into, fallbackIdFieldName); err == nil && key != `` { idFieldName = key } else if err != nil { return err } else { return fmt.Errorf("Could not determine identity field name") } if data, err := self.toMap(collection, idFieldName); err == nil { return maputil.TaggedStructFromMap(data, into, RecordStructTag) } else { return err } } }
[ "func", "(", "self", "*", "Record", ")", "Populate", "(", "into", "interface", "{", "}", ",", "collection", "*", "Collection", ")", "error", "{", "// special case for what is essentially copying another record into this one", "if", "record", ",", "ok", ":=", "into", ".", "(", "*", "Record", ")", ";", "ok", "{", "return", "self", ".", "Copy", "(", "record", ",", "collection", ")", "\n", "}", "else", "{", "if", "err", ":=", "validatePtrToStructType", "(", "into", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// if the struct we got is a zero value, and we've been given a collection,", "// use it with NewInstance", "if", "collection", "!=", "nil", "{", "if", "typeutil", ".", "IsZero", "(", "into", ")", "{", "into", "=", "collection", ".", "NewInstance", "(", ")", "\n", "}", "\n", "}", "\n\n", "var", "idFieldName", "string", "\n", "var", "fallbackIdFieldName", "string", "\n\n", "// if a collection is specified, set the fallback identity field name to what the collection", "// knows the ID field is called. This is used for input structs that don't explicitly tag", "// a field with the \",identity\" option", "if", "collection", "!=", "nil", "{", "idFieldName", "=", "collection", ".", "GetIdentityFieldName", "(", ")", "\n", "}", "\n\n", "// get the name of the identity field from the given struct", "if", "_", ",", "key", ",", "err", ":=", "getIdentityFieldNameFromStruct", "(", "into", ",", "fallbackIdFieldName", ")", ";", "err", "==", "nil", "&&", "key", "!=", "``", "{", "idFieldName", "=", "key", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "else", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "data", ",", "err", ":=", "self", ".", "toMap", "(", "collection", ",", "idFieldName", ")", ";", "err", "==", "nil", "{", "return", "maputil", ".", "TaggedStructFromMap", "(", "data", ",", "into", ",", "RecordStructTag", ")", "\n", "}", "else", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}" ]
// Populates a given struct with with the values in this record.
[ "Populates", "a", "given", "struct", "with", "with", "the", "values", "in", "this", "record", "." ]
29df2462a60d3752a1218e3b6736c5fdb1e77c2d
https://github.com/ghetzel/pivot/blob/29df2462a60d3752a1218e3b6736c5fdb1e77c2d/dal/record.go#L242-L284
17,399
cloudfoundry/lager
lagerctx/context.go
NewContext
func NewContext(parent context.Context, logger lager.Logger) context.Context { return context.WithValue(parent, contextKey{}, logger) }
go
func NewContext(parent context.Context, logger lager.Logger) context.Context { return context.WithValue(parent, contextKey{}, logger) }
[ "func", "NewContext", "(", "parent", "context", ".", "Context", ",", "logger", "lager", ".", "Logger", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "parent", ",", "contextKey", "{", "}", ",", "logger", ")", "\n", "}" ]
// NewContext returns a derived context containing the logger.
[ "NewContext", "returns", "a", "derived", "context", "containing", "the", "logger", "." ]
54c4f2530ddeb742ce9c9ee26f5fa758d6c1b3b6
https://github.com/cloudfoundry/lager/blob/54c4f2530ddeb742ce9c9ee26f5fa758d6c1b3b6/lagerctx/context.go#L12-L14