Skip to content

Commit f2dbb25

Browse files
committed
Improve handling of arguments: inject in source for -play
With -E disallow arguments after the program. With -play, -Eplay and -share inject the arguments into the program source in an init func.
1 parent 16862cf commit f2dbb25

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

main.go

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,12 @@ func _main() error {
292292
}
293293

294294
args := flag.Args()[1:]
295+
if len(args) > 0 {
296+
switch action {
297+
case actionDump:
298+
return errors.New("arguments not expected")
299+
}
300+
}
295301

296302
if goCmdResolved, err := exec.LookPath(goCmd); err != nil {
297303
return fmt.Errorf("%q: %v", goCmd, err)
@@ -385,7 +391,10 @@ func _main() error {
385391
defer os.Remove(dir + "/go.sum")
386392
}
387393

388-
var src bytes.Buffer
394+
var (
395+
src bytes.Buffer
396+
injectArgs bool // inject our arguments into os.Args in the program source
397+
)
389398

390399
// If sending to the Go Playground, export GOEXPERIMENT as a comment
391400
if action >= actionDumpPlay {
@@ -399,6 +408,12 @@ func _main() error {
399408
src.WriteString(exp)
400409
src.WriteString("\n\n")
401410
}
411+
412+
injectArgs = len(args) > 0
413+
if injectArgs {
414+
// We need the os package to patch os.Args
415+
imports.Set("os")
416+
}
402417
}
403418

404419
src.WriteString("package main\n")
@@ -414,6 +429,9 @@ func _main() error {
414429
}
415430
fmt.Fprintf(&src, "import %s %q\n", alias, path)
416431
}
432+
if injectArgs {
433+
fmt.Fprintf(&src, "func init() { os.Args = append(os.Args[:1], %#v...) }\n\n", args)
434+
}
417435
src.WriteString("func main() {\n")
418436
if action <= actionDump {
419437
src.WriteString("//line :1\n")

0 commit comments

Comments
 (0)