2
0
mirror of https://github.com/jmespath/jp synced 2025-08-22 01:27:28 +00:00

Use godep to vendor dependencies

This commit is contained in:
James Saryerwinnie 2015-08-10 22:46:39 -07:00
parent 71047238e8
commit bbaf4212af
696 changed files with 11744 additions and 2 deletions

15
Godeps/Godeps.json generated Normal file
View File

@ -0,0 +1,15 @@
{
"ImportPath": "github.com/jmespath/jp",
"GoVersion": "go1.4.2",
"Deps": [
{
"ImportPath": "github.com/codegangsta/cli",
"Comment": "1.2.0-66-g6086d79",
"Rev": "6086d7927ec35315964d9fea46df6c04e6d697c1"
},
{
"ImportPath": "github.com/jmespath/go-jmespath",
"Rev": "4fc9c086304a9794c7f5f3c570f4290ba18b79d0"
}
]
}

5
Godeps/Readme generated Normal file
View File

@ -0,0 +1,5 @@
This directory tree is generated automatically by godep.
Please do not edit.
See https://github.com/tools/godep for more information.

2
Godeps/_workspace/.gitignore generated vendored Normal file
View File

@ -0,0 +1,2 @@
/pkg
/bin

View File

@ -0,0 +1,6 @@
language: go
go: 1.1
script:
- go vet ./...
- go test -v ./...

View File

