Skip to content
This repository has been archived by the owner on May 26, 2023. It is now read-only.

Commit

Permalink
fix working directory and variable parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
Tim Schrodi committed Mar 5, 2021
1 parent eeda025 commit e5444eb
Show file tree
Hide file tree
Showing 9 changed files with 69 additions and 74 deletions.
10 changes: 5 additions & 5 deletions pkg/commands/componentarchive/componentreferences/add.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package componentreferences
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
Expand Down Expand Up @@ -133,13 +134,12 @@ func (o *Options) Run(ctx context.Context, log logr.Logger, fs vfs.FileSystem) e
}

func (o *Options) Complete(args []string) error {
if len(args) != 0 {
o.BuilderOptions.ComponentArchivePath = args[0]
args = o.TemplateOptions.Parse(args)
if len(args) == 0 {
return errors.New("at least a component archive path argument has to be defined")
}
o.BuilderOptions.ComponentArchivePath = args[0]
o.BuilderOptions.Default()
if err := o.TemplateOptions.Complete(args); err != nil {
return err
}

if len(args) > 1 {
o.ComponentReferenceObjectPaths = append(o.ComponentReferenceObjectPaths, args[1:]...)
Expand Down
13 changes: 12 additions & 1 deletion pkg/commands/componentarchive/input/input.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,18 @@ func (input *BlobInput) SetMediaTypeIfNotDefined(mediaType string) {
func (input *BlobInput) Read(fs vfs.FileSystem, inputFilePath string) (*BlobOutput, error) {
inputPath := input.Path
if !filepath.IsAbs(input.Path) {
inputPath = filepath.Join(filepath.Dir(inputFilePath), input.Path)
var wd string
if len(inputFilePath) == 0 {
// default to working directory if now input filepath is given
var err error
wd, err = os.Getwd()
if err != nil {
return nil, fmt.Errorf("unable to read current working directory: %w", err)
}
} else {
wd = filepath.Dir(inputFilePath)
}
inputPath = filepath.Join(wd, input.Path)
}
inputInfo, err := fs.Stat(inputPath)
if err != nil {
Expand Down
35 changes: 15 additions & 20 deletions pkg/commands/componentarchive/resources/add.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package resources
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
Expand Down Expand Up @@ -64,6 +65,7 @@ func NewAddCommand(ctx context.Context) *cobra.Command {
opts := &Options{}
cmd := &cobra.Command{
Use: "add [component archive path] [resource-path]...",
Args: cobra.MinimumNArgs(1),
Short: "Adds a resource to an component archive",
Long: fmt.Sprintf(`
add generates resources from a resource template and adds it to the given component descriptor in the component archive.
Expand Down Expand Up @@ -186,19 +188,15 @@ func (o *Options) Run(ctx context.Context, log logr.Logger, fs vfs.FileSystem) e
}

func (o *Options) Complete(args []string) error {
if len(args) != 0 {
o.BuilderOptions.ComponentArchivePath = args[0]
}
o.BuilderOptions.Default()
args = o.TemplateOptions.Parse(args)

if err := o.TemplateOptions.Complete(args); err != nil {
return err
if len(args) == 0 {
return errors.New("at least a component archive path argument has to be defined")
}
o.BuilderOptions.ComponentArchivePath = args[0]
o.BuilderOptions.Default()

// parse input files
if len(args) > 1 {
o.ResourceObjectPaths = append(o.ResourceObjectPaths, args[1:]...)
}
o.ResourceObjectPaths = append(o.ResourceObjectPaths, args[1:]...)
if len(o.ResourceObjectPath) != 0 {
o.ResourceObjectPaths = append(o.ResourceObjectPaths, o.ResourceObjectPath)
}
Expand All @@ -218,10 +216,6 @@ func (o *Options) AddFlags(fs *pflag.FlagSet) {
}

func (o *Options) generateResources(log logr.Logger, fs vfs.FileSystem, cd *cdv2.ComponentDescriptor) ([]InternalResourceOptions, error) {
wd, err := os.Getwd()
if err != nil {
return nil, fmt.Errorf("unable to get current working directory: %w", err)
}
if len(o.ResourceObjectPaths) == 0 {
// try to read from stdin if no resources are defined
resources := make([]InternalResourceOptions, 0)
Expand All @@ -231,11 +225,11 @@ func (o *Options) generateResources(log logr.Logger, fs vfs.FileSystem, cd *cdv2
return nil, nil
}
if (stdinInfo.Mode()&os.ModeNamedPipe != 0) || stdinInfo.Size() != 0 {
stdinResources, err := o.generateResourcesFromReader(cd, os.Stdin)
stdinResources, err := o.generateResourcesFromReader(log, cd, os.Stdin)
if err != nil {
return nil, fmt.Errorf("unable to read from stdin: %w", err)
}
resources = append(resources, convertToInternalResourceOptions(stdinResources, wd)...)
resources = append(resources, convertToInternalResourceOptions(stdinResources, "")...)
}
return resources, nil
}
Expand All @@ -248,11 +242,11 @@ func (o *Options) generateResources(log logr.Logger, fs vfs.FileSystem, cd *cdv2
return nil, fmt.Errorf("unable to read from stdin: %w", err)
}
if (stdinInfo.Mode()&os.ModeNamedPipe != 0) || stdinInfo.Size() != 0 {
stdinResources, err := o.generateResourcesFromReader(cd, os.Stdin)
stdinResources, err := o.generateResourcesFromReader(log, cd, os.Stdin)
if err != nil {
return nil, fmt.Errorf("unable to read from stdin: %w", err)
}
resources = append(resources, convertToInternalResourceOptions(stdinResources, wd)...)
resources = append(resources, convertToInternalResourceOptions(stdinResources, "")...)
}
continue
}
Expand All @@ -261,7 +255,7 @@ func (o *Options) generateResources(log logr.Logger, fs vfs.FileSystem, cd *cdv2
if err != nil {
return nil, fmt.Errorf("unable to read resource object from %s: %w", resourcePath, err)
}
newResources, err := o.generateResourcesFromReader(cd, resourceObjectReader)
newResources, err := o.generateResourcesFromReader(log, cd, resourceObjectReader)
if err != nil {
if err2 := resourceObjectReader.Close(); err2 != nil {
log.Error(err, "unable to close file reader", "path", resourcePath)
Expand All @@ -278,7 +272,7 @@ func (o *Options) generateResources(log logr.Logger, fs vfs.FileSystem, cd *cdv2
}

// generateResourcesFromPath generates a resource given resource options and a resource template file.
func (o *Options) generateResourcesFromReader(cd *cdv2.ComponentDescriptor, reader io.Reader) ([]ResourceOptions, error) {
func (o *Options) generateResourcesFromReader(log logr.Logger, cd *cdv2.ComponentDescriptor, reader io.Reader) ([]ResourceOptions, error) {
var data bytes.Buffer
if _, err := io.Copy(&data, reader); err != nil {
return nil, err
Expand All @@ -288,6 +282,7 @@ func (o *Options) generateResourcesFromReader(cd *cdv2.ComponentDescriptor, read
if err != nil {
return nil, fmt.Errorf("unable to template resource: %w", err)
}
log.V(5).Info(tmplData)
return generateResourcesFromReader(cd, bytes.NewBuffer([]byte(tmplData)))
}

Expand Down
3 changes: 1 addition & 2 deletions pkg/commands/componentarchive/resources/add_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,10 +100,9 @@ var _ = Describe("Add", func() {

It("should add a resource defined by the deprecated -r option", func() {
opts := &resources.Options{
BuilderOptions: componentarchive.BuilderOptions{ComponentArchivePath: "./00-component"},
ResourceObjectPath: "./resources/00-res.yaml",
}
Expect(opts.Complete([]string{})).To(Succeed())
Expect(opts.Complete([]string{"./00-component"})).To(Succeed())

Expect(opts.Run(context.TODO(), testlog.NullLogger{}, testdataFs)).To(Succeed())

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
---
name: 'ubuntu'
version: '${MY_VERSION}'
type: 'ociImage'
Expand All @@ -6,4 +7,5 @@ extraIdentity:
myid: test
access:
type: 'ociRegistry'
imageReference: 'ubuntu:${MY_VERSION}'
imageReference: 'ubuntu:${MY_VERSION}'
---
25 changes: 10 additions & 15 deletions pkg/commands/componentarchive/sources/add.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package sources
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
Expand Down Expand Up @@ -172,18 +173,16 @@ func (o *Options) Run(ctx context.Context, log logr.Logger, fs vfs.FileSystem) e
}

func (o *Options) Complete(args []string) error {
if len(args) != 0 {
o.BuilderOptions.ComponentArchivePath = args[0]
}
o.BuilderOptions.Default()
args = o.TemplateOptions.Parse(args)

if err := o.TemplateOptions.Complete(args); err != nil {
return err
if len(args) == 0 {
return errors.New("at least a component archive path argument has to be defined")
}

if len(args) > 1 {
o.SourceObjectPaths = append(o.SourceObjectPaths, args[1:]...)
}
o.BuilderOptions.ComponentArchivePath = args[0]
o.BuilderOptions.Default()

o.SourceObjectPaths = append(o.SourceObjectPaths, args[1:]...)
if len(o.SourceObjectPath) != 0 {
o.SourceObjectPaths = append(o.SourceObjectPaths, o.SourceObjectPath)
}
Expand All @@ -204,10 +203,6 @@ func (o *Options) AddFlags(fs *pflag.FlagSet) {

// generateSources parses component references from the given path and stdin.
func (o *Options) generateSources(log logr.Logger, fs vfs.FileSystem) ([]InternalSourceOptions, error) {
wd, err := os.Getwd()
if err != nil {
return nil, fmt.Errorf("unable to get current working directory: %w", err)
}
if len(o.SourceObjectPaths) == 0 {
// try to read from stdin if no resources are defined
sourceOptions := make([]InternalSourceOptions, 0)
Expand All @@ -221,7 +216,7 @@ func (o *Options) generateSources(log logr.Logger, fs vfs.FileSystem) ([]Interna
if err != nil {
return nil, fmt.Errorf("unable to read from stdin: %w", err)
}
sourceOptions = append(sourceOptions, convertToInternalSourceOptions(stdinResources, wd)...)
sourceOptions = append(sourceOptions, convertToInternalSourceOptions(stdinResources, "")...)
}
return sourceOptions, nil
}
Expand All @@ -238,7 +233,7 @@ func (o *Options) generateSources(log logr.Logger, fs vfs.FileSystem) ([]Interna
if err != nil {
return nil, fmt.Errorf("unable to read from stdin: %w", err)
}
sourceOptions = append(sourceOptions, convertToInternalSourceOptions(stdinResources, wd)...)
sourceOptions = append(sourceOptions, convertToInternalSourceOptions(stdinResources, "")...)
}
continue
}
Expand Down
3 changes: 1 addition & 2 deletions pkg/commands/componentarchive/sources/add_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,9 @@ var _ = Describe("Add", func() {

It("should add a source file defined by the deprecated -r flag", func() {
opts := &sources.Options{
BuilderOptions: componentarchive.BuilderOptions{ComponentArchivePath: "./00-component"},
SourceObjectPath: "./resources/00-src.yaml",
}
Expect(opts.Complete([]string{})).To(Succeed())
Expect(opts.Complete([]string{"./00-component"})).To(Succeed())

Expect(opts.Run(context.TODO(), testlog.NullLogger{}, testdataFs)).To(Succeed())

Expand Down
34 changes: 12 additions & 22 deletions pkg/template/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
package template

import (
"strings"

"github.com/drone/envsubst"
)

Expand Down Expand Up @@ -37,33 +39,21 @@ key:
`
}

// Complete parses commandline argument variables.
func (o *Options) Complete(args []string) error {
parseVars := false
// Parse parses commandline argument variables.
// it returns all non variable arguments
func (o *Options) Parse(args []string) []string {
o.Vars = make(map[string]string)
var addArgs []string
for _, arg := range args {
// only start parsing after "--"
if arg == "--" {
parseVars = true
continue
}
if !parseVars {
if i := strings.Index(arg, "="); i > 0 {
value := arg[i+1:]
name := arg[0:i]
o.Vars[name] = value
continue
}

// parse value
name := ""
value := ""
for i := 1; i < len(arg); i++ { // equals cannot be first
if arg[i] == '=' {
value = arg[i+1:]
name = arg[0:i]
break
}
}
o.Vars[name] = value
addArgs = append(addArgs, arg)
}
return nil
return addArgs
}

// Template templates a string with the parsed vars.
Expand Down
16 changes: 10 additions & 6 deletions pkg/template/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,23 @@ var _ = Describe("Template", func() {

It("should parse one argument after a '--'", func() {
opts := template.Options{}
Expect(opts.Complete([]string{"--", "MY_VAR=test"})).To(Succeed())
Expect(opts.Parse([]string{"MY_VAR=test"})).To(BeNil())
Expect(opts.Vars).To(HaveKeyWithValue("MY_VAR", "test"))
})

It("should parse no argument if no '--' separator is provided", func() {
It("should return non variable arguments", func() {
opts := template.Options{}
Expect(opts.Complete([]string{"MY_VAR=test"})).To(Succeed())
Expect(opts.Vars).To(HaveLen(0))

args := opts.Parse([]string{"--", "MY_VAR=test", "my-arg"})
Expect(args).To(Equal([]string{
"--", "my-arg",
}))
Expect(opts.Vars).To(HaveKeyWithValue("MY_VAR", "test"))
})

It("should parse multiple values after a '--'", func() {
It("should parse multiple values", func() {
opts := template.Options{}
Expect(opts.Complete([]string{"--", "MY_VAR=test", "myOtherVar=true"})).To(Succeed())
Expect(opts.Parse([]string{"MY_VAR=test", "myOtherVar=true"})).To(BeNil())
Expect(opts.Vars).To(HaveKeyWithValue("MY_VAR", "test"))
Expect(opts.Vars).To(HaveKeyWithValue("myOtherVar", "true"))
})
Expand Down

0 comments on commit e5444eb

Please sign in to comment.