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/frontend/compute/project.ts
Views: 687
1
import { webapp_client } from "@cocalc/frontend/webapp-client";
2
// Write a (relatively SMALL) text file to the file system
3
// on a compute server, using the file system exec api call.
4
// This writes to a tmp file, then moves it, so that the
5
// write is atomic, e.g., because an application of this is
6
// to our proxy, which watches for file changes and reads the
7
// file, and reading a file while it is being written can
8
// be corrupt.
9
10
export async function writeTextFileToComputeServer({
11
value,
12
project_id,
13
compute_server_id,
14
path, // won't work if path has double quotes in it!
15
sudo,
16
}: {
17
value: string;
18
project_id: string;
19
compute_server_id: number;
20
path: string;
21
sudo?: boolean;
22
}) {
23
// Base64 encode the value.
24
const base64value = Buffer.from(value).toString("base64");
25
const random = `.tmp${Math.random()}`;
26
if (sudo) {
27
// Decode the base64 string before echoing it.
28
const args = [
29
"sh",
30
"-c",
31
`echo "${base64value}" | base64 --decode > "${path}${random}" && mv "${path}${random}" "${path}"`,
32
];
33
34
await webapp_client.exec({
35
filesystem: true,
36
compute_server_id,
37
project_id,
38
command: "sudo",
39
args,
40
});
41
} else {
42
await webapp_client.exec({
43
filesystem: true,
44
compute_server_id,
45
project_id,
46
command: `echo "${base64value}" | base64 --decode > "${path}${random}" && mv "${path}${random}" "${path}"`,
47
});
48
}
49
}
50
51