@adinsure-ops/ops-cli
Version:
Operations CLI for working with AdInsure
206 lines (205 loc) • 9.29 kB
JavaScript
import { __awaiter } from "tslib";
import { Flags, ux } from '@oclif/core';
import axios from 'axios';
import chalk from 'chalk';
import fs from 'fs-extra';
import os from 'os';
import path from 'path';
import CommandBase from '../../command.base.js';
import ChildProcessCommand from '../../lib/command.js';
import OpsConfig from '../../lib/config.js';
class DownloadStudio extends CommandBase {
constructor() {
super(...arguments);
this.url_azure = 'https://ops.adinsure.com/api/storage/extensions/';
this.url_gitlabru = 'https://gitlabru.adacta-fintech.ru/api/v4/projects/2/packages/generic';
}
/**
* Get unique AdInsure Studio vsix zip by specified version
* @param {string} version The version of AdInsure Studio vsix
* @returns {Promise<AxiosResponse<any, any>>}
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
downloadFileFromAzure(version) {
return __awaiter(this, void 0, void 0, function* () {
return axios.get(`${this.url_azure}/adinsure-studio-${version}.vsix`, {
headers: {
Authorization: 'Bearer ' + (yield this.security.getToken()),
'Content-Type': 'application/octet-stream',
},
responseType: 'arraybuffer',
});
});
}
/**
* Get unique AdInsure Studio zip by specified version
* @param {string} version The version of AdInsure Studio
* @returns {Promise<AxiosResponse<any, any>>}
*/
//eslint-disable-next-line @typescript-eslint/no-explicit-any
downloadFileFromGitLabRu(version) {
return __awaiter(this, void 0, void 0, function* () {
const packageName = 'adinsure-studio';
const fileName = `${packageName}-${version}.vsix`;
return axios.get(`${this.url_gitlabru}/${packageName}/${version}/${fileName}`, {
headers: {
'PRIVATE-TOKEN': this.security.getTokenRu(),
},
responseType: 'arraybuffer',
});
});
}
installExtension(extensionPath) {
return __awaiter(this, void 0, void 0, function* () {
const cp = new ChildProcessCommand();
const commandResult = yield cp.runCommand(['code.cmd', '--install-extension', extensionPath, '--force']);
if (commandResult.error) {
this.error(`${chalk.redBright('Installing into VSCode failed!')}\n${commandResult.error}`);
}
});
}
findExtensionIfEnabled(studioVersion, enabled) {
return __awaiter(this, void 0, void 0, function* () {
var _a;
if (!enabled) {
return false;
}
const cp = new ChildProcessCommand();
const result = yield cp.runCommand(['code.cmd', '--list-extensions', '--show-versions']);
return (_a = result === null || result === void 0 ? void 0 : result.data) === null || _a === void 0 ? void 0 : _a.includes(studioVersion);
});
}
run() {
const _super = Object.create(null, {
run: { get: () => super.run }
});
return __awaiter(this, void 0, void 0, function* () {
_super.run.call(this);
// Set default based on config, else use './' as final fallback
const config = new OpsConfig(this.security.getConfigPath());
const defaultFolder = config.get('download_folder');
DownloadStudio.flags.output.default = defaultFolder || './';
const { flags } = yield this.parse(DownloadStudio);
// The os.homedir expands the ~ char, as the node path.resolve method does not expand it
let outputDir = flags.output;
const basePath = outputDir.charAt(0) === '~'
? os.homedir() + outputDir.split('~')[1]
: outputDir;
if (flags.force && !(yield fs.pathExists(basePath))) {
yield fs.mkdirp(basePath);
}
if (!(yield fs.pathExists(basePath))) {
this.error(`${chalk.red('The output directory in which you want to download the studio does not exist!')}${chalk.yellow('\nYou can force to create it with the -f flag.')}`, { exit: 1 });
}
const filename = `adinsure-studio-${flags.version}.vsix`;
const studioVersion = `adacta-fintech.adinsure-studio@${flags.version}`;
const filePath = path.resolve(basePath, filename);
console.log(filePath);
const skipInstallation = yield this.findExtensionIfEnabled(studioVersion, flags.skip);
if (skipInstallation) {
this.log(`The ${studioVersion} already exists. Skipping install.`);
return 0;
}
try {
const alreadyDownloaded = yield fs.pathExists(filePath);
if (alreadyDownloaded && flags.install) {
ux.action.start(`Installing already downloaded AdInsure Studio version ${flags.version} from ${filePath}`, undefined, { stdout: true });
yield this.installExtension(filePath);
ux.action.stop(`${chalk.green('Done')}`);
return;
}
ux.action.start(`Downloading AdInsure Studio version ${flags.version} to ${filePath}`, undefined, { stdout: true });
var file;
if (!flags.source) {
const config = new OpsConfig(this.security.getConfigPath());
flags.source = config.get('endpoint') || 'azure'; // no flag -> DEFAULT source is azure
}
if (flags.source === 'azure') {
file = yield this.downloadFileFromAzure(flags.version);
}
else {
file = yield this.downloadFileFromGitLabRu(flags.version);
}
const writeStream = fs.createWriteStream(filePath);
writeStream.write(file.data, 'binary');
writeStream.on('finish', () => __awaiter(this, void 0, void 0, function* () {
ux.action.stop(`${chalk.green('OK')}`);
if (flags.install) {
ux.action.start(`Installing into VSCode`, undefined, { stdout: true });
yield this.installExtension(filePath);
ux.action.stop(`${chalk.green('Done')}`);
if (!flags.keep) {
ux.action.start(`Removing VSIX file`, undefined, { stdout: true });
fs.removeSync(filePath);
}
ux.action.stop(`${chalk.green('Done')}`);
this.log(`${chalk.yellow('Use \'CRTL + SHIFT + P\' and select reload windows to apply this studio version.')}`);
}
}));
writeStream.end();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
}
catch (error) {
switch (error.statusCode) {
case 404: {
this.error('Does not exist.', { exit: 1 });
}
case 400: {
this.error('Try refreshing your login credentials with "ops login" or "ops login:ru".', { exit: 1 });
}
default: {
this.error(error.message);
}
}
}
});
}
}
DownloadStudio.description = 'download AdInsure Studio vsix from azure storage';
DownloadStudio.usage = 'download:studio <flags>';
DownloadStudio.examples = [
`$ ops download:studio -v 15.0.0 -o ~/Downloads`,
`$ ops download:studio -v 15.0.0 -o ~/Downloads -f`,
`$ ops download:studio -v 15.0.0 -i`,
`$ ops download:studio -v 15.0.0 -i -s`,
`$ ops download:studio -v 15.0.0 -i -k`,
`$ ops download:studio -v 15.0.0 --source=gitlabru`,
];
DownloadStudio.flags = {
source: Flags.string({
description: '[default: azure] artifact source, configurable with config:set endpoint <option>',
options: ['azure', 'gitlabru'],
}),
version: Flags.string({
char: 'v',
description: 'version we want to download',
required: true,
}),
output: Flags.string({
char: 'o',
description: 'output directory',
default: './',
}),
install: Flags.boolean({
char: 'i',
description: 'install plugin to vscode. save to temp folder and remove vsix after.',
default: false,
}),
skip: Flags.boolean({
char: 's',
description: 'only with install. If passed, and desired version is installed it will skip it.',
dependsOn: ['install'],
}),
keep: Flags.boolean({
char: 'k',
description: 'only with install. If passed, it will not remove the vsix file.',
dependsOn: ['install'],
}),
force: Flags.boolean({
char: 'f',
description: 'Create output directory if it does not exist.',
default: false,
dependsOn: ['output'],
}),
};
export default DownloadStudio;