aboutsummaryrefslogtreecommitdiffstats
path: root/submodule.go
blob: 83c28b7fd2c539218ab1010989272cdbdeb7f61e (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
package git

import (
	"srcd.works/go-git.v4/config"
	"srcd.works/go-git.v4/plumbing"
)

// Submodule a submodule allows you to keep another Git repository in a
// subdirectory of your repository.
type Submodule struct {
	m *config.Submodule
	w *Worktree
	// r is the submodule repository
	r *Repository
}

// Config returns the submodule config
func (s *Submodule) Config() *config.Submodule {
	return s.m
}

// Init initialize the submodule reading the recoreded Entry in the index for
// the given submodule
func (s *Submodule) Init() error {
	e, err := s.w.readIndexEntry(s.m.Path)
	if err != nil {
		return err
	}

	_, err = s.r.CreateRemote(&config.RemoteConfig{
		Name: DefaultRemoteName,
		URL:  s.m.URL,
	})

	if err != nil {
		return err
	}

	return s.fetchAndCheckout(e.Hash)
}

// Update  the registered submodule to match what the superproject expects
func (s *Submodule) Update() error {
	e, err := s.w.readIndexEntry(s.m.Path)
	if err != nil {
		return err
	}

	return s.fetchAndCheckout(e.Hash)
}

func (s *Submodule) fetchAndCheckout(hash plumbing.Hash) error {
	if err := s.r.Fetch(&FetchOptions{}); err != nil && err != NoErrAlreadyUpToDate {
		return err
	}

	w, err := s.r.Worktree()
	if err != nil {
		return err
	}

	if err := w.Checkout(hash); err != nil {
		return err
	}

	head := plumbing.NewHashReference(plumbing.HEAD, hash)
	return s.r.Storer.SetReference(head)
}

// Submodules list of several submodules from the same repository
type Submodules []*Submodule

// Init initialize the submodule recorded in the index
func (s Submodules) Init() error {
	for _, sub := range s {
		if err := sub.Init(); err != nil {
			return err
		}
	}

	return nil
}