Skip to content

Commit

Permalink
chore(pie-monorepo-utils): DSW-000 fix lint error (#2071)
Browse files Browse the repository at this point in the history
fix lint error

Co-authored-by: Ben Siggery <[email protected]>
  • Loading branch information
siggerzz and Ben Siggery authored Nov 18, 2024
1 parent 2dd4d53 commit 4dfd612
Show file tree
Hide file tree
Showing 8 changed files with 48 additions and 43 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { beforeEach, describe, expect, test, vi } from 'vitest';
const workflow = require('../../changeset-snapshot/create-and-publish');
import {
beforeEach, describe, expect, test, vi,
} from 'vitest';

const { Readable } = require('stream');
const workflow = require('../../changeset-snapshot/create-and-publish');

let context;
let execa;
Expand Down Expand Up @@ -29,7 +32,7 @@ const mockExecaCommand = () => {
mockStdoutStream.pipe = vi.fn().mockImplementation((destination) => destination);

return mockProcess;
};
};

describe('create and publish workflow', () => {
beforeEach(() => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable camelcase */
module.exports = async ({ github, context }, execa) => {
await execa.command('yarn changeset:version --snapshot snapshot-release', { stdio: 'inherit' });

Expand All @@ -24,7 +25,7 @@ Test the snapshot${multiple ? 's' : ''} by updating your \`package.json\` with t
body += `> [!NOTE]
> If you have more than one of these packages installed, we suggest using the new snapshots for all of them to help avoid version conflicts.
${newTags.map(tag => `\`\`\`sh
${newTags.map((tag) => `\`\`\`sh
yarn up ${tag} --mode=update-lockfile
\`\`\``).join('\n')}
Then finally:
Expand All @@ -37,7 +38,7 @@ yarn up ${newTags[0]}
\`\`\``;
}
} else {
body = `No changed packages found! Please make sure you have added a changeset entry for the packages you would like to snapshot.`;
body = 'No changed packages found! Please make sure you have added a changeset entry for the packages you would like to snapshot.';
}

await github.rest.issues.createComment({
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable camelcase */
module.exports = async ({ github, context }, execa) => {
await execa.command('yarn changeset:version --snapshot snapshot-release', { stdio: 'inherit' });

Expand All @@ -11,12 +12,11 @@ module.exports = async ({ github, context }, execa) => {
.map(([_, tag]) => tag)
.filter((tag) => !/^wc-.+$|pie-(monorepo|docs|storybook)/.test(tag));

// Extract the snapshot version from one of the tags
const snapshotVersion = newTags[0].match(/\d{14}$/)[0];

// Extract the snapshot version from one of the tags
const snapshotVersion = newTags[0].match(/\d{14}$/)[0];

// Extract package names by removing version and scope from the tags
const packageNames = newTags.map(tag => `@justeattakeaway/${tag.match(/pie-[\w-]+/)[0]}`);
// Extract package names by removing version and scope from the tags
const packageNames = newTags.map((tag) => `@justeattakeaway/${tag.match(/pie-[\w-]+/)[0]}`);

let body;

Expand All @@ -26,7 +26,7 @@ module.exports = async ({ github, context }, execa) => {
body = `@${context.actor} Your snapshot${multiple ? 's have' : ' has'} been published to npm!\n\nTest the snapshot${multiple ? 's' : ''} by updating your \`package.json\` with the newly-published version${multiple ? 's' : ''}:\n`;

if (multiple) {
body += `> [!NOTE]\n> If you have more than one of these packages installed, we suggest using the new snapshots for all of them to help avoid version conflicts.\n\n${newTags.map(tag => `\`\`\`sh\nyarn up ${tag} --mode=update-lockfile\n\`\`\``).join('\n')}\nThen finally:\n\`\`\`sh\nyarn install\n\`\`\``;
body += `> [!NOTE]\n> If you have more than one of these packages installed, we suggest using the new snapshots for all of them to help avoid version conflicts.\n\n${newTags.map((tag) => `\`\`\`sh\nyarn up ${tag} --mode=update-lockfile\n\`\`\``).join('\n')}\nThen finally:\n\`\`\`sh\nyarn install\n\`\`\``;
} else {
body += `\`\`\`sh\nyarn up ${newTags[0]}\n\`\`\``;
}
Expand All @@ -38,12 +38,12 @@ module.exports = async ({ github, context }, execa) => {
repo: 'pie-aperture',
event_type: 'pie-trigger',
client_payload: {
'pie-branch': process.env.PIE_BRANCH,
'pie-pr-number': process.env.PIE_PR_NUMBER,
'snapshot-version': snapshotVersion,
'snapshot-packages': packageNames.join(' ')
}
})
'pie-branch': process.env.PIE_BRANCH,
'pie-pr-number': process.env.PIE_PR_NUMBER,
'snapshot-version': snapshotVersion,
'snapshot-packages': packageNames.join(' '),
},
});
} catch (error) {
console.error(`Failed to dispatch workflow: ${error.message}`);
await github.rest.issues.createComment({
Expand All @@ -53,9 +53,8 @@ module.exports = async ({ github, context }, execa) => {
body: `Failed to trigger PIE Aperture workflow: ${error.message}`,
});
}

} else {
body = `No changed packages found! Please make sure you have added a changeset entry for the packages you would like to snapshot.`;
body = 'No changed packages found! Please make sure you have added a changeset entry for the packages you would like to snapshot.';
}

