├── .gitignore
├── demo
├── ijq.gif
└── ijq.tape
├── README.srht.html
├── testdata
└── caterror
├── go.mod
├── Makefile
├── .build.yml
├── history.go
├── README.md
├── main_test.go
├── history_test.go
├── ijq.1.scd
├── go.sum
├── main.go
└── COPYING
/.gitignore:
--------------------------------------------------------------------------------
1 | ijq
2 | ijq.1
3 | cover.out
--------------------------------------------------------------------------------
/demo/ijq.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gpanders/ijq/HEAD/demo/ijq.gif
--------------------------------------------------------------------------------
/README.srht.html:
--------------------------------------------------------------------------------
1 |
ijq has moved to Codeberg
2 |
--------------------------------------------------------------------------------
/testdata/caterror:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 | # Ignore all flags specified, and just cat with non-zero exit code.
3 | cat >&2
4 | exit 1
5 |
--------------------------------------------------------------------------------
/demo/ijq.tape:
--------------------------------------------------------------------------------
1 | Output demo/ijq.gif
2 | Set Height 1080
3 | Set Width 1920
4 |
5 | Hide
6 | Type "make ijq && clear"
7 | Enter
8 | Type "curl https://dummyjson.com/comments | ./ijq"
9 | Enter
10 | Sleep 2
11 | Show
12 |
13 | Sleep 2
14 |
15 | Type@0.4 "comments[] | select(.user.id < 60)"
16 |
17 | Sleep 2
18 |
19 | Type@0.4 " | {id, body}"
20 |
21 | Sleep 3
22 |
23 | Up
24 |
25 | Sleep 1
26 |
27 | Down @0.2 10
28 |
29 | Sleep 1
30 |
31 | Tab
32 |
33 | Sleep 1
34 |
35 | Down@0.2 20
36 |
37 | Sleep 2
38 |
39 | Up@0.2 10
40 |
41 | Sleep 6
42 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module codeberg.org/gpanders/ijq
2 |
3 | go 1.20
4 |
5 | require (
6 | github.com/gdamore/tcell/v2 v2.7.1
7 | github.com/kyoh86/xdg v1.2.0
8 | github.com/rivo/tview v0.0.0-20241103174730-c76f7879f592
9 | github.com/stretchr/testify v1.7.0
10 | golang.org/x/term v0.17.0
11 | )
12 |
13 | require (
14 | github.com/davecgh/go-spew v1.1.0 // indirect
15 | github.com/gdamore/encoding v1.0.0 // indirect
16 | github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
17 | github.com/mattn/go-runewidth v0.0.15 // indirect
18 | github.com/pmezard/go-difflib v1.0.0 // indirect
19 | github.com/rivo/uniseg v0.4.7 // indirect
20 | golang.org/x/sys v0.17.0 // indirect
21 | golang.org/x/text v0.14.0 // indirect
22 | gopkg.in/yaml.v3 v3.0.1 // indirect
23 | )
24 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | prefix = /usr/local
2 |
3 | # Support upper case PREFIX
4 | ifneq ($(PREFIX),)
5 | prefix := $(PREFIX)
6 | endif
7 |
8 | bindir = $(prefix)/bin
9 | mandir = $(prefix)/share/man
10 |
11 | SRCS = main.go history.go
12 |
13 | VERSION = 1.2.0
14 |
15 | .PHONY: all
16 | all: ijq docs
17 |
18 | .PHONY: docs
19 | docs: ijq.1
20 |
21 | ijq: $(SRCS)
22 | go build -ldflags="-s -w -X main.Version=$(VERSION)" -o $@
23 |
24 | %.1: %.1.scd
25 | scdoc < $< > $@
26 |
27 | .PHONY: test
28 | test:
29 | go test -v -coverprofile=./cover.out .
30 |
31 | .PHONY: viewcover
32 | viewcover:
33 | go tool cover -html=./cover.out
34 |
35 | .PHONY: install
36 | install: ijq ijq.1
37 | install -d $(DESTDIR)$(bindir) $(DESTDIR)$(mandir)/man1
38 | install -m 0755 ijq $(DESTDIR)$(bindir)
39 | install -m 0644 ijq.1 $(DESTDIR)$(mandir)/man1
40 |
41 | .PHONY: uninstall
42 | uninstall:
43 | rm $(DESTDIR)$(bindir)/ijq $(DESTDIR)$(mandir)/man1/ijq.1
44 |
45 | .PHONY: clean
46 | clean:
47 | rm -f ijq ijq.1
48 |
49 | demo/ijq.gif: demo/ijq.tape
50 | vhs < $<
51 |
--------------------------------------------------------------------------------
/.build.yml:
--------------------------------------------------------------------------------
1 | image: alpine/edge
2 | oauth: git.sr.ht/OBJECTS:RW git.sr.ht/REPOSITORIES:RW git.sr.ht/PROFILE:RO
3 | packages:
4 | - git
5 | - go
6 | - make
7 | - musl-dev
8 | - scdoc
9 | - hut
10 | sources:
11 | - https://git.sr.ht/~gpanders/ijq
12 | environment:
13 | GIT_SSH_COMMAND: ssh -o StrictHostKeyChecking=no
14 | triggers:
15 | - action: email
16 | condition: failure
17 | to: Gregory Anders
18 | tasks:
19 | - setup: |
20 | echo 'cd ijq' >> ~/.buildenv
21 | - test: |
22 | make test
23 | - update-readme: |
24 | hut git update --readme README.srht.html
25 | - nopr: |
26 | # Don't run on GitHub PRs
27 | [ "$BUILD_SUBMITTER" = 'git.sr.ht' ] || complete-build
28 | - build: |
29 | tag=$(git describe --exact-match 2>/dev/null || true)
30 | if [ -z "$tag" ]; then
31 | echo "Current commit is not a tag; not building anything"
32 | exit 0
33 | fi
34 |
35 | version=$(echo "$tag" | tr -d 'v')
36 | mkdir ijq-"$version"
37 |
38 | build() {
39 | os="$1"
40 | arch="$2"
41 | make GOOS="$os" GOARCH="$arch" clean all
42 | cp ijq ijq.1 COPYING ijq-"$version"/
43 |
44 | if [ "$os" = windows ]; then
45 | mv ijq-"$version"/ijq{,.exe}
46 | fi
47 |
48 | tar czf ijq-"$version"-"$os"-"$arch".tar.gz ijq-"$version"
49 | hut git artifact upload --rev "$tag" ijq-"$version"-"$os"-"$arch".tar.gz
50 | }
51 |
52 | build darwin amd64
53 | build darwin arm64
54 | build linux amd64
55 | build windows amd64
56 |
--------------------------------------------------------------------------------
/history.go:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2021 Gregory Anders
2 | // Copyright (C) 2021 Herby Gillot
3 | //
4 | // SPDX-License-Identifier: GPL-3.0-or-later
5 | //
6 | // This program is free software: you can redistribute it and/or modify
7 | // it under the terms of the GNU General Public License as published by
8 | // the Free Software Foundation, either version 3 of the License, or
9 | // (at your option) any later version.
10 | //
11 | // This program is distributed in the hope that it will be useful,
12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | // GNU General Public License for more details.
15 | //
16 | // You should have received a copy of the GNU General Public License
17 | // along with this program. If not, see .
18 |
19 | package main
20 |
21 | import (
22 | "bufio"
23 | "bytes"
24 | "errors"
25 | "fmt"
26 | "os"
27 | "path/filepath"
28 | "strings"
29 | )
30 |
31 | type history struct {
32 | path string
33 | Items []string
34 | }
35 |
36 | func (h *history) Init(path string) error {
37 | h.path = path
38 |
39 | filebytes, err := os.ReadFile(path)
40 | if err != nil {
41 | // If the history file doesn't exist, then
42 | // return an empty history.
43 | if errors.Is(err, os.ErrNotExist) {
44 | return nil
45 | } else {
46 | return fmt.Errorf("error retrieving history: %w", err)
47 | }
48 | }
49 |
50 | scanner := bufio.NewScanner(bytes.NewReader(filebytes))
51 | for scanner.Scan() {
52 | h.Items = append(h.Items, scanner.Text())
53 | }
54 |
55 | if err := scanner.Err(); err != nil {
56 | return fmt.Errorf(
57 | "error retrieving history: %w", err,
58 | )
59 | }
60 |
61 | return nil
62 | }
63 |
64 | func (h *history) Add(expression string) error {
65 | expression = strings.TrimSpace(expression)
66 | if expression == "" {
67 | return nil
68 | }
69 |
70 | if h.path == "" {
71 | return nil
72 | }
73 |
74 | // Don't continue with adding the expression if it is saved in history
75 | // already.
76 | if contains(h.Items, expression) {
77 | return nil
78 | }
79 |
80 | h.Items = append(h.Items, expression)
81 |
82 | file, err := h.openFile()
83 | if err != nil {
84 | return fmt.Errorf("error opening history for writing: %w", err)
85 | }
86 |
87 | fmt.Fprintln(file, expression)
88 |
89 | if err = file.Close(); err != nil {
90 | return fmt.Errorf("error closing history file: %w", err)
91 | }
92 |
93 | return nil
94 | }
95 |
96 | func (h *history) openFile() (*os.File, error) {
97 | err := os.MkdirAll(filepath.Dir(h.path), os.ModePerm)
98 | if err != nil {
99 | return nil, err
100 | }
101 |
102 | f, err := os.OpenFile(h.path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
103 | if err != nil {
104 | return nil, err
105 | }
106 |
107 | return f, nil
108 | }
109 |
110 | func contains(arr []string, elem string) bool {
111 | for _, v := range arr {
112 | if elem == v {
113 | return true
114 | }
115 | }
116 |
117 | return false
118 | }
119 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ijq
2 | ===
3 |
4 | Interactive `jq` tool. Like [jqplay] for the commandline.
5 |
6 | [jqplay]: https://jqplay.org
7 |
8 | Demo
9 | ----
10 |
11 | 
12 |
13 | Installation
14 | ------------
15 |
16 | ### Install from package manager
17 |
18 | [](https://repology.org/project/ijq/versions)
19 |
20 | ### Build from source
21 |
22 | Install [go]. To install `ijq` under `/usr/local/bin/` simply run
23 |
24 | make install
25 |
26 | from the root of the project. To install to another location, set the `PREFIX`
27 | variable, e.g.
28 |
29 | make PREFIX=~/.local install
30 |
31 | To generate the man page you will also need to have [scdoc] installed.
32 |
33 | [go]: https://golang.org/dl/
34 | [scdoc]: https://sr.ht/~sircmpwn/scdoc
35 |
36 | Usage
37 | -----
38 |
39 | ijq uses [jq] under the hood, so make sure you have that installed first.
40 |
41 | Read from a file:
42 |
43 | ijq file.json
44 |
45 | Read from stdin:
46 |
47 | curl -s https://api.github.com/users/gpanders | ijq
48 |
49 | Press `Return` to close `ijq` and print the current filtered output to stdout.
50 | This will also print the current filter to stderr. This allows you to save the
51 | filter for re-use with `jq` in the future:
52 |
53 | ijq file.json 2>filter.jq
54 |
55 | # Same output as above
56 | jq -f filter.jq file.json
57 |
58 | Pressing `Return` also saves the filter to a history file
59 | (`$XDG_DATA_HOME/ijq/history` by default). You can browse the history by
60 | deleting everything in the filter field. Change the history file used with the
61 | `-H` option, or specify an empty string to disable history entirely (i.e. `-H
62 | ''`).
63 |
64 | If `$XDG_DATA_HOME` is undefined, then the directory used is [platform
65 | dependent][xdg].
66 |
67 | Use `Shift` plus the arrow keys to move between the different windows. When
68 | either of the input or output views have focus, you can use the arrow keys to
69 | scroll up and down. Vi keys also work, i.e. you can use `j`/`k` to scroll up or
70 | down, `g` to move to the top of the view, `G` to jump to the bottom of the
71 | view, and `Ctrl-F`/`Ctrl-B` to scroll up or down a page at a time.
72 |
73 | Use `Ctrl-C` to exit `ijq` immediately, discarding all filters and state.
74 |
75 | You can configure the colors by setting the `JQ_COLORS` environment variable.
76 | See the [jq documentation][colors] for more details.
77 |
78 | [jq]: https://jqlang.github.io/jq/
79 | [colors]: https://jqlang.github.io/jq/manual/#colors
80 | [xdg]: https://github.com/kyoh86/xdg#xdg-base-directory
81 |
82 | Contributing
83 | ------------
84 |
85 | Bugs can be reported on the [issue tracker][issues]. PRs are accepted on
86 | [GitHub][github] or [Codeberg][codeberg].
87 |
88 | [issues]: https://codeberg.org/gpanders/ijq/issues
89 | [github]: https://github.com/gpanders/ijq
90 | [codeberg]: https://codeberg.org/gpanders/ijq
91 |
92 | Note for Packagers
93 | ------------------
94 |
95 | Subscribe to release announcements on [Codeberg][codeberg] to be notified of
96 | new releases, or subscribe to the [RSS
97 | feed](https://codeberg.org/gpanders/ijq/releases.rss).
98 |
99 | Similar Work
100 | ------------
101 |
102 | - [jqplay]
103 | - [vim-jqplay]
104 |
105 | [vim-jqplay]: https://github.com/bfrg/vim-jqplay
106 |
107 | License
108 | -------
109 |
110 | [GPLv3](https://www.gnu.org/licenses/gpl-3.0.en.html)
111 |
--------------------------------------------------------------------------------
/main_test.go:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2021 Gregory Anders
2 | // Copyright (C) 2021 Herby Gillot
3 | //
4 | // SPDX-License-Identifier: GPL-3.0-or-later
5 | //
6 | // This program is free software: you can redistribute it and/or modify
7 | // it under the terms of the GNU General Public License as published by
8 | // the Free Software Foundation, either version 3 of the License, or
9 | // (at your option) any later version.
10 | //
11 | // This program is distributed in the hope that it will be useful,
12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | // GNU General Public License for more details.
15 | //
16 | // You should have received a copy of the GNU General Public License
17 | // along with this program. If not, see .
18 |
19 | package main
20 |
21 | import (
22 | "bytes"
23 | "context"
24 | "os/exec"
25 | "strings"
26 | "testing"
27 |
28 | "github.com/stretchr/testify/assert"
29 | )
30 |
31 | func TestOptionsToSlice(t *testing.T) {
32 | opt := &Options{}
33 |
34 | opt.compact = true
35 | assert.Contains(t, opt.ToSlice(), "-c")
36 | opt.compact = false
37 | assert.NotContains(t, opt.ToSlice(), "-c")
38 |
39 | opt.nullInput = true
40 | assert.Contains(t, opt.ToSlice(), "-n")
41 | opt.nullInput = false
42 | assert.NotContains(t, opt.ToSlice(), "-n")
43 |
44 | opt.slurp = true
45 | assert.Contains(t, opt.ToSlice(), "-s")
46 | opt.slurp = false
47 | assert.NotContains(t, opt.ToSlice(), "-s")
48 |
49 | opt.rawOutput = true
50 | assert.Contains(t, opt.ToSlice(), "-r")
51 | opt.rawOutput = false
52 | assert.NotContains(t, opt.ToSlice(), "-r")
53 |
54 | opt.rawInput = true
55 | assert.Contains(t, opt.ToSlice(), "-R")
56 | opt.rawInput = false
57 | assert.NotContains(t, opt.ToSlice(), "-R")
58 |
59 | opt.monochrome = true
60 | assert.Contains(t, opt.ToSlice(), "-M")
61 | opt.monochrome = false
62 | assert.NotContains(t, opt.ToSlice(), "-M")
63 |
64 | opt.forceColor = true
65 | assert.Contains(t, opt.ToSlice(), "-C")
66 | opt.forceColor = false
67 | assert.NotContains(t, opt.ToSlice(), "-C")
68 |
69 | opt.sortKeys = true
70 | assert.Contains(t, opt.ToSlice(), "-S")
71 | opt.sortKeys = false
72 | assert.NotContains(t, opt.ToSlice(), "-S")
73 | }
74 |
75 | func TestDocumentReadFrom(t *testing.T) {
76 | testMsg := "hello world"
77 | testReader := strings.NewReader(testMsg)
78 |
79 | doc := &Document{}
80 |
81 | readCount, err := doc.ReadFrom(testReader)
82 | assert.NoError(t, err)
83 | assert.Equal(t, len(testMsg), int(readCount))
84 | }
85 |
86 | func TestDocumentWriteTo(t *testing.T) {
87 | testMsg := "hello world"
88 | testReader := strings.NewReader(testMsg)
89 |
90 | doc := &Document{
91 | filter: "-",
92 | options: Options{
93 | command: "cat",
94 | },
95 | ctx: context.Background(),
96 | }
97 |
98 | readCount, err := doc.ReadFrom(testReader)
99 | assert.NoError(t, err)
100 | assert.Equal(t, len(testMsg), int(readCount))
101 |
102 | buffer := bytes.Buffer{}
103 |
104 | writeCount, err := doc.WriteTo(&buffer)
105 | assert.NoError(t, err)
106 | assert.Equal(t, 0, int(writeCount))
107 |
108 | assert.Equal(t, testMsg, buffer.String())
109 | }
110 |
111 | func TestDocumentExecError(t *testing.T) {
112 | testMsg := "hello world"
113 | testReader := strings.NewReader(testMsg)
114 |
115 | doc := &Document{
116 | options: Options{
117 | command: "./testdata/caterror",
118 | },
119 | ctx: context.Background(),
120 | }
121 |
122 | readCount, err := doc.ReadFrom(testReader)
123 | assert.NoError(t, err)
124 | assert.Equal(t, len(testMsg), int(readCount))
125 |
126 | buffer := bytes.Buffer{}
127 |
128 | writeCount, err := doc.WriteTo(&buffer)
129 | assert.Error(t, err)
130 | assert.Equal(t, 0, int(writeCount))
131 |
132 | exiterr, ok := err.(*exec.ExitError)
133 | assert.True(t, ok)
134 | assert.NotNil(t, exiterr)
135 | assert.Equal(t, testMsg, string(exiterr.Stderr))
136 |
137 | assert.Empty(t, buffer.String())
138 | }
139 |
--------------------------------------------------------------------------------
/history_test.go:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2021 Gregory Anders
2 | // Copyright (C) 2021 Herby Gillot
3 | //
4 | // SPDX-License-Identifier: GPL-3.0-or-later
5 | //
6 | // This program is free software: you can redistribute it and/or modify
7 | // it under the terms of the GNU General Public License as published by
8 | // the Free Software Foundation, either version 3 of the License, or
9 | // (at your option) any later version.
10 | //
11 | // This program is distributed in the hope that it will be useful,
12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | // GNU General Public License for more details.
15 | //
16 | // You should have received a copy of the GNU General Public License
17 | // along with this program. If not, see .
18 |
19 | package main
20 |
21 | import (
22 | "io/ioutil"
23 | "math/rand"
24 | "os"
25 | "path"
26 | "strconv"
27 | "testing"
28 | "time"
29 |
30 | "github.com/stretchr/testify/assert"
31 | )
32 |
33 | func randomFilename(namebase string) string {
34 | random := rand.New(rand.NewSource(time.Now().UnixNano()))
35 | if namebase == "" {
36 | namebase = "file"
37 | }
38 |
39 | return namebase + "." + strconv.Itoa(random.Int())
40 | }
41 |
42 | func makeHistoryFilename() string {
43 | return randomFilename("./history")
44 | }
45 |
46 | func TestHistoryAddNoFilename(t *testing.T) {
47 | var h history
48 | err := h.Add("foo")
49 | assert.NoError(t, err)
50 | assert.Nil(t, err)
51 | assert.Empty(t, h.Items)
52 | }
53 |
54 | func TestHistoryAddEmptyString(t *testing.T) {
55 | histfile := makeHistoryFilename()
56 | var h history
57 | h.Init(histfile)
58 | err := h.Add("")
59 | assert.NoError(t, err)
60 | assert.Nil(t, err)
61 | assert.NoFileExists(t, histfile)
62 | }
63 |
64 | func TestContains(t *testing.T) {
65 | things := []string{"one", "two", "three"}
66 |
67 | assert.True(t, contains(things, "one"))
68 | assert.True(t, contains(things, "two"))
69 | assert.True(t, contains(things, "three"))
70 | assert.False(t, contains(things, "four"))
71 | }
72 |
73 | func TestHistoryAdd(t *testing.T) {
74 | histFile := makeHistoryFilename()
75 |
76 | before := "one\ntwo\n"
77 | after := "one\ntwo\nthree\n"
78 |
79 | err := ioutil.WriteFile(histFile, []byte(before), 0644)
80 | assert.NoError(t, err)
81 |
82 | var h history
83 | h.Init(histFile)
84 |
85 | err = h.Add("three")
86 | assert.NoError(t, err)
87 |
88 | contents, err := ioutil.ReadFile(histFile)
89 | assert.NoError(t, err)
90 | assert.Equal(t, []byte(after), contents)
91 |
92 | assert.NoError(t, os.Remove(histFile))
93 | }
94 |
95 | func TestHistoryAddRepeating(t *testing.T) {
96 | histFile := makeHistoryFilename()
97 |
98 | contents := "one\ntwo\n"
99 |
100 | err := ioutil.WriteFile(histFile, []byte(contents), 0644)
101 | assert.NoError(t, err)
102 |
103 | var h history
104 | h.Init(histFile)
105 |
106 | err = h.Add("one")
107 | assert.NoError(t, err)
108 |
109 | retrieved, err := ioutil.ReadFile(histFile)
110 | assert.NoError(t, err)
111 | assert.Equal(t, []byte(contents), retrieved)
112 |
113 | assert.NoError(t, os.Remove(histFile))
114 | }
115 |
116 | func TestHistoryWithinSubDir(t *testing.T) {
117 | rootDir := "./testdata/myroot"
118 |
119 | histFile := path.Join(rootDir, "myhistory")
120 |
121 | var h history
122 | h.Init(histFile)
123 |
124 | err := h.Add("one")
125 | assert.NoError(t, err)
126 | assert.FileExists(t, histFile)
127 |
128 | assert.NoError(t, os.RemoveAll(rootDir))
129 | }
130 |
131 | func TestHistoryGetMissingFile(t *testing.T) {
132 | historyFile := "./this.does.not.exist"
133 |
134 | var h history
135 | h.Init(historyFile)
136 | assert.NoFileExists(t, historyFile)
137 | }
138 |
139 | func TestHistory(t *testing.T) {
140 | histFile := makeHistoryFilename()
141 |
142 | var h history
143 | h.Init(histFile)
144 |
145 | var err error
146 |
147 | err = h.Add("one")
148 | assert.NoError(t, err)
149 | err = h.Add("two")
150 | assert.NoError(t, err)
151 | err = h.Add("three")
152 | assert.NoError(t, err)
153 |
154 | assert.NoError(t, err)
155 |
156 | assert.Equal(
157 | t,
158 | h.Items,
159 | []string{"one", "two", "three"},
160 | )
161 |
162 | // Add new after Get
163 | err = h.Add("four")
164 | assert.NoError(t, err)
165 |
166 | assert.Equal(
167 | t,
168 | h.Items,
169 | []string{"one", "two", "three", "four"},
170 | )
171 |
172 | // Attempt to add item already in history
173 | err = h.Add("one")
174 | assert.NoError(t, err)
175 |
176 | assert.Equal(
177 | t,
178 | h.Items,
179 | []string{"one", "two", "three", "four"},
180 | )
181 |
182 | assert.NoError(t, os.Remove(histFile))
183 | }
184 |
--------------------------------------------------------------------------------
/ijq.1.scd:
--------------------------------------------------------------------------------
1 | ijq(1)
2 |
3 | # NAME
4 |
5 | ijq - interactive jq
6 |
7 | # SYNOPSIS
8 |
9 | *ijq* [*-cnsrRMSV*] [*-f* _file_] [_filter_] [_files ..._]
10 |
11 | # DESCRIPTION
12 |
13 | *ijq* is a near drop-in replacement for *jq* that allows you to interactively
14 | see the results of your filter as you construct it.
15 |
16 | *ijq* contains two panes and an input field: the left pane is the original,
17 | unmodified input data and the right pane contains the filtered output. When you
18 | are finished, press Return or Ctrl-C to exit. The filtered output will be
19 | written to standard output and the filter itself will be written to standard
20 | error.
21 |
22 | *ijq* maintains a history of used filters, unless disabled with the *-H* option.
23 | Delete all text in the filter field to browse any available history.
24 |
25 | If _files_ is omitted then *ijq* reads data from standard input.
26 |
27 | All of the options mirror their counterparts in *jq*. The options are:
28 |
29 | *-c*
30 | Use compact instead of pretty-printed output.
31 |
32 | *-n*
33 | Don't read any input. Useful for using *ijq* as a calculator or to
34 | construct JSON data from scratch.
35 |
36 | *-s*
37 | Read all input into a single array and apply the given filter to it.
38 |
39 | *-r*
40 | If the filter output is a string it will be written directly to standard
41 | output rather than being formatted as a JSON string with quotes. Useful
42 | for using *ijq* in a pipeline with other programs that expect normal
43 | string input.
44 |
45 | *-R*
46 | Don't parse the input as JSON, instead passing each line of input to the
47 | filter as a string. If combined with *-s* then the entire input is
48 | passed to the filter as a single long string.
49 |
50 | *-M*
51 | Disable colored output.
52 |
53 | *-S*
54 | Output the fields of each object with the fields in sorted order.
55 |
56 | *-f* _file_
57 | Read the filter from _file_. When this option is used, all positional
58 | arguments (if any) are interpreted as input files.
59 |
60 | *ijq* has some options that influence its configuration and starting layout.
61 | They are designed to avoid conflicts with *jq*. If *jq* adds in the future
62 | adds an option that conflicts with one of these, they might change here.
63 |
64 | *-H* _file_
65 | Specify the path to store history. If set to '' (-H ''), then history
66 | will not be captured.
67 |
68 | *-hide-input-pane*
69 | Hides the input (left) viewing pane, which shows the original input.
70 |
71 | # KEY BINDINGS
72 |
73 | *Shift + Up*, *Shift + Left*
74 | Focus the input (left) viewing pane.
75 |
76 | *Shift + Right*
77 | Focus the output (right) viewing pane.
78 |
79 | *Shift + Down*
80 | Focus the text input field.
81 |
82 | *Tab*
83 | When the text input field has focus, navigate between the autocompletion
84 | list. When one of the viewing panes has focus, toggle between the
85 | different views.
86 |
87 | *Shift-Tab*
88 | Like *Tab*, but moves in the opposite direction.
89 |
90 | *Ctrl-A*
91 | When the text input field has focus, move the cursor to the beginning of
92 | the input. When one of the viewing panes has focus, set the column
93 | offset to 0.
94 |
95 | *Ctrl-E*
96 | When the text input field has focus, move the cursor to the end of the
97 | input. When one of the viewing panes has focus, set the column offset to
98 | view the longest visible line.
99 |
100 | *Ctrl-F*
101 | When the text input field has focus, move the cursor one character
102 | forward. When one of the viewing panes has focus, scroll down one page.
103 |
104 | *Ctrl-B*
105 | When the text input field has focus, move the cursor one character
106 | backward. When one of the viewing panes has focus, scroll up one page.
107 |
108 | *Ctrl-D*
109 | When the text input field has focus, delete the character under the
110 | cursor. When one of the viewing panes has focus, scroll down one half
111 | page.
112 |
113 | *Ctrl-U*
114 | When the text input field has focus, delete all of the text from the
115 | cursor to the beginning of the field. When one of the viewing panes has
116 | focus, scroll up one half page.
117 |
118 | *Ctrl-O*
119 | Toggle visibility of the input (left) viewing pane.
120 |
121 | *u*, *d*, *f*, *b*
122 | When one of the viewing panes has focus, scroll a half/full page
123 | up/down.
124 |
125 | *Left*, *Down*, *Up*, *Right*
126 | *h*, *j*, *k*, *l*
127 | When one of the viewing panes has focus, move the view
128 | left/down/up/right.
129 |
130 | *Return*
131 | Close *ijq*. Write the contents of the output pane to stdout and the
132 | current input filter to stderr. The current input filter is also saved
133 | to the history file.
134 |
135 | *Ctrl-C*
136 | Exit *ijq* immediately, discarding all state.
137 |
138 | # DEMO
139 |
140 | See https://asciinema.org/a/496932 for a demo.
141 |
142 | # SEE ALSO
143 |
144 | jq(1)
145 |
146 | # AUTHOR
147 |
148 | Gregory Anders
149 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
2 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
3 | github.com/gdamore/encoding v1.0.0 h1:+7OoQ1Bc6eTm5niUzBa0Ctsh6JbMW6Ra+YNuAtDBdko=
4 | github.com/gdamore/encoding v1.0.0/go.mod h1:alR0ol34c49FCSBLjhosxzcPHQbf2trDkoo5dl+VrEg=
5 | github.com/gdamore/tcell/v2 v2.7.1 h1:TiCcmpWHiAU7F0rA2I3S2Y4mmLmO9KHxJ7E1QhYzQbc=
6 | github.com/gdamore/tcell/v2 v2.7.1/go.mod h1:dSXtXTSK0VsW1biw65DZLZ2NKr7j0qP/0J7ONmsraWg=
7 | github.com/kyoh86/xdg v1.2.0 h1:CERuT/ShdTDj+A2UaX3hQ3mOV369+Sj+wyn2nIRIIkI=
8 | github.com/kyoh86/xdg v1.2.0/go.mod h1:/mg8zwu1+qe76oTFUBnyS7rJzk7LLC0VGEzJyJ19DHs=
9 | github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
10 | github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
11 | github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=
12 | github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
13 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
14 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
15 | github.com/rivo/tview v0.0.0-20241103174730-c76f7879f592 h1:YIJ+B1hePP6AgynC5TcqpO0H9k3SSoZa2BGyL6vDUzM=
16 | github.com/rivo/tview v0.0.0-20241103174730-c76f7879f592/go.mod h1:02iFIz7K/A9jGCvrizLPvoqr4cEIx7q54RH5Qudkrss=
17 | github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
18 | github.com/rivo/uniseg v0.4.3/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
19 | github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
20 | github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
21 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
22 | github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
23 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
24 | github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
25 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
26 | golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
27 | golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
28 | golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
29 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
30 | golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
31 | golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
32 | golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
33 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
34 | golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
35 | golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
36 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
37 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
38 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
39 | golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
40 | golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
41 | golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
42 | golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y=
43 | golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
44 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
45 | golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
46 | golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
47 | golang.org/x/term v0.17.0 h1:mkTF7LCd6WGJNL3K1Ad7kwxNfYAW6a8a8QqtMblp/4U=
48 | golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
49 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
50 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
51 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
52 | golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
53 | golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
54 | golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
55 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
56 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
57 | golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
58 | golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
59 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
60 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
61 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
62 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
63 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
64 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
65 |
--------------------------------------------------------------------------------
/main.go:
--------------------------------------------------------------------------------
1 | // Copyright (C) 2021 Gregory Anders
2 | // Copyright (C) 2021 Herby Gillot
3 | //
4 | // SPDX-License-Identifier: GPL-3.0-or-later
5 | //
6 | // This program is free software: you can redistribute it and/or modify
7 | // it under the terms of the GNU General Public License as published by
8 | // the Free Software Foundation, either version 3 of the License, or
9 | // (at your option) any later version.
10 | //
11 | // This program is distributed in the hope that it will be useful,
12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | // GNU General Public License for more details.
15 | //
16 | // You should have received a copy of the GNU General Public License
17 | // along with this program. If not, see .
18 |
19 | package main
20 |
21 | import (
22 | "bytes"
23 | "context"
24 | "encoding/json"
25 | "flag"
26 | "fmt"
27 | "io"
28 | "log"
29 | "os"
30 | "os/exec"
31 | "path/filepath"
32 | "strings"
33 | "sync"
34 |
35 | "github.com/gdamore/tcell/v2"
36 | "github.com/kyoh86/xdg"
37 | "github.com/rivo/tview"
38 | "golang.org/x/term"
39 | )
40 |
41 | const defaultCommand string = "jq"
42 |
43 | // Special characters that, if present in a JSON key, need to be quoted in the
44 | // jq filter
45 | const specialChars string = ".-:$/"
46 |
47 | const alphabet string = "abcdefghijklmnopqrstuvwxyz"
48 |
49 | var Version string
50 |
51 | type Options struct {
52 | compact bool
53 | command string
54 | nullInput bool
55 | slurp bool
56 | rawOutput bool
57 | rawInput bool
58 | monochrome bool
59 | sortKeys bool
60 | historyFile string
61 | forceColor bool
62 | hideInputPane bool
63 | }
64 |
65 | // Convert the Options struct to a string slice of option flags that gets
66 | // passed to jq.
67 | func (o *Options) ToSlice() []string {
68 | opts := []string{}
69 |
70 | if o.compact {
71 | opts = append(opts, "-c")
72 | }
73 |
74 | if o.nullInput {
75 | opts = append(opts, "-n")
76 | }
77 |
78 | if o.slurp {
79 | opts = append(opts, "-s")
80 | }
81 |
82 | if o.rawOutput {
83 | opts = append(opts, "-r")
84 | }
85 |
86 | if o.rawInput {
87 | opts = append(opts, "-R")
88 | }
89 |
90 | if o.monochrome {
91 | opts = append(opts, "-M")
92 | }
93 |
94 | if o.forceColor {
95 | opts = append(opts, "-C")
96 | }
97 |
98 | if o.sortKeys {
99 | opts = append(opts, "-S")
100 | }
101 |
102 | return opts
103 | }
104 |
105 | type Document struct {
106 | input string
107 | filter string
108 | options Options
109 | ctx context.Context
110 | }
111 |
112 | func (d Document) WithFilter(filter string) Document {
113 | return Document{input: d.input, filter: filter, options: d.options, ctx: context.Background()}
114 | }
115 |
116 | func (d *Document) ReadFrom(r io.Reader) (n int64, err error) {
117 | var buf bytes.Buffer
118 | n, err = buf.ReadFrom(r)
119 | d.input = buf.String()
120 | return n, err
121 | }
122 |
123 | func (d Document) WriteTo(w io.Writer) (n int64, err error) {
124 | opts := d.options
125 | if p, ok := w.(*pane); ok {
126 | // Writer is a pane, so set options accordingly
127 | opts.forceColor = true
128 | opts.monochrome = false
129 | opts.compact = false
130 | opts.rawOutput = false
131 | w = tview.ANSIWriter(p)
132 |
133 | // Mark the pane as dirty so the text view is cleared before
134 | // new output is written.
135 | p.dirty = true
136 | defer func() {
137 | if p.dirty && err == nil {
138 | // If there was no error and the pane is still marked as dirty that
139 | // means jq didn't emit any output, so we need to clear the pane
140 | // manually
141 | p.tv.Clear()
142 | }
143 | }()
144 | }
145 |
146 | args := append(opts.ToSlice(), d.filter)
147 | cmd := exec.CommandContext(d.ctx, d.options.command, args...)
148 |
149 | var b bytes.Buffer
150 | cmd.Stdin = strings.NewReader(d.input)
151 | cmd.Stdout = w
152 | cmd.Stderr = &b
153 |
154 | if err := cmd.Run(); err != nil {
155 | if exiterr, ok := err.(*exec.ExitError); ok {
156 | exiterr.Stderr = b.Bytes()
157 | }
158 | return 0, err
159 | }
160 |
161 | return 0, nil
162 | }
163 |
164 | type pane struct {
165 | tv *tview.TextView
166 | dirty bool
167 | }
168 |
169 | func (pane *pane) Write(p []byte) (n int, err error) {
170 | if pane.dirty {
171 | pane.tv.Clear()
172 | pane.dirty = false
173 | }
174 |
175 | return pane.tv.Write(p)
176 | }
177 |
178 | func parseArgs() (Options, string, []string) {
179 | flag.Usage = func() {
180 | fmt.Fprintf(os.Stderr, "ijq - interactive jq\n\n")
181 | fmt.Fprintf(os.Stderr, "Usage: ijq [-cnsrRMSV] [-f file] [filter] [files ...]\n\n")
182 | fmt.Fprintf(os.Stderr, "Options:\n")
183 | flag.PrintDefaults()
184 | }
185 |
186 | options := Options{}
187 | flag.BoolVar(&options.compact, "c", false, "compact instead of pretty-printed output")
188 | flag.BoolVar(&options.nullInput, "n", false, "use ```null` as the single input value")
189 | flag.BoolVar(&options.slurp, "s", false, "read (slurp) all inputs into an array; apply filter to it")
190 | flag.BoolVar(&options.rawOutput, "r", false, "output raw strings, not JSON texts")
191 | flag.BoolVar(&options.rawInput, "R", false, "read raw strings, not JSON texts")
192 | flag.BoolVar(&options.forceColor, "C", false, "force colorized JSON, even if writing to a pipe or file")
193 | flag.BoolVar(&options.monochrome, "M", false, "monochrome (don't colorize JSON)")
194 | flag.BoolVar(&options.sortKeys, "S", false, "sort keys of objects on output")
195 | flag.BoolVar(&options.hideInputPane, "hide-input-pane", false, "hide input (left) viewing pane")
196 |
197 | flag.StringVar(
198 | &options.command,
199 | "jqbin",
200 | defaultCommand,
201 | "name of or path to jq binary to use",
202 | )
203 |
204 | flag.StringVar(
205 | &options.historyFile,
206 | "H",
207 | filepath.Join(xdg.DataHome(), "ijq", "history"),
208 | "set path to history file. Set to '' to disable history.",
209 | )
210 |
211 | filterFile := flag.String("f", "", "read initial filter from `filename`")
212 | version := flag.Bool("V", false, "print version and exit")
213 |
214 | flag.Parse()
215 |
216 | if *version {
217 | fmt.Println("ijq " + Version)
218 | os.Exit(0)
219 | }
220 |
221 | filter := "."
222 | args := flag.Args()
223 |
224 | stdinIsTty := term.IsTerminal(int(os.Stdin.Fd()))
225 |
226 | if *filterFile != "" {
227 | contents, err := os.ReadFile(*filterFile)
228 | if err != nil {
229 | log.Fatalln(err)
230 | }
231 |
232 | filter = string(contents)
233 | } else if len(args) > 1 || (len(args) > 0 && (!stdinIsTty || options.nullInput)) {
234 | filter = args[0]
235 | args = args[1:]
236 | } else if len(args) == 0 && stdinIsTty && !options.nullInput {
237 | flag.Usage()
238 | os.Exit(1)
239 | }
240 |
241 | return options, filter, args
242 | }
243 |
244 | func scrollHalfPage(tv *tview.TextView, up bool) {
245 | _, _, _, height := tv.GetInnerRect()
246 | row, col := tv.GetScrollOffset()
247 | if up {
248 | tv.ScrollTo(row-height/2, col)
249 | } else {
250 | tv.ScrollTo(row+height/2, col)
251 | }
252 | }
253 |
254 | func scrollHorizontally(tv *tview.TextView, end bool) {
255 | if end {
256 | text := tv.GetText(true)
257 | _, _, width, height := tv.GetInnerRect()
258 | row, _ := tv.GetScrollOffset()
259 | maxLen := 0
260 | for i, line := range strings.Split(text, "\n") {
261 | if i < row {
262 | continue
263 | }
264 |
265 | if i > row+height {
266 | break
267 | }
268 |
269 | if length := len(line); length > maxLen {
270 | maxLen = length
271 | }
272 | }
273 |
274 | if maxLen > width {
275 | tv.ScrollTo(row, maxLen-width)
276 | }
277 | } else {
278 | row, _ := tv.GetScrollOffset()
279 | tv.ScrollTo(row, 0)
280 | }
281 | }
282 |
283 | func updateScrollIndicator(name string, lineCount int, tv *tview.TextView) {
284 | row, _ := tv.GetScrollOffset()
285 | if row <= 0 {
286 | tv.SetTitle(fmt.Sprintf("%s (Top)", name))
287 | return
288 | }
289 |
290 | _, _, _, height := tv.GetInnerRect()
291 | if row+height >= lineCount {
292 | tv.SetTitle(fmt.Sprintf("%s (Bot)", name))
293 | return
294 | }
295 |
296 | percent := row * 100 / lineCount
297 | tv.SetTitle(fmt.Sprintf("%s (%d%%)", name, percent))
298 | }
299 |
300 | func createApp(doc Document) *tview.Application {
301 | app := tview.NewApplication()
302 |
303 | // tview uses colors for a dark background by default, so reset some of
304 | // the styles to simply use the colors from the terminal to better
305 | // support light color themes
306 | tview.Styles.PrimaryTextColor = tcell.ColorDefault
307 | tview.Styles.PrimitiveBackgroundColor = tcell.ColorDefault
308 | tview.Styles.BorderColor = tcell.ColorDefault
309 | tview.Styles.TitleColor = tcell.ColorDefault
310 | tview.Styles.GraphicsColor = tcell.ColorDefault
311 |
312 | inputView := tview.NewTextView()
313 | inputView.SetDynamicColors(true).SetWrap(false).SetBorder(true)
314 | inputPane := pane{tv: inputView}
315 | isInputPaneHidden := doc.options.hideInputPane
316 |
317 | outputView := tview.NewTextView()
318 | outputView.SetDynamicColors(true).SetWrap(false).SetBorder(true)
319 | outputPane := pane{tv: outputView}
320 |
321 | errorView := tview.NewTextView()
322 | errorView.SetDynamicColors(false).SetTitle("Error").SetBorder(true)
323 |
324 | var filterHistory history
325 | filterHistory.Init(doc.options.historyFile)
326 |
327 | var (
328 | mutex sync.Mutex
329 | cancel context.CancelFunc
330 | )
331 | cond := sync.NewCond(&mutex)
332 |
333 | // Initialize pending to true so that the output pane will update with the initial filter
334 | pending := true
335 |
336 | filterMap := make(map[string][]string)
337 | filterInput := tview.NewInputField()
338 | filterInput.
339 | SetText(doc.filter).
340 | SetFieldBackgroundColor(tcell.ColorDefault).
341 | SetFieldTextColor(tcell.ColorDefault).
342 | SetChangedFunc(func(text string) {
343 | errorView.Clear()
344 | filterInput.SetFieldTextColor(tcell.ColorDefault)
345 |
346 | if text == doc.filter {
347 | return
348 | }
349 |
350 | cancel()
351 |
352 | mutex.Lock()
353 | defer mutex.Unlock()
354 |
355 | doc = doc.WithFilter(text)
356 | pending = true
357 | cond.Signal()
358 | }).
359 | SetDoneFunc(func(key tcell.Key) {
360 | switch key {
361 | case tcell.KeyEnter:
362 | app.Stop()
363 |
364 | fmt.Fprintln(os.Stderr, doc.filter)
365 |
366 | // Enable or disable colors depending on if
367 | // stdout is a tty, respecting options set by
368 | // the user
369 | isTty := term.IsTerminal(int(os.Stdout.Fd()))
370 | if !isTty && !doc.options.forceColor {
371 | doc.options.monochrome = true
372 | } else if isTty && !doc.options.monochrome {
373 | doc.options.forceColor = true
374 | }
375 |
376 | filterHistory.Add(doc.filter)
377 |
378 | if _, err := doc.WriteTo(os.Stdout); err != nil {
379 | log.Fatalln(err)
380 | }
381 | }
382 | }).
383 | SetAutocompleteFunc(func(text string) []string {
384 | if text == "" {
385 | return filterHistory.Items
386 | }
387 |
388 | if pos := strings.LastIndexByte(text, '.'); pos != -1 {
389 | prefix := text[0:pos]
390 | trimmed := strings.TrimSpace(prefix)
391 |
392 | mutex.Lock()
393 | candidates, ok := filterMap[trimmed]
394 | mutex.Unlock()
395 | if ok {
396 | cur := text[pos+1:]
397 | var entries []string
398 | for _, c := range candidates {
399 | key := c[pos+1:]
400 | if strings.HasPrefix(key, cur) {
401 | entries = append(entries, c)
402 | }
403 | }
404 |
405 | return entries
406 | }
407 |
408 | go func() {
409 | var filt string
410 | if prefix != "" {
411 | p, _ := strings.CutSuffix(trimmed, "|")
412 | filt = p + "| keys"
413 | } else {
414 | filt = "keys"
415 | }
416 |
417 | var buf bytes.Buffer
418 | _, err := doc.WithFilter("[" + filt + "] | unique | first").WriteTo(&buf)
419 | if err != nil {
420 | return
421 | }
422 |
423 | var keys []string
424 | if err := json.Unmarshal(buf.Bytes(), &keys); err != nil {
425 | return
426 | }
427 |
428 | entries := keys[:0]
429 | for _, k := range keys {
430 | first := strings.ToLower(string(k[0]))
431 | if strings.ContainsAny(k, specialChars) || !strings.Contains(alphabet, first) {
432 | k = `"` + k + `"`
433 | }
434 | entries = append(entries, prefix+"."+k)
435 | }
436 |
437 | mutex.Lock()
438 | filterMap[trimmed] = entries
439 | mutex.Unlock()
440 |
441 | filterInput.Autocomplete()
442 |
443 | app.Draw()
444 | }()
445 | }
446 |
447 | return nil
448 | }).
449 | SetAutocompleteUseTags(false).
450 | SetAutocompleteStyles(tcell.ColorBlack, tcell.StyleDefault.Background(tcell.ColorBlack), tcell.StyleDefault.Reverse(true)).
451 | SetTitle("Filter").
452 | SetBorder(true)
453 |
454 | // Initialize the initial line counts to some large number. If the
455 | // input is small, this will be updated to the correct value before it
456 | // is ever displayed in the UI. But for large inputs (which will take
457 | // longer to calculate the correct value), this is a better initial
458 | // guess.
459 | inputLineCount := 10000
460 | outputLineCount := 10000
461 |
462 | // Process document with empty filter to populate input view
463 | go func() {
464 | _, err := doc.WithFilter(".").WriteTo(&inputPane)
465 | if err != nil {
466 | log.Fatalf("Error while running jq on input: %s\n", err)
467 | }
468 |
469 | inputLineCount = strings.Count(inputView.GetText(false), "\n")
470 | }()
471 |
472 | // Create a cancellable context when writing to the output view. If the
473 | // filter input changes, the context is cancelled and the process is
474 | // killed.
475 | doc.ctx, cancel = context.WithCancel(context.Background())
476 |
477 | go func() {
478 | for {
479 | cond.L.Lock()
480 | for !pending {
481 | cond.Wait()
482 | }
483 |
484 | d := doc
485 | pending = false
486 | cond.L.Unlock()
487 |
488 | // Re-initialize the cancellable context
489 | d.ctx, cancel = context.WithCancel(context.Background())
490 |
491 | _, err := d.WriteTo(&outputPane)
492 | if err != nil {
493 | if exitErr, ok := err.(*exec.ExitError); ok {
494 | if code := exitErr.ExitCode(); code != -1 {
495 | app.QueueUpdate(func() {
496 | filterInput.SetFieldTextColor(tcell.ColorMaroon)
497 | fmt.Fprint(tview.ANSIWriter(errorView), string(exitErr.Stderr))
498 | })
499 | }
500 | }
501 | } else {
502 | outputLineCount = strings.Count(outputView.GetText(false), "\n")
503 | }
504 |
505 | app.Draw()
506 | }
507 | }()
508 |
509 | inputPaneProportion := 1
510 | if isInputPaneHidden {
511 | inputPaneProportion = 0
512 | }
513 | viewFlex := tview.NewFlex().
514 | AddItem(inputView, 0, inputPaneProportion, false).
515 | AddItem(outputView, 0, 1, false)
516 | grid := tview.NewGrid().
517 | SetRows(0, 3, 4).
518 | SetColumns(0).
519 | AddItem(viewFlex, 0, 0, 1, 1, 0, 0, false).
520 | AddItem(tview.NewFlex().
521 | AddItem(tview.NewBox(), 0, 1, false).
522 | AddItem(filterInput, 0, 4, true).
523 | AddItem(tview.NewBox(), 0, 1, false), 1, 0, 1, 1, 0, 0, true).
524 | AddItem(tview.NewFlex().
525 | AddItem(tview.NewBox(), 0, 1, false).
526 | AddItem(errorView, 0, 4, false).
527 | AddItem(tview.NewBox(), 0, 1, false), 2, 0, 1, 1, 0, 0, false)
528 |
529 | app.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
530 | shift := event.Modifiers()&tcell.ModShift != 0
531 | focused := app.GetFocus()
532 |
533 | switch key := event.Key(); key {
534 | case tcell.KeyCtrlN:
535 | return tcell.NewEventKey(tcell.KeyDown, ' ', tcell.ModNone)
536 | case tcell.KeyCtrlP:
537 | return tcell.NewEventKey(tcell.KeyUp, ' ', tcell.ModNone)
538 | case tcell.KeyCtrlV:
539 | return tcell.NewEventKey(tcell.KeyPgDn, ' ', tcell.ModNone)
540 | case tcell.KeyCtrlA:
541 | if tv, ok := focused.(*tview.TextView); ok {
542 | scrollHorizontally(tv, false)
543 | return nil
544 | }
545 | case tcell.KeyCtrlE:
546 | if tv, ok := focused.(*tview.TextView); ok {
547 | scrollHorizontally(tv, true)
548 | return nil
549 | }
550 | case tcell.KeyCtrlU:
551 | if tv, ok := focused.(*tview.TextView); ok {
552 | scrollHalfPage(tv, true)
553 | return nil
554 | }
555 | case tcell.KeyCtrlD:
556 | if tv, ok := focused.(*tview.TextView); ok {
557 | scrollHalfPage(tv, false)
558 | return nil
559 | }
560 | case tcell.KeyCtrlF:
561 | if filterInput.HasFocus() {
562 | return tcell.NewEventKey(tcell.KeyRight, ' ', tcell.ModNone)
563 | }
564 | case tcell.KeyCtrlB:
565 | if filterInput.HasFocus() {
566 | return tcell.NewEventKey(tcell.KeyLeft, ' ', tcell.ModNone)
567 | }
568 | case tcell.KeyUp:
569 | if shift && filterInput.HasFocus() {
570 | if !isInputPaneHidden {
571 | app.SetFocus(inputView)
572 | } else {
573 | app.SetFocus(outputView)
574 | }
575 | return nil
576 | }
577 | case tcell.KeyLeft:
578 | if shift && !isInputPaneHidden {
579 | app.SetFocus(inputView)
580 | return nil
581 | }
582 | case tcell.KeyRight:
583 | if shift {
584 | app.SetFocus(outputView)
585 | return nil
586 | }
587 | case tcell.KeyDown:
588 | if shift {
589 | app.SetFocus(filterInput)
590 | return nil
591 | }
592 | case tcell.KeyTab:
593 | if inputView.HasFocus() {
594 | app.SetFocus(outputView)
595 | return nil
596 | } else if outputView.HasFocus() {
597 | app.SetFocus(filterInput)
598 | return nil
599 | } else if filterInput.HasFocus() {
600 | return tcell.NewEventKey(tcell.KeyDown, ' ', tcell.ModNone)
601 | }
602 | case tcell.KeyBacktab:
603 | if inputView.HasFocus() {
604 | app.SetFocus(filterInput)
605 | return nil
606 | } else if outputView.HasFocus() {
607 | app.SetFocus(inputView)
608 | return nil
609 | } else if filterInput.HasFocus() {
610 | return tcell.NewEventKey(tcell.KeyUp, ' ', tcell.ModNone)
611 | }
612 | case tcell.KeyCtrlO:
613 | if !isInputPaneHidden {
614 | if inputView.HasFocus() {
615 | app.SetFocus(outputView)
616 | }
617 | viewFlex.ResizeItem(inputView, 0, 0)
618 | isInputPaneHidden = true
619 | return nil
620 | } else {
621 | viewFlex.ResizeItem(inputView, 0, 1)
622 | isInputPaneHidden = false
623 | return nil
624 | }
625 | }
626 |
627 | if tv, ok := focused.(*tview.TextView); ok {
628 | switch ru := event.Rune(); ru {
629 | case '0':
630 | scrollHorizontally(tv, false)
631 | return nil
632 | case '$':
633 | scrollHorizontally(tv, true)
634 | return nil
635 | case 'd':
636 | scrollHalfPage(tv, false)
637 | return nil
638 | case 'u':
639 | scrollHalfPage(tv, true)
640 | return nil
641 | case 'b':
642 | return tcell.NewEventKey(tcell.KeyCtrlB, ' ', tcell.ModNone)
643 | case 'f':
644 | return tcell.NewEventKey(tcell.KeyCtrlF, ' ', tcell.ModNone)
645 | case 'v':
646 | if event.Modifiers()&tcell.ModAlt != 0 {
647 | return tcell.NewEventKey(tcell.KeyPgUp, ' ', tcell.ModNone)
648 | }
649 | case 'G':
650 | // tview handles G natively but does not
651 | // redraw, so the scroll indicator doesn't
652 | // update. So we handle G ourselves and force a
653 | // redraw
654 | tv.ScrollToEnd()
655 | app.ForceDraw()
656 | }
657 | }
658 |
659 | return event
660 | })
661 |
662 | app.SetBeforeDrawFunc(func(screen tcell.Screen) bool {
663 | // Start a synchronized update
664 | tty, ok := screen.Tty()
665 | if ok {
666 | tty.Write([]byte("\x1b[?2026h"))
667 | }
668 |
669 | updateScrollIndicator("Input", inputLineCount, inputView)
670 | updateScrollIndicator("Output", outputLineCount, outputView)
671 |
672 | return false
673 | })
674 |
675 | app.SetAfterDrawFunc(func(screen tcell.Screen) {
676 | // Finish a synchronized update
677 | tty, ok := screen.Tty()
678 | if ok {
679 | tty.Write([]byte("\x1b[?2026l"))
680 | }
681 | })
682 |
683 | app.SetRoot(grid, true).EnableMouse(true).SetFocus(grid)
684 |
685 | return app
686 | }
687 |
688 | func main() {
689 | // Remove log prefix
690 | log.SetFlags(0)
691 |
692 | options, filter, args := parseArgs()
693 |
694 | if _, err := exec.LookPath(options.command); err != nil {
695 | log.Fatalf("%s is not installed or could not be found: %s\n", options.command, err)
696 | }
697 |
698 | doc := Document{filter: filter, options: options}
699 |
700 | if !options.nullInput {
701 | var in io.Reader = os.Stdin
702 | if len(args) > 0 {
703 | var files []io.Reader
704 | for _, fname := range args {
705 | f, err := os.Open(fname)
706 | if err != nil {
707 | log.Fatalln(err)
708 | }
709 |
710 | defer f.Close()
711 |
712 | files = append(files, f)
713 | }
714 |
715 | in = io.MultiReader(files...)
716 | }
717 |
718 | if _, err := doc.ReadFrom(in); err != nil {
719 | log.Fatalln(err)
720 | }
721 | }
722 |
723 | app := createApp(doc)
724 | if err := app.Run(); err != nil {
725 | log.Fatalln(err)
726 | }
727 | }
728 |
--------------------------------------------------------------------------------
/COPYING:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------