Skip to content

Commit

Permalink
implement cd() only for issue #144
Browse files Browse the repository at this point in the history
  • Loading branch information
ntwrick committed Feb 1, 2019
1 parent ac4e220 commit b67991f
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 2 deletions.
29 changes: 27 additions & 2 deletions docs/types/builtin-function.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,10 +116,35 @@ type("") # "STRING"
type({}) # "HASH"
```
### cd() or cd(path)
Sets the current working directory to `$HOME` or the given path.
Note that the path may have a `"~/"` prefix which will be replaced
with `$HOME/`.
The path to the current working directory can be seen with `pwd()`
``` bash
cd()
pwd() # /home/user
cd("~/git/abs")
pwd() # /home/user/git/abs
cd("/usr/local/bin")
pwd() # /usr/local/bin
```
### pwd()
Returns the working directory where the script was started for -- equivalent
to `env("PWD")`:
Returns the path to the current working directory -- equivalent
to `env("PWD")`.
If executed from a script this will initially be the directory
containing the script.
To change the working directory, see `cd()`.
``` bash
pwd() # /go/src/github.com/abs-lang/abs
Expand Down
1 change: 1 addition & 0 deletions evaluator/evaluator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -657,6 +657,7 @@ func TestBuiltinFunctions(t *testing.T) {
{`arg("o")`, "argument 0 to arg(...) is not supported (got: o, allowed: NUMBER)"},
{`arg(3)`, ""},
{`pwd().split("").reverse().slice(0, 33).reverse().join("").replace("\\", "/", -1).suffix("/evaluator")`, true}, // Little trick to get travis to run this test, as the base path is not /go/src/
{`cd("/usr/bin"); pwd()`, "/usr/bin"},
{`rand(1)`, 0},
{`int(10)`, 10},
{`int(10.5)`, 10},
Expand Down
27 changes: 27 additions & 0 deletions evaluator/functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,11 @@ func getFns() map[string]*object.Builtin {
Types: []string{},
Fn: pwdFn,
},
// cd(path)
"cd": &object.Builtin{
Types: []string{},
Fn: cdFn,
},
// echo(arg:"hello")
"echo": &object.Builtin{
Types: []string{},
Expand Down Expand Up @@ -411,6 +416,28 @@ func pwdFn(args ...object.Object) object.Object {
return &object.String{Token: tok, Value: dir}
}

// cd(path)
func cdFn(args ...object.Object) object.Object {
// Default cd $HOME
path := os.Getenv("HOME")
if len(args) == 1 {
// arg: path
pathStr := args[0].(*object.String)
rawPath := pathStr.Value
// expand ~/ path prefix
if strings.HasPrefix(rawPath, "~/") {
path = strings.Replace(rawPath, "~/", path+"/", 1)
} else if len(rawPath) > 0 {
path = rawPath
}
}
error := os.Chdir(path)
if error != nil {
return newError(tok, error.Error())
}
return NULL
}

// echo(arg:"hello")
func echoFn(args ...object.Object) object.Object {
if len(args) == 0 {
Expand Down

0 comments on commit b67991f

Please sign in to comment.