| 1 |
// Copyright 2025 Google LLC |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
package execv |
| 16 |
|
| 17 |
import ( |
| 18 |
"context" |
| 19 |
"errors" |
| 20 |
"fmt" |
| 21 |
"log/slog" |
| 22 |
"os" |
| 23 |
"os/exec" |
| 24 |
"strings" |
| 25 |
) |
| 26 |
|
| 27 |
// Run executes a command in a specified working directory and logs its output. |
| 28 |
func Run(ctx context.Context, args []string, workingDir string) error { |
| 29 |
cmd := exec.CommandContext(ctx, args[0], args[1:]...) |
| 30 |
cmd.Env = os.Environ() |
| 31 |
cmd.Dir = workingDir |
| 32 |
slog.Debug("librariangen: running command", "command", strings.Join(cmd.Args, " "), "dir", cmd.Dir) |
| 33 |
|
| 34 |
output, err := cmd.Output() |
| 35 |
if len(output) > 0 { |
| 36 |
slog.Debug("librariangen: command stdout", "output", string(output)) |
| 37 |
} |
| 38 |
if err != nil { |
| 39 |
var exitErr *exec.ExitError |
| 40 |
if errors.As(err, &exitErr) { |
| 41 |
// The command ran and exited with a non-zero exit code. |
| 42 |
if len(exitErr.Stderr) > 0 { |
| 43 |
slog.Debug("librariangen: command stderr", "output", string(exitErr.Stderr)) |
| 44 |
} |
| 45 |
return fmt.Errorf("librariangen: command failed with exit error: %s: %w", exitErr.Stderr, err) |
| 46 |
} |
| 47 |
// Another error occurred (e.g., command not found). |
| 48 |
return fmt.Errorf("librariangen: command failed: %w", err) |
| 49 |
} |
| 50 |
return nil |
| 51 |
} |