@ -0,0 +1,21 @@
Copyright (C) 2013 Jeremy Saenz
All Rights Reserved.
MIT LICENSE
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -0,0 +1,298 @@
[![Build Status](https://travis-ci.org/codegangsta/cli.png?branch=master)](https://travis-ci.org/codegangsta/cli)
# cli.go
cli.go is simple, fast, and fun package for building command line apps in Go. The goal is to enable developers to write fast and distributable command line applications in an expressive way.
You can view the API docs here:
http://godoc.org/github.com/codegangsta/cli
## Overview
Command line apps are usually so tiny that there is absolutely no reason why your code should *not* be self-documenting. Things like generating help text and parsing command flags/options should not hinder productivity when writing a command line app.
**This is where cli.go comes into play.** cli.go makes command line programming fun, organized, and expressive!
## Installation
Make sure you have a working Go environment (go 1.1 is *required*). [See the install instructions](http://golang.org/doc/install.html).
To install `cli.go`, simply run:
```
$ go get github.com/codegangsta/cli
```
Make sure your `PATH` includes to the `$GOPATH/bin` directory so your commands can be easily used:
```
export PATH=$PATH:$GOPATH/bin
```
## Getting Started
One of the philosophies behind cli.go is that an API should be playful and full of discovery. So a cli.go app can be as little as one line of code in `main()`.
``` go
package main
import (
"os"
"github.com/codegangsta/cli"
)
func main() {
cli.NewApp().Run(os.Args)
}
```
This app will run and show help text, but is not very useful. Let's give an action to execute and some help documentation:
``` go
package main
import (
"os"
"github.com/codegangsta/cli"
)
func main() {
app := cli.NewApp()
app.Name = "boom"
app.Usage = "make an explosive entrance"
app.Action = func(c *cli.Context) {
println("boom! I say!")
}
app.Run(os.Args)
}
```
Running this already gives you a ton of functionality, plus support for things like subcommands and flags, which are covered below.
## Example
Being a programmer can be a lonely job. Thankfully by the power of automation that is not the case! Let's create a greeter app to fend off our demons of loneliness!
Start by creating a directory named `greet`, and within it, add a file, `greet.go` with the following code in it:
``` go
package main
import (
"os"
"github.com/codegangsta/cli"
)
func main() {
app := cli.NewApp()
app.Name = "greet"
app.Usage = "fight the loneliness!"
app.Action = func(c *cli.Context) {
println("Hello friend!")
}
app.Run(os.Args)
}
```
Install our command to the `$GOPATH/bin` directory:
```
$ go install
```
Finally run our new command:
```
$ greet
Hello friend!
```
cli.go also generates some bitchass help text:
```
$ greet help
NAME:
greet - fight the loneliness!
USAGE:
greet [global options] command [command options] [arguments...]
VERSION:
0.0.0
COMMANDS:
help, h Shows a list of commands or help for one command
GLOBAL OPTIONS
--version Shows version information
```
### Arguments
You can lookup arguments by calling the `Args` function on `cli.Context`.
``` go
...
app.Action = func(c *cli.Context) {
println("Hello", c.Args()[0])
}
...
```
### Flags
Setting and querying flags is simple.
``` go
...
app.Flags = []cli.Flag {
cli.StringFlag{
Name: "lang",
Value: "english",
Usage: "language for the greeting",
},
}
app.Action = func(c *cli.Context) {
name := "someone"
if len(c.Args()) > 0 {
name = c.Args()[0]
}
if c.String("lang") == "spanish" {
println("Hola", name)
} else {
println("Hello", name)
}
}
...
```
#### Alternate Names
You can set alternate (or short) names for flags by providing a comma-delimited list for the `Name`. e.g.
``` go
app.Flags = []cli.Flag {
cli.StringFlag{
Name: "lang, l",
Value: "english",
Usage: "language for the greeting",
},
}
```
That flag can then be set with `--lang spanish` or `-l spanish`. Note that giving two different forms of the same flag in the same command invocation is an error.
#### Values from the Environment
You can also have the default value set from the environment via `EnvVar`. e.g.
``` go
app.Flags = []cli.Flag {
cli.StringFlag{
Name: "lang, l",
Value: "english",
Usage: "language for the greeting",
EnvVar: "APP_LANG",
},
}
```
The `EnvVar` may also be given as a comma-delimited "cascade", where the first environment variable that resolves is used as the default.
``` go
app.Flags = []cli.Flag {
cli.StringFlag{
Name: "lang, l",
Value: "english",
Usage: "language for the greeting",
EnvVar: "LEGACY_COMPAT_LANG,APP_LANG,LANG",
},
}
```
### Subcommands
Subcommands can be defined for a more git-like command line app.
```go
...
app.Commands = []cli.Command{
{
Name: "add",
ShortName: "a",
Usage: "add a task to the list",
Action: func(c *cli.Context) {
println("added task: ", c.Args().First())
},
},
{
Name: "complete",
ShortName: "c",
Usage: "complete a task on the list",
Action: func(c *cli.Context) {
println("completed task: ", c.Args().First())
},
},
{
Name: "template",
ShortName: "r",
Usage: "options for task templates",
Subcommands: []cli.Command{
{
Name: "add",
Usage: "add a new template",
Action: func(c *cli.Context) {
println("new task template: ", c.Args().First())
},
},
{
Name: "remove",
Usage: "remove an existing template",
Action: func(c *cli.Context) {
println("removed task template: ", c.Args().First())
},
},
},
},
}
...
```
### Bash Completion
You can enable completion commands by setting the `EnableBashCompletion`
flag on the `App` object. By default, this setting will only auto-complete to
show an app's subcommands, but you can write your own completion methods for
the App or its subcommands.
```go
...
var tasks = []string{"cook", "clean", "laundry", "eat", "sleep", "code"}
app := cli.NewApp()
app.EnableBashCompletion = true
app.Commands = []cli.Command{
{
Name: "complete",
ShortName: "c",
Usage: "complete a task on the list",
Action: func(c *cli.Context) {
println("completed task: ", c.Args().First())
},
BashComplete: func(c *cli.Context) {
// This will complete if no args are passed
if len(c.Args()) > 0 {
return
}
for _, t := range tasks {
fmt.Println(t)
}
},
}
}
...
```
#### To Enable
Source the `autocomplete/bash_autocomplete` file in your `.bashrc` file while
setting the `PROG` variable to the name of your program:
`PROG=myprogram source /.../cli/autocomplete/bash_autocomplete`
## Contribution Guidelines
Feel free to put up a pull request to fix a bug or maybe add a feature. I will give it a code review and make sure that it does not break backwards compatibility. If I or any other collaborators agree that it is in line with the vision of the project, we will work with you to get the code into a mergeable state and merge it into the master branch.
If you have contributed something significant to the project, I will most likely add you as a collaborator. As a collaborator you are given the ability to merge others pull requests. It is very important that new code does not break existing code, so be careful about what code you do choose to merge. If you have any questions feel free to link @codegangsta to the issue in question and we can review it together.
If you feel like you have contributed to the project but have not yet been added as a collaborator, I probably forgot to add you. Hit @codegangsta up over email and we will get it figured out.

275
Godeps/_workspace/src/github.com/codegangsta/cli/app.go generated vendored Normal file
View File

@ -0,0 +1,275 @@
package cli
import (
"fmt"
"io"
"io/ioutil"
"os"
"text/tabwriter"
"text/template"
"time"
)
// App is the main structure of a cli application. It is recomended that
// and app be created with the cli.NewApp() function
type App struct {
// The name of the program. Defaults to os.Args[0]
Name string
// Description of the program.
Usage string
// Version of the program
Version string
// List of commands to execute
Commands []Command
// List of flags to parse
Flags []Flag
// Boolean to enable bash completion commands
EnableBashCompletion bool
// Boolean to hide built-in help command
HideHelp bool
// Boolean to hide built-in version flag
HideVersion bool
// An action to execute when the bash-completion flag is set
BashComplete func(context *Context)
// An action to execute before any subcommands are run, but after the context is ready
// If a non-nil error is returned, no subcommands are run
Before func(context *Context) error
// The action to execute when no subcommands are specified
Action func(context *Context)
// Execute this function if the proper command cannot be found
CommandNotFound func(context *Context, command string)
// Compilation date
Compiled time.Time
// Author
Author string
// Author e-mail
Email string
// Writer writer to write output to
Writer io.Writer
}
// Tries to find out when this binary was compiled.
// Returns the current time if it fails to find it.
func compileTime() time.Time {
info, err := os.Stat(os.Args[0])
if err != nil {
return time.Now()
}
return info.ModTime()
}
// Creates a new cli Application with some reasonable defaults for Name, Usage, Version and Action.
func NewApp() *App {
return &App{
Name: os.Args[0],
Usage: "A new cli application",
Version: "0.0.0",
BashComplete: DefaultAppComplete,
Action: helpCommand.Action,
Compiled: compileTime(),
Author: "Author",
Email: "unknown@email",
Writer: os.Stdout,
}
}
// Entry point to the cli app. Parses the arguments slice and routes to the proper flag/args combination
func (a *App) Run(arguments []string) error {
if HelpPrinter == nil {
defer func() {
HelpPrinter = nil
}()
HelpPrinter = func(templ string, data interface{}) {
w := tabwriter.NewWriter(a.Writer, 0, 8, 1, '\t', 0)
t := template.Must(template.New("help").Parse(templ))
err := t.Execute(w, data)
if err != nil {
panic(err)
}
w.Flush()
}
}
// append help to commands
if a.Command(helpCommand.Name) == nil && !a.HideHelp {
a.Commands = append(a.Commands, helpCommand)
if (HelpFlag != BoolFlag{}) {
a.appendFlag(HelpFlag)
}
}
//append version/help flags
if a.EnableBashCompletion {
a.appendFlag(BashCompletionFlag)
}
if !a.HideVersion {
a.appendFlag(VersionFlag)
}
// parse flags
set := flagSet(a.Name, a.Flags)
set.SetOutput(ioutil.Discard)
err := set.Parse(arguments[1:])
nerr := normalizeFlags(a.Flags, set)
if nerr != nil {
fmt.Fprintln(a.Writer, nerr)
context := NewContext(a, set, set)
ShowAppHelp(context)
fmt.Fprintln(a.Writer)
return nerr
}
context := NewContext(a, set, set)
if err != nil {
fmt.Fprintf(a.Writer, "Incorrect Usage.\n\n")
ShowAppHelp(context)
fmt.Fprintln(a.Writer)
return err
}
if checkCompletions(context) {
return nil
}
if checkHelp(context) {
return nil
}
if checkVersion(context) {
return nil
}
if a.Before != nil {
err := a.Before(context)
if err != nil {
return err
}
}
args := context.Args()
if args.Present() {
name := args.First()
c := a.Command(name)
if c != nil {
return c.Run(context)
}
}
// Run default Action
a.Action(context)
return nil
}
// Another entry point to the cli app, takes care of passing arguments and error handling
func (a *App) RunAndExitOnError() {
if err := a.Run(os.Args); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
// Invokes the subcommand given the context, parses ctx.Args() to generate command-specific flags
func (a *App) RunAsSubcommand(ctx *Context) error {
// append help to commands
if len(a.Commands) > 0 {
if a.Command(helpCommand.Name) == nil && !a.HideHelp {
a.Commands = append(a.Commands, helpCommand)
if (HelpFlag != BoolFlag{}) {
a.appendFlag(HelpFlag)
}
}
}
// append flags
if a.EnableBashCompletion {
a.appendFlag(BashCompletionFlag)
}
// parse flags
set := flagSet(a.Name, a.Flags)
set.SetOutput(ioutil.Discard)
err := set.Parse(ctx.Args().Tail())
nerr := normalizeFlags(a.Flags, set)
context := NewContext(a, set, ctx.globalSet)
if nerr != nil {
fmt.Fprintln(a.Writer, nerr)
if len(a.Commands) > 0 {
ShowSubcommandHelp(context)
} else {
ShowCommandHelp(ctx, context.Args().First())
}
fmt.Fprintln(a.Writer)
return nerr
}
if err != nil {
fmt.Fprintf(a.Writer, "Incorrect Usage.\n\n")
ShowSubcommandHelp(context)
return err
}
if checkCompletions(context) {
return nil
}
if len(a.Commands) > 0 {
if checkSubcommandHelp(context) {
return nil
}
} else {
if checkCommandHelp(ctx, context.Args().First()) {
return nil
}
}
if a.Before != nil {
err := a.Before(context)
if err != nil {
return err
}
}
args := context.Args()
if args.Present() {
name := args.First()
c := a.Command(name)
if c != nil {
return c.Run(context)
}
}
// Run default Action
a.Action(context)
return nil
}
// Returns the named command on App. Returns nil if the command does not exist
func (a *App) Command(name string) *Command {
for _, c := range a.Commands {
if c.HasName(name) {
return &c
}
}
return nil
}
func (a *App) hasFlag(flag Flag) bool {
for _, f := range a.Flags {
if flag == f {
return true
}
}
return false
}
func (a *App) appendFlag(flag Flag) {
if !a.hasFlag(flag) {
a.Flags = append(a.Flags, flag)
}
}

View File

@ -0,0 +1,554 @@
package cli_test
import (
"flag"
"fmt"
"os"
"testing"
"github.com/jmespath/jp/Godeps/_workspace/src/github.com/codegangsta/cli"
)
func ExampleApp() {
// set args for examples sake
os.Args = []string{"greet", "--name", "Jeremy"}
app := cli.NewApp()
app.Name = "greet"
app.Flags = []cli.Flag{
cli.StringFlag{Name: "name", Value: "bob", Usage: "a name to say"},
}
app.Action = func(c *cli.Context) {
fmt.Printf("Hello %v\n", c.String("name"))
}
app.Run(os.Args)
// Output:
// Hello Jeremy
}
func ExampleAppSubcommand() {
// set args for examples sake
os.Args = []string{"say", "hi", "english", "--name", "Jeremy"}
app := cli.NewApp()
app.Name = "say"
app.Commands = []cli.Command{
{
Name: "hello",
ShortName: "hi",
Usage: "use it to see a description",
Description: "This is how we describe hello the function",
Subcommands: []cli.Command{
{
Name: "english",
ShortName: "en",
Usage: "sends a greeting in english",
Description: "greets someone in english",
Flags: []cli.Flag{
cli.StringFlag{
Name: "name",
Value: "Bob",
Usage: "Name of the person to greet",
},
},
Action: func(c *cli.Context) {
fmt.Println("Hello,", c.String("name"))
},
},
},
},
}
app.Run(os.Args)
// Output:
// Hello, Jeremy
}
func ExampleAppHelp() {
// set args for examples sake
os.Args = []string{"greet", "h", "describeit"}
app := cli.NewApp()
app.Name = "greet"
app.Flags = []cli.Flag{
cli.StringFlag{Name: "name", Value: "bob", Usage: "a name to say"},
}
app.Commands = []cli.Command{
{
Name: "describeit",
ShortName: "d",
Usage: "use it to see a description",
Description: "This is how we describe describeit the function",
Action: func(c *cli.Context) {
fmt.Printf("i like to describe things")
},
},
}
app.Run(os.Args)
// Output:
// NAME:
// describeit - use it to see a description
//
// USAGE:
// command describeit [arguments...]
//
// DESCRIPTION:
// This is how we describe describeit the function
}
func ExampleAppBashComplete() {
// set args for examples sake
os.Args = []string{"greet", "--generate-bash-completion"}
app := cli.NewApp()
app.Name = "greet"
app.EnableBashCompletion = true
app.Commands = []cli.Command{
{
Name: "describeit",
ShortName: "d",
Usage: "use it to see a description",
Description: "This is how we describe describeit the function",
Action: func(c *cli.Context) {
fmt.Printf("i like to describe things")
},
}, {
Name: "next",
Usage: "next example",
Description: "more stuff to see when generating bash completion",
Action: func(c *cli.Context) {
fmt.Printf("the next example")
},
},
}
app.Run(os.Args)
// Output:
// describeit
// d
// next
// help
// h
}
func TestApp_Run(t *testing.T) {
s := ""
app := cli.NewApp()
app.Action = func(c *cli.Context) {
s = s + c.Args().First()
}
err := app.Run([]string{"command", "foo"})
expect(t, err, nil)
err = app.Run([]string{"command", "bar"})
expect(t, err, nil)
expect(t, s, "foobar")
}
var commandAppTests = []struct {
name string
expected bool
}{
{"foobar", true},
{"batbaz", true},
{"b", true},
{"f", true},
{"bat", false},
{"nothing", false},
}
func TestApp_Command(t *testing.T) {
app := cli.NewApp()
fooCommand := cli.Command{Name: "foobar", ShortName: "f"}
batCommand := cli.Command{Name: "batbaz", ShortName: "b"}
app.Commands = []cli.Command{
fooCommand,
batCommand,
}
for _, test := range commandAppTests {
expect(t, app.Command(test.name) != nil, test.expected)
}
}
func TestApp_CommandWithArgBeforeFlags(t *testing.T) {
var parsedOption, firstArg string
app := cli.NewApp()
command := cli.Command{
Name: "cmd",
Flags: []cli.Flag{
cli.StringFlag{Name: "option", Value: "", Usage: "some option"},
},
Action: func(c *cli.Context) {
parsedOption = c.String("option")
firstArg = c.Args().First()
},
}
app.Commands = []cli.Command{command}
app.Run([]string{"", "cmd", "my-arg", "--option", "my-option"})
expect(t, parsedOption, "my-option")
expect(t, firstArg, "my-arg")
}
func TestApp_RunAsSubcommandParseFlags(t *testing.T) {
var context *cli.Context
a := cli.NewApp()
a.Commands = []cli.Command{
{
Name: "foo",
Action: func(c *cli.Context) {
context = c
},
Flags: []cli.Flag{
cli.StringFlag{
Name: "lang",
Value: "english",
Usage: "language for the greeting",
},
},
Before: func(_ *cli.Context) error { return nil },
},
}
a.Run([]string{"", "foo", "--lang", "spanish", "abcd"})
expect(t, context.Args().Get(0), "abcd")
expect(t, context.String("lang"), "spanish")
}
func TestApp_CommandWithFlagBeforeTerminator(t *testing.T) {
var parsedOption string
var args []string
app := cli.NewApp()
command := cli.Command{
Name: "cmd",
Flags: []cli.Flag{
cli.StringFlag{Name: "option", Value: "", Usage: "some option"},
},
Action: func(c *cli.Context) {
parsedOption = c.String("option")
args = c.Args()
},
}
app.Commands = []cli.Command{command}
app.Run([]string{"", "cmd", "my-arg", "--option", "my-option", "--", "--notARealFlag"})
expect(t, parsedOption, "my-option")
expect(t, args[0], "my-arg")
expect(t, args[1], "--")
expect(t, args[2], "--notARealFlag")
}
func TestApp_CommandWithNoFlagBeforeTerminator(t *testing.T) {
var args []string
app := cli.NewApp()
command := cli.Command{
Name: "cmd",
Action: func(c *cli.Context) {
args = c.Args()
},
}
app.Commands = []cli.Command{command}
app.Run([]string{"", "cmd", "my-arg", "--", "notAFlagAtAll"})
expect(t, args[0], "my-arg")
expect(t, args[1], "--")
expect(t, args[2], "notAFlagAtAll")
}
func TestApp_Float64Flag(t *testing.T) {
var meters float64
app := cli.NewApp()
app.Flags = []cli.Flag{
cli.Float64Flag{Name: "height", Value: 1.5, Usage: "Set the height, in meters"},
}
app.Action = func(c *cli.Context) {
meters = c.Float64("height")
}
app.Run([]string{"", "--height", "1.93"})
expect(t, meters, 1.93)
}
func TestApp_ParseSliceFlags(t *testing.T) {
var parsedOption, firstArg string
var parsedIntSlice []int
var parsedStringSlice []string
app := cli.NewApp()
command := cli.Command{
Name: "cmd",
Flags: []cli.Flag{
cli.IntSliceFlag{Name: "p", Value: &cli.IntSlice{}, Usage: "set one or more ip addr"},
cli.StringSliceFlag{Name: "ip", Value: &cli.StringSlice{}, Usage: "set one or more ports to open"},
},
Action: func(c *cli.Context) {
parsedIntSlice = c.IntSlice("p")
parsedStringSlice = c.StringSlice("ip")
parsedOption = c.String("option")
firstArg = c.Args().First()
},
}
app.Commands = []cli.Command{command}
app.Run([]string{"", "cmd", "my-arg", "-p", "22", "-p", "80", "-ip", "8.8.8.8", "-ip", "8.8.4.4"})
IntsEquals := func(a, b []int) bool {
if len(a) != len(b) {
return false
}
for i, v := range a {
if v != b[i] {
return false
}
}
return true
}
StrsEquals := func(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i, v := range a {
if v != b[i] {
return false
}
}
return true
}
var expectedIntSlice = []int{22, 80}
var expectedStringSlice = []string{"8.8.8.8", "8.8.4.4"}
if !IntsEquals(parsedIntSlice, expectedIntSlice) {
t.Errorf("%v does not match %v", parsedIntSlice, expectedIntSlice)
}
if !StrsEquals(parsedStringSlice, expectedStringSlice) {
t.Errorf("%v does not match %v", parsedStringSlice, expectedStringSlice)
}
}
func TestApp_DefaultStdout(t *testing.T) {
app := cli.NewApp()
if app.Writer != os.Stdout {
t.Error("Default output writer not set.")
}
}
type mockWriter struct {
written []byte
}
func (fw *mockWriter) Write(p []byte) (n int, err error) {
if fw.written == nil {
fw.written = p
} else {
fw.written = append(fw.written, p...)
}
return len(p), nil
}
func (fw *mockWriter) GetWritten() (b []byte) {
return fw.written
}
func TestApp_SetStdout(t *testing.T) {
w := &mockWriter{}
app := cli.NewApp()
app.Name = "test"
app.Writer = w
err := app.Run([]string{"help"})
if err != nil {
t.Fatalf("Run error: %s", err)
}
if len(w.written) == 0 {
t.Error("App did not write output to desired writer.")
}
}
func TestApp_BeforeFunc(t *testing.T) {
beforeRun, subcommandRun := false, false
beforeError := fmt.Errorf("fail")
var err error
app := cli.NewApp()
app.Before = func(c *cli.Context) error {
beforeRun = true
s := c.String("opt")
if s == "fail" {
return beforeError
}
return nil
}
app.Commands = []cli.Command{
cli.Command{
Name: "sub",
Action: func(c *cli.Context) {
subcommandRun = true
},
},
}
app.Flags = []cli.Flag{
cli.StringFlag{Name: "opt"},
}
// run with the Before() func succeeding
err = app.Run([]string{"command", "--opt", "succeed", "sub"})
if err != nil {
t.Fatalf("Run error: %s", err)
}
if beforeRun == false {
t.Errorf("Before() not executed when expected")
}
if subcommandRun == false {
t.Errorf("Subcommand not executed when expected")
}
// reset
beforeRun, subcommandRun = false, false
// run with the Before() func failing
err = app.Run([]string{"command", "--opt", "fail", "sub"})
// should be the same error produced by the Before func
if err != beforeError {
t.Errorf("Run error expected, but not received")
}
if beforeRun == false {
t.Errorf("Before() not executed when expected")
}
if subcommandRun == true {
t.Errorf("Subcommand executed when NOT expected")
}
}
func TestAppNoHelpFlag(t *testing.T) {
oldFlag := cli.HelpFlag
defer func() {
cli.HelpFlag = oldFlag
}()
cli.HelpFlag = cli.BoolFlag{}
app := cli.NewApp()
err := app.Run([]string{"test", "-h"})
if err != flag.ErrHelp {
t.Errorf("expected error about missing help flag, but got: %s (%T)", err, err)
}
}
func TestAppHelpPrinter(t *testing.T) {
oldPrinter := cli.HelpPrinter
defer func() {
cli.HelpPrinter = oldPrinter
}()
var wasCalled = false
cli.HelpPrinter = func(template string, data interface{}) {
wasCalled = true
}
app := cli.NewApp()
app.Run([]string{"-h"})
if wasCalled == false {
t.Errorf("Help printer expected to be called, but was not")
}
}
func TestAppVersionPrinter(t *testing.T) {
oldPrinter := cli.VersionPrinter
defer func() {
cli.VersionPrinter = oldPrinter
}()
var wasCalled = false
cli.VersionPrinter = func(c *cli.Context) {
wasCalled = true
}
app := cli.NewApp()
ctx := cli.NewContext(app, nil, nil)
cli.ShowVersion(ctx)
if wasCalled == false {
t.Errorf("Version printer expected to be called, but was not")
}
}
func TestAppCommandNotFound(t *testing.T) {
beforeRun, subcommandRun := false, false
app := cli.NewApp()
app.CommandNotFound = func(c *cli.Context, command string) {
beforeRun = true
}
app.Commands = []cli.Command{
cli.Command{
Name: "bar",
Action: func(c *cli.Context) {
subcommandRun = true
},
},
}
app.Run([]string{"command", "foo"})
expect(t, beforeRun, true)
expect(t, subcommandRun, false)
}
func TestGlobalFlagsInSubcommands(t *testing.T) {
subcommandRun := false
app := cli.NewApp()
app.Flags = []cli.Flag{
cli.BoolFlag{Name: "debug, d", Usage: "Enable debugging"},
}
app.Commands = []cli.Command{
cli.Command{
Name: "foo",
Subcommands: []cli.Command{
{
Name: "bar",
Action: func(c *cli.Context) {
if c.GlobalBool("debug") {
subcommandRun = true
}
},
},
},
},
}
app.Run([]string{"command", "-d", "foo", "bar"})
expect(t, subcommandRun, true)
}

View File

@ -0,0 +1,13 @@
#! /bin/bash
_cli_bash_autocomplete() {
local cur prev opts base
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
opts=$( ${COMP_WORDS[@]:0:$COMP_CWORD} --generate-bash-completion )
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
}
complete -F _cli_bash_autocomplete $PROG

View File

@ -0,0 +1,5 @@
autoload -U compinit && compinit
autoload -U bashcompinit && bashcompinit
script_dir=$(dirname $0)
source ${script_dir}/bash_autocomplete

View File

@ -0,0 +1,19 @@
// Package cli provides a minimal framework for creating and organizing command line
// Go applications. cli is designed to be easy to understand and write, the most simple
// cli application can be written as follows:
// func main() {
// cli.NewApp().Run(os.Args)
// }
//
// Of course this application does not do much, so let's make this an actual application:
// func main() {
// app := cli.NewApp()
// app.Name = "greet"
// app.Usage = "say a greeting"
// app.Action = func(c *cli.Context) {
// println("Greetings")
// }
//
// app.Run(os.Args)
// }
package cli

View File

@ -0,0 +1,100 @@
package cli_test
import (
"os"
"github.com/jmespath/jp/Godeps/_workspace/src/github.com/codegangsta/cli"
)
func Example() {
app := cli.NewApp()
app.Name = "todo"
app.Usage = "task list on the command line"
app.Commands = []cli.Command{
{
Name: "add",
ShortName: "a",
Usage: "add a task to the list",
Action: func(c *cli.Context) {
println("added task: ", c.Args().First())
},
},
{
Name: "complete",
ShortName: "c",
Usage: "complete a task on the list",
Action: func(c *cli.Context) {
println("completed task: ", c.Args().First())
},
},
}
app.Run(os.Args)
}
func ExampleSubcommand() {
app := cli.NewApp()
app.Name = "say"
app.Commands = []cli.Command{
{
Name: "hello",
ShortName: "hi",
Usage: "use it to see a description",
Description: "This is how we describe hello the function",
Subcommands: []cli.Command{
{
Name: "english",
ShortName: "en",
Usage: "sends a greeting in english",
Description: "greets someone in english",
Flags: []cli.Flag{
cli.StringFlag{
Name: "name",
Value: "Bob",
Usage: "Name of the person to greet",
},
},
Action: func(c *cli.Context) {
println("Hello, ", c.String("name"))
},
}, {
Name: "spanish",
ShortName: "sp",
Usage: "sends a greeting in spanish",
Flags: []cli.Flag{
cli.StringFlag{
Name: "surname",
Value: "Jones",
Usage: "Surname of the person to greet",
},
},
Action: func(c *cli.Context) {
println("Hola, ", c.String("surname"))
},
}, {
Name: "french",
ShortName: "fr",
Usage: "sends a greeting in french",
Flags: []cli.Flag{
cli.StringFlag{
Name: "nickname",
Value: "Stevie",
Usage: "Nickname of the person to greet",
},
},
Action: func(c *cli.Context) {
println("Bonjour, ", c.String("nickname"))
},
},
},
}, {
Name: "bye",
Usage: "says goodbye",
Action: func(c *cli.Context) {
println("bye")
},
},
}
app.Run(os.Args)
}

View File

@ -0,0 +1,156 @@
package cli
import (
"fmt"
"io/ioutil"
"strings"
)
// Command is a subcommand for a cli.App.
type Command struct {
// The name of the command
Name string
// short name of the command. Typically one character
ShortName string
// A short description of the usage of this command
Usage string
// A longer explanation of how the command works
Description string
// The function to call when checking for bash command completions
BashComplete func(context *Context)
// An action to execute before any sub-subcommands are run, but after the context is ready
// If a non-nil error is returned, no sub-subcommands are run
Before func(context *Context) error
// The function to call when this command is invoked
Action func(context *Context)
// List of child commands
Subcommands []Command
// List of flags to parse
Flags []Flag
// Treat all flags as normal arguments if true
SkipFlagParsing bool
// Boolean to hide built-in help command
HideHelp bool
}
// Invokes the command given the context, parses ctx.Args() to generate command-specific flags
func (c Command) Run(ctx *Context) error {
if len(c.Subcommands) > 0 || c.Before != nil {
return c.startApp(ctx)
}
if !c.HideHelp && (HelpFlag != BoolFlag{}) {
// append help to flags
c.Flags = append(
c.Flags,
HelpFlag,
)
}
if ctx.App.EnableBashCompletion {
c.Flags = append(c.Flags, BashCompletionFlag)
}
set := flagSet(c.Name, c.Flags)
set.SetOutput(ioutil.Discard)
firstFlagIndex := -1
terminatorIndex := -1
for index, arg := range ctx.Args() {
if arg == "--" {
terminatorIndex = index
break
} else if strings.HasPrefix(arg, "-") && firstFlagIndex == -1 {
firstFlagIndex = index
}
}
var err error
if firstFlagIndex > -1 && !c.SkipFlagParsing {
args := ctx.Args()
regularArgs := make([]string, len(args[1:firstFlagIndex]))
copy(regularArgs, args[1:firstFlagIndex])
var flagArgs []string
if terminatorIndex > -1 {
flagArgs = args[firstFlagIndex:terminatorIndex]
regularArgs = append(regularArgs, args[terminatorIndex:]...)
} else {
flagArgs = args[firstFlagIndex:]
}
err = set.Parse(append(flagArgs, regularArgs...))
} else {
err = set.Parse(ctx.Args().Tail())
}
if err != nil {
fmt.Fprint(ctx.App.Writer, "Incorrect Usage.\n\n")
ShowCommandHelp(ctx, c.Name)
fmt.Fprintln(ctx.App.Writer)
return err
}
nerr := normalizeFlags(c.Flags, set)
if nerr != nil {
fmt.Fprintln(ctx.App.Writer, nerr)
fmt.Fprintln(ctx.App.Writer)
ShowCommandHelp(ctx, c.Name)
fmt.Fprintln(ctx.App.Writer)
return nerr
}
context := NewContext(ctx.App, set, ctx.globalSet)
if checkCommandCompletions(context, c.Name) {
return nil
}
if checkCommandHelp(context, c.Name) {
return nil
}
context.Command = c
c.Action(context)
return nil
}
// Returns true if Command.Name or Command.ShortName matches given name
func (c Command) HasName(name string) bool {
return c.Name == name || c.ShortName == name
}
func (c Command) startApp(ctx *Context) error {
app := NewApp()
// set the name and usage
app.Name = fmt.Sprintf("%s %s", ctx.App.Name, c.Name)
if c.Description != "" {
app.Usage = c.Description
} else {
app.Usage = c.Usage
}
// set CommandNotFound
app.CommandNotFound = ctx.App.CommandNotFound
// set the flags and commands
app.Commands = c.Subcommands
app.Flags = c.Flags
app.HideHelp = c.HideHelp
// bash completion
app.EnableBashCompletion = ctx.App.EnableBashCompletion
if c.BashComplete != nil {
app.BashComplete = c.BashComplete
}
// set the actions
app.Before = c.Before
if c.Action != nil {
app.Action = c.Action
} else {
app.Action = helpSubcommand.Action
}
return app.RunAsSubcommand(ctx)
}

View File

@ -0,0 +1,49 @@
package cli_test
import (
"flag"
"testing"
"github.com/jmespath/jp/Godeps/_workspace/src/github.com/codegangsta/cli"
)
func TestCommandDoNotIgnoreFlags(t *testing.T) {
app := cli.NewApp()
set := flag.NewFlagSet("test", 0)
test := []string{"blah", "blah", "-break"}
set.Parse(test)
c := cli.NewContext(app, set, set)
command := cli.Command{
Name: "test-cmd",
ShortName: "tc",
Usage: "this is for testing",
Description: "testing",
Action: func(_ *cli.Context) {},
}
err := command.Run(c)
expect(t, err.Error(), "flag provided but not defined: -break")
}
func TestCommandIgnoreFlags(t *testing.T) {
app := cli.NewApp()
set := flag.NewFlagSet("test", 0)
test := []string{"blah", "blah"}
set.Parse(test)
c := cli.NewContext(app, set, set)
command := cli.Command{
Name: "test-cmd",
ShortName: "tc",
Usage: "this is for testing",
Description: "testing",
Action: func(_ *cli.Context) {},
SkipFlagParsing: true,
}
err := command.Run(c)
expect(t, err, nil)
}

View File

@ -0,0 +1,339 @@
package cli
import (
"errors"
"flag"
"strconv"
"strings"
"time"
)
// Context is a type that is passed through to
// each Handler action in a cli application. Context
// can be used to retrieve context-specific Args and
// parsed command-line options.
type Context struct {
App *App
Command Command
flagSet *flag.FlagSet
globalSet *flag.FlagSet
setFlags map[string]bool
globalSetFlags map[string]bool
}
// Creates a new context. For use in when invoking an App or Command action.
func NewContext(app *App, set *flag.FlagSet, globalSet *flag.FlagSet) *Context {
return &Context{App: app, flagSet: set, globalSet: globalSet}
}
// Looks up the value of a local int flag, returns 0 if no int flag exists
func (c *Context) Int(name string) int {
return lookupInt(name, c.flagSet)
}
// Looks up the value of a local time.Duration flag, returns 0 if no time.Duration flag exists
func (c *Context) Duration(name string) time.Duration {
return lookupDuration(name, c.flagSet)
}
// Looks up the value of a local float64 flag, returns 0 if no float64 flag exists
func (c *Context) Float64(name string) float64 {
return lookupFloat64(name, c.flagSet)
}
// Looks up the value of a local bool flag, returns false if no bool flag exists
func (c *Context) Bool(name string) bool {
return lookupBool(name, c.flagSet)
}
// Looks up the value of a local boolT flag, returns false if no bool flag exists
func (c *Context) BoolT(name string) bool {
return lookupBoolT(name, c.flagSet)
}
// Looks up the value of a local string flag, returns "" if no string flag exists
func (c *Context) String(name string) string {
return lookupString(name, c.flagSet)
}
// Looks up the value of a local string slice flag, returns nil if no string slice flag exists
func (c *Context) StringSlice(name string) []string {
return lookupStringSlice(name, c.flagSet)
}
// Looks up the value of a local int slice flag, returns nil if no int slice flag exists
func (c *Context) IntSlice(name string) []int {
return lookupIntSlice(name, c.flagSet)
}
// Looks up the value of a local generic flag, returns nil if no generic flag exists
func (c *Context) Generic(name string) interface{} {
return lookupGeneric(name, c.flagSet)
}
// Looks up the value of a global int flag, returns 0 if no int flag exists
func (c *Context) GlobalInt(name string) int {
return lookupInt(name, c.globalSet)
}
// Looks up the value of a global time.Duration flag, returns 0 if no time.Duration flag exists
func (c *Context) GlobalDuration(name string) time.Duration {
return lookupDuration(name, c.globalSet)
}
// Looks up the value of a global bool flag, returns false if no bool flag exists
func (c *Context) GlobalBool(name string) bool {
return lookupBool(name, c.globalSet)
}
// Looks up the value of a global string flag, returns "" if no string flag exists
func (c *Context) GlobalString(name string) string {
return lookupString(name, c.globalSet)
}
// Looks up the value of a global string slice flag, returns nil if no string slice flag exists
func (c *Context) GlobalStringSlice(name string) []string {
return lookupStringSlice(name, c.globalSet)
}
// Looks up the value of a global int slice flag, returns nil if no int slice flag exists
func (c *Context) GlobalIntSlice(name string) []int {
return lookupIntSlice(name, c.globalSet)
}
// Looks up the value of a global generic flag, returns nil if no generic flag exists
func (c *Context) GlobalGeneric(name string) interface{} {
return lookupGeneric(name, c.globalSet)
}
// Determines if the flag was actually set
func (c *Context) IsSet(name string) bool {
if c.setFlags == nil {
c.setFlags = make(map[string]bool)
c.flagSet.Visit(func(f *flag.Flag) {
c.setFlags[f.Name] = true
})
}
return c.setFlags[name] == true
}
// Determines if the global flag was actually set
func (c *Context) GlobalIsSet(name string) bool {
if c.globalSetFlags == nil {
c.globalSetFlags = make(map[string]bool)
c.globalSet.Visit(func(f *flag.Flag) {
c.globalSetFlags[f.Name] = true
})
}
return c.globalSetFlags[name] == true
}
// Returns a slice of flag names used in this context.
func (c *Context) FlagNames() (names []string) {
for _, flag := range c.Command.Flags {
name := strings.Split(flag.getName(), ",")[0]
if name == "help" {
continue
}
names = append(names, name)
}
return
}
// Returns a slice of global flag names used by the app.
func (c *Context) GlobalFlagNames() (names []string) {
for _, flag := range c.App.Flags {
name := strings.Split(flag.getName(), ",")[0]
if name == "help" || name == "version" {
continue
}
names = append(names, name)
}
return
}
type Args []string
// Returns the command line arguments associated with the context.
func (c *Context) Args() Args {
args := Args(c.flagSet.Args())
return args
}
// Returns the nth argument, or else a blank string
func (a Args) Get(n int) string {
if len(a) > n {
return a[n]
}
return ""
}
// Returns the first argument, or else a blank string
func (a Args) First() string {
return a.Get(0)
}
// Return the rest of the arguments (not the first one)
// or else an empty string slice
func (a Args) Tail() []string {
if len(a) >= 2 {
return []string(a)[1:]
}
return []string{}
}
// Checks if there are any arguments present
func (a Args) Present() bool {
return len(a) != 0
}
// Swaps arguments at the given indexes
func (a Args) Swap(from, to int) error {
if from >= len(a) || to >= len(a) {
return errors.New("index out of range")
}
a[from], a[to] = a[to], a[from]
return nil
}
func lookupInt(name string, set *flag.FlagSet) int {
f := set.Lookup(name)
if f != nil {
val, err := strconv.Atoi(f.Value.String())
if err != nil {
return 0
}
return val
}
return 0
}
func lookupDuration(name string, set *flag.FlagSet) time.Duration {
f := set.Lookup(name)
if f != nil {
val, err := time.ParseDuration(f.Value.String())
if err == nil {
return val
}
}
return 0
}
func lookupFloat64(name string, set *flag.FlagSet) float64 {
f := set.Lookup(name)
if f != nil {
val, err := strconv.ParseFloat(f.Value.String(), 64)
if err != nil {
return 0
}
return val
}
return 0
}
func lookupString(name string, set *flag.FlagSet) string {
f := set.Lookup(name)
if f != nil {
return f.Value.String()
}
return ""
}
func lookupStringSlice(name string, set *flag.FlagSet) []string {
f := set.Lookup(name)
if f != nil {
return (f.Value.(*StringSlice)).Value()
}
return nil
}
func lookupIntSlice(name string, set *flag.FlagSet) []int {
f := set.Lookup(name)
if f != nil {
return (f.Value.(*IntSlice)).Value()
}
return nil
}
func lookupGeneric(name string, set *flag.FlagSet) interface{} {
f := set.Lookup(name)
if f != nil {
return f.Value
}
return nil
}
func lookupBool(name string, set *flag.FlagSet) bool {
f := set.Lookup(name)
if f != nil {
val, err := strconv.ParseBool(f.Value.String())
if err != nil {
return false
}
return val
}
return false
}
func lookupBoolT(name string, set *flag.FlagSet) bool {
f := set.Lookup(name)
if f != nil {
val, err := strconv.ParseBool(f.Value.String())
if err != nil {
return true
}
return val
}
return false
}
func copyFlag(name string, ff *flag.Flag, set *flag.FlagSet) {
switch ff.Value.(type) {
case *StringSlice:
default:
set.Set(name, ff.Value.String())
}
}
func normalizeFlags(flags []Flag, set *flag.FlagSet) error {
visited := make(map[string]bool)
set.Visit(func(f *flag.Flag) {
visited[f.Name] = true
})
for _, f := range flags {
parts := strings.Split(f.getName(), ",")
if len(parts) == 1 {
continue
}
var ff *flag.Flag
for _, name := range parts {
name = strings.Trim(name, " ")
if visited[name] {
if ff != nil {
return errors.New("Cannot use two forms of the same flag: " + name + " " + ff.Name)
}
ff = set.Lookup(name)
}
}
if ff == nil {
continue
}
for _, name := range parts {
name = strings.Trim(name, " ")
if !visited[name] {
copyFlag(name, ff, set)
}
}
}
return nil
}

View File

@ -0,0 +1,99 @@
package cli_test
import (
"flag"
"testing"
"time"
"github.com/jmespath/jp/Godeps/_workspace/src/github.com/codegangsta/cli"
)
func TestNewContext(t *testing.T) {
set := flag.NewFlagSet("test", 0)
set.Int("myflag", 12, "doc")
globalSet := flag.NewFlagSet("test", 0)
globalSet.Int("myflag", 42, "doc")
command := cli.Command{Name: "mycommand"}
c := cli.NewContext(nil, set, globalSet)
c.Command = command
expect(t, c.Int("myflag"), 12)
expect(t, c.GlobalInt("myflag"), 42)
expect(t, c.Command.Name, "mycommand")
}
func TestContext_Int(t *testing.T) {
set := flag.NewFlagSet("test", 0)
set.Int("myflag", 12, "doc")
c := cli.NewContext(nil, set, set)
expect(t, c.Int("myflag"), 12)
}
func TestContext_Duration(t *testing.T) {
set := flag.NewFlagSet("test", 0)
set.Duration("myflag", time.Duration(12*time.Second), "doc")
c := cli.NewContext(nil, set, set)
expect(t, c.Duration("myflag"), time.Duration(12*time.Second))
}
func TestContext_String(t *testing.T) {
set := flag.NewFlagSet("test", 0)
set.String("myflag", "hello world", "doc")
c := cli.NewContext(nil, set, set)
expect(t, c.String("myflag"), "hello world")
}
func TestContext_Bool(t *testing.T) {
set := flag.NewFlagSet("test", 0)
set.Bool("myflag", false, "doc")
c := cli.NewContext(nil, set, set)
expect(t, c.Bool("myflag"), false)
}
func TestContext_BoolT(t *testing.T) {
set := flag.NewFlagSet("test", 0)
set.Bool("myflag", true, "doc")
c := cli.NewContext(nil, set, set)
expect(t, c.BoolT("myflag"), true)
}
func TestContext_Args(t *testing.T) {
set := flag.NewFlagSet("test", 0)
set.Bool("myflag", false, "doc")
c := cli.NewContext(nil, set, set)
set.Parse([]string{"--myflag", "bat", "baz"})
expect(t, len(c.Args()), 2)
expect(t, c.Bool("myflag"), true)
}
func TestContext_IsSet(t *testing.T) {
set := flag.NewFlagSet("test", 0)
set.Bool("myflag", false, "doc")
set.String("otherflag", "hello world", "doc")
globalSet := flag.NewFlagSet("test", 0)
globalSet.Bool("myflagGlobal", true, "doc")
c := cli.NewContext(nil, set, globalSet)
set.Parse([]string{"--myflag", "bat", "baz"})
globalSet.Parse([]string{"--myflagGlobal", "bat", "baz"})
expect(t, c.IsSet("myflag"), true)
expect(t, c.IsSet("otherflag"), false)
expect(t, c.IsSet("bogusflag"), false)
expect(t, c.IsSet("myflagGlobal"), false)
}
func TestContext_GlobalIsSet(t *testing.T) {
set := flag.NewFlagSet("test", 0)
set.Bool("myflag", false, "doc")
set.String("otherflag", "hello world", "doc")
globalSet := flag.NewFlagSet("test", 0)
globalSet.Bool("myflagGlobal", true, "doc")
globalSet.Bool("myflagGlobalUnset", true, "doc")
c := cli.NewContext(nil, set, globalSet)
set.Parse([]string{"--myflag", "bat", "baz"})
globalSet.Parse([]string{"--myflagGlobal", "bat", "baz"})
expect(t, c.GlobalIsSet("myflag"), false)
expect(t, c.GlobalIsSet("otherflag"), false)
expect(t, c.GlobalIsSet("bogusflag"), false)
expect(t, c.GlobalIsSet("myflagGlobal"), true)
expect(t, c.GlobalIsSet("myflagGlobalUnset"), false)
expect(t, c.GlobalIsSet("bogusGlobal"), false)
}

View File

@ -0,0 +1,454 @@
package cli
import (
"flag"
"fmt"
"os"
"strconv"
"strings"
"time"
)
// This flag enables bash-completion for all commands and subcommands
var BashCompletionFlag = BoolFlag{
Name: "generate-bash-completion",
}
// This flag prints the version for the application
var VersionFlag = BoolFlag{
Name: "version, v",
Usage: "print the version",
}
// This flag prints the help for all commands and subcommands
// Set to the zero value (BoolFlag{}) to disable flag -- keeps subcommand
// unless HideHelp is set to true)
var HelpFlag = BoolFlag{
Name: "help, h",
Usage: "show help",
}
// Flag is a common interface related to parsing flags in cli.
// For more advanced flag parsing techniques, it is recomended that
// this interface be implemented.
type Flag interface {
fmt.Stringer
// Apply Flag settings to the given flag set
Apply(*flag.FlagSet)
getName() string
}
func flagSet(name string, flags []Flag) *flag.FlagSet {
set := flag.NewFlagSet(name, flag.ContinueOnError)
for _, f := range flags {
f.Apply(set)
}
return set
}
func eachName(longName string, fn func(string)) {
parts := strings.Split(longName, ",")
for _, name := range parts {
name = strings.Trim(name, " ")
fn(name)
}
}
// Generic is a generic parseable type identified by a specific flag
type Generic interface {
Set(value string) error
String() string
}
// GenericFlag is the flag type for types implementing Generic
type GenericFlag struct {
Name string
Value Generic
Usage string
EnvVar string
}
// String returns the string representation of the generic flag to display the
// help text to the user (uses the String() method of the generic flag to show
// the value)
func (f GenericFlag) String() string {
return withEnvHint(f.EnvVar, fmt.Sprintf("%s%s \"%v\"\t%v", prefixFor(f.Name), f.Name, f.Value, f.Usage))
}
// Apply takes the flagset and calls Set on the generic flag with the value
// provided by the user for parsing by the flag
func (f GenericFlag) Apply(set *flag.FlagSet) {
val := f.Value
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal := os.Getenv(envVar); envVal != "" {
val.Set(envVal)
break
}
}
}
eachName(f.Name, func(name string) {
set.Var(f.Value, name, f.Usage)
})
}
func (f GenericFlag) getName() string {
return f.Name
}
type StringSlice []string
func (f *StringSlice) Set(value string) error {
*f = append(*f, value)
return nil
}
func (f *StringSlice) String() string {
return fmt.Sprintf("%s", *f)
}
func (f *StringSlice) Value() []string {
return *f
}
type StringSliceFlag struct {
Name string
Value *StringSlice
Usage string
EnvVar string
}
func (f StringSliceFlag) String() string {
firstName := strings.Trim(strings.Split(f.Name, ",")[0], " ")
pref := prefixFor(firstName)
return withEnvHint(f.EnvVar, fmt.Sprintf("%s [%v]\t%v", prefixedNames(f.Name), pref+firstName+" option "+pref+firstName+" option", f.Usage))
}
func (f StringSliceFlag) Apply(set *flag.FlagSet) {
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal := os.Getenv(envVar); envVal != "" {
newVal := &StringSlice{}
for _, s := range strings.Split(envVal, ",") {
s = strings.TrimSpace(s)
newVal.Set(s)
}
f.Value = newVal
break
}
}
}
eachName(f.Name, func(name string) {
set.Var(f.Value, name, f.Usage)
})
}
func (f StringSliceFlag) getName() string {
return f.Name
}
type IntSlice []int
func (f *IntSlice) Set(value string) error {
tmp, err := strconv.Atoi(value)
if err != nil {
return err
} else {
*f = append(*f, tmp)
}
return nil
}
func (f *IntSlice) String() string {
return fmt.Sprintf("%d", *f)
}
func (f *IntSlice) Value() []int {
return *f
}
type IntSliceFlag struct {
Name string
Value *IntSlice
Usage string
EnvVar string
}
func (f IntSliceFlag) String() string {
firstName := strings.Trim(strings.Split(f.Name, ",")[0], " ")
pref := prefixFor(firstName)
return withEnvHint(f.EnvVar, fmt.Sprintf("%s [%v]\t%v", prefixedNames(f.Name), pref+firstName+" option "+pref+firstName+" option", f.Usage))
}
func (f IntSliceFlag) Apply(set *flag.FlagSet) {
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal := os.Getenv(envVar); envVal != "" {
newVal := &IntSlice{}
for _, s := range strings.Split(envVal, ",") {
s = strings.TrimSpace(s)
err := newVal.Set(s)
if err != nil {
fmt.Fprintf(os.Stderr, err.Error())
}
}
f.Value = newVal
break
}
}
}
eachName(f.Name, func(name string) {
set.Var(f.Value, name, f.Usage)
})
}
func (f IntSliceFlag) getName() string {
return f.Name
}
type BoolFlag struct {
Name string
Usage string
EnvVar string
}
func (f BoolFlag) String() string {
return withEnvHint(f.EnvVar, fmt.Sprintf("%s\t%v", prefixedNames(f.Name), f.Usage))
}
func (f BoolFlag) Apply(set *flag.FlagSet) {
val := false
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal := os.Getenv(envVar); envVal != "" {
envValBool, err := strconv.ParseBool(envVal)
if err == nil {
val = envValBool
}
break
}
}
}
eachName(f.Name, func(name string) {
set.Bool(name, val, f.Usage)
})
}
func (f BoolFlag) getName() string {
return f.Name
}
type BoolTFlag struct {
Name string
Usage string
EnvVar string
}
func (f BoolTFlag) String() string {
return withEnvHint(f.EnvVar, fmt.Sprintf("%s\t%v", prefixedNames(f.Name), f.Usage))
}
func (f BoolTFlag) Apply(set *flag.FlagSet) {
val := true
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal := os.Getenv(envVar); envVal != "" {
envValBool, err := strconv.ParseBool(envVal)
if err == nil {
val = envValBool
break
}
}
}
}
eachName(f.Name, func(name string) {
set.Bool(name, val, f.Usage)
})
}
func (f BoolTFlag) getName() string {
return f.Name
}
type StringFlag struct {
Name string
Value string
Usage string
EnvVar string
}
func (f StringFlag) String() string {
var fmtString string
fmtString = "%s %v\t%v"
if len(f.Value) > 0 {
fmtString = "%s \"%v\"\t%v"
} else {
fmtString = "%s %v\t%v"
}
return withEnvHint(f.EnvVar, fmt.Sprintf(fmtString, prefixedNames(f.Name), f.Value, f.Usage))
}
func (f StringFlag) Apply(set *flag.FlagSet) {
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal := os.Getenv(envVar); envVal != "" {
f.Value = envVal
break
}
}
}
eachName(f.Name, func(name string) {
set.String(name, f.Value, f.Usage)
})
}
func (f StringFlag) getName() string {
return f.Name
}
type IntFlag struct {
Name string
Value int
Usage string
EnvVar string
}
func (f IntFlag) String() string {
return withEnvHint(f.EnvVar, fmt.Sprintf("%s \"%v\"\t%v", prefixedNames(f.Name), f.Value, f.Usage))
}
func (f IntFlag) Apply(set *flag.FlagSet) {
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal := os.Getenv(envVar); envVal != "" {
envValInt, err := strconv.ParseInt(envVal, 0, 64)
if err == nil {
f.Value = int(envValInt)
break
}
}
}
}
eachName(f.Name, func(name string) {
set.Int(name, f.Value, f.Usage)
})
}
func (f IntFlag) getName() string {
return f.Name
}
type DurationFlag struct {
Name string
Value time.Duration
Usage string
EnvVar string
}
func (f DurationFlag) String() string {
return withEnvHint(f.EnvVar, fmt.Sprintf("%s \"%v\"\t%v", prefixedNames(f.Name), f.Value, f.Usage))
}
func (f DurationFlag) Apply(set *flag.FlagSet) {
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal := os.Getenv(envVar); envVal != "" {
envValDuration, err := time.ParseDuration(envVal)
if err == nil {
f.Value = envValDuration
break
}
}
}
}
eachName(f.Name, func(name string) {
set.Duration(name, f.Value, f.Usage)
})
}
func (f DurationFlag) getName() string {
return f.Name
}
type Float64Flag struct {
Name string
Value float64
Usage string
EnvVar string
}
func (f Float64Flag) String() string {
return withEnvHint(f.EnvVar, fmt.Sprintf("%s \"%v\"\t%v", prefixedNames(f.Name), f.Value, f.Usage))
}
func (f Float64Flag) Apply(set *flag.FlagSet) {
if f.EnvVar != "" {
for _, envVar := range strings.Split(f.EnvVar, ",") {
envVar = strings.TrimSpace(envVar)
if envVal := os.Getenv(envVar); envVal != "" {
envValFloat, err := strconv.ParseFloat(envVal, 10)
if err == nil {
f.Value = float64(envValFloat)
}
}
}
}
eachName(f.Name, func(name string) {
set.Float64(name, f.Value, f.Usage)
})
}
func (f Float64Flag) getName() string {
return f.Name
}
func prefixFor(name string) (prefix string) {
if len(name) == 1 {
prefix = "-"
} else {
prefix = "--"
}
return
}
func prefixedNames(fullName string) (prefixed string) {
parts := strings.Split(fullName, ",")
for i, name := range parts {
name = strings.Trim(name, " ")
prefixed += prefixFor(name) + name
if i < len(parts)-1 {
prefixed += ", "
}
}
return
}
func withEnvHint(envVar, str string) string {
envText := ""
if envVar != "" {
envText = fmt.Sprintf(" [$%s]", strings.Join(strings.Split(envVar, ","), ", $"))
}
return str + envText
}

