-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathStructuredRepositoryFacade.cs
More file actions
454 lines (391 loc) · 16.6 KB
/
StructuredRepositoryFacade.cs
File metadata and controls
454 lines (391 loc) · 16.6 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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
////////////////////////////////////////////////////////////////////////////
//
// GitReader - Lightweight Git local repository traversal library.
// Copyright (c) Kouji Matsui (@kozy_kekyo, @kekyo@mi.kekyo.net)
//
// Licensed under Apache-v2: https://opensource.org/licenses/Apache-2.0
//
////////////////////////////////////////////////////////////////////////////
using GitReader.Collections;
using GitReader.Internal;
using GitReader.IO;
using GitReader.Primitive;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace GitReader.Structures;
internal static class StructuredRepositoryFacade
{
public readonly struct RepositoryReferenceExtracted
{
public readonly StructuredRepository Repository;
public readonly WeakReference WeakReference;
public RepositoryReferenceExtracted(
StructuredRepository repository, WeakReference weakReference)
{
this.Repository = repository;
this.WeakReference = weakReference;
}
public void Deconstruct(out StructuredRepository repository, out WeakReference weakReference)
{
repository = this.Repository;
weakReference = this.WeakReference;
}
}
public static RepositoryReferenceExtracted GetRelatedRepository(
this IRepositoryReference repositoryReference)
{
if (repositoryReference.Repository.Target is not StructuredRepository repository ||
repository.objectAccessor == null)
{
throw new InvalidOperationException(
"The repository already discarded.");
}
return new(repository, repositoryReference.Repository);
}
//////////////////////////////////////////////////////////////////////////
private static async Task<Branch?> GetCurrentHeadAsync(
StructuredRepository repository,
WeakReference rwr,
CancellationToken ct)
{
if (await RepositoryAccessor.ReadHashAsync(
repository, "HEAD", ct) is { } results)
{
return new(rwr, results.Names.Last(), results.Hash, false);
}
else
{
return null;
}
}
//////////////////////////////////////////////////////////////////////////
private static async Task<ReadOnlyDictionary<string, Branch[]>> GetStructuredBranchesAsync(
StructuredRepository repository,
WeakReference rwr,
CancellationToken ct)
{
Debug.Assert(object.ReferenceEquals(rwr.Target, repository));
var (references, remoteReferences) = await repository.concurrentScope.Join(
RepositoryAccessor.ReadReferencesAsync(
repository, ReferenceTypes.Branches, ct),
RepositoryAccessor.ReadReferencesAsync(
repository, ReferenceTypes.RemoteBranches, ct));
return references.
Select(r => new Branch(rwr, r.Name, r.Target, false)).
Concat(remoteReferences.Select(r => new Branch(rwr, r.Name, r.Target, true))).
GroupBy(b => b.Name).
ToDictionary(g => g.Key, g => g.ToArray());
}
private static async Task<ReadOnlyDictionary<string, Tag>> GetStructuredTagsAsync(
StructuredRepository repository,
WeakReference rwr,
CancellationToken ct)
{
var tagReferences = await RepositoryAccessor.ReadTagReferencesAsync(
repository, ct);
var tags = await repository.concurrentScope.WhenAll(ct,
tagReferences.Select(async tagReference =>
{
var primitiveTag = await PrimitiveRepositoryFacade.GetTagAsync(repository, tagReference, ct);
// TagHash is the hash of the tag object itself (for annotated tags), or null for lightweight tags
var tagHash = tagReference.CommitHash is not null ? tagReference.ObjectOrCommitHash : (Hash?)null;
return new Tag(rwr, tagHash,
primitiveTag.Type, primitiveTag.Hash, primitiveTag.Name,
primitiveTag.Tagger is { } tagger ? new Annotation(tagger, primitiveTag.Message) : null);
}));
return tags.
Where(tag => tag != null).
DistinctBy(tag => tag.Name).
ToDictionary(tag => tag.Name);
}
private static async Task<Stash[]> GetStructuredStashesAsync(
StructuredRepository repository,
WeakReference rwr,
CancellationToken ct)
{
var primitiveStashes = await RepositoryAccessor.ReadStashesAsync(repository, ct);
return primitiveStashes.Select(stash =>
new Stash(rwr, stash.Current, stash.Committer, stash.Message)).
Reverse().
ToArray();
}
public static async Task<ReflogEntry[]> GetHeadReflogsAsync(
StructuredRepository repository,
WeakReference rwr,
CancellationToken ct)
{
var primitiveReflogEntries = await RepositoryAccessor.ReadReflogEntriesAsync(repository, "HEAD", ct);
return primitiveReflogEntries.Select(stash =>
new ReflogEntry(rwr, stash.Current, stash.Old, stash.Committer, stash.Message)).
Reverse().
ToArray();
}
//////////////////////////////////////////////////////////////////////////
private static async Task<StructuredRepository> InternalOpenStructuredAsync(
string repositoryPath,
string[] alternativePaths,
IFileSystem fileSystem,
IConcurrentScope concurrentScope,
CancellationToken ct)
{
var repository = new StructuredRepository(
repositoryPath, alternativePaths, fileSystem, concurrentScope);
try
{
// Must set remote urls first
repository.remoteUrls = await RepositoryAccessor.ReadRemoteReferencesAsync(repository, ct);
// Read FETCH_HEAD and packed-refs.
var (fhc1, fhc2) = await repository.concurrentScope.Join(
RepositoryAccessor.ReadFetchHeadsAsync(repository, ct),
RepositoryAccessor.ReadPackedRefsAsync(repository, ct));
repository.referenceCache = fhc1.Combine(fhc2);
// Read all other requirements.
var rwr = new WeakReference(repository);
var (head, branchesAll, tags, stashes) = await repository.concurrentScope.Join(
GetCurrentHeadAsync(repository, rwr, ct),
GetStructuredBranchesAsync(repository, rwr, ct),
GetStructuredTagsAsync(repository, rwr, ct),
GetStructuredStashesAsync(repository, rwr, ct));
repository.head = head;
repository.branchesAll = branchesAll;
repository.tags = tags;
repository.stashes = stashes;
return repository;
}
catch
{
repository.Dispose();
throw;
}
}
public static async Task<StructuredRepository> OpenStructuredAsync(
string path,
IFileSystem fileSystem,
IConcurrentScope concurrentScope,
CancellationToken ct)
{
var (gitPath, alternativePaths) = await RepositoryAccessor.DetectLocalRepositoryPathAsync(
path, fileSystem, ct);
return await InternalOpenStructuredAsync(
gitPath, alternativePaths, fileSystem, concurrentScope, ct);
}
//////////////////////////////////////////////////////////////////////////
public static async Task<Commit?> GetCommitDirectlyAsync(
StructuredRepository repository,
Hash hash,
CancellationToken ct)
{
var commit = await RepositoryAccessor.ReadCommitAsync(
repository, hash, ct);
return commit is { } c ?
new(new(repository), c) : null;
}
public static async Task<Commit> GetCommitAsync(
IInternalCommitReference commitReference,
CancellationToken ct)
{
var (repository, rwr) = GetRelatedRepository(commitReference);
var commit = await RepositoryAccessor.ReadCommitAsync(
repository, commitReference.Hash, ct);
return new(rwr, commit!.Value);
}
public static async Task<Commit> GetCommitAsync(
IRepositoryReference repositoryReference,
Hash hash,
CancellationToken ct)
{
var (repository, rwr) = GetRelatedRepository(repositoryReference);
var commit = await RepositoryAccessor.ReadCommitAsync(
repository, hash, ct);
return new(rwr, commit!.Value);
}
public static async Task<Annotation> GetAnnotationAsync(
Tag tag,
CancellationToken ct)
{
if (tag.annotation is not { } annotation)
{
if (tag.TagHash is { } tagHash)
{
var (repository, _) = GetRelatedRepository(tag);
var t = await RepositoryAccessor.ReadTagAsync(
repository, tagHash, ct);
annotation = new(t!.Value.Tagger, t!.Value.Message);
Interlocked.CompareExchange(ref tag.annotation, annotation, null);
}
else
{
throw new InvalidOperationException(
$"Tag {tag.Name} does not have annotation.");
}
}
return annotation;
}
public static async Task<Commit?> GetPrimaryParentAsync(
Commit commit,
CancellationToken ct)
{
if (commit.parents.Count == 0)
{
return null;
}
var (repository, rwr) = GetRelatedRepository(commit);
var pc = await RepositoryAccessor.ReadCommitAsync(
repository, commit.parents[0], ct);
return pc is { } ?
new(rwr, pc!.Value) :
throw new InvalidDataException(
$"Could not find a commit: {commit.parents[0]}");
}
public static Task<Commit[]> GetParentsAsync(
Commit commit,
CancellationToken ct)
{
var (repository, rwr) = GetRelatedRepository(commit);
return repository.concurrentScope.WhenAll(ct,
commit.parents.Select((async parent =>
{
var pc = await RepositoryAccessor.ReadCommitAsync(
repository, parent, ct);
return pc is { } ?
new Commit(rwr, pc!.Value) :
throw new InvalidDataException(
$"Could not find a commit: {parent}");
})));
}
public static Branch[] GetRelatedBranches(Commit commit)
{
var (repository, _) = GetRelatedRepository(commit);
return repository.Branches.Values.
Collect(branch => branch.Head.Equals(commit.Hash) ? branch : null).
ToArray();
}
public static Tag[] GetRelatedTags(Commit commit)
{
var (repository, _) = GetRelatedRepository(commit);
return repository.Tags.Values.
Collect(tag => (tag.ObjectHash is { } oh && oh.Equals(commit.Hash)) ? tag : null).
ToArray();
}
public static async Task<TreeRoot> GetTreeAsync(
Commit commit,
CancellationToken ct)
{
var (repository, rwr) = GetRelatedRepository(commit);
var rootTree = await RepositoryAccessor.ReadTreeAsync(
repository, commit.treeRoot, ct);
// This is a rather aggressive algorithm that recursively and in parallel searches all entries
// in the tree and builds all elements.
#if NET45_OR_GREATER || NETSTANDARD || NETCOREAPP
async ValueTask<TreeEntry[]> GetChildrenAsync(
ReadOnlyArray<PrimitiveTreeEntry> entries, Tree parent) =>
#else
async Task<TreeEntry[]> GetChildrenAsync(
ReadOnlyArray<PrimitiveTreeEntry> entries, Tree parent) =>
#endif
(await repository.concurrentScope.WhenAll(ct,
entries.Select((async entry =>
{
var modeFlags = (ModeFlags)((int)entry.Modes & 0x1ff);
switch (entry.SpecialModes)
{
case PrimitiveSpecialModes.Directory:
var tree = await RepositoryAccessor.ReadTreeAsync(
repository!, entry.Hash, ct);
var directory = new TreeDirectoryEntry(
entry.Hash, entry.Name, modeFlags, parent);
var children = await GetChildrenAsync(tree.Children, directory);
directory.SetChildren(children);
return (TreeEntry)directory;
case PrimitiveSpecialModes.Blob:
return new TreeBlobEntry(
rwr, entry.Hash, entry.Name, modeFlags, parent);
case PrimitiveSpecialModes.SubModule:
return new TreeSubModuleEntry(
rwr, entry.Hash, entry.Name, modeFlags, parent);
default:
// TODO:
return null!;
}
})))).
Where(entry => entry != null).
ToArray();
var treeRoot = new TreeRoot(commit.Hash);
var children = await GetChildrenAsync(rootTree.Children, treeRoot);
treeRoot.SetChildren(children);
return treeRoot;
}
public static async Task<StructuredRepository> OpenSubModuleAsync(
TreeSubModuleEntry subModule,
CancellationToken ct)
{
var (repository, _) = GetRelatedRepository(subModule);
if (await RepositoryAccessor.GetCandidateFilePathAsync(
repository, repository.fileSystem.Combine(
"modules",
repository.fileSystem.Combine(subModule.
Traverse<TreeEntry>(tree => tree.Parent as TreeEntry).
Select(tree => tree.Name).
Reverse().
ToArray()),
"config"), ct) is not { } cp)
{
throw new ArgumentException("Submodule repository does not exist.");
}
return await InternalOpenStructuredAsync(
cp.BasePath, [], repository.fileSystem, repository.concurrentScope, ct);
}
public static Task<Stream> OpenBlobAsync(
TreeBlobEntry entry,
CancellationToken ct)
{
var (repository, rwr) = GetRelatedRepository(entry);
return RepositoryAccessor.OpenBlobAsync(
repository, entry.Hash, ct)
#if NET45_OR_GREATER || NETSTANDARD || NETCOREAPP
.AsTask()
#endif
;
}
//////////////////////////////////////////////////////////////////////////
/// <summary>
/// Gets structured working directory status information for the specified repository with a custom filter.
/// </summary>
/// <param name="repository">The structured repository to get working directory status from.</param>
/// <param name="overrideGlobFilter">The path filter to apply.</param>
/// <param name="ct">The cancellation token.</param>
/// <returns>A ValueTask containing the structured working directory status.</returns>
#if NET45_OR_GREATER || NETSTANDARD || NETCOREAPP
public static async ValueTask<WorkingDirectoryStatus> GetWorkingDirectoryStatusAsync(
StructuredRepository repository, GlobFilter overrideGlobFilter, CancellationToken ct = default)
#else
public static async Task<WorkingDirectoryStatus> GetWorkingDirectoryStatusAsync(
StructuredRepository repository, GlobFilter overrideGlobFilter, CancellationToken ct = default)
#endif
{
var primitiveStatus = await PrimitiveRepositoryFacade.GetWorkingDirectoryStatusAsync(
repository, ct);
var primitiveUntrackedFiles = await PrimitiveRepositoryFacade.GetUntrackedFilesAsync(
repository, primitiveStatus, overrideGlobFilter, ct);
var stagedFiles = primitiveStatus.StagedFiles.
Select(pf => new WorkingDirectoryFile(
pf.Path, pf.Status, pf.IndexHash, pf.WorkingTreeHash)).
ToArray();
var unstagedFiles = primitiveStatus.UnstagedFiles.
Select(pf => new WorkingDirectoryFile(
pf.Path, pf.Status, pf.IndexHash, pf.WorkingTreeHash)).
ToArray();
var untrackedFiles = primitiveUntrackedFiles.
Select(pf => new WorkingDirectoryFile(
pf.Path, pf.Status, pf.IndexHash, pf.WorkingTreeHash)).
ToArray();
return new WorkingDirectoryStatus(
new ReadOnlyArray<WorkingDirectoryFile>(stagedFiles),
new ReadOnlyArray<WorkingDirectoryFile>(unstagedFiles),
new ReadOnlyArray<WorkingDirectoryFile>(untrackedFiles));
}
}