Debian Codegraph @

commands/patch/apply.go

raw
1 package patch
2
3 import (
4 "fmt"
5 "slices"
6 "strings"
7 "unicode"
8
9 "git.sr.ht/~rjarry/aerc/app"
10 "git.sr.ht/~rjarry/aerc/commands"
11 "git.sr.ht/~rjarry/aerc/commands/msg"
12 "git.sr.ht/~rjarry/aerc/lib/log"
13 "git.sr.ht/~rjarry/aerc/lib/pama"
14 "git.sr.ht/~rjarry/aerc/lib/pama/models"
15 )
16
17 type Apply struct {
18 Cmd string `opt:"-c" desc:"Apply patches with provided command."`
19 Worktree string `opt:"-w" desc:"Create linked worktree on this <commit-ish>."`
20 Tag string `opt:"tag" required:"true" complete:"CompleteTag" desc:"Identify patches with tag."`
21 }
22
23 func init() {
24 register(Apply{})
25 }
26
27 func (Apply) Description() string {
28 return "Apply the selected message(s) to the current project."
29 }
30
31 func (Apply) Context() commands.CommandContext {
32 return commands.MESSAGE_LIST | commands.MESSAGE_VIEWER
33 }
34
35 func (Apply) Aliases() []string {
36 return []string{"apply"}
37 }
38
39 func (*Apply) CompleteTag(arg string) []string {
40 patches, err := pama.New().CurrentPatches()
41 if err != nil {
42 log.Errorf("failed to current patches for completion: %v", err)
43 patches = nil
44 }
45
46 acct := app.SelectedAccount()
47 if acct == nil {
48 return nil
49 }
50
51 uids, err := acct.MarkedMessages()
52 if err != nil {
53 return nil
54 }
55 if len(uids) == 0 {
56 msg, err := acct.SelectedMessage()
57 if err == nil {
58 uids = append(uids, msg.Uid)
59 }
60 }
61
62 store := acct.Store()
63 if store == nil {
64 return nil
65 }
66
67 var subjects []string
68 for _, uid := range uids {
69 if msg, ok := store.Messages[uid]; !ok || msg == nil || msg.Envelope == nil {
70 continue
71 } else {
72 subjects = append(subjects, msg.Envelope.Subject)
73 }
74 }
75 return proposePatchName(patches, subjects)
76 }
77
78 func (a Apply) Execute(args []string) error {
79 patch := a.Tag
80 worktree := a.Worktree
81 applyCmd := a.Cmd
82
83 m := pama.New()
84 p, err := m.CurrentProject()
85 if err != nil {
86 return err
87 }
88 log.Tracef("Current project: %v", p)
89
90 if worktree != "" {
91 p, err = m.CreateWorktree(p, worktree, patch)
92 if err != nil {
93 return err
94 }
95 err = m.SwitchProject(p.Name)
96 if err != nil {
97 log.Warnf("could not switch to worktree project: %v", err)
98 }
99 }
100
101 if models.Commits(p.Commits).HasTag(patch) {
102 return fmt.Errorf("Patch name '%s' already exists.", patch)
103 }
104
105 if !m.Clean(p) {
106 return fmt.Errorf("Aborting... There are unstaged changes in " +
107 "your repository.")
108 }
109
110 commit, err := m.Head(p)
111 if err != nil {
112 return err
113 }
114 log.Tracef("HEAD commit before: %s", commit)
115
116 if applyCmd != "" {
117 rootFmt := "%r"
118 if strings.Contains(applyCmd, rootFmt) {
119 applyCmd = strings.ReplaceAll(applyCmd, rootFmt, p.Root)
120 }
121 log.Infof("use custom apply command: %s", applyCmd)
122 } else {
123 applyCmd, err = m.ApplyCmd(p)
124 if err != nil {
125 return err
126 }
127 }
128
129 msgData := collectMessageData()
130
131 // apply patches with the pipe cmd
132 pipe := msg.Pipe{
133 Background: false,
134 Full: true,
135 Part: false,
136 Command: applyCmd,
137 }
138 return pipe.Run(func() {
139 p, err = m.ApplyUpdate(p, patch, commit, msgData)
140 if err != nil {
141 log.Errorf("Failed to save patch data: %v", err)
142 }
143 })
144 }
145
146 // collectMessageData returns a map where the key is the message id and the
147 // value the subject of the marked messages
148 func collectMessageData() map[string]string {
149 acct := app.SelectedAccount()
150 if acct == nil {
151 return nil
152 }
153
154 uids, err := commands.MarkedOrSelected(acct)
155 if err != nil {
156 log.Errorf("error occurred: %v", err)
157 return nil
158 }
159
160 store := acct.Store()
161 if store == nil {
162 return nil
163 }
164
165 kv := make(map[string]string)
166 for _, uid := range uids {
167 msginfo, ok := store.Messages[uid]
168 if !ok || msginfo == nil {
169 continue
170 }
171 id, err := msginfo.MsgId()
172 if err != nil {
173 continue
174 }
175 if msginfo.Envelope == nil {
176 continue
177 }
178
179 kv[id] = msginfo.Envelope.Subject
180 }
181
182 return kv
183 }
184
185 func proposePatchName(patches, subjects []string) []string {
186 parse := func(s string) (string, string, bool) {
187 var tag strings.Builder
188 var version string
189 var i, j int
190
191 i = strings.Index(s, "[")
192 if i < 0 {
193 goto noPatch
194 }
195 s = s[i+1:]
196
197 j = strings.Index(s, "]")
198 if j < 0 {
199 goto noPatch
200 }
201 for _, elem := range strings.Fields(s[:j]) {
202 vers := strings.ToLower(elem)
203 if !strings.HasPrefix(vers, "v") {
204 continue
205 }
206 isVersion := true
207 for _, r := range vers[1:] {
208 if !unicode.IsDigit(r) {
209 isVersion = false
210 break
211 }
212 }
213 if isVersion {
214 version = vers
215 break
216 }
217 }
218 s = strings.TrimSpace(s[j+1:])
219
220 for _, r := range s {
221 if unicode.IsSpace(r) || r == ':' {
222 break
223 }
224 _, err := tag.WriteRune(r)
225 if err != nil {
226 continue
227 }
228 }
229 return tag.String(), version, true
230 noPatch:
231 return "", "", false
232 }
233
234 summary := make(map[string]struct{})
235
236 var results []string
237 for _, s := range subjects {
238 tag, version, isPatch := parse(s)
239 if tag == "" || !isPatch {
240 continue
241 }
242 if version == "" {
243 version = "v1"
244 }
245 result := fmt.Sprintf("%s_%s", tag, version)
246 result = strings.ReplaceAll(result, " ", "")
247
248 collision := false
249 for _, name := range patches {
250 if name == result {
251 collision = true
252 }
253 }
254 if collision {
255 continue
256 }
257
258 _, ok := summary[result]
259 if ok {
260 continue
261 }
262 results = append(results, result)
263 summary[result] = struct{}{}
264 }
265
266 slices.Sort(results)
267 return results
268 }