Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

style: use semicolons, trailing comma with prettier #539

Merged
merged 2 commits into from
Aug 26, 2024
Merged
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
40 changes: 20 additions & 20 deletions .github/actions/bump-manifest-version.cjs
Original file line number Diff line number Diff line change
@@ -1,28 +1,28 @@
// @ts-check
/* eslint-disable @typescript-eslint/no-require-imports, no-console */
const fs = require('node:fs/promises')
const fs = require('node:fs/promises');

/** @param {import('github-script').AsyncFunctionArguments} AsyncFunctionArguments */
module.exports = async ({ core }) => {
const manifestPath = './src/manifest.json'
const manifestFile = await fs.readFile(manifestPath, 'utf8')
const manifest = JSON.parse(manifestFile)
const manifestPath = './src/manifest.json';
const manifestFile = await fs.readFile(manifestPath, 'utf8');
const manifest = JSON.parse(manifestFile);
/**@type {string} */
const existingVersion = manifest.version
const existingVersion = manifest.version;

const bumpType = /** @type {BumpType} */ (process.env.INPUT_VERSION)
const bumpType = /** @type {BumpType} */ (process.env.INPUT_VERSION);
if (!bumpType) {
throw new Error('Missing bump type')
throw new Error('Missing bump type');
}

const version = bumpVersion(existingVersion, bumpType).join('.')
const version = bumpVersion(existingVersion, bumpType).join('.');

console.log({ existingVersion, bumpType, version })
console.log({ existingVersion, bumpType, version });

manifest.version = version
await fs.writeFile(manifestPath, JSON.stringify(manifest, null, 2))
core.setOutput('version', version)
}
manifest.version = version;
await fs.writeFile(manifestPath, JSON.stringify(manifest, null, 2));
core.setOutput('version', version);
};

/**
* @typedef {'build' | 'patch' | 'minor'} BumpType
Expand All @@ -31,20 +31,20 @@ module.exports = async ({ core }) => {
* @return {[major: number, minor: number, patch: number, build: number]}
*/
function bumpVersion(existingVersion, type) {
const parts = existingVersion.split('.').map(Number)
const parts = existingVersion.split('.').map(Number);
if (parts.length !== 4 || parts.some((e) => !Number.isSafeInteger(e))) {
throw new Error('Existing version does not have right format')
throw new Error('Existing version does not have right format');
}
const [major, minor, patch, build] = parts
const [major, minor, patch, build] = parts;

switch (type) {
case 'build':
return [major, minor, patch, build + 1]
return [major, minor, patch, build + 1];
case 'patch':
return [major, minor, patch + 1, 0]
return [major, minor, patch + 1, 0];
case 'minor':
return [major, minor + 1, 0, 0]
return [major, minor + 1, 0, 0];
default:
throw new Error('Unknown bump type: ' + type)
throw new Error('Unknown bump type: ' + type);
}
}
16 changes: 8 additions & 8 deletions .github/actions/constants.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,25 @@
*/

const BADGE =
'<img src="https://img.shields.io/badge/{{ CONCLUSION }}-{{ BADGE_COLOR }}?style=for-the-badge&label={{ BADGE_LABEL }}" alt="Badge" />'
'<img src="https://img.shields.io/badge/{{ CONCLUSION }}-{{ BADGE_COLOR }}?style=for-the-badge&label={{ BADGE_LABEL }}" alt="Badge" />';
/** @type {Browser[]} */
const BROWSERS = ['chrome', 'firefox']
const BROWSERS = ['chrome', 'firefox'];
const COLORS = {
green: '3fb950',
red: 'd73a49'
}
red: 'd73a49',
};
const TEMPLATE_VARS = {
tableBody: '{{ TABLE_BODY }}',
sha: '{{ SHA }}',
conclusion: '{{ CONCLUSION }}',
badgeColor: '{{ BADGE_COLOR }}',
badgeLabel: '{{ BADGE_LABEL }}',
jobLogs: '{{ JOB_LOGS }}'
}
jobLogs: '{{ JOB_LOGS }}',
};

module.exports = {
BADGE,
BROWSERS,
COLORS,
TEMPLATE_VARS
}
TEMPLATE_VARS,
};
40 changes: 20 additions & 20 deletions .github/actions/delete-artifacts.cjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// @ts-check
/* eslint-disable @typescript-eslint/no-require-imports, no-console */
const { BROWSERS } = require('./constants.cjs')
const { BROWSERS } = require('./constants.cjs');

