id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequencelengths 21
1.41k
| docstring
stringlengths 6
2.61k
| docstring_tokens
sequencelengths 3
215
| sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
165,100 | hashicorp/packer | helper/ssh/key_pair.go | authorizedKeysLine | func authorizedKeysLine(key gossh.PublicKey, comment string) []byte {
marshaledPublicKey := gossh.MarshalAuthorizedKey(key)
// Remove the mandatory unix new line. Awful, but the go
// ssh library automatically appends a unix new line.
// We remove it so a key comment can be safely appended to the
// end of the string.
marshaledPublicKey = bytes.TrimSpace(marshaledPublicKey)
if len(strings.TrimSpace(comment)) > 0 {
marshaledPublicKey = append(marshaledPublicKey, ' ')
marshaledPublicKey = append(marshaledPublicKey, comment...)
}
return marshaledPublicKey
} | go | func authorizedKeysLine(key gossh.PublicKey, comment string) []byte {
marshaledPublicKey := gossh.MarshalAuthorizedKey(key)
// Remove the mandatory unix new line. Awful, but the go
// ssh library automatically appends a unix new line.
// We remove it so a key comment can be safely appended to the
// end of the string.
marshaledPublicKey = bytes.TrimSpace(marshaledPublicKey)
if len(strings.TrimSpace(comment)) > 0 {
marshaledPublicKey = append(marshaledPublicKey, ' ')
marshaledPublicKey = append(marshaledPublicKey, comment...)
}
return marshaledPublicKey
} | [
"func",
"authorizedKeysLine",
"(",
"key",
"gossh",
".",
"PublicKey",
",",
"comment",
"string",
")",
"[",
"]",
"byte",
"{",
"marshaledPublicKey",
":=",
"gossh",
".",
"MarshalAuthorizedKey",
"(",
"key",
")",
"\n\n",
"// Remove the mandatory unix new line. Awful, but the go",
"// ssh library automatically appends a unix new line.",
"// We remove it so a key comment can be safely appended to the",
"// end of the string.",
"marshaledPublicKey",
"=",
"bytes",
".",
"TrimSpace",
"(",
"marshaledPublicKey",
")",
"\n\n",
"if",
"len",
"(",
"strings",
".",
"TrimSpace",
"(",
"comment",
")",
")",
">",
"0",
"{",
"marshaledPublicKey",
"=",
"append",
"(",
"marshaledPublicKey",
",",
"' '",
")",
"\n",
"marshaledPublicKey",
"=",
"append",
"(",
"marshaledPublicKey",
",",
"comment",
"...",
")",
"\n",
"}",
"\n\n",
"return",
"marshaledPublicKey",
"\n",
"}"
] | // authorizedKeysLine serializes key for inclusion in an OpenSSH
// authorized_keys file. The return value ends without newline so
// a comment can be appended to the end. | [
"authorizedKeysLine",
"serializes",
"key",
"for",
"inclusion",
"in",
"an",
"OpenSSH",
"authorized_keys",
"file",
".",
"The",
"return",
"value",
"ends",
"without",
"newline",
"so",
"a",
"comment",
"can",
"be",
"appended",
"to",
"the",
"end",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/helper/ssh/key_pair.go#L243-L258 |
165,101 | hashicorp/packer | template/template.go | Raw | func (t *Template) Raw() (*rawTemplate, error) {
var out rawTemplate
out.MinVersion = t.MinVersion
out.Description = t.Description
for k, v := range t.Comments {
out.Comments = append(out.Comments, map[string]string{k: v})
}
for _, b := range t.Builders {
out.Builders = append(out.Builders, b)
}
for _, p := range t.Provisioners {
out.Provisioners = append(out.Provisioners, p)
}
for _, pp := range t.PostProcessors {
out.PostProcessors = append(out.PostProcessors, pp)
}
for _, v := range t.SensitiveVariables {
out.SensitiveVariables = append(out.SensitiveVariables, v.Key)
}
for k, v := range t.Variables {
if out.Variables == nil {
out.Variables = make(map[string]interface{})
}
out.Variables[k] = v
}
if t.Push.Name != "" {
b, _ := json.Marshal(t.Push)
var m map[string]interface{}
_ = json.Unmarshal(b, &m)
out.Push = m
}
return &out, nil
} | go | func (t *Template) Raw() (*rawTemplate, error) {
var out rawTemplate
out.MinVersion = t.MinVersion
out.Description = t.Description
for k, v := range t.Comments {
out.Comments = append(out.Comments, map[string]string{k: v})
}
for _, b := range t.Builders {
out.Builders = append(out.Builders, b)
}
for _, p := range t.Provisioners {
out.Provisioners = append(out.Provisioners, p)
}
for _, pp := range t.PostProcessors {
out.PostProcessors = append(out.PostProcessors, pp)
}
for _, v := range t.SensitiveVariables {
out.SensitiveVariables = append(out.SensitiveVariables, v.Key)
}
for k, v := range t.Variables {
if out.Variables == nil {
out.Variables = make(map[string]interface{})
}
out.Variables[k] = v
}
if t.Push.Name != "" {
b, _ := json.Marshal(t.Push)
var m map[string]interface{}
_ = json.Unmarshal(b, &m)
out.Push = m
}
return &out, nil
} | [
"func",
"(",
"t",
"*",
"Template",
")",
"Raw",
"(",
")",
"(",
"*",
"rawTemplate",
",",
"error",
")",
"{",
"var",
"out",
"rawTemplate",
"\n\n",
"out",
".",
"MinVersion",
"=",
"t",
".",
"MinVersion",
"\n",
"out",
".",
"Description",
"=",
"t",
".",
"Description",
"\n\n",
"for",
"k",
",",
"v",
":=",
"range",
"t",
".",
"Comments",
"{",
"out",
".",
"Comments",
"=",
"append",
"(",
"out",
".",
"Comments",
",",
"map",
"[",
"string",
"]",
"string",
"{",
"k",
":",
"v",
"}",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"b",
":=",
"range",
"t",
".",
"Builders",
"{",
"out",
".",
"Builders",
"=",
"append",
"(",
"out",
".",
"Builders",
",",
"b",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"p",
":=",
"range",
"t",
".",
"Provisioners",
"{",
"out",
".",
"Provisioners",
"=",
"append",
"(",
"out",
".",
"Provisioners",
",",
"p",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"pp",
":=",
"range",
"t",
".",
"PostProcessors",
"{",
"out",
".",
"PostProcessors",
"=",
"append",
"(",
"out",
".",
"PostProcessors",
",",
"pp",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"v",
":=",
"range",
"t",
".",
"SensitiveVariables",
"{",
"out",
".",
"SensitiveVariables",
"=",
"append",
"(",
"out",
".",
"SensitiveVariables",
",",
"v",
".",
"Key",
")",
"\n",
"}",
"\n\n",
"for",
"k",
",",
"v",
":=",
"range",
"t",
".",
"Variables",
"{",
"if",
"out",
".",
"Variables",
"==",
"nil",
"{",
"out",
".",
"Variables",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"}",
"\n\n",
"out",
".",
"Variables",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n\n",
"if",
"t",
".",
"Push",
".",
"Name",
"!=",
"\"",
"\"",
"{",
"b",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"t",
".",
"Push",
")",
"\n\n",
"var",
"m",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"\n",
"_",
"=",
"json",
".",
"Unmarshal",
"(",
"b",
",",
"&",
"m",
")",
"\n\n",
"out",
".",
"Push",
"=",
"m",
"\n",
"}",
"\n\n",
"return",
"&",
"out",
",",
"nil",
"\n",
"}"
] | // Raw converts a Template struct back into the raw Packer template structure | [
"Raw",
"converts",
"a",
"Template",
"struct",
"back",
"into",
"the",
"raw",
"Packer",
"template",
"structure"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/template/template.go#L35-L79 |
165,102 | hashicorp/packer | template/template.go | MarshalJSON | func (b *Builder) MarshalJSON() ([]byte, error) {
// Avoid recursion
type Builder_ Builder
out, _ := json.Marshal(Builder_(*b))
var m map[string]json.RawMessage
_ = json.Unmarshal(out, &m)
// Flatten Config
delete(m, "config")
for k, v := range b.Config {
out, _ = json.Marshal(v)
m[k] = out
}
return json.Marshal(m)
} | go | func (b *Builder) MarshalJSON() ([]byte, error) {
// Avoid recursion
type Builder_ Builder
out, _ := json.Marshal(Builder_(*b))
var m map[string]json.RawMessage
_ = json.Unmarshal(out, &m)
// Flatten Config
delete(m, "config")
for k, v := range b.Config {
out, _ = json.Marshal(v)
m[k] = out
}
return json.Marshal(m)
} | [
"func",
"(",
"b",
"*",
"Builder",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"// Avoid recursion",
"type",
"Builder_",
"Builder",
"\n",
"out",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"Builder_",
"(",
"*",
"b",
")",
")",
"\n\n",
"var",
"m",
"map",
"[",
"string",
"]",
"json",
".",
"RawMessage",
"\n",
"_",
"=",
"json",
".",
"Unmarshal",
"(",
"out",
",",
"&",
"m",
")",
"\n\n",
"// Flatten Config",
"delete",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"b",
".",
"Config",
"{",
"out",
",",
"_",
"=",
"json",
".",
"Marshal",
"(",
"v",
")",
"\n",
"m",
"[",
"k",
"]",
"=",
"out",
"\n",
"}",
"\n\n",
"return",
"json",
".",
"Marshal",
"(",
"m",
")",
"\n",
"}"
] | // MarshalJSON conducts the necessary flattening of the Builder struct
// to provide valid Packer template JSON | [
"MarshalJSON",
"conducts",
"the",
"necessary",
"flattening",
"of",
"the",
"Builder",
"struct",
"to",
"provide",
"valid",
"Packer",
"template",
"JSON"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/template/template.go#L90-L106 |
165,103 | hashicorp/packer | template/template.go | MarshalJSON | func (p *PostProcessor) MarshalJSON() ([]byte, error) {
// Early exit for simple definitions
if len(p.Config) == 0 && len(p.OnlyExcept.Only) == 0 && len(p.OnlyExcept.Except) == 0 && p.KeepInputArtifact == nil {
return json.Marshal(p.Type)
}
// Avoid recursion
type PostProcessor_ PostProcessor
out, _ := json.Marshal(PostProcessor_(*p))
var m map[string]json.RawMessage
_ = json.Unmarshal(out, &m)
// Flatten Config
delete(m, "config")
for k, v := range p.Config {
out, _ = json.Marshal(v)
m[k] = out
}
return json.Marshal(m)
} | go | func (p *PostProcessor) MarshalJSON() ([]byte, error) {
// Early exit for simple definitions
if len(p.Config) == 0 && len(p.OnlyExcept.Only) == 0 && len(p.OnlyExcept.Except) == 0 && p.KeepInputArtifact == nil {
return json.Marshal(p.Type)
}
// Avoid recursion
type PostProcessor_ PostProcessor
out, _ := json.Marshal(PostProcessor_(*p))
var m map[string]json.RawMessage
_ = json.Unmarshal(out, &m)
// Flatten Config
delete(m, "config")
for k, v := range p.Config {
out, _ = json.Marshal(v)
m[k] = out
}
return json.Marshal(m)
} | [
"func",
"(",
"p",
"*",
"PostProcessor",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"// Early exit for simple definitions",
"if",
"len",
"(",
"p",
".",
"Config",
")",
"==",
"0",
"&&",
"len",
"(",
"p",
".",
"OnlyExcept",
".",
"Only",
")",
"==",
"0",
"&&",
"len",
"(",
"p",
".",
"OnlyExcept",
".",
"Except",
")",
"==",
"0",
"&&",
"p",
".",
"KeepInputArtifact",
"==",
"nil",
"{",
"return",
"json",
".",
"Marshal",
"(",
"p",
".",
"Type",
")",
"\n",
"}",
"\n\n",
"// Avoid recursion",
"type",
"PostProcessor_",
"PostProcessor",
"\n",
"out",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"PostProcessor_",
"(",
"*",
"p",
")",
")",
"\n\n",
"var",
"m",
"map",
"[",
"string",
"]",
"json",
".",
"RawMessage",
"\n",
"_",
"=",
"json",
".",
"Unmarshal",
"(",
"out",
",",
"&",
"m",
")",
"\n\n",
"// Flatten Config",
"delete",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"p",
".",
"Config",
"{",
"out",
",",
"_",
"=",
"json",
".",
"Marshal",
"(",
"v",
")",
"\n",
"m",
"[",
"k",
"]",
"=",
"out",
"\n",
"}",
"\n\n",
"return",
"json",
".",
"Marshal",
"(",
"m",
")",
"\n",
"}"
] | // MarshalJSON conducts the necessary flattening of the PostProcessor struct
// to provide valid Packer template JSON | [
"MarshalJSON",
"conducts",
"the",
"necessary",
"flattening",
"of",
"the",
"PostProcessor",
"struct",
"to",
"provide",
"valid",
"Packer",
"template",
"JSON"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/template/template.go#L120-L141 |
165,104 | hashicorp/packer | template/template.go | MarshalJSON | func (p *Provisioner) MarshalJSON() ([]byte, error) {
// Avoid recursion
type Provisioner_ Provisioner
out, _ := json.Marshal(Provisioner_(*p))
var m map[string]json.RawMessage
_ = json.Unmarshal(out, &m)
// Flatten Config
delete(m, "config")
for k, v := range p.Config {
out, _ = json.Marshal(v)
m[k] = out
}
return json.Marshal(m)
} | go | func (p *Provisioner) MarshalJSON() ([]byte, error) {
// Avoid recursion
type Provisioner_ Provisioner
out, _ := json.Marshal(Provisioner_(*p))
var m map[string]json.RawMessage
_ = json.Unmarshal(out, &m)
// Flatten Config
delete(m, "config")
for k, v := range p.Config {
out, _ = json.Marshal(v)
m[k] = out
}
return json.Marshal(m)
} | [
"func",
"(",
"p",
"*",
"Provisioner",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"// Avoid recursion",
"type",
"Provisioner_",
"Provisioner",
"\n",
"out",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"Provisioner_",
"(",
"*",
"p",
")",
")",
"\n\n",
"var",
"m",
"map",
"[",
"string",
"]",
"json",
".",
"RawMessage",
"\n",
"_",
"=",
"json",
".",
"Unmarshal",
"(",
"out",
",",
"&",
"m",
")",
"\n\n",
"// Flatten Config",
"delete",
"(",
"m",
",",
"\"",
"\"",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"p",
".",
"Config",
"{",
"out",
",",
"_",
"=",
"json",
".",
"Marshal",
"(",
"v",
")",
"\n",
"m",
"[",
"k",
"]",
"=",
"out",
"\n",
"}",
"\n\n",
"return",
"json",
".",
"Marshal",
"(",
"m",
")",
"\n",
"}"
] | // MarshalJSON conducts the necessary flattening of the Provisioner struct
// to provide valid Packer template JSON | [
"MarshalJSON",
"conducts",
"the",
"necessary",
"flattening",
"of",
"the",
"Provisioner",
"struct",
"to",
"provide",
"valid",
"Packer",
"template",
"JSON"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/template/template.go#L156-L172 |
165,105 | hashicorp/packer | template/template.go | Skip | func (o *OnlyExcept) Skip(n string) bool {
if len(o.Only) > 0 {
for _, v := range o.Only {
if v == n {
return false
}
}
return true
}
if len(o.Except) > 0 {
for _, v := range o.Except {
if v == n {
return true
}
}
return false
}
return false
} | go | func (o *OnlyExcept) Skip(n string) bool {
if len(o.Only) > 0 {
for _, v := range o.Only {
if v == n {
return false
}
}
return true
}
if len(o.Except) > 0 {
for _, v := range o.Except {
if v == n {
return true
}
}
return false
}
return false
} | [
"func",
"(",
"o",
"*",
"OnlyExcept",
")",
"Skip",
"(",
"n",
"string",
")",
"bool",
"{",
"if",
"len",
"(",
"o",
".",
"Only",
")",
">",
"0",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"o",
".",
"Only",
"{",
"if",
"v",
"==",
"n",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"true",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"o",
".",
"Except",
")",
">",
"0",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"o",
".",
"Except",
"{",
"if",
"v",
"==",
"n",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"false",
"\n",
"}",
"\n\n",
"return",
"false",
"\n",
"}"
] | // Skip says whether or not to skip the build with the given name. | [
"Skip",
"says",
"whether",
"or",
"not",
"to",
"skip",
"the",
"build",
"with",
"the",
"given",
"name",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/template/template.go#L264-L286 |
165,106 | hashicorp/packer | template/template.go | Validate | func (o *OnlyExcept) Validate(t *Template) error {
if len(o.Only) > 0 && len(o.Except) > 0 {
return errors.New("only one of 'only' or 'except' may be specified")
}
var err error
for _, n := range o.Only {
if _, ok := t.Builders[n]; !ok {
err = multierror.Append(err, fmt.Errorf(
"'only' specified builder '%s' not found", n))
}
}
for _, n := range o.Except {
if _, ok := t.Builders[n]; !ok {
err = multierror.Append(err, fmt.Errorf(
"'except' specified builder '%s' not found", n))
}
}
return err
} | go | func (o *OnlyExcept) Validate(t *Template) error {
if len(o.Only) > 0 && len(o.Except) > 0 {
return errors.New("only one of 'only' or 'except' may be specified")
}
var err error
for _, n := range o.Only {
if _, ok := t.Builders[n]; !ok {
err = multierror.Append(err, fmt.Errorf(
"'only' specified builder '%s' not found", n))
}
}
for _, n := range o.Except {
if _, ok := t.Builders[n]; !ok {
err = multierror.Append(err, fmt.Errorf(
"'except' specified builder '%s' not found", n))
}
}
return err
} | [
"func",
"(",
"o",
"*",
"OnlyExcept",
")",
"Validate",
"(",
"t",
"*",
"Template",
")",
"error",
"{",
"if",
"len",
"(",
"o",
".",
"Only",
")",
">",
"0",
"&&",
"len",
"(",
"o",
".",
"Except",
")",
">",
"0",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"err",
"error",
"\n",
"for",
"_",
",",
"n",
":=",
"range",
"o",
".",
"Only",
"{",
"if",
"_",
",",
"ok",
":=",
"t",
".",
"Builders",
"[",
"n",
"]",
";",
"!",
"ok",
"{",
"err",
"=",
"multierror",
".",
"Append",
"(",
"err",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"n",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"n",
":=",
"range",
"o",
".",
"Except",
"{",
"if",
"_",
",",
"ok",
":=",
"t",
".",
"Builders",
"[",
"n",
"]",
";",
"!",
"ok",
"{",
"err",
"=",
"multierror",
".",
"Append",
"(",
"err",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"n",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"err",
"\n",
"}"
] | // Validate validates that the OnlyExcept settings are correct for a thing. | [
"Validate",
"validates",
"that",
"the",
"OnlyExcept",
"settings",
"are",
"correct",
"for",
"a",
"thing",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/template/template.go#L289-L309 |
165,107 | hashicorp/packer | builder/vmware/iso/config.go | validateVMXTemplatePath | func (c *Config) validateVMXTemplatePath() error {
f, err := os.Open(c.VMXTemplatePath)
if err != nil {
return err
}
defer f.Close()
data, err := ioutil.ReadAll(f)
if err != nil {
return err
}
return interpolate.Validate(string(data), &c.ctx)
} | go | func (c *Config) validateVMXTemplatePath() error {
f, err := os.Open(c.VMXTemplatePath)
if err != nil {
return err
}
defer f.Close()
data, err := ioutil.ReadAll(f)
if err != nil {
return err
}
return interpolate.Validate(string(data), &c.ctx)
} | [
"func",
"(",
"c",
"*",
"Config",
")",
"validateVMXTemplatePath",
"(",
")",
"error",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"c",
".",
"VMXTemplatePath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n\n",
"data",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"f",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"interpolate",
".",
"Validate",
"(",
"string",
"(",
"data",
")",
",",
"&",
"c",
".",
"ctx",
")",
"\n",
"}"
] | // Make sure custom vmx template exists and that data can be read from it | [
"Make",
"sure",
"custom",
"vmx",
"template",
"exists",
"and",
"that",
"data",
"can",
"be",
"read",
"from",
"it"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/vmware/iso/config.go#L245-L258 |
165,108 | hashicorp/packer | post-processor/vagrant/util.go | CopyContents | func CopyContents(dst, src string) error {
srcF, err := os.Open(src)
if err != nil {
return err
}
defer srcF.Close()
dstDir, _ := filepath.Split(dst)
if dstDir != "" {
err := os.MkdirAll(dstDir, 0755)
if err != nil {
return err
}
}
dstF, err := os.Create(dst)
if err != nil {
return err
}
defer dstF.Close()
if _, err := io.Copy(dstF, srcF); err != nil {
return err
}
return nil
} | go | func CopyContents(dst, src string) error {
srcF, err := os.Open(src)
if err != nil {
return err
}
defer srcF.Close()
dstDir, _ := filepath.Split(dst)
if dstDir != "" {
err := os.MkdirAll(dstDir, 0755)
if err != nil {
return err
}
}
dstF, err := os.Create(dst)
if err != nil {
return err
}
defer dstF.Close()
if _, err := io.Copy(dstF, srcF); err != nil {
return err
}
return nil
} | [
"func",
"CopyContents",
"(",
"dst",
",",
"src",
"string",
")",
"error",
"{",
"srcF",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"src",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"srcF",
".",
"Close",
"(",
")",
"\n\n",
"dstDir",
",",
"_",
":=",
"filepath",
".",
"Split",
"(",
"dst",
")",
"\n",
"if",
"dstDir",
"!=",
"\"",
"\"",
"{",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"dstDir",
",",
"0755",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"dstF",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"dst",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"dstF",
".",
"Close",
"(",
")",
"\n\n",
"if",
"_",
",",
"err",
":=",
"io",
".",
"Copy",
"(",
"dstF",
",",
"srcF",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Copies a file by copying the contents of the file to another place. | [
"Copies",
"a",
"file",
"by",
"copying",
"the",
"contents",
"of",
"the",
"file",
"to",
"another",
"place",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/post-processor/vagrant/util.go#L26-L52 |
165,109 | hashicorp/packer | post-processor/vagrant/util.go | DirToBox | func DirToBox(dst, dir string, ui packer.Ui, level int) error {
log.Printf("Turning dir into box: %s => %s", dir, dst)
// Make the containing directory, if it does not already exist
err := os.MkdirAll(filepath.Dir(dst), 0755)
if err != nil {
return err
}
dstF, err := os.Create(dst)
if err != nil {
return err
}
defer dstF.Close()
var dstWriter io.WriteCloser = dstF
if level != flate.NoCompression {
log.Printf("Compressing with gzip compression level: %d", level)
gzipWriter, err := makePgzipWriter(dstWriter, level)
if err != nil {
return err
}
defer gzipWriter.Close()
dstWriter = gzipWriter
}
tarWriter := tar.NewWriter(dstWriter)
defer tarWriter.Close()
// This is the walk func that tars each of the files in the dir
tarWalk := func(path string, info os.FileInfo, prevErr error) error {
// If there was a prior error, return it
if prevErr != nil {
return prevErr
}
// Skip directories
if info.IsDir() {
log.Printf("Skipping directory '%s' for box '%s'", path, dst)
return nil
}
log.Printf("Box add: '%s' to '%s'", path, dst)
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
header, err := tar.FileInfoHeader(info, "")
if err != nil {
return err
}
// go >=1.10 wants to use GNU tar format to workaround issues in
// libarchive < 3.3.2
setHeaderFormat(header)
// We have to set the Name explicitly because it is supposed to
// be a relative path to the root. Otherwise, the tar ends up
// being a bunch of files in the root, even if they're actually
// nested in a dir in the original "dir" param.
header.Name, err = filepath.Rel(dir, path)
if err != nil {
return err
}
if ui != nil {
ui.Message(fmt.Sprintf("Compressing: %s", header.Name))
}
if err := tarWriter.WriteHeader(header); err != nil {
return err
}
if _, err := io.Copy(tarWriter, f); err != nil {
return err
}
return nil
}
// Tar.gz everything up
return filepath.Walk(dir, tarWalk)
} | go | func DirToBox(dst, dir string, ui packer.Ui, level int) error {
log.Printf("Turning dir into box: %s => %s", dir, dst)
// Make the containing directory, if it does not already exist
err := os.MkdirAll(filepath.Dir(dst), 0755)
if err != nil {
return err
}
dstF, err := os.Create(dst)
if err != nil {
return err
}
defer dstF.Close()
var dstWriter io.WriteCloser = dstF
if level != flate.NoCompression {
log.Printf("Compressing with gzip compression level: %d", level)
gzipWriter, err := makePgzipWriter(dstWriter, level)
if err != nil {
return err
}
defer gzipWriter.Close()
dstWriter = gzipWriter
}
tarWriter := tar.NewWriter(dstWriter)
defer tarWriter.Close()
// This is the walk func that tars each of the files in the dir
tarWalk := func(path string, info os.FileInfo, prevErr error) error {
// If there was a prior error, return it
if prevErr != nil {
return prevErr
}
// Skip directories
if info.IsDir() {
log.Printf("Skipping directory '%s' for box '%s'", path, dst)
return nil
}
log.Printf("Box add: '%s' to '%s'", path, dst)
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
header, err := tar.FileInfoHeader(info, "")
if err != nil {
return err
}
// go >=1.10 wants to use GNU tar format to workaround issues in
// libarchive < 3.3.2
setHeaderFormat(header)
// We have to set the Name explicitly because it is supposed to
// be a relative path to the root. Otherwise, the tar ends up
// being a bunch of files in the root, even if they're actually
// nested in a dir in the original "dir" param.
header.Name, err = filepath.Rel(dir, path)
if err != nil {
return err
}
if ui != nil {
ui.Message(fmt.Sprintf("Compressing: %s", header.Name))
}
if err := tarWriter.WriteHeader(header); err != nil {
return err
}
if _, err := io.Copy(tarWriter, f); err != nil {
return err
}
return nil
}
// Tar.gz everything up
return filepath.Walk(dir, tarWalk)
} | [
"func",
"DirToBox",
"(",
"dst",
",",
"dir",
"string",
",",
"ui",
"packer",
".",
"Ui",
",",
"level",
"int",
")",
"error",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"dir",
",",
"dst",
")",
"\n\n",
"// Make the containing directory, if it does not already exist",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"filepath",
".",
"Dir",
"(",
"dst",
")",
",",
"0755",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"dstF",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"dst",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"dstF",
".",
"Close",
"(",
")",
"\n\n",
"var",
"dstWriter",
"io",
".",
"WriteCloser",
"=",
"dstF",
"\n",
"if",
"level",
"!=",
"flate",
".",
"NoCompression",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"level",
")",
"\n",
"gzipWriter",
",",
"err",
":=",
"makePgzipWriter",
"(",
"dstWriter",
",",
"level",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"gzipWriter",
".",
"Close",
"(",
")",
"\n\n",
"dstWriter",
"=",
"gzipWriter",
"\n",
"}",
"\n\n",
"tarWriter",
":=",
"tar",
".",
"NewWriter",
"(",
"dstWriter",
")",
"\n",
"defer",
"tarWriter",
".",
"Close",
"(",
")",
"\n\n",
"// This is the walk func that tars each of the files in the dir",
"tarWalk",
":=",
"func",
"(",
"path",
"string",
",",
"info",
"os",
".",
"FileInfo",
",",
"prevErr",
"error",
")",
"error",
"{",
"// If there was a prior error, return it",
"if",
"prevErr",
"!=",
"nil",
"{",
"return",
"prevErr",
"\n",
"}",
"\n\n",
"// Skip directories",
"if",
"info",
".",
"IsDir",
"(",
")",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"path",
",",
"dst",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"path",
",",
"dst",
")",
"\n",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n\n",
"header",
",",
"err",
":=",
"tar",
".",
"FileInfoHeader",
"(",
"info",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// go >=1.10 wants to use GNU tar format to workaround issues in",
"// libarchive < 3.3.2",
"setHeaderFormat",
"(",
"header",
")",
"\n\n",
"// We have to set the Name explicitly because it is supposed to",
"// be a relative path to the root. Otherwise, the tar ends up",
"// being a bunch of files in the root, even if they're actually",
"// nested in a dir in the original \"dir\" param.",
"header",
".",
"Name",
",",
"err",
"=",
"filepath",
".",
"Rel",
"(",
"dir",
",",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"ui",
"!=",
"nil",
"{",
"ui",
".",
"Message",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"header",
".",
"Name",
")",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"tarWriter",
".",
"WriteHeader",
"(",
"header",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"_",
",",
"err",
":=",
"io",
".",
"Copy",
"(",
"tarWriter",
",",
"f",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Tar.gz everything up",
"return",
"filepath",
".",
"Walk",
"(",
"dir",
",",
"tarWalk",
")",
"\n",
"}"
] | // DirToBox takes the directory and compresses it into a Vagrant-compatible
// box. This function does not perform checks to verify that dir is
// actually a proper box. This is an expected precondition. | [
"DirToBox",
"takes",
"the",
"directory",
"and",
"compresses",
"it",
"into",
"a",
"Vagrant",
"-",
"compatible",
"box",
".",
"This",
"function",
"does",
"not",
"perform",
"checks",
"to",
"verify",
"that",
"dir",
"is",
"actually",
"a",
"proper",
"box",
".",
"This",
"is",
"an",
"expected",
"precondition",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/post-processor/vagrant/util.go#L74-L159 |
165,110 | hashicorp/packer | post-processor/vagrant/util.go | WriteMetadata | func WriteMetadata(dir string, contents interface{}) error {
if _, err := os.Stat(filepath.Join(dir, "metadata.json")); os.IsNotExist(err) {
f, err := os.Create(filepath.Join(dir, "metadata.json"))
if err != nil {
return err
}
defer f.Close()
enc := json.NewEncoder(f)
return enc.Encode(contents)
}
return nil
} | go | func WriteMetadata(dir string, contents interface{}) error {
if _, err := os.Stat(filepath.Join(dir, "metadata.json")); os.IsNotExist(err) {
f, err := os.Create(filepath.Join(dir, "metadata.json"))
if err != nil {
return err
}
defer f.Close()
enc := json.NewEncoder(f)
return enc.Encode(contents)
}
return nil
} | [
"func",
"WriteMetadata",
"(",
"dir",
"string",
",",
"contents",
"interface",
"{",
"}",
")",
"error",
"{",
"if",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"filepath",
".",
"Join",
"(",
"dir",
",",
"\"",
"\"",
")",
")",
";",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"filepath",
".",
"Join",
"(",
"dir",
",",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n\n",
"enc",
":=",
"json",
".",
"NewEncoder",
"(",
"f",
")",
"\n",
"return",
"enc",
".",
"Encode",
"(",
"contents",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // WriteMetadata writes the "metadata.json" file for a Vagrant box. | [
"WriteMetadata",
"writes",
"the",
"metadata",
".",
"json",
"file",
"for",
"a",
"Vagrant",
"box",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/post-processor/vagrant/util.go#L162-L175 |
165,111 | hashicorp/packer | common/uuid/uuid.go | TimeOrderedUUID | func TimeOrderedUUID() string {
unix := uint32(time.Now().UTC().Unix())
b := make([]byte, 12)
n, err := rand.Read(b)
if n != len(b) {
err = fmt.Errorf("Not enough entropy available")
}
if err != nil {
panic(err)
}
return fmt.Sprintf("%08x-%04x-%04x-%04x-%04x%08x",
unix, b[0:2], b[2:4], b[4:6], b[6:8], b[8:])
} | go | func TimeOrderedUUID() string {
unix := uint32(time.Now().UTC().Unix())
b := make([]byte, 12)
n, err := rand.Read(b)
if n != len(b) {
err = fmt.Errorf("Not enough entropy available")
}
if err != nil {
panic(err)
}
return fmt.Sprintf("%08x-%04x-%04x-%04x-%04x%08x",
unix, b[0:2], b[2:4], b[4:6], b[6:8], b[8:])
} | [
"func",
"TimeOrderedUUID",
"(",
")",
"string",
"{",
"unix",
":=",
"uint32",
"(",
"time",
".",
"Now",
"(",
")",
".",
"UTC",
"(",
")",
".",
"Unix",
"(",
")",
")",
"\n\n",
"b",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"12",
")",
"\n",
"n",
",",
"err",
":=",
"rand",
".",
"Read",
"(",
"b",
")",
"\n",
"if",
"n",
"!=",
"len",
"(",
"b",
")",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"unix",
",",
"b",
"[",
"0",
":",
"2",
"]",
",",
"b",
"[",
"2",
":",
"4",
"]",
",",
"b",
"[",
"4",
":",
"6",
"]",
",",
"b",
"[",
"6",
":",
"8",
"]",
",",
"b",
"[",
"8",
":",
"]",
")",
"\n",
"}"
] | // Generates a time ordered UUID. Top 32 bits are a timestamp,
// bottom 96 are random. | [
"Generates",
"a",
"time",
"ordered",
"UUID",
".",
"Top",
"32",
"bits",
"are",
"a",
"timestamp",
"bottom",
"96",
"are",
"random",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/common/uuid/uuid.go#L11-L24 |
165,112 | hashicorp/packer | template/interpolate/funcs.go | Funcs | func Funcs(ctx *Context) template.FuncMap {
result := make(map[string]interface{})
for k, v := range FuncGens {
result[k] = v(ctx)
}
if ctx != nil {
for k, v := range ctx.Funcs {
result[k] = v
}
}
return template.FuncMap(result)
} | go | func Funcs(ctx *Context) template.FuncMap {
result := make(map[string]interface{})
for k, v := range FuncGens {
result[k] = v(ctx)
}
if ctx != nil {
for k, v := range ctx.Funcs {
result[k] = v
}
}
return template.FuncMap(result)
} | [
"func",
"Funcs",
"(",
"ctx",
"*",
"Context",
")",
"template",
".",
"FuncMap",
"{",
"result",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"FuncGens",
"{",
"result",
"[",
"k",
"]",
"=",
"v",
"(",
"ctx",
")",
"\n",
"}",
"\n",
"if",
"ctx",
"!=",
"nil",
"{",
"for",
"k",
",",
"v",
":=",
"range",
"ctx",
".",
"Funcs",
"{",
"result",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"template",
".",
"FuncMap",
"(",
"result",
")",
"\n",
"}"
] | // Funcs returns the functions that can be used for interpolation given
// a context. | [
"Funcs",
"returns",
"the",
"functions",
"that",
"can",
"be",
"used",
"for",
"interpolation",
"given",
"a",
"context",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/template/interpolate/funcs.go#L56-L68 |
165,113 | hashicorp/packer | common/retry/retry.go | Run | func (cfg Config) Run(ctx context.Context, fn func(context.Context) error) error {
retryDelay := func() time.Duration { return 2 * time.Second }
if cfg.RetryDelay != nil {
retryDelay = cfg.RetryDelay
}
shouldRetry := func(error) bool { return true }
if cfg.ShouldRetry != nil {
shouldRetry = cfg.ShouldRetry
}
var startTimeout <-chan time.Time // nil chans never unlock !
if cfg.StartTimeout != 0 {
startTimeout = time.After(cfg.StartTimeout)
}
var err error
for try := 0; ; try++ {
if cfg.Tries != 0 && try == cfg.Tries {
return &RetryExhaustedError{err}
}
if err = fn(ctx); err == nil {
return nil
}
if !shouldRetry(err) {
return err
}
log.Print(fmt.Errorf("Retryable error: %s", err))
select {
case <-ctx.Done():
return err
case <-startTimeout:
return err
default:
time.Sleep(retryDelay())
}
}
} | go | func (cfg Config) Run(ctx context.Context, fn func(context.Context) error) error {
retryDelay := func() time.Duration { return 2 * time.Second }
if cfg.RetryDelay != nil {
retryDelay = cfg.RetryDelay
}
shouldRetry := func(error) bool { return true }
if cfg.ShouldRetry != nil {
shouldRetry = cfg.ShouldRetry
}
var startTimeout <-chan time.Time // nil chans never unlock !
if cfg.StartTimeout != 0 {
startTimeout = time.After(cfg.StartTimeout)
}
var err error
for try := 0; ; try++ {
if cfg.Tries != 0 && try == cfg.Tries {
return &RetryExhaustedError{err}
}
if err = fn(ctx); err == nil {
return nil
}
if !shouldRetry(err) {
return err
}
log.Print(fmt.Errorf("Retryable error: %s", err))
select {
case <-ctx.Done():
return err
case <-startTimeout:
return err
default:
time.Sleep(retryDelay())
}
}
} | [
"func",
"(",
"cfg",
"Config",
")",
"Run",
"(",
"ctx",
"context",
".",
"Context",
",",
"fn",
"func",
"(",
"context",
".",
"Context",
")",
"error",
")",
"error",
"{",
"retryDelay",
":=",
"func",
"(",
")",
"time",
".",
"Duration",
"{",
"return",
"2",
"*",
"time",
".",
"Second",
"}",
"\n",
"if",
"cfg",
".",
"RetryDelay",
"!=",
"nil",
"{",
"retryDelay",
"=",
"cfg",
".",
"RetryDelay",
"\n",
"}",
"\n",
"shouldRetry",
":=",
"func",
"(",
"error",
")",
"bool",
"{",
"return",
"true",
"}",
"\n",
"if",
"cfg",
".",
"ShouldRetry",
"!=",
"nil",
"{",
"shouldRetry",
"=",
"cfg",
".",
"ShouldRetry",
"\n",
"}",
"\n",
"var",
"startTimeout",
"<-",
"chan",
"time",
".",
"Time",
"// nil chans never unlock !",
"\n",
"if",
"cfg",
".",
"StartTimeout",
"!=",
"0",
"{",
"startTimeout",
"=",
"time",
".",
"After",
"(",
"cfg",
".",
"StartTimeout",
")",
"\n",
"}",
"\n\n",
"var",
"err",
"error",
"\n",
"for",
"try",
":=",
"0",
";",
";",
"try",
"++",
"{",
"if",
"cfg",
".",
"Tries",
"!=",
"0",
"&&",
"try",
"==",
"cfg",
".",
"Tries",
"{",
"return",
"&",
"RetryExhaustedError",
"{",
"err",
"}",
"\n",
"}",
"\n",
"if",
"err",
"=",
"fn",
"(",
"ctx",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"!",
"shouldRetry",
"(",
"err",
")",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"log",
".",
"Print",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n\n",
"select",
"{",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"return",
"err",
"\n",
"case",
"<-",
"startTimeout",
":",
"return",
"err",
"\n",
"default",
":",
"time",
".",
"Sleep",
"(",
"retryDelay",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Run fn until context is cancelled up until StartTimeout time has passed. | [
"Run",
"fn",
"until",
"context",
"is",
"cancelled",
"up",
"until",
"StartTimeout",
"time",
"has",
"passed",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/common/retry/retry.go#L40-L77 |
165,114 | hashicorp/packer | builder/azure/arm/tempname.go | generatePassword | func generatePassword() string {
var s string
for i := 0; i < 100; i++ {
s := random.AlphaNum(32)
if !strings.ContainsAny(s, random.PossibleNumbers) {
continue
}
if !strings.ContainsAny(s, random.PossibleLowerCase) {
continue
}
if !strings.ContainsAny(s, random.PossibleUpperCase) {
continue
}
return s
}
// if an acceptable password cannot be generated in 100 tries, give up
return s
} | go | func generatePassword() string {
var s string
for i := 0; i < 100; i++ {
s := random.AlphaNum(32)
if !strings.ContainsAny(s, random.PossibleNumbers) {
continue
}
if !strings.ContainsAny(s, random.PossibleLowerCase) {
continue
}
if !strings.ContainsAny(s, random.PossibleUpperCase) {
continue
}
return s
}
// if an acceptable password cannot be generated in 100 tries, give up
return s
} | [
"func",
"generatePassword",
"(",
")",
"string",
"{",
"var",
"s",
"string",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"100",
";",
"i",
"++",
"{",
"s",
":=",
"random",
".",
"AlphaNum",
"(",
"32",
")",
"\n",
"if",
"!",
"strings",
".",
"ContainsAny",
"(",
"s",
",",
"random",
".",
"PossibleNumbers",
")",
"{",
"continue",
"\n",
"}",
"\n\n",
"if",
"!",
"strings",
".",
"ContainsAny",
"(",
"s",
",",
"random",
".",
"PossibleLowerCase",
")",
"{",
"continue",
"\n",
"}",
"\n\n",
"if",
"!",
"strings",
".",
"ContainsAny",
"(",
"s",
",",
"random",
".",
"PossibleUpperCase",
")",
"{",
"continue",
"\n",
"}",
"\n\n",
"return",
"s",
"\n",
"}",
"\n\n",
"// if an acceptable password cannot be generated in 100 tries, give up",
"return",
"s",
"\n",
"}"
] | // generate a password that is acceptable to Azure
// Three of the four items must be met.
// 1. Contains an uppercase character
// 2. Contains a lowercase character
// 3. Contains a numeric digit
// 4. Contains a special character | [
"generate",
"a",
"password",
"that",
"is",
"acceptable",
"to",
"Azure",
"Three",
"of",
"the",
"four",
"items",
"must",
"be",
"met",
".",
"1",
".",
"Contains",
"an",
"uppercase",
"character",
"2",
".",
"Contains",
"a",
"lowercase",
"character",
"3",
".",
"Contains",
"a",
"numeric",
"digit",
"4",
".",
"Contains",
"a",
"special",
"character"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/azure/arm/tempname.go#L50-L71 |
165,115 | hashicorp/packer | post-processor/vsphere-template/step_mark_as_template.go | unregisterPreviousVM | func unregisterPreviousVM(cli *govmomi.Client, folder *object.Folder, name string) error {
si := object.NewSearchIndex(cli.Client)
fullPath := path.Join(folder.InventoryPath, name)
ref, err := si.FindByInventoryPath(context.Background(), fullPath)
if err != nil {
return err
}
if ref != nil {
if vm, ok := ref.(*object.VirtualMachine); ok {
return vm.Unregister(context.Background())
} else {
return fmt.Errorf("an object name '%v' already exists", name)
}
}
return nil
} | go | func unregisterPreviousVM(cli *govmomi.Client, folder *object.Folder, name string) error {
si := object.NewSearchIndex(cli.Client)
fullPath := path.Join(folder.InventoryPath, name)
ref, err := si.FindByInventoryPath(context.Background(), fullPath)
if err != nil {
return err
}
if ref != nil {
if vm, ok := ref.(*object.VirtualMachine); ok {
return vm.Unregister(context.Background())
} else {
return fmt.Errorf("an object name '%v' already exists", name)
}
}
return nil
} | [
"func",
"unregisterPreviousVM",
"(",
"cli",
"*",
"govmomi",
".",
"Client",
",",
"folder",
"*",
"object",
".",
"Folder",
",",
"name",
"string",
")",
"error",
"{",
"si",
":=",
"object",
".",
"NewSearchIndex",
"(",
"cli",
".",
"Client",
")",
"\n",
"fullPath",
":=",
"path",
".",
"Join",
"(",
"folder",
".",
"InventoryPath",
",",
"name",
")",
"\n\n",
"ref",
",",
"err",
":=",
"si",
".",
"FindByInventoryPath",
"(",
"context",
".",
"Background",
"(",
")",
",",
"fullPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"ref",
"!=",
"nil",
"{",
"if",
"vm",
",",
"ok",
":=",
"ref",
".",
"(",
"*",
"object",
".",
"VirtualMachine",
")",
";",
"ok",
"{",
"return",
"vm",
".",
"Unregister",
"(",
"context",
".",
"Background",
"(",
")",
")",
"\n",
"}",
"else",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // If in the target folder a virtual machine or template already exists
// it will be removed to maintain consistency | [
"If",
"in",
"the",
"target",
"folder",
"a",
"virtual",
"machine",
"or",
"template",
"already",
"exists",
"it",
"will",
"be",
"removed",
"to",
"maintain",
"consistency"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/post-processor/vsphere-template/step_mark_as_template.go#L150-L169 |
165,116 | hashicorp/packer | builder/hyperv/common/step_create_external_switch.go | Run | func (s *StepCreateExternalSwitch) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
driver := state.Get("driver").(Driver)
ui := state.Get("ui").(packer.Ui)
vmName := state.Get("vmName").(string)
errorMsg := "Error creating external switch: %s"
var err error
ui.Say("Creating external switch...")
packerExternalSwitchName := "paes_" + uuid.TimeOrderedUUID()
// CreateExternalVirtualSwitch checks for an existing external switch,
// creating one if required, and connects the VM to it
err = driver.CreateExternalVirtualSwitch(vmName, packerExternalSwitchName)
if err != nil {
err := fmt.Errorf(errorMsg, err)
state.Put("error", err)
ui.Error(err.Error())
s.SwitchName = ""
return multistep.ActionHalt
}
switchName, err := driver.GetVirtualMachineSwitchName(vmName)
if err != nil {
err := fmt.Errorf(errorMsg, err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
if len(switchName) == 0 {
err := fmt.Errorf(errorMsg, err)
state.Put("error", "Can't get the VM switch name")
ui.Error(err.Error())
return multistep.ActionHalt
}
ui.Say("External switch name is: '" + switchName + "'")
if switchName != packerExternalSwitchName {
s.SwitchName = ""
} else {
s.SwitchName = packerExternalSwitchName
s.oldSwitchName = state.Get("SwitchName").(string)
}
// Set the final name in the state bag so others can use it
state.Put("SwitchName", switchName)
return multistep.ActionContinue
} | go | func (s *StepCreateExternalSwitch) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
driver := state.Get("driver").(Driver)
ui := state.Get("ui").(packer.Ui)
vmName := state.Get("vmName").(string)
errorMsg := "Error creating external switch: %s"
var err error
ui.Say("Creating external switch...")
packerExternalSwitchName := "paes_" + uuid.TimeOrderedUUID()
// CreateExternalVirtualSwitch checks for an existing external switch,
// creating one if required, and connects the VM to it
err = driver.CreateExternalVirtualSwitch(vmName, packerExternalSwitchName)
if err != nil {
err := fmt.Errorf(errorMsg, err)
state.Put("error", err)
ui.Error(err.Error())
s.SwitchName = ""
return multistep.ActionHalt
}
switchName, err := driver.GetVirtualMachineSwitchName(vmName)
if err != nil {
err := fmt.Errorf(errorMsg, err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
if len(switchName) == 0 {
err := fmt.Errorf(errorMsg, err)
state.Put("error", "Can't get the VM switch name")
ui.Error(err.Error())
return multistep.ActionHalt
}
ui.Say("External switch name is: '" + switchName + "'")
if switchName != packerExternalSwitchName {
s.SwitchName = ""
} else {
s.SwitchName = packerExternalSwitchName
s.oldSwitchName = state.Get("SwitchName").(string)
}
// Set the final name in the state bag so others can use it
state.Put("SwitchName", switchName)
return multistep.ActionContinue
} | [
"func",
"(",
"s",
"*",
"StepCreateExternalSwitch",
")",
"Run",
"(",
"ctx",
"context",
".",
"Context",
",",
"state",
"multistep",
".",
"StateBag",
")",
"multistep",
".",
"StepAction",
"{",
"driver",
":=",
"state",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"Driver",
")",
"\n",
"ui",
":=",
"state",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"packer",
".",
"Ui",
")",
"\n\n",
"vmName",
":=",
"state",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
"\n",
"errorMsg",
":=",
"\"",
"\"",
"\n",
"var",
"err",
"error",
"\n\n",
"ui",
".",
"Say",
"(",
"\"",
"\"",
")",
"\n\n",
"packerExternalSwitchName",
":=",
"\"",
"\"",
"+",
"uuid",
".",
"TimeOrderedUUID",
"(",
")",
"\n\n",
"// CreateExternalVirtualSwitch checks for an existing external switch,",
"// creating one if required, and connects the VM to it",
"err",
"=",
"driver",
".",
"CreateExternalVirtualSwitch",
"(",
"vmName",
",",
"packerExternalSwitchName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"err",
":=",
"fmt",
".",
"Errorf",
"(",
"errorMsg",
",",
"err",
")",
"\n",
"state",
".",
"Put",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"ui",
".",
"Error",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"s",
".",
"SwitchName",
"=",
"\"",
"\"",
"\n",
"return",
"multistep",
".",
"ActionHalt",
"\n",
"}",
"\n\n",
"switchName",
",",
"err",
":=",
"driver",
".",
"GetVirtualMachineSwitchName",
"(",
"vmName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"err",
":=",
"fmt",
".",
"Errorf",
"(",
"errorMsg",
",",
"err",
")",
"\n",
"state",
".",
"Put",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"ui",
".",
"Error",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"multistep",
".",
"ActionHalt",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"switchName",
")",
"==",
"0",
"{",
"err",
":=",
"fmt",
".",
"Errorf",
"(",
"errorMsg",
",",
"err",
")",
"\n",
"state",
".",
"Put",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"ui",
".",
"Error",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"multistep",
".",
"ActionHalt",
"\n",
"}",
"\n\n",
"ui",
".",
"Say",
"(",
"\"",
"\"",
"+",
"switchName",
"+",
"\"",
"\"",
")",
"\n\n",
"if",
"switchName",
"!=",
"packerExternalSwitchName",
"{",
"s",
".",
"SwitchName",
"=",
"\"",
"\"",
"\n",
"}",
"else",
"{",
"s",
".",
"SwitchName",
"=",
"packerExternalSwitchName",
"\n",
"s",
".",
"oldSwitchName",
"=",
"state",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
"\n",
"}",
"\n\n",
"// Set the final name in the state bag so others can use it",
"state",
".",
"Put",
"(",
"\"",
"\"",
",",
"switchName",
")",
"\n\n",
"return",
"multistep",
".",
"ActionContinue",
"\n",
"}"
] | // Run runs the step required to create an external switch. Depending on
// the connectivity of the host machine, the external switch will allow the
// build VM to connect to the outside world. | [
"Run",
"runs",
"the",
"step",
"required",
"to",
"create",
"an",
"external",
"switch",
".",
"Depending",
"on",
"the",
"connectivity",
"of",
"the",
"host",
"machine",
"the",
"external",
"switch",
"will",
"allow",
"the",
"build",
"VM",
"to",
"connect",
"to",
"the",
"outside",
"world",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/hyperv/common/step_create_external_switch.go#L24-L75 |
165,117 | hashicorp/packer | common/step_create_floppy.go | removeBase | func removeBase(base string, path string) (string, error) {
var idx int
var err error
if res, err := filepath.Abs(path); err == nil {
path = res
}
path = filepath.Clean(path)
if base, err = filepath.Abs(base); err != nil {
return path, err
}
c1, c2 := strings.Split(base, string(os.PathSeparator)), strings.Split(path, string(os.PathSeparator))
for idx = 0; idx < len(c1); idx++ {
if len(c1[idx]) == 0 && len(c2[idx]) != 0 {
break
}
if c1[idx] != c2[idx] {
return "", fmt.Errorf("Path %s is not prefixed by Base %s", path, base)
}
}
return strings.Join(c2[idx:], string(os.PathSeparator)), nil
} | go | func removeBase(base string, path string) (string, error) {
var idx int
var err error
if res, err := filepath.Abs(path); err == nil {
path = res
}
path = filepath.Clean(path)
if base, err = filepath.Abs(base); err != nil {
return path, err
}
c1, c2 := strings.Split(base, string(os.PathSeparator)), strings.Split(path, string(os.PathSeparator))
for idx = 0; idx < len(c1); idx++ {
if len(c1[idx]) == 0 && len(c2[idx]) != 0 {
break
}
if c1[idx] != c2[idx] {
return "", fmt.Errorf("Path %s is not prefixed by Base %s", path, base)
}
}
return strings.Join(c2[idx:], string(os.PathSeparator)), nil
} | [
"func",
"removeBase",
"(",
"base",
"string",
",",
"path",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"var",
"idx",
"int",
"\n",
"var",
"err",
"error",
"\n\n",
"if",
"res",
",",
"err",
":=",
"filepath",
".",
"Abs",
"(",
"path",
")",
";",
"err",
"==",
"nil",
"{",
"path",
"=",
"res",
"\n",
"}",
"\n",
"path",
"=",
"filepath",
".",
"Clean",
"(",
"path",
")",
"\n\n",
"if",
"base",
",",
"err",
"=",
"filepath",
".",
"Abs",
"(",
"base",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"path",
",",
"err",
"\n",
"}",
"\n\n",
"c1",
",",
"c2",
":=",
"strings",
".",
"Split",
"(",
"base",
",",
"string",
"(",
"os",
".",
"PathSeparator",
")",
")",
",",
"strings",
".",
"Split",
"(",
"path",
",",
"string",
"(",
"os",
".",
"PathSeparator",
")",
")",
"\n",
"for",
"idx",
"=",
"0",
";",
"idx",
"<",
"len",
"(",
"c1",
")",
";",
"idx",
"++",
"{",
"if",
"len",
"(",
"c1",
"[",
"idx",
"]",
")",
"==",
"0",
"&&",
"len",
"(",
"c2",
"[",
"idx",
"]",
")",
"!=",
"0",
"{",
"break",
"\n",
"}",
"\n",
"if",
"c1",
"[",
"idx",
"]",
"!=",
"c2",
"[",
"idx",
"]",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"path",
",",
"base",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"strings",
".",
"Join",
"(",
"c2",
"[",
"idx",
":",
"]",
",",
"string",
"(",
"os",
".",
"PathSeparator",
")",
")",
",",
"nil",
"\n",
"}"
] | // removeBase will take a regular os.PathSeparator-separated path and remove the
// prefix directory base from it. Both paths are converted to their absolute
// formats before the stripping takes place. | [
"removeBase",
"will",
"take",
"a",
"regular",
"os",
".",
"PathSeparator",
"-",
"separated",
"path",
"and",
"remove",
"the",
"prefix",
"directory",
"base",
"from",
"it",
".",
"Both",
"paths",
"are",
"converted",
"to",
"their",
"absolute",
"formats",
"before",
"the",
"stripping",
"takes",
"place",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/common/step_create_floppy.go#L311-L334 |
165,118 | hashicorp/packer | builder/parallels/common/driver.go | NewDriver | func NewDriver() (Driver, error) {
var drivers map[string]Driver
var prlctlPath string
var prlsrvctlPath string
var supportedVersions []string
DHCPLeaseFile := "/Library/Preferences/Parallels/parallels_dhcp_leases"
if runtime.GOOS != "darwin" {
return nil, fmt.Errorf(
"Parallels builder works only on \"darwin\" platform!")
}
if prlctlPath == "" {
var err error
prlctlPath, err = exec.LookPath("prlctl")
if err != nil {
return nil, err
}
}
log.Printf("prlctl path: %s", prlctlPath)
if prlsrvctlPath == "" {
var err error
prlsrvctlPath, err = exec.LookPath("prlsrvctl")
if err != nil {
return nil, err
}
}
log.Printf("prlsrvctl path: %s", prlsrvctlPath)
drivers = map[string]Driver{
"11": &Parallels11Driver{
Parallels9Driver: Parallels9Driver{
PrlctlPath: prlctlPath,
PrlsrvctlPath: prlsrvctlPath,
dhcpLeaseFile: DHCPLeaseFile,
},
},
"10": &Parallels10Driver{
Parallels9Driver: Parallels9Driver{
PrlctlPath: prlctlPath,
PrlsrvctlPath: prlsrvctlPath,
dhcpLeaseFile: DHCPLeaseFile,
},
},
"9": &Parallels9Driver{
PrlctlPath: prlctlPath,
PrlsrvctlPath: prlsrvctlPath,
dhcpLeaseFile: DHCPLeaseFile,
},
}
for v, d := range drivers {
version, _ := d.Version()
if strings.HasPrefix(version, v) {
if err := d.Verify(); err != nil {
return nil, err
}
return d, nil
}
supportedVersions = append(supportedVersions, v)
}
latestDriver := 11
version, _ := drivers[strconv.Itoa(latestDriver)].Version()
majVer, _ := strconv.Atoi(strings.SplitN(version, ".", 2)[0])
log.Printf("Parallels version: %s", version)
if majVer > latestDriver {
log.Printf("Your version of Parallels Desktop for Mac is %s, Packer will use driver for version %d.", version, latestDriver)
return drivers[strconv.Itoa(latestDriver)], nil
}
return nil, fmt.Errorf(
"Unable to initialize any driver. Supported Parallels Desktop versions: "+
"%s\n", strings.Join(supportedVersions, ", "))
} | go | func NewDriver() (Driver, error) {
var drivers map[string]Driver
var prlctlPath string
var prlsrvctlPath string
var supportedVersions []string
DHCPLeaseFile := "/Library/Preferences/Parallels/parallels_dhcp_leases"
if runtime.GOOS != "darwin" {
return nil, fmt.Errorf(
"Parallels builder works only on \"darwin\" platform!")
}
if prlctlPath == "" {
var err error
prlctlPath, err = exec.LookPath("prlctl")
if err != nil {
return nil, err
}
}
log.Printf("prlctl path: %s", prlctlPath)
if prlsrvctlPath == "" {
var err error
prlsrvctlPath, err = exec.LookPath("prlsrvctl")
if err != nil {
return nil, err
}
}
log.Printf("prlsrvctl path: %s", prlsrvctlPath)
drivers = map[string]Driver{
"11": &Parallels11Driver{
Parallels9Driver: Parallels9Driver{
PrlctlPath: prlctlPath,
PrlsrvctlPath: prlsrvctlPath,
dhcpLeaseFile: DHCPLeaseFile,
},
},
"10": &Parallels10Driver{
Parallels9Driver: Parallels9Driver{
PrlctlPath: prlctlPath,
PrlsrvctlPath: prlsrvctlPath,
dhcpLeaseFile: DHCPLeaseFile,
},
},
"9": &Parallels9Driver{
PrlctlPath: prlctlPath,
PrlsrvctlPath: prlsrvctlPath,
dhcpLeaseFile: DHCPLeaseFile,
},
}
for v, d := range drivers {
version, _ := d.Version()
if strings.HasPrefix(version, v) {
if err := d.Verify(); err != nil {
return nil, err
}
return d, nil
}
supportedVersions = append(supportedVersions, v)
}
latestDriver := 11
version, _ := drivers[strconv.Itoa(latestDriver)].Version()
majVer, _ := strconv.Atoi(strings.SplitN(version, ".", 2)[0])
log.Printf("Parallels version: %s", version)
if majVer > latestDriver {
log.Printf("Your version of Parallels Desktop for Mac is %s, Packer will use driver for version %d.", version, latestDriver)
return drivers[strconv.Itoa(latestDriver)], nil
}
return nil, fmt.Errorf(
"Unable to initialize any driver. Supported Parallels Desktop versions: "+
"%s\n", strings.Join(supportedVersions, ", "))
} | [
"func",
"NewDriver",
"(",
")",
"(",
"Driver",
",",
"error",
")",
"{",
"var",
"drivers",
"map",
"[",
"string",
"]",
"Driver",
"\n",
"var",
"prlctlPath",
"string",
"\n",
"var",
"prlsrvctlPath",
"string",
"\n",
"var",
"supportedVersions",
"[",
"]",
"string",
"\n",
"DHCPLeaseFile",
":=",
"\"",
"\"",
"\n\n",
"if",
"runtime",
".",
"GOOS",
"!=",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\\"",
"\\\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"prlctlPath",
"==",
"\"",
"\"",
"{",
"var",
"err",
"error",
"\n",
"prlctlPath",
",",
"err",
"=",
"exec",
".",
"LookPath",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"prlctlPath",
")",
"\n\n",
"if",
"prlsrvctlPath",
"==",
"\"",
"\"",
"{",
"var",
"err",
"error",
"\n",
"prlsrvctlPath",
",",
"err",
"=",
"exec",
".",
"LookPath",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"prlsrvctlPath",
")",
"\n\n",
"drivers",
"=",
"map",
"[",
"string",
"]",
"Driver",
"{",
"\"",
"\"",
":",
"&",
"Parallels11Driver",
"{",
"Parallels9Driver",
":",
"Parallels9Driver",
"{",
"PrlctlPath",
":",
"prlctlPath",
",",
"PrlsrvctlPath",
":",
"prlsrvctlPath",
",",
"dhcpLeaseFile",
":",
"DHCPLeaseFile",
",",
"}",
",",
"}",
",",
"\"",
"\"",
":",
"&",
"Parallels10Driver",
"{",
"Parallels9Driver",
":",
"Parallels9Driver",
"{",
"PrlctlPath",
":",
"prlctlPath",
",",
"PrlsrvctlPath",
":",
"prlsrvctlPath",
",",
"dhcpLeaseFile",
":",
"DHCPLeaseFile",
",",
"}",
",",
"}",
",",
"\"",
"\"",
":",
"&",
"Parallels9Driver",
"{",
"PrlctlPath",
":",
"prlctlPath",
",",
"PrlsrvctlPath",
":",
"prlsrvctlPath",
",",
"dhcpLeaseFile",
":",
"DHCPLeaseFile",
",",
"}",
",",
"}",
"\n\n",
"for",
"v",
",",
"d",
":=",
"range",
"drivers",
"{",
"version",
",",
"_",
":=",
"d",
".",
"Version",
"(",
")",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"version",
",",
"v",
")",
"{",
"if",
"err",
":=",
"d",
".",
"Verify",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"d",
",",
"nil",
"\n",
"}",
"\n",
"supportedVersions",
"=",
"append",
"(",
"supportedVersions",
",",
"v",
")",
"\n",
"}",
"\n\n",
"latestDriver",
":=",
"11",
"\n",
"version",
",",
"_",
":=",
"drivers",
"[",
"strconv",
".",
"Itoa",
"(",
"latestDriver",
")",
"]",
".",
"Version",
"(",
")",
"\n",
"majVer",
",",
"_",
":=",
"strconv",
".",
"Atoi",
"(",
"strings",
".",
"SplitN",
"(",
"version",
",",
"\"",
"\"",
",",
"2",
")",
"[",
"0",
"]",
")",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"version",
")",
"\n",
"if",
"majVer",
">",
"latestDriver",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"version",
",",
"latestDriver",
")",
"\n",
"return",
"drivers",
"[",
"strconv",
".",
"Itoa",
"(",
"latestDriver",
")",
"]",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
"+",
"\"",
"\\n",
"\"",
",",
"strings",
".",
"Join",
"(",
"supportedVersions",
",",
"\"",
"\"",
")",
")",
"\n",
"}"
] | // NewDriver returns a new driver implementation for this version of Parallels
// Desktop, or an error if the driver couldn't be initialized. | [
"NewDriver",
"returns",
"a",
"new",
"driver",
"implementation",
"for",
"this",
"version",
"of",
"Parallels",
"Desktop",
"or",
"an",
"error",
"if",
"the",
"driver",
"couldn",
"t",
"be",
"initialized",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/parallels/common/driver.go#L66-L143 |
165,119 | hashicorp/packer | packer/rpc/ui_progress_tracking.go | TrackProgress | func (u *Ui) TrackProgress(src string, currentSize, totalSize int64, stream io.ReadCloser) io.ReadCloser {
pl := &TrackProgressParameters{
Src: src,
CurrentSize: currentSize,
TotalSize: totalSize,
}
var trackingID string
if err := u.client.Call("Ui.NewTrackProgress", pl, &trackingID); err != nil {
log.Printf("Error in Ui.NewTrackProgress RPC call: %s", err)
return stream
}
cli := &ProgressTrackingClient{
id: trackingID,
client: u.client,
stream: stream,
}
return cli
} | go | func (u *Ui) TrackProgress(src string, currentSize, totalSize int64, stream io.ReadCloser) io.ReadCloser {
pl := &TrackProgressParameters{
Src: src,
CurrentSize: currentSize,
TotalSize: totalSize,
}
var trackingID string
if err := u.client.Call("Ui.NewTrackProgress", pl, &trackingID); err != nil {
log.Printf("Error in Ui.NewTrackProgress RPC call: %s", err)
return stream
}
cli := &ProgressTrackingClient{
id: trackingID,
client: u.client,
stream: stream,
}
return cli
} | [
"func",
"(",
"u",
"*",
"Ui",
")",
"TrackProgress",
"(",
"src",
"string",
",",
"currentSize",
",",
"totalSize",
"int64",
",",
"stream",
"io",
".",
"ReadCloser",
")",
"io",
".",
"ReadCloser",
"{",
"pl",
":=",
"&",
"TrackProgressParameters",
"{",
"Src",
":",
"src",
",",
"CurrentSize",
":",
"currentSize",
",",
"TotalSize",
":",
"totalSize",
",",
"}",
"\n",
"var",
"trackingID",
"string",
"\n",
"if",
"err",
":=",
"u",
".",
"client",
".",
"Call",
"(",
"\"",
"\"",
",",
"pl",
",",
"&",
"trackingID",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"stream",
"\n",
"}",
"\n",
"cli",
":=",
"&",
"ProgressTrackingClient",
"{",
"id",
":",
"trackingID",
",",
"client",
":",
"u",
".",
"client",
",",
"stream",
":",
"stream",
",",
"}",
"\n",
"return",
"cli",
"\n",
"}"
] | // TrackProgress starts a pair of ProgressTrackingClient and ProgressProgressTrackingServer
// that will send the size of each read bytes of stream.
// In order to track an operation on the terminal side. | [
"TrackProgress",
"starts",
"a",
"pair",
"of",
"ProgressTrackingClient",
"and",
"ProgressProgressTrackingServer",
"that",
"will",
"send",
"the",
"size",
"of",
"each",
"read",
"bytes",
"of",
"stream",
".",
"In",
"order",
"to",
"track",
"an",
"operation",
"on",
"the",
"terminal",
"side",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/packer/rpc/ui_progress_tracking.go#L14-L31 |
165,120 | hashicorp/packer | builder/amazon/common/ssh.go | SSHHost | func SSHHost(e ec2Describer, sshInterface string) func(multistep.StateBag) (string, error) {
return func(state multistep.StateBag) (string, error) {
const tries = 2
// <= with current structure to check result of describing `tries` times
for j := 0; j <= tries; j++ {
var host string
i := state.Get("instance").(*ec2.Instance)
if sshInterface != "" {
switch sshInterface {
case "public_ip":
if i.PublicIpAddress != nil {
host = *i.PublicIpAddress
}
case "private_ip":
if i.PrivateIpAddress != nil {
host = *i.PrivateIpAddress
}
case "public_dns":
if i.PublicDnsName != nil {
host = *i.PublicDnsName
}
case "private_dns":
if i.PrivateDnsName != nil {
host = *i.PrivateDnsName
}
default:
panic(fmt.Sprintf("Unknown interface type: %s", sshInterface))
}
} else if i.VpcId != nil && *i.VpcId != "" {
if i.PublicIpAddress != nil && *i.PublicIpAddress != "" {
host = *i.PublicIpAddress
} else if i.PrivateIpAddress != nil && *i.PrivateIpAddress != "" {
host = *i.PrivateIpAddress
}
} else if i.PublicDnsName != nil && *i.PublicDnsName != "" {
host = *i.PublicDnsName
}
if host != "" {
return host, nil
}
r, err := e.DescribeInstances(&ec2.DescribeInstancesInput{
InstanceIds: []*string{i.InstanceId},
})
if err != nil {
return "", err
}
if len(r.Reservations) == 0 || len(r.Reservations[0].Instances) == 0 {
return "", fmt.Errorf("instance not found: %s", *i.InstanceId)
}
state.Put("instance", r.Reservations[0].Instances[0])
time.Sleep(sshHostSleepDuration)
}
return "", errors.New("couldn't determine address for instance")
}
} | go | func SSHHost(e ec2Describer, sshInterface string) func(multistep.StateBag) (string, error) {
return func(state multistep.StateBag) (string, error) {
const tries = 2
// <= with current structure to check result of describing `tries` times
for j := 0; j <= tries; j++ {
var host string
i := state.Get("instance").(*ec2.Instance)
if sshInterface != "" {
switch sshInterface {
case "public_ip":
if i.PublicIpAddress != nil {
host = *i.PublicIpAddress
}
case "private_ip":
if i.PrivateIpAddress != nil {
host = *i.PrivateIpAddress
}
case "public_dns":
if i.PublicDnsName != nil {
host = *i.PublicDnsName
}
case "private_dns":
if i.PrivateDnsName != nil {
host = *i.PrivateDnsName
}
default:
panic(fmt.Sprintf("Unknown interface type: %s", sshInterface))
}
} else if i.VpcId != nil && *i.VpcId != "" {
if i.PublicIpAddress != nil && *i.PublicIpAddress != "" {
host = *i.PublicIpAddress
} else if i.PrivateIpAddress != nil && *i.PrivateIpAddress != "" {
host = *i.PrivateIpAddress
}
} else if i.PublicDnsName != nil && *i.PublicDnsName != "" {
host = *i.PublicDnsName
}
if host != "" {
return host, nil
}
r, err := e.DescribeInstances(&ec2.DescribeInstancesInput{
InstanceIds: []*string{i.InstanceId},
})
if err != nil {
return "", err
}
if len(r.Reservations) == 0 || len(r.Reservations[0].Instances) == 0 {
return "", fmt.Errorf("instance not found: %s", *i.InstanceId)
}
state.Put("instance", r.Reservations[0].Instances[0])
time.Sleep(sshHostSleepDuration)
}
return "", errors.New("couldn't determine address for instance")
}
} | [
"func",
"SSHHost",
"(",
"e",
"ec2Describer",
",",
"sshInterface",
"string",
")",
"func",
"(",
"multistep",
".",
"StateBag",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"func",
"(",
"state",
"multistep",
".",
"StateBag",
")",
"(",
"string",
",",
"error",
")",
"{",
"const",
"tries",
"=",
"2",
"\n",
"// <= with current structure to check result of describing `tries` times",
"for",
"j",
":=",
"0",
";",
"j",
"<=",
"tries",
";",
"j",
"++",
"{",
"var",
"host",
"string",
"\n",
"i",
":=",
"state",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"*",
"ec2",
".",
"Instance",
")",
"\n",
"if",
"sshInterface",
"!=",
"\"",
"\"",
"{",
"switch",
"sshInterface",
"{",
"case",
"\"",
"\"",
":",
"if",
"i",
".",
"PublicIpAddress",
"!=",
"nil",
"{",
"host",
"=",
"*",
"i",
".",
"PublicIpAddress",
"\n",
"}",
"\n",
"case",
"\"",
"\"",
":",
"if",
"i",
".",
"PrivateIpAddress",
"!=",
"nil",
"{",
"host",
"=",
"*",
"i",
".",
"PrivateIpAddress",
"\n",
"}",
"\n",
"case",
"\"",
"\"",
":",
"if",
"i",
".",
"PublicDnsName",
"!=",
"nil",
"{",
"host",
"=",
"*",
"i",
".",
"PublicDnsName",
"\n",
"}",
"\n",
"case",
"\"",
"\"",
":",
"if",
"i",
".",
"PrivateDnsName",
"!=",
"nil",
"{",
"host",
"=",
"*",
"i",
".",
"PrivateDnsName",
"\n",
"}",
"\n",
"default",
":",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"sshInterface",
")",
")",
"\n",
"}",
"\n",
"}",
"else",
"if",
"i",
".",
"VpcId",
"!=",
"nil",
"&&",
"*",
"i",
".",
"VpcId",
"!=",
"\"",
"\"",
"{",
"if",
"i",
".",
"PublicIpAddress",
"!=",
"nil",
"&&",
"*",
"i",
".",
"PublicIpAddress",
"!=",
"\"",
"\"",
"{",
"host",
"=",
"*",
"i",
".",
"PublicIpAddress",
"\n",
"}",
"else",
"if",
"i",
".",
"PrivateIpAddress",
"!=",
"nil",
"&&",
"*",
"i",
".",
"PrivateIpAddress",
"!=",
"\"",
"\"",
"{",
"host",
"=",
"*",
"i",
".",
"PrivateIpAddress",
"\n",
"}",
"\n",
"}",
"else",
"if",
"i",
".",
"PublicDnsName",
"!=",
"nil",
"&&",
"*",
"i",
".",
"PublicDnsName",
"!=",
"\"",
"\"",
"{",
"host",
"=",
"*",
"i",
".",
"PublicDnsName",
"\n",
"}",
"\n\n",
"if",
"host",
"!=",
"\"",
"\"",
"{",
"return",
"host",
",",
"nil",
"\n",
"}",
"\n\n",
"r",
",",
"err",
":=",
"e",
".",
"DescribeInstances",
"(",
"&",
"ec2",
".",
"DescribeInstancesInput",
"{",
"InstanceIds",
":",
"[",
"]",
"*",
"string",
"{",
"i",
".",
"InstanceId",
"}",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"r",
".",
"Reservations",
")",
"==",
"0",
"||",
"len",
"(",
"r",
".",
"Reservations",
"[",
"0",
"]",
".",
"Instances",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"*",
"i",
".",
"InstanceId",
")",
"\n",
"}",
"\n\n",
"state",
".",
"Put",
"(",
"\"",
"\"",
",",
"r",
".",
"Reservations",
"[",
"0",
"]",
".",
"Instances",
"[",
"0",
"]",
")",
"\n",
"time",
".",
"Sleep",
"(",
"sshHostSleepDuration",
")",
"\n",
"}",
"\n\n",
"return",
"\"",
"\"",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}"
] | // SSHHost returns a function that can be given to the SSH communicator
// for determining the SSH address based on the instance DNS name. | [
"SSHHost",
"returns",
"a",
"function",
"that",
"can",
"be",
"given",
"to",
"the",
"SSH",
"communicator",
"for",
"determining",
"the",
"SSH",
"address",
"based",
"on",
"the",
"instance",
"DNS",
"name",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/amazon/common/ssh.go#L23-L82 |
165,121 | hashicorp/packer | packer/rpc/mux_broker.go | Run | func (m *muxBroker) Run() {
for {
stream, err := m.session.AcceptStream()
if err != nil {
// Once we receive an error, just exit
break
}
// Read the stream ID from the stream
var id uint32
if err := binary.Read(stream, binary.LittleEndian, &id); err != nil {
stream.Close()
continue
}
// Initialize the waiter
p := m.getStream(id)
select {
case p.ch <- stream:
default:
}
// Wait for a timeout
go m.timeoutWait(id, p)
}
} | go | func (m *muxBroker) Run() {
for {
stream, err := m.session.AcceptStream()
if err != nil {
// Once we receive an error, just exit
break
}
// Read the stream ID from the stream
var id uint32
if err := binary.Read(stream, binary.LittleEndian, &id); err != nil {
stream.Close()
continue
}
// Initialize the waiter
p := m.getStream(id)
select {
case p.ch <- stream:
default:
}
// Wait for a timeout
go m.timeoutWait(id, p)
}
} | [
"func",
"(",
"m",
"*",
"muxBroker",
")",
"Run",
"(",
")",
"{",
"for",
"{",
"stream",
",",
"err",
":=",
"m",
".",
"session",
".",
"AcceptStream",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Once we receive an error, just exit",
"break",
"\n",
"}",
"\n\n",
"// Read the stream ID from the stream",
"var",
"id",
"uint32",
"\n",
"if",
"err",
":=",
"binary",
".",
"Read",
"(",
"stream",
",",
"binary",
".",
"LittleEndian",
",",
"&",
"id",
")",
";",
"err",
"!=",
"nil",
"{",
"stream",
".",
"Close",
"(",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"// Initialize the waiter",
"p",
":=",
"m",
".",
"getStream",
"(",
"id",
")",
"\n",
"select",
"{",
"case",
"p",
".",
"ch",
"<-",
"stream",
":",
"default",
":",
"}",
"\n\n",
"// Wait for a timeout",
"go",
"m",
".",
"timeoutWait",
"(",
"id",
",",
"p",
")",
"\n",
"}",
"\n",
"}"
] | // Run starts the brokering and should be executed in a goroutine, since it
// blocks forever, or until the session closes. | [
"Run",
"starts",
"the",
"brokering",
"and",
"should",
"be",
"executed",
"in",
"a",
"goroutine",
"since",
"it",
"blocks",
"forever",
"or",
"until",
"the",
"session",
"closes",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/packer/rpc/mux_broker.go#L124-L149 |
165,122 | hashicorp/packer | common/iochan/iochan.go | LineReader | func LineReader(r io.Reader) <-chan string {
ch := make(chan string)
go func() {
scanner := bufio.NewScanner(r)
defer close(ch)
for scanner.Scan() {
ch <- scanner.Text()
}
}()
return ch
} | go | func LineReader(r io.Reader) <-chan string {
ch := make(chan string)
go func() {
scanner := bufio.NewScanner(r)
defer close(ch)
for scanner.Scan() {
ch <- scanner.Text()
}
}()
return ch
} | [
"func",
"LineReader",
"(",
"r",
"io",
".",
"Reader",
")",
"<-",
"chan",
"string",
"{",
"ch",
":=",
"make",
"(",
"chan",
"string",
")",
"\n\n",
"go",
"func",
"(",
")",
"{",
"scanner",
":=",
"bufio",
".",
"NewScanner",
"(",
"r",
")",
"\n",
"defer",
"close",
"(",
"ch",
")",
"\n\n",
"for",
"scanner",
".",
"Scan",
"(",
")",
"{",
"ch",
"<-",
"scanner",
".",
"Text",
"(",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"return",
"ch",
"\n",
"}"
] | // LineReader takes an io.Reader and produces the contents of the reader on the
// returned channel. Internally bufio.NewScanner is used, io.ScanLines parses
// lines and returns them without carriage return. Scan can panic if the split
// function returns too many empty tokens without advancing the input.
//
// The channel will be closed either by reaching the end of the input or an
// error. | [
"LineReader",
"takes",
"an",
"io",
".",
"Reader",
"and",
"produces",
"the",
"contents",
"of",
"the",
"reader",
"on",
"the",
"returned",
"channel",
".",
"Internally",
"bufio",
".",
"NewScanner",
"is",
"used",
"io",
".",
"ScanLines",
"parses",
"lines",
"and",
"returns",
"them",
"without",
"carriage",
"return",
".",
"Scan",
"can",
"panic",
"if",
"the",
"split",
"function",
"returns",
"too",
"many",
"empty",
"tokens",
"without",
"advancing",
"the",
"input",
".",
"The",
"channel",
"will",
"be",
"closed",
"either",
"by",
"reaching",
"the",
"end",
"of",
"the",
"input",
"or",
"an",
"error",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/common/iochan/iochan.go#L15-L28 |
165,123 | hashicorp/packer | builder/azure/common/devicelogin.go | tokenFromFile | func tokenFromFile(say func(string), oauthCfg adal.OAuthConfig, tokenPath, clientID, resource string,
callback adal.TokenRefreshCallback) (*adal.ServicePrincipalToken, error) {
say(fmt.Sprintf("Loading auth token from file: %s", tokenPath))
if _, err := os.Stat(tokenPath); err != nil {
if os.IsNotExist(err) { // file not found
return nil, nil
}
return nil, err
}
token, err := adal.LoadToken(tokenPath)
if err != nil {
return nil, fmt.Errorf("Failed to load token from file: %v", err)
}
spt, err := adal.NewServicePrincipalTokenFromManualToken(oauthCfg, clientID, resource, *token, callback)
if err != nil {
return nil, fmt.Errorf("Error constructing service principal token: %v", err)
}
return spt, nil
} | go | func tokenFromFile(say func(string), oauthCfg adal.OAuthConfig, tokenPath, clientID, resource string,
callback adal.TokenRefreshCallback) (*adal.ServicePrincipalToken, error) {
say(fmt.Sprintf("Loading auth token from file: %s", tokenPath))
if _, err := os.Stat(tokenPath); err != nil {
if os.IsNotExist(err) { // file not found
return nil, nil
}
return nil, err
}
token, err := adal.LoadToken(tokenPath)
if err != nil {
return nil, fmt.Errorf("Failed to load token from file: %v", err)
}
spt, err := adal.NewServicePrincipalTokenFromManualToken(oauthCfg, clientID, resource, *token, callback)
if err != nil {
return nil, fmt.Errorf("Error constructing service principal token: %v", err)
}
return spt, nil
} | [
"func",
"tokenFromFile",
"(",
"say",
"func",
"(",
"string",
")",
",",
"oauthCfg",
"adal",
".",
"OAuthConfig",
",",
"tokenPath",
",",
"clientID",
",",
"resource",
"string",
",",
"callback",
"adal",
".",
"TokenRefreshCallback",
")",
"(",
"*",
"adal",
".",
"ServicePrincipalToken",
",",
"error",
")",
"{",
"say",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"tokenPath",
")",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"tokenPath",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"// file not found",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"token",
",",
"err",
":=",
"adal",
".",
"LoadToken",
"(",
"tokenPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"spt",
",",
"err",
":=",
"adal",
".",
"NewServicePrincipalTokenFromManualToken",
"(",
"oauthCfg",
",",
"clientID",
",",
"resource",
",",
"*",
"token",
",",
"callback",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"spt",
",",
"nil",
"\n",
"}"
] | // tokenFromFile returns a token from the specified file if it is found, otherwise
// returns nil. Any error retrieving or creating the token is returned as an error. | [
"tokenFromFile",
"returns",
"a",
"token",
"from",
"the",
"specified",
"file",
"if",
"it",
"is",
"found",
"otherwise",
"returns",
"nil",
".",
"Any",
"error",
"retrieving",
"or",
"creating",
"the",
"token",
"is",
"returned",
"as",
"an",
"error",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/azure/common/devicelogin.go#L99-L119 |
165,124 | hashicorp/packer | builder/azure/common/devicelogin.go | tokenFromDeviceFlow | func tokenFromDeviceFlow(say func(string), oauthCfg adal.OAuthConfig, clientID, resource string) (*adal.ServicePrincipalToken, error) {
cl := autorest.NewClientWithUserAgent(useragent.String())
deviceCode, err := adal.InitiateDeviceAuth(&cl, oauthCfg, clientID, resource)
if err != nil {
return nil, fmt.Errorf("Failed to start device auth: %v", err)
}
// Example message: “To sign in, open https://aka.ms/devicelogin and enter
// the code 0000000 to authenticate.”
say(fmt.Sprintf("Microsoft Azure: %s", to.String(deviceCode.Message)))
token, err := adal.WaitForUserCompletion(&cl, deviceCode)
if err != nil {
return nil, fmt.Errorf("Failed to complete device auth: %v", err)
}
spt, err := adal.NewServicePrincipalTokenFromManualToken(oauthCfg, clientID, resource, *token)
if err != nil {
return nil, fmt.Errorf("Error constructing service principal token: %v", err)
}
return spt, nil
} | go | func tokenFromDeviceFlow(say func(string), oauthCfg adal.OAuthConfig, clientID, resource string) (*adal.ServicePrincipalToken, error) {
cl := autorest.NewClientWithUserAgent(useragent.String())
deviceCode, err := adal.InitiateDeviceAuth(&cl, oauthCfg, clientID, resource)
if err != nil {
return nil, fmt.Errorf("Failed to start device auth: %v", err)
}
// Example message: “To sign in, open https://aka.ms/devicelogin and enter
// the code 0000000 to authenticate.”
say(fmt.Sprintf("Microsoft Azure: %s", to.String(deviceCode.Message)))
token, err := adal.WaitForUserCompletion(&cl, deviceCode)
if err != nil {
return nil, fmt.Errorf("Failed to complete device auth: %v", err)
}
spt, err := adal.NewServicePrincipalTokenFromManualToken(oauthCfg, clientID, resource, *token)
if err != nil {
return nil, fmt.Errorf("Error constructing service principal token: %v", err)
}
return spt, nil
} | [
"func",
"tokenFromDeviceFlow",
"(",
"say",
"func",
"(",
"string",
")",
",",
"oauthCfg",
"adal",
".",
"OAuthConfig",
",",
"clientID",
",",
"resource",
"string",
")",
"(",
"*",
"adal",
".",
"ServicePrincipalToken",
",",
"error",
")",
"{",
"cl",
":=",
"autorest",
".",
"NewClientWithUserAgent",
"(",
"useragent",
".",
"String",
"(",
")",
")",
"\n",
"deviceCode",
",",
"err",
":=",
"adal",
".",
"InitiateDeviceAuth",
"(",
"&",
"cl",
",",
"oauthCfg",
",",
"clientID",
",",
"resource",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Example message: “To sign in, open https://aka.ms/devicelogin and enter",
"// the code 0000000 to authenticate.”",
"say",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"to",
".",
"String",
"(",
"deviceCode",
".",
"Message",
")",
")",
")",
"\n\n",
"token",
",",
"err",
":=",
"adal",
".",
"WaitForUserCompletion",
"(",
"&",
"cl",
",",
"deviceCode",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"spt",
",",
"err",
":=",
"adal",
".",
"NewServicePrincipalTokenFromManualToken",
"(",
"oauthCfg",
",",
"clientID",
",",
"resource",
",",
"*",
"token",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"spt",
",",
"nil",
"\n",
"}"
] | // tokenFromDeviceFlow prints a message to the screen for user to take action to
// consent application on a browser and in the meanwhile the authentication
// endpoint is polled until user gives consent, denies or the flow times out.
// Returned token must be saved. | [
"tokenFromDeviceFlow",
"prints",
"a",
"message",
"to",
"the",
"screen",
"for",
"user",
"to",
"take",
"action",
"to",
"consent",
"application",
"on",
"a",
"browser",
"and",
"in",
"the",
"meanwhile",
"the",
"authentication",
"endpoint",
"is",
"polled",
"until",
"user",
"gives",
"consent",
"denies",
"or",
"the",
"flow",
"times",
"out",
".",
"Returned",
"token",
"must",
"be",
"saved",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/azure/common/devicelogin.go#L125-L146 |
165,125 | hashicorp/packer | builder/azure/common/devicelogin.go | tokenCachePath | func tokenCachePath(tenantID string) string {
var dir string
u, err := user.Current()
if err != nil || u.HomeDir == "" {
dir, _ = filepath.Abs(os.Args[0])
} else {
dir = u.HomeDir
}
return filepath.Join(dir, ".azure", "packer", fmt.Sprintf("oauth-%s.json", tenantID))
} | go | func tokenCachePath(tenantID string) string {
var dir string
u, err := user.Current()
if err != nil || u.HomeDir == "" {
dir, _ = filepath.Abs(os.Args[0])
} else {
dir = u.HomeDir
}
return filepath.Join(dir, ".azure", "packer", fmt.Sprintf("oauth-%s.json", tenantID))
} | [
"func",
"tokenCachePath",
"(",
"tenantID",
"string",
")",
"string",
"{",
"var",
"dir",
"string",
"\n\n",
"u",
",",
"err",
":=",
"user",
".",
"Current",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"u",
".",
"HomeDir",
"==",
"\"",
"\"",
"{",
"dir",
",",
"_",
"=",
"filepath",
".",
"Abs",
"(",
"os",
".",
"Args",
"[",
"0",
"]",
")",
"\n",
"}",
"else",
"{",
"dir",
"=",
"u",
".",
"HomeDir",
"\n",
"}",
"\n\n",
"return",
"filepath",
".",
"Join",
"(",
"dir",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"tenantID",
")",
")",
"\n",
"}"
] | // tokenCachePath returns the full path the OAuth 2.0 token should be saved at
// for given tenant ID. | [
"tokenCachePath",
"returns",
"the",
"full",
"path",
"the",
"OAuth",
"2",
".",
"0",
"token",
"should",
"be",
"saved",
"at",
"for",
"given",
"tenant",
"ID",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/azure/common/devicelogin.go#L150-L161 |
165,126 | hashicorp/packer | builder/azure/common/devicelogin.go | mkTokenCallback | func mkTokenCallback(path string) adal.TokenRefreshCallback {
return func(t adal.Token) error {
if err := adal.SaveToken(path, 0600, t); err != nil {
return err
}
return nil
}
} | go | func mkTokenCallback(path string) adal.TokenRefreshCallback {
return func(t adal.Token) error {
if err := adal.SaveToken(path, 0600, t); err != nil {
return err
}
return nil
}
} | [
"func",
"mkTokenCallback",
"(",
"path",
"string",
")",
"adal",
".",
"TokenRefreshCallback",
"{",
"return",
"func",
"(",
"t",
"adal",
".",
"Token",
")",
"error",
"{",
"if",
"err",
":=",
"adal",
".",
"SaveToken",
"(",
"path",
",",
"0600",
",",
"t",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // mkTokenCallback returns a callback function that can be used to save the
// token initially or register to the Azure SDK to be called when the token is
// refreshed. | [
"mkTokenCallback",
"returns",
"a",
"callback",
"function",
"that",
"can",
"be",
"used",
"to",
"save",
"the",
"token",
"initially",
"or",
"register",
"to",
"the",
"Azure",
"SDK",
"to",
"be",
"called",
"when",
"the",
"token",
"is",
"refreshed",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/azure/common/devicelogin.go#L166-L173 |
165,127 | hashicorp/packer | builder/azure/common/devicelogin.go | FindTenantID | func FindTenantID(env azure.Environment, subscriptionID string) (string, error) {
const hdrKey = "WWW-Authenticate"
c := subscriptions.NewClientWithBaseURI(env.ResourceManagerEndpoint)
// we expect this request to fail (err != nil), but we are only interested
// in headers, so surface the error if the Response is not present (i.e.
// network error etc)
subs, err := c.Get(context.TODO(), subscriptionID)
if subs.Response.Response == nil {
return "", fmt.Errorf("Request failed: %v", err)
}
// Expecting 401 StatusUnauthorized here, just read the header
if subs.StatusCode != http.StatusUnauthorized {
return "", fmt.Errorf("Unexpected response from Get Subscription: %v", err)
}
hdr := subs.Header.Get(hdrKey)
if hdr == "" {
return "", fmt.Errorf("Header %v not found in Get Subscription response", hdrKey)
}
// Example value for hdr:
// Bearer authorization_uri="https://login.windows.net/996fe9d1-6171-40aa-945b-4c64b63bf655", error="invalid_token", error_description="The authentication failed because of missing 'Authorization' header."
r := regexp.MustCompile(`authorization_uri=".*/([0-9a-f\-]+)"`)
m := r.FindStringSubmatch(hdr)
if m == nil {
return "", fmt.Errorf("Could not find the tenant ID in header: %s %q", hdrKey, hdr)
}
return m[1], nil
} | go | func FindTenantID(env azure.Environment, subscriptionID string) (string, error) {
const hdrKey = "WWW-Authenticate"
c := subscriptions.NewClientWithBaseURI(env.ResourceManagerEndpoint)
// we expect this request to fail (err != nil), but we are only interested
// in headers, so surface the error if the Response is not present (i.e.
// network error etc)
subs, err := c.Get(context.TODO(), subscriptionID)
if subs.Response.Response == nil {
return "", fmt.Errorf("Request failed: %v", err)
}
// Expecting 401 StatusUnauthorized here, just read the header
if subs.StatusCode != http.StatusUnauthorized {
return "", fmt.Errorf("Unexpected response from Get Subscription: %v", err)
}
hdr := subs.Header.Get(hdrKey)
if hdr == "" {
return "", fmt.Errorf("Header %v not found in Get Subscription response", hdrKey)
}
// Example value for hdr:
// Bearer authorization_uri="https://login.windows.net/996fe9d1-6171-40aa-945b-4c64b63bf655", error="invalid_token", error_description="The authentication failed because of missing 'Authorization' header."
r := regexp.MustCompile(`authorization_uri=".*/([0-9a-f\-]+)"`)
m := r.FindStringSubmatch(hdr)
if m == nil {
return "", fmt.Errorf("Could not find the tenant ID in header: %s %q", hdrKey, hdr)
}
return m[1], nil
} | [
"func",
"FindTenantID",
"(",
"env",
"azure",
".",
"Environment",
",",
"subscriptionID",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"const",
"hdrKey",
"=",
"\"",
"\"",
"\n",
"c",
":=",
"subscriptions",
".",
"NewClientWithBaseURI",
"(",
"env",
".",
"ResourceManagerEndpoint",
")",
"\n\n",
"// we expect this request to fail (err != nil), but we are only interested",
"// in headers, so surface the error if the Response is not present (i.e.",
"// network error etc)",
"subs",
",",
"err",
":=",
"c",
".",
"Get",
"(",
"context",
".",
"TODO",
"(",
")",
",",
"subscriptionID",
")",
"\n",
"if",
"subs",
".",
"Response",
".",
"Response",
"==",
"nil",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Expecting 401 StatusUnauthorized here, just read the header",
"if",
"subs",
".",
"StatusCode",
"!=",
"http",
".",
"StatusUnauthorized",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"hdr",
":=",
"subs",
".",
"Header",
".",
"Get",
"(",
"hdrKey",
")",
"\n",
"if",
"hdr",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"hdrKey",
")",
"\n",
"}",
"\n\n",
"// Example value for hdr:",
"// Bearer authorization_uri=\"https://login.windows.net/996fe9d1-6171-40aa-945b-4c64b63bf655\", error=\"invalid_token\", error_description=\"The authentication failed because of missing 'Authorization' header.\"",
"r",
":=",
"regexp",
".",
"MustCompile",
"(",
"`authorization_uri=\".*/([0-9a-f\\-]+)\"`",
")",
"\n",
"m",
":=",
"r",
".",
"FindStringSubmatch",
"(",
"hdr",
")",
"\n",
"if",
"m",
"==",
"nil",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"hdrKey",
",",
"hdr",
")",
"\n",
"}",
"\n",
"return",
"m",
"[",
"1",
"]",
",",
"nil",
"\n",
"}"
] | // FindTenantID figures out the AAD tenant ID of the subscription by making an
// unauthenticated request to the Get Subscription Details endpoint and parses
// the value from WWW-Authenticate header. | [
"FindTenantID",
"figures",
"out",
"the",
"AAD",
"tenant",
"ID",
"of",
"the",
"subscription",
"by",
"making",
"an",
"unauthenticated",
"request",
"to",
"the",
"Get",
"Subscription",
"Details",
"endpoint",
"and",
"parses",
"the",
"value",
"from",
"WWW",
"-",
"Authenticate",
"header",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/azure/common/devicelogin.go#L178-L207 |
165,128 | hashicorp/packer | builder/azure/pkcs12/bmp-string.go | bmpString | func bmpString(s string) ([]byte, error) {
// References:
// https://tools.ietf.org/html/rfc7292#appendix-B.1
// http://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane
// - non-BMP characters are encoded in UTF 16 by using a surrogate pair of 16-bit codes
// EncodeRune returns 0xfffd if the rune does not need special encoding
// - the above RFC provides the info that BMPStrings are NULL terminated.
ret := make([]byte, 0, 2*len(s)+2)
for _, r := range s {
if t, _ := utf16.EncodeRune(r); t != 0xfffd {
return nil, errors.New("pkcs12: string contains characters that cannot be encoded in UCS-2")
}
ret = append(ret, byte(r/256), byte(r%256))
}
return append(ret, 0, 0), nil
} | go | func bmpString(s string) ([]byte, error) {
// References:
// https://tools.ietf.org/html/rfc7292#appendix-B.1
// http://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane
// - non-BMP characters are encoded in UTF 16 by using a surrogate pair of 16-bit codes
// EncodeRune returns 0xfffd if the rune does not need special encoding
// - the above RFC provides the info that BMPStrings are NULL terminated.
ret := make([]byte, 0, 2*len(s)+2)
for _, r := range s {
if t, _ := utf16.EncodeRune(r); t != 0xfffd {
return nil, errors.New("pkcs12: string contains characters that cannot be encoded in UCS-2")
}
ret = append(ret, byte(r/256), byte(r%256))
}
return append(ret, 0, 0), nil
} | [
"func",
"bmpString",
"(",
"s",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"// References:",
"// https://tools.ietf.org/html/rfc7292#appendix-B.1",
"// http://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane",
"// - non-BMP characters are encoded in UTF 16 by using a surrogate pair of 16-bit codes",
"//\t EncodeRune returns 0xfffd if the rune does not need special encoding",
"// - the above RFC provides the info that BMPStrings are NULL terminated.",
"ret",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"2",
"*",
"len",
"(",
"s",
")",
"+",
"2",
")",
"\n\n",
"for",
"_",
",",
"r",
":=",
"range",
"s",
"{",
"if",
"t",
",",
"_",
":=",
"utf16",
".",
"EncodeRune",
"(",
"r",
")",
";",
"t",
"!=",
"0xfffd",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"ret",
"=",
"append",
"(",
"ret",
",",
"byte",
"(",
"r",
"/",
"256",
")",
",",
"byte",
"(",
"r",
"%",
"256",
")",
")",
"\n",
"}",
"\n\n",
"return",
"append",
"(",
"ret",
",",
"0",
",",
"0",
")",
",",
"nil",
"\n",
"}"
] | // bmpString returns s encoded in UCS-2 with a zero terminator. | [
"bmpString",
"returns",
"s",
"encoded",
"in",
"UCS",
"-",
"2",
"with",
"a",
"zero",
"terminator",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/azure/pkcs12/bmp-string.go#L13-L31 |
165,129 | hashicorp/packer | builder/azure/arm/template_funcs.go | templateCleanImageName | func templateCleanImageName(s string) string {
if ok, _ := assertManagedImageName(s, ""); ok {
return s
}
b := []byte(s)
newb := make([]byte, len(b))
for i := range newb {
if isValidByteValue(b[i]) {
newb[i] = b[i]
} else {
newb[i] = '-'
}
}
newb = bytes.TrimRight(newb, "-_.")
return string(newb)
} | go | func templateCleanImageName(s string) string {
if ok, _ := assertManagedImageName(s, ""); ok {
return s
}
b := []byte(s)
newb := make([]byte, len(b))
for i := range newb {
if isValidByteValue(b[i]) {
newb[i] = b[i]
} else {
newb[i] = '-'
}
}
newb = bytes.TrimRight(newb, "-_.")
return string(newb)
} | [
"func",
"templateCleanImageName",
"(",
"s",
"string",
")",
"string",
"{",
"if",
"ok",
",",
"_",
":=",
"assertManagedImageName",
"(",
"s",
",",
"\"",
"\"",
")",
";",
"ok",
"{",
"return",
"s",
"\n",
"}",
"\n",
"b",
":=",
"[",
"]",
"byte",
"(",
"s",
")",
"\n",
"newb",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"b",
")",
")",
"\n",
"for",
"i",
":=",
"range",
"newb",
"{",
"if",
"isValidByteValue",
"(",
"b",
"[",
"i",
"]",
")",
"{",
"newb",
"[",
"i",
"]",
"=",
"b",
"[",
"i",
"]",
"\n",
"}",
"else",
"{",
"newb",
"[",
"i",
"]",
"=",
"'-'",
"\n",
"}",
"\n",
"}",
"\n\n",
"newb",
"=",
"bytes",
".",
"TrimRight",
"(",
"newb",
",",
"\"",
"\"",
")",
"\n",
"return",
"string",
"(",
"newb",
")",
"\n",
"}"
] | // Clean up image name by replacing invalid characters with "-"
// Names are not allowed to end in '.', '-', or '_' and are trimmed. | [
"Clean",
"up",
"image",
"name",
"by",
"replacing",
"invalid",
"characters",
"with",
"-",
"Names",
"are",
"not",
"allowed",
"to",
"end",
"in",
".",
"-",
"or",
"_",
"and",
"are",
"trimmed",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/azure/arm/template_funcs.go#L25-L41 |
165,130 | hashicorp/packer | communicator/winrm/time.go | formatDuration | func formatDuration(duration time.Duration) string {
// We're not supporting negative durations
if duration.Seconds() <= 0 {
return "PT0S"
}
h := int(duration.Hours())
m := int(duration.Minutes()) - (h * 60)
s := int(duration.Seconds()) - (h*3600 + m*60)
res := "PT"
if h > 0 {
res = fmt.Sprintf("%s%dH", res, h)
}
if m > 0 {
res = fmt.Sprintf("%s%dM", res, m)
}
if s > 0 {
res = fmt.Sprintf("%s%dS", res, s)
}
return res
} | go | func formatDuration(duration time.Duration) string {
// We're not supporting negative durations
if duration.Seconds() <= 0 {
return "PT0S"
}
h := int(duration.Hours())
m := int(duration.Minutes()) - (h * 60)
s := int(duration.Seconds()) - (h*3600 + m*60)
res := "PT"
if h > 0 {
res = fmt.Sprintf("%s%dH", res, h)
}
if m > 0 {
res = fmt.Sprintf("%s%dM", res, m)
}
if s > 0 {
res = fmt.Sprintf("%s%dS", res, s)
}
return res
} | [
"func",
"formatDuration",
"(",
"duration",
"time",
".",
"Duration",
")",
"string",
"{",
"// We're not supporting negative durations",
"if",
"duration",
".",
"Seconds",
"(",
")",
"<=",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"h",
":=",
"int",
"(",
"duration",
".",
"Hours",
"(",
")",
")",
"\n",
"m",
":=",
"int",
"(",
"duration",
".",
"Minutes",
"(",
")",
")",
"-",
"(",
"h",
"*",
"60",
")",
"\n",
"s",
":=",
"int",
"(",
"duration",
".",
"Seconds",
"(",
")",
")",
"-",
"(",
"h",
"*",
"3600",
"+",
"m",
"*",
"60",
")",
"\n\n",
"res",
":=",
"\"",
"\"",
"\n",
"if",
"h",
">",
"0",
"{",
"res",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"res",
",",
"h",
")",
"\n",
"}",
"\n",
"if",
"m",
">",
"0",
"{",
"res",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"res",
",",
"m",
")",
"\n",
"}",
"\n",
"if",
"s",
">",
"0",
"{",
"res",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"res",
",",
"s",
")",
"\n",
"}",
"\n\n",
"return",
"res",
"\n",
"}"
] | // formatDuration formats the given time.Duration into an ISO8601
// duration string. | [
"formatDuration",
"formats",
"the",
"given",
"time",
".",
"Duration",
"into",
"an",
"ISO8601",
"duration",
"string",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/communicator/winrm/time.go#L10-L32 |
165,131 | hashicorp/packer | builder/file/builder.go | Run | func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (packer.Artifact, error) {
artifact := new(FileArtifact)
if b.config.Source != "" {
source, err := os.Open(b.config.Source)
defer source.Close()
if err != nil {
return nil, err
}
// Create will truncate an existing file
target, err := os.Create(b.config.Target)
defer target.Close()
if err != nil {
return nil, err
}
ui.Say(fmt.Sprintf("Copying %s to %s", source.Name(), target.Name()))
bytes, err := io.Copy(target, source)
if err != nil {
return nil, err
}
ui.Say(fmt.Sprintf("Copied %d bytes", bytes))
artifact.filename = target.Name()
} else {
// We're going to write Contents; if it's empty we'll just create an
// empty file.
err := ioutil.WriteFile(b.config.Target, []byte(b.config.Content), 0600)
if err != nil {
return nil, err
}
artifact.filename = b.config.Target
}
if hook != nil {
if err := hook.Run(ctx, packer.HookProvision, ui, new(packer.MockCommunicator), nil); err != nil {
return nil, err
}
}
return artifact, nil
} | go | func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (packer.Artifact, error) {
artifact := new(FileArtifact)
if b.config.Source != "" {
source, err := os.Open(b.config.Source)
defer source.Close()
if err != nil {
return nil, err
}
// Create will truncate an existing file
target, err := os.Create(b.config.Target)
defer target.Close()
if err != nil {
return nil, err
}
ui.Say(fmt.Sprintf("Copying %s to %s", source.Name(), target.Name()))
bytes, err := io.Copy(target, source)
if err != nil {
return nil, err
}
ui.Say(fmt.Sprintf("Copied %d bytes", bytes))
artifact.filename = target.Name()
} else {
// We're going to write Contents; if it's empty we'll just create an
// empty file.
err := ioutil.WriteFile(b.config.Target, []byte(b.config.Content), 0600)
if err != nil {
return nil, err
}
artifact.filename = b.config.Target
}
if hook != nil {
if err := hook.Run(ctx, packer.HookProvision, ui, new(packer.MockCommunicator), nil); err != nil {
return nil, err
}
}
return artifact, nil
} | [
"func",
"(",
"b",
"*",
"Builder",
")",
"Run",
"(",
"ctx",
"context",
".",
"Context",
",",
"ui",
"packer",
".",
"Ui",
",",
"hook",
"packer",
".",
"Hook",
")",
"(",
"packer",
".",
"Artifact",
",",
"error",
")",
"{",
"artifact",
":=",
"new",
"(",
"FileArtifact",
")",
"\n\n",
"if",
"b",
".",
"config",
".",
"Source",
"!=",
"\"",
"\"",
"{",
"source",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"b",
".",
"config",
".",
"Source",
")",
"\n",
"defer",
"source",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Create will truncate an existing file",
"target",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"b",
".",
"config",
".",
"Target",
")",
"\n",
"defer",
"target",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"ui",
".",
"Say",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"source",
".",
"Name",
"(",
")",
",",
"target",
".",
"Name",
"(",
")",
")",
")",
"\n",
"bytes",
",",
"err",
":=",
"io",
".",
"Copy",
"(",
"target",
",",
"source",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"ui",
".",
"Say",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"bytes",
")",
")",
"\n",
"artifact",
".",
"filename",
"=",
"target",
".",
"Name",
"(",
")",
"\n",
"}",
"else",
"{",
"// We're going to write Contents; if it's empty we'll just create an",
"// empty file.",
"err",
":=",
"ioutil",
".",
"WriteFile",
"(",
"b",
".",
"config",
".",
"Target",
",",
"[",
"]",
"byte",
"(",
"b",
".",
"config",
".",
"Content",
")",
",",
"0600",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"artifact",
".",
"filename",
"=",
"b",
".",
"config",
".",
"Target",
"\n",
"}",
"\n\n",
"if",
"hook",
"!=",
"nil",
"{",
"if",
"err",
":=",
"hook",
".",
"Run",
"(",
"ctx",
",",
"packer",
".",
"HookProvision",
",",
"ui",
",",
"new",
"(",
"packer",
".",
"MockCommunicator",
")",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"artifact",
",",
"nil",
"\n",
"}"
] | // Run is where the actual build should take place. It takes a Build and a Ui. | [
"Run",
"is",
"where",
"the",
"actual",
"build",
"should",
"take",
"place",
".",
"It",
"takes",
"a",
"Build",
"and",
"a",
"Ui",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/file/builder.go#L37-L78 |
165,132 | hashicorp/packer | builder/googlecompute/step_teardown_instance.go | Run | func (s *StepTeardownInstance) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
config := state.Get("config").(*Config)
driver := state.Get("driver").(Driver)
ui := state.Get("ui").(packer.Ui)
name := config.InstanceName
if name == "" {
return multistep.ActionHalt
}
ui.Say("Deleting instance...")
instanceLog, _ := driver.GetSerialPortOutput(config.Zone, name)
state.Put("instance_log", instanceLog)
errCh, err := driver.DeleteInstance(config.Zone, name)
if err == nil {
select {
case err = <-errCh:
case <-time.After(config.stateTimeout):
err = errors.New("time out while waiting for instance to delete")
}
}
if err != nil {
ui.Error(fmt.Sprintf(
"Error deleting instance. Please delete it manually.\n\n"+
"Name: %s\n"+
"Error: %s", name, err))
return multistep.ActionHalt
}
ui.Message("Instance has been deleted!")
state.Put("instance_name", "")
return multistep.ActionContinue
} | go | func (s *StepTeardownInstance) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
config := state.Get("config").(*Config)
driver := state.Get("driver").(Driver)
ui := state.Get("ui").(packer.Ui)
name := config.InstanceName
if name == "" {
return multistep.ActionHalt
}
ui.Say("Deleting instance...")
instanceLog, _ := driver.GetSerialPortOutput(config.Zone, name)
state.Put("instance_log", instanceLog)
errCh, err := driver.DeleteInstance(config.Zone, name)
if err == nil {
select {
case err = <-errCh:
case <-time.After(config.stateTimeout):
err = errors.New("time out while waiting for instance to delete")
}
}
if err != nil {
ui.Error(fmt.Sprintf(
"Error deleting instance. Please delete it manually.\n\n"+
"Name: %s\n"+
"Error: %s", name, err))
return multistep.ActionHalt
}
ui.Message("Instance has been deleted!")
state.Put("instance_name", "")
return multistep.ActionContinue
} | [
"func",
"(",
"s",
"*",
"StepTeardownInstance",
")",
"Run",
"(",
"ctx",
"context",
".",
"Context",
",",
"state",
"multistep",
".",
"StateBag",
")",
"multistep",
".",
"StepAction",
"{",
"config",
":=",
"state",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"*",
"Config",
")",
"\n",
"driver",
":=",
"state",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"Driver",
")",
"\n",
"ui",
":=",
"state",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"packer",
".",
"Ui",
")",
"\n\n",
"name",
":=",
"config",
".",
"InstanceName",
"\n",
"if",
"name",
"==",
"\"",
"\"",
"{",
"return",
"multistep",
".",
"ActionHalt",
"\n",
"}",
"\n\n",
"ui",
".",
"Say",
"(",
"\"",
"\"",
")",
"\n",
"instanceLog",
",",
"_",
":=",
"driver",
".",
"GetSerialPortOutput",
"(",
"config",
".",
"Zone",
",",
"name",
")",
"\n",
"state",
".",
"Put",
"(",
"\"",
"\"",
",",
"instanceLog",
")",
"\n",
"errCh",
",",
"err",
":=",
"driver",
".",
"DeleteInstance",
"(",
"config",
".",
"Zone",
",",
"name",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"select",
"{",
"case",
"err",
"=",
"<-",
"errCh",
":",
"case",
"<-",
"time",
".",
"After",
"(",
"config",
".",
"stateTimeout",
")",
":",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"ui",
".",
"Error",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\\n",
"\"",
"+",
"\"",
"\\n",
"\"",
"+",
"\"",
"\"",
",",
"name",
",",
"err",
")",
")",
"\n",
"return",
"multistep",
".",
"ActionHalt",
"\n",
"}",
"\n",
"ui",
".",
"Message",
"(",
"\"",
"\"",
")",
"\n",
"state",
".",
"Put",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"return",
"multistep",
".",
"ActionContinue",
"\n",
"}"
] | // Run executes the Packer build step that tears down a GCE instance. | [
"Run",
"executes",
"the",
"Packer",
"build",
"step",
"that",
"tears",
"down",
"a",
"GCE",
"instance",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/googlecompute/step_teardown_instance.go#L20-L53 |
165,133 | hashicorp/packer | builder/googlecompute/step_teardown_instance.go | Cleanup | func (s *StepTeardownInstance) Cleanup(state multistep.StateBag) {
config := state.Get("config").(*Config)
driver := state.Get("driver").(Driver)
ui := state.Get("ui").(packer.Ui)
ui.Say("Deleting disk...")
errCh, err := driver.DeleteDisk(config.Zone, config.DiskName)
if err == nil {
select {
case err = <-errCh:
case <-time.After(config.stateTimeout):
err = errors.New("time out while waiting for disk to delete")
}
}
if err != nil {
ui.Error(fmt.Sprintf(
"Error deleting disk. Please delete it manually.\n\n"+
"DiskName: %s\n"+
"Zone: %s\n"+
"Error: %s", config.DiskName, config.Zone, err))
}
ui.Message("Disk has been deleted!")
return
} | go | func (s *StepTeardownInstance) Cleanup(state multistep.StateBag) {
config := state.Get("config").(*Config)
driver := state.Get("driver").(Driver)
ui := state.Get("ui").(packer.Ui)
ui.Say("Deleting disk...")
errCh, err := driver.DeleteDisk(config.Zone, config.DiskName)
if err == nil {
select {
case err = <-errCh:
case <-time.After(config.stateTimeout):
err = errors.New("time out while waiting for disk to delete")
}
}
if err != nil {
ui.Error(fmt.Sprintf(
"Error deleting disk. Please delete it manually.\n\n"+
"DiskName: %s\n"+
"Zone: %s\n"+
"Error: %s", config.DiskName, config.Zone, err))
}
ui.Message("Disk has been deleted!")
return
} | [
"func",
"(",
"s",
"*",
"StepTeardownInstance",
")",
"Cleanup",
"(",
"state",
"multistep",
".",
"StateBag",
")",
"{",
"config",
":=",
"state",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"*",
"Config",
")",
"\n",
"driver",
":=",
"state",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"Driver",
")",
"\n",
"ui",
":=",
"state",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"packer",
".",
"Ui",
")",
"\n\n",
"ui",
".",
"Say",
"(",
"\"",
"\"",
")",
"\n",
"errCh",
",",
"err",
":=",
"driver",
".",
"DeleteDisk",
"(",
"config",
".",
"Zone",
",",
"config",
".",
"DiskName",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"select",
"{",
"case",
"err",
"=",
"<-",
"errCh",
":",
"case",
"<-",
"time",
".",
"After",
"(",
"config",
".",
"stateTimeout",
")",
":",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"ui",
".",
"Error",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\\n",
"\"",
"+",
"\"",
"\\n",
"\"",
"+",
"\"",
"\\n",
"\"",
"+",
"\"",
"\"",
",",
"config",
".",
"DiskName",
",",
"config",
".",
"Zone",
",",
"err",
")",
")",
"\n",
"}",
"\n\n",
"ui",
".",
"Message",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"\n",
"}"
] | // Deleting the instance does not remove the boot disk. This cleanup removes
// the disk. | [
"Deleting",
"the",
"instance",
"does",
"not",
"remove",
"the",
"boot",
"disk",
".",
"This",
"cleanup",
"removes",
"the",
"disk",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/googlecompute/step_teardown_instance.go#L57-L83 |
165,134 | hashicorp/packer | communicator/ssh/communicator.go | New | func New(address string, config *Config) (result *comm, err error) {
// Establish an initial connection and connect
result = &comm{
config: config,
address: address,
}
if err = result.reconnect(); err != nil {
result = nil
return
}
return
} | go | func New(address string, config *Config) (result *comm, err error) {
// Establish an initial connection and connect
result = &comm{
config: config,
address: address,
}
if err = result.reconnect(); err != nil {
result = nil
return
}
return
} | [
"func",
"New",
"(",
"address",
"string",
",",
"config",
"*",
"Config",
")",
"(",
"result",
"*",
"comm",
",",
"err",
"error",
")",
"{",
"// Establish an initial connection and connect",
"result",
"=",
"&",
"comm",
"{",
"config",
":",
"config",
",",
"address",
":",
"address",
",",
"}",
"\n\n",
"if",
"err",
"=",
"result",
".",
"reconnect",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"result",
"=",
"nil",
"\n",
"return",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // Creates a new packer.Communicator implementation over SSH. This takes
// an already existing TCP connection and SSH configuration. | [
"Creates",
"a",
"new",
"packer",
".",
"Communicator",
"implementation",
"over",
"SSH",
".",
"This",
"takes",
"an",
"already",
"existing",
"TCP",
"connection",
"and",
"SSH",
"configuration",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/communicator/ssh/communicator.go#L71-L84 |
165,135 | hashicorp/packer | builder/parallels/common/prlctl_post_config.go | Prepare | func (c *PrlctlPostConfig) Prepare(ctx *interpolate.Context) []error {
if c.PrlctlPost == nil {
c.PrlctlPost = make([][]string, 0)
}
return nil
} | go | func (c *PrlctlPostConfig) Prepare(ctx *interpolate.Context) []error {
if c.PrlctlPost == nil {
c.PrlctlPost = make([][]string, 0)
}
return nil
} | [
"func",
"(",
"c",
"*",
"PrlctlPostConfig",
")",
"Prepare",
"(",
"ctx",
"*",
"interpolate",
".",
"Context",
")",
"[",
"]",
"error",
"{",
"if",
"c",
".",
"PrlctlPost",
"==",
"nil",
"{",
"c",
".",
"PrlctlPost",
"=",
"make",
"(",
"[",
"]",
"[",
"]",
"string",
",",
"0",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Prepare sets the default value of "PrlctlPost" property. | [
"Prepare",
"sets",
"the",
"default",
"value",
"of",
"PrlctlPost",
"property",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/parallels/common/prlctl_post_config.go#L14-L20 |
165,136 | hashicorp/packer | builder/oracle/oci/driver_mock.go | DeleteImage | func (d *driverMock) DeleteImage(ctx context.Context, id string) error {
if d.DeleteImageErr != nil {
return d.DeleteImageErr
}
d.DeleteImageID = id
return nil
} | go | func (d *driverMock) DeleteImage(ctx context.Context, id string) error {
if d.DeleteImageErr != nil {
return d.DeleteImageErr
}
d.DeleteImageID = id
return nil
} | [
"func",
"(",
"d",
"*",
"driverMock",
")",
"DeleteImage",
"(",
"ctx",
"context",
".",
"Context",
",",
"id",
"string",
")",
"error",
"{",
"if",
"d",
".",
"DeleteImageErr",
"!=",
"nil",
"{",
"return",
"d",
".",
"DeleteImageErr",
"\n",
"}",
"\n\n",
"d",
".",
"DeleteImageID",
"=",
"id",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // DeleteImage mocks deleting a custom image. | [
"DeleteImage",
"mocks",
"deleting",
"a",
"custom",
"image",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/oracle/oci/driver_mock.go#L54-L62 |
165,137 | hashicorp/packer | builder/cloudstack/builder.go | Run | func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (packer.Artifact, error) {
b.ui = ui
// Create a CloudStack API client.
client := cloudstack.NewAsyncClient(
b.config.APIURL,
b.config.APIKey,
b.config.SecretKey,
!b.config.SSLNoVerify,
)
// Set the time to wait before timing out
client.AsyncTimeout(int64(b.config.AsyncTimeout.Seconds()))
// Some CloudStack service providers only allow HTTP GET calls.
client.HTTPGETOnly = b.config.HTTPGetOnly
// Set up the state.
state := new(multistep.BasicStateBag)
state.Put("client", client)
state.Put("config", b.config)
state.Put("hook", hook)
state.Put("ui", ui)
// Build the steps.
steps := []multistep.Step{
&stepPrepareConfig{},
&common.StepHTTPServer{
HTTPDir: b.config.HTTPDir,
HTTPPortMin: b.config.HTTPPortMin,
HTTPPortMax: b.config.HTTPPortMax,
},
&stepKeypair{
Debug: b.config.PackerDebug,
Comm: &b.config.Comm,
DebugKeyPath: fmt.Sprintf("cs_%s.pem", b.config.PackerBuildName),
},
&stepCreateSecurityGroup{},
&stepCreateInstance{
Ctx: b.config.ctx,
Debug: b.config.PackerDebug,
},
&stepSetupNetworking{},
&communicator.StepConnect{
Config: &b.config.Comm,
Host: commHost,
SSHConfig: b.config.Comm.SSHConfigFunc(),
SSHPort: commPort,
WinRMPort: commPort,
},
&common.StepProvision{},
&common.StepCleanupTempKeys{
Comm: &b.config.Comm,
},
&stepShutdownInstance{},
&stepCreateTemplate{},
}
// Configure the runner and run the steps.
b.runner = common.NewRunner(steps, b.config.PackerConfig, ui)
b.runner.Run(ctx, state)
// If there was an error, return that
if rawErr, ok := state.GetOk("error"); ok {
ui.Error(rawErr.(error).Error())
return nil, rawErr.(error)
}
// If there was no template created, just return
if _, ok := state.GetOk("template"); !ok {
return nil, nil
}
// Build the artifact and return it
artifact := &Artifact{
client: client,
config: b.config,
template: state.Get("template").(*cloudstack.CreateTemplateResponse),
}
return artifact, nil
} | go | func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (packer.Artifact, error) {
b.ui = ui
// Create a CloudStack API client.
client := cloudstack.NewAsyncClient(
b.config.APIURL,
b.config.APIKey,
b.config.SecretKey,
!b.config.SSLNoVerify,
)
// Set the time to wait before timing out
client.AsyncTimeout(int64(b.config.AsyncTimeout.Seconds()))
// Some CloudStack service providers only allow HTTP GET calls.
client.HTTPGETOnly = b.config.HTTPGetOnly
// Set up the state.
state := new(multistep.BasicStateBag)
state.Put("client", client)
state.Put("config", b.config)
state.Put("hook", hook)
state.Put("ui", ui)
// Build the steps.
steps := []multistep.Step{
&stepPrepareConfig{},
&common.StepHTTPServer{
HTTPDir: b.config.HTTPDir,
HTTPPortMin: b.config.HTTPPortMin,
HTTPPortMax: b.config.HTTPPortMax,
},
&stepKeypair{
Debug: b.config.PackerDebug,
Comm: &b.config.Comm,
DebugKeyPath: fmt.Sprintf("cs_%s.pem", b.config.PackerBuildName),
},
&stepCreateSecurityGroup{},
&stepCreateInstance{
Ctx: b.config.ctx,
Debug: b.config.PackerDebug,
},
&stepSetupNetworking{},
&communicator.StepConnect{
Config: &b.config.Comm,
Host: commHost,
SSHConfig: b.config.Comm.SSHConfigFunc(),
SSHPort: commPort,
WinRMPort: commPort,
},
&common.StepProvision{},
&common.StepCleanupTempKeys{
Comm: &b.config.Comm,
},
&stepShutdownInstance{},
&stepCreateTemplate{},
}
// Configure the runner and run the steps.
b.runner = common.NewRunner(steps, b.config.PackerConfig, ui)
b.runner.Run(ctx, state)
// If there was an error, return that
if rawErr, ok := state.GetOk("error"); ok {
ui.Error(rawErr.(error).Error())
return nil, rawErr.(error)
}
// If there was no template created, just return
if _, ok := state.GetOk("template"); !ok {
return nil, nil
}
// Build the artifact and return it
artifact := &Artifact{
client: client,
config: b.config,
template: state.Get("template").(*cloudstack.CreateTemplateResponse),
}
return artifact, nil
} | [
"func",
"(",
"b",
"*",
"Builder",
")",
"Run",
"(",
"ctx",
"context",
".",
"Context",
",",
"ui",
"packer",
".",
"Ui",
",",
"hook",
"packer",
".",
"Hook",
")",
"(",
"packer",
".",
"Artifact",
",",
"error",
")",
"{",
"b",
".",
"ui",
"=",
"ui",
"\n\n",
"// Create a CloudStack API client.",
"client",
":=",
"cloudstack",
".",
"NewAsyncClient",
"(",
"b",
".",
"config",
".",
"APIURL",
",",
"b",
".",
"config",
".",
"APIKey",
",",
"b",
".",
"config",
".",
"SecretKey",
",",
"!",
"b",
".",
"config",
".",
"SSLNoVerify",
",",
")",
"\n\n",
"// Set the time to wait before timing out",
"client",
".",
"AsyncTimeout",
"(",
"int64",
"(",
"b",
".",
"config",
".",
"AsyncTimeout",
".",
"Seconds",
"(",
")",
")",
")",
"\n\n",
"// Some CloudStack service providers only allow HTTP GET calls.",
"client",
".",
"HTTPGETOnly",
"=",
"b",
".",
"config",
".",
"HTTPGetOnly",
"\n\n",
"// Set up the state.",
"state",
":=",
"new",
"(",
"multistep",
".",
"BasicStateBag",
")",
"\n",
"state",
".",
"Put",
"(",
"\"",
"\"",
",",
"client",
")",
"\n",
"state",
".",
"Put",
"(",
"\"",
"\"",
",",
"b",
".",
"config",
")",
"\n",
"state",
".",
"Put",
"(",
"\"",
"\"",
",",
"hook",
")",
"\n",
"state",
".",
"Put",
"(",
"\"",
"\"",
",",
"ui",
")",
"\n\n",
"// Build the steps.",
"steps",
":=",
"[",
"]",
"multistep",
".",
"Step",
"{",
"&",
"stepPrepareConfig",
"{",
"}",
",",
"&",
"common",
".",
"StepHTTPServer",
"{",
"HTTPDir",
":",
"b",
".",
"config",
".",
"HTTPDir",
",",
"HTTPPortMin",
":",
"b",
".",
"config",
".",
"HTTPPortMin",
",",
"HTTPPortMax",
":",
"b",
".",
"config",
".",
"HTTPPortMax",
",",
"}",
",",
"&",
"stepKeypair",
"{",
"Debug",
":",
"b",
".",
"config",
".",
"PackerDebug",
",",
"Comm",
":",
"&",
"b",
".",
"config",
".",
"Comm",
",",
"DebugKeyPath",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"b",
".",
"config",
".",
"PackerBuildName",
")",
",",
"}",
",",
"&",
"stepCreateSecurityGroup",
"{",
"}",
",",
"&",
"stepCreateInstance",
"{",
"Ctx",
":",
"b",
".",
"config",
".",
"ctx",
",",
"Debug",
":",
"b",
".",
"config",
".",
"PackerDebug",
",",
"}",
",",
"&",
"stepSetupNetworking",
"{",
"}",
",",
"&",
"communicator",
".",
"StepConnect",
"{",
"Config",
":",
"&",
"b",
".",
"config",
".",
"Comm",
",",
"Host",
":",
"commHost",
",",
"SSHConfig",
":",
"b",
".",
"config",
".",
"Comm",
".",
"SSHConfigFunc",
"(",
")",
",",
"SSHPort",
":",
"commPort",
",",
"WinRMPort",
":",
"commPort",
",",
"}",
",",
"&",
"common",
".",
"StepProvision",
"{",
"}",
",",
"&",
"common",
".",
"StepCleanupTempKeys",
"{",
"Comm",
":",
"&",
"b",
".",
"config",
".",
"Comm",
",",
"}",
",",
"&",
"stepShutdownInstance",
"{",
"}",
",",
"&",
"stepCreateTemplate",
"{",
"}",
",",
"}",
"\n\n",
"// Configure the runner and run the steps.",
"b",
".",
"runner",
"=",
"common",
".",
"NewRunner",
"(",
"steps",
",",
"b",
".",
"config",
".",
"PackerConfig",
",",
"ui",
")",
"\n",
"b",
".",
"runner",
".",
"Run",
"(",
"ctx",
",",
"state",
")",
"\n\n",
"// If there was an error, return that",
"if",
"rawErr",
",",
"ok",
":=",
"state",
".",
"GetOk",
"(",
"\"",
"\"",
")",
";",
"ok",
"{",
"ui",
".",
"Error",
"(",
"rawErr",
".",
"(",
"error",
")",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"nil",
",",
"rawErr",
".",
"(",
"error",
")",
"\n",
"}",
"\n\n",
"// If there was no template created, just return",
"if",
"_",
",",
"ok",
":=",
"state",
".",
"GetOk",
"(",
"\"",
"\"",
")",
";",
"!",
"ok",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"// Build the artifact and return it",
"artifact",
":=",
"&",
"Artifact",
"{",
"client",
":",
"client",
",",
"config",
":",
"b",
".",
"config",
",",
"template",
":",
"state",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"*",
"cloudstack",
".",
"CreateTemplateResponse",
")",
",",
"}",
"\n\n",
"return",
"artifact",
",",
"nil",
"\n",
"}"
] | // Run implements the packer.Builder interface. | [
"Run",
"implements",
"the",
"packer",
".",
"Builder",
"interface",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/cloudstack/builder.go#L35-L116 |
165,138 | hashicorp/packer | builder/vagrant/artifact.go | NewArtifact | func NewArtifact(provider, dir string) packer.Artifact {
return &artifact{
OutputDir: dir,
BoxName: "package.box",
Provider: provider,
}
} | go | func NewArtifact(provider, dir string) packer.Artifact {
return &artifact{
OutputDir: dir,
BoxName: "package.box",
Provider: provider,
}
} | [
"func",
"NewArtifact",
"(",
"provider",
",",
"dir",
"string",
")",
"packer",
".",
"Artifact",
"{",
"return",
"&",
"artifact",
"{",
"OutputDir",
":",
"dir",
",",
"BoxName",
":",
"\"",
"\"",
",",
"Provider",
":",
"provider",
",",
"}",
"\n",
"}"
] | // NewArtifact returns a vagrant artifact containing the .box file | [
"NewArtifact",
"returns",
"a",
"vagrant",
"artifact",
"containing",
"the",
".",
"box",
"file"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/vagrant/artifact.go#L22-L28 |
165,139 | hashicorp/packer | builder/parallels/common/step_compact_disk.go | Run | func (s *StepCompactDisk) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
driver := state.Get("driver").(Driver)
vmName := state.Get("vmName").(string)
ui := state.Get("ui").(packer.Ui)
if s.Skip {
ui.Say("Skipping disk compaction step...")
return multistep.ActionContinue
}
ui.Say("Compacting the disk image")
diskPath, err := driver.DiskPath(vmName)
if err != nil {
err = fmt.Errorf("Error detecting virtual disk path: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
if err := driver.CompactDisk(diskPath); err != nil {
state.Put("error", fmt.Errorf("Error compacting disk: %s", err))
ui.Error(err.Error())
return multistep.ActionHalt
}
return multistep.ActionContinue
} | go | func (s *StepCompactDisk) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
driver := state.Get("driver").(Driver)
vmName := state.Get("vmName").(string)
ui := state.Get("ui").(packer.Ui)
if s.Skip {
ui.Say("Skipping disk compaction step...")
return multistep.ActionContinue
}
ui.Say("Compacting the disk image")
diskPath, err := driver.DiskPath(vmName)
if err != nil {
err = fmt.Errorf("Error detecting virtual disk path: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
if err := driver.CompactDisk(diskPath); err != nil {
state.Put("error", fmt.Errorf("Error compacting disk: %s", err))
ui.Error(err.Error())
return multistep.ActionHalt
}
return multistep.ActionContinue
} | [
"func",
"(",
"s",
"*",
"StepCompactDisk",
")",
"Run",
"(",
"ctx",
"context",
".",
"Context",
",",
"state",
"multistep",
".",
"StateBag",
")",
"multistep",
".",
"StepAction",
"{",
"driver",
":=",
"state",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"Driver",
")",
"\n",
"vmName",
":=",
"state",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
"\n",
"ui",
":=",
"state",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"packer",
".",
"Ui",
")",
"\n\n",
"if",
"s",
".",
"Skip",
"{",
"ui",
".",
"Say",
"(",
"\"",
"\"",
")",
"\n",
"return",
"multistep",
".",
"ActionContinue",
"\n",
"}",
"\n\n",
"ui",
".",
"Say",
"(",
"\"",
"\"",
")",
"\n",
"diskPath",
",",
"err",
":=",
"driver",
".",
"DiskPath",
"(",
"vmName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"state",
".",
"Put",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"ui",
".",
"Error",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"multistep",
".",
"ActionHalt",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"driver",
".",
"CompactDisk",
"(",
"diskPath",
")",
";",
"err",
"!=",
"nil",
"{",
"state",
".",
"Put",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"ui",
".",
"Error",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"multistep",
".",
"ActionHalt",
"\n",
"}",
"\n\n",
"return",
"multistep",
".",
"ActionContinue",
"\n",
"}"
] | // Run runs the compaction of the virtual disk attached to the VM. | [
"Run",
"runs",
"the",
"compaction",
"of",
"the",
"virtual",
"disk",
"attached",
"to",
"the",
"VM",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/parallels/common/step_compact_disk.go#L26-L52 |
165,140 | hashicorp/packer | builder/googlecompute/winrm.go | winrmConfig | func winrmConfig(state multistep.StateBag) (*communicator.WinRMConfig, error) {
config := state.Get("config").(*Config)
password := state.Get("winrm_password").(string)
return &communicator.WinRMConfig{
Username: config.Comm.WinRMUser,
Password: password,
}, nil
} | go | func winrmConfig(state multistep.StateBag) (*communicator.WinRMConfig, error) {
config := state.Get("config").(*Config)
password := state.Get("winrm_password").(string)
return &communicator.WinRMConfig{
Username: config.Comm.WinRMUser,
Password: password,
}, nil
} | [
"func",
"winrmConfig",
"(",
"state",
"multistep",
".",
"StateBag",
")",
"(",
"*",
"communicator",
".",
"WinRMConfig",
",",
"error",
")",
"{",
"config",
":=",
"state",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"*",
"Config",
")",
"\n",
"password",
":=",
"state",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"string",
")",
"\n\n",
"return",
"&",
"communicator",
".",
"WinRMConfig",
"{",
"Username",
":",
"config",
".",
"Comm",
".",
"WinRMUser",
",",
"Password",
":",
"password",
",",
"}",
",",
"nil",
"\n",
"}"
] | // winrmConfig returns the WinRM configuration. | [
"winrmConfig",
"returns",
"the",
"WinRM",
"configuration",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/googlecompute/winrm.go#L9-L17 |
165,141 | hashicorp/packer | builder/parallels/common/driver_9.go | Import | func (d *Parallels9Driver) Import(name, srcPath, dstDir string, reassignMAC bool) error {
err := d.Prlctl("register", srcPath, "--preserve-uuid")
if err != nil {
return err
}
srcID, err := getVMID(srcPath)
if err != nil {
return err
}
srcMAC := "auto"
if !reassignMAC {
srcMAC, err = getFirstMACAddress(srcPath)
if err != nil {
return err
}
}
err = d.Prlctl("clone", srcID, "--name", name, "--dst", dstDir)
if err != nil {
return err
}
err = d.Prlctl("unregister", srcID)
if err != nil {
return err
}
err = d.Prlctl("set", name, "--device-set", "net0", "--mac", srcMAC)
if err != nil {
return err
}
return nil
} | go | func (d *Parallels9Driver) Import(name, srcPath, dstDir string, reassignMAC bool) error {
err := d.Prlctl("register", srcPath, "--preserve-uuid")
if err != nil {
return err
}
srcID, err := getVMID(srcPath)
if err != nil {
return err
}
srcMAC := "auto"
if !reassignMAC {
srcMAC, err = getFirstMACAddress(srcPath)
if err != nil {
return err
}
}
err = d.Prlctl("clone", srcID, "--name", name, "--dst", dstDir)
if err != nil {
return err
}
err = d.Prlctl("unregister", srcID)
if err != nil {
return err
}
err = d.Prlctl("set", name, "--device-set", "net0", "--mac", srcMAC)
if err != nil {
return err
}
return nil
} | [
"func",
"(",
"d",
"*",
"Parallels9Driver",
")",
"Import",
"(",
"name",
",",
"srcPath",
",",
"dstDir",
"string",
",",
"reassignMAC",
"bool",
")",
"error",
"{",
"err",
":=",
"d",
".",
"Prlctl",
"(",
"\"",
"\"",
",",
"srcPath",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"srcID",
",",
"err",
":=",
"getVMID",
"(",
"srcPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"srcMAC",
":=",
"\"",
"\"",
"\n",
"if",
"!",
"reassignMAC",
"{",
"srcMAC",
",",
"err",
"=",
"getFirstMACAddress",
"(",
"srcPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"err",
"=",
"d",
".",
"Prlctl",
"(",
"\"",
"\"",
",",
"srcID",
",",
"\"",
"\"",
",",
"name",
",",
"\"",
"\"",
",",
"dstDir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"err",
"=",
"d",
".",
"Prlctl",
"(",
"\"",
"\"",
",",
"srcID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"err",
"=",
"d",
".",
"Prlctl",
"(",
"\"",
"\"",
",",
"name",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"srcMAC",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Import creates a clone of the source VM and reassigns the MAC address if needed. | [
"Import",
"creates",
"a",
"clone",
"of",
"the",
"source",
"VM",
"and",
"reassigns",
"the",
"MAC",
"address",
"if",
"needed",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/parallels/common/driver_9.go#L34-L68 |
165,142 | hashicorp/packer | builder/parallels/common/driver_9.go | CompactDisk | func (d *Parallels9Driver) CompactDisk(diskPath string) error {
prlDiskToolPath, err := exec.LookPath("prl_disk_tool")
if err != nil {
return err
}
// Analyze the disk content and remove unused blocks
command := []string{
"compact",
"--hdd", diskPath,
}
if err := exec.Command(prlDiskToolPath, command...).Run(); err != nil {
return err
}
// Remove null blocks
command = []string{
"compact", "--buildmap",
"--hdd", diskPath,
}
if err := exec.Command(prlDiskToolPath, command...).Run(); err != nil {
return err
}
return nil
} | go | func (d *Parallels9Driver) CompactDisk(diskPath string) error {
prlDiskToolPath, err := exec.LookPath("prl_disk_tool")
if err != nil {
return err
}
// Analyze the disk content and remove unused blocks
command := []string{
"compact",
"--hdd", diskPath,
}
if err := exec.Command(prlDiskToolPath, command...).Run(); err != nil {
return err
}
// Remove null blocks
command = []string{
"compact", "--buildmap",
"--hdd", diskPath,
}
if err := exec.Command(prlDiskToolPath, command...).Run(); err != nil {
return err
}
return nil
} | [
"func",
"(",
"d",
"*",
"Parallels9Driver",
")",
"CompactDisk",
"(",
"diskPath",
"string",
")",
"error",
"{",
"prlDiskToolPath",
",",
"err",
":=",
"exec",
".",
"LookPath",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Analyze the disk content and remove unused blocks",
"command",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"diskPath",
",",
"}",
"\n",
"if",
"err",
":=",
"exec",
".",
"Command",
"(",
"prlDiskToolPath",
",",
"command",
"...",
")",
".",
"Run",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Remove null blocks",
"command",
"=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"diskPath",
",",
"}",
"\n",
"if",
"err",
":=",
"exec",
".",
"Command",
"(",
"prlDiskToolPath",
",",
"command",
"...",
")",
".",
"Run",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // CompactDisk performs the compaction of the specified virtual disk image. | [
"CompactDisk",
"performs",
"the",
"compaction",
"of",
"the",
"specified",
"virtual",
"disk",
"image",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/parallels/common/driver_9.go#L124-L149 |
165,143 | hashicorp/packer | builder/parallels/common/driver_9.go | DeviceAddCDROM | func (d *Parallels9Driver) DeviceAddCDROM(name string, image string) (string, error) {
command := []string{
"set", name,
"--device-add", "cdrom",
"--image", image,
"--enable", "--connect",
}
out, err := exec.Command(d.PrlctlPath, command...).Output()
if err != nil {
return "", err
}
deviceRe := regexp.MustCompile(`\s+(cdrom\d+)\s+`)
matches := deviceRe.FindStringSubmatch(string(out))
if matches == nil {
return "", fmt.Errorf(
"Could not determine cdrom device name in the output:\n%s", string(out))
}
deviceName := matches[1]
return deviceName, nil
} | go | func (d *Parallels9Driver) DeviceAddCDROM(name string, image string) (string, error) {
command := []string{
"set", name,
"--device-add", "cdrom",
"--image", image,
"--enable", "--connect",
}
out, err := exec.Command(d.PrlctlPath, command...).Output()
if err != nil {
return "", err
}
deviceRe := regexp.MustCompile(`\s+(cdrom\d+)\s+`)
matches := deviceRe.FindStringSubmatch(string(out))
if matches == nil {
return "", fmt.Errorf(
"Could not determine cdrom device name in the output:\n%s", string(out))
}
deviceName := matches[1]
return deviceName, nil
} | [
"func",
"(",
"d",
"*",
"Parallels9Driver",
")",
"DeviceAddCDROM",
"(",
"name",
"string",
",",
"image",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"command",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"name",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"image",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"}",
"\n\n",
"out",
",",
"err",
":=",
"exec",
".",
"Command",
"(",
"d",
".",
"PrlctlPath",
",",
"command",
"...",
")",
".",
"Output",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"deviceRe",
":=",
"regexp",
".",
"MustCompile",
"(",
"`\\s+(cdrom\\d+)\\s+`",
")",
"\n",
"matches",
":=",
"deviceRe",
".",
"FindStringSubmatch",
"(",
"string",
"(",
"out",
")",
")",
"\n",
"if",
"matches",
"==",
"nil",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\n",
"\"",
",",
"string",
"(",
"out",
")",
")",
"\n",
"}",
"\n\n",
"deviceName",
":=",
"matches",
"[",
"1",
"]",
"\n",
"return",
"deviceName",
",",
"nil",
"\n",
"}"
] | // DeviceAddCDROM adds a virtual CDROM device and attaches the specified image. | [
"DeviceAddCDROM",
"adds",
"a",
"virtual",
"CDROM",
"device",
"and",
"attaches",
"the",
"specified",
"image",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/parallels/common/driver_9.go#L152-L174 |
165,144 | hashicorp/packer | builder/parallels/common/driver_9.go | DiskPath | func (d *Parallels9Driver) DiskPath(name string) (string, error) {
out, err := exec.Command(d.PrlctlPath, "list", "-i", name).Output()
if err != nil {
return "", err
}
HDDRe := regexp.MustCompile("hdd0.* image='(.*)' type=*")
matches := HDDRe.FindStringSubmatch(string(out))
if matches == nil {
return "", fmt.Errorf(
"Could not determine hdd image path in the output:\n%s", string(out))
}
HDDPath := matches[1]
return HDDPath, nil
} | go | func (d *Parallels9Driver) DiskPath(name string) (string, error) {
out, err := exec.Command(d.PrlctlPath, "list", "-i", name).Output()
if err != nil {
return "", err
}
HDDRe := regexp.MustCompile("hdd0.* image='(.*)' type=*")
matches := HDDRe.FindStringSubmatch(string(out))
if matches == nil {
return "", fmt.Errorf(
"Could not determine hdd image path in the output:\n%s", string(out))
}
HDDPath := matches[1]
return HDDPath, nil
} | [
"func",
"(",
"d",
"*",
"Parallels9Driver",
")",
"DiskPath",
"(",
"name",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"out",
",",
"err",
":=",
"exec",
".",
"Command",
"(",
"d",
".",
"PrlctlPath",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"name",
")",
".",
"Output",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"HDDRe",
":=",
"regexp",
".",
"MustCompile",
"(",
"\"",
"\"",
")",
"\n",
"matches",
":=",
"HDDRe",
".",
"FindStringSubmatch",
"(",
"string",
"(",
"out",
")",
")",
"\n",
"if",
"matches",
"==",
"nil",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\n",
"\"",
",",
"string",
"(",
"out",
")",
")",
"\n",
"}",
"\n\n",
"HDDPath",
":=",
"matches",
"[",
"1",
"]",
"\n",
"return",
"HDDPath",
",",
"nil",
"\n",
"}"
] | // DiskPath returns a full path to the first virtual disk drive. | [
"DiskPath",
"returns",
"a",
"full",
"path",
"to",
"the",
"first",
"virtual",
"disk",
"drive",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/parallels/common/driver_9.go#L177-L192 |
165,145 | hashicorp/packer | builder/parallels/common/driver_9.go | IsRunning | func (d *Parallels9Driver) IsRunning(name string) (bool, error) {
var stdout bytes.Buffer
cmd := exec.Command(d.PrlctlPath, "list", name, "--no-header", "--output", "status")
cmd.Stdout = &stdout
if err := cmd.Run(); err != nil {
return false, err
}
log.Printf("Checking VM state: %s\n", strings.TrimSpace(stdout.String()))
for _, line := range strings.Split(stdout.String(), "\n") {
if line == "running" {
return true, nil
}
if line == "suspended" {
return true, nil
}
if line == "paused" {
return true, nil
}
if line == "stopping" {
return true, nil
}
}
return false, nil
} | go | func (d *Parallels9Driver) IsRunning(name string) (bool, error) {
var stdout bytes.Buffer
cmd := exec.Command(d.PrlctlPath, "list", name, "--no-header", "--output", "status")
cmd.Stdout = &stdout
if err := cmd.Run(); err != nil {
return false, err
}
log.Printf("Checking VM state: %s\n", strings.TrimSpace(stdout.String()))
for _, line := range strings.Split(stdout.String(), "\n") {
if line == "running" {
return true, nil
}
if line == "suspended" {
return true, nil
}
if line == "paused" {
return true, nil
}
if line == "stopping" {
return true, nil
}
}
return false, nil
} | [
"func",
"(",
"d",
"*",
"Parallels9Driver",
")",
"IsRunning",
"(",
"name",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"var",
"stdout",
"bytes",
".",
"Buffer",
"\n\n",
"cmd",
":=",
"exec",
".",
"Command",
"(",
"d",
".",
"PrlctlPath",
",",
"\"",
"\"",
",",
"name",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"cmd",
".",
"Stdout",
"=",
"&",
"stdout",
"\n",
"if",
"err",
":=",
"cmd",
".",
"Run",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"strings",
".",
"TrimSpace",
"(",
"stdout",
".",
"String",
"(",
")",
")",
")",
"\n\n",
"for",
"_",
",",
"line",
":=",
"range",
"strings",
".",
"Split",
"(",
"stdout",
".",
"String",
"(",
")",
",",
"\"",
"\\n",
"\"",
")",
"{",
"if",
"line",
"==",
"\"",
"\"",
"{",
"return",
"true",
",",
"nil",
"\n",
"}",
"\n\n",
"if",
"line",
"==",
"\"",
"\"",
"{",
"return",
"true",
",",
"nil",
"\n",
"}",
"\n",
"if",
"line",
"==",
"\"",
"\"",
"{",
"return",
"true",
",",
"nil",
"\n",
"}",
"\n",
"if",
"line",
"==",
"\"",
"\"",
"{",
"return",
"true",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"false",
",",
"nil",
"\n",
"}"
] | // IsRunning determines whether the VM is running or not. | [
"IsRunning",
"determines",
"whether",
"the",
"VM",
"is",
"running",
"or",
"not",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/parallels/common/driver_9.go#L195-L223 |
165,146 | hashicorp/packer | builder/parallels/common/driver_9.go | Stop | func (d *Parallels9Driver) Stop(name string) error {
if err := d.Prlctl("stop", name, "--kill"); err != nil {
return err
}
// We sleep here for a little bit to let the session "unlock"
time.Sleep(2 * time.Second)
return nil
} | go | func (d *Parallels9Driver) Stop(name string) error {
if err := d.Prlctl("stop", name, "--kill"); err != nil {
return err
}
// We sleep here for a little bit to let the session "unlock"
time.Sleep(2 * time.Second)
return nil
} | [
"func",
"(",
"d",
"*",
"Parallels9Driver",
")",
"Stop",
"(",
"name",
"string",
")",
"error",
"{",
"if",
"err",
":=",
"d",
".",
"Prlctl",
"(",
"\"",
"\"",
",",
"name",
",",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// We sleep here for a little bit to let the session \"unlock\"",
"time",
".",
"Sleep",
"(",
"2",
"*",
"time",
".",
"Second",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Stop forcibly stops the VM. | [
"Stop",
"forcibly",
"stops",
"the",
"VM",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/parallels/common/driver_9.go#L226-L235 |
165,147 | hashicorp/packer | builder/parallels/common/driver_9.go | Version | func (d *Parallels9Driver) Version() (string, error) {
out, err := exec.Command(d.PrlctlPath, "--version").Output()
if err != nil {
return "", err
}
versionRe := regexp.MustCompile(`prlctl version (\d+\.\d+.\d+)`)
matches := versionRe.FindStringSubmatch(string(out))
if matches == nil {
return "", fmt.Errorf(
"Could not find Parallels Desktop version in output:\n%s", string(out))
}
version := matches[1]
return version, nil
} | go | func (d *Parallels9Driver) Version() (string, error) {
out, err := exec.Command(d.PrlctlPath, "--version").Output()
if err != nil {
return "", err
}
versionRe := regexp.MustCompile(`prlctl version (\d+\.\d+.\d+)`)
matches := versionRe.FindStringSubmatch(string(out))
if matches == nil {
return "", fmt.Errorf(
"Could not find Parallels Desktop version in output:\n%s", string(out))
}
version := matches[1]
return version, nil
} | [
"func",
"(",
"d",
"*",
"Parallels9Driver",
")",
"Version",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"out",
",",
"err",
":=",
"exec",
".",
"Command",
"(",
"d",
".",
"PrlctlPath",
",",
"\"",
"\"",
")",
".",
"Output",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"versionRe",
":=",
"regexp",
".",
"MustCompile",
"(",
"`prlctl version (\\d+\\.\\d+.\\d+)`",
")",
"\n",
"matches",
":=",
"versionRe",
".",
"FindStringSubmatch",
"(",
"string",
"(",
"out",
")",
")",
"\n",
"if",
"matches",
"==",
"nil",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\n",
"\"",
",",
"string",
"(",
"out",
")",
")",
"\n",
"}",
"\n\n",
"version",
":=",
"matches",
"[",
"1",
"]",
"\n",
"return",
"version",
",",
"nil",
"\n",
"}"
] | // Version returns the version of Parallels Desktop installed on that host. | [
"Version",
"returns",
"the",
"version",
"of",
"Parallels",
"Desktop",
"installed",
"on",
"that",
"host",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/parallels/common/driver_9.go#L266-L281 |
165,148 | hashicorp/packer | builder/parallels/common/driver_9.go | MAC | func (d *Parallels9Driver) MAC(vmName string) (string, error) {
var stdout bytes.Buffer
cmd := exec.Command(d.PrlctlPath, "list", "-i", vmName)
cmd.Stdout = &stdout
if err := cmd.Run(); err != nil {
log.Printf("MAC address for NIC: nic0 on Virtual Machine: %s not found!\n", vmName)
return "", err
}
stdoutString := strings.TrimSpace(stdout.String())
re := regexp.MustCompile("net0.* mac=([0-9A-F]{12}) card=.*")
macMatch := re.FindAllStringSubmatch(stdoutString, 1)
if len(macMatch) != 1 {
return "", fmt.Errorf("MAC address for NIC: nic0 on Virtual Machine: %s not found!\n", vmName)
}
mac := macMatch[0][1]
log.Printf("Found MAC address for NIC: net0 - %s\n", mac)
return mac, nil
} | go | func (d *Parallels9Driver) MAC(vmName string) (string, error) {
var stdout bytes.Buffer
cmd := exec.Command(d.PrlctlPath, "list", "-i", vmName)
cmd.Stdout = &stdout
if err := cmd.Run(); err != nil {
log.Printf("MAC address for NIC: nic0 on Virtual Machine: %s not found!\n", vmName)
return "", err
}
stdoutString := strings.TrimSpace(stdout.String())
re := regexp.MustCompile("net0.* mac=([0-9A-F]{12}) card=.*")
macMatch := re.FindAllStringSubmatch(stdoutString, 1)
if len(macMatch) != 1 {
return "", fmt.Errorf("MAC address for NIC: nic0 on Virtual Machine: %s not found!\n", vmName)
}
mac := macMatch[0][1]
log.Printf("Found MAC address for NIC: net0 - %s\n", mac)
return mac, nil
} | [
"func",
"(",
"d",
"*",
"Parallels9Driver",
")",
"MAC",
"(",
"vmName",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"var",
"stdout",
"bytes",
".",
"Buffer",
"\n\n",
"cmd",
":=",
"exec",
".",
"Command",
"(",
"d",
".",
"PrlctlPath",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"vmName",
")",
"\n",
"cmd",
".",
"Stdout",
"=",
"&",
"stdout",
"\n",
"if",
"err",
":=",
"cmd",
".",
"Run",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"vmName",
")",
"\n",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"stdoutString",
":=",
"strings",
".",
"TrimSpace",
"(",
"stdout",
".",
"String",
"(",
")",
")",
"\n",
"re",
":=",
"regexp",
".",
"MustCompile",
"(",
"\"",
"\"",
")",
"\n",
"macMatch",
":=",
"re",
".",
"FindAllStringSubmatch",
"(",
"stdoutString",
",",
"1",
")",
"\n\n",
"if",
"len",
"(",
"macMatch",
")",
"!=",
"1",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\n",
"\"",
",",
"vmName",
")",
"\n",
"}",
"\n\n",
"mac",
":=",
"macMatch",
"[",
"0",
"]",
"[",
"1",
"]",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"mac",
")",
"\n",
"return",
"mac",
",",
"nil",
"\n",
"}"
] | // MAC returns the MAC address of the VM's first network interface. | [
"MAC",
"returns",
"the",
"MAC",
"address",
"of",
"the",
"VM",
"s",
"first",
"network",
"interface",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/parallels/common/driver_9.go#L353-L374 |
165,149 | hashicorp/packer | builder/azure/common/gluestrings.go | GlueStrings | func GlueStrings(a, b string) string {
shift := 0
for shift < len(a) {
i := 0
for (i+shift < len(a)) && (i < len(b)) && (a[i+shift] == b[i]) {
i++
}
if i+shift == len(a) {
break
}
shift++
}
return a[:shift] + b
} | go | func GlueStrings(a, b string) string {
shift := 0
for shift < len(a) {
i := 0
for (i+shift < len(a)) && (i < len(b)) && (a[i+shift] == b[i]) {
i++
}
if i+shift == len(a) {
break
}
shift++
}
return a[:shift] + b
} | [
"func",
"GlueStrings",
"(",
"a",
",",
"b",
"string",
")",
"string",
"{",
"shift",
":=",
"0",
"\n",
"for",
"shift",
"<",
"len",
"(",
"a",
")",
"{",
"i",
":=",
"0",
"\n",
"for",
"(",
"i",
"+",
"shift",
"<",
"len",
"(",
"a",
")",
")",
"&&",
"(",
"i",
"<",
"len",
"(",
"b",
")",
")",
"&&",
"(",
"a",
"[",
"i",
"+",
"shift",
"]",
"==",
"b",
"[",
"i",
"]",
")",
"{",
"i",
"++",
"\n",
"}",
"\n",
"if",
"i",
"+",
"shift",
"==",
"len",
"(",
"a",
")",
"{",
"break",
"\n",
"}",
"\n",
"shift",
"++",
"\n",
"}",
"\n\n",
"return",
"a",
"[",
":",
"shift",
"]",
"+",
"b",
"\n",
"}"
] | // removes overlap between the end of a and the start of b and
// glues them together | [
"removes",
"overlap",
"between",
"the",
"end",
"of",
"a",
"and",
"the",
"start",
"of",
"b",
"and",
"glues",
"them",
"together"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/azure/common/gluestrings.go#L5-L19 |
165,150 | hashicorp/packer | main.go | realMain | func realMain() int {
var wrapConfig panicwrap.WrapConfig
// When following env variable is set, packer
// wont panic wrap itself as it's already wrapped.
// i.e.: when terraform runs it.
wrapConfig.CookieKey = "PACKER_WRAP_COOKIE"
wrapConfig.CookieValue = "49C22B1A-3A93-4C98-97FA-E07D18C787B5"
if !panicwrap.Wrapped(&wrapConfig) {
// Generate a UUID for this packer run and pass it to the environment.
// GenerateUUID always returns a nil error (based on rand.Read) so we'll
// just ignore it.
UUID, _ := uuid.GenerateUUID()
os.Setenv("PACKER_RUN_UUID", UUID)
// Determine where logs should go in general (requested by the user)
logWriter, err := logOutput()
if err != nil {
fmt.Fprintf(os.Stderr, "Couldn't setup log output: %s", err)
return 1
}
if logWriter == nil {
logWriter = ioutil.Discard
}
packer.LogSecretFilter.SetOutput(logWriter)
//packer.LogSecrets.
// Disable logging here
log.SetOutput(ioutil.Discard)
// We always send logs to a temporary file that we use in case
// there is a panic. Otherwise, we delete it.
logTempFile, err := tmp.File("packer-log")
if err != nil {
fmt.Fprintf(os.Stderr, "Couldn't setup logging tempfile: %s", err)
return 1
}
defer os.Remove(logTempFile.Name())
defer logTempFile.Close()
// Tell the logger to log to this file
os.Setenv(EnvLog, "")
os.Setenv(EnvLogFile, "")
// Setup the prefixed readers that send data properly to
// stdout/stderr.
doneCh := make(chan struct{})
outR, outW := io.Pipe()
go copyOutput(outR, doneCh)
// Enable checkpoint for panic reporting
if config, _ := loadConfig(); config != nil && !config.DisableCheckpoint {
packer.CheckpointReporter = packer.NewCheckpointReporter(
config.DisableCheckpointSignature,
)
}
// Create the configuration for panicwrap and wrap our executable
wrapConfig.Handler = panicHandler(logTempFile)
wrapConfig.Writer = io.MultiWriter(logTempFile, &packer.LogSecretFilter)
wrapConfig.Stdout = outW
wrapConfig.DetectDuration = 500 * time.Millisecond
wrapConfig.ForwardSignals = []os.Signal{syscall.SIGTERM}
exitStatus, err := panicwrap.Wrap(&wrapConfig)
if err != nil {
fmt.Fprintf(os.Stderr, "Couldn't start Packer: %s", err)
return 1
}
// If >= 0, we're the parent, so just exit
if exitStatus >= 0 {
// Close the stdout writer so that our copy process can finish
outW.Close()
// Wait for the output copying to finish
<-doneCh
return exitStatus
}
// We're the child, so just close the tempfile we made in order to
// save file handles since the tempfile is only used by the parent.
logTempFile.Close()
}
// Call the real main
return wrappedMain()
} | go | func realMain() int {
var wrapConfig panicwrap.WrapConfig
// When following env variable is set, packer
// wont panic wrap itself as it's already wrapped.
// i.e.: when terraform runs it.
wrapConfig.CookieKey = "PACKER_WRAP_COOKIE"
wrapConfig.CookieValue = "49C22B1A-3A93-4C98-97FA-E07D18C787B5"
if !panicwrap.Wrapped(&wrapConfig) {
// Generate a UUID for this packer run and pass it to the environment.
// GenerateUUID always returns a nil error (based on rand.Read) so we'll
// just ignore it.
UUID, _ := uuid.GenerateUUID()
os.Setenv("PACKER_RUN_UUID", UUID)
// Determine where logs should go in general (requested by the user)
logWriter, err := logOutput()
if err != nil {
fmt.Fprintf(os.Stderr, "Couldn't setup log output: %s", err)
return 1
}
if logWriter == nil {
logWriter = ioutil.Discard
}
packer.LogSecretFilter.SetOutput(logWriter)
//packer.LogSecrets.
// Disable logging here
log.SetOutput(ioutil.Discard)
// We always send logs to a temporary file that we use in case
// there is a panic. Otherwise, we delete it.
logTempFile, err := tmp.File("packer-log")
if err != nil {
fmt.Fprintf(os.Stderr, "Couldn't setup logging tempfile: %s", err)
return 1
}
defer os.Remove(logTempFile.Name())
defer logTempFile.Close()
// Tell the logger to log to this file
os.Setenv(EnvLog, "")
os.Setenv(EnvLogFile, "")
// Setup the prefixed readers that send data properly to
// stdout/stderr.
doneCh := make(chan struct{})
outR, outW := io.Pipe()
go copyOutput(outR, doneCh)
// Enable checkpoint for panic reporting
if config, _ := loadConfig(); config != nil && !config.DisableCheckpoint {
packer.CheckpointReporter = packer.NewCheckpointReporter(
config.DisableCheckpointSignature,
)
}
// Create the configuration for panicwrap and wrap our executable
wrapConfig.Handler = panicHandler(logTempFile)
wrapConfig.Writer = io.MultiWriter(logTempFile, &packer.LogSecretFilter)
wrapConfig.Stdout = outW
wrapConfig.DetectDuration = 500 * time.Millisecond
wrapConfig.ForwardSignals = []os.Signal{syscall.SIGTERM}
exitStatus, err := panicwrap.Wrap(&wrapConfig)
if err != nil {
fmt.Fprintf(os.Stderr, "Couldn't start Packer: %s", err)
return 1
}
// If >= 0, we're the parent, so just exit
if exitStatus >= 0 {
// Close the stdout writer so that our copy process can finish
outW.Close()
// Wait for the output copying to finish
<-doneCh
return exitStatus
}
// We're the child, so just close the tempfile we made in order to
// save file handles since the tempfile is only used by the parent.
logTempFile.Close()
}
// Call the real main
return wrappedMain()
} | [
"func",
"realMain",
"(",
")",
"int",
"{",
"var",
"wrapConfig",
"panicwrap",
".",
"WrapConfig",
"\n",
"// When following env variable is set, packer",
"// wont panic wrap itself as it's already wrapped.",
"// i.e.: when terraform runs it.",
"wrapConfig",
".",
"CookieKey",
"=",
"\"",
"\"",
"\n",
"wrapConfig",
".",
"CookieValue",
"=",
"\"",
"\"",
"\n\n",
"if",
"!",
"panicwrap",
".",
"Wrapped",
"(",
"&",
"wrapConfig",
")",
"{",
"// Generate a UUID for this packer run and pass it to the environment.",
"// GenerateUUID always returns a nil error (based on rand.Read) so we'll",
"// just ignore it.",
"UUID",
",",
"_",
":=",
"uuid",
".",
"GenerateUUID",
"(",
")",
"\n",
"os",
".",
"Setenv",
"(",
"\"",
"\"",
",",
"UUID",
")",
"\n\n",
"// Determine where logs should go in general (requested by the user)",
"logWriter",
",",
"err",
":=",
"logOutput",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"1",
"\n",
"}",
"\n",
"if",
"logWriter",
"==",
"nil",
"{",
"logWriter",
"=",
"ioutil",
".",
"Discard",
"\n",
"}",
"\n\n",
"packer",
".",
"LogSecretFilter",
".",
"SetOutput",
"(",
"logWriter",
")",
"\n\n",
"//packer.LogSecrets.",
"// Disable logging here",
"log",
".",
"SetOutput",
"(",
"ioutil",
".",
"Discard",
")",
"\n\n",
"// We always send logs to a temporary file that we use in case",
"// there is a panic. Otherwise, we delete it.",
"logTempFile",
",",
"err",
":=",
"tmp",
".",
"File",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"1",
"\n",
"}",
"\n",
"defer",
"os",
".",
"Remove",
"(",
"logTempFile",
".",
"Name",
"(",
")",
")",
"\n",
"defer",
"logTempFile",
".",
"Close",
"(",
")",
"\n\n",
"// Tell the logger to log to this file",
"os",
".",
"Setenv",
"(",
"EnvLog",
",",
"\"",
"\"",
")",
"\n",
"os",
".",
"Setenv",
"(",
"EnvLogFile",
",",
"\"",
"\"",
")",
"\n\n",
"// Setup the prefixed readers that send data properly to",
"// stdout/stderr.",
"doneCh",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"outR",
",",
"outW",
":=",
"io",
".",
"Pipe",
"(",
")",
"\n",
"go",
"copyOutput",
"(",
"outR",
",",
"doneCh",
")",
"\n\n",
"// Enable checkpoint for panic reporting",
"if",
"config",
",",
"_",
":=",
"loadConfig",
"(",
")",
";",
"config",
"!=",
"nil",
"&&",
"!",
"config",
".",
"DisableCheckpoint",
"{",
"packer",
".",
"CheckpointReporter",
"=",
"packer",
".",
"NewCheckpointReporter",
"(",
"config",
".",
"DisableCheckpointSignature",
",",
")",
"\n",
"}",
"\n\n",
"// Create the configuration for panicwrap and wrap our executable",
"wrapConfig",
".",
"Handler",
"=",
"panicHandler",
"(",
"logTempFile",
")",
"\n",
"wrapConfig",
".",
"Writer",
"=",
"io",
".",
"MultiWriter",
"(",
"logTempFile",
",",
"&",
"packer",
".",
"LogSecretFilter",
")",
"\n",
"wrapConfig",
".",
"Stdout",
"=",
"outW",
"\n",
"wrapConfig",
".",
"DetectDuration",
"=",
"500",
"*",
"time",
".",
"Millisecond",
"\n",
"wrapConfig",
".",
"ForwardSignals",
"=",
"[",
"]",
"os",
".",
"Signal",
"{",
"syscall",
".",
"SIGTERM",
"}",
"\n",
"exitStatus",
",",
"err",
":=",
"panicwrap",
".",
"Wrap",
"(",
"&",
"wrapConfig",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"1",
"\n",
"}",
"\n\n",
"// If >= 0, we're the parent, so just exit",
"if",
"exitStatus",
">=",
"0",
"{",
"// Close the stdout writer so that our copy process can finish",
"outW",
".",
"Close",
"(",
")",
"\n\n",
"// Wait for the output copying to finish",
"<-",
"doneCh",
"\n\n",
"return",
"exitStatus",
"\n",
"}",
"\n\n",
"// We're the child, so just close the tempfile we made in order to",
"// save file handles since the tempfile is only used by the parent.",
"logTempFile",
".",
"Close",
"(",
")",
"\n",
"}",
"\n\n",
"// Call the real main",
"return",
"wrappedMain",
"(",
")",
"\n",
"}"
] | // realMain is executed from main and returns the exit status to exit with. | [
"realMain",
"is",
"executed",
"from",
"main",
"and",
"returns",
"the",
"exit",
"status",
"to",
"exit",
"with",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/main.go#L39-L128 |
165,151 | hashicorp/packer | main.go | wrappedMain | func wrappedMain() int {
// If there is no explicit number of Go threads to use, then set it
if os.Getenv("GOMAXPROCS") == "" {
runtime.GOMAXPROCS(runtime.NumCPU())
}
packer.LogSecretFilter.SetOutput(os.Stderr)
log.SetOutput(&packer.LogSecretFilter)
log.Printf("[INFO] Packer version: %s", version.FormattedVersion())
log.Printf("Packer Target OS/Arch: %s %s", runtime.GOOS, runtime.GOARCH)
log.Printf("Built with Go Version: %s", runtime.Version())
inPlugin := os.Getenv(plugin.MagicCookieKey) == plugin.MagicCookieValue
config, err := loadConfig()
if err != nil {
fmt.Fprintf(os.Stderr, "Error loading configuration: \n\n%s\n", err)
return 1
}
log.Printf("Packer config: %+v", config)
// Fire off the checkpoint.
go runCheckpoint(config)
if !config.DisableCheckpoint {
packer.CheckpointReporter = packer.NewCheckpointReporter(
config.DisableCheckpointSignature,
)
}
cacheDir, err := packer.CachePath()
if err != nil {
fmt.Fprintf(os.Stderr, "Error preparing cache directory: \n\n%s\n", err)
return 1
}
log.Printf("Setting cache directory: %s", cacheDir)
// Determine if we're in machine-readable mode by mucking around with
// the arguments...
args, machineReadable := extractMachineReadable(os.Args[1:])
defer plugin.CleanupClients()
var ui packer.Ui
if machineReadable {
// Setup the UI as we're being machine-readable
ui = &packer.MachineReadableUi{
Writer: os.Stdout,
}
// Set this so that we don't get colored output in our machine-
// readable UI.
if err := os.Setenv("PACKER_NO_COLOR", "1"); err != nil {
fmt.Fprintf(os.Stderr, "Packer failed to initialize UI: %s\n", err)
return 1
}
} else {
basicUi := &packer.BasicUi{
Reader: os.Stdin,
Writer: os.Stdout,
ErrorWriter: os.Stdout,
}
ui = basicUi
if !inPlugin {
if TTY, err := tty.Open(); err != nil {
fmt.Fprintf(os.Stderr, "No tty available: %s\n", err)
} else {
basicUi.TTY = TTY
defer TTY.Close()
}
}
}
// Create the CLI meta
CommandMeta = &command.Meta{
CoreConfig: &packer.CoreConfig{
Components: packer.ComponentFinder{
Builder: config.LoadBuilder,
Hook: config.LoadHook,
PostProcessor: config.LoadPostProcessor,
Provisioner: config.LoadProvisioner,
},
Version: version.Version,
},
Ui: ui,
}
cli := &cli.CLI{
Args: args,
Autocomplete: true,
Commands: Commands,
HelpFunc: excludeHelpFunc(Commands, []string{"plugin"}),
HelpWriter: os.Stdout,
Name: "packer",
Version: version.Version,
}
exitCode, err := cli.Run()
if !inPlugin {
if err := packer.CheckpointReporter.Finalize(cli.Subcommand(), exitCode, err); err != nil {
log.Printf("[WARN] (telemetry) Error finalizing report. This is safe to ignore. %s", err.Error())
}
}
if err != nil {
fmt.Fprintf(os.Stderr, "Error executing CLI: %s\n", err)
return 1
}
return exitCode
} | go | func wrappedMain() int {
// If there is no explicit number of Go threads to use, then set it
if os.Getenv("GOMAXPROCS") == "" {
runtime.GOMAXPROCS(runtime.NumCPU())
}
packer.LogSecretFilter.SetOutput(os.Stderr)
log.SetOutput(&packer.LogSecretFilter)
log.Printf("[INFO] Packer version: %s", version.FormattedVersion())
log.Printf("Packer Target OS/Arch: %s %s", runtime.GOOS, runtime.GOARCH)
log.Printf("Built with Go Version: %s", runtime.Version())
inPlugin := os.Getenv(plugin.MagicCookieKey) == plugin.MagicCookieValue
config, err := loadConfig()
if err != nil {
fmt.Fprintf(os.Stderr, "Error loading configuration: \n\n%s\n", err)
return 1
}
log.Printf("Packer config: %+v", config)
// Fire off the checkpoint.
go runCheckpoint(config)
if !config.DisableCheckpoint {
packer.CheckpointReporter = packer.NewCheckpointReporter(
config.DisableCheckpointSignature,
)
}
cacheDir, err := packer.CachePath()
if err != nil {
fmt.Fprintf(os.Stderr, "Error preparing cache directory: \n\n%s\n", err)
return 1
}
log.Printf("Setting cache directory: %s", cacheDir)
// Determine if we're in machine-readable mode by mucking around with
// the arguments...
args, machineReadable := extractMachineReadable(os.Args[1:])
defer plugin.CleanupClients()
var ui packer.Ui
if machineReadable {
// Setup the UI as we're being machine-readable
ui = &packer.MachineReadableUi{
Writer: os.Stdout,
}
// Set this so that we don't get colored output in our machine-
// readable UI.
if err := os.Setenv("PACKER_NO_COLOR", "1"); err != nil {
fmt.Fprintf(os.Stderr, "Packer failed to initialize UI: %s\n", err)
return 1
}
} else {
basicUi := &packer.BasicUi{
Reader: os.Stdin,
Writer: os.Stdout,
ErrorWriter: os.Stdout,
}
ui = basicUi
if !inPlugin {
if TTY, err := tty.Open(); err != nil {
fmt.Fprintf(os.Stderr, "No tty available: %s\n", err)
} else {
basicUi.TTY = TTY
defer TTY.Close()
}
}
}
// Create the CLI meta
CommandMeta = &command.Meta{
CoreConfig: &packer.CoreConfig{
Components: packer.ComponentFinder{
Builder: config.LoadBuilder,
Hook: config.LoadHook,
PostProcessor: config.LoadPostProcessor,
Provisioner: config.LoadProvisioner,
},
Version: version.Version,
},
Ui: ui,
}
cli := &cli.CLI{
Args: args,
Autocomplete: true,
Commands: Commands,
HelpFunc: excludeHelpFunc(Commands, []string{"plugin"}),
HelpWriter: os.Stdout,
Name: "packer",
Version: version.Version,
}
exitCode, err := cli.Run()
if !inPlugin {
if err := packer.CheckpointReporter.Finalize(cli.Subcommand(), exitCode, err); err != nil {
log.Printf("[WARN] (telemetry) Error finalizing report. This is safe to ignore. %s", err.Error())
}
}
if err != nil {
fmt.Fprintf(os.Stderr, "Error executing CLI: %s\n", err)
return 1
}
return exitCode
} | [
"func",
"wrappedMain",
"(",
")",
"int",
"{",
"// If there is no explicit number of Go threads to use, then set it",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"==",
"\"",
"\"",
"{",
"runtime",
".",
"GOMAXPROCS",
"(",
"runtime",
".",
"NumCPU",
"(",
")",
")",
"\n",
"}",
"\n\n",
"packer",
".",
"LogSecretFilter",
".",
"SetOutput",
"(",
"os",
".",
"Stderr",
")",
"\n",
"log",
".",
"SetOutput",
"(",
"&",
"packer",
".",
"LogSecretFilter",
")",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"version",
".",
"FormattedVersion",
"(",
")",
")",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"runtime",
".",
"GOOS",
",",
"runtime",
".",
"GOARCH",
")",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"runtime",
".",
"Version",
"(",
")",
")",
"\n\n",
"inPlugin",
":=",
"os",
".",
"Getenv",
"(",
"plugin",
".",
"MagicCookieKey",
")",
"==",
"plugin",
".",
"MagicCookieValue",
"\n\n",
"config",
",",
"err",
":=",
"loadConfig",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\n",
"\\n",
"\\n",
"\"",
",",
"err",
")",
"\n",
"return",
"1",
"\n",
"}",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"config",
")",
"\n\n",
"// Fire off the checkpoint.",
"go",
"runCheckpoint",
"(",
"config",
")",
"\n",
"if",
"!",
"config",
".",
"DisableCheckpoint",
"{",
"packer",
".",
"CheckpointReporter",
"=",
"packer",
".",
"NewCheckpointReporter",
"(",
"config",
".",
"DisableCheckpointSignature",
",",
")",
"\n",
"}",
"\n\n",
"cacheDir",
",",
"err",
":=",
"packer",
".",
"CachePath",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\n",
"\\n",
"\\n",
"\"",
",",
"err",
")",
"\n",
"return",
"1",
"\n",
"}",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"cacheDir",
")",
"\n\n",
"// Determine if we're in machine-readable mode by mucking around with",
"// the arguments...",
"args",
",",
"machineReadable",
":=",
"extractMachineReadable",
"(",
"os",
".",
"Args",
"[",
"1",
":",
"]",
")",
"\n\n",
"defer",
"plugin",
".",
"CleanupClients",
"(",
")",
"\n\n",
"var",
"ui",
"packer",
".",
"Ui",
"\n",
"if",
"machineReadable",
"{",
"// Setup the UI as we're being machine-readable",
"ui",
"=",
"&",
"packer",
".",
"MachineReadableUi",
"{",
"Writer",
":",
"os",
".",
"Stdout",
",",
"}",
"\n\n",
"// Set this so that we don't get colored output in our machine-",
"// readable UI.",
"if",
"err",
":=",
"os",
".",
"Setenv",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\n",
"\"",
",",
"err",
")",
"\n",
"return",
"1",
"\n",
"}",
"\n",
"}",
"else",
"{",
"basicUi",
":=",
"&",
"packer",
".",
"BasicUi",
"{",
"Reader",
":",
"os",
".",
"Stdin",
",",
"Writer",
":",
"os",
".",
"Stdout",
",",
"ErrorWriter",
":",
"os",
".",
"Stdout",
",",
"}",
"\n",
"ui",
"=",
"basicUi",
"\n",
"if",
"!",
"inPlugin",
"{",
"if",
"TTY",
",",
"err",
":=",
"tty",
".",
"Open",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\n",
"\"",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"basicUi",
".",
"TTY",
"=",
"TTY",
"\n",
"defer",
"TTY",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"// Create the CLI meta",
"CommandMeta",
"=",
"&",
"command",
".",
"Meta",
"{",
"CoreConfig",
":",
"&",
"packer",
".",
"CoreConfig",
"{",
"Components",
":",
"packer",
".",
"ComponentFinder",
"{",
"Builder",
":",
"config",
".",
"LoadBuilder",
",",
"Hook",
":",
"config",
".",
"LoadHook",
",",
"PostProcessor",
":",
"config",
".",
"LoadPostProcessor",
",",
"Provisioner",
":",
"config",
".",
"LoadProvisioner",
",",
"}",
",",
"Version",
":",
"version",
".",
"Version",
",",
"}",
",",
"Ui",
":",
"ui",
",",
"}",
"\n\n",
"cli",
":=",
"&",
"cli",
".",
"CLI",
"{",
"Args",
":",
"args",
",",
"Autocomplete",
":",
"true",
",",
"Commands",
":",
"Commands",
",",
"HelpFunc",
":",
"excludeHelpFunc",
"(",
"Commands",
",",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
")",
",",
"HelpWriter",
":",
"os",
".",
"Stdout",
",",
"Name",
":",
"\"",
"\"",
",",
"Version",
":",
"version",
".",
"Version",
",",
"}",
"\n\n",
"exitCode",
",",
"err",
":=",
"cli",
".",
"Run",
"(",
")",
"\n",
"if",
"!",
"inPlugin",
"{",
"if",
"err",
":=",
"packer",
".",
"CheckpointReporter",
".",
"Finalize",
"(",
"cli",
".",
"Subcommand",
"(",
")",
",",
"exitCode",
",",
"err",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\\n",
"\"",
",",
"err",
")",
"\n",
"return",
"1",
"\n",
"}",
"\n\n",
"return",
"exitCode",
"\n",
"}"
] | // wrappedMain is called only when we're wrapped by panicwrap and
// returns the exit status to exit with. | [
"wrappedMain",
"is",
"called",
"only",
"when",
"we",
"re",
"wrapped",
"by",
"panicwrap",
"and",
"returns",
"the",
"exit",
"status",
"to",
"exit",
"with",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/main.go#L132-L241 |
165,152 | hashicorp/packer | main.go | excludeHelpFunc | func excludeHelpFunc(commands map[string]cli.CommandFactory, exclude []string) cli.HelpFunc {
// Make search slice into a map so we can use use the `if found` idiom
// instead of a nested loop.
var excludes = make(map[string]interface{}, len(exclude))
for _, item := range exclude {
excludes[item] = nil
}
// Create filtered list of commands
helpCommands := []string{}
for command := range commands {
if _, found := excludes[command]; !found {
helpCommands = append(helpCommands, command)
}
}
return cli.FilteredHelpFunc(helpCommands, cli.BasicHelpFunc("packer"))
} | go | func excludeHelpFunc(commands map[string]cli.CommandFactory, exclude []string) cli.HelpFunc {
// Make search slice into a map so we can use use the `if found` idiom
// instead of a nested loop.
var excludes = make(map[string]interface{}, len(exclude))
for _, item := range exclude {
excludes[item] = nil
}
// Create filtered list of commands
helpCommands := []string{}
for command := range commands {
if _, found := excludes[command]; !found {
helpCommands = append(helpCommands, command)
}
}
return cli.FilteredHelpFunc(helpCommands, cli.BasicHelpFunc("packer"))
} | [
"func",
"excludeHelpFunc",
"(",
"commands",
"map",
"[",
"string",
"]",
"cli",
".",
"CommandFactory",
",",
"exclude",
"[",
"]",
"string",
")",
"cli",
".",
"HelpFunc",
"{",
"// Make search slice into a map so we can use use the `if found` idiom",
"// instead of a nested loop.",
"var",
"excludes",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"len",
"(",
"exclude",
")",
")",
"\n",
"for",
"_",
",",
"item",
":=",
"range",
"exclude",
"{",
"excludes",
"[",
"item",
"]",
"=",
"nil",
"\n",
"}",
"\n\n",
"// Create filtered list of commands",
"helpCommands",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"command",
":=",
"range",
"commands",
"{",
"if",
"_",
",",
"found",
":=",
"excludes",
"[",
"command",
"]",
";",
"!",
"found",
"{",
"helpCommands",
"=",
"append",
"(",
"helpCommands",
",",
"command",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"cli",
".",
"FilteredHelpFunc",
"(",
"helpCommands",
",",
"cli",
".",
"BasicHelpFunc",
"(",
"\"",
"\"",
")",
")",
"\n",
"}"
] | // excludeHelpFunc filters commands we don't want to show from the list of
// commands displayed in packer's help text. | [
"excludeHelpFunc",
"filters",
"commands",
"we",
"don",
"t",
"want",
"to",
"show",
"from",
"the",
"list",
"of",
"commands",
"displayed",
"in",
"packer",
"s",
"help",
"text",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/main.go#L245-L262 |
165,153 | hashicorp/packer | main.go | extractMachineReadable | func extractMachineReadable(args []string) ([]string, bool) {
for i, arg := range args {
if arg == "-machine-readable" {
// We found it. Slice it out.
result := make([]string, len(args)-1)
copy(result, args[:i])
copy(result[i:], args[i+1:])
return result, true
}
}
return args, false
} | go | func extractMachineReadable(args []string) ([]string, bool) {
for i, arg := range args {
if arg == "-machine-readable" {
// We found it. Slice it out.
result := make([]string, len(args)-1)
copy(result, args[:i])
copy(result[i:], args[i+1:])
return result, true
}
}
return args, false
} | [
"func",
"extractMachineReadable",
"(",
"args",
"[",
"]",
"string",
")",
"(",
"[",
"]",
"string",
",",
"bool",
")",
"{",
"for",
"i",
",",
"arg",
":=",
"range",
"args",
"{",
"if",
"arg",
"==",
"\"",
"\"",
"{",
"// We found it. Slice it out.",
"result",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"args",
")",
"-",
"1",
")",
"\n",
"copy",
"(",
"result",
",",
"args",
"[",
":",
"i",
"]",
")",
"\n",
"copy",
"(",
"result",
"[",
"i",
":",
"]",
",",
"args",
"[",
"i",
"+",
"1",
":",
"]",
")",
"\n",
"return",
"result",
",",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"args",
",",
"false",
"\n",
"}"
] | // extractMachineReadable checks the args for the machine readable
// flag and returns whether or not it is on. It modifies the args
// to remove this flag. | [
"extractMachineReadable",
"checks",
"the",
"args",
"for",
"the",
"machine",
"readable",
"flag",
"and",
"returns",
"whether",
"or",
"not",
"it",
"is",
"on",
".",
"It",
"modifies",
"the",
"args",
"to",
"remove",
"this",
"flag",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/main.go#L267-L279 |
165,154 | hashicorp/packer | builder/amazon/common/regions.go | ValidateRegion | func (c *AccessConfig) ValidateRegion(regions ...string) error {
ec2conn, err := c.NewEC2Connection()
if err != nil {
return err
}
validRegions, err := listEC2Regions(ec2conn)
if err != nil {
return err
}
var invalidRegions []string
for _, region := range regions {
if region == "" {
continue
}
found := false
for _, validRegion := range validRegions {
if region == validRegion {
found = true
break
}
}
if !found {
invalidRegions = append(invalidRegions, region)
}
}
if len(invalidRegions) > 0 {
return fmt.Errorf("Invalid region(s): %v, available regions: %v", invalidRegions, validRegions)
}
return nil
} | go | func (c *AccessConfig) ValidateRegion(regions ...string) error {
ec2conn, err := c.NewEC2Connection()
if err != nil {
return err
}
validRegions, err := listEC2Regions(ec2conn)
if err != nil {
return err
}
var invalidRegions []string
for _, region := range regions {
if region == "" {
continue
}
found := false
for _, validRegion := range validRegions {
if region == validRegion {
found = true
break
}
}
if !found {
invalidRegions = append(invalidRegions, region)
}
}
if len(invalidRegions) > 0 {
return fmt.Errorf("Invalid region(s): %v, available regions: %v", invalidRegions, validRegions)
}
return nil
} | [
"func",
"(",
"c",
"*",
"AccessConfig",
")",
"ValidateRegion",
"(",
"regions",
"...",
"string",
")",
"error",
"{",
"ec2conn",
",",
"err",
":=",
"c",
".",
"NewEC2Connection",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"validRegions",
",",
"err",
":=",
"listEC2Regions",
"(",
"ec2conn",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"var",
"invalidRegions",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"region",
":=",
"range",
"regions",
"{",
"if",
"region",
"==",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n",
"found",
":=",
"false",
"\n",
"for",
"_",
",",
"validRegion",
":=",
"range",
"validRegions",
"{",
"if",
"region",
"==",
"validRegion",
"{",
"found",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"found",
"{",
"invalidRegions",
"=",
"append",
"(",
"invalidRegions",
",",
"region",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"invalidRegions",
")",
">",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"invalidRegions",
",",
"validRegions",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // ValidateRegion returns an nil if the regions are valid
// and exists; otherwise an error.
// ValidateRegion calls ec2conn.DescribeRegions to get the list of
// regions available to this account. | [
"ValidateRegion",
"returns",
"an",
"nil",
"if",
"the",
"regions",
"are",
"valid",
"and",
"exists",
";",
"otherwise",
"an",
"error",
".",
"ValidateRegion",
"calls",
"ec2conn",
".",
"DescribeRegions",
"to",
"get",
"the",
"list",
"of",
"regions",
"available",
"to",
"this",
"account",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/amazon/common/regions.go#L26-L58 |
165,155 | hashicorp/packer | builder/parallels/common/driver_11.go | Verify | func (d *Parallels11Driver) Verify() error {
stdout, err := exec.Command(d.PrlsrvctlPath, "info", "--license").Output()
if err != nil {
return err
}
editionRe := regexp.MustCompile(`edition="(\w+)"`)
matches := editionRe.FindStringSubmatch(string(stdout))
if matches == nil {
return fmt.Errorf(
"Could not determine your Parallels Desktop edition using: %s info --license", d.PrlsrvctlPath)
}
switch matches[1] {
case "pro", "business":
break
default:
return fmt.Errorf("Packer can be used only with Parallels Desktop 11 Pro or Business edition. You use: %s edition", matches[1])
}
return nil
} | go | func (d *Parallels11Driver) Verify() error {
stdout, err := exec.Command(d.PrlsrvctlPath, "info", "--license").Output()
if err != nil {
return err
}
editionRe := regexp.MustCompile(`edition="(\w+)"`)
matches := editionRe.FindStringSubmatch(string(stdout))
if matches == nil {
return fmt.Errorf(
"Could not determine your Parallels Desktop edition using: %s info --license", d.PrlsrvctlPath)
}
switch matches[1] {
case "pro", "business":
break
default:
return fmt.Errorf("Packer can be used only with Parallels Desktop 11 Pro or Business edition. You use: %s edition", matches[1])
}
return nil
} | [
"func",
"(",
"d",
"*",
"Parallels11Driver",
")",
"Verify",
"(",
")",
"error",
"{",
"stdout",
",",
"err",
":=",
"exec",
".",
"Command",
"(",
"d",
".",
"PrlsrvctlPath",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
".",
"Output",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"editionRe",
":=",
"regexp",
".",
"MustCompile",
"(",
"`edition=\"(\\w+)\"`",
")",
"\n",
"matches",
":=",
"editionRe",
".",
"FindStringSubmatch",
"(",
"string",
"(",
"stdout",
")",
")",
"\n",
"if",
"matches",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"d",
".",
"PrlsrvctlPath",
")",
"\n",
"}",
"\n",
"switch",
"matches",
"[",
"1",
"]",
"{",
"case",
"\"",
"\"",
",",
"\"",
"\"",
":",
"break",
"\n",
"default",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"matches",
"[",
"1",
"]",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Verify raises an error if the builder could not be used on that host machine. | [
"Verify",
"raises",
"an",
"error",
"if",
"the",
"builder",
"could",
"not",
"be",
"used",
"on",
"that",
"host",
"machine",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/parallels/common/driver_11.go#L16-L37 |
165,156 | hashicorp/packer | builder/vmware/common/driver_workstation9_windows.go | workstationProgramFilePaths | func workstationProgramFilePaths() []string {
path, err := workstationVMwareRoot()
if err != nil {
log.Printf("Error finding VMware root: %s", err)
}
paths := make([]string, 0, 5)
if os.Getenv("VMWARE_HOME") != "" {
paths = append(paths, os.Getenv("VMWARE_HOME"))
}
if path != "" {
paths = append(paths, path)
}
if os.Getenv("ProgramFiles(x86)") != "" {
paths = append(paths,
filepath.Join(os.Getenv("ProgramFiles(x86)"), "/VMware/VMware Workstation"))
}
if os.Getenv("ProgramFiles") != "" {
paths = append(paths,
filepath.Join(os.Getenv("ProgramFiles"), "/VMware/VMware Workstation"))
}
return paths
} | go | func workstationProgramFilePaths() []string {
path, err := workstationVMwareRoot()
if err != nil {
log.Printf("Error finding VMware root: %s", err)
}
paths := make([]string, 0, 5)
if os.Getenv("VMWARE_HOME") != "" {
paths = append(paths, os.Getenv("VMWARE_HOME"))
}
if path != "" {
paths = append(paths, path)
}
if os.Getenv("ProgramFiles(x86)") != "" {
paths = append(paths,
filepath.Join(os.Getenv("ProgramFiles(x86)"), "/VMware/VMware Workstation"))
}
if os.Getenv("ProgramFiles") != "" {
paths = append(paths,
filepath.Join(os.Getenv("ProgramFiles"), "/VMware/VMware Workstation"))
}
return paths
} | [
"func",
"workstationProgramFilePaths",
"(",
")",
"[",
"]",
"string",
"{",
"path",
",",
"err",
":=",
"workstationVMwareRoot",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"paths",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"5",
")",
"\n",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"paths",
"=",
"append",
"(",
"paths",
",",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n\n",
"if",
"path",
"!=",
"\"",
"\"",
"{",
"paths",
"=",
"append",
"(",
"paths",
",",
"path",
")",
"\n",
"}",
"\n\n",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"paths",
"=",
"append",
"(",
"paths",
",",
"filepath",
".",
"Join",
"(",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n\n",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"paths",
"=",
"append",
"(",
"paths",
",",
"filepath",
".",
"Join",
"(",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n\n",
"return",
"paths",
"\n",
"}"
] | // workstationProgramFilesPaths returns a list of paths that are eligible
// to contain program files we may want just as vmware.exe. | [
"workstationProgramFilesPaths",
"returns",
"a",
"list",
"of",
"paths",
"that",
"are",
"eligible",
"to",
"contain",
"program",
"files",
"we",
"may",
"want",
"just",
"as",
"vmware",
".",
"exe",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/vmware/common/driver_workstation9_windows.go#L166-L192 |
165,157 | hashicorp/packer | builder/vmware/common/driver_workstation9_windows.go | workstationDataFilePaths | func workstationDataFilePaths() []string {
leasesPath, err := workstationDhcpLeasesPathRegistry()
if err != nil {
log.Printf("Error getting DHCP leases path: %s", err)
}
if leasesPath != "" {
leasesPath = filepath.Dir(leasesPath)
}
paths := make([]string, 0, 5)
if os.Getenv("VMWARE_DATA") != "" {
paths = append(paths, os.Getenv("VMWARE_DATA"))
}
if leasesPath != "" {
paths = append(paths, leasesPath)
}
if os.Getenv("ProgramData") != "" {
paths = append(paths,
filepath.Join(os.Getenv("ProgramData"), "/VMware"))
}
if os.Getenv("ALLUSERSPROFILE") != "" {
paths = append(paths,
filepath.Join(os.Getenv("ALLUSERSPROFILE"), "/Application Data/VMware"))
}
return paths
} | go | func workstationDataFilePaths() []string {
leasesPath, err := workstationDhcpLeasesPathRegistry()
if err != nil {
log.Printf("Error getting DHCP leases path: %s", err)
}
if leasesPath != "" {
leasesPath = filepath.Dir(leasesPath)
}
paths := make([]string, 0, 5)
if os.Getenv("VMWARE_DATA") != "" {
paths = append(paths, os.Getenv("VMWARE_DATA"))
}
if leasesPath != "" {
paths = append(paths, leasesPath)
}
if os.Getenv("ProgramData") != "" {
paths = append(paths,
filepath.Join(os.Getenv("ProgramData"), "/VMware"))
}
if os.Getenv("ALLUSERSPROFILE") != "" {
paths = append(paths,
filepath.Join(os.Getenv("ALLUSERSPROFILE"), "/Application Data/VMware"))
}
return paths
} | [
"func",
"workstationDataFilePaths",
"(",
")",
"[",
"]",
"string",
"{",
"leasesPath",
",",
"err",
":=",
"workstationDhcpLeasesPathRegistry",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"leasesPath",
"!=",
"\"",
"\"",
"{",
"leasesPath",
"=",
"filepath",
".",
"Dir",
"(",
"leasesPath",
")",
"\n",
"}",
"\n\n",
"paths",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"5",
")",
"\n",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"paths",
"=",
"append",
"(",
"paths",
",",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n\n",
"if",
"leasesPath",
"!=",
"\"",
"\"",
"{",
"paths",
"=",
"append",
"(",
"paths",
",",
"leasesPath",
")",
"\n",
"}",
"\n\n",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"paths",
"=",
"append",
"(",
"paths",
",",
"filepath",
".",
"Join",
"(",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n\n",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"paths",
"=",
"append",
"(",
"paths",
",",
"filepath",
".",
"Join",
"(",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n\n",
"return",
"paths",
"\n",
"}"
] | // workstationDataFilePaths returns a list of paths that are eligible
// to contain data files we may want such as vmnet NAT configuration files. | [
"workstationDataFilePaths",
"returns",
"a",
"list",
"of",
"paths",
"that",
"are",
"eligible",
"to",
"contain",
"data",
"files",
"we",
"may",
"want",
"such",
"as",
"vmnet",
"NAT",
"configuration",
"files",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/vmware/common/driver_workstation9_windows.go#L196-L226 |
165,158 | hashicorp/packer | builder/docker/ecr_login.go | EcrGetLogin | func (c *AwsAccessConfig) EcrGetLogin(ecrUrl string) (string, string, error) {
exp := regexp.MustCompile(`(?:http://|https://|)([0-9]*)\.dkr\.ecr\.(.*)\.amazonaws\.com.*`)
splitUrl := exp.FindStringSubmatch(ecrUrl)
if len(splitUrl) != 3 {
return "", "", fmt.Errorf("Failed to parse the ECR URL: %s it should be on the form <account number>.dkr.ecr.<region>.amazonaws.com", ecrUrl)
}
accountId := splitUrl[1]
region := splitUrl[2]
log.Println(fmt.Sprintf("Getting ECR token for account: %s in %s..", accountId, region))
c.cfg = &common.AccessConfig{
AccessKey: c.AccessKey,
ProfileName: c.Profile,
RawRegion: region,
SecretKey: c.SecretKey,
Token: c.Token,
}
session, err := c.cfg.Session()
if err != nil {
return "", "", fmt.Errorf("failed to create session: %s", err)
}
service := ecr.New(session)
params := &ecr.GetAuthorizationTokenInput{
RegistryIds: []*string{
aws.String(accountId),
},
}
resp, err := service.GetAuthorizationToken(params)
if err != nil {
return "", "", fmt.Errorf(err.Error())
}
auth, err := base64.StdEncoding.DecodeString(*resp.AuthorizationData[0].AuthorizationToken)
if err != nil {
return "", "", fmt.Errorf("Error decoding ECR AuthorizationToken: %s", err)
}
authParts := strings.SplitN(string(auth), ":", 2)
log.Printf("Successfully got login for ECR: %s", ecrUrl)
return authParts[0], authParts[1], nil
} | go | func (c *AwsAccessConfig) EcrGetLogin(ecrUrl string) (string, string, error) {
exp := regexp.MustCompile(`(?:http://|https://|)([0-9]*)\.dkr\.ecr\.(.*)\.amazonaws\.com.*`)
splitUrl := exp.FindStringSubmatch(ecrUrl)
if len(splitUrl) != 3 {
return "", "", fmt.Errorf("Failed to parse the ECR URL: %s it should be on the form <account number>.dkr.ecr.<region>.amazonaws.com", ecrUrl)
}
accountId := splitUrl[1]
region := splitUrl[2]
log.Println(fmt.Sprintf("Getting ECR token for account: %s in %s..", accountId, region))
c.cfg = &common.AccessConfig{
AccessKey: c.AccessKey,
ProfileName: c.Profile,
RawRegion: region,
SecretKey: c.SecretKey,
Token: c.Token,
}
session, err := c.cfg.Session()
if err != nil {
return "", "", fmt.Errorf("failed to create session: %s", err)
}
service := ecr.New(session)
params := &ecr.GetAuthorizationTokenInput{
RegistryIds: []*string{
aws.String(accountId),
},
}
resp, err := service.GetAuthorizationToken(params)
if err != nil {
return "", "", fmt.Errorf(err.Error())
}
auth, err := base64.StdEncoding.DecodeString(*resp.AuthorizationData[0].AuthorizationToken)
if err != nil {
return "", "", fmt.Errorf("Error decoding ECR AuthorizationToken: %s", err)
}
authParts := strings.SplitN(string(auth), ":", 2)
log.Printf("Successfully got login for ECR: %s", ecrUrl)
return authParts[0], authParts[1], nil
} | [
"func",
"(",
"c",
"*",
"AwsAccessConfig",
")",
"EcrGetLogin",
"(",
"ecrUrl",
"string",
")",
"(",
"string",
",",
"string",
",",
"error",
")",
"{",
"exp",
":=",
"regexp",
".",
"MustCompile",
"(",
"`(?:http://|https://|)([0-9]*)\\.dkr\\.ecr\\.(.*)\\.amazonaws\\.com.*`",
")",
"\n",
"splitUrl",
":=",
"exp",
".",
"FindStringSubmatch",
"(",
"ecrUrl",
")",
"\n",
"if",
"len",
"(",
"splitUrl",
")",
"!=",
"3",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"ecrUrl",
")",
"\n",
"}",
"\n",
"accountId",
":=",
"splitUrl",
"[",
"1",
"]",
"\n",
"region",
":=",
"splitUrl",
"[",
"2",
"]",
"\n\n",
"log",
".",
"Println",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"accountId",
",",
"region",
")",
")",
"\n\n",
"c",
".",
"cfg",
"=",
"&",
"common",
".",
"AccessConfig",
"{",
"AccessKey",
":",
"c",
".",
"AccessKey",
",",
"ProfileName",
":",
"c",
".",
"Profile",
",",
"RawRegion",
":",
"region",
",",
"SecretKey",
":",
"c",
".",
"SecretKey",
",",
"Token",
":",
"c",
".",
"Token",
",",
"}",
"\n\n",
"session",
",",
"err",
":=",
"c",
".",
"cfg",
".",
"Session",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"service",
":=",
"ecr",
".",
"New",
"(",
"session",
")",
"\n\n",
"params",
":=",
"&",
"ecr",
".",
"GetAuthorizationTokenInput",
"{",
"RegistryIds",
":",
"[",
"]",
"*",
"string",
"{",
"aws",
".",
"String",
"(",
"accountId",
")",
",",
"}",
",",
"}",
"\n",
"resp",
",",
"err",
":=",
"service",
".",
"GetAuthorizationToken",
"(",
"params",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n\n",
"auth",
",",
"err",
":=",
"base64",
".",
"StdEncoding",
".",
"DecodeString",
"(",
"*",
"resp",
".",
"AuthorizationData",
"[",
"0",
"]",
".",
"AuthorizationToken",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"authParts",
":=",
"strings",
".",
"SplitN",
"(",
"string",
"(",
"auth",
")",
",",
"\"",
"\"",
",",
"2",
")",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"ecrUrl",
")",
"\n\n",
"return",
"authParts",
"[",
"0",
"]",
",",
"authParts",
"[",
"1",
"]",
",",
"nil",
"\n",
"}"
] | // Get a login token for Amazon AWS ECR. Returns username and password
// or an error. | [
"Get",
"a",
"login",
"token",
"for",
"Amazon",
"AWS",
"ECR",
".",
"Returns",
"username",
"and",
"password",
"or",
"an",
"error",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/docker/ecr_login.go#L25-L71 |
165,159 | hashicorp/packer | builder/oracle/oci/config_provider.go | NewRawConfigurationProvider | func NewRawConfigurationProvider(tenancy, user, region, fingerprint, privateKey string, privateKeyPassphrase *string) common.ConfigurationProvider {
return rawConfigurationProvider{tenancy, user, region, fingerprint, privateKey, privateKeyPassphrase}
} | go | func NewRawConfigurationProvider(tenancy, user, region, fingerprint, privateKey string, privateKeyPassphrase *string) common.ConfigurationProvider {
return rawConfigurationProvider{tenancy, user, region, fingerprint, privateKey, privateKeyPassphrase}
} | [
"func",
"NewRawConfigurationProvider",
"(",
"tenancy",
",",
"user",
",",
"region",
",",
"fingerprint",
",",
"privateKey",
"string",
",",
"privateKeyPassphrase",
"*",
"string",
")",
"common",
".",
"ConfigurationProvider",
"{",
"return",
"rawConfigurationProvider",
"{",
"tenancy",
",",
"user",
",",
"region",
",",
"fingerprint",
",",
"privateKey",
",",
"privateKeyPassphrase",
"}",
"\n",
"}"
] | // NewRawConfigurationProvider will create a rawConfigurationProvider. | [
"NewRawConfigurationProvider",
"will",
"create",
"a",
"rawConfigurationProvider",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/oracle/oci/config_provider.go#L23-L25 |
165,160 | hashicorp/packer | builder/alicloud/ecs/access_config.go | Client | func (c *AlicloudAccessConfig) Client() (*ClientWrapper, error) {
if c.client != nil {
return c.client, nil
}
if c.SecurityToken == "" {
c.SecurityToken = os.Getenv("SECURITY_TOKEN")
}
client, err := ecs.NewClientWithStsToken(c.AlicloudRegion, c.AlicloudAccessKey,
c.AlicloudSecretKey, c.SecurityToken)
if err != nil {
return nil, err
}
client.AppendUserAgent(Packer, version.FormattedVersion())
client.SetReadTimeout(DefaultRequestReadTimeout)
c.client = &ClientWrapper{client}
return c.client, nil
} | go | func (c *AlicloudAccessConfig) Client() (*ClientWrapper, error) {
if c.client != nil {
return c.client, nil
}
if c.SecurityToken == "" {
c.SecurityToken = os.Getenv("SECURITY_TOKEN")
}
client, err := ecs.NewClientWithStsToken(c.AlicloudRegion, c.AlicloudAccessKey,
c.AlicloudSecretKey, c.SecurityToken)
if err != nil {
return nil, err
}
client.AppendUserAgent(Packer, version.FormattedVersion())
client.SetReadTimeout(DefaultRequestReadTimeout)
c.client = &ClientWrapper{client}
return c.client, nil
} | [
"func",
"(",
"c",
"*",
"AlicloudAccessConfig",
")",
"Client",
"(",
")",
"(",
"*",
"ClientWrapper",
",",
"error",
")",
"{",
"if",
"c",
".",
"client",
"!=",
"nil",
"{",
"return",
"c",
".",
"client",
",",
"nil",
"\n",
"}",
"\n",
"if",
"c",
".",
"SecurityToken",
"==",
"\"",
"\"",
"{",
"c",
".",
"SecurityToken",
"=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"client",
",",
"err",
":=",
"ecs",
".",
"NewClientWithStsToken",
"(",
"c",
".",
"AlicloudRegion",
",",
"c",
".",
"AlicloudAccessKey",
",",
"c",
".",
"AlicloudSecretKey",
",",
"c",
".",
"SecurityToken",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"client",
".",
"AppendUserAgent",
"(",
"Packer",
",",
"version",
".",
"FormattedVersion",
"(",
")",
")",
"\n",
"client",
".",
"SetReadTimeout",
"(",
"DefaultRequestReadTimeout",
")",
"\n",
"c",
".",
"client",
"=",
"&",
"ClientWrapper",
"{",
"client",
"}",
"\n\n",
"return",
"c",
".",
"client",
",",
"nil",
"\n",
"}"
] | // Client for AlicloudClient | [
"Client",
"for",
"AlicloudClient"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/alicloud/ecs/access_config.go#L28-L47 |
165,161 | hashicorp/packer | communicator/ssh/connect.go | ProxyConnectFunc | func ProxyConnectFunc(socksProxy string, socksAuth *proxy.Auth, network, addr string) func() (net.Conn, error) {
return func() (net.Conn, error) {
// create a socks5 dialer
dialer, err := proxy.SOCKS5("tcp", socksProxy, socksAuth, proxy.Direct)
if err != nil {
return nil, fmt.Errorf("Can't connect to the proxy: %s", err)
}
c, err := dialer.Dial(network, addr)
if err != nil {
return nil, err
}
return c, nil
}
} | go | func ProxyConnectFunc(socksProxy string, socksAuth *proxy.Auth, network, addr string) func() (net.Conn, error) {
return func() (net.Conn, error) {
// create a socks5 dialer
dialer, err := proxy.SOCKS5("tcp", socksProxy, socksAuth, proxy.Direct)
if err != nil {
return nil, fmt.Errorf("Can't connect to the proxy: %s", err)
}
c, err := dialer.Dial(network, addr)
if err != nil {
return nil, err
}
return c, nil
}
} | [
"func",
"ProxyConnectFunc",
"(",
"socksProxy",
"string",
",",
"socksAuth",
"*",
"proxy",
".",
"Auth",
",",
"network",
",",
"addr",
"string",
")",
"func",
"(",
")",
"(",
"net",
".",
"Conn",
",",
"error",
")",
"{",
"return",
"func",
"(",
")",
"(",
"net",
".",
"Conn",
",",
"error",
")",
"{",
"// create a socks5 dialer",
"dialer",
",",
"err",
":=",
"proxy",
".",
"SOCKS5",
"(",
"\"",
"\"",
",",
"socksProxy",
",",
"socksAuth",
",",
"proxy",
".",
"Direct",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"c",
",",
"err",
":=",
"dialer",
".",
"Dial",
"(",
"network",
",",
"addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"c",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // ProxyConnectFunc is a convenience method for returning a function
// that connects to a host using SOCKS5 proxy | [
"ProxyConnectFunc",
"is",
"a",
"convenience",
"method",
"for",
"returning",
"a",
"function",
"that",
"connects",
"to",
"a",
"host",
"using",
"SOCKS5",
"proxy"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/communicator/ssh/connect.go#L33-L48 |
165,162 | hashicorp/packer | common/net/configure_port.go | Listen | func (lc ListenRangeConfig) Listen(ctx context.Context) (*Listener, error) {
if lc.Network == "" {
lc.Network = "tcp"
}
portRange := lc.Max - lc.Min
var listener *Listener
err := retry.Config{
RetryDelay: func() time.Duration { return 1 * time.Millisecond },
}.Run(ctx, func(context.Context) error {
port := lc.Min
if portRange > 0 {
port += rand.Intn(portRange)
}
lockFilePath, err := packer.CachePath("port", strconv.Itoa(port))
if err != nil {
return err
}
lock := filelock.New(lockFilePath)
locked, err := lock.TryLock()
if err != nil {
return err
}
if !locked {
return ErrPortFileLocked(port)
}
l, err := lc.ListenConfig.Listen(ctx, lc.Network, fmt.Sprintf("%s:%d", lc.Addr, port))
if err != nil {
if err := lock.Unlock(); err != nil {
log.Fatalf("Could not unlock file lock for port %d: %v", port, err)
}
return &ErrPortBusy{
Port: port,
Err: err,
}
}
log.Printf("Found available port: %d on IP: %s", port, lc.Addr)
listener = &Listener{
Address: lc.Addr,
Port: port,
Listener: l,
lock: lock,
}
return nil
})
return listener, err
} | go | func (lc ListenRangeConfig) Listen(ctx context.Context) (*Listener, error) {
if lc.Network == "" {
lc.Network = "tcp"
}
portRange := lc.Max - lc.Min
var listener *Listener
err := retry.Config{
RetryDelay: func() time.Duration { return 1 * time.Millisecond },
}.Run(ctx, func(context.Context) error {
port := lc.Min
if portRange > 0 {
port += rand.Intn(portRange)
}
lockFilePath, err := packer.CachePath("port", strconv.Itoa(port))
if err != nil {
return err
}
lock := filelock.New(lockFilePath)
locked, err := lock.TryLock()
if err != nil {
return err
}
if !locked {
return ErrPortFileLocked(port)
}
l, err := lc.ListenConfig.Listen(ctx, lc.Network, fmt.Sprintf("%s:%d", lc.Addr, port))
if err != nil {
if err := lock.Unlock(); err != nil {
log.Fatalf("Could not unlock file lock for port %d: %v", port, err)
}
return &ErrPortBusy{
Port: port,
Err: err,
}
}
log.Printf("Found available port: %d on IP: %s", port, lc.Addr)
listener = &Listener{
Address: lc.Addr,
Port: port,
Listener: l,
lock: lock,
}
return nil
})
return listener, err
} | [
"func",
"(",
"lc",
"ListenRangeConfig",
")",
"Listen",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"*",
"Listener",
",",
"error",
")",
"{",
"if",
"lc",
".",
"Network",
"==",
"\"",
"\"",
"{",
"lc",
".",
"Network",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"portRange",
":=",
"lc",
".",
"Max",
"-",
"lc",
".",
"Min",
"\n\n",
"var",
"listener",
"*",
"Listener",
"\n\n",
"err",
":=",
"retry",
".",
"Config",
"{",
"RetryDelay",
":",
"func",
"(",
")",
"time",
".",
"Duration",
"{",
"return",
"1",
"*",
"time",
".",
"Millisecond",
"}",
",",
"}",
".",
"Run",
"(",
"ctx",
",",
"func",
"(",
"context",
".",
"Context",
")",
"error",
"{",
"port",
":=",
"lc",
".",
"Min",
"\n",
"if",
"portRange",
">",
"0",
"{",
"port",
"+=",
"rand",
".",
"Intn",
"(",
"portRange",
")",
"\n",
"}",
"\n\n",
"lockFilePath",
",",
"err",
":=",
"packer",
".",
"CachePath",
"(",
"\"",
"\"",
",",
"strconv",
".",
"Itoa",
"(",
"port",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"lock",
":=",
"filelock",
".",
"New",
"(",
"lockFilePath",
")",
"\n",
"locked",
",",
"err",
":=",
"lock",
".",
"TryLock",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"!",
"locked",
"{",
"return",
"ErrPortFileLocked",
"(",
"port",
")",
"\n",
"}",
"\n\n",
"l",
",",
"err",
":=",
"lc",
".",
"ListenConfig",
".",
"Listen",
"(",
"ctx",
",",
"lc",
".",
"Network",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"lc",
".",
"Addr",
",",
"port",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
":=",
"lock",
".",
"Unlock",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"port",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"&",
"ErrPortBusy",
"{",
"Port",
":",
"port",
",",
"Err",
":",
"err",
",",
"}",
"\n",
"}",
"\n\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"port",
",",
"lc",
".",
"Addr",
")",
"\n",
"listener",
"=",
"&",
"Listener",
"{",
"Address",
":",
"lc",
".",
"Addr",
",",
"Port",
":",
"port",
",",
"Listener",
":",
"l",
",",
"lock",
":",
"lock",
",",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"return",
"listener",
",",
"err",
"\n",
"}"
] | // Listen tries to Listen to a random open TCP port in the [min, max) range
// until ctx is cancelled.
// Listen uses net.ListenConfig.Listen internally. | [
"Listen",
"tries",
"to",
"Listen",
"to",
"a",
"random",
"open",
"TCP",
"port",
"in",
"the",
"[",
"min",
"max",
")",
"range",
"until",
"ctx",
"is",
"cancelled",
".",
"Listen",
"uses",
"net",
".",
"ListenConfig",
".",
"Listen",
"internally",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/common/net/configure_port.go#L54-L105 |
165,163 | hashicorp/packer | communicator/none/communicator.go | New | func New(config string) (result *comm, err error) {
// Establish an initial connection and connect
result = &comm{
config: config,
}
return
} | go | func New(config string) (result *comm, err error) {
// Establish an initial connection and connect
result = &comm{
config: config,
}
return
} | [
"func",
"New",
"(",
"config",
"string",
")",
"(",
"result",
"*",
"comm",
",",
"err",
"error",
")",
"{",
"// Establish an initial connection and connect",
"result",
"=",
"&",
"comm",
"{",
"config",
":",
"config",
",",
"}",
"\n\n",
"return",
"\n",
"}"
] | // Creates a null packer.Communicator implementation. This takes
// an already existing configuration. | [
"Creates",
"a",
"null",
"packer",
".",
"Communicator",
"implementation",
".",
"This",
"takes",
"an",
"already",
"existing",
"configuration",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/communicator/none/communicator.go#L18-L25 |
165,164 | hashicorp/packer | builder/azure/pkcs12/pkcs12.go | unmarshal | func unmarshal(in []byte, out interface{}) error {
trailing, err := asn1.Unmarshal(in, out)
if err != nil {
return err
}
if len(trailing) != 0 {
return errors.New("pkcs12: trailing data found")
}
return nil
} | go | func unmarshal(in []byte, out interface{}) error {
trailing, err := asn1.Unmarshal(in, out)
if err != nil {
return err
}
if len(trailing) != 0 {
return errors.New("pkcs12: trailing data found")
}
return nil
} | [
"func",
"unmarshal",
"(",
"in",
"[",
"]",
"byte",
",",
"out",
"interface",
"{",
"}",
")",
"error",
"{",
"trailing",
",",
"err",
":=",
"asn1",
".",
"Unmarshal",
"(",
"in",
",",
"out",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"trailing",
")",
"!=",
"0",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // unmarshal calls asn1.Unmarshal, but also returns an error if there is any
// trailing data after unmarshalling. | [
"unmarshal",
"calls",
"asn1",
".",
"Unmarshal",
"but",
"also",
"returns",
"an",
"error",
"if",
"there",
"is",
"any",
"trailing",
"data",
"after",
"unmarshalling",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/azure/pkcs12/pkcs12.go#L96-L105 |
165,165 | hashicorp/packer | builder/azure/pkcs12/pkcs12.go | Decode | func Decode(pfxData []byte, password string) (privateKey interface{}, certificate *x509.Certificate, err error) {
encodedPassword, err := bmpString(password)
if err != nil {
return nil, nil, err
}
bags, encodedPassword, err := getSafeContents(pfxData, encodedPassword)
if err != nil {
return nil, nil, err
}
if len(bags) != 2 {
err = errors.New("pkcs12: expected exactly two safe bags in the PFX PDU")
return
}
for _, bag := range bags {
switch {
case bag.Id.Equal(oidCertBag):
if certificate != nil {
err = errors.New("pkcs12: expected exactly one certificate bag")
}
certsData, err := decodeCertBag(bag.Value.Bytes)
if err != nil {
return nil, nil, err
}
certs, err := x509.ParseCertificates(certsData)
if err != nil {
return nil, nil, err
}
if len(certs) != 1 {
err = errors.New("pkcs12: expected exactly one certificate in the certBag")
return nil, nil, err
}
certificate = certs[0]
case bag.Id.Equal(oidPKCS8ShroudedKeyBag):
if privateKey != nil {
err = errors.New("pkcs12: expected exactly one key bag")
}
if privateKey, err = decodePkcs8ShroudedKeyBag(bag.Value.Bytes, encodedPassword); err != nil {
return nil, nil, err
}
}
}
if certificate == nil {
return nil, nil, errors.New("pkcs12: certificate missing")
}
if privateKey == nil {
return nil, nil, errors.New("pkcs12: private key missing")
}
return
} | go | func Decode(pfxData []byte, password string) (privateKey interface{}, certificate *x509.Certificate, err error) {
encodedPassword, err := bmpString(password)
if err != nil {
return nil, nil, err
}
bags, encodedPassword, err := getSafeContents(pfxData, encodedPassword)
if err != nil {
return nil, nil, err
}
if len(bags) != 2 {
err = errors.New("pkcs12: expected exactly two safe bags in the PFX PDU")
return
}
for _, bag := range bags {
switch {
case bag.Id.Equal(oidCertBag):
if certificate != nil {
err = errors.New("pkcs12: expected exactly one certificate bag")
}
certsData, err := decodeCertBag(bag.Value.Bytes)
if err != nil {
return nil, nil, err
}
certs, err := x509.ParseCertificates(certsData)
if err != nil {
return nil, nil, err
}
if len(certs) != 1 {
err = errors.New("pkcs12: expected exactly one certificate in the certBag")
return nil, nil, err
}
certificate = certs[0]
case bag.Id.Equal(oidPKCS8ShroudedKeyBag):
if privateKey != nil {
err = errors.New("pkcs12: expected exactly one key bag")
}
if privateKey, err = decodePkcs8ShroudedKeyBag(bag.Value.Bytes, encodedPassword); err != nil {
return nil, nil, err
}
}
}
if certificate == nil {
return nil, nil, errors.New("pkcs12: certificate missing")
}
if privateKey == nil {
return nil, nil, errors.New("pkcs12: private key missing")
}
return
} | [
"func",
"Decode",
"(",
"pfxData",
"[",
"]",
"byte",
",",
"password",
"string",
")",
"(",
"privateKey",
"interface",
"{",
"}",
",",
"certificate",
"*",
"x509",
".",
"Certificate",
",",
"err",
"error",
")",
"{",
"encodedPassword",
",",
"err",
":=",
"bmpString",
"(",
"password",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"bags",
",",
"encodedPassword",
",",
"err",
":=",
"getSafeContents",
"(",
"pfxData",
",",
"encodedPassword",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"bags",
")",
"!=",
"2",
"{",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"bag",
":=",
"range",
"bags",
"{",
"switch",
"{",
"case",
"bag",
".",
"Id",
".",
"Equal",
"(",
"oidCertBag",
")",
":",
"if",
"certificate",
"!=",
"nil",
"{",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"certsData",
",",
"err",
":=",
"decodeCertBag",
"(",
"bag",
".",
"Value",
".",
"Bytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"certs",
",",
"err",
":=",
"x509",
".",
"ParseCertificates",
"(",
"certsData",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"certs",
")",
"!=",
"1",
"{",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"certificate",
"=",
"certs",
"[",
"0",
"]",
"\n\n",
"case",
"bag",
".",
"Id",
".",
"Equal",
"(",
"oidPKCS8ShroudedKeyBag",
")",
":",
"if",
"privateKey",
"!=",
"nil",
"{",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"privateKey",
",",
"err",
"=",
"decodePkcs8ShroudedKeyBag",
"(",
"bag",
".",
"Value",
".",
"Bytes",
",",
"encodedPassword",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"certificate",
"==",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"privateKey",
"==",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // Decode extracts a certificate and private key from pfxData. This function
// assumes that there is only one certificate and only one private key in the
// pfxData. | [
"Decode",
"extracts",
"a",
"certificate",
"and",
"private",
"key",
"from",
"pfxData",
".",
"This",
"function",
"assumes",
"that",
"there",
"is",
"only",
"one",
"certificate",
"and",
"only",
"one",
"private",
"key",
"in",
"the",
"pfxData",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/azure/pkcs12/pkcs12.go#L212-L267 |
165,166 | hashicorp/packer | config.go | decodeConfig | func decodeConfig(r io.Reader, c *config) error {
decoder := json.NewDecoder(r)
return decoder.Decode(c)
} | go | func decodeConfig(r io.Reader, c *config) error {
decoder := json.NewDecoder(r)
return decoder.Decode(c)
} | [
"func",
"decodeConfig",
"(",
"r",
"io",
".",
"Reader",
",",
"c",
"*",
"config",
")",
"error",
"{",
"decoder",
":=",
"json",
".",
"NewDecoder",
"(",
"r",
")",
"\n",
"return",
"decoder",
".",
"Decode",
"(",
"c",
")",
"\n",
"}"
] | // Decodes configuration in JSON format from the given io.Reader into
// the config object pointed to. | [
"Decodes",
"configuration",
"in",
"JSON",
"format",
"from",
"the",
"given",
"io",
".",
"Reader",
"into",
"the",
"config",
"object",
"pointed",
"to",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/config.go#L37-L40 |
165,167 | hashicorp/packer | config.go | Discover | func (c *config) Discover() error {
// If we are already inside a plugin process we should not need to
// discover anything.
if os.Getenv(plugin.MagicCookieKey) == plugin.MagicCookieValue {
return nil
}
// First, look in the same directory as the executable.
exePath, err := osext.Executable()
if err != nil {
log.Printf("[ERR] Error loading exe directory: %s", err)
} else {
if err := c.discover(filepath.Dir(exePath)); err != nil {
return err
}
}
// Next, look in the plugins directory.
dir, err := packer.ConfigDir()
if err != nil {
log.Printf("[ERR] Error loading config directory: %s", err)
} else {
if err := c.discover(filepath.Join(dir, "plugins")); err != nil {
return err
}
}
// Next, look in the CWD.
if err := c.discover("."); err != nil {
return err
}
// Finally, try to use an internal plugin. Note that this will not override
// any previously-loaded plugins.
if err := c.discoverInternal(); err != nil {
return err
}
return nil
} | go | func (c *config) Discover() error {
// If we are already inside a plugin process we should not need to
// discover anything.
if os.Getenv(plugin.MagicCookieKey) == plugin.MagicCookieValue {
return nil
}
// First, look in the same directory as the executable.
exePath, err := osext.Executable()
if err != nil {
log.Printf("[ERR] Error loading exe directory: %s", err)
} else {
if err := c.discover(filepath.Dir(exePath)); err != nil {
return err
}
}
// Next, look in the plugins directory.
dir, err := packer.ConfigDir()
if err != nil {
log.Printf("[ERR] Error loading config directory: %s", err)
} else {
if err := c.discover(filepath.Join(dir, "plugins")); err != nil {
return err
}
}
// Next, look in the CWD.
if err := c.discover("."); err != nil {
return err
}
// Finally, try to use an internal plugin. Note that this will not override
// any previously-loaded plugins.
if err := c.discoverInternal(); err != nil {
return err
}
return nil
} | [
"func",
"(",
"c",
"*",
"config",
")",
"Discover",
"(",
")",
"error",
"{",
"// If we are already inside a plugin process we should not need to",
"// discover anything.",
"if",
"os",
".",
"Getenv",
"(",
"plugin",
".",
"MagicCookieKey",
")",
"==",
"plugin",
".",
"MagicCookieValue",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// First, look in the same directory as the executable.",
"exePath",
",",
"err",
":=",
"osext",
".",
"Executable",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"if",
"err",
":=",
"c",
".",
"discover",
"(",
"filepath",
".",
"Dir",
"(",
"exePath",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Next, look in the plugins directory.",
"dir",
",",
"err",
":=",
"packer",
".",
"ConfigDir",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"if",
"err",
":=",
"c",
".",
"discover",
"(",
"filepath",
".",
"Join",
"(",
"dir",
",",
"\"",
"\"",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Next, look in the CWD.",
"if",
"err",
":=",
"c",
".",
"discover",
"(",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Finally, try to use an internal plugin. Note that this will not override",
"// any previously-loaded plugins.",
"if",
"err",
":=",
"c",
".",
"discoverInternal",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Discover discovers plugins.
//
// Search the directory of the executable, then the plugins directory, and
// finally the CWD, in that order. Any conflicts will overwrite previously
// found plugins, in that order.
// Hence, the priority order is the reverse of the search order - i.e., the
// CWD has the highest priority. | [
"Discover",
"discovers",
"plugins",
".",
"Search",
"the",
"directory",
"of",
"the",
"executable",
"then",
"the",
"plugins",
"directory",
"and",
"finally",
"the",
"CWD",
"in",
"that",
"order",
".",
"Any",
"conflicts",
"will",
"overwrite",
"previously",
"found",
"plugins",
"in",
"that",
"order",
".",
"Hence",
"the",
"priority",
"order",
"is",
"the",
"reverse",
"of",
"the",
"search",
"order",
"-",
"i",
".",
"e",
".",
"the",
"CWD",
"has",
"the",
"highest",
"priority",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/config.go#L49-L88 |
165,168 | hashicorp/packer | config.go | LoadBuilder | func (c *config) LoadBuilder(name string) (packer.Builder, error) {
log.Printf("Loading builder: %s\n", name)
bin, ok := c.Builders[name]
if !ok {
log.Printf("Builder not found: %s\n", name)
return nil, nil
}
return c.pluginClient(bin).Builder()
} | go | func (c *config) LoadBuilder(name string) (packer.Builder, error) {
log.Printf("Loading builder: %s\n", name)
bin, ok := c.Builders[name]
if !ok {
log.Printf("Builder not found: %s\n", name)
return nil, nil
}
return c.pluginClient(bin).Builder()
} | [
"func",
"(",
"c",
"*",
"config",
")",
"LoadBuilder",
"(",
"name",
"string",
")",
"(",
"packer",
".",
"Builder",
",",
"error",
")",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"name",
")",
"\n",
"bin",
",",
"ok",
":=",
"c",
".",
"Builders",
"[",
"name",
"]",
"\n",
"if",
"!",
"ok",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"name",
")",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"c",
".",
"pluginClient",
"(",
"bin",
")",
".",
"Builder",
"(",
")",
"\n",
"}"
] | // This is a proper packer.BuilderFunc that can be used to load packer.Builder
// implementations from the defined plugins. | [
"This",
"is",
"a",
"proper",
"packer",
".",
"BuilderFunc",
"that",
"can",
"be",
"used",
"to",
"load",
"packer",
".",
"Builder",
"implementations",
"from",
"the",
"defined",
"plugins",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/config.go#L92-L101 |
165,169 | hashicorp/packer | config.go | LoadHook | func (c *config) LoadHook(name string) (packer.Hook, error) {
log.Printf("Loading hook: %s\n", name)
return c.pluginClient(name).Hook()
} | go | func (c *config) LoadHook(name string) (packer.Hook, error) {
log.Printf("Loading hook: %s\n", name)
return c.pluginClient(name).Hook()
} | [
"func",
"(",
"c",
"*",
"config",
")",
"LoadHook",
"(",
"name",
"string",
")",
"(",
"packer",
".",
"Hook",
",",
"error",
")",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"name",
")",
"\n",
"return",
"c",
".",
"pluginClient",
"(",
"name",
")",
".",
"Hook",
"(",
")",
"\n",
"}"
] | // This is a proper implementation of packer.HookFunc that can be used
// to load packer.Hook implementations from the defined plugins. | [
"This",
"is",
"a",
"proper",
"implementation",
"of",
"packer",
".",
"HookFunc",
"that",
"can",
"be",
"used",
"to",
"load",
"packer",
".",
"Hook",
"implementations",
"from",
"the",
"defined",
"plugins",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/config.go#L105-L108 |
165,170 | hashicorp/packer | config.go | LoadPostProcessor | func (c *config) LoadPostProcessor(name string) (packer.PostProcessor, error) {
log.Printf("Loading post-processor: %s", name)
bin, ok := c.PostProcessors[name]
if !ok {
log.Printf("Post-processor not found: %s", name)
return nil, nil
}
return c.pluginClient(bin).PostProcessor()
} | go | func (c *config) LoadPostProcessor(name string) (packer.PostProcessor, error) {
log.Printf("Loading post-processor: %s", name)
bin, ok := c.PostProcessors[name]
if !ok {
log.Printf("Post-processor not found: %s", name)
return nil, nil
}
return c.pluginClient(bin).PostProcessor()
} | [
"func",
"(",
"c",
"*",
"config",
")",
"LoadPostProcessor",
"(",
"name",
"string",
")",
"(",
"packer",
".",
"PostProcessor",
",",
"error",
")",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"bin",
",",
"ok",
":=",
"c",
".",
"PostProcessors",
"[",
"name",
"]",
"\n",
"if",
"!",
"ok",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"c",
".",
"pluginClient",
"(",
"bin",
")",
".",
"PostProcessor",
"(",
")",
"\n",
"}"
] | // This is a proper packer.PostProcessorFunc that can be used to load
// packer.PostProcessor implementations from defined plugins. | [
"This",
"is",
"a",
"proper",
"packer",
".",
"PostProcessorFunc",
"that",
"can",
"be",
"used",
"to",
"load",
"packer",
".",
"PostProcessor",
"implementations",
"from",
"defined",
"plugins",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/config.go#L112-L121 |
165,171 | hashicorp/packer | config.go | LoadProvisioner | func (c *config) LoadProvisioner(name string) (packer.Provisioner, error) {
log.Printf("Loading provisioner: %s\n", name)
bin, ok := c.Provisioners[name]
if !ok {
log.Printf("Provisioner not found: %s\n", name)
return nil, nil
}
return c.pluginClient(bin).Provisioner()
} | go | func (c *config) LoadProvisioner(name string) (packer.Provisioner, error) {
log.Printf("Loading provisioner: %s\n", name)
bin, ok := c.Provisioners[name]
if !ok {
log.Printf("Provisioner not found: %s\n", name)
return nil, nil
}
return c.pluginClient(bin).Provisioner()
} | [
"func",
"(",
"c",
"*",
"config",
")",
"LoadProvisioner",
"(",
"name",
"string",
")",
"(",
"packer",
".",
"Provisioner",
",",
"error",
")",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"name",
")",
"\n",
"bin",
",",
"ok",
":=",
"c",
".",
"Provisioners",
"[",
"name",
"]",
"\n",
"if",
"!",
"ok",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"name",
")",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"c",
".",
"pluginClient",
"(",
"bin",
")",
".",
"Provisioner",
"(",
")",
"\n",
"}"
] | // This is a proper packer.ProvisionerFunc that can be used to load
// packer.Provisioner implementations from defined plugins. | [
"This",
"is",
"a",
"proper",
"packer",
".",
"ProvisionerFunc",
"that",
"can",
"be",
"used",
"to",
"load",
"packer",
".",
"Provisioner",
"implementations",
"from",
"defined",
"plugins",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/config.go#L125-L134 |
165,172 | hashicorp/packer | builder/googlecompute/builder.go | Run | func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (packer.Artifact, error) {
driver, err := NewDriverGCE(
ui, b.config.ProjectId, &b.config.Account)
if err != nil {
return nil, err
}
// Set up the state.
state := new(multistep.BasicStateBag)
state.Put("config", b.config)
state.Put("driver", driver)
state.Put("hook", hook)
state.Put("ui", ui)
// Build the steps.
steps := []multistep.Step{
new(StepCheckExistingImage),
&StepCreateSSHKey{
Debug: b.config.PackerDebug,
DebugKeyPath: fmt.Sprintf("gce_%s.pem", b.config.PackerBuildName),
},
&StepCreateInstance{
Debug: b.config.PackerDebug,
},
&StepCreateWindowsPassword{
Debug: b.config.PackerDebug,
DebugKeyPath: fmt.Sprintf("gce_windows_%s.pem", b.config.PackerBuildName),
},
&StepInstanceInfo{
Debug: b.config.PackerDebug,
},
&communicator.StepConnect{
Config: &b.config.Comm,
Host: commHost,
SSHConfig: b.config.Comm.SSHConfigFunc(),
WinRMConfig: winrmConfig,
},
new(common.StepProvision),
&common.StepCleanupTempKeys{
Comm: &b.config.Comm,
},
}
if _, exists := b.config.Metadata[StartupScriptKey]; exists || b.config.StartupScriptFile != "" {
steps = append(steps, new(StepWaitStartupScript))
}
steps = append(steps, new(StepTeardownInstance), new(StepCreateImage))
// Run the steps.
b.runner = common.NewRunner(steps, b.config.PackerConfig, ui)
b.runner.Run(ctx, state)
// Report any errors.
if rawErr, ok := state.GetOk("error"); ok {
return nil, rawErr.(error)
}
if _, ok := state.GetOk("image"); !ok {
log.Println("Failed to find image in state. Bug?")
return nil, nil
}
artifact := &Artifact{
image: state.Get("image").(*Image),
driver: driver,
config: b.config,
}
return artifact, nil
} | go | func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (packer.Artifact, error) {
driver, err := NewDriverGCE(
ui, b.config.ProjectId, &b.config.Account)
if err != nil {
return nil, err
}
// Set up the state.
state := new(multistep.BasicStateBag)
state.Put("config", b.config)
state.Put("driver", driver)
state.Put("hook", hook)
state.Put("ui", ui)
// Build the steps.
steps := []multistep.Step{
new(StepCheckExistingImage),
&StepCreateSSHKey{
Debug: b.config.PackerDebug,
DebugKeyPath: fmt.Sprintf("gce_%s.pem", b.config.PackerBuildName),
},
&StepCreateInstance{
Debug: b.config.PackerDebug,
},
&StepCreateWindowsPassword{
Debug: b.config.PackerDebug,
DebugKeyPath: fmt.Sprintf("gce_windows_%s.pem", b.config.PackerBuildName),
},
&StepInstanceInfo{
Debug: b.config.PackerDebug,
},
&communicator.StepConnect{
Config: &b.config.Comm,
Host: commHost,
SSHConfig: b.config.Comm.SSHConfigFunc(),
WinRMConfig: winrmConfig,
},
new(common.StepProvision),
&common.StepCleanupTempKeys{
Comm: &b.config.Comm,
},
}
if _, exists := b.config.Metadata[StartupScriptKey]; exists || b.config.StartupScriptFile != "" {
steps = append(steps, new(StepWaitStartupScript))
}
steps = append(steps, new(StepTeardownInstance), new(StepCreateImage))
// Run the steps.
b.runner = common.NewRunner(steps, b.config.PackerConfig, ui)
b.runner.Run(ctx, state)
// Report any errors.
if rawErr, ok := state.GetOk("error"); ok {
return nil, rawErr.(error)
}
if _, ok := state.GetOk("image"); !ok {
log.Println("Failed to find image in state. Bug?")
return nil, nil
}
artifact := &Artifact{
image: state.Get("image").(*Image),
driver: driver,
config: b.config,
}
return artifact, nil
} | [
"func",
"(",
"b",
"*",
"Builder",
")",
"Run",
"(",
"ctx",
"context",
".",
"Context",
",",
"ui",
"packer",
".",
"Ui",
",",
"hook",
"packer",
".",
"Hook",
")",
"(",
"packer",
".",
"Artifact",
",",
"error",
")",
"{",
"driver",
",",
"err",
":=",
"NewDriverGCE",
"(",
"ui",
",",
"b",
".",
"config",
".",
"ProjectId",
",",
"&",
"b",
".",
"config",
".",
"Account",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Set up the state.",
"state",
":=",
"new",
"(",
"multistep",
".",
"BasicStateBag",
")",
"\n",
"state",
".",
"Put",
"(",
"\"",
"\"",
",",
"b",
".",
"config",
")",
"\n",
"state",
".",
"Put",
"(",
"\"",
"\"",
",",
"driver",
")",
"\n",
"state",
".",
"Put",
"(",
"\"",
"\"",
",",
"hook",
")",
"\n",
"state",
".",
"Put",
"(",
"\"",
"\"",
",",
"ui",
")",
"\n\n",
"// Build the steps.",
"steps",
":=",
"[",
"]",
"multistep",
".",
"Step",
"{",
"new",
"(",
"StepCheckExistingImage",
")",
",",
"&",
"StepCreateSSHKey",
"{",
"Debug",
":",
"b",
".",
"config",
".",
"PackerDebug",
",",
"DebugKeyPath",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"b",
".",
"config",
".",
"PackerBuildName",
")",
",",
"}",
",",
"&",
"StepCreateInstance",
"{",
"Debug",
":",
"b",
".",
"config",
".",
"PackerDebug",
",",
"}",
",",
"&",
"StepCreateWindowsPassword",
"{",
"Debug",
":",
"b",
".",
"config",
".",
"PackerDebug",
",",
"DebugKeyPath",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"b",
".",
"config",
".",
"PackerBuildName",
")",
",",
"}",
",",
"&",
"StepInstanceInfo",
"{",
"Debug",
":",
"b",
".",
"config",
".",
"PackerDebug",
",",
"}",
",",
"&",
"communicator",
".",
"StepConnect",
"{",
"Config",
":",
"&",
"b",
".",
"config",
".",
"Comm",
",",
"Host",
":",
"commHost",
",",
"SSHConfig",
":",
"b",
".",
"config",
".",
"Comm",
".",
"SSHConfigFunc",
"(",
")",
",",
"WinRMConfig",
":",
"winrmConfig",
",",
"}",
",",
"new",
"(",
"common",
".",
"StepProvision",
")",
",",
"&",
"common",
".",
"StepCleanupTempKeys",
"{",
"Comm",
":",
"&",
"b",
".",
"config",
".",
"Comm",
",",
"}",
",",
"}",
"\n",
"if",
"_",
",",
"exists",
":=",
"b",
".",
"config",
".",
"Metadata",
"[",
"StartupScriptKey",
"]",
";",
"exists",
"||",
"b",
".",
"config",
".",
"StartupScriptFile",
"!=",
"\"",
"\"",
"{",
"steps",
"=",
"append",
"(",
"steps",
",",
"new",
"(",
"StepWaitStartupScript",
")",
")",
"\n",
"}",
"\n",
"steps",
"=",
"append",
"(",
"steps",
",",
"new",
"(",
"StepTeardownInstance",
")",
",",
"new",
"(",
"StepCreateImage",
")",
")",
"\n\n",
"// Run the steps.",
"b",
".",
"runner",
"=",
"common",
".",
"NewRunner",
"(",
"steps",
",",
"b",
".",
"config",
".",
"PackerConfig",
",",
"ui",
")",
"\n",
"b",
".",
"runner",
".",
"Run",
"(",
"ctx",
",",
"state",
")",
"\n\n",
"// Report any errors.",
"if",
"rawErr",
",",
"ok",
":=",
"state",
".",
"GetOk",
"(",
"\"",
"\"",
")",
";",
"ok",
"{",
"return",
"nil",
",",
"rawErr",
".",
"(",
"error",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"state",
".",
"GetOk",
"(",
"\"",
"\"",
")",
";",
"!",
"ok",
"{",
"log",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"artifact",
":=",
"&",
"Artifact",
"{",
"image",
":",
"state",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"*",
"Image",
")",
",",
"driver",
":",
"driver",
",",
"config",
":",
"b",
".",
"config",
",",
"}",
"\n",
"return",
"artifact",
",",
"nil",
"\n",
"}"
] | // Run executes a googlecompute Packer build and returns a packer.Artifact
// representing a GCE machine image. | [
"Run",
"executes",
"a",
"googlecompute",
"Packer",
"build",
"and",
"returns",
"a",
"packer",
".",
"Artifact",
"representing",
"a",
"GCE",
"machine",
"image",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/googlecompute/builder.go#L37-L103 |
165,173 | hashicorp/packer | builder/googlecompute/artifact.go | Destroy | func (a *Artifact) Destroy() error {
log.Printf("Destroying image: %s", a.image.Name)
errCh := a.driver.DeleteImage(a.image.Name)
return <-errCh
} | go | func (a *Artifact) Destroy() error {
log.Printf("Destroying image: %s", a.image.Name)
errCh := a.driver.DeleteImage(a.image.Name)
return <-errCh
} | [
"func",
"(",
"a",
"*",
"Artifact",
")",
"Destroy",
"(",
")",
"error",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"a",
".",
"image",
".",
"Name",
")",
"\n",
"errCh",
":=",
"a",
".",
"driver",
".",
"DeleteImage",
"(",
"a",
".",
"image",
".",
"Name",
")",
"\n",
"return",
"<-",
"errCh",
"\n",
"}"
] | // Destroy destroys the GCE image represented by the artifact. | [
"Destroy",
"destroys",
"the",
"GCE",
"image",
"represented",
"by",
"the",
"artifact",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/googlecompute/artifact.go#L21-L25 |
165,174 | hashicorp/packer | builder/amazon/chroot/device.go | AvailableDevice | func AvailableDevice() (string, error) {
prefix, err := devicePrefix()
if err != nil {
return "", err
}
letters := "fghijklmnop"
for _, letter := range letters {
device := fmt.Sprintf("/dev/%s%c", prefix, letter)
// If the block device itself, i.e. /dev/sf, exists, then we
// can't use any of the numbers either.
if _, err := os.Stat(device); err == nil {
continue
}
// To be able to build both Paravirtual and HVM images, the unnumbered
// device and the first numbered one must be available.
// E.g. /dev/xvdf and /dev/xvdf1
numbered_device := fmt.Sprintf("%s%d", device, 1)
if _, err := os.Stat(numbered_device); err != nil {
return device, nil
}
}
return "", errors.New("available device could not be found")
} | go | func AvailableDevice() (string, error) {
prefix, err := devicePrefix()
if err != nil {
return "", err
}
letters := "fghijklmnop"
for _, letter := range letters {
device := fmt.Sprintf("/dev/%s%c", prefix, letter)
// If the block device itself, i.e. /dev/sf, exists, then we
// can't use any of the numbers either.
if _, err := os.Stat(device); err == nil {
continue
}
// To be able to build both Paravirtual and HVM images, the unnumbered
// device and the first numbered one must be available.
// E.g. /dev/xvdf and /dev/xvdf1
numbered_device := fmt.Sprintf("%s%d", device, 1)
if _, err := os.Stat(numbered_device); err != nil {
return device, nil
}
}
return "", errors.New("available device could not be found")
} | [
"func",
"AvailableDevice",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"prefix",
",",
"err",
":=",
"devicePrefix",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"letters",
":=",
"\"",
"\"",
"\n",
"for",
"_",
",",
"letter",
":=",
"range",
"letters",
"{",
"device",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"prefix",
",",
"letter",
")",
"\n\n",
"// If the block device itself, i.e. /dev/sf, exists, then we",
"// can't use any of the numbers either.",
"if",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"device",
")",
";",
"err",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"\n\n",
"// To be able to build both Paravirtual and HVM images, the unnumbered",
"// device and the first numbered one must be available.",
"// E.g. /dev/xvdf and /dev/xvdf1",
"numbered_device",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"device",
",",
"1",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"numbered_device",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"device",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"\"",
"\"",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // AvailableDevice finds an available device and returns it. Note that
// you should externally hold a flock or something in order to guarantee
// that this device is available across processes. | [
"AvailableDevice",
"finds",
"an",
"available",
"device",
"and",
"returns",
"it",
".",
"Note",
"that",
"you",
"should",
"externally",
"hold",
"a",
"flock",
"or",
"something",
"in",
"order",
"to",
"guarantee",
"that",
"this",
"device",
"is",
"available",
"across",
"processes",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/amazon/chroot/device.go#L14-L40 |
165,175 | hashicorp/packer | post-processor/vagrant/virtualbox.go | DecompressOva | func DecompressOva(dir, src string) error {
log.Printf("Turning ova to dir: %s => %s", src, dir)
srcF, err := os.Open(src)
if err != nil {
return err
}
defer srcF.Close()
tarReader := tar.NewReader(srcF)
for {
hdr, err := tarReader.Next()
if hdr == nil || err == io.EOF {
break
}
if err != nil {
return err
}
// We use the fileinfo to get the file name because we are not
// expecting path information as from the tar header. It's important
// that we not use the path name from the tar header without checking
// for the presence of `..`. If we accidentally allow for that, we can
// open ourselves up to a path traversal vulnerability.
info := hdr.FileInfo()
// Shouldn't be any directories, skip them
if info.IsDir() {
continue
}
// We wrap this in an anonymous function so that the defers
// inside are handled more quickly so we can give up file handles.
err = func() error {
path := filepath.Join(dir, info.Name())
output, err := os.Create(path)
if err != nil {
return err
}
defer output.Close()
os.Chmod(path, info.Mode())
os.Chtimes(path, hdr.AccessTime, hdr.ModTime)
_, err = io.Copy(output, tarReader)
return err
}()
if err != nil {
return err
}
}
return nil
} | go | func DecompressOva(dir, src string) error {
log.Printf("Turning ova to dir: %s => %s", src, dir)
srcF, err := os.Open(src)
if err != nil {
return err
}
defer srcF.Close()
tarReader := tar.NewReader(srcF)
for {
hdr, err := tarReader.Next()
if hdr == nil || err == io.EOF {
break
}
if err != nil {
return err
}
// We use the fileinfo to get the file name because we are not
// expecting path information as from the tar header. It's important
// that we not use the path name from the tar header without checking
// for the presence of `..`. If we accidentally allow for that, we can
// open ourselves up to a path traversal vulnerability.
info := hdr.FileInfo()
// Shouldn't be any directories, skip them
if info.IsDir() {
continue
}
// We wrap this in an anonymous function so that the defers
// inside are handled more quickly so we can give up file handles.
err = func() error {
path := filepath.Join(dir, info.Name())
output, err := os.Create(path)
if err != nil {
return err
}
defer output.Close()
os.Chmod(path, info.Mode())
os.Chtimes(path, hdr.AccessTime, hdr.ModTime)
_, err = io.Copy(output, tarReader)
return err
}()
if err != nil {
return err
}
}
return nil
} | [
"func",
"DecompressOva",
"(",
"dir",
",",
"src",
"string",
")",
"error",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"src",
",",
"dir",
")",
"\n",
"srcF",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"src",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"srcF",
".",
"Close",
"(",
")",
"\n\n",
"tarReader",
":=",
"tar",
".",
"NewReader",
"(",
"srcF",
")",
"\n",
"for",
"{",
"hdr",
",",
"err",
":=",
"tarReader",
".",
"Next",
"(",
")",
"\n",
"if",
"hdr",
"==",
"nil",
"||",
"err",
"==",
"io",
".",
"EOF",
"{",
"break",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// We use the fileinfo to get the file name because we are not",
"// expecting path information as from the tar header. It's important",
"// that we not use the path name from the tar header without checking",
"// for the presence of `..`. If we accidentally allow for that, we can",
"// open ourselves up to a path traversal vulnerability.",
"info",
":=",
"hdr",
".",
"FileInfo",
"(",
")",
"\n\n",
"// Shouldn't be any directories, skip them",
"if",
"info",
".",
"IsDir",
"(",
")",
"{",
"continue",
"\n",
"}",
"\n\n",
"// We wrap this in an anonymous function so that the defers",
"// inside are handled more quickly so we can give up file handles.",
"err",
"=",
"func",
"(",
")",
"error",
"{",
"path",
":=",
"filepath",
".",
"Join",
"(",
"dir",
",",
"info",
".",
"Name",
"(",
")",
")",
"\n",
"output",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"output",
".",
"Close",
"(",
")",
"\n\n",
"os",
".",
"Chmod",
"(",
"path",
",",
"info",
".",
"Mode",
"(",
")",
")",
"\n",
"os",
".",
"Chtimes",
"(",
"path",
",",
"hdr",
".",
"AccessTime",
",",
"hdr",
".",
"ModTime",
")",
"\n",
"_",
",",
"err",
"=",
"io",
".",
"Copy",
"(",
"output",
",",
"tarReader",
")",
"\n",
"return",
"err",
"\n",
"}",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // DecompressOva takes an ova file and decompresses it into the target
// directory. | [
"DecompressOva",
"takes",
"an",
"ova",
"file",
"and",
"decompresses",
"it",
"into",
"the",
"target",
"directory",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/post-processor/vagrant/virtualbox.go#L122-L173 |
165,176 | hashicorp/packer | helper/common/shared_state.go | sharedStateFilename | func sharedStateFilename(suffix string, buildName string) string {
uuid := os.Getenv("PACKER_RUN_UUID")
return filepath.Join(os.TempDir(), fmt.Sprintf("packer-%s-%s-%s", uuid, suffix, buildName))
} | go | func sharedStateFilename(suffix string, buildName string) string {
uuid := os.Getenv("PACKER_RUN_UUID")
return filepath.Join(os.TempDir(), fmt.Sprintf("packer-%s-%s-%s", uuid, suffix, buildName))
} | [
"func",
"sharedStateFilename",
"(",
"suffix",
"string",
",",
"buildName",
"string",
")",
"string",
"{",
"uuid",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\n",
"return",
"filepath",
".",
"Join",
"(",
"os",
".",
"TempDir",
"(",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"uuid",
",",
"suffix",
",",
"buildName",
")",
")",
"\n",
"}"
] | // Used to set variables which we need to access later in the build, where
// state bag and config information won't work | [
"Used",
"to",
"set",
"variables",
"which",
"we",
"need",
"to",
"access",
"later",
"in",
"the",
"build",
"where",
"state",
"bag",
"and",
"config",
"information",
"won",
"t",
"work"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/helper/common/shared_state.go#L12-L15 |
165,177 | hashicorp/packer | builder/parallels/common/ssh_config.go | Prepare | func (c *SSHConfig) Prepare(ctx *interpolate.Context) []error {
// TODO: backwards compatibility, write fixer instead
if c.SSHWaitTimeout != 0 {
c.Comm.SSHTimeout = c.SSHWaitTimeout
}
return c.Comm.Prepare(ctx)
} | go | func (c *SSHConfig) Prepare(ctx *interpolate.Context) []error {
// TODO: backwards compatibility, write fixer instead
if c.SSHWaitTimeout != 0 {
c.Comm.SSHTimeout = c.SSHWaitTimeout
}
return c.Comm.Prepare(ctx)
} | [
"func",
"(",
"c",
"*",
"SSHConfig",
")",
"Prepare",
"(",
"ctx",
"*",
"interpolate",
".",
"Context",
")",
"[",
"]",
"error",
"{",
"// TODO: backwards compatibility, write fixer instead",
"if",
"c",
".",
"SSHWaitTimeout",
"!=",
"0",
"{",
"c",
".",
"Comm",
".",
"SSHTimeout",
"=",
"c",
".",
"SSHWaitTimeout",
"\n",
"}",
"\n\n",
"return",
"c",
".",
"Comm",
".",
"Prepare",
"(",
"ctx",
")",
"\n",
"}"
] | // Prepare sets the default values for SSH communicator properties. | [
"Prepare",
"sets",
"the",
"default",
"values",
"for",
"SSH",
"communicator",
"properties",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/parallels/common/ssh_config.go#L20-L27 |
165,178 | hashicorp/packer | builder/azure/arm/azure_error_response.go | formatAzureErrorResponse | func formatAzureErrorResponse(error azureErrorDetails, buf *bytes.Buffer, indent string) {
if error.isEmpty() {
return
}
buf.WriteString(fmt.Sprintf("ERROR: %s-> %s : %s\n", indent, error.Code, error.Message))
for _, x := range error.Details {
newIndent := fmt.Sprintf("%s ", indent)
var aer azureErrorResponse
err := json.Unmarshal([]byte(x.Message), &aer)
if err == nil {
buf.WriteString(fmt.Sprintf("ERROR: %s-> %s\n", newIndent, x.Code))
formatAzureErrorResponse(aer.ErrorDetails, buf, newIndent)
} else {
buf.WriteString(fmt.Sprintf("ERROR: %s-> %s : %s\n", newIndent, x.Code, x.Message))
}
}
} | go | func formatAzureErrorResponse(error azureErrorDetails, buf *bytes.Buffer, indent string) {
if error.isEmpty() {
return
}
buf.WriteString(fmt.Sprintf("ERROR: %s-> %s : %s\n", indent, error.Code, error.Message))
for _, x := range error.Details {
newIndent := fmt.Sprintf("%s ", indent)
var aer azureErrorResponse
err := json.Unmarshal([]byte(x.Message), &aer)
if err == nil {
buf.WriteString(fmt.Sprintf("ERROR: %s-> %s\n", newIndent, x.Code))
formatAzureErrorResponse(aer.ErrorDetails, buf, newIndent)
} else {
buf.WriteString(fmt.Sprintf("ERROR: %s-> %s : %s\n", newIndent, x.Code, x.Message))
}
}
} | [
"func",
"formatAzureErrorResponse",
"(",
"error",
"azureErrorDetails",
",",
"buf",
"*",
"bytes",
".",
"Buffer",
",",
"indent",
"string",
")",
"{",
"if",
"error",
".",
"isEmpty",
"(",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"buf",
".",
"WriteString",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\"",
",",
"indent",
",",
"error",
".",
"Code",
",",
"error",
".",
"Message",
")",
")",
"\n",
"for",
"_",
",",
"x",
":=",
"range",
"error",
".",
"Details",
"{",
"newIndent",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"indent",
")",
"\n\n",
"var",
"aer",
"azureErrorResponse",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"[",
"]",
"byte",
"(",
"x",
".",
"Message",
")",
",",
"&",
"aer",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"buf",
".",
"WriteString",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\"",
",",
"newIndent",
",",
"x",
".",
"Code",
")",
")",
"\n",
"formatAzureErrorResponse",
"(",
"aer",
".",
"ErrorDetails",
",",
"buf",
",",
"newIndent",
")",
"\n",
"}",
"else",
"{",
"buf",
".",
"WriteString",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\"",
",",
"newIndent",
",",
"x",
".",
"Code",
",",
"x",
".",
"Message",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // format a Azure Error Response by recursing through the JSON structure.
//
// Errors may contain nested errors, which are JSON documents that have been
// serialized and escaped. Keep following this nesting all the way down... | [
"format",
"a",
"Azure",
"Error",
"Response",
"by",
"recursing",
"through",
"the",
"JSON",
"structure",
".",
"Errors",
"may",
"contain",
"nested",
"errors",
"which",
"are",
"JSON",
"documents",
"that",
"have",
"been",
"serialized",
"and",
"escaped",
".",
"Keep",
"following",
"this",
"nesting",
"all",
"the",
"way",
"down",
"..."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/azure/arm/azure_error_response.go#L49-L67 |
165,179 | hashicorp/packer | builder/azure/arm/builder.go | setRuntimeParameters | func (b *Builder) setRuntimeParameters(stateBag multistep.StateBag) {
stateBag.Put(constants.ArmLocation, b.config.Location)
stateBag.Put(constants.ArmManagedImageLocation, b.config.manageImageLocation)
} | go | func (b *Builder) setRuntimeParameters(stateBag multistep.StateBag) {
stateBag.Put(constants.ArmLocation, b.config.Location)
stateBag.Put(constants.ArmManagedImageLocation, b.config.manageImageLocation)
} | [
"func",
"(",
"b",
"*",
"Builder",
")",
"setRuntimeParameters",
"(",
"stateBag",
"multistep",
".",
"StateBag",
")",
"{",
"stateBag",
".",
"Put",
"(",
"constants",
".",
"ArmLocation",
",",
"b",
".",
"config",
".",
"Location",
")",
"\n",
"stateBag",
".",
"Put",
"(",
"constants",
".",
"ArmManagedImageLocation",
",",
"b",
".",
"config",
".",
"manageImageLocation",
")",
"\n",
"}"
] | // Parameters that are only known at runtime after querying Azure. | [
"Parameters",
"that",
"are",
"only",
"known",
"at",
"runtime",
"after",
"querying",
"Azure",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/azure/arm/builder.go#L375-L378 |
165,180 | hashicorp/packer | builder/amazon/common/access_config.go | Session | func (c *AccessConfig) Session() (*session.Session, error) {
if c.session != nil {
return c.session, nil
}
config := aws.NewConfig().WithCredentialsChainVerboseErrors(true)
staticCreds := credentials.NewStaticCredentials(c.AccessKey, c.SecretKey, c.Token)
if _, err := staticCreds.Get(); err != credentials.ErrStaticCredentialsEmpty {
config.WithCredentials(staticCreds)
}
if c.RawRegion != "" {
config = config.WithRegion(c.RawRegion)
}
if c.CustomEndpointEc2 != "" {
config = config.WithEndpoint(c.CustomEndpointEc2)
}
config = config.WithHTTPClient(cleanhttp.DefaultClient())
transport := config.HTTPClient.Transport.(*http.Transport)
if c.InsecureSkipTLSVerify {
transport.TLSClientConfig = &tls.Config{
InsecureSkipVerify: true,
}
}
transport.Proxy = http.ProxyFromEnvironment
opts := session.Options{
SharedConfigState: session.SharedConfigEnable,
Config: *config,
}
if c.ProfileName != "" {
opts.Profile = c.ProfileName
}
if c.MFACode != "" {
opts.AssumeRoleTokenProvider = func() (string, error) {
return c.MFACode, nil
}
}
sess, err := session.NewSessionWithOptions(opts)
if err != nil {
return nil, err
}
log.Printf("Found region %s", *sess.Config.Region)
c.session = sess
cp, err := c.session.Config.Credentials.Get()
if err != nil {
if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NoCredentialProviders" {
return nil, fmt.Errorf("No valid credential sources found for AWS Builder. " +
"Please see https://www.packer.io/docs/builders/amazon.html#specifying-amazon-credentials " +
"for more information on providing credentials for the AWS Builder.")
} else {
return nil, fmt.Errorf("Error loading credentials for AWS Provider: %s", err)
}
}
log.Printf("[INFO] AWS Auth provider used: %q", cp.ProviderName)
if c.DecodeAuthZMessages {
DecodeAuthZMessages(c.session)
}
LogEnvOverrideWarnings()
return c.session, nil
} | go | func (c *AccessConfig) Session() (*session.Session, error) {
if c.session != nil {
return c.session, nil
}
config := aws.NewConfig().WithCredentialsChainVerboseErrors(true)
staticCreds := credentials.NewStaticCredentials(c.AccessKey, c.SecretKey, c.Token)
if _, err := staticCreds.Get(); err != credentials.ErrStaticCredentialsEmpty {
config.WithCredentials(staticCreds)
}
if c.RawRegion != "" {
config = config.WithRegion(c.RawRegion)
}
if c.CustomEndpointEc2 != "" {
config = config.WithEndpoint(c.CustomEndpointEc2)
}
config = config.WithHTTPClient(cleanhttp.DefaultClient())
transport := config.HTTPClient.Transport.(*http.Transport)
if c.InsecureSkipTLSVerify {
transport.TLSClientConfig = &tls.Config{
InsecureSkipVerify: true,
}
}
transport.Proxy = http.ProxyFromEnvironment
opts := session.Options{
SharedConfigState: session.SharedConfigEnable,
Config: *config,
}
if c.ProfileName != "" {
opts.Profile = c.ProfileName
}
if c.MFACode != "" {
opts.AssumeRoleTokenProvider = func() (string, error) {
return c.MFACode, nil
}
}
sess, err := session.NewSessionWithOptions(opts)
if err != nil {
return nil, err
}
log.Printf("Found region %s", *sess.Config.Region)
c.session = sess
cp, err := c.session.Config.Credentials.Get()
if err != nil {
if awsErr, ok := err.(awserr.Error); ok && awsErr.Code() == "NoCredentialProviders" {
return nil, fmt.Errorf("No valid credential sources found for AWS Builder. " +
"Please see https://www.packer.io/docs/builders/amazon.html#specifying-amazon-credentials " +
"for more information on providing credentials for the AWS Builder.")
} else {
return nil, fmt.Errorf("Error loading credentials for AWS Provider: %s", err)
}
}
log.Printf("[INFO] AWS Auth provider used: %q", cp.ProviderName)
if c.DecodeAuthZMessages {
DecodeAuthZMessages(c.session)
}
LogEnvOverrideWarnings()
return c.session, nil
} | [
"func",
"(",
"c",
"*",
"AccessConfig",
")",
"Session",
"(",
")",
"(",
"*",
"session",
".",
"Session",
",",
"error",
")",
"{",
"if",
"c",
".",
"session",
"!=",
"nil",
"{",
"return",
"c",
".",
"session",
",",
"nil",
"\n",
"}",
"\n\n",
"config",
":=",
"aws",
".",
"NewConfig",
"(",
")",
".",
"WithCredentialsChainVerboseErrors",
"(",
"true",
")",
"\n\n",
"staticCreds",
":=",
"credentials",
".",
"NewStaticCredentials",
"(",
"c",
".",
"AccessKey",
",",
"c",
".",
"SecretKey",
",",
"c",
".",
"Token",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"staticCreds",
".",
"Get",
"(",
")",
";",
"err",
"!=",
"credentials",
".",
"ErrStaticCredentialsEmpty",
"{",
"config",
".",
"WithCredentials",
"(",
"staticCreds",
")",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"RawRegion",
"!=",
"\"",
"\"",
"{",
"config",
"=",
"config",
".",
"WithRegion",
"(",
"c",
".",
"RawRegion",
")",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"CustomEndpointEc2",
"!=",
"\"",
"\"",
"{",
"config",
"=",
"config",
".",
"WithEndpoint",
"(",
"c",
".",
"CustomEndpointEc2",
")",
"\n",
"}",
"\n\n",
"config",
"=",
"config",
".",
"WithHTTPClient",
"(",
"cleanhttp",
".",
"DefaultClient",
"(",
")",
")",
"\n",
"transport",
":=",
"config",
".",
"HTTPClient",
".",
"Transport",
".",
"(",
"*",
"http",
".",
"Transport",
")",
"\n",
"if",
"c",
".",
"InsecureSkipTLSVerify",
"{",
"transport",
".",
"TLSClientConfig",
"=",
"&",
"tls",
".",
"Config",
"{",
"InsecureSkipVerify",
":",
"true",
",",
"}",
"\n",
"}",
"\n",
"transport",
".",
"Proxy",
"=",
"http",
".",
"ProxyFromEnvironment",
"\n\n",
"opts",
":=",
"session",
".",
"Options",
"{",
"SharedConfigState",
":",
"session",
".",
"SharedConfigEnable",
",",
"Config",
":",
"*",
"config",
",",
"}",
"\n\n",
"if",
"c",
".",
"ProfileName",
"!=",
"\"",
"\"",
"{",
"opts",
".",
"Profile",
"=",
"c",
".",
"ProfileName",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"MFACode",
"!=",
"\"",
"\"",
"{",
"opts",
".",
"AssumeRoleTokenProvider",
"=",
"func",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"c",
".",
"MFACode",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"sess",
",",
"err",
":=",
"session",
".",
"NewSessionWithOptions",
"(",
"opts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"*",
"sess",
".",
"Config",
".",
"Region",
")",
"\n",
"c",
".",
"session",
"=",
"sess",
"\n\n",
"cp",
",",
"err",
":=",
"c",
".",
"session",
".",
"Config",
".",
"Credentials",
".",
"Get",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"awsErr",
",",
"ok",
":=",
"err",
".",
"(",
"awserr",
".",
"Error",
")",
";",
"ok",
"&&",
"awsErr",
".",
"Code",
"(",
")",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
"+",
"\"",
"\"",
"+",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"cp",
".",
"ProviderName",
")",
"\n\n",
"if",
"c",
".",
"DecodeAuthZMessages",
"{",
"DecodeAuthZMessages",
"(",
"c",
".",
"session",
")",
"\n",
"}",
"\n",
"LogEnvOverrideWarnings",
"(",
")",
"\n\n",
"return",
"c",
".",
"session",
",",
"nil",
"\n",
"}"
] | // Config returns a valid aws.Config object for access to AWS services, or
// an error if the authentication and region couldn't be resolved | [
"Config",
"returns",
"a",
"valid",
"aws",
".",
"Config",
"object",
"for",
"access",
"to",
"AWS",
"services",
"or",
"an",
"error",
"if",
"the",
"authentication",
"and",
"region",
"couldn",
"t",
"be",
"resolved"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/amazon/common/access_config.go#L54-L123 |
165,181 | hashicorp/packer | builder/googlecompute/networking.go | getNetworking | func getNetworking(c *InstanceConfig) (string, string, error) {
networkId := c.Network
subnetworkId := c.Subnetwork
// Apply network naming requirements per
// https://cloud.google.com/compute/docs/reference/latest/instances#resource
switch c.Network {
// It is possible to omit the network property as long as a subnet is
// specified. That will be validated later.
case "":
break
// This special short name should be expanded.
case "default":
networkId = "global/networks/default"
// A value other than "default" was provided for the network name.
default:
// If the value doesn't contain a slash, we assume it's not a full or
// partial URL. We will expand it into a partial URL here and avoid
// making an API call to discover the network as it's common for the
// caller to not have permission against network discovery APIs.
if !strings.Contains(c.Network, "/") {
networkId = "projects/" + c.NetworkProjectId + "/global/networks/" + c.Network
}
}
// Apply subnetwork naming requirements per
// https://cloud.google.com/compute/docs/reference/latest/instances#resource
switch c.Subnetwork {
case "":
// You can't omit both subnetwork and network
if networkId == "" {
return networkId, subnetworkId, fmt.Errorf("both network and subnetwork were empty.")
}
// An empty subnetwork is only valid for networks in legacy mode or
// auto-subnet mode. We could make an API call to get that information
// about the network, but it's common for the caller to not have
// permission to that API. We'll proceed assuming they're correct in
// omitting the subnetwork and let the compute.insert API surface an
// error about an invalid network configuration if it exists.
break
default:
// If the value doesn't contain a slash, we assume it's not a full or
// partial URL. We will expand it into a partial URL here and avoid
// making a call to discover the subnetwork.
if !strings.Contains(c.Subnetwork, "/") {
subnetworkId = "projects/" + c.NetworkProjectId + "/regions/" + c.Region + "/subnetworks/" + c.Subnetwork
}
}
return networkId, subnetworkId, nil
} | go | func getNetworking(c *InstanceConfig) (string, string, error) {
networkId := c.Network
subnetworkId := c.Subnetwork
// Apply network naming requirements per
// https://cloud.google.com/compute/docs/reference/latest/instances#resource
switch c.Network {
// It is possible to omit the network property as long as a subnet is
// specified. That will be validated later.
case "":
break
// This special short name should be expanded.
case "default":
networkId = "global/networks/default"
// A value other than "default" was provided for the network name.
default:
// If the value doesn't contain a slash, we assume it's not a full or
// partial URL. We will expand it into a partial URL here and avoid
// making an API call to discover the network as it's common for the
// caller to not have permission against network discovery APIs.
if !strings.Contains(c.Network, "/") {
networkId = "projects/" + c.NetworkProjectId + "/global/networks/" + c.Network
}
}
// Apply subnetwork naming requirements per
// https://cloud.google.com/compute/docs/reference/latest/instances#resource
switch c.Subnetwork {
case "":
// You can't omit both subnetwork and network
if networkId == "" {
return networkId, subnetworkId, fmt.Errorf("both network and subnetwork were empty.")
}
// An empty subnetwork is only valid for networks in legacy mode or
// auto-subnet mode. We could make an API call to get that information
// about the network, but it's common for the caller to not have
// permission to that API. We'll proceed assuming they're correct in
// omitting the subnetwork and let the compute.insert API surface an
// error about an invalid network configuration if it exists.
break
default:
// If the value doesn't contain a slash, we assume it's not a full or
// partial URL. We will expand it into a partial URL here and avoid
// making a call to discover the subnetwork.
if !strings.Contains(c.Subnetwork, "/") {
subnetworkId = "projects/" + c.NetworkProjectId + "/regions/" + c.Region + "/subnetworks/" + c.Subnetwork
}
}
return networkId, subnetworkId, nil
} | [
"func",
"getNetworking",
"(",
"c",
"*",
"InstanceConfig",
")",
"(",
"string",
",",
"string",
",",
"error",
")",
"{",
"networkId",
":=",
"c",
".",
"Network",
"\n",
"subnetworkId",
":=",
"c",
".",
"Subnetwork",
"\n\n",
"// Apply network naming requirements per",
"// https://cloud.google.com/compute/docs/reference/latest/instances#resource",
"switch",
"c",
".",
"Network",
"{",
"// It is possible to omit the network property as long as a subnet is",
"// specified. That will be validated later.",
"case",
"\"",
"\"",
":",
"break",
"\n",
"// This special short name should be expanded.",
"case",
"\"",
"\"",
":",
"networkId",
"=",
"\"",
"\"",
"\n",
"// A value other than \"default\" was provided for the network name.",
"default",
":",
"// If the value doesn't contain a slash, we assume it's not a full or",
"// partial URL. We will expand it into a partial URL here and avoid",
"// making an API call to discover the network as it's common for the",
"// caller to not have permission against network discovery APIs.",
"if",
"!",
"strings",
".",
"Contains",
"(",
"c",
".",
"Network",
",",
"\"",
"\"",
")",
"{",
"networkId",
"=",
"\"",
"\"",
"+",
"c",
".",
"NetworkProjectId",
"+",
"\"",
"\"",
"+",
"c",
".",
"Network",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Apply subnetwork naming requirements per",
"// https://cloud.google.com/compute/docs/reference/latest/instances#resource",
"switch",
"c",
".",
"Subnetwork",
"{",
"case",
"\"",
"\"",
":",
"// You can't omit both subnetwork and network",
"if",
"networkId",
"==",
"\"",
"\"",
"{",
"return",
"networkId",
",",
"subnetworkId",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// An empty subnetwork is only valid for networks in legacy mode or",
"// auto-subnet mode. We could make an API call to get that information",
"// about the network, but it's common for the caller to not have",
"// permission to that API. We'll proceed assuming they're correct in",
"// omitting the subnetwork and let the compute.insert API surface an",
"// error about an invalid network configuration if it exists.",
"break",
"\n",
"default",
":",
"// If the value doesn't contain a slash, we assume it's not a full or",
"// partial URL. We will expand it into a partial URL here and avoid",
"// making a call to discover the subnetwork.",
"if",
"!",
"strings",
".",
"Contains",
"(",
"c",
".",
"Subnetwork",
",",
"\"",
"\"",
")",
"{",
"subnetworkId",
"=",
"\"",
"\"",
"+",
"c",
".",
"NetworkProjectId",
"+",
"\"",
"\"",
"+",
"c",
".",
"Region",
"+",
"\"",
"\"",
"+",
"c",
".",
"Subnetwork",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"networkId",
",",
"subnetworkId",
",",
"nil",
"\n",
"}"
] | // This method will build a network and subnetwork ID from the provided
// instance config, and return them in that order. | [
"This",
"method",
"will",
"build",
"a",
"network",
"and",
"subnetwork",
"ID",
"from",
"the",
"provided",
"instance",
"config",
"and",
"return",
"them",
"in",
"that",
"order",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/googlecompute/networking.go#L10-L59 |
165,182 | hashicorp/packer | builder/oracle/oci/artifact.go | Destroy | func (a *Artifact) Destroy() error {
return a.driver.DeleteImage(context.TODO(), *a.Image.Id)
} | go | func (a *Artifact) Destroy() error {
return a.driver.DeleteImage(context.TODO(), *a.Image.Id)
} | [
"func",
"(",
"a",
"*",
"Artifact",
")",
"Destroy",
"(",
")",
"error",
"{",
"return",
"a",
".",
"driver",
".",
"DeleteImage",
"(",
"context",
".",
"TODO",
"(",
")",
",",
"*",
"a",
".",
"Image",
".",
"Id",
")",
"\n",
"}"
] | // Destroy deletes the custom image associated with the artifact. | [
"Destroy",
"deletes",
"the",
"custom",
"image",
"associated",
"with",
"the",
"artifact",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/oracle/oci/artifact.go#L51-L53 |
165,183 | hashicorp/packer | builder/vmware/common/driver_player5_windows.go | playerVMwareRoot | func playerVMwareRoot() (s string, err error) {
key := `SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\vmplayer.exe`
subkey := "Path"
s, err = readRegString(syscall.HKEY_LOCAL_MACHINE, key, subkey)
if err != nil {
log.Printf(`Unable to read registry key %s\%s`, key, subkey)
return
}
return normalizePath(s), nil
} | go | func playerVMwareRoot() (s string, err error) {
key := `SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\vmplayer.exe`
subkey := "Path"
s, err = readRegString(syscall.HKEY_LOCAL_MACHINE, key, subkey)
if err != nil {
log.Printf(`Unable to read registry key %s\%s`, key, subkey)
return
}
return normalizePath(s), nil
} | [
"func",
"playerVMwareRoot",
"(",
")",
"(",
"s",
"string",
",",
"err",
"error",
")",
"{",
"key",
":=",
"`SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\vmplayer.exe`",
"\n",
"subkey",
":=",
"\"",
"\"",
"\n",
"s",
",",
"err",
"=",
"readRegString",
"(",
"syscall",
".",
"HKEY_LOCAL_MACHINE",
",",
"key",
",",
"subkey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"`Unable to read registry key %s\\%s`",
",",
"key",
",",
"subkey",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"return",
"normalizePath",
"(",
"s",
")",
",",
"nil",
"\n",
"}"
] | // This reads the VMware installation path from the Windows registry. | [
"This",
"reads",
"the",
"VMware",
"installation",
"path",
"from",
"the",
"Windows",
"registry",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/vmware/common/driver_player5_windows.go#L84-L94 |
165,184 | hashicorp/packer | builder/vmware/common/driver_player5_windows.go | playerProgramFilePaths | func playerProgramFilePaths() []string {
path, err := playerVMwareRoot()
if err != nil {
log.Printf("Error finding VMware root: %s", err)
}
paths := make([]string, 0, 5)
if os.Getenv("VMWARE_HOME") != "" {
paths = append(paths, os.Getenv("VMWARE_HOME"))
}
if path != "" {
paths = append(paths, path)
}
if os.Getenv("ProgramFiles(x86)") != "" {
paths = append(paths,
filepath.Join(os.Getenv("ProgramFiles(x86)"), "/VMware/VMware Player"))
}
if os.Getenv("ProgramFiles") != "" {
paths = append(paths,
filepath.Join(os.Getenv("ProgramFiles"), "/VMware/VMware Player"))
}
if os.Getenv("QEMU_HOME") != "" {
paths = append(paths, os.Getenv("QEMU_HOME"))
}
if os.Getenv("ProgramFiles(x86)") != "" {
paths = append(paths,
filepath.Join(os.Getenv("ProgramFiles(x86)"), "/QEMU"))
}
if os.Getenv("ProgramFiles") != "" {
paths = append(paths,
filepath.Join(os.Getenv("ProgramFiles"), "/QEMU"))
}
if os.Getenv("SystemDrive") != "" {
paths = append(paths,
filepath.Join(os.Getenv("SystemDrive"), "/QEMU"))
}
return paths
} | go | func playerProgramFilePaths() []string {
path, err := playerVMwareRoot()
if err != nil {
log.Printf("Error finding VMware root: %s", err)
}
paths := make([]string, 0, 5)
if os.Getenv("VMWARE_HOME") != "" {
paths = append(paths, os.Getenv("VMWARE_HOME"))
}
if path != "" {
paths = append(paths, path)
}
if os.Getenv("ProgramFiles(x86)") != "" {
paths = append(paths,
filepath.Join(os.Getenv("ProgramFiles(x86)"), "/VMware/VMware Player"))
}
if os.Getenv("ProgramFiles") != "" {
paths = append(paths,
filepath.Join(os.Getenv("ProgramFiles"), "/VMware/VMware Player"))
}
if os.Getenv("QEMU_HOME") != "" {
paths = append(paths, os.Getenv("QEMU_HOME"))
}
if os.Getenv("ProgramFiles(x86)") != "" {
paths = append(paths,
filepath.Join(os.Getenv("ProgramFiles(x86)"), "/QEMU"))
}
if os.Getenv("ProgramFiles") != "" {
paths = append(paths,
filepath.Join(os.Getenv("ProgramFiles"), "/QEMU"))
}
if os.Getenv("SystemDrive") != "" {
paths = append(paths,
filepath.Join(os.Getenv("SystemDrive"), "/QEMU"))
}
return paths
} | [
"func",
"playerProgramFilePaths",
"(",
")",
"[",
"]",
"string",
"{",
"path",
",",
"err",
":=",
"playerVMwareRoot",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"paths",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"5",
")",
"\n",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"paths",
"=",
"append",
"(",
"paths",
",",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n\n",
"if",
"path",
"!=",
"\"",
"\"",
"{",
"paths",
"=",
"append",
"(",
"paths",
",",
"path",
")",
"\n",
"}",
"\n\n",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"paths",
"=",
"append",
"(",
"paths",
",",
"filepath",
".",
"Join",
"(",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n\n",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"paths",
"=",
"append",
"(",
"paths",
",",
"filepath",
".",
"Join",
"(",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n\n",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"paths",
"=",
"append",
"(",
"paths",
",",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n\n",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"paths",
"=",
"append",
"(",
"paths",
",",
"filepath",
".",
"Join",
"(",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n\n",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"paths",
"=",
"append",
"(",
"paths",
",",
"filepath",
".",
"Join",
"(",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n\n",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"paths",
"=",
"append",
"(",
"paths",
",",
"filepath",
".",
"Join",
"(",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n\n",
"return",
"paths",
"\n",
"}"
] | // playerProgramFilesPaths returns a list of paths that are eligible
// to contain program files we may want just as vmware.exe. | [
"playerProgramFilesPaths",
"returns",
"a",
"list",
"of",
"paths",
"that",
"are",
"eligible",
"to",
"contain",
"program",
"files",
"we",
"may",
"want",
"just",
"as",
"vmware",
".",
"exe",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/vmware/common/driver_player5_windows.go#L122-L167 |
165,185 | hashicorp/packer | builder/vmware/common/driver_player5_windows.go | playerDataFilePaths | func playerDataFilePaths() []string {
leasesPath, err := playerDhcpLeasesPathRegistry()
if err != nil {
log.Printf("Error getting DHCP leases path: %s", err)
}
if leasesPath != "" {
leasesPath = filepath.Dir(leasesPath)
}
paths := make([]string, 0, 5)
if os.Getenv("VMWARE_DATA") != "" {
paths = append(paths, os.Getenv("VMWARE_DATA"))
}
if leasesPath != "" {
paths = append(paths, leasesPath)
}
if os.Getenv("ProgramData") != "" {
paths = append(paths,
filepath.Join(os.Getenv("ProgramData"), "/VMware"))
}
if os.Getenv("ALLUSERSPROFILE") != "" {
paths = append(paths,
filepath.Join(os.Getenv("ALLUSERSPROFILE"), "/Application Data/VMware"))
}
return paths
} | go | func playerDataFilePaths() []string {
leasesPath, err := playerDhcpLeasesPathRegistry()
if err != nil {
log.Printf("Error getting DHCP leases path: %s", err)
}
if leasesPath != "" {
leasesPath = filepath.Dir(leasesPath)
}
paths := make([]string, 0, 5)
if os.Getenv("VMWARE_DATA") != "" {
paths = append(paths, os.Getenv("VMWARE_DATA"))
}
if leasesPath != "" {
paths = append(paths, leasesPath)
}
if os.Getenv("ProgramData") != "" {
paths = append(paths,
filepath.Join(os.Getenv("ProgramData"), "/VMware"))
}
if os.Getenv("ALLUSERSPROFILE") != "" {
paths = append(paths,
filepath.Join(os.Getenv("ALLUSERSPROFILE"), "/Application Data/VMware"))
}
return paths
} | [
"func",
"playerDataFilePaths",
"(",
")",
"[",
"]",
"string",
"{",
"leasesPath",
",",
"err",
":=",
"playerDhcpLeasesPathRegistry",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"leasesPath",
"!=",
"\"",
"\"",
"{",
"leasesPath",
"=",
"filepath",
".",
"Dir",
"(",
"leasesPath",
")",
"\n",
"}",
"\n\n",
"paths",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"5",
")",
"\n",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"paths",
"=",
"append",
"(",
"paths",
",",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n\n",
"if",
"leasesPath",
"!=",
"\"",
"\"",
"{",
"paths",
"=",
"append",
"(",
"paths",
",",
"leasesPath",
")",
"\n",
"}",
"\n\n",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"paths",
"=",
"append",
"(",
"paths",
",",
"filepath",
".",
"Join",
"(",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n\n",
"if",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
"{",
"paths",
"=",
"append",
"(",
"paths",
",",
"filepath",
".",
"Join",
"(",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n\n",
"return",
"paths",
"\n",
"}"
] | // playerDataFilePaths returns a list of paths that are eligible
// to contain data files we may want such as vmnet NAT configuration files. | [
"playerDataFilePaths",
"returns",
"a",
"list",
"of",
"paths",
"that",
"are",
"eligible",
"to",
"contain",
"data",
"files",
"we",
"may",
"want",
"such",
"as",
"vmnet",
"NAT",
"configuration",
"files",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/vmware/common/driver_player5_windows.go#L171-L201 |
165,186 | hashicorp/packer | builder/yandex/template_func.go | templateCleanImageName | func templateCleanImageName(s string) string {
if reImageFamily.MatchString(s) {
return s
}
b := []byte(strings.ToLower(s))
newb := make([]byte, len(b))
for i := range newb {
if isalphanumeric(b[i]) {
newb[i] = b[i]
} else {
newb[i] = '-'
}
}
return string(newb)
} | go | func templateCleanImageName(s string) string {
if reImageFamily.MatchString(s) {
return s
}
b := []byte(strings.ToLower(s))
newb := make([]byte, len(b))
for i := range newb {
if isalphanumeric(b[i]) {
newb[i] = b[i]
} else {
newb[i] = '-'
}
}
return string(newb)
} | [
"func",
"templateCleanImageName",
"(",
"s",
"string",
")",
"string",
"{",
"if",
"reImageFamily",
".",
"MatchString",
"(",
"s",
")",
"{",
"return",
"s",
"\n",
"}",
"\n",
"b",
":=",
"[",
"]",
"byte",
"(",
"strings",
".",
"ToLower",
"(",
"s",
")",
")",
"\n",
"newb",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"b",
")",
")",
"\n",
"for",
"i",
":=",
"range",
"newb",
"{",
"if",
"isalphanumeric",
"(",
"b",
"[",
"i",
"]",
")",
"{",
"newb",
"[",
"i",
"]",
"=",
"b",
"[",
"i",
"]",
"\n",
"}",
"else",
"{",
"newb",
"[",
"i",
"]",
"=",
"'-'",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"string",
"(",
"newb",
")",
"\n",
"}"
] | // Clean up image name by replacing invalid characters with "-"
// and converting upper cases to lower cases | [
"Clean",
"up",
"image",
"name",
"by",
"replacing",
"invalid",
"characters",
"with",
"-",
"and",
"converting",
"upper",
"cases",
"to",
"lower",
"cases"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/yandex/template_func.go#L18-L32 |
165,187 | hashicorp/packer | provisioner/shell/unix_reader.go | scanUnixLine | func scanUnixLine(data []byte, atEOF bool) (advance int, token []byte, err error) {
advance, token, err = bufio.ScanLines(data, atEOF)
if advance == 0 {
// If we reached the end of a line without a newline, then
// just return as it is. Otherwise the Scanner will keep trying
// to scan, blocking forever.
return
}
return advance, append(token, '\n'), err
} | go | func scanUnixLine(data []byte, atEOF bool) (advance int, token []byte, err error) {
advance, token, err = bufio.ScanLines(data, atEOF)
if advance == 0 {
// If we reached the end of a line without a newline, then
// just return as it is. Otherwise the Scanner will keep trying
// to scan, blocking forever.
return
}
return advance, append(token, '\n'), err
} | [
"func",
"scanUnixLine",
"(",
"data",
"[",
"]",
"byte",
",",
"atEOF",
"bool",
")",
"(",
"advance",
"int",
",",
"token",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"advance",
",",
"token",
",",
"err",
"=",
"bufio",
".",
"ScanLines",
"(",
"data",
",",
"atEOF",
")",
"\n",
"if",
"advance",
"==",
"0",
"{",
"// If we reached the end of a line without a newline, then",
"// just return as it is. Otherwise the Scanner will keep trying",
"// to scan, blocking forever.",
"return",
"\n",
"}",
"\n\n",
"return",
"advance",
",",
"append",
"(",
"token",
",",
"'\\n'",
")",
",",
"err",
"\n",
"}"
] | // scanUnixLine is a bufio.Scanner SplitFunc. It tokenizes on lines, but
// only returns unix-style lines. So even if the line is "one\r\n", the
// token returned will be "one\n". | [
"scanUnixLine",
"is",
"a",
"bufio",
".",
"Scanner",
"SplitFunc",
".",
"It",
"tokenizes",
"on",
"lines",
"but",
"only",
"returns",
"unix",
"-",
"style",
"lines",
".",
"So",
"even",
"if",
"the",
"line",
"is",
"one",
"\\",
"r",
"\\",
"n",
"the",
"token",
"returned",
"will",
"be",
"one",
"\\",
"n",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/provisioner/shell/unix_reader.go#L55-L65 |
165,188 | hashicorp/packer | builder/yandex/builder.go | Run | func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (packer.Artifact, error) {
driver, err := NewDriverYC(ui, b.config)
if err != nil {
return nil, err
}
// Set up the state
state := &multistep.BasicStateBag{}
state.Put("config", b.config)
state.Put("driver", driver)
state.Put("sdk", driver.SDK())
state.Put("hook", hook)
state.Put("ui", ui)
// Build the steps
steps := []multistep.Step{
&stepCreateSSHKey{
Debug: b.config.PackerDebug,
DebugKeyPath: fmt.Sprintf("yc_%s.pem", b.config.PackerBuildName),
},
&stepCreateInstance{
Debug: b.config.PackerDebug,
SerialLogFile: b.config.SerialLogFile,
},
&stepInstanceInfo{},
&communicator.StepConnect{
Config: &b.config.Communicator,
Host: commHost,
SSHConfig: b.config.Communicator.SSHConfigFunc(),
},
&common.StepProvision{},
&common.StepCleanupTempKeys{
Comm: &b.config.Communicator,
},
&stepTeardownInstance{},
&stepCreateImage{},
}
// Run the steps
b.runner = common.NewRunner(steps, b.config.PackerConfig, ui)
b.runner.Run(ctx, state)
// Report any errors
if rawErr, ok := state.GetOk("error"); ok {
return nil, rawErr.(error)
}
image, ok := state.GetOk("image")
if !ok {
return nil, fmt.Errorf("Failed to find 'image' in state. Bug?")
}
artifact := &Artifact{
image: image.(*compute.Image),
config: b.config,
}
return artifact, nil
} | go | func (b *Builder) Run(ctx context.Context, ui packer.Ui, hook packer.Hook) (packer.Artifact, error) {
driver, err := NewDriverYC(ui, b.config)
if err != nil {
return nil, err
}
// Set up the state
state := &multistep.BasicStateBag{}
state.Put("config", b.config)
state.Put("driver", driver)
state.Put("sdk", driver.SDK())
state.Put("hook", hook)
state.Put("ui", ui)
// Build the steps
steps := []multistep.Step{
&stepCreateSSHKey{
Debug: b.config.PackerDebug,
DebugKeyPath: fmt.Sprintf("yc_%s.pem", b.config.PackerBuildName),
},
&stepCreateInstance{
Debug: b.config.PackerDebug,
SerialLogFile: b.config.SerialLogFile,
},
&stepInstanceInfo{},
&communicator.StepConnect{
Config: &b.config.Communicator,
Host: commHost,
SSHConfig: b.config.Communicator.SSHConfigFunc(),
},
&common.StepProvision{},
&common.StepCleanupTempKeys{
Comm: &b.config.Communicator,
},
&stepTeardownInstance{},
&stepCreateImage{},
}
// Run the steps
b.runner = common.NewRunner(steps, b.config.PackerConfig, ui)
b.runner.Run(ctx, state)
// Report any errors
if rawErr, ok := state.GetOk("error"); ok {
return nil, rawErr.(error)
}
image, ok := state.GetOk("image")
if !ok {
return nil, fmt.Errorf("Failed to find 'image' in state. Bug?")
}
artifact := &Artifact{
image: image.(*compute.Image),
config: b.config,
}
return artifact, nil
} | [
"func",
"(",
"b",
"*",
"Builder",
")",
"Run",
"(",
"ctx",
"context",
".",
"Context",
",",
"ui",
"packer",
".",
"Ui",
",",
"hook",
"packer",
".",
"Hook",
")",
"(",
"packer",
".",
"Artifact",
",",
"error",
")",
"{",
"driver",
",",
"err",
":=",
"NewDriverYC",
"(",
"ui",
",",
"b",
".",
"config",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Set up the state",
"state",
":=",
"&",
"multistep",
".",
"BasicStateBag",
"{",
"}",
"\n",
"state",
".",
"Put",
"(",
"\"",
"\"",
",",
"b",
".",
"config",
")",
"\n",
"state",
".",
"Put",
"(",
"\"",
"\"",
",",
"driver",
")",
"\n",
"state",
".",
"Put",
"(",
"\"",
"\"",
",",
"driver",
".",
"SDK",
"(",
")",
")",
"\n",
"state",
".",
"Put",
"(",
"\"",
"\"",
",",
"hook",
")",
"\n",
"state",
".",
"Put",
"(",
"\"",
"\"",
",",
"ui",
")",
"\n\n",
"// Build the steps",
"steps",
":=",
"[",
"]",
"multistep",
".",
"Step",
"{",
"&",
"stepCreateSSHKey",
"{",
"Debug",
":",
"b",
".",
"config",
".",
"PackerDebug",
",",
"DebugKeyPath",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"b",
".",
"config",
".",
"PackerBuildName",
")",
",",
"}",
",",
"&",
"stepCreateInstance",
"{",
"Debug",
":",
"b",
".",
"config",
".",
"PackerDebug",
",",
"SerialLogFile",
":",
"b",
".",
"config",
".",
"SerialLogFile",
",",
"}",
",",
"&",
"stepInstanceInfo",
"{",
"}",
",",
"&",
"communicator",
".",
"StepConnect",
"{",
"Config",
":",
"&",
"b",
".",
"config",
".",
"Communicator",
",",
"Host",
":",
"commHost",
",",
"SSHConfig",
":",
"b",
".",
"config",
".",
"Communicator",
".",
"SSHConfigFunc",
"(",
")",
",",
"}",
",",
"&",
"common",
".",
"StepProvision",
"{",
"}",
",",
"&",
"common",
".",
"StepCleanupTempKeys",
"{",
"Comm",
":",
"&",
"b",
".",
"config",
".",
"Communicator",
",",
"}",
",",
"&",
"stepTeardownInstance",
"{",
"}",
",",
"&",
"stepCreateImage",
"{",
"}",
",",
"}",
"\n\n",
"// Run the steps",
"b",
".",
"runner",
"=",
"common",
".",
"NewRunner",
"(",
"steps",
",",
"b",
".",
"config",
".",
"PackerConfig",
",",
"ui",
")",
"\n",
"b",
".",
"runner",
".",
"Run",
"(",
"ctx",
",",
"state",
")",
"\n\n",
"// Report any errors",
"if",
"rawErr",
",",
"ok",
":=",
"state",
".",
"GetOk",
"(",
"\"",
"\"",
")",
";",
"ok",
"{",
"return",
"nil",
",",
"rawErr",
".",
"(",
"error",
")",
"\n",
"}",
"\n\n",
"image",
",",
"ok",
":=",
"state",
".",
"GetOk",
"(",
"\"",
"\"",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"artifact",
":=",
"&",
"Artifact",
"{",
"image",
":",
"image",
".",
"(",
"*",
"compute",
".",
"Image",
")",
",",
"config",
":",
"b",
".",
"config",
",",
"}",
"\n",
"return",
"artifact",
",",
"nil",
"\n",
"}"
] | // Run executes a yandex Packer build and returns a packer.Artifact
// representing a Yandex.Cloud compute image. | [
"Run",
"executes",
"a",
"yandex",
"Packer",
"build",
"and",
"returns",
"a",
"packer",
".",
"Artifact",
"representing",
"a",
"Yandex",
".",
"Cloud",
"compute",
"image",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/yandex/builder.go#L36-L94 |
165,189 | hashicorp/packer | builder/vmware/common/driver_esx5.go | UpdateVMX | func (ESX5Driver) UpdateVMX(_, password string, port int, data map[string]string) {
// Do not set remotedisplay.vnc.ip - this breaks ESXi.
data["remotedisplay.vnc.enabled"] = "TRUE"
data["remotedisplay.vnc.port"] = fmt.Sprintf("%d", port)
if len(password) > 0 {
data["remotedisplay.vnc.password"] = password
}
} | go | func (ESX5Driver) UpdateVMX(_, password string, port int, data map[string]string) {
// Do not set remotedisplay.vnc.ip - this breaks ESXi.
data["remotedisplay.vnc.enabled"] = "TRUE"
data["remotedisplay.vnc.port"] = fmt.Sprintf("%d", port)
if len(password) > 0 {
data["remotedisplay.vnc.password"] = password
}
} | [
"func",
"(",
"ESX5Driver",
")",
"UpdateVMX",
"(",
"_",
",",
"password",
"string",
",",
"port",
"int",
",",
"data",
"map",
"[",
"string",
"]",
"string",
")",
"{",
"// Do not set remotedisplay.vnc.ip - this breaks ESXi.",
"data",
"[",
"\"",
"\"",
"]",
"=",
"\"",
"\"",
"\n",
"data",
"[",
"\"",
"\"",
"]",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"port",
")",
"\n",
"if",
"len",
"(",
"password",
")",
">",
"0",
"{",
"data",
"[",
"\"",
"\"",
"]",
"=",
"password",
"\n",
"}",
"\n",
"}"
] | // UpdateVMX, adds the VNC port to the VMX data. | [
"UpdateVMX",
"adds",
"the",
"VNC",
"port",
"to",
"the",
"VMX",
"data",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/vmware/common/driver_esx5.go#L430-L437 |
165,190 | hashicorp/packer | builder/vmware/common/vmx.go | ParseVMX | func ParseVMX(contents string) map[string]string {
results := make(map[string]string)
lineRe := regexp.MustCompile(`^(.+?)\s*=\s*"?(.*?)"?\s*$`)
for _, line := range strings.Split(contents, "\n") {
matches := lineRe.FindStringSubmatch(line)
if matches == nil {
continue
}
key := strings.ToLower(matches[1])
results[key] = matches[2]
}
return results
} | go | func ParseVMX(contents string) map[string]string {
results := make(map[string]string)
lineRe := regexp.MustCompile(`^(.+?)\s*=\s*"?(.*?)"?\s*$`)
for _, line := range strings.Split(contents, "\n") {
matches := lineRe.FindStringSubmatch(line)
if matches == nil {
continue
}
key := strings.ToLower(matches[1])
results[key] = matches[2]
}
return results
} | [
"func",
"ParseVMX",
"(",
"contents",
"string",
")",
"map",
"[",
"string",
"]",
"string",
"{",
"results",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n\n",
"lineRe",
":=",
"regexp",
".",
"MustCompile",
"(",
"`^(.+?)\\s*=\\s*\"?(.*?)\"?\\s*$`",
")",
"\n\n",
"for",
"_",
",",
"line",
":=",
"range",
"strings",
".",
"Split",
"(",
"contents",
",",
"\"",
"\\n",
"\"",
")",
"{",
"matches",
":=",
"lineRe",
".",
"FindStringSubmatch",
"(",
"line",
")",
"\n",
"if",
"matches",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"\n\n",
"key",
":=",
"strings",
".",
"ToLower",
"(",
"matches",
"[",
"1",
"]",
")",
"\n",
"results",
"[",
"key",
"]",
"=",
"matches",
"[",
"2",
"]",
"\n",
"}",
"\n\n",
"return",
"results",
"\n",
"}"
] | // ParseVMX parses the keys and values from a VMX file and returns
// them as a Go map. | [
"ParseVMX",
"parses",
"the",
"keys",
"and",
"values",
"from",
"a",
"VMX",
"file",
"and",
"returns",
"them",
"as",
"a",
"Go",
"map",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/vmware/common/vmx.go#L17-L33 |
165,191 | hashicorp/packer | builder/vmware/common/vmx.go | EncodeVMX | func EncodeVMX(contents map[string]string) string {
var buf bytes.Buffer
i := 0
keys := make([]string, len(contents))
for k := range contents {
keys[i] = k
i++
}
// a list of VMX key fragments that the value must not be quoted
// fragments are used to cover multiples (i.e. multiple disks)
// keys are still lowercase at this point, use lower fragments
noQuotes := []string{
".virtualssd",
}
// a list of VMX key fragments that are case sensitive
// fragments are used to cover multiples (i.e. multiple disks)
caseSensitive := []string{
".virtualSSD",
}
sort.Strings(keys)
for _, k := range keys {
pat := "%s = \"%s\"\n"
// items with no quotes
for _, q := range noQuotes {
if strings.Contains(k, q) {
pat = "%s = %s\n"
break
}
}
key := k
// case sensitive key fragments
for _, c := range caseSensitive {
key = strings.Replace(key, strings.ToLower(c), c, 1)
}
buf.WriteString(fmt.Sprintf(pat, key, contents[k]))
}
return buf.String()
} | go | func EncodeVMX(contents map[string]string) string {
var buf bytes.Buffer
i := 0
keys := make([]string, len(contents))
for k := range contents {
keys[i] = k
i++
}
// a list of VMX key fragments that the value must not be quoted
// fragments are used to cover multiples (i.e. multiple disks)
// keys are still lowercase at this point, use lower fragments
noQuotes := []string{
".virtualssd",
}
// a list of VMX key fragments that are case sensitive
// fragments are used to cover multiples (i.e. multiple disks)
caseSensitive := []string{
".virtualSSD",
}
sort.Strings(keys)
for _, k := range keys {
pat := "%s = \"%s\"\n"
// items with no quotes
for _, q := range noQuotes {
if strings.Contains(k, q) {
pat = "%s = %s\n"
break
}
}
key := k
// case sensitive key fragments
for _, c := range caseSensitive {
key = strings.Replace(key, strings.ToLower(c), c, 1)
}
buf.WriteString(fmt.Sprintf(pat, key, contents[k]))
}
return buf.String()
} | [
"func",
"EncodeVMX",
"(",
"contents",
"map",
"[",
"string",
"]",
"string",
")",
"string",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n\n",
"i",
":=",
"0",
"\n",
"keys",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"contents",
")",
")",
"\n",
"for",
"k",
":=",
"range",
"contents",
"{",
"keys",
"[",
"i",
"]",
"=",
"k",
"\n",
"i",
"++",
"\n",
"}",
"\n\n",
"// a list of VMX key fragments that the value must not be quoted",
"// fragments are used to cover multiples (i.e. multiple disks)",
"// keys are still lowercase at this point, use lower fragments",
"noQuotes",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"}",
"\n\n",
"// a list of VMX key fragments that are case sensitive",
"// fragments are used to cover multiples (i.e. multiple disks)",
"caseSensitive",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"}",
"\n\n",
"sort",
".",
"Strings",
"(",
"keys",
")",
"\n",
"for",
"_",
",",
"k",
":=",
"range",
"keys",
"{",
"pat",
":=",
"\"",
"\\\"",
"\\\"",
"\\n",
"\"",
"\n",
"// items with no quotes",
"for",
"_",
",",
"q",
":=",
"range",
"noQuotes",
"{",
"if",
"strings",
".",
"Contains",
"(",
"k",
",",
"q",
")",
"{",
"pat",
"=",
"\"",
"\\n",
"\"",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"key",
":=",
"k",
"\n",
"// case sensitive key fragments",
"for",
"_",
",",
"c",
":=",
"range",
"caseSensitive",
"{",
"key",
"=",
"strings",
".",
"Replace",
"(",
"key",
",",
"strings",
".",
"ToLower",
"(",
"c",
")",
",",
"c",
",",
"1",
")",
"\n",
"}",
"\n",
"buf",
".",
"WriteString",
"(",
"fmt",
".",
"Sprintf",
"(",
"pat",
",",
"key",
",",
"contents",
"[",
"k",
"]",
")",
")",
"\n",
"}",
"\n\n",
"return",
"buf",
".",
"String",
"(",
")",
"\n",
"}"
] | // EncodeVMX takes a map and turns it into valid VMX contents. | [
"EncodeVMX",
"takes",
"a",
"map",
"and",
"turns",
"it",
"into",
"valid",
"VMX",
"contents",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/vmware/common/vmx.go#L36-L78 |
165,192 | hashicorp/packer | builder/vmware/common/vmx.go | WriteVMX | func WriteVMX(path string, data map[string]string) (err error) {
log.Printf("Writing VMX to: %s", path)
f, err := os.Create(path)
if err != nil {
return
}
defer f.Close()
var buf bytes.Buffer
buf.WriteString(EncodeVMX(data))
if _, err = io.Copy(f, &buf); err != nil {
return
}
return
} | go | func WriteVMX(path string, data map[string]string) (err error) {
log.Printf("Writing VMX to: %s", path)
f, err := os.Create(path)
if err != nil {
return
}
defer f.Close()
var buf bytes.Buffer
buf.WriteString(EncodeVMX(data))
if _, err = io.Copy(f, &buf); err != nil {
return
}
return
} | [
"func",
"WriteVMX",
"(",
"path",
"string",
",",
"data",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"err",
"error",
")",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"path",
")",
"\n",
"f",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n\n",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"buf",
".",
"WriteString",
"(",
"EncodeVMX",
"(",
"data",
")",
")",
"\n",
"if",
"_",
",",
"err",
"=",
"io",
".",
"Copy",
"(",
"f",
",",
"&",
"buf",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // WriteVMX takes a path to a VMX file and contents in the form of a
// map and writes it out. | [
"WriteVMX",
"takes",
"a",
"path",
"to",
"a",
"VMX",
"file",
"and",
"contents",
"in",
"the",
"form",
"of",
"a",
"map",
"and",
"writes",
"it",
"out",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/vmware/common/vmx.go#L82-L97 |
165,193 | hashicorp/packer | template/interpolate/i.go | Render | func Render(v string, ctx *Context) (string, error) {
return (&I{Value: v}).Render(ctx)
} | go | func Render(v string, ctx *Context) (string, error) {
return (&I{Value: v}).Render(ctx)
} | [
"func",
"Render",
"(",
"v",
"string",
",",
"ctx",
"*",
"Context",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"(",
"&",
"I",
"{",
"Value",
":",
"v",
"}",
")",
".",
"Render",
"(",
"ctx",
")",
"\n",
"}"
] | // Render is shorthand for constructing an I and calling Render. | [
"Render",
"is",
"shorthand",
"for",
"constructing",
"an",
"I",
"and",
"calling",
"Render",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/template/interpolate/i.go#L40-L42 |
165,194 | hashicorp/packer | template/interpolate/i.go | Validate | func Validate(v string, ctx *Context) error {
return (&I{Value: v}).Validate(ctx)
} | go | func Validate(v string, ctx *Context) error {
return (&I{Value: v}).Validate(ctx)
} | [
"func",
"Validate",
"(",
"v",
"string",
",",
"ctx",
"*",
"Context",
")",
"error",
"{",
"return",
"(",
"&",
"I",
"{",
"Value",
":",
"v",
"}",
")",
".",
"Validate",
"(",
"ctx",
")",
"\n",
"}"
] | // Validate is shorthand for constructing an I and calling Validate. | [
"Validate",
"is",
"shorthand",
"for",
"constructing",
"an",
"I",
"and",
"calling",
"Validate",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/template/interpolate/i.go#L45-L47 |
165,195 | hashicorp/packer | template/interpolate/i.go | Render | func (i *I) Render(ictx *Context) (string, error) {
tpl, err := i.template(ictx)
if err != nil {
return "", err
}
var result bytes.Buffer
var data interface{}
if ictx != nil {
data = ictx.Data
}
if err := tpl.Execute(&result, data); err != nil {
return "", err
}
return result.String(), nil
} | go | func (i *I) Render(ictx *Context) (string, error) {
tpl, err := i.template(ictx)
if err != nil {
return "", err
}
var result bytes.Buffer
var data interface{}
if ictx != nil {
data = ictx.Data
}
if err := tpl.Execute(&result, data); err != nil {
return "", err
}
return result.String(), nil
} | [
"func",
"(",
"i",
"*",
"I",
")",
"Render",
"(",
"ictx",
"*",
"Context",
")",
"(",
"string",
",",
"error",
")",
"{",
"tpl",
",",
"err",
":=",
"i",
".",
"template",
"(",
"ictx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"var",
"result",
"bytes",
".",
"Buffer",
"\n",
"var",
"data",
"interface",
"{",
"}",
"\n",
"if",
"ictx",
"!=",
"nil",
"{",
"data",
"=",
"ictx",
".",
"Data",
"\n",
"}",
"\n",
"if",
"err",
":=",
"tpl",
".",
"Execute",
"(",
"&",
"result",
",",
"data",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"result",
".",
"String",
"(",
")",
",",
"nil",
"\n",
"}"
] | // Render renders the interpolation with the given context. | [
"Render",
"renders",
"the",
"interpolation",
"with",
"the",
"given",
"context",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/template/interpolate/i.go#L56-L72 |
165,196 | hashicorp/packer | template/interpolate/i.go | Validate | func (i *I) Validate(ctx *Context) error {
_, err := i.template(ctx)
return err
} | go | func (i *I) Validate(ctx *Context) error {
_, err := i.template(ctx)
return err
} | [
"func",
"(",
"i",
"*",
"I",
")",
"Validate",
"(",
"ctx",
"*",
"Context",
")",
"error",
"{",
"_",
",",
"err",
":=",
"i",
".",
"template",
"(",
"ctx",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Validate validates that the template is syntactically valid. | [
"Validate",
"validates",
"that",
"the",
"template",
"is",
"syntactically",
"valid",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/template/interpolate/i.go#L75-L78 |
165,197 | hashicorp/packer | builder/amazon/chroot/step_register_ami.go | buildBaseRegisterOpts | func buildBaseRegisterOpts(config *Config, sourceImage *ec2.Image, rootVolumeSize int64, snapshotID string) *ec2.RegisterImageInput {
var (
mappings []*ec2.BlockDeviceMapping
rootDeviceName string
)
generatingNewBlockDeviceMappings := config.FromScratch || len(config.AMIMappings) > 0
if generatingNewBlockDeviceMappings {
mappings = config.AMIBlockDevices.BuildAMIDevices()
rootDeviceName = config.RootDeviceName
} else {
// If config.FromScratch is false, source image must be set
mappings = sourceImage.BlockDeviceMappings
rootDeviceName = *sourceImage.RootDeviceName
}
newMappings := make([]*ec2.BlockDeviceMapping, len(mappings))
for i, device := range mappings {
newDevice := device
if *newDevice.DeviceName == rootDeviceName {
if newDevice.Ebs != nil {
newDevice.Ebs.SnapshotId = aws.String(snapshotID)
} else {
newDevice.Ebs = &ec2.EbsBlockDevice{SnapshotId: aws.String(snapshotID)}
}
if generatingNewBlockDeviceMappings || rootVolumeSize > *newDevice.Ebs.VolumeSize {
newDevice.Ebs.VolumeSize = aws.Int64(rootVolumeSize)
}
}
// assume working from a snapshot, so we unset the Encrypted field if set,
// otherwise AWS API will return InvalidParameter
if newDevice.Ebs != nil && newDevice.Ebs.Encrypted != nil {
newDevice.Ebs.Encrypted = nil
}
newMappings[i] = newDevice
}
if config.FromScratch {
return &ec2.RegisterImageInput{
Name: &config.AMIName,
Architecture: aws.String(ec2.ArchitectureValuesX8664),
RootDeviceName: aws.String(rootDeviceName),
VirtualizationType: aws.String(config.AMIVirtType),
BlockDeviceMappings: newMappings,
}
}
return buildRegisterOptsFromExistingImage(config, sourceImage, newMappings, rootDeviceName)
} | go | func buildBaseRegisterOpts(config *Config, sourceImage *ec2.Image, rootVolumeSize int64, snapshotID string) *ec2.RegisterImageInput {
var (
mappings []*ec2.BlockDeviceMapping
rootDeviceName string
)
generatingNewBlockDeviceMappings := config.FromScratch || len(config.AMIMappings) > 0
if generatingNewBlockDeviceMappings {
mappings = config.AMIBlockDevices.BuildAMIDevices()
rootDeviceName = config.RootDeviceName
} else {
// If config.FromScratch is false, source image must be set
mappings = sourceImage.BlockDeviceMappings
rootDeviceName = *sourceImage.RootDeviceName
}
newMappings := make([]*ec2.BlockDeviceMapping, len(mappings))
for i, device := range mappings {
newDevice := device
if *newDevice.DeviceName == rootDeviceName {
if newDevice.Ebs != nil {
newDevice.Ebs.SnapshotId = aws.String(snapshotID)
} else {
newDevice.Ebs = &ec2.EbsBlockDevice{SnapshotId: aws.String(snapshotID)}
}
if generatingNewBlockDeviceMappings || rootVolumeSize > *newDevice.Ebs.VolumeSize {
newDevice.Ebs.VolumeSize = aws.Int64(rootVolumeSize)
}
}
// assume working from a snapshot, so we unset the Encrypted field if set,
// otherwise AWS API will return InvalidParameter
if newDevice.Ebs != nil && newDevice.Ebs.Encrypted != nil {
newDevice.Ebs.Encrypted = nil
}
newMappings[i] = newDevice
}
if config.FromScratch {
return &ec2.RegisterImageInput{
Name: &config.AMIName,
Architecture: aws.String(ec2.ArchitectureValuesX8664),
RootDeviceName: aws.String(rootDeviceName),
VirtualizationType: aws.String(config.AMIVirtType),
BlockDeviceMappings: newMappings,
}
}
return buildRegisterOptsFromExistingImage(config, sourceImage, newMappings, rootDeviceName)
} | [
"func",
"buildBaseRegisterOpts",
"(",
"config",
"*",
"Config",
",",
"sourceImage",
"*",
"ec2",
".",
"Image",
",",
"rootVolumeSize",
"int64",
",",
"snapshotID",
"string",
")",
"*",
"ec2",
".",
"RegisterImageInput",
"{",
"var",
"(",
"mappings",
"[",
"]",
"*",
"ec2",
".",
"BlockDeviceMapping",
"\n",
"rootDeviceName",
"string",
"\n",
")",
"\n\n",
"generatingNewBlockDeviceMappings",
":=",
"config",
".",
"FromScratch",
"||",
"len",
"(",
"config",
".",
"AMIMappings",
")",
">",
"0",
"\n",
"if",
"generatingNewBlockDeviceMappings",
"{",
"mappings",
"=",
"config",
".",
"AMIBlockDevices",
".",
"BuildAMIDevices",
"(",
")",
"\n",
"rootDeviceName",
"=",
"config",
".",
"RootDeviceName",
"\n",
"}",
"else",
"{",
"// If config.FromScratch is false, source image must be set",
"mappings",
"=",
"sourceImage",
".",
"BlockDeviceMappings",
"\n",
"rootDeviceName",
"=",
"*",
"sourceImage",
".",
"RootDeviceName",
"\n",
"}",
"\n\n",
"newMappings",
":=",
"make",
"(",
"[",
"]",
"*",
"ec2",
".",
"BlockDeviceMapping",
",",
"len",
"(",
"mappings",
")",
")",
"\n",
"for",
"i",
",",
"device",
":=",
"range",
"mappings",
"{",
"newDevice",
":=",
"device",
"\n",
"if",
"*",
"newDevice",
".",
"DeviceName",
"==",
"rootDeviceName",
"{",
"if",
"newDevice",
".",
"Ebs",
"!=",
"nil",
"{",
"newDevice",
".",
"Ebs",
".",
"SnapshotId",
"=",
"aws",
".",
"String",
"(",
"snapshotID",
")",
"\n",
"}",
"else",
"{",
"newDevice",
".",
"Ebs",
"=",
"&",
"ec2",
".",
"EbsBlockDevice",
"{",
"SnapshotId",
":",
"aws",
".",
"String",
"(",
"snapshotID",
")",
"}",
"\n",
"}",
"\n\n",
"if",
"generatingNewBlockDeviceMappings",
"||",
"rootVolumeSize",
">",
"*",
"newDevice",
".",
"Ebs",
".",
"VolumeSize",
"{",
"newDevice",
".",
"Ebs",
".",
"VolumeSize",
"=",
"aws",
".",
"Int64",
"(",
"rootVolumeSize",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// assume working from a snapshot, so we unset the Encrypted field if set,",
"// otherwise AWS API will return InvalidParameter",
"if",
"newDevice",
".",
"Ebs",
"!=",
"nil",
"&&",
"newDevice",
".",
"Ebs",
".",
"Encrypted",
"!=",
"nil",
"{",
"newDevice",
".",
"Ebs",
".",
"Encrypted",
"=",
"nil",
"\n",
"}",
"\n\n",
"newMappings",
"[",
"i",
"]",
"=",
"newDevice",
"\n",
"}",
"\n\n",
"if",
"config",
".",
"FromScratch",
"{",
"return",
"&",
"ec2",
".",
"RegisterImageInput",
"{",
"Name",
":",
"&",
"config",
".",
"AMIName",
",",
"Architecture",
":",
"aws",
".",
"String",
"(",
"ec2",
".",
"ArchitectureValuesX8664",
")",
",",
"RootDeviceName",
":",
"aws",
".",
"String",
"(",
"rootDeviceName",
")",
",",
"VirtualizationType",
":",
"aws",
".",
"String",
"(",
"config",
".",
"AMIVirtType",
")",
",",
"BlockDeviceMappings",
":",
"newMappings",
",",
"}",
"\n",
"}",
"\n\n",
"return",
"buildRegisterOptsFromExistingImage",
"(",
"config",
",",
"sourceImage",
",",
"newMappings",
",",
"rootDeviceName",
")",
"\n",
"}"
] | // Builds the base register opts with architecture, name, root block device, mappings, virtualizationtype | [
"Builds",
"the",
"base",
"register",
"opts",
"with",
"architecture",
"name",
"root",
"block",
"device",
"mappings",
"virtualizationtype"
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/amazon/chroot/step_register_ami.go#L77-L128 |
165,198 | hashicorp/packer | helper/ssh/ssh.go | FileSigner | func FileSigner(path string) (ssh.Signer, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
keyBytes, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
// We parse the private key on our own first so that we can
// show a nicer error if the private key has a password.
block, _ := pem.Decode(keyBytes)
if block == nil {
return nil, fmt.Errorf(
"Failed to read key '%s': no key found", path)
}
if block.Headers["Proc-Type"] == "4,ENCRYPTED" {
return nil, fmt.Errorf(
"Failed to read key '%s': password protected keys are\n"+
"not supported. Please decrypt the key prior to use.", path)
}
signer, err := ssh.ParsePrivateKey(keyBytes)
if err != nil {
return nil, fmt.Errorf("Error setting up SSH config: %s", err)
}
return signer, nil
} | go | func FileSigner(path string) (ssh.Signer, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
keyBytes, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
// We parse the private key on our own first so that we can
// show a nicer error if the private key has a password.
block, _ := pem.Decode(keyBytes)
if block == nil {
return nil, fmt.Errorf(
"Failed to read key '%s': no key found", path)
}
if block.Headers["Proc-Type"] == "4,ENCRYPTED" {
return nil, fmt.Errorf(
"Failed to read key '%s': password protected keys are\n"+
"not supported. Please decrypt the key prior to use.", path)
}
signer, err := ssh.ParsePrivateKey(keyBytes)
if err != nil {
return nil, fmt.Errorf("Error setting up SSH config: %s", err)
}
return signer, nil
} | [
"func",
"FileSigner",
"(",
"path",
"string",
")",
"(",
"ssh",
".",
"Signer",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n\n",
"keyBytes",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"f",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// We parse the private key on our own first so that we can",
"// show a nicer error if the private key has a password.",
"block",
",",
"_",
":=",
"pem",
".",
"Decode",
"(",
"keyBytes",
")",
"\n",
"if",
"block",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"path",
")",
"\n",
"}",
"\n",
"if",
"block",
".",
"Headers",
"[",
"\"",
"\"",
"]",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\n",
"\"",
"+",
"\"",
"\"",
",",
"path",
")",
"\n",
"}",
"\n\n",
"signer",
",",
"err",
":=",
"ssh",
".",
"ParsePrivateKey",
"(",
"keyBytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"signer",
",",
"nil",
"\n",
"}"
] | // FileSigner returns an ssh.Signer for a key file. | [
"FileSigner",
"returns",
"an",
"ssh",
".",
"Signer",
"for",
"a",
"key",
"file",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/helper/ssh/ssh.go#L13-L44 |
165,199 | hashicorp/packer | builder/googlecompute/step_create_instance.go | Run | func (s *StepCreateInstance) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
c := state.Get("config").(*Config)
d := state.Get("driver").(Driver)
ui := state.Get("ui").(packer.Ui)
sourceImage, err := getImage(c, d)
if err != nil {
err := fmt.Errorf("Error getting source image for instance creation: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
ui.Say(fmt.Sprintf("Using image: %s", sourceImage.Name))
if sourceImage.IsWindows() && c.Comm.Type == "winrm" && c.Comm.WinRMPassword == "" {
state.Put("create_windows_password", true)
}
ui.Say("Creating instance...")
name := c.InstanceName
var errCh <-chan error
var metadata map[string]string
metadata, err = c.createInstanceMetadata(sourceImage, string(c.Comm.SSHPublicKey))
errCh, err = d.RunInstance(&InstanceConfig{
AcceleratorType: c.AcceleratorType,
AcceleratorCount: c.AcceleratorCount,
Address: c.Address,
Description: "New instance created by Packer",
DisableDefaultServiceAccount: c.DisableDefaultServiceAccount,
DiskSizeGb: c.DiskSizeGb,
DiskType: c.DiskType,
Image: sourceImage,
Labels: c.Labels,
MachineType: c.MachineType,
Metadata: metadata,
MinCpuPlatform: c.MinCpuPlatform,
Name: name,
Network: c.Network,
NetworkProjectId: c.NetworkProjectId,
OmitExternalIP: c.OmitExternalIP,
OnHostMaintenance: c.OnHostMaintenance,
Preemptible: c.Preemptible,
Region: c.Region,
ServiceAccountEmail: c.ServiceAccountEmail,
Scopes: c.Scopes,
Subnetwork: c.Subnetwork,
Tags: c.Tags,
Zone: c.Zone,
})
if err == nil {
ui.Message("Waiting for creation operation to complete...")
select {
case err = <-errCh:
case <-time.After(c.stateTimeout):
err = errors.New("time out while waiting for instance to create")
}
}
if err != nil {
err := fmt.Errorf("Error creating instance: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
ui.Message("Instance has been created!")
if s.Debug {
if name != "" {
ui.Message(fmt.Sprintf("Instance: %s started in %s", name, c.Zone))
}
}
// Things succeeded, store the name so we can remove it later
state.Put("instance_name", name)
return multistep.ActionContinue
} | go | func (s *StepCreateInstance) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
c := state.Get("config").(*Config)
d := state.Get("driver").(Driver)
ui := state.Get("ui").(packer.Ui)
sourceImage, err := getImage(c, d)
if err != nil {
err := fmt.Errorf("Error getting source image for instance creation: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
ui.Say(fmt.Sprintf("Using image: %s", sourceImage.Name))
if sourceImage.IsWindows() && c.Comm.Type == "winrm" && c.Comm.WinRMPassword == "" {
state.Put("create_windows_password", true)
}
ui.Say("Creating instance...")
name := c.InstanceName
var errCh <-chan error
var metadata map[string]string
metadata, err = c.createInstanceMetadata(sourceImage, string(c.Comm.SSHPublicKey))
errCh, err = d.RunInstance(&InstanceConfig{
AcceleratorType: c.AcceleratorType,
AcceleratorCount: c.AcceleratorCount,
Address: c.Address,
Description: "New instance created by Packer",
DisableDefaultServiceAccount: c.DisableDefaultServiceAccount,
DiskSizeGb: c.DiskSizeGb,
DiskType: c.DiskType,
Image: sourceImage,
Labels: c.Labels,
MachineType: c.MachineType,
Metadata: metadata,
MinCpuPlatform: c.MinCpuPlatform,
Name: name,
Network: c.Network,
NetworkProjectId: c.NetworkProjectId,
OmitExternalIP: c.OmitExternalIP,
OnHostMaintenance: c.OnHostMaintenance,
Preemptible: c.Preemptible,
Region: c.Region,
ServiceAccountEmail: c.ServiceAccountEmail,
Scopes: c.Scopes,
Subnetwork: c.Subnetwork,
Tags: c.Tags,
Zone: c.Zone,
})
if err == nil {
ui.Message("Waiting for creation operation to complete...")
select {
case err = <-errCh:
case <-time.After(c.stateTimeout):
err = errors.New("time out while waiting for instance to create")
}
}
if err != nil {
err := fmt.Errorf("Error creating instance: %s", err)
state.Put("error", err)
ui.Error(err.Error())
return multistep.ActionHalt
}
ui.Message("Instance has been created!")
if s.Debug {
if name != "" {
ui.Message(fmt.Sprintf("Instance: %s started in %s", name, c.Zone))
}
}
// Things succeeded, store the name so we can remove it later
state.Put("instance_name", name)
return multistep.ActionContinue
} | [
"func",
"(",
"s",
"*",
"StepCreateInstance",
")",
"Run",
"(",
"ctx",
"context",
".",
"Context",
",",
"state",
"multistep",
".",
"StateBag",
")",
"multistep",
".",
"StepAction",
"{",
"c",
":=",
"state",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"*",
"Config",
")",
"\n",
"d",
":=",
"state",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"Driver",
")",
"\n\n",
"ui",
":=",
"state",
".",
"Get",
"(",
"\"",
"\"",
")",
".",
"(",
"packer",
".",
"Ui",
")",
"\n\n",
"sourceImage",
",",
"err",
":=",
"getImage",
"(",
"c",
",",
"d",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"err",
":=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"state",
".",
"Put",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"ui",
".",
"Error",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"multistep",
".",
"ActionHalt",
"\n",
"}",
"\n\n",
"ui",
".",
"Say",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"sourceImage",
".",
"Name",
")",
")",
"\n\n",
"if",
"sourceImage",
".",
"IsWindows",
"(",
")",
"&&",
"c",
".",
"Comm",
".",
"Type",
"==",
"\"",
"\"",
"&&",
"c",
".",
"Comm",
".",
"WinRMPassword",
"==",
"\"",
"\"",
"{",
"state",
".",
"Put",
"(",
"\"",
"\"",
",",
"true",
")",
"\n",
"}",
"\n\n",
"ui",
".",
"Say",
"(",
"\"",
"\"",
")",
"\n",
"name",
":=",
"c",
".",
"InstanceName",
"\n\n",
"var",
"errCh",
"<-",
"chan",
"error",
"\n",
"var",
"metadata",
"map",
"[",
"string",
"]",
"string",
"\n",
"metadata",
",",
"err",
"=",
"c",
".",
"createInstanceMetadata",
"(",
"sourceImage",
",",
"string",
"(",
"c",
".",
"Comm",
".",
"SSHPublicKey",
")",
")",
"\n",
"errCh",
",",
"err",
"=",
"d",
".",
"RunInstance",
"(",
"&",
"InstanceConfig",
"{",
"AcceleratorType",
":",
"c",
".",
"AcceleratorType",
",",
"AcceleratorCount",
":",
"c",
".",
"AcceleratorCount",
",",
"Address",
":",
"c",
".",
"Address",
",",
"Description",
":",
"\"",
"\"",
",",
"DisableDefaultServiceAccount",
":",
"c",
".",
"DisableDefaultServiceAccount",
",",
"DiskSizeGb",
":",
"c",
".",
"DiskSizeGb",
",",
"DiskType",
":",
"c",
".",
"DiskType",
",",
"Image",
":",
"sourceImage",
",",
"Labels",
":",
"c",
".",
"Labels",
",",
"MachineType",
":",
"c",
".",
"MachineType",
",",
"Metadata",
":",
"metadata",
",",
"MinCpuPlatform",
":",
"c",
".",
"MinCpuPlatform",
",",
"Name",
":",
"name",
",",
"Network",
":",
"c",
".",
"Network",
",",
"NetworkProjectId",
":",
"c",
".",
"NetworkProjectId",
",",
"OmitExternalIP",
":",
"c",
".",
"OmitExternalIP",
",",
"OnHostMaintenance",
":",
"c",
".",
"OnHostMaintenance",
",",
"Preemptible",
":",
"c",
".",
"Preemptible",
",",
"Region",
":",
"c",
".",
"Region",
",",
"ServiceAccountEmail",
":",
"c",
".",
"ServiceAccountEmail",
",",
"Scopes",
":",
"c",
".",
"Scopes",
",",
"Subnetwork",
":",
"c",
".",
"Subnetwork",
",",
"Tags",
":",
"c",
".",
"Tags",
",",
"Zone",
":",
"c",
".",
"Zone",
",",
"}",
")",
"\n\n",
"if",
"err",
"==",
"nil",
"{",
"ui",
".",
"Message",
"(",
"\"",
"\"",
")",
"\n",
"select",
"{",
"case",
"err",
"=",
"<-",
"errCh",
":",
"case",
"<-",
"time",
".",
"After",
"(",
"c",
".",
"stateTimeout",
")",
":",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"err",
":=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"state",
".",
"Put",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"ui",
".",
"Error",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"multistep",
".",
"ActionHalt",
"\n",
"}",
"\n\n",
"ui",
".",
"Message",
"(",
"\"",
"\"",
")",
"\n\n",
"if",
"s",
".",
"Debug",
"{",
"if",
"name",
"!=",
"\"",
"\"",
"{",
"ui",
".",
"Message",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"name",
",",
"c",
".",
"Zone",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Things succeeded, store the name so we can remove it later",
"state",
".",
"Put",
"(",
"\"",
"\"",
",",
"name",
")",
"\n\n",
"return",
"multistep",
".",
"ActionContinue",
"\n",
"}"
] | // Run executes the Packer build step that creates a GCE instance. | [
"Run",
"executes",
"the",
"Packer",
"build",
"step",
"that",
"creates",
"a",
"GCE",
"instance",
"."
] | d343852c15da050ee3ad039cc4cadfbf7f9b1759 | https://github.com/hashicorp/packer/blob/d343852c15da050ee3ad039cc4cadfbf7f9b1759/builder/googlecompute/step_create_instance.go#L76-L157 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.