View File

@ -0,0 +1,742 @@
package cli_test
import (
"fmt"
"os"
"reflect"
"strings"
"testing"
"github.com/jmespath/jp/Godeps/_workspace/src/github.com/codegangsta/cli"
)
var boolFlagTests = []struct {
name string
expected string
}{
{"help", "--help\t"},
{"h", "-h\t"},
}
func TestBoolFlagHelpOutput(t *testing.T) {
for _, test := range boolFlagTests {
flag := cli.BoolFlag{Name: test.name}
output := flag.String()
if output != test.expected {
t.Errorf("%s does not match %s", output, test.expected)
}
}
}
var stringFlagTests = []struct {
name string
value string
expected string
}{
{"help", "", "--help \t"},
{"h", "", "-h \t"},
{"h", "", "-h \t"},
{"test", "Something", "--test \"Something\"\t"},
}
func TestStringFlagHelpOutput(t *testing.T) {
for _, test := range stringFlagTests {
flag := cli.StringFlag{Name: test.name, Value: test.value}
output := flag.String()
if output != test.expected {
t.Errorf("%s does not match %s", output, test.expected)
}
}
}
func TestStringFlagWithEnvVarHelpOutput(t *testing.T) {
os.Clearenv()
os.Setenv("APP_FOO", "derp")
for _, test := range stringFlagTests {
flag := cli.StringFlag{Name: test.name, Value: test.value, EnvVar: "APP_FOO"}
output := flag.String()
if !strings.HasSuffix(output, " [$APP_FOO]") {
t.Errorf("%s does not end with [$APP_FOO]", output)
}
}
}
var stringSliceFlagTests = []struct {
name string
value *cli.StringSlice
expected string
}{
{"help", func() *cli.StringSlice {
s := &cli.StringSlice{}
s.Set("")
return s
}(), "--help [--help option --help option]\t"},
{"h", func() *cli.StringSlice {
s := &cli.StringSlice{}
s.Set("")
return s
}(), "-h [-h option -h option]\t"},
{"h", func() *cli.StringSlice {
s := &cli.StringSlice{}
s.Set("")
return s
}(), "-h [-h option -h option]\t"},
{"test", func() *cli.StringSlice {
s := &cli.StringSlice{}
s.Set("Something")
return s
}(), "--test [--test option --test option]\t"},
}
func TestStringSliceFlagHelpOutput(t *testing.T) {
for _, test := range stringSliceFlagTests {
flag := cli.StringSliceFlag{Name: test.name, Value: test.value}
output := flag.String()
if output != test.expected {
t.Errorf("%q does not match %q", output, test.expected)
}
}
}
func TestStringSliceFlagWithEnvVarHelpOutput(t *testing.T) {
os.Clearenv()
os.Setenv("APP_QWWX", "11,4")
for _, test := range stringSliceFlagTests {
flag := cli.StringSliceFlag{Name: test.name, Value: test.value, EnvVar: "APP_QWWX"}
output := flag.String()
if !strings.HasSuffix(output, " [$APP_QWWX]") {
t.Errorf("%q does not end with [$APP_QWWX]", output)
}
}
}
var intFlagTests = []struct {
name string
expected string
}{
{"help", "--help \"0\"\t"},
{"h", "-h \"0\"\t"},
}
func TestIntFlagHelpOutput(t *testing.T) {
for _, test := range intFlagTests {
flag := cli.IntFlag{Name: test.name}
output := flag.String()
if output != test.expected {
t.Errorf("%s does not match %s", output, test.expected)
}
}
}
func TestIntFlagWithEnvVarHelpOutput(t *testing.T) {
os.Clearenv()
os.Setenv("APP_BAR", "2")
for _, test := range intFlagTests {
flag := cli.IntFlag{Name: test.name, EnvVar: "APP_BAR"}
output := flag.String()
if !strings.HasSuffix(output, " [$APP_BAR]") {
t.Errorf("%s does not end with [$APP_BAR]", output)
}
}
}
var durationFlagTests = []struct {
name string
expected string
}{
{"help", "--help \"0\"\t"},
{"h", "-h \"0\"\t"},
}
func TestDurationFlagHelpOutput(t *testing.T) {
for _, test := range durationFlagTests {
flag := cli.DurationFlag{Name: test.name}
output := flag.String()
if output != test.expected {
t.Errorf("%s does not match %s", output, test.expected)
}
}
}
func TestDurationFlagWithEnvVarHelpOutput(t *testing.T) {
os.Clearenv()
os.Setenv("APP_BAR", "2h3m6s")
for _, test := range durationFlagTests {
flag := cli.DurationFlag{Name: test.name, EnvVar: "APP_BAR"}
output := flag.String()
if !strings.HasSuffix(output, " [$APP_BAR]") {
t.Errorf("%s does not end with [$APP_BAR]", output)
}
}
}
var intSliceFlagTests = []struct {
name string
value *cli.IntSlice
expected string
}{
{"help", &cli.IntSlice{}, "--help [--help option --help option]\t"},
{"h", &cli.IntSlice{}, "-h [-h option -h option]\t"},
{"h", &cli.IntSlice{}, "-h [-h option -h option]\t"},
{"test", func() *cli.IntSlice {
i := &cli.IntSlice{}
i.Set("9")
return i
}(), "--test [--test option --test option]\t"},
}
func TestIntSliceFlagHelpOutput(t *testing.T) {
for _, test := range intSliceFlagTests {
flag := cli.IntSliceFlag{Name: test.name, Value: test.value}
output := flag.String()
if output != test.expected {
t.Errorf("%q does not match %q", output, test.expected)
}
}
}
func TestIntSliceFlagWithEnvVarHelpOutput(t *testing.T) {
os.Clearenv()
os.Setenv("APP_SMURF", "42,3")
for _, test := range intSliceFlagTests {
flag := cli.IntSliceFlag{Name: test.name, Value: test.value, EnvVar: "APP_SMURF"}
output := flag.String()
if !strings.HasSuffix(output, " [$APP_SMURF]") {
t.Errorf("%q does not end with [$APP_SMURF]", output)
}
}
}
var float64FlagTests = []struct {
name string
expected string
}{
{"help", "--help \"0\"\t"},
{"h", "-h \"0\"\t"},
}
func TestFloat64FlagHelpOutput(t *testing.T) {
for _, test := range float64FlagTests {
flag := cli.Float64Flag{Name: test.name}
output := flag.String()
if output != test.expected {
t.Errorf("%s does not match %s", output, test.expected)
}
}
}
func TestFloat64FlagWithEnvVarHelpOutput(t *testing.T) {
os.Clearenv()
os.Setenv("APP_BAZ", "99.4")
for _, test := range float64FlagTests {
flag := cli.Float64Flag{Name: test.name, EnvVar: "APP_BAZ"}
output := flag.String()
if !strings.HasSuffix(output, " [$APP_BAZ]") {
t.Errorf("%s does not end with [$APP_BAZ]", output)
}
}
}
var genericFlagTests = []struct {
name string
value cli.Generic
expected string
}{
{"test", &Parser{"abc", "def"}, "--test \"abc,def\"\ttest flag"},
{"t", &Parser{"abc", "def"}, "-t \"abc,def\"\ttest flag"},
}
func TestGenericFlagHelpOutput(t *testing.T) {
for _, test := range genericFlagTests {
flag := cli.GenericFlag{Name: test.name, Value: test.value, Usage: "test flag"}
output := flag.String()
if output != test.expected {
t.Errorf("%q does not match %q", output, test.expected)
}
}
}
func TestGenericFlagWithEnvVarHelpOutput(t *testing.T) {
os.Clearenv()
os.Setenv("APP_ZAP", "3")
for _, test := range genericFlagTests {
flag := cli.GenericFlag{Name: test.name, EnvVar: "APP_ZAP"}
output := flag.String()
if !strings.HasSuffix(output, " [$APP_ZAP]") {
t.Errorf("%s does not end with [$APP_ZAP]", output)
}
}
}
func TestParseMultiString(t *testing.T) {
(&cli.App{
Flags: []cli.Flag{
cli.StringFlag{Name: "serve, s"},
},
Action: func(ctx *cli.Context) {
if ctx.String("serve") != "10" {
t.Errorf("main name not set")
}
if ctx.String("s") != "10" {
t.Errorf("short name not set")
}
},
}).Run([]string{"run", "-s", "10"})
}
func TestParseMultiStringFromEnv(t *testing.T) {
os.Clearenv()
os.Setenv("APP_COUNT", "20")
(&cli.App{
Flags: []cli.Flag{
cli.StringFlag{Name: "count, c", EnvVar: "APP_COUNT"},
},
Action: func(ctx *cli.Context) {
if ctx.String("count") != "20" {
t.Errorf("main name not set")
}
if ctx.String("c") != "20" {
t.Errorf("short name not set")
}
},
}).Run([]string{"run"})
}
func TestParseMultiStringFromEnvCascade(t *testing.T) {
os.Clearenv()
os.Setenv("APP_COUNT", "20")
(&cli.App{
Flags: []cli.Flag{
cli.StringFlag{Name: "count, c", EnvVar: "COMPAT_COUNT,APP_COUNT"},
},
Action: func(ctx *cli.Context) {
if ctx.String("count") != "20" {
t.Errorf("main name not set")
}
if ctx.String("c") != "20" {
t.Errorf("short name not set")
}
},
}).Run([]string{"run"})
}
func TestParseMultiStringSlice(t *testing.T) {
(&cli.App{
Flags: []cli.Flag{
cli.StringSliceFlag{Name: "serve, s", Value: &cli.StringSlice{}},
},
Action: func(ctx *cli.Context) {
if !reflect.DeepEqual(ctx.StringSlice("serve"), []string{"10", "20"}) {
t.Errorf("main name not set")
}
if !reflect.DeepEqual(ctx.StringSlice("s"), []string{"10", "20"}) {
t.Errorf("short name not set")
}
},
}).Run([]string{"run", "-s", "10", "-s", "20"})
}
func TestParseMultiStringSliceFromEnv(t *testing.T) {
os.Clearenv()
os.Setenv("APP_INTERVALS", "20,30,40")
(&cli.App{
Flags: []cli.Flag{
cli.StringSliceFlag{Name: "intervals, i", Value: &cli.StringSlice{}, EnvVar: "APP_INTERVALS"},
},
Action: func(ctx *cli.Context) {
if !reflect.DeepEqual(ctx.StringSlice("intervals"), []string{"20", "30", "40"}) {
t.Errorf("main name not set from env")
}
if !reflect.DeepEqual(ctx.StringSlice("i"), []string{"20", "30", "40"}) {
t.Errorf("short name not set from env")
}
},
}).Run([]string{"run"})
}
func TestParseMultiStringSliceFromEnvCascade(t *testing.T) {
os.Clearenv()
os.Setenv("APP_INTERVALS", "20,30,40")
(&cli.App{
Flags: []cli.Flag{
cli.StringSliceFlag{Name: "intervals, i", Value: &cli.StringSlice{}, EnvVar: "COMPAT_INTERVALS,APP_INTERVALS"},
},
Action: func(ctx *cli.Context) {
if !reflect.DeepEqual(ctx.StringSlice("intervals"), []string{"20", "30", "40"}) {
t.Errorf("main name not set from env")
}
if !reflect.DeepEqual(ctx.StringSlice("i"), []string{"20", "30", "40"}) {
t.Errorf("short name not set from env")
}
},
}).Run([]string{"run"})
}
func TestParseMultiInt(t *testing.T) {
a := cli.App{
Flags: []cli.Flag{
cli.IntFlag{Name: "serve, s"},
},
Action: func(ctx *cli.Context) {
if ctx.Int("serve") != 10 {
t.Errorf("main name not set")
}
if ctx.Int("s") != 10 {
t.Errorf("short name not set")
}
},
}
a.Run([]string{"run", "-s", "10"})
}
func TestParseMultiIntFromEnv(t *testing.T) {
os.Clearenv()
os.Setenv("APP_TIMEOUT_SECONDS", "10")
a := cli.App{
Flags: []cli.Flag{
cli.IntFlag{Name: "timeout, t", EnvVar: "APP_TIMEOUT_SECONDS"},
},
Action: func(ctx *cli.Context) {
if ctx.Int("timeout") != 10 {
t.Errorf("main name not set")
}
if ctx.Int("t") != 10 {
t.Errorf("short name not set")
}
},
}
a.Run([]string{"run"})
}
func TestParseMultiIntFromEnvCascade(t *testing.T) {
os.Clearenv()
os.Setenv("APP_TIMEOUT_SECONDS", "10")
a := cli.App{
Flags: []cli.Flag{
cli.IntFlag{Name: "timeout, t", EnvVar: "COMPAT_TIMEOUT_SECONDS,APP_TIMEOUT_SECONDS"},
},
Action: func(ctx *cli.Context) {
if ctx.Int("timeout") != 10 {
t.Errorf("main name not set")
}
if ctx.Int("t") != 10 {
t.Errorf("short name not set")
}
},
}
a.Run([]string{"run"})
}
func TestParseMultiIntSlice(t *testing.T) {
(&cli.App{
Flags: []cli.Flag{
cli.IntSliceFlag{Name: "serve, s", Value: &cli.IntSlice{}},
},
Action: func(ctx *cli.Context) {
if !reflect.DeepEqual(ctx.IntSlice("serve"), []int{10, 20}) {
t.Errorf("main name not set")
}
if !reflect.DeepEqual(ctx.IntSlice("s"), []int{10, 20}) {
t.Errorf("short name not set")
}
},
}).Run([]string{"run", "-s", "10", "-s", "20"})
}
func TestParseMultiIntSliceFromEnv(t *testing.T) {
os.Clearenv()
os.Setenv("APP_INTERVALS", "20,30,40")
(&cli.App{
Flags: []cli.Flag{
cli.IntSliceFlag{Name: "intervals, i", Value: &cli.IntSlice{}, EnvVar: "APP_INTERVALS"},
},
Action: func(ctx *cli.Context) {
if !reflect.DeepEqual(ctx.IntSlice("intervals"), []int{20, 30, 40}) {
t.Errorf("main name not set from env")
}
if !reflect.DeepEqual(ctx.IntSlice("i"), []int{20, 30, 40}) {
t.Errorf("short name not set from env")
}
},
}).Run([]string{"run"})
}
func TestParseMultiIntSliceFromEnvCascade(t *testing.T) {
os.Clearenv()
os.Setenv("APP_INTERVALS", "20,30,40")
(&cli.App{
Flags: []cli.Flag{
cli.IntSliceFlag{Name: "intervals, i", Value: &cli.IntSlice{}, EnvVar: "COMPAT_INTERVALS,APP_INTERVALS"},
},
Action: func(ctx *cli.Context) {
if !reflect.DeepEqual(ctx.IntSlice("intervals"), []int{20, 30, 40}) {
t.Errorf("main name not set from env")
}
if !reflect.DeepEqual(ctx.IntSlice("i"), []int{20, 30, 40}) {
t.Errorf("short name not set from env")
}
},
}).Run([]string{"run"})
}
func TestParseMultiFloat64(t *testing.T) {
a := cli.App{
Flags: []cli.Flag{
cli.Float64Flag{Name: "serve, s"},
},
Action: func(ctx *cli.Context) {
if ctx.Float64("serve") != 10.2 {
t.Errorf("main name not set")
}
if ctx.Float64("s") != 10.2 {
t.Errorf("short name not set")
}
},
}
a.Run([]string{"run", "-s", "10.2"})
}
func TestParseMultiFloat64FromEnv(t *testing.T) {
os.Clearenv()
os.Setenv("APP_TIMEOUT_SECONDS", "15.5")
a := cli.App{
Flags: []cli.Flag{
cli.Float64Flag{Name: "timeout, t", EnvVar: "APP_TIMEOUT_SECONDS"},
},
Action: func(ctx *cli.Context) {
if ctx.Float64("timeout") != 15.5 {
t.Errorf("main name not set")
}
if ctx.Float64("t") != 15.5 {
t.Errorf("short name not set")
}
},
}
a.Run([]string{"run"})
}
func TestParseMultiFloat64FromEnvCascade(t *testing.T) {
os.Clearenv()
os.Setenv("APP_TIMEOUT_SECONDS", "15.5")
a := cli.App{
Flags: []cli.Flag{
cli.Float64Flag{Name: "timeout, t", EnvVar: "COMPAT_TIMEOUT_SECONDS,APP_TIMEOUT_SECONDS"},
},
Action: func(ctx *cli.Context) {
if ctx.Float64("timeout") != 15.5 {
t.Errorf("main name not set")
}
if ctx.Float64("t") != 15.5 {
t.Errorf("short name not set")
}
},
}
a.Run([]string{"run"})
}
func TestParseMultiBool(t *testing.T) {
a := cli.App{
Flags: []cli.Flag{
cli.BoolFlag{Name: "serve, s"},
},
Action: func(ctx *cli.Context) {
if ctx.Bool("serve") != true {
t.Errorf("main name not set")
}
if ctx.Bool("s") != true {
t.Errorf("short name not set")
}
},
}
a.Run([]string{"run", "--serve"})
}
func TestParseMultiBoolFromEnv(t *testing.T) {
os.Clearenv()
os.Setenv("APP_DEBUG", "1")
a := cli.App{
Flags: []cli.Flag{
cli.BoolFlag{Name: "debug, d", EnvVar: "APP_DEBUG"},
},
Action: func(ctx *cli.Context) {
if ctx.Bool("debug") != true {
t.Errorf("main name not set from env")
}
if ctx.Bool("d") != true {
t.Errorf("short name not set from env")
}
},
}
a.Run([]string{"run"})
}
func TestParseMultiBoolFromEnvCascade(t *testing.T) {
os.Clearenv()
os.Setenv("APP_DEBUG", "1")
a := cli.App{
Flags: []cli.Flag{
cli.BoolFlag{Name: "debug, d", EnvVar: "COMPAT_DEBUG,APP_DEBUG"},
},
Action: func(ctx *cli.Context) {
if ctx.Bool("debug") != true {
t.Errorf("main name not set from env")
}
if ctx.Bool("d") != true {
t.Errorf("short name not set from env")
}
},
}
a.Run([]string{"run"})
}
func TestParseMultiBoolT(t *testing.T) {
a := cli.App{
Flags: []cli.Flag{
cli.BoolTFlag{Name: "serve, s"},
},
Action: func(ctx *cli.Context) {
if ctx.BoolT("serve") != true {
t.Errorf("main name not set")
}
if ctx.BoolT("s") != true {
t.Errorf("short name not set")
}
},
}
a.Run([]string{"run", "--serve"})
}
func TestParseMultiBoolTFromEnv(t *testing.T) {
os.Clearenv()
os.Setenv("APP_DEBUG", "0")
a := cli.App{
Flags: []cli.Flag{
cli.BoolTFlag{Name: "debug, d", EnvVar: "APP_DEBUG"},
},
Action: func(ctx *cli.Context) {
if ctx.BoolT("debug") != false {
t.Errorf("main name not set from env")
}
if ctx.BoolT("d") != false {
t.Errorf("short name not set from env")
}
},
}
a.Run([]string{"run"})
}
func TestParseMultiBoolTFromEnvCascade(t *testing.T) {
os.Clearenv()
os.Setenv("APP_DEBUG", "0")
a := cli.App{
Flags: []cli.Flag{
cli.BoolTFlag{Name: "debug, d", EnvVar: "COMPAT_DEBUG,APP_DEBUG"},
},
Action: func(ctx *cli.Context) {
if ctx.BoolT("debug") != false {
t.Errorf("main name not set from env")
}
if ctx.BoolT("d") != false {
t.Errorf("short name not set from env")
}
},
}
a.Run([]string{"run"})
}
type Parser [2]string
func (p *Parser) Set(value string) error {
parts := strings.Split(value, ",")
if len(parts) != 2 {
return fmt.Errorf("invalid format")
}
(*p)[0] = parts[0]
(*p)[1] = parts[1]
return nil
}
func (p *Parser) String() string {
return fmt.Sprintf("%s,%s", p[0], p[1])
}
func TestParseGeneric(t *testing.T) {
a := cli.App{
Flags: []cli.Flag{
cli.GenericFlag{Name: "serve, s", Value: &Parser{}},
},
Action: func(ctx *cli.Context) {
if !reflect.DeepEqual(ctx.Generic("serve"), &Parser{"10", "20"}) {
t.Errorf("main name not set")
}
if !reflect.DeepEqual(ctx.Generic("s"), &Parser{"10", "20"}) {
t.Errorf("short name not set")
}
},
}
a.Run([]string{"run", "-s", "10,20"})
}
func TestParseGenericFromEnv(t *testing.T) {
os.Clearenv()
os.Setenv("APP_SERVE", "20,30")
a := cli.App{
Flags: []cli.Flag{
cli.GenericFlag{Name: "serve, s", Value: &Parser{}, EnvVar: "APP_SERVE"},
},
Action: func(ctx *cli.Context) {
if !reflect.DeepEqual(ctx.Generic("serve"), &Parser{"20", "30"}) {
t.Errorf("main name not set from env")
}
if !reflect.DeepEqual(ctx.Generic("s"), &Parser{"20", "30"}) {
t.Errorf("short name not set from env")
}
},
}
a.Run([]string{"run"})
}
func TestParseGenericFromEnvCascade(t *testing.T) {
os.Clearenv()
os.Setenv("APP_FOO", "99,2000")
a := cli.App{
Flags: []cli.Flag{
cli.GenericFlag{Name: "foos", Value: &Parser{}, EnvVar: "COMPAT_FOO,APP_FOO"},
},
Action: func(ctx *cli.Context) {
if !reflect.DeepEqual(ctx.Generic("foos"), &Parser{"99", "2000"}) {
t.Errorf("value not set from env")
}
},
}
a.Run([]string{"run"})
}

