diff --git a/csv.go b/csv.go index 7cbaee7..1ae8f49 100644 --- a/csv.go +++ b/csv.go @@ -6,6 +6,10 @@ import ( "io" ) +// CSVColumn is a filter function that reads the source as a CSV file and extracts the cell +// values of the named column, excluding the header itself. If the column cannot be found, +// the filter will produce nothing. If the column index is beyond the number of columns +// for a particular row, it will be skipped. func CSVColumn(name string) func(r io.Reader, w io.Writer) error { return func(r io.Reader, w io.Writer) error { cr := csv.NewReader(r) diff --git a/csv_test.go b/csv_test.go index 7bd15f8..5127152 100644 --- a/csv_test.go +++ b/csv_test.go @@ -29,3 +29,16 @@ func TestCSVColumn(t *testing.T) { }) }) } + +func ExampleCSVColumn() { + script.Slice([]string{ + "letter,fruit,word", + "a,apple,alpha", + "b,banana,bravo", + "c,cherry,charlie", + }).Filter(scriptx.CSVColumn("fruit")).Stdout() + // Output: + // apple + // banana + // cherry +} diff --git a/exec.go b/exec.go index 98c50aa..281b375 100644 --- a/exec.go +++ b/exec.go @@ -5,10 +5,16 @@ import ( "os" ) +// Runnable is a pipeline that can be executed by Run. The *script.Pipe type implements this interface type Runnable interface { + // Stdout invokes the runnable task with the result written to stdout, if successful. It returns the number + // of bytes written out, or an error if the task was unsuccessful. Stdout() (int, error) } +// Run takes a number of pipes and executes them in order, until they all succeed or the first error is encountered. +// If a runnable task fails with an error, it will write the error to stderr and terminate the program with exit code 1. +// It's designed to be used within the "main()" function. func Run(pipes ...Runnable) { for _, pipe := range pipes { if _, err := pipe.Stdout(); err != nil { diff --git a/json.go b/json.go index 9428215..25908f9 100644 --- a/json.go +++ b/json.go @@ -5,6 +5,9 @@ import ( "io" ) +// ToJSON is a filter function which converts each line from the source to a JSON structure. +// The result is a line-terminated list of JSON objects. +// The passed in function is to return a Go value that can be marshalled to JSON value. func ToJSON(fn func(line string) any) func(r io.Reader, w io.Writer) error { return func(r io.Reader, w io.Writer) error { return eachLine(r, func(line string) (err error) { diff --git a/json_test.go b/json_test.go index a8c08ca..37fa9e5 100644 --- a/json_test.go +++ b/json_test.go @@ -43,3 +43,17 @@ func TestToJSON(t *testing.T) { }) }) } + +func ExampleToJSON() { + fruits := []string{"apple", "banana", "pineapple"} + script.Slice(fruits).Filter(scriptx.ToJSON(func(fruit string) any { + return map[string]any{ + "fruit": fruit, + "length": len(fruit), + } + })).Stdout() + // Output: + // {"fruit":"apple","length":5} + // {"fruit":"banana","length":6} + // {"fruit":"pineapple","length":9} +}