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/backend/files/rename-file.ts
Views: 687
1
import { getHome } from "./util";
2
import { move, pathExists } from "fs-extra";
3
import { stat } from "node:fs/promises";
4
import { move_file_variations } from "@cocalc/util/delete-files";
5
import { join } from "path";
6
import getLogger from "@cocalc/backend/logger";
7
8
const log = getLogger("rename-file");
9
10
export async function rename_file(
11
src: string,
12
dest: string,
13
set_deleted: (path: string) => Promise<void>,
14
home?: string,
15
): Promise<void> {
16
if (src == dest) return; // no-op
17
const HOME = getHome(home);
18
if (!src.startsWith("/")) {
19
src = join(HOME, src);
20
}
21
if (!dest.startsWith("/")) {
22
dest = join(HOME, dest);
23
}
24
log.debug({ src, dest, home, HOME });
25
await set_deleted(src); // todo: later may have a set_moved...
26
const to_move: { src: string; dest: string }[] = [{ src, dest }];
27
28
try {
29
const s = await stat(src);
30
if (!s.isDirectory()) {
31
for (const variation of move_file_variations(src, dest)) {
32
if (await pathExists(variation.src)) {
33
await set_deleted(variation.src);
34
to_move.push(variation);
35
}
36
}
37
}
38
} catch (_err) {}
39
40
for (const x of to_move) {
41
await move(x.src, x.dest);
42
}
43
}
44
45