aboutsummaryrefslogtreecommitdiffstats
path: root/commands/patch/apply.go
blob: c9818876e139c68fd5b8130722c7e9e0a74a666b (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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package patch

import (
	"fmt"
	"sort"
	"strings"
	"unicode"

	"git.sr.ht/~rjarry/aerc/app"
	"git.sr.ht/~rjarry/aerc/commands"
	"git.sr.ht/~rjarry/aerc/commands/msg"
	"git.sr.ht/~rjarry/aerc/lib/log"
	"git.sr.ht/~rjarry/aerc/lib/pama"
	"git.sr.ht/~rjarry/aerc/lib/pama/models"
)

type Apply struct {
	Cmd      string `opt:"-c"`
	Worktree string `opt:"-w"`
	Tag      string `opt:"tag" required:"true" complete:"CompleteTag"`
}

func init() {
	register(Apply{})
}

func (Apply) Context() commands.CommandContext {
	return commands.MESSAGE
}

func (Apply) Aliases() []string {
	return []string{"apply"}
}

func (*Apply) CompleteTag(arg string) []string {
	patches, err := pama.New().CurrentPatches()
	if err != nil {
		log.Errorf("failed to current patches for completion: %v", err)
		patches = nil
	}

	acct := app.SelectedAccount()
	if acct == nil {
		return nil
	}

	uids, err := acct.MarkedMessages()
	if err != nil {
		return nil
	}
	if len(uids) == 0 {
		msg, err := acct.SelectedMessage()
		if err == nil {
			uids = append(uids, msg.Uid)
		}
	}

	store := acct.Store()
	if store == nil {
		return nil
	}

	var subjects []string
	for _, uid := range uids {
		if msg, ok := store.Messages[uid]; !ok || msg == nil || msg.Envelope == nil {
			continue
		} else {
			subjects = append(subjects, msg.Envelope.Subject)
		}
	}
	return proposePatchName(patches, subjects)
}

func (a Apply) Execute(args []string) error {
	patch := a.Tag
	worktree := a.Worktree
	applyCmd := a.Cmd

	m := pama.New()
	p, err := m.CurrentProject()
	if err != nil {
		return err
	}
	log.Tracef("Current project: %v", p)

	if worktree != "" {
		p, err = m.CreateWorktree(p, worktree, patch)
		if err != nil {
			return err
		}
		err = m.SwitchProject(p.Name)
		if err != nil {
			log.Warnf("could not switch to worktree project: %v", err)
		}
	}

	if models.Commits(p.Commits).HasTag(patch) {
		return fmt.Errorf("Patch name '%s' already exists.", patch)
	}

	if !m.Clean(p) {
		return fmt.Errorf("Aborting... There are unstaged changes in " +
			"your repository.")
	}

	commit, err := m.Head(p)
	if err != nil {
		return err
	}
	log.Tracef("HEAD commit before: %s", commit)

	if applyCmd != "" {
		rootFmt := "%r"
		if strings.Contains(applyCmd, rootFmt) {
			applyCmd = strings.ReplaceAll(applyCmd, rootFmt, p.Root)
		}
		log.Infof("use custom apply command: %s", applyCmd)
	} else {
		applyCmd, err = m.ApplyCmd(p)
		if err != nil {
			return err
		}
	}

	msgData := collectMessageData()

	// apply patches with the pipe cmd
	pipe := msg.Pipe{
		Background: false,
		Full:       true,
		Part:       false,
		Command:    applyCmd,
	}
	return pipe.Run(func() {
		p, err = m.ApplyUpdate(p, patch, commit, msgData)
		if err != nil {
			log.Errorf("Failed to save patch data: %v", err)
		}
	})
}

// collectMessageData returns a map where the key is the message id and the
// value the subject of the marked messages
func collectMessageData() map[string]string {
	acct := app.SelectedAccount()
	if acct == nil {
		return nil
	}

	uids, err := commands.MarkedOrSelected(acct)
	if err != nil {
		log.Errorf("error occurred: %v", err)
		return nil
	}

	store := acct.Store()
	if store == nil {
		return nil
	}

	kv := make(map[string]string)
	for _, uid := range uids {
		msginfo, ok := store.Messages[uid]
		if !ok || msginfo == nil {
			continue
		}
		id, err := msginfo.MsgId()
		if err != nil {
			continue
		}
		if msginfo.Envelope == nil {
			continue
		}

		kv[id] = msginfo.Envelope.Subject
	}

	return kv
}

func proposePatchName(patches, subjects []string) []string {
	parse := func(s string) (string, string, bool) {
		var tag strings.Builder
		var version string
		var i, j int

		i = strings.Index(s, "[")
		if i < 0 {
			goto noPatch
		}
		s = s[i+1:]

		j = strings.Index(s, "]")
		if j < 0 {
			goto noPatch
		}
		for _, elem := range strings.Fields(s[:j]) {
			vers := strings.ToLower(elem)
			if !strings.HasPrefix(vers, "v") {
				continue
			}
			isVersion := true
			for _, r := range vers[1:] {
				if !unicode.IsDigit(r) {
					isVersion = false
					break
				}
			}
			if isVersion {
				version = vers
				break
			}
		}
		s = strings.TrimSpace(s[j+1:])

		for _, r := range s {
			if unicode.IsSpace(r) || r == ':' {
				break
			}
			_, err := tag.WriteRune(r)
			if err != nil {
				continue
			}
		}
		return tag.String(), version, true
	noPatch:
		return "", "", false
	}

	summary := make(map[string]struct{})

	var results []string
	for _, s := range subjects {
		tag, version, isPatch := parse(s)
		if tag == "" || !isPatch {
			continue
		}
		if version == "" {
			version = "v1"
		}
		result := fmt.Sprintf("%s_%s", tag, version)
		result = strings.ReplaceAll(result, " ", "")

		collision := false
		for _, name := range patches {
			if name == result {
				collision = true
			}
		}
		if collision {
			continue
		}

		_, ok := summary[result]
		if ok {
			continue
		}
		results = append(results, result)
		summary[result] = struct{}{}
	}

	sort.Strings(results)
	return results
}