Debian Codegraph @

internal/gapicgen/execv/command.go

raw
1 // Copyright 2021 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 provides a wrapper around exec.Cmd for debugging purposes.
16 package execv
17
18 import (
19 "io/fs"
20 "log"
21 "os"
22 "os/exec"
23 "path/filepath"
24 "strings"
25 )
26
27 // CmdWrapper is a wrapper around exec.Cmd for debugging purposes.
28 type CmdWrapper struct {
29 *exec.Cmd
30 }
31
32 // Command wraps a exec.Command to add some logging about commands being run.
33 // The commands stdout/stderr default to os.Stdout/os.Stderr respectfully.
34 func Command(name string, arg ...string) *CmdWrapper {
35 c := &CmdWrapper{exec.Command(name, arg...)}
36 c.Stderr = os.Stderr
37 c.Stdin = os.Stdin
38 return &CmdWrapper{exec.Command(name, arg...)}
39 }
40
41 // Run a command.
42 func (c *CmdWrapper) Run() error {
43 b, err := c.Output()
44 if len(b) > 0 {
45 log.Printf("Command Output: %s", b)
46 }
47 return err
48 }
49
50 // Output a command.
51 func (c *CmdWrapper) Output() ([]byte, error) {
52 log.Printf("[%s] >>>> %v <<<<", c.Dir, strings.Join(c.Args, " "))
53 b, err := c.Cmd.Output()
54 if err != nil {
55 if ee, ok := err.(*exec.ExitError); ok {
56 log.Println(string(ee.Stderr))
57 }
58 }
59 return b, err
60 }
61
62 // ForEachMod runs the given function with the directory of
63 // every non-internal module.
64 func ForEachMod(rootDir string, fn func(dir string) error) error {
65 return filepath.WalkDir(rootDir, func(path string, d fs.DirEntry, err error) error {
66 if err != nil {
67 return err
68 }
69 if strings.Contains(path, "internal") {
70 return filepath.SkipDir
71 }
72 if d.Name() == "go.mod" {
73 if err := fn(filepath.Dir(path)); err != nil {
74 return err
75 }
76 }
77 return nil
78 })
79 }