alexflint / go-arg

Struct-based argument parsing in Go
https://pkg.go.dev/github.com/alexflint/go-arg
BSD 2-Clause "Simplified" License
2.04k stars 100 forks source link

Hyphen to indicate take input from os.Stdin #260

Open fbaube opened 4 months ago

fbaube commented 4 months ago

It is a Unix convention that a hyphen as a command line argument instructs a program to take input from standard input rather than from a named file.

Would it be possible to implement this ?

It certainly comes in handy when using a program with a pipe, or when pasting input.

alexflint commented 4 months ago

I use this convention quite often in programs I write using go-arg too. I've found it's best to implement at the level of the application using the library, rather than right within the library. I often have a string argument that is used as a filename, with a special case for when it's set to "-". Is this what you mean? Or is it that you would read lines from standard input to populate an argument?

fbaube commented 4 months ago

I don't mean a file named "-".

I mean, one input source is standard input (rather than a named file).

Stdin could be coming from a pipe. Stdin could be coming from interactive typing (or pasting).

For example,

// GetStringFromStdin reads os.Stdin completely and returns a string.
func GetStringFromStdin() (string, error) {
        println("==> Reading from Stdin; press ^D right after a newline to end")
        bb, e := io.ReadAll(os.Stdin)
        if e != nil {
                return "", fmt.Errorf("Cannot read from Stdin: %w", e)
        }
        // MimeType = "text/plain"
        return string(bb), nil
}

HTH!