yaml

package
v0.5.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 5, 2020 License: Apache-2.0 Imports: 19 Imported by: 6

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Error

func Error(i interface{}) error

Error return new UnmarshalError.

Example
package main

import (
	"fmt"

	"github.com/k-kinzal/aliases/pkg/aliases/yaml"
)

func main() {
	err := yaml.Error("parse error")
	fmt.Println(err)
}
Output:

yaml error: parse error

func Errorf

func Errorf(format string, a ...interface{}) error

Errorf return new UnmarshalError with formated message.

Example
package main

import (
	"fmt"

	"github.com/k-kinzal/aliases/pkg/aliases/yaml"
)

func main() {
	reason := "undefined key"
	err := yaml.Errorf("parse error: %s", reason)
	fmt.Println(err)
}
Output:

yaml error: parse error: undefined key

func IsShell

func IsShell(fl validator.FieldLevel) bool

IsShell is check that `$parameter` or `${parameter}` or `$(expression)` or `\`expression\“ is included.

Types

type Config

type Config map[string]*Option

func LoadFile

func LoadFile(path string) (*Config, error)

func Unmarshal

func Unmarshal(buf []byte) (*Config, error)

Unmarshal parses YAML-encoded data and returns config specification.

Example
package main

import (
	"fmt"

	"github.com/k-kinzal/aliases/pkg/aliases/yaml"
)

func main() {
	content := `
/path/to/command1:
  image: alpine
  tag: latest
  name: alpine1
/path/to/command2:
  image: alpine
  tag: latest
  name: alpine2
`
	config, err := yaml.Unmarshal([]byte(content))
	if err != nil {
		panic(err)
	}
	fmt.Println(*(*config)["/path/to/command1"].Name)
	fmt.Println(*(*config)["/path/to/command2"].Name)
}
Output:

alpine1
alpine2

func (*Config) Get

func (config *Config) Get(path SpecPath) *Option

func (*Config) Set

func (config *Config) Set(path SpecPath, option Option)

type ConfigSpec

type ConfigSpec map[string]OptionSpec

ConfigSpec is the specification of aliases config

``` /path/to/command:

image: alpine
tag: latest
...

