cogs

package module
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Dec 15, 2021 License: MPL-2.0 Imports: 21 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

COGS: COnfiguration manaGement S

cogs is a cli tool that allows generation of configuration files by referencing multiple sources of truth.

Sources of truth can include:

cogs allows one to deduplicate sources of truth by maintaining a source of reference (the cog file) that points to the location of values (such as port numbers and password strings).

installation:

With go:

Clone this repo and cd into it.

source <(go env)
go build -o $GOPATH/bin/ ./cmd/cogs

Without go

PLatform can be Linux/Windows/Darwin:

PL="Darwin" VR="0.11.0" \
  curl -SLk \
  "github.com/mkatychev/cogs/releases/download/v${VR}/cogs_${VR}_${PL}_x86_64.tar.gz" | \
  tar xvz -C /usr/local/bin cogs

help string:

COGS COnfiguration manaGement S

Usage:
  cogs gen <cog-file> <ctx>... [options]

Options:
  -h --help        Show this screen.
  --version        Show version.
  --no-enc, -n     Skips fetching encrypted vars.
  --no-decrypt	   Skips decrypting encrypted vars.
  --envsubst, -e   Perform environmental substitution on the given cog file.
  --keys=<key,>    Include specific keys, comma separated.
  --not=<key,>     Exclude specific keys, comma separated.
  --out=<type>     Configuration output type [default: json].
                   <type>: json, toml, yaml, dotenv, list.
  
  --export, -x     If --out=dotenv: Prepends "export " to each line.
  --preserve, -p   If --out=dotenv: Preserves variable casing.
  --sep=<sep>      If --out=list:   Delimits values with a <sep>arator.

cogs gen - outputs a flat and serialized K:V array

annotated spec:

 # every cog manifest should have a name key that corresponds to a string
name = "basic example"

# key value pairs for a context/ctx are defined under <ctx>.vars
# try running `cogs gen basic ./examples/1.basic.cog.toml` to see what output
# cogs generates
[basic.vars]
var = "var_value"
other_var = "other_var_value"

# if <var>.path is given a string value,
# cogs will look for the key name of <var> in the file that that corresponds to
# the <var>.path key,
# returning the corresponding value
manifest_var.path = "../test_files/manifest.yaml"
# try removing manifest_var from "./test_files/manifest.yaml" and see what happens

# some variables can set an explicit key name to look for instead of defaulting
# to look for the key name "<var>":
# if <var>.name is defined then cogs will look for a key name that matches <var>.name
look_for_manifest_var.path = "../test_files/manifest.yaml"
look_for_manifest_var.name = "manifest_var"

# dangling variable names should return an error
# uncomment the line below and run `cogs gen basic ./examples/1.basic.cog.toml`:
# empty_var.name = "some_name"

example data:

The example data (in ./examples) are ordered by increasing complexity and should be used as a tutorial. Run cogs gen on the files in the order below, then read the file to see how the underlying logic is used.

  1. basic example:
    • cogs gen examples/1.basic.cog.toml basic
    • cogs gen examples/1.basic.cog.toml basic extra, multi-ctx example
  2. HTTP examples:
    • cogs gen examples/2.http.cog.toml get, GET example
    • cogs gen examples/2.http.cog.toml post, POST example:
  3. secret values and paths example:
    • gpg --import test_files/sops_functional_tests_key.asc should be run to import the test private key used for encrypted dummy data
    • cogs gen examples/3.secrets.cog.toml sops
  4. read types example:
    • cogs gen examples/4.read_types.cog.toml kustomize
  5. advanced patterns example:
    • cogs gen examples/5.advanced.cog.toml complex_json
  6. envsubst patterns example:
    • NVIM=nvim cogs gen examples/6.envsubst.cog.toml envsubst --envsubst

envsubst cheatsheet:

