bitwarden-estensione-browser/src/commands/import.command.ts

59 lines
2.0 KiB
TypeScript
Raw Normal View History

import * as program from 'commander';
2018-08-06 16:38:32 +02:00
import { ImportService } from 'jslib/abstractions/import.service';
2019-03-16 03:34:59 +01:00
import { Response } from 'jslib/cli/models/response';
import { MessageResponse } from 'jslib/cli/models/response/messageResponse';
import { CliUtils } from '../utils';
export class ImportCommand {
2018-08-16 20:43:12 +02:00
constructor(private importService: ImportService) { }
2018-08-16 20:43:12 +02:00
async run(format: string, filepath: string, cmd: program.Command): Promise<Response> {
2018-08-06 16:38:32 +02:00
if (cmd.formats || false) {
return this.list();
} else {
2018-08-16 20:43:12 +02:00
return this.import(format, filepath);
2018-08-06 16:38:32 +02:00
}
}
2018-08-16 20:43:12 +02:00
private async import(format: string, filepath: string) {
2018-08-06 16:38:32 +02:00
if (format == null || format === '') {
return Response.badRequest('`format` was not provided.');
}
if (filepath == null || filepath === '') {
return Response.badRequest('`filepath` was not provided.');
}
const importer = await this.importService.getImporter(format, null);
if (importer === null) {
return Response.badRequest('Proper importer type required.');
}
2018-08-06 16:38:32 +02:00
try {
const contents = await CliUtils.readFile(filepath);
if (contents === null || contents === '') {
return Response.badRequest('Import file was empty.');
}
const err = await this.importService.import(importer, contents, null);
2018-10-11 22:46:04 +02:00
if (err != null) {
return Response.badRequest(err.message);
2018-08-06 16:38:32 +02:00
}
const res = new MessageResponse('Imported ' + filepath, null);
return Response.success(res);
2018-08-06 16:38:32 +02:00
} catch (err) {
return Response.badRequest(err);
}
}
2018-08-06 16:38:32 +02:00
private async list() {
const options = this.importService.getImportOptions().sort((a, b) => {
2018-08-06 16:38:32 +02:00
return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
}).map((option) => option.id).join('\n');
const res = new MessageResponse('Supported input formats:', options);
res.raw = options;
return Response.success(res);
}
}