View File

@ -0,0 +1,211 @@
package cli
import "fmt"
// The text template for the Default help topic.
// cli.go uses text/template to render templates. You can
// render custom help text by setting this variable.
var AppHelpTemplate = `NAME:
{{.Name}} - {{.Usage}}
USAGE:
{{.Name}} {{if .Flags}}[global options] {{end}}command{{if .Flags}} [command options]{{end}} [arguments...]
VERSION:
{{.Version}}{{if or .Author .Email}}
AUTHOR:{{if .Author}}
{{.Author}}{{if .Email}} - <{{.Email}}>{{end}}{{else}}
{{.Email}}{{end}}{{end}}
COMMANDS:
{{range .Commands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
{{end}}{{if .Flags}}
GLOBAL OPTIONS:
{{range .Flags}}{{.}}
{{end}}{{end}}
`
// The text template for the command help topic.
// cli.go uses text/template to render templates. You can
// render custom help text by setting this variable.
var CommandHelpTemplate = `NAME:
{{.Name}} - {{.Usage}}
USAGE:
command {{.Name}}{{if .Flags}} [command options]{{end}} [arguments...]{{if .Description}}
DESCRIPTION:
{{.Description}}{{end}}{{if .Flags}}
OPTIONS:
{{range .Flags}}{{.}}
{{end}}{{ end }}
`
// The text template for the subcommand help topic.
// cli.go uses text/template to render templates. You can
// render custom help text by setting this variable.
var SubcommandHelpTemplate = `NAME:
{{.Name}} - {{.Usage}}
USAGE:
{{.Name}} command{{if .Flags}} [command options]{{end}} [arguments...]
COMMANDS:
{{range .Commands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
{{end}}{{if .Flags}}
OPTIONS:
{{range .Flags}}{{.}}
{{end}}{{end}}
`
var helpCommand = Command{
Name: "help",
ShortName: "h",
Usage: "Shows a list of commands or help for one command",
Action: func(c *Context) {
args := c.Args()
if args.Present() {
ShowCommandHelp(c, args.First())
} else {
ShowAppHelp(c)
}
},
}
var helpSubcommand = Command{
Name: "help",
ShortName: "h",
Usage: "Shows a list of commands or help for one command",
Action: func(c *Context) {
args := c.Args()
if args.Present() {
ShowCommandHelp(c, args.First())
} else {
ShowSubcommandHelp(c)
}
},
}
// Prints help for the App
type helpPrinter func(templ string, data interface{})
var HelpPrinter helpPrinter = nil
// Prints version for the App
var VersionPrinter = printVersion
func ShowAppHelp(c *Context) {
HelpPrinter(AppHelpTemplate, c.App)
}
// Prints the list of subcommands as the default app completion method
func DefaultAppComplete(c *Context) {
for _, command := range c.App.Commands {
fmt.Fprintln(c.App.Writer, command.Name)
if command.ShortName != "" {
fmt.Fprintln(c.App.Writer, command.ShortName)
}
}
}
// Prints help for the given command
func ShowCommandHelp(c *Context, command string) {
for _, c := range c.App.Commands {
if c.HasName(command) {
HelpPrinter(CommandHelpTemplate, c)
return
}
}
if c.App.CommandNotFound != nil {
c.App.CommandNotFound(c, command)
} else {
fmt.Fprintf(c.App.Writer, "No help topic for '%v'\n", command)
}
}
// Prints help for the given subcommand
func ShowSubcommandHelp(c *Context) {
ShowCommandHelp(c, c.Command.Name)
}
// Prints the version number of the App
func ShowVersion(c *Context) {
VersionPrinter(c)
}
func printVersion(c *Context) {
fmt.Fprintf(c.App.Writer, "%v version %v\n", c.App.Name, c.App.Version)
}
// Prints the lists of commands within a given context
func ShowCompletions(c *Context) {
a := c.App
if a != nil && a.BashComplete != nil {
a.BashComplete(c)
}
}
// Prints the custom completions for a given command
func ShowCommandCompletions(ctx *Context, command string) {
c := ctx.App.Command(command)
if c != nil && c.BashComplete != nil {
c.BashComplete(ctx)
}
}
func checkVersion(c *Context) bool {
if c.GlobalBool("version") {
ShowVersion(c)
return true
}
return false
}
func checkHelp(c *Context) bool {
if c.GlobalBool("h") || c.GlobalBool("help") {
ShowAppHelp(c)
return true
}
return false
}
func checkCommandHelp(c *Context, name string) bool {
if c.Bool("h") || c.Bool("help") {
ShowCommandHelp(c, name)
return true
}
return false
}
func checkSubcommandHelp(c *Context) bool {
if c.GlobalBool("h") || c.GlobalBool("help") {
ShowSubcommandHelp(c)
return true
}
return false
}
func checkCompletions(c *Context) bool {
if (c.GlobalBool(BashCompletionFlag.Name) || c.Bool(BashCompletionFlag.Name)) && c.App.EnableBashCompletion {
ShowCompletions(c)
return true
}
return false
}
func checkCommandCompletions(c *Context, name string) bool {
if c.Bool(BashCompletionFlag.Name) && c.App.EnableBashCompletion {
ShowCommandCompletions(c, name)
return true
}
return false
}

View File

@ -0,0 +1,19 @@
package cli_test
import (
"reflect"
"testing"
)
/* Test Helpers */
func expect(t *testing.T, a interface{}, b interface{}) {
if a != b {
t.Errorf("Expected %v (type %v) - Got %v (type %v)", b, reflect.TypeOf(b), a, reflect.TypeOf(a))
}
}
func refute(t *testing.T, a interface{}, b interface{}) {
if a == b {
t.Errorf("Did not expect %v (type %v) - Got %v (type %v)", b, reflect.TypeOf(b), a, reflect.TypeOf(a))
}
}

View File

@ -0,0 +1,4 @@
jpgo
jmespath-fuzz.zip
cpu.out
go-jmespath.test

View File

@ -0,0 +1,9 @@
language: go
sudo: false
go:
- 1.4
install: go get -v -t ./...
script: make test

View File

@ -0,0 +1,13 @@
Copyright 2015 James Saryerwinnie
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
http://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.

View File

@ -0,0 +1,44 @@
CMD = jpgo
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " test to run all the tests"
@echo " build to build the library and jp executable"
@echo " generate to run codegen"
generate:
go generate ./...
build:
rm -f $(CMD)
go build ./...
rm -f cmd/$(CMD)/$(CMD) && cd cmd/$(CMD)/ && go build ./...
mv cmd/$(CMD)/$(CMD) .
test:
go test -v ./...
check:
go vet ./...
@echo "golint ./..."
@lint=`golint ./...`; \
lint=`echo "$$lint" | grep -v "astnodetype_string.go" | grep -v "toktype_string.go"`; \
echo "$$lint"; \
if [ "$$lint" != "" ]; then exit 1; fi
htmlc:
go test -coverprofile="/tmp/jpcov" && go tool cover -html="/tmp/jpcov" && unlink /tmp/jpcov
buildfuzz:
go-fuzz-build github.com/jmespath/go-jmespath/fuzz
fuzz: buildfuzz
go-fuzz -bin=./jmespath-fuzz.zip -workdir=fuzz/corpus
bench:
go test -bench . -cpuprofile cpu.out
pprof-cpu:
go tool pprof ./go-jmespath.test ./cpu.out

View File

