upload-sea-smb.mjs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. import { mkdir, readFile, rename, rm, stat } from "node:fs/promises";
  2. import { basename, isAbsolute, relative, resolve } from "node:path";
  3. import { createInterface } from "node:readline/promises";
  4. import { pathToFileURL } from "node:url";
  5. import { outputBinaryName, supportedTargets } from "./sea-targets.mjs";
  6. import { copyReleaseFiles, createConsoleProgressReporter, fileMode } from "./upload-progress.mjs";
  7. import { resolveIntranetMachineHost } from "../../../../../scripts/intranetDefaults.mjs";
  8. export const resolveDefaultSmbUrl = (env = process.env) =>
  9. `smb://${resolveIntranetMachineHost(env)}/shared`;
  10. export const DEFAULT_SMB_URL = resolveDefaultSmbUrl();
  11. export const DEFAULT_MOUNT_ROOT = "/Volumes/shared";
  12. export const DEFAULT_DESTINATION_ROOT = resolve(DEFAULT_MOUNT_ROOT, "zcode", "deps");
  13. export const RELEASE_DIRECTORY_PREFIX = "zcode-cli-";
  14. const root = resolve(import.meta.dirname, "../../..");
  15. const cliRoot = resolve(import.meta.dirname, "..");
  16. const defaultDist = resolve(cliRoot, "dist");
  17. const usage = `Usage:
  18. node packages/cli/scripts/upload-sea-smb.mjs
  19. node packages/cli/scripts/upload-sea-smb.mjs --force
  20. node packages/cli/scripts/upload-sea-smb.mjs --dest-root /Volumes/shared/zcode/deps
  21. node packages/cli/scripts/upload-sea-smb.mjs --dist packages/cli/dist
  22. node packages/cli/scripts/upload-sea-smb.mjs --version 0.12.3
  23. Options:
  24. --dist <path> SEA binary dist directory. Defaults to packages/cli/dist.
  25. --dest-root <path> Mounted SMB release root. Defaults to /Volumes/shared/zcode/deps.
  26. --version <text> Release version. Defaults to the root package.json version.
  27. --smb-url <url> SMB label for messages. Defaults to ${DEFAULT_SMB_URL}.
  28. --force, -f Replace an existing version directory.
  29. --help, -h Show this help.
  30. `;
  31. export const seaUploadBinaryNames = () =>
  32. supportedTargets.map((target) => outputBinaryName(target));
  33. const resolvePath = (value, cwd) => (isAbsolute(value) ? value : resolve(cwd, value));
  34. const readArgValue = (argv, arg, index) => {
  35. if (arg.includes("=")) {
  36. return {
  37. nextIndex: index,
  38. value: arg.slice(arg.indexOf("=") + 1),
  39. };
  40. }
  41. const value = argv[index + 1];
  42. if (!value || value.startsWith("--")) {
  43. throw new Error(`Missing value for ${arg}`);
  44. }
  45. return {
  46. nextIndex: index + 1,
  47. value,
  48. };
  49. };
  50. export const parseUploadSeaSmbArgs = (argv, { cwd = process.cwd(), env = process.env } = {}) => {
  51. const options = {
  52. destinationRoot: DEFAULT_DESTINATION_ROOT,
  53. distDir: defaultDist,
  54. force: false,
  55. help: false,
  56. smbUrl: resolveDefaultSmbUrl(env),
  57. version: undefined,
  58. };
  59. for (let index = 0; index < argv.length; index += 1) {
  60. const arg = argv[index];
  61. if (arg === "--") continue;
  62. if (arg === "--help" || arg === "-h") {
  63. options.help = true;
  64. continue;
  65. }
  66. if (arg === "--force" || arg === "-f") {
  67. options.force = true;
  68. continue;
  69. }
  70. if (arg === "--dist" || arg.startsWith("--dist=")) {
  71. const { nextIndex, value } = readArgValue(argv, arg, index);
  72. options.distDir = resolvePath(value, cwd);
  73. index = nextIndex;
  74. continue;
  75. }
  76. if (arg === "--dest-root" || arg.startsWith("--dest-root=")) {
  77. const { nextIndex, value } = readArgValue(argv, arg, index);
  78. options.destinationRoot = resolvePath(value, cwd);
  79. index = nextIndex;
  80. continue;
  81. }
  82. if (arg === "--version" || arg.startsWith("--version=")) {
  83. const { nextIndex, value } = readArgValue(argv, arg, index);
  84. options.version = value;
  85. index = nextIndex;
  86. continue;
  87. }
  88. if (arg === "--smb-url" || arg.startsWith("--smb-url=")) {
  89. const { nextIndex, value } = readArgValue(argv, arg, index);
  90. options.smbUrl = value;
  91. index = nextIndex;
  92. continue;
  93. }
  94. throw new Error(`Unknown option "${arg}". Run with --help for usage.`);
  95. }
  96. return options;
  97. };
  98. const missingFileErrorCode = "ENOENT";
  99. const maybeStat = async (path) => {
  100. try {
  101. return await stat(path);
  102. } catch (error) {
  103. if (error?.code === missingFileErrorCode) return null;
  104. throw error;
  105. }
  106. };
  107. export const readRootPackageVersion = async ({ rootDirectory = root } = {}) => {
  108. const packagePath = resolve(rootDirectory, "package.json");
  109. const parsed = JSON.parse(await readFile(packagePath, "utf8"));
  110. if (typeof parsed.version !== "string" || parsed.version.trim() === "") {
  111. throw new Error(`Invalid root package version in ${packagePath}`);
  112. }
  113. return parsed.version;
  114. };
  115. export const releaseDirectoryName = (version) => {
  116. const normalized = version.trim();
  117. if (!normalized || normalized === "." || normalized === ".." || /[\\/]/.test(normalized)) {
  118. throw new Error(`Invalid release version "${version}"`);
  119. }
  120. return `${RELEASE_DIRECTORY_PREFIX}${normalized}`;
  121. };
  122. const assertInsideDirectory = ({ child, parent }) => {
  123. const childRelativePath = relative(parent, child);
  124. if (!childRelativePath || childRelativePath.startsWith("..") || isAbsolute(childRelativePath)) {
  125. throw new Error(`Refusing to write outside destination root: ${child}`);
  126. }
  127. };
  128. export const collectSeaUploadFiles = async ({ distDir }) => {
  129. const missing = [];
  130. const files = [];
  131. for (const fileName of seaUploadBinaryNames()) {
  132. const source = resolve(distDir, fileName);
  133. const fileStat = await maybeStat(source);
  134. if (!fileStat?.isFile()) {
  135. missing.push(fileName);
  136. continue;
  137. }
  138. files.push({
  139. fileName,
  140. mode: fileMode(fileStat),
  141. size: fileStat.size,
  142. source,
  143. });
  144. }
  145. if (missing.length > 0) {
  146. throw new Error(
  147. `Missing SEA binaries in ${distDir}: ${missing.join(", ")}. ` +
  148. "Run `pnpm --filter @zcode/cli build:sea` first.",
  149. );
  150. }
  151. return files;
  152. };
  153. const ensureDirectory = async (path, label) => {
  154. const pathStat = await maybeStat(path);
  155. if (!pathStat) {
  156. throw new Error(`${label} does not exist: ${path}`);
  157. }
  158. if (!pathStat.isDirectory()) {
  159. throw new Error(`${label} is not a directory: ${path}`);
  160. }
  161. };
  162. export const ensureDestinationRoot = async ({ destinationRoot, smbUrl }) => {
  163. if (destinationRoot === DEFAULT_DESTINATION_ROOT) {
  164. await ensureDirectory(
  165. DEFAULT_MOUNT_ROOT,
  166. `Default SMB mount root for ${smbUrl}. Mount ${smbUrl} before uploading`,
  167. );
  168. }
  169. await mkdir(destinationRoot, {
  170. recursive: true,
  171. });
  172. await ensureDirectory(destinationRoot, "Destination root");
  173. };
  174. export const promptExistingVersionAction = async ({
  175. destination,
  176. stdin = process.stdin,
  177. stdout = process.stdout,
  178. } = {}) => {
  179. if (!stdin.isTTY) {
  180. throw new Error(
  181. `Release directory already exists: ${destination}. ` +
  182. "Re-run with --force to replace it, or remove it manually.",
  183. );
  184. }
  185. const rl = createInterface({
  186. input: stdin,
  187. output: stdout,
  188. });
  189. try {
  190. for (;;) {
  191. const answer = (
  192. await rl.question(
  193. `Release directory already exists: ${destination}\nChoose [a]bandon or [f]orce update: `,
  194. )
  195. )
  196. .trim()
  197. .toLowerCase();
  198. if (!answer || answer === "a" || answer === "abandon") return "abandon";
  199. if (answer === "f" || answer === "force") return "force";
  200. stdout.write("Please enter `a` to abandon or `f` to force update.\n");
  201. }
  202. } finally {
  203. rl.close();
  204. }
  205. };
  206. export const uploadSeaBinaries = async ({
  207. confirmExistingVersion = promptExistingVersionAction,
  208. destinationRoot,
  209. distDir,
  210. force,
  211. onProgress = () => {},
  212. rootDirectory = root,
  213. smbUrl,
  214. version,
  215. }) => {
  216. const releaseVersion = version ?? (await readRootPackageVersion({ rootDirectory }));
  217. const releaseName = releaseDirectoryName(releaseVersion);
  218. const targetDirectory = resolve(destinationRoot, releaseName);
  219. const stagingDirectory = resolve(
  220. destinationRoot,
  221. `.${releaseName}.uploading-${process.pid}-${Date.now()}`,
  222. );
  223. assertInsideDirectory({
  224. child: targetDirectory,
  225. parent: destinationRoot,
  226. });
  227. assertInsideDirectory({
  228. child: stagingDirectory,
  229. parent: destinationRoot,
  230. });
  231. const files = await collectSeaUploadFiles({
  232. distDir,
  233. });
  234. const totalBytes = files.reduce((sum, file) => sum + file.size, 0);
  235. await ensureDestinationRoot({
  236. destinationRoot,
  237. smbUrl,
  238. });
  239. const existing = await maybeStat(targetDirectory);
  240. if (existing && !existing.isDirectory()) {
  241. throw new Error(`Release destination exists but is not a directory: ${targetDirectory}`);
  242. }
  243. let shouldReplace = force;
  244. if (existing && !force) {
  245. const action = await confirmExistingVersion({
  246. destination: targetDirectory,
  247. });
  248. if (action === "abandon") {
  249. return {
  250. bytes: totalBytes,
  251. destination: targetDirectory,
  252. files,
  253. status: "abandoned",
  254. version: releaseVersion,
  255. };
  256. }
  257. shouldReplace = true;
  258. }
  259. await rm(stagingDirectory, {
  260. force: true,
  261. recursive: true,
  262. });
  263. await mkdir(stagingDirectory, {
  264. recursive: true,
  265. });
  266. try {
  267. await copyReleaseFiles({
  268. files,
  269. onProgress,
  270. stagingDirectory,
  271. });
  272. if (shouldReplace) {
  273. await rm(targetDirectory, {
  274. force: true,
  275. recursive: true,
  276. });
  277. }
  278. await rename(stagingDirectory, targetDirectory);
  279. } catch (error) {
  280. await rm(stagingDirectory, {
  281. force: true,
  282. recursive: true,
  283. }).catch(() => undefined);
  284. throw error;
  285. }
  286. return {
  287. bytes: totalBytes,
  288. destination: targetDirectory,
  289. files,
  290. status: "uploaded",
  291. version: releaseVersion,
  292. };
  293. };
  294. export const main = async (argv = process.argv.slice(2)) => {
  295. const options = parseUploadSeaSmbArgs(argv);
  296. if (options.help) {
  297. process.stdout.write(usage);
  298. return;
  299. }
  300. const result = await uploadSeaBinaries({
  301. ...options,
  302. onProgress: createConsoleProgressReporter(),
  303. });
  304. if (result.status === "abandoned") {
  305. process.stdout.write(`[upload] abandoned existing release ${basename(result.destination)}\n`);
  306. return;
  307. }
  308. process.stdout.write(`[upload] uploaded ${result.files.length} files to ${result.destination}\n`);
  309. };
  310. const entryPath = process.argv[1];
  311. if (entryPath && import.meta.url === pathToFileURL(entryPath).href) {
  312. try {
  313. await main();
  314. } catch (error) {
  315. console.error(error instanceof Error ? error.message : String(error));
  316. process.exitCode = 1;
  317. }
  318. }