build-strap 3.0.0-dev.42 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +3 -34
  3. package/dist/src/ant.d.ts +19 -0
  4. package/dist/src/ant.js +18 -0
  5. package/dist/src/cert.d.ts +12 -0
  6. package/dist/src/cert.js +91 -0
  7. package/dist/src/clean.d.ts +4 -0
  8. package/dist/src/clean.js +11 -0
  9. package/dist/src/copy.d.ts +7 -0
  10. package/dist/src/copy.js +53 -0
  11. package/dist/src/cp.d.ts +17 -0
  12. package/dist/src/cp.js +88 -0
  13. package/dist/src/docker.container.d.ts +73 -0
  14. package/dist/src/docker.container.js +247 -0
  15. package/dist/src/docker.d.ts +68 -0
  16. package/dist/src/docker.js +188 -0
  17. package/dist/src/docker.network.d.ts +42 -0
  18. package/dist/src/docker.network.js +85 -0
  19. package/dist/src/docker.volume.d.ts +26 -0
  20. package/dist/src/docker.volume.js +62 -0
  21. package/dist/src/dockerCleanup.d.ts +38 -0
  22. package/dist/src/dockerCleanup.js +77 -0
  23. package/dist/src/dockerCompose.d.ts +154 -0
  24. package/dist/src/dockerCompose.js +439 -0
  25. package/dist/src/fs.d.ts +5 -0
  26. package/dist/src/fs.js +38 -0
  27. package/dist/src/git.d.ts +9 -0
  28. package/dist/src/git.js +24 -0
  29. package/dist/src/index.d.ts +20 -0
  30. package/dist/src/index.js +20 -0
  31. package/dist/src/maps.d.ts +33 -0
  32. package/dist/src/maps.js +41 -0
  33. package/dist/src/npm.d.ts +35 -0
  34. package/dist/src/npm.js +104 -0
  35. package/dist/src/pkg.d.ts +33 -0
  36. package/dist/src/pkg.js +33 -0
  37. package/dist/src/publish.d.ts +27 -0
  38. package/dist/src/publish.js +57 -0
  39. package/dist/src/run.d.ts +13 -0
  40. package/dist/src/run.js +44 -0
  41. package/dist/src/tgz.d.ts +13 -0
  42. package/dist/src/tgz.js +67 -0
  43. package/dist/src/version.d.ts +34 -0
  44. package/dist/src/version.js +101 -0
  45. package/dist/src/yarn.d.ts +26 -0
  46. package/dist/src/yarn.js +75 -0
  47. package/package.json +74 -20
  48. package/ant.js +0 -43
  49. package/ant.js.flow +0 -42
  50. package/artifactory.js +0 -617
  51. package/artifactory.js.flow +0 -616
  52. package/cert.conf +0 -20
  53. package/cert.js +0 -153
  54. package/cert.js.flow +0 -152
  55. package/clean.js +0 -20
  56. package/clean.js.flow +0 -19
  57. package/copy.js +0 -80
  58. package/copy.js.flow +0 -79
  59. package/cp.js +0 -173
  60. package/cp.js.flow +0 -172
  61. package/docker.container.js +0 -390
  62. package/docker.container.js.flow +0 -389
  63. package/docker.js +0 -368
  64. package/docker.js.flow +0 -367
  65. package/docker.network.js +0 -160
  66. package/docker.network.js.flow +0 -159
  67. package/docker.volume.js +0 -136
  68. package/docker.volume.js.flow +0 -136
  69. package/dockerCleanup.js +0 -152
  70. package/dockerCleanup.js.flow +0 -151
  71. package/dockerCompose.js +0 -766
  72. package/dockerCompose.js.flow +0 -765
  73. package/flow.js +0 -21
  74. package/flow.js.flow +0 -20
  75. package/fs.js +0 -95
  76. package/fs.js.flow +0 -96
  77. package/git.js +0 -35
  78. package/git.js.flow +0 -34
  79. package/hg.js +0 -35
  80. package/hg.js.flow +0 -34
  81. package/index.js +0 -27
  82. package/index.js.flow +0 -26
  83. package/inline-resources.js +0 -158
  84. package/inline-resources.js.flow +0 -157
  85. package/maps.js +0 -112
  86. package/maps.js.flow +0 -111
  87. package/npm.js +0 -145
  88. package/npm.js.flow +0 -144
  89. package/pkg.js +0 -81
  90. package/pkg.js.flow +0 -80
  91. package/publish.js +0 -145
  92. package/publish.js.flow +0 -144
  93. package/run.js +0 -90
  94. package/run.js.flow +0 -89
  95. package/src/ant.js +0 -42
  96. package/src/artifactory.js +0 -616
  97. package/src/cert.conf +0 -20
  98. package/src/cert.js +0 -152
  99. package/src/clean.js +0 -19
  100. package/src/copy.js +0 -79
  101. package/src/cp.js +0 -172
  102. package/src/docker.container.js +0 -389
  103. package/src/docker.js +0 -367
  104. package/src/docker.network.js +0 -159
  105. package/src/docker.volume.js +0 -136
  106. package/src/dockerCleanup.js +0 -151
  107. package/src/dockerCompose.js +0 -765
  108. package/src/flow.js +0 -20
  109. package/src/fs.js +0 -96
  110. package/src/git.js +0 -34
  111. package/src/hg.js +0 -34
  112. package/src/index.js +0 -26
  113. package/src/inline-resources.js +0 -157
  114. package/src/maps.js +0 -111
  115. package/src/npm.js +0 -144
  116. package/src/pkg.js +0 -80
  117. package/src/publish.js +0 -144
  118. package/src/run.js +0 -89
  119. package/src/test.js +0 -55
  120. package/src/tgz.js +0 -101
  121. package/src/version.js +0 -141
  122. package/src/yarn.js +0 -123
  123. package/test.js +0 -56
  124. package/test.js.flow +0 -55
  125. package/tgz.js +0 -102
  126. package/tgz.js.flow +0 -101
  127. package/version.js +0 -142
  128. package/version.js.flow +0 -141
  129. package/yarn.js +0 -124
  130. package/yarn.js.flow +0 -123
