Skip to content

Commit

Permalink
add __file__ variable to environment (#3705)
Browse files Browse the repository at this point in the history
Co-authored-by: dgomez <dgomez@absolute.com>
  • Loading branch information
DaytonG and dgomez committed Aug 14, 2020
1 parent 9a51de7 commit 3af12c5
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
9 changes: 8 additions & 1 deletion internal/tiltfile/starkit/environment.go
Expand Up @@ -241,7 +241,14 @@ func (e *Environment) doLoad(t *starlark.Thread, localPath string) (starlark.Str
contentBytes = []byte(contents)
}

return starlark.ExecFile(t, localPath, contentBytes, e.predeclared)
// Create a copy of predeclared variables so we can specify Tiltfile-specific values.
predeclared := starlark.StringDict{}
for k, v := range e.predeclared {
predeclared[k] = v
}
predeclared["__file__"] = starlark.String(localPath)

return starlark.ExecFile(t, localPath, contentBytes, predeclared)
}

type ArgUnpacker func(fnName string, args starlark.Tuple, kwargs []starlark.Tuple, pairs ...interface{}) error
Expand Down
22 changes: 22 additions & 0 deletions internal/tiltfile/starkit/environment_test.go
Expand Up @@ -198,3 +198,25 @@ load('../bar/Tiltfile', 'unused')
path := strings.TrimSpace(f.out.String())
require.Equal(t, "bar", filepath.Base(filepath.Dir(path)))
}

// Tiltfile loads Tiltfile2
// 1 prints its __file__ and calls a method in 2 to do the same
func TestUseMagicFileVar(t *testing.T) {
f := NewFixture(t, PwdExtension{})
f.File("Tiltfile2", `
def print_mypath():
print(__file__)
`)
f.File("Tiltfile", `
load('Tiltfile2', 'print_mypath')
print(__file__)
print_mypath()
`)

_, err := f.ExecFile("Tiltfile")
require.NoError(t, err)

paths := strings.Split(strings.TrimSpace(f.out.String()), "\n")
require.Equal(t, "Tiltfile", filepath.Base(paths[0]))
require.Equal(t, "Tiltfile2", filepath.Base(paths[1]))
}

0 comments on commit 3af12c5

Please sign in to comment.