Last active
December 15, 2015 16:48
-
-
Save ik5/5291330 to your computer and use it in GitHub Desktop.
My first go program - updating local directories with their scm command
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"fmt" | |
"os" | |
"os/exec" | |
) | |
func isDir(path string) (bool, error) { | |
stat, err := os.Stat(path) | |
if err != nil { | |
return false, err | |
} | |
return stat.IsDir(), nil | |
} | |
func getSCM(path string) string { | |
if b, _ := isDir(path + "/.git"); b == true { | |
return "git" | |
} | |
if b, _ := isDir(path + "/.hg"); b == true { | |
return "hg" | |
} | |
return "" | |
} | |
func execSCM(scm, action string) { | |
cmd := exec.Command("/usr/bin/env", scm, action) | |
var out bytes.Buffer | |
cmd.Stdout = &out | |
err := cmd.Run() | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "Could not execute command: %v", err) | |
return | |
} | |
fmt.Printf("%s\n", out.String()) | |
} | |
func updateSCM(dir, path, scm string) { | |
if scm == "" { | |
return | |
} | |
fmt.Printf("Updating %s\n", dir) | |
os.Chdir(path) | |
execSCM(scm, "pull") | |
os.Chdir("..") | |
} | |
func updateDirs(path string, list []os.FileInfo) { | |
for _, item := range list { | |
file := path + "/" + item.Name() | |
if item.IsDir() { | |
scm := getSCM(file) | |
updateSCM(item.Name(), file, scm) | |
} | |
} | |
} | |
func main() { | |
path, err := os.Getwd() | |
if err != nil { | |
panic(err) | |
} | |
var file *os.File | |
file, err = os.Open(path) | |
if err != nil { | |
panic(err) | |
} | |
defer file.Close() | |
var list []os.FileInfo | |
list, err = file.Readdir(-1) | |
if err != nil { | |
panic(err) | |
} | |
if len(list) == 0 { | |
fmt.Printf("No files where found at %s\n", path) | |
os.Exit(-1) | |
} | |
updateDirs(path, list) | |
fmt.Println("Done") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment