Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Decouple ParseAndRun to allow customization of Invocation #442

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
36 changes: 26 additions & 10 deletions mage/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,18 +132,19 @@ func (i Invocation) UsesMagefiles() bool {
// files in the given directory with the given args (do not include the command
// name in the args).
func ParseAndRun(stdout, stderr io.Writer, stdin io.Reader, args []string) int {
errlog := log.New(stderr, "", 0)
out := log.New(stdout, "", 0)
inv, cmd, err := Parse(stderr, stdout, args)
inv.Stderr = stderr
inv.Stdin = stdin
if err == flag.ErrHelp {
return 0
}
if err != nil {
errlog.Println("Error:", err)
return 2
if retcode, doExit := HandleParseError(err, stderr); doExit {
return retcode
}
inv.Stdin = stdin
return Run(inv, cmd)
}

// Run compiles and runs the mage files in invocation parsed by Parse function.
// The parameters to this function are the same as the return values of Parse.
func Run(inv Invocation, cmd Command) int {
errlog := log.New(inv.Stderr, "", 0)
out := log.New(inv.Stdout, "", 0)

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

Expand Down Expand Up @@ -306,6 +308,20 @@ Options:
return inv, cmd, err
}

// HandleParseError handles errors returned by Parse function. It returns the
// return code and a boolean indicating whether the program should exit.
func HandleParseError(err error, stderr io.Writer) (int, bool) {
errlog := log.New(stderr, "", 0)
if err == flag.ErrHelp {
return 0, true
}
if err != nil {
errlog.Println("Error:", err)
return 2, true
}
return 0, false
}

const dotDirectory = "."

// Invoke runs Mage with the given arguments.
Expand Down