summaryrefslogtreecommitdiff
path: root/doPatch.go
blob: 763f14b6b2bfabbf5124c0dbf12c8cab90f47dd7 (plain)
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
// Copyright 2017-2025 WIT.COM Inc. All rights reserved.
// Use of this source code is governed by the GPL 3.0

package main

import (
	"bytes"
	"errors"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strings"

	"go.wit.com/lib/config"
	"go.wit.com/lib/env"
	"go.wit.com/lib/fhelp"
	"go.wit.com/lib/protobuf/forgepb"
	"go.wit.com/lib/protobuf/gitpb"
	"go.wit.com/log"
)

func isPatchingSafe() bool {
	if me.forge.IsModeNormal() {
		return true
	}
	log.Info("This patch command is not safe to run now")
	log.Info("you must reset the state of your git repositories. Run:")
	log.Info("")
	log.Info("forge normal (or use --force)")
	log.Info("")
	if argv.Force {
		return true
	}
	return false
}

func doPatch() (string, error) {
	// var changed bool
	me.curpatches = forgepb.NewPatches()
	me.curpatches.Filename = env.Get("curpatches")
	if me.curpatches.Filename == "" {
		panic("config failed. no 'curpatches' set in ~/.config/forge/config.text")
	}
	if err := config.LoadCacheDir(me.curpatches); err != nil {
		log.Info("tried to load curpatches from:", me.curpatches.Filename)
		panic("no file")
	}

	// just show the table and exit
	if argv.Patch.Show {
		footer := me.curpatches.PrintTable()
		return "all current patches: " + footer, nil
	}

	// send them onward again
	if argv.Patch.Submit {
		return doPatchSubmit()
	}

	psets := forgepb.NewSets()
	newpb, _, err := psets.HttpPostVerbose(myServer(), "get")
	if err != nil {
		return "http post failed", err
	}
	if newpb == nil {
		return "psets.HttpPost returned nil", err
	}
	footer, err := doPatchGet(newpb)
	if footer == "" {
		log.Info(footer)
	}

	// forces patching to be done in 'NORMAL' mode
	// forge is too new to be able to handle anything else
	if !isPatchingSafe() {
		return "not safe", errors.New("not safe to work on patches")
	}

	s, err := doPatchProcess()
	return s, err
}

// submit's current working patches
func doPatchSubmit() (string, error) {
	pset, err := me.forge.MakeDevelPatchSet("testing")
	if err != nil {
		return "MakeDevelPatchSet(testing)", err
	}
	if pset.Patches == nil {
		return "pset.Patches == nil", err
	}
	if pset.Patches.Len() == 0 {
		return "did not find any patches", nil
	}
	footer := pset.PrintTable()
	_, _, err = pset.HttpPost(myServer(), "new")
	return footer, err
}

