Repository navigation
Expand file tree
/
Copy pathrepack.adm
More file actions
431 lines (414 loc) · 14.8 KB
/
Copy pathrepack.adm
File metadata and controls
431 lines (414 loc) · 14.8 KB
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
425
426
427
428
429
430
431
partial module adm.dev.git {
use (
std.os
std.time
)
// How to repack.
// How far a long operation has come: the phase it is in (`counting`,
// `compressing`, `writing`, `packing references`, `pruning`, `fetching`,
// `checking out`), what it has done of the phase and how much there is
// (0 when unknown).
struct Progress {
phase string
done int
total int
}
// How `Repository.repack` writes the pack and what it reports as it goes.
struct RepackOptions {
// Write a reachability bitmap; none: for bare repositories, as git's
// `repack.writeBitmaps`.
bitmap ?bool = none
// Write objects no reference reaches as loose objects instead of
// dropping them, so `prune` can expire them by age (`-A`).
keepUnreachable bool = true
pack PackOptions = PackOptions{}
// Told how far the repack has come, at each phase and after each
// batch of objects written; returning false stops it, the old packs
// kept and the new one dropped.
progress ?(def(Progress) bool) = none
}
// How `gc` tidies the repository.
struct GcOptions {
// Unreachable loose objects older than this go (`gc.pruneExpire`).
expire duration = 336h
// Told how far the work has come, as a repack's `progress` is;
// returning false stops it before the next phase, the repository
// left as it was.
progress ?(def(Progress) bool) = none
}
// What `countObjects` reports, as `git count-objects -v` does.
struct ObjectCount {
// Loose objects and their bytes on disk.
loose int
looseBytes int64
// Pack files, the objects in them and their bytes (`.pack` files).
packs int
packed int
packBytes int64
// Files in the pack folder that are no pack, index, bitmap, rev,
// keep, promisor or mtimes file, and their bytes.
garbage int
garbageBytes int64
// References in loose files, and in `packed-refs` (a reftable's
// references all count as packed).
looseRefs int
packedRefs int
}
// The error a stopped operation fails with: its code is `stopped`.
internal def stoppedError(what string) error {
return Error{message: "git: {what} stopped", code: "stopped"}
}
// Tells `progress` where the work is; fails with a `stopped` error when
// it answers false. Nothing without a callback.
internal def report(progress ?(def(Progress) bool), what string, phase string, done int, total int) !none {
return none when progress is none
fail stoppedError(what) unless progress(Progress{phase: phase, done: done, total: total})
return none
}
// The objects a repository keeps: those its references, HEAD, reflogs
// and index (of every worktree) reach.
internal def reachableRoots(repo Repository) !ObjectId[] {
let out ObjectId[] = []
let seen map<string, bool> = {}
let add = def (id ObjectId) {
return when id.isZero() || seen.hasKey(id.str())
seen[id.str()] = true
out.push(id)
}
let head = repo.headId() onerror recover none
add(head) unless head is none
let names string[] = ["HEAD"]
for let r in try repo.refs("refs/") {
names.push(r.name)
let id = repo.refTarget(r.name) onerror recover none
add(id) unless id is none
}
for let name in names {
for let e in repo.reflog(name) onerror recover ReflogEntry[] {
add(e.oldId)
add(e.newId)
}
}
let gitDirs string[] = [repo.gitDir]
let worktrees = os.join(repo.commonDir, "worktrees")
if try os.exists(worktrees) {
for let w in try os.readDir(worktrees) {
gitDirs.push(w.path) when w.info.isDir
}
}
for let dir in gitDirs {
let wtHead = string(os.readFile(os.join(dir, "HEAD")) onerror recover byte[]).trim()
if wtHead.len() == idLength(repo.format) * 2 {
let id = idOrNone(wtHead)
add(id) unless id is none
}
continue unless try os.exists(os.join(dir, "index"))
let idx = try readIndexFile(os.join(dir, "index"), repo.format, dir)
for let e in idx.entries {
add(e.id) unless (e.mode & 0o170000) == 0o160000 || !repo.objects.hasLocal(e.id)
}
}
return out
}
// Packs every reachable object into one new pack (with its index,
// reverse index and, when asked, bitmap) and removes the old packs and
// the loose objects it holds (`git repack -a -d`). Returns the new
// pack's checksum; none when there is nothing to pack. Fails when a
// file cannot be written; the old packs stay until the new one is
// complete.
internal def repackAll(repo Repository, options RepackOptions) !?ObjectId {
let roots = try reachableRoots(repo)
// A partial clone packs what it has; what it lacks stays with the
// remote.
let hook = repo.objects.fetchMissing
repo.objects.fetchMissing = none
let items = objectsToPack(repo, roots.filter(id => repo.objects.hasLocal(id)), [], ObjectFilter{}) onerror (err error) {
repo.objects.fetchMissing = hook
fail err
}
repo.objects.fetchMissing = hook
items = items.filter(it => repo.objects.hasLocal(it.id))
try report(options.progress, "repack", "counting", items.len(), items.len())
let packOptions = PackOptions{...options.pack, progress: options.progress}
let packDir = os.join(repo.objects.dir, "pack")
let oldPacks = repo.objects.packs.clone()
let wasPromisor = oldPacks.filter(p => os.exists(p.path.slice(0, p.path.len() - 5) + ".promisor") onerror recover false).len() > 0
let kept = oldPacks.filter(p => os.exists(p.path.slice(0, p.path.len() - 5) + ".keep") onerror recover false)
if options.keepUnreachable {
try explodeUnreachable(repo, items, oldPacks)
}
let sum ?ObjectId = none
if items.len() > 0 {
let s = try writePackFiles(repo, items, packOptions)
sum = s
let base = os.join(packDir, "pack-{s.str()}")
if wasPromisor {
try writeAtomically(base + ".promisor", byte[], 0o444)
}
// A partial clone's pack is not closed under reachability: no bitmap.
let bitmap = options.bitmap
if !wasPromisor && (bitmap is none ?? (repo.isBare(), bitmap)) {
try writeBitmapFor(repo, base + ".pack", roots)
}
}
// The new pack is complete: the old ones and the multi-pack index go.
let fresh = sum is none ?? ("", "pack-{sum.str()}.pack")
for let p in oldPacks {
continue when os.base(p.path) == fresh || kept.filter(k => k.path == p.path).len() > 0
let stem = p.path.slice(0, p.path.len() - 5)
for let ext in string[".pack", ".idx", ".rev", ".bitmap", ".promisor", ".mtimes"] {
os.remove(stem + ext) onerror recover none
}
}
for let e in try os.readDir(packDir) {
let name = os.base(e.path)
if name.startsWith("multi-pack-index") {
os.remove(e.path) onerror recover none
}
}
try reopenObjects(repo)
try pruneLooseInPacks(repo)
return sum
}
// Opens the object database again (the packs changed), keeping its
// lazy-fetch hook.
internal def reopenObjects(repo Repository) !none {
let hook = repo.objects.fetchMissing
let level = repo.objects.level
repo.objects.close()
let fresh = new ObjectDatabase(repo.objects.dir, repo.format)
fresh.level = level
fresh.fetchMissing = hook
try fresh.open()
repo.objects = fresh
let b = repo.bitmap
b.close() unless b is none
repo.bitmap = none
repo.bitmapLoaded = false
return none
}
// Writes the objects of the old packs that the new pack leaves out as
// loose objects, so nothing is lost before `prune` decides.
internal def explodeUnreachable(repo Repository, items PackItem[], packs Pack[]) !none {
let keep map<string, bool> = {}
for let it in items {
keep[it.id.str()] = true
}
for let p in packs {
for let n = 0; n < p.count; n++ {
let id = p.idAt(n)
continue when keep.hasKey(id.str())
let (kind, data) = try repo.objects.readRaw(id)
let _ = try repo.objects.write(kind, data)
keep[id.str()] = true
}
}
return none
}
// Removes loose objects a pack holds (`git prune-packed`).
internal def pruneLooseInPacks(repo Repository) !none {
for let dir in try os.readDir(repo.objects.dir) {
let name = os.base(dir.path)
continue unless dir.info.isDir && name.len() == 2 && hexValue(name.bytes()[0]) >= 0 && hexValue(name.bytes()[1]) >= 0
for let f in try os.readDir(dir.path) {
let id = idOrNone(name + os.base(f.path))
continue when id is none
if !(repo.objects.findPacked(id) is none) {
os.remove(f.path) onerror recover none
}
}
os.remove(dir.path) onerror recover none
}
return none
}
// Removes loose objects nothing reaches that are older than `expiry`
// (`git prune --expire`), or with `dry` only counts them. Returns how
// many went, or would go, and their bytes.
internal def pruneUnreachable(repo Repository, expiry time.Time, dry bool = false) !(int, int64) {
let roots = try reachableRoots(repo)
let hook = repo.objects.fetchMissing
repo.objects.fetchMissing = none
let items = objectsToPack(repo, roots.filter(id => repo.objects.hasLocal(id)), [], ObjectFilter{}) onerror (err error) {
repo.objects.fetchMissing = hook
fail err
}
repo.objects.fetchMissing = hook
let reachable map<string, bool> = {}
for let it in items {
reachable[it.id.str()] = true
}
let removed = 0
let bytes int64 = 0
for let dir in try os.readDir(repo.objects.dir) {
let name = os.base(dir.path)
continue unless dir.info.isDir && name.len() == 2 && hexValue(name.bytes()[0]) >= 0 && hexValue(name.bytes()[1]) >= 0
for let f in try os.readDir(dir.path) {
let id = idOrNone(name + os.base(f.path))
continue when id is none || reachable.hasKey(id.str())
continue when f.info.modTime > expiry
removed++
bytes += f.info.size
continue when dry
os.remove(f.path) onerror recover none
}
if !dry {
os.remove(dir.path) onerror recover none
}
}
return (removed, bytes)
}
// What the repository holds, counted as `git count-objects -v` counts
// it, with the references loose and packed.
internal def countObjectsOf(repo Repository) !ObjectCount {
let out = ObjectCount{}
for let dir in try os.readDir(repo.objects.dir) {
let name = os.base(dir.path)
continue unless dir.info.isDir && name.len() == 2 && hexValue(name.bytes()[0]) >= 0 && hexValue(name.bytes()[1]) >= 0
for let f in try os.readDir(dir.path) {
out.loose++
out.looseBytes += f.info.size
}
}
let packDir = os.join(repo.objects.dir, "pack")
let known = string[".pack", ".idx", ".rev", ".bitmap", ".keep", ".promisor", ".mtimes"]
if os.exists(packDir) onerror recover false {
for let f in try os.readDir(packDir) {
let name = os.base(f.path)
continue when f.info.isDir || name.startsWith("multi-pack-index")
let fine = false
for let ext in known {
fine = true when name.startsWith("pack-") && name.endsWith(ext)
}
continue when fine
out.garbage++
out.garbageBytes += f.info.size
}
}
for let p in repo.objects.packs {
out.packs++
out.packed += p.count
out.packBytes += (os.stat(p.path) onerror recover os.FileInfo{}).size
}
let refsDir = os.join(repo.commonDir, "refs")
out.looseRefs = countFiles(refsDir)
let packed = string(os.readFile(os.join(repo.commonDir, "packed-refs")) onerror recover byte[])
for let line in packed.split("\n") {
out.packedRefs++ unless line == "" || line.startsWith("#") || line.startsWith("^")
}
if repo.refFormat == RefFormat.Reftable {
out.packedRefs = (try repo.refs("refs/")).len()
}
return out
}
// The files under a folder, at any depth.
internal def countFiles(dir string) int {
let n = 0
for let e in os.readDir(dir) onerror recover os.DirEntry[] {
n += e.info.isDir ?? (countFiles(e.path), 1)
}
return n
}
// ---- bitmaps --------------------------------------------------------------
// Writes `<pack>.bitmap`: type bitmaps, the reachable set of the tips
// and of every hundredth commit, and the name-hash cache.
internal def writeBitmapFor(repo Repository, packPath string, roots ObjectId[]) !none {
let p = new Pack(packPath, repo.format)
try p.load()
let b = new PackBitmap()
b.pack = p
b.count = p.count
b.indexAt = p.reverse()
b.bitOf = inverseOrder(b.indexAt)
// Types by bit.
for let bit = 0; bit < p.count; bit++ {
let id = p.idAt(b.indexAt[bit])
let (kind, _) = try repo.info(id)
switch kind {
case ObjectKind.Commit:
b.commits.add(bit)
case ObjectKind.Tree:
b.trees.add(bit)
case ObjectKind.Blob:
b.blobs.add(bit)
case ObjectKind.Tag:
b.tags.add(bit)
}
}
// Selection: tips, and every hundredth commit of a date walk.
let tips ObjectId[] = []
for let r in roots {
let c = repo.peel(r, ObjectKind.Commit) onerror recover zeroId(repo.format)
tips.push(c) unless c.isZero() || tips.filter(t => t.equals(c)).len() > 0
}
let walk = new RevWalk(repo)
for let t in tips {
try walk.push(t)
}
let ordered = try walk.all()
let selected map<string, bool> = {}
for let t in tips {
selected[t.str()] = true
}
for let (i, c) in ordered {
selected[c.id.str()] = true when i % 100 == 0
}
// Oldest first, so each set stops at the sets already made.
let entries int[] = []
for let i = ordered.len() - 1; i >= 0; i-- {
let c = ordered[i]
continue unless selected.hasKey(c.id.str())
let bit = b.bitOfId(c.id)
continue when bit < 0
let set = try reachableBits(repo, b, [c.id], none)
fail "git: the pack does not hold everything {c.id.short()} reaches" when b.extra.len() > 0
b.byBit[bit] = entries.len()
b.decoded[entries.len()] = set
entries.push(bit)
}
let hashLen = idLength(repo.format)
let out byte[] = "BITM".bytes()
out.push(0, 1, 0, 0x5)
putBe(out, int64(entries.len()), 4)
out.push(...p.data[p.data.len() - hashLen:])
out.push(...writeEwah(b.commits, p.count))
out.push(...writeEwah(b.trees, p.count))
out.push(...writeEwah(b.blobs, p.count))
out.push(...writeEwah(b.tags, p.count))
for let (i, bit) in entries {
putBe(out, int64(b.indexAt[bit]), 4)
out.push(0, 0)
out.push(...writeEwah(b.decoded[i], p.count))
}
// The name hashes in index order, from the paths the pack was made
// with.
let names = try nameHashesFor(repo, p, roots)
for let n = 0; n < p.count; n++ {
putBe(out, int64(names[n]), 4)
}
let h = newHasher(repo.format)
out.push(...h.hash(out))
p.close()
return try writeAtomically(packPath.slice(0, packPath.len() - 5) + ".bitmap", out, 0o444)
}
// git's name hash of each object of a pack, by index position: the path
// a walk from the roots first meets it at; 0 for commits and tags.
internal def nameHashesFor(repo Repository, p Pack, roots ObjectId[]) !uint32[] {
let out uint32[]
out.len(p.count)
for let i = 0; i < p.count; i++ {
out[i] = 0
}
let saved = repo.bitmapLoaded
repo.bitmapLoaded = true
let items = objectsToPack(repo, roots.filter(id => repo.objects.hasLocal(id)), []) onerror (err error) {
repo.bitmapLoaded = saved
fail err
}
repo.bitmapLoaded = saved
for let it in items {
let n = p.find(it.id.bytes)
out[n] = uint32(nameHash(it.path)) when n >= 0 && it.path != ""
}
return out
}
}