Skip to content

Instantly share code, notes, and snippets.

@ik5 ik5/update.go
Last active Dec 15, 2015

Embed
What would you like to do?
My first go program - updating local directories with their scm command
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
You can’t perform that action at this time.