UNPKG

@controlplane/cli

Version:

Control Plane Corporation CLI

212 lines 8.59 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.STRUCTURED_FORMATS = void 0; exports.format = format; exports.formatAsync = formatAsync; exports.write = write; exports.slimObject = slimObject; const format_1 = require("../util/format"); const api_1 = require("../rest/api"); const client_1 = require("../session/client"); const errors_1 = require("../util/errors"); /** The output formats that serialize the full object, as opposed to a human-oriented table. */ exports.STRUCTURED_FORMATS = ['json', 'json-slim', 'yaml', 'yaml-slim']; function format(obj, options) { var _a; if (typeof obj == 'string') { return obj; } if (obj == null) { // null or undefined return ''; } if (((_a = options === null || options === void 0 ? void 0 : options._hints) === null || _a === void 0 ? void 0 : _a.kind) === 'error') { if (!Array.isArray(obj)) { obj = [obj]; } obj = obj.map((o) => { var _a, _b, _c, _d; if ((_b = (_a = o.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.status) { return (_c = o.response) === null || _c === void 0 ? void 0 : _c.data; } if (o.isAxiosError) { const axiosError = o; // For network errors (e.g., certificate errors, connection refused), there is no response. // Use the error message and code instead. if (!axiosError.response) { return { code: axiosError.code, message: axiosError.message, }; } return { status: axiosError.response.status, message: axiosError.response.data, }; } return ((_d = o.response) === null || _d === void 0 ? void 0 : _d.data) || o.message; }); // If we have a single plain string error message, return it as-is if (obj.length === 1 && typeof obj[0] === 'string') { return obj[0]; } } switch (options === null || options === void 0 ? void 0 : options.output) { case 'yaml-slim': obj = slimObject(obj); return toPrettyYaml(obj, options === null || options === void 0 ? void 0 : options.color, options === null || options === void 0 ? void 0 : options._separateDocs); case 'yaml': return toPrettyYaml(obj, options === null || options === void 0 ? void 0 : options.color, options === null || options === void 0 ? void 0 : options._separateDocs); case 'json-slim': obj = slimObject(obj); return toPrettyJson(obj, options === null || options === void 0 ? void 0 : options.color); case 'json': return toPrettyJson(obj, options === null || options === void 0 ? void 0 : options.color); case 'names': return toNames(obj); default: try { return toPrettyTable(obj, options); } catch (e) { console.error(e); const message = `ERROR: An issue prevented the data from being formatted into a table. Attempt the operation again with '-o json' for output in JSON format. For support, please provide the error above to the Control Plane team.`; throw new errors_1.PrettifyTableError(message, e); } } } async function formatAsync(session, obj, options) { switch (options === null || options === void 0 ? void 0 : options.output) { case 'tf': return await toTerraform(session, obj); case 'crd': return await toCrd(session, obj, options); } return format(obj, options); } function write(stream, value) { if (typeof value === 'object') { value = format(value, { output: 'json' }); } if (stream == process.stdout) { console.log(value); } else if (stream == process.stderr) { console.error(value); } else { // only gets here in unit tests // handle in-memory buffers (for testing only) throw new Error('can only work with console streams'); } } function slimObject(obj) { if (Array.isArray(obj)) { obj = obj.map(slimObject); } else if (obj.kind === 'list') { delete obj.links; obj.items = obj.items.map(slimObject); } else { delete obj.id; delete obj.version; delete obj.created; delete obj.lastModified; delete obj.links; delete obj.status; delete obj.alias; delete obj.origin; delete obj.repository; delete obj.tag; delete obj.manifest; delete obj.digest; if (obj.tags) { delete obj.tags['cpln/deployTimestamp']; } } return obj; } function toPrettyJson(obj, color) { if (color) { return require('json-colorizer').colorize((0, format_1.toSortedJson)(obj)) + '\n'; } else { let sorted = (0, format_1.toSortedJson)(obj); return JSON.stringify(sorted, undefined, ' '); } } function toPrettyYaml(obj, color, separateDocs) { // Declare a variable to hold the final YAML output let output; // If separateDocs is true and the object is an array, create separate documents if (separateDocs && Array.isArray(obj)) { // Convert each item in the array to YAML and collect the results const docs = obj.map((item) => (0, format_1.toSortedYamlString)(item)); // Join the individual YAML documents using the '---' separator output = docs.join('---\n'); } else { // Otherwise, use the normal conversion output = (0, format_1.toSortedYamlString)(obj); } // If color is enabled, highlight the YAML output and return it if (color) { const highlight = require('cli-highlight').highlight; return highlight(output, { language: 'yaml', ignoreIllegals: true }); } // Return the final YAML string without color highlighting return output; } function toNames(obj) { const objects = getObjectsArray(obj); const names = objects.map((obj) => { if (!obj.hasOwnProperty('name')) { throw new errors_1.FormatNamesError('ERROR: Unable to format to "names", one or more objects are missing the "name" property.'); } return obj.name; }); return names.join('\n').trim(); } function getObjectsArray(obj) { if (Array.isArray(obj)) { return obj; } if (typeof obj === 'object' && obj.kind === 'list' && Array.isArray(obj.items)) { return obj.items; } return [obj]; } function toPrettyTable(obj, options) { // lazily require the table formatter as the lib is big return require('./table').toPrettyTable(obj, options !== null && options !== void 0 ? options : {}); } async function toTerraform(session, obj) { const resource = obj; // Find the self link of the resource so we can export by link const selfLink = resource.links.find((link) => link.rel === 'self').href; // Get the service endpoint const serviceEndpoint = await (0, api_1.getDiscoveryEndpoint)(session.request.endpoint, 'terraform-exporter'); // Create the client const client = (0, client_1.makeSessionClient)(session, serviceEndpoint); // Export to Terraform by its self link and return the result return await client.get(selfLink); } async function toCrd(session, obj, options) { const resource = obj; // Find the self link of the resource so we can export by link const selfLink = resource.links.find((link) => link.rel === 'self').href; // Get the service endpoint const serviceEndpoint = await (0, api_1.getDiscoveryEndpoint)(session.request.endpoint, 'k8s-crd-exporter'); // Create the client const client = (0, client_1.makeSessionClient)(session, serviceEndpoint); // Get the resource by its self link const response = await client.get(selfLink); // If the response is of kind 'List', let's tell the YAML prettifier to separate response items with a separator if (response.kind == 'list') { return toPrettyYaml(response.items, options === null || options === void 0 ? void 0 : options.color, true); } // Return the YAML representation of the response return toPrettyYaml(response, options === null || options === void 0 ? void 0 : options.color); } //# sourceMappingURL=format.js.map