2020-04-23 12:46:19 +00:00
|
|
|
/**
|
|
|
|
* @license
|
2021-04-27 13:58:54 +00:00
|
|
|
* Copyright 2017-2021 Balena Ltd.
|
2020-04-23 12:46:19 +00:00
|
|
|
*
|
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
* you may not use this file except in compliance with the License.
|
|
|
|
* You may obtain a copy of the License at
|
|
|
|
*
|
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
*
|
|
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
* See the License for the specific language governing permissions and
|
|
|
|
* limitations under the License.
|
|
|
|
*/
|
|
|
|
|
2022-01-03 13:47:07 +00:00
|
|
|
import type { Renderer } from './compose_ts';
|
|
|
|
import type * as SDK from 'balena-sdk';
|
|
|
|
import type Dockerode = require('dockerode');
|
2020-04-23 12:46:19 +00:00
|
|
|
import * as path from 'path';
|
2022-06-28 12:22:42 +00:00
|
|
|
import type { Composition, ImageDescriptor } from '@balena/compose/dist/parse';
|
2023-12-11 16:55:49 +00:00
|
|
|
import type { RetryParametersObj } from 'pinejs-client-core';
|
2022-01-03 13:47:07 +00:00
|
|
|
import type {
|
|
|
|
BuiltImage,
|
|
|
|
ComposeOpts,
|
|
|
|
ComposeProject,
|
|
|
|
Release,
|
|
|
|
TaggedImage,
|
|
|
|
} from './compose-types';
|
2020-10-01 23:10:40 +00:00
|
|
|
import { getChalk } from './lazy';
|
2022-01-03 13:47:07 +00:00
|
|
|
import Logger = require('./logger');
|
2024-03-14 12:11:53 +00:00
|
|
|
import type { ProgressCallback } from 'docker-progress';
|
2022-01-03 13:47:07 +00:00
|
|
|
|
|
|
|
export function generateOpts(options: {
|
|
|
|
source?: string;
|
|
|
|
projectName?: string;
|
|
|
|
nologs: boolean;
|
|
|
|
'noconvert-eol': boolean;
|
|
|
|
dockerfile?: string;
|
|
|
|
'multi-dockerignore': boolean;
|
|
|
|
'noparent-check': boolean;
|
|
|
|
}): Promise<ComposeOpts> {
|
|
|
|
const { promises: fs } = require('fs') as typeof import('fs');
|
2020-06-15 22:53:07 +00:00
|
|
|
return fs.realpath(options.source || '.').then((projectPath) => ({
|
2020-04-23 12:46:19 +00:00
|
|
|
projectName: options.projectName,
|
|
|
|
projectPath,
|
2020-07-30 08:39:05 +00:00
|
|
|
inlineLogs: !options.nologs,
|
|
|
|
convertEol: !options['noconvert-eol'],
|
2020-04-23 12:46:19 +00:00
|
|
|
dockerfilePath: options.dockerfile,
|
2020-06-24 23:01:53 +00:00
|
|
|
multiDockerignore: !!options['multi-dockerignore'],
|
2020-04-23 12:46:19 +00:00
|
|
|
noParentCheck: options['noparent-check'],
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
2022-01-03 13:47:07 +00:00
|
|
|
/** Parse the given composition and return a structure with info. Input is:
|
|
|
|
* - composePath: the *absolute* path to the directory containing the compose file
|
|
|
|
* - composeStr: the contents of the compose file, as a string
|
2020-04-23 12:46:19 +00:00
|
|
|
*/
|
2021-09-09 00:22:32 +00:00
|
|
|
export function createProject(
|
2022-01-03 13:47:07 +00:00
|
|
|
composePath: string,
|
|
|
|
composeStr: string,
|
2021-09-09 00:22:32 +00:00
|
|
|
projectName = '',
|
|
|
|
imageTag = '',
|
2022-01-03 13:47:07 +00:00
|
|
|
): ComposeProject {
|
|
|
|
const yml = require('js-yaml') as typeof import('js-yaml');
|
|
|
|
const compose =
|
2022-06-28 12:22:42 +00:00
|
|
|
require('@balena/compose/dist/parse') as typeof import('@balena/compose/dist/parse');
|
2020-04-23 12:46:19 +00:00
|
|
|
|
|
|
|
// both methods below may throw.
|
2021-10-20 12:07:20 +00:00
|
|
|
const rawComposition = yml.load(composeStr);
|
2020-04-23 12:46:19 +00:00
|
|
|
const composition = compose.normalize(rawComposition);
|
|
|
|
|
2021-09-09 00:22:32 +00:00
|
|
|
projectName ||= path.basename(composePath);
|
2020-08-27 10:50:57 +00:00
|
|
|
|
2020-06-15 22:53:07 +00:00
|
|
|
const descriptors = compose.parse(composition).map(function (descr) {
|
2020-04-23 12:46:19 +00:00
|
|
|
// generate an image name based on the project and service names
|
|
|
|
// if one is not given and the service requires a build
|
|
|
|
if (
|
|
|
|
typeof descr.image !== 'string' &&
|
|
|
|
descr.image.context != null &&
|
|
|
|
descr.image.tag == null
|
|
|
|
) {
|
2022-01-03 13:47:07 +00:00
|
|
|
const { makeImageName } =
|
|
|
|
require('./compose_ts') as typeof import('./compose_ts');
|
2021-09-09 00:22:32 +00:00
|
|
|
descr.image.tag = makeImageName(projectName, descr.serviceName, imageTag);
|
2020-04-23 12:46:19 +00:00
|
|
|
}
|
|
|
|
return descr;
|
|
|
|
});
|
|
|
|
return {
|
|
|
|
path: composePath,
|
|
|
|
name: projectName,
|
|
|
|
composition,
|
|
|
|
descriptors,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2023-12-11 16:55:49 +00:00
|
|
|
const getRequestRetryParameters = (): RetryParametersObj => {
|
|
|
|
if (
|
|
|
|
process.env.BALENA_CLI_TEST_TYPE != null &&
|
|
|
|
process.env.BALENA_CLI_TEST_TYPE !== ''
|
|
|
|
) {
|
|
|
|
// We only read the test env vars when in test mode.
|
|
|
|
const { intVar } =
|
|
|
|
require('@balena/env-parsing') as typeof import('@balena/env-parsing');
|
|
|
|
// We use the BALENARCTEST namespace and only parse the env vars while in test mode
|
|
|
|
// since we plan to switch all pinejs clients with the one of the SDK and might not
|
|
|
|
// want to have to support these env vars.
|
|
|
|
return {
|
|
|
|
minDelayMs: intVar('BALENARCTEST_API_RETRY_MIN_DELAY_MS'),
|
|
|
|
maxDelayMs: intVar('BALENARCTEST_API_RETRY_MAX_DELAY_MS'),
|
|
|
|
maxAttempts: intVar('BALENARCTEST_API_RETRY_MAX_ATTEMPTS'),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
minDelayMs: 1000,
|
|
|
|
maxDelayMs: 60000,
|
|
|
|
maxAttempts: 7,
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
2020-08-04 13:17:51 +00:00
|
|
|
export const createRelease = async function (
|
2023-12-11 16:55:49 +00:00
|
|
|
logger: Logger,
|
2022-01-03 13:47:07 +00:00
|
|
|
apiEndpoint: string,
|
|
|
|
auth: string,
|
|
|
|
userId: number,
|
|
|
|
appId: number,
|
|
|
|
composition: Composition,
|
|
|
|
draft: boolean,
|
2023-12-11 16:55:49 +00:00
|
|
|
semver: string | undefined,
|
|
|
|
contract: string | undefined,
|
2022-01-03 13:47:07 +00:00
|
|
|
): Promise<Release> {
|
|
|
|
const _ = require('lodash') as typeof import('lodash');
|
|
|
|
const crypto = require('crypto') as typeof import('crypto');
|
|
|
|
const releaseMod =
|
2022-06-28 12:22:42 +00:00
|
|
|
require('@balena/compose/dist/release') as typeof import('@balena/compose/dist/release');
|
2020-04-23 12:46:19 +00:00
|
|
|
|
2023-12-11 16:55:49 +00:00
|
|
|
const client = releaseMod.createClient({
|
|
|
|
apiEndpoint,
|
|
|
|
auth,
|
|
|
|
retry: {
|
|
|
|
...getRequestRetryParameters(),
|
|
|
|
onRetry: (err, delayMs, attempt, maxAttempts) => {
|
|
|
|
const code = err?.statusCode ?? 0;
|
|
|
|
logger.logDebug(
|
|
|
|
`API call failed with code ${code}. Attempting retry ${attempt} of ${maxAttempts} in ${
|
|
|
|
delayMs / 1000
|
|
|
|
} seconds`,
|
|
|
|
);
|
|
|
|
},
|
|
|
|
},
|
|
|
|
});
|
2020-04-23 12:46:19 +00:00
|
|
|
|
2020-08-04 13:17:51 +00:00
|
|
|
const { release, serviceImages } = await releaseMod.create({
|
|
|
|
client,
|
|
|
|
user: userId,
|
|
|
|
application: appId,
|
|
|
|
composition,
|
|
|
|
source: 'local',
|
|
|
|
commit: crypto.pseudoRandomBytes(16).toString('hex').toLowerCase(),
|
2021-05-19 22:12:49 +00:00
|
|
|
semver,
|
|
|
|
is_final: !draft,
|
2021-08-26 14:05:50 +00:00
|
|
|
contract,
|
2020-08-04 13:17:51 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
return {
|
|
|
|
client,
|
2021-01-13 13:12:38 +00:00
|
|
|
release: _.pick(release, [
|
|
|
|
'id',
|
|
|
|
'status',
|
|
|
|
'commit',
|
|
|
|
'composition',
|
|
|
|
'source',
|
2021-05-19 22:12:49 +00:00
|
|
|
'is_final',
|
|
|
|
'contract',
|
|
|
|
'semver',
|
2021-01-13 13:12:38 +00:00
|
|
|
'start_timestamp',
|
|
|
|
'end_timestamp',
|
2020-08-04 13:17:51 +00:00
|
|
|
]),
|
2022-01-03 13:47:07 +00:00
|
|
|
serviceImages: _.mapValues(
|
|
|
|
serviceImages,
|
|
|
|
(serviceImage) =>
|
|
|
|
_.omit(serviceImage, [
|
|
|
|
'created_at',
|
|
|
|
'is_a_build_of__service',
|
|
|
|
'__metadata',
|
|
|
|
]) as Omit<
|
|
|
|
typeof serviceImage,
|
|
|
|
'created_at' | 'is_a_build_of__service' | '__metadata'
|
|
|
|
>,
|
2020-08-04 13:17:51 +00:00
|
|
|
),
|
|
|
|
};
|
2020-04-23 12:46:19 +00:00
|
|
|
};
|
|
|
|
|
2022-01-03 13:47:07 +00:00
|
|
|
export const tagServiceImages = (
|
|
|
|
docker: Dockerode,
|
|
|
|
images: BuiltImage[],
|
|
|
|
serviceImages: Release['serviceImages'],
|
|
|
|
): Promise<TaggedImage[]> =>
|
2020-06-30 20:17:24 +00:00
|
|
|
Promise.all(
|
|
|
|
images.map(function (d) {
|
|
|
|
const serviceImage = serviceImages[d.serviceName];
|
|
|
|
const imageName = serviceImage.is_stored_at__image_location;
|
|
|
|
const match = /(.*?)\/(.*?)(?::([^/]*))?$/.exec(imageName);
|
|
|
|
if (match == null) {
|
|
|
|
throw new Error(`Could not parse imageName: '${imageName}'`);
|
|
|
|
}
|
|
|
|
const [, registry, repo, tag = 'latest'] = match;
|
|
|
|
const name = `${registry}/${repo}`;
|
|
|
|
return docker
|
|
|
|
.getImage(d.name)
|
|
|
|
.tag({ repo: name, tag, force: true })
|
|
|
|
.then(() => docker.getImage(`${name}:${tag}`))
|
|
|
|
.then((localImage) => ({
|
|
|
|
serviceName: d.serviceName,
|
|
|
|
serviceImage,
|
|
|
|
localImage,
|
|
|
|
registry,
|
|
|
|
repo,
|
|
|
|
logs: d.logs,
|
|
|
|
props: d.props,
|
|
|
|
}));
|
|
|
|
}),
|
|
|
|
);
|
2020-04-23 12:46:19 +00:00
|
|
|
|
2022-01-03 13:47:07 +00:00
|
|
|
export const getPreviousRepos = (
|
|
|
|
sdk: SDK.BalenaSDK,
|
|
|
|
logger: Logger,
|
|
|
|
appID: number,
|
|
|
|
): Promise<string[]> =>
|
2020-04-23 12:46:19 +00:00
|
|
|
sdk.pine
|
2022-01-03 13:47:07 +00:00
|
|
|
.get<SDK.Release>({
|
2020-04-23 12:46:19 +00:00
|
|
|
resource: 'release',
|
|
|
|
options: {
|
2022-01-03 13:47:07 +00:00
|
|
|
$select: 'id',
|
2020-04-23 12:46:19 +00:00
|
|
|
$filter: {
|
|
|
|
belongs_to__application: appID,
|
|
|
|
status: 'success',
|
|
|
|
},
|
|
|
|
$expand: {
|
|
|
|
contains__image: {
|
2022-01-03 13:47:07 +00:00
|
|
|
$select: 'image',
|
|
|
|
$expand: { image: { $select: 'is_stored_at__image_location' } },
|
2020-04-23 12:46:19 +00:00
|
|
|
},
|
|
|
|
},
|
|
|
|
$orderby: 'id desc',
|
|
|
|
$top: 1,
|
|
|
|
},
|
|
|
|
})
|
2020-06-15 22:53:07 +00:00
|
|
|
.then(function (release) {
|
2020-04-23 12:46:19 +00:00
|
|
|
// grab all images from the latest release, return all image locations in the registry
|
|
|
|
if (release.length > 0) {
|
2022-01-03 13:47:07 +00:00
|
|
|
const images = release[0].contains__image as Array<{
|
|
|
|
image: [SDK.Image];
|
|
|
|
}>;
|
|
|
|
const { getRegistryAndName } =
|
2022-06-28 12:22:42 +00:00
|
|
|
require('@balena/compose/dist/multibuild') as typeof import('@balena/compose/dist/multibuild');
|
2020-06-30 20:17:24 +00:00
|
|
|
return Promise.all(
|
|
|
|
images.map(function (d) {
|
2021-04-27 13:58:54 +00:00
|
|
|
const imageName = d.image[0].is_stored_at__image_location || '';
|
|
|
|
const registry = getRegistryAndName(imageName);
|
|
|
|
logger.logDebug(
|
|
|
|
`Requesting access to previously pushed image repo (${registry.imageName})`,
|
|
|
|
);
|
|
|
|
return registry.imageName;
|
2020-06-30 20:17:24 +00:00
|
|
|
}),
|
|
|
|
);
|
2020-04-29 11:13:19 +00:00
|
|
|
} else {
|
|
|
|
return [];
|
2020-04-23 12:46:19 +00:00
|
|
|
}
|
|
|
|
})
|
2020-06-15 22:53:07 +00:00
|
|
|
.catch((e) => {
|
2020-04-23 12:46:19 +00:00
|
|
|
logger.logDebug(`Failed to access previously pushed image repo: ${e}`);
|
2020-04-29 11:13:19 +00:00
|
|
|
return [];
|
2020-04-23 12:46:19 +00:00
|
|
|
});
|
|
|
|
|
2020-06-15 22:53:07 +00:00
|
|
|
export const authorizePush = function (
|
2022-01-03 13:47:07 +00:00
|
|
|
sdk: SDK.BalenaSDK,
|
|
|
|
tokenAuthEndpoint: string,
|
|
|
|
registry: string,
|
|
|
|
images: string[],
|
|
|
|
previousRepos: string[],
|
|
|
|
): Promise<string> {
|
2020-04-23 12:46:19 +00:00
|
|
|
if (!Array.isArray(images)) {
|
|
|
|
images = [images];
|
|
|
|
}
|
|
|
|
|
|
|
|
images.push(...previousRepos);
|
|
|
|
return sdk.request
|
|
|
|
.send({
|
|
|
|
baseUrl: tokenAuthEndpoint,
|
|
|
|
url: '/auth/v1/token',
|
|
|
|
qs: {
|
|
|
|
service: registry,
|
2020-06-15 22:53:07 +00:00
|
|
|
scope: images.map((repo) => `repository:${repo}:pull,push`),
|
2020-04-23 12:46:19 +00:00
|
|
|
},
|
|
|
|
})
|
2020-07-31 15:25:48 +00:00
|
|
|
.then(({ body }) => body.token)
|
|
|
|
.catch(() => '');
|
2020-04-23 12:46:19 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
// utilities
|
|
|
|
|
2022-01-03 13:47:07 +00:00
|
|
|
const renderProgressBar = function (percentage: number, stepCount: number) {
|
|
|
|
const _ = require('lodash') as typeof import('lodash');
|
2020-04-23 12:46:19 +00:00
|
|
|
percentage = _.clamp(percentage, 0, 100);
|
|
|
|
const barCount = Math.floor((stepCount * percentage) / 100);
|
|
|
|
const spaceCount = stepCount - barCount;
|
|
|
|
const bar = `[${_.repeat('=', barCount)}>${_.repeat(' ', spaceCount)}]`;
|
2022-01-03 13:47:07 +00:00
|
|
|
return `${bar} ${_.padStart(`${percentage}`, 3)}%`;
|
2020-04-23 12:46:19 +00:00
|
|
|
};
|
|
|
|
|
2022-01-03 13:47:07 +00:00
|
|
|
export const pushProgressRenderer = function (
|
|
|
|
tty: ReturnType<typeof import('./tty')>,
|
|
|
|
prefix: string,
|
|
|
|
): ProgressCallback & { end: () => void } {
|
|
|
|
const fn: ProgressCallback & { end: () => void } = function (e) {
|
2020-04-23 12:46:19 +00:00
|
|
|
const { error, percentage } = e;
|
|
|
|
if (error != null) {
|
|
|
|
throw new Error(error);
|
|
|
|
}
|
|
|
|
const bar = renderProgressBar(percentage, 40);
|
|
|
|
return tty.replaceLine(`${prefix}${bar}\r`);
|
|
|
|
};
|
|
|
|
fn.end = () => {
|
|
|
|
tty.clearLine();
|
|
|
|
};
|
|
|
|
return fn;
|
|
|
|
};
|
|
|
|
|
2022-01-03 13:47:07 +00:00
|
|
|
export class BuildProgressUI implements Renderer {
|
|
|
|
public streams;
|
|
|
|
private _prefix;
|
|
|
|
private _prefixWidth;
|
|
|
|
private _tty;
|
|
|
|
private _services;
|
|
|
|
private _startTime: undefined | number;
|
|
|
|
private _ended;
|
|
|
|
private _serviceToDataMap: Dictionary<{
|
|
|
|
status?: string;
|
|
|
|
progress?: number;
|
|
|
|
error?: Error;
|
|
|
|
}> = {};
|
|
|
|
private _cancelled;
|
|
|
|
private _spinner;
|
|
|
|
private _runloop:
|
|
|
|
| undefined
|
|
|
|
| ReturnType<typeof import('./compose_ts').createRunLoop>;
|
|
|
|
|
|
|
|
// these are to handle window wrapping
|
|
|
|
private _maxLineWidth: undefined | number;
|
|
|
|
private _lineWidths: number[] = [];
|
|
|
|
|
|
|
|
constructor(
|
|
|
|
tty: ReturnType<typeof import('./tty')>,
|
|
|
|
descriptors: ImageDescriptor[],
|
|
|
|
) {
|
2020-04-23 12:46:19 +00:00
|
|
|
this._handleEvent = this._handleEvent.bind(this);
|
|
|
|
this.start = this.start.bind(this);
|
|
|
|
this.end = this.end.bind(this);
|
|
|
|
this._display = this._display.bind(this);
|
2022-01-03 13:47:07 +00:00
|
|
|
const _ = require('lodash') as typeof import('lodash');
|
|
|
|
const through = require('through2') as typeof import('through2');
|
2020-04-23 12:46:19 +00:00
|
|
|
|
|
|
|
const eventHandler = this._handleEvent;
|
|
|
|
const services = _.map(descriptors, 'serviceName');
|
|
|
|
|
|
|
|
const streams = _(services)
|
2020-06-15 22:53:07 +00:00
|
|
|
.map(function (service) {
|
|
|
|
const stream = through.obj(function (event, _enc, cb) {
|
2020-04-23 12:46:19 +00:00
|
|
|
eventHandler(service, event);
|
|
|
|
return cb();
|
|
|
|
});
|
|
|
|
stream.pipe(tty.stream, { end: false });
|
|
|
|
return [service, stream];
|
|
|
|
})
|
|
|
|
.fromPairs()
|
|
|
|
.value();
|
|
|
|
|
|
|
|
this._tty = tty;
|
|
|
|
this._services = services;
|
|
|
|
|
|
|
|
// Logger magically prefixes the log line with [Build] etc., but it doesn't
|
|
|
|
// work well with the spinner we're also showing. Manually build the prefix
|
|
|
|
// here and bypass the logger.
|
|
|
|
const prefix = getChalk().blue('[Build]') + ' ';
|
|
|
|
|
|
|
|
const offset = 10; // account for escape sequences inserted for colouring
|
|
|
|
this._prefixWidth =
|
2022-01-03 13:47:07 +00:00
|
|
|
offset + prefix.length + _.max(_.map(services, (s) => s.length))!;
|
2020-04-23 12:46:19 +00:00
|
|
|
this._prefix = prefix;
|
|
|
|
|
|
|
|
this._ended = false;
|
|
|
|
this._cancelled = false;
|
2022-01-03 13:47:07 +00:00
|
|
|
this._spinner = (
|
|
|
|
require('./compose_ts') as typeof import('./compose_ts')
|
|
|
|
).createSpinner();
|
2020-04-23 12:46:19 +00:00
|
|
|
|
|
|
|
this.streams = streams;
|
|
|
|
}
|
|
|
|
|
2022-01-03 13:47:07 +00:00
|
|
|
_handleEvent(
|
|
|
|
service: string,
|
|
|
|
event: { status?: string; progress?: number; error?: Error },
|
|
|
|
) {
|
2020-04-23 12:46:19 +00:00
|
|
|
this._serviceToDataMap[service] = event;
|
|
|
|
}
|
|
|
|
|
|
|
|
start() {
|
|
|
|
this._tty.hideCursor();
|
2020-06-15 22:53:07 +00:00
|
|
|
this._services.forEach((service) => {
|
2020-04-23 12:46:19 +00:00
|
|
|
this.streams[service].write({ status: 'Preparing...' });
|
|
|
|
});
|
2022-01-03 13:47:07 +00:00
|
|
|
this._runloop = (
|
|
|
|
require('./compose_ts') as typeof import('./compose_ts')
|
|
|
|
).createRunLoop(this._display);
|
2020-04-23 12:46:19 +00:00
|
|
|
this._startTime = Date.now();
|
|
|
|
}
|
|
|
|
|
2022-01-03 13:47:07 +00:00
|
|
|
end(summary?: Dictionary<string>) {
|
2020-04-23 12:46:19 +00:00
|
|
|
if (this._ended) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
this._ended = true;
|
|
|
|
this._runloop?.end();
|
2022-01-03 13:47:07 +00:00
|
|
|
this._runloop = undefined;
|
2020-04-23 12:46:19 +00:00
|
|
|
|
|
|
|
this._clear();
|
|
|
|
this._renderStatus(true);
|
|
|
|
this._renderSummary(summary ?? this._getServiceSummary());
|
|
|
|
this._tty.showCursor();
|
|
|
|
}
|
|
|
|
|
|
|
|
_display() {
|
|
|
|
this._clear();
|
|
|
|
this._renderStatus();
|
|
|
|
this._renderSummary(this._getServiceSummary());
|
|
|
|
this._tty.cursorUp(this._services.length + 1); // for status line
|
|
|
|
}
|
|
|
|
|
|
|
|
_clear() {
|
|
|
|
this._tty.deleteToEnd();
|
|
|
|
this._maxLineWidth = this._tty.currentWindowSize().width;
|
|
|
|
}
|
|
|
|
|
|
|
|
_getServiceSummary() {
|
2022-01-03 13:47:07 +00:00
|
|
|
const _ = require('lodash') as typeof import('lodash');
|
2020-04-23 12:46:19 +00:00
|
|
|
|
|
|
|
const services = this._services;
|
|
|
|
const serviceToDataMap = this._serviceToDataMap;
|
|
|
|
|
|
|
|
return _(services)
|
2020-06-15 22:53:07 +00:00
|
|
|
.map(function (service) {
|
2020-04-23 12:46:19 +00:00
|
|
|
const { status, progress, error } = serviceToDataMap[service] ?? {};
|
|
|
|
if (error) {
|
|
|
|
return `${error}`;
|
|
|
|
} else if (progress) {
|
|
|
|
const bar = renderProgressBar(progress, 20);
|
|
|
|
if (status) {
|
|
|
|
return `${bar} ${status}`;
|
|
|
|
}
|
|
|
|
return `${bar}`;
|
|
|
|
} else if (status) {
|
|
|
|
return `${status}`;
|
|
|
|
} else {
|
|
|
|
return 'Waiting...';
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.map((data, index) => [services[index], data])
|
|
|
|
.fromPairs()
|
|
|
|
.value();
|
|
|
|
}
|
|
|
|
|
2022-01-03 13:47:07 +00:00
|
|
|
_renderStatus(end = false) {
|
|
|
|
const moment = require('moment') as typeof import('moment');
|
|
|
|
(
|
|
|
|
require('moment-duration-format') as typeof import('moment-duration-format')
|
|
|
|
)(moment);
|
2020-04-23 12:46:19 +00:00
|
|
|
|
|
|
|
this._tty.clearLine();
|
|
|
|
this._tty.write(this._prefix);
|
|
|
|
if (end && this._cancelled) {
|
|
|
|
this._tty.writeLine('Build cancelled');
|
|
|
|
} else if (end) {
|
|
|
|
const serviceCount = this._services.length;
|
|
|
|
const serviceStr =
|
|
|
|
serviceCount === 1 ? '1 service' : `${serviceCount} services`;
|
|
|
|
const durationStr =
|
|
|
|
this._startTime == null
|
|
|
|
? 'unknown time'
|
|
|
|
: moment
|
|
|
|
.duration(
|
|
|
|
Math.floor((Date.now() - this._startTime) / 1000),
|
|
|
|
'seconds',
|
|
|
|
)
|
|
|
|
.format();
|
|
|
|
this._tty.writeLine(`Built ${serviceStr} in ${durationStr}`);
|
|
|
|
} else {
|
|
|
|
this._tty.writeLine(`Building services... ${this._spinner()}`);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-03 13:47:07 +00:00
|
|
|
_renderSummary(serviceToStrMap: Dictionary<string>) {
|
|
|
|
const _ = require('lodash') as typeof import('lodash');
|
2020-04-23 12:46:19 +00:00
|
|
|
const chalk = getChalk();
|
2022-01-03 13:47:07 +00:00
|
|
|
const truncate = require('cli-truncate') as typeof import('cli-truncate');
|
|
|
|
const strlen = require('string-width') as typeof import('string-width');
|
2020-04-23 12:46:19 +00:00
|
|
|
|
|
|
|
this._services.forEach((service, index) => {
|
|
|
|
let str = _.padEnd(this._prefix + chalk.bold(service), this._prefixWidth);
|
|
|
|
str += serviceToStrMap[service];
|
|
|
|
if (this._maxLineWidth != null) {
|
|
|
|
str = truncate(str, this._maxLineWidth);
|
|
|
|
}
|
|
|
|
this._lineWidths[index] = strlen(str);
|
|
|
|
|
|
|
|
this._tty.clearLine();
|
|
|
|
this._tty.writeLine(str);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-03 13:47:07 +00:00
|
|
|
export class BuildProgressInline implements Renderer {
|
|
|
|
public streams;
|
|
|
|
private _prefixWidth;
|
|
|
|
private _outStream;
|
|
|
|
private _services;
|
|
|
|
private _startTime: number | undefined;
|
|
|
|
private _ended;
|
|
|
|
|
|
|
|
constructor(
|
|
|
|
outStream: NodeJS.ReadWriteStream,
|
|
|
|
descriptors: Array<{ serviceName: string }>,
|
|
|
|
) {
|
2020-04-23 12:46:19 +00:00
|
|
|
this.start = this.start.bind(this);
|
|
|
|
this.end = this.end.bind(this);
|
|
|
|
this._renderEvent = this._renderEvent.bind(this);
|
2022-01-03 13:47:07 +00:00
|
|
|
const _ = require('lodash') as typeof import('lodash');
|
|
|
|
const through = require('through2') as typeof import('through2');
|
2020-04-23 12:46:19 +00:00
|
|
|
|
|
|
|
const services = _.map(descriptors, 'serviceName');
|
|
|
|
const eventHandler = this._renderEvent;
|
|
|
|
const streams = _(services)
|
2020-06-15 22:53:07 +00:00
|
|
|
.map(function (service) {
|
|
|
|
const stream = through.obj(function (event, _enc, cb) {
|
2020-04-23 12:46:19 +00:00
|
|
|
eventHandler(service, event);
|
|
|
|
return cb();
|
|
|
|
});
|
|
|
|
stream.pipe(outStream, { end: false });
|
|
|
|
return [service, stream];
|
|
|
|
})
|
|
|
|
.fromPairs()
|
|
|
|
.value();
|
|
|
|
|
|
|
|
const offset = 10; // account for escape sequences inserted for colouring
|
2022-01-03 13:47:07 +00:00
|
|
|
this._prefixWidth = offset + _.max(_.map(services, (s) => s.length))!;
|
2020-04-23 12:46:19 +00:00
|
|
|
this._outStream = outStream;
|
|
|
|
this._services = services;
|
|
|
|
this._ended = false;
|
|
|
|
|
|
|
|
this.streams = streams;
|
|
|
|
}
|
|
|
|
|
|
|
|
start() {
|
|
|
|
this._outStream.write('Building services...\n');
|
2020-06-15 22:53:07 +00:00
|
|
|
this._services.forEach((service) => {
|
2020-04-23 12:46:19 +00:00
|
|
|
this.streams[service].write({ status: 'Preparing...' });
|
|
|
|
});
|
|
|
|
this._startTime = Date.now();
|
|
|
|
}
|
|
|
|
|
2022-01-03 13:47:07 +00:00
|
|
|
end(summary?: Dictionary<string>) {
|
|
|
|
const moment = require('moment') as typeof import('moment');
|
|
|
|
(
|
|
|
|
require('moment-duration-format') as typeof import('moment-duration-format')
|
|
|
|
)(moment);
|
2020-04-23 12:46:19 +00:00
|
|
|
|
|
|
|
if (this._ended) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
this._ended = true;
|
|
|
|
|
|
|
|
if (summary != null) {
|
2020-06-15 22:53:07 +00:00
|
|
|
this._services.forEach((service) => {
|
2020-10-20 00:09:49 +00:00
|
|
|
this._renderEvent(service, { status: summary[service] });
|
2020-04-23 12:46:19 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
const serviceCount = this._services.length;
|
|
|
|
const serviceStr =
|
|
|
|
serviceCount === 1 ? '1 service' : `${serviceCount} services`;
|
|
|
|
const durationStr =
|
|
|
|
this._startTime == null
|
|
|
|
? 'unknown time'
|
|
|
|
: moment
|
|
|
|
.duration(
|
|
|
|
Math.floor((Date.now() - this._startTime) / 1000),
|
|
|
|
'seconds',
|
|
|
|
)
|
|
|
|
.format();
|
|
|
|
this._outStream.write(`Built ${serviceStr} in ${durationStr}\n`);
|
|
|
|
}
|
|
|
|
|
2022-01-03 13:47:07 +00:00
|
|
|
_renderEvent(service: string, event: { status?: string; error?: Error }) {
|
|
|
|
const _ = require('lodash') as typeof import('lodash');
|
2020-04-23 12:46:19 +00:00
|
|
|
|
2020-06-15 22:53:07 +00:00
|
|
|
const str = (function () {
|
2020-04-23 12:46:19 +00:00
|
|
|
const { status, error } = event;
|
|
|
|
if (error) {
|
|
|
|
return `${error}`;
|
|
|
|
} else if (status) {
|
|
|
|
return `${status}`;
|
|
|
|
} else {
|
|
|
|
return 'Waiting...';
|
|
|
|
}
|
|
|
|
})();
|
|
|
|
|
|
|
|
const prefix = _.padEnd(getChalk().bold(service), this._prefixWidth);
|
|
|
|
this._outStream.write(prefix);
|
|
|
|
this._outStream.write(str);
|
|
|
|
this._outStream.write('\n');
|
|
|
|
}
|
|
|
|
}
|