/**
* @param {Pick<import('github-script').AsyncFunctionArguments, 'github' | 'context'>} AsyncFunctionArguments
Expand All @@ -10,9 +10,9 @@ async function getBrowserArtifacts({ github, context }, name) {
const result = await github.rest.actions.listArtifactsForRepo({
owner: context.repo.owner,
repo: context.repo.repo,
name
})
return result.data.artifacts
name,
});
return result.data.artifacts;
}

/**
Expand All @@ -22,40 +22,40 @@ async function getBrowserArtifacts({ github, context }, name) {
async function getPRArtifacts({ github, context }, prNumber) {
const data = await Promise.all(
BROWSERS.map((browser) =>
getBrowserArtifacts({ github, context }, `${prNumber}-${browser}`)
)
)
getBrowserArtifacts({ github, context }, `${prNumber}-${browser}`),
),
);

/** @type {{id: number}[]} */
const artifacts = []
const artifacts = [];
for (let i = 0; i < data.length; i++) {
// same as `artifacts.push(...data[i])` but it's a bit faster
artifacts.push.apply(artifacts, data[i])
artifacts.push.apply(artifacts, data[i]);
}
return artifacts
return artifacts;
}

/** @param {import('github-script').AsyncFunctionArguments} AsyncFunctionArguments */
module.exports = async ({ github, context, core }) => {
if (context.payload.action !== 'closed') {
core.setFailed('This action only works on closed PRs.')
core.setFailed('This action only works on closed PRs.');
}

const { owner, repo } = context.repo
const { owner, repo } = context.repo;
/** @type {number} */
const prNumber = context.payload.number
const prNumber = context.payload.number;

const artifacts = await getPRArtifacts({ github, context }, prNumber)
const artifacts = await getPRArtifacts({ github, context }, prNumber);

await Promise.all(
artifacts.map((artifact) =>
github.rest.actions.deleteArtifact({
owner,
repo,
artifact_id: artifact.id
})
)
)
artifact_id: artifact.id,
}),
),
);

console.log(`Deleted ${artifacts.length} artifacts for PR #${prNumber}.`)
}
console.log(`Deleted ${artifacts.length} artifacts for PR #${prNumber}.`);
};
8 changes: 4 additions & 4 deletions .github/actions/get-built-version.cjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// @ts-check
/* eslint-disable @typescript-eslint/no-require-imports */
const fs = require('node:fs/promises')
const fs = require('node:fs/promises');

/**
* Retrieves the manifest version from the built extension.
Expand All @@ -9,7 +9,7 @@ const fs = require('node:fs/promises')
module.exports = async ({ core }) => {
const manifest = await fs
.readFile('./dist/chrome/manifest.json', 'utf8')
.then(JSON.parse)
.then(JSON.parse);

core.setOutput('version', manifest.version)
}
core.setOutput('version', manifest.version);
};
90 changes: 45 additions & 45 deletions .github/actions/get-workflow-artifacts.cjs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// @ts-check
/* eslint-disable @typescript-eslint/no-require-imports, no-console */
const fs = require('node:fs/promises')
const { COLORS, TEMPLATE_VARS, BADGE } = require('./constants.cjs')
const fs = require('node:fs/promises');
const { COLORS, TEMPLATE_VARS, BADGE } = require('./constants.cjs');

