File: stack_struct.go

package info (click to toggle)
glab 1.53.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 20,936 kB
  • sloc: sh: 295; makefile: 153; perl: 99; ruby: 68; javascript: 67
file content (341 lines) | stat: -rw-r--r-- 7,120 bytes parent folder | download
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
package git

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/fs"
	"iter"
	"os"
	"path/filepath"
	"strings"
)

type StackRef struct {
	Prev        string `json:"prev"`
	Branch      string `json:"branch"`
	SHA         string `json:"sha"`
	Next        string `json:"next"`
	MR          string `json:"mr"`
	Description string `json:"description"`
}

// Stack represents a stacked diff data structure.
// Refs are structured as a doubly linked list where
// the links are identified with the StackRef.Prev
// and StackRef.Next fields.
// The StackRef.SHA is the id that the former two
// fields can point to.
// All stacks must be created with GatherStackRefs
// which validates the stack for consistency.
type Stack struct {
	Title string
	Refs  map[string]StackRef
}

func (s Stack) Empty() bool { return len(s.Refs) == 0 }

func (s *Stack) RemoveRef(ref StackRef) error {
	if ref.IsFirst() && ref.IsLast() {
		// this is the only ref, so just remove it
		err := DeleteStackRefFile(s.Title, ref)
		delete(s.Refs, ref.SHA)
		if err != nil {
			return fmt.Errorf("could not delete reference file %v:", err)
		}

		return nil
	}

	err := s.adjustAdjacentRefs(ref)
	if err != nil {
		return fmt.Errorf("error adjusting next reference %v:", err)
	}

	err = DeleteStackRefFile(s.Title, ref)
	if err != nil {
		return fmt.Errorf("could not delete reference file %v:", err)
	}

	err = s.RemoveBranch(ref)
	if err != nil {
		return fmt.Errorf("could not remove branch %v:", err)
	}

	delete(s.Refs, ref.SHA)

	return nil
}

func (s *Stack) RemoveBranch(ref StackRef) error {
	var branch string
	var err error

	if ref.IsFirst() {
		branch, err = GetDefaultBranch(DefaultRemote)
		if err != nil {
			return err
		}

	} else {
		branch = s.Refs[ref.Prev].Branch
	}

	err = CheckoutBranch(branch)
	if err != nil {
		return err
	}

	err = DeleteLocalBranch(ref.Branch)
	if err != nil {
		return err
	}

	return nil
}

func (s *Stack) adjustAdjacentRefs(ref StackRef) error {
	refs := s.Refs

	if ref.Prev != "" {
		prev := refs[ref.Prev]
		delete(refs, ref.Prev)

		prev.Next = ref.Next
		refs[ref.Prev] = prev

		err := UpdateStackRefFile(s.Title, prev)
		if err != nil {
			return fmt.Errorf("could not update reference file %v:", err)
		}
	}

	if ref.Next != "" {
		next := refs[ref.Next]
		delete(refs, ref.Next)

		next.Prev = ref.Prev
		refs[ref.Next] = next

		err := UpdateStackRefFile(s.Title, next)
		if err != nil {
			return fmt.Errorf("could not update reference file %v:", err)
		}
	}

	return nil
}

func (s *Stack) IndexAt(ref StackRef) int {
	for i, r := range s.Iter2() {
		if r == ref {
			return i
		}
	}

	return -1
}

func (s *Stack) Last() StackRef {
	if s.Empty() {
		return StackRef{}
	}

	for _, ref := range s.Refs {
		if ref.IsLast() {
			return ref
		}
	}

	// All Stacks should be created with GatherStackRefs which validates the Stack consistency.
	panic(errors.New("can't find the last ref in the chain. Data might be corrupted."))
}

func (s *Stack) First() StackRef {
	if s.Empty() {
		return StackRef{}
	}

	for _, ref := range s.Refs {
		if ref.IsFirst() {
			return ref
		}
	}

	// All Stacks should be created with GatherStackRefs which validates the Stack consistency.
	panic(errors.New("can't find the first ref in the chain. Data might be corrupted."))
}

