本文整理汇总了Golang中github.com/docker/docker/builder/dockerfile/parser.Parse函数的典型用法代码示例。如果您正苦于以下问题:Golang Parse函数的具体用法?Golang Parse怎么用?Golang Parse使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Parse函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestReplaceLastFrom
func TestReplaceLastFrom(t *testing.T) {
tests := []struct {
original string
image string
want string
}{
{
original: `# no FROM instruction`,
image: "centos",
want: ``,
},
{
original: `FROM scratch
# FROM busybox
RUN echo "hello world"
`,
image: "centos",
want: `FROM centos
RUN echo "hello world"
`,
},
{
original: `FROM scratch
FROM busybox
RUN echo "hello world"
`,
image: "centos",
want: `FROM scratch
FROM centos
RUN echo "hello world"
`,
},
}
for i, test := range tests {
got, err := parser.Parse(strings.NewReader(test.original))
if err != nil {
t.Errorf("test[%d]: %v", i, err)
continue
}
want, err := parser.Parse(strings.NewReader(test.want))
if err != nil {
t.Errorf("test[%d]: %v", i, err)
continue
}
replaceLastFrom(got, test.image)
if !bytes.Equal(dockerfile.ParseTreeToDockerfile(got), dockerfile.ParseTreeToDockerfile(want)) {
t.Errorf("test[%d]: replaceLastFrom(node, %+v) = %+v; want %+v", i, test.image, got, want)
t.Logf("resulting Dockerfile:\n%s", dockerfile.ParseTreeToDockerfile(got))
}
}
}
示例2: FromImage
// FromImage updates the builder to use the provided image (resetting RunConfig
// and recording the image environment), and updates the node with any ONBUILD
// statements extracted from the parent image.
func (b *Builder) FromImage(image *docker.Image, node *parser.Node) error {
SplitChildren(node, command.From)
b.RunConfig = *image.Config
b.Env = b.RunConfig.Env
b.RunConfig.Env = nil
// Check to see if we have a default PATH, note that windows won't
// have one as its set by HCS
if runtime.GOOS != "windows" && !hasEnvName(b.Env, "PATH") {
b.RunConfig.Env = append(b.RunConfig.Env, "PATH="+defaultPathEnv)
}
// Join the image onbuild statements into node
if image.Config == nil || len(image.Config.OnBuild) == 0 {
return nil
}
extra, err := parser.Parse(bytes.NewBufferString(strings.Join(image.Config.OnBuild, "\n")))
if err != nil {
return err
}
for _, child := range extra.Children {
switch strings.ToUpper(child.Value) {
case "ONBUILD":
return fmt.Errorf("Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed")
case "MAINTAINER", "FROM":
return fmt.Errorf("%s isn't allowed as an ONBUILD trigger", child.Value)
}
}
node.Children = append(extra.Children, node.Children...)
// Since we've processed the OnBuild statements, clear them from the runconfig state.
b.RunConfig.OnBuild = nil
return nil
}
示例3: NewBuilder
// NewBuilder creates a new Dockerfile builder from an optional dockerfile and a Config.
// If dockerfile is nil, the Dockerfile specified by Config.DockerfileName,
// will be read from the Context passed to Build().
func NewBuilder(clientCtx context.Context, config *types.ImageBuildOptions, backend builder.Backend, buildContext builder.Context, dockerfile io.ReadCloser) (b *Builder, err error) {
if config == nil {
config = new(types.ImageBuildOptions)
}
if config.BuildArgs == nil {
config.BuildArgs = make(map[string]string)
}
ctx, cancel := context.WithCancel(clientCtx)
b = &Builder{
clientCtx: ctx,
cancel: cancel,
options: config,
Stdout: os.Stdout,
Stderr: os.Stderr,
docker: backend,
context: buildContext,
runConfig: new(container.Config),
tmpContainers: map[string]struct{}{},
id: stringid.GenerateNonCryptoID(),
allowedBuildArgs: make(map[string]bool),
}
if dockerfile != nil {
b.dockerfile, err = parser.Parse(dockerfile)
if err != nil {
return nil, err
}
}
return b, nil
}
示例4: BuildFromConfig
// BuildFromConfig builds directly from `changes`, treating it as if it were the contents of a Dockerfile
// It will:
// - Call parse.Parse() to get an AST root for the concatenated Dockerfile entries.
// - Do build by calling builder.dispatch() to call all entries' handling routines
//
// BuildFromConfig is used by the /commit endpoint, with the changes
// coming from the query parameter of the same name.
//
// TODO: Remove?
func BuildFromConfig(config *container.Config, changes []string) (*container.Config, error) {
ast, err := parser.Parse(bytes.NewBufferString(strings.Join(changes, "\n")))
if err != nil {
return nil, err
}
// ensure that the commands are valid
for _, n := range ast.Children {
if !validCommitCommands[n.Value] {
return nil, fmt.Errorf("%s is not a valid change command", n.Value)
}
}
b, err := NewBuilder(context.Background(), nil, nil, nil, nil)
if err != nil {
return nil, err
}
b.runConfig = config
b.Stdout = ioutil.Discard
b.Stderr = ioutil.Discard
b.disableCommit = true
for i, n := range ast.Children {
if err := b.dispatch(i, n); err != nil {
return nil, err
}
}
return b.runConfig, nil
}
示例5: main
func main() {
var f *os.File
var err error
if len(os.Args) < 2 {
fmt.Println("please supply filename(s)")
os.Exit(1)
}
for _, fn := range os.Args[1:] {
f, err = os.Open(fn)
if err != nil {
panic(err)
}
d := parser.Directive{LookingForDirectives: true}
parser.SetEscapeToken(parser.DefaultEscapeToken, &d)
ast, err := parser.Parse(f, &d)
if err != nil {
panic(err)
} else {
fmt.Println(ast.Dump())
}
}
}
示例6: TestNextValuesOnbuild
// TestNextValuesOnbuild tests calling nextValues with ONBUILD instructions as
// input.
func TestNextValuesOnbuild(t *testing.T) {
testCases := map[string][]string{
`ONBUILD ADD . /app/src`: {".", "/app/src"},
`ONBUILD RUN echo "Hello universe!"`: {`echo "Hello universe!"`},
}
for original, want := range testCases {
node, err := parser.Parse(strings.NewReader(original))
if err != nil {
t.Fatalf("parse error: %s: %v", original, err)
}
if len(node.Children) != 1 {
t.Fatalf("unexpected number of children in test case: %s", original)
}
// The Docker parser always wrap instructions in a root node.
// Look at the node representing the instruction following
// ONBUILD, the one and only one in each test case.
node = node.Children[0].Next
if node == nil || len(node.Children) != 1 {
t.Fatalf("unexpected number of children in ONBUILD instruction of test case: %s", original)
}
node = node.Children[0]
if got := nextValues(node); !reflect.DeepEqual(got, want) {
t.Errorf("nextValues(%+v) = %#v; want %#v", node, got, want)
}
}
}
示例7: NewBuilder
// NewBuilder creates a new Dockerfile builder from an optional dockerfile and a Config.
// If dockerfile is nil, the Dockerfile specified by Config.DockerfileName,
// will be read from the Context passed to Build().
func NewBuilder(config *Config, docker builder.Backend, context builder.Context, dockerfile io.ReadCloser) (b *Builder, err error) {
if config == nil {
config = new(Config)
}
if config.BuildArgs == nil {
config.BuildArgs = make(map[string]string)
}
b = &Builder{
Config: config,
Stdout: os.Stdout,
Stderr: os.Stderr,
docker: docker,
context: context,
runConfig: new(container.Config),
tmpContainers: map[string]struct{}{},
cancelled: make(chan struct{}),
id: stringid.GenerateNonCryptoID(),
allowedBuildArgs: make(map[string]bool),
}
if dockerfile != nil {
b.dockerfile, err = parser.Parse(dockerfile)
if err != nil {
return nil, err
}
}
return b, nil
}
示例8: TestRun
func TestRun(t *testing.T) {
f, err := os.Open("dockerclient/testdata/Dockerfile.add")
if err != nil {
t.Fatal(err)
}
node, err := parser.Parse(f)
if err != nil {
t.Fatal(err)
}
b := NewBuilder()
from, err := b.From(node)
if err != nil {
t.Fatal(err)
}
if from != "busybox" {
t.Fatalf("unexpected from: %s", from)
}
for _, child := range node.Children {
step := b.Step()
if err := step.Resolve(child); err != nil {
t.Fatal(err)
}
if err := b.Run(step, LogExecutor); err != nil {
t.Fatal(err)
}
}
t.Logf("config: %#v", b.Config())
t.Logf(node.Dump())
}
示例9: get_label_value
func get_label_value(dockerfile_name string, label_name string) (label_value string, err error) {
f, err := os.Open(dockerfile_name)
if err != nil {
return
}
defer f.Close()
ast, err := parser.Parse(f)
if err != nil {
return
}
// root node only has children and represents the entire file
for _, n := range ast.Children {
if n.Value == "label" {
// found a label statement, see if it has our label
for nn := n.Next; nn != nil; nn = nn.Next.Next {
if nn.Value == label_name {
nn = nn.Next
label_value, err = strconv.Unquote(strings.Replace(nn.Value, "$ {", "${", -1))
return
}
}
}
}
return "", nil
}
示例10: GuessFromDockerfile
//GuessFromDockerfile will guess some information from a Dockerfile file
//guessing means to get all the LABELs and process them somehow
func GuessFromDockerfile(filename string) (map[string]string, string, error) {
dockerfileContent, err := ioutil.ReadFile(filename)
if err != nil {
jww.ERROR.Println("failed to read the Dockerfile")
return nil, "", err
}
// lets parse the Dockerfile
ast, err := parser.Parse(bytes.NewReader(dockerfileContent))
if err != nil {
jww.FATAL.Println("Dockerfile parse error")
return nil, "", err
}
var result map[string]string
result = make(map[string]string)
for _, s := range guessFromLabels(ast) {
result[strings.Replace(s.Key, "\"", "", -1)] = strings.Replace(s.Value, "\"", "", -1)
}
for key, value := range result {
jww.DEBUG.Printf("result: LABEL: %s;\t VALUE: %s\n", key, value)
}
// if --experimental is true, we print all snippets to STDOUT
resultingNulecule := ""
if viper.GetBool("Experimental") {
resultingNulecule = snippetsFromLabelsMap(result)
}
return result, resultingNulecule, err
}
示例11: TestNextValues
// TestNextValues tests calling nextValues with multiple valid combinations of
// input.
func TestNextValues(t *testing.T) {
testCases := map[string][]string{
`FROM busybox:latest`: {"busybox:latest"},
`MAINTAINER [email protected]`: {"[email protected]"},
`LABEL version=1.0`: {"version", "1.0"},
`EXPOSE 8080`: {"8080"},
`VOLUME /var/run/www`: {"/var/run/www"},
`ENV PATH=/bin`: {"PATH", "/bin"},
`ADD file /home/`: {"file", "/home/"},
`COPY dir/ /tmp/`: {"dir/", "/tmp/"},
`RUN echo "Hello world!"`: {`echo "Hello world!"`},
`ENTRYPOINT /bin/sh`: {"/bin/sh"},
`CMD ["-c", "env"]`: {"-c", "env"},
`USER 1001`: {"1001"},
`WORKDIR /home`: {"/home"},
}
for original, want := range testCases {
node, err := parser.Parse(strings.NewReader(original))
if err != nil {
t.Fatalf("parse error: %s: %v", original, err)
}
if len(node.Children) != 1 {
t.Fatalf("unexpected number of children in test case: %s", original)
}
// The Docker parser always wrap instructions in a root node.
// Look at the node representing the first instruction, the one
// and only one in each test case.
node = node.Children[0]
if got := nextValues(node); !reflect.DeepEqual(got, want) {
t.Errorf("nextValues(%+v) = %#v; want %#v", node, got, want)
}
}
}
示例12: parseDockerfile
func (b *Builder) parseDockerfile() error {
f, err := b.context.Open(b.options.Dockerfile)
if err != nil {
if os.IsNotExist(err) {
return fmt.Errorf("Cannot locate specified Dockerfile: %s", b.options.Dockerfile)
}
return err
}
defer f.Close()
if f, ok := f.(*os.File); ok {
// ignoring error because Open already succeeded
fi, err := f.Stat()
if err != nil {
return fmt.Errorf("Unexpected error reading Dockerfile: %v", err)
}
if fi.Size() == 0 {
return fmt.Errorf("The Dockerfile (%s) cannot be empty", b.options.Dockerfile)
}
}
b.dockerfile, err = parser.Parse(f, &b.directive)
if err != nil {
return err
}
return nil
}
示例13: executeTestCase
func executeTestCase(t *testing.T, testCase dispatchTestCase) {
contextDir, cleanup := createTestTempDir(t, "", "builder-dockerfile-test")
defer cleanup()
for filename, content := range testCase.files {
createTestTempFile(t, contextDir, filename, content, 0777)
}
tarStream, err := archive.Tar(contextDir, archive.Uncompressed)
if err != nil {
t.Fatalf("Error when creating tar stream: %s", err)
}
defer func() {
if err = tarStream.Close(); err != nil {
t.Fatalf("Error when closing tar stream: %s", err)
}
}()
context, err := builder.MakeTarSumContext(tarStream)
if err != nil {
t.Fatalf("Error when creating tar context: %s", err)
}
defer func() {
if err = context.Close(); err != nil {
t.Fatalf("Error when closing tar context: %s", err)
}
}()
r := strings.NewReader(testCase.dockerfile)
d := parser.Directive{}
parser.SetEscapeToken(parser.DefaultEscapeToken, &d)
n, err := parser.Parse(r, &d)
if err != nil {
t.Fatalf("Error when parsing Dockerfile: %s", err)
}
config := &container.Config{}
options := &types.ImageBuildOptions{}
b := &Builder{runConfig: config, options: options, Stdout: ioutil.Discard, context: context}
err = b.dispatch(0, n.Children[0])
if err == nil {
t.Fatalf("No error when executing test %s", testCase.name)
}
if !strings.Contains(err.Error(), testCase.expectedError) {
t.Fatalf("Wrong error message. Should be \"%s\". Got \"%s\"", testCase.expectedError, err.Error())
}
}
示例14: NewDockerfile
func NewDockerfile(contents string) (Dockerfile, error) {
if len(contents) == 0 {
return nil, errors.New("Dockerfile is empty")
}
node, err := parser.Parse(strings.NewReader(contents))
if err != nil {
return nil, err
}
return dockerfileContents{node, contents}, nil
}
示例15: DockerfileRead
// DockerfileRead reads a Dockerfile as io.Reader
func DockerfileRead(input io.Reader) (*Dockerfile, error) {
dockerfile := Dockerfile{}
root, err := parser.Parse(input)
if err != nil {
return nil, err
}
dockerfile.root = root
return &dockerfile, nil
}