/**
* @typedef {import('./constants.cjs').Browser} Browser
Expand All @@ -12,14 +12,14 @@ const ARTIFACTS_DATA = {
chrome: {
name: 'Chrome',
url: '',
size: ''
size: '',
},
firefox: {
name: 'Firefox',
url: '',
size: ''
}
}
size: '',
},
};

/**
* @param {string} conclusion
Expand All @@ -29,81 +29,81 @@ const ARTIFACTS_DATA = {
function getBadge(conclusion, badgeColor, badgeLabel) {
return BADGE.replace(TEMPLATE_VARS.conclusion, conclusion)
.replace(TEMPLATE_VARS.badgeColor, badgeColor)
.replace(TEMPLATE_VARS.badgeLabel, badgeLabel)
.replace(TEMPLATE_VARS.badgeLabel, badgeLabel);
}

/**
* @param {number} bytes
* @param {number} decimals
*/
function formatBytes(bytes, decimals = 2) {
if (!Number(bytes)) return '0B'
const k = 1024
const dm = decimals < 0 ? 0 : decimals
const sizes = ['B', 'KB', 'MB', 'GB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))}${sizes[i]}`
if (!Number(bytes)) return '0B';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))}${sizes[i]}`;
}

/** @param {import('github-script').AsyncFunctionArguments} AsyncFunctionArguments */
module.exports = async ({ github, context, core }) => {
const { owner, repo } = context.repo
const baseUrl = context.payload.repository?.html_url
const suiteId = context.payload.workflow_run.check_suite_id
const runId = context.payload.workflow_run.id
const conclusion = context.payload.workflow_run.conclusion
const sha = context.payload.workflow_run.pull_requests[0].head.sha
const prNumber = context.payload.workflow_run.pull_requests[0].number
const jobLogsUrl = `${baseUrl}/actions/runs/${context.payload.workflow_run.id}`
const { owner, repo } = context.repo;
const baseUrl = context.payload.repository?.html_url;
const suiteId = context.payload.workflow_run.check_suite_id;
const runId = context.payload.workflow_run.id;
const conclusion = context.payload.workflow_run.conclusion;
const sha = context.payload.workflow_run.pull_requests[0].head.sha;
const prNumber = context.payload.workflow_run.pull_requests[0].number;
const jobLogsUrl = `${baseUrl}/actions/runs/${context.payload.workflow_run.id}`;
const template = await fs.readFile(
'./.github/actions/templates/build-status.md',
'utf8'
)
'utf8',
);

/** @type {string[]} */
const tableRows = []
const tableRows = [];

core.setOutput('conclusion', conclusion)
core.setOutput('conclusion', conclusion);

if (conclusion === 'cancelled') {
return
return;
}

const artifacts = await github.rest.actions.listWorkflowRunArtifacts({
owner,
repo,
run_id: runId
})
run_id: runId,
});

artifacts.data.artifacts.forEach((artifact) => {
const key = /** @type {Browser} */ (artifact.name.split('-')[1])
const key = /** @type {Browser} */ (artifact.name.split('-')[1]);
ARTIFACTS_DATA[key].url =
`${baseUrl}/suites/${suiteId}/artifacts/${artifact.id}`
ARTIFACTS_DATA[key].size = formatBytes(artifact.size_in_bytes)
})
`${baseUrl}/suites/${suiteId}/artifacts/${artifact.id}`;
ARTIFACTS_DATA[key].size = formatBytes(artifact.size_in_bytes);
});

Object.keys(ARTIFACTS_DATA).forEach((k) => {
const { name, url, size } = ARTIFACTS_DATA[/** @type {Browser} */ (k)]
const { name, url, size } = ARTIFACTS_DATA[/** @type {Browser} */ (k)];
if (!url && !size) {
const badgeUrl = getBadge('failure', COLORS.red, name)
const badgeUrl = getBadge('failure', COLORS.red, name);
tableRows.push(
`<tr><td align="center">${badgeUrl}</td><td align="center">N/A</td></tr>`
)
`<tr><td align="center">${badgeUrl}</td><td align="center">N/A</td></tr>`,
);
} else {
const badgeUrl = getBadge('success', COLORS.green, `${name} (${size})`)
const badgeUrl = getBadge('success', COLORS.green, `${name} (${size})`);
tableRows.push(
`<tr><td align="center">${badgeUrl}</td><td align="center"><a href="${url}">Download</a></td></tr>`
)
`<tr><td align="center">${badgeUrl}</td><td align="center"><a href="${url}">Download</a></td></tr>`,
);
}
})
});

const tableBody = tableRows.join('')
const tableBody = tableRows.join('');
const commentBody = template
.replace(TEMPLATE_VARS.conclusion, conclusion)
.replace(TEMPLATE_VARS.sha, sha)
.replace(TEMPLATE_VARS.jobLogs, `<a href="${jobLogsUrl}">Run #${runId}</a>`)
.replace(TEMPLATE_VARS.tableBody, tableBody)
.replace(TEMPLATE_VARS.tableBody, tableBody);

core.setOutput('comment_body', commentBody)
core.setOutput('pr_number', prNumber)
}
core.setOutput('comment_body', commentBody);
core.setOutput('pr_number', prNumber);
};
26 changes: 14 additions & 12 deletions .github/actions/validate-stable-release.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,34 +7,36 @@
*/
module.exports = async ({ github, context }) => {
if (context.ref !== 'refs/heads/main') {
throw new Error('This action only works on main branch')
throw new Error('This action only works on main branch');
}

const { owner, repo } = context.repo
const previewVersionTag = process.env.INPUT_VERSION
const { owner, repo } = context.repo;
const previewVersionTag = process.env.INPUT_VERSION;
if (!previewVersionTag) {
throw new Error('Missing env.INPUT_VERSION')
throw new Error('Missing env.INPUT_VERSION');
}
if (!previewVersionTag.match(/^v[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+-preview$/)) {
throw new Error('Input "version" must match vX.X.X.X-preview')
throw new Error('Input "version" must match vX.X.X.X-preview');
}

const versionTag = previewVersionTag.replace('-preview', '')
const versionTag = previewVersionTag.replace('-preview', '');
try {
await github.rest.repos.getReleaseByTag({
owner,
repo,
tag: versionTag
})
throw new Error('Release already promoted to stable')
tag: versionTag,
});
throw new Error('Release already promoted to stable');
} catch (error) {
if (!error.status) {
throw error
throw error;
}
if (error.status === 404) {
// do nothing
} else {
throw new Error(`Failed to check: HTTP ${error.status}`, { cause: error })
throw new Error(`Failed to check: HTTP ${error.status}`, {
cause: error,
});
}
}
}
};
Loading