Skip to content

Commit

Permalink
Add option to specify file via stdin
Browse files Browse the repository at this point in the history
Signed-off-by: Shubham Sharma <[email protected]>
  • Loading branch information
shubham1172 committed Feb 8, 2023
1 parent 3f9002e commit 22ecc74
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 9 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,6 @@
# vendor/

# Files generated by the examples
generated-*.*
generated-*.*

ym
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,10 @@ Create a file `ops.yaml` with the following content:
Then run `ym`:

```bash
ym -f ops.yaml
# Run ym with the ops.yaml file.
ym -file ops.yaml
# Or, pipe the ops.yaml file to ym.
cat ops.yaml | ym
```

The `foo.yaml` file will be updated to:
Expand Down
24 changes: 17 additions & 7 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,27 @@ func parseConfiguration(data []byte) ([]YmEntry, error) {
return entries, nil
}

// getFileContent returns the contents of a file.
// If the file is not provided, it will try to read from stdin.
func getFileContent(f string) ([]byte, error) {
if f == "" {
fi, err := os.Stdin.Stat()
// Check if stdin is a pipe or a terminal
if err != nil || (fi.Mode()&os.ModeCharDevice) != 0 {
flag.Usage()
os.Exit(1)
}
return io.ReadAll(os.Stdin)
}
return os.ReadFile(f)
}

func main() {
var file string
flag.StringVar(&file, "file", "", "path to the operations file")
flag.StringVar(&file, "file", "", "path to the operations file (or specify via stdin)")
flag.Parse()

if file == "" {
flag.Usage()
os.Exit(1)
}

data, err := os.ReadFile(file)
data, err := getFileContent(file)
if err != nil {
log.Fatalf("error reading file: %v", err)
}
Expand Down

0 comments on commit 22ecc74

Please sign in to comment.