Add go-run-args to pass command line arguments to `go run`

When executing the main function which requires command line arguments, user can
set `go-run-args` to pass command line arguments to compiled binary.

The example below demonstrates how to pass command line arguments by setting
`go-run-args` as file local variable:

package main

import (
	"fmt"
	"os"
	"strconv"
)

func main() {
	//Atoi converts a string to an int
	fmt.Println("Arguments:", os.Args)
	a, _ := strconv.Atoi(os.Args[1])
	b, _ := strconv.Atoi(os.Args[2])

	result := sum(a, b)
	fmt.Printf("The sum of %d and %d is %d\n", a, b, result)
}

func sum(a, b int) int {
	return a + b
}

// Local Variables:
// go-run-args: "10 5"
// End:
This commit is contained in:
Enze Chi 2019-04-04 16:20:48 +11:00 committed by smile13241324
parent c175e96d85
commit 21c442050a
4 changed files with 19 additions and 3 deletions

View File

@ -805,6 +805,7 @@ Other:
(thanks to Boris Buliga)
- Cleanup =which-key= by removing obsolete entries and adding some missing
ones (thans to duianto)
- Add =go-run-args= to pass command line arguments to `go run`
- Fixed:
- Fixed ~h~ key binding in compilation and grep buffers (thanks to Sylvain
Benner)
@ -2170,4 +2171,5 @@ Other:
Hoffmann, Xiang Ji, Yi Liu, zer09, Zhige Xin)
*** Release notes summarized
Thanks to: Grant Shangreaux, Songpeng Zu, Igor Almeida, Miciah Dashiel Butler
Masters, Abhishek(Compro) Prasad, Deepak Khidia, Ward Harris, Jiahao Jiang
Masters, Abhishek(Compro) Prasad, Deepak Khidia, Ward Harris, Jiahao Jiang,
Enze Chi

View File

@ -153,6 +153,15 @@ or
(go :variables gofmt-command "goimports")
#+END_SRC
To run current main package with command line arguments, set the value of
=go-run-args= as file local variable, e.g.
#+BEGIN_SRC emacs-lisp
// Local Variables:
// go-run-args: "--output run.log"
// End:
#+END_SRC
** Indentation
By default, the tab width in Go mode is 8 spaces. To use a different value set
the layer variable =go-tab-width=, e.g.

View File

@ -39,3 +39,6 @@
(defvar go-test-verbose nil
"Control verbosity of `go test` output")
(defvar go-run-args ""
"Additional arguments to by supplied to `go run` during runtime.")

View File

@ -115,9 +115,11 @@
(defun spacemacs/go-run-main ()
(interactive)
(shell-command
(format "go run %s"
(format "go run %s %s"
(shell-quote-argument (or (file-remote-p (buffer-file-name (buffer-base-buffer)) 'localname)
(buffer-file-name (buffer-base-buffer)))))))
(buffer-file-name (buffer-base-buffer))))
go-run-args)))
(defun spacemacs/go-packages-gopkgs ()
"Return a list of all Go packages, using `gopkgs'."
(sort (process-lines "gopkgs") #'string<))