73 lines
1.6 KiB
Go
73 lines
1.6 KiB
Go
/*
|
|
filter --- Simple interactive data filter for POSIX pipelines
|
|
|
|
Copyright (c) 2022 Sameer Rahmani <lxsameer@gnu.org>
|
|
This program is free software; you can redistribute it and/or modify
|
|
it under the terms of the GNU General Public License as published by
|
|
the Free Software Foundation, either version 2 of the License.
|
|
This program is distributed in the hope that it will be useful,
|
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
GNU General Public License for more details.
|
|
You should have received a copy of the GNU General Public License
|
|
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
*/
|
|
|
|
package main
|
|
|
|
import (
|
|
"bufio"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
)
|
|
|
|
type Item struct {
|
|
Text string
|
|
Selected bool
|
|
}
|
|
|
|
type Items = *[]*Item
|
|
|
|
func NewItem(text string) *Item {
|
|
return &Item{
|
|
Text: text,
|
|
Selected: false,
|
|
}
|
|
}
|
|
|
|
// Pffff Golang, right? :D
|
|
func min(a, b int) int {
|
|
if a < b {
|
|
return a
|
|
}
|
|
return b
|
|
}
|
|
|
|
// Reads the input from stdin and makes sure that the current
|
|
// process is being run in a pipeline and converts the data
|
|
// to an array of items.
|
|
func ReadFromStdin() (Items, error) {
|
|
info, err := os.Stdin.Stat()
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
if info.Mode()&os.ModeCharDevice != 0 {
|
|
return nil, fmt.Errorf("the command is intended to work with pipes. For example `git log | filter | xarg | ...`")
|
|
}
|
|
|
|
reader := bufio.NewReader(os.Stdin)
|
|
var output []*Item
|
|
|
|
for {
|
|
input, _, err := reader.ReadLine()
|
|
if err != nil && err == io.EOF {
|
|
break
|
|
}
|
|
item := NewItem(string(input))
|
|
output = append(output, item)
|
|
}
|
|
return &output, nil
|
|
}
|