Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"changes": [
{
"packageName": "@microsoft/rush",
"comment": "Fix the right border of PNPM's \"Ignored build scripts\" warning box sticking out when Rush rewrites \"pnpm approve-builds\" in it.",
"type": "patch"
}
],
"packageName": "@microsoft/rush"
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import type { Subspace } from '../../api/Subspace';
import { BaseLinkManager, SymlinkKind } from '../base/BaseLinkManager';
import { FlagFile } from '../../api/FlagFile';
import { Stopwatch } from '../../utilities/Stopwatch';
import { replaceTextInPnpmOutput } from '../../utilities/pnpmOutputUtilities';

export interface IPnpmModules {
hoistedDependencies: { [dep in string]: { [depPath in string]: string } };
Expand Down Expand Up @@ -584,8 +585,9 @@ export class WorkspaceInstallManager extends BaseInstallManager {

// Replace `pnpm approve-builds` with `rush-pnpm approve-builds` when running
// `rush install` or `rush update` to instruct users to use the correct command
const modifiedChunk: string = chunk.replace(
/pnpm approve-builds/g,
const modifiedChunk: string = replaceTextInPnpmOutput(
chunk,
'pnpm approve-builds',
`rush-pnpm --subspace ${subspace.subspaceName} approve-builds`
);

Expand Down
162 changes: 162 additions & 0 deletions libraries/rush-lib/src/utilities/pnpmOutputUtilities.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.

interface ILine {
text: string;
ending: string;
}

interface IBoxRow {
left: string; // the left border, e.g. '│'
inner: string; // everything between the borders, e.g. ' Run "pnpm approve-builds" ... '
right: string; // the right border, e.g. '│'
}

function splitLines(chunk: string): ILine[] {
const parts: string[] = chunk.split(/(\r?\n)/);
const lines: ILine[] = [];

for (let i: number = 0; i < parts.length; i += 2) {
lines.push({ text: parts[i], ending: parts[i + 1] ?? '' });
}

return lines;
}

// A row of a box that PNPM draws, such as "│ Some text │". Each border may be wrapped in color
// codes. Group 1 is the left border, group 2 is the text between the borders (which must not contain
// color codes, so that its length matches its width on screen), and group 3 is the right border.
const BOX_ROW_REGEXP: RegExp =
// eslint-disable-next-line no-control-regex
/^((?:\u001b\[[0-9;]*m)*│(?:\u001b\[[0-9;]*m)*)([^\u001b]*)((?:\u001b\[[0-9;]*m)*│(?:\u001b\[[0-9;]*m)*)$/;

function tryParseBoxRow(text: string): IBoxRow | undefined {
const match: RegExpExecArray | null = BOX_ROW_REGEXP.exec(text);
if (!match) {
return undefined;
}

return {
left: match[1],
inner: match[2],
right: match[3]
};
}

// Replaces the text in a box row, keeping the row's width. Returns undefined if the new text doesn't fit.
function tryReplaceInBoxRow(row: IBoxRow, searchValue: string, replaceValue: string): string | undefined {
const innerWidth: number = row.inner.length;
const newText: string = row.inner.replaceAll(searchValue, replaceValue).trimEnd();
if (newText.length > innerWidth) {
return undefined;
}

return row.left + newText.padEnd(innerWidth) + row.right;
}

function wrapWords(words: string[], width: number): string[] {
const rows: string[] = [];
let currentRow: string = '';
for (const word of words) {
if (currentRow === '') {
currentRow = word;
} else if ((currentRow + word).length + 1 <= width) {
currentRow += ' ' + word;
} else {
rows.push(currentRow);
currentRow = word;
}
}

if (currentRow !== '') {
rows.push(currentRow);
}
return rows;
}

// Replaces every occurrence of searchValue in a chunk of PNPM output. In a box row, the row keeps its
// width so that the right border stays in line (https://github.com/microsoft/rushstack/issues/5682).
export function replaceTextInPnpmOutput(chunk: string, searchValue: string, replaceValue: string): string {
if (!chunk.includes(searchValue)) {
return chunk;
}

const lines: ILine[] = splitLines(chunk);
const output: string[] = [];
for (let i: number = 0; i < lines.length; i++) {
const { text, ending } = lines[i];

// The line has nothing to replace.
if (!text.includes(searchValue)) {
output.push(text + ending);
continue;
}

// Not a box row, or not a complete one: plain replacement, as before.
const row: IBoxRow | undefined = tryParseBoxRow(text);
if (!row) {
output.push(text.replaceAll(searchValue, replaceValue) + ending);
continue;
}

// A box row where the new text fits.
const replacedRow: string | undefined = tryReplaceInBoxRow(row, searchValue, replaceValue);
if (replacedRow !== undefined) {
output.push(replacedRow + ending);
continue;
}

const innerWidth: number = row.inner.length;
const indent: number = row.inner.length - row.inner.trimStart().length;
const textWidth: number = innerWidth - indent * 2;
if (textWidth <= 0) {
output.push(text.replaceAll(searchValue, replaceValue) + ending);
continue;
}

const words: string[] = row.inner
.replaceAll(searchValue, replaceValue)
.split(' ')
.filter((word) => word !== '');

let lastRowIndex: number = i; // the last row that's part of this paragraph
while (lastRowIndex + 1 < lines.length) {
const nextRow: IBoxRow | undefined = tryParseBoxRow(lines[lastRowIndex + 1].text);

// Stop at anything that isn't a row of the same box.
if (!nextRow || nextRow.inner.length !== innerWidth) {
break;
}

// Stop at a blank row, which ends the paragraph, or at a row laid out differently.
const nextIndent: number = nextRow.inner.length - nextRow.inner.trimStart().length;
if (nextRow.inner.trim() === '' || nextIndent !== indent) {
break;
}

// A row with its own text to replace gets its own pass through the main loop.
if (nextRow.inner.includes(searchValue)) {
break;
}

words.push(...nextRow.inner.split(' ').filter((word) => word !== ''));

lastRowIndex++;
}

// Wrap the words, and rebuild each wrapped row as a box row of the original width.
const wrappedRows: string[] = wrapWords(words, textWidth);
for (let k: number = 0; k < wrappedRows.length; k++) {
const isLastRow: boolean = k === wrappedRows.length - 1;
const rowEnding: string = isLastRow ? lines[lastRowIndex].ending : ending || '\n';
output.push(
row.left + ' '.repeat(indent) + wrappedRows[k].padEnd(innerWidth - indent) + row.right + rowEnding
);
}

// Skip the rows below whose words were moved into the wrapped rows.
i = lastRowIndex;
}

return output.join('');
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.

import { replaceTextInPnpmOutput } from '../pnpmOutputUtilities';

describe(replaceTextInPnpmOutput.name, () => {
const searchValue: string = 'pnpm approve-builds';
const replaceValue: string = 'rush-pnpm --subspace default approve-builds';

// The warning box as PNPM prints it.
const pnpmBox: string =
'╭ Warning ─────────────────────────────────────────────────────────────────────╮\n' +
'│ │\n' +
'│ Ignored build scripts: rs-module-lexer@2.8.0. │\n' +
'│ Run "pnpm approve-builds" to pick which dependencies should be allowed │\n' +
'│ to run scripts. │\n' +
'│ │\n' +
'╰──────────────────────────────────────────────────────────────────────────────╯\n';

// The same box after the replacement, with the long row wrapped to keep the box's width.
const expectedBox: string =
'╭ Warning ─────────────────────────────────────────────────────────────────────╮\n' +
'│ │\n' +
'│ Ignored build scripts: rs-module-lexer@2.8.0. │\n' +
'│ Run "rush-pnpm --subspace default approve-builds" to pick which │\n' +
'│ dependencies should be allowed to run scripts. │\n' +
'│ │\n' +
'╰──────────────────────────────────────────────────────────────────────────────╯\n';

it('leaves output without the search text unchanged', () => {
const chunk: string = 'Done in 735ms\n';
expect(replaceTextInPnpmOutput(chunk, searchValue, replaceValue)).toEqual(chunk);
});

it('replaces text outside a box', () => {
const chunk: string = 'Run "pnpm approve-builds" now\n';
expect(replaceTextInPnpmOutput(chunk, searchValue, replaceValue)).toEqual(
'Run "rush-pnpm --subspace default approve-builds" now\n'
);
});

it('keeps the width of a box row when the new text fits', () => {
const chunk: string =
'│ Run "pnpm approve-builds" to pick which dependencies should be allowed │\n';
expect(replaceTextInPnpmOutput(chunk, searchValue, 'rush-pnpm approve-builds')).toEqual(
'│ Run "rush-pnpm approve-builds" to pick which dependencies should be allowed│\n'
);
});

it('wraps a box row when the new text does not fit', () => {
expect(replaceTextInPnpmOutput(pnpmBox, searchValue, replaceValue)).toEqual(expectedBox);
});

it('keeps the color codes around the borders of a box', () => {
const colorBorders = (box: string): string => box.replaceAll('│', '\u001b[33m│\u001b[39m');

expect(replaceTextInPnpmOutput(colorBorders(pnpmBox), searchValue, replaceValue)).toEqual(
colorBorders(expectedBox)
);
});

it('keeps Windows line endings', () => {
const useWindowsLineEndings = (box: string): string => box.replaceAll('\n', '\r\n');

expect(replaceTextInPnpmOutput(useWindowsLineEndings(pnpmBox), searchValue, replaceValue)).toEqual(
useWindowsLineEndings(expectedBox)
);
});

it('does a plain replacement in a box row that is cut off at the end of the chunk', () => {
const chunk: string =
'│ Ignored build scripts: rs-module-lexer@2.8.0. │\n' +
'│ Run "pnpm approve-builds" to pick which depen';

expect(replaceTextInPnpmOutput(chunk, searchValue, replaceValue)).toEqual(
'│ Ignored build scripts: rs-module-lexer@2.8.0. │\n' +
'│ Run "rush-pnpm --subspace default approve-builds" to pick which depen'
);
});
});