github.com/hideaki10/command-line@v0.9.8/bk/no-test/repo_manager.go (about) 1 package repo_manager 2 3 import ( 4 "errors" 5 "fmt" 6 "os" 7 "os/exec" 8 "path/filepath" 9 "strings" 10 ) 11 12 type RepoManager struct { 13 repos []string 14 ignoreErrors bool 15 } 16 17 func NewRepoManager(baseDir string, repoNames []string, ignoreErrors bool) (repoManager *RepoManager, err error) { 18 _, err = os.Stat(baseDir) 19 if err != nil { 20 if os.IsNotExist(err) { 21 err = errors.New(fmt.Sprintf("base dir: '%s' doesn't exist", baseDir)) 22 } 23 return 24 } 25 26 baseDir, err = filepath.Abs(baseDir) 27 if err != nil { 28 return 29 } 30 31 if baseDir[len(baseDir)-1] != '/' { 32 baseDir += "/" 33 } 34 35 if len(repoNames) == 0 { 36 err = errors.New("repo list can't be empty") 37 return 38 } 39 40 repoManager = &RepoManager{ 41 ignoreErrors: ignoreErrors, 42 } 43 for _, r := range repoNames { 44 path := baseDir + r 45 repoManager.repos = append(repoManager.repos, path) 46 } 47 48 return 49 } 50 51 func (m *RepoManager) GetRepos() []string { 52 return m.repos 53 } 54 55 func (m *RepoManager) Exec(cmd string) (output map[string]string, err error) { 56 output = map[string]string{} 57 var components []string 58 var multiWord []string 59 for _, component := range strings.Split(cmd, " ") { 60 if strings.HasPrefix(component, "\"") { 61 multiWord = append(multiWord, component[1:]) 62 continue 63 } 64 65 if len(multiWord) > 0 { 66 if !strings.HasSuffix(component, "\"") { 67 multiWord = append(multiWord, component) 68 continue 69 } 70 71 multiWord = append(multiWord, component[:len(component)-1]) 72 component = strings.Join(multiWord, " ") 73 multiWord = []string{} 74 } 75 76 components = append(components, component) 77 } 78 79 // Restore working directory after executing the command 80 wd, _ := os.Getwd() 81 defer os.Chdir(wd) 82 83 var out []byte 84 for _, r := range m.repos { 85 // Go to the repo's directory 86 err = os.Chdir(r) 87 if err != nil { 88 if m.ignoreErrors { 89 continue 90 } 91 return 92 } 93 94 // Execute the command 95 out, err = exec.Command("git", components...).CombinedOutput() 96 // Store the result 97 output[r] = string(out) 98 99 // Bail out if there was an error and NOT ignoring errors 100 if err != nil && !m.ignoreErrors { 101 return 102 } 103 } 104 return 105 }