// Create a GitHub comment with the update instructions
Expand All @@ -65,4 +64,4 @@ module.exports = async ({ github, context }, execa) => {
repo: context.repo.repo,
body,
});
};
};
Original file line number Diff line number Diff line change
@@ -1,28 +1,29 @@
/* eslint-disable camelcase */
const fs = require('fs');

function readFileAsText(filePath) {
function readFileAsText (filePath) {
const fileExists = fs.existsSync(filePath);
if (!fileExists) return null;

const fileContent = fs.readFileSync(filePath, { encoding: 'utf-8' });
return fileContent;
}

function readChangesetFile(filePath) {
function readChangesetFile (filePath) {
const fileContent = readFileAsText(filePath);

const sections = fileContent.split('---')
.map((section) => section.trim())
.filter(Boolean);

if (sections.length < 2) {
throw new Error("The changeset file content looks incorrect. Ensure there are two `---` sections.");
throw new Error('The changeset file content looks incorrect. Ensure there are two `---` sections.');
}

return sections[1];
}

function getPrBody(changes) {
function getPrBody (changes) {
return `## Changes
This PR updates icons.
Expand All @@ -36,23 +37,23 @@ ${changes}
### Reviewer 2 -
- [ ] I have reviewed the \`PIE Docs\` PR preview
- [ ] If there are visual test updates, I have reviewed them`
- [ ] If there are visual test updates, I have reviewed them`;
}

/**
* Check if issues file exists, read from it and format the text
* @param {string} filePath issues json file path
* @returns A string containing the issues already formatted as MD
*/
function readIconsIssues(filePath) {
function readIconsIssues (filePath) {
const fileContent = readFileAsText(filePath);
if (!fileContent) return null;

const jsonData = JSON.parse(fileContent);

return `## 🚧🚧🚧 The following issues were found while updating the icons: 🚧🚧🚧
${jsonData.map(item => `- ${item}`).join('\n')}`
${jsonData.map((item) => `- ${item}`).join('\n')}`;
}

module.exports = async ({ github, branchName, changesetFilePath }) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { execSync } = require('child_process')
const { execSync } = require('child_process');

const scriptPrefix = 'check-added-packages:';

Expand All @@ -14,7 +14,7 @@ async function getPackageJsonAtRef (ref, filePath) {

return JSON.parse(fileContent);
} catch (err) {
throw new Error(`${scriptPrefix} Failed to fetch package.json from ${ref}. "${err.message}"`)
throw new Error(`${scriptPrefix} Failed to fetch package.json from ${ref}. "${err.message}"`);
}
}

Expand Down Expand Up @@ -44,13 +44,13 @@ async function getAddedComponentPackages (filePath, packagePrefix = '@justeattak
// Get package.json from the base branch (main)
const basePackageJson = await getPackageJsonAtRef('main', filePath);
if (!basePackageJson) {
throw new Error(`${scriptPrefix} Failed to retrieve package.json from main branch. "${err.message}"`)
throw new Error(`${scriptPrefix} Failed to retrieve package.json from main branch.`);
}

// Get package.json from the current PR branch
const currentPackageJson = await getPackageJsonAtRef(currentBranchName, filePath);
if (!currentPackageJson) {
throw new Error(`${scriptPrefix} Failed to retrieve package.json from the current branch. "${err.message}"`)
throw new Error(`${scriptPrefix} Failed to retrieve package.json from the current branch.`);
}

// Compare dependencies
Expand All @@ -65,4 +65,4 @@ async function getAddedComponentPackages (filePath, packagePrefix = '@justeattak
module.exports = {
scriptPrefix,
getAddedComponentPackages,
}
};
4 changes: 2 additions & 2 deletions packages/tools/pie-monorepo-utils/pr-labeler/get-labels.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ module.exports = async ({ prBranchName, prNumber, artifactFilePath }) => {
// Check what labels should be created
const addedComponentPackages = await getAddedComponentPackages(packageFilePath, packagePrefix, prBranchName);

if (addedComponentPackages.length===0) {
if (addedComponentPackages.length === 0) {
console.info(`${scriptPrefix} No components were added, nothing to update.`);
return;
}

// Save artifact with label names to be created by the "labeler-get-labels.yml" workflow
const newLabels = addedComponentPackages.map(componentName => componentName.replace(packagePrefix, ''));
const newLabels = addedComponentPackages.map((componentName) => componentName.replace(packagePrefix, ''));
const artifactStr = JSON.stringify({ prNumber, newLabels }, null, 2);
fs.writeFileSync(artifactFilePath, artifactStr, { encoding: 'utf8' });
} catch (error) {
Expand Down
18 changes: 9 additions & 9 deletions packages/tools/pie-monorepo-utils/pr-labeler/set-labels.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
/* eslint-disable camelcase, no-restricted-syntax, no-await-in-loop */
const fs = require('fs');
const { execSync } = require('child_process');

module.exports = async ({ github, context }) => {
const { repo : { owner, repo }} = context;
const { repo: { owner, repo } } = context;

const allArtifacts = await github.rest.actions.listWorkflowRunArtifacts({
owner,
repo,
run_id: context.payload.workflow_run.id,
});
const matchArtifact = allArtifacts.data.artifacts.find((artifact) => {
return artifact.name == "tmp-labels.json"
});
const matchArtifact = allArtifacts.data.artifacts.find((artifact) => artifact.name === 'tmp-labels.json');

// There are no labels to add
if (!matchArtifact) return;
Expand All @@ -35,23 +34,24 @@ module.exports = async ({ github, context }) => {

// Fetch existing labels
const repoLabelsResponse = await github.rest.issues.listLabelsForRepo({ owner, repo });
const repoLabels = repoLabelsResponse.data.map(({name}) => name);
const repoLabels = repoLabelsResponse.data.map(({ name }) => name);

// Verify which labels are new and create them
/* eslint-disable no-restricted-syntax */
for (const newLabel of newLabels) {
const labelExists = repoLabels.includes(newLabel)
const labelIsValid = newLabel.startsWith('pie-') && newLabel.length <= 32
const labelExists = repoLabels.includes(newLabel);
const labelIsValid = newLabel.startsWith('pie-') && newLabel.length <= 32;

if (!labelExists && labelIsValid) {
console.info(`Creating label`);
console.info('Creating label');
await github.rest.issues.createLabel({
name: newLabel,
color: 'ededed',
owner,
repo,
});

console.info(`Assigning label to the PR`);
console.info('Assigning label to the PR');
await github.rest.issues.addLabels({
issue_number: prNumber,
labels: [newLabel],
Expand Down
1 change: 1 addition & 0 deletions turbo.json
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@
"lint:scripts": {
"cache": true,
"inputs": [
"$TURBO_DEFAULT$",
"src/**",
"src/react.ts"
],
Expand Down

0 comments on commit 4dfd612

Please sign in to comment.