forked from rcmachado/changelog
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
root.go
96 lines (82 loc) · 2.18 KB
/
root.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package cmd
import (
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
)
var ioStreams *IOStreams
// IOStreams holds input/output streams for commands
type IOStreams struct {
In io.Reader
Out io.Writer
}
var rootCmd = &cobra.Command{
Use: "changelog",
Short: "Manipulate and validate changelog files",
Long: `changelog manipulate and validate markdown changelog files following the keepachangelog.com specification.`,
PersistentPreRun: func(cmd *cobra.Command, args []string) {
fs := cmd.Flags()
fdr := openFileOrExit(fs, "filename", os.O_RDONLY, os.Stdin)
input, err := ioutil.ReadAll(fdr)
if err != nil {
fmt.Printf("Failed to read input: %v", err)
os.Exit(1)
}
fdr.Close()
ioStreams.In = bytes.NewReader(input)
fdw := openFileOrExit(fs, "output", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.Stdout)
ioStreams.Out = bufio.NewWriter(fdw)
},
PersistentPostRun: func(cmd *cobra.Command, args []string) {
if ioStreams.Out != nil {
ioStreams.Out.(*bufio.Writer).Flush()
}
},
}
func openFileOrExit(fs *pflag.FlagSet, option string, flag int, defaultIfDash *os.File) *os.File {
filename, err := fs.GetString(option)
if err != nil {
fmt.Printf("Failed to get option '%s': %s\n", option, err)
os.Exit(2)
}
if filename == "-" {
return defaultIfDash
}
file, err := os.OpenFile(filename, flag, 0644)
if err != nil {
fmt.Printf("Failed to open file '%s': %s\n", filename, err)
os.Exit(2)
}
return file
}
func init() {
ioStreams = &IOStreams{}
rootCmd.AddCommand(
newInitCmd(ioStreams),
newFmtCmd(ioStreams),
newReleaseCmd(ioStreams),
newShowCmd(ioStreams),
newLatestCmd(ioStreams),
)
manipulationCmds := newChangeTypeCmds(ioStreams)
for _, cmd := range manipulationCmds {
rootCmd.AddCommand(cmd)
}
flags := rootCmd.PersistentFlags()
flags.StringP("filename", "f", "CHANGELOG.md", "Changelog file or '-' for stdin")
rootCmd.MarkFlagFilename("filename")
flags.StringP("output", "o", "-", "Output file or '-' for stdout")
rootCmd.MarkFlagFilename("output")
}
// Execute the program with command-line args
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}