blob: f73aa264166af6dc59d7c5f7751abe16bd9a259b [file] [log] [blame]
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package builtins
import (
"path/filepath"
"fuchsia.googlesource.com/infra/infra/fxicfg/errs"
"fuchsia.googlesource.com/infra/infra/fxicfg/state"
"go.starlark.net/starlark"
)
// setOutputDir sets the directory where output files are generated. This must be given
// relative to the main starlark entrypoint file. It is an error to call this more than
// once, even if the directory is the same each time.
func setOutputDir(thread *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
do := func() error {
var dir string
if err := starlark.UnpackPositionalArgs("set_output_dir", args, kwargs, 0, &dir); err != nil {
return err
}
s, err := state.GetThreadState(thread)
if err != nil {
return err
}
if s.OutputDir != "" {
return errs.WithReason(errs.ErrIllegalWrite, "output dir already set to %q", s.OutputDir)
}
s.OutputDir = dir
state.SetThreadState(thread, s)
return nil
}
return starlark.None, do()
}
// addOutputFile registers a file to be generated at the end of execution. The path to the
// file is treated as relative to the directory given to set_output_dir. If an absolute
// path is given, an error is returned.
func addOutputFile(thread *starlark.Thread, fn *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {
do := func() error {
var path, textproto string
if err := starlark.UnpackArgs("add_output_file", args, kwargs, "path", &path, "data", &textproto); err != nil {
return err
}
s, err := state.GetThreadState(thread)
if err != nil {
return err
}
if path == "" {
return errs.WithReason(errs.ErrInvalidArg, "path must not be empty")
}
if filepath.IsAbs(path) {
return errs.WithReason(errs.ErrInvalidArg, "%q is not relative to output dir", path)
}
if _, ok := s.OutputFiles[path]; ok {
return errs.WithReason(errs.ErrInvalidArg, "%q has already been added", path)
}
s.OutputFiles[path] = []byte(textproto)
state.SetThreadState(thread, s)
return nil
}
return starlark.None, do()
}