Giter Club home page Giter Club logo

yq's Introduction

yq

Build Docker Pulls Github Releases (by Release) Go Report CodeQL

a lightweight and portable command-line YAML, JSON and XML processor. yq uses jq like syntax but works with yaml files as well as json, xml, properties, csv and tsv. It doesn't yet support everything jq does - but it does support the most common operations and functions, and more is being added continuously.

yq is written in go - so you can download a dependency free binary for your platform and you are good to go! If you prefer there are a variety of package managers that can be used as well as Docker and Podman, all listed below.

Quick Usage Guide

Read a value:

yq '.a.b[0].c' file.yaml

Pipe from STDIN:

yq '.a.b[0].c' < file.yaml

Update a yaml file, in place

yq -i '.a.b[0].c = "cool"' file.yaml

Update using environment variables

NAME=mike yq -i '.a.b[0].c = strenv(NAME)' file.yaml

Merge multiple files

# merge two files
yq -n 'load("file1.yaml") * load("file2.yaml")'

# merge using globs:
# note the use of `ea` to evaluate all the files at once
# instead of in sequence
yq ea '. as $item ireduce ({}; . * $item )' path/to/*.yml

Multiple updates to a yaml file

yq -i '
  .a.b[0].c = "cool" |
  .x.y.z = "foobar" |
  .person.name = strenv(NAME)
' file.yaml

Find and update an item in an array:

yq '(.[] | select(.name == "foo") | .address) = "12 cat st"'

Convert JSON to YAML

yq -Poy sample.json

See recipes for more examples and the documentation for more information.

Take a look at the discussions for common questions, and cool ideas

Install

wget

Use wget to download, gzipped pre-compiled binaries:

For instance, VERSION=v4.2.0 and BINARY=yq_linux_amd64

Compressed via tar.gz

wget https://github.com/mikefarah/yq/releases/download/${VERSION}/${BINARY}.tar.gz -O - |\
  tar xz && mv ${BINARY} /usr/bin/yq

Plain binary

wget https://github.com/mikefarah/yq/releases/download/${VERSION}/${BINARY} -O /usr/bin/yq &&\
    chmod +x /usr/bin/yq

Latest version

wget https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 -O /usr/bin/yq &&\
    chmod +x /usr/bin/yq

MacOS / Linux via Homebrew:

Using Homebrew

brew install yq

Linux via snap:

snap install yq

Snap notes

yq installs with strict confinement in snap, this means it doesn't have direct access to root files. To read root files you can:

sudo cat /etc/myfile | yq '.a.path'

And to write to a root file you can either use sponge:

sudo cat /etc/myfile | yq '.a.path = "value"' | sudo sponge /etc/myfile

or write to a temporary file:

sudo cat /etc/myfile | yq '.a.path = "value"' | sudo tee /etc/myfile.tmp
sudo mv /etc/myfile.tmp /etc/myfile
rm /etc/myfile.tmp

Run with Docker or Podman

Oneshot use:

docker run --rm -v "${PWD}":/workdir mikefarah/yq [command] [flags] [expression ]FILE...

Note that you can run yq in docker without network access and other privileges if you desire, namely --security-opt=no-new-privileges --cap-drop all --network none.

podman run --rm -v "${PWD}":/workdir mikefarah/yq [command] [flags] [expression ]FILE...

Pipe in via STDIN:

You'll need to pass the -i\--interactive flag to docker:

docker run -i --rm mikefarah/yq '.this.thing' < myfile.yml
podman run -i --rm mikefarah/yq '.this.thing' < myfile.yml

Run commands interactively:

docker run --rm -it -v "${PWD}":/workdir --entrypoint sh mikefarah/yq
podman run --rm -it -v "${PWD}":/workdir --entrypoint sh mikefarah/yq

It can be useful to have a bash function to avoid typing the whole docker command:

yq() {
  docker run --rm -i -v "${PWD}":/workdir mikefarah/yq "$@"
}
yq() {
  podman run --rm -i -v "${PWD}":/workdir mikefarah/yq "$@"
}

Running as root:

yq's container image no longer runs under root (#860). If you'd like to install more things in the container image, or you're having permissions issues when attempting to read/write files you'll need to either:

docker run --user="root" -it --entrypoint sh mikefarah/yq
podman run --user="root" -it --entrypoint sh mikefarah/yq

Or, in your Dockerfile:

FROM mikefarah/yq

USER root
RUN apk add --no-cache bash
USER yq

Missing timezone data

By default, the alpine image yq uses does not include timezone data. If you'd like to use the tz operator, you'll need to include this data:

FROM mikefarah/yq

USER root
RUN apk add --no-cache tzdata
USER yq

Podman with SELinux

If you are using podman with SELinux, you will need to set the shared volume flag :z on the volume mount:

-v "${PWD}":/workdir:z

GitHub Action

  - name: Set foobar to cool
    uses: mikefarah/yq@master
    with:
      cmd: yq -i '.foo.bar = "cool"' 'config.yml'
  - name: Get an entry with a variable that might contain dots or spaces
    id: get_username
    uses: mikefarah/yq@master
    with:
      cmd: yq '.all.children.["${{ matrix.ip_address }}"].username' ops/inventories/production.yml
  - name: Reuse a variable obtained in another step
    run: echo ${{ steps.get_username.outputs.result }}

See https://mikefarah.gitbook.io/yq/usage/github-action for more.

Go Install:

go install github.com/mikefarah/yq/v4@latest

Community Supported Installation methods

As these are supported by the community ❤️ - however, they may be out of date with the officially supported releases.

Please note that the Debian package (previously supported by @rmescandon) is no longer maintained. Please use an alternative installation method.

Nix

nix profile install nixpkgs#yq-go

See here

Webi

webi yq

See webi Supported by @adithyasunil26 (https://github.com/webinstall/webi-installers/tree/master/yq)

Arch Linux

pacman -S go-yq

Windows:

Using Chocolatey

Chocolatey Chocolatey

choco install yq

Supported by @chillum (https://chocolatey.org/packages/yq)

Using scoop

scoop install main/yq

Using winget

winget install --id MikeFarah.yq

Mac:

Using MacPorts

sudo port selfupdate
sudo port install yq

Supported by @herbygillot (https://ports.macports.org/maintainer/github/herbygillot)

Alpine Linux

  • Enable edge/community repo by adding $MIRROR/alpine/edge/community to /etc/apk/repositories
  • Update database index with apk update
  • Install yq with apk add yq

Supported by Tuan Hoang https://pkgs.alpinelinux.org/package/edge/community/x86/yq

Features

Check out the documentation for more detailed and advanced usage.

Usage:
  yq [flags]
  yq [command]

Examples:

# yq defaults to 'eval' command if no command is specified. See "yq eval --help" for more examples.
yq '.stuff' < myfile.yml # outputs the data at the "stuff" node from "myfile.yml"

yq -i '.stuff = "foo"' myfile.yml # update myfile.yml in place


Available Commands:
  completion       Generate the autocompletion script for the specified shell
  eval             (default) Apply the expression to each document in each yaml file in sequence
  eval-all         Loads _all_ yaml documents of _all_ yaml files and runs expression once
  help             Help about any command

Flags:
  -C, --colors                        force print with colors
  -e, --exit-status                   set exit status if there are no matches or null or false is returned
  -f, --front-matter string           (extract|process) first input as yaml front-matter. Extract will pull out the yaml content, process will run the expression against the yaml content, leaving the remaining data intact
      --header-preprocess             Slurp any header comments and separators before processing expression. (default true)
  -h, --help                          help for yq
  -I, --indent int                    sets indent level for output (default 2)
  -i, --inplace                       update the file in place of first file given.
  -p, --input-format string           [yaml|y|xml|x] parse format for input. Note that json is a subset of yaml. (default "yaml")
  -M, --no-colors                     force print with no colors
  -N, --no-doc                        Don't print document separators (---)
  -n, --null-input                    Don't read input, simply evaluate the expression given. Useful for creating docs from scratch.
  -o, --output-format string          [yaml|y|json|j|props|p|xml|x] output format type. (default "yaml")
  -P, --prettyPrint                   pretty print, shorthand for '... style = ""'
  -s, --split-exp string              print each result (or doc) into a file named (exp). [exp] argument must return a string. You can use $index in the expression as the result counter.
      --unwrapScalar                  unwrap scalar, print the value with no quotes, colors or comments (default true)
  -v, --verbose                       verbose mode
  -V, --version                       Print version information and quit
      --xml-attribute-prefix string   prefix for xml attributes (default "+")
      --xml-content-name string       name for xml content (if no attribute name is present). (default "+content")

Use "yq [command] --help" for more information about a command.

Known Issues / Missing Features

  • yq attempts to preserve comment positions and whitespace as much as possible, but it does not handle all scenarios (see https://github.com/go-yaml/yaml/tree/v3 for details)
  • Powershell has its own...opinions on quoting yq
  • "yes", "no" were dropped as boolean values in the yaml 1.2 standard - which is the standard yq assumes.

See tips and tricks for more common problems and solutions.

yq's People

Contributors

actualben avatar bison-monica avatar cjnosal avatar codekow avatar dan-vystrcil avatar dependabot[bot] avatar ebourg avatar hobti01 avatar inspirit1986 avatar kenjones-cisco avatar matfax avatar mattphelps-8451 avatar mbenson avatar mhuxtable avatar mikefarah avatar mkatychev avatar mmorel-35 avatar naveensrinivasan avatar rmescandon avatar robertomier avatar runzexia avatar ryansiu1995 avatar scop avatar shashankv02 avatar supersandro2000 avatar teejaded avatar thehowl avatar vaab avatar xpzouying avatar zash avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yq's Issues

Bug in new array append feature with empty arrays.

Just did some testing on new append feature and noticed following bug:

command:
echo -e "a: 2\n" | yaml w - b[+] v

result:
a: 2
b:

  • null
  • v

Looks like one line fix:
change line: array = make([]interface{}, 1)
to: array = make([]interface{}, 0)

Add Array/String Slice

Add support for Array/String Slice

The .[10:15] syntax can be used to return a subarray of an array or substring of a string. The array returned by .[10:15] will be of length 5, containing the elements from index 10 (inclusive) to index 15 (exclusive). Either index may be negative (in which case it counts backwards from the end of the array), or omitted (in which case it refers to the start or end of the array).

Expected

a: Easy! as one two three
b:
  c: 2
  d: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
  e:
    - name: fred
      value: 3
    - name: sam
      value: 4
$ yaml r sample.yaml  b.d[2:5]
- 5
- 6
- 7
- 8

Add support for built-in function 'has(key)'

Add support for built-in function 'has(key)'

The builtin function has returns whether the input object has the given key, or the input array has an element at the given index.

has($key) has the same effect as checking whether $key is a member of the array returned by keys, although has will be faster.

push to exist array structure

In my case, I have to write yaml arrays to file in this way

    yaml w -i $COMPOSE_FILE services.$peerContainer.environment[0] a
    yaml w -i $COMPOSE_FILE services.$peerContainer.environment[1] b  
    yaml w -i $COMPOSE_FILE services.$peerContainer.environment[2] c  
    yaml w -i $COMPOSE_FILE services.$peerContainer.environment[3] d  
    yaml w -i $COMPOSE_FILE services.$peerContainer.environment[4] e  
    yaml w -i $COMPOSE_FILE services.$peerContainer.environment[5] f  
    yaml w -i $COMPOSE_FILE services.$peerContainer.environment[6] g  

which manually input index is clumsy. script file option might help, but I do not like to use this method
Is there any plan to support new feature like that
yaml w -i --append $COMPOSE_FILE services.$peerContainer.environment[] newValPush2end

Add support for Operator '*, /, and %'

Add support for Operator '*, /, and %'

These infix operators behave as expected when given two numbers. Division by zero raises an error. x % y computes x modulo y.

Multiplying a string by a number produces the concatenation of that string that many times. "x" * 0 produces null.

Dividing a string by another splits the first using the second as separators.

Multiplying two objects will merge them recursively: this works like addition but if both objects contain a value for the same key, and the values are objects, the two are merged with the same strategy.

Can't write Array

Build a config.yml like this:
test:
- aa

When I use yaml r config.yml test[0] , it output aa.
When I use yaml w -i config.yml test[0] bb , it gives this error.

panic: interface conversion: interface {} is []interface {}, not map[interface {}]interface {}

goroutine 1 [running]:
panic(0x665980, 0xc820070780)
/usr/local/Cellar/go/1.6/libexec/src/runtime/panic.go:464 +0x3e6
main.write(0xc820076f90, 0x7ffc1e8d26be, 0x4, 0xc82006fbd0, 0x1, 0x1, 0x5fe200, 0xc820074b20)
/Users/mikefarah/dev/go/src/github.com/mikefarah/yaml/data_navigator.go:13 +0x261
main.updateYaml(0xc820076cf0, 0x3, 0x3, 0x0, 0x0)
/Users/mikefarah/dev/go/src/github.com/mikefarah/yaml/yaml.go:122 +0x278
main.writeProperty(0xc82010c1e0, 0xc820076cf0, 0x3, 0x3)
/Users/mikefarah/dev/go/src/github.com/mikefarah/yaml/yaml.go:98 +0x4a
github.com/mikefarah/yaml/Godeps/_workspace/src/github.com/spf13/cobra.(_Command).execute(0xc82010c1e0, 0xc820076b70, 0x3, 0x3, 0x0, 0x0)
/Users/mikefarah/dev/go/src/github.com/mikefarah/yaml/Godeps/_workspace/src/github.com/spf13/cobra/command.go:547 +0x85a
github.com/mikefarah/yaml/Godeps/_workspace/src/github.com/spf13/cobra.(_Command).Execute(0xc82010c3c0, 0x0, 0x0)
/Users/mikefarah/dev/go/src/github.com/mikefarah/yaml/Godeps/_workspace/src/github.com/spf13/cobra/command.go:630 +0x46a
main.main()
/Users/mikefarah/dev/go/src/github.com/mikefarah/yaml/yaml.go:29 +0x36d

So is this an issue or I'm using wrong way to write Array?

Add support for built-in function 'to_entries, from_entries, with_entries'

Add support for built-in function 'to_entries, from_entries, with_entries'

These functions convert between an object and an array of key-value pairs. If to_entries is passed an object, then for each k: v entry in the input, the output array includes {"key": k, "value": v}.

from_entries does the opposite conversion, and with_entries(foo) is a shorthand for to_entries | map(foo) | from_entries, useful for doing some operation to all keys and values of an object. from_entries accepts key, Key, name, Name, value and Value as keys.

Add support for built-in function 'in'

Add support for built-in function 'in'

The builtin function in returns whether or not the input key is in the given object, or the input index corresponds to an element in the given array. It is, essentially, an inverse version of has.

List Values Are Unindented

I can't tell if this is expected, or a bug. Let's say I have the following Yaml file:

title: "My Book"
tags:
  - "adventure"
  - "novel"

and I run the following command: `yaml write -i mybooks.yml author "J.K. Rowling"

The updated Yaml file now looks like:

title: My Book
tags:
- adventure
- novel
author: J.K. Rowling

This GitHub Issue is due to the fact that the 'tags' list has lost its indention. That didn't look like valid Yaml to me so I ran it through http://www.yamllint.com/. While the Yaml did validate, the tags list was "corrected" to the indention I had it previously. So is this a bug?

Also, as you can see, the quotes around the strings are gone. I can see from this issue that it's because of the parser so I guess we can't do anything about it. Sucks though.

Convert to JSON panics if key not string

The Swagger / OpenAPI yaml files have responses where the code is the key.

      responses:
        201:
          description: Version successfully provisioned
          schema:
              $ref: '#/definitions/versionProvision'
yaml -j read api-docs/api.yaml paths
panic: interface conversion: interface {} is int, not string

goroutine 1 [running]:
main.toJSON(0x5e0500, 0xc0420ef780, 0xc0420b39a0, 0xc04208a8a8)
        /Users/mikefarah/dev/go/src/github.com/mikefarah/yaml/json_converter.go:29 +0x37c
main.toJSON(0x5e0500, 0xc0420ef7c0, 0xc0420b3a78, 0xc04208a748)
        /Users/mikefarah/dev/go/src/github.com/mikefarah/yaml/json_converter.go:29 +0x2c0
main.toJSON(0x5e0500, 0xc0420ef800, 0xc0420712f0, 0x0)
        /Users/mikefarah/dev/go/src/github.com/mikefarah/yaml/json_converter.go:29 +0x2c0
main.toJSON(0x5e0500, 0xc0420f5c20, 0xc04207ce00, 0xb)
        /Users/mikefarah/dev/go/src/github.com/mikefarah/yaml/json_converter.go:29 +0x2c0
main.jsonToString(0x5e0500, 0xc0420f5c20, 0x5aae17, 0xc042048c00)
        /Users/mikefarah/dev/go/src/github.com/mikefarah/yaml/json_converter.go:9 +0x49
main.print(0x5e0500, 0xc0420f5c20)
        /Users/mikefarah/dev/go/src/github.com/mikefarah/yaml/yaml.go:251 +0x4f
main.readProperty(0xc0420ba000, 0xc042070db0, 0x2, 0x3)
        /Users/mikefarah/dev/go/src/github.com/mikefarah/yaml/yaml.go:116 +0x6d
github.com/spf13/cobra.(*Command).execute(0xc0420ba000, 0xc042070cc0, 0x3, 0x3, 0xc0420ba000, 0xc042070cc0)
        /Users/mikefarah/dev/go/src/github.com/spf13/cobra/command.go:651 +0x241
github.com/spf13/cobra.(*Command).ExecuteC(0xc0420ba6c0, 0xc0420b3f78, 0xc, 0xc042046780)
        /Users/mikefarah/dev/go/src/github.com/spf13/cobra/command.go:726 +0x340
github.com/spf13/cobra.(*Command).Execute(0xc0420ba6c0, 0xc0420b3f60, 0x3)
        /Users/mikefarah/dev/go/src/github.com/spf13/cobra/command.go:685 +0x32
main.main()
        /Users/mikefarah/dev/go/src/github.com/mikefarah/yaml/yaml.go:40 +0x428

Add support for Operator '-'

Add support for Operator '-'

As well as normal arithmetic subtraction on numbers, the - operator can be used on arrays to remove all occurrences of the second array’s elements from the first array.

Any way to list top level keys only?

Is it currently possible to have the CLI only list the top level keys? For example, given the following yaml file:

a:
  b:
    c:
    - 'test'
    - "test2"
  d:
  e:

Is there a way to only list b, d and e and no other subkeys with something like yaml r test.yml a?

Add support for built-in function 'length'

Add support for built-in function 'length'

The builtin function length gets the length of various different types of value:

The length of a string is the number of Unicode codepoints it contains (which will be the same as its JSON-encoded length in bytes if it’s pure ASCII).

The length of an array is the number of elements.

The length of an object is the number of key-value pairs.

The length of null is zero.

update element of array

This is not an issue, but very important task for me:
let.s assume I have following yaml:

test:
  a:
    - name: name1
      value: 1
    - name: name2
      value: 2

and I need to update only value where name == name1

Is it possible with this tool?

Handle 'index out of range' errors more gracefully

When attempting to extract an entry from an empty array, the program exits rather abruptly with a panic:

$ echo 'a: []' | yaml r - 'a[0]'
panic: runtime error: index out of range

goroutine 1 [running]:
main.readArray(0x3c64e0, 0x0, 0x0, 0x0, 0xc20801e670, 0x0, 0x0, 0x0, 0x0)
        /Users/morgan/Projects/golang/src/github.com/mikefarah/yaml/data_navigator.go:65 +0xd6
main.recurse(0x1b5300, 0xc20801e600, 0x7fff5fbff9e3, 0x1, 0xc20801e670, 0x0, 0x0, 0x0, 0x0)
        /Users/morgan/Projects/golang/src/github.com/mikefarah/yaml/data_navigator.go:52 +0x36e
main.calculateValue(0x1b5300, 0xc20801e600, 0xc20801e670, 0x1, 0x1, 0x0, 0x0)
        /Users/morgan/Projects/golang/src/github.com/mikefarah/yaml/data_navigator.go:80 +0xcb
main.readMap(0xc20803ca50, 0x7fff5fbff9e1, 0x1, 0xc20801e670, 0x1, 0x1, 0x0, 0x0)
        /Users/morgan/Projects/golang/src/github.com/mikefarah/yaml/data_navigator.go:25 +0x182
main.read(0xc20801e520, 0x2, 0x2, 0x0, 0x0)
        /Users/morgan/Projects/golang/src/github.com/mikefarah/yaml/yaml.go:94 +0x196
main.readProperty(0xc208088000, 0xc20801e520, 0x2, 0x2)
        /Users/morgan/Projects/golang/src/github.com/mikefarah/yaml/yaml.go:80 +0x3c
github.com/mikefarah/yaml/Godeps/_workspace/src/github.com/spf13/cobra.(*Command).execute(0xc208088000, 0xc20801e3a0, 0x2, 0x2, 0x0, 0x0)
        /Users/morgan/Projects/golang/src/github.com/mikefarah/yaml/Godeps/_workspace/src/github.com/spf13/cobra/command.go:547 +0x82f
github.com/mikefarah/yaml/Godeps/_workspace/src/github.com/spf13/cobra.(*Command).Execute(0xc2080883c0, 0x0, 0x0)
        /Users/morgan/Projects/golang/src/github.com/mikefarah/yaml/Godeps/_workspace/src/github.com/spf13/cobra/command.go:630 +0x414
main.main()
        /Users/morgan/Projects/golang/src/github.com/mikefarah/yaml/yaml.go:29 +0x3c9

This is a bit user-hostile, and doesn't really point to where the issue arises in the source file in order to debug it.

how to make boolean to string in Yaml to Json convert

test.yml

UseMock: true
abc: 123

When I do yaml r -j testyml > test.json, it make the json file like

{"UseMock":true,"abc":123}

I want to convert true (bool) to true (string)
i.e
Require

{"UseMock":"true","abc":123}

Can't handle multiple yaml documents within one file

Say I have:

---
mykey: myvalue
---
mykey: myothervalue
---
mykey: myotherothervalue

I'd expect the tool to be able to handle all three documents and give me a list of values when I run
yaml r myfile.yaml mykey, instead it'd just give me the first value.

Is this something you'd be willing to add as a feature? Happy to work on it myself but I have limited go knowledge.

Can't process valid yaml

Running command yaml read test.yaml gather_facts results in output null, expected result is false. Culprit is the - in-front of become, which is valid yaml. If I remove it, it works but it should obviously work with it as well.

---
- become: true
  gather_facts: false
  hosts: lalaland
  name: "Apply smth"
  roles:
    - lala
    - land
  serial: 1

Dots in variable name

This script doesnt work for:

# parameters.yml
parameters:
  database.name: app
$ yaml read parameters.yml parameters.database.name
null

I think this is valid yaml.
Am I missing something?

Can't handle multiple yaml documents within one file

Given the following Kubernetes YAML configuration file:

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
   name: somename
spec:
   revisionHistoryLimit: 5
   minReadySeconds: 10
   strategy:
      type: RollingUpdate
      rollingUpdate:
         maxUnavailable: 0
         maxSurge: 1
   replicas: 1
   template:
      metadata:
         labels:
            microservice: somename
      spec: 
         containers:
         - name: serviceapi
           image: myimage:0.0.6
           ports:
           - containerPort: 8080
           env:
##### ENVIRONMENT VARIABLES
            - name: somename
              valueFrom:
                configMapKeyRef:
                   name: serviceapi-environment-configuration
                   key: somekey
---
apiVersion: v1
kind: Service
metadata:
  name: somename
  labels: 
     microservice: somename
spec:
   type: NodePort
   ports:
   - port: 8080
   selector:
      microservice: somename
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: some-name
  namespace: default
data:
  someData: data

This command will work:

./yaml w -i myfile.yaml spec.template.spec.containers[0].image myimage:0.0.19

The image value will be replaced, however, the file will then change to this:

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
   name: somename
spec:
   revisionHistoryLimit: 5
   minReadySeconds: 10
   strategy:
      type: RollingUpdate
      rollingUpdate:
         maxUnavailable: 0
         maxSurge: 1
   replicas: 1
   template:
      metadata:
         labels:
            microservice: somename
      spec: 
         containers:
         - name: serviceapi
           image: myimage:0.0.19
           ports:
           - containerPort: 8080
           env:
##### ENVIRONMENT VARIABLES
            - name: somename
              valueFrom:
                configMapKeyRef:
                   name: serviceapi-environment-configuration
                   key: somekey

As you can see, the Services and ConfigMap sections (denoted with ---) have disappeared.

Support --version Subcommand

Right now, yaml --version (or even yaml version) doesn't return the version of the release. I've seen in other Issues the author refer to release numbers. This should be outputted.

Can't read files that consist of a string or a sequence

The following two examples don't seem to work for me on Linux using version 1.11.

$ echo 'alphabet' | yaml r -
[error parsing data:  yaml: unmarshal errors:
  line 1: cannot unmarshal !!str `alphabet` into yaml.MapSlice]

$ echo -e '- alpha\n- beta' | yaml r -
[error parsing data:  yaml: unmarshal errors:
  line 1: cannot unmarshal !!str `alpha` into yaml.MapItem
  line 2: cannot unmarshal !!str `beta` into yaml.MapItem]

no matches found: write_files[0].path [cloud-config.yml]

I'm trying to read a value of write_files[0].content and then set another value to the same path.

It doesn't work with write_files[0].path

$ yaml r templates/coreos-install-cloud-config/skeleton.yml \                     
        write_files[0].path 
bash: no matches found: write_files[0].path

Doesn't work with write_files[0]

yaml r templates/coreos-install-cloud-config/skeleton.yml \
        write_files[0]
bash: no matches found: write_files[0]

But if I request the full value of write_files the I get what I asked for:

yaml r templates/coreos-install-cloud-config/skeleton.yml \
        write_files        
- path: /root/process-cloud-config.sh
  permissions: "0755"
  owner: root
  content: null
- path: /root/cloud-config.yml
  permissions: "0644"
  owner: root
  content: null

Here is the file I'm processing:

write_files:
  - path: /root/process-cloud-config.sh
    permissions: "0755"
    owner: root
    content: 

  - path: /root/cloud-config.yml
    permissions: "0644"
    owner: root
    content:

Can you advise how to handle my case with yaml tool?

Single quotes vs Double quotes

When updating a Yaml file, the original quotes are not maintained, e.g. 'version' originally has single quotes, but this ends up with double quotes.

version: '2'
services:
  test:
    image: ubuntu:14.04
    stdin_open: true
    tty: true

yaml w docker-compose.yml services.test.image nginx:master

services:
  test:
    image: nginx:master
    stdin_open: true
    tty: true
version: "2"

Incorrect parsing of file with nested key

Given the following example:

version: '2'
services:
  test:
    image: ubuntu:14.04
    stdin_open: true
    tty: true

When I try to update the image key, using both the in place and write to stdout command:

yaml w docker-compose.yml services.test.image nginx:master
yaml w -i docker-compose.yml services.test.image nginx:master

I get unexpected output:

services:
  test:
    image: nginx:master
    stdin_open: true
    tty: true
version: "2"

Add support for built-in function 'add'

Add support for built-in function 'add'

The filter add takes as input an array, and produces as output the elements of the array added together. This might mean summed, concatenated or merged depending on the types of the elements of the input array - the rules are the same as those for the + operator (described above).

If the input is an empty array, add returns null.

Add support for Pipe

Add support for Pipe

The | operator combines two filters by feeding the output(s) of the one on the left into the input of the one on the right. It’s pretty much the same as the Unix shell’s pipe, if you’re used to that.

If the one on the left produces multiple results, the one on the right will be run for each of those results. So, the expression .[] | .foo retrieves the “foo” field of each element of the input array.

Note that .a.b.c is the same as .a | .b | .c.

Note too that . is the input value at the particular stage in a “pipeline”, specifically: where the . expression appears. Thus .a | . | .b is the same as .a.b, as the . in the middle refers to whatever value .a produced.

Add support for built-in function 'keys, keys_unsorted'

Add support for built-in function 'keys, keys_unsorted'

The builtin function keys, when given an object, returns its keys in an array.

The keys are sorted “alphabetically”, by unicode codepoint order. This is not an order that makes particular sense in any particular language, but you can count on it being the same for any two objects with the same set of keys, regardless of locale settings.

When keys is given an array, it returns the valid indices for that array: the integers from 0 to length-1.

The keys_unsorted function is just like keys, but if the input is an object then the keys will not be sorted, instead the keys will roughly be in insertion order.

In place write strips out comments

The CLI strips out comments given the following yaml file:

# comment
a:
  b:

Using the following command for my test:

yaml w -i test.yml a.b.c[0] "test"

Yaml file order is not maintained

When using the write command, the order of the fields in the Yaml file is not maintained.

version: '2'
services:
  test:
    image: ubuntu:14.04
    stdin_open: true
    tty: true

yaml w docker-compose.yml services.test.image nginx:master

services:
  test:
    image: nginx:master
    stdin_open: true
    tty: true
version: "2"

Add support for Comma

Add support for Comma

If two filters are separated by a comma, then the same input will be fed into both and the two filters’
output value streams will be concatenated in order: first, all of the outputs produced by the left expression, and then all of the outputs produced by the right. For instance, filter .foo, .bar, produces both the “foo” fields and “bar” fields as separate outputs.

Expected

a: Easy! as one two three
b:
  c: 2
  d: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
  e:
    - name: fred
      value: 3
    - name: sam
      value: 4
$ yaml r sample.yaml 'b.e[0].name,b.e[1].name'
fred sam

Add support for Operator '+'

Add support for Operator '+'

The operator + takes two filters, applies them both to the same input, and adds the results together. What “adding” means depends on the types involved:

Numbers are added by normal arithmetic.

Arrays are added by being concatenated into a larger array.

Strings are added by being joined into a larger string.

Objects are added by merging, that is, inserting all the key-value pairs from both objects into a single combined object. If both objects contain a value for the same key, the object on the right of the + wins. (For recursive merge use the * operator.)

null can be added to any value, and returns the other value unchanged.

Setting value to empty string

Version: 1.10

File: (project.yml)

metadata:
  name: example
  version: 0.4.0
  pretag: dev

Command:

    yaml write -i project.yml metadata.pretag ''

Response:

panic: runtime error: index out of range

goroutine 1 [running]:
panic(0x5e3500, 0xc4200100c0)
        /usr/local/Cellar/go/1.7.5/libexec/src/runtime/panic.go:500 +0x1a1
main.parseValue(0x7ffd1417ced1, 0x0, 0x1, 0xc4200ae880)
        /Users/mikefarah/dev/go/src/github.com/mikefarah/yaml/yaml.go:199 +0x83e
main.updateYaml(0xc4200bc2d0, 0x3, 0x5, 0x0, 0xc4200e3c77)
        /Users/mikefarah/dev/go/src/github.com/mikefarah/yaml/yaml.go:188 +0x2e1
main.writeProperty(0xc4201481e0, 0xc4200bc2d0, 0x3, 0x5)
        /Users/mikefarah/dev/go/src/github.com/mikefarah/yaml/yaml.go:162 +0x58
github.com/mikefarah/yaml/Godeps/_workspace/src/github.com/spf13/cobra.(*Command).execute(0xc4201481e0, 0xc4200bc280, 0x5, 0x5, 0xc4201481e0, 0xc4200bc280)
        /Users/mikefarah/dev/go/src/github.com/mikefarah/yaml/Godeps/_workspace/src/github.com/spf13/cobra/command.go:547 +0x411
github.com/mikefarah/yaml/Godeps/_workspace/src/github.com/spf13/cobra.(*Command).Execute(0xc4201485a0, 0xc4200e3f10, 0x3)
        /Users/mikefarah/dev/go/src/github.com/mikefarah/yaml/Godeps/_workspace/src/github.com/spf13/cobra/command.go:630 +0x398
main.main()
        /Users/mikefarah/dev/go/src/github.com/mikefarah/yaml/yaml.go:41 +0x449

Seems like setting a value to empty should be valid, but instead it will panic.

Error: unknown shorthand flag when value starts with a hypen

yaml w -i task-output/manifest.yml 'env.JAVA_OPTS' '-Djava.security.egd=file:///dev/urandom'
Usage:
  yaml write [yaml_file] [path] [value] [flags]

Aliases:
  write, w


Examples:

yaml write things.yaml a.b.c cat
yaml write --inplace things.yaml a.b.c cat
yaml w -i things.yaml a.b.c cat
yaml w --script update_script.yaml things.yaml
yaml w -i -s update_script.yaml things.yaml


Flags:
  -i, --inplace[=false]: update the yaml file inplace
  -s, --script="": yaml script for updating yaml

Global Flags:
  -J, --fromjson[=false]: input as json
  -j, --tojson[=false]: output as json
  -t, --trim[=true]: trim yaml output
  -v, --verbose[=false]: verbose mode

Error: unknown shorthand flag: 'D' in -Djava.security.egd=file:///dev/urandom

Can't create sequence

I'm trying to create this:

applications:
- name: wasabi
- name: oscar

By doing this:

touch manifest.yml
yaml w -i manifest.yml applications[0].name wasabi
yaml w -i manifest.yml applications[1].name oscar

but... the third line (yaml w -i manifest.yml applications[1].name oscar) results in this:

# yaml w -i manifest.yml applications[1].name oscar
panic: runtime error: index out of range

goroutine 1 [running]:
panic(0x5e3500, 0xc420010080)
	/usr/local/Cellar/go/1.7.5/libexec/src/runtime/panic.go:500 +0x1a1
main.writeArray(0x5cb680, 0xc42000ec60, 0xc4200487d0, 0x2, 0x3, 0x5cfbc0, 0xc420010fd0, 0xc4200b1980, 0x4d3040, 0xc420066c90)
	/Users/mikefarah/dev/go/src/github.com/mikefarah/yaml/data_navigator.go:85 +0x5c3
main.updatedChildValue(0x5cb680, 0xc42000ec60, 0xc4200487d0, 0x2, 0x3, 0x5cfbc0, 0xc420010fd0, 0x4146be, 0xc42000ece0)
	/Users/mikefarah/dev/go/src/github.com/mikefarah/yaml/data_navigator.go:61 +0x1a6
main.writeMap(0x5da5a0, 0xc42000ece0, 0xc4200487c0, 0x3, 0x4, 0x5cfbc0, 0xc420010fd0, 0xc4200b1b47, 0xc4200b1b60, 0x52f630)
	/Users/mikefarah/dev/go/src/github.com/mikefarah/yaml/data_navigator.go:44 +0x38c
main.updateYaml(0xc420048740, 0x3, 0x4, 0xc420010fb5, 0xc4200b1c77)
	/Users/mikefarah/dev/go/src/github.com/mikefarah/yaml/yaml.go:191 +0x2de
main.writeProperty(0xc4201021e0, 0xc420048740, 0x3, 0x4)
	/Users/mikefarah/dev/go/src/github.com/mikefarah/yaml/yaml.go:167 +0x58
github.com/mikefarah/yaml/Godeps/_workspace/src/github.com/spf13/cobra.(*Command).execute(0xc4201021e0, 0xc4200485c0, 0x4, 0x4, 0xc4201021e0, 0xc4200485c0)
	/Users/mikefarah/dev/go/src/github.com/mikefarah/yaml/Godeps/_workspace/src/github.com/spf13/cobra/command.go:547 +0x411
github.com/mikefarah/yaml/Godeps/_workspace/src/github.com/spf13/cobra.(*Command).Execute(0xc4201025a0, 0xc4200b1f10, 0x3)
	/Users/mikefarah/dev/go/src/github.com/mikefarah/yaml/Godeps/_workspace/src/github.com/spf13/cobra/command.go:630 +0x398
main.main()
	/Users/mikefarah/dev/go/src/github.com/mikefarah/yaml/yaml.go:41 +0x449

I'm new to this project, so not sure if i'm doing something wrong... or if I've hit a bug.

[Feature] Add `merge` subcommand

Add ability to merge multiple yaml files.

example:

yaml merge data1.yaml data2.yaml data3.yaml

yaml merge --overwrite data1.yaml data2.yaml data3.yaml

yaml merge -i data1.yaml data2.yaml data3.yaml

If agreeable, I can submit a PR with the enhancement.

delete node at a path

Is there possible to support write key with empty value like that:

networks:  
    networkName:

Add support for built-in function 'map(x), map_values(x)'

Add support for built-in function 'map(x), map_values(x)'

For any filter x, map(x) will run that filter for each element of the input array, and return the outputs in a new array. map(.+1) will increment each element of an array of numbers.

Similarly, map_values(x) will run that filter for each element, but it will return an object when an object is passed.

map(x) is equivalent to [.[] | x]. In fact, this is how it’s defined. Similarly, map_values(x) is defined as .[] |= x.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.