aboutsummaryrefslogtreecommitdiffstats
path: root/utils/utils.go
blob: 5f686f7da0aa4a717c5b41c67fdc1252edf88301 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package utils

import (
	"io/ioutil"
	"log"
	"os"
	"os/user"

	"gopkg.in/yaml.v2"
)

var history_file string = ".git-checkout-history"

type BranchList struct {
	Branches []string
}

func getHomeDir() string {
	usr, err := user.Current()
	if err != nil {
		log.Fatal(err)
	}
	return usr.HomeDir
}

func OpenHistoryFile() (f *os.File, err error) {
	file_path := getHomeDir() + "/" + history_file
	if _, err := os.Stat(file_path); os.IsNotExist(err) {
		return os.Create(file_path)
	} else {
		return os.Open(file_path)
	}
}

func Store(branch string) {
	branchList := BranchList{}
	rcfile, err := OpenHistoryFile()
	if err != nil {
		log.Fatal(err)
	}
	rcfile.Close()
	
	file_path := getHomeDir() + "/" + history_file
	data, err := ioutil.ReadFile(file_path)
	if err != nil {
		log.Fatal(err)
	}
	
	err = yaml.Unmarshal(data, &branchList)
	if err != nil {
		log.Fatal(err)
	}
	
	branchList.Branches = append([]string{branch}, branchList.Branches...)
	
	data, err = yaml.Marshal(&branchList)
	if err != nil {
		log.Fatal(err)
	}
	
	err = ioutil.WriteFile(file_path, data, 0644)
	if err != nil {
		log.Fatal(err)
	}
}

func Branches() []string {
	branchList := BranchList{}
	
	file_path := getHomeDir() + "/" + history_file
	data, err := ioutil.ReadFile(file_path)
	if err != nil {
		log.Fatal("ERROR: No checkout history file. Run `checkout-store` to create it.")
	}
	
	err = yaml.Unmarshal(data, &branchList)
	if err != nil {
		log.Fatal(err)
	}
	
	return branchList.Branches
}