```

func (*ConfigSpec) BreadthWalk

func (spec *ConfigSpec) BreadthWalk(fn func(path SpecPath, current OptionSpec) (*OptionSpec, error)) error

BreadthWalk is executes the function when entry traverse OptionSpec.

Example
package main

import (
	"fmt"

	"github.com/k-kinzal/aliases/pkg/aliases/yaml"
)

func ptr(s string) *string {
	return &s
}

func hierarchy(path yaml.SpecPath) int {
	p := path.Parent()
	i := 1
	for p != nil {
		p = p.Parent()
		i++
	}
	return i
}

func main() {
	config := yaml.ConfigSpec{
		"/path/to/command1": yaml.OptionSpec{
			Image: "alpine",
			Tag:   "latest",
			Name:  ptr("alpine1"),
		},
		"/path/to/command2": yaml.OptionSpec{
			Image: "alpine",
			Tag:   "latest",
			Name:  ptr("alpine2"),
			Dependencies: []yaml.DependencySpec{
				*yaml.NewDependencySpec("/path/to/command1"),
				*yaml.NewDependencySpec("/path/to/command2"),
				*yaml.NewDependencySpec(yaml.ConfigSpec{
					"/path/to/command3": yaml.OptionSpec{
						Image: "alpine",
						Tag:   "latest",
						Name:  ptr("alpine3"),
						Dependencies: []yaml.DependencySpec{
							*yaml.NewDependencySpec("/path/to/command1"),
							*yaml.NewDependencySpec("/path/to/command2"),
							*yaml.NewDependencySpec(yaml.ConfigSpec{
								"/path/to/command5": yaml.OptionSpec{
									Image: "alpine",
									Tag:   "latest",
									Name:  ptr("alpine5"),
								},
							}),
						},
					},
				}),
				*yaml.NewDependencySpec(yaml.ConfigSpec{
					"/path/to/command4": yaml.OptionSpec{
						Image: "alpine",
						Tag:   "latest",
						Name:  ptr("alpine4"),
					},
				}),
			},
		},
	}
	if err := config.BreadthWalk(func(path yaml.SpecPath, current yaml.OptionSpec) (spec *yaml.OptionSpec, e error) {
		fmt.Println(hierarchy(path)) // get number of hierarchy
		return &current, nil
	}); err != nil {
		panic(err)
	}
}
Output:

1
1
2
2
3

func (*ConfigSpec) DepthWalk

func (spec *ConfigSpec) DepthWalk(fn func(path SpecPath, current OptionSpec) (*OptionSpec, error)) error

Walk is executes the function when leaving traverse OptionSpec.

Example
package main

import (
	"fmt"

	"github.com/k-kinzal/aliases/pkg/aliases/yaml"
)

func ptr(s string) *string {
	return &s
}

func hierarchy(path yaml.SpecPath) int {
	p := path.Parent()
	i := 1
	for p != nil {
		p = p.Parent()
		i++
	}
	return i
}

func main() {
	config := yaml.ConfigSpec{
		"/path/to/command1": yaml.OptionSpec{
			Image: "alpine",
			Tag:   "latest",
			Name:  ptr("alpine2"),
			Dependencies: []yaml.DependencySpec{
				*yaml.NewDependencySpec("/path/to/command1"),
				*yaml.NewDependencySpec(yaml.ConfigSpec{
					"/path/to/command3": yaml.OptionSpec{
						Image: "alpine",
						Tag:   "latest",
						Name:  ptr("alpine3"),
						Dependencies: []yaml.DependencySpec{
							*yaml.NewDependencySpec("/path/to/command1"),
							*yaml.NewDependencySpec(yaml.ConfigSpec{
								"/path/to/command5": yaml.OptionSpec{
									Image: "alpine",
									Tag:   "latest",
									Name:  ptr("alpine5"),
								},
							}),
						},
					},
				}),
				*yaml.NewDependencySpec(yaml.ConfigSpec{
					"/path/to/command4": yaml.OptionSpec{
						Image: "alpine",
						Tag:   "latest",
						Name:  ptr("alpine4"),
					},
				}),
			},
		},
	}
	if err := config.DepthWalk(func(path yaml.SpecPath, current yaml.OptionSpec) (spec *yaml.OptionSpec, e error) {
		fmt.Println(hierarchy(path)) // get number of hierarchy
		return &current, nil
	}); err != nil {
		panic(err)
	}
}
Output:

3
2
2
1

type DependencySpec

type DependencySpec struct {
	types.Union
}

DependencySpec is a dependency on ConfigSpec or a string of references to other options.

```yaml dependencies:

  • command1
  • command2: ...

```

func NewDependencySpec

func NewDependencySpec(value interface{}) *DependencySpec

NewDependencySpec creates a new DependencySpec.

Example
package main

import (
	"fmt"

	"github.com/k-kinzal/aliases/pkg/aliases/yaml"
)

func main() {
	dep := yaml.NewDependencySpec("/path/to/command")

	fmt.Println(dep.IsString())
}
Output:

true

func (*DependencySpec) Config

func (spec *DependencySpec) Config() ConfigSpec

Config is return ConfigSpec value.

Example
package main

import (
	"fmt"

	"github.com/k-kinzal/aliases/pkg/aliases/yaml"
)

func main() {
	config1 := yaml.ConfigSpec{
		"/path/to/command": yaml.OptionSpec{
			Image: "alpine",
			Tag:   "latest",
		},
	}

	dep := yaml.NewDependencySpec(config1)

	for index, option := range dep.Config() {
		fmt.Println(index)
		fmt.Println(option.Image)
		fmt.Println(option.Tag)
	}

	fmt.Println()
}
Output:

/path/to/command
alpine
latest

func (*DependencySpec) IsConfig

func (spec *DependencySpec) IsConfig() bool

IsConfig returns true if the value is a ConfigSpec.

Example
package main

import (
	"fmt"

	"github.com/k-kinzal/aliases/pkg/aliases/yaml"
)

func main() {
	dep := yaml.NewDependencySpec(yaml.ConfigSpec{})

	fmt.Println(dep.IsConfig())
}
Output:

true

func (*DependencySpec) IsString

func (spec *DependencySpec) IsString() bool

IsString returns true if the value is a string.

Example
package main

import (
	"fmt"

	"github.com/k-kinzal/aliases/pkg/aliases/yaml"
)

func main() {
	dep := yaml.NewDependencySpec("/path/to/command")

	fmt.Println(dep.IsString())
}
Output:

true

func (*DependencySpec) String

func (spec *DependencySpec) String() string

String is return string value.

Example
package main

import (
	"fmt"

	"github.com/k-kinzal/aliases/pkg/aliases/yaml"
)

func main() {
	dep := yaml.NewDependencySpec("/path/to/command")

	fmt.Println(dep.String())
}
Output:

/path/to/command

func (*DependencySpec) UnmarshalYAML

func (spec *DependencySpec) UnmarshalYAML(unmarshal func(interface{}) error) error
Example
package main

import (
	"fmt"

	"github.com/k-kinzal/aliases/pkg/aliases/yaml"

	y "gopkg.in/yaml.v2"
)

func main() {
	content := `
