@sasjs/cli
Version:
Command line interface for SASjs
381 lines (380 loc) • 19.1 kB
JavaScript
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.JobCommand = void 0;
var utils_1 = require("@sasjs/utils");
var path_1 = __importDefault(require("path"));
var command_1 = require("../../types/command");
var targetCommand_1 = require("../../types/command/targetCommand");
var utils_2 = require("../../utils");
var getLogFilePath_1 = require("../../utils/getLogFilePath");
var prefixAppLoc_1 = require("../../utils/prefixAppLoc");
var execute_1 = require("./internal/execute");
var node_1 = __importDefault(require("@sasjs/adapter/node"));
var JobSubCommand;
(function (JobSubCommand) {
JobSubCommand["Execute"] = "execute";
JobSubCommand["Exec"] = "exec";
})(JobSubCommand || (JobSubCommand = {}));
var syntax = 'job <subCommand> <jobPath> [options]';
var usage = 'sasjs job <execute> <jobPath> [options]';
var description = 'Performs operations on jobs';
var examples = [
{
command: 'sasjs job execute /Public/folder/someJob -l ./jobLog.log -o ./jobOutput.json -t myTarget',
description: 'Executes the job at /Public/folder/somJob, saves the logs to jobLog.log and the output to jobOutput.json.'
}
];
var executeParseOptions = {
ignoreWarnings: {
type: 'boolean',
alias: 'i',
default: false,
description: 'If present, CLI will return status 0 when the job state is warning.'
},
log: {
type: 'string',
alias: 'l',
description: 'Path where the log of the finished job will be saved. If used, -w is implied.'
},
output: {
type: 'string',
alias: 'o',
description: 'path where output of the finished job execution will be saved.'
},
// returnStatusOnly flag is deprecated and is left to display warning if used
returnStatusOnly: {
type: 'boolean',
default: false,
alias: 'r',
description: 'If present and wait flag is provided, CLI will job status only (0 = success, 1 = warning, 2 = error).'
},
source: {
type: 'string',
alias: 's',
description: 'Path to an input JSON containing job variables.'
},
wait: {
type: 'boolean',
alias: 'w',
default: false,
description: 'Wait for job completion.'
},
statusFile: {
type: 'string',
description: 'Flag indicating if CLI should fetch and save status to the local file. If filepath is not provided, the status is printed to the console.'
},
streamLog: {
type: 'boolean',
description: 'Flag indicating whether the logs should be streamed to a local file as the job executes.'
},
verbose: {
type: 'string',
alias: 'v',
default: false,
description: "If present, CLI will return status 0, 1 or 2 together with HTTP response summaries. If set to 'bleached', HTTP response summaries will be logged without extra colors."
}
};
var JobCommand = /** @class */ (function (_super) {
__extends(JobCommand, _super);
function JobCommand(args) {
var _this = this;
var jobSubCommands = Object.values(JobSubCommand);
var subCommand = args[3];
var parseOptions = jobSubCommands.includes(subCommand)
? executeParseOptions
: {};
_this = _super.call(this, args, {
parseOptions: parseOptions,
usage: usage,
description: description,
examples: examples,
syntax: syntax
}) || this;
_this.sasjs = new node_1.default();
_this.jobSubCommands = jobSubCommands;
_this.verbose = getVerbose(args, _this.parsed.verbose);
return _this;
}
/**
* Method responsible for command execution.
* @returns - promise that resolves into return code.
*/
JobCommand.prototype.execute = function () {
var _a;
return __awaiter(this, void 0, void 0, function () {
var returnStatusOnly, target, sasjsAndAuthConfig, sasjs, authConfig, authConfigSas9, _b, _c, _d, _e;
return __generator(this, function (_f) {
switch (_f.label) {
case 0:
returnStatusOnly = !!this.parsed.returnStatusOnly;
if (returnStatusOnly) {
process.logger.warn('--returnStatusOnly (-r) flag is deprecated.');
}
return [4 /*yield*/, this.getTargetInfo()];
case 1:
target = (_f.sent()).target;
return [4 /*yield*/, (0, utils_2.getSASjsAndAuthConfig)(target).catch(function (err) {
var _a;
// handle getting instance of @sasjs/adapter and auth config failure
(_a = process.logger) === null || _a === void 0 ? void 0 : _a.error('Unable to execute job. Error fetching auth config: ', err);
return {
sasjs: (0, utils_2.getSASjs)(target),
authConfig: undefined,
authConfigSas9: undefined
};
})];
case 2:
sasjsAndAuthConfig = _f.sent();
sasjs = sasjsAndAuthConfig.sasjs;
authConfig = sasjsAndAuthConfig.authConfig;
authConfigSas9 = sasjsAndAuthConfig.authConfigSas9;
if (!sasjs || (!authConfig && !authConfigSas9)) {
return [2 /*return*/, command_1.ReturnCode.InternalError];
}
this.sasjs = sasjs;
this.authConfig = authConfig || authConfigSas9;
if (this.verbose)
this.sasjs.setVerboseMode(this.verbose);
_b = target.serverType;
switch (_b) {
case utils_1.ServerType.SasViya: return [3 /*break*/, 3];
case utils_1.ServerType.Sas9: return [3 /*break*/, 7];
case utils_1.ServerType.Sasjs: return [3 /*break*/, 11];
}
return [3 /*break*/, 15];
case 3:
if (!this.jobSubCommands.includes(this.parsed.subCommand)) return [3 /*break*/, 5];
return [4 /*yield*/, this.executeJobViya(target)];
case 4:
_c = _f.sent();
return [3 /*break*/, 6];
case 5:
_c = command_1.ReturnCode.InvalidCommand;
_f.label = 6;
case 6: return [2 /*return*/, _c];
case 7:
if (!this.jobSubCommands.includes(this.parsed.subCommand)) return [3 /*break*/, 9];
return [4 /*yield*/, this.executeJobSas9(target)];
case 8:
_d = _f.sent();
return [3 /*break*/, 10];
case 9:
_d = command_1.ReturnCode.InvalidCommand;
_f.label = 10;
case 10: return [2 /*return*/, _d];
case 11:
if (typeof this.parsed.jobPath !== 'string')
return [2 /*return*/, command_1.ReturnCode.InvalidCommand];
if (!this.jobSubCommands.includes(this.parsed.subCommand)) return [3 /*break*/, 13];
return [4 /*yield*/, this.executeJobSasjs(target)];
case 12:
_e = _f.sent();
return [3 /*break*/, 14];
case 13:
_e = command_1.ReturnCode.InvalidCommand;
_f.label = 14;
case 14: return [2 /*return*/, _e];
case 15:
(_a = process.logger) === null || _a === void 0 ? void 0 : _a.error("This command is not supported for specified server type.\nPlease try again with a different server type.");
return [2 /*return*/, command_1.ReturnCode.InternalError];
}
});
});
};
/**
* Executes job on SASJS server.
* @param target - SASJS server configuration.
* @returns - promise that resolves into return code.
*/
JobCommand.prototype.executeJobSasjs = function (target) {
var _a;
return __awaiter(this, void 0, void 0, function () {
var jobPath, log, output, returnCode;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
jobPath = (0, prefixAppLoc_1.prefixAppLoc)(target.appLoc, this.parsed.jobPath);
log = (0, getLogFilePath_1.getLogFilePath)(this.parsed.log, jobPath);
output = ((_a = this.parsed.output) === null || _a === void 0 ? void 0 : _a.length)
? this.parsed.output
: undefined;
return [4 /*yield*/, (0, execute_1.executeJobSasjs)(this.sasjs, target, jobPath, log, output, this.authConfig)
.then(function () { return command_1.ReturnCode.Success; })
.catch(function (err) {
var _a;
// handle job execution failure
(_a = process.logger) === null || _a === void 0 ? void 0 : _a.error('Error executing job: ', err);
return command_1.ReturnCode.InternalError;
})];
case 1:
returnCode = _b.sent();
return [2 /*return*/, returnCode];
}
});
});
};
/**
* Executes job on SAS9 server.
* @param target - SAS9 server configuration.
* @returns - promise that resolves into return code.
*/
JobCommand.prototype.executeJobSas9 = function (target) {
var _a;
return __awaiter(this, void 0, void 0, function () {
var jobPath, log, source, output, userName, password, returnCode;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
jobPath = (0, prefixAppLoc_1.prefixAppLoc)(target.appLoc, this.parsed.jobPath);
log = (0, getLogFilePath_1.getLogFilePath)(this.parsed.log, jobPath);
source = this.parsed.source;
output = ((_a = this.parsed.output) === null || _a === void 0 ? void 0 : _a.length)
? this.parsed.output
: undefined;
this.authConfig = this.authConfig;
userName = this.authConfig.userName;
password = (0, utils_1.decodeFromBase64)(this.authConfig.password);
return [4 /*yield*/, (0, execute_1.executeJobSas9)(this.sasjs, { userName: userName, password: password }, jobPath, log, output, source)
.then(function () { return command_1.ReturnCode.Success; })
.catch(function (err) {
var _a;
// handle job execution failure
(_a = process.logger) === null || _a === void 0 ? void 0 : _a.error('Error executing job: ', err);
return command_1.ReturnCode.InternalError;
})];
case 1:
returnCode = _b.sent();
return [2 /*return*/, returnCode];
}
});
});
};
/**
* Executes job on Viya server.
* @param target - Viya server configuration.
* @returns - promise that resolves into return code.
*/
JobCommand.prototype.executeJobViya = function (target) {
var _a, _b;
return __awaiter(this, void 0, void 0, function () {
var jobPath, statusFile, log, ignoreWarnings, streamLog, source, wait, output, returnCode;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
jobPath = (0, prefixAppLoc_1.prefixAppLoc)(target.appLoc, this.parsed.jobPath);
statusFile = getStatusFilePath(this.parsed.statusFile);
log = (0, getLogFilePath_1.getLogFilePath)(this.parsed.log, jobPath);
ignoreWarnings = !!this.parsed.ignoreWarnings;
streamLog = !!this.parsed.streamLog;
source = this.parsed.source;
wait = this.parsed.wait || !!log;
output = ((_a = this.parsed.output) === null || _a === void 0 ? void 0 : _a.length)
? this.parsed.output
: ((_b = this.parsed.output) === null || _b === void 0 ? void 0 : _b.length) === 0
? true
: false;
if (!!this.verbose && !wait)
wait = true;
return [4 /*yield*/, (0, execute_1.executeJobViya)(this.sasjs, this.authConfig, jobPath, target, wait, output, log, statusFile, ignoreWarnings, source, streamLog)
.then(function () { return command_1.ReturnCode.Success; })
.catch(function (err) {
var _a;
// handle job execution failure
(_a = process.logger) === null || _a === void 0 ? void 0 : _a.error('Error executing job: ', err);
return command_1.ReturnCode.InternalError;
})];
case 1:
returnCode = _c.sent();
return [2 /*return*/, returnCode];
}
});
});
};
return JobCommand;
}(targetCommand_1.TargetCommand));
exports.JobCommand = JobCommand;
/**
* Gets status file path.
* @param statusFileArg - file path provided as command attribute.
* @returns - absolute status file path or undefined if command attribute wasn't provided.
*/
var getStatusFilePath = function (statusFileArg) {
if (statusFileArg) {
var currentDirPath = path_1.default.isAbsolute(statusFileArg)
? ''
: process.projectDir;
return path_1.default.join(currentDirPath, statusFileArg);
}
return undefined;
};
/**
* Determines verbose mode based on command arguments.
* @param args - command arguments.
* @param verboseArg - value of the verbose argument.
* @returns - verbose mode.
*/
var getVerbose = function (args, verboseArg) {
var verboseArgPresent = args.includes('-v') || args.includes('--verbose');
if (verboseArgPresent) {
// if verboseArg, use the string as verbose mode(any strings not equal to
// 'bleached' will be ignored)
if (typeof verboseArg === 'string')
return verboseArg;
return true;
}
return undefined;
};