aboutsummaryrefslogtreecommitdiffstats
path: root/commands/patch/rebase.go
blob: 6ef43299b61d2128403186f43cf7702a9bf257c2 (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
package patch

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"os"
	"os/exec"
	"sort"
	"strings"
	"time"

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

type Rebase struct {
	Commit string `opt:"commit" required:"false"`
}

func init() {
	register(Rebase{})
}

func (Rebase) Context() commands.CommandContext {
	return commands.GLOBAL
}

func (Rebase) Aliases() []string {
	return []string{"rebase"}
}

func (r Rebase) Execute(args []string) error {
	m := pama.New()
	current, err := m.CurrentProject()
	if err != nil {
		return err
	}

	baseID := r.Commit
	if baseID == "" {
		baseID = current.Base.ID
	}

	commits, err := m.RebaseCommits(current, baseID)
	if err != nil {
		return err
	}

	if len(commits) == 0 {
		err := m.SaveRebased(current, baseID, nil)
		if err != nil {
			return fmt.Errorf("No commits to rebase, but saving of new reference failed: %w", err)
		}
		app.PushStatus("No commits to rebase.", 10*time.Second)
		return nil
	}

	rebase := newRebase(commits)
	f, err := os.CreateTemp("", "aerc-patch-rebase-*")
	if err != nil {
		return err
	}
	name := f.Name()
	_, err = io.Copy(f, rebase.content())
	if err != nil {
		return err
	}
	f.Close()

	createWidget := func() (ui.DrawableInteractive, error) {
		editorCmd, err := app.CmdFallbackSearch(config.EditorCmds(), true)
		if err != nil {
			return nil, err
		}
		editor := exec.Command("/bin/sh", "-c", editorCmd+" "+name)
		term, err := app.NewTerminal(editor)
		if err != nil {
			return nil, err
		}
		term.OnClose = func(_ error) {
			app.CloseDialog()
			defer os.Remove(name)
			defer term.Focus(false)

			f, err := os.Open(name)
			if err != nil {
				app.PushError(fmt.Sprintf("failed to open file: %v", err))
				return
			}
			defer f.Close()

			if editor.ProcessState.ExitCode() > 0 {
				app.PushError("Quitting rebase without saving.")
				return
			}
			err = m.SaveRebased(current, baseID, rebase.parse(f))
			if err != nil {
				app.PushError(fmt.Sprintf("Failed to save rebased commits: %v", err))
				return
			}
			app.PushStatus("Successfully rebased.", 10*time.Second)
		}
		term.Show(true)
		term.Focus(true)
		return term, nil
	}

	viewer, err := createWidget()
	if err != nil {
		return err
	}

	app.AddDialog(app.NewDialog(
		ui.NewBox(viewer, fmt.Sprintf("Patch Rebase on %-6.6s", baseID), "",
			app.SelectedAccountUiConfig(),
		),
		// start pos on screen
		func(h int) int {
			return h / 8
		},
		// dialog height
		func(h int) int {
			return h - 2*h/8
		},
	))

	return nil
}

type rebase struct {
	commits []models.Commit
	table   map[string]models.Commit
	order   []string
}

func newRebase(commits []models.Commit) *rebase {
	return &rebase{
		commits: commits,
		table:   make(map[string]models.Commit),
	}
}

const (
	header string = ""
	footer string = `
# Rebase aerc's patch data. This will not affect the underlying repository in
# any way.
#
# Change the name in the first column to assign a new tag to a commit. To group
# multiple commits, use the same tag name.
#
# An 'untracked' tag indicates that aerc lost track of that commit, either due
# to a commit-hash change or because that commit was applied outside of aerc.
#
# Do not change anything else besides the tag names (first column).
#
# Do not reorder the lines. The ordering should remain as in the repository.
#
# If you remove a line or keep an 'untracked' tag, those commits will be removed
# from aerc's patch tracking.
#
`
)

func (r *rebase) content() io.Reader {
	var buf bytes.Buffer
	buf.WriteString(header)
	for _, c := range r.commits {
		tag := c.Tag
		if tag == "" {
			tag = models.Untracked
		}
		shortHash := fmt.Sprintf("%6.6s", c.ID)
		buf.WriteString(
			fmt.Sprintf("%-12s     %6.6s     %s\n", tag, shortHash, c.Info()))
		r.table[shortHash] = c
		r.order = append(r.order, shortHash)
	}
	buf.WriteString(footer)
	return &buf
}

func (r *rebase) parse(reader io.Reader) []models.Commit {
	var commits []models.Commit
	var hashes []string
	scanner := bufio.NewScanner(reader)
	duplicated := make(map[string]struct{})
	for scanner.Scan() {
		s := scanner.Text()
		i := strings.Index(s, "#")
		if i >= 0 {
			s = s[:i]
		}
		if strings.TrimSpace(s) == "" {
			continue
		}

		fds := strings.Fields(s)
		if len(fds) < 2 {
			continue
		}

		tag, shortHash := fds[0], fds[1]
		if tag == models.Untracked {
			continue
		}
		_, dedup := duplicated[shortHash]
		if dedup {
			log.Warnf("rebase: skipping duplicated hash: %s", shortHash)
			continue
		}

		hashes = append(hashes, shortHash)
		c, ok := r.table[shortHash]
		if !ok {
			log.Errorf("Looks like the commit hashes were changed "+
				"during the rebase. Dropping: %v", shortHash)
			continue
		}
		log.Tracef("save commit %s with tag %s", shortHash, tag)
		c.Tag = tag
		commits = append(commits, c)
		duplicated[shortHash] = struct{}{}
	}
	reorder(commits, hashes, r.order)
	return commits
}

func reorder(toSort []models.Commit, now []string, by []string) {
	byMap := make(map[string]int)
	for i, s := range by {
		byMap[s] = i
	}

	complete := true
	for _, s := range now {
		_, ok := byMap[s]
		complete = complete && ok
	}
	if !complete {
		return
	}

	sort.SliceStable(toSort, func(i, j int) bool {
		return byMap[now[i]] < byMap[now[j]]
	})
}