Skip to content
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
3 changes: 2 additions & 1 deletion src/cli.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Command } from 'commander';
import { createRequire } from 'module';
import { setGlobalOptions, setGlobalUser } from './lib/output.js';
import { ExitCode } from './lib/exitCodes.js';
import { loadConfig } from './lib/config.js';
import { registerGitCommands } from './services/git/commands.js';
import { registerJiraCommands } from './services/jira/commands.js';
Expand Down Expand Up @@ -63,5 +64,5 @@ Services:

program.parseAsync(process.argv).catch((err: unknown) => {
process.stderr.write(`Fatal: ${err instanceof Error ? err.message : String(err)}\n`);
process.exit(1);
process.exit(ExitCode.GENERAL_ERROR);
});
16 changes: 16 additions & 0 deletions src/lib/exitCodes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export const ExitCode = {
SUCCESS: 0,
GENERAL_ERROR: 1,
USAGE_ERROR: 2,
NETWORK_ERROR: 69, // EX_UNAVAILABLE from sysexits.h
AUTH_ERROR: 77, // EX_NOPERM from sysexits.h
CONFIG_ERROR: 78, // EX_CONFIG from sysexits.h
} as const;

export type ExitCode = (typeof ExitCode)[keyof typeof ExitCode];

export function exitCodeFromStatus(httpStatus: number): ExitCode {
if (httpStatus === 401 || httpStatus === 403) return ExitCode.AUTH_ERROR;
if (httpStatus === 0) return ExitCode.NETWORK_ERROR;
return ExitCode.GENERAL_ERROR;
}
35 changes: 29 additions & 6 deletions src/lib/http.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { ResolvedConfig } from '../types/config.js';
import { PncliError } from './errors.js';
import { ExitCode } from './exitCodes.js';
import { log } from './output.js';

export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
Expand Down Expand Up @@ -73,8 +74,28 @@ async function request<T>(
try {
const body = await response.text();
const parsed = JSON.parse(body);
if (parsed.message) message = parsed.message;
else if (parsed.errors?.[0]?.message) message = parsed.errors[0].message;
const parts: string[] = [];
// Jira: errorMessages is string[]
if (Array.isArray(parsed.errorMessages)) {
parts.push(...(parsed.errorMessages as string[]).filter(Boolean));
}
// errors as object map (Jira: Record<string, string>)
if (parsed.errors && typeof parsed.errors === 'object' && !Array.isArray(parsed.errors)) {
for (const [field, msg] of Object.entries(parsed.errors as Record<string, string>)) {
parts.push(`${field}: ${msg}`);
}
}
// errors as array of objects with message field (other APIs)
if (Array.isArray(parsed.errors)) {
for (const e of parsed.errors as Array<{ message?: string }>) {
if (e?.message) parts.push(e.message);
}
}
// Generic APIs: { message: "..." }
if (parts.length === 0 && parsed.message) {
parts.push(String(parsed.message));
}
if (parts.length > 0) message = parts.join('; ');
} catch {
// ignore parse errors
}
Expand Down Expand Up @@ -106,7 +127,8 @@ export class HttpClient {
return {
'Authorization': `Bearer ${apiToken}`,
'Content-Type': 'application/json',
'Accept': 'application/json'
'Accept': 'application/json',
'Connection': 'close'
};
}

Expand All @@ -116,7 +138,8 @@ export class HttpClient {
return {
'Authorization': `Bearer ${pat}`,
'Content-Type': 'application/json',
'Accept': 'application/json'
'Accept': 'application/json',
'Connection': 'close'
};
}

Expand All @@ -139,7 +162,7 @@ export class HttpClient {
const safeHeaders = { ...headers, Authorization: '[REDACTED]' };
process.stderr.write(`DRY RUN: ${init.method} ${url}\nHeaders: ${JSON.stringify(safeHeaders, null, 2)}\n`);
if (opts.body) process.stderr.write(`Body: ${JSON.stringify(opts.body, null, 2)}\n`);
process.exit(0);
process.exit(ExitCode.SUCCESS);
}

return request<T>(url, init, opts.timeoutMs ?? 30000);
Expand All @@ -164,7 +187,7 @@ export class HttpClient {
const safeHeaders = { ...headers, Authorization: '[REDACTED]' };
process.stderr.write(`DRY RUN: ${init.method} ${url}\nHeaders: ${JSON.stringify(safeHeaders, null, 2)}\n`);
if (opts.body) process.stderr.write(`Body: ${JSON.stringify(opts.body, null, 2)}\n`);
process.exit(0);
process.exit(ExitCode.SUCCESS);
}

return request<T>(url, init, opts.timeoutMs ?? 30000);
Expand Down
4 changes: 3 additions & 1 deletion src/lib/output.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import chalk from 'chalk';
import type { Meta, SuccessEnvelope, ErrorEnvelope, ErrorDetail } from '../types/common.js';
import { PncliError } from './errors.js';
import { ExitCode, exitCodeFromStatus } from './exitCodes.js';

let globalOptions = { pretty: false, verbose: false };
let globalUser: { email: string | undefined; userId: string | undefined } = { email: undefined, userId: undefined };
Expand Down Expand Up @@ -62,7 +63,8 @@ export function fail(
(globalOptions.pretty ? JSON.stringify(envelope, null, 2) : JSON.stringify(envelope)) + '\n'
);

process.exit(1);
const exitCode = err instanceof PncliError ? exitCodeFromStatus(err.status) : ExitCode.GENERAL_ERROR;
process.exit(exitCode);
}

export function log(message: string): void {
Expand Down
9 changes: 5 additions & 4 deletions src/services/config/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
getGlobalConfigPath
} from '../../lib/config.js';
import { success, fail, warn } from '../../lib/output.js';
import { ExitCode } from '../../lib/exitCodes.js';
import fs from 'fs';

export function registerConfigCommands(program: Command): void {
Expand All @@ -30,7 +31,7 @@ export function registerConfigCommands(program: Command): void {
// Handle prompt cancellation (Ctrl+C) gracefully
if (err instanceof Error && err.message.includes('User force closed')) {
process.stderr.write('\nSetup cancelled.\n');
process.exit(1);
process.exit(ExitCode.GENERAL_ERROR);
}
fail(err, 'config', 'init', start);
}
Expand Down Expand Up @@ -127,7 +128,7 @@ async function initGlobalConfig(start: number): Promise<void> {

if (!confirmed) {
process.stderr.write('Aborted.\n');
process.exit(0);
process.exit(ExitCode.SUCCESS);
}

writeGlobalConfig({
Expand Down Expand Up @@ -185,7 +186,7 @@ async function initRepoConfig(start: number): Promise<void> {

if (!confirmed) {
process.stderr.write('Aborted.\n');
process.exit(0);
process.exit(ExitCode.SUCCESS);
}

// Warn if .pncli.json already exists
Expand All @@ -196,7 +197,7 @@ async function initRepoConfig(start: number): Promise<void> {
});
if (!overwrite) {
process.stderr.write('Aborted.\n');
process.exit(0);
process.exit(ExitCode.SUCCESS);
}
}

Expand Down
Loading