func doPatchProcess() (string, error) {
	var needfix int
	needapply := forgepb.NewPatches()
	for patch := range me.curpatches.IterAll() {
		repo := me.forge.Repos.FindByNamespace(patch.Namespace)
		if repo == nil {
			// log.Info("no namespace", patch.PatchId, patch.Namespace, patch.Comment)
			patch.State = "no namespace"
			continue
		}
		if patch.NewHash == "na" {
			patch.State = "was na"
			needfix = 1
		}
		newId, newHash, err := isPatchIdApplied(repo, patch)
		if errors.Is(err, ErrorGitPullOnDirty) {
			log.Info(patch.PatchId, newId, repo.Namespace, "repo dirty", patch.Comment)
			patch.State = "repo dirty"
			// log.Info("a patch with that comment couldn't be found in the repo")
		} else if err != nil {
			// log.Info(patch.PatchId, newId, repo.Namespace, err, patch.Comment)
			patch.State = "applied err"
			patch.StateChange = log.Sprintf("%v", err)
			// return "isPatchIdApplied() error", patch.Error(err)
		}
		if newId == "" {
			// new patch !
			// log.Info(patch.PatchId, "newId==''", patch.Comment)
		} else {
			if (newId == patch.PatchId) && (newHash == patch.CommitHash) {
				// log.Info(patch.PatchId, newId, repo.Namespace, "patch made here", patch.Comment)
				patch.StateChange = "made here"
				patch.NewHash = "author"
				continue
			}
			if newId == patch.PatchId {
				patch.NewHash = patch.CommitHash
				// log.Info(patch.PatchId, newId, repo.Namespace, "patch already applied", patch.Comment)
				patch.StateChange = "did already"
				if patch.State == "was na" {
					patch.State = "applied"
				}
				continue
			}
			if newId != patch.PatchId {
				// log.Info(patch.PatchId, newId, repo.Namespace, "probably duplicate subject? (mismatch)", patch.Comment)
				patch.StateChange = "dup subject?"
				// try this. it should compute every patch id in the repo
				// os.Chdir(repo.FullPath)
				// newNewId, err := searchAllCommits(targetPatchID string) (string, error) {
			}
		}
		// log.Info(patch.PatchId, newId, repo.Namespace, "new patch", patch.Comment)
		patch.State = "new patch"
		needapply.Clone(patch)
	}
	var applycounter int
	for patch := range needapply.IterAll() {
		repo := me.forge.Repos.FindByNamespace(patch.Namespace)
		if repo == nil {
			if argv.Verbose {
				// dump the whole patch
				log.Info("skipping patch for unknown namespace", patch.Namespace)
			}
			continue
		}
		if argv.Patch == nil {
			needfix += 1
			continue
		}
		// if !me.argv.If("--apply") {
		if !argv.Patch.Apply {
			// --apply isn't set. don't go any further
			needfix += 1
			continue
		}
		// show some of the patch details
		if argv.Verbose {
			// dump the whole patch
			log.Info(string(patch.Data))
		}
		log.Info(repo.FullPath, "")
		log.Info(repo.FullPath, patch.Comment)
		for _, fname := range patch.Files {
			log.Info(repo.FullPath, fname)
		}
		for _, line := range strings.Split(string(patch.Data), "\n") {
			// log.Info(repo.FullPath, line)
			if strings.HasPrefix(line, "From: ") {
				log.Info(repo.FullPath, line)
				continue
			}
			if strings.HasPrefix(line, "Date: ") {
				log.Info(repo.FullPath, line)
				continue
			}
			if strings.HasPrefix(line, "---") {
				break
			}
			if line == "-- " {
				break
			}
		}
		log.Info(repo.FullPath, patch.Gan, patch.Gae, patch.GaI)
		// prompt user to apply patch
		applycounter += 1
		s := log.Sprintf("apply this patch (%d/%d)? (--force to autoapply)", applycounter, needapply.Len())
		if fhelp.QuestionUser(s) {
			newhash, err := applyPatch(repo, patch)
			if err != nil {
				log.Info("apply results:", newhash, err)
			}
			if err != nil {
				return "git am problem. manually investigate or purge everything and start over", err
			}
		}
	}
	// NOW, FINALLY, AFTER A LOT OF WORK, THE FUN PART
	newpatches := forgepb.NewPatches()
	for p := range me.curpatches.IterAll() {
		if p.NewHash == "author" {
			// this is your patch
			continue
		}
		if (p.NewHash != "") && p.StateChange == "did already" {
			// already applied
			continue
		}
		if p.State == "no namespace" {
			// you don't have this repo on your disk
			continue
		}
		newpatches.Clone(p)
	}
	me.curpatches.Save()
	if newpatches.Len() == 0 {
		s := log.Sprintf("All (%d) current patches are appled. You are completely up to date!", me.curpatches.Len())
		return s, nil
	}
	footer := newpatches.PrintTable()
	log.Info("BRAND NEW PATCHES:", footer)
	var s string
	s = log.Sprintf("There are %d new patches. Use --apply to apply them", needfix)
	return s, nil
}

