FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

cmd/download: pipe to stdout if stdout != TTY · github-release/github-release@1fc92c5 · GitHub

Repository navigation

Commit 1fc92c5

Browse files
committed
cmd/download: pipe to stdout if stdout != TTY
Fixes #61.
1 parent d07a13c commit 1fc92c5

2 files changed

Lines changed: 22 additions & 6 deletions

File tree

‎cmd.go‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -214,11 +214,16 @@ func downloadcmd(opt Options) error {
214214
return fmt.Errorf("github did not respond with 200 OK but with %v", resp.Status)
215215
}
216216

217-
out, err := os.Create(name)
218-
if err != nil {
219-
return fmt.Errorf("could not create file %s", name)
217+
out := os.Stdout // Pipe the asset to stdout by default.
218+
if isCharDevice(out) {
219+
// If stdout is a char device, assume it's a TTY (terminal). In this
220+
// case, don't pipe th easset to stdout, but create it as a file in
221+
// the current working folder.
222+
if out, err = os.Create(name); err != nil {
223+
return fmt.Errorf("could not create file %s", name)
224+
}
225+
defer out.Close()
220226
}
221-
defer out.Close()
222227

223228
n, err := io.Copy(out, resp.Body)
224229
if n != contentLength {

‎util.go‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package main
22

33
import (
44
"fmt"
5+
"os"
56
"time"
67
)
78

@@ -18,15 +19,15 @@ func nvls(xs ...string) string {
1819

1920
func vprintln(a ...interface{}) (int, error) {
2021
if VERBOSITY > 0 {
21-
return fmt.Println(a...)
22+
return fmt.Fprintln(os.Stderr, a...)
2223
}
2324

2425
return 0, nil
2526
}
2627

2728
func vprintf(format string, a ...interface{}) (int, error) {
2829
if VERBOSITY > 0 {
29-
return fmt.Printf(format, a...)
30+
return fmt.Fprintf(os.Stderr, format, a...)
3031
}
3132

3233
return 0, nil
@@ -39,3 +40,13 @@ func timeFmtOr(t *time.Time, fmt, def string) string {
3940
}
4041
return t.Format(fmt)
4142
}
43+
44+
// isCharDevice returns true if f is a character device (panics if f can't
45+
// be stat'ed).
46+
func isCharDevice(f *os.File) bool {
47+
stat, err := f.Stat()
48+
if err != nil {
49+
panic(err)
50+
}
51+
return (stat.Mode() & os.ModeCharDevice) != 0
52+
}

0 commit comments

Comments
 (0)

Back | FazBrowse Home | New Git URL