aboutsummaryrefslogtreecommitdiffstats
path: root/worktree.go
blob: 2aefa7661d739d0f6a3294cc1c63ea9493afda99 (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
package git

import (
	"io"
	"os"

	"gopkg.in/src-d/go-git.v4/plumbing"
	"gopkg.in/src-d/go-git.v4/plumbing/object"

	"srcd.works/go-billy.v1"
)

type Worktree struct {
	r  *Repository
	fs billy.Filesystem
}

func (w *Worktree) Checkout(commit plumbing.Hash) error {
	c, err := w.r.Commit(commit)
	if err != nil {
		return err
	}

	files, err := c.Files()
	if err != nil {
		return err
	}

	return files.ForEach(w.checkoutFile)
}

func (w *Worktree) checkoutFile(f *object.File) error {
	from, err := f.Reader()
	if err != nil {
		return err
	}

	defer from.Close()
	to, err := w.fs.OpenFile(f.Name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode)
	if err != nil {
		return err
	}

	if _, err := io.Copy(to, from); err != nil {
		return err
	}

	return to.Close()
}