bitburner/scripts/update.js

187 lines
7.0 KiB
JavaScript
Raw Normal View History

2022-03-09 14:06:14 -05:00
export class ArgError extends Error {}
2022-03-19 13:55:27 -04:00
class ArgParser {
2022-02-11 01:08:32 -05:00
/**
* Create a unix-like argument parser to extract flags from the argument list. Can also create help messages.
2022-03-09 14:06:14 -05:00
* @param name {string} - Script name
* @param desc {string} - Help text desciption
* @param examples {string[]} - Help text examples
* @param argList {name: string, desc: string, flags: string[], type: string, default: any}[] - Array of CLI arguments
2022-03-19 13:55:27 -04:00
* @param allowUnknown {boolean} - Allow unknown flags
2022-02-11 01:08:32 -05:00
*/
2022-03-19 13:55:27 -04:00
constructor(name, desc, examples, argList, allowUnknown = false) {
2022-03-09 14:06:14 -05:00
this.name = name ?? 'example.js';
this.description = desc ?? 'Example description';
this.examples = examples || [`${argList.find(arg => !!arg.flags) ? '[OPTIONS] ' : ''}${argList.filter(arg => !arg.flags).map(arg => (arg.optional ? `[${arg.name.toUpperCase()}]` : arg.name.toUpperCase()) + (arg.extras ? '...' : '')).join(' ')}`];
this.examples.push('--help');
this.argList = argList || [];
this.argList.push({name: 'help', desc: 'Display this help message', flags: ['-h', '--help'], type: 'bool'});
2022-03-19 13:55:27 -04:00
this.allowUnknown = allowUnknown;
2022-02-11 01:08:32 -05:00
}
/**
2022-03-09 14:06:14 -05:00
* Parse an array into an arguments dictionary using the configuration.
* @param args {string[]} - Array of arguments to be parsed
* @returns {object} - Dictionary of arguments with defaults applied
2022-02-11 01:08:32 -05:00
*/
parse(args) {
2022-03-09 14:06:14 -05:00
// Parse arguments
const queue = [...args], extra = [];
const parsed = this.argList.reduce((acc, arg) => ({...acc, [arg.name]: arg.default ?? (arg.type == 'bool' ? false : null)}), {});
// Flags
while(queue.length) {
let parse = queue.splice(0, 1)[0];
if(parse[0] == '-') {
// Check combined flags
if(parse[1] != '-' && parse.length > 2) {
parse = `-${parse[1]}`;
queue = parse.substring(1).split('').map(a => `-${a}`).concat(queue);
}
// Find & add flag
2022-02-11 01:08:32 -05:00
const split = parse.split('=');
2022-03-09 14:06:14 -05:00
const arg = this.argList.find(arg => arg.flags && arg.flags.includes(split[0] || parse));
2022-03-19 13:55:27 -04:00
if(arg == null) {
if(!this.allowUnknown) throw new ArgError(`Option unknown: ${parse}`);
extra.push(parse);
continue;
}
2022-03-09 14:06:14 -05:00
if(arg.name == 'help') throw new ArgError('Help');
const value = arg.type == 'bool' ? true : split[1] || queue.splice(queue.findIndex(q => q[0] != '-'), 1)[0];
if(value == null) throw new ArgError(`Option missing value: ${arg.name}`);
parsed[arg.name] = value;
2022-03-15 20:41:23 -04:00
} else {
2022-03-09 14:06:14 -05:00
// Save for required parsing
extra.push(parse);
2022-02-11 01:08:32 -05:00
}
}
2022-03-09 14:06:14 -05:00
// Arguments
this.argList.filter(arg => !arg.flags && !arg.extras).forEach(arg => {
if(!arg.optional && !extra.length) throw new ArgError(`Argument missing: ${arg.name.toUpperCase()}`);
const value = extra.splice(0, 1)[0];
if(value != null) parsed[arg.name] = value;
});
// Extras
const extraKey = this.argList.find(arg => arg.extras)?.name || 'extra';
parsed[extraKey] = extra;
return parsed;
2022-02-11 01:08:32 -05:00
}
/**
2022-03-09 14:06:14 -05:00
* Create help message from the provided description, examples & argument list.
* @param message {string} - Message to display, defaults to the description
2022-03-15 20:41:23 -04:00
* @returns {string} - Help message
2022-02-11 01:08:32 -05:00
*/
help(msg) {
2022-03-09 14:06:14 -05:00
// Description
let message = '\n\n' + (msg && msg.toLowerCase() != 'help' ? msg : this.description);
// Usage
if(this.examples.length) message += '\n\nUsage:\t' + this.examples.map(ex => `run ${this.name} ${ex}`).join('\n\t');
// Arguments
const req = this.argList.filter(a => !a.flags);
if(req.length) message += '\n\n\t' + req.map(arg => {
const padding = 3 - ~~(arg.name.length / 8);
return `${arg.name.toUpperCase()}${Array(padding).fill('\t').join('')} ${arg.desc}`;
2022-02-11 01:08:32 -05:00
}).join('\n\t');
2022-03-09 14:06:14 -05:00
// Flags
const opts = this.argList.filter(a => a.flags);
if(opts.length) message += '\n\nOptions:\n\t' + opts.map(a => {
const flgs = a.flags.join(' ');
2022-02-11 01:08:32 -05:00
const padding = 3 - ~~(flgs.length / 8);
return `${flgs}${Array(padding).fill('\t').join('')} ${a.desc}`;
}).join('\n\t');
2022-03-09 14:06:14 -05:00
// Print final message
2022-02-11 01:08:32 -05:00
return `${message}\n\n`;
}
}
2022-02-04 17:17:13 -05:00
/**
2022-03-09 14:06:14 -05:00
* Print a download bar to the terminal.
* @params ns {NS} - Bitburner API
* @params file - Filename to display with progress bar
2022-02-04 17:17:13 -05:00
*/
2022-03-19 13:55:27 -04:00
async function downloadPrint(ns, file) {
2022-03-09 14:06:14 -05:00
const speed = ~~(Math.random() * 100) / 10;
2022-03-11 11:36:41 -05:00
const spacing = Array((40 - file.length) || 1).fill(' ').join('');
await slowPrint(ns, `${file}${spacing}[==================>] 100%\t(${speed} MB/s)`);
2022-03-09 14:06:14 -05:00
}
2022-02-10 15:25:21 -05:00
2022-03-09 14:06:14 -05:00
/**
* Print text to the terminal & then delay for a random amount of time to emulate execution time.
2022-03-19 13:55:27 -04:00
* @param ns {NS} - BitBurner API
* @param message {string} - Text to display
* @param min {number} - minimum amount of time to wait after printing text
* @param max {number} - maximum amount of time to wait after printing text
2022-03-09 14:06:14 -05:00
*/
2022-03-19 13:55:27 -04:00
async function slowPrint(ns, message, min = 0.5, max = 1.5) {
2022-03-09 14:06:14 -05:00
const time = ~~(Math.random() * (max * 1000 - min * 1000)) + min * 1000;
ns.tprint(message);
await ns.sleep(time);
}
2022-02-11 01:08:32 -05:00
2022-03-09 14:06:14 -05:00
/**
* Automatically download all the scripts in the repository.
* @params ns {NS} - BitBurner API
*/
export async function main(ns) {
2022-02-10 12:10:26 -05:00
// Setup
2022-03-09 14:06:14 -05:00
ns.disableLog('ALL');
const updateFile = 'update.js';
const argParser = new ArgParser(updateFile, 'Download the latest script updates from the repository using wget.', null, [
2022-03-11 11:44:23 -05:00
{name: 'device', desc: 'Device to update, defaults to current machine', optional: true, default: ns.getHostname(), type: 'string'},
{name: 'skip-self', desc: 'Skip updating self (for debugging & used internally)', flags: ['--skip-self'], type: 'bool'},
{name: 'no-banner', desc: 'Hide the banner (Used internally)', flags: ['--no-banner'], type: 'bool'}
2022-03-09 14:06:14 -05:00
]);
2022-03-19 13:55:27 -04:00
2022-03-09 14:06:14 -05:00
try {
2022-03-19 13:55:27 -04:00
const args = argParser.parse(ns.args || []);
const src = 'https://gitlab.zakscode.com/ztimson/BitBurner/-/raw/develop/scripts/';
const dest = '/scripts/';
const fileList = [
'lib/arg-parser.js',
'lib/logger.js',
'lib/utils.js',
'botnet-manager.js',
'connect.js',
'copy.js',
'crawler.js',
'find-target.js',
'hacknet-manager.js',
'miner.js',
'network-graph.js',
'rootkit.js'
];
if(!args['no-banner']) {
// Banner
ns.tprint('===================================================');
ns.tprint(`Updating: ${args['device']}`);
ns.tprint('===================================================');
}
// Run
if(!args['skip-self']) { // Update self & restart
await slowPrint(ns, 'Updating self:');
await ns.wget(`${src}${updateFile}`, `${dest}${updateFile}`, args['device']);
await downloadPrint(ns, `${dest}${updateFile}`);
ns.tprint('');
await slowPrint(ns, 'Restarting...');
const pid = ns.run(`${dest}${updateFile}`, 1, args['device'], '--skip-self', '--no-banner');
if(pid == 0) ns.tprint('Failed');
else ns.tprint('Complete');
return await slowPrint(ns, '');
} else { // Update everything else
await slowPrint(ns, 'Downloading scripts:');
for(let file of fileList) {
await ns.wget(`${src}${file}`, `${dest}${file}`, args['device']);
await downloadPrint(ns, `${dest}${file}`);
}
ns.tprint('');
ns.tprint('Done!');
ns.tprint('');
}
2022-03-09 14:06:14 -05:00
} catch(err) {
2022-03-19 13:55:27 -04:00
if(err instanceof ArgParser.ArgError) return ns.tprint(argParser.help(err.message));
2022-03-09 14:06:14 -05:00
throw err;
}
2022-03-11 11:56:04 -05:00
}