Debian Codegraph @

internal/command/cmd.go

raw symbols SCIP
1 package command
2
3 import (
4 "log"
5 "os/exec"
6 "strings"
7 "syscall"
8 )
9
10 // Mode indicates that whether command should run native code or use git
11 // command to operate.
12 type Mode uint8
13
14 const (
15 // ModeLegacy uses traditional git command line tool to operate
16 ModeLegacy = iota
17 // ModeNative uses native implementation of given git command
18 ModeNative
19 )
20
21 // Run runs the OS command and return its output. If the output
22 // returns error it also encapsulates it as a golang.error which is a return code
23 // of the command except zero
24 func Run(d string, c string, args []string) (string, error) {
25 cmd := exec.Command(c, args...)
26 if d != "" {
27 cmd.Dir = d
28 }
29 output, err := cmd.CombinedOutput()
30 return trimTrailingNewline(string(output)), err
31 }
32
33 // Return returns if we supposed to get return value as an int of a command
34 // this method can be used. It is practical when you use a command and process a
35 // failover according to a specific return code
36 func Return(d string, c string, args []string) (int, error) {
37 cmd := exec.Command(c, args...)
38 if d != "" {
39 cmd.Dir = d
40 }
41 var err error
42 // this time the execution is a little different
43 if err := cmd.Start(); err != nil {
44 return -1, err
45 }
46 if err := cmd.Wait(); err != nil {
47 if exiterr, ok := err.(*exec.ExitError); ok {
48 // The program has exited with an exit code != 0
49
50 // This works on both Unix and Windows. Although package
51 // syscall is generally platform dependent, WaitStatus is
52 // defined for both Unix and Windows and in both cases has
53 // an ExitStatus() method with the same signature.
54 if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
55 statusCode := status.ExitStatus()
56 return statusCode, err
57 }
58 } else {
59 log.Fatalf("cmd.Wait: %v", err)
60 }
61 }
62 return -1, err
63 }
64
65 // trimTrailingNewline removes the trailing new line form a string. this method
66 // is used mostly on outputs of a command
67 func trimTrailingNewline(s string) string {
68 if strings.HasSuffix(s, "\n") || strings.HasSuffix(s, "\r") {
69 return s[:len(s)-1]
70 }
71 return s
72 }