@@ -0,0 +1,104 @@
1
+ import fs from 'fs-extra';
2
+ import { platform } from 'os';
3
+ import path from 'path';
4
+ import { exec, spawn } from './cp.js';
5
+ import { getCfg, getPkgName } from './pkg.js';
6
+ import { buildLog } from './run.js';
7
+ import { getDevBranch, getVersion } from './version.js';
8
+ export function getNpmConfig() {
9
+ return getCfg().npm || {};
10
+ }
11
+ const envNpmCreds = (process.env.NPM_CREDS && JSON.parse(process.env.NPM_CREDS)) || null;
12
+ const npmExe = (npmPath) => npmPath || (platform() === 'win32' ? 'npm.cmd' : 'npm');
13
+ export async function npmExec(args, npmPath) {
14
+ return (await exec(`${npmExe(npmPath)} ${args.join(' ')}`)).stdout.toString();
15
+ }
16
+ export async function npmGetVersions(packageName, npmPath) {
17
+ try {
18
+ return JSON.parse(await npmExec(['show', packageName, 'versions'], npmPath));
19
+ }
20
+ catch (err) {
21
+ buildLog(`warning: failed to find existing package for ${packageName} in npm registry: ${err.message}`);
22
+ return [];
23
+ }
24
+ }
25
+ export async function npmPublish({ npmAuthToken, npmConfig, npmCreds, npmPath, publishPath = '.', skipExisting = false, tag, workDir: passedWorkDir, writeNpmrc = false, } = {}) {
26
+ const creds = npmCreds || envNpmCreds;
27
+ const authToken = npmAuthToken || process.env.NPM_TOKEN;
28
+ const name = getPkgName();
29
+ const { access, dryRun, publish, registry } = npmConfig || getNpmConfig();
30
+ if (!publish) {
31
+ buildLog('npm publish info missing from package.json, skipping npm publish');
32
+ return false;
33
+ }
34
+ const resolvedPath = path.resolve(publishPath);
35
+ const workDir = passedWorkDir ||
36
+ ((await fs.stat(resolvedPath)).isDirectory()
37
+ ? resolvedPath
38
+ : path.dirname(resolvedPath));
39
+ if (!(await fs.pathExists(path.join(workDir, 'package.json')))) {
40
+ buildLog(`warning: no package.json found in ${workDir}, skipping npm publish`);
41
+ return false;
42
+ }
43
+ if (writeNpmrc && (creds || registry || authToken)) {
44
+ // Write out .npmrc with credentials
45
+ const theRegistry = registry || 'https://registry.npmjs.org/';
46
+ const [, host] = /^(?:http(?:s)?:\/\/)?(.+)$/.exec(theRegistry) || [];
47
+ await fs.mkdirp(workDir);
48
+ await fs.writeFile(path.join(workDir, '.npmrc'), `registry=${theRegistry}
49
+ ${authToken ? `//${host}:_authToken=${authToken}` : ''}
50
+ ${creds
51
+ ? `_auth=${Buffer.from(`${creds.username}:${creds.password}`).toString('base64')}
52
+ always-auth=true
53
+ email=${creds.email}`
54
+ : ''}`);
55
+ }
56
+ const existing = await npmGetVersions(name, npmPath);
57
+ const { branch, isRelease, npm: npmVersion } = await getVersion();
58
+ if (existing.includes(npmVersion)) {
59
+ if (skipExisting) {
60
+ buildLog('npm package with this same version already exists. Skipping publish...');
61
+ return false;
62
+ }
63
+ throw new Error('Failed to publish npm package, this version already exists!');
64
+ }
65
+ await spawn(npmExe(npmPath), [
66
+ 'publish',
67
+ resolvedPath,
68
+ '--tag',
69
+ tag ||
70
+ (isRelease
71
+ ? 'latest'
72
+ : branch === (await getDevBranch())
73
+ ? 'next'
74
+ : 'branch'),
75
+ ...(access ? ['--access', access] : []),
76
+ ...(dryRun ? ['--dry-run'] : []),
77
+ '--color=always',
78
+ ], {
79
+ cwd: workDir,
80
+ env: {
81
+ ...process.env,
82
+ NPM_TOKEN: authToken,
83
+ },
84
+ stdio: 'inherit',
85
+ });
86
+ return true;
87
+ }
88
+ export async function npmPack({ destination, npmConfig, npmPath, workDir = '.', }) {
89
+ const { dryRun } = npmConfig || getNpmConfig();
90
+ if (destination) {
91
+ await fs.ensureDir(destination);
92
+ }
93
+ const { stdout } = await spawn(npmExe(npmPath), [
94
+ 'pack',
95
+ ...(dryRun ? ['--dry-run'] : []),
96
+ ...(destination ? ['--pack-destination', destination] : []),
97
+ '--color=always',
98
+ ], {
99
+ captureOutput: true,
100
+ cwd: workDir,
101
+ pipeOutput: true,
102
+ });
103
+ return path.resolve(destination || '.', stdout.trim());
104
+ }
@@ -0,0 +1,33 @@
1
+ import { CertConfig } from './cert.js';
2
+ import { DockerConfig } from './docker.js';
3
+ import { NpmConfig } from './npm.js';
4
+ export interface BuildStrapConfig {
5
+ cert?: CertConfig;
6
+ copyright?: string;
7
+ devBranch?: string;
8
+ docker?: DockerConfig;
9
+ npm?: NpmConfig;
10
+ releaseBranch?: string;
11
+ repoType?: 'git' | 'hg';
12
+ }
13
+ export interface PackageJson {
14
+ authors?: string[];
15
+ buildStrap: BuildStrapConfig;
16
+ dependencies?: Record<string, string>;
17
+ description?: string;
18
+ devDependencies?: Record<string, string>;
19
+ engines?: Record<string, string>;
20
+ license?: string;
21
+ main?: string;
22
+ name: string;
23
+ peerDependencies?: Record<string, string>;
24
+ private?: boolean;
25
+ repository?: string;
26
+ scripts?: Record<string, string>;
27
+ version: string;
28
+ }
29
+ export declare function getPkg(): PackageJson;
30
+ export declare function getCfg(): BuildStrapConfig;
31
+ export declare function setPkg(p: PackageJson): void;
32
+ export declare function getPkgName(includeScope?: boolean): string;
33
+ export declare function getPkgScope(): null | string;
@@ -0,0 +1,33 @@
1
+ // eslint-disable-next-line no-underscore-dangle
2
+ let _pkg = null;
3
+ export function getPkg() {
4
+ if (_pkg == null) {
5
+ throw new Error('Must call setPkg() with package.json content before building.');
6
+ }
7
+ return _pkg;
8
+ }
9
+ export function getCfg() {
10
+ return getPkg().buildStrap || {};
11
+ }
12
+ export function setPkg(p) {
13
+ _pkg = p;
14
+ }
15
+ const pkgNameRegex = /^(?:(@[^/]+)\/)?(.+)$/i;
16
+ export function getPkgName(includeScope = false) {
17
+ const pkg = getPkg();
18
+ if (!(pkg.name && pkg.name.length)) {
19
+ throw new Error('Package name not found in package.json, but this is a required property!');
20
+ }
21
+ if (includeScope) {
22
+ return pkg.name;
23
+ }
24
+ const [, , shortName] = pkg.name.match(pkgNameRegex) || [];
25
+ if (!shortName) {
26
+ throw new Error('Package name in package.json has invalid format.');
27
+ }
28
+ return shortName;
29
+ }
30
+ export function getPkgScope() {
31
+ const pkgName = getPkgName(true);
32
+ return pkgName.match(pkgNameRegex)?.[1] || null;
33
+ }
@@ -0,0 +1,27 @@
1
+ import { NpmConfig, NpmCreds } from './npm.js';
2
+ import { ArtifactInfo } from './tgz.js';
3
+ import { type Version } from './version.js';
4
+ export interface CreateArtifactOptions {
5
+ distDir: string;
6
+ fileName?: string;
7
+ outDir: string;
8
+ }
9
+ export interface Artifact {
10
+ fileName: string;
11
+ filePath: string;
12
+ info: ArtifactInfo;
13
+ name: string;
14
+ version: Version;
15
+ }
16
+ export declare function createArtifact({ distDir, fileName, outDir, }: CreateArtifactOptions): Promise<Artifact>;
17
+ export interface PublishConfiguration extends CreateArtifactOptions {
18
+ doPublish: boolean;
19
+ npmAuthToken?: string;
20
+ npmConfig?: NpmConfig;
21
+ npmCreds?: NpmCreds;
22
+ npmPath?: string;
23
+ npmSkipExisting?: boolean;
24
+ npmTag?: string;
25
+ prePublishFn?: () => any;
26
+ }
27
+ export declare function publish({ distDir, doPublish, fileName, npmAuthToken, npmConfig, npmCreds, npmPath, npmSkipExisting, npmTag, outDir, prePublishFn, }: PublishConfiguration): Promise<void>;
@@ -0,0 +1,57 @@
1
+ import fs from 'fs-extra';
2
+ import path from 'path';
3
+ import { npmPublish } from './npm.js';
4
+ import { getPkgName } from './pkg.js';
5
+ import { buildLog, run } from './run.js';
6
+ import { tgzDir } from './tgz.js';
7
+ import { getVersion } from './version.js';
8
+ // create tgz from distDir in outDir
9
+ export async function createArtifact({ distDir, fileName, outDir, }) {
10
+ const version = await getVersion();
11
+ const name = getPkgName();
12
+ buildLog(`gzipping ${name} v${version.info}...`);
13
+ const tgzFileName = fileName || `${name}-${version.info}.tgz`;
14
+ const tgzFilePath = path.join(outDir, tgzFileName);
15
+ const info = await tgzDir(distDir, tgzFilePath, {
16
+ prefix: 'package',
17
+ });
18
+ buildLog(`md5: ${info.md5}`);
19
+ buildLog(`sha1: ${info.sha1}`);
20
+ buildLog(`sha512: ${info.sha512}`);
21
+ buildLog(`size: ${info.size} bytes`);
22
+ return {
23
+ fileName: tgzFileName,
24
+ filePath: tgzFilePath,
25
+ info,
26
+ name,
27
+ version,
28
+ };
29
+ }
30
+ // tgz the distDir, and copy it to the outDir
31
+ export async function publish({ distDir, doPublish, fileName, npmAuthToken, npmConfig, npmCreds, npmPath, npmSkipExisting = false, npmTag, outDir, prePublishFn, }) {
32
+ if (typeof prePublishFn === 'function') {
33
+ await run(async () => {
34
+ await prePublishFn();
35
+ });
36
+ }
37
+ const { filePath: tgzFilePath } = await createArtifact({
38
+ distDir,
39
+ fileName,
40
+ outDir,
41
+ });
42
+ if (!doPublish) {
43
+ buildLog('Skipping publish for dev build. Use `--publish` arg to publish for real.');
44
+ return;
45
+ }
46
+ // Publish to all repos configured in package.json
47
+ await fs.copyFile(path.join(distDir, 'package.json'), path.join(outDir, 'package.json'));
48
+ await npmPublish({
49
+ npmAuthToken,
50
+ npmConfig,
51
+ npmCreds,
52
+ npmPath,
53
+ publishPath: tgzFilePath,
54
+ skipExisting: npmSkipExisting,
55
+ tag: npmTag,
56
+ });
57
+ }
@@ -0,0 +1,13 @@
1
+ export declare function format(time?: Date): string;
2
+ export declare function buildLog(msg: string, time?: Date): void;
3
+ export declare type RunnableModule<Args extends string[], Result> = ((...args: Args) => Promise<Result>) | {
4
+ default: (...args: Args) => Promise<Result>;
5
+ };
6
+ export declare function run<Args extends string[], Result>(fn: RunnableModule<Args, Result>, ...options: Args): Promise<Result>;
7
+ export interface RunCliOptions<Args extends string[], Result> {
8
+ argv?: string[];
9
+ defaultAction?: string | RunnableModule<Args, Result>;
10
+ passthroughArgv?: Args | boolean;
11
+ resolveFn?: (path: string) => Promise<RunnableModule<Args, Result>> | RunnableModule<Args, Result>;
12
+ }
13
+ export declare function runCli<Args extends string[], Result>({ resolveFn, defaultAction, argv, passthroughArgv, }?: RunCliOptions<Args, Result>): Promise<Result>;
@@ -0,0 +1,44 @@
1
+ export function format(time = new Date()) {
2
+ return time.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, '$1');
3
+ }
4
+ const silenceLogs = process.argv.includes('--silence-buildLog');
5
+ export function buildLog(msg, time) {
6
+ if (silenceLogs) {
7
+ return;
8
+ }
9
+ console.info(`[${format(time || new Date())}] ${msg}`);
10
+ }
11
+ export async function run(fn, ...options) {
12
+ if (fn == null) {
13
+ throw new Error(`Invalid argument passed to run(${fn})`);
14
+ }
15
+ const task = typeof fn === 'function' ? fn : fn.default;
16
+ if (typeof task !== 'function') {
17
+ throw new Error('First argument to run must be a function or module with default function.');
18
+ }
19
+ const start = new Date();
20
+ buildLog(`Starting '${task.name}'...`, start);
21
+ const result = await task(...options);
22
+ const end = new Date();
23
+ const time = end.getTime() - start.getTime();
24
+ buildLog(`Finished '${task.name}' after ${time} ms`, end);
25
+ return result;
26
+ }
27
+ export async function runCli({ resolveFn = async (path) => import(`./${path}.js`), defaultAction = 'build', argv = process.argv, passthroughArgv = false, } = {}) {
28
+ const module = argv.length > 2
29
+ ? await resolveFn(argv[2])
30
+ : typeof defaultAction === 'string'
31
+ ? await resolveFn(defaultAction)
32
+ : defaultAction;
33
+ const args = Array.isArray(passthroughArgv)
34
+ ? passthroughArgv.includes(argv[2] || defaultAction)
35
+ ? argv.slice(3)
36
+ : []
37
+ : passthroughArgv
38
+ ? argv.slice(3)
39
+ : [];
40
+ return run(module, ...args).catch((err) => {
41
+ console.error((err && err.stack) || err);
42
+ process.exit(1);
43
+ });
44
+ }
@@ -0,0 +1,13 @@
1
+ /// <reference types="node" />
2
+ import { Readable } from 'stream';
3
+ import tar from 'tar';
4
+ export declare type ArtifactInfo = {
5
+ contentType?: string;
6
+ md5: string;
7
+ sha1: string;
8
+ sha512: string;
9
+ size: number;
10
+ };
11
+ export declare const generateFileHash: (filePath: string, type: 'md5' | 'sha1' | 'sha512') => Promise<string>;
12
+ export declare function getArtifactInfo(artifact: string | Readable): Promise<ArtifactInfo>;
13
+ export declare function tgzDir(srcDir: string, outPath: string, options?: tar.CreateOptions): Promise<ArtifactInfo>;
@@ -0,0 +1,67 @@
1
+ import crypto from 'crypto';
2
+ import fs from 'fs-extra';
3
+ import path from 'path';
4
+ import StreamCounter from 'stream-counter';
5
+ import tar from 'tar';
6
+ import { buildLog } from './run.js';
7
+ const generateHash = async (stream, type) => new Promise((resolve, reject) => {
8
+ stream
9
+ .pipe(crypto.createHash(type).setEncoding('hex'))
10
+ .on('finish', function onFinish() {
11
+ resolve(this.read());
12
+ })
13
+ .on('end', function onEnd() {
14
+ resolve(this.read());
15
+ })
16
+ .on('error', (err) => reject(err));
17
+ });
18
+ export const generateFileHash = async (filePath, type) => generateHash(fs.createReadStream(filePath), type);
19
+ const countBytes = async (stream) => new Promise((resolve, reject) => {
20
+ const counter = new StreamCounter();
21
+ stream
22
+ .pipe(counter)
23
+ .on('finish', () => resolve(counter.bytes))
24
+ .on('end', () => resolve(counter.bytes))
25
+ .on('error', (err) => reject(err));
26
+ });
27
+ const writeStreamToFile = async (stream, filePath) => new Promise((resolve, reject) => {
28
+ stream
29
+ .pipe(fs.createWriteStream(filePath))
30
+ .on('finish', () => {
31
+ buildLog(`Successfully wrote file: ${filePath}`);
32
+ resolve();
33
+ })
34
+ .on('error', (err) => reject(err));
35
+ });
36
+ // Take the given file (path or stream) and compute metadata for it.
37
+ // md5 + sha hashes, and size in bytes
38
+ export async function getArtifactInfo(artifact) {
39
+ // make it into a stream
40
+ const stream = typeof artifact === 'string' ? fs.createReadStream(artifact) : artifact;
41
+ const [md5, sha1, sha512, size] = await Promise.all([
42
+ generateHash(stream, 'md5'),
43
+ generateHash(stream, 'sha1'),
44
+ generateHash(stream, 'sha512'),
45
+ countBytes(stream),
46
+ ]);
47
+ return { md5, sha1, sha512, size };
48
+ }
49
+ // Creates a gzipped tarball of a directory, returns sha1 + md5 hash and size of resulting file
50
+ export async function tgzDir(srcDir, outPath, options) {
51
+ await fs.ensureDir(path.dirname(outPath));
52
+ const tgzStream = tar.c({
53
+ cwd: srcDir,
54
+ gzip: true,
55
+ portable: true,
56
+ ...options,
57
+ }, ['.']);
58
+ // write the file to disk (outPath)
59
+ const [info] = await Promise.all([
60
+ getArtifactInfo(tgzStream),
61
+ writeStreamToFile(tgzStream, `${outPath}`),
62
+ ]);
63
+ return {
64
+ ...info,
65
+ contentType: 'application/gzip',
66
+ };
67
+ }
@@ -0,0 +1,34 @@
1
+ export declare function getBuild(): string;
2
+ export declare function getReleaseBranch(): string;
3
+ declare enum RepoType {
4
+ git = "git",
5
+ hg = "hg",
6
+ unknown = "unknown"
7
+ }
8
+ export declare function getRepoType(): Promise<RepoType>;
9
+ declare type RepoInfo = {
10
+ branch: string;
11
+ revision: string;
12
+ };
13
+ export declare function getRepoInfo(): Promise<RepoInfo>;
14
+ export declare function getDevBranch(): Promise<string>;
15
+ export declare function getIsRelease(passedBranch?: null | string, releaseOverride?: null | boolean): Promise<boolean>;
16
+ export declare function useVersionCache(useCache?: boolean): void;
17
+ export interface Version {
18
+ branch: string;
19
+ build: string;
20
+ info: string;
21
+ isRelease: boolean;
22
+ major: string;
23
+ minor: string;
24
+ name: string;
25
+ npm: string;
26
+ patch: string;
27
+ revision: string;
28
+ short: string;
29
+ }
30
+ export declare function getVersion(logIt?: boolean, release?: null | boolean): Promise<Version>;
31
+ export declare function getBanner(): Promise<string>;
32
+ export declare function getVersionCode(): Promise<string>;
33
+ export declare function getUniqueBuildTag(): Promise<string>;
34
+ export {};
@@ -0,0 +1,101 @@
1
+ import fs from 'fs';
2
+ import { gitInfo } from './git.js';
3
+ import { getCfg, getPkg } from './pkg.js';
4
+ import { buildLog } from './run.js';
5
+ export function getBuild() {
6
+ const arg = process.argv.find((el) => /^--buildNum=\d+$/.test(el));
7
+ return (arg && arg.substring(11)) || process.env.BUILD_NUMBER || '0';
8
+ }
9
+ export function getReleaseBranch() {
10
+ const { releaseBranch } = getCfg();
11
+ return releaseBranch || 'master';
12
+ }
13
+ var RepoType;
14
+ (function (RepoType) {
15
+ RepoType["git"] = "git";
16
+ RepoType["hg"] = "hg";
17
+ RepoType["unknown"] = "unknown";
18
+ })(RepoType || (RepoType = {}));
19
+ export async function getRepoType() {
20
+ const { repoType } = getCfg();
21
+ return (repoType ||
22
+ (fs.existsSync('./.git')
23
+ ? RepoType.git
24
+ : fs.existsSync('./.hg')
25
+ ? RepoType.hg
26
+ : RepoType.unknown));
27
+ }
28
+ export async function getRepoInfo() {
29
+ const repoType = await getRepoType();
30
+ if (repoType !== RepoType.git) {
31
+ throw new Error(`Unsupported repo type: ${repoType}`);
32
+ }
33
+ const { branch, revision } = await gitInfo();
34
+ if (!branch || !revision) {
35
+ throw new Error('Failed to parse branch and revision from source repo.');
36
+ }
37
+ return { branch, revision };
38
+ }
39
+ export async function getDevBranch() {
40
+ const { devBranch } = getCfg();
41
+ return devBranch || (await getRepoType()) === 'hg' ? 'default' : 'dev';
42
+ }
43
+ export async function getIsRelease(passedBranch = null, releaseOverride = null) {
44
+ const branch = passedBranch || (await getRepoInfo()).branch;
45
+ return releaseOverride != null
46
+ ? releaseOverride
47
+ : process.argv.includes('--force-release-version')
48
+ ? true
49
+ : branch === getReleaseBranch();
50
+ }
51
+ let cacheVersion = true;
52
+ export function useVersionCache(useCache = true) {
53
+ cacheVersion = useCache;
54
+ }
55
+ let version = null;
56
+ export async function getVersion(logIt = true, release = null) {
57
+ if (!cacheVersion || version == null) {
58
+ const { name, version: pkgVers } = getPkg();
59
+ const { branch, revision } = await getRepoInfo();
60
+ const [, major, minor, patch] = pkgVers.match(/^(\d+)\.(\d+)\.(\d+)$/) || [];
61
+ if (!major || !minor || !patch) {
62
+ throw new Error('Invalid version format in package.json');
63
+ }
64
+ const build = getBuild();
65
+ const isRelease = await getIsRelease(branch, release);
66
+ const short = `${major}.${minor}.${patch}`;
67
+ const npm = `${short}${isRelease ? '' : `-${branch}.${build}`}`;
68
+ const info = `${short}${isRelease ? `+${build}.` : `-${branch}.${build}+`}${revision}`;
69
+ version = {
70
+ branch,
71
+ build,
72
+ info,
73
+ isRelease,
74
+ major,
75
+ minor,
76
+ name,
77
+ npm,
78
+ patch,
79
+ revision,
80
+ short,
81
+ };
82
+ if (logIt) {
83
+ buildLog(`Building version ${info}`);
84
+ }
85
+ }
86
+ return version;
87
+ }
88
+ export async function getBanner() {
89
+ const { copyright = '' } = getCfg();
90
+ const { info, name } = await getVersion();
91
+ const today = new Date();
92
+ return `${name} v${info} | (c) ${today.getFullYear()} ${copyright} | built on ${today.toISOString()}`;
93
+ }
94
+ export async function getVersionCode() {
95
+ return `// This file is auto-generated
96
+ export const version = ${JSON.stringify(await getVersion(), null, 2)}`;
97
+ }
98
+ export async function getUniqueBuildTag() {
99
+ const { branch, build, revision } = await getVersion();
100
+ return `${branch}-${revision}-${build}`;
101
+ }
@@ -0,0 +1,26 @@
1
+ import { SpawnOptions, SpawnResult } from './cp.js';
2
+ export interface YarnOptions {
3
+ args?: string[];
4
+ spawnOptions?: SpawnOptions;
5
+ }
6
+ export declare function yarn({ args, spawnOptions, }?: YarnOptions): Promise<SpawnResult>;
7
+ export declare const yarnFiles: string[];
8
+ export interface YarnInstallOptions {
9
+ force?: boolean;
10
+ hashFilePath?: string;
11
+ nodeModulesPath?: string;
12
+ }
13
+ export declare function yarnInstall({ force, hashFilePath, nodeModulesPath, }?: YarnInstallOptions): Promise<void>;
14
+ export interface YarnUpgradeOptions {
15
+ /**
16
+ * `false` by default
17
+ * we assume any package with an explicit version shouldn't be touched
18
+ */
19
+ all?: boolean;
20
+ /**
21
+ * Use `yarn outdated` to find packages that should be upgraded
22
+ * May include breaking changes (major version changes)
23
+ */
24
+ outdated?: boolean;
25
+ }
26
+ export declare function yarnUpgrade({ all, outdated, }?: YarnUpgradeOptions): Promise<void>;
@@ -0,0 +1,75 @@
1
+ import fs from 'fs-extra';
2
+ import path from 'path';
3
+ import { spawn } from './cp.js';
4
+ import { readDir } from './fs.js';
5
+ import { getPkg } from './pkg.js';
6
+ import { buildLog } from './run.js';
7
+ import { generateFileHash } from './tgz.js';
8
+ export async function yarn({ args = [], spawnOptions, } = {}) {
9
+ const localYarn = path.join(path.dirname(process.execPath), '/node_modules/yarn/bin/yarn.js');
10
+ const spawnOpts = {
11
+ env: process.env,
12
+ shell: true,
13
+ stdio: 'inherit',
14
+ ...spawnOptions,
15
+ };
16
+ return (await fs.pathExists(localYarn))
17
+ ? // prefer to use local copy of yarn
18
+ spawn(process.execPath, [localYarn, ...args], spawnOpts)
19
+ : // fall back to globally installed yarn
20
+ spawn('yarn', args, spawnOpts);
21
+ }
22
+ export const yarnFiles = ['./package.json', './yarn.lock'];
23
+ // Smart yarn invocation, only if package changed
24
+ export async function yarnInstall({ force = false, hashFilePath = './download/buildHash_yarn.md5', nodeModulesPath = './node_modules', } = {}) {
25
+ await fs.ensureDir(nodeModulesPath);
26
+ const currentHash = (await Promise.all(yarnFiles.map(async (f) => generateFileHash(f, 'md5')))).join('|');
27
+ await fs.ensureFile(hashFilePath);
28
+ const prevHash = await fs.readFile(hashFilePath, 'utf8');
29
+ if (currentHash !== prevHash) {
30
+ buildLog('node package definition changed since last build, invoking yarn.');
31
+ }
32
+ else if (!(await readDir(`${nodeModulesPath}/**/*.js`)).length) {
33
+ buildLog('node packages missing, invoking yarn.');
34
+ }
35
+ else if (force) {
36
+ buildLog('node packages unchanged, but yarn forced on command line...');
37
+ }
38
+ else {
39
+ buildLog('node packages unchanged since last build, skipping yarn.');
40
+ return;
41
+ }
42
+ await yarn();
43
+ await fs.writeFile(hashFilePath, currentHash);
44
+ }
45
+ export async function yarnUpgrade({ all = false, outdated = false, } = {}) {
46
+ if (outdated) {
47
+ const { code, stdout } = await yarn({
48
+ args: ['outdated'],
49
+ spawnOptions: {
50
+ captureOutput: true,
51
+ rejectOnErrorCode: false,
52
+ stdio: 'pipe',
53
+ },
54
+ });
55
+ if (code === 0) {
56
+ buildLog('No outdated packages.');
57
+ }
58
+ else {
59
+ const { dependencies = {}, devDependencies = {} } = getPkg();
60
+ const packages = stdout
61
+ .split('\n')
62
+ .slice(5, -1)
63
+ .map((l) => l.split(/\s+/)[0])
64
+ .filter((p) => all || !/^\d/.test(dependencies[p] || devDependencies[p] || ''));
65
+ if (packages.length) {
66
+ await yarn({ args: ['add', ...packages] });
67
+ buildLog(`Upgraded: ${packages.join(', ')}`);
68
+ }
69
+ else {
70
+ buildLog('No eligible outdated packages');
71
+ }
72
+ }
73
+ }
74
+ await yarn({ args: ['upgrade'] });
75
+ }