Skip to content

Instantly share code, notes, and snippets.

@leonjza
Created October 23, 2023 18:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leonjza/9d53b30a6b85ff837a27170a185aa5f7 to your computer and use it in GitHub Desktop.
Save leonjza/9d53b30a6b85ff837a27170a185aa5f7 to your computer and use it in GitHub Desktop.
gream

gream

I was curious about how hard it would be to implement something like pypipe[1] in go. Turns out, not that hard.

[1] https://github.com/bugen/pypipe

example

$ echo "foo bar" | go run main.go 4
b
module gream
go 1.21.3
require github.com/traefik/yaegi v0.15.1
github.com/traefik/yaegi v0.15.1 h1:YA5SbaL6HZA0Exh9T/oArRHqGN2HQ+zgmCY7dkoTXu4=
github.com/traefik/yaegi v0.15.1/go.mod h1:AVRxhaI2G+nUsaM1zyktzwXn69G3t/AuTDrCiTds9p0=
package main
// silly pypipe poc in go: https://github.com/bugen/pypipe
// 2023 @leonjza
import (
"os"
"strings"
"github.com/traefik/yaegi/interp"
"github.com/traefik/yaegi/stdlib"
)
func main() {
var col string
if len(os.Args) <= 1 {
col = "0"
} else {
col = os.Args[1]
}
i := interp.New(interp.Options{})
i.Use(stdlib.Symbols)
_, err := i.Eval(`import "bufio"`)
if err != nil {
panic(err)
}
_, err = i.Eval(`import "fmt"`)
if err != nil {
panic(err)
}
_, err = i.Eval(`import "os"`)
if err != nil {
panic(err)
}
_, err = i.Eval(`import "strings"`)
if err != nil {
panic(err)
}
lineProcessor := `
s := bufio.NewScanner(os.Stdin)
for s.Scan() {
l := strings.TrimSpace(s.Text())
fmt.Println(string(l[COLUMN]))
}
`
lineProcessor = strings.Replace(lineProcessor, `COLUMN`, col, 1)
_, err = i.Eval(lineProcessor)
if err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment