#!/usr/bin/env bun import fs from "node:fs/promises"; import { dirname } from "node:path"; import { getManifestFromGit, getMigrationFilePath } from "../datasources/manifest-fs"; import { datasourceDropSQL } from "../datasources/to-sql"; import { getEnvConfig } from "../utils/env-config"; import { getUpstartApiClient } from "../utils/upstart-api"; /** * A datasource file was deleted: drop its table (a migration, applied to the preview and remote * databases like the others) and remove the datasource from the site on Upstart. The manifest is * read from the last commit, where the file still exists. */ async function main() { const { UP_SITE_ID: siteId, UP_API_TOKEN: apiToken } = getEnvConfig(); const filePath = process.argv[2]; if (!filePath) { throw new Error("Please provide the path to the deleted datasource manifest file."); } const manifest = await getManifestFromGit(filePath, "HEAD"); console.log(`Deleting datasource "${manifest.id}" of site ${siteId}...`); const migrationFilePath = getMigrationFilePath({ migrationType: "drop", suffix: manifest.id }); if (!(await fs.exists(dirname(migrationFilePath)))) { await fs.mkdir(dirname(migrationFilePath), { recursive: true }); } await fs.writeFile(migrationFilePath, datasourceDropSQL(manifest)); const client = getUpstartApiClient(apiToken); const path = `v1/sites/${siteId}/datasources/${manifest.id}`; // Never registered (its creation failed, or it was removed already): nothing to remove. const existing = await client.callApi(path, "GET"); if (existing.status === 404) { console.log(`Datasource "${manifest.id}" is not registered on Upstart: nothing to remove.`); return; } const response = await client.callApi(path, "DELETE"); if (!response.success) { console.error(`Failed to delete datasource ${manifest.id}: ${JSON.stringify(response.data)}`); process.exit(1); } } main() .then(() => { process.exit(0); }) .catch((e) => { console.error(e instanceof Error ? e.message : e); process.exit(1); });