aboutsummaryrefslogtreecommitdiffstats
path: root/bug/remote_actions.go
blob: 2070ba21620dca33565b01d65e0e134869dc5b9a (plain) (blame)
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package bug

import (
	"fmt"
	"github.com/MichaelMure/git-bug/repository"
	"strings"
)

const MsgNew = "new"
const MsgInvalid = "invalid data"
const MsgUpdated = "updated"
const MsgNothing = "nothing to do"

func Fetch(repo repository.Repo, remote string) error {
	remoteRefSpec := fmt.Sprintf(bugsRemoteRefPattern, remote)
	fetchRefSpec := fmt.Sprintf("%s*:%s*", bugsRefPattern, remoteRefSpec)

	return repo.FetchRefs(remote, fetchRefSpec)
}

func Push(repo repository.Repo, remote string) error {
	return repo.PushRefs(remote, bugsRefPattern+"*")
}

type MergeResult struct {
	Err error

	Id      string
	HumanId string
	Status  string
}

func newMergeError(id string, err error) MergeResult {
	return MergeResult{
		Id:      id,
		HumanId: formatHumanId(id),
		Status:  err.Error(),
	}
}

func newMergeStatus(id string, status string) MergeResult {
	return MergeResult{
		Id:      id,
		HumanId: formatHumanId(id),
		Status:  status,
	}
}

func MergeAll(repo repository.Repo, remote string) <-chan MergeResult {
	out := make(chan MergeResult)

	go func() {
		defer close(out)

		remoteRefSpec := fmt.Sprintf(bugsRemoteRefPattern, remote)
		remoteRefs, err := repo.ListRefs(remoteRefSpec)

		if err != nil {
			out <- MergeResult{Err: err}
			return
		}

		for _, remoteRef := range remoteRefs {
			refSplitted := strings.Split(remoteRef, "/")
			id := refSplitted[len(refSplitted)-1]

			remoteBug, err := readBug(repo, remoteRef)

			if err != nil {
				out <- newMergeError(id, err)
				continue
			}

			// Check for error in remote data
			if !remoteBug.IsValid() {
				out <- newMergeStatus(id, MsgInvalid)
				continue
			}

			localRef := bugsRefPattern + remoteBug.Id()
			localExist, err := repo.RefExist(localRef)

			// the bug is not local yet, simply create the reference
			if !localExist {
				err := repo.CopyRef(remoteRef, localRef)

				if err != nil {
					out <- newMergeError(id, err)
					return
				}

				out <- newMergeStatus(id, MsgNew)
				continue
			}

			localBug, err := readBug(repo, localRef)

			if err != nil {
				out <- newMergeError(id, err)
				return
			}

			updated, err := localBug.Merge(repo, remoteBug)

			if err != nil {
				out <- newMergeError(id, err)
				return
			}

			if updated {
				out <- newMergeStatus(id, MsgUpdated)
			} else {
				out <- newMergeStatus(id, MsgNothing)
			}
		}
	}()

	return out
}