const TOKEN = 'test';
import { join } from "node:path";
import type { I_CommandCode } from "../command_runner.ts";
import { } from "../../../utils/read_file.ts";
import { Command } from "./enum.ts";
import { existsSync } from "jsr:@std/fs/exists";
import { Zip } from "../../../modules/zip.ts";
import { FileSize } from "../../../utils/file_size.ts";
import { HOST_URL } from "../../config.ts";
import { ScanFiles } from "../../../utils/scan_files.ts";
import { Option } from "../options.ts";
export const publish_command = {
command: Command.publish,
aliases: ['deploy', 'upload', 'push'],
description: 'Publishes the current code to Viapak under a new version',
more_info: ['Usage: viapak publish [--force]'],
help_text: [],
optional_options: [Option.force],
execute: async ({ options }) => {
try {
const __dirname = Deno.cwd();
const deno_json_path = join(__dirname, 'deno.json');
if(!existsSync(deno_json_path, { isFile: true })) throw new Error('deno.json not found. Are you running this in a project root directory?');
const deno_meta = JSON.parse(Deno.readTextFileSync(join(__dirname, 'deno.json')) ?? "{}");
const { name, version } = deno_meta;
if(!name) throw new Error('Please add a package name to your deno.json');
if(!version) throw new Error('Please add a package version to your deno.json');
console.log(`Publishing ${name}@${version}...`);
console.log(` '- Compressing package...`);
const files = ScanFiles(__dirname);
const temp_publish_zip_path = join(__dirname, '_publish.zip');
if(existsSync(temp_publish_zip_path)) Deno.removeSync(temp_publish_zip_path);
await Zip.Process(files, { destination_file_path: temp_publish_zip_path }).then(async zip => {
console.log(` '- Uploading package... (${FileSize(zip.length)})`);
const headers = new Headers({
'Content-Type': 'application/zip',
'Content-Length': zip.length.toString(),
'Authorization': `Bearer ${TOKEN}`,
})
const FORCE = options.force;
if(FORCE) {
const confirm_force = confirm(` X You have set the --force flag to overwrite ${name}@${version} if it exists. Are you sure? This can't be undone!`);
if(!confirm_force) {
console.log();
Deno.exit(0);
}
headers.append('X-Force', 'TRUE');
}
const req = new Request(new URL(`publish/${name}@${version}`, HOST_URL), {
method: 'PUT',
headers,
body: zip.stream,
});
const response = await fetch(req);
if(!response.ok) {
throw new Error(await response.text());
}
console.log(` '- ${name}@${version} ${FORCE ? 'overwritten' : 'published'}!`);
return;
});
} catch(e: any) {
console.error(` '- Could not publish!`);
console.error(` ${e.message}`);
}
console.log("");
}
} as I_CommandCode;