diff --git a/index.js b/index.js index b14c425..8e7e7d5 100755 --- a/index.js +++ b/index.js @@ -1,5 +1,6 @@ #!/usr/bin/env node +import CommandSummary from './src/command-summary.js'; import Config from './src/config.js'; import Github from './src/github.js'; import RepoOptions from './src/repo-options.js'; @@ -12,6 +13,8 @@ import gistsCommand from './src/commands/gists.js'; UI.printWelcome(); const main = async () => { + let summary; + try { if (!Config.load()) { const token = await UI.promptAuth(); @@ -24,15 +27,15 @@ const main = async () => { case 'repo': case 'repository': case 'repositories': - await reposCommand(RepoOptions.parse(process.argv.slice(3))); + summary = await reposCommand(RepoOptions.parse(process.argv.slice(3))); break; case 'codespaces': case 'codespace': - await codespacesCommand(); + summary = await codespacesCommand(); break; case 'gists': case 'gist': - await gistsCommand(); + summary = await gistsCommand(); break; case 'help': UI.printHelp(); @@ -56,6 +59,17 @@ const main = async () => { process.exitCode = 1; return; } + + // Mutations are never replayed: a token-wide failure only invalidates the + // cached credentials so the next invocation authenticates again. + const outcome = CommandSummary.resolveOutcome(summary); + + if (outcome.invalidateConfig) { + Config.deleteFile(); + UI.printError(summary.authError.message); + } + + if (outcome.exitCode !== 0) process.exitCode = outcome.exitCode; }; main(); diff --git a/src/command-summary.js b/src/command-summary.js new file mode 100644 index 0000000..a457fb4 --- /dev/null +++ b/src/command-summary.js @@ -0,0 +1,16 @@ +function create() { + return { processed: [], failed: [], authError: undefined }; +} + +// Translates a command summary into the process-level effects owned by the entry point. +function resolveOutcome(summary) { + return { + invalidateConfig: Boolean(summary?.authError), + exitCode: summary?.failed?.length > 0 ? 1 : 0, + }; +} + +export default { + create, + resolveOutcome, +}; diff --git a/src/commands/codespaces.js b/src/commands/codespaces.js index a94fb91..9820383 100644 --- a/src/commands/codespaces.js +++ b/src/commands/codespaces.js @@ -1,30 +1,28 @@ -import Config from '../config.js'; +import CommandSummary from '../command-summary.js'; import UI from '../ui.js'; const codespacesCommand = async () => { const codespaces = await UI.getCodespaces(); - if (!codespaces) { - Config.deleteFile(); - return await main(); - } let res = await UI.promptSelectCodespaces(codespaces); if (res.codespaces.length === 0) { UI.printNoCodespaceSelected(); - return 0; + return CommandSummary.create(); } const codespacesToDelete = res.codespaces; const codespaceCount = codespacesToDelete.length; res = await UI.promptConfirm(codespaceCount, 'codespaces', 'delete'); - if (res.confirm === 'Yes') { - await UI.deleteCodespaces(codespacesToDelete); - } else { + if (res.confirm !== 'Yes') { UI.printNoCodespacesDeleted(); + + return CommandSummary.create(); } + + return await UI.deleteCodespaces(codespacesToDelete); }; export default codespacesCommand; diff --git a/src/commands/gists.js b/src/commands/gists.js index a0cf8bb..ed7a166 100644 --- a/src/commands/gists.js +++ b/src/commands/gists.js @@ -1,3 +1,4 @@ +import CommandSummary from '../command-summary.js'; import UI from '../ui.js'; const gistsCommand = async () => { @@ -6,17 +7,19 @@ const gistsCommand = async () => { if (res.gists.length === 0) { UI.printNoGistSelected(); - return 0; + return CommandSummary.create(); } const gistsToDelete = res.gists; res = await UI.promptConfirm(gistsToDelete.length, 'gists', 'delete'); - if (res.confirm === 'Yes') { - await UI.deleteGists(gistsToDelete); - } else { + if (res.confirm !== 'Yes') { UI.printNoGistsDeleted(); + + return CommandSummary.create(); } + + return await UI.deleteGists(gistsToDelete); }; export default gistsCommand; diff --git a/src/commands/repos.js b/src/commands/repos.js index 5f7454a..91a50c7 100644 --- a/src/commands/repos.js +++ b/src/commands/repos.js @@ -1,14 +1,10 @@ -import Config from '../config.js'; +import CommandSummary from '../command-summary.js'; import RepoOptions from '../repo-options.js'; import UI from '../ui.js'; const reposCommand = async (options = {}) => { const { archive = false, force = false } = options; const repositories = await UI.getRepositories(); - if (!repositories) { - Config.deleteFile(); - return await main(); - } let reposToProcess = RepoOptions.selectRepositories(repositories, options); @@ -25,7 +21,7 @@ const reposCommand = async (options = {}) => { } else { UI.printNoReposSelected(); } - return 0; + return CommandSummary.create(); } const repoCount = reposToProcess.length; @@ -40,15 +36,15 @@ const reposCommand = async (options = {}) => { } else { UI.printNoReposDeleted(); } - return 0; + return CommandSummary.create(); } } if (archive) { - await UI.archiveRepositories(reposToProcess); - } else { - await UI.deleteRepositories(reposToProcess); + return await UI.archiveRepositories(reposToProcess); } + + return await UI.deleteRepositories(reposToProcess); }; export default reposCommand; diff --git a/src/github.js b/src/github.js index 0cbe23e..c5048ea 100644 --- a/src/github.js +++ b/src/github.js @@ -104,7 +104,7 @@ function checkPermissions(authScopes, clientScopes) { } async function deleteRepository(repository) { - const res = await apiCall( + await apiCall( 'DELETE', `/repos/${repository}`, undefined, @@ -112,13 +112,11 @@ async function deleteRepository(repository) { RESOURCE_SCOPES.deleteRepository ); - if (res.status !== 204) return false; - return true; } async function archiveRepository(repository) { - const res = await apiCall( + await apiCall( 'PATCH', `/repos/${repository}`, undefined, @@ -126,13 +124,11 @@ async function archiveRepository(repository) { RESOURCE_SCOPES.repositories ); - if (res.status !== 200) return false; - return true; } async function deleteCodespace(codespace) { - const res = await apiCall( + await apiCall( 'DELETE', `/user/codespaces/${codespace}`, undefined, @@ -140,21 +136,11 @@ async function deleteCodespace(codespace) { RESOURCE_SCOPES.codespaces ); - if (res.status !== 204) return false; - return true; } async function deleteGist(gist) { - const res = await apiCall( - 'DELETE', - `/gists/${gist}`, - undefined, - undefined, - RESOURCE_SCOPES.gists - ); - - if (res.status !== 204) return false; + await apiCall('DELETE', `/gists/${gist}`, undefined, undefined, RESOURCE_SCOPES.gists); return true; } @@ -184,9 +170,9 @@ async function apiCall(method, endpoint, page, data, requiredScopes = []) { try { const res = await request(query, params); - const scopes = parseScopes(res.headers) || []; + const scopes = parseScopes(res.headers); - if (!checkPermissions(scopes, requiredScopes)) throw new ScopesError(); + if (scopes && !checkPermissions(scopes, requiredScopes)) throw new ScopesError(); return res; } catch (error) { diff --git a/src/ui.js b/src/ui.js index 438c115..5ee491a 100644 --- a/src/ui.js +++ b/src/ui.js @@ -191,10 +191,7 @@ async function getRepositories() { return repositories; } catch (error) { spinner.stop(); - - if (error instanceof Github.AuthError || error instanceof Github.ScopesError) { - throw error; - } + throw error; } } @@ -212,10 +209,7 @@ async function getCodespaces() { return codespaces; } catch (error) { spinner.stop(); - - if (error instanceof Github.AuthError || error instanceof Github.ScopesError) { - throw error; - } + throw error; } } @@ -253,104 +247,104 @@ function printGistsFound(count) { return `${count} ${count === 1 ? 'gist' : 'gists'} found.`; } -async function deleteRepositories(repositories) { - const deletedRepos = []; +function isTokenError(error) { + return error instanceof Github.AuthError || error instanceof Github.ScopesError; +} + +function getErrorMessage(error) { + return error.response?.data?.message || error.message; +} - for (const repo of repositories) { +async function processItems(items, mutate, formatProcessed) { + const processed = []; + const failed = []; + let authError; + + for (const item of items) { const spinner = ora().start(); try { - await Github.deleteRepository(repo); - deletedRepos.push(repo); + await mutate(item); + processed.push(item); - spinner.stopAndPersist({ symbol: '', text: style.strikethrough.dim(repo) }); + spinner.stopAndPersist({ symbol: '', text: formatProcessed(item) }); } catch (error) { - const message = error.response?.data?.message; + failed.push(item); + + spinner.fail(style.dim(`${item} (Oops! ${getErrorMessage(error)})`)); - spinner.fail(style.dim(`${repo} (Oops! ${message})`)); + if (isTokenError(error)) { + authError = error; + break; + } } } - if (deletedRepos.length > 0) { - printConfirmation(deletedRepos, 'repos', 'delete'); + return { processed, failed, authError }; +} + +async function deleteRepositories(repositories) { + const summary = await processItems( + repositories, + (repo) => Github.deleteRepository(repo), + (repo) => style.strikethrough.dim(repo) + ); + + if (summary.processed.length > 0) { + printConfirmation(summary.processed, 'repos', 'delete'); } else { printNoReposDeleted(); } + + return summary; } async function archiveRepositories(repositories) { - const archivedRepos = []; - - for (const repo of repositories) { - const spinner = ora().start(); - - try { - await Github.archiveRepository(repo); - archivedRepos.push(repo); - - spinner.stopAndPersist({ symbol: '', text: style.dim(repo) }); - } catch (error) { - const message = error.response?.data?.message; - - spinner.fail(style.dim(`${repo} (Oops! ${message})`)); - } - } - - if (archivedRepos.length > 0) { - printConfirmation(archivedRepos, 'repos', 'archive'); + const summary = await processItems( + repositories, + (repo) => Github.archiveRepository(repo), + (repo) => style.dim(repo) + ); + + if (summary.processed.length > 0) { + printConfirmation(summary.processed, 'repos', 'archive'); } else { printNoReposArchived(); } + + return summary; } async function deleteCodespaces(codespaces) { - const deletedCodespaces = []; - - for (const codespace of codespaces) { - const spinner = ora().start(); - - try { - await Github.deleteCodespace(codespace); - deletedCodespaces.push(codespace); - - spinner.stopAndPersist({ symbol: '', text: style.strikethrough.dim(codespace) }); - } catch (error) { - const message = error.response?.data?.message; - - spinner.fail(style.dim(`${codespace} (Oops! ${message})`)); - } - } - - if (deletedCodespaces.length > 0) { - printConfirmation(deletedCodespaces, 'codespaces', 'delete'); + const summary = await processItems( + codespaces, + (codespace) => Github.deleteCodespace(codespace), + (codespace) => style.strikethrough.dim(codespace) + ); + + if (summary.processed.length > 0) { + printConfirmation(summary.processed, 'codespaces', 'delete'); } else { printNoCodespacesDeleted(); } + + return summary; } async function deleteGists(gists) { - const deletedGists = []; - - for (const gist of gists) { - const spinner = ora().start(); - - try { - await Github.deleteGist(gist); - deletedGists.push(gist); - - spinner.stopAndPersist({ symbol: '', text: style.strikethrough.dim(gist) }); - } catch (error) { - const message = error.response?.data?.message || error.message; - - spinner.fail(style.dim(`${gist} (Oops! ${message})`)); - } - } - - if (deletedGists.length > 0) { - printConfirmation(deletedGists, 'gists', 'delete'); + const summary = await processItems( + gists, + (gist) => Github.deleteGist(gist), + (gist) => style.strikethrough.dim(gist) + ); + + if (summary.processed.length > 0) { + printConfirmation(summary.processed, 'gists', 'delete'); } else { printNoGistsDeleted(); } + + return summary; } async function promptConfirm(count, type, action) { diff --git a/test/test.js b/test/test.js index 42e4a4b..fee3cd6 100644 --- a/test/test.js +++ b/test/test.js @@ -2,6 +2,7 @@ import assert from 'assert'; import { describe, it } from 'node:test'; import codespacesCommand from '../src/commands/codespaces.js'; +import CommandSummary from '../src/command-summary.js'; import gistsCommand from '../src/commands/gists.js'; import Github from '../src/github.js'; import reposCommand from '../src/commands/repos.js'; @@ -16,12 +17,28 @@ async function withUiStubs(stubs, callback) { Object.assign(UI, stubs); try { - await callback(); + return await callback(); } finally { Object.assign(UI, originalFunctions); } } +async function withGithubStubs(stubs, callback) { + const originalFunctions = Object.fromEntries( + Object.keys(stubs).map((name) => [name, Github[name]]) + ); + const originalLog = console.log; + Object.assign(Github, stubs); + console.log = () => {}; + + try { + return await callback(); + } finally { + console.log = originalLog; + Object.assign(Github, originalFunctions); + } +} + async function withMockGithubFetch(fetchMock, callback) { const originalFetch = globalThis.fetch; const originalToken = process.env.GITHUB_TOKEN; @@ -29,7 +46,7 @@ async function withMockGithubFetch(fetchMock, callback) { Github.setToken('test-token'); try { - await callback(); + return await callback(); } finally { globalThis.fetch = originalFetch; if (originalToken === undefined) { @@ -233,6 +250,41 @@ describe('reposCommand(options)', () => { assert.equal(reportedNoMatches, true); }); + + it('should propagate repository listing failures without processing repositories', async () => { + const listingError = new Error('Internal Server Error'); + const options = RepoOptions.parse(['--list', 'adrianmg/demo-one', '--force']); + + await withUiStubs( + { + getRepositories: async () => { + throw listingError; + }, + promptSelectRepositories: async () => + assert.fail('repositories should not be selected'), + deleteRepositories: async () => assert.fail('repositories should not be deleted'), + }, + async () => { + await assert.rejects(reposCommand(options), (error) => error === listingError); + } + ); + }); + + it('should return the deletion summary reported by the UI', async () => { + const summary = { processed: ['adrianmg/demo-two'], failed: [] }; + const options = RepoOptions.parse(['--list', 'adrianmg/demo-two', '--force']); + + const result = await withUiStubs( + { + getRepositories: async () => repositories, + printReposMatched: () => {}, + deleteRepositories: async () => summary, + }, + async () => reposCommand(options) + ); + + assert.deepEqual(result, summary); + }); }); describe('gistsCommand()', () => { @@ -325,6 +377,128 @@ describe('codespacesCommand()', () => { assert.deepEqual(confirmation, [1, 'codespaces', 'delete']); assert.deepEqual(deletedCodespaces, ['codespace-one']); }); + + it('should propagate codespace listing failures', async () => { + const listingError = new Error('Network request failed'); + + await withUiStubs( + { + getCodespaces: async () => { + throw listingError; + }, + promptSelectCodespaces: async () => + assert.fail('codespaces should not be selected'), + deleteCodespaces: async () => assert.fail('codespaces should not be deleted'), + }, + async () => { + await assert.rejects(codespacesCommand(), (error) => error === listingError); + } + ); + }); + + it('should return the deletion summary reported by the UI', async () => { + const summary = { processed: [], failed: ['codespace-one'] }; + + const result = await withUiStubs( + { + getCodespaces: async () => [{ name: 'codespace-one' }], + promptSelectCodespaces: async () => ({ codespaces: ['codespace-one'] }), + promptConfirm: async () => ({ confirm: 'Yes' }), + deleteCodespaces: async () => summary, + }, + codespacesCommand + ); + + assert.deepEqual(result, summary); + }); +}); + +describe('UI mutation batches', () => { + it('should report a failed repository and keep processing the batch', async () => { + const attempts = []; + const failure = new Error('Request failed'); + failure.response = { data: { message: 'Must have admin rights' } }; + + const summary = await withGithubStubs( + { + deleteRepository: async (repository) => { + attempts.push(repository); + if (repository === 'adrianmg/demo-two') throw failure; + + return true; + }, + }, + async () => + UI.deleteRepositories([ + 'adrianmg/demo-one', + 'adrianmg/demo-two', + 'adrianmg/demo-three', + ]) + ); + + assert.deepEqual(attempts, [ + 'adrianmg/demo-one', + 'adrianmg/demo-two', + 'adrianmg/demo-three', + ]); + assert.deepEqual(summary.processed, ['adrianmg/demo-one', 'adrianmg/demo-three']); + assert.deepEqual(summary.failed, ['adrianmg/demo-two']); + assert.equal(summary.authError, undefined); + }); + + it('should abort the batch on a token-wide failure without throwing', async () => { + const attempts = []; + const scopesError = new Github.ScopesError(); + + const summary = await withGithubStubs( + { + deleteCodespace: async (codespace) => { + attempts.push(codespace); + if (codespace === 'codespace-two') throw scopesError; + + return true; + }, + }, + async () => + UI.deleteCodespaces(['codespace-one', 'codespace-two', 'codespace-three']) + ); + + assert.deepEqual(attempts, ['codespace-one', 'codespace-two']); + assert.deepEqual(summary.processed, ['codespace-one']); + assert.deepEqual(summary.failed, ['codespace-two']); + assert.equal(summary.authError, scopesError); + }); +}); + +describe('CommandSummary.resolveOutcome(summary)', () => { + it('should keep a successful exit status and cached credentials', () => { + assert.deepEqual(CommandSummary.resolveOutcome(CommandSummary.create()), { + invalidateConfig: false, + exitCode: 0, + }); + assert.deepEqual(CommandSummary.resolveOutcome(undefined), { + invalidateConfig: false, + exitCode: 0, + }); + }); + + it('should fail the process when any mutation failed', () => { + assert.deepEqual( + CommandSummary.resolveOutcome({ processed: ['one'], failed: ['two'] }), + { invalidateConfig: false, exitCode: 1 } + ); + }); + + it('should invalidate cached credentials after a token-wide failure', () => { + assert.deepEqual( + CommandSummary.resolveOutcome({ + processed: [], + failed: ['one'], + authError: new Github.AuthError(), + }), + { invalidateConfig: true, exitCode: 1 } + ); + }); }); describe('Utils.uiGetLabel(type, count)', () => { @@ -418,6 +592,65 @@ describe('Github gist API', () => { }); }); +describe('Github mutation requests', () => { + it('should accept the accepted status returned by codespace deletion', async () => { + let request; + + await withMockGithubFetch( + async (url, options) => { + request = { url: new URL(url), method: options.method }; + return githubResponse({}, 202); + }, + async () => { + assert.equal(await Github.deleteCodespace('codespace-one'), true); + } + ); + + assert.equal(request.method, 'DELETE'); + assert.equal(request.url.pathname, '/user/codespaces/codespace-one'); + }); + + it('should map an unauthorized response to an authentication error', async () => { + await withMockGithubFetch( + async () => githubResponse({ message: 'Bad credentials' }, 401), + async () => { + await assert.rejects( + Github.deleteRepository('adrianmg/example'), + Github.AuthError + ); + } + ); + }); + + it('should preserve a generic error when the request never reaches GitHub', async () => { + const networkError = new TypeError('fetch failed'); + + await withMockGithubFetch( + async () => { + throw networkError; + }, + async () => { + await assert.rejects(Github.deleteRepository('adrianmg/example'), (error) => { + assert.equal(error instanceof Github.AuthError, false); + assert.equal(error instanceof Github.ScopesError, false); + assert.match(error.message, /fetch failed/); + + return true; + }); + } + ); + }); + + it('should accept a successful DELETE response with status 204 and no x-oauth-scopes header', async () => { + await withMockGithubFetch( + async () => new Response(null, { status: 204 }), + async () => { + assert.equal(await Github.deleteRepository('adrianmg/example'), true); + } + ); + }); +}); + describe('Github endpoint permissions', () => { it('should not require unrelated Codespaces access to list repositories', async () => { await withMockGithubFetch(