Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SampleGen: write a string or bytes field of the response object to a local file #150

Merged
merged 5 commits into from
Jul 18, 2019
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions cmd/gen-go-sample/gapic.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,10 @@ type GAPICSample struct {
}

type OutputSpec struct {
Define string
Print []string
Loop *LoopSpec
Define string
Print []string
Loop *LoopSpec
WriteFile *WriteFileSpec
}

type LoopSpec struct {
Expand All @@ -76,6 +77,11 @@ type LoopSpec struct {
Body []OutputSpec
}

type WriteFileSpec struct {
Contents string
FileName []string
}

type ResourceName struct {
EntityName string `yaml:"entity_name"`
NamePattern string `yaml:"name_pattern"`
Expand Down
29 changes: 29 additions & 0 deletions cmd/gen-go-sample/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,35 @@ func TestMapOut(t *testing.T) {
compare(t, g, filepath.Join("testdata", "sample_map_out.want"))
}

func TestWriteFile(t *testing.T) {
t.Parallel()

g := initTestGenerator()
vs := SampleValueSet{
ID: "my_value_set",
OnSuccess: []OutputSpec{
{
WriteFile: &WriteFileSpec{
FileName: []string{"my_bob.mp3"},
Contents: "$resp.data_bob",
},
},
{
WriteFile: &WriteFileSpec{
FileName: []string{"my_alice_%s.mp3", "$resp.a"},
Contents: "$resp.b",
},
},
},
}

if err := g.genSample("foo.FooService", GAPICMethod{Name: "UnaryMethod"}, "awesome_region", vs); err != nil {
t.Fatal(err)
}
compare(t, g, filepath.Join("testdata", "sample_write_file.want"))

}

func initTestGenerator() *generator {
eType := &descriptor.EnumDescriptorProto{
Name: proto.String("EType"),
Expand Down
70 changes: 59 additions & 11 deletions cmd/gen-go-sample/out.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,11 @@
package main

import (
"fmt"
"strings"
"text/scanner"

"github.com/golang/protobuf/protoc-gen-go/descriptor"
"github.com/googleapis/gapic-generator-go/internal/errors"
"github.com/googleapis/gapic-generator-go/internal/pbinfo"
)
Expand Down Expand Up @@ -95,6 +97,10 @@ func writeOutputSpec(out OutputSpec, st *symTab, gen *generator) error {
err = writeMap(l, st, gen)
}
}
if dp := out.WriteFile; dp != nil {
used++
err = writeDump(dp.FileName[0], dp.FileName[1:], dp.Contents, st, gen)
}

if used == 0 {
return errors.E(nil, "OutputSpec not defined")
Expand Down Expand Up @@ -133,24 +139,50 @@ func writeDefine(txt string, st *symTab, gen *generator) error {
var fmtStrReplacer = strings.NewReplacer("%%", "%%", "%s", "%v")

func writePrint(pFmt string, pArgs []string, st *symTab, gen *generator) error {
var sb strings.Builder
for _, arg := range pArgs {
sb.WriteString(", ")

sc, report := initScanner(arg)
path, _, err := writePath(sc, st, gen.descInfo)
if err != nil {
return report(err)
}
sb.WriteString(path)
argList, err := writePaths(pArgs, st, gen)
if err != nil {
return err
}

gen.pt.Printf("fmt.Printf(%q%s)", fmtStrReplacer.Replace(pFmt)+"\n", sb.String())
gen.pt.Printf("fmt.Printf(%q%s)", fmtStrReplacer.Replace(pFmt)+"\n", argList)
gen.imports[pbinfo.ImportSpec{Path: "fmt"}] = true

return nil
}

func writeDump(fnFmt string, fnArgs []string, contPath string, st *symTab, gen *generator) error {
argList, err := writePaths(fnArgs, st, gen)
if err != nil {
return err
}

fn := fnFmt
if len(argList) != 0 {
fn = fmt.Sprintf("fmt.Sprintf(%q%s)", fmtStrReplacer.Replace(fnFmt), argList)
}

sc, report := initScanner(contPath)
cont, typ, err := writePath(sc, st, gen.descInfo)

noahdietz marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return report(err)
}

if typ.prim == descriptor.FieldDescriptorProto_TYPE_BYTES {
gen.pt.Printf("if err := ioutil.WriteFile(%s, %s, 0644); err != nil {\n", fn, cont)
} else if typ.prim == descriptor.FieldDescriptorProto_TYPE_STRING && !typ.repeated {
gen.pt.Printf("if err := ioutil.WriteFile(%s, bytes[](%s), 0644), err != nil {\n", fn, cont)
} else {
return errors.E(nil, "illegal type for file contents, expecting string or bytes, got %v", typ)
}

gen.pt.Printf(" return err")
gen.pt.Printf("}")

gen.imports[pbinfo.ImportSpec{Path: "ioutil"}] = true
return nil
}

func writeLoop(l *LoopSpec, st *symTab, gen *generator) error {
if l.Variable == "" {
return errors.E(nil, "variable not specified for looping over arrays")
Expand Down Expand Up @@ -260,3 +292,19 @@ func writePath(sc *scanner.Scanner, st *symTab, info pbinfo.Info) (string, initT

return sb.String(), itLeaf.typ, nil
}

// writePaths translates each path into go field accessors, and joins them by commas.
func writePaths(args []string, st *symTab, gen *generator) (string, error) {
var sb strings.Builder
for _, arg := range args {
sb.WriteString(", ")

sc, report := initScanner(arg)
path, _, err := writePath(sc, st, gen.descInfo)
if err != nil {
return "", report(err)
}
sb.WriteString(path)
}
return sb.String(), nil
}
61 changes: 61 additions & 0 deletions cmd/gen-go-sample/testdata/sample_write_file.want
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// Copyright 2018 Google LLC
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2019

//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Code generated by protoc-gen-go_gapic. DO NOT EDIT.

package main
import(
"context"
"flag"
"fmt"
"ioutil"
"log"

foo "path.to/client/foo"
foopb "path.to/pb/foo"
)
// [START awesome_region]

func sampleUnaryMethod() error {
ctx := context.Background()
c, err := foo.NewClient(ctx)
if err != nil {
return err
}

req := &foopb.InputType{
}
resp, err := c.UnaryMethod(ctx, req)
if err != nil {
return err
}

if err := ioutil.WriteFile(my_bob.mp3, resp.GetDataBob(), 0644); err != nil {
noahdietz marked this conversation as resolved.
Show resolved Hide resolved
return err
}
if err := ioutil.WriteFile(fmt.Sprintf("my_alice_%v.mp3", resp.GetA()), bytes[](resp.GetB()), 0644), err != nil {
return err
}
return nil
}

// [END awesome_region]

func main() {
flag.Parse()
if err := sampleUnaryMethod(); err != nil {
log.Fatal(err)
}
}