Skip to content

Commit e864580

Browse files
committed
Decouple ParseAndRun to allow customization of Invocation
1 parent 300bbc8 commit e864580

File tree

1 file changed

+26
-10
lines changed

1 file changed

+26
-10
lines changed

mage/main.go

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -132,18 +132,19 @@ func (i Invocation) UsesMagefiles() bool {
132132
// files in the given directory with the given args (do not include the command
133133
// name in the args).
134134
func ParseAndRun(stdout, stderr io.Writer, stdin io.Reader, args []string) int {
135-
errlog := log.New(stderr, "", 0)
136-
out := log.New(stdout, "", 0)
137135
inv, cmd, err := Parse(stderr, stdout, args)
138-
inv.Stderr = stderr
139-
inv.Stdin = stdin
140-
if err == flag.ErrHelp {
141-
return 0
142-
}
143-
if err != nil {
144-
errlog.Println("Error:", err)
145-
return 2
136+
if retcode, doExit := HandleParseError(err, stderr); doExit {
137+
return retcode
146138
}
139+
inv.Stdin = stdin
140+
return Run(inv, cmd)
141+
}
142+
143+
// Run compiles and runs the mage files in invocation parsed by Parse function.
144+
// The parameters to this function are the same as the return values of Parse.
145+
func Run(inv Invocation, cmd Command) int {
146+
errlog := log.New(inv.Stderr, "", 0)
147+
out := log.New(inv.Stdout, "", 0)
147148

148149
switch cmd {
149150
case Version:
@@ -179,6 +180,7 @@ func ParseAndRun(stdout, stderr io.Writer, stdin io.Reader, args []string) int {
179180
// flag.ErrHelp, the calling process should exit with code 0.
180181
func Parse(stderr, stdout io.Writer, args []string) (inv Invocation, cmd Command, err error) {
181182
inv.Stdout = stdout
183+
inv.Stderr = stderr
182184
fs := flag.FlagSet{}
183185
fs.SetOutput(stdout)
184186

@@ -306,6 +308,20 @@ Options:
306308
return inv, cmd, err
307309
}
308310

311+
// HandleParseError handles errors returned by Parse function. It returns the
312+
// return code and a boolean indicating whether the program should exit.
313+
func HandleParseError(err error, stderr io.Writer) (int, bool) {
314+
errlog := log.New(stderr, "", 0)
315+
if err == flag.ErrHelp {
316+
return 0, true
317+
}
318+
if err != nil {
319+
errlog.Println("Error:", err)
320+
return 2, true
321+
}
322+
return 0, false
323+
}
324+
309325
const dotDirectory = "."
310326

311327
// Invoke runs Mage with the given arguments.

0 commit comments

Comments
 (0)