1 // Copyright 2022 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
21 // A State encapsulates the current state of a running script engine,
22 // including the script environment and any running background commands.
24 engine *Engine // the engine currently executing the script, if any
27 cancel context.CancelFunc
31 workdir string // initial working directory
32 pwd string // current working directory during execution
33 env []string // environment list (for os/exec)
34 envMap map[string]string // environment mapping (matches env)
35 stdout string // standard output from last 'go' command; for 'stdout' command
36 stderr string // standard error from last 'go' command; for 'stderr' command
38 background []backgroundCmd
41 type backgroundCmd struct {
46 // NewState returns a new State permanently associated with ctx, with its
47 // initial working directory in workdir and its initial environment set to
48 // initialEnv (or os.Environ(), if initialEnv is nil).
50 // The new State also contains pseudo-environment-variables for
51 // ${/} and ${:} (for the platform's path and list separators respectively),
52 // but does not pass those to subprocesses.
53 func NewState(ctx context.Context, workdir string, initialEnv []string) (*State, error) {
54 absWork, err := filepath.Abs(workdir)
59 ctx, cancel := context.WithCancel(ctx)
61 // Make a fresh copy of the env slice to avoid aliasing bugs if we ever
62 // start modifying it in place; this also establishes the invariant that
63 // s.env contains no duplicates.
64 env := cleanEnv(initialEnv, absWork)
66 envMap := make(map[string]string, len(env))
68 // Add entries for ${:} and ${/} to make it easier to write platform-independent
70 envMap["/"] = string(os.PathSeparator)
71 envMap[":"] = string(os.PathListSeparator)
73 for _, kv := range env {
74 if k, v, ok := strings.Cut(kv, "="); ok {
87 s.Setenv("PWD", absWork)
91 // CloseAndWait cancels the State's Context and waits for any background commands to
92 // finish. If any remaining background command ended in an unexpected state,
93 // Close returns a non-nil error.
94 func (s *State) CloseAndWait(log io.Writer) error {
96 wait, err := Wait().Run(s)
98 panic("script: internal error: Wait unexpectedly returns its own WaitFunc")
100 if flushErr := s.flushLog(log); err == nil {
106 // Chdir changes the State's working directory to the given path.
107 func (s *State) Chdir(path string) error {
109 if _, err := os.Stat(dir); err != nil {
110 return &fs.PathError{Op: "Chdir", Path: dir, Err: err}
117 // Context returns the Context with which the State was created.
118 func (s *State) Context() context.Context {
122 // Environ returns a copy of the current script environment,
123 // in the form "key=value".
124 func (s *State) Environ() []string {
125 return append([]string(nil), s.env...)
128 // ExpandEnv replaces ${var} or $var in the string according to the values of
129 // the environment variables in s. References to undefined variables are
130 // replaced by the empty string.
131 func (s *State) ExpandEnv(str string, inRegexp bool) string {
132 return os.Expand(str, func(key string) string {
135 // Quote to literal strings: we want paths like C:\work\go1.4 to remain
136 // paths rather than regular expressions.
137 e = regexp.QuoteMeta(e)
143 // ExtractFiles extracts the files in ar to the state's current directory,
144 // expanding any environment variables within each name.
146 // The files must reside within the working directory with which the State was
147 // originally created.
148 func (s *State) ExtractFiles(ar *txtar.Archive) error {
150 // Add trailing separator to terminate wd.
151 // This prevents extracting to outside paths which prefix wd,
152 // e.g. extracting to /home/foobar when wd is /home/foo
153 if !strings.HasSuffix(wd, string(filepath.Separator)) {
154 wd += string(filepath.Separator)
157 for _, f := range ar.Files {
158 name := s.Path(s.ExpandEnv(f.Name, false))
160 if !strings.HasPrefix(name, wd) {
161 return fmt.Errorf("file %#q is outside working directory", f.Name)
164 if err := os.MkdirAll(filepath.Dir(name), 0777); err != nil {
167 if err := os.WriteFile(name, f.Data, 0666); err != nil {
175 // Getwd returns the directory in which to run the next script command.
176 func (s *State) Getwd() string { return s.pwd }
178 // Logf writes output to the script's log without updating its stdout or stderr
179 // buffers. (The output log functions as a kind of meta-stderr.)
180 func (s *State) Logf(format string, args ...any) {
181 fmt.Fprintf(&s.log, format, args...)
184 // flushLog writes the contents of the script's log to w and clears the log.
185 func (s *State) flushLog(w io.Writer) error {
186 _, err := w.Write(s.log.Bytes())
191 // LookupEnv retrieves the value of the environment variable in s named by the key.
192 func (s *State) LookupEnv(key string) (string, bool) {
193 v, ok := s.envMap[key]
197 // Path returns the absolute path in the host operating system for a
198 // script-based (generally slash-separated and relative) path.
199 func (s *State) Path(path string) string {
200 if filepath.IsAbs(path) {
201 return filepath.Clean(path)
203 return filepath.Join(s.pwd, path)
206 // Setenv sets the value of the environment variable in s named by the key.
207 func (s *State) Setenv(key, value string) error {
208 s.env = cleanEnv(append(s.env, key+"="+value), s.pwd)
209 s.envMap[key] = value
213 // Stdout returns the stdout output of the last command run,
214 // or the empty string if no command has been run.
215 func (s *State) Stdout() string { return s.stdout }
217 // Stderr returns the stderr output of the last command run,
218 // or the empty string if no command has been run.
219 func (s *State) Stderr() string { return s.stderr }
221 // cleanEnv returns a copy of env with any duplicates removed in favor of
222 // later values and any required system variables defined.
224 // If env is nil, cleanEnv copies the environment from os.Environ().
225 func cleanEnv(env []string, pwd string) []string {
226 // There are some funky edge-cases in this logic, especially on Windows (with
227 // case-insensitive environment variables and variables with keys like "=C:").
228 // Rather than duplicating exec.dedupEnv here, cheat and use exec.Cmd directly.
229 cmd := &exec.Cmd{Env: env}