aboutsummaryrefslogtreecommitdiffstats
path: root/lib/pama/worktree.go
blob: 1718e430a903e5219b53cef568676b8c00380d8a (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
package pama

import (
	"fmt"
	"os"
	"path"
	"path/filepath"
	"strings"

	"git.sr.ht/~rjarry/aerc/lib/log"
	"git.sr.ht/~rjarry/aerc/lib/pama/models"
	"git.sr.ht/~rjarry/aerc/lib/xdg"
)

func cacheDir() (string, error) {
	dir, err := os.UserCacheDir()
	if err != nil {
		dir = xdg.ExpandHome("~/.cache")
	}
	return path.Join(dir, "aerc"), nil
}

func makeWorktreeName(baseProject, tag string) string {
	unique, err := generateTag(4)
	if err != nil {
		log.Infof("could not generate unique id: %v", err)
	}
	return strings.Join([]string{baseProject, "worktree", tag, unique}, "_")
}

func isWorktree(p models.Project) bool {
	return p.Worktree.Name != "" && p.Worktree.Root != ""
}

func (m PatchManager) CreateWorktree(p models.Project, commitID, tag string,
) (models.Project, error) {
	var w models.Project

	if isWorktree(p) {
		return w, fmt.Errorf("This is already a worktree.")
	}

	w.RevctrlID = p.RevctrlID
	w.Base = models.Commit{ID: commitID}
	w.Name = makeWorktreeName(p.Name, tag)
	w.Worktree = models.WorktreeParent{Name: p.Name, Root: p.Root}

	dir, err := cacheDir()
	if err != nil {
		return p, err
	}
	w.Root = filepath.Join(dir, "worktrees", w.Name)

	rc, err := m.rc(p.RevctrlID, p.Root)
	if err != nil {
		return p, revErr(err)
	}

	err = rc.CreateWorktree(w.Root, w.Base.ID)
	if err != nil {
		return p, revErr(err)
	}

	err = m.store().StoreProject(w, true)
	if err != nil {
		return p, storeErr(err)
	}

	return w, nil
}

func (m PatchManager) deleteWorktree(p models.Project) error {
	if !isWorktree(p) {
		return nil
	}

	rc, err := m.rc(p.RevctrlID, p.Worktree.Root)
	if err != nil {
		return revErr(err)
	}

	err = rc.DeleteWorktree(p.Root)
	if err != nil {
		return revErr(err)
	}

	return nil
}