func applyPatch(repo *gitpb.Repo, p *forgepb.Patch) (string, error) {
	_, filen := filepath.Split(p.Filename)
	tmpname := filepath.Join("/tmp", filen)
	log.Info("saving as", tmpname, p.Filename)
	raw, err := os.OpenFile(tmpname, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
	if err != nil {
		return "", err
	}
	raw.Write(p.Data)
	raw.Close()

	log.Info("")
	// always run abort first
	cmd := []string{"git", "am", "--abort"}
	stats := repo.Run(cmd)
	if stats.Error != nil {
		panic("git am --abort failed")
	}
	log.Info("Ran 'git am --abort' for safety and everything seems ok")
	// if stats.Outp == nil {
	// 	log.Info("todo: move this to linux/ and do things correctly")
	// }

	// git apply --check /tmp/0001-renamed-file-and-added-stuff.patch
	cmd = []string{"git", "apply", "--check", tmpname}
	log.Info("Running:", cmd)
	stats = repo.Run(cmd)
	if stats.Error != nil {
		panic("git apply --check failed")
	}
	if stats.Exit != 0 {
		panic("git apply --check failed")
	}
	log.Info("Ran 'git apply --check' and everything seems ok")

	/*
			// The current 'best practice' thanks to Gemini. the current LLM's are useful for this sorta thing

			// git apply --reject /tmp/0001-renamed-file-and-added-stuff.patch

		     Step 4: Fix the Conflict

		      1. List the reject files: ls *.rej.
		      2. Open the .rej file and the corresponding source file (e.g., some/file.go.rej and some/file.go).
		      3. The .rej file shows you the lines that couldn't be applied. Manually edit your source file to incorporate the changes
		         from the patch correctly.
		      4. Once you've fixed the file, delete the .rej file.

		     Step 5: Commit the Result

		     Once all .rej files are gone and your code is in the state you want, you need to finalize the operation. Since you
		     applied the changes manually, you now need to commit them.

		      1 # Add all the files you manually fixed
		      2 git add .
		      3
		      4 # Now, commit the changes. You can get the commit message from the patch file.
		      5 git commit -F /tmp/0001-renamed-file-and-added-stuff.patch

			git reset --hard HEAD
			git clean -fd          # The -f flag forces the removal, and -d removes untracked directories.
	*/

	cmd = []string{"git", "am", tmpname}
	err = repo.RunVerbose(cmd)
	if err != nil {
		// always run abort after failure. todo: add --keep
		cmd := []string{"git", "am", "--abort"}
		err = repo.RunVerbose(cmd)
		log.Info("git am failed. run 'git am --abort' here")
		return "", log.Errorf("git am failed")
	}
	log.Info(cmd)
	log.Info("everything worked ok")
	return "patch applied with git am", nil
}

func doPatchGet(newpb *forgepb.Sets) (string, error) {
	newpatches := forgepb.NewPatches()
	if newpb == nil {
		return "doPatchGet() newpb == nil", errors.New("doPatchGet() newpb == nil")
	}
	for pset := range newpb.IterAll() {
		if pset.Patches.Len() == 0 {
			log.Info("pset is empty", pset.Name)
			continue
		}
		for patch := range pset.Patches.IterAll() {
			if len(patch.Data) == 0 {
				continue
			}
			patchid, hash, err := gitpb.FindPatchIdFromGitAm(patch.Data)
			if err != nil {
				log.Info("git patchid exec err", err)
				continue
			}
			if hash != patch.CommitHash {
				log.Info("ERROR: patch commit hashes's didn't match", hash, patch.CommitHash)
				continue
			}
			if patchid != patch.PatchId {
				log.Info("ERROR: patchid's didn't match", patchid, patch.PatchId)
				continue
			}
			found := me.curpatches.FindByPatchId(patch.PatchId)
			if found != nil {
				// already have this patch
				continue
			}
			// gitpb.FindPatchIdFromGitAmBroken(patch.Data) // doesn't os.Exec()
			log.Info("adding new patch", patch.CommitHash, patch.PatchId, patch.Filename)
			me.curpatches.AppendByPatchId(patch)
			newpatches.AppendByPatchId(patch)
		}
	}
	if newpatches.Len() == 0 {
		return "", nil
	}
	footer := newpatches.PrintTable()
	me.curpatches.Save()
	s := log.Sprintf("got %d new patches. %s", newpatches.Len(), footer)
	return s, nil
}

var ErrorGitPullOnDirty error = errors.New("git comment is not there")

func isPatchIdApplied(repo *gitpb.Repo, patch *forgepb.Patch) (string, string, error) {
	comment := cleanSubject(patch.Comment)

	os.Chdir(repo.GetFullPath())
	newhash, err := findCommitBySubject(repo, comment, patch)
	if err != nil {
		return "", "", err
	}

	patchId, err := repo.FindPatchIdByHash(newhash)
	if err != nil {
		return "", "", err
	}

	// log.Infof("%s %s found hash by comment %s \n", patchId, newhash, patch.Comment)
	return patchId, newhash, nil
}

func cleanSubject(line string) string {
	// Regular expression to remove "Subject:" and "[PATCH...]" patterns
	re := regexp.MustCompile(`(?i)^Subject:\s*(\[\s*PATCH[^\]]*\]\s*)?`)
	cleaned := re.ReplaceAllString(line, "")
	return strings.TrimSpace(cleaned)
}

func findCommitBySubject(repo *gitpb.Repo, subject string, newpatch *forgepb.Patch) (string, error) {
	parts := strings.Split(subject, " /")
	subject = parts[0]
	if subject == "" {
		return "", errors.New("subject blank. must brute force")
	}
	cmd := exec.Command("git", "log", "--pretty=format:%H %s", "--grep="+subject, "-i")
	var out bytes.Buffer
	cmd.Stdout = &out
	err := cmd.Run()
	if err != nil {
		return "", err
	}

	lines := strings.Split(out.String(), "\n")
	for _, line := range lines {
		if strings.Contains(strings.ToLower(line), strings.ToLower(subject)) {
			parts := strings.Fields(line)
			patchId, _ := repo.FindPatchIdByHash(parts[0])
			if patchId == newpatch.PatchId {
				return strings.Fields(line)[0], nil // return the commit hash
			}
		}
	}
	return "", fmt.Errorf("no commit found for subject: %s", subject)
}