Skip to content

Commit

Permalink
feat: add optional out flag, simplify write step
Browse files Browse the repository at this point in the history
  • Loading branch information
jar-b committed Jun 5, 2021
1 parent 5e36211 commit 00e9989
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 20 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ Flags:
print generated contents, but do not write to file (optional)
-force
force overwrite of existing contents (optional)
-out string
output file (optional, defaults to adding to source file)
```

Examples:
Expand Down
29 changes: 9 additions & 20 deletions cmd/mdtoc/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (

var (
force, dryRun bool
out string
)

func init() {
Expand All @@ -24,14 +25,15 @@ func init() {
func main() {
flag.BoolVar(&force, "force", false, "force overwrite of existing contents (optional)")
flag.BoolVar(&dryRun, "dry-run", false, "print generated contents, but do not write to file (optional)")
flag.StringVar(&out, "out", "", "output file (optional, defaults to adding to source file)")
flag.Parse()

if flag.NArg() != 1 {
log.Fatal("unexpected number of args")
}
file := flag.Arg(0)
in := flag.Arg(0)

b, err := os.ReadFile(file)
b, err := os.ReadFile(in)
if err != nil {
log.Fatalf("reading file: %v", err)
}
Expand All @@ -54,26 +56,13 @@ func main() {
log.Fatalf("adding toc: %v", err)
}

err = overwrite(file, new)
if err != nil {
log.Fatalf("writing file: %v", err)
}
}

// overrwrite trucates an existing file and replaces with the content of b
func overwrite(file string, b []byte) error {
f, err := os.OpenFile(file, os.O_WRONLY, 0664)
if err != nil {
log.Fatalf("opening file: %v", err)
target := in
if out != "" {
target = out
}
defer f.Close()

f.Truncate(0)
f.Seek(0, 0)
_, err = f.Write(b)
err = os.WriteFile(target, new, 0644)
if err != nil {
return err
log.Fatalf("writing file: %v", err)
}

return nil
}

0 comments on commit 00e9989

Please sign in to comment.