- /path/to/command1
- /path/to/command2:
    images: alpine
    tag: latest
    dependencies:
    - /path/to/command3
    - /path/to/command4:
        images: alpine
        tag: latest
`
	var dependencies []yaml.DependencySpec
	if err := y.Unmarshal([]byte(content), &dependencies); err != nil {
		panic(err)
	}

	fmt.Println(dependencies[0].IsString())
	fmt.Println(dependencies[1].IsConfig())
	for _, option := range dependencies[1].Config() {
		fmt.Println(option.Dependencies[0].IsString())
		fmt.Println(option.Dependencies[1].IsConfig())
	}
}
Output:

true
true
true
true

type DockerSpec added in v0.4.0

type DockerSpec struct {
	Image string `yaml:"image" default:"docker"`
	Tag   string `yaml:"tag" default:"18.09.0"`
}

DockerSpec is docker binary config to mount

type Option

type Option struct {
	*OptionSpec
	Path         SpecPath
	Dependencies []*Option
}

func (*Option) Index

func (option *Option) Index() string

index return configuration index.

func (*Option) Namespace

func (option *Option) Namespace() string

type OptionSpec

type OptionSpec struct {
	// binary settings
	Docker *DockerSpec
	// docker run settings
	Image   string   `yaml:"image" validate:"required"`
	Tag     string   `yaml:"tag" validate:"required"`
	Command *string  `yaml:"command"`
	Args    []string `yaml:"args"`
	// docker run option settings
	AddHost             []string          `yaml:"addHost"` // host:ip
	Attach              []string          `yaml:"attach" validate:"omitempty,dive,oneof=STDIN STDOUT STDERR"`
	BlkioWeight         *string           `yaml:"blkioWeight" validate:"omitempty,uint16|shell,_,shell|min=10,_,shell|max=1000"`
	BlkioWeightDevice   []string          `yaml:"blkioWeightDevice"`
	CIDFile             *string           `yaml:"cidfile"`
	CPUPeriod           *string           `yaml:"cpuPeriod" validate:"omitempty,nanocpus|shell"`
	CPUQuota            *string           `yaml:"cpuQuota" validate:"omitempty,int64|shell"`
	CPURtPeriod         *string           `yaml:"cpuRtPeriod" validate:"omitempty,int64|shell"`
	CPURtRuntime        *string           `yaml:"cpuRtRuntime" validate:"omitempty,int64|shell"`
	CPUShares           *string           `yaml:"cpuShares" validate:"omitempty,int64|shell"`
	CPUs                *string           `yaml:"cpus"`
	CPUsetCPUs          *string           `yaml:"cpusetCpus"`
	CPUsetMems          *string           `yaml:"cpusetMems"`
	CapAdd              []string          `yaml:"capAdd"`
	CapDrop             []string          `yaml:"capDrop"`
	CgroupParent        *string           `yaml:"cgroupParent"`
	DNS                 []string          `yaml:"dns"`
	DNSOption           []string          `yaml:"dnsOption"`
	DNSSearch           []string          `yaml:"dnsSearch"`
	Detach              *string           `yaml:"detach" validate:"omitempty,bool|shell"`
	DetachKeys          *string           `yaml:"detachKeys"`
	Device              []string          `yaml:"device"`
	DeviceCgroupRule    []string          `yaml:"deviceCgroupRule"`
	DeviceReadBPS       []string          `yaml:"deviceReadBps"`
	DeviceReadIOPS      []string          `yaml:"deviceReadIops"`
	DeviceWriteBPS      []string          `yaml:"deviceWriteBps"`
	DeviceWriteIOPS     []string          `yaml:"deviceWriteIops"`
	DisableContentTrust *string           `yaml:"disableContentTrust" validate:"omitempty,bool|shell"`
	Domainname          *string           `yaml:"domainname"`
	Entrypoint          *string           `yaml:"entrypoint"`
	Env                 map[string]string `yaml:"env"`
	EnvFile             []string          `yaml:"shellFile"`
	Expose              []string          `yaml:"expose"`
	GroupAdd            []string          `yaml:"groupAdd"`
	HealthCmd           *string           `yaml:"healthCmd"`
	HealthInterval      *string           `yaml:"healthInterval" validate:"omitempty,duration|shell"`
	HealthRetries       *string           `yaml:"healthRetries" validate:"omitempty,int|shell"`
	HealthStartPeriod   *string           `yaml:"healthStartPeriod" validate:"omitempty,duration|shell"`
	HealthTimeout       *string           `yaml:"healthTimeout" validate:"omitempty,duration|shell"`
	Hostname            *string           `yaml:"hostname"`
	IP                  *string           `yaml:"ip" validate:"omitempty,ipv4|shell"`
	IP6                 *string           `yaml:"ip6" validate:"omitempty,ipv6|shell"`
	IPC                 *string           `yaml:"ipc"`
	Init                *string           `yaml:"init" validate:"omitempty,bool|shell"`
	Interactive         *string           `yaml:"interactive" validate:"omitempty,bool|shell" default:"true"`
	Isolation           *string           `yaml:"isolation"`
	KernelMemory        *string           `yaml:"kernelMemory" validate:"omitempty,membytes|shell"`
	Label               map[string]string `yaml:"label"`
	LabelFile           []string          `yaml:"labelFile"`
	Link                []string          `yaml:"link"`
	LinkLocalIP         []string          `yaml:"linkLocalIp"`
	LogDriver           *string           `yaml:"logDriver"`
	LogOpt              map[string]string `yaml:"logOpt"`
	MacAddress          *string           `yaml:"macAddress" validate:"omitempty,mac|shell"`
	Memory              *string           `yaml:"memory" validate:"omitempty,membytes|shell"`
	MemoryReservation   *string           `yaml:"memoryReservation" validate:"omitempty,membytes|shell"`
	MemorySwap          *string           `yaml:"memorySwap" validate:"omitempty,memswapbytes|shell"`
	MemorySwappiness    *string           `yaml:"memorySwappiness" validate:"omitempty,int64|shell,_,shell|min=-1,_,shell|max=100"`
	Mount               map[string]string `yaml:"mount"`
	Name                *string           `yaml:"name"`
	Network             *string           `yaml:"network" default:"host"`
	NetworkAlias        []string          `yaml:"networkAlias"`
	NoHealthcheck       *string           `yaml:"noHealthcheck" validate:"omitempty,bool|shell"`
	OOMKillDisable      *string           `yaml:"oomKillDisable" validate:"omitempty,bool|shell"`
	OOMScoreAdj         *string           `yaml:"oomScoreAdj" validate:"omitempty,int|shell,_,shell|min=-1000,_,shell|max=1000"`
	PID                 *string           `yaml:"pid"`
	PidsLimit           *string           `yaml:"pidsLimit" validate:"omitempty,int64|shell"`
	Platform            *string           `yaml:"platform"`
	Privileged          *string           `yaml:"privileged" validate:"omitempty,bool|shell"`
	Publish             []string          `yaml:"publish"`
	PublishAll          *string           `yaml:"publishAll" validate:"omitempty,bool|shell"`
	ReadOnly            *string           `yaml:"readOnly" validate:"omitempty,bool|shell"`
	Restart             *string           `yaml:"restart"`
	Rm                  *string           `yaml:"rm" validate:"omitempty,bool|shell" default:"true"`
	Runtime             *string           `yaml:"runtime"`
	SecurityOpt         map[string]string `yaml:"securityOpt"`
	ShmSize             *string           `yaml:"shmSize" validate:"omitempty,membytes|shell"`
	SigProxy            *string           `yaml:"sigProxy" validate:"omitempty,bool|shell"`
	StopSignal          *string           `yaml:"stopSignal"`
	StopTimeout         *string           `yaml:"stopTimeout" validate:"omitempty,int|shell"`
	StorageOpt          map[string]string `yaml:"storageOpt"`
	Sysctl              map[string]string `yaml:"sysctl"`
	TTY                 *string           `yaml:"tty" validate:"omitempty,bool|shell" default:"tty >/dev/null"`
	Tmpfs               []string          `yaml:"tmpfs"`
	UTS                 *string           `yaml:"uts"`
	Ulimit              map[string]string `yaml:"ulimit"`
	User                *string           `yaml:"user"` // <name|uid>[:<group|gid>]
	Userns              *string           `yaml:"userns"`
	Volume              []string          `yaml:"volume"`
	VolumeDriver        *string           `yaml:"volumeDriver"`
	VolumesFrom         []string          `yaml:"volumesFrom"`
	Workdir             *string           `yaml:"workdir"`
	// extend docker run option settings
	EnvPrefix []string `yaml:"envPrefix"`
	// dependency
	Dependencies []DependencySpec `yaml:"dependencies"`
}

OptionSpec is the specification of option in aliases config

``` image: alpine tag: latest ... ```

type SpecPath

type SpecPath string

SpecPath is the path that points to the location of OptionSpec.

func (*SpecPath) Base

func (p *SpecPath) Base() string

Base returns filename of OptionSpec.

Example
package main

import (
	"fmt"

	"github.com/k-kinzal/aliases/pkg/aliases/yaml"
)

func main() {
	var path yaml.SpecPath = "/path/to/command1.dependencies[0]./path/to/command2"
	fmt.Println(path.Base())
}
Output:

command2

func (*SpecPath) Dependencies

func (p *SpecPath) Dependencies(i int, index string) *SpecPath

Dependencies returns the path point to the location of dependency OptionSpec.

Example
package main

import (
	"fmt"

	"github.com/k-kinzal/aliases/pkg/aliases/yaml"
)

func main() {
	var path yaml.SpecPath = "/path/to/command1"
	fmt.Println(path.Dependencies(0, "/path/to/command2"))
}
Output:

/path/to/command1.dependencies[0]./path/to/command2

func (*SpecPath) Index

func (p *SpecPath) Index() int

Index returns index of parent dependencies.

Example
package main

import (
	"fmt"

	"github.com/k-kinzal/aliases/pkg/aliases/yaml"
)

func main() {
	var path yaml.SpecPath = "/path/to/command1.dependencies[0]./path/to/command2.dependencies[1]./path/to/command3"
	fmt.Println(path.Index())
}
Output:

1

func (*SpecPath) Name

func (p *SpecPath) Name() string

Name returns name of OptionSpec.

Example
package main

import (
	"fmt"

	"github.com/k-kinzal/aliases/pkg/aliases/yaml"
)

func main() { // is path of root OptionSpec
	var path1 yaml.SpecPath = "/path/to/command1"
	fmt.Println(path1.Name())

	var path2 yaml.SpecPath = "/path/to/command1.dependencies[0]./path/to/command2"
	fmt.Println(path2.Name())
}
Output:

/path/to/command1
/path/to/command2

func (*SpecPath) Parent

func (p *SpecPath) Parent() *SpecPath

Parent returns the path that points to the location of the parent OptionSpec.

Example
package main

import (
	"fmt"

	"github.com/k-kinzal/aliases/pkg/aliases/yaml"
)

func main() {
	var path yaml.SpecPath = "/path/to/command1.dependencies[0]./path/to/command2"
	fmt.Println(path.Parent())
}
Output:

/path/to/command1

func (*SpecPath) String

func (p *SpecPath) String() string

String converts string from SpecPath

type UnmarshalError

type UnmarshalError struct {
	// contains filtered or unexported fields
}

UnmarshalError is an error occurred in YAML-encoded data.

func (*UnmarshalError) Error

func (e *UnmarshalError) Error() string

Error returns error message.

type Validate

type Validate struct {
	*validator.Validate
}

Validate is wrapper to validator.v9.

func NewValidator

func NewValidator() *Validate

NewValidator creates a new Validator.

Example
package main

import (
	"fmt"

	"github.com/k-kinzal/aliases/pkg/aliases/yaml"
)

func main() {
	i := struct {
		Data string `validate:"_"`
	}{
		Data: "foo",
	}
	v := yaml.NewValidator()
	if err := v.Struct(i); err != nil {
		panic(err)
	} else {
		fmt.Println(err)
	}

}
Output:

<nil>

func (*Validate) Struct

func (v *Validate) Struct(s interface{}) error

Struct is wrapper to validator.v9:Struct.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL