1
0
mirror of https://github.com/go-task/task.git synced 2025-06-04 23:38:05 +02:00

58 lines
1.7 KiB
Go
Raw Normal View History

2018-07-22 18:05:13 -03:00
// Copyright (c) 2018, Daniel Martí <mvdan@mvdan.cc>
// See LICENSE for licensing information
package shell
import (
"context"
"fmt"
"os"
2019-09-26 19:04:09 -03:00
"mvdan.cc/sh/v3/expand"
"mvdan.cc/sh/v3/interp"
"mvdan.cc/sh/v3/syntax"
2018-07-22 18:05:13 -03:00
)
// SourceFile sources a shell file from disk and returns the variables
2018-12-15 15:44:17 -02:00
// declared in it. It is a convenience function that uses a default shell
// parser, parses a file from disk, and calls SourceNode.
2018-07-22 18:05:13 -03:00
//
2018-12-15 15:44:17 -02:00
// This function should be used with caution, as it can interpret arbitrary
// code. Untrusted shell programs shoudn't be sourced outside of a sandbox
// environment.
func SourceFile(ctx context.Context, path string) (map[string]expand.Variable, error) {
2018-07-22 18:05:13 -03:00
f, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("could not open: %v", err)
}
defer f.Close()
2018-12-15 15:44:17 -02:00
file, err := syntax.NewParser().Parse(f, path)
2018-07-22 18:05:13 -03:00
if err != nil {
return nil, fmt.Errorf("could not parse: %v", err)
}
2018-12-15 15:44:17 -02:00
return SourceNode(ctx, file)
2018-07-22 18:05:13 -03:00
}
// SourceNode sources a shell program from a node and returns the
2018-12-15 15:44:17 -02:00
// variables declared in it. It accepts the same set of node types that
// interp/Runner.Run does.
2018-07-22 18:05:13 -03:00
//
2018-12-15 15:44:17 -02:00
// This function should be used with caution, as it can interpret arbitrary
// code. Untrusted shell programs shoudn't be sourced outside of a sandbox
// environment.
func SourceNode(ctx context.Context, node syntax.Node) (map[string]expand.Variable, error) {
r, _ := interp.New()
2018-09-01 11:00:49 -03:00
if err := r.Run(ctx, node); err != nil {
2018-07-22 18:05:13 -03:00
return nil, fmt.Errorf("could not run: %v", err)
}
// delete the internal shell vars that the user is not
// interested in
delete(r.Vars, "PWD")
delete(r.Vars, "UID")
2018-07-22 18:05:13 -03:00
delete(r.Vars, "HOME")
delete(r.Vars, "PATH")
delete(r.Vars, "IFS")
delete(r.Vars, "OPTIND")
return r.Vars, nil
}