repo
stringlengths 5
67
| path
stringlengths 4
218
| func_name
stringlengths 0
151
| original_string
stringlengths 52
373k
| language
stringclasses 6
values | code
stringlengths 52
373k
| code_tokens
listlengths 10
512
| docstring
stringlengths 3
47.2k
| docstring_tokens
listlengths 3
234
| sha
stringlengths 40
40
| url
stringlengths 85
339
| partition
stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
rightscale/rsc
|
ca/cac/codegen_client.go
|
UserSettingLocator
|
func (api *API) UserSettingLocator(href string) *UserSettingLocator {
return &UserSettingLocator{Href(href), api}
}
|
go
|
func (api *API) UserSettingLocator(href string) *UserSettingLocator {
return &UserSettingLocator{Href(href), api}
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"UserSettingLocator",
"(",
"href",
"string",
")",
"*",
"UserSettingLocator",
"{",
"return",
"&",
"UserSettingLocator",
"{",
"Href",
"(",
"href",
")",
",",
"api",
"}",
"\n",
"}"
] |
// UserSettingLocator builds a locator from the given href.
|
[
"UserSettingLocator",
"builds",
"a",
"locator",
"from",
"the",
"given",
"href",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ca/cac/codegen_client.go#L3902-L3904
|
test
|
rightscale/rsc
|
recorder/main.go
|
readAllAsync
|
func readAllAsync(f io.ReadCloser) (*[]byte, chan struct{}) {
done := make(chan struct{}, 1) // signal that the read is done
var buf []byte // placeholder buffer for the result
go func() {
var err error
buf, err = ioutil.ReadAll(f)
if err != nil {
buf = make([]byte, 0)
}
f.Close()
done <- struct{}{}
}()
return &buf, done
}
|
go
|
func readAllAsync(f io.ReadCloser) (*[]byte, chan struct{}) {
done := make(chan struct{}, 1) // signal that the read is done
var buf []byte // placeholder buffer for the result
go func() {
var err error
buf, err = ioutil.ReadAll(f)
if err != nil {
buf = make([]byte, 0)
}
f.Close()
done <- struct{}{}
}()
return &buf, done
}
|
[
"func",
"readAllAsync",
"(",
"f",
"io",
".",
"ReadCloser",
")",
"(",
"*",
"[",
"]",
"byte",
",",
"chan",
"struct",
"{",
"}",
")",
"{",
"done",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"1",
")",
"\n",
"var",
"buf",
"[",
"]",
"byte",
"\n",
"go",
"func",
"(",
")",
"{",
"var",
"err",
"error",
"\n",
"buf",
",",
"err",
"=",
"ioutil",
".",
"ReadAll",
"(",
"f",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"buf",
"=",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
")",
"\n",
"}",
"\n",
"f",
".",
"Close",
"(",
")",
"\n",
"done",
"<-",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"(",
")",
"\n",
"return",
"&",
"buf",
",",
"done",
"\n",
"}"
] |
// Read file asynchronously
|
[
"Read",
"file",
"asynchronously"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/recorder/main.go#L104-L117
|
test
|
rightscale/rsc
|
recorder/main.go
|
extractArg
|
func extractArg(name string, args []string) (string, []string) {
var val string
var newArgs []string
var skip bool
for i, a := range args {
if skip {
skip = false
continue
}
if strings.Contains(a, "=") {
elems := strings.SplitN(a, "=", 2)
if elems[0] == name {
val = elems[1]
} else {
newArgs = append(newArgs, a)
}
} else if a == name && len(args) > (i+1) {
val = args[i+1]
skip = true
} else {
newArgs = append(newArgs, a)
}
}
return val, newArgs
}
|
go
|
func extractArg(name string, args []string) (string, []string) {
var val string
var newArgs []string
var skip bool
for i, a := range args {
if skip {
skip = false
continue
}
if strings.Contains(a, "=") {
elems := strings.SplitN(a, "=", 2)
if elems[0] == name {
val = elems[1]
} else {
newArgs = append(newArgs, a)
}
} else if a == name && len(args) > (i+1) {
val = args[i+1]
skip = true
} else {
newArgs = append(newArgs, a)
}
}
return val, newArgs
}
|
[
"func",
"extractArg",
"(",
"name",
"string",
",",
"args",
"[",
"]",
"string",
")",
"(",
"string",
",",
"[",
"]",
"string",
")",
"{",
"var",
"val",
"string",
"\n",
"var",
"newArgs",
"[",
"]",
"string",
"\n",
"var",
"skip",
"bool",
"\n",
"for",
"i",
",",
"a",
":=",
"range",
"args",
"{",
"if",
"skip",
"{",
"skip",
"=",
"false",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"strings",
".",
"Contains",
"(",
"a",
",",
"\"=\"",
")",
"{",
"elems",
":=",
"strings",
".",
"SplitN",
"(",
"a",
",",
"\"=\"",
",",
"2",
")",
"\n",
"if",
"elems",
"[",
"0",
"]",
"==",
"name",
"{",
"val",
"=",
"elems",
"[",
"1",
"]",
"\n",
"}",
"else",
"{",
"newArgs",
"=",
"append",
"(",
"newArgs",
",",
"a",
")",
"\n",
"}",
"\n",
"}",
"else",
"if",
"a",
"==",
"name",
"&&",
"len",
"(",
"args",
")",
">",
"(",
"i",
"+",
"1",
")",
"{",
"val",
"=",
"args",
"[",
"i",
"+",
"1",
"]",
"\n",
"skip",
"=",
"true",
"\n",
"}",
"else",
"{",
"newArgs",
"=",
"append",
"(",
"newArgs",
",",
"a",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"val",
",",
"newArgs",
"\n",
"}"
] |
// Extract command line argument with given name and return remaining arguments
|
[
"Extract",
"command",
"line",
"argument",
"with",
"given",
"name",
"and",
"return",
"remaining",
"arguments"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/recorder/main.go#L120-L144
|
test
|
rightscale/rsc
|
recorder/main.go
|
write
|
func write(b []byte) {
f, err := os.OpenFile(output, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
fail("failed to open output file")
}
f.Write(b)
f.WriteString("\n")
f.Close()
}
|
go
|
func write(b []byte) {
f, err := os.OpenFile(output, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
fail("failed to open output file")
}
f.Write(b)
f.WriteString("\n")
f.Close()
}
|
[
"func",
"write",
"(",
"b",
"[",
"]",
"byte",
")",
"{",
"f",
",",
"err",
":=",
"os",
".",
"OpenFile",
"(",
"output",
",",
"os",
".",
"O_APPEND",
"|",
"os",
".",
"O_WRONLY",
"|",
"os",
".",
"O_CREATE",
",",
"0644",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fail",
"(",
"\"failed to open output file\"",
")",
"\n",
"}",
"\n",
"f",
".",
"Write",
"(",
"b",
")",
"\n",
"f",
".",
"WriteString",
"(",
"\"\\n\"",
")",
"\n",
"\\n",
"\n",
"}"
] |
// Helper function that appends a string to output file
|
[
"Helper",
"function",
"that",
"appends",
"a",
"string",
"to",
"output",
"file"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/recorder/main.go#L147-L155
|
test
|
rightscale/rsc
|
policy/codegen_client.go
|
AppliedPolicyLocator
|
func (api *API) AppliedPolicyLocator(href string) *AppliedPolicyLocator {
return &AppliedPolicyLocator{Href(href), api}
}
|
go
|
func (api *API) AppliedPolicyLocator(href string) *AppliedPolicyLocator {
return &AppliedPolicyLocator{Href(href), api}
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"AppliedPolicyLocator",
"(",
"href",
"string",
")",
"*",
"AppliedPolicyLocator",
"{",
"return",
"&",
"AppliedPolicyLocator",
"{",
"Href",
"(",
"href",
")",
",",
"api",
"}",
"\n",
"}"
] |
// AppliedPolicyLocator builds a locator from the given href.
|
[
"AppliedPolicyLocator",
"builds",
"a",
"locator",
"from",
"the",
"given",
"href",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/policy/codegen_client.go#L94-L96
|
test
|
rightscale/rsc
|
policy/codegen_client.go
|
ApprovalLocator
|
func (api *API) ApprovalLocator(href string) *ApprovalLocator {
return &ApprovalLocator{Href(href), api}
}
|
go
|
func (api *API) ApprovalLocator(href string) *ApprovalLocator {
return &ApprovalLocator{Href(href), api}
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"ApprovalLocator",
"(",
"href",
"string",
")",
"*",
"ApprovalLocator",
"{",
"return",
"&",
"ApprovalLocator",
"{",
"Href",
"(",
"href",
")",
",",
"api",
"}",
"\n",
"}"
] |
// ApprovalLocator builds a locator from the given href.
|
[
"ApprovalLocator",
"builds",
"a",
"locator",
"from",
"the",
"given",
"href",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/policy/codegen_client.go#L399-L401
|
test
|
rightscale/rsc
|
policy/codegen_client.go
|
IncidentLocator
|
func (api *API) IncidentLocator(href string) *IncidentLocator {
return &IncidentLocator{Href(href), api}
}
|
go
|
func (api *API) IncidentLocator(href string) *IncidentLocator {
return &IncidentLocator{Href(href), api}
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"IncidentLocator",
"(",
"href",
"string",
")",
"*",
"IncidentLocator",
"{",
"return",
"&",
"IncidentLocator",
"{",
"Href",
"(",
"href",
")",
",",
"api",
"}",
"\n",
"}"
] |
// IncidentLocator builds a locator from the given href.
|
[
"IncidentLocator",
"builds",
"a",
"locator",
"from",
"the",
"given",
"href",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/policy/codegen_client.go#L610-L612
|
test
|
rightscale/rsc
|
policy/codegen_client.go
|
PolicyTemplateLocator
|
func (api *API) PolicyTemplateLocator(href string) *PolicyTemplateLocator {
return &PolicyTemplateLocator{Href(href), api}
}
|
go
|
func (api *API) PolicyTemplateLocator(href string) *PolicyTemplateLocator {
return &PolicyTemplateLocator{Href(href), api}
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"PolicyTemplateLocator",
"(",
"href",
"string",
")",
"*",
"PolicyTemplateLocator",
"{",
"return",
"&",
"PolicyTemplateLocator",
"{",
"Href",
"(",
"href",
")",
",",
"api",
"}",
"\n",
"}"
] |
// PolicyTemplateLocator builds a locator from the given href.
|
[
"PolicyTemplateLocator",
"builds",
"a",
"locator",
"from",
"the",
"given",
"href",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/policy/codegen_client.go#L844-L846
|
test
|
rightscale/rsc
|
policy/codegen_client.go
|
PublishedTemplateLocator
|
func (api *API) PublishedTemplateLocator(href string) *PublishedTemplateLocator {
return &PublishedTemplateLocator{Href(href), api}
}
|
go
|
func (api *API) PublishedTemplateLocator(href string) *PublishedTemplateLocator {
return &PublishedTemplateLocator{Href(href), api}
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"PublishedTemplateLocator",
"(",
"href",
"string",
")",
"*",
"PublishedTemplateLocator",
"{",
"return",
"&",
"PublishedTemplateLocator",
"{",
"Href",
"(",
"href",
")",
",",
"api",
"}",
"\n",
"}"
] |
// PublishedTemplateLocator builds a locator from the given href.
|
[
"PublishedTemplateLocator",
"builds",
"a",
"locator",
"from",
"the",
"given",
"href",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/policy/codegen_client.go#L1129-L1131
|
test
|
rightscale/rsc
|
rl10/codegen_client.go
|
DebugCookbookPathLocator
|
func (api *API) DebugCookbookPathLocator(href string) *DebugCookbookPathLocator {
return &DebugCookbookPathLocator{Href(href), api}
}
|
go
|
func (api *API) DebugCookbookPathLocator(href string) *DebugCookbookPathLocator {
return &DebugCookbookPathLocator{Href(href), api}
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"DebugCookbookPathLocator",
"(",
"href",
"string",
")",
"*",
"DebugCookbookPathLocator",
"{",
"return",
"&",
"DebugCookbookPathLocator",
"{",
"Href",
"(",
"href",
")",
",",
"api",
"}",
"\n",
"}"
] |
// DebugCookbookPathLocator builds a locator from the given href.
|
[
"DebugCookbookPathLocator",
"builds",
"a",
"locator",
"from",
"the",
"given",
"href",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rl10/codegen_client.go#L71-L73
|
test
|
rightscale/rsc
|
rl10/codegen_client.go
|
DockerControlLocator
|
func (api *API) DockerControlLocator(href string) *DockerControlLocator {
return &DockerControlLocator{Href(href), api}
}
|
go
|
func (api *API) DockerControlLocator(href string) *DockerControlLocator {
return &DockerControlLocator{Href(href), api}
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"DockerControlLocator",
"(",
"href",
"string",
")",
"*",
"DockerControlLocator",
"{",
"return",
"&",
"DockerControlLocator",
"{",
"Href",
"(",
"href",
")",
",",
"api",
"}",
"\n",
"}"
] |
// DockerControlLocator builds a locator from the given href.
|
[
"DockerControlLocator",
"builds",
"a",
"locator",
"from",
"the",
"given",
"href",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rl10/codegen_client.go#L202-L204
|
test
|
rightscale/rsc
|
rl10/codegen_client.go
|
EnvLocator
|
func (api *API) EnvLocator(href string) *EnvLocator {
return &EnvLocator{Href(href), api}
}
|
go
|
func (api *API) EnvLocator(href string) *EnvLocator {
return &EnvLocator{Href(href), api}
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"EnvLocator",
"(",
"href",
"string",
")",
"*",
"EnvLocator",
"{",
"return",
"&",
"EnvLocator",
"{",
"Href",
"(",
"href",
")",
",",
"api",
"}",
"\n",
"}"
] |
// EnvLocator builds a locator from the given href.
|
[
"EnvLocator",
"builds",
"a",
"locator",
"from",
"the",
"given",
"href",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rl10/codegen_client.go#L306-L308
|
test
|
rightscale/rsc
|
rl10/codegen_client.go
|
LoginControlLocator
|
func (api *API) LoginControlLocator(href string) *LoginControlLocator {
return &LoginControlLocator{Href(href), api}
}
|
go
|
func (api *API) LoginControlLocator(href string) *LoginControlLocator {
return &LoginControlLocator{Href(href), api}
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"LoginControlLocator",
"(",
"href",
"string",
")",
"*",
"LoginControlLocator",
"{",
"return",
"&",
"LoginControlLocator",
"{",
"Href",
"(",
"href",
")",
",",
"api",
"}",
"\n",
"}"
] |
// LoginControlLocator builds a locator from the given href.
|
[
"LoginControlLocator",
"builds",
"a",
"locator",
"from",
"the",
"given",
"href",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rl10/codegen_client.go#L474-L476
|
test
|
rightscale/rsc
|
rl10/codegen_client.go
|
ProcLocator
|
func (api *API) ProcLocator(href string) *ProcLocator {
return &ProcLocator{Href(href), api}
}
|
go
|
func (api *API) ProcLocator(href string) *ProcLocator {
return &ProcLocator{Href(href), api}
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"ProcLocator",
"(",
"href",
"string",
")",
"*",
"ProcLocator",
"{",
"return",
"&",
"ProcLocator",
"{",
"Href",
"(",
"href",
")",
",",
"api",
"}",
"\n",
"}"
] |
// ProcLocator builds a locator from the given href.
|
[
"ProcLocator",
"builds",
"a",
"locator",
"from",
"the",
"given",
"href",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rl10/codegen_client.go#L574-L576
|
test
|
rightscale/rsc
|
rl10/codegen_client.go
|
Rl10Locator
|
func (api *API) Rl10Locator(href string) *Rl10Locator {
return &Rl10Locator{Href(href), api}
}
|
go
|
func (api *API) Rl10Locator(href string) *Rl10Locator {
return &Rl10Locator{Href(href), api}
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"Rl10Locator",
"(",
"href",
"string",
")",
"*",
"Rl10Locator",
"{",
"return",
"&",
"Rl10Locator",
"{",
"Href",
"(",
"href",
")",
",",
"api",
"}",
"\n",
"}"
] |
// Rl10Locator builds a locator from the given href.
|
[
"Rl10Locator",
"builds",
"a",
"locator",
"from",
"the",
"given",
"href",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rl10/codegen_client.go#L712-L714
|
test
|
rightscale/rsc
|
rl10/codegen_client.go
|
TSSLocator
|
func (api *API) TSSLocator(href string) *TSSLocator {
return &TSSLocator{Href(href), api}
}
|
go
|
func (api *API) TSSLocator(href string) *TSSLocator {
return &TSSLocator{Href(href), api}
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"TSSLocator",
"(",
"href",
"string",
")",
"*",
"TSSLocator",
"{",
"return",
"&",
"TSSLocator",
"{",
"Href",
"(",
"href",
")",
",",
"api",
"}",
"\n",
"}"
] |
// TSSLocator builds a locator from the given href.
|
[
"TSSLocator",
"builds",
"a",
"locator",
"from",
"the",
"given",
"href",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rl10/codegen_client.go#L877-L879
|
test
|
rightscale/rsc
|
rl10/codegen_client.go
|
TSSControlLocator
|
func (api *API) TSSControlLocator(href string) *TSSControlLocator {
return &TSSControlLocator{Href(href), api}
}
|
go
|
func (api *API) TSSControlLocator(href string) *TSSControlLocator {
return &TSSControlLocator{Href(href), api}
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"TSSControlLocator",
"(",
"href",
"string",
")",
"*",
"TSSControlLocator",
"{",
"return",
"&",
"TSSControlLocator",
"{",
"Href",
"(",
"href",
")",
",",
"api",
"}",
"\n",
"}"
] |
// TSSControlLocator builds a locator from the given href.
|
[
"TSSControlLocator",
"builds",
"a",
"locator",
"from",
"the",
"given",
"href",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rl10/codegen_client.go#L978-L980
|
test
|
rightscale/rsc
|
rl10/codegen_client.go
|
TSSPluginLocator
|
func (api *API) TSSPluginLocator(href string) *TSSPluginLocator {
return &TSSPluginLocator{Href(href), api}
}
|
go
|
func (api *API) TSSPluginLocator(href string) *TSSPluginLocator {
return &TSSPluginLocator{Href(href), api}
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"TSSPluginLocator",
"(",
"href",
"string",
")",
"*",
"TSSPluginLocator",
"{",
"return",
"&",
"TSSPluginLocator",
"{",
"Href",
"(",
"href",
")",
",",
"api",
"}",
"\n",
"}"
] |
// TSSPluginLocator builds a locator from the given href.
|
[
"TSSPluginLocator",
"builds",
"a",
"locator",
"from",
"the",
"given",
"href",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rl10/codegen_client.go#L1128-L1130
|
test
|
rightscale/rsc
|
gen/writers/angular.go
|
NewAngularWriter
|
func NewAngularWriter() (*AngularWriter, error) {
funcMap := template.FuncMap{
"comment": comment,
"commandLine": commandLine,
"path": path,
"mandatory": mandatory,
}
resourceT, err := template.New("resource-client").Funcs(funcMap).Parse(angularTmpl)
if err != nil {
return nil, err
}
return &AngularWriter{
angularTmpl: resourceT,
}, nil
}
|
go
|
func NewAngularWriter() (*AngularWriter, error) {
funcMap := template.FuncMap{
"comment": comment,
"commandLine": commandLine,
"path": path,
"mandatory": mandatory,
}
resourceT, err := template.New("resource-client").Funcs(funcMap).Parse(angularTmpl)
if err != nil {
return nil, err
}
return &AngularWriter{
angularTmpl: resourceT,
}, nil
}
|
[
"func",
"NewAngularWriter",
"(",
")",
"(",
"*",
"AngularWriter",
",",
"error",
")",
"{",
"funcMap",
":=",
"template",
".",
"FuncMap",
"{",
"\"comment\"",
":",
"comment",
",",
"\"commandLine\"",
":",
"commandLine",
",",
"\"path\"",
":",
"path",
",",
"\"mandatory\"",
":",
"mandatory",
",",
"}",
"\n",
"resourceT",
",",
"err",
":=",
"template",
".",
"New",
"(",
"\"resource-client\"",
")",
".",
"Funcs",
"(",
"funcMap",
")",
".",
"Parse",
"(",
"angularTmpl",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"AngularWriter",
"{",
"angularTmpl",
":",
"resourceT",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// NewAngularWriter creates a new code writer that generates angular.js types.
|
[
"NewAngularWriter",
"creates",
"a",
"new",
"code",
"writer",
"that",
"generates",
"angular",
".",
"js",
"types",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/writers/angular.go#L17-L31
|
test
|
rightscale/rsc
|
gen/writers/angular.go
|
WriteResource
|
func (c *AngularWriter) WriteResource(resource *gen.Resource, w io.Writer) error {
return c.angularTmpl.Execute(w, resource)
}
|
go
|
func (c *AngularWriter) WriteResource(resource *gen.Resource, w io.Writer) error {
return c.angularTmpl.Execute(w, resource)
}
|
[
"func",
"(",
"c",
"*",
"AngularWriter",
")",
"WriteResource",
"(",
"resource",
"*",
"gen",
".",
"Resource",
",",
"w",
"io",
".",
"Writer",
")",
"error",
"{",
"return",
"c",
".",
"angularTmpl",
".",
"Execute",
"(",
"w",
",",
"resource",
")",
"\n",
"}"
] |
// WriteResource writes the code for a resource.
|
[
"WriteResource",
"writes",
"the",
"code",
"for",
"a",
"resource",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/writers/angular.go#L34-L36
|
test
|
rightscale/rsc
|
gen/writers/angular.go
|
path
|
func path(a *gen.Action) string {
pattern := a.PathPatterns[0]
vars := pattern.Variables
ivars := make([]interface{}, len(vars))
for i, v := range vars {
ivars[i] = interface{}(":" + v)
}
return fmt.Sprintf(pattern.Pattern, ivars...)
}
|
go
|
func path(a *gen.Action) string {
pattern := a.PathPatterns[0]
vars := pattern.Variables
ivars := make([]interface{}, len(vars))
for i, v := range vars {
ivars[i] = interface{}(":" + v)
}
return fmt.Sprintf(pattern.Pattern, ivars...)
}
|
[
"func",
"path",
"(",
"a",
"*",
"gen",
".",
"Action",
")",
"string",
"{",
"pattern",
":=",
"a",
".",
"PathPatterns",
"[",
"0",
"]",
"\n",
"vars",
":=",
"pattern",
".",
"Variables",
"\n",
"ivars",
":=",
"make",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"len",
"(",
"vars",
")",
")",
"\n",
"for",
"i",
",",
"v",
":=",
"range",
"vars",
"{",
"ivars",
"[",
"i",
"]",
"=",
"interface",
"{",
"}",
"(",
"\":\"",
"+",
"v",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"pattern",
".",
"Pattern",
",",
"ivars",
"...",
")",
"\n",
"}"
] |
// Path for given action, for now simplify and take first path in PathPatterns.
// In the future we may want to create one "action" in generated JS per path.
|
[
"Path",
"for",
"given",
"action",
"for",
"now",
"simplify",
"and",
"take",
"first",
"path",
"in",
"PathPatterns",
".",
"In",
"the",
"future",
"we",
"may",
"want",
"to",
"create",
"one",
"action",
"in",
"generated",
"JS",
"per",
"path",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/writers/angular.go#L40-L48
|
test
|
rightscale/rsc
|
gen/writers/angular.go
|
mandatory
|
func mandatory(a gen.Action, param string) bool {
for _, p := range a.Params {
if p.Name == param {
return p.Mandatory
}
}
panic("praxisgen bug: Unknown param " + param + " for action " + a.Name)
}
|
go
|
func mandatory(a gen.Action, param string) bool {
for _, p := range a.Params {
if p.Name == param {
return p.Mandatory
}
}
panic("praxisgen bug: Unknown param " + param + " for action " + a.Name)
}
|
[
"func",
"mandatory",
"(",
"a",
"gen",
".",
"Action",
",",
"param",
"string",
")",
"bool",
"{",
"for",
"_",
",",
"p",
":=",
"range",
"a",
".",
"Params",
"{",
"if",
"p",
".",
"Name",
"==",
"param",
"{",
"return",
"p",
".",
"Mandatory",
"\n",
"}",
"\n",
"}",
"\n",
"panic",
"(",
"\"praxisgen bug: Unknown param \"",
"+",
"param",
"+",
"\" for action \"",
"+",
"a",
".",
"Name",
")",
"\n",
"}"
] |
// Returns true if parameter with given name is mandatory
|
[
"Returns",
"true",
"if",
"parameter",
"with",
"given",
"name",
"is",
"mandatory"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/writers/angular.go#L51-L58
|
test
|
rightscale/rsc
|
rsapi/rsapi.go
|
New
|
func New(host string, auth Authenticator) *API {
client := httpclient.New()
if strings.HasPrefix(host, "http://") {
host = host[7:]
} else if strings.HasPrefix(host, "https://") {
host = host[8:]
}
a := &API{
Auth: auth,
Host: host,
Client: client,
}
if auth != nil {
auth.SetHost(host)
}
return a
}
|
go
|
func New(host string, auth Authenticator) *API {
client := httpclient.New()
if strings.HasPrefix(host, "http://") {
host = host[7:]
} else if strings.HasPrefix(host, "https://") {
host = host[8:]
}
a := &API{
Auth: auth,
Host: host,
Client: client,
}
if auth != nil {
auth.SetHost(host)
}
return a
}
|
[
"func",
"New",
"(",
"host",
"string",
",",
"auth",
"Authenticator",
")",
"*",
"API",
"{",
"client",
":=",
"httpclient",
".",
"New",
"(",
")",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"host",
",",
"\"http://\"",
")",
"{",
"host",
"=",
"host",
"[",
"7",
":",
"]",
"\n",
"}",
"else",
"if",
"strings",
".",
"HasPrefix",
"(",
"host",
",",
"\"https://\"",
")",
"{",
"host",
"=",
"host",
"[",
"8",
":",
"]",
"\n",
"}",
"\n",
"a",
":=",
"&",
"API",
"{",
"Auth",
":",
"auth",
",",
"Host",
":",
"host",
",",
"Client",
":",
"client",
",",
"}",
"\n",
"if",
"auth",
"!=",
"nil",
"{",
"auth",
".",
"SetHost",
"(",
"host",
")",
"\n",
"}",
"\n",
"return",
"a",
"\n",
"}"
] |
// New returns a API client that uses the given authenticator.
// host may be blank in which case client attempts to resolve it using auth.
|
[
"New",
"returns",
"a",
"API",
"client",
"that",
"uses",
"the",
"given",
"authenticator",
".",
"host",
"may",
"be",
"blank",
"in",
"which",
"case",
"client",
"attempts",
"to",
"resolve",
"it",
"using",
"auth",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/rsapi.go#L44-L60
|
test
|
rightscale/rsc
|
rsapi/rsapi.go
|
FromCommandLine
|
func FromCommandLine(cmdLine *cmd.CommandLine) (*API, error) {
var client *API
ss := strings.HasPrefix(cmdLine.Command, "ss")
if cmdLine.RL10 {
var err error
if client, err = NewRL10(); err != nil {
return nil, err
}
} else if cmdLine.OAuthToken != "" {
auth := NewOAuthAuthenticator(cmdLine.OAuthToken, cmdLine.Account)
if ss {
auth = NewSSAuthenticator(auth, cmdLine.Account)
}
client = New(cmdLine.Host, auth)
} else if cmdLine.OAuthAccessToken != "" {
auth := NewTokenAuthenticator(cmdLine.OAuthAccessToken, cmdLine.Account)
if ss {
auth = NewSSAuthenticator(auth, cmdLine.Account)
}
client = New(cmdLine.Host, auth)
} else if cmdLine.APIToken != "" {
auth := NewInstanceAuthenticator(cmdLine.APIToken, cmdLine.Account)
if ss {
auth = NewSSAuthenticator(auth, cmdLine.Account)
}
client = New(cmdLine.Host, auth)
} else if cmdLine.Username != "" && cmdLine.Password != "" {
auth := NewBasicAuthenticator(cmdLine.Username, cmdLine.Password, cmdLine.Account)
if ss {
auth = NewSSAuthenticator(auth, cmdLine.Account)
}
client = New(cmdLine.Host, auth)
} else {
// No auth, used by tests
client = New(cmdLine.Host, nil)
httpclient.Insecure = true
}
if !cmdLine.ShowHelp && !cmdLine.NoAuth {
if cmdLine.OAuthToken == "" && cmdLine.OAuthAccessToken == "" && cmdLine.APIToken == "" && cmdLine.Username == "" && !cmdLine.RL10 {
return nil, fmt.Errorf("Missing authentication information, use '--email EMAIL --password PWD', '--token TOKEN' or 'setup'")
}
if cmdLine.Verbose || cmdLine.Dump == "debug" {
httpclient.DumpFormat = httpclient.Debug
}
if cmdLine.Dump == "json" {
httpclient.DumpFormat = httpclient.JSON
}
if cmdLine.Dump == "record" {
httpclient.DumpFormat = httpclient.JSON | httpclient.Record
}
if cmdLine.Verbose {
httpclient.DumpFormat |= httpclient.Verbose
}
client.FetchLocationResource = cmdLine.FetchResource
}
return client, nil
}
|
go
|
func FromCommandLine(cmdLine *cmd.CommandLine) (*API, error) {
var client *API
ss := strings.HasPrefix(cmdLine.Command, "ss")
if cmdLine.RL10 {
var err error
if client, err = NewRL10(); err != nil {
return nil, err
}
} else if cmdLine.OAuthToken != "" {
auth := NewOAuthAuthenticator(cmdLine.OAuthToken, cmdLine.Account)
if ss {
auth = NewSSAuthenticator(auth, cmdLine.Account)
}
client = New(cmdLine.Host, auth)
} else if cmdLine.OAuthAccessToken != "" {
auth := NewTokenAuthenticator(cmdLine.OAuthAccessToken, cmdLine.Account)
if ss {
auth = NewSSAuthenticator(auth, cmdLine.Account)
}
client = New(cmdLine.Host, auth)
} else if cmdLine.APIToken != "" {
auth := NewInstanceAuthenticator(cmdLine.APIToken, cmdLine.Account)
if ss {
auth = NewSSAuthenticator(auth, cmdLine.Account)
}
client = New(cmdLine.Host, auth)
} else if cmdLine.Username != "" && cmdLine.Password != "" {
auth := NewBasicAuthenticator(cmdLine.Username, cmdLine.Password, cmdLine.Account)
if ss {
auth = NewSSAuthenticator(auth, cmdLine.Account)
}
client = New(cmdLine.Host, auth)
} else {
// No auth, used by tests
client = New(cmdLine.Host, nil)
httpclient.Insecure = true
}
if !cmdLine.ShowHelp && !cmdLine.NoAuth {
if cmdLine.OAuthToken == "" && cmdLine.OAuthAccessToken == "" && cmdLine.APIToken == "" && cmdLine.Username == "" && !cmdLine.RL10 {
return nil, fmt.Errorf("Missing authentication information, use '--email EMAIL --password PWD', '--token TOKEN' or 'setup'")
}
if cmdLine.Verbose || cmdLine.Dump == "debug" {
httpclient.DumpFormat = httpclient.Debug
}
if cmdLine.Dump == "json" {
httpclient.DumpFormat = httpclient.JSON
}
if cmdLine.Dump == "record" {
httpclient.DumpFormat = httpclient.JSON | httpclient.Record
}
if cmdLine.Verbose {
httpclient.DumpFormat |= httpclient.Verbose
}
client.FetchLocationResource = cmdLine.FetchResource
}
return client, nil
}
|
[
"func",
"FromCommandLine",
"(",
"cmdLine",
"*",
"cmd",
".",
"CommandLine",
")",
"(",
"*",
"API",
",",
"error",
")",
"{",
"var",
"client",
"*",
"API",
"\n",
"ss",
":=",
"strings",
".",
"HasPrefix",
"(",
"cmdLine",
".",
"Command",
",",
"\"ss\"",
")",
"\n",
"if",
"cmdLine",
".",
"RL10",
"{",
"var",
"err",
"error",
"\n",
"if",
"client",
",",
"err",
"=",
"NewRL10",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"else",
"if",
"cmdLine",
".",
"OAuthToken",
"!=",
"\"\"",
"{",
"auth",
":=",
"NewOAuthAuthenticator",
"(",
"cmdLine",
".",
"OAuthToken",
",",
"cmdLine",
".",
"Account",
")",
"\n",
"if",
"ss",
"{",
"auth",
"=",
"NewSSAuthenticator",
"(",
"auth",
",",
"cmdLine",
".",
"Account",
")",
"\n",
"}",
"\n",
"client",
"=",
"New",
"(",
"cmdLine",
".",
"Host",
",",
"auth",
")",
"\n",
"}",
"else",
"if",
"cmdLine",
".",
"OAuthAccessToken",
"!=",
"\"\"",
"{",
"auth",
":=",
"NewTokenAuthenticator",
"(",
"cmdLine",
".",
"OAuthAccessToken",
",",
"cmdLine",
".",
"Account",
")",
"\n",
"if",
"ss",
"{",
"auth",
"=",
"NewSSAuthenticator",
"(",
"auth",
",",
"cmdLine",
".",
"Account",
")",
"\n",
"}",
"\n",
"client",
"=",
"New",
"(",
"cmdLine",
".",
"Host",
",",
"auth",
")",
"\n",
"}",
"else",
"if",
"cmdLine",
".",
"APIToken",
"!=",
"\"\"",
"{",
"auth",
":=",
"NewInstanceAuthenticator",
"(",
"cmdLine",
".",
"APIToken",
",",
"cmdLine",
".",
"Account",
")",
"\n",
"if",
"ss",
"{",
"auth",
"=",
"NewSSAuthenticator",
"(",
"auth",
",",
"cmdLine",
".",
"Account",
")",
"\n",
"}",
"\n",
"client",
"=",
"New",
"(",
"cmdLine",
".",
"Host",
",",
"auth",
")",
"\n",
"}",
"else",
"if",
"cmdLine",
".",
"Username",
"!=",
"\"\"",
"&&",
"cmdLine",
".",
"Password",
"!=",
"\"\"",
"{",
"auth",
":=",
"NewBasicAuthenticator",
"(",
"cmdLine",
".",
"Username",
",",
"cmdLine",
".",
"Password",
",",
"cmdLine",
".",
"Account",
")",
"\n",
"if",
"ss",
"{",
"auth",
"=",
"NewSSAuthenticator",
"(",
"auth",
",",
"cmdLine",
".",
"Account",
")",
"\n",
"}",
"\n",
"client",
"=",
"New",
"(",
"cmdLine",
".",
"Host",
",",
"auth",
")",
"\n",
"}",
"else",
"{",
"client",
"=",
"New",
"(",
"cmdLine",
".",
"Host",
",",
"nil",
")",
"\n",
"httpclient",
".",
"Insecure",
"=",
"true",
"\n",
"}",
"\n",
"if",
"!",
"cmdLine",
".",
"ShowHelp",
"&&",
"!",
"cmdLine",
".",
"NoAuth",
"{",
"if",
"cmdLine",
".",
"OAuthToken",
"==",
"\"\"",
"&&",
"cmdLine",
".",
"OAuthAccessToken",
"==",
"\"\"",
"&&",
"cmdLine",
".",
"APIToken",
"==",
"\"\"",
"&&",
"cmdLine",
".",
"Username",
"==",
"\"\"",
"&&",
"!",
"cmdLine",
".",
"RL10",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Missing authentication information, use '--email EMAIL --password PWD', '--token TOKEN' or 'setup'\"",
")",
"\n",
"}",
"\n",
"if",
"cmdLine",
".",
"Verbose",
"||",
"cmdLine",
".",
"Dump",
"==",
"\"debug\"",
"{",
"httpclient",
".",
"DumpFormat",
"=",
"httpclient",
".",
"Debug",
"\n",
"}",
"\n",
"if",
"cmdLine",
".",
"Dump",
"==",
"\"json\"",
"{",
"httpclient",
".",
"DumpFormat",
"=",
"httpclient",
".",
"JSON",
"\n",
"}",
"\n",
"if",
"cmdLine",
".",
"Dump",
"==",
"\"record\"",
"{",
"httpclient",
".",
"DumpFormat",
"=",
"httpclient",
".",
"JSON",
"|",
"httpclient",
".",
"Record",
"\n",
"}",
"\n",
"if",
"cmdLine",
".",
"Verbose",
"{",
"httpclient",
".",
"DumpFormat",
"|=",
"httpclient",
".",
"Verbose",
"\n",
"}",
"\n",
"client",
".",
"FetchLocationResource",
"=",
"cmdLine",
".",
"FetchResource",
"\n",
"}",
"\n",
"return",
"client",
",",
"nil",
"\n",
"}"
] |
// FromCommandLine builds an API client from the command line.
|
[
"FromCommandLine",
"builds",
"an",
"API",
"client",
"from",
"the",
"command",
"line",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/rsapi.go#L107-L163
|
test
|
rightscale/rsc
|
rsapi/rsapi.go
|
CanAuthenticate
|
func (a *API) CanAuthenticate() error {
res := a.Auth.CanAuthenticate(a.Host)
return res
}
|
go
|
func (a *API) CanAuthenticate() error {
res := a.Auth.CanAuthenticate(a.Host)
return res
}
|
[
"func",
"(",
"a",
"*",
"API",
")",
"CanAuthenticate",
"(",
")",
"error",
"{",
"res",
":=",
"a",
".",
"Auth",
".",
"CanAuthenticate",
"(",
"a",
".",
"Host",
")",
"\n",
"return",
"res",
"\n",
"}"
] |
// CanAuthenticate makes a test authenticated request to the RightScale API and returns an error
// if it fails.
|
[
"CanAuthenticate",
"makes",
"a",
"test",
"authenticated",
"request",
"to",
"the",
"RightScale",
"API",
"and",
"returns",
"an",
"error",
"if",
"it",
"fails",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rsapi/rsapi.go#L167-L170
|
test
|
rightscale/rsc
|
encrypt.go
|
Encrypt
|
func Encrypt(text string) (string, error) {
bytes := []byte(text)
key := seekret()
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
b := encodeBase64(bytes)
ciphertext := make([]byte, aes.BlockSize+len(b))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return "", err
}
cfb := cipher.NewCFBEncrypter(block, iv)
cfb.XORKeyStream(ciphertext[aes.BlockSize:], b)
return string(encodeBase64(ciphertext)), nil
}
|
go
|
func Encrypt(text string) (string, error) {
bytes := []byte(text)
key := seekret()
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
b := encodeBase64(bytes)
ciphertext := make([]byte, aes.BlockSize+len(b))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return "", err
}
cfb := cipher.NewCFBEncrypter(block, iv)
cfb.XORKeyStream(ciphertext[aes.BlockSize:], b)
return string(encodeBase64(ciphertext)), nil
}
|
[
"func",
"Encrypt",
"(",
"text",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"bytes",
":=",
"[",
"]",
"byte",
"(",
"text",
")",
"\n",
"key",
":=",
"seekret",
"(",
")",
"\n",
"block",
",",
"err",
":=",
"aes",
".",
"NewCipher",
"(",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"b",
":=",
"encodeBase64",
"(",
"bytes",
")",
"\n",
"ciphertext",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"aes",
".",
"BlockSize",
"+",
"len",
"(",
"b",
")",
")",
"\n",
"iv",
":=",
"ciphertext",
"[",
":",
"aes",
".",
"BlockSize",
"]",
"\n",
"if",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"rand",
".",
"Reader",
",",
"iv",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"cfb",
":=",
"cipher",
".",
"NewCFBEncrypter",
"(",
"block",
",",
"iv",
")",
"\n",
"cfb",
".",
"XORKeyStream",
"(",
"ciphertext",
"[",
"aes",
".",
"BlockSize",
":",
"]",
",",
"b",
")",
"\n",
"return",
"string",
"(",
"encodeBase64",
"(",
"ciphertext",
")",
")",
",",
"nil",
"\n",
"}"
] |
// Encrypt encrypts the given text with a hard-coded secret. Not truly secure.
|
[
"Encrypt",
"encrypts",
"the",
"given",
"text",
"with",
"a",
"hard",
"-",
"coded",
"secret",
".",
"Not",
"truly",
"secure",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/encrypt.go#L29-L45
|
test
|
rightscale/rsc
|
encrypt.go
|
Decrypt
|
func Decrypt(text string) (string, error) {
if text == "" {
return "", nil
}
key := seekret()
bytes := decodeBase64([]byte(text))
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
if len(bytes) < aes.BlockSize {
return "", errors.New("ciphertext too short")
}
iv := bytes[:aes.BlockSize]
bytes = bytes[aes.BlockSize:]
cfb := cipher.NewCFBDecrypter(block, iv)
cfb.XORKeyStream(bytes, bytes)
return string(decodeBase64(bytes)), nil
}
|
go
|
func Decrypt(text string) (string, error) {
if text == "" {
return "", nil
}
key := seekret()
bytes := decodeBase64([]byte(text))
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
if len(bytes) < aes.BlockSize {
return "", errors.New("ciphertext too short")
}
iv := bytes[:aes.BlockSize]
bytes = bytes[aes.BlockSize:]
cfb := cipher.NewCFBDecrypter(block, iv)
cfb.XORKeyStream(bytes, bytes)
return string(decodeBase64(bytes)), nil
}
|
[
"func",
"Decrypt",
"(",
"text",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"text",
"==",
"\"\"",
"{",
"return",
"\"\"",
",",
"nil",
"\n",
"}",
"\n",
"key",
":=",
"seekret",
"(",
")",
"\n",
"bytes",
":=",
"decodeBase64",
"(",
"[",
"]",
"byte",
"(",
"text",
")",
")",
"\n",
"block",
",",
"err",
":=",
"aes",
".",
"NewCipher",
"(",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"bytes",
")",
"<",
"aes",
".",
"BlockSize",
"{",
"return",
"\"\"",
",",
"errors",
".",
"New",
"(",
"\"ciphertext too short\"",
")",
"\n",
"}",
"\n",
"iv",
":=",
"bytes",
"[",
":",
"aes",
".",
"BlockSize",
"]",
"\n",
"bytes",
"=",
"bytes",
"[",
"aes",
".",
"BlockSize",
":",
"]",
"\n",
"cfb",
":=",
"cipher",
".",
"NewCFBDecrypter",
"(",
"block",
",",
"iv",
")",
"\n",
"cfb",
".",
"XORKeyStream",
"(",
"bytes",
",",
"bytes",
")",
"\n",
"return",
"string",
"(",
"decodeBase64",
"(",
"bytes",
")",
")",
",",
"nil",
"\n",
"}"
] |
// Decrypt decrypts the given encrypted string using the hard-coded secret.
|
[
"Decrypt",
"decrypts",
"the",
"given",
"encrypted",
"string",
"using",
"the",
"hard",
"-",
"coded",
"secret",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/encrypt.go#L48-L66
|
test
|
rightscale/rsc
|
gen/goav2gen/definition.go
|
guessType
|
func (a *APIAnalyzer) guessType(ec EvalCtx, d *Definition, refID string) string {
// First get the type name and and view from the swagger reference definition
// name -- are a few cases where that's the only place that has the view
if t, ok := a.TypeOverrides[refID]; ok {
return t
}
var name, view string
if strings.Contains(refID, "RequestBody") {
bits := strings.Split(refID, "RequestBody")
name = bits[0]
if len(bits) > 1 {
view = strings.ToLower(bits[1])
}
} else if strings.Contains(refID, "ResponseBody") {
bits := strings.Split(refID, "ResponseBody")
name = bits[0]
if len(bits) > 1 {
view = strings.ToLower(bits[1])
}
} else {
name = refID
}
// Now try and get it from the media type -- this is preferred if its set.
if mt := mediaType(d.Title); mt != "" {
if strings.Contains(mt, "application") {
bits := strings.Split(mt, ".")
name := bits[len(bits)-1]
attrs := mediaTypeAttrs(d.Title)
if attrs["type"] != "" {
name += "_" + attrs["type"]
}
if attrs["view"] != "" && attrs["view"] != "default" {
name += "_" + attrs["view"]
} else if view != "" {
name += "_" + view
}
dbg("DEBUG media type refID:%#v title:%#v name:%#v view:%#v -> type:%#v\n", refID, d.Title, name, view, name)
return toTypeName(name)
} else if strings.Contains(mt, "text/") {
return "string"
} else {
fail("Don't know how to handle media type %s", mt)
}
}
if view != "" {
return name + "_" + view
}
return name
}
|
go
|
func (a *APIAnalyzer) guessType(ec EvalCtx, d *Definition, refID string) string {
// First get the type name and and view from the swagger reference definition
// name -- are a few cases where that's the only place that has the view
if t, ok := a.TypeOverrides[refID]; ok {
return t
}
var name, view string
if strings.Contains(refID, "RequestBody") {
bits := strings.Split(refID, "RequestBody")
name = bits[0]
if len(bits) > 1 {
view = strings.ToLower(bits[1])
}
} else if strings.Contains(refID, "ResponseBody") {
bits := strings.Split(refID, "ResponseBody")
name = bits[0]
if len(bits) > 1 {
view = strings.ToLower(bits[1])
}
} else {
name = refID
}
// Now try and get it from the media type -- this is preferred if its set.
if mt := mediaType(d.Title); mt != "" {
if strings.Contains(mt, "application") {
bits := strings.Split(mt, ".")
name := bits[len(bits)-1]
attrs := mediaTypeAttrs(d.Title)
if attrs["type"] != "" {
name += "_" + attrs["type"]
}
if attrs["view"] != "" && attrs["view"] != "default" {
name += "_" + attrs["view"]
} else if view != "" {
name += "_" + view
}
dbg("DEBUG media type refID:%#v title:%#v name:%#v view:%#v -> type:%#v\n", refID, d.Title, name, view, name)
return toTypeName(name)
} else if strings.Contains(mt, "text/") {
return "string"
} else {
fail("Don't know how to handle media type %s", mt)
}
}
if view != "" {
return name + "_" + view
}
return name
}
|
[
"func",
"(",
"a",
"*",
"APIAnalyzer",
")",
"guessType",
"(",
"ec",
"EvalCtx",
",",
"d",
"*",
"Definition",
",",
"refID",
"string",
")",
"string",
"{",
"if",
"t",
",",
"ok",
":=",
"a",
".",
"TypeOverrides",
"[",
"refID",
"]",
";",
"ok",
"{",
"return",
"t",
"\n",
"}",
"\n",
"var",
"name",
",",
"view",
"string",
"\n",
"if",
"strings",
".",
"Contains",
"(",
"refID",
",",
"\"RequestBody\"",
")",
"{",
"bits",
":=",
"strings",
".",
"Split",
"(",
"refID",
",",
"\"RequestBody\"",
")",
"\n",
"name",
"=",
"bits",
"[",
"0",
"]",
"\n",
"if",
"len",
"(",
"bits",
")",
">",
"1",
"{",
"view",
"=",
"strings",
".",
"ToLower",
"(",
"bits",
"[",
"1",
"]",
")",
"\n",
"}",
"\n",
"}",
"else",
"if",
"strings",
".",
"Contains",
"(",
"refID",
",",
"\"ResponseBody\"",
")",
"{",
"bits",
":=",
"strings",
".",
"Split",
"(",
"refID",
",",
"\"ResponseBody\"",
")",
"\n",
"name",
"=",
"bits",
"[",
"0",
"]",
"\n",
"if",
"len",
"(",
"bits",
")",
">",
"1",
"{",
"view",
"=",
"strings",
".",
"ToLower",
"(",
"bits",
"[",
"1",
"]",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"name",
"=",
"refID",
"\n",
"}",
"\n",
"if",
"mt",
":=",
"mediaType",
"(",
"d",
".",
"Title",
")",
";",
"mt",
"!=",
"\"\"",
"{",
"if",
"strings",
".",
"Contains",
"(",
"mt",
",",
"\"application\"",
")",
"{",
"bits",
":=",
"strings",
".",
"Split",
"(",
"mt",
",",
"\".\"",
")",
"\n",
"name",
":=",
"bits",
"[",
"len",
"(",
"bits",
")",
"-",
"1",
"]",
"\n",
"attrs",
":=",
"mediaTypeAttrs",
"(",
"d",
".",
"Title",
")",
"\n",
"if",
"attrs",
"[",
"\"type\"",
"]",
"!=",
"\"\"",
"{",
"name",
"+=",
"\"_\"",
"+",
"attrs",
"[",
"\"type\"",
"]",
"\n",
"}",
"\n",
"if",
"attrs",
"[",
"\"view\"",
"]",
"!=",
"\"\"",
"&&",
"attrs",
"[",
"\"view\"",
"]",
"!=",
"\"default\"",
"{",
"name",
"+=",
"\"_\"",
"+",
"attrs",
"[",
"\"view\"",
"]",
"\n",
"}",
"else",
"if",
"view",
"!=",
"\"\"",
"{",
"name",
"+=",
"\"_\"",
"+",
"view",
"\n",
"}",
"\n",
"dbg",
"(",
"\"DEBUG media type refID:%#v title:%#v name:%#v view:%#v -> type:%#v\\n\"",
",",
"\\n",
",",
"refID",
",",
"d",
".",
"Title",
",",
"name",
",",
"view",
")",
"\n",
"name",
"\n",
"}",
"else",
"return",
"toTypeName",
"(",
"name",
")",
"\n",
"}",
"\n",
"if",
"strings",
".",
"Contains",
"(",
"mt",
",",
"\"text/\"",
")",
"{",
"return",
"\"string\"",
"\n",
"}",
"else",
"{",
"fail",
"(",
"\"Don't know how to handle media type %s\"",
",",
"mt",
")",
"\n",
"}",
"\n",
"if",
"view",
"!=",
"\"\"",
"{",
"return",
"name",
"+",
"\"_\"",
"+",
"view",
"\n",
"}",
"\n",
"}"
] |
// guessType tries to guess the resource name based on the definition and service.
// This info is not stored in the swagger. TBD manual overrides if needed.
|
[
"guessType",
"tries",
"to",
"guess",
"the",
"resource",
"name",
"based",
"on",
"the",
"definition",
"and",
"service",
".",
"This",
"info",
"is",
"not",
"stored",
"in",
"the",
"swagger",
".",
"TBD",
"manual",
"overrides",
"if",
"needed",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/goav2gen/definition.go#L52-L102
|
test
|
rightscale/rsc
|
gen/goav2gen/definition.go
|
addType
|
func (a *APIAnalyzer) addType(ec EvalCtx, dt *gen.ObjectDataType, r Ref) {
a.api.NeedJSON = true
if a.refByType[dt.TypeName] == r.ID() {
return
}
if other, ok := a.api.Types[dt.TypeName]; ok {
if !ec.IsResult {
// If its an input parameter, fix the collision by amending this types name
dt.TypeName += "Param"
if a.refByType[dt.TypeName] == r.ID() {
return
}
}
oldFields := []string{}
newFields := []string{}
for _, f := range other.Fields {
oldFields = append(oldFields, f.Name)
}
for _, f := range dt.Fields {
newFields = append(newFields, f.Name)
}
use := "Old"
if len(newFields) > len(oldFields) {
use = "New"
}
if strings.Join(oldFields, ",") != strings.Join(newFields, ",") {
warn("Warning: Type collision when adding new type %s!\n New: id %s fields %v\n Old: id %s fields %v\n Using %s, which has more fields\n",
dt.TypeName, r.ID(), newFields, a.refByType[dt.TypeName], oldFields, use)
}
if use == "Old" {
return
}
}
dbg("DEBUG NEW TYPE %s\n", prettify(dt))
a.refByType[dt.TypeName] = r.ID()
a.api.Types[dt.TypeName] = dt
}
|
go
|
func (a *APIAnalyzer) addType(ec EvalCtx, dt *gen.ObjectDataType, r Ref) {
a.api.NeedJSON = true
if a.refByType[dt.TypeName] == r.ID() {
return
}
if other, ok := a.api.Types[dt.TypeName]; ok {
if !ec.IsResult {
// If its an input parameter, fix the collision by amending this types name
dt.TypeName += "Param"
if a.refByType[dt.TypeName] == r.ID() {
return
}
}
oldFields := []string{}
newFields := []string{}
for _, f := range other.Fields {
oldFields = append(oldFields, f.Name)
}
for _, f := range dt.Fields {
newFields = append(newFields, f.Name)
}
use := "Old"
if len(newFields) > len(oldFields) {
use = "New"
}
if strings.Join(oldFields, ",") != strings.Join(newFields, ",") {
warn("Warning: Type collision when adding new type %s!\n New: id %s fields %v\n Old: id %s fields %v\n Using %s, which has more fields\n",
dt.TypeName, r.ID(), newFields, a.refByType[dt.TypeName], oldFields, use)
}
if use == "Old" {
return
}
}
dbg("DEBUG NEW TYPE %s\n", prettify(dt))
a.refByType[dt.TypeName] = r.ID()
a.api.Types[dt.TypeName] = dt
}
|
[
"func",
"(",
"a",
"*",
"APIAnalyzer",
")",
"addType",
"(",
"ec",
"EvalCtx",
",",
"dt",
"*",
"gen",
".",
"ObjectDataType",
",",
"r",
"Ref",
")",
"{",
"a",
".",
"api",
".",
"NeedJSON",
"=",
"true",
"\n",
"if",
"a",
".",
"refByType",
"[",
"dt",
".",
"TypeName",
"]",
"==",
"r",
".",
"ID",
"(",
")",
"{",
"return",
"\n",
"}",
"\n",
"if",
"other",
",",
"ok",
":=",
"a",
".",
"api",
".",
"Types",
"[",
"dt",
".",
"TypeName",
"]",
";",
"ok",
"{",
"if",
"!",
"ec",
".",
"IsResult",
"{",
"dt",
".",
"TypeName",
"+=",
"\"Param\"",
"\n",
"if",
"a",
".",
"refByType",
"[",
"dt",
".",
"TypeName",
"]",
"==",
"r",
".",
"ID",
"(",
")",
"{",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"oldFields",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"newFields",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"other",
".",
"Fields",
"{",
"oldFields",
"=",
"append",
"(",
"oldFields",
",",
"f",
".",
"Name",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"dt",
".",
"Fields",
"{",
"newFields",
"=",
"append",
"(",
"newFields",
",",
"f",
".",
"Name",
")",
"\n",
"}",
"\n",
"use",
":=",
"\"Old\"",
"\n",
"if",
"len",
"(",
"newFields",
")",
">",
"len",
"(",
"oldFields",
")",
"{",
"use",
"=",
"\"New\"",
"\n",
"}",
"\n",
"if",
"strings",
".",
"Join",
"(",
"oldFields",
",",
"\",\"",
")",
"!=",
"strings",
".",
"Join",
"(",
"newFields",
",",
"\",\"",
")",
"{",
"warn",
"(",
"\"Warning: Type collision when adding new type %s!\\n New: id %s fields %v\\n Old: id %s fields %v\\n Using %s, which has more fields\\n\"",
",",
"\\n",
",",
"\\n",
",",
"\\n",
",",
"\\n",
",",
"dt",
".",
"TypeName",
",",
"r",
".",
"ID",
"(",
")",
")",
"\n",
"}",
"\n",
"newFields",
"\n",
"}",
"\n",
"a",
".",
"refByType",
"[",
"dt",
".",
"TypeName",
"]",
"\n",
"oldFields",
"\n",
"use",
"\n",
"}"
] |
// addType conditionally adds a new type, trying its best to avoid type
// collisions. This is the downside of swagger 2 vs swagger 3. For swagger 2
// if you the same type like "User" returned in multiple places, each have to
// create their own definition in the swagger "definitions" section for goa
// v2. So they'll be X copies of identical definition for a User struct lets
// say. This tries to collapse those things down into one return type struct.
|
[
"addType",
"conditionally",
"adds",
"a",
"new",
"type",
"trying",
"its",
"best",
"to",
"avoid",
"type",
"collisions",
".",
"This",
"is",
"the",
"downside",
"of",
"swagger",
"2",
"vs",
"swagger",
"3",
".",
"For",
"swagger",
"2",
"if",
"you",
"the",
"same",
"type",
"like",
"User",
"returned",
"in",
"multiple",
"places",
"each",
"have",
"to",
"create",
"their",
"own",
"definition",
"in",
"the",
"swagger",
"definitions",
"section",
"for",
"goa",
"v2",
".",
"So",
"they",
"ll",
"be",
"X",
"copies",
"of",
"identical",
"definition",
"for",
"a",
"User",
"struct",
"lets",
"say",
".",
"This",
"tries",
"to",
"collapse",
"those",
"things",
"down",
"into",
"one",
"return",
"type",
"struct",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/goav2gen/definition.go#L207-L244
|
test
|
rightscale/rsc
|
gen/goav2gen/api.go
|
extractCmdLineParams
|
func extractCmdLineParams(a *gen.ActionParam, root string, seen map[string]*[]*gen.ActionParam, parentNotMandatory bool) []*gen.ActionParam {
switch t := a.Type.(type) {
case *gen.BasicDataType, *gen.EnumerableDataType, *gen.UploadDataType:
dup := gen.ActionParam{
Name: a.Name,
QueryName: root,
Description: a.Description,
VarName: a.VarName,
Location: a.Location,
Type: a.Type,
Mandatory: a.Mandatory && !parentNotMandatory, // yay for double negations!
NonBlank: a.NonBlank,
Regexp: a.Regexp,
ValidValues: a.ValidValues,
Min: a.Min,
Max: a.Max,
}
return []*gen.ActionParam{&dup}
case *gen.ArrayDataType:
p := t.ElemType
eq, ok := seen[p.Name]
if !ok {
eq = &[]*gen.ActionParam{}
seen[p.Name] = eq
*eq = extractCmdLineParams(p, root+"[]", seen, parentNotMandatory || !a.Mandatory)
}
return *eq
case *gen.ObjectDataType:
params := []*gen.ActionParam{}
for _, f := range t.Fields {
eq, ok := seen[f.Name]
if !ok {
eq = &[]*gen.ActionParam{}
seen[f.Name] = eq
*eq = extractCmdLineParams(f, fmt.Sprintf("%s[%s]", root, f.Name), seen, parentNotMandatory || !a.Mandatory)
}
params = append(params, *eq...)
}
return params
}
return nil
}
|
go
|
func extractCmdLineParams(a *gen.ActionParam, root string, seen map[string]*[]*gen.ActionParam, parentNotMandatory bool) []*gen.ActionParam {
switch t := a.Type.(type) {
case *gen.BasicDataType, *gen.EnumerableDataType, *gen.UploadDataType:
dup := gen.ActionParam{
Name: a.Name,
QueryName: root,
Description: a.Description,
VarName: a.VarName,
Location: a.Location,
Type: a.Type,
Mandatory: a.Mandatory && !parentNotMandatory, // yay for double negations!
NonBlank: a.NonBlank,
Regexp: a.Regexp,
ValidValues: a.ValidValues,
Min: a.Min,
Max: a.Max,
}
return []*gen.ActionParam{&dup}
case *gen.ArrayDataType:
p := t.ElemType
eq, ok := seen[p.Name]
if !ok {
eq = &[]*gen.ActionParam{}
seen[p.Name] = eq
*eq = extractCmdLineParams(p, root+"[]", seen, parentNotMandatory || !a.Mandatory)
}
return *eq
case *gen.ObjectDataType:
params := []*gen.ActionParam{}
for _, f := range t.Fields {
eq, ok := seen[f.Name]
if !ok {
eq = &[]*gen.ActionParam{}
seen[f.Name] = eq
*eq = extractCmdLineParams(f, fmt.Sprintf("%s[%s]", root, f.Name), seen, parentNotMandatory || !a.Mandatory)
}
params = append(params, *eq...)
}
return params
}
return nil
}
|
[
"func",
"extractCmdLineParams",
"(",
"a",
"*",
"gen",
".",
"ActionParam",
",",
"root",
"string",
",",
"seen",
"map",
"[",
"string",
"]",
"*",
"[",
"]",
"*",
"gen",
".",
"ActionParam",
",",
"parentNotMandatory",
"bool",
")",
"[",
"]",
"*",
"gen",
".",
"ActionParam",
"{",
"switch",
"t",
":=",
"a",
".",
"Type",
".",
"(",
"type",
")",
"{",
"case",
"*",
"gen",
".",
"BasicDataType",
",",
"*",
"gen",
".",
"EnumerableDataType",
",",
"*",
"gen",
".",
"UploadDataType",
":",
"dup",
":=",
"gen",
".",
"ActionParam",
"{",
"Name",
":",
"a",
".",
"Name",
",",
"QueryName",
":",
"root",
",",
"Description",
":",
"a",
".",
"Description",
",",
"VarName",
":",
"a",
".",
"VarName",
",",
"Location",
":",
"a",
".",
"Location",
",",
"Type",
":",
"a",
".",
"Type",
",",
"Mandatory",
":",
"a",
".",
"Mandatory",
"&&",
"!",
"parentNotMandatory",
",",
"NonBlank",
":",
"a",
".",
"NonBlank",
",",
"Regexp",
":",
"a",
".",
"Regexp",
",",
"ValidValues",
":",
"a",
".",
"ValidValues",
",",
"Min",
":",
"a",
".",
"Min",
",",
"Max",
":",
"a",
".",
"Max",
",",
"}",
"\n",
"return",
"[",
"]",
"*",
"gen",
".",
"ActionParam",
"{",
"&",
"dup",
"}",
"\n",
"case",
"*",
"gen",
".",
"ArrayDataType",
":",
"p",
":=",
"t",
".",
"ElemType",
"\n",
"eq",
",",
"ok",
":=",
"seen",
"[",
"p",
".",
"Name",
"]",
"\n",
"if",
"!",
"ok",
"{",
"eq",
"=",
"&",
"[",
"]",
"*",
"gen",
".",
"ActionParam",
"{",
"}",
"\n",
"seen",
"[",
"p",
".",
"Name",
"]",
"=",
"eq",
"\n",
"*",
"eq",
"=",
"extractCmdLineParams",
"(",
"p",
",",
"root",
"+",
"\"[]\"",
",",
"seen",
",",
"parentNotMandatory",
"||",
"!",
"a",
".",
"Mandatory",
")",
"\n",
"}",
"\n",
"return",
"*",
"eq",
"\n",
"case",
"*",
"gen",
".",
"ObjectDataType",
":",
"params",
":=",
"[",
"]",
"*",
"gen",
".",
"ActionParam",
"{",
"}",
"\n",
"for",
"_",
",",
"f",
":=",
"range",
"t",
".",
"Fields",
"{",
"eq",
",",
"ok",
":=",
"seen",
"[",
"f",
".",
"Name",
"]",
"\n",
"if",
"!",
"ok",
"{",
"eq",
"=",
"&",
"[",
"]",
"*",
"gen",
".",
"ActionParam",
"{",
"}",
"\n",
"seen",
"[",
"f",
".",
"Name",
"]",
"=",
"eq",
"\n",
"*",
"eq",
"=",
"extractCmdLineParams",
"(",
"f",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%s[%s]\"",
",",
"root",
",",
"f",
".",
"Name",
")",
",",
"seen",
",",
"parentNotMandatory",
"||",
"!",
"a",
".",
"Mandatory",
")",
"\n",
"}",
"\n",
"params",
"=",
"append",
"(",
"params",
",",
"*",
"eq",
"...",
")",
"\n",
"}",
"\n",
"return",
"params",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// extractCmdLineParams generates flags for the command line
|
[
"extractCmdLineParams",
"generates",
"flags",
"for",
"the",
"command",
"line"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/goav2gen/api.go#L122-L163
|
test
|
rightscale/rsc
|
gen/writers/metadata.go
|
NewMetadataWriter
|
func NewMetadataWriter() (*MetadataWriter, error) {
funcMap := template.FuncMap{
"comment": comment,
"join": strings.Join,
"commandLine": commandLine,
"toStringArray": toStringArray,
"flagType": flagType,
"location": location,
"escapeBackticks": escapeBackticks,
}
headerT, err := template.New("header-metadata").Funcs(funcMap).Parse(headerMetadataTmpl)
if err != nil {
return nil, err
}
resourceT, err := template.New("resource-metadata").Funcs(funcMap).Parse(resourceMetadataTmpl)
if err != nil {
return nil, err
}
return &MetadataWriter{
headerTmpl: headerT,
resourceTmpl: resourceT,
}, nil
}
|
go
|
func NewMetadataWriter() (*MetadataWriter, error) {
funcMap := template.FuncMap{
"comment": comment,
"join": strings.Join,
"commandLine": commandLine,
"toStringArray": toStringArray,
"flagType": flagType,
"location": location,
"escapeBackticks": escapeBackticks,
}
headerT, err := template.New("header-metadata").Funcs(funcMap).Parse(headerMetadataTmpl)
if err != nil {
return nil, err
}
resourceT, err := template.New("resource-metadata").Funcs(funcMap).Parse(resourceMetadataTmpl)
if err != nil {
return nil, err
}
return &MetadataWriter{
headerTmpl: headerT,
resourceTmpl: resourceT,
}, nil
}
|
[
"func",
"NewMetadataWriter",
"(",
")",
"(",
"*",
"MetadataWriter",
",",
"error",
")",
"{",
"funcMap",
":=",
"template",
".",
"FuncMap",
"{",
"\"comment\"",
":",
"comment",
",",
"\"join\"",
":",
"strings",
".",
"Join",
",",
"\"commandLine\"",
":",
"commandLine",
",",
"\"toStringArray\"",
":",
"toStringArray",
",",
"\"flagType\"",
":",
"flagType",
",",
"\"location\"",
":",
"location",
",",
"\"escapeBackticks\"",
":",
"escapeBackticks",
",",
"}",
"\n",
"headerT",
",",
"err",
":=",
"template",
".",
"New",
"(",
"\"header-metadata\"",
")",
".",
"Funcs",
"(",
"funcMap",
")",
".",
"Parse",
"(",
"headerMetadataTmpl",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"resourceT",
",",
"err",
":=",
"template",
".",
"New",
"(",
"\"resource-metadata\"",
")",
".",
"Funcs",
"(",
"funcMap",
")",
".",
"Parse",
"(",
"resourceMetadataTmpl",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"MetadataWriter",
"{",
"headerTmpl",
":",
"headerT",
",",
"resourceTmpl",
":",
"resourceT",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// NewMetadataWriter creates a new writer that generates metadata data structures.
|
[
"NewMetadataWriter",
"creates",
"a",
"new",
"writer",
"that",
"generates",
"metadata",
"data",
"structures",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/writers/metadata.go#L18-L40
|
test
|
rightscale/rsc
|
gen/writers/metadata.go
|
WriteHeader
|
func (c *MetadataWriter) WriteHeader(pkg string, w io.Writer) error {
return c.headerTmpl.Execute(w, pkg)
}
|
go
|
func (c *MetadataWriter) WriteHeader(pkg string, w io.Writer) error {
return c.headerTmpl.Execute(w, pkg)
}
|
[
"func",
"(",
"c",
"*",
"MetadataWriter",
")",
"WriteHeader",
"(",
"pkg",
"string",
",",
"w",
"io",
".",
"Writer",
")",
"error",
"{",
"return",
"c",
".",
"headerTmpl",
".",
"Execute",
"(",
"w",
",",
"pkg",
")",
"\n",
"}"
] |
// WriteHeader writes the generic header text.
|
[
"WriteHeader",
"writes",
"the",
"generic",
"header",
"text",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/writers/metadata.go#L43-L45
|
test
|
rightscale/rsc
|
gen/writers/metadata.go
|
WriteMetadata
|
func (c *MetadataWriter) WriteMetadata(d *gen.APIDescriptor, w io.Writer) error {
resources := make([]*gen.Resource, len(d.ResourceNames))
for i, n := range d.ResourceNames {
resources[i] = d.Resources[n]
}
return c.resourceTmpl.Execute(w, resources)
}
|
go
|
func (c *MetadataWriter) WriteMetadata(d *gen.APIDescriptor, w io.Writer) error {
resources := make([]*gen.Resource, len(d.ResourceNames))
for i, n := range d.ResourceNames {
resources[i] = d.Resources[n]
}
return c.resourceTmpl.Execute(w, resources)
}
|
[
"func",
"(",
"c",
"*",
"MetadataWriter",
")",
"WriteMetadata",
"(",
"d",
"*",
"gen",
".",
"APIDescriptor",
",",
"w",
"io",
".",
"Writer",
")",
"error",
"{",
"resources",
":=",
"make",
"(",
"[",
"]",
"*",
"gen",
".",
"Resource",
",",
"len",
"(",
"d",
".",
"ResourceNames",
")",
")",
"\n",
"for",
"i",
",",
"n",
":=",
"range",
"d",
".",
"ResourceNames",
"{",
"resources",
"[",
"i",
"]",
"=",
"d",
".",
"Resources",
"[",
"n",
"]",
"\n",
"}",
"\n",
"return",
"c",
".",
"resourceTmpl",
".",
"Execute",
"(",
"w",
",",
"resources",
")",
"\n",
"}"
] |
// WriteMetadata writes the data structures that describe the API resources and actions.
|
[
"WriteMetadata",
"writes",
"the",
"data",
"structures",
"that",
"describe",
"the",
"API",
"resources",
"and",
"actions",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/writers/metadata.go#L48-L54
|
test
|
rightscale/rsc
|
gen/writers/metadata.go
|
location
|
func location(p *gen.ActionParam) string {
switch p.Location {
case gen.PathParam:
return "metadata.PathParam"
case gen.QueryParam:
return "metadata.QueryParam"
case gen.PayloadParam:
return "metadata.PayloadParam"
default:
return ""
}
}
|
go
|
func location(p *gen.ActionParam) string {
switch p.Location {
case gen.PathParam:
return "metadata.PathParam"
case gen.QueryParam:
return "metadata.QueryParam"
case gen.PayloadParam:
return "metadata.PayloadParam"
default:
return ""
}
}
|
[
"func",
"location",
"(",
"p",
"*",
"gen",
".",
"ActionParam",
")",
"string",
"{",
"switch",
"p",
".",
"Location",
"{",
"case",
"gen",
".",
"PathParam",
":",
"return",
"\"metadata.PathParam\"",
"\n",
"case",
"gen",
".",
"QueryParam",
":",
"return",
"\"metadata.QueryParam\"",
"\n",
"case",
"gen",
".",
"PayloadParam",
":",
"return",
"\"metadata.PayloadParam\"",
"\n",
"default",
":",
"return",
"\"\"",
"\n",
"}",
"\n",
"}"
] |
// Return code corresponding to param location
|
[
"Return",
"code",
"corresponding",
"to",
"param",
"location"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/writers/metadata.go#L57-L68
|
test
|
rightscale/rsc
|
rl10/rl10.go
|
New
|
func New(host string, auth rsapi.Authenticator) *API {
return fromAPI(rsapi.New(host, auth))
}
|
go
|
func New(host string, auth rsapi.Authenticator) *API {
return fromAPI(rsapi.New(host, auth))
}
|
[
"func",
"New",
"(",
"host",
"string",
",",
"auth",
"rsapi",
".",
"Authenticator",
")",
"*",
"API",
"{",
"return",
"fromAPI",
"(",
"rsapi",
".",
"New",
"(",
"host",
",",
"auth",
")",
")",
"\n",
"}"
] |
// New returns a client that uses RL10 authentication.
// accountId, host and auth arguments are not used.
// If no HTTP client is specified then the default client is used.
|
[
"New",
"returns",
"a",
"client",
"that",
"uses",
"RL10",
"authentication",
".",
"accountId",
"host",
"and",
"auth",
"arguments",
"are",
"not",
"used",
".",
"If",
"no",
"HTTP",
"client",
"is",
"specified",
"then",
"the",
"default",
"client",
"is",
"used",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rl10/rl10.go#L16-L18
|
test
|
rightscale/rsc
|
rl10/rl10.go
|
fromAPI
|
func fromAPI(api *rsapi.API) *API {
api.Metadata = GenMetadata
return &API{api}
}
|
go
|
func fromAPI(api *rsapi.API) *API {
api.Metadata = GenMetadata
return &API{api}
}
|
[
"func",
"fromAPI",
"(",
"api",
"*",
"rsapi",
".",
"API",
")",
"*",
"API",
"{",
"api",
".",
"Metadata",
"=",
"GenMetadata",
"\n",
"return",
"&",
"API",
"{",
"api",
"}",
"\n",
"}"
] |
// Wrap generic client into RL10 client
|
[
"Wrap",
"generic",
"client",
"into",
"RL10",
"client"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/rl10/rl10.go#L41-L44
|
test
|
rightscale/rsc
|
cm16/http.go
|
BuildRequest
|
func (a *API) BuildRequest(resource, action, href string, params rsapi.APIParams) (*http.Request, error) {
// First lookup metadata
res, ok := GenMetadata[resource]
if !ok {
return nil, fmt.Errorf("No resource with name '%s'", resource)
}
act := res.GetAction(action)
if act == nil {
return nil, fmt.Errorf("No action with name '%s' on %s", action, resource)
}
// Now lookup action request HTTP method, url, params and payload.
vars, err := res.ExtractVariables(href)
if err != nil {
return nil, err
}
actionURL, err := act.URL(vars)
if err != nil {
return nil, err
}
_, queryParams := rsapi.IdentifyParams(act, params)
return a.BuildHTTPRequest("GET", actionURL.Path, "1.6", queryParams, nil)
}
|
go
|
func (a *API) BuildRequest(resource, action, href string, params rsapi.APIParams) (*http.Request, error) {
// First lookup metadata
res, ok := GenMetadata[resource]
if !ok {
return nil, fmt.Errorf("No resource with name '%s'", resource)
}
act := res.GetAction(action)
if act == nil {
return nil, fmt.Errorf("No action with name '%s' on %s", action, resource)
}
// Now lookup action request HTTP method, url, params and payload.
vars, err := res.ExtractVariables(href)
if err != nil {
return nil, err
}
actionURL, err := act.URL(vars)
if err != nil {
return nil, err
}
_, queryParams := rsapi.IdentifyParams(act, params)
return a.BuildHTTPRequest("GET", actionURL.Path, "1.6", queryParams, nil)
}
|
[
"func",
"(",
"a",
"*",
"API",
")",
"BuildRequest",
"(",
"resource",
",",
"action",
",",
"href",
"string",
",",
"params",
"rsapi",
".",
"APIParams",
")",
"(",
"*",
"http",
".",
"Request",
",",
"error",
")",
"{",
"res",
",",
"ok",
":=",
"GenMetadata",
"[",
"resource",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"No resource with name '%s'\"",
",",
"resource",
")",
"\n",
"}",
"\n",
"act",
":=",
"res",
".",
"GetAction",
"(",
"action",
")",
"\n",
"if",
"act",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"No action with name '%s' on %s\"",
",",
"action",
",",
"resource",
")",
"\n",
"}",
"\n",
"vars",
",",
"err",
":=",
"res",
".",
"ExtractVariables",
"(",
"href",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"actionURL",
",",
"err",
":=",
"act",
".",
"URL",
"(",
"vars",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"_",
",",
"queryParams",
":=",
"rsapi",
".",
"IdentifyParams",
"(",
"act",
",",
"params",
")",
"\n",
"return",
"a",
".",
"BuildHTTPRequest",
"(",
"\"GET\"",
",",
"actionURL",
".",
"Path",
",",
"\"1.6\"",
",",
"queryParams",
",",
"nil",
")",
"\n",
"}"
] |
// BuildRequest builds a HTTP request from a resource name and href and an action name and
// parameters.
// It is intended for generic clients that need to consume APIs in a generic maner.
// The method builds an HTTP request that can be fed to PerformRequest.
|
[
"BuildRequest",
"builds",
"a",
"HTTP",
"request",
"from",
"a",
"resource",
"name",
"and",
"href",
"and",
"an",
"action",
"name",
"and",
"parameters",
".",
"It",
"is",
"intended",
"for",
"generic",
"clients",
"that",
"need",
"to",
"consume",
"APIs",
"in",
"a",
"generic",
"maner",
".",
"The",
"method",
"builds",
"an",
"HTTP",
"request",
"that",
"can",
"be",
"fed",
"to",
"PerformRequest",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm16/http.go#L14-L36
|
test
|
rightscale/rsc
|
ca/ca.go
|
setupMetadata
|
func setupMetadata() (result map[string]*metadata.Resource) {
result = make(map[string]*metadata.Resource)
for n, r := range cac.GenMetadata {
result[n] = r
}
return
}
|
go
|
func setupMetadata() (result map[string]*metadata.Resource) {
result = make(map[string]*metadata.Resource)
for n, r := range cac.GenMetadata {
result[n] = r
}
return
}
|
[
"func",
"setupMetadata",
"(",
")",
"(",
"result",
"map",
"[",
"string",
"]",
"*",
"metadata",
".",
"Resource",
")",
"{",
"result",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"metadata",
".",
"Resource",
")",
"\n",
"for",
"n",
",",
"r",
":=",
"range",
"cac",
".",
"GenMetadata",
"{",
"result",
"[",
"n",
"]",
"=",
"r",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// Initialize GenMetadata from each CA API generated metadata
|
[
"Initialize",
"GenMetadata",
"from",
"each",
"CA",
"API",
"generated",
"metadata"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ca/ca.go#L60-L66
|
test
|
rightscale/rsc
|
displayer.go
|
NewDisplayer
|
func NewDisplayer(resp *http.Response) (*Displayer, error) {
defer resp.Body.Close()
js, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("Failed to read response (%s)", err)
}
disp := Displayer{response: resp, body: string(js)}
if len(js) > 2 {
err = json.Unmarshal(js, &disp.RawOutput)
if err != nil {
disp.RawOutput = string(js)
}
}
return &disp, nil
}
|
go
|
func NewDisplayer(resp *http.Response) (*Displayer, error) {
defer resp.Body.Close()
js, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("Failed to read response (%s)", err)
}
disp := Displayer{response: resp, body: string(js)}
if len(js) > 2 {
err = json.Unmarshal(js, &disp.RawOutput)
if err != nil {
disp.RawOutput = string(js)
}
}
return &disp, nil
}
|
[
"func",
"NewDisplayer",
"(",
"resp",
"*",
"http",
".",
"Response",
")",
"(",
"*",
"Displayer",
",",
"error",
")",
"{",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"js",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"resp",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Failed to read response (%s)\"",
",",
"err",
")",
"\n",
"}",
"\n",
"disp",
":=",
"Displayer",
"{",
"response",
":",
"resp",
",",
"body",
":",
"string",
"(",
"js",
")",
"}",
"\n",
"if",
"len",
"(",
"js",
")",
">",
"2",
"{",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"js",
",",
"&",
"disp",
".",
"RawOutput",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"disp",
".",
"RawOutput",
"=",
"string",
"(",
"js",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"&",
"disp",
",",
"nil",
"\n",
"}"
] |
// NewDisplayer creates a new displayer using the response body.
|
[
"NewDisplayer",
"creates",
"a",
"new",
"displayer",
"using",
"the",
"response",
"body",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/displayer.go#L22-L36
|
test
|
rightscale/rsc
|
displayer.go
|
ApplySingleExtract
|
func (d *Displayer) ApplySingleExtract(extract string) error {
if err := d.ApplyExtract(extract, true); err != nil {
return err
}
outputs := d.RawOutput.([]interface{})
if len(outputs) != 1 {
d.RawOutput = nil
return fmt.Errorf("JSON selector '%s' returned %d instead of one value",
extract, len(outputs))
}
if len(outputs) == 0 {
d.RawOutput = ""
} else {
switch v := outputs[0].(type) {
case nil:
d.RawOutput = ""
case float64, bool:
d.RawOutput = fmt.Sprint(v)
case string:
d.RawOutput = v
default:
d.RawOutput = v
}
d.RawOutput = outputs[0]
}
return nil
}
|
go
|
func (d *Displayer) ApplySingleExtract(extract string) error {
if err := d.ApplyExtract(extract, true); err != nil {
return err
}
outputs := d.RawOutput.([]interface{})
if len(outputs) != 1 {
d.RawOutput = nil
return fmt.Errorf("JSON selector '%s' returned %d instead of one value",
extract, len(outputs))
}
if len(outputs) == 0 {
d.RawOutput = ""
} else {
switch v := outputs[0].(type) {
case nil:
d.RawOutput = ""
case float64, bool:
d.RawOutput = fmt.Sprint(v)
case string:
d.RawOutput = v
default:
d.RawOutput = v
}
d.RawOutput = outputs[0]
}
return nil
}
|
[
"func",
"(",
"d",
"*",
"Displayer",
")",
"ApplySingleExtract",
"(",
"extract",
"string",
")",
"error",
"{",
"if",
"err",
":=",
"d",
".",
"ApplyExtract",
"(",
"extract",
",",
"true",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"outputs",
":=",
"d",
".",
"RawOutput",
".",
"(",
"[",
"]",
"interface",
"{",
"}",
")",
"\n",
"if",
"len",
"(",
"outputs",
")",
"!=",
"1",
"{",
"d",
".",
"RawOutput",
"=",
"nil",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"JSON selector '%s' returned %d instead of one value\"",
",",
"extract",
",",
"len",
"(",
"outputs",
")",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"outputs",
")",
"==",
"0",
"{",
"d",
".",
"RawOutput",
"=",
"\"\"",
"\n",
"}",
"else",
"{",
"switch",
"v",
":=",
"outputs",
"[",
"0",
"]",
".",
"(",
"type",
")",
"{",
"case",
"nil",
":",
"d",
".",
"RawOutput",
"=",
"\"\"",
"\n",
"case",
"float64",
",",
"bool",
":",
"d",
".",
"RawOutput",
"=",
"fmt",
".",
"Sprint",
"(",
"v",
")",
"\n",
"case",
"string",
":",
"d",
".",
"RawOutput",
"=",
"v",
"\n",
"default",
":",
"d",
".",
"RawOutput",
"=",
"v",
"\n",
"}",
"\n",
"d",
".",
"RawOutput",
"=",
"outputs",
"[",
"0",
"]",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// ApplySingleExtract applies the given JSON selector and returns the results.
// It's an error if the selector yields more than one value.
|
[
"ApplySingleExtract",
"applies",
"the",
"given",
"JSON",
"selector",
"and",
"returns",
"the",
"results",
".",
"It",
"s",
"an",
"error",
"if",
"the",
"selector",
"yields",
"more",
"than",
"one",
"value",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/displayer.go#L40-L66
|
test
|
rightscale/rsc
|
displayer.go
|
ApplyExtract
|
func (d *Displayer) ApplyExtract(selector string, js bool) error {
parser, err := jsonselect.CreateParserFromString(d.body)
if err != nil {
return fmt.Errorf("Failed to load response JSON: %s, JSON was:\n%s", err, d.body)
}
outputs, err := parser.GetValues(selector)
if !js {
out := ""
for _, o := range outputs {
b, _ := json.Marshal(o)
out += string(b) + "\n"
}
d.RawOutput = out
} else {
d.RawOutput = outputs
}
if err != nil {
return fmt.Errorf("Failed to apply JSON selector '%s' to response: %s, JSON was:\n%s",
selector, err, d.body)
}
return nil
}
|
go
|
func (d *Displayer) ApplyExtract(selector string, js bool) error {
parser, err := jsonselect.CreateParserFromString(d.body)
if err != nil {
return fmt.Errorf("Failed to load response JSON: %s, JSON was:\n%s", err, d.body)
}
outputs, err := parser.GetValues(selector)
if !js {
out := ""
for _, o := range outputs {
b, _ := json.Marshal(o)
out += string(b) + "\n"
}
d.RawOutput = out
} else {
d.RawOutput = outputs
}
if err != nil {
return fmt.Errorf("Failed to apply JSON selector '%s' to response: %s, JSON was:\n%s",
selector, err, d.body)
}
return nil
}
|
[
"func",
"(",
"d",
"*",
"Displayer",
")",
"ApplyExtract",
"(",
"selector",
"string",
",",
"js",
"bool",
")",
"error",
"{",
"parser",
",",
"err",
":=",
"jsonselect",
".",
"CreateParserFromString",
"(",
"d",
".",
"body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Failed to load response JSON: %s, JSON was:\\n%s\"",
",",
"\\n",
",",
"err",
")",
"\n",
"}",
"\n",
"d",
".",
"body",
"\n",
"outputs",
",",
"err",
":=",
"parser",
".",
"GetValues",
"(",
"selector",
")",
"\n",
"if",
"!",
"js",
"{",
"out",
":=",
"\"\"",
"\n",
"for",
"_",
",",
"o",
":=",
"range",
"outputs",
"{",
"b",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"o",
")",
"\n",
"out",
"+=",
"string",
"(",
"b",
")",
"+",
"\"\\n\"",
"\n",
"}",
"\n",
"\\n",
"\n",
"}",
"else",
"d",
".",
"RawOutput",
"=",
"out",
"\n",
"{",
"d",
".",
"RawOutput",
"=",
"outputs",
"\n",
"}",
"\n",
"}"
] |
// ApplyExtract applies selector to js.
|
[
"ApplyExtract",
"applies",
"selector",
"to",
"js",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/displayer.go#L69-L90
|
test
|
rightscale/rsc
|
displayer.go
|
ApplyHeaderExtract
|
func (d *Displayer) ApplyHeaderExtract(header string) error {
d.RawOutput = d.response.Header.Get(header)
if d.RawOutput == "" {
return fmt.Errorf("Response does not contain the '%s' header", header)
}
return nil
}
|
go
|
func (d *Displayer) ApplyHeaderExtract(header string) error {
d.RawOutput = d.response.Header.Get(header)
if d.RawOutput == "" {
return fmt.Errorf("Response does not contain the '%s' header", header)
}
return nil
}
|
[
"func",
"(",
"d",
"*",
"Displayer",
")",
"ApplyHeaderExtract",
"(",
"header",
"string",
")",
"error",
"{",
"d",
".",
"RawOutput",
"=",
"d",
".",
"response",
".",
"Header",
".",
"Get",
"(",
"header",
")",
"\n",
"if",
"d",
".",
"RawOutput",
"==",
"\"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Response does not contain the '%s' header\"",
",",
"header",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// ApplyHeaderExtract reads the value of the given header.
|
[
"ApplyHeaderExtract",
"reads",
"the",
"value",
"of",
"the",
"given",
"header",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/displayer.go#L93-L99
|
test
|
rightscale/rsc
|
displayer.go
|
Output
|
func (d *Displayer) Output() string {
output := d.RawOutput
if output == nil {
return ""
}
if outputStr, ok := d.RawOutput.(string); ok {
suffix := ""
if d.prettify {
suffix = "\n"
}
return outputStr + suffix
}
var out string
var err error
if d.prettify {
var b []byte
b, err = json.MarshalIndent(output, "", " ")
if err == nil {
out = string(b) + "\n"
}
} else {
var b []byte
b, err = json.Marshal(output)
out = string(b)
}
if err != nil {
fm := "%v"
if d.prettify {
fm += "\n"
}
return fmt.Sprintf(fm, output)
}
return out
}
|
go
|
func (d *Displayer) Output() string {
output := d.RawOutput
if output == nil {
return ""
}
if outputStr, ok := d.RawOutput.(string); ok {
suffix := ""
if d.prettify {
suffix = "\n"
}
return outputStr + suffix
}
var out string
var err error
if d.prettify {
var b []byte
b, err = json.MarshalIndent(output, "", " ")
if err == nil {
out = string(b) + "\n"
}
} else {
var b []byte
b, err = json.Marshal(output)
out = string(b)
}
if err != nil {
fm := "%v"
if d.prettify {
fm += "\n"
}
return fmt.Sprintf(fm, output)
}
return out
}
|
[
"func",
"(",
"d",
"*",
"Displayer",
")",
"Output",
"(",
")",
"string",
"{",
"output",
":=",
"d",
".",
"RawOutput",
"\n",
"if",
"output",
"==",
"nil",
"{",
"return",
"\"\"",
"\n",
"}",
"\n",
"if",
"outputStr",
",",
"ok",
":=",
"d",
".",
"RawOutput",
".",
"(",
"string",
")",
";",
"ok",
"{",
"suffix",
":=",
"\"\"",
"\n",
"if",
"d",
".",
"prettify",
"{",
"suffix",
"=",
"\"\\n\"",
"\n",
"}",
"\n",
"\\n",
"\n",
"}",
"\n",
"return",
"outputStr",
"+",
"suffix",
"\n",
"var",
"out",
"string",
"\n",
"var",
"err",
"error",
"\n",
"if",
"d",
".",
"prettify",
"{",
"var",
"b",
"[",
"]",
"byte",
"\n",
"b",
",",
"err",
"=",
"json",
".",
"MarshalIndent",
"(",
"output",
",",
"\"\"",
",",
"\" \"",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"out",
"=",
"string",
"(",
"b",
")",
"+",
"\"\\n\"",
"\n",
"}",
"\n",
"}",
"else",
"\\n",
"\n",
"{",
"var",
"b",
"[",
"]",
"byte",
"\n",
"b",
",",
"err",
"=",
"json",
".",
"Marshal",
"(",
"output",
")",
"\n",
"out",
"=",
"string",
"(",
"b",
")",
"\n",
"}",
"\n",
"}"
] |
// Output returns the current output.
|
[
"Output",
"returns",
"the",
"current",
"output",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/displayer.go#L107-L140
|
test
|
rightscale/rsc
|
gen/api15gen/api_analyzer.go
|
NewAPIAnalyzer
|
func NewAPIAnalyzer(resources map[string]interface{}, attributeTypes map[string]string) *APIAnalyzer {
return &APIAnalyzer{
rawResources: resources,
attributeTypes: attributeTypes,
rawTypes: make(map[string][]*gen.ObjectDataType),
}
}
|
go
|
func NewAPIAnalyzer(resources map[string]interface{}, attributeTypes map[string]string) *APIAnalyzer {
return &APIAnalyzer{
rawResources: resources,
attributeTypes: attributeTypes,
rawTypes: make(map[string][]*gen.ObjectDataType),
}
}
|
[
"func",
"NewAPIAnalyzer",
"(",
"resources",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"attributeTypes",
"map",
"[",
"string",
"]",
"string",
")",
"*",
"APIAnalyzer",
"{",
"return",
"&",
"APIAnalyzer",
"{",
"rawResources",
":",
"resources",
",",
"attributeTypes",
":",
"attributeTypes",
",",
"rawTypes",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"*",
"gen",
".",
"ObjectDataType",
")",
",",
"}",
"\n",
"}"
] |
// NewAPIAnalyzer is the factory method for the API analyzer
|
[
"NewAPIAnalyzer",
"is",
"the",
"factory",
"method",
"for",
"the",
"API",
"analyzer"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/api15gen/api_analyzer.go#L39-L45
|
test
|
rightscale/rsc
|
gen/api15gen/api_analyzer.go
|
Analyze
|
func (a *APIAnalyzer) Analyze() *gen.APIDescriptor {
a.AnalyzeAliases()
var descriptor = &gen.APIDescriptor{
Resources: make(map[string]*gen.Resource),
Types: make(map[string]*gen.ObjectDataType),
}
var rawResourceNames = make([]string, len(a.rawResources))
var idx = 0
for n := range a.rawResources {
rawResourceNames[idx] = n
idx++
}
sort.Strings(rawResourceNames)
for _, name := range rawResourceNames {
var resource = a.rawResources[name]
a.AnalyzeResource(name, resource, descriptor)
}
descriptor.FinalizeTypeNames(a.rawTypes)
return descriptor
}
|
go
|
func (a *APIAnalyzer) Analyze() *gen.APIDescriptor {
a.AnalyzeAliases()
var descriptor = &gen.APIDescriptor{
Resources: make(map[string]*gen.Resource),
Types: make(map[string]*gen.ObjectDataType),
}
var rawResourceNames = make([]string, len(a.rawResources))
var idx = 0
for n := range a.rawResources {
rawResourceNames[idx] = n
idx++
}
sort.Strings(rawResourceNames)
for _, name := range rawResourceNames {
var resource = a.rawResources[name]
a.AnalyzeResource(name, resource, descriptor)
}
descriptor.FinalizeTypeNames(a.rawTypes)
return descriptor
}
|
[
"func",
"(",
"a",
"*",
"APIAnalyzer",
")",
"Analyze",
"(",
")",
"*",
"gen",
".",
"APIDescriptor",
"{",
"a",
".",
"AnalyzeAliases",
"(",
")",
"\n",
"var",
"descriptor",
"=",
"&",
"gen",
".",
"APIDescriptor",
"{",
"Resources",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"gen",
".",
"Resource",
")",
",",
"Types",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"gen",
".",
"ObjectDataType",
")",
",",
"}",
"\n",
"var",
"rawResourceNames",
"=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"a",
".",
"rawResources",
")",
")",
"\n",
"var",
"idx",
"=",
"0",
"\n",
"for",
"n",
":=",
"range",
"a",
".",
"rawResources",
"{",
"rawResourceNames",
"[",
"idx",
"]",
"=",
"n",
"\n",
"idx",
"++",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"rawResourceNames",
")",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"rawResourceNames",
"{",
"var",
"resource",
"=",
"a",
".",
"rawResources",
"[",
"name",
"]",
"\n",
"a",
".",
"AnalyzeResource",
"(",
"name",
",",
"resource",
",",
"descriptor",
")",
"\n",
"}",
"\n",
"descriptor",
".",
"FinalizeTypeNames",
"(",
"a",
".",
"rawTypes",
")",
"\n",
"return",
"descriptor",
"\n",
"}"
] |
// Analyze iterate through all resources and initializes the Resources and ParamTypes fields of
// the APIAnalyzer struct accordingly.
|
[
"Analyze",
"iterate",
"through",
"all",
"resources",
"and",
"initializes",
"the",
"Resources",
"and",
"ParamTypes",
"fields",
"of",
"the",
"APIAnalyzer",
"struct",
"accordingly",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/api15gen/api_analyzer.go#L49-L68
|
test
|
rightscale/rsc
|
gen/api15gen/api_analyzer.go
|
AnalyzeAliases
|
func (a *APIAnalyzer) AnalyzeAliases() {
for from, to := range aliases {
splits := strings.SplitN(from, "#", 2)
fromResName := splits[0]
fromActionName := splits[1]
splits = strings.SplitN(to, "#", 2)
toResName := splits[0]
toActionName := splits[1]
fromRes := a.rawResources[fromResName]
fromAct := fromRes.(map[string]interface{})["methods"].(map[string]interface{})[fromActionName].(map[string]interface{})
toRes := a.rawResources[toResName]
toAct := toRes.(map[string]interface{})["methods"].(map[string]interface{})[toActionName].(map[string]interface{})
fromAct["parameters"] = toAct["parameters"]
fromAct["status_code"] = toAct["status_code"]
fromAct["access_rules"] = toAct["access_rules"]
}
}
|
go
|
func (a *APIAnalyzer) AnalyzeAliases() {
for from, to := range aliases {
splits := strings.SplitN(from, "#", 2)
fromResName := splits[0]
fromActionName := splits[1]
splits = strings.SplitN(to, "#", 2)
toResName := splits[0]
toActionName := splits[1]
fromRes := a.rawResources[fromResName]
fromAct := fromRes.(map[string]interface{})["methods"].(map[string]interface{})[fromActionName].(map[string]interface{})
toRes := a.rawResources[toResName]
toAct := toRes.(map[string]interface{})["methods"].(map[string]interface{})[toActionName].(map[string]interface{})
fromAct["parameters"] = toAct["parameters"]
fromAct["status_code"] = toAct["status_code"]
fromAct["access_rules"] = toAct["access_rules"]
}
}
|
[
"func",
"(",
"a",
"*",
"APIAnalyzer",
")",
"AnalyzeAliases",
"(",
")",
"{",
"for",
"from",
",",
"to",
":=",
"range",
"aliases",
"{",
"splits",
":=",
"strings",
".",
"SplitN",
"(",
"from",
",",
"\"#\"",
",",
"2",
")",
"\n",
"fromResName",
":=",
"splits",
"[",
"0",
"]",
"\n",
"fromActionName",
":=",
"splits",
"[",
"1",
"]",
"\n",
"splits",
"=",
"strings",
".",
"SplitN",
"(",
"to",
",",
"\"#\"",
",",
"2",
")",
"\n",
"toResName",
":=",
"splits",
"[",
"0",
"]",
"\n",
"toActionName",
":=",
"splits",
"[",
"1",
"]",
"\n",
"fromRes",
":=",
"a",
".",
"rawResources",
"[",
"fromResName",
"]",
"\n",
"fromAct",
":=",
"fromRes",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"[",
"\"methods\"",
"]",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"[",
"fromActionName",
"]",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"toRes",
":=",
"a",
".",
"rawResources",
"[",
"toResName",
"]",
"\n",
"toAct",
":=",
"toRes",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"[",
"\"methods\"",
"]",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"[",
"toActionName",
"]",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"fromAct",
"[",
"\"parameters\"",
"]",
"=",
"toAct",
"[",
"\"parameters\"",
"]",
"\n",
"fromAct",
"[",
"\"status_code\"",
"]",
"=",
"toAct",
"[",
"\"status_code\"",
"]",
"\n",
"fromAct",
"[",
"\"access_rules\"",
"]",
"=",
"toAct",
"[",
"\"access_rules\"",
"]",
"\n",
"}",
"\n",
"}"
] |
// AnalyzeAliases goes through the aliases and copies the details from original actions to the
// aliased actions. It skips the route field since we have the routes hard-coded in the
// ParseRoute function.
|
[
"AnalyzeAliases",
"goes",
"through",
"the",
"aliases",
"and",
"copies",
"the",
"details",
"from",
"original",
"actions",
"to",
"the",
"aliased",
"actions",
".",
"It",
"skips",
"the",
"route",
"field",
"since",
"we",
"have",
"the",
"routes",
"hard",
"-",
"coded",
"in",
"the",
"ParseRoute",
"function",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/api15gen/api_analyzer.go#L73-L91
|
test
|
rightscale/rsc
|
gen/api15gen/api_analyzer.go
|
LocatorFunc
|
func LocatorFunc(attributes []*gen.Attribute, name string) string {
hasLinks := false
for _, a := range attributes {
if a.FieldName == "Links" {
hasLinks = true
break
}
}
if !hasLinks {
return ""
}
return `for _, l := range r.Links {
if l["rel"] == "self" {
return api.` + name + `Locator(l["href"])
}
}
return nil`
}
|
go
|
func LocatorFunc(attributes []*gen.Attribute, name string) string {
hasLinks := false
for _, a := range attributes {
if a.FieldName == "Links" {
hasLinks = true
break
}
}
if !hasLinks {
return ""
}
return `for _, l := range r.Links {
if l["rel"] == "self" {
return api.` + name + `Locator(l["href"])
}
}
return nil`
}
|
[
"func",
"LocatorFunc",
"(",
"attributes",
"[",
"]",
"*",
"gen",
".",
"Attribute",
",",
"name",
"string",
")",
"string",
"{",
"hasLinks",
":=",
"false",
"\n",
"for",
"_",
",",
"a",
":=",
"range",
"attributes",
"{",
"if",
"a",
".",
"FieldName",
"==",
"\"Links\"",
"{",
"hasLinks",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"hasLinks",
"{",
"return",
"\"\"",
"\n",
"}",
"\n",
"return",
"`for _, l := range r.Links {\t\t\tif l[\"rel\"] == \"self\" {\t\t\t\treturn api.`",
"+",
"name",
"+",
"`Locator(l[\"href\"])\t\t\t}\t\t}\t\treturn nil`",
"\n",
"}"
] |
// LocatorFunc returns the source code for building a locator instance from a resource.
|
[
"LocatorFunc",
"returns",
"the",
"source",
"code",
"for",
"building",
"a",
"locator",
"instance",
"from",
"a",
"resource",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/api15gen/api_analyzer.go#L341-L358
|
test
|
rightscale/rsc
|
gen/api15gen/api_analyzer.go
|
ParseRoute
|
func ParseRoute(moniker string, routes []string) (pathPatterns []*gen.PathPattern) {
// :(((( some routes are empty
var paths []string
var method string
switch moniker {
case "Deployments#servers":
method, paths = "GET", []string{"/api/deployments/:id/servers"}
case "ServerArrays#current_instances":
method, paths = "GET", []string{"/api/server_arrays/:id/current_instances"}
case "ServerArrays#launch":
method, paths = "POST", []string{"/api/server_arrays/:id/launch"}
case "ServerArrays#multi_run_executable":
method, paths = "POST", []string{"/api/server_arrays/:id/multi_run_executable"}
case "ServerArrays#multi_terminate":
method, paths = "POST", []string{"/api/server_arrays/:id/multi_terminate"}
case "Servers#launch":
method, paths = "POST", []string{"/api/servers/:id/launch"}
case "Servers#terminate":
method, paths = "POST", []string{"/api/servers/:id/terminate"}
default:
for _, route := range routes {
bound := routeRegexp.FindStringIndex(route)
match := route[0:bound[0]]
method = strings.TrimRight(match[0:7], " ")
path := strings.TrimRight(match[7:], " ")
path = strings.TrimSuffix(path, "(.:format)?")
if isDeprecated(path) || isCustom(method, path) {
continue
}
paths = append(paths, path)
}
}
pathPatterns = make([]*gen.PathPattern, len(paths))
for i, p := range paths {
rx := routeVariablesRegexp.ReplaceAllLiteralString(regexp.QuoteMeta(p), `/([^/]+)`)
rx = fmt.Sprintf("^%s$", rx)
pattern := gen.PathPattern{
HTTPMethod: method,
Path: p,
Pattern: routeVariablesRegexp.ReplaceAllLiteralString(p, "/%s"),
Regexp: rx,
}
matches := routeVariablesRegexp.FindAllStringSubmatch(p, -1)
if len(matches) > 0 {
pattern.Variables = make([]string, len(matches))
for i, m := range matches {
pattern.Variables[i] = m[1]
}
}
pathPatterns[i] = &pattern
}
return
}
|
go
|
func ParseRoute(moniker string, routes []string) (pathPatterns []*gen.PathPattern) {
// :(((( some routes are empty
var paths []string
var method string
switch moniker {
case "Deployments#servers":
method, paths = "GET", []string{"/api/deployments/:id/servers"}
case "ServerArrays#current_instances":
method, paths = "GET", []string{"/api/server_arrays/:id/current_instances"}
case "ServerArrays#launch":
method, paths = "POST", []string{"/api/server_arrays/:id/launch"}
case "ServerArrays#multi_run_executable":
method, paths = "POST", []string{"/api/server_arrays/:id/multi_run_executable"}
case "ServerArrays#multi_terminate":
method, paths = "POST", []string{"/api/server_arrays/:id/multi_terminate"}
case "Servers#launch":
method, paths = "POST", []string{"/api/servers/:id/launch"}
case "Servers#terminate":
method, paths = "POST", []string{"/api/servers/:id/terminate"}
default:
for _, route := range routes {
bound := routeRegexp.FindStringIndex(route)
match := route[0:bound[0]]
method = strings.TrimRight(match[0:7], " ")
path := strings.TrimRight(match[7:], " ")
path = strings.TrimSuffix(path, "(.:format)?")
if isDeprecated(path) || isCustom(method, path) {
continue
}
paths = append(paths, path)
}
}
pathPatterns = make([]*gen.PathPattern, len(paths))
for i, p := range paths {
rx := routeVariablesRegexp.ReplaceAllLiteralString(regexp.QuoteMeta(p), `/([^/]+)`)
rx = fmt.Sprintf("^%s$", rx)
pattern := gen.PathPattern{
HTTPMethod: method,
Path: p,
Pattern: routeVariablesRegexp.ReplaceAllLiteralString(p, "/%s"),
Regexp: rx,
}
matches := routeVariablesRegexp.FindAllStringSubmatch(p, -1)
if len(matches) > 0 {
pattern.Variables = make([]string, len(matches))
for i, m := range matches {
pattern.Variables[i] = m[1]
}
}
pathPatterns[i] = &pattern
}
return
}
|
[
"func",
"ParseRoute",
"(",
"moniker",
"string",
",",
"routes",
"[",
"]",
"string",
")",
"(",
"pathPatterns",
"[",
"]",
"*",
"gen",
".",
"PathPattern",
")",
"{",
"var",
"paths",
"[",
"]",
"string",
"\n",
"var",
"method",
"string",
"\n",
"switch",
"moniker",
"{",
"case",
"\"Deployments#servers\"",
":",
"method",
",",
"paths",
"=",
"\"GET\"",
",",
"[",
"]",
"string",
"{",
"\"/api/deployments/:id/servers\"",
"}",
"\n",
"case",
"\"ServerArrays#current_instances\"",
":",
"method",
",",
"paths",
"=",
"\"GET\"",
",",
"[",
"]",
"string",
"{",
"\"/api/server_arrays/:id/current_instances\"",
"}",
"\n",
"case",
"\"ServerArrays#launch\"",
":",
"method",
",",
"paths",
"=",
"\"POST\"",
",",
"[",
"]",
"string",
"{",
"\"/api/server_arrays/:id/launch\"",
"}",
"\n",
"case",
"\"ServerArrays#multi_run_executable\"",
":",
"method",
",",
"paths",
"=",
"\"POST\"",
",",
"[",
"]",
"string",
"{",
"\"/api/server_arrays/:id/multi_run_executable\"",
"}",
"\n",
"case",
"\"ServerArrays#multi_terminate\"",
":",
"method",
",",
"paths",
"=",
"\"POST\"",
",",
"[",
"]",
"string",
"{",
"\"/api/server_arrays/:id/multi_terminate\"",
"}",
"\n",
"case",
"\"Servers#launch\"",
":",
"method",
",",
"paths",
"=",
"\"POST\"",
",",
"[",
"]",
"string",
"{",
"\"/api/servers/:id/launch\"",
"}",
"\n",
"case",
"\"Servers#terminate\"",
":",
"method",
",",
"paths",
"=",
"\"POST\"",
",",
"[",
"]",
"string",
"{",
"\"/api/servers/:id/terminate\"",
"}",
"\n",
"default",
":",
"for",
"_",
",",
"route",
":=",
"range",
"routes",
"{",
"bound",
":=",
"routeRegexp",
".",
"FindStringIndex",
"(",
"route",
")",
"\n",
"match",
":=",
"route",
"[",
"0",
":",
"bound",
"[",
"0",
"]",
"]",
"\n",
"method",
"=",
"strings",
".",
"TrimRight",
"(",
"match",
"[",
"0",
":",
"7",
"]",
",",
"\" \"",
")",
"\n",
"path",
":=",
"strings",
".",
"TrimRight",
"(",
"match",
"[",
"7",
":",
"]",
",",
"\" \"",
")",
"\n",
"path",
"=",
"strings",
".",
"TrimSuffix",
"(",
"path",
",",
"\"(.:format)?\"",
")",
"\n",
"if",
"isDeprecated",
"(",
"path",
")",
"||",
"isCustom",
"(",
"method",
",",
"path",
")",
"{",
"continue",
"\n",
"}",
"\n",
"paths",
"=",
"append",
"(",
"paths",
",",
"path",
")",
"\n",
"}",
"\n",
"}",
"\n",
"pathPatterns",
"=",
"make",
"(",
"[",
"]",
"*",
"gen",
".",
"PathPattern",
",",
"len",
"(",
"paths",
")",
")",
"\n",
"for",
"i",
",",
"p",
":=",
"range",
"paths",
"{",
"rx",
":=",
"routeVariablesRegexp",
".",
"ReplaceAllLiteralString",
"(",
"regexp",
".",
"QuoteMeta",
"(",
"p",
")",
",",
"`/([^/]+)`",
")",
"\n",
"rx",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"^%s$\"",
",",
"rx",
")",
"\n",
"pattern",
":=",
"gen",
".",
"PathPattern",
"{",
"HTTPMethod",
":",
"method",
",",
"Path",
":",
"p",
",",
"Pattern",
":",
"routeVariablesRegexp",
".",
"ReplaceAllLiteralString",
"(",
"p",
",",
"\"/%s\"",
")",
",",
"Regexp",
":",
"rx",
",",
"}",
"\n",
"matches",
":=",
"routeVariablesRegexp",
".",
"FindAllStringSubmatch",
"(",
"p",
",",
"-",
"1",
")",
"\n",
"if",
"len",
"(",
"matches",
")",
">",
"0",
"{",
"pattern",
".",
"Variables",
"=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"matches",
")",
")",
"\n",
"for",
"i",
",",
"m",
":=",
"range",
"matches",
"{",
"pattern",
".",
"Variables",
"[",
"i",
"]",
"=",
"m",
"[",
"1",
"]",
"\n",
"}",
"\n",
"}",
"\n",
"pathPatterns",
"[",
"i",
"]",
"=",
"&",
"pattern",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// ParseRoute parses a API 1.5 route and returns corresponding path patterns.
|
[
"ParseRoute",
"parses",
"a",
"API",
"1",
".",
"5",
"route",
"and",
"returns",
"corresponding",
"path",
"patterns",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/api15gen/api_analyzer.go#L361-L413
|
test
|
rightscale/rsc
|
gen/api15gen/api_analyzer.go
|
isDeprecated
|
func isDeprecated(path string) bool {
return strings.Contains(path, "/api/session") && !strings.Contains(path, "/api/sessions")
}
|
go
|
func isDeprecated(path string) bool {
return strings.Contains(path, "/api/session") && !strings.Contains(path, "/api/sessions")
}
|
[
"func",
"isDeprecated",
"(",
"path",
"string",
")",
"bool",
"{",
"return",
"strings",
".",
"Contains",
"(",
"path",
",",
"\"/api/session\"",
")",
"&&",
"!",
"strings",
".",
"Contains",
"(",
"path",
",",
"\"/api/sessions\"",
")",
"\n",
"}"
] |
// true if path is for a deprecated API
|
[
"true",
"if",
"path",
"is",
"for",
"a",
"deprecated",
"API"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/api15gen/api_analyzer.go#L416-L418
|
test
|
rightscale/rsc
|
gen/api15gen/api_analyzer.go
|
isQueryParam
|
func isQueryParam(a, n string) bool {
return n == "view" || n == "filter" || (a == "index" && (n == "with_deleted" || n == "with_inherited" || n == "latest_only" || n == "lineage"))
}
|
go
|
func isQueryParam(a, n string) bool {
return n == "view" || n == "filter" || (a == "index" && (n == "with_deleted" || n == "with_inherited" || n == "latest_only" || n == "lineage"))
}
|
[
"func",
"isQueryParam",
"(",
"a",
",",
"n",
"string",
")",
"bool",
"{",
"return",
"n",
"==",
"\"view\"",
"||",
"n",
"==",
"\"filter\"",
"||",
"(",
"a",
"==",
"\"index\"",
"&&",
"(",
"n",
"==",
"\"with_deleted\"",
"||",
"n",
"==",
"\"with_inherited\"",
"||",
"n",
"==",
"\"latest_only\"",
"||",
"n",
"==",
"\"lineage\"",
")",
")",
"\n",
"}"
] |
// Heuristic to determine whether given param is a query string param
// For now only consider view and filter...
|
[
"Heuristic",
"to",
"determine",
"whether",
"given",
"param",
"is",
"a",
"query",
"string",
"param",
"For",
"now",
"only",
"consider",
"view",
"and",
"filter",
"..."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/api15gen/api_analyzer.go#L427-L429
|
test
|
rightscale/rsc
|
gen/api15gen/api_analyzer.go
|
isPathParam
|
func isPathParam(p string, pathPatterns []*gen.PathPattern) bool {
for _, pattern := range pathPatterns {
for _, v := range pattern.Variables {
if p == v {
return true
}
}
}
return false
}
|
go
|
func isPathParam(p string, pathPatterns []*gen.PathPattern) bool {
for _, pattern := range pathPatterns {
for _, v := range pattern.Variables {
if p == v {
return true
}
}
}
return false
}
|
[
"func",
"isPathParam",
"(",
"p",
"string",
",",
"pathPatterns",
"[",
"]",
"*",
"gen",
".",
"PathPattern",
")",
"bool",
"{",
"for",
"_",
",",
"pattern",
":=",
"range",
"pathPatterns",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"pattern",
".",
"Variables",
"{",
"if",
"p",
"==",
"v",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// Look in given path patterns to chek whether given parameter name corresponds to a variable
// name.
|
[
"Look",
"in",
"given",
"path",
"patterns",
"to",
"chek",
"whether",
"given",
"parameter",
"name",
"corresponds",
"to",
"a",
"variable",
"name",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/api15gen/api_analyzer.go#L433-L442
|
test
|
rightscale/rsc
|
cm15/examples/auditail/main.go
|
fetchAuditEntries
|
func fetchAuditEntries(client *cm15.API, filterEmail string) ([]*cm15.AuditEntry, error) {
auditLocator := client.AuditEntryLocator("/api/audit_entries")
var apiParams = rsapi.APIParams{"filter": []string{"user_email==" + filterEmail}}
auditEntries, err := auditLocator.Index(
tomorrow(), // End date
"100", // Limit
yesterday(), // Start date
apiParams,
)
if err != nil {
return auditEntries, err
}
return auditEntries, nil
}
|
go
|
func fetchAuditEntries(client *cm15.API, filterEmail string) ([]*cm15.AuditEntry, error) {
auditLocator := client.AuditEntryLocator("/api/audit_entries")
var apiParams = rsapi.APIParams{"filter": []string{"user_email==" + filterEmail}}
auditEntries, err := auditLocator.Index(
tomorrow(), // End date
"100", // Limit
yesterday(), // Start date
apiParams,
)
if err != nil {
return auditEntries, err
}
return auditEntries, nil
}
|
[
"func",
"fetchAuditEntries",
"(",
"client",
"*",
"cm15",
".",
"API",
",",
"filterEmail",
"string",
")",
"(",
"[",
"]",
"*",
"cm15",
".",
"AuditEntry",
",",
"error",
")",
"{",
"auditLocator",
":=",
"client",
".",
"AuditEntryLocator",
"(",
"\"/api/audit_entries\"",
")",
"\n",
"var",
"apiParams",
"=",
"rsapi",
".",
"APIParams",
"{",
"\"filter\"",
":",
"[",
"]",
"string",
"{",
"\"user_email==\"",
"+",
"filterEmail",
"}",
"}",
"\n",
"auditEntries",
",",
"err",
":=",
"auditLocator",
".",
"Index",
"(",
"tomorrow",
"(",
")",
",",
"\"100\"",
",",
"yesterday",
"(",
")",
",",
"apiParams",
",",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"auditEntries",
",",
"err",
"\n",
"}",
"\n",
"return",
"auditEntries",
",",
"nil",
"\n",
"}"
] |
// Make an API call and fetch the audit entries matching specified criteria
|
[
"Make",
"an",
"API",
"call",
"and",
"fetch",
"the",
"audit",
"entries",
"matching",
"specified",
"criteria"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/examples/auditail/main.go#L72-L85
|
test
|
rightscale/rsc
|
cm15/examples/auditail/main.go
|
formatTime
|
func formatTime(tm time.Time) string {
year, month, date := tm.Date()
return time.Date(year, month, date, 0, 0, 0, 0, time.UTC).Format("2006/01/02 15:04:05 -0700")
}
|
go
|
func formatTime(tm time.Time) string {
year, month, date := tm.Date()
return time.Date(year, month, date, 0, 0, 0, 0, time.UTC).Format("2006/01/02 15:04:05 -0700")
}
|
[
"func",
"formatTime",
"(",
"tm",
"time",
".",
"Time",
")",
"string",
"{",
"year",
",",
"month",
",",
"date",
":=",
"tm",
".",
"Date",
"(",
")",
"\n",
"return",
"time",
".",
"Date",
"(",
"year",
",",
"month",
",",
"date",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"time",
".",
"UTC",
")",
".",
"Format",
"(",
"\"2006/01/02 15:04:05 -0700\"",
")",
"\n",
"}"
] |
// Returns time in RightScale API supported format
|
[
"Returns",
"time",
"in",
"RightScale",
"API",
"supported",
"format"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/examples/auditail/main.go#L98-L101
|
test
|
rightscale/rsc
|
cm15/examples/auditail/main.go
|
printAudits
|
func printAudits(entries []*cm15.AuditEntry) {
for _, a := range entries {
fmt.Printf("[%v] <%v>: %v\n", a.UpdatedAt, a.UserEmail, a.Summary)
}
}
|
go
|
func printAudits(entries []*cm15.AuditEntry) {
for _, a := range entries {
fmt.Printf("[%v] <%v>: %v\n", a.UpdatedAt, a.UserEmail, a.Summary)
}
}
|
[
"func",
"printAudits",
"(",
"entries",
"[",
"]",
"*",
"cm15",
".",
"AuditEntry",
")",
"{",
"for",
"_",
",",
"a",
":=",
"range",
"entries",
"{",
"fmt",
".",
"Printf",
"(",
"\"[%v] <%v>: %v\\n\"",
",",
"\\n",
",",
"a",
".",
"UpdatedAt",
",",
"a",
".",
"UserEmail",
")",
"\n",
"}",
"\n",
"}"
] |
// Prints the audit entries to console
|
[
"Prints",
"the",
"audit",
"entries",
"to",
"console"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/examples/auditail/main.go#L104-L108
|
test
|
rightscale/rsc
|
cm15/examples/auditail/main.go
|
extractUnique
|
func extractUnique(oldEntries, newEntries []*cm15.AuditEntry) []*cm15.AuditEntry {
var uniqueEntries = make([]*cm15.AuditEntry, 0)
var oldHrefs = make([]string, len(oldEntries))
for i, e := range oldEntries {
oldHrefs[i] = getHref(e)
}
for _, newEntry := range newEntries {
if !stringInSlice(getHref(newEntry), oldHrefs) {
uniqueEntries = append(uniqueEntries, newEntry)
}
}
return uniqueEntries
}
|
go
|
func extractUnique(oldEntries, newEntries []*cm15.AuditEntry) []*cm15.AuditEntry {
var uniqueEntries = make([]*cm15.AuditEntry, 0)
var oldHrefs = make([]string, len(oldEntries))
for i, e := range oldEntries {
oldHrefs[i] = getHref(e)
}
for _, newEntry := range newEntries {
if !stringInSlice(getHref(newEntry), oldHrefs) {
uniqueEntries = append(uniqueEntries, newEntry)
}
}
return uniqueEntries
}
|
[
"func",
"extractUnique",
"(",
"oldEntries",
",",
"newEntries",
"[",
"]",
"*",
"cm15",
".",
"AuditEntry",
")",
"[",
"]",
"*",
"cm15",
".",
"AuditEntry",
"{",
"var",
"uniqueEntries",
"=",
"make",
"(",
"[",
"]",
"*",
"cm15",
".",
"AuditEntry",
",",
"0",
")",
"\n",
"var",
"oldHrefs",
"=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"oldEntries",
")",
")",
"\n",
"for",
"i",
",",
"e",
":=",
"range",
"oldEntries",
"{",
"oldHrefs",
"[",
"i",
"]",
"=",
"getHref",
"(",
"e",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"newEntry",
":=",
"range",
"newEntries",
"{",
"if",
"!",
"stringInSlice",
"(",
"getHref",
"(",
"newEntry",
")",
",",
"oldHrefs",
")",
"{",
"uniqueEntries",
"=",
"append",
"(",
"uniqueEntries",
",",
"newEntry",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"uniqueEntries",
"\n",
"}"
] |
// Extract unique audit entries from the newly received list by comparing the href of audit entries
// in the old list.
|
[
"Extract",
"unique",
"audit",
"entries",
"from",
"the",
"newly",
"received",
"list",
"by",
"comparing",
"the",
"href",
"of",
"audit",
"entries",
"in",
"the",
"old",
"list",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/examples/auditail/main.go#L112-L124
|
test
|
rightscale/rsc
|
cm15/examples/auditail/main.go
|
getHref
|
func getHref(entry *cm15.AuditEntry) string {
var href string
for _, link := range entry.Links {
if link["rel"] == "self" {
href = link["href"]
break
}
}
return href
}
|
go
|
func getHref(entry *cm15.AuditEntry) string {
var href string
for _, link := range entry.Links {
if link["rel"] == "self" {
href = link["href"]
break
}
}
return href
}
|
[
"func",
"getHref",
"(",
"entry",
"*",
"cm15",
".",
"AuditEntry",
")",
"string",
"{",
"var",
"href",
"string",
"\n",
"for",
"_",
",",
"link",
":=",
"range",
"entry",
".",
"Links",
"{",
"if",
"link",
"[",
"\"rel\"",
"]",
"==",
"\"self\"",
"{",
"href",
"=",
"link",
"[",
"\"href\"",
"]",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"href",
"\n",
"}"
] |
// Get the href of an audit entry from the Links attribute by inspecting the self link
|
[
"Get",
"the",
"href",
"of",
"an",
"audit",
"entry",
"from",
"the",
"Links",
"attribute",
"by",
"inspecting",
"the",
"self",
"link"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/examples/auditail/main.go#L127-L136
|
test
|
rightscale/rsc
|
cm15/examples/auditail/main.go
|
fail
|
func fail(format string, v ...interface{}) {
if !strings.HasSuffix(format, "\n") {
format += "\n"
}
fmt.Println(fmt.Sprintf(format, v...))
os.Exit(1)
}
|
go
|
func fail(format string, v ...interface{}) {
if !strings.HasSuffix(format, "\n") {
format += "\n"
}
fmt.Println(fmt.Sprintf(format, v...))
os.Exit(1)
}
|
[
"func",
"fail",
"(",
"format",
"string",
",",
"v",
"...",
"interface",
"{",
"}",
")",
"{",
"if",
"!",
"strings",
".",
"HasSuffix",
"(",
"format",
",",
"\"\\n\"",
")",
"\\n",
"\n",
"{",
"format",
"+=",
"\"\\n\"",
"\n",
"}",
"\n",
"\\n",
"\n",
"}"
] |
// Print error message and exit with code 1
|
[
"Print",
"error",
"message",
"and",
"exit",
"with",
"code",
"1"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/cm15/examples/auditail/main.go#L149-L155
|
test
|
rightscale/rsc
|
gen/writers/helpers.go
|
parameters
|
func parameters(a *gen.Action) string {
var m = a.MandatoryParams()
var hasOptional = a.HasOptionalParams()
var countParams = len(m)
if hasOptional {
countParams++
}
var params = make([]string, countParams)
for i, param := range m {
params[i] = fmt.Sprintf("%s %s", fixReserved(param.VarName), param.Signature())
}
if hasOptional {
params[countParams-1] = "options rsapi.APIParams"
}
return strings.Join(params, ", ")
}
|
go
|
func parameters(a *gen.Action) string {
var m = a.MandatoryParams()
var hasOptional = a.HasOptionalParams()
var countParams = len(m)
if hasOptional {
countParams++
}
var params = make([]string, countParams)
for i, param := range m {
params[i] = fmt.Sprintf("%s %s", fixReserved(param.VarName), param.Signature())
}
if hasOptional {
params[countParams-1] = "options rsapi.APIParams"
}
return strings.Join(params, ", ")
}
|
[
"func",
"parameters",
"(",
"a",
"*",
"gen",
".",
"Action",
")",
"string",
"{",
"var",
"m",
"=",
"a",
".",
"MandatoryParams",
"(",
")",
"\n",
"var",
"hasOptional",
"=",
"a",
".",
"HasOptionalParams",
"(",
")",
"\n",
"var",
"countParams",
"=",
"len",
"(",
"m",
")",
"\n",
"if",
"hasOptional",
"{",
"countParams",
"++",
"\n",
"}",
"\n",
"var",
"params",
"=",
"make",
"(",
"[",
"]",
"string",
",",
"countParams",
")",
"\n",
"for",
"i",
",",
"param",
":=",
"range",
"m",
"{",
"params",
"[",
"i",
"]",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%s %s\"",
",",
"fixReserved",
"(",
"param",
".",
"VarName",
")",
",",
"param",
".",
"Signature",
"(",
")",
")",
"\n",
"}",
"\n",
"if",
"hasOptional",
"{",
"params",
"[",
"countParams",
"-",
"1",
"]",
"=",
"\"options rsapi.APIParams\"",
"\n",
"}",
"\n",
"return",
"strings",
".",
"Join",
"(",
"params",
",",
"\", \"",
")",
"\n",
"}"
] |
// Serialize action parameters
|
[
"Serialize",
"action",
"parameters"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/writers/helpers.go#L90-L106
|
test
|
rightscale/rsc
|
gen/writers/helpers.go
|
paramsInitializer
|
func paramsInitializer(action *gen.Action, location int, varName string) string {
var fields []string
var optionals []*gen.ActionParam
varName = fixReserved(varName)
for _, param := range action.Params {
if param.Location != location {
continue
}
if param.Mandatory {
name := param.Name
if location == 1 { // QueryParam
name = param.QueryName
}
fields = append(fields, fmt.Sprintf("\"%s\": %s,", name, fixReserved(param.VarName)))
} else {
optionals = append(optionals, param)
}
}
if len(fields) == 0 && len(optionals) == 0 {
return ""
}
var paramsDecl = fmt.Sprintf("rsapi.APIParams{\n%s\n}", strings.Join(fields, "\n\t"))
if len(optionals) == 0 {
return fmt.Sprintf("\n%s = %s", varName, paramsDecl)
}
var inits = make([]string, len(optionals))
for i, opt := range optionals {
name := opt.Name
if location == 1 { // QueryParam
name = opt.QueryName
}
inits[i] = fmt.Sprintf("\tvar %sOpt = options[\"%s\"]\n\tif %sOpt != nil {\n\t\t%s[\"%s\"] = %sOpt\n\t}",
opt.VarName, opt.Name, opt.VarName, varName, name, opt.VarName)
}
var paramsInits = strings.Join(inits, "\n\t")
return fmt.Sprintf("\n%s = %s\n%s", varName, paramsDecl, paramsInits)
}
|
go
|
func paramsInitializer(action *gen.Action, location int, varName string) string {
var fields []string
var optionals []*gen.ActionParam
varName = fixReserved(varName)
for _, param := range action.Params {
if param.Location != location {
continue
}
if param.Mandatory {
name := param.Name
if location == 1 { // QueryParam
name = param.QueryName
}
fields = append(fields, fmt.Sprintf("\"%s\": %s,", name, fixReserved(param.VarName)))
} else {
optionals = append(optionals, param)
}
}
if len(fields) == 0 && len(optionals) == 0 {
return ""
}
var paramsDecl = fmt.Sprintf("rsapi.APIParams{\n%s\n}", strings.Join(fields, "\n\t"))
if len(optionals) == 0 {
return fmt.Sprintf("\n%s = %s", varName, paramsDecl)
}
var inits = make([]string, len(optionals))
for i, opt := range optionals {
name := opt.Name
if location == 1 { // QueryParam
name = opt.QueryName
}
inits[i] = fmt.Sprintf("\tvar %sOpt = options[\"%s\"]\n\tif %sOpt != nil {\n\t\t%s[\"%s\"] = %sOpt\n\t}",
opt.VarName, opt.Name, opt.VarName, varName, name, opt.VarName)
}
var paramsInits = strings.Join(inits, "\n\t")
return fmt.Sprintf("\n%s = %s\n%s", varName, paramsDecl, paramsInits)
}
|
[
"func",
"paramsInitializer",
"(",
"action",
"*",
"gen",
".",
"Action",
",",
"location",
"int",
",",
"varName",
"string",
")",
"string",
"{",
"var",
"fields",
"[",
"]",
"string",
"\n",
"var",
"optionals",
"[",
"]",
"*",
"gen",
".",
"ActionParam",
"\n",
"varName",
"=",
"fixReserved",
"(",
"varName",
")",
"\n",
"for",
"_",
",",
"param",
":=",
"range",
"action",
".",
"Params",
"{",
"if",
"param",
".",
"Location",
"!=",
"location",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"param",
".",
"Mandatory",
"{",
"name",
":=",
"param",
".",
"Name",
"\n",
"if",
"location",
"==",
"1",
"{",
"name",
"=",
"param",
".",
"QueryName",
"\n",
"}",
"\n",
"fields",
"=",
"append",
"(",
"fields",
",",
"fmt",
".",
"Sprintf",
"(",
"\"\\\"%s\\\": %s,\"",
",",
"\\\"",
",",
"\\\"",
")",
")",
"\n",
"}",
"else",
"name",
"\n",
"}",
"\n",
"fixReserved",
"(",
"param",
".",
"VarName",
")",
"\n",
"{",
"optionals",
"=",
"append",
"(",
"optionals",
",",
"param",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"fields",
")",
"==",
"0",
"&&",
"len",
"(",
"optionals",
")",
"==",
"0",
"{",
"return",
"\"\"",
"\n",
"}",
"\n",
"var",
"paramsDecl",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"rsapi.APIParams{\\n%s\\n}\"",
",",
"\\n",
")",
"\n",
"\\n",
"\n",
"strings",
".",
"Join",
"(",
"fields",
",",
"\"\\n\\t\"",
")",
"\n",
"\\n",
"\n",
"}"
] |
// Produces code that initializes a APIParams struct with the values of parameters for the given
// action and location.
|
[
"Produces",
"code",
"that",
"initializes",
"a",
"APIParams",
"struct",
"with",
"the",
"values",
"of",
"parameters",
"for",
"the",
"given",
"action",
"and",
"location",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/writers/helpers.go#L110-L146
|
test
|
rightscale/rsc
|
gen/writers/helpers.go
|
commandLine
|
func commandLine() string {
return fmt.Sprintf("$ %s %s", os.Args[0], strings.Join(os.Args[1:], " "))
}
|
go
|
func commandLine() string {
return fmt.Sprintf("$ %s %s", os.Args[0], strings.Join(os.Args[1:], " "))
}
|
[
"func",
"commandLine",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"$ %s %s\"",
",",
"os",
".",
"Args",
"[",
"0",
"]",
",",
"strings",
".",
"Join",
"(",
"os",
".",
"Args",
"[",
"1",
":",
"]",
",",
"\" \"",
")",
")",
"\n",
"}"
] |
// Command line used to run tool
|
[
"Command",
"line",
"used",
"to",
"run",
"tool"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/writers/helpers.go#L149-L151
|
test
|
rightscale/rsc
|
gen/writers/helpers.go
|
toVerb
|
func toVerb(text string) (res string) {
res = strings.ToUpper(string(text[0])) + strings.ToLower(text[1:])
if text == "GET" || text == "POST" {
res += "Raw"
}
return
}
|
go
|
func toVerb(text string) (res string) {
res = strings.ToUpper(string(text[0])) + strings.ToLower(text[1:])
if text == "GET" || text == "POST" {
res += "Raw"
}
return
}
|
[
"func",
"toVerb",
"(",
"text",
"string",
")",
"(",
"res",
"string",
")",
"{",
"res",
"=",
"strings",
".",
"ToUpper",
"(",
"string",
"(",
"text",
"[",
"0",
"]",
")",
")",
"+",
"strings",
".",
"ToLower",
"(",
"text",
"[",
"1",
":",
"]",
")",
"\n",
"if",
"text",
"==",
"\"GET\"",
"||",
"text",
"==",
"\"POST\"",
"{",
"res",
"+=",
"\"Raw\"",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// GET => Get
|
[
"GET",
"=",
">",
"Get"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/writers/helpers.go#L174-L180
|
test
|
rightscale/rsc
|
gen/writers/helpers.go
|
escapeBackticks
|
func escapeBackticks(d string) string {
elems := strings.Split(d, "`")
return strings.Join(elems, "` + `")
}
|
go
|
func escapeBackticks(d string) string {
elems := strings.Split(d, "`")
return strings.Join(elems, "` + `")
}
|
[
"func",
"escapeBackticks",
"(",
"d",
"string",
")",
"string",
"{",
"elems",
":=",
"strings",
".",
"Split",
"(",
"d",
",",
"\"`\"",
")",
"\n",
"return",
"strings",
".",
"Join",
"(",
"elems",
",",
"\"` + `\"",
")",
"\n",
"}"
] |
// Escape ` in string to be wrapped in them
|
[
"Escape",
"in",
"string",
"to",
"be",
"wrapped",
"in",
"them"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/writers/helpers.go#L200-L203
|
test
|
rightscale/rsc
|
ss/ssc/codegen_client.go
|
AccountPreferenceLocator
|
func (api *API) AccountPreferenceLocator(href string) *AccountPreferenceLocator {
return &AccountPreferenceLocator{Href(href), api}
}
|
go
|
func (api *API) AccountPreferenceLocator(href string) *AccountPreferenceLocator {
return &AccountPreferenceLocator{Href(href), api}
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"AccountPreferenceLocator",
"(",
"href",
"string",
")",
"*",
"AccountPreferenceLocator",
"{",
"return",
"&",
"AccountPreferenceLocator",
"{",
"Href",
"(",
"href",
")",
",",
"api",
"}",
"\n",
"}"
] |
// AccountPreferenceLocator builds a locator from the given href.
|
[
"AccountPreferenceLocator",
"builds",
"a",
"locator",
"from",
"the",
"given",
"href",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ssc/codegen_client.go#L87-L89
|
test
|
rightscale/rsc
|
ss/ssc/codegen_client.go
|
ApplicationLocator
|
func (api *API) ApplicationLocator(href string) *ApplicationLocator {
return &ApplicationLocator{Href(href), api}
}
|
go
|
func (api *API) ApplicationLocator(href string) *ApplicationLocator {
return &ApplicationLocator{Href(href), api}
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"ApplicationLocator",
"(",
"href",
"string",
")",
"*",
"ApplicationLocator",
"{",
"return",
"&",
"ApplicationLocator",
"{",
"Href",
"(",
"href",
")",
",",
"api",
"}",
"\n",
"}"
] |
// ApplicationLocator builds a locator from the given href.
|
[
"ApplicationLocator",
"builds",
"a",
"locator",
"from",
"the",
"given",
"href",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ssc/codegen_client.go#L293-L295
|
test
|
rightscale/rsc
|
ss/ssc/codegen_client.go
|
EndUserLocator
|
func (api *API) EndUserLocator(href string) *EndUserLocator {
return &EndUserLocator{Href(href), api}
}
|
go
|
func (api *API) EndUserLocator(href string) *EndUserLocator {
return &EndUserLocator{Href(href), api}
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"EndUserLocator",
"(",
"href",
"string",
")",
"*",
"EndUserLocator",
"{",
"return",
"&",
"EndUserLocator",
"{",
"Href",
"(",
"href",
")",
",",
"api",
"}",
"\n",
"}"
] |
// EndUserLocator builds a locator from the given href.
|
[
"EndUserLocator",
"builds",
"a",
"locator",
"from",
"the",
"given",
"href",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ssc/codegen_client.go#L756-L758
|
test
|
rightscale/rsc
|
ss/ssc/codegen_client.go
|
NotificationRuleLocator
|
func (api *API) NotificationRuleLocator(href string) *NotificationRuleLocator {
return &NotificationRuleLocator{Href(href), api}
}
|
go
|
func (api *API) NotificationRuleLocator(href string) *NotificationRuleLocator {
return &NotificationRuleLocator{Href(href), api}
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"NotificationRuleLocator",
"(",
"href",
"string",
")",
"*",
"NotificationRuleLocator",
"{",
"return",
"&",
"NotificationRuleLocator",
"{",
"Href",
"(",
"href",
")",
",",
"api",
"}",
"\n",
"}"
] |
// NotificationRuleLocator builds a locator from the given href.
|
[
"NotificationRuleLocator",
"builds",
"a",
"locator",
"from",
"the",
"given",
"href",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ssc/codegen_client.go#L949-L951
|
test
|
rightscale/rsc
|
ss/ssc/codegen_client.go
|
UserPreferenceLocator
|
func (api *API) UserPreferenceLocator(href string) *UserPreferenceLocator {
return &UserPreferenceLocator{Href(href), api}
}
|
go
|
func (api *API) UserPreferenceLocator(href string) *UserPreferenceLocator {
return &UserPreferenceLocator{Href(href), api}
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"UserPreferenceLocator",
"(",
"href",
"string",
")",
"*",
"UserPreferenceLocator",
"{",
"return",
"&",
"UserPreferenceLocator",
"{",
"Href",
"(",
"href",
")",
",",
"api",
"}",
"\n",
"}"
] |
// UserPreferenceLocator builds a locator from the given href.
|
[
"UserPreferenceLocator",
"builds",
"a",
"locator",
"from",
"the",
"given",
"href",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ssc/codegen_client.go#L1241-L1243
|
test
|
rightscale/rsc
|
ss/ssc/codegen_client.go
|
UserPreferenceInfoLocator
|
func (api *API) UserPreferenceInfoLocator(href string) *UserPreferenceInfoLocator {
return &UserPreferenceInfoLocator{Href(href), api}
}
|
go
|
func (api *API) UserPreferenceInfoLocator(href string) *UserPreferenceInfoLocator {
return &UserPreferenceInfoLocator{Href(href), api}
}
|
[
"func",
"(",
"api",
"*",
"API",
")",
"UserPreferenceInfoLocator",
"(",
"href",
"string",
")",
"*",
"UserPreferenceInfoLocator",
"{",
"return",
"&",
"UserPreferenceInfoLocator",
"{",
"Href",
"(",
"href",
")",
",",
"api",
"}",
"\n",
"}"
] |
// UserPreferenceInfoLocator builds a locator from the given href.
|
[
"UserPreferenceInfoLocator",
"builds",
"a",
"locator",
"from",
"the",
"given",
"href",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/ss/ssc/codegen_client.go#L1487-L1489
|
test
|
rightscale/rsc
|
config.go
|
LoadConfig
|
func LoadConfig(path string) (*ClientConfig, error) {
content, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
var config ClientConfig
err = json.Unmarshal(content, &config)
if err != nil {
return nil, err
}
config.Password, err = Decrypt(config.Password)
if err != nil {
return nil, err
}
config.RefreshToken, err = Decrypt(config.RefreshToken)
return &config, err
}
|
go
|
func LoadConfig(path string) (*ClientConfig, error) {
content, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
var config ClientConfig
err = json.Unmarshal(content, &config)
if err != nil {
return nil, err
}
config.Password, err = Decrypt(config.Password)
if err != nil {
return nil, err
}
config.RefreshToken, err = Decrypt(config.RefreshToken)
return &config, err
}
|
[
"func",
"LoadConfig",
"(",
"path",
"string",
")",
"(",
"*",
"ClientConfig",
",",
"error",
")",
"{",
"content",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"var",
"config",
"ClientConfig",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"content",
",",
"&",
"config",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"config",
".",
"Password",
",",
"err",
"=",
"Decrypt",
"(",
"config",
".",
"Password",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"config",
".",
"RefreshToken",
",",
"err",
"=",
"Decrypt",
"(",
"config",
".",
"RefreshToken",
")",
"\n",
"return",
"&",
"config",
",",
"err",
"\n",
"}"
] |
// LoadConfig loads the client configuration from disk
|
[
"LoadConfig",
"loads",
"the",
"client",
"configuration",
"from",
"disk"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/config.go#L20-L36
|
test
|
rightscale/rsc
|
config.go
|
CreateConfig
|
func CreateConfig(path string) error {
config, _ := LoadConfig(path)
var emailDef, passwordDef, accountDef, hostDef, refreshTokenDef string
if config != nil {
yn := PromptConfirmation("Found existing configuration file %v, overwrite? (y/N): ", path)
if yn != "y" {
PrintSuccess("Exiting")
return nil
}
emailDef = fmt.Sprintf(" (%v)", config.Email)
accountDef = fmt.Sprintf(" (%v)", config.Account)
passwordDef = " (leave blank to leave unchanged)"
if config.LoginHost == "" {
config.LoginHost = "my.rightscale.com"
}
hostDef = fmt.Sprintf(" (%v)", config.LoginHost)
refreshTokenDef = " (leave blank to leave unchanged)"
} else {
config = &ClientConfig{}
}
fmt.Fprintf(out, "Account ID%v: ", accountDef)
var newAccount string
fmt.Fscanln(in, &newAccount)
if newAccount != "" {
a, err := strconv.Atoi(newAccount)
if err != nil {
return fmt.Errorf("Account ID must be an integer, got '%s'.", newAccount)
}
config.Account = a
}
fmt.Fprintf(out, "Login email%v: ", emailDef)
var newEmail string
fmt.Fscanln(in, &newEmail)
if newEmail != "" {
config.Email = newEmail
}
fmt.Fprintf(out, "Login password%v: ", passwordDef)
var newPassword string
fmt.Fscanln(in, &newPassword)
if newPassword != "" {
config.Password = newPassword
}
fmt.Fprintf(out, "API Login host%v: ", hostDef)
var newLoginHost string
fmt.Fscanln(in, &newLoginHost)
if newLoginHost != "" {
config.LoginHost = newLoginHost
}
fmt.Fprintf(out, "API Refresh Token%v: ", refreshTokenDef)
var newRefreshToken string
fmt.Fscanln(in, &newRefreshToken)
if newRefreshToken != "" {
config.RefreshToken = newRefreshToken
}
err := config.Save(path)
if err != nil {
return fmt.Errorf("Failed to save config: %s", err)
}
return nil
}
|
go
|
func CreateConfig(path string) error {
config, _ := LoadConfig(path)
var emailDef, passwordDef, accountDef, hostDef, refreshTokenDef string
if config != nil {
yn := PromptConfirmation("Found existing configuration file %v, overwrite? (y/N): ", path)
if yn != "y" {
PrintSuccess("Exiting")
return nil
}
emailDef = fmt.Sprintf(" (%v)", config.Email)
accountDef = fmt.Sprintf(" (%v)", config.Account)
passwordDef = " (leave blank to leave unchanged)"
if config.LoginHost == "" {
config.LoginHost = "my.rightscale.com"
}
hostDef = fmt.Sprintf(" (%v)", config.LoginHost)
refreshTokenDef = " (leave blank to leave unchanged)"
} else {
config = &ClientConfig{}
}
fmt.Fprintf(out, "Account ID%v: ", accountDef)
var newAccount string
fmt.Fscanln(in, &newAccount)
if newAccount != "" {
a, err := strconv.Atoi(newAccount)
if err != nil {
return fmt.Errorf("Account ID must be an integer, got '%s'.", newAccount)
}
config.Account = a
}
fmt.Fprintf(out, "Login email%v: ", emailDef)
var newEmail string
fmt.Fscanln(in, &newEmail)
if newEmail != "" {
config.Email = newEmail
}
fmt.Fprintf(out, "Login password%v: ", passwordDef)
var newPassword string
fmt.Fscanln(in, &newPassword)
if newPassword != "" {
config.Password = newPassword
}
fmt.Fprintf(out, "API Login host%v: ", hostDef)
var newLoginHost string
fmt.Fscanln(in, &newLoginHost)
if newLoginHost != "" {
config.LoginHost = newLoginHost
}
fmt.Fprintf(out, "API Refresh Token%v: ", refreshTokenDef)
var newRefreshToken string
fmt.Fscanln(in, &newRefreshToken)
if newRefreshToken != "" {
config.RefreshToken = newRefreshToken
}
err := config.Save(path)
if err != nil {
return fmt.Errorf("Failed to save config: %s", err)
}
return nil
}
|
[
"func",
"CreateConfig",
"(",
"path",
"string",
")",
"error",
"{",
"config",
",",
"_",
":=",
"LoadConfig",
"(",
"path",
")",
"\n",
"var",
"emailDef",
",",
"passwordDef",
",",
"accountDef",
",",
"hostDef",
",",
"refreshTokenDef",
"string",
"\n",
"if",
"config",
"!=",
"nil",
"{",
"yn",
":=",
"PromptConfirmation",
"(",
"\"Found existing configuration file %v, overwrite? (y/N): \"",
",",
"path",
")",
"\n",
"if",
"yn",
"!=",
"\"y\"",
"{",
"PrintSuccess",
"(",
"\"Exiting\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"emailDef",
"=",
"fmt",
".",
"Sprintf",
"(",
"\" (%v)\"",
",",
"config",
".",
"Email",
")",
"\n",
"accountDef",
"=",
"fmt",
".",
"Sprintf",
"(",
"\" (%v)\"",
",",
"config",
".",
"Account",
")",
"\n",
"passwordDef",
"=",
"\" (leave blank to leave unchanged)\"",
"\n",
"if",
"config",
".",
"LoginHost",
"==",
"\"\"",
"{",
"config",
".",
"LoginHost",
"=",
"\"my.rightscale.com\"",
"\n",
"}",
"\n",
"hostDef",
"=",
"fmt",
".",
"Sprintf",
"(",
"\" (%v)\"",
",",
"config",
".",
"LoginHost",
")",
"\n",
"refreshTokenDef",
"=",
"\" (leave blank to leave unchanged)\"",
"\n",
"}",
"else",
"{",
"config",
"=",
"&",
"ClientConfig",
"{",
"}",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintf",
"(",
"out",
",",
"\"Account ID%v: \"",
",",
"accountDef",
")",
"\n",
"var",
"newAccount",
"string",
"\n",
"fmt",
".",
"Fscanln",
"(",
"in",
",",
"&",
"newAccount",
")",
"\n",
"if",
"newAccount",
"!=",
"\"\"",
"{",
"a",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"newAccount",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Account ID must be an integer, got '%s'.\"",
",",
"newAccount",
")",
"\n",
"}",
"\n",
"config",
".",
"Account",
"=",
"a",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintf",
"(",
"out",
",",
"\"Login email%v: \"",
",",
"emailDef",
")",
"\n",
"var",
"newEmail",
"string",
"\n",
"fmt",
".",
"Fscanln",
"(",
"in",
",",
"&",
"newEmail",
")",
"\n",
"if",
"newEmail",
"!=",
"\"\"",
"{",
"config",
".",
"Email",
"=",
"newEmail",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintf",
"(",
"out",
",",
"\"Login password%v: \"",
",",
"passwordDef",
")",
"\n",
"var",
"newPassword",
"string",
"\n",
"fmt",
".",
"Fscanln",
"(",
"in",
",",
"&",
"newPassword",
")",
"\n",
"if",
"newPassword",
"!=",
"\"\"",
"{",
"config",
".",
"Password",
"=",
"newPassword",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintf",
"(",
"out",
",",
"\"API Login host%v: \"",
",",
"hostDef",
")",
"\n",
"var",
"newLoginHost",
"string",
"\n",
"fmt",
".",
"Fscanln",
"(",
"in",
",",
"&",
"newLoginHost",
")",
"\n",
"if",
"newLoginHost",
"!=",
"\"\"",
"{",
"config",
".",
"LoginHost",
"=",
"newLoginHost",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintf",
"(",
"out",
",",
"\"API Refresh Token%v: \"",
",",
"refreshTokenDef",
")",
"\n",
"var",
"newRefreshToken",
"string",
"\n",
"fmt",
".",
"Fscanln",
"(",
"in",
",",
"&",
"newRefreshToken",
")",
"\n",
"if",
"newRefreshToken",
"!=",
"\"\"",
"{",
"config",
".",
"RefreshToken",
"=",
"newRefreshToken",
"\n",
"}",
"\n",
"err",
":=",
"config",
".",
"Save",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Failed to save config: %s\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// CreateConfig creates a configuration file and saves it to the file at the given path.
|
[
"CreateConfig",
"creates",
"a",
"configuration",
"file",
"and",
"saves",
"it",
"to",
"the",
"file",
"at",
"the",
"given",
"path",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/config.go#L63-L129
|
test
|
rightscale/rsc
|
policy/auth.go
|
fromAPI
|
func fromAPI(api *rsapi.API) *API {
api.FileEncoding = rsapi.FileEncodingJSON
api.Host = HostFromLogin(api.Host)
api.Metadata = GenMetadata
api.VersionHeader = "Api-Version"
return &API{api}
}
|
go
|
func fromAPI(api *rsapi.API) *API {
api.FileEncoding = rsapi.FileEncodingJSON
api.Host = HostFromLogin(api.Host)
api.Metadata = GenMetadata
api.VersionHeader = "Api-Version"
return &API{api}
}
|
[
"func",
"fromAPI",
"(",
"api",
"*",
"rsapi",
".",
"API",
")",
"*",
"API",
"{",
"api",
".",
"FileEncoding",
"=",
"rsapi",
".",
"FileEncodingJSON",
"\n",
"api",
".",
"Host",
"=",
"HostFromLogin",
"(",
"api",
".",
"Host",
")",
"\n",
"api",
".",
"Metadata",
"=",
"GenMetadata",
"\n",
"api",
".",
"VersionHeader",
"=",
"\"Api-Version\"",
"\n",
"return",
"&",
"API",
"{",
"api",
"}",
"\n",
"}"
] |
// Wrap generic client into API 1.0 client
|
[
"Wrap",
"generic",
"client",
"into",
"API",
"1",
".",
"0",
"client"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/policy/auth.go#L35-L41
|
test
|
rightscale/rsc
|
policy/auth.go
|
HostFromLogin
|
func HostFromLogin(host string) string {
urlElems := strings.Split(host, ".")
hostPrefix := urlElems[0]
elems := strings.Split(hostPrefix, "-")
if len(elems) == 1 && elems[0] == "cm" {
// accommodates micromoo host inference, such as "cm.rightscale.local" => "selfservice.rightscale.local"
elems[0] = "governance"
} else if len(elems) < 2 {
// don't know how to compute this policy host; use the cm host
return host
} else {
elems[len(elems)-2] = "governance"
}
policyHostPrefix := strings.Join(elems, "-")
return strings.Join(append([]string{policyHostPrefix}, urlElems[1:]...), ".")
}
|
go
|
func HostFromLogin(host string) string {
urlElems := strings.Split(host, ".")
hostPrefix := urlElems[0]
elems := strings.Split(hostPrefix, "-")
if len(elems) == 1 && elems[0] == "cm" {
// accommodates micromoo host inference, such as "cm.rightscale.local" => "selfservice.rightscale.local"
elems[0] = "governance"
} else if len(elems) < 2 {
// don't know how to compute this policy host; use the cm host
return host
} else {
elems[len(elems)-2] = "governance"
}
policyHostPrefix := strings.Join(elems, "-")
return strings.Join(append([]string{policyHostPrefix}, urlElems[1:]...), ".")
}
|
[
"func",
"HostFromLogin",
"(",
"host",
"string",
")",
"string",
"{",
"urlElems",
":=",
"strings",
".",
"Split",
"(",
"host",
",",
"\".\"",
")",
"\n",
"hostPrefix",
":=",
"urlElems",
"[",
"0",
"]",
"\n",
"elems",
":=",
"strings",
".",
"Split",
"(",
"hostPrefix",
",",
"\"-\"",
")",
"\n",
"if",
"len",
"(",
"elems",
")",
"==",
"1",
"&&",
"elems",
"[",
"0",
"]",
"==",
"\"cm\"",
"{",
"elems",
"[",
"0",
"]",
"=",
"\"governance\"",
"\n",
"}",
"else",
"if",
"len",
"(",
"elems",
")",
"<",
"2",
"{",
"return",
"host",
"\n",
"}",
"else",
"{",
"elems",
"[",
"len",
"(",
"elems",
")",
"-",
"2",
"]",
"=",
"\"governance\"",
"\n",
"}",
"\n",
"policyHostPrefix",
":=",
"strings",
".",
"Join",
"(",
"elems",
",",
"\"-\"",
")",
"\n",
"return",
"strings",
".",
"Join",
"(",
"append",
"(",
"[",
"]",
"string",
"{",
"policyHostPrefix",
"}",
",",
"urlElems",
"[",
"1",
":",
"]",
"...",
")",
",",
"\".\"",
")",
"\n",
"}"
] |
// HostFromLogin returns the policy endpoint from its login endpoint.
// The following isn't great but seems better than having to enter by hand.
|
[
"HostFromLogin",
"returns",
"the",
"policy",
"endpoint",
"from",
"its",
"login",
"endpoint",
".",
"The",
"following",
"isn",
"t",
"great",
"but",
"seems",
"better",
"than",
"having",
"to",
"enter",
"by",
"hand",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/policy/auth.go#L45-L61
|
test
|
rightscale/rsc
|
gen/goav2gen/param.go
|
AnalyzeParam
|
func (a *APIAnalyzer) AnalyzeParam(ec EvalCtx, p *Parameter) *gen.ActionParam {
location, ok := loc[p.In]
if !ok {
location = -1
}
ap := &gen.ActionParam{
Name: p.Name,
QueryName: p.Name,
Description: cleanDescription(p.Description),
VarName: toVarName(p.Name),
Location: location,
Mandatory: p.Required,
NonBlank: p.Required || p.Pattern != "",
Regexp: p.Pattern,
ValidValues: p.Enum,
}
if p.Schema != nil {
ap.Type = a.typeForRef(ec, p.Schema)
} else {
ap.Type = basicType(p.Type)
}
return ap
}
|
go
|
func (a *APIAnalyzer) AnalyzeParam(ec EvalCtx, p *Parameter) *gen.ActionParam {
location, ok := loc[p.In]
if !ok {
location = -1
}
ap := &gen.ActionParam{
Name: p.Name,
QueryName: p.Name,
Description: cleanDescription(p.Description),
VarName: toVarName(p.Name),
Location: location,
Mandatory: p.Required,
NonBlank: p.Required || p.Pattern != "",
Regexp: p.Pattern,
ValidValues: p.Enum,
}
if p.Schema != nil {
ap.Type = a.typeForRef(ec, p.Schema)
} else {
ap.Type = basicType(p.Type)
}
return ap
}
|
[
"func",
"(",
"a",
"*",
"APIAnalyzer",
")",
"AnalyzeParam",
"(",
"ec",
"EvalCtx",
",",
"p",
"*",
"Parameter",
")",
"*",
"gen",
".",
"ActionParam",
"{",
"location",
",",
"ok",
":=",
"loc",
"[",
"p",
".",
"In",
"]",
"\n",
"if",
"!",
"ok",
"{",
"location",
"=",
"-",
"1",
"\n",
"}",
"\n",
"ap",
":=",
"&",
"gen",
".",
"ActionParam",
"{",
"Name",
":",
"p",
".",
"Name",
",",
"QueryName",
":",
"p",
".",
"Name",
",",
"Description",
":",
"cleanDescription",
"(",
"p",
".",
"Description",
")",
",",
"VarName",
":",
"toVarName",
"(",
"p",
".",
"Name",
")",
",",
"Location",
":",
"location",
",",
"Mandatory",
":",
"p",
".",
"Required",
",",
"NonBlank",
":",
"p",
".",
"Required",
"||",
"p",
".",
"Pattern",
"!=",
"\"\"",
",",
"Regexp",
":",
"p",
".",
"Pattern",
",",
"ValidValues",
":",
"p",
".",
"Enum",
",",
"}",
"\n",
"if",
"p",
".",
"Schema",
"!=",
"nil",
"{",
"ap",
".",
"Type",
"=",
"a",
".",
"typeForRef",
"(",
"ec",
",",
"p",
".",
"Schema",
")",
"\n",
"}",
"else",
"{",
"ap",
".",
"Type",
"=",
"basicType",
"(",
"p",
".",
"Type",
")",
"\n",
"}",
"\n",
"return",
"ap",
"\n",
"}"
] |
// AnalyzeParam analyzes input parameters to methods
|
[
"AnalyzeParam",
"analyzes",
"input",
"parameters",
"to",
"methods"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/goav2gen/param.go#L15-L38
|
test
|
rightscale/rsc
|
gen/praxisgen/type_analysis.go
|
AnalyzeAttribute
|
func (a *APIAnalyzer) AnalyzeAttribute(name, query string, attr map[string]interface{}) (*gen.ActionParam, error) {
param := gen.ActionParam{Name: name, QueryName: query, VarName: toVarName(name)}
if d, ok := attr["description"]; ok {
param.Description = removeBlankLines(d.(string))
}
if r, ok := attr["required"]; ok {
if r.(bool) {
param.Mandatory = true
}
}
if options, ok := attr["options"]; ok {
opts, ok := options.(map[string]interface{})
if ok {
for n, o := range opts {
switch n {
case "max":
param.Max = int(o.(float64))
case "min":
param.Min = int(o.(float64))
case "regexp":
param.Regexp = o.(string)
}
}
}
}
if values, ok := attr["values"]; ok {
param.ValidValues = values.([]interface{})
}
t := attr["type"].(map[string]interface{})
dataType, err := a.AnalyzeType(t, query)
if err != nil {
return nil, err
}
param.Type = dataType
switch dataType.(type) {
case *gen.ArrayDataType:
param.QueryName += "[]"
}
return ¶m, nil
}
|
go
|
func (a *APIAnalyzer) AnalyzeAttribute(name, query string, attr map[string]interface{}) (*gen.ActionParam, error) {
param := gen.ActionParam{Name: name, QueryName: query, VarName: toVarName(name)}
if d, ok := attr["description"]; ok {
param.Description = removeBlankLines(d.(string))
}
if r, ok := attr["required"]; ok {
if r.(bool) {
param.Mandatory = true
}
}
if options, ok := attr["options"]; ok {
opts, ok := options.(map[string]interface{})
if ok {
for n, o := range opts {
switch n {
case "max":
param.Max = int(o.(float64))
case "min":
param.Min = int(o.(float64))
case "regexp":
param.Regexp = o.(string)
}
}
}
}
if values, ok := attr["values"]; ok {
param.ValidValues = values.([]interface{})
}
t := attr["type"].(map[string]interface{})
dataType, err := a.AnalyzeType(t, query)
if err != nil {
return nil, err
}
param.Type = dataType
switch dataType.(type) {
case *gen.ArrayDataType:
param.QueryName += "[]"
}
return ¶m, nil
}
|
[
"func",
"(",
"a",
"*",
"APIAnalyzer",
")",
"AnalyzeAttribute",
"(",
"name",
",",
"query",
"string",
",",
"attr",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"*",
"gen",
".",
"ActionParam",
",",
"error",
")",
"{",
"param",
":=",
"gen",
".",
"ActionParam",
"{",
"Name",
":",
"name",
",",
"QueryName",
":",
"query",
",",
"VarName",
":",
"toVarName",
"(",
"name",
")",
"}",
"\n",
"if",
"d",
",",
"ok",
":=",
"attr",
"[",
"\"description\"",
"]",
";",
"ok",
"{",
"param",
".",
"Description",
"=",
"removeBlankLines",
"(",
"d",
".",
"(",
"string",
")",
")",
"\n",
"}",
"\n",
"if",
"r",
",",
"ok",
":=",
"attr",
"[",
"\"required\"",
"]",
";",
"ok",
"{",
"if",
"r",
".",
"(",
"bool",
")",
"{",
"param",
".",
"Mandatory",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"options",
",",
"ok",
":=",
"attr",
"[",
"\"options\"",
"]",
";",
"ok",
"{",
"opts",
",",
"ok",
":=",
"options",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"if",
"ok",
"{",
"for",
"n",
",",
"o",
":=",
"range",
"opts",
"{",
"switch",
"n",
"{",
"case",
"\"max\"",
":",
"param",
".",
"Max",
"=",
"int",
"(",
"o",
".",
"(",
"float64",
")",
")",
"\n",
"case",
"\"min\"",
":",
"param",
".",
"Min",
"=",
"int",
"(",
"o",
".",
"(",
"float64",
")",
")",
"\n",
"case",
"\"regexp\"",
":",
"param",
".",
"Regexp",
"=",
"o",
".",
"(",
"string",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"values",
",",
"ok",
":=",
"attr",
"[",
"\"values\"",
"]",
";",
"ok",
"{",
"param",
".",
"ValidValues",
"=",
"values",
".",
"(",
"[",
"]",
"interface",
"{",
"}",
")",
"\n",
"}",
"\n",
"t",
":=",
"attr",
"[",
"\"type\"",
"]",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"dataType",
",",
"err",
":=",
"a",
".",
"AnalyzeType",
"(",
"t",
",",
"query",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"param",
".",
"Type",
"=",
"dataType",
"\n",
"switch",
"dataType",
".",
"(",
"type",
")",
"{",
"case",
"*",
"gen",
".",
"ArrayDataType",
":",
"param",
".",
"QueryName",
"+=",
"\"[]\"",
"\n",
"}",
"\n",
"return",
"&",
"param",
",",
"nil",
"\n",
"}"
] |
// AnalyzeAttribute analyzes an attribute creating a corresponding ActionParam.
|
[
"AnalyzeAttribute",
"analyzes",
"an",
"attribute",
"creating",
"a",
"corresponding",
"ActionParam",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/praxisgen/type_analysis.go#L17-L57
|
test
|
rightscale/rsc
|
gen/praxisgen/type_analysis.go
|
AnalyzeType
|
func (a *APIAnalyzer) AnalyzeType(typeDef map[string]interface{}, query string) (gen.DataType, error) {
n, ok := typeDef["name"].(string)
if !ok {
n = "Struct" // Assume inline struct (e.g. payload types)
}
if strings.HasSuffix(n, "FileUpload") {
// A little bit hacky but this is to make upload work with resticle
// The idea is that a type named "FileUpload" is assumed to define a multipart
// request with a file part.
// The type must define a "name" and "filename" string fields.
t, ok := a.RawTypes[n]
if !ok {
return nil, fmt.Errorf("Unknown type %s for %s", n, prettify(typeDef))
}
attrs, ok := t["attributes"]
if !ok {
return nil, fmt.Errorf("Invalid file upload type %s for %s: no attributes", n, prettify(typeDef))
}
mattrs, ok := attrs.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("Invalid file upload type %s for %s: basic type", n, prettify(typeDef))
}
_, ok = mattrs["name"]
if !ok {
return nil, fmt.Errorf("Invalid file upload type %s for %s: no name", n, prettify(typeDef))
}
_, ok = mattrs["filename"]
if !ok {
return nil, fmt.Errorf("Invalid file upload type %s for %s: no filename", n, prettify(typeDef))
}
return &gen.UploadDataType{TypeName: n}, nil
}
if isBuiltInType(n) {
n = "String"
}
var dataType gen.DataType
switch n {
case "Integer":
i := gen.BasicDataType("int")
dataType = &i
case "Float":
f := gen.BasicDataType("float64")
dataType = &f
case "String":
s := gen.BasicDataType("string")
dataType = &s
case "Boolean":
b := gen.BasicDataType("bool")
dataType = &b
case "Object":
o := gen.BasicDataType("interface{}")
dataType = &o
case "DateTime":
t := gen.BasicDataType("*time.Time") // Need pointer for case where value is null
a.descriptor.NeedTime = true
dataType = &t
case "Collection", "Ids":
member, ok := typeDef["member_attribute"].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("Missing \"member_attribute\" for %s", prettify(typeDef))
}
elemType, err := a.AnalyzeAttribute(n+"Member", query+"[]", member)
if err != nil {
return nil, fmt.Errorf("Failed to compute type of \"member_attribute\": %s", err)
}
dataType = &gen.ArrayDataType{elemType}
case "Struct":
attrs, ok := typeDef["attributes"].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("Failed to retrieve attributes of struct for %s", prettify(typeDef))
}
obj, err := a.CreateType(query, attrs)
if err != nil {
return nil, err
}
dataType = obj
case "Hash":
keys, ok := typeDef["keys"].(map[string]interface{})
if !ok {
dataType = new(gen.EnumerableDataType)
} else {
obj, err := a.CreateType(query, keys)
if err != nil {
return nil, err
}
dataType = obj
}
default:
// First check if we already analyzed that type
if t := a.Registry.GetNamedType(n); t != nil {
return t, nil
}
// No then analyze it
t, ok := a.RawTypes[n]
if !ok {
return nil, fmt.Errorf("Unknown type %s for %s", n, prettify(typeDef))
}
attrs, ok := t["attributes"]
if !ok {
// No attribute, it's a string
s := gen.BasicDataType("string")
dataType = &s
} else {
att := attrs.(map[string]interface{})
obj := a.Registry.CreateNamedType(n)
obj.Fields = make([]*gen.ActionParam, len(att))
for idx, an := range sortedKeys(att) {
at := att[an]
aq := fmt.Sprintf("%s[%s]", query, an)
ap, err := a.AnalyzeAttribute(an, aq, at.(map[string]interface{}))
if err != nil {
return nil, err
}
obj.Fields[idx] = ap
}
// We're done
dataType = obj
}
}
return dataType, nil
}
|
go
|
func (a *APIAnalyzer) AnalyzeType(typeDef map[string]interface{}, query string) (gen.DataType, error) {
n, ok := typeDef["name"].(string)
if !ok {
n = "Struct" // Assume inline struct (e.g. payload types)
}
if strings.HasSuffix(n, "FileUpload") {
// A little bit hacky but this is to make upload work with resticle
// The idea is that a type named "FileUpload" is assumed to define a multipart
// request with a file part.
// The type must define a "name" and "filename" string fields.
t, ok := a.RawTypes[n]
if !ok {
return nil, fmt.Errorf("Unknown type %s for %s", n, prettify(typeDef))
}
attrs, ok := t["attributes"]
if !ok {
return nil, fmt.Errorf("Invalid file upload type %s for %s: no attributes", n, prettify(typeDef))
}
mattrs, ok := attrs.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("Invalid file upload type %s for %s: basic type", n, prettify(typeDef))
}
_, ok = mattrs["name"]
if !ok {
return nil, fmt.Errorf("Invalid file upload type %s for %s: no name", n, prettify(typeDef))
}
_, ok = mattrs["filename"]
if !ok {
return nil, fmt.Errorf("Invalid file upload type %s for %s: no filename", n, prettify(typeDef))
}
return &gen.UploadDataType{TypeName: n}, nil
}
if isBuiltInType(n) {
n = "String"
}
var dataType gen.DataType
switch n {
case "Integer":
i := gen.BasicDataType("int")
dataType = &i
case "Float":
f := gen.BasicDataType("float64")
dataType = &f
case "String":
s := gen.BasicDataType("string")
dataType = &s
case "Boolean":
b := gen.BasicDataType("bool")
dataType = &b
case "Object":
o := gen.BasicDataType("interface{}")
dataType = &o
case "DateTime":
t := gen.BasicDataType("*time.Time") // Need pointer for case where value is null
a.descriptor.NeedTime = true
dataType = &t
case "Collection", "Ids":
member, ok := typeDef["member_attribute"].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("Missing \"member_attribute\" for %s", prettify(typeDef))
}
elemType, err := a.AnalyzeAttribute(n+"Member", query+"[]", member)
if err != nil {
return nil, fmt.Errorf("Failed to compute type of \"member_attribute\": %s", err)
}
dataType = &gen.ArrayDataType{elemType}
case "Struct":
attrs, ok := typeDef["attributes"].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("Failed to retrieve attributes of struct for %s", prettify(typeDef))
}
obj, err := a.CreateType(query, attrs)
if err != nil {
return nil, err
}
dataType = obj
case "Hash":
keys, ok := typeDef["keys"].(map[string]interface{})
if !ok {
dataType = new(gen.EnumerableDataType)
} else {
obj, err := a.CreateType(query, keys)
if err != nil {
return nil, err
}
dataType = obj
}
default:
// First check if we already analyzed that type
if t := a.Registry.GetNamedType(n); t != nil {
return t, nil
}
// No then analyze it
t, ok := a.RawTypes[n]
if !ok {
return nil, fmt.Errorf("Unknown type %s for %s", n, prettify(typeDef))
}
attrs, ok := t["attributes"]
if !ok {
// No attribute, it's a string
s := gen.BasicDataType("string")
dataType = &s
} else {
att := attrs.(map[string]interface{})
obj := a.Registry.CreateNamedType(n)
obj.Fields = make([]*gen.ActionParam, len(att))
for idx, an := range sortedKeys(att) {
at := att[an]
aq := fmt.Sprintf("%s[%s]", query, an)
ap, err := a.AnalyzeAttribute(an, aq, at.(map[string]interface{}))
if err != nil {
return nil, err
}
obj.Fields[idx] = ap
}
// We're done
dataType = obj
}
}
return dataType, nil
}
|
[
"func",
"(",
"a",
"*",
"APIAnalyzer",
")",
"AnalyzeType",
"(",
"typeDef",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"query",
"string",
")",
"(",
"gen",
".",
"DataType",
",",
"error",
")",
"{",
"n",
",",
"ok",
":=",
"typeDef",
"[",
"\"name\"",
"]",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"n",
"=",
"\"Struct\"",
"\n",
"}",
"\n",
"if",
"strings",
".",
"HasSuffix",
"(",
"n",
",",
"\"FileUpload\"",
")",
"{",
"t",
",",
"ok",
":=",
"a",
".",
"RawTypes",
"[",
"n",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Unknown type %s for %s\"",
",",
"n",
",",
"prettify",
"(",
"typeDef",
")",
")",
"\n",
"}",
"\n",
"attrs",
",",
"ok",
":=",
"t",
"[",
"\"attributes\"",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Invalid file upload type %s for %s: no attributes\"",
",",
"n",
",",
"prettify",
"(",
"typeDef",
")",
")",
"\n",
"}",
"\n",
"mattrs",
",",
"ok",
":=",
"attrs",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Invalid file upload type %s for %s: basic type\"",
",",
"n",
",",
"prettify",
"(",
"typeDef",
")",
")",
"\n",
"}",
"\n",
"_",
",",
"ok",
"=",
"mattrs",
"[",
"\"name\"",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Invalid file upload type %s for %s: no name\"",
",",
"n",
",",
"prettify",
"(",
"typeDef",
")",
")",
"\n",
"}",
"\n",
"_",
",",
"ok",
"=",
"mattrs",
"[",
"\"filename\"",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Invalid file upload type %s for %s: no filename\"",
",",
"n",
",",
"prettify",
"(",
"typeDef",
")",
")",
"\n",
"}",
"\n",
"return",
"&",
"gen",
".",
"UploadDataType",
"{",
"TypeName",
":",
"n",
"}",
",",
"nil",
"\n",
"}",
"\n",
"if",
"isBuiltInType",
"(",
"n",
")",
"{",
"n",
"=",
"\"String\"",
"\n",
"}",
"\n",
"var",
"dataType",
"gen",
".",
"DataType",
"\n",
"switch",
"n",
"{",
"case",
"\"Integer\"",
":",
"i",
":=",
"gen",
".",
"BasicDataType",
"(",
"\"int\"",
")",
"\n",
"dataType",
"=",
"&",
"i",
"\n",
"case",
"\"Float\"",
":",
"f",
":=",
"gen",
".",
"BasicDataType",
"(",
"\"float64\"",
")",
"\n",
"dataType",
"=",
"&",
"f",
"\n",
"case",
"\"String\"",
":",
"s",
":=",
"gen",
".",
"BasicDataType",
"(",
"\"string\"",
")",
"\n",
"dataType",
"=",
"&",
"s",
"\n",
"case",
"\"Boolean\"",
":",
"b",
":=",
"gen",
".",
"BasicDataType",
"(",
"\"bool\"",
")",
"\n",
"dataType",
"=",
"&",
"b",
"\n",
"case",
"\"Object\"",
":",
"o",
":=",
"gen",
".",
"BasicDataType",
"(",
"\"interface{}\"",
")",
"\n",
"dataType",
"=",
"&",
"o",
"\n",
"case",
"\"DateTime\"",
":",
"t",
":=",
"gen",
".",
"BasicDataType",
"(",
"\"*time.Time\"",
")",
"\n",
"a",
".",
"descriptor",
".",
"NeedTime",
"=",
"true",
"\n",
"dataType",
"=",
"&",
"t",
"\n",
"case",
"\"Collection\"",
",",
"\"Ids\"",
":",
"member",
",",
"ok",
":=",
"typeDef",
"[",
"\"member_attribute\"",
"]",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Missing \\\"member_attribute\\\" for %s\"",
",",
"\\\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"prettify",
"(",
"typeDef",
")",
"\n",
"elemType",
",",
"err",
":=",
"a",
".",
"AnalyzeAttribute",
"(",
"n",
"+",
"\"Member\"",
",",
"query",
"+",
"\"[]\"",
",",
"member",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Failed to compute type of \\\"member_attribute\\\": %s\"",
",",
"\\\"",
")",
"\n",
"}",
"\\\"",
"err",
"}",
"\n",
"dataType",
"=",
"&",
"gen",
".",
"ArrayDataType",
"{",
"elemType",
"}",
"\n",
"}"
] |
// AnalyzeType analyzes a type given its JSON definition.
|
[
"AnalyzeType",
"analyzes",
"a",
"type",
"given",
"its",
"JSON",
"definition",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/praxisgen/type_analysis.go#L60-L184
|
test
|
rightscale/rsc
|
gen/praxisgen/type_analysis.go
|
CreateType
|
func (a *APIAnalyzer) CreateType(query string, attributes map[string]interface{}) (*gen.ObjectDataType, error) {
name := inflect.Camelize(bracketRegexp.ReplaceAllLiteralString(query, "_") + "_struct")
obj := a.Registry.CreateInlineType(name)
obj.Fields = make([]*gen.ActionParam, len(attributes))
for idx, an := range sortedKeys(attributes) {
at := attributes[an]
var childQ string
if query == "payload" {
childQ = an
} else {
childQ = fmt.Sprintf("%s[%s]", query, an)
}
att, err := a.AnalyzeAttribute(an, childQ, at.(map[string]interface{}))
if err != nil {
return nil, fmt.Errorf("Failed to compute type of attribute %s: %s", an, err)
}
obj.Fields[idx] = att
}
return obj, nil
}
|
go
|
func (a *APIAnalyzer) CreateType(query string, attributes map[string]interface{}) (*gen.ObjectDataType, error) {
name := inflect.Camelize(bracketRegexp.ReplaceAllLiteralString(query, "_") + "_struct")
obj := a.Registry.CreateInlineType(name)
obj.Fields = make([]*gen.ActionParam, len(attributes))
for idx, an := range sortedKeys(attributes) {
at := attributes[an]
var childQ string
if query == "payload" {
childQ = an
} else {
childQ = fmt.Sprintf("%s[%s]", query, an)
}
att, err := a.AnalyzeAttribute(an, childQ, at.(map[string]interface{}))
if err != nil {
return nil, fmt.Errorf("Failed to compute type of attribute %s: %s", an, err)
}
obj.Fields[idx] = att
}
return obj, nil
}
|
[
"func",
"(",
"a",
"*",
"APIAnalyzer",
")",
"CreateType",
"(",
"query",
"string",
",",
"attributes",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"*",
"gen",
".",
"ObjectDataType",
",",
"error",
")",
"{",
"name",
":=",
"inflect",
".",
"Camelize",
"(",
"bracketRegexp",
".",
"ReplaceAllLiteralString",
"(",
"query",
",",
"\"_\"",
")",
"+",
"\"_struct\"",
")",
"\n",
"obj",
":=",
"a",
".",
"Registry",
".",
"CreateInlineType",
"(",
"name",
")",
"\n",
"obj",
".",
"Fields",
"=",
"make",
"(",
"[",
"]",
"*",
"gen",
".",
"ActionParam",
",",
"len",
"(",
"attributes",
")",
")",
"\n",
"for",
"idx",
",",
"an",
":=",
"range",
"sortedKeys",
"(",
"attributes",
")",
"{",
"at",
":=",
"attributes",
"[",
"an",
"]",
"\n",
"var",
"childQ",
"string",
"\n",
"if",
"query",
"==",
"\"payload\"",
"{",
"childQ",
"=",
"an",
"\n",
"}",
"else",
"{",
"childQ",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%s[%s]\"",
",",
"query",
",",
"an",
")",
"\n",
"}",
"\n",
"att",
",",
"err",
":=",
"a",
".",
"AnalyzeAttribute",
"(",
"an",
",",
"childQ",
",",
"at",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Failed to compute type of attribute %s: %s\"",
",",
"an",
",",
"err",
")",
"\n",
"}",
"\n",
"obj",
".",
"Fields",
"[",
"idx",
"]",
"=",
"att",
"\n",
"}",
"\n",
"return",
"obj",
",",
"nil",
"\n",
"}"
] |
// CreateType is a helper method that creates or retrieve a object data type given its attributes.
|
[
"CreateType",
"is",
"a",
"helper",
"method",
"that",
"creates",
"or",
"retrieve",
"a",
"object",
"data",
"type",
"given",
"its",
"attributes",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/praxisgen/type_analysis.go#L187-L206
|
test
|
rightscale/rsc
|
gen/goav2gen/swagger.go
|
Ref
|
func (d *Doc) Ref(r Ref) *Definition {
if refIF, ok := r["$ref"]; ok {
refKey := strings.TrimPrefix(refIF.(string), "#/definitions/")
return d.Definitions[refKey]
}
return nil
}
|
go
|
func (d *Doc) Ref(r Ref) *Definition {
if refIF, ok := r["$ref"]; ok {
refKey := strings.TrimPrefix(refIF.(string), "#/definitions/")
return d.Definitions[refKey]
}
return nil
}
|
[
"func",
"(",
"d",
"*",
"Doc",
")",
"Ref",
"(",
"r",
"Ref",
")",
"*",
"Definition",
"{",
"if",
"refIF",
",",
"ok",
":=",
"r",
"[",
"\"$ref\"",
"]",
";",
"ok",
"{",
"refKey",
":=",
"strings",
".",
"TrimPrefix",
"(",
"refIF",
".",
"(",
"string",
")",
",",
"\"#/definitions/\"",
")",
"\n",
"return",
"d",
".",
"Definitions",
"[",
"refKey",
"]",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Ref gets a definition for a Schema reference, if it exists
|
[
"Ref",
"gets",
"a",
"definition",
"for",
"a",
"Schema",
"reference",
"if",
"it",
"exists"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/goav2gen/swagger.go#L110-L116
|
test
|
rightscale/rsc
|
gen/goav2gen/swagger.go
|
Type
|
func (r Ref) Type() string {
if _, ok := r["$ref"]; ok {
return "object"
}
if refIF, ok := r["type"]; ok {
return refIF.(string)
}
return ""
}
|
go
|
func (r Ref) Type() string {
if _, ok := r["$ref"]; ok {
return "object"
}
if refIF, ok := r["type"]; ok {
return refIF.(string)
}
return ""
}
|
[
"func",
"(",
"r",
"Ref",
")",
"Type",
"(",
")",
"string",
"{",
"if",
"_",
",",
"ok",
":=",
"r",
"[",
"\"$ref\"",
"]",
";",
"ok",
"{",
"return",
"\"object\"",
"\n",
"}",
"\n",
"if",
"refIF",
",",
"ok",
":=",
"r",
"[",
"\"type\"",
"]",
";",
"ok",
"{",
"return",
"refIF",
".",
"(",
"string",
")",
"\n",
"}",
"\n",
"return",
"\"\"",
"\n",
"}"
] |
// Type gets a type for a Schema reference, if it exists
|
[
"Type",
"gets",
"a",
"type",
"for",
"a",
"Schema",
"reference",
"if",
"it",
"exists"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/goav2gen/swagger.go#L119-L127
|
test
|
rightscale/rsc
|
gen/goav2gen/swagger.go
|
Required
|
func (r Ref) Required() []string {
if refIF, ok := r["required"]; ok {
return refIF.([]string)
}
return []string{}
}
|
go
|
func (r Ref) Required() []string {
if refIF, ok := r["required"]; ok {
return refIF.([]string)
}
return []string{}
}
|
[
"func",
"(",
"r",
"Ref",
")",
"Required",
"(",
")",
"[",
"]",
"string",
"{",
"if",
"refIF",
",",
"ok",
":=",
"r",
"[",
"\"required\"",
"]",
";",
"ok",
"{",
"return",
"refIF",
".",
"(",
"[",
"]",
"string",
")",
"\n",
"}",
"\n",
"return",
"[",
"]",
"string",
"{",
"}",
"\n",
"}"
] |
// Required gets a type for a Schema reference, if it exists
|
[
"Required",
"gets",
"a",
"type",
"for",
"a",
"Schema",
"reference",
"if",
"it",
"exists"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/goav2gen/swagger.go#L130-L135
|
test
|
rightscale/rsc
|
gen/goav2gen/swagger.go
|
ID
|
func (r Ref) ID() string {
if refIF, ok := r["$ref"]; ok {
return strings.TrimPrefix(refIF.(string), "#/definitions/")
}
return ""
}
|
go
|
func (r Ref) ID() string {
if refIF, ok := r["$ref"]; ok {
return strings.TrimPrefix(refIF.(string), "#/definitions/")
}
return ""
}
|
[
"func",
"(",
"r",
"Ref",
")",
"ID",
"(",
")",
"string",
"{",
"if",
"refIF",
",",
"ok",
":=",
"r",
"[",
"\"$ref\"",
"]",
";",
"ok",
"{",
"return",
"strings",
".",
"TrimPrefix",
"(",
"refIF",
".",
"(",
"string",
")",
",",
"\"#/definitions/\"",
")",
"\n",
"}",
"\n",
"return",
"\"\"",
"\n",
"}"
] |
// ID of the reference
|
[
"ID",
"of",
"the",
"reference"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/goav2gen/swagger.go#L138-L143
|
test
|
rightscale/rsc
|
gen/goav2gen/swagger.go
|
Service
|
func (ep *Endpoint) Service() string {
if len(ep.Tags) > 0 {
return ep.Tags[0]
}
if len(ep.OperationID) > 0 {
return strings.Split(ep.OperationID, "#")[0]
}
return ""
}
|
go
|
func (ep *Endpoint) Service() string {
if len(ep.Tags) > 0 {
return ep.Tags[0]
}
if len(ep.OperationID) > 0 {
return strings.Split(ep.OperationID, "#")[0]
}
return ""
}
|
[
"func",
"(",
"ep",
"*",
"Endpoint",
")",
"Service",
"(",
")",
"string",
"{",
"if",
"len",
"(",
"ep",
".",
"Tags",
")",
">",
"0",
"{",
"return",
"ep",
".",
"Tags",
"[",
"0",
"]",
"\n",
"}",
"\n",
"if",
"len",
"(",
"ep",
".",
"OperationID",
")",
">",
"0",
"{",
"return",
"strings",
".",
"Split",
"(",
"ep",
".",
"OperationID",
",",
"\"#\"",
")",
"[",
"0",
"]",
"\n",
"}",
"\n",
"return",
"\"\"",
"\n",
"}"
] |
// Service returns the goa.v2 service
|
[
"Service",
"returns",
"the",
"goa",
".",
"v2",
"service"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/goav2gen/swagger.go#L146-L154
|
test
|
rightscale/rsc
|
gen/goav2gen/swagger.go
|
Method
|
func (ep *Endpoint) Method() string {
if strings.Contains(ep.OperationID, "#") {
return strings.Split(ep.OperationID, "#")[1]
}
return ""
}
|
go
|
func (ep *Endpoint) Method() string {
if strings.Contains(ep.OperationID, "#") {
return strings.Split(ep.OperationID, "#")[1]
}
return ""
}
|
[
"func",
"(",
"ep",
"*",
"Endpoint",
")",
"Method",
"(",
")",
"string",
"{",
"if",
"strings",
".",
"Contains",
"(",
"ep",
".",
"OperationID",
",",
"\"#\"",
")",
"{",
"return",
"strings",
".",
"Split",
"(",
"ep",
".",
"OperationID",
",",
"\"#\"",
")",
"[",
"1",
"]",
"\n",
"}",
"\n",
"return",
"\"\"",
"\n",
"}"
] |
// Methods returns the goa.v2 method
|
[
"Methods",
"returns",
"the",
"goa",
".",
"v2",
"method"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/goav2gen/swagger.go#L157-L162
|
test
|
rightscale/rsc
|
gen/praxisgen/api_analyzer.go
|
NewTypeRegistry
|
func NewTypeRegistry() *TypeRegistry {
return &TypeRegistry{
NamedTypes: make(map[string]*gen.ObjectDataType),
InlineTypes: make(map[string][]*gen.ObjectDataType),
}
}
|
go
|
func NewTypeRegistry() *TypeRegistry {
return &TypeRegistry{
NamedTypes: make(map[string]*gen.ObjectDataType),
InlineTypes: make(map[string][]*gen.ObjectDataType),
}
}
|
[
"func",
"NewTypeRegistry",
"(",
")",
"*",
"TypeRegistry",
"{",
"return",
"&",
"TypeRegistry",
"{",
"NamedTypes",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"gen",
".",
"ObjectDataType",
")",
",",
"InlineTypes",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"*",
"gen",
".",
"ObjectDataType",
")",
",",
"}",
"\n",
"}"
] |
// NewTypeRegistry creates a type registry.
|
[
"NewTypeRegistry",
"creates",
"a",
"type",
"registry",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/praxisgen/api_analyzer.go#L83-L88
|
test
|
rightscale/rsc
|
gen/praxisgen/api_analyzer.go
|
GetNamedType
|
func (reg *TypeRegistry) GetNamedType(name string) *gen.ObjectDataType {
return reg.NamedTypes[toGoTypeName(name)]
}
|
go
|
func (reg *TypeRegistry) GetNamedType(name string) *gen.ObjectDataType {
return reg.NamedTypes[toGoTypeName(name)]
}
|
[
"func",
"(",
"reg",
"*",
"TypeRegistry",
")",
"GetNamedType",
"(",
"name",
"string",
")",
"*",
"gen",
".",
"ObjectDataType",
"{",
"return",
"reg",
".",
"NamedTypes",
"[",
"toGoTypeName",
"(",
"name",
")",
"]",
"\n",
"}"
] |
// GetNamedType retrieves a type given its name.
|
[
"GetNamedType",
"retrieves",
"a",
"type",
"given",
"its",
"name",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/praxisgen/api_analyzer.go#L91-L93
|
test
|
rightscale/rsc
|
gen/praxisgen/api_analyzer.go
|
CreateNamedType
|
func (reg *TypeRegistry) CreateNamedType(name string) *gen.ObjectDataType {
goName := toGoTypeName(name)
obj := gen.ObjectDataType{TypeName: goName}
if _, ok := reg.NamedTypes[goName]; ok {
panic("BUG: Can't create two named types with same name....")
}
reg.NamedTypes[goName] = &obj
return &obj
}
|
go
|
func (reg *TypeRegistry) CreateNamedType(name string) *gen.ObjectDataType {
goName := toGoTypeName(name)
obj := gen.ObjectDataType{TypeName: goName}
if _, ok := reg.NamedTypes[goName]; ok {
panic("BUG: Can't create two named types with same name....")
}
reg.NamedTypes[goName] = &obj
return &obj
}
|
[
"func",
"(",
"reg",
"*",
"TypeRegistry",
")",
"CreateNamedType",
"(",
"name",
"string",
")",
"*",
"gen",
".",
"ObjectDataType",
"{",
"goName",
":=",
"toGoTypeName",
"(",
"name",
")",
"\n",
"obj",
":=",
"gen",
".",
"ObjectDataType",
"{",
"TypeName",
":",
"goName",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"reg",
".",
"NamedTypes",
"[",
"goName",
"]",
";",
"ok",
"{",
"panic",
"(",
"\"BUG: Can't create two named types with same name....\"",
")",
"\n",
"}",
"\n",
"reg",
".",
"NamedTypes",
"[",
"goName",
"]",
"=",
"&",
"obj",
"\n",
"return",
"&",
"obj",
"\n",
"}"
] |
// CreateNamedType returns a new type given a name, the name must be unique.
|
[
"CreateNamedType",
"returns",
"a",
"new",
"type",
"given",
"a",
"name",
"the",
"name",
"must",
"be",
"unique",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/praxisgen/api_analyzer.go#L96-L104
|
test
|
rightscale/rsc
|
gen/praxisgen/api_analyzer.go
|
CreateInlineType
|
func (reg *TypeRegistry) CreateInlineType(name string) *gen.ObjectDataType {
goName := toGoTypeName(name)
obj := gen.ObjectDataType{TypeName: goName}
reg.InlineTypes[goName] = append(reg.InlineTypes[goName], &obj)
return &obj
}
|
go
|
func (reg *TypeRegistry) CreateInlineType(name string) *gen.ObjectDataType {
goName := toGoTypeName(name)
obj := gen.ObjectDataType{TypeName: goName}
reg.InlineTypes[goName] = append(reg.InlineTypes[goName], &obj)
return &obj
}
|
[
"func",
"(",
"reg",
"*",
"TypeRegistry",
")",
"CreateInlineType",
"(",
"name",
"string",
")",
"*",
"gen",
".",
"ObjectDataType",
"{",
"goName",
":=",
"toGoTypeName",
"(",
"name",
")",
"\n",
"obj",
":=",
"gen",
".",
"ObjectDataType",
"{",
"TypeName",
":",
"goName",
"}",
"\n",
"reg",
".",
"InlineTypes",
"[",
"goName",
"]",
"=",
"append",
"(",
"reg",
".",
"InlineTypes",
"[",
"goName",
"]",
",",
"&",
"obj",
")",
"\n",
"return",
"&",
"obj",
"\n",
"}"
] |
// CreateInlineType creates a new inline type.
|
[
"CreateInlineType",
"creates",
"a",
"new",
"inline",
"type",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/praxisgen/api_analyzer.go#L107-L112
|
test
|
rightscale/rsc
|
gen/praxisgen/api_analyzer.go
|
FinalizeTypeNames
|
func (reg *TypeRegistry) FinalizeTypeNames(d *gen.APIDescriptor) {
for n, named := range reg.NamedTypes {
reg.InlineTypes[n] = append(reg.InlineTypes[n], named)
}
d.FinalizeTypeNames(reg.InlineTypes)
}
|
go
|
func (reg *TypeRegistry) FinalizeTypeNames(d *gen.APIDescriptor) {
for n, named := range reg.NamedTypes {
reg.InlineTypes[n] = append(reg.InlineTypes[n], named)
}
d.FinalizeTypeNames(reg.InlineTypes)
}
|
[
"func",
"(",
"reg",
"*",
"TypeRegistry",
")",
"FinalizeTypeNames",
"(",
"d",
"*",
"gen",
".",
"APIDescriptor",
")",
"{",
"for",
"n",
",",
"named",
":=",
"range",
"reg",
".",
"NamedTypes",
"{",
"reg",
".",
"InlineTypes",
"[",
"n",
"]",
"=",
"append",
"(",
"reg",
".",
"InlineTypes",
"[",
"n",
"]",
",",
"named",
")",
"\n",
"}",
"\n",
"d",
".",
"FinalizeTypeNames",
"(",
"reg",
".",
"InlineTypes",
")",
"\n",
"}"
] |
// FinalizeTypeNames makes sure type names are unique, it should be called after analysis
// has completed.
|
[
"FinalizeTypeNames",
"makes",
"sure",
"type",
"names",
"are",
"unique",
"it",
"should",
"be",
"called",
"after",
"analysis",
"has",
"completed",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/praxisgen/api_analyzer.go#L116-L121
|
test
|
rightscale/rsc
|
gen/data_types.go
|
Merge
|
func (d *APIDescriptor) Merge(other *APIDescriptor) error {
if d.Version != other.Version {
return fmt.Errorf("Can't merge API descriptors with different versions")
}
for _, name := range d.ResourceNames {
for _, otherName := range other.ResourceNames {
if name == otherName {
return fmt.Errorf("%s is a resource that exists in multiple APIs, generate separate clients", name)
}
}
}
for _, name := range d.TypeNames {
for i, otherName := range other.TypeNames {
if name == otherName {
newName := MakeUniq(otherName, append(d.TypeNames, other.TypeNames...))
first := other.TypeNames[:i]
last := append([]string{newName}, other.TypeNames[i+1:]...)
other.TypeNames = append(first, last...)
typ := other.Types[name]
delete(other.Types, name)
typ.TypeName = newName
other.Types[newName] = typ
}
}
}
for name, resource := range other.Resources {
d.Resources[name] = resource
}
for name, typ := range other.Types {
d.Types[name] = typ
}
d.ResourceNames = append(d.ResourceNames, other.ResourceNames...)
d.TypeNames = append(d.TypeNames, other.TypeNames...)
return nil
}
|
go
|
func (d *APIDescriptor) Merge(other *APIDescriptor) error {
if d.Version != other.Version {
return fmt.Errorf("Can't merge API descriptors with different versions")
}
for _, name := range d.ResourceNames {
for _, otherName := range other.ResourceNames {
if name == otherName {
return fmt.Errorf("%s is a resource that exists in multiple APIs, generate separate clients", name)
}
}
}
for _, name := range d.TypeNames {
for i, otherName := range other.TypeNames {
if name == otherName {
newName := MakeUniq(otherName, append(d.TypeNames, other.TypeNames...))
first := other.TypeNames[:i]
last := append([]string{newName}, other.TypeNames[i+1:]...)
other.TypeNames = append(first, last...)
typ := other.Types[name]
delete(other.Types, name)
typ.TypeName = newName
other.Types[newName] = typ
}
}
}
for name, resource := range other.Resources {
d.Resources[name] = resource
}
for name, typ := range other.Types {
d.Types[name] = typ
}
d.ResourceNames = append(d.ResourceNames, other.ResourceNames...)
d.TypeNames = append(d.TypeNames, other.TypeNames...)
return nil
}
|
[
"func",
"(",
"d",
"*",
"APIDescriptor",
")",
"Merge",
"(",
"other",
"*",
"APIDescriptor",
")",
"error",
"{",
"if",
"d",
".",
"Version",
"!=",
"other",
".",
"Version",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Can't merge API descriptors with different versions\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"d",
".",
"ResourceNames",
"{",
"for",
"_",
",",
"otherName",
":=",
"range",
"other",
".",
"ResourceNames",
"{",
"if",
"name",
"==",
"otherName",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"%s is a resource that exists in multiple APIs, generate separate clients\"",
",",
"name",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"d",
".",
"TypeNames",
"{",
"for",
"i",
",",
"otherName",
":=",
"range",
"other",
".",
"TypeNames",
"{",
"if",
"name",
"==",
"otherName",
"{",
"newName",
":=",
"MakeUniq",
"(",
"otherName",
",",
"append",
"(",
"d",
".",
"TypeNames",
",",
"other",
".",
"TypeNames",
"...",
")",
")",
"\n",
"first",
":=",
"other",
".",
"TypeNames",
"[",
":",
"i",
"]",
"\n",
"last",
":=",
"append",
"(",
"[",
"]",
"string",
"{",
"newName",
"}",
",",
"other",
".",
"TypeNames",
"[",
"i",
"+",
"1",
":",
"]",
"...",
")",
"\n",
"other",
".",
"TypeNames",
"=",
"append",
"(",
"first",
",",
"last",
"...",
")",
"\n",
"typ",
":=",
"other",
".",
"Types",
"[",
"name",
"]",
"\n",
"delete",
"(",
"other",
".",
"Types",
",",
"name",
")",
"\n",
"typ",
".",
"TypeName",
"=",
"newName",
"\n",
"other",
".",
"Types",
"[",
"newName",
"]",
"=",
"typ",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"name",
",",
"resource",
":=",
"range",
"other",
".",
"Resources",
"{",
"d",
".",
"Resources",
"[",
"name",
"]",
"=",
"resource",
"\n",
"}",
"\n",
"for",
"name",
",",
"typ",
":=",
"range",
"other",
".",
"Types",
"{",
"d",
".",
"Types",
"[",
"name",
"]",
"=",
"typ",
"\n",
"}",
"\n",
"d",
".",
"ResourceNames",
"=",
"append",
"(",
"d",
".",
"ResourceNames",
",",
"other",
".",
"ResourceNames",
"...",
")",
"\n",
"d",
".",
"TypeNames",
"=",
"append",
"(",
"d",
".",
"TypeNames",
",",
"other",
".",
"TypeNames",
"...",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Merge two descriptors together, make sure there are no duplicate resource names and that
// common types are compatible.
|
[
"Merge",
"two",
"descriptors",
"together",
"make",
"sure",
"there",
"are",
"no",
"duplicate",
"resource",
"names",
"and",
"that",
"common",
"types",
"are",
"compatible",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/data_types.go#L24-L58
|
test
|
rightscale/rsc
|
gen/data_types.go
|
FinalizeTypeNames
|
func (d *APIDescriptor) FinalizeTypeNames(rawTypes map[string][]*ObjectDataType) {
// 1. Make sure data type names don't clash with resource names
rawTypeNames := make([]string, len(rawTypes))
idx := 0
for n := range rawTypes {
rawTypeNames[idx] = n
idx++
}
sort.Strings(rawTypeNames)
for _, tn := range rawTypeNames {
types := rawTypes[tn]
for rn := range d.Resources {
if tn == rn {
oldTn := tn
if strings.HasSuffix(tn, "Param") {
tn = fmt.Sprintf("%s2", tn)
} else {
tn = fmt.Sprintf("%sParam", tn)
}
for _, ty := range types {
ty.TypeName = tn
}
rawTypes[tn] = types
delete(rawTypes, oldTn)
}
}
}
// 2. Make data type names unique
idx = 0
for n := range rawTypes {
rawTypeNames[idx] = n
idx++
}
sort.Strings(rawTypeNames)
for _, tn := range rawTypeNames {
types := rawTypes[tn]
first := types[0]
d.Types[tn] = first
if len(types) > 1 {
for i, ty := range types[1:] {
found := false
for j := 0; j < i+1; j++ {
if ty.IsEquivalent(types[j]) {
found = true
break
}
}
if !found {
newName := d.uniqueTypeName(tn)
ty.TypeName = newName
d.Types[newName] = ty
d.TypeNames = append(d.TypeNames, newName)
}
}
}
}
// 3. Finally initialize .ResourceNames and .TypeNames
idx = 0
resourceNames := make([]string, len(d.Resources))
for n := range d.Resources {
resourceNames[idx] = n
idx++
}
sort.Strings(resourceNames)
d.ResourceNames = resourceNames
typeNames := make([]string, len(d.Types))
idx = 0
for tn := range d.Types {
typeNames[idx] = tn
idx++
}
sort.Strings(typeNames)
d.TypeNames = typeNames
}
|
go
|
func (d *APIDescriptor) FinalizeTypeNames(rawTypes map[string][]*ObjectDataType) {
// 1. Make sure data type names don't clash with resource names
rawTypeNames := make([]string, len(rawTypes))
idx := 0
for n := range rawTypes {
rawTypeNames[idx] = n
idx++
}
sort.Strings(rawTypeNames)
for _, tn := range rawTypeNames {
types := rawTypes[tn]
for rn := range d.Resources {
if tn == rn {
oldTn := tn
if strings.HasSuffix(tn, "Param") {
tn = fmt.Sprintf("%s2", tn)
} else {
tn = fmt.Sprintf("%sParam", tn)
}
for _, ty := range types {
ty.TypeName = tn
}
rawTypes[tn] = types
delete(rawTypes, oldTn)
}
}
}
// 2. Make data type names unique
idx = 0
for n := range rawTypes {
rawTypeNames[idx] = n
idx++
}
sort.Strings(rawTypeNames)
for _, tn := range rawTypeNames {
types := rawTypes[tn]
first := types[0]
d.Types[tn] = first
if len(types) > 1 {
for i, ty := range types[1:] {
found := false
for j := 0; j < i+1; j++ {
if ty.IsEquivalent(types[j]) {
found = true
break
}
}
if !found {
newName := d.uniqueTypeName(tn)
ty.TypeName = newName
d.Types[newName] = ty
d.TypeNames = append(d.TypeNames, newName)
}
}
}
}
// 3. Finally initialize .ResourceNames and .TypeNames
idx = 0
resourceNames := make([]string, len(d.Resources))
for n := range d.Resources {
resourceNames[idx] = n
idx++
}
sort.Strings(resourceNames)
d.ResourceNames = resourceNames
typeNames := make([]string, len(d.Types))
idx = 0
for tn := range d.Types {
typeNames[idx] = tn
idx++
}
sort.Strings(typeNames)
d.TypeNames = typeNames
}
|
[
"func",
"(",
"d",
"*",
"APIDescriptor",
")",
"FinalizeTypeNames",
"(",
"rawTypes",
"map",
"[",
"string",
"]",
"[",
"]",
"*",
"ObjectDataType",
")",
"{",
"rawTypeNames",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"rawTypes",
")",
")",
"\n",
"idx",
":=",
"0",
"\n",
"for",
"n",
":=",
"range",
"rawTypes",
"{",
"rawTypeNames",
"[",
"idx",
"]",
"=",
"n",
"\n",
"idx",
"++",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"rawTypeNames",
")",
"\n",
"for",
"_",
",",
"tn",
":=",
"range",
"rawTypeNames",
"{",
"types",
":=",
"rawTypes",
"[",
"tn",
"]",
"\n",
"for",
"rn",
":=",
"range",
"d",
".",
"Resources",
"{",
"if",
"tn",
"==",
"rn",
"{",
"oldTn",
":=",
"tn",
"\n",
"if",
"strings",
".",
"HasSuffix",
"(",
"tn",
",",
"\"Param\"",
")",
"{",
"tn",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%s2\"",
",",
"tn",
")",
"\n",
"}",
"else",
"{",
"tn",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%sParam\"",
",",
"tn",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"ty",
":=",
"range",
"types",
"{",
"ty",
".",
"TypeName",
"=",
"tn",
"\n",
"}",
"\n",
"rawTypes",
"[",
"tn",
"]",
"=",
"types",
"\n",
"delete",
"(",
"rawTypes",
",",
"oldTn",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"idx",
"=",
"0",
"\n",
"for",
"n",
":=",
"range",
"rawTypes",
"{",
"rawTypeNames",
"[",
"idx",
"]",
"=",
"n",
"\n",
"idx",
"++",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"rawTypeNames",
")",
"\n",
"for",
"_",
",",
"tn",
":=",
"range",
"rawTypeNames",
"{",
"types",
":=",
"rawTypes",
"[",
"tn",
"]",
"\n",
"first",
":=",
"types",
"[",
"0",
"]",
"\n",
"d",
".",
"Types",
"[",
"tn",
"]",
"=",
"first",
"\n",
"if",
"len",
"(",
"types",
")",
">",
"1",
"{",
"for",
"i",
",",
"ty",
":=",
"range",
"types",
"[",
"1",
":",
"]",
"{",
"found",
":=",
"false",
"\n",
"for",
"j",
":=",
"0",
";",
"j",
"<",
"i",
"+",
"1",
";",
"j",
"++",
"{",
"if",
"ty",
".",
"IsEquivalent",
"(",
"types",
"[",
"j",
"]",
")",
"{",
"found",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"found",
"{",
"newName",
":=",
"d",
".",
"uniqueTypeName",
"(",
"tn",
")",
"\n",
"ty",
".",
"TypeName",
"=",
"newName",
"\n",
"d",
".",
"Types",
"[",
"newName",
"]",
"=",
"ty",
"\n",
"d",
".",
"TypeNames",
"=",
"append",
"(",
"d",
".",
"TypeNames",
",",
"newName",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"idx",
"=",
"0",
"\n",
"resourceNames",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"d",
".",
"Resources",
")",
")",
"\n",
"for",
"n",
":=",
"range",
"d",
".",
"Resources",
"{",
"resourceNames",
"[",
"idx",
"]",
"=",
"n",
"\n",
"idx",
"++",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"resourceNames",
")",
"\n",
"d",
".",
"ResourceNames",
"=",
"resourceNames",
"\n",
"typeNames",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"d",
".",
"Types",
")",
")",
"\n",
"idx",
"=",
"0",
"\n",
"for",
"tn",
":=",
"range",
"d",
".",
"Types",
"{",
"typeNames",
"[",
"idx",
"]",
"=",
"tn",
"\n",
"idx",
"++",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"typeNames",
")",
"\n",
"d",
".",
"TypeNames",
"=",
"typeNames",
"\n",
"}"
] |
// FinalizeTypeNames goes through all the types generated by the analyzer and generate unique names.
|
[
"FinalizeTypeNames",
"goes",
"through",
"all",
"the",
"types",
"generated",
"by",
"the",
"analyzer",
"and",
"generate",
"unique",
"names",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/data_types.go#L61-L138
|
test
|
rightscale/rsc
|
gen/data_types.go
|
uniqueTypeName
|
func (d *APIDescriptor) uniqueTypeName(prefix string) string {
u := fmt.Sprintf("%s%d", prefix, 2)
taken := false
for _, tn := range d.TypeNames {
if tn == u {
taken = true
break
}
}
idx := 3
for taken {
u = fmt.Sprintf("%s%d", prefix, idx)
taken = false
for _, tn := range d.TypeNames {
if tn == u {
taken = true
break
}
}
if taken {
idx++
}
}
return u
}
|
go
|
func (d *APIDescriptor) uniqueTypeName(prefix string) string {
u := fmt.Sprintf("%s%d", prefix, 2)
taken := false
for _, tn := range d.TypeNames {
if tn == u {
taken = true
break
}
}
idx := 3
for taken {
u = fmt.Sprintf("%s%d", prefix, idx)
taken = false
for _, tn := range d.TypeNames {
if tn == u {
taken = true
break
}
}
if taken {
idx++
}
}
return u
}
|
[
"func",
"(",
"d",
"*",
"APIDescriptor",
")",
"uniqueTypeName",
"(",
"prefix",
"string",
")",
"string",
"{",
"u",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%s%d\"",
",",
"prefix",
",",
"2",
")",
"\n",
"taken",
":=",
"false",
"\n",
"for",
"_",
",",
"tn",
":=",
"range",
"d",
".",
"TypeNames",
"{",
"if",
"tn",
"==",
"u",
"{",
"taken",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"idx",
":=",
"3",
"\n",
"for",
"taken",
"{",
"u",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%s%d\"",
",",
"prefix",
",",
"idx",
")",
"\n",
"taken",
"=",
"false",
"\n",
"for",
"_",
",",
"tn",
":=",
"range",
"d",
".",
"TypeNames",
"{",
"if",
"tn",
"==",
"u",
"{",
"taken",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"taken",
"{",
"idx",
"++",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"u",
"\n",
"}"
] |
// Build unique type name by appending "next available index" to given prefix
|
[
"Build",
"unique",
"type",
"name",
"by",
"appending",
"next",
"available",
"index",
"to",
"given",
"prefix"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/data_types.go#L141-L165
|
test
|
rightscale/rsc
|
gen/data_types.go
|
MandatoryParams
|
func (a *Action) MandatoryParams() []*ActionParam {
m := make([]*ActionParam, len(a.Params))
i := 0
for _, p := range a.Params {
if p.Mandatory {
m[i] = p
i++
}
}
return m[:i]
}
|
go
|
func (a *Action) MandatoryParams() []*ActionParam {
m := make([]*ActionParam, len(a.Params))
i := 0
for _, p := range a.Params {
if p.Mandatory {
m[i] = p
i++
}
}
return m[:i]
}
|
[
"func",
"(",
"a",
"*",
"Action",
")",
"MandatoryParams",
"(",
")",
"[",
"]",
"*",
"ActionParam",
"{",
"m",
":=",
"make",
"(",
"[",
"]",
"*",
"ActionParam",
",",
"len",
"(",
"a",
".",
"Params",
")",
")",
"\n",
"i",
":=",
"0",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"a",
".",
"Params",
"{",
"if",
"p",
".",
"Mandatory",
"{",
"m",
"[",
"i",
"]",
"=",
"p",
"\n",
"i",
"++",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"m",
"[",
":",
"i",
"]",
"\n",
"}"
] |
// MandatoryParams returns the list of all action mandatory parameters
|
[
"MandatoryParams",
"returns",
"the",
"list",
"of",
"all",
"action",
"mandatory",
"parameters"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/data_types.go#L207-L217
|
test
|
rightscale/rsc
|
gen/data_types.go
|
HasOptionalParams
|
func (a *Action) HasOptionalParams() bool {
for _, param := range a.Params {
if !param.Mandatory {
return true
}
}
return false
}
|
go
|
func (a *Action) HasOptionalParams() bool {
for _, param := range a.Params {
if !param.Mandatory {
return true
}
}
return false
}
|
[
"func",
"(",
"a",
"*",
"Action",
")",
"HasOptionalParams",
"(",
")",
"bool",
"{",
"for",
"_",
",",
"param",
":=",
"range",
"a",
".",
"Params",
"{",
"if",
"!",
"param",
".",
"Mandatory",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// HasOptionalParams returns true if the action takes optional parameters, false otherwise.
|
[
"HasOptionalParams",
"returns",
"true",
"if",
"the",
"action",
"takes",
"optional",
"parameters",
"false",
"otherwise",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/data_types.go#L220-L227
|
test
|
rightscale/rsc
|
gen/data_types.go
|
MakeUniq
|
func MakeUniq(base string, taken []string) string {
idx := 1
uniq := base
inuse := true
for inuse {
inuse = false
for _, gn := range taken {
if gn == uniq {
inuse = true
break
}
}
if inuse {
idx++
uniq = base + strconv.Itoa(idx)
}
}
return uniq
}
|
go
|
func MakeUniq(base string, taken []string) string {
idx := 1
uniq := base
inuse := true
for inuse {
inuse = false
for _, gn := range taken {
if gn == uniq {
inuse = true
break
}
}
if inuse {
idx++
uniq = base + strconv.Itoa(idx)
}
}
return uniq
}
|
[
"func",
"MakeUniq",
"(",
"base",
"string",
",",
"taken",
"[",
"]",
"string",
")",
"string",
"{",
"idx",
":=",
"1",
"\n",
"uniq",
":=",
"base",
"\n",
"inuse",
":=",
"true",
"\n",
"for",
"inuse",
"{",
"inuse",
"=",
"false",
"\n",
"for",
"_",
",",
"gn",
":=",
"range",
"taken",
"{",
"if",
"gn",
"==",
"uniq",
"{",
"inuse",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"inuse",
"{",
"idx",
"++",
"\n",
"uniq",
"=",
"base",
"+",
"strconv",
".",
"Itoa",
"(",
"idx",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"uniq",
"\n",
"}"
] |
// MakeUniq makes a unique name given a prefix and a set of names.
|
[
"MakeUniq",
"makes",
"a",
"unique",
"name",
"given",
"a",
"prefix",
"and",
"a",
"set",
"of",
"names",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/data_types.go#L418-L436
|
test
|
rightscale/rsc
|
gen/writers/client.go
|
NewClientWriter
|
func NewClientWriter() (*ClientWriter, error) {
funcMap := template.FuncMap{
"comment": comment,
"commandLine": commandLine,
"parameters": parameters,
"paramsInitializer": paramsInitializer,
"blankCondition": blankCondition,
"stripStar": stripStar,
}
headerT, err := template.New("header-client").Funcs(funcMap).Parse(headerTmpl)
if err != nil {
return nil, err
}
resourceT, err := template.New("resource-client").Funcs(funcMap).Parse(resourceTmpl)
if err != nil {
return nil, err
}
return &ClientWriter{
headerTmpl: headerT,
resourceTmpl: resourceT,
}, nil
}
|
go
|
func NewClientWriter() (*ClientWriter, error) {
funcMap := template.FuncMap{
"comment": comment,
"commandLine": commandLine,
"parameters": parameters,
"paramsInitializer": paramsInitializer,
"blankCondition": blankCondition,
"stripStar": stripStar,
}
headerT, err := template.New("header-client").Funcs(funcMap).Parse(headerTmpl)
if err != nil {
return nil, err
}
resourceT, err := template.New("resource-client").Funcs(funcMap).Parse(resourceTmpl)
if err != nil {
return nil, err
}
return &ClientWriter{
headerTmpl: headerT,
resourceTmpl: resourceT,
}, nil
}
|
[
"func",
"NewClientWriter",
"(",
")",
"(",
"*",
"ClientWriter",
",",
"error",
")",
"{",
"funcMap",
":=",
"template",
".",
"FuncMap",
"{",
"\"comment\"",
":",
"comment",
",",
"\"commandLine\"",
":",
"commandLine",
",",
"\"parameters\"",
":",
"parameters",
",",
"\"paramsInitializer\"",
":",
"paramsInitializer",
",",
"\"blankCondition\"",
":",
"blankCondition",
",",
"\"stripStar\"",
":",
"stripStar",
",",
"}",
"\n",
"headerT",
",",
"err",
":=",
"template",
".",
"New",
"(",
"\"header-client\"",
")",
".",
"Funcs",
"(",
"funcMap",
")",
".",
"Parse",
"(",
"headerTmpl",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"resourceT",
",",
"err",
":=",
"template",
".",
"New",
"(",
"\"resource-client\"",
")",
".",
"Funcs",
"(",
"funcMap",
")",
".",
"Parse",
"(",
"resourceTmpl",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"ClientWriter",
"{",
"headerTmpl",
":",
"headerT",
",",
"resourceTmpl",
":",
"resourceT",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// NewClientWriter is the client writer factory.
|
[
"NewClientWriter",
"is",
"the",
"client",
"writer",
"factory",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/writers/client.go#L19-L40
|
test
|
rightscale/rsc
|
gen/writers/client.go
|
WriteHeader
|
func (c *ClientWriter) WriteHeader(pkg, version string, needTime, needJSON bool, w io.Writer) error {
ctx := map[string]interface{}{
"Pkg": pkg,
"APIVersion": version,
"NeedTime": needTime,
"NeedJSON": needJSON,
}
return c.headerTmpl.Execute(w, ctx)
}
|
go
|
func (c *ClientWriter) WriteHeader(pkg, version string, needTime, needJSON bool, w io.Writer) error {
ctx := map[string]interface{}{
"Pkg": pkg,
"APIVersion": version,
"NeedTime": needTime,
"NeedJSON": needJSON,
}
return c.headerTmpl.Execute(w, ctx)
}
|
[
"func",
"(",
"c",
"*",
"ClientWriter",
")",
"WriteHeader",
"(",
"pkg",
",",
"version",
"string",
",",
"needTime",
",",
"needJSON",
"bool",
",",
"w",
"io",
".",
"Writer",
")",
"error",
"{",
"ctx",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"Pkg\"",
":",
"pkg",
",",
"\"APIVersion\"",
":",
"version",
",",
"\"NeedTime\"",
":",
"needTime",
",",
"\"NeedJSON\"",
":",
"needJSON",
",",
"}",
"\n",
"return",
"c",
".",
"headerTmpl",
".",
"Execute",
"(",
"w",
",",
"ctx",
")",
"\n",
"}"
] |
// WriteHeader writes the header text.
|
[
"WriteHeader",
"writes",
"the",
"header",
"text",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/writers/client.go#L43-L51
|
test
|
rightscale/rsc
|
gen/writers/client.go
|
WriteResourceHeader
|
func (c *ClientWriter) WriteResourceHeader(name string, w io.Writer) {
fmt.Fprintf(w, "/****** %s ******/\n\n", name)
}
|
go
|
func (c *ClientWriter) WriteResourceHeader(name string, w io.Writer) {
fmt.Fprintf(w, "/****** %s ******/\n\n", name)
}
|
[
"func",
"(",
"c",
"*",
"ClientWriter",
")",
"WriteResourceHeader",
"(",
"name",
"string",
",",
"w",
"io",
".",
"Writer",
")",
"{",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"/****** %s ******/\\n\\n\"",
",",
"\\n",
")",
"\n",
"}"
] |
// WriteResourceHeader writes the resource header.
|
[
"WriteResourceHeader",
"writes",
"the",
"resource",
"header",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/writers/client.go#L54-L56
|
test
|
rightscale/rsc
|
gen/writers/client.go
|
WriteType
|
func (c *ClientWriter) WriteType(o *gen.ObjectDataType, w io.Writer) {
fields := make([]string, len(o.Fields))
for i, f := range o.Fields {
fields[i] = fmt.Sprintf("%s %s `json:\"%s,omitempty\"`", strings.Title(f.VarName),
f.Signature(), f.Name)
}
decl := fmt.Sprintf("type %s struct {\n%s\n}", o.TypeName,
strings.Join(fields, "\n\t"))
fmt.Fprintf(w, "%s\n\n", decl)
}
|
go
|
func (c *ClientWriter) WriteType(o *gen.ObjectDataType, w io.Writer) {
fields := make([]string, len(o.Fields))
for i, f := range o.Fields {
fields[i] = fmt.Sprintf("%s %s `json:\"%s,omitempty\"`", strings.Title(f.VarName),
f.Signature(), f.Name)
}
decl := fmt.Sprintf("type %s struct {\n%s\n}", o.TypeName,
strings.Join(fields, "\n\t"))
fmt.Fprintf(w, "%s\n\n", decl)
}
|
[
"func",
"(",
"c",
"*",
"ClientWriter",
")",
"WriteType",
"(",
"o",
"*",
"gen",
".",
"ObjectDataType",
",",
"w",
"io",
".",
"Writer",
")",
"{",
"fields",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"o",
".",
"Fields",
")",
")",
"\n",
"for",
"i",
",",
"f",
":=",
"range",
"o",
".",
"Fields",
"{",
"fields",
"[",
"i",
"]",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%s %s `json:\\\"%s,omitempty\\\"`\"",
",",
"\\\"",
",",
"\\\"",
",",
"strings",
".",
"Title",
"(",
"f",
".",
"VarName",
")",
")",
"\n",
"}",
"\n",
"f",
".",
"Signature",
"(",
")",
"\n",
"f",
".",
"Name",
"\n",
"}"
] |
// WriteType writest the type declaration for a resource action arguments.
|
[
"WriteType",
"writest",
"the",
"type",
"declaration",
"for",
"a",
"resource",
"action",
"arguments",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/writers/client.go#L64-L73
|
test
|
rightscale/rsc
|
gen/writers/client.go
|
WriteResource
|
func (c *ClientWriter) WriteResource(resource *gen.Resource, w io.Writer) error {
return c.resourceTmpl.Execute(w, resource)
}
|
go
|
func (c *ClientWriter) WriteResource(resource *gen.Resource, w io.Writer) error {
return c.resourceTmpl.Execute(w, resource)
}
|
[
"func",
"(",
"c",
"*",
"ClientWriter",
")",
"WriteResource",
"(",
"resource",
"*",
"gen",
".",
"Resource",
",",
"w",
"io",
".",
"Writer",
")",
"error",
"{",
"return",
"c",
".",
"resourceTmpl",
".",
"Execute",
"(",
"w",
",",
"resource",
")",
"\n",
"}"
] |
// WriteResource writest the code for a resource.
|
[
"WriteResource",
"writest",
"the",
"code",
"for",
"a",
"resource",
"."
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/writers/client.go#L76-L78
|
test
|
rightscale/rsc
|
gen/goav2gen/endpoint.go
|
WithTrail
|
func (ec EvalCtx) WithTrail(t string) EvalCtx {
newEC := ec
trailCopy := make([]string, 0, len(ec.Trail)+1)
for _, val := range ec.Trail {
trailCopy = append(trailCopy, val)
}
newEC.Trail = append(trailCopy, t)
return newEC
}
|
go
|
func (ec EvalCtx) WithTrail(t string) EvalCtx {
newEC := ec
trailCopy := make([]string, 0, len(ec.Trail)+1)
for _, val := range ec.Trail {
trailCopy = append(trailCopy, val)
}
newEC.Trail = append(trailCopy, t)
return newEC
}
|
[
"func",
"(",
"ec",
"EvalCtx",
")",
"WithTrail",
"(",
"t",
"string",
")",
"EvalCtx",
"{",
"newEC",
":=",
"ec",
"\n",
"trailCopy",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"ec",
".",
"Trail",
")",
"+",
"1",
")",
"\n",
"for",
"_",
",",
"val",
":=",
"range",
"ec",
".",
"Trail",
"{",
"trailCopy",
"=",
"append",
"(",
"trailCopy",
",",
"val",
")",
"\n",
"}",
"\n",
"newEC",
".",
"Trail",
"=",
"append",
"(",
"trailCopy",
",",
"t",
")",
"\n",
"return",
"newEC",
"\n",
"}"
] |
// WithTrail creates a new context with trail appended to
|
[
"WithTrail",
"creates",
"a",
"new",
"context",
"with",
"trail",
"appended",
"to"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/goav2gen/endpoint.go#L23-L31
|
test
|
rightscale/rsc
|
gen/goav2gen/endpoint.go
|
AnalyzeEndpoint
|
func (a *APIAnalyzer) AnalyzeEndpoint(verb string, path string, ep *Endpoint) error {
path = joinPath(a.Doc.BasePath, path)
dbg("\n------\nDEBUG AnalyzeEndpoint %s %s %+v\n", verb, path, ep)
pattern := toPattern(verb, path)
dbg("DEBUG AnalyzeEndpoint pattern %v\n", pattern)
svc := ep.Service()
// Get Resource -- base it on the service name for now
res := a.api.Resources[svc]
if res == nil {
res = &gen.Resource{
Name: svc,
ClientName: a.ClientName,
Actions: []*gen.Action{},
}
a.api.Resources[svc] = res
}
action := &gen.Action{
Name: ep.Method(),
MethodName: toMethodName(ep.Method()),
Description: cleanDescription(ep.Description),
ResourceName: svc,
PathPatterns: []*gen.PathPattern{pattern},
}
res.Actions = append(res.Actions, action)
var returnDT gen.DataType
var hasLocation bool
for code, response := range ep.Responses {
if code >= 300 {
continue
}
if response.Headers != nil {
if _, ok := response.Headers["Location"]; ok {
hasLocation = true
}
}
if response.Schema == nil {
dbg("DEBUG MISSING SCHEMA SKIP!\n")
break
}
dbg("DEBUG AnalyzeEndpoint %d RESPONSE %#v\n", code, response)
returnDef := a.Doc.Ref(response.Schema)
if returnDef != nil {
ec := EvalCtx{IsResult: true, Trail: nil, Svc: res, Method: action}
if mediaType(returnDef.Title) == "" {
warn("Warning: AnalyzeEndpoint: MediaType not set for %s, will be hard to guess the result type\n", response.Schema.ID())
continue
}
returnDT = a.AnalyzeDefinition(ec, returnDef, response.Schema.ID())
if returnObj, ok := returnDT.(*gen.ObjectDataType); ok {
isResourceType := verb == "get" && returnObj.TypeName == svc
dbg("DEBUG AnalyzeEndpoint Path %s Verb %s returnTypeName %s svc %s\n", path, verb, returnObj.TypeName, svc)
if isResourceType {
res.Description = cleanDescription(ep.Description)
res.Identifier = mediaType(returnDef.Title)
}
a.addType(ec, returnObj, response.Schema)
}
} else {
returnDT = basicType(response.Schema.Type())
}
break
}
for _, p := range ep.Parameters {
ec := EvalCtx{IsResult: false, Trail: nil, Svc: res, Method: action}
ap := a.AnalyzeParam(ec, p)
switch p.In {
case "header":
action.HeaderParamNames = append(action.HeaderParamNames, p.Name)
action.Params = append(action.Params, ap)
case "query":
action.QueryParamNames = append(action.QueryParamNames, p.Name)
action.Params = append(action.Params, ap)
case "path":
action.PathParamNames = append(action.PathParamNames, p.Name)
action.Params = append(action.Params, ap)
case "body":
def := a.Doc.Ref(p.Schema)
if def != nil {
if def.Type == "array" {
fail("Array type for body not implemented yet")
} else if def.Type == "object" {
// Flatten the first level of object
dt := a.AnalyzeDefinition(ec, def, p.Schema.ID())
if obj, ok := dt.(*gen.ObjectDataType); ok {
a.addType(ec, obj, p.Schema)
action.Payload = obj
for _, f := range obj.Fields {
action.PayloadParamNames = append(action.PayloadParamNames, f.Name)
action.Params = append(action.Params, f)
}
}
}
}
}
}
if returnDT != nil {
action.Return = signature(returnDT)
}
action.ReturnLocation = hasLocation
dbg("DEBUG ACTION %s", prettify(action))
return nil
}
|
go
|
func (a *APIAnalyzer) AnalyzeEndpoint(verb string, path string, ep *Endpoint) error {
path = joinPath(a.Doc.BasePath, path)
dbg("\n------\nDEBUG AnalyzeEndpoint %s %s %+v\n", verb, path, ep)
pattern := toPattern(verb, path)
dbg("DEBUG AnalyzeEndpoint pattern %v\n", pattern)
svc := ep.Service()
// Get Resource -- base it on the service name for now
res := a.api.Resources[svc]
if res == nil {
res = &gen.Resource{
Name: svc,
ClientName: a.ClientName,
Actions: []*gen.Action{},
}
a.api.Resources[svc] = res
}
action := &gen.Action{
Name: ep.Method(),
MethodName: toMethodName(ep.Method()),
Description: cleanDescription(ep.Description),
ResourceName: svc,
PathPatterns: []*gen.PathPattern{pattern},
}
res.Actions = append(res.Actions, action)
var returnDT gen.DataType
var hasLocation bool
for code, response := range ep.Responses {
if code >= 300 {
continue
}
if response.Headers != nil {
if _, ok := response.Headers["Location"]; ok {
hasLocation = true
}
}
if response.Schema == nil {
dbg("DEBUG MISSING SCHEMA SKIP!\n")
break
}
dbg("DEBUG AnalyzeEndpoint %d RESPONSE %#v\n", code, response)
returnDef := a.Doc.Ref(response.Schema)
if returnDef != nil {
ec := EvalCtx{IsResult: true, Trail: nil, Svc: res, Method: action}
if mediaType(returnDef.Title) == "" {
warn("Warning: AnalyzeEndpoint: MediaType not set for %s, will be hard to guess the result type\n", response.Schema.ID())
continue
}
returnDT = a.AnalyzeDefinition(ec, returnDef, response.Schema.ID())
if returnObj, ok := returnDT.(*gen.ObjectDataType); ok {
isResourceType := verb == "get" && returnObj.TypeName == svc
dbg("DEBUG AnalyzeEndpoint Path %s Verb %s returnTypeName %s svc %s\n", path, verb, returnObj.TypeName, svc)
if isResourceType {
res.Description = cleanDescription(ep.Description)
res.Identifier = mediaType(returnDef.Title)
}
a.addType(ec, returnObj, response.Schema)
}
} else {
returnDT = basicType(response.Schema.Type())
}
break
}
for _, p := range ep.Parameters {
ec := EvalCtx{IsResult: false, Trail: nil, Svc: res, Method: action}
ap := a.AnalyzeParam(ec, p)
switch p.In {
case "header":
action.HeaderParamNames = append(action.HeaderParamNames, p.Name)
action.Params = append(action.Params, ap)
case "query":
action.QueryParamNames = append(action.QueryParamNames, p.Name)
action.Params = append(action.Params, ap)
case "path":
action.PathParamNames = append(action.PathParamNames, p.Name)
action.Params = append(action.Params, ap)
case "body":
def := a.Doc.Ref(p.Schema)
if def != nil {
if def.Type == "array" {
fail("Array type for body not implemented yet")
} else if def.Type == "object" {
// Flatten the first level of object
dt := a.AnalyzeDefinition(ec, def, p.Schema.ID())
if obj, ok := dt.(*gen.ObjectDataType); ok {
a.addType(ec, obj, p.Schema)
action.Payload = obj
for _, f := range obj.Fields {
action.PayloadParamNames = append(action.PayloadParamNames, f.Name)
action.Params = append(action.Params, f)
}
}
}
}
}
}
if returnDT != nil {
action.Return = signature(returnDT)
}
action.ReturnLocation = hasLocation
dbg("DEBUG ACTION %s", prettify(action))
return nil
}
|
[
"func",
"(",
"a",
"*",
"APIAnalyzer",
")",
"AnalyzeEndpoint",
"(",
"verb",
"string",
",",
"path",
"string",
",",
"ep",
"*",
"Endpoint",
")",
"error",
"{",
"path",
"=",
"joinPath",
"(",
"a",
".",
"Doc",
".",
"BasePath",
",",
"path",
")",
"\n",
"dbg",
"(",
"\"\\n------\\nDEBUG AnalyzeEndpoint %s %s %+v\\n\"",
",",
"\\n",
",",
"\\n",
",",
"\\n",
")",
"\n",
"verb",
"\n",
"path",
"\n",
"ep",
"\n",
"pattern",
":=",
"toPattern",
"(",
"verb",
",",
"path",
")",
"\n",
"dbg",
"(",
"\"DEBUG AnalyzeEndpoint pattern %v\\n\"",
",",
"\\n",
")",
"\n",
"pattern",
"\n",
"svc",
":=",
"ep",
".",
"Service",
"(",
")",
"\n",
"res",
":=",
"a",
".",
"api",
".",
"Resources",
"[",
"svc",
"]",
"\n",
"if",
"res",
"==",
"nil",
"{",
"res",
"=",
"&",
"gen",
".",
"Resource",
"{",
"Name",
":",
"svc",
",",
"ClientName",
":",
"a",
".",
"ClientName",
",",
"Actions",
":",
"[",
"]",
"*",
"gen",
".",
"Action",
"{",
"}",
",",
"}",
"\n",
"a",
".",
"api",
".",
"Resources",
"[",
"svc",
"]",
"=",
"res",
"\n",
"}",
"\n",
"action",
":=",
"&",
"gen",
".",
"Action",
"{",
"Name",
":",
"ep",
".",
"Method",
"(",
")",
",",
"MethodName",
":",
"toMethodName",
"(",
"ep",
".",
"Method",
"(",
")",
")",
",",
"Description",
":",
"cleanDescription",
"(",
"ep",
".",
"Description",
")",
",",
"ResourceName",
":",
"svc",
",",
"PathPatterns",
":",
"[",
"]",
"*",
"gen",
".",
"PathPattern",
"{",
"pattern",
"}",
",",
"}",
"\n",
"res",
".",
"Actions",
"=",
"append",
"(",
"res",
".",
"Actions",
",",
"action",
")",
"\n",
"var",
"returnDT",
"gen",
".",
"DataType",
"\n",
"var",
"hasLocation",
"bool",
"\n",
"for",
"code",
",",
"response",
":=",
"range",
"ep",
".",
"Responses",
"{",
"if",
"code",
">=",
"300",
"{",
"continue",
"\n",
"}",
"\n",
"if",
"response",
".",
"Headers",
"!=",
"nil",
"{",
"if",
"_",
",",
"ok",
":=",
"response",
".",
"Headers",
"[",
"\"Location\"",
"]",
";",
"ok",
"{",
"hasLocation",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"response",
".",
"Schema",
"==",
"nil",
"{",
"dbg",
"(",
"\"DEBUG MISSING SCHEMA SKIP!\\n\"",
")",
"\n",
"\\n",
"\n",
"}",
"\n",
"break",
"\n",
"dbg",
"(",
"\"DEBUG AnalyzeEndpoint %d RESPONSE %#v\\n\"",
",",
"\\n",
",",
"code",
")",
"\n",
"response",
"\n",
"returnDef",
":=",
"a",
".",
"Doc",
".",
"Ref",
"(",
"response",
".",
"Schema",
")",
"\n",
"}",
"\n",
"if",
"returnDef",
"!=",
"nil",
"{",
"ec",
":=",
"EvalCtx",
"{",
"IsResult",
":",
"true",
",",
"Trail",
":",
"nil",
",",
"Svc",
":",
"res",
",",
"Method",
":",
"action",
"}",
"\n",
"if",
"mediaType",
"(",
"returnDef",
".",
"Title",
")",
"==",
"\"\"",
"{",
"warn",
"(",
"\"Warning: AnalyzeEndpoint: MediaType not set for %s, will be hard to guess the result type\\n\"",
",",
"\\n",
")",
"\n",
"response",
".",
"Schema",
".",
"ID",
"(",
")",
"\n",
"}",
"\n",
"continue",
"\n",
"returnDT",
"=",
"a",
".",
"AnalyzeDefinition",
"(",
"ec",
",",
"returnDef",
",",
"response",
".",
"Schema",
".",
"ID",
"(",
")",
")",
"\n",
"}",
"else",
"if",
"returnObj",
",",
"ok",
":=",
"returnDT",
".",
"(",
"*",
"gen",
".",
"ObjectDataType",
")",
";",
"ok",
"{",
"isResourceType",
":=",
"verb",
"==",
"\"get\"",
"&&",
"returnObj",
".",
"TypeName",
"==",
"svc",
"\n",
"dbg",
"(",
"\"DEBUG AnalyzeEndpoint Path %s Verb %s returnTypeName %s svc %s\\n\"",
",",
"\\n",
",",
"path",
",",
"verb",
",",
"returnObj",
".",
"TypeName",
")",
"\n",
"svc",
"\n",
"if",
"isResourceType",
"{",
"res",
".",
"Description",
"=",
"cleanDescription",
"(",
"ep",
".",
"Description",
")",
"\n",
"res",
".",
"Identifier",
"=",
"mediaType",
"(",
"returnDef",
".",
"Title",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// AnalyzeEndpoint creates an API descriptor from goa v2 generated swagger definition
|
[
"AnalyzeEndpoint",
"creates",
"an",
"API",
"descriptor",
"from",
"goa",
"v2",
"generated",
"swagger",
"definition"
] |
96079a1ee7238dae9cbb7efa77dd94a479d217bd
|
https://github.com/rightscale/rsc/blob/96079a1ee7238dae9cbb7efa77dd94a479d217bd/gen/goav2gen/endpoint.go#L34-L146
|
test
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.