Skip to content

Commit

Permalink
add builtin ENV: __EXEC_FILENAME for getting executable filename. see…
Browse files Browse the repository at this point in the history
… issue #40
  • Loading branch information
mkideal committed Aug 11, 2018
1 parent 33e58ff commit 66f92ff
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 7 deletions.
2 changes: 1 addition & 1 deletion _examples/027-global-option/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ func main() {
// root command
type rootT struct {
cli.Helper
Self *rootT `json:"-" cli:"c,config" usage:"config" parser:"jsonfile" dft:"1.json"`
Self *rootT `json:"-" cli:"c,config" usage:"config" parser:"jsonfile" dft:"$__EXEC_FILENAME.json"`
Host string `cli:"H,host" usage:"host addr" dft:"$HOST"`
Port int `cli:"p,port" usage:"listening port"`
}
Expand Down
4 changes: 2 additions & 2 deletions _examples/027-global-option/run.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ set -e

go build -o app

cat >1.json<<EOF
cat >app.json<<EOF
{
"host": "127.0.0.1",
"port": 8080
Expand Down Expand Up @@ -45,5 +45,5 @@ HOST=10.0.0.1 ./app sub -H 168.0.0.1 -w xxx
echo

echo
rm 1.json
rm app.json
rm app
28 changes: 24 additions & 4 deletions flag.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ import (
"fmt"
"math"
"os"
"path/filepath"
"reflect"
"runtime"
"strconv"
"strings"

Expand Down Expand Up @@ -115,6 +117,10 @@ func isWordByte(b byte) bool {
b == '_'
}

const (
builtinVar_EXEC_FILENAME = "__EXEC_FILENAME"
)

func parseExpression(s string, isNumber bool) (string, error) {
const escapeByte = '$'
var (
Expand All @@ -127,11 +133,25 @@ func parseExpression(s string, isNumber bool) (string, error) {
if envName == "" {
return fmt.Errorf("unexpected end after %v", escapeByte)
}
env := os.Getenv(envName)
if env == "" && isNumber {
env = "0"
var value string
switch envName {
case builtinVar_EXEC_FILENAME:
filename, err := filepath.Abs(os.Args[0])
if err != nil {
return err
}
if runtime.GOOS == "windows" {
value = strings.TrimSuffix(filename, ".exe")
} else {
value = filename
}
default:
value = os.Getenv(envName)
if value == "" && isNumber {
value = "0"
}
}
exprBuf.WriteString(env)
exprBuf.WriteString(value)
return nil
}
for i, b := range src {
Expand Down

0 comments on commit 66f92ff

Please sign in to comment.