Explorar el Código

Make stars not go lost in the ether

`stars` is a little program that saves your favourites from *places* and
updates them as necessary.
Lucas Stadler %!s(int64=10) %!d(string=hace) años
padre
commit
94510593c3
Se han modificado 1 ficheros con 86 adiciones y 0 borrados
  1. 86 0
      go/stars/stars.go

+ 86 - 0
go/stars/stars.go

@ -0,0 +1,86 @@
1
// `stars` fetches your GitHub stars and updates them as necessary.
2
package main
3
4
import (
5
	"encoding/json"
6
	"fmt"
7
	"os"
8
	"os/exec"
9
	"path"
10
	"strings"
11
	"time"
12
)
13
14
var userName = "heyLu"
15
var directory = "github-stars"
16
17
func main() {
18
	var stars []starInfo
19
	decoder := json.NewDecoder(os.Stdin)
20
	err := decoder.Decode(&stars)
21
	if err != nil {
22
		panic(err)
23
	}
24
25
	for _, info := range stars {
26
		fmt.Printf("% 48s - %s\n", info.RepoName, info.Description)
27
		err := updateRepo(info)
28
		if err != nil {
29
			fmt.Println(err)
30
			os.Exit(1)
31
		}
32
	}
33
}
34
35
func updateRepo(info starInfo) error {
36
	f, err := os.Open(path.Join(directory, info.RepoName))
37
	if err != nil {
38
		if os.IsNotExist(err) {
39
			return gitClone(info)
40
		}
41
42
		return err
43
	}
44
	f.Close()
45
46
	lastCommit, err := gitLastCommit(info)
47
	if err != nil {
48
		return err
49
	}
50
51
	if lastCommit.Before(info.PushedAt) {
52
		return gitPull(info)
53
	}
54
55
	return nil
56
}
57
58
func gitClone(info starInfo) error {
59
	cmd := exec.Command("git", "clone", info.CloneUrl,
60
		path.Join(directory, info.RepoName))
61
	return cmd.Run()
62
}
63
64
func gitPull(info starInfo) error {
65
	cmd := exec.Command("git", "-C", path.Join(directory, info.RepoName), "pull")
66
	return cmd.Run()
67
}
68
69
func gitLastCommit(info starInfo) (time.Time, error) {
70
	cmd := exec.Command("git", "-C", path.Join(directory, info.RepoName),
71
		"log", "-n", "1", "--format=%cd", "--date=iso8601-strict")
72
	out, err := cmd.Output()
73
	if err != nil {
74
		return time.Time{}, err
75
	}
76
77
	outStr := strings.TrimSpace(string(out))
78
	return time.Parse(time.RFC3339, outStr)
79
}
80
81
type starInfo struct {
82
	RepoName    string    `json:"full_name"`
83
	Description string    `json:"description"`
84
	CloneUrl    string    `json:"git_url"`
85
	PushedAt    time.Time `json:"pushed_at"`
86
}