// Iter returns an iterator to range from the first to the last ref in the stack.
func (s *Stack) Iter() iter.Seq[StackRef] {
	return func(yield func(StackRef) bool) {
		ref := s.First()
		for !ref.Empty() {
			if !yield(ref) {
				return
			}

			ref = s.Refs[ref.Next]
		}
	}
}

func (s *Stack) Branches() (branches []string) {
	for ref := range s.Iter() {
		branches = append(branches, ref.Branch)
	}

	return
}

// Iter2 returns an iterator like Iter, but includes an index
func (s *Stack) Iter2() iter.Seq2[int, StackRef] {
	return func(yield func(int, StackRef) bool) {
		ref := s.First()
		i := 0

		for !ref.Empty() {
			if !yield(i, ref) {
				return
			}

			i++
			ref = s.Refs[ref.Next]
		}
	}
}

func GatherStackRefs(title string) (Stack, error) {
	stack := Stack{Title: title}
	stack.Refs = make(map[string]StackRef)

	root, err := StackRootDir(title)
	if err != nil {
		return stack, err
	}

	err = filepath.WalkDir(root, func(dir string, d fs.DirEntry, err error) error {
		if err != nil {
			return err
		}

		if d.IsDir() {
			return nil
		}
		// read files in the stacked ref directory
		// TODO: this may be quicker if we introduce a package
		// https://github.com/bmatcuk/doublestar
		if filepath.Ext(d.Name()) == ".json" {
			data, err := os.ReadFile(dir)
			if err != nil {
				return err
			}

			// marshal them into our StackRef type
			stackRef := StackRef{}
			err = json.Unmarshal(data, &stackRef)
			if err != nil {
				return err
			}

			stack.Refs[stackRef.SHA] = stackRef
		}

		return nil
	})
	if err != nil {
		if os.IsNotExist(err) { // there might not be any refs yet, this is ok.
			return stack, nil
		} else {
			return stack, err
		}
	}

	err = validateStackRefs(stack)
	if err != nil {
		return Stack{}, err
	}

	return stack, nil
}

func validateStackRefs(s Stack) error {
	endRefs := 0
	startRefs := 0

	if s.Empty() {
		// empty stacks are okay.
		return nil
	}

	for _, ref := range s.Refs {
		if ref.IsFirst() {
			startRefs++
		}

		if ref.IsLast() {
			endRefs++
		}

		if endRefs > 1 || startRefs > 1 {
			return errors.New("More than one end or start ref detected. Data might be corrupted.")
		}
	}

	if startRefs != 1 {
		return errors.New("expected exactly one start ref. Data might be corrupted.")
	}
	if endRefs != 1 {
		return errors.New("expected exactly one end ref. Data might be corrupted.")
	}
	return nil
}

func CurrentStackRefFromCurrentBranch(title string) (StackRef, error) {
	stack, err := GatherStackRefs(title)
	if err != nil {
		return StackRef{}, err
	}

	branch, err := CurrentBranch()
	if err != nil {
		return StackRef{}, err
	}

	return stack.RefFromBranch(branch)
}

func (s Stack) RefFromBranch(branch string) (StackRef, error) {
	for ref := range s.Iter() {
		if ref.Branch == branch {
			return ref, nil
		}
	}

	return StackRef{}, errors.New("Could not find stack ref for branch: " + branch)
}

// Empty returns true if the stack ref does not have an associated SHA (commit).
// This indicates that the StackRef is invalid.
func (r StackRef) Empty() bool { return r.SHA == "" }

// IsFirst returns true if the stack ref is the first of the stack.
// A stack ref is considered the first if it does not reference any previous ref.
func (r StackRef) IsFirst() bool { return r.Prev == "" }

// IsLast returns true if the stack ref is the last of the stack.
// A stack ref is considered the last if it does not reference any next ref.
func (r StackRef) IsLast() bool { return r.Next == "" }

// Subject returns the stack ref description suitable as commit Subject
// and for other in space limited places.
// It only takes the first line of the description into account
// and truncates it to 72 characters.
func (r StackRef) Subject() string {
	ls := strings.SplitN(r.Description, "\n", 1)
	if len(ls[0]) <= 72 {
		return ls[0]
	}

	return ls[0][:69] + "..."
}