├── .github └── workflows │ ├── goreadme.yml │ └── test.yml ├── LICENSE ├── README.md ├── cat.go ├── cat_test.go ├── cut.go ├── cut_test.go ├── exec.go ├── exec_test.go ├── from.go ├── from_test.go ├── go.mod ├── go.sum ├── grep.go ├── grep_test.go ├── head.go ├── head_test.go ├── ls.go ├── ls_test.go ├── modify.go ├── modify_test.go ├── sort.go ├── sort_test.go ├── stream.go ├── stream_test.go ├── testdata ├── a.txt └── b.txt ├── to.go ├── to_test.go ├── uniq.go ├── uniq_test.go ├── wc.go └── wc_test.go /.github/workflows/goreadme.yml: -------------------------------------------------------------------------------- 1 | on: 2 | pull_request: 3 | branches: [master] 4 | push: 5 | branches: [master] 6 | jobs: 7 | goreadme: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - name: Check out repository 11 | uses: actions/checkout@v2 12 | - name: Update readme according to Go doc 13 | uses: posener/goreadme@v1.2.13 14 | with: 15 | recursive: 'true' 16 | badge-codecov: 'true' 17 | badge-godoc: 'true' 18 | github-token: '${{ secrets.GITHUB_TOKEN }}' 19 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | on: 2 | pull_request: 3 | branches: [master] 4 | push: 5 | branches: [master] 6 | jobs: 7 | test: 8 | strategy: 9 | matrix: 10 | go-version: 11 | - 1.20.x 12 | platform: 13 | - ubuntu-latest 14 | - macos-latest 15 | runs-on: ${{ matrix.platform }} 16 | steps: 17 | - name: Install Go 18 | uses: actions/setup-go@v4 19 | with: 20 | go-version: ${{ matrix.go-version }} 21 | - name: Checkout code 22 | uses: actions/checkout@v2 23 | - name: Test 24 | run: go test -count=1 -v -shuffle=on -race -coverprofile=coverage.txt -covermode=atomic ./... 25 | - name: Report coverage 26 | uses: codecov/codecov-action@v1 27 | with: 28 | file: coverage.txt 29 | fail_ci_if_error: true 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # script 2 | 3 | [![codecov](https://codecov.io/gh/posener/script/branch/master/graph/badge.svg)](https://codecov.io/gh/posener/script) 4 | [![GoDoc](https://img.shields.io/badge/pkg.go.dev-doc-blue)](http://pkg.go.dev/github.com/posener/script) 5 | 6 | Package script provides helper functions to write scripts. 7 | 8 | Inspired by [https://github.com/bitfield/script](https://github.com/bitfield/script), with some improvements: 9 | 10 | * Output between streamed commands is a stream and not loaded to memory. 11 | 12 | * Better representation and handling of errors. 13 | 14 | * Proper incocation, usage and handling of stderr of custom commands. 15 | 16 | The script chain is represented by a 17 | [`Stream`](https://godoc.org/github.com/posener/script#Stream) object. While each command in the 18 | stream is abstracted by the [`Command`](https://godoc.org/github.com/posener/script#Command) 19 | struct. This library provides basic functionality, but can be extended freely. 20 | 21 | ## Examples 22 | 23 | ### HelloWorld 24 | 25 | A simple "hello world" example that creats a stream and pipe it to the stdout. 26 | 27 | ```golang 28 | // Create an "hello world" stream and use the ToStdout method to write it to stdout. 29 | Echo("hello world").ToStdout() 30 | ``` 31 | 32 | Output: 33 | 34 | ``` 35 | hello world 36 | ``` 37 | 38 | ### Iterate 39 | 40 | An example that shows how to iterate scanned lines. 41 | 42 | ```golang 43 | // Stream can be any stream, in this case we have echoed 3 lines. 44 | stream := Echo("first\nsecond\nthird") 45 | 46 | // To iterate over the stream lines, it is better not to read it into memory and split over the 47 | // lines, but use the `bufio.Scanner`: 48 | defer stream.Close() 49 | scanner := bufio.NewScanner(stream) 50 | for scanner.Scan() { 51 | fmt.Println(scanner.Text()) 52 | } 53 | ``` 54 | 55 | Output: 56 | 57 | ``` 58 | first 59 | second 60 | third 61 | ``` 62 | 63 | ### Through 64 | 65 | An example that shows how to create custom commands using the `Through` method with a `PipeFn` 66 | function. 67 | 68 | ```golang 69 | Echo("1\n2\n3").Through(PipeFn(func(r io.Reader) (io.Reader, error) { 70 | // Create a command that sums up all numbers in input. 71 | // 72 | // In this example we create a reader function such that the whole code will fit into the 73 | // example function body. A more proper and readable way to do it was to create a new 74 | // type with a state that implements the `io.Reader` interface. 75 | 76 | // Use buffered reader to read lines from input. 77 | buf := bufio.NewReader(r) 78 | 79 | // Store the sum of all numbers. 80 | sum := 0 81 | 82 | // Read function reads the next line and adds it to the sum. If it gets and EOF error, it 83 | // writes the sum to the output and returns an EOF. 84 | read := func(b []byte) (int, error) { 85 | // Read next line from input. 86 | line, _, err := buf.ReadLine() 87 | 88 | // if EOF write sum to output. 89 | if err == io.EOF { 90 | return copy(b, append([]byte(strconv.Itoa(sum)), '\n')), io.EOF 91 | } 92 | if err != nil { 93 | return 0, err 94 | } 95 | 96 | // Convert the line to a number and add it to the sum. 97 | if i, err := strconv.Atoi(string(line)); err == nil { 98 | sum += i 99 | } 100 | 101 | // We don't write anything to output, so we return 0 bytes with no error. 102 | return 0, nil 103 | } 104 | 105 | return readerFn(read), nil 106 | })).ToStdout() 107 | ``` 108 | 109 | Output: 110 | 111 | ``` 112 | 6 113 | ``` 114 | 115 | --- 116 | Readme created from Go doc with [goreadme](https://github.com/posener/goreadme) 117 | -------------------------------------------------------------------------------- /cat.go: -------------------------------------------------------------------------------- 1 | package script 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "io" 7 | "os" 8 | ) 9 | 10 | // Cat outputs the contents of the given files. 11 | // 12 | // Shell command: cat . 13 | func Cat(paths ...string) Stream { 14 | var ( 15 | readers []io.Reader 16 | closers multicloser 17 | merr error 18 | ) 19 | 20 | for _, path := range paths { 21 | f, err := os.Open(path) 22 | if err != nil { 23 | merr = errors.Join(merr, fmt.Errorf("open path %s: %w", path, err)) 24 | } else { 25 | readers = append(readers, f) 26 | closers = append(closers, f) 27 | } 28 | } 29 | 30 | return Stream{ 31 | r: readcloser{Reader: io.MultiReader(readers...), Closer: closers}, 32 | stage: "cat", 33 | err: merr, 34 | } 35 | } 36 | 37 | type multicloser []io.Closer 38 | 39 | func (mc multicloser) Close() error { 40 | var merr error 41 | for _, c := range mc { 42 | if err := c.Close(); err != nil { 43 | merr = errors.Join(merr, err) 44 | } 45 | } 46 | return merr 47 | } 48 | -------------------------------------------------------------------------------- /cat_test.go: -------------------------------------------------------------------------------- 1 | package script 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | "github.com/stretchr/testify/require" 8 | ) 9 | 10 | func TestCat(t *testing.T) { 11 | t.Parallel() 12 | 13 | t.Run("One file", func(t *testing.T) { 14 | got, err := Cat("testdata/a.txt").ToString() 15 | require.NoError(t, err) 16 | assert.Equal(t, "a\n", got) 17 | }) 18 | 19 | t.Run("Multiple files", func(t *testing.T) { 20 | got, err := Cat("testdata/a.txt", "testdata/b.txt").ToString() 21 | require.NoError(t, err) 22 | assert.Equal(t, "a\nbb\n", got) 23 | }) 24 | 25 | t.Run("No such file", func(t *testing.T) { 26 | got, err := Cat("testdata/c.txt").ToString() 27 | assert.Error(t, err) 28 | assert.Equal(t, "", got) 29 | }) 30 | } 31 | -------------------------------------------------------------------------------- /cut.go: -------------------------------------------------------------------------------- 1 | package script 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | ) 7 | 8 | // Cut takes selected fields from each line. The fields are 1 based (first field is 1). 9 | // 10 | // Shell command: `cut -f`. 11 | func (s Stream) Cut(fields ...int) Stream { 12 | return s.Modify(Cut{Fields: fields}) 13 | } 14 | 15 | // Cut is a `Modifier` that takes selected fields from each line according to a given delimiter. 16 | // The default delimiter is tab. 17 | // 18 | // Shell command: `cut -d -f`. 19 | type Cut struct { 20 | // Fields defines which fields will be collected to the output of the command. The fields are 1 21 | // based (first field is 1). 22 | Fields []int 23 | // Delim is the delimited by which the fields of each line are sparated. 24 | Delim []byte 25 | } 26 | 27 | func (c Cut) Modify(line []byte) (modifed []byte, err error) { 28 | if line == nil { 29 | return nil, nil 30 | } 31 | if len(c.Fields) == 0 { 32 | return nil, nil 33 | } 34 | if len(c.Delim) == 0 { 35 | c.Delim = []byte{'\t'} 36 | } 37 | 38 | parts := bytes.Split(line, c.Delim) 39 | out := make([][]byte, 0, len(parts)) 40 | for _, i := range c.Fields { 41 | i-- // Fields are 1 based, translate to zero base. 42 | if i < len(parts) { 43 | out = append(out, parts[i]) 44 | } 45 | } 46 | return append(bytes.Join(out, c.Delim), '\n'), nil 47 | } 48 | 49 | func (c Cut) Name() string { 50 | return fmt.Sprintf("cut(%v, delim=%v)", c.Fields, c.Delim) 51 | } 52 | -------------------------------------------------------------------------------- /cut_test.go: -------------------------------------------------------------------------------- 1 | package script 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | "github.com/stretchr/testify/require" 8 | ) 9 | 10 | func TestCut(t *testing.T) { 11 | t.Parallel() 12 | 13 | t.Run("multiple lines", func(t *testing.T) { 14 | got, err := Echo("a\tbb\tccc\nddd\tee\tf").Cut(1, 3).ToString() 15 | require.NoError(t, err) 16 | assert.Equal(t, "a\tccc\nddd\tf\n", got) 17 | }) 18 | 19 | t.Run("double separator", func(t *testing.T) { 20 | got, err := Echo("a\t\tb").Cut(1, 2).ToString() 21 | require.NoError(t, err) 22 | assert.Equal(t, "a\t\n", got) 23 | }) 24 | 25 | t.Run("field out of range", func(t *testing.T) { 26 | got, err := Echo("a\tb").Cut(1, 3).ToString() 27 | require.NoError(t, err) 28 | assert.Equal(t, "a\n", got) 29 | }) 30 | 31 | t.Run("custom delimiter", func(t *testing.T) { 32 | got, err := Echo("a b c").Modify(Cut{Delim: []byte{' '}, Fields: []int{1, 3}}).ToString() 33 | require.NoError(t, err) 34 | assert.Equal(t, "a c\n", got) 35 | }) 36 | } 37 | -------------------------------------------------------------------------------- /exec.go: -------------------------------------------------------------------------------- 1 | package script 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "io" 7 | "os/exec" 8 | ) 9 | 10 | // Exec executes a command and returns a stream of the stdout of the command. 11 | func Exec(cmd string, args ...string) Stream { 12 | return From("empty", nil).Through(exe{cmd: cmd, args: args}) 13 | } 14 | 15 | // ExecHandleStderr executes a command, returns a stream of the stdout of the command and enable 16 | // collecting the stderr of the command. 17 | // 18 | // If the stderr is nil, it will be ignored. 19 | // 20 | // For example, collecting the stderr to memory can be done by providing a `&bytes.Buffer` as 21 | // `stderr`. Writing it to stderr can be done by providing `os.Stderr` as `stderr`. Logging it 22 | // to a file can be done by providing an `os.File` as the `stderr`. 23 | func ExecHandleStderr(stderr io.Writer, cmd string, args ...string) Stream { 24 | return From("empty", nil).Through(exe{cmd: cmd, args: args, stderr: stderr}) 25 | } 26 | 27 | // Exec executes a command and returns a stream of the stdout of the command. 28 | func (s Stream) Exec(cmd string, args ...string) Stream { 29 | return s.Through(exe{cmd: cmd, args: args}) 30 | } 31 | 32 | // ExecHandleStderr executes a command, returns a stream of the stdout of the command and enable 33 | // collecting the stderr of the command. 34 | // 35 | // If the stderr is nil, it will be ignored. 36 | func (s Stream) ExecHandleStderr(stderr io.Writer, cmd string, args ...string) Stream { 37 | return s.Through(exe{cmd: cmd, args: args, stderr: stderr}) 38 | } 39 | 40 | type exe struct { 41 | cmd string 42 | args []string 43 | stderr io.Writer 44 | } 45 | 46 | func (e exe) Name() string { 47 | return fmt.Sprintf("exec(%v, %+v)", e.cmd, e.args) 48 | } 49 | 50 | func (e exe) Pipe(stdin io.Reader) (io.Reader, error) { 51 | cmd := exec.Command(e.cmd, e.args...) 52 | var merr error 53 | 54 | // Pipe previous stdin if available. 55 | if stdin != nil { 56 | cmd.Stdin = stdin 57 | } 58 | 59 | // Pipe stdout to the current command output. 60 | cmdOut, err := cmd.StdoutPipe() 61 | if err != nil { 62 | merr = errors.Join(merr, fmt.Errorf("pipe stdout: %w", err)) 63 | } 64 | 65 | if e.stderr == nil { 66 | e.stderr = io.Discard 67 | } 68 | cmd.Stderr = e.stderr 69 | 70 | // start the process 71 | err = cmd.Start() 72 | if err != nil { 73 | merr = errors.Join(merr, fmt.Errorf("start process: %w", err)) 74 | } 75 | return readcloser{ 76 | Reader: cmdOut, 77 | Closer: closerFn(func() error { return cmd.Wait() }), 78 | }, merr 79 | } 80 | 81 | type closerFn func() error 82 | 83 | func (f closerFn) Close() error { return f() } 84 | -------------------------------------------------------------------------------- /exec_test.go: -------------------------------------------------------------------------------- 1 | package script 2 | 3 | import ( 4 | "bytes" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | "github.com/stretchr/testify/require" 9 | ) 10 | 11 | func TestExec(t *testing.T) { 12 | t.Parallel() 13 | 14 | t.Run("without stdin", func(t *testing.T) { 15 | stdout, err := Exec("echo", "hello world").ToString() 16 | 17 | require.NoError(t, err) 18 | assert.Equal(t, "hello world\n", stdout) 19 | }) 20 | 21 | t.Run("with stdin", func(t *testing.T) { 22 | stdout, err := Echo("hello world").Exec("cat").ToString() 23 | 24 | require.NoError(t, err) 25 | assert.Equal(t, "hello world\n", stdout) 26 | }) 27 | 28 | t.Run("exit code", func(t *testing.T) { 29 | stdout, err := Exec("false").ToString() 30 | 31 | assert.Error(t, err) 32 | assert.Equal(t, "", stdout) 33 | }) 34 | 35 | t.Run("stderr", func(t *testing.T) { 36 | var stderr bytes.Buffer 37 | stdout, err := ExecHandleStderr(&stderr, "cat", "no-such-file", "testdata/a.txt").ToString() 38 | 39 | assert.Error(t, err) 40 | assert.Equal(t, "a\n", stdout) // Content of testdata/a.txt 41 | assert.Equal(t, "cat: no-such-file: No such file or directory\n", stderr.String()) 42 | }) 43 | } 44 | -------------------------------------------------------------------------------- /from.go: -------------------------------------------------------------------------------- 1 | package script 2 | 3 | import ( 4 | "bytes" 5 | "io" 6 | "os" 7 | "strings" 8 | ) 9 | 10 | // From creates a stream from a reader. 11 | func From(name string, r io.Reader) Stream { 12 | return Stream{stage: name, r: r} 13 | } 14 | 15 | // Writer creates a stream from a function that writes to a writer. 16 | func Writer(name string, writer func(io.Writer) error) Stream { 17 | b := bytes.NewBuffer(nil) 18 | err := writer(b) 19 | return Stream{stage: name, r: b, err: err} 20 | } 21 | 22 | // Stdin starts a stream from stdin. 23 | func Stdin() Stream { 24 | stdin := io.NopCloser(os.Stdin) // Prevent closing of stdin. 25 | return From("stdin", stdin) 26 | } 27 | 28 | // Echo writes to stdout. 29 | // 30 | // Shell command: `echo ` 31 | func Echo(s string) Stream { 32 | return From("echo", strings.NewReader(s+"\n")) 33 | } 34 | -------------------------------------------------------------------------------- /from_test.go: -------------------------------------------------------------------------------- 1 | package script 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "io" 7 | "io/ioutil" 8 | "os" 9 | "testing" 10 | 11 | "github.com/stretchr/testify/assert" 12 | "github.com/stretchr/testify/require" 13 | ) 14 | 15 | func TestEcho(t *testing.T) { 16 | t.Parallel() 17 | 18 | s, err := Echo("hello world").ToString() 19 | require.NoError(t, err) 20 | assert.Equal(t, "hello world\n", s) 21 | } 22 | 23 | func TestStdin(t *testing.T) { 24 | // Create a temporary file to fake stdin. 25 | fakeStdin, err := ioutil.TempFile("", "") 26 | require.NoError(t, err) 27 | defer os.Remove(fakeStdin.Name()) 28 | defer fakeStdin.Close() 29 | _, err = fakeStdin.WriteString("hello world\n") 30 | require.NoError(t, err) 31 | _, err = fakeStdin.Seek(0, 0) 32 | require.NoError(t, err) 33 | 34 | // Temporarely replace stdin with the temporary file. 35 | stdin := os.Stdin 36 | os.Stdin = fakeStdin 37 | defer func() { os.Stdin = stdin }() 38 | 39 | // Test 40 | s, err := Stdin().ToString() 41 | require.NoError(t, err) 42 | assert.Equal(t, "hello world\n", s) 43 | } 44 | 45 | func TestWriter(t *testing.T) { 46 | t.Parallel() 47 | got, err := Writer("json", func(w io.Writer) error { return json.NewEncoder(w).Encode("foo") }).ToString() 48 | require.NoError(t, err) 49 | assert.Equal(t, "\"foo\"\n", got) 50 | } 51 | 52 | func TestWriter_failure(t *testing.T) { 53 | t.Parallel() 54 | _, err := Writer("fail", func(w io.Writer) error { return errors.New("failed") }).ToString() 55 | assert.Error(t, err) 56 | } 57 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/posener/script 2 | 3 | go 1.20 4 | 5 | require github.com/stretchr/testify v1.8.4 6 | 7 | require ( 8 | github.com/davecgh/go-spew v1.1.1 // indirect 9 | github.com/pmezard/go-difflib v1.0.0 // indirect 10 | gopkg.in/yaml.v3 v3.0.1 // indirect 11 | ) 12 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 2 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 4 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 5 | github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= 6 | github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= 7 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 8 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 9 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 10 | -------------------------------------------------------------------------------- /grep.go: -------------------------------------------------------------------------------- 1 | package script 2 | 3 | import ( 4 | "fmt" 5 | "regexp" 6 | ) 7 | 8 | // Grep filters only line that match the given regexp. 9 | // 10 | // Shell command: `grep `. 11 | func (s Stream) Grep(re *regexp.Regexp) Stream { 12 | return s.Modify(Grep{Re: re}) 13 | } 14 | 15 | // Grep is a modifier that filters only line that match `Re`. If Invert was set only line that did 16 | // not match the regex will be returned. 17 | // 18 | // Usage: 19 | // 20 | // ().Modify(script.Grep{Re: }) 21 | // 22 | // Shell command: `grep [-v ] `. 23 | type Grep struct { 24 | Re *regexp.Regexp 25 | Inverse bool 26 | } 27 | 28 | func (g Grep) Modify(line []byte) (modifed []byte, err error) { 29 | if line == nil { 30 | return nil, nil 31 | } 32 | if g.Re.Match(line) != g.Inverse { 33 | return append(line, '\n'), nil 34 | } 35 | return nil, nil 36 | } 37 | 38 | func (g Grep) Name() string { 39 | return fmt.Sprintf("grep(%v, invert=%v)", g.Re, g.Inverse) 40 | } 41 | -------------------------------------------------------------------------------- /grep_test.go: -------------------------------------------------------------------------------- 1 | package script 2 | 3 | import ( 4 | "regexp" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | "github.com/stretchr/testify/require" 9 | ) 10 | 11 | func TestGrep(t *testing.T) { 12 | t.Parallel() 13 | 14 | t.Run("grep", func(t *testing.T) { 15 | got, err := Echo("a\nb\na\nc").Grep(regexp.MustCompile(`^a`)).ToString() 16 | require.NoError(t, err) 17 | assert.Equal(t, "a\na\n", got) 18 | }) 19 | 20 | t.Run("invert", func(t *testing.T) { 21 | got, err := Echo("a\nb\na\nc").Modify(Grep{Re: regexp.MustCompile(`^a`), Inverse: true}).ToString() 22 | require.NoError(t, err) 23 | assert.Equal(t, "b\nc\n", got) 24 | }) 25 | } 26 | -------------------------------------------------------------------------------- /head.go: -------------------------------------------------------------------------------- 1 | package script 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "io" 7 | ) 8 | 9 | // Head reads only the n first lines of the given reader. If n is a negative number, all lines 10 | // besides last n lines will be read. 11 | // 12 | // Shell command: `head -n ` 13 | func (s Stream) Head(n int) Stream { 14 | if n < 0 { 15 | return s.Modify(&negHead{n: -n, lines: make([][]byte, 0, -n)}) 16 | } 17 | return s.Modify(&head{n: n}) 18 | } 19 | 20 | // Tail reads only the n last lines of the given reader. If n is a negative number, all lines 21 | // besides the first n lines will be read. 22 | // 23 | // Shell command: `tail -n ` 24 | func (s Stream) Tail(n int) Stream { 25 | if n < 0 { 26 | return s.Modify(&negTail{n: -n}) 27 | } 28 | return s.Modify(&tail{n: n, lines: make([][]byte, 0, n)}) 29 | } 30 | 31 | type head struct { 32 | n int 33 | } 34 | 35 | func (h *head) Modify(line []byte) ([]byte, error) { 36 | if line == nil || h.n == 0 { 37 | return nil, io.EOF 38 | } 39 | h.n-- 40 | return append(line, '\n'), nil 41 | } 42 | 43 | func (h *head) Name() string { 44 | return fmt.Sprintf("head(%d)", h.n) 45 | } 46 | 47 | type negHead struct { 48 | n int 49 | lines [][]byte 50 | } 51 | 52 | func (h *negHead) Modify(line []byte) ([]byte, error) { 53 | if h.n == 0 { 54 | return nil, io.EOF 55 | } 56 | if line == nil { 57 | return nil, io.EOF 58 | } 59 | 60 | // Still got room in the buffer, append the current line. 61 | if len(h.lines) < cap(h.lines) { 62 | h.lines = append(h.lines, line) 63 | return nil, nil 64 | } 65 | // Insert the new line and pop the first line and return it. 66 | ret := h.lines[0] 67 | for i := 0; i < len(h.lines)-1; i++ { 68 | h.lines[i] = h.lines[i+1] 69 | } 70 | h.lines[len(h.lines)-1] = line 71 | 72 | return append(ret, byte('\n')), nil 73 | } 74 | 75 | func (h *negHead) Name() string { 76 | return fmt.Sprintf("head(-%d)", h.n) 77 | } 78 | 79 | type tail struct { 80 | n int 81 | lines [][]byte 82 | } 83 | 84 | func (t *tail) Modify(line []byte) ([]byte, error) { 85 | if t.n == 0 { 86 | return nil, io.EOF 87 | } 88 | if line == nil { 89 | return append(bytes.Join(t.lines, []byte{'\n'}), '\n'), io.EOF 90 | } 91 | 92 | // Shift all lines and append the new line. 93 | if len(t.lines) < cap(t.lines) { 94 | t.lines = append(t.lines, line) 95 | } else { 96 | for i := 0; i < len(t.lines)-1; i++ { 97 | t.lines[i] = t.lines[i+1] 98 | } 99 | t.lines[len(t.lines)-1] = line 100 | } 101 | 102 | return nil, nil 103 | } 104 | 105 | func (t *tail) Name() string { 106 | return fmt.Sprintf("tail(%d)", t.n) 107 | } 108 | 109 | type negTail struct { 110 | n int 111 | } 112 | 113 | func (t *negTail) Modify(line []byte) ([]byte, error) { 114 | if line == nil { 115 | return nil, io.EOF 116 | } 117 | if t.n > 0 { 118 | t.n-- 119 | return nil, nil 120 | } 121 | return append(line, '\n'), nil 122 | } 123 | 124 | func (t *negTail) Name() string { 125 | return fmt.Sprintf("tail(-%d)", t.n) 126 | } 127 | -------------------------------------------------------------------------------- /head_test.go: -------------------------------------------------------------------------------- 1 | package script 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | "github.com/stretchr/testify/require" 9 | ) 10 | 11 | func TestHeadTail(t *testing.T) { 12 | t.Parallel() 13 | 14 | const text = "a\nbb\nccc" 15 | const text2 = "a\r\nbb\r\nccc" 16 | 17 | tests := []struct { 18 | src string 19 | n int 20 | head string 21 | tail string 22 | }{ 23 | {src: text, n: -3, head: "", tail: ""}, 24 | {src: text, n: -2, head: "a\n", tail: "ccc\n"}, 25 | {src: text, n: -1, head: "a\nbb\n", tail: "bb\nccc\n"}, 26 | {src: text, n: 0, head: "", tail: ""}, 27 | {src: text, n: 1, head: "a\n", tail: "ccc\n"}, 28 | {src: text, n: 2, head: "a\nbb\n", tail: "bb\nccc\n"}, 29 | {src: text, n: 3, head: "a\nbb\nccc\n", tail: "a\nbb\nccc\n"}, 30 | 31 | // {src: text2, n: -3, head: "", tail: ""}, 32 | // {src: text2, n: -2, head: "", tail: ""}, 33 | // {src: text2, n: -1, head: "bb\n", tail: "a\n"}, 34 | // {src: text2, n: 0, head: "", tail: ""}, 35 | // {src: text2, n: 1, head: "a\n", tail: "bb\n"}, 36 | // {src: text2, n: 2, head: "a\nbb\n", tail: "a\nbb\n"}, 37 | // {src: text2, n: 3, head: "a\nbb\n", tail: "a\nbb\n"}, 38 | } 39 | 40 | for _, tt := range tests { 41 | t.Run(fmt.Sprintf("head/%s/%d", tt.src, tt.n), func(t *testing.T) { 42 | got, err := Echo(tt.src).Head(tt.n).ToString() 43 | require.NoError(t, err) 44 | assert.Equal(t, tt.head, got) 45 | }) 46 | t.Run(fmt.Sprintf("tail/%s/%d", tt.src, tt.n), func(t *testing.T) { 47 | got, err := Echo(tt.src).Tail(tt.n).ToString() 48 | require.NoError(t, err) 49 | assert.Equal(t, tt.tail, got) 50 | }) 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /ls.go: -------------------------------------------------------------------------------- 1 | package script 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "io" 7 | "os" 8 | "path/filepath" 9 | ) 10 | 11 | // Files is a stream of a list of files. A user can either use the file list directly or the the 12 | // created stream. In the stream, each line contains a path to a file. 13 | type Files struct { 14 | Stream 15 | Files []FileInfo 16 | } 17 | 18 | // File contains information about a file. 19 | type FileInfo struct { 20 | // FileInfo contains information about the file. 21 | os.FileInfo 22 | // Path is the path of the file. It may be relative or absolute, depending on how the `Ls` 23 | // command was invoked. 24 | Path string 25 | } 26 | 27 | // Ls returns a stream of a list files. In the returned stream, each line will contain a path to 28 | // a single file. 29 | // 30 | // If the provided paths list is empty, the local directory will be listed. 31 | // 32 | // The provided paths may be relative to the local directory or absolute - this will influence the 33 | // format of the returned paths in the output. 34 | // 35 | // If some provided paths correlate to the arguments correlate to the same file, it will also appear 36 | // multiple times in the output. 37 | // 38 | // If any of the paths fails to be listed, it will result in an error in the output, but the stream 39 | // will still conain all paths that were successfully listed. 40 | // 41 | // Shell command: `ls`. 42 | func Ls(paths ...string) Files { 43 | // Default to local directory. 44 | if len(paths) == 0 { 45 | paths = append(paths, ".") 46 | } 47 | 48 | var ( 49 | files []FileInfo 50 | merr error 51 | ) 52 | 53 | for _, path := range paths { 54 | info, err := os.Stat(path) 55 | if err != nil { 56 | merr = errors.Join(merr, fmt.Errorf("stat path %s: %w", path, err)) 57 | continue 58 | } 59 | 60 | // Path is a single file. 61 | if !info.IsDir() { 62 | files = append(files, FileInfo{Path: path, FileInfo: info}) 63 | continue 64 | } 65 | 66 | // Path is a directory. 67 | dirEntries, err := os.ReadDir(path) 68 | if err != nil { 69 | merr = errors.Join(merr, fmt.Errorf("read dir %s: %w", path, err)) 70 | continue 71 | } 72 | 73 | for _, entry := range dirEntries { 74 | info, err := entry.Info() 75 | if err != nil { 76 | merr = errors.Join(merr, fmt.Errorf("failed to get file info from dir entry: %w", err)) 77 | } 78 | files = append(files, FileInfo{Path: filepath.Join(path, info.Name()), FileInfo: info}) 79 | } 80 | } 81 | 82 | return Files{ 83 | Stream: Stream{ 84 | stage: fmt.Sprintf("ls (%+v)", paths), 85 | r: &filesReader{files: files}, 86 | err: merr, 87 | }, 88 | Files: files, 89 | } 90 | } 91 | 92 | // filesReader reads from a file info list. 93 | type filesReader struct { 94 | files []FileInfo 95 | // seek indicates which file to write for the next Read function call. 96 | seek int 97 | } 98 | 99 | func (f *filesReader) Read(out []byte) (int, error) { 100 | if f.seek >= len(f.files) { 101 | return 0, io.EOF 102 | } 103 | 104 | line := []byte(f.files[f.seek].Path + "\n") 105 | f.seek++ 106 | 107 | n := copy(out, line) 108 | return n, nil 109 | } 110 | -------------------------------------------------------------------------------- /ls_test.go: -------------------------------------------------------------------------------- 1 | package script 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | "github.com/stretchr/testify/require" 8 | ) 9 | 10 | func TestLs(t *testing.T) { 11 | t.Parallel() 12 | 13 | tests := []struct { 14 | name string 15 | paths []string 16 | wantError bool 17 | want string 18 | }{ 19 | { 20 | name: "single file", 21 | paths: []string{"testdata/a.txt"}, 22 | want: "testdata/a.txt\n", 23 | }, 24 | { 25 | name: "directory", 26 | paths: []string{"testdata"}, 27 | want: "testdata/a.txt\ntestdata/b.txt\n", 28 | }, 29 | { 30 | name: "multiple paths", 31 | paths: []string{"testdata", "testdata/a.txt"}, 32 | want: "testdata/a.txt\ntestdata/b.txt\ntestdata/a.txt\n", 33 | }, 34 | { 35 | name: "error", 36 | paths: []string{"no-such-file"}, 37 | wantError: true, 38 | want: "", 39 | }, 40 | { 41 | name: "error with successful path", 42 | paths: []string{"no-such-file", "testdata/a.txt"}, 43 | wantError: true, 44 | want: "testdata/a.txt\n", 45 | }, 46 | } 47 | 48 | for _, tt := range tests { 49 | t.Run(tt.name, func(t *testing.T) { 50 | got, err := Ls(tt.paths...).ToString() 51 | require.Equal(t, tt.wantError, err != nil) 52 | assert.Equal(t, tt.want, got) 53 | }) 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /modify.go: -------------------------------------------------------------------------------- 1 | package script 2 | 3 | import ( 4 | "bufio" 5 | "io" 6 | "reflect" 7 | ) 8 | 9 | // Modifier modifies input lines to output. On each line of the input the Modify method is called, 10 | // and the modifier can change it, omit it, or break the iteration. 11 | type Modifier interface { 12 | // Modify a line. The input of this function will always be a single line from the input of the 13 | // stream, without the trailing '\n'. It should return the output of the stream and should 14 | // append a trailing '\n' if it want it to be a line in the output. 15 | // 16 | // When EOF of input stream is met, the function will be called once more with a nil line value 17 | // to enable output any buffered data. 18 | // 19 | // When the return modified value is nil, the line will be discarded. 20 | // 21 | // When the returned eof value is true, the Read will return that error. 22 | Modify(line []byte) (modifed []byte, err error) 23 | // Name returns the name of the command that will represent this modifier. 24 | Name() string 25 | } 26 | 27 | // ModifyFn is a function for modifying input lines. 28 | type ModifyFn func(line []byte) (modifed []byte, err error) 29 | 30 | func (m ModifyFn) Modify(line []byte) (modifed []byte, err error) { return m(line) } 31 | 32 | func (m ModifyFn) Name() string { return reflect.TypeOf(m).Name() } 33 | 34 | // Modify applies modifier on every line of the input. 35 | func (s Stream) Modify(modifier Modifier) Stream { 36 | return s.Through(modPipe{Modifier: modifier}) 37 | } 38 | 39 | // modPipe takes a Modifier and exposes the Pipe interface. 40 | type modPipe struct { 41 | Modifier 42 | r *bufio.Reader 43 | // partialOut stores leftover of a line that was not fully read by output. 44 | partialOut []byte 45 | err error 46 | } 47 | 48 | func (m modPipe) Pipe(stdin io.Reader) (io.Reader, error) { 49 | m.r = bufio.NewReader(stdin) 50 | return &m, nil 51 | } 52 | 53 | func (m modPipe) Close() error { 54 | if m.err == io.EOF { 55 | return nil 56 | } 57 | return m.err 58 | } 59 | 60 | func (m *modPipe) Read(out []byte) (n int, err error) { 61 | if len(m.partialOut) > 0 { 62 | m.partialOut, n = copyBytes(out, m.partialOut) 63 | return n, nil 64 | } 65 | if m.err != nil { 66 | return 0, m.err 67 | } 68 | 69 | // partialIn stores a line that was not fully read from input. 70 | var partialIn []byte 71 | 72 | for { 73 | line, isPrefix, err := m.r.ReadLine() 74 | if err != nil { 75 | if err != io.EOF { 76 | return 0, err 77 | } 78 | // Remember that we have EOF for next read call. 79 | m.err = io.EOF 80 | } 81 | if len(partialIn) > 0 { 82 | line = append(partialIn, line...) 83 | partialIn = nil 84 | } 85 | if isPrefix { 86 | partialIn = line 87 | continue 88 | } 89 | 90 | line, err = m.Modifier.Modify(line) 91 | if err != nil { 92 | m.err = err 93 | } 94 | 95 | m.partialOut, n = copyBytes(out, line) 96 | // If n is zero and err is nil, don't return. Otherwise, scanner.Scanners will 97 | // return io.ErrNoProgress when (0, nil) is returned too many times. 98 | if n == 0 && m.err == nil { 99 | continue 100 | } 101 | return n, nil 102 | } 103 | } 104 | 105 | func copyBytes(dst, src []byte) (leftover []byte, n int) { 106 | n = len(src) 107 | if n > len(dst) { 108 | n = len(dst) 109 | } 110 | copy(dst[:n], src[:n]) 111 | return src[n:], n 112 | } 113 | -------------------------------------------------------------------------------- /modify_test.go: -------------------------------------------------------------------------------- 1 | package script 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "io" 7 | "regexp" 8 | "strings" 9 | "testing" 10 | 11 | "github.com/stretchr/testify/assert" 12 | "github.com/stretchr/testify/require" 13 | ) 14 | 15 | func testModifier(in []byte) ([]byte, error) { 16 | // In case of EOF: 17 | if in == nil { 18 | return nil, nil 19 | } 20 | 21 | in = append([]byte{'@'}, in...) 22 | return append(in, '@', '\n'), nil 23 | } 24 | 25 | func testEOFModifier(in []byte) ([]byte, error) { 26 | return nil, io.EOF 27 | } 28 | 29 | func testErrorModifier(in []byte) ([]byte, error) { 30 | return nil, fmt.Errorf("error") 31 | } 32 | 33 | func TestModify(t *testing.T) { 34 | t.Parallel() 35 | // Create line that is long enough such that it won't be read in a single bufio read-line 36 | // of 4096 bytes. 37 | longLine := strings.Repeat("a", 10000) 38 | 39 | tests := []struct { 40 | name string 41 | input string 42 | modifier Modifier 43 | want string 44 | }{ 45 | { 46 | name: "simple", 47 | modifier: ModifyFn(testModifier), 48 | input: "a\nb\nc", 49 | want: "@a@\n@b@\n@c@\n", 50 | }, 51 | { 52 | name: "long line correctness", 53 | modifier: ModifyFn(testModifier), 54 | input: longLine + "\n" + longLine, 55 | want: "@" + longLine + "@\n@" + longLine + "@\n", 56 | }, 57 | { 58 | name: "eof handling", 59 | modifier: ModifyFn(testEOFModifier), 60 | input: "a", 61 | want: "", 62 | }, 63 | } 64 | 65 | for _, tt := range tests { 66 | t.Run(tt.name, func(t *testing.T) { 67 | got, err := Echo(tt.input).Modify(tt.modifier).ToString() 68 | require.NoError(t, err) 69 | assert.Equal(t, tt.want, got) 70 | }) 71 | } 72 | } 73 | 74 | func TestModify_error(t *testing.T) { 75 | t.Parallel() 76 | got, err := Echo("a").Modify(ModifyFn(testErrorModifier)).ToString() 77 | assert.Error(t, err) 78 | assert.Equal(t, "", got) 79 | } 80 | 81 | func TestModify_Read_ErrNoProgress(t *testing.T) { 82 | t.Parallel() 83 | var sb strings.Builder 84 | for i := 0; i < 101*2; i++ { 85 | sb.WriteString("foo\n") 86 | } 87 | s := Echo(sb.String()).Grep(regexp.MustCompile("^bar$")) 88 | scanner := bufio.NewScanner(s) 89 | for scanner.Scan() { 90 | } 91 | assert.NoError(t, scanner.Err()) 92 | } 93 | -------------------------------------------------------------------------------- /sort.go: -------------------------------------------------------------------------------- 1 | package script 2 | 3 | import ( 4 | "bufio" 5 | "errors" 6 | "fmt" 7 | "sort" 8 | "strings" 9 | ) 10 | 11 | // Sort returns a stream with lines ordered alphabetically. 12 | // 13 | // Shell command: `wc`. 14 | func (s Stream) Sort(reverse bool) Stream { 15 | var ( 16 | lines []string 17 | merr error 18 | ) 19 | scanner := bufio.NewScanner(s.r) 20 | for scanner.Scan() { 21 | lines = append(lines, scanner.Text()) 22 | } 23 | if err := scanner.Err(); err != nil { 24 | merr = errors.Join(merr, fmt.Errorf("scanning stream: %w", err)) 25 | } 26 | 27 | sort.Slice(lines, func(i, j int) bool { return (lines[i] < lines[j]) != reverse }) 28 | 29 | var out strings.Builder 30 | for _, line := range lines { 31 | _, err := out.WriteString(line + "\n") 32 | if err != nil { 33 | merr = errors.Join(merr, fmt.Errorf("writing line %q: %w", line, err)) 34 | } 35 | } 36 | 37 | return Stream{ 38 | stage: fmt.Sprintf("sort(%v)", reverse), 39 | r: strings.NewReader(out.String()), 40 | err: merr, 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /sort_test.go: -------------------------------------------------------------------------------- 1 | package script 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | "github.com/stretchr/testify/require" 8 | ) 9 | 10 | func TestSort(t *testing.T) { 11 | t.Parallel() 12 | 13 | t.Run("sort", func(t *testing.T) { 14 | out, err := Echo("ab\na\nb").Sort(false).ToString() 15 | require.NoError(t, err) 16 | assert.Equal(t, "a\nab\nb\n", out) 17 | }) 18 | 19 | t.Run("sort reversed", func(t *testing.T) { 20 | out, err := Echo("ab\na\nb").Sort(true).ToString() 21 | require.NoError(t, err) 22 | assert.Equal(t, "b\nab\na\n", out) 23 | }) 24 | } 25 | -------------------------------------------------------------------------------- /stream.go: -------------------------------------------------------------------------------- 1 | // Package script provides helper functions to write scripts. 2 | // 3 | // Inspired by https://github.com/bitfield/script, with some improvements: 4 | // 5 | // * Output between streamed commands is a stream and not loaded to memory. 6 | // 7 | // * Better representation and handling of errors. 8 | // 9 | // * Proper incocation, usage and handling of stderr of custom commands. 10 | // 11 | // The script chain is represented by a 12 | // (`Stream`) https://godoc.org/github.com/posener/script#Stream object. While each command in the 13 | // stream is abstracted by the (`Command`) https://godoc.org/github.com/posener/script#Command 14 | // struct. This library provides basic functionality, but can be extended freely. 15 | package script 16 | 17 | import ( 18 | "errors" 19 | "io" 20 | "reflect" 21 | ) 22 | 23 | // Stream is a chain of operations on a stream of bytes. The stdout of each operation in the stream 24 | // feeds the following operation stdin. The stream object have different methods that allow 25 | // manipulating it, most of them resemble well known linux commands. 26 | // 27 | // A custom modifier can be used with the `Through` or with the `Modify` functions. 28 | // 29 | // The stream object is created by some in this library or from any `io.Reader` using the `From` 30 | // function. It can be dumped using some functions in this library, to a custom reader using the 31 | // `To` method. 32 | type Stream struct { 33 | // r is the output reader of this stream. If r also implements the `io.Closer` interface, it 34 | // will be closed when the stream is closed. 35 | r io.Reader 36 | // stage is the name of the current stage in the stream. 37 | stage string 38 | // parent points to the stage before the current stage in the stream. 39 | parent *Stream 40 | // err contains an error from the current stage in the stream. 41 | err error 42 | } 43 | 44 | // Read can be used to read from the stream. 45 | func (s Stream) Read(b []byte) (int, error) { 46 | return s.r.Read(b) 47 | } 48 | 49 | // Close closes all the stages in the stream and return the errors that occurred in all of the 50 | // stages. 51 | func (s Stream) Close() error { 52 | var merr error 53 | for cur := &s; cur != nil; cur = cur.parent { 54 | if cur.err != nil { 55 | merr = errors.Join(merr, cur.err) 56 | } 57 | if closer, ok := cur.r.(io.Closer); ok { 58 | if err := closer.Close(); err != nil { 59 | merr = errors.Join(merr, err) 60 | } 61 | } 62 | } 63 | return merr 64 | } 65 | 66 | // Through passes the current stream through a pipe. This function can be used to add custom 67 | // commands that are not available in this library. 68 | func (s Stream) Through(pipe Pipe) Stream { 69 | r, err := pipe.Pipe(s.r) 70 | if r == nil { 71 | panic("a command must contain a reader") 72 | } 73 | return Stream{ 74 | stage: pipe.Name(), 75 | r: r, 76 | err: err, 77 | parent: &s, 78 | } 79 | } 80 | 81 | // Pipe reads from a reader and returns another reader. 82 | type Pipe interface { 83 | // Pipe gets a reader and returns another reader. A pipe may return an error and a reader 84 | // together. 85 | Pipe(stdin io.Reader) (io.Reader, error) 86 | // Name of pipe. 87 | Name() string 88 | } 89 | 90 | // PipeFn is a function that implements Pipe. 91 | type PipeFn func(io.Reader) (io.Reader, error) 92 | 93 | func (f PipeFn) Pipe(stdin io.Reader) (io.Reader, error) { return f(stdin) } 94 | 95 | func (f PipeFn) Name() string { return reflect.TypeOf(f).Name() } 96 | 97 | type readcloser struct { 98 | io.Reader 99 | io.Closer 100 | } 101 | -------------------------------------------------------------------------------- /stream_test.go: -------------------------------------------------------------------------------- 1 | package script 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "io" 7 | "strconv" 8 | ) 9 | 10 | // A simple "hello world" example that creats a stream and pipe it to the stdout. 11 | func Example_helloWorld() { 12 | // Create an "hello world" stream and use the ToStdout method to write it to stdout. 13 | Echo("hello world").ToStdout() 14 | 15 | // Output: hello world 16 | } 17 | 18 | // An example that shows how to iterate scanned lines. 19 | func Example_iterate() { 20 | // Stream can be any stream, in this case we have echoed 3 lines. 21 | stream := Echo("first\nsecond\nthird") 22 | 23 | // To iterate over the stream lines, it is better not to read it into memory and split over the 24 | // lines, but use the `bufio.Scanner`: 25 | defer stream.Close() 26 | scanner := bufio.NewScanner(stream) 27 | for scanner.Scan() { 28 | fmt.Println(scanner.Text()) 29 | } 30 | 31 | // Output: first 32 | // second 33 | // third 34 | } 35 | 36 | // An example that shows how to create custom commands using the `Through` method with a `PipeFn` 37 | // function. 38 | func Example_through() { 39 | Echo("1\n2\n3").Through(PipeFn(func(r io.Reader) (io.Reader, error) { 40 | // Create a command that sums up all numbers in input. 41 | // 42 | // In this example we create a reader function such that the whole code will fit into the 43 | // example function body. A more proper and readable way to do it was to create a new 44 | // type with a state that implements the `io.Reader` interface. 45 | 46 | // Use buffered reader to read lines from input. 47 | buf := bufio.NewReader(r) 48 | 49 | // Store the sum of all numbers. 50 | sum := 0 51 | 52 | // Read function reads the next line and adds it to the sum. If it gets and EOF error, it 53 | // writes the sum to the output and returns an EOF. 54 | read := func(b []byte) (int, error) { 55 | // Read next line from input. 56 | line, _, err := buf.ReadLine() 57 | 58 | // if EOF write sum to output. 59 | if err == io.EOF { 60 | return copy(b, append([]byte(strconv.Itoa(sum)), '\n')), io.EOF 61 | } 62 | if err != nil { 63 | return 0, err 64 | } 65 | 66 | // Convert the line to a number and add it to the sum. 67 | if i, err := strconv.Atoi(string(line)); err == nil { 68 | sum += i 69 | } 70 | 71 | // We don't write anything to output, so we return 0 bytes with no error. 72 | return 0, nil 73 | } 74 | 75 | return readerFn(read), nil 76 | })).ToStdout() 77 | 78 | // Output: 6 79 | } 80 | 81 | type readerFn func(b []byte) (int, error) 82 | 83 | func (f readerFn) Read(b []byte) (int, error) { 84 | return f(b) 85 | } 86 | -------------------------------------------------------------------------------- /testdata/a.txt: -------------------------------------------------------------------------------- 1 | a 2 | -------------------------------------------------------------------------------- /testdata/b.txt: -------------------------------------------------------------------------------- 1 | bb 2 | -------------------------------------------------------------------------------- /to.go: -------------------------------------------------------------------------------- 1 | package script 2 | 3 | import ( 4 | "bytes" 5 | "errors" 6 | "io" 7 | "os" 8 | "path/filepath" 9 | ) 10 | 11 | // To writes the output of the stream to an io.Writer and closes it. 12 | func (s Stream) To(w io.Writer) error { 13 | var merr error 14 | if _, err := io.Copy(w, s); err != nil { 15 | merr = errors.Join(merr, err) 16 | } 17 | if err := s.Close(); err != nil { 18 | merr = errors.Join(merr, err) 19 | } 20 | return merr 21 | } 22 | 23 | func (s Stream) Iterate(iterator func(line []byte) error) error { 24 | return s.Modify(ModifyFn(func(line []byte) (modifed []byte, err error) { 25 | err = iterator(line) 26 | return nil, err 27 | })).To(io.Discard) 28 | } 29 | 30 | // ToStdout pipes the stdout of the stream to screen. 31 | func (s Stream) ToStdout() error { 32 | return s.To(os.Stdout) 33 | } 34 | 35 | // ToString reads stdout of the stream and returns it as a string. 36 | func (s Stream) ToString() (string, error) { 37 | var out bytes.Buffer 38 | err := s.To(&out) 39 | return out.String(), err 40 | 41 | } 42 | 43 | // ToFile dumps the output of the stream to a file. 44 | func (s Stream) ToFile(path string) error { 45 | f, err := File(path) 46 | if err != nil { 47 | return err 48 | } 49 | defer f.Close() 50 | return s.To(f) 51 | } 52 | 53 | // AppendFile appends the output of the stream to a file. 54 | func (s Stream) AppendFile(path string) error { 55 | f, err := AppendFile(path) 56 | if err != nil { 57 | return err 58 | } 59 | defer f.Close() 60 | return s.To(f) 61 | } 62 | 63 | // ToTempFile dumps the output of the stream to a temporary file and returns the temporary files' 64 | // path. 65 | func (s Stream) ToTempFile() (path string, err error) { 66 | f, err := os.CreateTemp("", "script-") 67 | if err != nil { 68 | return "", err 69 | } 70 | defer f.Close() 71 | return f.Name(), s.To(f) 72 | } 73 | 74 | // Discard executes the stream pipeline but discards the output. 75 | func (s Stream) Discard() error { 76 | return s.To(io.Discard) 77 | } 78 | 79 | func File(path string) (io.WriteCloser, error) { 80 | err := makeDir(path) 81 | if err != nil { 82 | return nil, err 83 | } 84 | return os.Create(path) 85 | } 86 | 87 | func AppendFile(path string) (io.WriteCloser, error) { 88 | err := makeDir(path) 89 | if err != nil { 90 | return nil, err 91 | } 92 | if _, err := os.Stat(path); err != nil { 93 | return File(path) 94 | } 95 | return os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0666) 96 | } 97 | 98 | func makeDir(path string) error { 99 | return os.MkdirAll(filepath.Dir(path), 0775) 100 | } 101 | -------------------------------------------------------------------------------- /to_test.go: -------------------------------------------------------------------------------- 1 | package script 2 | 3 | import ( 4 | "io/ioutil" 5 | "os" 6 | "path/filepath" 7 | "testing" 8 | 9 | "github.com/stretchr/testify/assert" 10 | "github.com/stretchr/testify/require" 11 | ) 12 | 13 | func TestToFile(t *testing.T) { 14 | t.Parallel() 15 | 16 | dir, err := ioutil.TempDir("", "script") 17 | require.NoError(t, err) 18 | 19 | path := filepath.Join(dir, "file") 20 | 21 | err = Echo("hello world").ToFile(path) 22 | require.NoError(t, err) 23 | defer os.Remove(path) 24 | 25 | got, err := Cat(path).ToString() 26 | require.NoError(t, err) 27 | 28 | assert.Equal(t, "hello world\n", got) 29 | } 30 | 31 | func TestAppendFile(t *testing.T) { 32 | t.Parallel() 33 | 34 | dir, err := ioutil.TempDir("", "script") 35 | require.NoError(t, err) 36 | 37 | path := filepath.Join(dir, "file") 38 | 39 | err = Echo("hello world").AppendFile(path) 40 | require.NoError(t, err) 41 | defer os.Remove(path) 42 | 43 | err = Echo("hello world").AppendFile(path) 44 | require.NoError(t, err) 45 | 46 | got, err := Cat(path).ToString() 47 | require.NoError(t, err) 48 | 49 | assert.Equal(t, "hello world\nhello world\n", got) 50 | } 51 | 52 | func TestToTempFile(t *testing.T) { 53 | t.Parallel() 54 | 55 | tmp, err := Echo("hello world").ToTempFile() 56 | require.NoError(t, err) 57 | defer os.Remove(tmp) 58 | 59 | got, err := Cat(tmp).ToString() 60 | require.NoError(t, err) 61 | 62 | assert.Equal(t, "hello world\n", got) 63 | } 64 | 65 | func TestIterate(t *testing.T) { 66 | t.Parallel() 67 | out := []byte{} 68 | Echo("a\nb\nc").Iterate(func(l []byte) error { 69 | out = append(out, l...) 70 | return nil 71 | }) 72 | assert.Equal(t, out, []byte("abc")) 73 | } 74 | -------------------------------------------------------------------------------- /uniq.go: -------------------------------------------------------------------------------- 1 | package script 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | ) 7 | 8 | // Uniq report or omit repeated lines. 9 | // 10 | // Shell command: `uniq`. 11 | func (s Stream) Uniq() Stream { 12 | return s.Modify(&Uniq{}) 13 | } 14 | 15 | // Uniq report or omit repeated lines. 16 | // 17 | // Usage: 18 | // 19 | // .Modify(&Uniq{...})... 20 | // 21 | // Shell command: `uniq`. 22 | type Uniq struct { 23 | WriteCount bool 24 | // last stores the last written line. 25 | last []byte 26 | // count is the number of times the `last` was in input. 27 | count int 28 | } 29 | 30 | func (u *Uniq) Modify(line []byte) ([]byte, error) { 31 | if line != nil /* not EOF */ && bytes.Equal(line, u.last) /* Repeated line */ { 32 | u.count++ 33 | return nil, nil 34 | } 35 | 36 | // Output the last seen line. 37 | var out []byte 38 | if u.count > 0 { 39 | if u.WriteCount { 40 | out = []byte(fmt.Sprintf("%d\t", u.count)) 41 | } 42 | out = append(out, u.last...) 43 | out = append(out, '\n') 44 | } 45 | 46 | // Remember the line without the '\n' suffix or count prefix. 47 | u.last = line 48 | u.count = 1 49 | 50 | return out, nil 51 | } 52 | 53 | func (u *Uniq) Name() string { 54 | return fmt.Sprintf("uniq(%v)", u.WriteCount) 55 | } 56 | -------------------------------------------------------------------------------- /uniq_test.go: -------------------------------------------------------------------------------- 1 | package script 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | "github.com/stretchr/testify/require" 8 | ) 9 | 10 | func TestUniq(t *testing.T) { 11 | t.Parallel() 12 | 13 | out, err := Echo("a\na\nb\nbb\na").Uniq().ToString() 14 | require.NoError(t, err) 15 | assert.Equal(t, "a\nb\nbb\na\n", out) 16 | } 17 | 18 | func TestUniq_count(t *testing.T) { 19 | t.Parallel() 20 | 21 | out, err := Echo("a\na\nb\nbb\na").Modify(&Uniq{WriteCount: true}).ToString() 22 | require.NoError(t, err) 23 | assert.Equal(t, "2\ta\n1\tb\n1\tbb\n1\ta\n", out) 24 | } 25 | -------------------------------------------------------------------------------- /wc.go: -------------------------------------------------------------------------------- 1 | package script 2 | 3 | import ( 4 | "bufio" 5 | "errors" 6 | "fmt" 7 | "strings" 8 | ) 9 | 10 | // Count represents the output of `wc` shell command. 11 | type Count struct { 12 | // Stream can be used to pipe the output of wc. 13 | Stream 14 | // Count the number of lines, words and chars in the input. 15 | Lines, Words, Chars int 16 | } 17 | 18 | // Wc counts the number of lines, words and characters. 19 | // 20 | // Shell command: `wc`. 21 | func (s Stream) Wc() Count { 22 | defer s.Close() 23 | 24 | var ( 25 | count Count 26 | merr error 27 | ) 28 | scanner := bufio.NewScanner(s) 29 | for scanner.Scan() { 30 | count.Lines++ 31 | count.Chars += len(scanner.Text()) + 1 32 | count.Words += countWords(scanner.Text()) 33 | } 34 | if err := scanner.Err(); err != nil { 35 | merr = errors.Join(merr, fmt.Errorf("scanning stream: %w", err)) 36 | } 37 | 38 | count.Stream = Stream{ 39 | stage: "wc", 40 | r: strings.NewReader(count.String()), 41 | err: merr, 42 | } 43 | return count 44 | } 45 | 46 | func (c Count) String() string { 47 | return fmt.Sprintf("%d\t%d\t%d\n", c.Lines, c.Words, c.Chars) 48 | } 49 | 50 | func countWords(s string) int { 51 | // TODO: improve performance. 52 | return len(strings.Fields(s)) 53 | } 54 | -------------------------------------------------------------------------------- /wc_test.go: -------------------------------------------------------------------------------- 1 | package script 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | "github.com/stretchr/testify/require" 9 | ) 10 | 11 | func TestWc(t *testing.T) { 12 | t.Parallel() 13 | 14 | t.Run("Multiple lines words and chars", func(t *testing.T) { 15 | wc := Echo("a b c\nd e \ng ").Wc() 16 | 17 | assert.Equal(t, 3, wc.Lines) 18 | assert.Equal(t, 6, wc.Words) 19 | assert.Equal(t, 14, wc.Chars) 20 | 21 | out, err := wc.ToString() 22 | require.NoError(t, err) 23 | assert.Equal(t, "3\t6\t14\n", out) 24 | }) 25 | 26 | t.Run("Empty text", func(t *testing.T) { 27 | wc := Echo("").Wc() 28 | 29 | assert.Equal(t, 1, wc.Lines) 30 | assert.Equal(t, 0, wc.Words) 31 | assert.Equal(t, 1, wc.Chars) 32 | }) 33 | 34 | t.Run("Scanner error", func(t *testing.T) { 35 | s := (&Stream{ 36 | r: readerFn(func(_ []byte) (int, error) { 37 | return 0, fmt.Errorf("oops") 38 | }), 39 | }) 40 | wc := s.Wc() 41 | 42 | assert.Equal(t, 0, wc.Lines) 43 | assert.Equal(t, 0, wc.Words) 44 | assert.Equal(t, 0, wc.Chars) 45 | 46 | _, err := wc.ToString() 47 | require.ErrorContains(t, err, "oops") 48 | }) 49 | } 50 | --------------------------------------------------------------------------------