CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/next/lib/share/proxy/get-contents.ts
Views: 687
1
/*
2
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
import { FileInfo, PathContents } from "lib/share/get-contents";
7
import { rawText, contents, defaultBranch, repos } from "./api";
8
import { join } from "path";
9
import { field_cmp } from "@cocalc/util/cmp";
10
11
export default async function getContents(
12
githubOrg: string,
13
githubRepo: string,
14
segments: string[],
15
): Promise<PathContents> {
16
if (!githubRepo) {
17
// get all repos attached to an org
18
const listing = await repos(githubOrg);
19
listing.sort(field_cmp("mtime"));
20
listing.reverse();
21
return { listing };
22
}
23
24
switch (segments[0]) {
25
case undefined:
26
case "tree":
27
// directory listing
28
const response = await contents(githubOrg, githubRepo, segments);
29
if (response["name"] != null) {
30
// it's a file rather than a directory
31
throw Error("not implemented");
32
}
33
const branch =
34
segments[0] == null
35
? await defaultBranch(githubOrg, githubRepo)
36
: segments[1];
37
const listing: FileInfo[] = [];
38
for (const file of response) {
39
const isdir = file.type == "dir";
40
let url;
41
if (isdir) {
42
if (segments[0] == null) {
43
url = `/github/${githubOrg}/${githubRepo}/${join(
44
"tree",
45
branch,
46
...segments,
47
file.name,
48
)}`;
49
} else {
50
url = `/github/${githubOrg}/${githubRepo}/${join(
51
...segments,
52
file.name,
53
)}`;
54
}
55
} else {
56
if (segments[0] == null) {
57
url = `/github/${githubOrg}/${githubRepo}/${join(
58
"blob",
59
branch,
60
...segments,
61
file.name,
62
)}`;
63
} else {
64
url = `/github/${githubOrg}/${githubRepo}/${join(
65
"blob",
66
segments[1],
67
...segments.slice(2),
68
file.name,
69
)}`;
70
}
71
}
72
listing.push({
73
url,
74
name: file.name,
75
isdir,
76
...(file.type == "file" ? { size: file.size } : undefined),
77
});
78
}
79
return { isdir: true, listing };
80
break;
81
case "blob":
82
const content = await rawText(githubOrg, githubRepo, segments);
83
return { content, size: content.length };
84
default:
85
throw Error("not implemented");
86
}
87
}
88
89