Expression Meaning
${var} Value of $var
${var-${DEFAULT}} If $var is not set, evaluate expression as ${DEFAULT}
${var:-${DEFAULT}} If $var is not set or is empty, evaluate expression as ${DEFAULT}
${var=${DEFAULT}} If $var is not set, evaluate expression as ${DEFAULT}
${var:=${DEFAULT}} If $var is not set or is empty, evaluate expression as ${DEFAULT}
$$var Escape expressions. Result will be the string $var
${var^} Uppercase first character of $var
${var^^} Uppercase all characters in $var
${var,} Lowercase first character of $var
${var,,} Lowercase all characters in $var
${#var} String length of $var
${var:n} Offset $var n characters from start
${var: -n} Offset $var n characters from end
${var:n:len} Offset $var n characters with max length of len
${var#pattern} Strip shortest pattern match from start
${var##pattern} Strip longest pattern match from start
${var%pattern} Strip shortest pattern match from end
${var%%pattern} Strip longest pattern match from end
${var/pattern/replacement} Replace as few pattern matches as possible with replacement
${var//pattern/replacement} Replace as many pattern matches as possible with replacement
${var/#pattern/replacement} Replace pattern match with replacement from $var start
${var/%pattern/replacement} Replace pattern match with replacement from $var end

Notes and references:

envsubst warning: make sure that any environmental substition declarations allow a file to be parsed as TOML without the usage of the --envsubst flag:

# valid envsubst definitions can be placed anywhere string values are valid
["${ENV}".vars]
thing = "${THING_VAR}"
# the `${ENV}` below creates a TOML read error
[env.vars]${ENV}
thing = "${THING_VAR}"

Further references

Documentation

Index

Constants

View Source
const (
	ErrNoEncAndNoDecrypt = errConst("NoEnc and NoDecrypt cannot both be true")
)

Errors raised by package x.

Variables

View Source
var DefaultMethod string = http.MethodGet

DefaultMethod uses GET for the default request type

View Source
var EnvSubst bool = false

EnvSubst decides whether to use environmental substitution or not

View Source
var NoDecrypt bool = false

NoDecrypt decides whether to decrypt encrypted values, not compatible with NoEnc

View Source
var NoEnc bool = false

NoEnc decides whether to handle encrypted variables

View Source
var RecursionLimit int = 12

RecursionLimit is the limit used to define when to abort successive traversals of gears

Functions

func Exclude

func Exclude(exclusionList []string, linkMap map[string]*Link) map[string]*Link

Exclude produces a laundered map with exclusionList values missing

func InList

func InList(s string, ss []string) bool

InList verifies that a given string is in a string slice

func IsEnvFile

func IsEnvFile(path string) bool

IsEnvFile returns true if a given file path corresponds to a .env file

func IsJSONFile

func IsJSONFile(path string) bool

IsJSONFile returns true if a given file path corresponds to a JSON file

func IsSimpleValue

func IsSimpleValue(i interface{}) bool

IsSimpleValue is intended to see if the underlying value allows a flat map to be retained

func IsTOMLFile

func IsTOMLFile(path string) bool

IsTOMLFile returns true if a given file path corresponds to a TOML file

func IsYAMLFile

func IsYAMLFile(path string) bool

IsYAMLFile returns true if a given file path corresponds to a YAML file

func OutputCfg

func OutputCfg(link *Link, outputType Format) (interface{}, error)

OutputCfg returns the corresponding value for a given Link struct

func SimpleValueToString

func SimpleValueToString(i interface{}) (str string, err error)

SimpleValueToString converts an underlying type to a string, returning an error if it is not a simple value

Types

type CfgMap

type CfgMap map[string]interface{}

CfgMap is meant to represent a map with values of one or more unknown types

func Generate

func Generate(ctxName, cogPath string, outputType Format, filter LinkFilter) (CfgMap, error)

Generate is a top level command that takes an context name argument and cog file path to return a string map

func Join

func Join(cfgs ...*CfgMap) (CfgMap, error)

Join merges any number of CfgMap elements into a single CfgMap, elements with a duplicate key name return an error.

type Format

type Format string

Format represents the final marshalled k/v output type from a resolved Gear TODO reconcile readType and Format patterns

const (
	JSON   Format = "json"
	YAML   Format = "yaml"
	TOML   Format = "toml"
	Dotenv Format = "dotenv"
	List   Format = "list" // omit keys
)

Formats for respective object notation

func FormatForPath

func FormatForPath(path string) Format

FormatForPath returns the correct format given the path to a file

func FormatLinkInput

func FormatLinkInput(link *Link) (format Format)

FormatLinkInput returns the correct format given the readType

func (Format) Validate

func (t Format) Validate() error

Validate ensures that a string maps to a valid Format

type Gear

type Gear struct {
	Name string
	// contains filtered or unexported fields
}

Gear represents one of the contexts in a cog manifest. The term "gear" is used to refer to the operating state of a machine (similar to how a microservice can operate locally or in a remote environment) rather than a gear object. The term "switching gears" is an apt representation of how one Cog manifest file can have many contexts/environments

func (*Gear) ResolveMap

func (g *Gear) ResolveMap(ctx baseContext) (CfgMap, error)

ResolveMap outputs the flat associative string, resolving potential filepath pointers held by Link objects by calling the .SetValue() method

func (*Gear) SetName

func (g *Gear) SetName(name string)

SetName sets the gear name to the provided string

type Link struct {
	KeyName    string      // the key name defined in the context file
	SearchName string      // same as keyName unless redefined using the `name` key: var.name="other_name"
	Value      interface{} // Holds a complex or simple value for the given Link
	Path       string      // filepath string where Link can be resolved
	SubPath    string      // object traversal string used to resolve Link if not at top level of document (yq syntax)
	// contains filtered or unexported fields
}

Link holds all the data needed to resolve one string key value pair

func (Link) String

func (c Link) String() string

String holds the string representation of a Link struct

type LinkFilter

type LinkFilter func(map[string]*Link) (map[string]*Link, error)

LinkFilter if a function meant to filter a LinkMap

type ReadType

type ReadType string

ReadType represents the logic used to derive the deserliazied value for a given Link

func (ReadType) String

func (t ReadType) String() string

func (ReadType) Validate

func (t ReadType) Validate() error

Validate ensures that a string is a valid readType enum

type Resolver

type Resolver interface {
	ResolveMap(baseContext) (CfgMap, error)
	SetName(string)
}

Resolver is meant to define an object that returns the final string map to be used in a configuration resolving any paths and sub paths defined in the underling config map

type Visitor

type Visitor interface {
	SetValue(*Link) error
	Errors() []error
}

Visitor allows a query path to return the underlying value for a given visitor

func NewDotenvVisitor

func NewDotenvVisitor(buf []byte) (Visitor, error)

NewDotenvVisitor returns a visitor object that satisfies the Visitor interface attempting to turn a supposed dotenv byte slice into a *yaml.Node object

func NewJSONVisitor

func NewJSONVisitor(buf []byte) (Visitor, error)

NewJSONVisitor returns a visitor object that satisfies the Visitor interface attempting to turn a supposed JSON byte slice into a *yaml.Node object

func NewTOMLVisitor

func NewTOMLVisitor(buf []byte) (Visitor, error)

NewTOMLVisitor returns a visitor object that satisfies the Visitor interface attempting to turn a supposed TOML byte slice into a *yaml.Node object

func NewYAMLVisitor

func NewYAMLVisitor(buf []byte) (Visitor, error)

NewYAMLVisitor returns a visitor object that satisfies the Visitor interface

Directories

Path Synopsis
cmd
cogs command

Jump to

Keyboard shortcuts

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