pull.go

 1package commands
 2
 3import (
 4	"errors"
 5	"fmt"
 6	"github.com/MichaelMure/git-bug/bug"
 7	"github.com/spf13/cobra"
 8)
 9
10func runPull(cmd *cobra.Command, args []string) error {
11	if len(args) > 1 {
12		return errors.New("Only pulling from one remote at a time is supported")
13	}
14
15	remote := "origin"
16	if len(args) == 1 {
17		remote = args[0]
18	}
19
20	fmt.Printf("Fetching remote ...\n\n")
21
22	if err := repo.FetchRefs(remote, bug.BugsRefPattern+"*", bug.BugsRemoteRefPattern+"*"); err != nil {
23		return err
24	}
25
26	fmt.Printf("\nMerging data ...\n\n")
27
28	remoteRefSpec := fmt.Sprintf(bug.BugsRemoteRefPattern, remote)
29	remoteRefs, err := repo.ListRefs(remoteRefSpec)
30
31	if err != nil {
32		return err
33	}
34
35	for _, ref := range remoteRefs {
36		remoteRef := fmt.Sprintf(bug.BugsRemoteRefPattern, remote) + ref
37		remoteBug, err := bug.ReadBug(repo, remoteRef)
38
39		if err != nil {
40			return err
41		}
42
43		// Check for error in remote data
44		if !remoteBug.IsValid() {
45			fmt.Printf("%s: %s\n", remoteBug.HumanId(), "invalid remote data")
46			continue
47		}
48
49		localRef := bug.BugsRefPattern + remoteBug.Id()
50		localExist, err := repo.RefExist(localRef)
51
52		// the bug is not local yet, simply create the reference
53		if !localExist {
54			err := repo.CopyRef(remoteRef, localRef)
55
56			if err != nil {
57				return err
58			}
59
60			fmt.Printf("%s: %s\n", remoteBug.HumanId(), "new")
61			continue
62		}
63
64		localBug, err := bug.ReadBug(repo, localRef)
65
66		if err != nil {
67			return err
68		}
69
70		updated, err := localBug.Merge(repo, remoteBug)
71
72		if err != nil {
73			return err
74		}
75
76		if updated {
77			fmt.Printf("%s: %s\n", remoteBug.HumanId(), "updated")
78		}
79	}
80
81	return nil
82}
83
84// showCmd defines the "push" subcommand.
85var pullCmd = &cobra.Command{
86	Use:   "pull [<remote>]",
87	Short: "Pull bugs update from a git remote",
88	RunE:  runPull,
89}
90
91func init() {
92	RootCmd.AddCommand(pullCmd)
93}