alexflint / go-arg

Struct-based argument parsing in Go
BSD 2-Clause "Simplified" License
1.98k stars 99 forks source link

Hyphen to indicate take input from os.Stdin #260

Open fbaube opened 1 month ago

fbaube commented 1 month 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 1 month 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 1 month 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!