-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTree.ts
More file actions
74 lines (53 loc) · 2.14 KB
/
Copy pathTree.ts
File metadata and controls
74 lines (53 loc) · 2.14 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
import { components } from '@octokit/openapi-types';
import { Filter, ListModel, Stream, toggle } from 'mobx-restful';
import { buildURLData } from 'web-utility';
import { githubClient } from './client';
type GitTree = components['schemas']['git-tree'];
export type Tree = Pick<GitTree, 'sha'> & Partial<Omit<GitTree & GitTree['tree'][number], 'sha'>>;
export class TreeModel extends Stream<Tree>(ListModel) {
client = githubClient;
constructor(
public owner: string,
public repository: string
) {
super();
this.baseURI = `repos/${owner}/${repository}/git/trees`;
}
/**
* @see {@link https://docs.github.com/en/rest/git/trees#get-a-tree}
*/
@toggle('downloading')
async getOne(treeSHA = 'HEAD', recursive?: boolean) {
const { body } = await this.client.get<GitTree>(
`${this.baseURI}/${treeSHA}?${buildURLData({ recursive })}`
);
return body!;
}
async *openStream({ path }: Filter<Tree>) {
const matchFilter = (item: Tree) => !path || item.path.startsWith(path);
const root = await this.getOne('HEAD', true);
const pathSet = new Set<string>(),
treeNodes: Tree[] = [];
for (const item of root.tree) {
pathSet.add(item.path);
if (item.type === 'tree') treeNodes.push(item);
if (matchFilter(item)) yield item;
}
let totalCount = root.tree.length;
if (root.truncated)
for (let index = 0; index < treeNodes.length; index++) {
const { path, sha } = treeNodes[index];
const { tree } = await this.getOne(sha);
for (const item of tree) {
const fullPath = `${path}/${item.path}`;
if (pathSet.has(fullPath)) continue;
pathSet.add(fullPath);
const node = { ...item, path: fullPath };
totalCount += 1;
if (matchFilter(node)) yield node;
if (node.type === 'tree') treeNodes.push(node);
}
}
this.totalCount = totalCount;
}
}