@ -0,0 +1,7 @@
# go-jmespath - A JMESPath implementation in Go
[![Build Status](https://img.shields.io/travis/jmespath/go-jmespath.svg)](https://travis-ci.org/jmespath/go-jmespath)
See http://jmespath.org for more info.

View File

@ -0,0 +1,12 @@
package jmespath
// Search evaluates a JMESPath expression against input data and returns the result.
func Search(expression string, data interface{}) (interface{}, error) {
intr := newInterpreter()
parser := NewParser()
ast, err := parser.Parse(expression)
if err != nil {
return nil, err
}
return intr.Execute(ast, data)
}

View File

@ -0,0 +1,16 @@
// generated by stringer -type astNodeType; DO NOT EDIT
package jmespath
import "fmt"
const _astNodeType_name = "ASTEmptyASTComparatorASTCurrentNodeASTExpRefASTFunctionExpressionASTFieldASTFilterProjectionASTFlattenASTIdentityASTIndexASTIndexExpressionASTKeyValPairASTLiteralASTMultiSelectHashASTMultiSelectListASTOrExpressionASTPipeASTProjectionASTSubexpressionASTSliceASTValueProjection"
var _astNodeType_index = [...]uint16{0, 8, 21, 35, 44, 65, 73, 92, 102, 113, 121, 139, 152, 162, 180, 198, 213, 220, 233, 249, 257, 275}
func (i astNodeType) String() string {
if i < 0 || i >= astNodeType(len(_astNodeType_index)-1) {
return fmt.Sprintf("astNodeType(%d)", i)
}
return _astNodeType_name[_astNodeType_index[i]:_astNodeType_index[i+1]]
}

View File

@ -0,0 +1,92 @@
[{
"given":
{"foo": {"bar": {"baz": "correct"}}},
"cases": [
{
"expression": "foo",
"result": {"bar": {"baz": "correct"}}
},
{
"expression": "foo.bar",
"result": {"baz": "correct"}
},
{
"expression": "foo.bar.baz",
"result": "correct"
},
{
"expression": "foo.bar.baz.bad",
"result": null
},
{
"expression": "foo.bar.bad",
"result": null
},
{
"expression": "foo.bad",
"result": null
},
{
"expression": "bad",
"result": null
},
{
"expression": "bad.morebad.morebad",
"result": null
}
]
},
{
"given":
{"foo": {"bar": ["one", "two", "three"]}},
"cases": [
{
"expression": "foo",
"result": {"bar": ["one", "two", "three"]}
},
{
"expression": "foo.bar",
"result": ["one", "two", "three"]
}
]
},
{
"given": ["one", "two", "three"],
"cases": [
{
"expression": "one",
"result": null
},
{
"expression": "two",
"result": null
},
{
"expression": "three",
"result": null
},
{
"expression": "one.two",
"result": null
}
]
},
{
"given":
{"foo": {"1": ["one", "two", "three"], "-1": "bar"}},
"cases": [
{
"expression": "foo.\"1\"",
"result": ["one", "two", "three"]
},
{
"expression": "foo.\"1\"[0]",
"result": "one"
},
{
"expression": "foo.\"-1\"",
"result": "bar"
}
]
}
]

View File

@ -0,0 +1,25 @@
[
{
"given": {
"foo": [{"name": "a"}, {"name": "b"}],
"bar": {"baz": "qux"}
},
"cases": [
{
"expression": "@",
"result": {
"foo": [{"name": "a"}, {"name": "b"}],
"bar": {"baz": "qux"}
}
},
{
"expression": "@.bar",
"result": {"baz": "qux"}
},
{
"expression": "@.foo[0]",
"result": {"name": "a"}
}
]
}
]

View File

@ -0,0 +1,46 @@
[{
"given": {
"foo.bar": "dot",
"foo bar": "space",
"foo\nbar": "newline",
"foo\"bar": "doublequote",
"c:\\\\windows\\path": "windows",
"/unix/path": "unix",
"\"\"\"": "threequotes",
"bar": {"baz": "qux"}
},
"cases": [
{
"expression": "\"foo.bar\"",
"result": "dot"
},
{
"expression": "\"foo bar\"",
"result": "space"
},
{
"expression": "\"foo\\nbar\"",
"result": "newline"
},
{
"expression": "\"foo\\\"bar\"",
"result": "doublequote"
},
{
"expression": "\"c:\\\\\\\\windows\\\\path\"",
"result": "windows"
},
{
"expression": "\"/unix/path\"",
"result": "unix"
},
{
"expression": "\"\\\"\\\"\\\"\"",
"result": "threequotes"
},
{
"expression": "\"bar\".\"baz\"",
"result": "qux"
}
]
}]

View File

@ -0,0 +1,319 @@
[
{
"given": {"foo": [{"name": "a"}, {"name": "b"}]},
"cases": [
{
"comment": "Matching a literal",
"expression": "foo[?name == 'a']",
"result": [{"name": "a"}]
}
]
},
{
"given": {"foo": [0, 1], "bar": [2, 3]},
"cases": [
{
"comment": "Matching a literal",
"expression": "*[?[0] == `0`]",
"result": [[], []]
}
]
},
{
"given": {"foo": [{"first": "foo", "last": "bar"},
{"first": "foo", "last": "foo"},
{"first": "foo", "last": "baz"}]},
"cases": [
{
"comment": "Matching an expression",
"expression": "foo[?first == last]",
"result": [{"first": "foo", "last": "foo"}]
},
{
"comment": "Verify projection created from filter",
"expression": "foo[?first == last].first",
"result": ["foo"]
}
]
},
{
"given": {"foo": [{"age": 20},
{"age": 25},
{"age": 30}]},
"cases": [
{
"comment": "Greater than with a number",
"expression": "foo[?age > `25`]",
"result": [{"age": 30}]
},
{
"expression": "foo[?age >= `25`]",
"result": [{"age": 25}, {"age": 30}]
},
{
"comment": "Greater than with a number",
"expression": "foo[?age > `30`]",
"result": []
},
{
"comment": "Greater than with a number",
"expression": "foo[?age < `25`]",
"result": [{"age": 20}]
},
{
"comment": "Greater than with a number",
"expression": "foo[?age <= `25`]",
"result": [{"age": 20}, {"age": 25}]
},
{
"comment": "Greater than with a number",
"expression": "foo[?age < `20`]",
"result": []
},
{
"expression": "foo[?age == `20`]",
"result": [{"age": 20}]
},
{
"expression": "foo[?age != `20`]",
"result": [{"age": 25}, {"age": 30}]
}
]
},
{
"given": {"foo": [{"top": {"name": "a"}},
{"top": {"name": "b"}}]},
"cases": [
{
"comment": "Filter with subexpression",
"expression": "foo[?top.name == 'a']",
"result": [{"top": {"name": "a"}}]
}
]
},
{
"given": {"foo": [{"top": {"first": "foo", "last": "bar"}},
{"top": {"first": "foo", "last": "foo"}},
{"top": {"first": "foo", "last": "baz"}}]},
"cases": [
{
"comment": "Matching an expression",
"expression": "foo[?top.first == top.last]",
"result": [{"top": {"first": "foo", "last": "foo"}}]
},
{
"comment": "Matching a JSON array",
"expression": "foo[?top == `{\"first\": \"foo\", \"last\": \"bar\"}`]",
"result": [{"top": {"first": "foo", "last": "bar"}}]
}
]
},
{
"given": {"foo": [
{"key": true},
{"key": false},
{"key": 0},
{"key": 1},
{"key": [0]},
{"key": {"bar": [0]}},
{"key": null},
{"key": [1]},
{"key": {"a":2}}
]},
"cases": [
{
"expression": "foo[?key == `true`]",
"result": [{"key": true}]
},
{
"expression": "foo[?key == `false`]",
"result": [{"key": false}]
},
{
"expression": "foo[?key == `0`]",
"result": [{"key": 0}]
},
{
"expression": "foo[?key == `1`]",
"result": [{"key": 1}]
},
{
"expression": "foo[?key == `[0]`]",
"result": [{"key": [0]}]
},
{
"expression": "foo[?key == `{\"bar\": [0]}`]",
"result": [{"key": {"bar": [0]}}]
},
{
"expression": "foo[?key == `null`]",
"result": [{"key": null}]
},
{
"expression": "foo[?key == `[1]`]",
"result": [{"key": [1]}]
},
{
"expression": "foo[?key == `{\"a\":2}`]",
"result": [{"key": {"a":2}}]
},
{
"expression": "foo[?`true` == key]",
"result": [{"key": true}]
},
{
"expression": "foo[?`false` == key]",
"result": [{"key": false}]
},
{
"expression": "foo[?`0` == key]",
"result": [{"key": 0}]
},
{
"expression": "foo[?`1` == key]",
"result": [{"key": 1}]
},
{
"expression": "foo[?`[0]` == key]",
"result": [{"key": [0]}]
},
{
"expression": "foo[?`{\"bar\": [0]}` == key]",
"result": [{"key": {"bar": [0]}}]
},
{
"expression": "foo[?`null` == key]",
"result": [{"key": null}]
},
{
"expression": "foo[?`[1]` == key]",
"result": [{"key": [1]}]
},
{
"expression": "foo[?`{\"a\":2}` == key]",
"result": [{"key": {"a":2}}]
},
{
"expression": "foo[?key != `true`]",
"result": [{"key": false}, {"key": 0}, {"key": 1}, {"key": [0]},
{"key": {"bar": [0]}}, {"key": null}, {"key": [1]}, {"key": {"a":2}}]
},
{
"expression": "foo[?key != `false`]",
"result": [{"key": true}, {"key": 0}, {"key": 1}, {"key": [0]},
{"key": {"bar": [0]}}, {"key": null}, {"key": [1]}, {"key": {"a":2}}]
},
{
"expression": "foo[?key != `0`]",
"result": [{"key": true}, {"key": false}, {"key": 1}, {"key": [0]},
{"key": {"bar": [0]}}, {"key": null}, {"key": [1]}, {"key": {"a":2}}]
},
{
"expression": "foo[?key != `1`]",
"result": [{"key": true}, {"key": false}, {"key": 0}, {"key": [0]},
{"key": {"bar": [0]}}, {"key": null}, {"key": [1]}, {"key": {"a":2}}]
},
{
"expression": "foo[?key != `null`]",
"result": [{"key": true}, {"key": false}, {"key": 0}, {"key": 1}, {"key": [0]},
{"key": {"bar": [0]}}, {"key": [1]}, {"key": {"a":2}}]
},
{
"expression": "foo[?key != `[1]`]",
"result": [{"key": true}, {"key": false}, {"key": 0}, {"key": 1}, {"key": [0]},
{"key": {"bar": [0]}}, {"key": null}, {"key": {"a":2}}]
},
{
"expression": "foo[?key != `{\"a\":2}`]",
"result": [{"key": true}, {"key": false}, {"key": 0}, {"key": 1}, {"key": [0]},
{"key": {"bar": [0]}}, {"key": null}, {"key": [1]}]
},
{
"expression": "foo[?`true` != key]",
"result": [{"key": false}, {"key": 0}, {"key": 1}, {"key": [0]},
{"key": {"bar": [0]}}, {"key": null}, {"key": [1]}, {"key": {"a":2}}]
},
{
"expression": "foo[?`false` != key]",
"result": [{"key": true}, {"key": 0}, {"key": 1}, {"key": [0]},
{"key": {"bar": [0]}}, {"key": null}, {"key": [1]}, {"key": {"a":2}}]
},
{
"expression": "foo[?`0` != key]",
"result": [{"key": true}, {"key": false}, {"key": 1}, {"key": [0]},
{"key": {"bar": [0]}}, {"key": null}, {"key": [1]}, {"key": {"a":2}}]
},
{
"expression": "foo[?`1` != key]",
"result": [{"key": true}, {"key": false}, {"key": 0}, {"key": [0]},
{"key": {"bar": [0]}}, {"key": null}, {"key": [1]}, {"key": {"a":2}}]
},
{
"expression": "foo[?`null` != key]",
"result": [{"key": true}, {"key": false}, {"key": 0}, {"key": 1}, {"key": [0]},
{"key": {"bar": [0]}}, {"key": [1]}, {"key": {"a":2}}]
},
{
"expression": "foo[?`[1]` != key]",
"result": [{"key": true}, {"key": false}, {"key": 0}, {"key": 1}, {"key": [0]},
{"key": {"bar": [0]}}, {"key": null}, {"key": {"a":2}}]
},
{
"expression": "foo[?`{\"a\":2}` != key]",
"result": [{"key": true}, {"key": false}, {"key": 0}, {"key": 1}, {"key": [0]},
{"key": {"bar": [0]}}, {"key": null}, {"key": [1]}]
}
]
},
{
"given": {"reservations": [
{"instances": [
{"foo": 1, "bar": 2}, {"foo": 1, "bar": 3},
{"foo": 1, "bar": 2}, {"foo": 2, "bar": 1}]}]},
"cases": [
{
"expression": "reservations[].instances[?bar==`1`]",
"result": [[{"foo": 2, "bar": 1}]]
},
{
"expression": "reservations[*].instances[?bar==`1`]",
"result": [[{"foo": 2, "bar": 1}]]
},
{
"expression": "reservations[].instances[?bar==`1`][]",
"result": [{"foo": 2, "bar": 1}]
}
]
},
{
"given": {
"baz": "other",
"foo": [
{"bar": 1}, {"bar": 2}, {"bar": 3}, {"bar": 4}, {"bar": 1, "baz": 2}
]
},
"cases": [
{
"expression": "foo[?bar==`1`].bar[0]",
"result": []
}
]
},
{
"given": {
"foo": [
{"a": 1, "b": {"c": "x"}},
{"a": 1, "b": {"c": "y"}},
{"a": 1, "b": {"c": "z"}},
{"a": 2, "b": {"c": "z"}},
{"a": 1, "baz": 2}
]
},
"cases": [
{
"expression": "foo[?a==`1`].b.c",
"result": ["x", "y", "z"]
}
]
}
]

View File

@ -0,0 +1,749 @@
[{
"given":
{
"foo": -1,
"zero": 0,
"numbers": [-1, 3, 4, 5],
"array": [-1, 3, 4, 5, "a", "100"],
"strings": ["a", "b", "c"],
"decimals": [1.01, 1.2, -1.5],
"str": "Str",
"false": false,
"empty_list": [],
"empty_hash": {},
"objects": {"foo": "bar", "bar": "baz"},
"null_key": null
},
"cases": [
{
"expression": "abs(foo)",
"result": 1
},
{
"expression": "abs(foo)",
"result": 1
},
{
"expression": "abs(str)",
"error": "invalid-type"
},
{
"expression": "abs(array[1])",
"result": 3
},
{
"expression": "abs(array[1])",
"result": 3
},
{
"expression": "abs(`false`)",
"error": "invalid-type"
},
{
"expression": "abs(`-24`)",
"result": 24
},
{
"expression": "abs(`-24`)",
"result": 24
},
{
"expression": "abs(`1`, `2`)",
"error": "invalid-arity"
},
{
"expression": "abs()",
"error": "invalid-arity"
},
{
"expression": "unknown_function(`1`, `2`)",
"error": "unknown-function"
},
{
"expression": "avg(numbers)",
"result": 2.75
},
{
"expression": "avg(array)",
"error": "invalid-type"
},
{
"expression": "avg('abc')",
"error": "invalid-type"
},
{
"expression": "avg(foo)",
"error": "invalid-type"
},
{
"expression": "avg(@)",
"error": "invalid-type"
},
{
"expression": "avg(strings)",
"error": "invalid-type"
},
{
"expression": "ceil(`1.2`)",
"result": 2
},
{
"expression": "ceil(decimals[0])",
"result": 2
},
{
"expression": "ceil(decimals[1])",
"result": 2
},
{
"expression": "ceil(decimals[2])",
"result": -1
},
{
"expression": "ceil('string')",
"error": "invalid-type"
},
{
"expression": "contains('abc', 'a')",
"result": true
},
{
"expression": "contains('abc', 'd')",
"result": false
},
{
"expression": "contains(`false`, 'd')",
"error": "invalid-type"
},
{
"expression": "contains(strings, 'a')",
"result": true
},
{
"expression": "contains(decimals, `1.2`)",
"result": true
},
{
"expression": "contains(decimals, `false`)",
"result": false
},
{
"expression": "ends_with(str, 'r')",
"result": true
},
{
"expression": "ends_with(str, 'tr')",
"result": true
},
{
"expression": "ends_with(str, 'Str')",
"result": true
},
{
"expression": "ends_with(str, 'SStr')",
"result": false
},
{
"expression": "ends_with(str, 'foo')",
"result": false
},
{
"expression": "ends_with(str, `0`)",
"error": "invalid-type"
},
{
"expression": "floor(`1.2`)",
"result": 1
},
{
"expression": "floor('string')",
"error": "invalid-type"
},
{
"expression": "floor(decimals[0])",
"result": 1
},
{
"expression": "floor(foo)",
"result": -1
},
{
"expression": "floor(str)",
"error": "invalid-type"
},
{
"expression": "length('abc')",
"result": 3
},
{
"expression": "length('')",
"result": 0
},
{
"expression": "length(@)",
"result": 12
},
{
"expression": "length(strings[0])",
"result": 1
},
{
"expression": "length(str)",
"result": 3
},
{
"expression": "length(array)",
"result": 6
},
{
"expression": "length(objects)",
"result": 2
},
{
"expression": "length(`false`)",
"error": "invalid-type"
},
{
"expression": "length(foo)",
"error": "invalid-type"
},
{
"expression": "length(strings[0])",
"result": 1
},
{
"expression": "max(numbers)",
"result": 5
},
{
"expression": "max(decimals)",
"result": 1.2
},
{
"expression": "max(strings)",
"result": "c"
},
{
"expression": "max(abc)",
"error": "invalid-type"
},
{
"expression": "max(array)",
"error": "invalid-type"
},
{
"expression": "max(decimals)",
"result": 1.2
},
{
"expression": "max(empty_list)",
"result": null
},
{
"expression": "merge(`{}`)",
"result": {}
},
{
"expression": "merge(`{}`, `{}`)",
"result": {}
},
{
"expression": "merge(`{\"a\": 1}`, `{\"b\": 2}`)",
"result": {"a": 1, "b": 2}
},
{
"expression": "merge(`{\"a\": 1}`, `{\"a\": 2}`)",
"result": {"a": 2}
},
{
"expression": "merge(`{\"a\": 1, \"b\": 2}`, `{\"a\": 2, \"c\": 3}`, `{\"d\": 4}`)",
"result": {"a": 2, "b": 2, "c": 3, "d": 4}
},
{
"expression": "min(numbers)",
"result": -1
},
{
"expression": "min(decimals)",
"result": -1.5
},
{
"expression": "min(abc)",
"error": "invalid-type"
},
{
"expression": "min(array)",
"error": "invalid-type"
},
{
"expression": "min(empty_list)",
"result": null
},
{
"expression": "min(decimals)",
"result": -1.5
},
{
"expression": "min(strings)",
"result": "a"
},
{
"expression": "type('abc')",
"result": "string"
},
{
"expression": "type(`1.0`)",
"result": "number"
},
{
"expression": "type(`2`)",
"result": "number"
},
{
"expression": "type(`true`)",
"result": "boolean"
},
{
"expression": "type(`false`)",
"result": "boolean"
},
{
"expression": "type(`null`)",
"result": "null"
},
{
"expression": "type(`[0]`)",
"result": "array"
},
{
"expression": "type(`{\"a\": \"b\"}`)",
"result": "object"
},
{
"expression": "type(@)",
"result": "object"
},
{
"expression": "sort(keys(objects))",
"result": ["bar", "foo"]
},
{
"expression": "keys(foo)",
"error": "invalid-type"
},
{
"expression": "keys(strings)",
"error": "invalid-type"
},
{
"expression": "keys(`false`)",
"error": "invalid-type"
},
{
"expression": "sort(values(objects))",
"result": ["bar", "baz"]
},
{
"expression": "keys(empty_hash)",
"result": []
},
{
"expression": "values(foo)",
"error": "invalid-type"
},
{
"expression": "join(', ', strings)",
"result": "a, b, c"
},
{
"expression": "join(', ', strings)",
"result": "a, b, c"
},
{
"expression": "join(',', `[\"a\", \"b\"]`)",
"result": "a,b"
},
{
"expression": "join(',', `[\"a\", 0]`)",
"error": "invalid-type"
},
{
"expression": "join(', ', str)",
"error": "invalid-type"
},
{
"expression": "join('|', strings)",
"result": "a|b|c"
},
{
"expression": "join(`2`, strings)",
"error": "invalid-type"
},
{
"expression": "join('|', decimals)",
"error": "invalid-type"
},
{
"expression": "join('|', decimals[].to_string(@))",
"result": "1.01|1.2|-1.5"
},
{
"expression": "join('|', empty_list)",
"result": ""
},
{
"expression": "reverse(numbers)",
"result": [5, 4, 3, -1]
},
{
"expression": "reverse(array)",
"result": ["100", "a", 5, 4, 3, -1]
},
{
"expression": "reverse(`[]`)",
"result": []
},
{
"expression": "reverse('')",
"result": ""
},
{
"expression": "reverse('hello world')",
"result": "dlrow olleh"
},
{
"expression": "starts_with(str, 'S')",
"result": true
},
{
"expression": "starts_with(str, 'St')",
"result": true
},
{
"expression": "starts_with(str, 'Str')",
"result": true
},
{
"expression": "starts_with(str, 'String')",
"result": false
},
{
"expression": "starts_with(str, `0`)",
"error": "invalid-type"
},
{
"expression": "sum(numbers)",
"result": 11
},
{
"expression": "sum(decimals)",
"result": 0.71
},
{
"expression": "sum(array)",
"error": "invalid-type"
},
{
"expression": "sum(array[].to_number(@))",
"result": 111
},
{
"expression": "sum(`[]`)",
"result": 0
},
{
"expression": "to_array('foo')",
"result": ["foo"]
},
{
"expression": "to_array(`0`)",
"result": [0]
},
{
"expression": "to_array(objects)",
"result": [{"foo": "bar", "bar": "baz"}]
},
{
"expression": "to_array(`[1, 2, 3]`)",
"result": [1, 2, 3]
},
{
"expression": "to_array(false)",
"result": [false]
},
{
"expression": "to_string('foo')",
"result": "foo"
},
{
"expression": "to_string(`1.2`)",
"result": "1.2"
},
{
"expression": "to_string(`[0, 1]`)",
"result": "[0,1]"
},
{
"expression": "to_number('1.0')",
"result": 1.0
},
{
"expression": "to_number('1.1')",
"result": 1.1
},
{
"expression": "to_number('4')",
"result": 4
},
{
"expression": "to_number('notanumber')",
"result": null
},
{
"expression": "to_number(`false`)",
"result": null
},
{
"expression": "to_number(`null`)",
"result": null
},
{
"expression": "to_number(`[0]`)",
"result": null
},
{
"expression": "to_number(`{\"foo\": 0}`)",
"result": null
},
{
"expression": "\"to_string\"(`1.0`)",
"error": "syntax"
},
{
"expression": "sort(numbers)",
"result": [-1, 3, 4, 5]
},
{
"expression": "sort(strings)",
"result": ["a", "b", "c"]
},
{
"expression": "sort(decimals)",
"result": [-1.5, 1.01, 1.2]
},
{
"expression": "sort(array)",
"error": "invalid-type"
},
{
"expression": "sort(abc)",
"error": "invalid-type"
},
{
"expression": "sort(empty_list)",
"result": []
},
{
"expression": "sort(@)",
"error": "invalid-type"
},
{
"expression": "not_null(unknown_key, str)",
"result": "Str"
},
{
"expression": "not_null(unknown_key, foo.bar, empty_list, str)",
"result": []
},
{
"expression": "not_null(unknown_key, null_key, empty_list, str)",
"result": []
},
{
"expression": "not_null(all, expressions, are_null)",
"result": null
},
{
"expression": "not_null()",
"error": "invalid-arity"
},
{
"description": "function projection on single arg function",
"expression": "numbers[].to_string(@)",
"result": ["-1", "3", "4", "5"]
},
{
"description": "function projection on single arg function",
"expression": "array[].to_number(@)",
"result": [-1, 3, 4, 5, 100]
}
]
}, {
"given":
{
"foo": [
{"b": "b", "a": "a"},
{"c": "c", "b": "b"},
{"d": "d", "c": "c"},
{"e": "e", "d": "d"},
{"f": "f", "e": "e"}
]
},
"cases": [
{
"description": "function projection on variadic function",
"expression": "foo[].not_null(f, e, d, c, b, a)",
"result": ["b", "c", "d", "e", "f"]
}
]
}, {
"given":
{
"people": [
{"age": 20, "age_str": "20", "bool": true, "name": "a", "extra": "foo"},
{"age": 40, "age_str": "40", "bool": false, "name": "b", "extra": "bar"},
{"age": 30, "age_str": "30", "bool": true, "name": "c"},
{"age": 50, "age_str": "50", "bool": false, "name": "d"},
{"age": 10, "age_str": "10", "bool": true, "name": 3}
]
},
"cases": [
{
"description": "sort by field expression",
"expression": "sort_by(people, &age)",
"result": [
{"age": 10, "age_str": "10", "bool": true, "name": 3},
{"age": 20, "age_str": "20", "bool": true, "name": "a", "extra": "foo"},
{"age": 30, "age_str": "30", "bool": true, "name": "c"},
{"age": 40, "age_str": "40", "bool": false, "name": "b", "extra": "bar"},
{"age": 50, "age_str": "50", "bool": false, "name": "d"}
]
},
{
"expression": "sort_by(people, &age_str)",
"result": [
{"age": 10, "age_str": "10", "bool": true, "name": 3},
{"age": 20, "age_str": "20", "bool": true, "name": "a", "extra": "foo"},
{"age": 30, "age_str": "30", "bool": true, "name": "c"},
{"age": 40, "age_str": "40", "bool": false, "name": "b", "extra": "bar"},
{"age": 50, "age_str": "50", "bool": false, "name": "d"}
]
},
{
"description": "sort by function expression",
"expression": "sort_by(people, &to_number(age_str))",
"result": [
{"age": 10, "age_str": "10", "bool": true, "name": 3},
{"age": 20, "age_str": "20", "bool": true, "name": "a", "extra": "foo"},
{"age": 30, "age_str": "30", "bool": true, "name": "c"},
{"age": 40, "age_str": "40", "bool": false, "name": "b", "extra": "bar"},
{"age": 50, "age_str": "50", "bool": false, "name": "d"}
]
},
{
"description": "function projection on sort_by function",
"expression": "sort_by(people, &age)[].name",
"result": [3, "a", "c", "b", "d"]
},
{
"expression": "sort_by(people, &extra)",
"error": "invalid-type"
},
{
"expression": "sort_by(people, &bool)",
"error": "invalid-type"
},
{
"expression": "sort_by(people, &name)",
"error": "invalid-type"
},
{
"expression": "sort_by(people, name)",
"error": "invalid-type"
},
{
"expression": "sort_by(people, &age)[].extra",
"result": ["foo", "bar"]
},
{
"expression": "sort_by(`[]`, &age)",
"result": []
},
{
"expression": "max_by(people, &age)",
"result": {"age": 50, "age_str": "50", "bool": false, "name": "d"}
},
{
"expression": "max_by(people, &age_str)",
"result": {"age": 50, "age_str": "50", "bool": false, "name": "d"}
},
{
"expression": "max_by(people, &bool)",
"error": "invalid-type"
},
{
"expression": "max_by(people, &extra)",
"error": "invalid-type"
},
{
"expression": "max_by(people, &to_number(age_str))",
"result": {"age": 50, "age_str": "50", "bool": false, "name": "d"}
},
{
"expression": "min_by(people, &age)",
"result": {"age": 10, "age_str": "10", "bool": true, "name": 3}
},
{
"expression": "min_by(people, &age_str)",
"result": {"age": 10, "age_str": "10", "bool": true, "name": 3}
},
{
"expression": "min_by(people, &bool)",
"error": "invalid-type"
},
{
"expression": "min_by(people, &extra)",
"error": "invalid-type"
},
{
"expression": "min_by(people, &to_number(age_str))",
"result": {"age": 10, "age_str": "10", "bool": true, "name": 3}
}
]
}, {
"given":
{
"people": [
{"age": 10, "order": "1"},
{"age": 10, "order": "2"},
{"age": 10, "order": "3"},
{"age": 10, "order": "4"},
{"age": 10, "order": "5"},
{"age": 10, "order": "6"},
{"age": 10, "order": "7"},
{"age": 10, "order": "8"},
{"age": 10, "order": "9"},
{"age": 10, "order": "10"},
{"age": 10, "order": "11"}
]
},
"cases": [
{
"description": "stable sort order",
"expression": "sort_by(people, &age)",
"result": [
{"age": 10, "order": "1"},
{"age": 10, "order": "2"},
{"age": 10, "order": "3"},
{"age": 10, "order": "4"},
{"age": 10, "order": "5"},
{"age": 10, "order": "6"},
{"age": 10, "order": "7"},
{"age": 10, "order": "8"},
{"age": 10, "order": "9"},
{"age": 10, "order": "10"},
{"age": 10, "order": "11"}
]
}
]
}]

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,346 @@
[{
"given":
{"foo": {"bar": ["zero", "one", "two"]}},
"cases": [
{
"expression": "foo.bar[0]",
"result": "zero"
},
{
"expression": "foo.bar[1]",
"result": "one"
},
{
"expression": "foo.bar[2]",
"result": "two"
},
{
"expression": "foo.bar[3]",
"result": null
},
{
"expression": "foo.bar[-1]",
"result": "two"
},
{
"expression": "foo.bar[-2]",
"result": "one"
},
{
"expression": "foo.bar[-3]",
"result": "zero"
},
{
"expression": "foo.bar[-4]",
"result": null
}
]
},
{
"given":
{"foo": [{"bar": "one"}, {"bar": "two"}, {"bar": "three"}, {"notbar": "four"}]},
"cases": [
{
"expression": "foo.bar",
"result": null
},
{
"expression": "foo[0].bar",
"result": "one"
},
{
"expression": "foo[1].bar",
"result": "two"
},
{
"expression": "foo[2].bar",
"result": "three"
},
{
"expression": "foo[3].notbar",
"result": "four"
},
{
"expression": "foo[3].bar",
"result": null
},
{
"expression": "foo[0]",
"result": {"bar": "one"}
},
{
"expression": "foo[1]",
"result": {"bar": "two"}
},
{
"expression": "foo[2]",
"result": {"bar": "three"}
},
{
"expression": "foo[3]",
"result": {"notbar": "four"}
},
{
"expression": "foo[4]",
"result": null
}
]
},
{
"given": [
"one", "two", "three"
],
"cases": [
{
"expression": "[0]",
"result": "one"
},
{
"expression": "[1]",
"result": "two"
},
{
"expression": "[2]",
"result": "three"
},
{
"expression": "[-1]",
"result": "three"
},
{
"expression": "[-2]",
"result": "two"
},
{
"expression": "[-3]",
"result": "one"
}
]
},
{
"given": {"reservations": [
{"instances": [{"foo": 1}, {"foo": 2}]}
]},
"cases": [
{
"expression": "reservations[].instances[].foo",
"result": [1, 2]
},
{
"expression": "reservations[].instances[].bar",
"result": []
},
{
"expression": "reservations[].notinstances[].foo",
"result": []
},
{
"expression": "reservations[].notinstances[].foo",
"result": []
}
]
},
{
"given": {"reservations": [{
"instances": [
{"foo": [{"bar": 1}, {"bar": 2}, {"notbar": 3}, {"bar": 4}]},
{"foo": [{"bar": 5}, {"bar": 6}, {"notbar": [7]}, {"bar": 8}]},
{"foo": "bar"},
{"notfoo": [{"bar": 20}, {"bar": 21}, {"notbar": [7]}, {"bar": 22}]},
{"bar": [{"baz": [1]}, {"baz": [2]}, {"baz": [3]}, {"baz": [4]}]},
{"baz": [{"baz": [1, 2]}, {"baz": []}, {"baz": []}, {"baz": [3, 4]}]},
{"qux": [{"baz": []}, {"baz": [1, 2, 3]}, {"baz": [4]}, {"baz": []}]}
],
"otherkey": {"foo": [{"bar": 1}, {"bar": 2}, {"notbar": 3}, {"bar": 4}]}
}, {
"instances": [
{"a": [{"bar": 1}, {"bar": 2}, {"notbar": 3}, {"bar": 4}]},
{"b": [{"bar": 5}, {"bar": 6}, {"notbar": [7]}, {"bar": 8}]},
{"c": "bar"},
{"notfoo": [{"bar": 23}, {"bar": 24}, {"notbar": [7]}, {"bar": 25}]},
{"qux": [{"baz": []}, {"baz": [1, 2, 3]}, {"baz": [4]}, {"baz": []}]}
],
"otherkey": {"foo": [{"bar": 1}, {"bar": 2}, {"notbar": 3}, {"bar": 4}]}
}
]},
"cases": [
{
"expression": "reservations[].instances[].foo[].bar",
"result": [1, 2, 4, 5, 6, 8]
},
{
"expression": "reservations[].instances[].foo[].baz",
"result": []
},
{
"expression": "reservations[].instances[].notfoo[].bar",
"result": [20, 21, 22, 23, 24, 25]
},
{
"expression": "reservations[].instances[].notfoo[].notbar",
"result": [[7], [7]]
},
{
"expression": "reservations[].notinstances[].foo",
"result": []
},
{
"expression": "reservations[].instances[].foo[].notbar",
"result": [3, [7]]
},
{
"expression": "reservations[].instances[].bar[].baz",
"result": [[1], [2], [3], [4]]
},
{
"expression": "reservations[].instances[].baz[].baz",
"result": [[1, 2], [], [], [3, 4]]
},
{
"expression": "reservations[].instances[].qux[].baz",
"result": [[], [1, 2, 3], [4], [], [], [1, 2, 3], [4], []]
},
{
"expression": "reservations[].instances[].qux[].baz[]",
"result": [1, 2, 3, 4, 1, 2, 3, 4]
}
]
},
{
"given": {
"foo": [
[["one", "two"], ["three", "four"]],
[["five", "six"], ["seven", "eight"]],
[["nine"], ["ten"]]
]
},
"cases": [
{
"expression": "foo[]",
"result": [["one", "two"], ["three", "four"], ["five", "six"],
["seven", "eight"], ["nine"], ["ten"]]
},
{
"expression": "foo[][0]",
"result": ["one", "three", "five", "seven", "nine", "ten"]
},
{
"expression": "foo[][1]",
"result": ["two", "four", "six", "eight"]
},
{
"expression": "foo[][0][0]",
"result": []
},
{
"expression": "foo[][2][2]",
"result": []
},
{
"expression": "foo[][0][0][100]",
"result": []
}
]
},
{
"given": {
"foo": [{
"bar": [
{
"qux": 2,
"baz": 1
},
{
"qux": 4,
"baz": 3
}
]
},
{
"bar": [
{
"qux": 6,
"baz": 5
},
{
"qux": 8,
"baz": 7
}
]
}
]
},
"cases": [
{
"expression": "foo",
"result": [{"bar": [{"qux": 2, "baz": 1}, {"qux": 4, "baz": 3}]},
{"bar": [{"qux": 6, "baz": 5}, {"qux": 8, "baz": 7}]}]
},
{
"expression": "foo[]",
"result": [{"bar": [{"qux": 2, "baz": 1}, {"qux": 4, "baz": 3}]},
{"bar": [{"qux": 6, "baz": 5}, {"qux": 8, "baz": 7}]}]
},
{
"expression": "foo[].bar",
"result": [[{"qux": 2, "baz": 1}, {"qux": 4, "baz": 3}],
[{"qux": 6, "baz": 5}, {"qux": 8, "baz": 7}]]
},
{
"expression": "foo[].bar[]",
"result": [{"qux": 2, "baz": 1}, {"qux": 4, "baz": 3},
{"qux": 6, "baz": 5}, {"qux": 8, "baz": 7}]
},
{
"expression": "foo[].bar[].baz",
"result": [1, 3, 5, 7]
}
]
},
{
"given": {
"string": "string",
"hash": {"foo": "bar", "bar": "baz"},
"number": 23,
"nullvalue": null
},
"cases": [
{
"expression": "string[]",
"result": null
},
{
"expression": "hash[]",
"result": null
},
{
"expression": "number[]",
"result": null
},
{
"expression": "nullvalue[]",
"result": null
},
{
"expression": "string[].foo",
"result": null
},
{
"expression": "hash[].foo",
"result": null
},
{
"expression": "number[].foo",
"result": null
},
{
"expression": "nullvalue[].foo",
"result": null
},
{
"expression": "nullvalue[].foo[].bar",
"result": null
}
]
}
]

View File

@ -0,0 +1,185 @@
[
{
"given": {
"foo": [{"name": "a"}, {"name": "b"}],
"bar": {"baz": "qux"}
},
"cases": [
{
"expression": "`\"foo\"`",
"result": "foo"
},
{
"comment": "Interpret escaped unicode.",
"expression": "`\"\\u03a6\"`",
"result": "Φ"
},
{
"expression": "`\"✓\"`",
"result": "✓"
},
{
"expression": "`[1, 2, 3]`",
"result": [1, 2, 3]
},
{
"expression": "`{\"a\": \"b\"}`",
"result": {"a": "b"}
},
{
"expression": "`true`",
"result": true
},
{
"expression": "`false`",
"result": false
},
{
"expression": "`null`",
"result": null
},
{
"expression": "`0`",
"result": 0
},
{
"expression": "`1`",
"result": 1
},
{
"expression": "`2`",
"result": 2
},
{
"expression": "`3`",
"result": 3
},
{
"expression": "`4`",
"result": 4
},
{
"expression": "`5`",
"result": 5
},
{
"expression": "`6`",
"result": 6
},
{
"expression": "`7`",
"result": 7
},
{
"expression": "`8`",
"result": 8
},
{
"expression": "`9`",
"result": 9
},
{
"comment": "Escaping a backtick in quotes",
"expression": "`\"foo\\`bar\"`",
"result": "foo`bar"
},
{
"comment": "Double quote in literal",
"expression": "`\"foo\\\"bar\"`",
"result": "foo\"bar"
},
{
"expression": "`\"1\\`\"`",
"result": "1`"
},
{
"comment": "Multiple literal expressions with escapes",
"expression": "`\"\\\\\"`.{a:`\"b\"`}",
"result": {"a": "b"}
},
{
"comment": "literal . identifier",
"expression": "`{\"a\": \"b\"}`.a",
"result": "b"
},
{
"comment": "literal . identifier . identifier",
"expression": "`{\"a\": {\"b\": \"c\"}}`.a.b",
"result": "c"
},
{
"comment": "literal . identifier bracket-expr",
"expression": "`[0, 1, 2]`[1]",
"result": 1
}
]
},
{
"comment": "Literals",
"given": {"type": "object"},
"cases": [
{
"comment": "Literal with leading whitespace",
"expression": "` {\"foo\": true}`",
"result": {"foo": true}
},
{
"comment": "Literal with trailing whitespace",
"expression": "`{\"foo\": true} `",
"result": {"foo": true}
},
{
"comment": "Literal on RHS of subexpr not allowed",
"expression": "foo.`\"bar\"`",
"error": "syntax"
}
]
},
{
"comment": "Raw String Literals",
"given": {},
"cases": [
{
"expression": "'foo'",
"result": "foo"
},
{
"expression": "' foo '",
"result": " foo "
},
{
"expression": "'0'",
"result": "0"
},
{
"expression": "'newline\n'",
"result": "newline\n"
},
{
"expression": "'\n'",
"result": "\n"
},
{
"expression": "'✓'",
"result": "✓"
},
{
"expression": "'𝄞'",
"result": "𝄞"
},
{
"expression": "' [foo] '",
"result": " [foo] "
},
{
"expression": "'[foo]'",
"result": "[foo]"
},
{
"comment": "Do not interpret escaped unicode.",
"expression": "'\\u03a6'",
"result": "\\u03a6"
}
]
}
]

View File

@ -0,0 +1,393 @@
[{
"given": {
"foo": {
"bar": "bar",
"baz": "baz",
"qux": "qux",
"nested": {
"one": {
"a": "first",
"b": "second",
"c": "third"
},
"two": {
"a": "first",
"b": "second",
"c": "third"
},
"three": {
"a": "first",
"b": "second",
"c": {"inner": "third"}
}
}
},
"bar": 1,
"baz": 2,
"qux\"": 3
},
"cases": [
{
"expression": "foo.{bar: bar}",
"result": {"bar": "bar"}
},
{
"expression": "foo.{\"bar\": bar}",
"result": {"bar": "bar"}
},
{
"expression": "foo.{\"foo.bar\": bar}",
"result": {"foo.bar": "bar"}
},
{
"expression": "foo.{bar: bar, baz: baz}",
"result": {"bar": "bar", "baz": "baz"}
},
{
"expression": "foo.{\"bar\": bar, \"baz\": baz}",
"result": {"bar": "bar", "baz": "baz"}
},
{
"expression": "{\"baz\": baz, \"qux\\\"\": \"qux\\\"\"}",
"result": {"baz": 2, "qux\"": 3}
},
{
"expression": "foo.{bar:bar,baz:baz}",
"result": {"bar": "bar", "baz": "baz"}
},
{
"expression": "foo.{bar: bar,qux: qux}",
"result": {"bar": "bar", "qux": "qux"}
},
{
"expression": "foo.{bar: bar, noexist: noexist}",
"result": {"bar": "bar", "noexist": null}
},
{
"expression": "foo.{noexist: noexist, alsonoexist: alsonoexist}",
"result": {"noexist": null, "alsonoexist": null}
},
{
"expression": "foo.badkey.{nokey: nokey, alsonokey: alsonokey}",
"result": null
},
{
"expression": "foo.nested.*.{a: a,b: b}",
"result": [{"a": "first", "b": "second"},
{"a": "first", "b": "second"},
{"a": "first", "b": "second"}]
},
{
"expression": "foo.nested.three.{a: a, cinner: c.inner}",
"result": {"a": "first", "cinner": "third"}
},
{
"expression": "foo.nested.three.{a: a, c: c.inner.bad.key}",
"result": {"a": "first", "c": null}
},
{
"expression": "foo.{a: nested.one.a, b: nested.two.b}",
"result": {"a": "first", "b": "second"}
},
{
"expression": "{bar: bar, baz: baz}",
"result": {"bar": 1, "baz": 2}
},
{
"expression": "{bar: bar}",
"result": {"bar": 1}
},
{
"expression": "{otherkey: bar}",
"result": {"otherkey": 1}
},
{
"expression": "{no: no, exist: exist}",
"result": {"no": null, "exist": null}
},
{
"expression": "foo.[bar]",
"result": ["bar"]
},
{
"expression": "foo.[bar,baz]",
"result": ["bar", "baz"]
},
{
"expression": "foo.[bar,qux]",
"result": ["bar", "qux"]
},
{
"expression": "foo.[bar,noexist]",
"result": ["bar", null]
},
{
"expression": "foo.[noexist,alsonoexist]",
"result": [null, null]
}
]
}, {
"given": {
"foo": {"bar": 1, "baz": [2, 3, 4]}
},
"cases": [
{
"expression": "foo.{bar:bar,baz:baz}",
"result": {"bar": 1, "baz": [2, 3, 4]}
},
{
"expression": "foo.[bar,baz[0]]",
"result": [1, 2]
},
{
"expression": "foo.[bar,baz[1]]",
"result": [1, 3]
},
{
"expression": "foo.[bar,baz[2]]",
"result": [1, 4]
},
{
"expression": "foo.[bar,baz[3]]",
"result": [1, null]
},
{
"expression": "foo.[bar[0],baz[3]]",
"result": [null, null]
}
]
}, {
"given": {
"foo": {"bar": 1, "baz": 2}
},
"cases": [
{
"expression": "foo.{bar: bar, baz: baz}",
"result": {"bar": 1, "baz": 2}
},
{
"expression": "foo.[bar,baz]",
"result": [1, 2]
}
]
}, {
"given": {
"foo": {
"bar": {"baz": [{"common": "first", "one": 1},
{"common": "second", "two": 2}]},
"ignoreme": 1,
"includeme": true
}
},
"cases": [
{
"expression": "foo.{bar: bar.baz[1],includeme: includeme}",
"result": {"bar": {"common": "second", "two": 2}, "includeme": true}
},
{
"expression": "foo.{\"bar.baz.two\": bar.baz[1].two, includeme: includeme}",
"result": {"bar.baz.two": 2, "includeme": true}
},
{
"expression": "foo.[includeme, bar.baz[*].common]",
"result": [true, ["first", "second"]]
},
{
"expression": "foo.[includeme, bar.baz[*].none]",
"result": [true, []]
},
{
"expression": "foo.[includeme, bar.baz[].common]",
"result": [true, ["first", "second"]]
}
]
}, {
"given": {
"reservations": [{
"instances": [
{"id": "id1",
"name": "first"},
{"id": "id2",
"name": "second"}
]}, {
"instances": [
{"id": "id3",
"name": "third"},
{"id": "id4",
"name": "fourth"}
]}
]},
"cases": [
{
"expression": "reservations[*].instances[*].{id: id, name: name}",
"result": [[{"id": "id1", "name": "first"}, {"id": "id2", "name": "second"}],
[{"id": "id3", "name": "third"}, {"id": "id4", "name": "fourth"}]]
},
{
"expression": "reservations[].instances[].{id: id, name: name}",
"result": [{"id": "id1", "name": "first"},
{"id": "id2", "name": "second"},
{"id": "id3", "name": "third"},
{"id": "id4", "name": "fourth"}]
},
{
"expression": "reservations[].instances[].[id, name]",
"result": [["id1", "first"],
["id2", "second"],
["id3", "third"],
["id4", "fourth"]]
}
]
},
{
"given": {
"foo": [{
"bar": [
{
"qux": 2,
"baz": 1
},
{
"qux": 4,
"baz": 3
}
]
},
{
"bar": [
{
"qux": 6,
"baz": 5
},
{
"qux": 8,
"baz": 7
}
]
}
]
},
"cases": [
{
"expression": "foo",
"result": [{"bar": [{"qux": 2, "baz": 1}, {"qux": 4, "baz": 3}]},
{"bar": [{"qux": 6, "baz": 5}, {"qux": 8, "baz": 7}]}]
},
{
"expression": "foo[]",
"result": [{"bar": [{"qux": 2, "baz": 1}, {"qux": 4, "baz": 3}]},
{"bar": [{"qux": 6, "baz": 5}, {"qux": 8, "baz": 7}]}]
},
{
"expression": "foo[].bar",
"result": [[{"qux": 2, "baz": 1}, {"qux": 4, "baz": 3}],
[{"qux": 6, "baz": 5}, {"qux": 8, "baz": 7}]]
},
{
"expression": "foo[].bar[]",
"result": [{"qux": 2, "baz": 1}, {"qux": 4, "baz": 3},
{"qux": 6, "baz": 5}, {"qux": 8, "baz": 7}]
},
{
"expression": "foo[].bar[].[baz, qux]",
"result": [[1, 2], [3, 4], [5, 6], [7, 8]]
},
{
"expression": "foo[].bar[].[baz]",
"result": [[1], [3], [5], [7]]
},
{
"expression": "foo[].bar[].[baz, qux][]",
"result": [1, 2, 3, 4, 5, 6, 7, 8]
}
]
},
{
"given": {
"foo": {
"baz": [
{
"bar": "abc"
}, {
"bar": "def"
}
],
"qux": ["zero"]
}
},
"cases": [
{
"expression": "foo.[baz[*].bar, qux[0]]",
"result": [["abc", "def"], "zero"]
}
]
},
{
"given": {
"foo": {
"baz": [
{
"bar": "a",
"bam": "b",
"boo": "c"
}, {
"bar": "d",
"bam": "e",
"boo": "f"
}
],
"qux": ["zero"]
}
},
"cases": [
{
"expression": "foo.[baz[*].[bar, boo], qux[0]]",
"result": [[["a", "c" ], ["d", "f" ]], "zero"]
}
]
},
{
"given": {
"foo": {
"baz": [
{
"bar": "a",
"bam": "b",
"boo": "c"
}, {
"bar": "d",
"bam": "e",
"boo": "f"
}
],
"qux": ["zero"]
}
},
"cases": [
{
"expression": "foo.[baz[*].not_there || baz[*].bar, qux[0]]",
"result": [["a", "d"], "zero"]
}
]
},
{
"given": {"type": "object"},
"cases": [
{
"comment": "Nested multiselect",
"expression": "[[*],*]",
"result": [null, ["object"]]
}
]
},
{
"given": [],
"cases": [
{
"comment": "Nested multiselect",
"expression": "[[*]]",
"result": [[]]
}
]
}
]

View File

@ -0,0 +1,59 @@
[{
"given":
{"outer": {"foo": "foo", "bar": "bar", "baz": "baz"}},
"cases": [
{
"expression": "outer.foo || outer.bar",
"result": "foo"
},
{
"expression": "outer.foo||outer.bar",
"result": "foo"
},
{
"expression": "outer.bar || outer.baz",
"result": "bar"
},
{
"expression": "outer.bar||outer.baz",
"result": "bar"
},
{
"expression": "outer.bad || outer.foo",
"result": "foo"
},
{
"expression": "outer.bad||outer.foo",
"result": "foo"
},
{
"expression": "outer.foo || outer.bad",
"result": "foo"
},
{
"expression": "outer.foo||outer.bad",
"result": "foo"
},
{
"expression": "outer.bad || outer.alsobad",
"result": null
},
{
"expression": "outer.bad||outer.alsobad",
"result": null
}
]
}, {
"given":
{"outer": {"foo": "foo", "bool": false, "empty_list": [], "empty_string": ""}},
"cases": [
{
"expression": "outer.empty_string || outer.foo",
"result": "foo"
},
{
"expression": "outer.nokey || outer.bool || outer.empty_list || outer.empty_string || outer.foo",
"result": "foo"
}
]
}]

View File

@ -0,0 +1,131 @@
[{
"given": {
"foo": {
"bar": {
"baz": "subkey"
},
"other": {
"baz": "subkey"
},
"other2": {
"baz": "subkey"
},
"other3": {
"notbaz": ["a", "b", "c"]
},
"other4": {
"notbaz": ["a", "b", "c"]
}
}
},
"cases": [
{
"expression": "foo.*.baz | [0]",
"result": "subkey"
},
{
"expression": "foo.*.baz | [1]",
"result": "subkey"
},
{
"expression": "foo.*.baz | [2]",
"result": "subkey"
},
{
"expression": "foo.bar.* | [0]",
"result": "subkey"
},
{
"expression": "foo.*.notbaz | [*]",
"result": [["a", "b", "c"], ["a", "b", "c"]]
},
{
"expression": "{\"a\": foo.bar, \"b\": foo.other} | *.baz",
"result": ["subkey", "subkey"]
}
]
}, {
"given": {
"foo": {
"bar": {
"baz": "one"
},
"other": {
"baz": "two"
},
"other2": {
"baz": "three"
},
"other3": {
"notbaz": ["a", "b", "c"]
},
"other4": {
"notbaz": ["d", "e", "f"]
}
}
},
"cases": [
{
"expression": "foo | bar",
"result": {"baz": "one"}
},
{
"expression": "foo | bar | baz",
"result": "one"
},
{
"expression": "foo|bar| baz",
"result": "one"
},
{
"expression": "not_there | [0]",
"result": null
},
{
"expression": "not_there | [0]",
"result": null
},
{
"expression": "[foo.bar, foo.other] | [0]",
"result": {"baz": "one"}
},
{
"expression": "{\"a\": foo.bar, \"b\": foo.other} | a",
"result": {"baz": "one"}
},
{
"expression": "{\"a\": foo.bar, \"b\": foo.other} | b",
"result": {"baz": "two"}
},
{
"expression": "foo.bam || foo.bar | baz",
"result": "one"
},
{
"expression": "foo | not_there || bar",
"result": {"baz": "one"}
}
]
}, {
"given": {
"foo": [{
"bar": [{
"baz": "one"
}, {
"baz": "two"
}]
}, {
"bar": [{
"baz": "three"
}, {
"baz": "four"
}]
}]
},
"cases": [
{
"expression": "foo[*].bar[*] | [0][0]",
"result": {"baz": "one"}
}
]
}]

View File

@ -0,0 +1,183 @@
[{
"given": {
"foo": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
"bar": {
"baz": 1
}
},
"cases": [
{
"expression": "bar[0:10]",
"result": null
},
{
"expression": "foo[0:10:1]",
"result": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
},
{
"expression": "foo[0:10]",
"result": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
},
{
"expression": "foo[0:10:]",
"result": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
},
{
"expression": "foo[0::1]",
"result": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
},
{
"expression": "foo[0::]",
"result": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
},
{
"expression": "foo[0:]",
"result": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
},
{
"expression": "foo[:10:1]",
"result": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
},
{
"expression": "foo[::1]",
"result": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
},
{
"expression": "foo[:10:]",
"result": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
},
{
"expression": "foo[::]",
"result": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
},
{
"expression": "foo[:]",
"result": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
},
{
"expression": "foo[1:9]",
"result": [1, 2, 3, 4, 5, 6, 7, 8]
},
{
"expression": "foo[0:10:2]",
"result": [0, 2, 4, 6, 8]
},
{
"expression": "foo[5:]",
"result": [5, 6, 7, 8, 9]
},
{
"expression": "foo[5::2]",
"result": [5, 7, 9]
},
{
"expression": "foo[::2]",
"result": [0, 2, 4, 6, 8]
},
{
"expression": "foo[::-1]",
"result": [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
},
{
"expression": "foo[1::2]",
"result": [1, 3, 5, 7, 9]
},
{
"expression": "foo[10:0:-1]",
"result": [9, 8, 7, 6, 5, 4, 3, 2, 1]
},
{
"expression": "foo[10:5:-1]",
"result": [9, 8, 7, 6]
},
{
"expression": "foo[8:2:-2]",
"result": [8, 6, 4]
},
{
"expression": "foo[0:20]",
"result": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
},
{
"expression": "foo[10:-20:-1]",
"result": [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
},
{
"expression": "foo[10:-20]",
"result": []
},
{
"expression": "foo[-4:-1]",
"result": [6, 7, 8]
},
{
"expression": "foo[:-5:-1]",
"result": [9, 8, 7, 6]
},
{
"expression": "foo[8:2:0]",
"error": "invalid-value"
},
{
"expression": "foo[8:2:0:1]",
"error": "syntax"
},
{
"expression": "foo[8:2&]",
"error": "syntax"
}
]
}, {
"given": {
"foo": [{"a": 1}, {"a": 2}, {"a": 3}],
"bar": [{"a": {"b": 1}}, {"a": {"b": 2}},
{"a": {"b": 3}}],
"baz": 50
},
"cases": [
{
"expression": "foo[:2].a",
"result": [1, 2]
},
{
"expression": "foo[:2].b",
"result": []
},
{
"expression": "foo[:2].a.b",
"result": []
},
{
"expression": "bar[::-1].a.b",
"result": [3, 2, 1]
},
{
"expression": "bar[:2].a.b",
"result": [1, 2]
},
{
"expression": "baz[:2].a",
"result": null
}
]
}, {
"given": [{"a": 1}, {"a": 2}, {"a": 3}],
"cases": [
{
"expression": "[:]",
"result": [{"a": 1}, {"a": 2}, {"a": 3}]
},
{
"expression": "[:2].a",
"result": [1, 2]
},
{
"expression": "[::-1].a",
"result": [3, 2, 1]
},
{
"expression": "[:2].b",
"result": []
}
]
}]

View File

@ -0,0 +1,598 @@
[{
"comment": "Dot syntax",
"given": {"type": "object"},
"cases": [
{
"expression": "foo.bar",
"result": null
},
{
"expression": "foo.1",
"error": "syntax"
},
{
"expression": "foo.-11",
"error": "syntax"
},
{
"expression": "foo",
"result": null
},
{
"expression": "foo.",
"error": "syntax"
},
{
"expression": "foo.",
"error": "syntax"
},
{
"expression": ".foo",
"error": "syntax"
},
{
"expression": "foo..bar",
"error": "syntax"
},
{
"expression": "foo.bar.",
"error": "syntax"
},
{
"expression": "foo[.]",
"error": "syntax"
}
]
},
{
"comment": "Simple token errors",
"given": {"type": "object"},
"cases": [
{
"expression": ".",
"error": "syntax"
},
{
"expression": ":",
"error": "syntax"
},
{
"expression": ",",
"error": "syntax"
},
{
"expression": "]",
"error": "syntax"
},
{
"expression": "[",
"error": "syntax"
},
{
"expression": "}",
"error": "syntax"
},
{
"expression": "{",
"error": "syntax"
},
{
"expression": ")",
"error": "syntax"
},
{
"expression": "(",
"error": "syntax"
},
{
"expression": "a[",
"error": "syntax"
},
{
"expression": "a]",
"error": "syntax"
},
{
"expression": "a][",
"error": "syntax"
}
]
},
{
"comment": "Wildcard syntax",
"given": {"type": "object"},
"cases": [
{
"expression": "*",
"result": ["object"]
},
{
"expression": "*.*",
"result": []
},
{
"expression": "*.foo",
"result": []
},
{
"expression": "*[0]",
"result": []
},
{
"expression": ".*",
"error": "syntax"
},
{
"expression": "*foo",
"error": "syntax"
},
{
"expression": "*0",
"error": "syntax"
},
{
"expression": "foo[*]bar",
"error": "syntax"
},
{
"expression": "foo[*]*",
"error": "syntax"
}
]
},
{
"comment": "Flatten syntax",
"given": {"type": "object"},
"cases": [
{
"expression": "[]",
"result": null
}
]
},
{
"comment": "Simple bracket syntax",
"given": {"type": "object"},
"cases": [
{
"expression": "[0]",
"result": null
},
{
"expression": "[*]",
"result": null
},
{
"expression": "*.[0]",
"error": "syntax"
},
{
"expression": "*.[\"0\"]",
"result": [[null]]
},
{
"expression": "[*].bar",
"result": null
},
{
"expression": "[*][0]",
"result": null
},
{
"expression": "foo[#]",
"error": "syntax"
}
]
},
{
"comment": "Multi-select list syntax",
"given": {"type": "object"},
"cases": [
{
"expression": "foo[0]",
"result": null
},
{
"comment": "Valid multi-select of a list",
"expression": "foo[0, 1]",
"error": "syntax"
},
{
"expression": "foo.[0]",
"error": "syntax"
},
{
"expression": "foo.[*]",
"result": null
},
{
"comment": "Multi-select of a list with trailing comma",
"expression": "foo[0, ]",
"error": "syntax"
},
{
"comment": "Multi-select of a list with trailing comma and no close",
"expression": "foo[0,",
"error": "syntax"
},
{
"comment": "Multi-select of a list with trailing comma and no close",
"expression": "foo.[a",
"error": "syntax"
},
{
"comment": "Multi-select of a list with extra comma",
"expression": "foo[0,, 1]",
"error": "syntax"
},
{
"comment": "Multi-select of a list using an identifier index",
"expression": "foo[abc]",
"error": "syntax"
},
{
"comment": "Multi-select of a list using identifier indices",
"expression": "foo[abc, def]",
"error": "syntax"
},
{
"comment": "Multi-select of a list using an identifier index",
"expression": "foo[abc, 1]",
"error": "syntax"
},
{
"comment": "Multi-select of a list using an identifier index with trailing comma",
"expression": "foo[abc, ]",
"error": "syntax"
},
{
"comment": "Valid multi-select of a hash using an identifier index",
"expression": "foo.[abc]",
"result": null
},
{
"comment": "Valid multi-select of a hash",
"expression": "foo.[abc, def]",
"result": null
},
{
"comment": "Multi-select of a hash using a numeric index",
"expression": "foo.[abc, 1]",
"error": "syntax"
},
{
"comment": "Multi-select of a hash with a trailing comma",
"expression": "foo.[abc, ]",
"error": "syntax"
},
{
"comment": "Multi-select of a hash with extra commas",
"expression": "foo.[abc,, def]",
"error": "syntax"
},
{
"comment": "Multi-select of a hash using number indices",
"expression": "foo.[0, 1]",
"error": "syntax"
}
]
},
{
"comment": "Multi-select hash syntax",
"given": {"type": "object"},
"cases": [
{
"comment": "No key or value",
"expression": "a{}",
"error": "syntax"
},
{
"comment": "No closing token",
"expression": "a{",
"error": "syntax"
},
{
"comment": "Not a key value pair",
"expression": "a{foo}",
"error": "syntax"
},
{
"comment": "Missing value and closing character",
"expression": "a{foo:",
"error": "syntax"
},
{
"comment": "Missing closing character",
"expression": "a{foo: 0",
"error": "syntax"
},
{
"comment": "Missing value",
"expression": "a{foo:}",
"error": "syntax"
},
{
"comment": "Trailing comma and no closing character",
"expression": "a{foo: 0, ",
"error": "syntax"
},
{
"comment": "Missing value with trailing comma",
"expression": "a{foo: ,}",
"error": "syntax"
},
{
"comment": "Accessing Array using an identifier",
"expression": "a{foo: bar}",
"error": "syntax"
},
{
"expression": "a{foo: 0}",
"error": "syntax"
},
{
"comment": "Missing key-value pair",
"expression": "a.{}",
"error": "syntax"
},
{
"comment": "Not a key-value pair",
"expression": "a.{foo}",
"error": "syntax"
},
{
"comment": "Missing value",
"expression": "a.{foo:}",
"error": "syntax"
},
{
"comment": "Missing value with trailing comma",
"expression": "a.{foo: ,}",
"error": "syntax"
},
{
"comment": "Valid multi-select hash extraction",
"expression": "a.{foo: bar}",
"result": null
},
{
"comment": "Valid multi-select hash extraction",
"expression": "a.{foo: bar, baz: bam}",
"result": null
},
{
"comment": "Trailing comma",
"expression": "a.{foo: bar, }",
"error": "syntax"
},
{
"comment": "Missing key in second key-value pair",
"expression": "a.{foo: bar, baz}",
"error": "syntax"
},
{
"comment": "Missing value in second key-value pair",
"expression": "a.{foo: bar, baz:}",
"error": "syntax"
},
{
"comment": "Trailing comma",
"expression": "a.{foo: bar, baz: bam, }",
"error": "syntax"
},
{
"comment": "Nested multi select",
"expression": "{\"\\\\\":{\" \":*}}",
"result": {"\\": {" ": ["object"]}}
}
]
},
{
"comment": "Or expressions",
"given": {"type": "object"},
"cases": [
{
"expression": "foo || bar",
"result": null
},
{
"expression": "foo ||",
"error": "syntax"
},
{
"expression": "foo.|| bar",
"error": "syntax"
},
{
"expression": " || foo",
"error": "syntax"
},
{
"expression": "foo || || foo",
"error": "syntax"
},
{
"expression": "foo.[a || b]",
"result": null
},
{
"expression": "foo.[a ||]",
"error": "syntax"
},
{
"expression": "\"foo",
"error": "syntax"
}
]
},
{
"comment": "Filter expressions",
"given": {"type": "object"},
"cases": [
{
"expression": "foo[?bar==`\"baz\"`]",
"result": null
},
{
"expression": "foo[? bar == `\"baz\"` ]",
"result": null
},
{
"expression": "foo[ ?bar==`\"baz\"`]",
"error": "syntax"
},
{
"expression": "foo[?bar==]",
"error": "syntax"
},
{
"expression": "foo[?==]",
"error": "syntax"
},
{
"expression": "foo[?==bar]",
"error": "syntax"
},
{
"expression": "foo[?bar==baz?]",
"error": "syntax"
},
{
"expression": "foo[?a.b.c==d.e.f]",
"result": null
},
{
"expression": "foo[?bar==`[0, 1, 2]`]",
"result": null
},
{
"expression": "foo[?bar==`[\"a\", \"b\", \"c\"]`]",
"result": null
},
{
"comment": "Literal char not escaped",
"expression": "foo[?bar==`[\"foo`bar\"]`]",
"error": "syntax"
},
{
"comment": "Literal char escaped",
"expression": "foo[?bar==`[\"foo\\`bar\"]`]",
"result": null
},
{
"comment": "Unknown comparator",
"expression": "foo[?bar<>baz]",
"error": "syntax"
},
{
"comment": "Unknown comparator",
"expression": "foo[?bar^baz]",
"error": "syntax"
},
{
"expression": "foo[bar==baz]",
"error": "syntax"
},
{
"comment": "Quoted identifier in filter expression no spaces",
"expression": "[?\"\\\\\">`\"foo\"`]",
"result": null
},
{
"comment": "Quoted identifier in filter expression with spaces",
"expression": "[?\"\\\\\" > `\"foo\"`]",
"result": null
}
]
},
{
"comment": "Filter expression errors",
"given": {"type": "object"},
"cases": [
{
"expression": "bar.`\"anything\"`",
"error": "syntax"
},
{
"expression": "bar.baz.noexists.`\"literal\"`",
"error": "syntax"
},
{
"comment": "Literal wildcard projection",
"expression": "foo[*].`\"literal\"`",
"error": "syntax"
},
{
"expression": "foo[*].name.`\"literal\"`",
"error": "syntax"
},
{
"expression": "foo[].name.`\"literal\"`",
"error": "syntax"
},
{
"expression": "foo[].name.`\"literal\"`.`\"subliteral\"`",
"error": "syntax"
},
{
"comment": "Projecting a literal onto an empty list",
"expression": "foo[*].name.noexist.`\"literal\"`",
"error": "syntax"
},
{
"expression": "foo[].name.noexist.`\"literal\"`",
"error": "syntax"
},
{
"expression": "twolen[*].`\"foo\"`",
"error": "syntax"
},
{
"comment": "Two level projection of a literal",
"expression": "twolen[*].threelen[*].`\"bar\"`",
"error": "syntax"
},
{
"comment": "Two level flattened projection of a literal",
"expression": "twolen[].threelen[].`\"bar\"`",
"error": "syntax"
}
]
},
{
"comment": "Identifiers",
"given": {"type": "object"},
"cases": [
{
"expression": "foo",
"result": null
},
{
"expression": "\"foo\"",
"result": null
},
{
"expression": "\"\\\\\"",
"result": null
}
]
},
{
"comment": "Combined syntax",
"given": [],
"cases": [
{
"expression": "*||*|*|*",
"result": null
},
{
"expression": "*[]||[*]",
"result": []
},
{
"expression": "[*.*]",
"result": [null]
}
]
}
]

View File

@ -0,0 +1,38 @@
[
{
"given": {"foo": [{"✓": "✓"}, {"✓": "✗"}]},
"cases": [
{
"expression": "foo[].\"✓\"",
"result": ["✓", "✗"]
}
]
},
{
"given": {"☯": true},
"cases": [
{
"expression": "\"☯\"",
"result": true
}
]
},
{
"given": {"♪♫•*¨*•.¸¸❤¸¸.•*¨*•♫♪": true},
"cases": [
{
"expression": "\"♪♫•*¨*•.¸¸❤¸¸.•*¨*•♫♪\"",
"result": true
}
]
},
{
"given": {"☃": true},
"cases": [
{
"expression": "\"☃\"",
"result": true
}
]
}
]

View File

@ -0,0 +1,460 @@
[{
"given": {
"foo": {
"bar": {
"baz": "val"
},
"other": {
"baz": "val"
},
"other2": {
"baz": "val"
},
"other3": {
"notbaz": ["a", "b", "c"]
},
"other4": {
"notbaz": ["a", "b", "c"]
},
"other5": {
"other": {
"a": 1,
"b": 1,
"c": 1
}
}
}
},
"cases": [
{
"expression": "foo.*.baz",
"result": ["val", "val", "val"]
},
{
"expression": "foo.bar.*",
"result": ["val"]
},
{
"expression": "foo.*.notbaz",
"result": [["a", "b", "c"], ["a", "b", "c"]]
},
{
"expression": "foo.*.notbaz[0]",
"result": ["a", "a"]
},
{
"expression": "foo.*.notbaz[-1]",
"result": ["c", "c"]
}
]
}, {
"given": {
"foo": {
"first-1": {
"second-1": "val"
},
"first-2": {
"second-1": "val"
},
"first-3": {
"second-1": "val"
}
}
},
"cases": [
{
"expression": "foo.*",
"result": [{"second-1": "val"}, {"second-1": "val"},
{"second-1": "val"}]
},
{
"expression": "foo.*.*",
"result": [["val"], ["val"], ["val"]]
},
{
"expression": "foo.*.*.*",
"result": [[], [], []]
},
{
"expression": "foo.*.*.*.*",
"result": [[], [], []]
}
]
}, {
"given": {
"foo": {
"bar": "one"
},
"other": {
"bar": "one"
},
"nomatch": {
"notbar": "three"
}
},
"cases": [
{
"expression": "*.bar",
"result": ["one", "one"]
}
]
}, {
"given": {
"top1": {
"sub1": {"foo": "one"}
},
"top2": {
"sub1": {"foo": "one"}
}
},
"cases": [
{
"expression": "*",
"result": [{"sub1": {"foo": "one"}},
{"sub1": {"foo": "one"}}]
},
{
"expression": "*.sub1",
"result": [{"foo": "one"},
{"foo": "one"}]
},
{
"expression": "*.*",
"result": [[{"foo": "one"}],
[{"foo": "one"}]]
},
{
"expression": "*.*.foo[]",
"result": ["one", "one"]
},
{
"expression": "*.sub1.foo",
"result": ["one", "one"]
}
]
},
{
"given":
{"foo": [{"bar": "one"}, {"bar": "two"}, {"bar": "three"}, {"notbar": "four"}]},
"cases": [
{
"expression": "foo[*].bar",
"result": ["one", "two", "three"]
},
{
"expression": "foo[*].notbar",
"result": ["four"]
}
]
},
{
"given":
[{"bar": "one"}, {"bar": "two"}, {"bar": "three"}, {"notbar": "four"}],
"cases": [
{
"expression": "[*]",
"result": [{"bar": "one"}, {"bar": "two"}, {"bar": "three"}, {"notbar": "four"}]
},
{
"expression": "[*].bar",
"result": ["one", "two", "three"]
},
{
"expression": "[*].notbar",
"result": ["four"]
}
]
},
{
"given": {
"foo": {
"bar": [
{"baz": ["one", "two", "three"]},
{"baz": ["four", "five", "six"]},
{"baz": ["seven", "eight", "nine"]}
]
}
},
"cases": [
{
"expression": "foo.bar[*].baz",
"result": [["one", "two", "three"], ["four", "five", "six"], ["seven", "eight", "nine"]]
},
{
"expression": "foo.bar[*].baz[0]",
"result": ["one", "four", "seven"]
},
{
"expression": "foo.bar[*].baz[1]",
"result": ["two", "five", "eight"]
},
{
"expression": "foo.bar[*].baz[2]",
"result": ["three", "six", "nine"]
},
{
"expression": "foo.bar[*].baz[3]",
"result": []
}
]
},
{
"given": {
"foo": {
"bar": [["one", "two"], ["three", "four"]]
}
},
"cases": [
{
"expression": "foo.bar[*]",
"result": [["one", "two"], ["three", "four"]]
},
{
"expression": "foo.bar[0]",
"result": ["one", "two"]
},
{
"expression": "foo.bar[0][0]",
"result": "one"
},
{
"expression": "foo.bar[0][0][0]",
"result": null
},
{
"expression": "foo.bar[0][0][0][0]",
"result": null
},
{
"expression": "foo[0][0]",
"result": null
}
]
},
{
"given": {
"foo": [
{"bar": [{"kind": "basic"}, {"kind": "intermediate"}]},
{"bar": [{"kind": "advanced"}, {"kind": "expert"}]},
{"bar": "string"}
]
},
"cases": [
{
"expression": "foo[*].bar[*].kind",
"result": [["basic", "intermediate"], ["advanced", "expert"]]
},
{
"expression": "foo[*].bar[0].kind",
"result": ["basic", "advanced"]
}
]
},
{
"given": {
"foo": [
{"bar": {"kind": "basic"}},
{"bar": {"kind": "intermediate"}},
{"bar": {"kind": "advanced"}},
{"bar": {"kind": "expert"}},
{"bar": "string"}
]
},
"cases": [
{
"expression": "foo[*].bar.kind",
"result": ["basic", "intermediate", "advanced", "expert"]
}
]
},
{
"given": {
"foo": [{"bar": ["one", "two"]}, {"bar": ["three", "four"]}, {"bar": ["five"]}]
},
"cases": [
{
"expression": "foo[*].bar[0]",
"result": ["one", "three", "five"]
},
{
"expression": "foo[*].bar[1]",
"result": ["two", "four"]
},
{
"expression": "foo[*].bar[2]",
"result": []
}
]
},
{
"given": {
"foo": [{"bar": []}, {"bar": []}, {"bar": []}]
},
"cases": [
{
"expression": "foo[*].bar[0]",
"result": []
}
]
},
{
"given": {
"foo": [["one", "two"], ["three", "four"], ["five"]]
},
"cases": [
{
"expression": "foo[*][0]",
"result": ["one", "three", "five"]
},
{
"expression": "foo[*][1]",
"result": ["two", "four"]
}
]
},
{
"given": {
"foo": [
[
["one", "two"], ["three", "four"]
], [
["five", "six"], ["seven", "eight"]
], [
["nine"], ["ten"]
]
]
},
"cases": [
{
"expression": "foo[*][0]",
"result": [["one", "two"], ["five", "six"], ["nine"]]
},
{
"expression": "foo[*][1]",
"result": [["three", "four"], ["seven", "eight"], ["ten"]]
},
{
"expression": "foo[*][0][0]",
"result": ["one", "five", "nine"]
},
{
"expression": "foo[*][1][0]",
"result": ["three", "seven", "ten"]
},
{
"expression": "foo[*][0][1]",
"result": ["two", "six"]
},
{
"expression": "foo[*][1][1]",
"result": ["four", "eight"]
},
{
"expression": "foo[*][2]",
"result": []
},
{
"expression": "foo[*][2][2]",
"result": []
},
{
"expression": "bar[*]",
"result": null
},
{
"expression": "bar[*].baz[*]",
"result": null
}
]
},
{
"given": {
"string": "string",
"hash": {"foo": "bar", "bar": "baz"},
"number": 23,
"nullvalue": null
},
"cases": [
{
"expression": "string[*]",
"result": null
},
{
"expression": "hash[*]",
"result": null
},
{
"expression": "number[*]",
"result": null
},
{
"expression": "nullvalue[*]",
"result": null
},
{
"expression": "string[*].foo",
"result": null
},
{
"expression": "hash[*].foo",
"result": null
},
{
"expression": "number[*].foo",
"result": null
},
{
"expression": "nullvalue[*].foo",
"result": null
},
{
"expression": "nullvalue[*].foo[*].bar",
"result": null
}
]
},
{
"given": {
"string": "string",
"hash": {"foo": "val", "bar": "val"},
"number": 23,
"array": [1, 2, 3],
"nullvalue": null
},
"cases": [
{
"expression": "string.*",
"result": null
},
{
"expression": "hash.*",
"result": ["val", "val"]
},
{
"expression": "number.*",
"result": null
},
{
"expression": "array.*",
"result": null
},
{
"expression": "nullvalue.*",
"result": null
}
]
},
{
"given": {
"a": [0, 1, 2],
"b": [0, 1, 2]
},
"cases": [
{
"expression": "*[0]",
"result": [0, 0]
}
]
}
]

View File

@ -0,0 +1,122 @@
package jmespath
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
)
type TestSuite struct {
Given interface{}
TestCases []TestCase `json:"cases"`
Comment string
}
type TestCase struct {
Comment string
Expression string
Result interface{}
Error string
}
var whiteListed = []string{
"compliance/basic.json",
"compliance/current.json",
"compliance/escape.json",
"compliance/filters.json",
"compliance/functions.json",
"compliance/identifiers.json",
"compliance/indices.json",
"compliance/literal.json",
"compliance/multiselect.json",
"compliance/ormatch.json",
"compliance/pipe.json",
"compliance/slice.json",
"compliance/syntax.json",
"compliance/unicode.json",
"compliance/wildcard.json",
}
func allowed(path string) bool {
for _, el := range whiteListed {
if el == path {
return true
}
}
return false
}
func TestCompliance(t *testing.T) {
assert := assert.New(t)
var complianceFiles []string
err := filepath.Walk("compliance", func(path string, _ os.FileInfo, _ error) error {
//if strings.HasSuffix(path, ".json") {
if allowed(path) {
complianceFiles = append(complianceFiles, path)
}
return nil
})
if assert.Nil(err) {
for _, filename := range complianceFiles {
runComplianceTest(assert, filename)
}
}
}
func runComplianceTest(assert *assert.Assertions, filename string) {
var testSuites []TestSuite
data, err := ioutil.ReadFile(filename)
if assert.Nil(err) {
err := json.Unmarshal(data, &testSuites)
if assert.Nil(err) {
for _, testsuite := range testSuites {
runTestSuite(assert, testsuite, filename)
}
}
}
}
func runTestSuite(assert *assert.Assertions, testsuite TestSuite, filename string) {
for _, testcase := range testsuite.TestCases {
if testcase.Error != "" {
// This is a test case that verifies we error out properly.
runSyntaxTestCase(assert, testsuite.Given, testcase, filename)
} else {
runTestCase(assert, testsuite.Given, testcase, filename)
}
}
}
func runSyntaxTestCase(assert *assert.Assertions, given interface{}, testcase TestCase, filename string) {
// Anything with an .Error means that we expect that JMESPath should return
// an error when we try to evaluate the expression.
_, err := Search(testcase.Expression, given)
assert.NotNil(err, fmt.Sprintf("Expression: %s", testcase.Expression))
}
func runTestCase(assert *assert.Assertions, given interface{}, testcase TestCase, filename string) {
lexer := NewLexer()
var err error
_, err = lexer.tokenize(testcase.Expression)
if err != nil {
errMsg := fmt.Sprintf("(%s) Could not lex expression: %s -- %s", filename, testcase.Expression, err.Error())
assert.Fail(errMsg)
return
}
parser := NewParser()
_, err = parser.Parse(testcase.Expression)
if err != nil {
errMsg := fmt.Sprintf("(%s) Could not parse expression: %s -- %s", filename, testcase.Expression, err.Error())
assert.Fail(errMsg)
return
}
actual, err := Search(testcase.Expression, given)
if assert.Nil(err, fmt.Sprintf("Expression: %s", testcase.Expression)) {
assert.Equal(testcase.Result, actual, fmt.Sprintf("Expression: %s", testcase.Expression))
}
}

View File

@ -0,0 +1,815 @@
package jmespath
import (
"encoding/json"
"errors"
"fmt"
"math"
"sort"
"strconv"
"strings"
)
type jpFunction func(arguments []interface{}) (interface{}, error)
type jpType string
const (
jpUnknown jpType = "unknown"
jpNumber jpType = "number"
jpString jpType = "string"
jpArray jpType = "array"
jpObject jpType = "object"
jpArrayNumber jpType = "array[number]"
jpArrayString jpType = "array[string]"
jpExpref jpType = "expref"
jpAny jpType = "any"
)
type functionEntry struct {
name string
arguments []argSpec
handler jpFunction
hasExpRef bool
}
type argSpec struct {
types []jpType
variadic bool
}
type byExprString struct {
intr *treeInterpreter
node ASTNode
items []interface{}
hasError bool
}
func (a *byExprString) Len() int {
return len(a.items)
}
func (a *byExprString) Swap(i, j int) {
a.items[i], a.items[j] = a.items[j], a.items[i]
}
func (a *byExprString) Less(i, j int) bool {
first, err := a.intr.Execute(a.node, a.items[i])
if err != nil {
a.hasError = true
// Return a dummy value.
return true
}
ith, ok := first.(string)
if !ok {
a.hasError = true
return true
}
second, err := a.intr.Execute(a.node, a.items[j])
if err != nil {
a.hasError = true
// Return a dummy value.
return true
}
jth, ok := second.(string)
if !ok {
a.hasError = true
return true
}
return ith < jth
}
type byExprFloat struct {
intr *treeInterpreter
node ASTNode
items []interface{}
hasError bool
}
func (a *byExprFloat) Len() int {
return len(a.items)
}
func (a *byExprFloat) Swap(i, j int) {
a.items[i], a.items[j] = a.items[j], a.items[i]
}
func (a *byExprFloat) Less(i, j int) bool {
first, err := a.intr.Execute(a.node, a.items[i])
if err != nil {
a.hasError = true
// Return a dummy value.
return true
}
ith, ok := first.(float64)
if !ok {
a.hasError = true
return true
}
second, err := a.intr.Execute(a.node, a.items[j])
if err != nil {
a.hasError = true
// Return a dummy value.
return true
}
jth, ok := second.(float64)
if !ok {
a.hasError = true
return true
}
return ith < jth
}
type functionCaller struct {
functionTable map[string]functionEntry
}
func newFunctionCaller() *functionCaller {
caller := &functionCaller{}
caller.functionTable = map[string]functionEntry{
"length": functionEntry{
name: "length",
arguments: []argSpec{
argSpec{types: []jpType{jpString, jpArray, jpObject}},
},
handler: jpfLength,
},
"starts_with": functionEntry{
name: "starts_with",
arguments: []argSpec{
argSpec{types: []jpType{jpString}},
argSpec{types: []jpType{jpString}},
},
handler: jpfStartsWith,
},
"abs": functionEntry{
name: "abs",
arguments: []argSpec{
argSpec{types: []jpType{jpNumber}},
},
handler: jpfAbs,
},
"avg": functionEntry{
name: "avg",
arguments: []argSpec{
argSpec{types: []jpType{jpArrayNumber}},
},
handler: jpfAvg,
},
"ceil": functionEntry{
name: "ceil",
arguments: []argSpec{
argSpec{types: []jpType{jpNumber}},
},
handler: jpfCeil,
},
"contains": functionEntry{
name: "contains",
arguments: []argSpec{
argSpec{types: []jpType{jpArray, jpString}},
argSpec{types: []jpType{jpAny}},
},
handler: jpfContains,
},
"ends_with": functionEntry{
name: "ends_with",
arguments: []argSpec{
argSpec{types: []jpType{jpString}},
argSpec{types: []jpType{jpString}},
},
handler: jpfEndsWith,
},
"floor": functionEntry{
name: "floor",
arguments: []argSpec{
argSpec{types: []jpType{jpNumber}},
},
handler: jpfFloor,
},
"max": functionEntry{
name: "max",
arguments: []argSpec{
argSpec{types: []jpType{jpArrayNumber, jpArrayString}},
},
handler: jpfMax,
},
"merge": functionEntry{
name: "merge",
arguments: []argSpec{
argSpec{types: []jpType{jpObject}, variadic: true},
},
handler: jpfMerge,
},
"max_by": functionEntry{
name: "max_by",
arguments: []argSpec{
argSpec{types: []jpType{jpArray}},
argSpec{types: []jpType{jpExpref}},
},
handler: jpfMaxBy,
hasExpRef: true,
},
"sum": functionEntry{
name: "sum",
arguments: []argSpec{
argSpec{types: []jpType{jpArrayNumber}},
},
handler: jpfSum,
},
"min": functionEntry{
name: "min",
arguments: []argSpec{
argSpec{types: []jpType{jpArrayNumber, jpArrayString}},
},
handler: jpfMin,
},
"min_by": functionEntry{
name: "min_by",
arguments: []argSpec{
argSpec{types: []jpType{jpArray}},
argSpec{types: []jpType{jpExpref}},
},
handler: jpfMinBy,
hasExpRef: true,
},
"type": functionEntry{
name: "type",
arguments: []argSpec{
argSpec{types: []jpType{jpAny}},
},
handler: jpfType,
},
"keys": functionEntry{
name: "keys",
arguments: []argSpec{
argSpec{types: []jpType{jpObject}},
},
handler: jpfKeys,
},
"values": functionEntry{
name: "values",
arguments: []argSpec{
argSpec{types: []jpType{jpObject}},
},
handler: jpfValues,
},
"sort": functionEntry{
name: "sort",
arguments: []argSpec{
argSpec{types: []jpType{jpArrayString, jpArrayNumber}},
},
handler: jpfSort,
},
"sort_by": functionEntry{
name: "sort_by",
arguments: []argSpec{
argSpec{types: []jpType{jpArray}},
argSpec{types: []jpType{jpExpref}},
},
handler: jpfSortBy,
hasExpRef: true,
},
"join": functionEntry{
name: "join",
arguments: []argSpec{
argSpec{types: []jpType{jpString}},
argSpec{types: []jpType{jpArrayString}},
},
handler: jpfJoin,
},
"reverse": functionEntry{
name: "reverse",
arguments: []argSpec{
argSpec{types: []jpType{jpArray, jpString}},
},
handler: jpfReverse,
},
"to_array": functionEntry{
name: "to_array",
arguments: []argSpec{
argSpec{types: []jpType{jpAny}},
},
handler: jpfToArray,
},
"to_string": functionEntry{
name: "to_string",
arguments: []argSpec{
argSpec{types: []jpType{jpAny}},
},
handler: jpfToString,
},
"to_number": functionEntry{
name: "to_number",
arguments: []argSpec{
argSpec{types: []jpType{jpAny}},
},
handler: jpfToNumber,
},
"not_null": functionEntry{
name: "not_null",
arguments: []argSpec{
argSpec{types: []jpType{jpAny}, variadic: true},
},
handler: jpfNotNull,
},
}
return caller
}
func (e *functionEntry) resolveArgs(arguments []interface{}) ([]interface{}, error) {
if len(e.arguments) == 0 {
return arguments, nil
}
if !e.arguments[len(e.arguments)-1].variadic {
if len(e.arguments) != len(arguments) {
return nil, errors.New("incorrect number of args")
}
for i, spec := range e.arguments {
userArg := arguments[i]
err := spec.typeCheck(userArg)
if err != nil {
return nil, err
}
}
return arguments, nil
}
if len(arguments) < len(e.arguments) {
return nil, errors.New("Invalid arity.")
}
return arguments, nil
}
func (a *argSpec) typeCheck(arg interface{}) error {
for _, t := range a.types {
switch t {
case jpNumber:
if _, ok := arg.(float64); ok {
return nil
}
case jpString:
if _, ok := arg.(string); ok {
return nil
}
case jpArray:
if _, ok := arg.([]interface{}); ok {
return nil
}
case jpObject:
if _, ok := arg.(map[string]interface{}); ok {
return nil
}
case jpArrayNumber:
if _, ok := toArrayNum(arg); ok {
return nil
}
case jpArrayString:
if _, ok := toArrayStr(arg); ok {
return nil
}
case jpAny:
return nil
case jpExpref:
if _, ok := arg.(expRef); ok {
return nil
}
}
}
return fmt.Errorf("Invalid type for: %v, expected: %#v", arg, a.types)
}
func (f *functionCaller) CallFunction(name string, arguments []interface{}, intr *treeInterpreter) (interface{}, error) {
entry, ok := f.functionTable[name]
if !ok {
return nil, errors.New("unknown function: " + name)
}
resolvedArgs, err := entry.resolveArgs(arguments)
if err != nil {
return nil, err
}
if entry.hasExpRef {
var extra []interface{}
extra = append(extra, intr)
resolvedArgs = append(extra, resolvedArgs...)
}
return entry.handler(resolvedArgs)
}
func jpfAbs(arguments []interface{}) (interface{}, error) {
num := arguments[0].(float64)
return math.Abs(num), nil
}
func jpfLength(arguments []interface{}) (interface{}, error) {
arg := arguments[0]
if c, ok := arg.(string); ok {
return float64(len(c)), nil
} else if c, ok := arg.([]interface{}); ok {
return float64(len(c)), nil
} else if c, ok := arg.(map[string]interface{}); ok {
return float64(len(c)), nil
}
return nil, errors.New("could not compute length()")
}
func jpfStartsWith(arguments []interface{}) (interface{}, error) {
search := arguments[0].(string)
prefix := arguments[1].(string)
return strings.HasPrefix(search, prefix), nil
}
func jpfAvg(arguments []interface{}) (interface{}, error) {
// We've already type checked the value so we can safely use
// type assertions.
args := arguments[0].([]interface{})
length := float64(len(args))
numerator := 0.0
for _, n := range args {
numerator += n.(float64)
}
return numerator / length, nil
}
func jpfCeil(arguments []interface{}) (interface{}, error) {
val := arguments[0].(float64)
return math.Ceil(val), nil
}
func jpfContains(arguments []interface{}) (interface{}, error) {
search := arguments[0]
el := arguments[1]
if searchStr, ok := search.(string); ok {
if elStr, ok := el.(string); ok {
return strings.Index(searchStr, elStr) != -1, nil
}
return false, nil
}
// Otherwise this is a generic contains for []interface{}
general := search.([]interface{})
for _, item := range general {
if item == el {
return true, nil
}
}
return false, nil
}
func jpfEndsWith(arguments []interface{}) (interface{}, error) {
search := arguments[0].(string)
suffix := arguments[1].(string)
return strings.HasSuffix(search, suffix), nil
}
func jpfFloor(arguments []interface{}) (interface{}, error) {
val := arguments[0].(float64)
return math.Floor(val), nil
}
func jpfMax(arguments []interface{}) (interface{}, error) {
if items, ok := toArrayNum(arguments[0]); ok {
if len(items) == 0 {
return nil, nil
}
if len(items) == 1 {
return items[0], nil
}
best := items[0]
for _, item := range items[1:] {
if item > best {
best = item
}
}
return best, nil
}
// Otherwise we're dealing with a max() of strings.
items, _ := toArrayStr(arguments[0])
if len(items) == 0 {
return nil, nil
}
if len(items) == 1 {
return items[0], nil
}
best := items[0]
for _, item := range items[1:] {
if item > best {
best = item
}
}
return best, nil
}
func jpfMerge(arguments []interface{}) (interface{}, error) {
final := make(map[string]interface{})
for _, m := range arguments {
mapped := m.(map[string]interface{})
for key, value := range mapped {
final[key] = value
}
}
return final, nil
}
func jpfMaxBy(arguments []interface{}) (interface{}, error) {
intr := arguments[0].(*treeInterpreter)
arr := arguments[1].([]interface{})
exp := arguments[2].(expRef)
node := exp.ref
if len(arr) == 0 {
return nil, nil
} else if len(arr) == 1 {
return arr[0], nil
}
start, err := intr.Execute(node, arr[0])
if err != nil {
return nil, err
}
switch t := start.(type) {
case float64:
bestVal := t
bestItem := arr[0]
for _, item := range arr[1:] {
result, err := intr.Execute(node, item)
if err != nil {
return nil, err
}
current, ok := result.(float64)
if !ok {
return nil, errors.New("invalid type, must be number")
}
if current > bestVal {
bestVal = current
bestItem = item
}
}
return bestItem, nil
case string:
bestVal := t
bestItem := arr[0]
for _, item := range arr[1:] {
result, err := intr.Execute(node, item)
if err != nil {
return nil, err
}
current, ok := result.(string)
if !ok {
return nil, errors.New("invalid type, must be string")
}
if current > bestVal {
bestVal = current
bestItem = item
}
}
return bestItem, nil
default:
return nil, errors.New("invalid type, must be number of string")
}
}
func jpfSum(arguments []interface{}) (interface{}, error) {
items, _ := toArrayNum(arguments[0])
sum := 0.0
for _, item := range items {
sum += item
}
return sum, nil
}
func jpfMin(arguments []interface{}) (interface{}, error) {
if items, ok := toArrayNum(arguments[0]); ok {
if len(items) == 0 {
return nil, nil
}
if len(items) == 1 {
return items[0], nil
}
best := items[0]
for _, item := range items[1:] {
if item < best {
best = item
}
}
return best, nil
}
items, _ := toArrayStr(arguments[0])
if len(items) == 0 {
return nil, nil
}
if len(items) == 1 {
return items[0], nil
}
best := items[0]
for _, item := range items[1:] {
if item < best {
best = item
}
}
return best, nil
}
func jpfMinBy(arguments []interface{}) (interface{}, error) {
intr := arguments[0].(*treeInterpreter)
arr := arguments[1].([]interface{})
exp := arguments[2].(expRef)
node := exp.ref
if len(arr) == 0 {
return nil, nil
} else if len(arr) == 1 {
return arr[0], nil
}
start, err := intr.Execute(node, arr[0])
if err != nil {
return nil, err
}
if t, ok := start.(float64); ok {
bestVal := t
bestItem := arr[0]
for _, item := range arr[1:] {
result, err := intr.Execute(node, item)
if err != nil {
return nil, err
}
current, ok := result.(float64)
if !ok {
return nil, errors.New("invalid type, must be number")
}
if current < bestVal {
bestVal = current
bestItem = item
}
}
return bestItem, nil
} else if t, ok := start.(string); ok {
bestVal := t
bestItem := arr[0]
for _, item := range arr[1:] {
result, err := intr.Execute(node, item)
if err != nil {
return nil, err
}
current, ok := result.(string)
if !ok {
return nil, errors.New("invalid type, must be string")
}
if current < bestVal {
bestVal = current
bestItem = item
}
}
return bestItem, nil
} else {
return nil, errors.New("invalid type, must be number of string")
}
}
func jpfType(arguments []interface{}) (interface{}, error) {
arg := arguments[0]
if _, ok := arg.(float64); ok {
return "number", nil
}
if _, ok := arg.(string); ok {
return "string", nil
}
if _, ok := arg.([]interface{}); ok {
return "array", nil
}
if _, ok := arg.(map[string]interface{}); ok {
return "object", nil
}
if arg == nil {
return "null", nil
}
if arg == true || arg == false {
return "boolean", nil
}
return nil, errors.New("unknown type")
}
func jpfKeys(arguments []interface{}) (interface{}, error) {
arg := arguments[0].(map[string]interface{})
collected := make([]interface{}, 0, len(arg))
for key := range arg {
collected = append(collected, key)
}
return collected, nil
}
func jpfValues(arguments []interface{}) (interface{}, error) {
arg := arguments[0].(map[string]interface{})
collected := make([]interface{}, 0, len(arg))
for _, value := range arg {
collected = append(collected, value)
}
return collected, nil
}
func jpfSort(arguments []interface{}) (interface{}, error) {
if items, ok := toArrayNum(arguments[0]); ok {
d := sort.Float64Slice(items)
sort.Stable(d)
final := make([]interface{}, len(d))
for i, val := range d {
final[i] = val
}
return final, nil
}
// Otherwise we're dealing with sort()'ing strings.
items, _ := toArrayStr(arguments[0])
d := sort.StringSlice(items)
sort.Stable(d)
final := make([]interface{}, len(d))
for i, val := range d {
final[i] = val
}
return final, nil
}
func jpfSortBy(arguments []interface{}) (interface{}, error) {
intr := arguments[0].(*treeInterpreter)
arr := arguments[1].([]interface{})
exp := arguments[2].(expRef)
node := exp.ref
if len(arr) == 0 {
return arr, nil
} else if len(arr) == 1 {
return arr, nil
}
start, err := intr.Execute(node, arr[0])
if err != nil {
return nil, err
}
if _, ok := start.(float64); ok {
sortable := &byExprFloat{intr, node, arr, false}
sort.Stable(sortable)
if sortable.hasError {
return nil, errors.New("error in sort_by comparison")
}
return arr, nil
} else if _, ok := start.(string); ok {
sortable := &byExprString{intr, node, arr, false}
sort.Stable(sortable)
if sortable.hasError {
return nil, errors.New("error in sort_by comparison")
}
return arr, nil
} else {
return nil, errors.New("invalid type, must be number of string")
}
}
func jpfJoin(arguments []interface{}) (interface{}, error) {
sep := arguments[0].(string)
// We can't just do arguments[1].([]string), we have to
// manually convert each item to a string.
arrayStr := []string{}
for _, item := range arguments[1].([]interface{}) {
arrayStr = append(arrayStr, item.(string))
}
return strings.Join(arrayStr, sep), nil
}
func jpfReverse(arguments []interface{}) (interface{}, error) {
if s, ok := arguments[0].(string); ok {
r := []rune(s)
for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r), nil
}
items := arguments[0].([]interface{})
length := len(items)
reversed := make([]interface{}, length)
for i, item := range items {
reversed[length-(i+1)] = item
}
return reversed, nil
}
func jpfToArray(arguments []interface{}) (interface{}, error) {
if _, ok := arguments[0].([]interface{}); ok {
return arguments[0], nil
}
return arguments[:1:1], nil
}
func jpfToString(arguments []interface{}) (interface{}, error) {
if v, ok := arguments[0].(string); ok {
return v, nil
}
result, err := json.Marshal(arguments[0])
if err != nil {
return nil, err
}
return string(result), nil
}
func jpfToNumber(arguments []interface{}) (interface{}, error) {
arg := arguments[0]
if v, ok := arg.(float64); ok {
return v, nil
}
if v, ok := arg.(string); ok {
conv, err := strconv.ParseFloat(v, 64)
if err != nil {
return nil, nil
}
return conv, nil
}
if _, ok := arg.([]interface{}); ok {
return nil, nil
}
if _, ok := arg.(map[string]interface{}); ok {
return nil, nil
}
if arg == nil {
return nil, nil
}
if arg == true || arg == false {
return nil, nil
}
return nil, errors.New("unknown type")
}
func jpfNotNull(arguments []interface{}) (interface{}, error) {
for _, arg := range arguments {
if arg != nil {
return arg, nil
}
}
return nil, nil
}

View File

@ -0,0 +1 @@
foo

View File

@ -0,0 +1 @@
foo.bar

View File

@ -0,0 +1 @@
ends_with(str, 'SStr')

View File

@ -0,0 +1 @@
ends_with(str, 'foo')

View File

@ -0,0 +1 @@
floor(`1.2`)

View File

@ -0,0 +1 @@
floor(decimals[0])

View File

@ -0,0 +1 @@
floor(foo)

View File

@ -0,0 +1 @@
length('abc')

View File

@ -0,0 +1 @@
length('')

View File

@ -0,0 +1 @@
length(@)

View File

@ -0,0 +1 @@
length(strings[0])

View File

@ -0,0 +1 @@
length(str)

View File

@ -0,0 +1 @@
length(array)

View File

@ -0,0 +1 @@
length(strings[0])

View File

@ -0,0 +1 @@
max(strings)

View File

@ -0,0 +1 @@
merge(`{}`)

View File

@ -0,0 +1 @@
merge(`{}`, `{}`)

View File

@ -0,0 +1 @@
two

View File

@ -0,0 +1 @@
merge(`{"a": 1}`, `{"b": 2}`)

View File

@ -0,0 +1 @@
merge(`{"a": 1}`, `{"a": 2}`)

View File

@ -0,0 +1 @@
merge(`{"a": 1, "b": 2}`, `{"a": 2, "c": 3}`, `{"d": 4}`)

View File

@ -0,0 +1 @@
min(numbers)

View File

@ -0,0 +1 @@
min(decimals)

View File

@ -0,0 +1 @@
type('abc')

View File

@ -0,0 +1 @@
type(`1.0`)

View File

@ -0,0 +1 @@
three

View File

@ -0,0 +1 @@
type(`2`)

View File

@ -0,0 +1 @@
type(`true`)

View File

@ -0,0 +1 @@
type(`false`)

View File

@ -0,0 +1 @@
type(`null`)

View File

@ -0,0 +1 @@
type(`[0]`)

View File

@ -0,0 +1 @@
type(`{"a": "b"}`)

View File

@ -0,0 +1 @@
type(@)

View File

@ -0,0 +1 @@
keys(objects)

View File

@ -0,0 +1 @@
values(objects)

View File

@ -0,0 +1 @@
keys(empty_hash)

View File

@ -0,0 +1 @@
one.two

View File

@ -0,0 +1 @@
join(', ', strings)

View File

@ -0,0 +1 @@
join(', ', strings)

View File

@ -0,0 +1 @@
join(',', `["a", "b"]`)

View File

@ -0,0 +1 @@
join('|', strings)

View File

@ -0,0 +1 @@
join('|', decimals[].to_string(@))

View File

@ -0,0 +1 @@
join('|', empty_list)

View File

@ -0,0 +1 @@
reverse(numbers)

View File

@ -0,0 +1 @@
reverse(array)

View File

@ -0,0 +1 @@
reverse(`[]`)

View File

@ -0,0 +1 @@
reverse('')

View File

@ -0,0 +1 @@
foo."1"

View File

@ -0,0 +1 @@
reverse('hello world')

View File

@ -0,0 +1 @@
starts_with(str, 'S')

View File

@ -0,0 +1 @@
starts_with(str, 'St')

View File

@ -0,0 +1 @@
starts_with(str, 'Str')

View File

@ -0,0 +1 @@
sum(numbers)

View File

@ -0,0 +1 @@
sum(decimals)

View File

@ -0,0 +1 @@
sum(array[].to_number(@))

View File

@ -0,0 +1 @@
sum(`[]`)

Some files were not shown because too many files have changed in this diff Show More