aboutsummaryrefslogtreecommitdiffstats
path: root/packages/monorepo-scripts/src/utils/utils.ts
blob: 26ac801bdd4985ffe9e810ffaacd187d76788431 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import batchPackages = require('@lerna/batch-packages');
import * as fs from 'fs';
import * as _ from 'lodash';
import { exec as execAsync } from 'promisify-child-process';
import semver = require('semver');

import { constants } from '../constants';
import { GitTagsByPackageName, Package, PackageJSON, UpdatedPackage } from '../types';

import { changelogUtils } from './changelog_utils';

export const utils = {
    log(...args: any[]): void {
        console.log(...args); // tslint:disable-line:no-console
    },
    getTopologicallySortedPackages(rootDir: string): Package[] {
        const packages = utils.getPackages(rootDir);
        const batchedPackages: PackageJSON[] = _.flatten(batchPackages(_.map(packages, pkg => pkg.packageJson), false));
        const topsortedPackages: Package[] = _.map(
            batchedPackages,
            (pkg: PackageJSON) => _.find(packages, pkg1 => pkg1.packageJson.name === pkg.name) as Package,
        );
        return topsortedPackages;
    },
    getPackages(rootDir: string): Package[] {
        const rootPackageJsonString = fs.readFileSync(`${rootDir}/package.json`, 'utf8');
        const rootPackageJson = JSON.parse(rootPackageJsonString);
        if (_.isUndefined(rootPackageJson.workspaces)) {
            throw new Error(`Did not find 'workspaces' key in root package.json`);
        }
        const packages = [];
        for (const workspace of rootPackageJson.workspaces) {
            // HACK: Remove allowed wildcards from workspace entries.
            // This might be entirely comprehensive.
            const workspacePath = workspace.replace('*', '').replace('**/*', '');
            const subpackageNames = fs.readdirSync(`${rootDir}/${workspacePath}`);
            for (const subpackageName of subpackageNames) {
                if (_.startsWith(subpackageName, '.')) {
                    continue;
                }
                const pathToPackageJson = `${rootDir}/${workspacePath}${subpackageName}`;
                try {
                    const packageJsonString = fs.readFileSync(`${pathToPackageJson}/package.json`, 'utf8');
                    const packageJson = JSON.parse(packageJsonString);
                    const pkg = {
                        location: pathToPackageJson,
                        packageJson,
                    };
                    packages.push(pkg);
                } catch (err) {
                    utils.log(`Couldn't find a 'package.json' for ${subpackageName}. Skipping.`);
                }
            }
        }
        return packages;
    },
    async getUpdatedPackagesAsync(shouldIncludePrivate: boolean): Promise<Package[]> {
        const updatedPublicPackages = await utils.getLernaUpdatedPackagesAsync(shouldIncludePrivate);
        const updatedPackageNames = _.map(updatedPublicPackages, pkg => pkg.name);

        const allPackages = utils.getPackages(constants.monorepoRootPath);
        const updatedPackages = _.filter(allPackages, pkg => {
            return _.includes(updatedPackageNames, pkg.packageJson.name);
        });
        return updatedPackages;
    },
    async getLernaUpdatedPackagesAsync(shouldIncludePrivate: boolean): Promise<UpdatedPackage[]> {
        const result = await execAsync(`${constants.lernaExecutable} updated --json`, {
            cwd: constants.monorepoRootPath,
        });
        const updatedPackages = JSON.parse(result.stdout);
        if (!shouldIncludePrivate) {
            const updatedPublicPackages = _.filter(updatedPackages, updatedPackage => !updatedPackage.private);
            return updatedPublicPackages;
        }
        return updatedPackages;
    },
    async getNextPackageVersionAsync(
        currentVersion: string,
        packageName: string,
        packageLocation: string,
    ): Promise<string> {
        let nextVersionIfValid;
        const changelog = changelogUtils.getChangelogOrCreateIfMissing(packageName, packageLocation);
        if (_.isEmpty(changelog)) {
            nextVersionIfValid = semver.inc(currentVersion, 'patch');
        }
        const lastEntry = changelog[0];
        if (semver.gt(currentVersion, lastEntry.version)) {
            throw new Error(`Package.json version cannot be greater then last CHANGELOG entry. Check: ${packageName}`);
        }
        nextVersionIfValid = semver.eq(lastEntry.version, currentVersion)
            ? semver.inc(currentVersion, 'patch')
            : lastEntry.version;
        if (_.isNull(nextVersionIfValid)) {
            throw new Error(`Encountered invalid semver: ${currentVersion} associated with ${packageName}`);
        }
        return nextVersionIfValid;
    },
    async getRemoteGitTagsAsync(): Promise<string[]> {
        const result = await execAsync(`git ls-remote --tags`, {
            cwd: constants.monorepoRootPath,
        });
        const tagsString = result.stdout;
        const tagOutputs: string[] = tagsString.split('\n');
        const tags = _.compact(
            _.map(tagOutputs, tagOutput => {
                const tag = tagOutput.split('refs/tags/')[1];
                // Tags with `^{}` are duplicateous so we ignore them
                // Source: https://stackoverflow.com/questions/15472107/when-listing-git-ls-remote-why-theres-after-the-tag-name
                if (_.endsWith(tag, '^{}')) {
                    return undefined;
                }
                return tag;
            }),
        );
        return tags;
    },
    async getLocalGitTagsAsync(): Promise<string[]> {
        const result = await execAsync(`git tag`, {
            cwd: constants.monorepoRootPath,
        });
        const tagsString = result.stdout;
        const tags = tagsString.split('\n');
        return tags;
    },
    async getGitTagsByPackageNameAsync(packageNames: string[], gitTags: string[]): Promise<GitTagsByPackageName> {
        const tagVersionByPackageName: GitTagsByPackageName = {};
        _.each(gitTags, tag => {
            const packageNameIfExists = _.find(packageNames, name => {
                return _.includes(tag, `${name}@`);
            });
            if (_.isUndefined(packageNameIfExists)) {
                return; // ignore tags not related to a package we care about.
            }
            const splitTag = tag.split(`${packageNameIfExists}@`);
            if (splitTag.length !== 2) {
                throw new Error(`Unexpected tag name found: ${tag}`);
            }
            const version = splitTag[1];
            (tagVersionByPackageName[packageNameIfExists] || (tagVersionByPackageName[packageNameIfExists] = [])).push(
                version,
            );
        });
        return tagVersionByPackageName;
    },
    async removeLocalTagAsync(tagName: string): Promise<void> {
        try {
            await execAsync(`git tag -d ${tagName}`, {
                cwd: constants.monorepoRootPath,
            });
        } catch (err) {
            throw new Error(`Failed to delete local git tag. Got err: ${err}`);
        }
        utils.log(`Removed local tag: ${tagName}`);
    },
    async removeRemoteTagAsync(tagName: string): Promise<void> {
        try {
            await execAsync(`git push origin ${tagName}`, {
                cwd: constants.monorepoRootPath,
            });
        } catch (err) {
            throw new Error(`Failed to delete remote git tag. Got err: ${err}`);
        }
        utils.log(`Removed remote tag: ${tagName}`);
    },
};
012-12-24 01:47:41 +0800'>2012-12-242-3/+3 * - Update to 2.059sunpoet2012-12-242-3/+3 * Shortly after the initial release, a new tarball was uploaded whichjohans2012-12-222-4/+3 * - Trim Makefile header per new bylawsdanfe2012-12-213-27/+22 * - Trim Makefile header per new bylawsdanfe2012-12-211-11/+13 * - Turn on the RSYNCABLE option by default since it is required for agabor2012-12-211-1/+2 * - Update The Glorious Glasgow Haskell Compiler to version 7.4.2pgj2012-12-2018-57/+27 * Convert to OptionsNG and trim Makefile headers.naddy2012-12-193-12/+16 * For a number of ports in archives category, trim the header and drop leadingdanfe2012-12-1832-198/+81 * Cleanup archives/p5-POE-Filter-* ports a bit:danfe2012-12-185-41/+17 * Cleanup Makefile and port description.danfe2012-12-182-24/+16 * - Switch to modern two-line Makefile headerdanfe2012-12-182-28/+25 * - Use two-line Makefile headerdanfe2012-12-181-10/+8 * Cleanup supporting perl version 5.8 and 5.10,az2012-12-174-31/+3 * - Drop GLX_X86 from OPTIONS_DEFINE (forgotten in r309016)danfe2012-12-161-1/+0 * - Set default perl version for ports which currently usingaz2012-12-161-1/+1 * - Pass maintainership to submitterbeech2012-12-161-2/+3 * Bump PORTREVISION for Thunar related portsolivierd2012-12-152-10/+8 * Update horde4 packages and applications to horde5mm2012-12-122-6/+11 * - Update devel/tbb to 4.1.1 and bump dependent port's PORTREVISIONsmartymac2012-12-121-1/+1 * Update PCRE to 8.32mm2012-12-111-2/+2 * Decommissioning java 1.5 (EOLed since October 2009):bapt2012-12-103-19/+6 * - Update rpm 4.10.2johans2012-12-103-8/+6 * - Reset MAINTAINER on ports with addresses that have unrecoverable bounces.zi2012-12-071-1/+1 * - Sanitize port COMMENTdanfe2012-12-053-4/+2 * - Update to 0.9delphij2012-12-052-9/+6 * - Update to 1.3.delphij2012-12-052-9/+5 * - Reset MAINTAINER due to unrecoverable bouncezi2012-12-052-2/+2 * - Update to 2.058sunpoet2012-12-042-8/+4 * - Update to 2.058sunpoet2012-12-042-11/+5 * - Update to 2.058sunpoet2012-12-042-11/+5 * - Update to 2.058sunpoet2012-12-042-11/+5 * - Update to 2.059sunpoet2012-12-042-8/+4 * - Update to 2.059sunpoet2012-12-042-8/+4 * - Update to 2.059sunpoet2012-12-042-8/+4 * Do not override DISTNAME, default value is perfectly fine and makes more sense.danfe2012-12-032-3/+2 * Convert to OptionsNG.rakuco2012-11-261-4/+7 * Convert to new options frameworkbapt2012-11-231-10/+8 * Chase libexplain updateehaupt2012-11-211-5/+2 * horde4 update:mm2012-11-192-3/+3 * update zpaq to 6.16bf2012-11-092-4/+4 * - Update to 0.6ehaupt2012-11-062-8/+4 * - Specify LICENSEfjoe2012-11-041-0/+2 * Update to 0.3.fjoe2012-11-032-4/+3 * update zpaq to 6.15bf2012-11-032-4/+4 * update to zpaq 6.14; add lazy2 and the updated level 2 zpaq specbf2012-11-024-83/+59 * - Update to 1.6.2 for php 5.4 compatibility, remove custom patch for 5.4flo2012-10-293-21/+4 * Augment CATEGORIES.danfe2012-10-261-1/+1