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

refactor: use nano-spawn #9

Merged
merged 3 commits into from
Nov 4, 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
5 changes: 2 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@
"bin": "dist/index.js",
"packageManager": "pnpm@9.12.1",
"scripts": {
"build": "pkgroll --minify --export-condition=node --target=node12.19",
"build": "pkgroll --minify --target=node12.19",
"lint": "lintroll --cache .",
"type-check": "tsc --noEmit",
"test": "tsx -C import tests",
"test": "tsx tests",
"prepack": "pnpm build && clean-pkg-json"
},
"dependencies": {
Expand All @@ -40,7 +40,6 @@
"byte-size": "^9.0.0",
"clean-pkg-json": "^1.2.0",
"cleye": "^1.3.2",
"execa": "^9.5.1",
"fs-fixture": "^2.6.0",
"kolorist": "^1.8.0",
"lintroll": "^1.10.0",
Expand Down
3 changes: 0 additions & 3 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

42 changes: 20 additions & 22 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import fs from 'node:fs/promises';
import { execa } from 'execa';
import spawn, { type SubprocessError } from 'nano-spawn';
import task from 'tasuku';
import { cli } from 'cleye';
import type { PackageJson } from '@npmcli/package-json';
Expand Down Expand Up @@ -87,7 +87,7 @@
// Validate remote exists
let remoteUrl;
try {
const getRemoteUrl = await execa('git', ['remote', 'get-url', remote]);
const getRemoteUrl = await spawn('git', ['remote', 'get-url', remote]);
remoteUrl = getRemoteUrl.stdout.trim();
} catch {
throw new Error(`Git remote ${stringify(remote)} does not exist`);
Expand All @@ -105,22 +105,20 @@
}

if (fresh) {
await execa('git', ['checkout', '--orphan', localTemporaryBranch]);
await spawn('git', ['checkout', '--orphan', localTemporaryBranch]);
} else {
const gitFetch = await execa('git', ['fetch', '--depth=1', remote, `${publishBranch}:${localTemporaryBranch}`], {
reject: false,
});
const gitFetch = await spawn('git', ['fetch', '--depth=1', remote, `${publishBranch}:${localTemporaryBranch}`]).catch(error => error as SubprocessError);

await execa('git', [
await spawn('git', [
'checkout',
...(gitFetch.failed ? ['-b'] : []),
...('exitCode' in gitFetch ? ['-b'] : []),
localTemporaryBranch,
]);
}

// Checkout the files tree from the previous branch
// This also applies any file deletions from the source branch
await execa('git', ['restore', '--source', currentBranch, ':/']);
await spawn('git', ['restore', '--source', currentBranch, ':/']);
});

if (!dry) {
Expand All @@ -134,10 +132,10 @@
}

setTitle('Running hook "prepare"');
await execa('npm', ['run', '--if-present', 'prepare']);
await spawn('npm', ['run', '--if-present', 'prepare']);

setTitle('Running hook "prepack"');
await execa('npm', ['run', '--if-present', 'prepack']);
await spawn('npm', ['run', '--if-present', 'prepack']);
});

if (!dry) {
Expand Down Expand Up @@ -226,25 +224,25 @@
);
const totalSize = fileSizes.reduce((accumulator, { size }) => accumulator + size, 0);

console.log(lightBlue('Publishing files'));

Check warning on line 227 in src/index.ts

View workflow job for this annotation

GitHub Actions / Test

Unexpected console statement
console.log(fileSizes.map(({ file, size }) => `${file} ${dim(byteSize(size).toString())}`).join('\n'));

Check warning on line 228 in src/index.ts

View workflow job for this annotation

GitHub Actions / Test

Unexpected console statement
console.log(`\n${lightBlue('Total size')}`, byteSize(totalSize).toString());

Check warning on line 229 in src/index.ts

View workflow job for this annotation

GitHub Actions / Test

Unexpected console statement

// Remove all files from Git tree
// This removes all files from the branch so only the publish files will be added
await execa('git', ['rm', '--cached', '-r', ':/'], {
await spawn('git', ['rm', '--cached', '-r', ':/']).catch(
// Can fail if tree is empty: fatal: pathspec ':/' did not match any files
reject: false,
});
() => {},
);

await execa('git', ['add', '-f', ...publishFiles]);
await spawn('git', ['add', '-f', ...publishFiles]);

const { stdout: trackedFiles } = await gitStatusTracked();
if (trackedFiles.length === 0) {
console.warn('⚠️ No new changes found to commit.');

Check warning on line 242 in src/index.ts

View workflow job for this annotation

GitHub Actions / Test

Unexpected console statement
} else {
// -a is passed in so it can stage deletions from `git restore`
await execa('git', ['commit', '--no-verify', '-am', `Published branch ${stringify(currentBranch)}`]);
await spawn('git', ['commit', '--no-verify', '-am', `Published branch ${stringify(currentBranch)}`]);
}

commitSha = await getCurrentCommit();
Expand All @@ -262,7 +260,7 @@
return;
}

await execa('git', [
await spawn('git', [
'push',
...(fresh ? ['--force'] : []),
'--no-verify',
Expand All @@ -284,15 +282,15 @@
}

// In case commit failed and there are uncommitted changes
await execa('git', ['reset', '--hard']);
await spawn('git', ['reset', '--hard']);

await execa('git', ['checkout', '-f', currentBranch]);
await spawn('git', ['checkout', '-f', currentBranch]);

// Delete local branch
await execa('git', ['branch', '-D', localTemporaryBranch], {
await spawn('git', ['branch', '-D', localTemporaryBranch]).catch(
// Ignore failures (e.g. in case it didin't even succeed to create this branch)
reject: false,
});
() => {},
);
});

revertBranch.clear();
Expand All @@ -316,7 +314,7 @@
},
);
})().catch((error) => {
console.error('Error:', error.message);

Check warning on line 317 in src/index.ts

View workflow job for this annotation

GitHub Actions / Test

Unexpected console statement

process.exit(1);
});
16 changes: 7 additions & 9 deletions src/utils/git.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { execa } from 'execa';
import spawn, { type SubprocessError } from 'nano-spawn';

export const gitStatusTracked = () => execa('git', ['status', '--porcelain', '--untracked-files=no']);
export const gitStatusTracked = () => spawn('git', ['status', '--porcelain', '--untracked-files=no']);

export const assertCleanTree = async () => {
const { stdout } = await gitStatusTracked().catch((error) => {
Expand All @@ -21,21 +21,19 @@ export const getCurrentBranchOrTagName = async () => {
* This commands supports older versions of Git, but since v2.22, you can do:
* git branch --show-current
*/
const getBranch = await execa(
const getBranch = await spawn(
'git',
['symbolic-ref', '--short', '-q', 'HEAD'],
{ reject: false },
);
).catch(error => error as SubprocessError);

if (getBranch.stdout) {
return getBranch.stdout;
}

const getTag = await execa(
const getTag = await spawn(
'git',
['describe', '--tags'],
{ reject: false },
);
).catch(error => error as SubprocessError);

if (getTag.stdout) {
return getTag.stdout;
Expand All @@ -45,6 +43,6 @@ export const getCurrentBranchOrTagName = async () => {
};

export const getCurrentCommit = async () => {
const getCommit = await execa('git', ['rev-parse', '--short', 'HEAD']);
const getCommit = await spawn('git', ['rev-parse', '--short', 'HEAD']);
return getCommit.stdout.trim();
};
Loading