diff --git a/CODEBASE.md b/CODEBASE.md index 626b8bd..dafb275 100644 --- a/CODEBASE.md +++ b/CODEBASE.md @@ -181,7 +181,8 @@ don't duplicate it here. `withCaseInsensitiveChoices`, `withUnvalidatedChoices`. - **`progress.ts`** — `ProgressTracker` JSONL event writer (`--progress-jsonl`). - **`dates.ts`** — `formatRelativeDate`, `parseDate`; **`input.ts`** — - `readStdin`, `openEditor`; **`validation.ts`** — `validateNonEmptyName`; + `readContent` / `readStdinLines` (explicit `--stdin`, via cli-core's + `readStdin`), `openEditor`; **`validation.ts`** — `validateNonEmptyName`; **`update.ts`** — `fetchLatestVersion`, `getConfiguredUpdateChannel`; **`errors.ts`** — `CliError(code, message, hints?)`, `ErrorCode` union, `isInsufficientScope`. diff --git a/docs/SPEC.md b/docs/SPEC.md index 2a17297..c6fffc1 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -179,16 +179,17 @@ Post a comment to a thread. Arguments: - `thread-ref` - Thread ID or Comms URL -- `content` - Comment content (optional if using stdin or editor) +- `content` - Comment content (optional if using `--stdin` or the editor) -Content input priority: +Content input: -1. Stdin (if piped: `echo "text" | tdc thread reply id:CbT8n2Kp4Qx6Rz9Lm3Va`) -2. Argument (if provided) -3. Opens `$EDITOR` (if neither stdin nor argument) +1. Argument (if provided) +2. Stdin, only with `--stdin` (`echo "text" | tdc thread reply id:CbT8n2Kp4Qx6Rz9Lm3Va --stdin`). Passing both an argument and `--stdin` is an error +3. Opens `$EDITOR` (if neither an argument nor `--stdin`) Options: +- `--stdin` - Read content from stdin - `--dry-run` - Show what would be posted without posting Output: @@ -255,12 +256,13 @@ Send a message in a conversation. Arguments: - `conversation-ref` - Conversation ID or Comms URL -- `content` - Message content (optional if using stdin or editor) +- `content` - Message content (optional if using `--stdin` or the editor) -Content input: Same as `tdc thread reply` (stdin → arg → $EDITOR) +Content input: Same as `tdc thread reply` (arg or `--stdin`, else $EDITOR) Options: +- `--stdin` - Read content from stdin - `--dry-run` - Show what would be sent without sending Output: @@ -306,12 +308,13 @@ Edit a conversation message. Arguments: - `message-ref` - Message ID or Comms URL -- `content` - New message content (optional if using stdin or editor) +- `content` - New message content (optional if using `--stdin` or the editor) -Content input: Same as `tdc thread reply` (stdin → arg → $EDITOR) +Content input: Same as `tdc thread reply` (arg or `--stdin`, else $EDITOR) Options: +- `--stdin` - Read content from stdin - `--dry-run` - Show what would be updated without updating #### `tdc msg delete ` @@ -499,7 +502,7 @@ tdc thread view https://comms.todoist.com/a/12345/ch/CbC8n2Kp4Qx6Rz9Lm3Va/t/CbT8 # Reply to a thread tdc thread reply id:CbT8n2Kp4Qx6Rz9Lm3Va "Great idea!" -echo "Multiline\nreply" | tdc thread reply id:CbT8n2Kp4Qx6Rz9Lm3Va +echo "Multiline\nreply" | tdc thread reply id:CbT8n2Kp4Qx6Rz9Lm3Va --stdin tdc thread reply id:CbT8n2Kp4Qx6Rz9Lm3Va # opens $EDITOR # Mark thread as done @@ -557,6 +560,6 @@ tdc search "project" --ndjson 4. **Batch Operations**: Use `client.batch()` for parallel API calls when fetching related data (channels, users for display) -5. **Content Input**: For reply commands, check stdin first, then arg, then spawn $EDITOR +5. **Content Input**: For reply commands, take the arg or, with `--stdin`, piped stdin (never both), else spawn $EDITOR 6. **Markdown Rendering**: Defer library choice. Start with raw markdown, add terminal rendering later based on real usage diff --git a/package-lock.json b/package-lock.json index f913b77..6a90bc8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,7 +10,7 @@ "hasInstallScript": true, "license": "MIT", "dependencies": { - "@doist/cli-core": "1.7.2", + "@doist/cli-core": "1.8.0", "@doist/comms-sdk": "3.11.0", "@pnpm/tabtab": "0.5.4", "chalk": "5.6.2", @@ -136,9 +136,9 @@ } }, "node_modules/@doist/cli-core": { - "version": "1.7.2", - "resolved": "https://registry.npmjs.org/@doist/cli-core/-/cli-core-1.7.2.tgz", - "integrity": "sha512-3K0M2OoSO5BdCSDhdHh+AQHqo5/uCBDcqH8LaWjINNRw/abMqZrxbhagQqoVkeTjWE5VDNqUuiKLaIHt4h+Bag==", + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@doist/cli-core/-/cli-core-1.8.0.tgz", + "integrity": "sha512-ffSDDCElKLIAsAwktOf8/hTRe+dmCnLSAeFbq8FRsmybI+51TDLUuqTMBgH1o4xPecvh7wYwIH0aZPCdfVkR9g==", "license": "MIT", "dependencies": { "chalk": "6.0.1", diff --git a/package.json b/package.json index 62a465e..461d08a 100644 --- a/package.json +++ b/package.json @@ -54,7 +54,7 @@ "CHANGELOG.md" ], "dependencies": { - "@doist/cli-core": "1.7.2", + "@doist/cli-core": "1.8.0", "@doist/comms-sdk": "3.11.0", "@pnpm/tabtab": "0.5.4", "chalk": "5.6.2", diff --git a/skills/comms-cli/SKILL.md b/skills/comms-cli/SKILL.md index 8f31d8c..fbf8709 100644 --- a/skills/comms-cli/SKILL.md +++ b/skills/comms-cli/SKILL.md @@ -123,10 +123,10 @@ tdc thread undone --yes # Unarchive thread (move it back to your i tdc thread undone --yes --json # Unarchive and return status as JSON tdc thread mark-read # Mark a thread read tdc thread mark-read --yes # Mark multiple threads read -printf "id:CbT8n2Kp4Qx6Rz9Lm3Va\nid:CbT9m4Qr7Vz2Nx8Lp5Sa\n" | tdc thread mark-read --dry-run # Preview bulk mark-read from stdin +printf "id:CbT8n2Kp4Qx6Rz9Lm3Va\nid:CbT9m4Qr7Vz2Nx8Lp5Sa\n" | tdc thread mark-read --stdin --dry-run # Preview bulk mark-read from stdin tdc thread mark-unread # Mark a whole thread unread; inverse of mark-read tdc thread mark-unread --from # Mark unread from that comment onward (single thread only) -tdc thread mark-unread --yes # Mark multiple threads unread (also accepts refs on stdin) +tdc thread mark-unread --yes # Mark multiple threads unread (also accepts refs on stdin with --stdin) tdc thread mute # Mute thread for 60 minutes (default) tdc thread mute --minutes 480 # Mute for custom duration tdc thread mute --json # Mute and return { id, mutedUntil } as JSON @@ -140,7 +140,7 @@ tdc thread rename "New title" # Rename a thread (change its title) tdc thread rename "New title" --json # Rename and return { id, title } as JSON tdc thread rename "New title" --json --full # Rename and return full thread as JSON tdc thread update "New body" # Update a thread's body (the first post) -echo "New body" | tdc thread update # Update body from stdin +echo "New body" | tdc thread update --stdin # Update body from stdin tdc thread update "New body" --dry-run # Preview without updating tdc thread update "New body" --json # Update and return { id, content } as JSON tdc thread update "New body" --json --full # Update and return full thread as JSON @@ -412,8 +412,8 @@ Translate old `twist.com` URLs to their Comms equivalents (e.g. for rewriting bo # Comma-separated list as an argument (token from the environment) TWIST_AUTH_TOKEN="$(tw auth token view)" tdc migrate urls "https://twist.com/a/1/ch/2/t/3,https://twist.com/a/1/ch/2/t/4" -# Or pipe URLs via stdin (comma- or newline-separated) -cat old-urls.txt | TWIST_AUTH_TOKEN="$(tw auth token view)" tdc migrate urls +# Or pipe URLs in with --stdin (comma- or newline-separated) +cat old-urls.txt | TWIST_AUTH_TOKEN="$(tw auth token view)" tdc migrate urls --stdin # --twist-token overrides the env var (visible in process lists — prefer the env var) tdc migrate urls "https://twist.com/a/1/ch/2/t/3" --twist-token @@ -467,20 +467,20 @@ Commands accept flexible references: ## Piping Input -Commands that accept content (`thread create`, `thread reply`, `comment update`, `conversation reply`, `msg update`) auto-detect piped stdin: +Commands that accept content (`thread create`, `thread reply`, `thread update`, `comment update`, `conversation reply`, `msg update`) read it from stdin only with `--stdin`; without the flag, piped input is ignored. `--stdin` can't be combined with a content argument, and with nothing piped in (stdin is a terminal) it fails with `STDIN_IS_TTY` instead of waiting: ```bash -cat notes.md | tdc thread reply -tdc thread create "Title" < body.md -echo "Quick reply" | tdc conversation reply +cat notes.md | tdc thread reply --stdin +tdc thread create "Title" --stdin < body.md +echo "Quick reply" | tdc conversation reply --stdin ``` -If no content argument is provided and no stdin is piped, the CLI opens `$EDITOR` for interactive input. In non-TTY environments (e.g. when called by an agent or in a pipeline), the editor is automatically skipped and the command fails fast with an actionable error message. Use `--non-interactive` to force this behavior even in a TTY, or `--interactive` to override auto-detection. +If neither a content argument nor `--stdin` is given, the CLI opens `$EDITOR` for interactive input. In non-TTY environments (e.g. when called by an agent or in a pipeline), the editor is automatically skipped and the command fails fast with an actionable error message. Use `--non-interactive` to force this behavior even in a TTY, or `--interactive` to override auto-detection. -`tdc thread mark-read` and `tdc thread mark-unread` also accept thread refs from stdin, one per line: +`tdc thread mark-read` and `tdc thread mark-unread` read thread refs from stdin with `--stdin`, one per line (`#` lines are skipped), added to any refs passed as arguments: ```bash -printf "id:CbT8n2Kp4Qx6Rz9Lm3Va\nid:CbT9m4Qr7Vz2Nx8Lp5Sa\n" | tdc thread mark-read --yes +printf "id:CbT8n2Kp4Qx6Rz9Lm3Va\nid:CbT9m4Qr7Vz2Nx8Lp5Sa\n" | tdc thread mark-read --stdin --yes ``` ## Common Workflows diff --git a/src/commands/comment/comment.test.ts b/src/commands/comment/comment.test.ts index fa9abb5..70e7819 100644 --- a/src/commands/comment/comment.test.ts +++ b/src/commands/comment/comment.test.ts @@ -1,4 +1,4 @@ -import { captureConsole, createTestProgram } from '@doist/cli-core/testing' +import { captureConsole, createTestProgram, mockStdin } from '@doist/cli-core/testing' import { beforeEach, describe, expect, it, vi } from 'vitest' const apiMocks = vi.hoisted(() => ({ @@ -14,8 +14,8 @@ vi.mock('../../lib/api.js', async (importOriginal) => ({ getCommsClient: apiMocks.getCommsClient, })) -vi.mock('../../lib/input.js', () => ({ - readStdin: vi.fn().mockResolvedValue(''), +vi.mock('../../lib/input.js', async (importOriginal) => ({ + ...(await importOriginal()), openEditor: vi.fn().mockResolvedValue(''), })) @@ -25,7 +25,6 @@ vi.mock('../../lib/markdown.js', () => ({ vi.mock('chalk') -import { readStdin } from '../../lib/input.js' import { registerCommentCommand } from './index.js' function createCommentFixture(id: string, creator = 1) { @@ -191,13 +190,13 @@ describe('comment update', () => { }) it('reads content from stdin', async () => { - vi.mocked(readStdin).mockResolvedValueOnce('Content from stdin') + mockStdin('Content from stdin') const client = createClient() apiMocks.getCommsClient.mockResolvedValue(client) const program = createProgram() captureConsole('log') - await program.parseAsync(['node', 'tdc', 'comment', 'update', '300']) + await program.parseAsync(['node', 'tdc', 'comment', 'update', '300', '--stdin']) expect(client.comments.updateComment).toHaveBeenCalledWith({ id: '300', diff --git a/src/commands/comment/index.ts b/src/commands/comment/index.ts index 2a4c1eb..69e4aec 100644 --- a/src/commands/comment/index.ts +++ b/src/commands/comment/index.ts @@ -33,6 +33,7 @@ Examples: comment .command('update [content]') .description('Update a thread comment') + .option('--stdin', 'Read content from stdin') .option('--dry-run', 'Show what would be updated without updating') .option('--json', 'Output updated comment as JSON') .option('--full', 'Include all fields in JSON output') @@ -41,7 +42,7 @@ Examples: ` Examples: tdc comment update id:CbM8n2Kp4Qx6Rz9Lm3Va "Updated text" - echo "New content" | tdc comment update id:CbM8n2Kp4Qx6Rz9Lm3Va + echo "New content" | tdc comment update id:CbM8n2Kp4Qx6Rz9Lm3Va --stdin tdc comment update id:CbM8n2Kp4Qx6Rz9Lm3Va "Fixed" --json`, ) .action(updateComment) diff --git a/src/commands/comment/update.ts b/src/commands/comment/update.ts index 633742a..991b675 100644 --- a/src/commands/comment/update.ts +++ b/src/commands/comment/update.ts @@ -1,11 +1,11 @@ import { getCommsClient } from '../../lib/api.js' import { CliError } from '../../lib/errors.js' -import { openEditor, readStdin } from '../../lib/input.js' -import type { MutationOptions } from '../../lib/options.js' +import { openEditor, readContent } from '../../lib/input.js' +import type { MutationOptions, StdinOptions } from '../../lib/options.js' import { formatJson, printDryRun } from '../../lib/output.js' import { resolveCommentId } from '../../lib/refs.js' -type UpdateOptions = MutationOptions +type UpdateOptions = MutationOptions & StdinOptions export async function updateComment( ref: string, @@ -14,17 +14,14 @@ export async function updateComment( ): Promise { const commentId = resolveCommentId(ref) - let newContent = await readStdin() - if (!newContent && content) { - newContent = content - } + let newContent = await readContent(content, options) if (!newContent) { newContent = await openEditor() } if (!newContent || newContent.trim() === '') { throw new CliError( 'MISSING_CONTENT', - 'No content provided. Pass content as an argument or pipe via stdin.', + 'No content provided. Pass content as an argument, or pipe it in with --stdin.', ) } diff --git a/src/commands/conversation/conversation.test.ts b/src/commands/conversation/conversation.test.ts index 3c290ac..1577165 100644 --- a/src/commands/conversation/conversation.test.ts +++ b/src/commands/conversation/conversation.test.ts @@ -5,6 +5,7 @@ import { captureConsole, createTestProgram, describeEmptyMachineOutput, + mockStdin, } from '@doist/cli-core/testing' import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' import { clearWorkspaceUserCache } from '../../lib/api.js' @@ -35,8 +36,8 @@ vi.mock('../../lib/markdown.js', () => ({ vi.mock('chalk') -vi.mock('../../lib/input.js', () => ({ - readStdin: vi.fn().mockResolvedValue(''), +vi.mock('../../lib/input.js', async (importOriginal) => ({ + ...(await importOriginal()), openEditor: vi.fn().mockResolvedValue(''), })) @@ -1369,6 +1370,24 @@ describe('conversation undone', () => { }) }) +describe('conversation reply --stdin', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('reads the message from stdin with --stdin', async () => { + const { client, program } = setupFileTest() + captureConsole('log') + mockStdin('Piped message\n') + + await program.parseAsync(['node', 'tdc', 'conversation', 'reply', '42', '--stdin']) + + expect(client.conversationMessages.createMessage).toHaveBeenCalledWith( + expect.objectContaining({ conversationId: '42', content: 'Piped message' }), + ) + }) +}) + describe('conversation reply --file', () => { const files = useFileFixtures('tdc-convo-reply-', 'photo.png', 'doc.pdf') diff --git a/src/commands/conversation/helpers.ts b/src/commands/conversation/helpers.ts index 455573d..2ee4df5 100644 --- a/src/commands/conversation/helpers.ts +++ b/src/commands/conversation/helpers.ts @@ -6,7 +6,12 @@ import { formatRelativeDate } from '../../lib/dates.js' import { CliError } from '../../lib/errors.js' import { isAccessible } from '../../lib/global-args.js' import { renderMarkdown } from '../../lib/markdown.js' -import type { MutationOptions, PaginatedViewOptions, ViewOptions } from '../../lib/options.js' +import type { + MutationOptions, + PaginatedViewOptions, + StdinOptions, + ViewOptions, +} from '../../lib/options.js' import { colors, formatJson, formatNdjson } from '../../lib/output.js' export type UnreadOptions = ViewOptions & { workspace?: string } @@ -40,7 +45,7 @@ export type ConversationRenderOptions = { export type ConversationState = 'active' | 'all' | 'archived' -export type ReplyOptions = MutationOptions & { file?: string[] } +export type ReplyOptions = MutationOptions & StdinOptions & { file?: string[] } export type MuteOptions = MutationOptions & { minutes?: string } diff --git a/src/commands/conversation/index.ts b/src/commands/conversation/index.ts index 86f0a59..af4f63a 100644 --- a/src/commands/conversation/index.ts +++ b/src/commands/conversation/index.ts @@ -131,6 +131,7 @@ Examples: .command('reply [content]') .description('Send a message in a conversation') .option('--file ', 'Attach a file (repeatable; content optional)', collect, []) + .option('--stdin', 'Read content from stdin') .option('--dry-run', 'Show what would be sent without sending') .option('--json', 'Output sent message as JSON') .option('--full', 'Include all fields in JSON output') @@ -139,7 +140,7 @@ Examples: ` Examples: tdc conversation reply id:CbV8n2Kp4Qx6Rz9Lm3Va "Hello!" - echo "Message body" | tdc conversation reply id:CbV8n2Kp4Qx6Rz9Lm3Va + echo "Message body" | tdc conversation reply id:CbV8n2Kp4Qx6Rz9Lm3Va --stdin tdc conversation reply id:CbV8n2Kp4Qx6Rz9Lm3Va "Update" --json tdc conversation reply id:CbV8n2Kp4Qx6Rz9Lm3Va "See attached" --file ./photo.jpg`, ) diff --git a/src/commands/conversation/reply.ts b/src/commands/conversation/reply.ts index e173be7..4947991 100644 --- a/src/commands/conversation/reply.ts +++ b/src/commands/conversation/reply.ts @@ -2,7 +2,7 @@ import chalk from 'chalk' import { getCommsClient } from '../../lib/api.js' import { uploadAttachments, validateAttachmentFiles } from '../../lib/attachments.js' import { CliError } from '../../lib/errors.js' -import { openEditor, readStdin } from '../../lib/input.js' +import { openEditor, readContent } from '../../lib/input.js' import { formatJson, printDryRun } from '../../lib/output.js' import { resolveConversationId } from '../../lib/refs.js' import type { ReplyOptions } from './helpers.js' @@ -17,10 +17,7 @@ export async function replyToConversation( const files = options.file ?? [] const hasFiles = files.length > 0 - let replyContent = await readStdin() - if (!replyContent && content) { - replyContent = content - } + let replyContent = await readContent(content, options) // A file-only message is allowed: skip the editor prompt and the empty-content guard. if (!replyContent && !hasFiles) { replyContent = await openEditor() @@ -28,7 +25,7 @@ export async function replyToConversation( if ((!replyContent || replyContent.trim() === '') && !hasFiles) { throw new CliError( 'MISSING_CONTENT', - 'No content provided. Pass content as an argument, pipe via stdin, or attach a file.', + 'No content provided. Pass content as an argument, pipe it in with --stdin, or attach a file.', ) } const messageContent = replyContent ?? '' diff --git a/src/commands/migrate/index.ts b/src/commands/migrate/index.ts index af0588d..928273f 100644 --- a/src/commands/migrate/index.ts +++ b/src/commands/migrate/index.ts @@ -8,6 +8,7 @@ export function registerMigrateCommand(program: Command): void { .command('urls [urls]') .description('Translate twist.com URLs to their Comms equivalents') .option('--twist-token ', 'Twist auth token (overrides $TWIST_AUTH_TOKEN)') + .option('--stdin', 'Read URLs from stdin (comma- or newline-separated)') .option('--json', 'Output as JSON') .option('--ndjson', 'Output as newline-delimited JSON') .addHelpText( @@ -19,7 +20,7 @@ Twist CLI (tw) is installed, you can populate it inline: Examples: TWIST_AUTH_TOKEN="$(tw auth token view)" tdc migrate urls "https://twist.com/a/1/ch/2/t/3,https://twist.com/a/1/ch/2/t/4" - cat old-urls.txt | TWIST_AUTH_TOKEN="$(tw auth token view)" tdc migrate urls + cat old-urls.txt | TWIST_AUTH_TOKEN="$(tw auth token view)" tdc migrate urls --stdin tdc migrate urls "https://twist.com/a/1/ch/2/t/3" --json # token from $TWIST_AUTH_TOKEN`, ) .action(migrateUrls) diff --git a/src/commands/migrate/migrate.test.ts b/src/commands/migrate/migrate.test.ts index 94fbcfe..d2d6961 100644 --- a/src/commands/migrate/migrate.test.ts +++ b/src/commands/migrate/migrate.test.ts @@ -1,4 +1,4 @@ -import { captureConsole, createTestProgram } from '@doist/cli-core/testing' +import { captureConsole, createTestProgram, mockStdin } from '@doist/cli-core/testing' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' const sdkMocks = vi.hoisted(() => ({ @@ -11,17 +11,8 @@ vi.mock('@doist/comms-sdk', async (importActual) => ({ fetchNewCommsUrls: sdkMocks.fetchNewCommsUrls, })) -const inputMocks = vi.hoisted(() => ({ - readStdin: vi.fn().mockResolvedValue(null), -})) - -vi.mock('../../lib/input.js', () => ({ - readStdin: inputMocks.readStdin, -})) - vi.mock('chalk') -import { readStdin } from '../../lib/input.js' import { registerMigrateCommand } from './index.js' const createProgram = () => createTestProgram(registerMigrateCommand) @@ -43,7 +34,6 @@ describe('migrate urls', () => { beforeEach(() => { vi.clearAllMocks() - inputMocks.readStdin.mockResolvedValue(null) delete process.env.TWIST_AUTH_TOKEN delete process.env.TWIST_BASE_URL process.exitCode = undefined @@ -84,8 +74,8 @@ describe('migrate urls', () => { expect(consoleSpy).toHaveBeenCalledWith(`${OLD_URL} -> ${NEW_URL}`) }) - it('reads URLs from stdin when no argument is given', async () => { - inputMocks.readStdin.mockResolvedValue(`${OLD_URL}\nhttps://twist.com/a/1/ch/2/t/4\n`) + it('reads URLs from stdin with --stdin', async () => { + const stdin = mockStdin(`${OLD_URL}\nhttps://twist.com/a/1/ch/2/t/4\n`) sdkMocks.fetchNewCommsUrls.mockResolvedValue([success(OLD_URL, NEW_URL)]) captureConsole('log') @@ -96,9 +86,10 @@ describe('migrate urls', () => { 'urls', '--twist-token', 'flag-token', + '--stdin', ]) - expect(readStdin).toHaveBeenCalled() + expect(stdin).toHaveBeenCalled() expect(sdkMocks.fetchNewCommsUrls).toHaveBeenCalledWith( expect.objectContaining({ oldUrls: [OLD_URL, 'https://twist.com/a/1/ch/2/t/4'], @@ -141,6 +132,43 @@ describe('migrate urls', () => { expect(sdkMocks.fetchNewCommsUrls).not.toHaveBeenCalled() }) + it('ignores piped URLs without --stdin', async () => { + mockStdin(`${OLD_URL}\n`) + + await expect( + createProgram().parseAsync([ + 'node', + 'tdc', + 'migrate', + 'urls', + '--twist-token', + 'flag-token', + ]), + ).rejects.toHaveProperty('code', 'MISSING_CONTENT') + expect(sdkMocks.fetchNewCommsUrls).not.toHaveBeenCalled() + }) + + it('errors with CONFLICTING_OPTIONS for a URL argument plus --stdin', async () => { + mockStdin(`${OLD_URL}\n`) + + await expect( + createProgram().parseAsync([ + 'node', + 'tdc', + 'migrate', + 'urls', + OLD_URL, + '--stdin', + '--twist-token', + 'flag-token', + ]), + ).rejects.toMatchObject({ + code: 'CONFLICTING_OPTIONS', + message: 'Pass URLs as an argument or with --stdin, not both.', + }) + expect(sdkMocks.fetchNewCommsUrls).not.toHaveBeenCalled() + }) + it('emits structured JSON with --json', async () => { sdkMocks.fetchNewCommsUrls.mockResolvedValue([ success(OLD_URL, NEW_URL), diff --git a/src/commands/migrate/urls.ts b/src/commands/migrate/urls.ts index 222ccf6..d4dc078 100644 --- a/src/commands/migrate/urls.ts +++ b/src/commands/migrate/urls.ts @@ -1,10 +1,11 @@ import { type CommsRequestError, fetchNewCommsUrls } from '@doist/comms-sdk' import { CliError } from '../../lib/errors.js' -import { readStdin } from '../../lib/input.js' +import { readContent } from '../../lib/input.js' +import type { StdinOptions } from '../../lib/options.js' import { colors, formatJson, formatNdjson } from '../../lib/output.js' import { withSpinner } from '../../lib/spinner.js' -type MigrateUrlsOptions = { +type MigrateUrlsOptions = StdinOptions & { twistToken?: string json?: boolean ndjson?: boolean @@ -59,13 +60,11 @@ export async function migrateUrls( ]) } - // readStdin() waits briefly for the first byte then reads to end, so an open - // but empty stdin (CI, spawned children) raises MISSING_CONTENT instead of hanging. - const rawInput = urlsArg ?? (await readStdin()) + const rawInput = await readContent(urlsArg, options, 'URLs') const oldUrls = rawInput ? parseUrls(rawInput) : [] if (oldUrls.length === 0) { throw new CliError('MISSING_CONTENT', 'No URLs provided.', [ - 'Pass a comma-separated list as an argument, or pipe URLs via stdin.', + 'Pass a comma-separated list as an argument, or pipe URLs in with --stdin.', ]) } diff --git a/src/commands/msg/index.ts b/src/commands/msg/index.ts index 7ab8d43..b354ad5 100644 --- a/src/commands/msg/index.ts +++ b/src/commands/msg/index.ts @@ -32,6 +32,7 @@ Examples: msg.command('update [content]') .description('Edit a conversation message') + .option('--stdin', 'Read content from stdin') .option('--dry-run', 'Show what would be updated without updating') .option('--json', 'Output updated message as JSON') .option('--full', 'Include all fields in JSON output') @@ -40,7 +41,7 @@ Examples: ` Examples: tdc msg update id:CbS8n2Kp4Qx6Rz9Lm3Va "Updated text" - echo "New content" | tdc msg update id:CbS8n2Kp4Qx6Rz9Lm3Va + echo "New content" | tdc msg update id:CbS8n2Kp4Qx6Rz9Lm3Va --stdin tdc msg update id:CbS8n2Kp4Qx6Rz9Lm3Va "Fixed typo" --json`, ) .action(updateMessage) diff --git a/src/commands/msg/msg.test.ts b/src/commands/msg/msg.test.ts index 6368983..8bba256 100644 --- a/src/commands/msg/msg.test.ts +++ b/src/commands/msg/msg.test.ts @@ -1,4 +1,4 @@ -import { captureConsole, createTestProgram } from '@doist/cli-core/testing' +import { captureConsole, createTestProgram, mockStdin } from '@doist/cli-core/testing' import { beforeEach, describe, expect, it, vi } from 'vitest' const apiMocks = vi.hoisted(() => ({ @@ -14,8 +14,8 @@ vi.mock('../../lib/refs.js', () => ({ resolveMessageId: vi.fn().mockReturnValue('200'), })) -vi.mock('../../lib/input.js', () => ({ - readStdin: vi.fn().mockResolvedValue(''), +vi.mock('../../lib/input.js', async (importOriginal) => ({ + ...(await importOriginal()), openEditor: vi.fn().mockResolvedValue(''), })) @@ -155,3 +155,44 @@ describe('msg delete', () => { expect(client.conversationMessages.deleteMessage).not.toHaveBeenCalled() }) }) + +describe('msg update', () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it('reads content from stdin with --stdin', async () => { + const client = createClient() + apiMocks.getCommsClient.mockResolvedValue(client) + captureConsole('log') + mockStdin('Piped message\n') + + await createProgram().parseAsync(['node', 'tdc', 'msg', 'update', '200', '--stdin']) + + expect(client.conversationMessages.updateMessage).toHaveBeenCalledWith({ + id: '200', + content: 'Piped message', + }) + }) + + it('ignores piped stdin without --stdin and uses the argument', async () => { + const client = createClient() + apiMocks.getCommsClient.mockResolvedValue(client) + captureConsole('log') + mockStdin('Piped message\n') + + await createProgram().parseAsync([ + 'node', + 'tdc', + 'msg', + 'update', + '200', + 'Argument message', + ]) + + expect(client.conversationMessages.updateMessage).toHaveBeenCalledWith({ + id: '200', + content: 'Argument message', + }) + }) +}) diff --git a/src/commands/msg/update.ts b/src/commands/msg/update.ts index b0a54d7..cebc982 100644 --- a/src/commands/msg/update.ts +++ b/src/commands/msg/update.ts @@ -1,11 +1,11 @@ import { getCommsClient } from '../../lib/api.js' import { CliError } from '../../lib/errors.js' -import { openEditor, readStdin } from '../../lib/input.js' -import type { MutationOptions } from '../../lib/options.js' +import { openEditor, readContent } from '../../lib/input.js' +import type { MutationOptions, StdinOptions } from '../../lib/options.js' import { formatJson, printDryRun } from '../../lib/output.js' import { resolveMessageId } from '../../lib/refs.js' -type UpdateOptions = MutationOptions +type UpdateOptions = MutationOptions & StdinOptions export async function updateMessage( ref: string, @@ -14,17 +14,14 @@ export async function updateMessage( ): Promise { const messageId = resolveMessageId(ref) - let newContent = await readStdin() - if (!newContent && content) { - newContent = content - } + let newContent = await readContent(content, options) if (!newContent) { newContent = await openEditor() } if (!newContent || newContent.trim() === '') { throw new CliError( 'MISSING_CONTENT', - 'No content provided. Pass content as an argument or pipe via stdin.', + 'No content provided. Pass content as an argument, or pipe it in with --stdin.', ) } diff --git a/src/commands/thread/create.ts b/src/commands/thread/create.ts index 4f2c2d2..f7a4004 100644 --- a/src/commands/thread/create.ts +++ b/src/commands/thread/create.ts @@ -3,18 +3,19 @@ import { getCommsClient } from '../../lib/api.js' import { uploadAttachments, validateAttachmentFiles } from '../../lib/attachments.js' import { getConfig } from '../../lib/config.js' import { CliError } from '../../lib/errors.js' -import { openEditor, readStdin } from '../../lib/input.js' -import type { MutationOptions } from '../../lib/options.js' +import { openEditor, readContent } from '../../lib/input.js' +import type { MutationOptions, StdinOptions } from '../../lib/options.js' import { formatJson, printDryRun } from '../../lib/output.js' import { assertChannelIsPublic } from '../../lib/public-channels.js' import { parseNotifyIdRefs, resolveChannelId } from '../../lib/refs.js' import { type ResolvedNotify, formatNotifyLabel, resolveNotifyIds } from './helpers.js' -type CreateOptions = MutationOptions & { - notify?: string - unarchive?: boolean - file?: string[] -} +type CreateOptions = MutationOptions & + StdinOptions & { + notify?: string + unarchive?: boolean + file?: string[] + } export async function createThread( channelRef: string, @@ -27,10 +28,7 @@ export async function createThread( const files = options.file ?? [] const hasFiles = files.length > 0 - let threadContent = await readStdin() - if (!threadContent && content) { - threadContent = content - } + let threadContent = await readContent(content, options) // A file-only thread is allowed: skip the editor prompt and the empty-content guard. if (!threadContent && !hasFiles) { threadContent = await openEditor() @@ -38,7 +36,7 @@ export async function createThread( if ((!threadContent || threadContent.trim() === '') && !hasFiles) { throw new CliError( 'MISSING_CONTENT', - 'No content provided. Pass content as an argument, pipe via stdin, or attach a file.', + 'No content provided. Pass content as an argument, pipe it in with --stdin, or attach a file.', ) } const messageContent = threadContent ?? '' diff --git a/src/commands/thread/helpers.ts b/src/commands/thread/helpers.ts index 89a986a..98e3ca6 100644 --- a/src/commands/thread/helpers.ts +++ b/src/commands/thread/helpers.ts @@ -4,9 +4,9 @@ import { getCommsClient, getWorkspaceGroups, getWorkspaceUsers } from '../../lib import { formatRelativeDate } from '../../lib/dates.js' import { CliError } from '../../lib/errors.js' import { isAccessible } from '../../lib/global-args.js' -import { readStdinToEnd } from '../../lib/input.js' +import { readStdinLines } from '../../lib/input.js' import { renderMarkdown } from '../../lib/markdown.js' -import type { MutationOptions } from '../../lib/options.js' +import type { MutationOptions, StdinOptions } from '../../lib/options.js' import { colors, formatJson, pluralize } from '../../lib/output.js' import { assertChannelIsPublic } from '../../lib/public-channels.js' import { partitionNotifyIds, resolveThreadId } from '../../lib/refs.js' @@ -108,7 +108,7 @@ export type ReadStatePlan = { export type ReadStateMutation = { verb: 'read' | 'unread' - /** Runs on the full ref list (positional plus stdin) before anything is loaded. */ + /** Runs on the full ref list (positional plus `--stdin`) before anything is loaded. */ validateRefs?(rawRefs: string[]): void /** * Builds the per-thread plan. Runs before the unread lookup so an invalid @@ -119,14 +119,14 @@ export type ReadStateMutation = { export async function runThreadReadStateMutation( refs: string[], - options: MutationOptions, + options: MutationOptions & StdinOptions, mutation: ReadStateMutation, ): Promise { - const rawRefs = await collectThreadRefs(refs) + const rawRefs = await collectThreadRefs(refs, options) if (rawRefs.length === 0) { throw new CliError( 'INVALID_REF', - 'No thread references provided. Pass refs as arguments or pipe them via stdin.', + 'No thread references provided. Pass refs as arguments, or pipe them in with --stdin.', ) } mutation.validateRefs?.(rawRefs) @@ -204,18 +204,10 @@ export async function runThreadReadStateMutation( } } -async function collectThreadRefs(refs: string[]): Promise { +async function collectThreadRefs(refs: string[], options: StdinOptions): Promise { const inlineRefs = refs.map((ref) => ref.trim()).filter(Boolean) - - const stdinContent = await readStdinToEnd() - if (!stdinContent) return inlineRefs - - const stdinRefs = stdinContent - .split(/\r?\n/) - .map((line) => line.trim()) - .filter((line) => line !== '' && !line.startsWith('#')) - - return [...inlineRefs, ...stdinRefs] + if (!options.stdin) return inlineRefs + return [...inlineRefs, ...(await readStdinLines())] } /** diff --git a/src/commands/thread/index.ts b/src/commands/thread/index.ts index c4d4c7f..2442262 100644 --- a/src/commands/thread/index.ts +++ b/src/commands/thread/index.ts @@ -59,6 +59,7 @@ Examples: .option('--close', 'Close the thread after replying') .option('--reopen', 'Reopen the thread after replying') .option('--file ', 'Attach a file (repeatable; content optional)', collect, []) + .option('--stdin', 'Read content from stdin') .option('--dry-run', 'Show what would be posted without posting') .option('--json', 'Output posted comment as JSON') .option('--full', 'Include all fields in JSON output') @@ -69,7 +70,7 @@ Examples: tdc thread reply id:CbT8n2Kp4Qx6Rz9Lm3Va "Sounds good!" tdc thread reply id:CbT8n2Kp4Qx6Rz9Lm3Va "For the record" --notify NONE tdc thread reply id:CbT8n2Kp4Qx6Rz9Lm3Va "Done" --close --notify NONE --dry-run - echo "Long reply" | tdc thread reply id:CbT8n2Kp4Qx6Rz9Lm3Va + echo "Long reply" | tdc thread reply id:CbT8n2Kp4Qx6Rz9Lm3Va --stdin tdc thread reply id:CbT8n2Kp4Qx6Rz9Lm3Va "Done" --close --json tdc thread reply id:CbT8n2Kp4Qx6Rz9Lm3Va "Heads up" --notify 67890,Cbzzm11ZeYZoJYD4a6rti tdc thread reply id:CbT8n2Kp4Qx6Rz9Lm3Va "See attached" --file ./diagram.png @@ -87,6 +88,7 @@ Examples: ) .option('--no-unarchive', 'Skip unarchive even if userSettings.unarchiveNewThreads is true') .option('--file ', 'Attach a file (repeatable; content optional)', collect, []) + .option('--stdin', 'Read content from stdin') .option('--dry-run', 'Show what would be posted without posting') .option('--json', 'Output created thread as JSON') .option('--full', 'Include all fields in JSON output') @@ -95,7 +97,7 @@ Examples: ` Examples: tdc thread create id:CbC8n2Kp4Qx6Rz9Lm3Va "Weekly update" "Here's what happened..." - echo "Body from stdin" | tdc thread create id:CbC8n2Kp4Qx6Rz9Lm3Va "Title" + echo "Body from stdin" | tdc thread create id:CbC8n2Kp4Qx6Rz9Lm3Va "Title" --stdin tdc thread create id:CbC8n2Kp4Qx6Rz9Lm3Va "Title" "Body" --notify 67890,11111 --json tdc thread create id:CbC8n2Kp4Qx6Rz9Lm3Va "Title" "Body" --unarchive tdc thread create id:CbC8n2Kp4Qx6Rz9Lm3Va "Title" --file ./report.pdf`, @@ -138,6 +140,7 @@ Examples: .command('mark-read [thread-refs...]') .description('Mark a thread read for the current user') .option('--yes', 'Skip confirmation for bulk operations') + .option('--stdin', 'Read thread refs from stdin, one per line') .option('--dry-run', 'Show what would happen without executing') .option('--json', 'Output result as JSON') .addHelpText( @@ -146,10 +149,10 @@ Examples: Examples: tdc thread mark-read id:CbT8n2Kp4Qx6Rz9Lm3Va tdc thread mark-read id:CbT8n2Kp4Qx6Rz9Lm3Va id:CbT9m4Qr7Vz2Nx8Lp5Sa --yes - printf "id:CbT8n2Kp4Qx6Rz9Lm3Va\\nid:CbT9m4Qr7Vz2Nx8Lp5Sa\\n" | tdc thread mark-read --yes`, + printf "id:CbT8n2Kp4Qx6Rz9Lm3Va\\nid:CbT9m4Qr7Vz2Nx8Lp5Sa\\n" | tdc thread mark-read --stdin --yes`, ) .action((refs, options) => { - if (refs.length === 0 && process.stdin.isTTY) { + if (refs.length === 0 && !options.stdin) { markReadCmd.help() return } @@ -164,6 +167,7 @@ Examples: 'Mark unread from this comment onward (single thread only; default: whole thread)', ) .option('--yes', 'Skip confirmation for bulk operations') + .option('--stdin', 'Read thread refs from stdin, one per line') .option('--dry-run', 'Show what would happen without executing') .option('--json', 'Output result as JSON') .addHelpText( @@ -173,10 +177,10 @@ Examples: tdc thread mark-unread id:CbT8n2Kp4Qx6Rz9Lm3Va tdc thread mark-unread id:CbT8n2Kp4Qx6Rz9Lm3Va --from id:CbM8n2Kp4Qx6Rz9Lm3Va tdc thread mark-unread id:CbT8n2Kp4Qx6Rz9Lm3Va id:CbT9m4Qr7Vz2Nx8Lp5Sa --yes - printf "id:CbT8n2Kp4Qx6Rz9Lm3Va\\nid:CbT9m4Qr7Vz2Nx8Lp5Sa\\n" | tdc thread mark-unread --yes`, + printf "id:CbT8n2Kp4Qx6Rz9Lm3Va\\nid:CbT9m4Qr7Vz2Nx8Lp5Sa\\n" | tdc thread mark-unread --stdin --yes`, ) .action((refs, options) => { - if (refs.length === 0 && process.stdin.isTTY) { + if (refs.length === 0 && !options.stdin) { markUnreadCmd.help() return } @@ -226,6 +230,7 @@ Examples: thread .command('update [content]') .description("Update a thread's body (the first post)") + .option('--stdin', 'Read content from stdin') .option('--dry-run', 'Show what would be updated without updating') .option('--json', 'Output updated thread as JSON') .option('--full', 'Include all fields in JSON output') @@ -234,7 +239,7 @@ Examples: ` Examples: tdc thread update id:CbT8n2Kp4Qx6Rz9Lm3Va "Updated body text" - echo "New body" | tdc thread update id:CbT8n2Kp4Qx6Rz9Lm3Va + echo "New body" | tdc thread update id:CbT8n2Kp4Qx6Rz9Lm3Va --stdin tdc thread update id:CbT8n2Kp4Qx6Rz9Lm3Va "Fixed" --json`, ) .action(updateThread) diff --git a/src/commands/thread/read.ts b/src/commands/thread/read.ts index 5648192..a8b42da 100644 --- a/src/commands/thread/read.ts +++ b/src/commands/thread/read.ts @@ -1,8 +1,8 @@ import type { Thread } from '@doist/comms-sdk' -import type { MutationOptions } from '../../lib/options.js' +import type { MutationOptions, StdinOptions } from '../../lib/options.js' import { runThreadReadStateMutation } from './helpers.js' -export type MarkThreadReadOptions = MutationOptions +export type MarkThreadReadOptions = MutationOptions & StdinOptions type MarkReadStatus = { id: string diff --git a/src/commands/thread/reply.ts b/src/commands/thread/reply.ts index a72c6a6..1397c8f 100644 --- a/src/commands/thread/reply.ts +++ b/src/commands/thread/reply.ts @@ -2,19 +2,20 @@ import chalk from 'chalk' import { getCommsClient } from '../../lib/api.js' import { uploadAttachments, validateAttachmentFiles } from '../../lib/attachments.js' import { CliError } from '../../lib/errors.js' -import { openEditor, readStdin } from '../../lib/input.js' -import type { MutationOptions } from '../../lib/options.js' +import { openEditor, readContent } from '../../lib/input.js' +import type { MutationOptions, StdinOptions } from '../../lib/options.js' import { formatJson, printDryRun } from '../../lib/output.js' import { assertChannelIsPublic } from '../../lib/public-channels.js' import { parseNotifyIdRefs, resolveThreadId } from '../../lib/refs.js' import { type ResolvedNotify, formatNotifyLabel, resolveNotifyIds } from './helpers.js' -type ReplyOptions = MutationOptions & { - notify?: string - close?: boolean - reopen?: boolean - file?: string[] -} +type ReplyOptions = MutationOptions & + StdinOptions & { + notify?: string + close?: boolean + reopen?: boolean + file?: string[] + } export async function replyToThread( ref: string, @@ -37,10 +38,7 @@ export async function replyToThread( ) } - let replyContent = await readStdin() - if (!replyContent && content) { - replyContent = content - } + let replyContent = await readContent(content, options) // A file-only reply is allowed: skip the editor prompt and the empty-content guard. if (!replyContent && !hasFiles) { replyContent = await openEditor() @@ -48,7 +46,7 @@ export async function replyToThread( if ((!replyContent || replyContent.trim() === '') && !hasFiles) { throw new CliError( 'MISSING_CONTENT', - 'No content provided. Pass content as an argument, pipe via stdin, or attach a file.', + 'No content provided. Pass content as an argument, pipe it in with --stdin, or attach a file.', ) } const messageContent = replyContent ?? '' diff --git a/src/commands/thread/thread.test.ts b/src/commands/thread/thread.test.ts index 8de0b3f..ad43b08 100644 --- a/src/commands/thread/thread.test.ts +++ b/src/commands/thread/thread.test.ts @@ -1,7 +1,12 @@ import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { captureConsole, createTestProgram } from '@doist/cli-core/testing' +import { + captureConsole, + captureStream, + createTestProgram, + mockStdin, +} from '@doist/cli-core/testing' import { CommsApi, type CustomFetch, generateId } from '@doist/comms-sdk' import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' @@ -38,16 +43,15 @@ vi.mock('../../lib/markdown.js', () => ({ renderMarkdown: vi.fn((text: string) => Promise.resolve(text)), })) -vi.mock('../../lib/input.js', () => ({ - readStdin: vi.fn().mockResolvedValue(''), - readStdinToEnd: vi.fn().mockResolvedValue(''), +vi.mock('../../lib/input.js', async (importOriginal) => ({ + ...(await importOriginal()), openEditor: vi.fn().mockResolvedValue(''), })) vi.mock('chalk') import { clearWorkspaceUserCache } from '../../lib/api.js' -import { openEditor, readStdin, readStdinToEnd } from '../../lib/input.js' +import { openEditor } from '../../lib/input.js' import { registerThreadCommand } from './index.js' function createThreadFixture(id: number | string) { @@ -308,8 +312,8 @@ describe('thread implicit view', () => { const program = createProgram() captureConsole('log') - vi.mocked(readStdin).mockResolvedValueOnce('closing comment') - await program.parseAsync(['node', 'tdc', 'thread', 'reply', '500', '--close']) + mockStdin('closing comment') + await program.parseAsync(['node', 'tdc', 'thread', 'reply', '500', '--close', '--stdin']) expect(client.threads.closeThread).toHaveBeenCalledWith( expect.objectContaining({ id: '500', content: 'closing comment' }), @@ -324,8 +328,8 @@ describe('thread implicit view', () => { const program = createProgram() captureConsole('log') - vi.mocked(readStdin).mockResolvedValueOnce('reopening comment') - await program.parseAsync(['node', 'tdc', 'thread', 'reply', '500', '--reopen']) + mockStdin('reopening comment') + await program.parseAsync(['node', 'tdc', 'thread', 'reply', '500', '--reopen', '--stdin']) expect(client.threads.reopenThread).toHaveBeenCalledWith( expect.objectContaining({ id: '500', content: 'reopening comment' }), @@ -931,14 +935,14 @@ describe('thread create', () => { }) it('reads content from stdin', async () => { - vi.mocked(readStdin).mockResolvedValueOnce('Content from stdin') + mockStdin('Content from stdin') const client = createClient() apiMocks.getCommsClient.mockResolvedValue(client) const program = createProgram() captureConsole('log') - await program.parseAsync(['node', 'tdc', 'thread', 'create', '100', 'My Title']) + await program.parseAsync(['node', 'tdc', 'thread', 'create', '100', 'My Title', '--stdin']) expect(client.threads.createThread).toHaveBeenCalledWith( expect.objectContaining({ @@ -1256,7 +1260,6 @@ describe('thread read', () => { beforeEach(() => { clearWorkspaceUserCache() vi.clearAllMocks() - vi.mocked(readStdinToEnd).mockResolvedValue('') }) it('marks a single unread thread read without requiring --yes', async () => { @@ -1461,101 +1464,71 @@ describe('thread read', () => { }) it('reads thread refs from stdin', async () => { - vi.mocked(readStdinToEnd).mockResolvedValueOnce('# comment\n500\n\n') - const originalIsTTY = process.stdin.isTTY - Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true }) - - try { - const client = createClient({ - unreadThreads: [ - { threadId: '500', channelId: 'CH100', objIndex: 1, directMention: false }, - ], - }) - apiMocks.getCommsClient.mockResolvedValue(client) - - const program = createProgram() - captureConsole('log') - - await program.parseAsync(['node', 'tdc', 'thread', 'mark-read']) - - expect(readStdinToEnd).toHaveBeenCalled() - expect(client.threads.markRead).toHaveBeenCalledWith({ id: '500', objIndex: 3 }) - } finally { - Object.defineProperty(process.stdin, 'isTTY', { - value: originalIsTTY, - configurable: true, - }) - } + const stdin = mockStdin('# comment\n500\n\n') + const client = createClient({ + unreadThreads: [ + { threadId: '500', channelId: 'CH100', objIndex: 1, directMention: false }, + ], + }) + apiMocks.getCommsClient.mockResolvedValue(client) + + const program = createProgram() + captureConsole('log') + + await program.parseAsync(['node', 'tdc', 'thread', 'mark-read', '--stdin']) + + expect(stdin).toHaveBeenCalled() + expect(client.threads.markRead).toHaveBeenCalledWith({ id: '500', objIndex: 3 }) }) it('reads multiple thread refs from stdin', async () => { - vi.mocked(readStdinToEnd).mockResolvedValueOnce('# comment\n500\n501\n') - const originalIsTTY = process.stdin.isTTY - Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true }) - - try { - const thread500 = createThreadFixture(500) - const thread501 = { ...createThreadFixture(501), title: 'Second Thread' } - const client = createClient({ - unreadThreads: [ - { threadId: '500', channelId: 'CH100', objIndex: 1, directMention: false }, - { threadId: '501', channelId: 'CH100', objIndex: 1, directMention: false }, - ], - }) - client.threads.getThread.mockImplementation(async (id: string) => - id === '501' ? thread501 : thread500, - ) - apiMocks.getCommsClient.mockResolvedValue(client) - - const program = createProgram() - captureConsole('log') - - await program.parseAsync(['node', 'tdc', 'thread', 'mark-read', '--yes']) - - expect(client.threads.markRead).toHaveBeenCalledWith({ id: '500', objIndex: 3 }) - expect(client.threads.markRead).toHaveBeenCalledWith({ id: '501', objIndex: 3 }) - expect(client.threads.markRead).toHaveBeenCalledTimes(2) - } finally { - Object.defineProperty(process.stdin, 'isTTY', { - value: originalIsTTY, - configurable: true, - }) - } + mockStdin('# comment\n500\n501\n') + const thread500 = createThreadFixture(500) + const thread501 = { ...createThreadFixture(501), title: 'Second Thread' } + const client = createClient({ + unreadThreads: [ + { threadId: '500', channelId: 'CH100', objIndex: 1, directMention: false }, + { threadId: '501', channelId: 'CH100', objIndex: 1, directMention: false }, + ], + }) + client.threads.getThread.mockImplementation(async (id: string) => + id === '501' ? thread501 : thread500, + ) + apiMocks.getCommsClient.mockResolvedValue(client) + + const program = createProgram() + captureConsole('log') + + await program.parseAsync(['node', 'tdc', 'thread', 'mark-read', '--yes', '--stdin']) + + expect(client.threads.markRead).toHaveBeenCalledWith({ id: '500', objIndex: 3 }) + expect(client.threads.markRead).toHaveBeenCalledWith({ id: '501', objIndex: 3 }) + expect(client.threads.markRead).toHaveBeenCalledTimes(2) }) it('combines positional and stdin thread refs', async () => { - vi.mocked(readStdinToEnd).mockResolvedValueOnce('501\n') - const originalIsTTY = process.stdin.isTTY - Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true }) - - try { - const thread500 = createThreadFixture(500) - const thread501 = { ...createThreadFixture(501), title: 'Second Thread' } - const client = createClient({ - unreadThreads: [ - { threadId: '500', channelId: 'CH100', objIndex: 1, directMention: false }, - { threadId: '501', channelId: 'CH100', objIndex: 1, directMention: false }, - ], - }) - client.threads.getThread.mockImplementation(async (id: string) => - id === '501' ? thread501 : thread500, - ) - apiMocks.getCommsClient.mockResolvedValue(client) - - const program = createProgram() - captureConsole('log') - - await program.parseAsync(['node', 'tdc', 'thread', 'mark-read', '500', '--yes']) - - expect(client.threads.markRead).toHaveBeenCalledWith({ id: '500', objIndex: 3 }) - expect(client.threads.markRead).toHaveBeenCalledWith({ id: '501', objIndex: 3 }) - expect(client.threads.markRead).toHaveBeenCalledTimes(2) - } finally { - Object.defineProperty(process.stdin, 'isTTY', { - value: originalIsTTY, - configurable: true, - }) - } + mockStdin('501\n') + const thread500 = createThreadFixture(500) + const thread501 = { ...createThreadFixture(501), title: 'Second Thread' } + const client = createClient({ + unreadThreads: [ + { threadId: '500', channelId: 'CH100', objIndex: 1, directMention: false }, + { threadId: '501', channelId: 'CH100', objIndex: 1, directMention: false }, + ], + }) + client.threads.getThread.mockImplementation(async (id: string) => + id === '501' ? thread501 : thread500, + ) + apiMocks.getCommsClient.mockResolvedValue(client) + + const program = createProgram() + captureConsole('log') + + await program.parseAsync(['node', 'tdc', 'thread', 'mark-read', '500', '--yes', '--stdin']) + + expect(client.threads.markRead).toHaveBeenCalledWith({ id: '500', objIndex: 3 }) + expect(client.threads.markRead).toHaveBeenCalledWith({ id: '501', objIndex: 3 }) + expect(client.threads.markRead).toHaveBeenCalledTimes(2) }) }) @@ -1790,14 +1763,14 @@ describe('thread update', () => { }) it('reads content from stdin', async () => { - vi.mocked(readStdin).mockResolvedValueOnce('Body from stdin') + mockStdin('Body from stdin') const client = createClient() apiMocks.getCommsClient.mockResolvedValue(client) const program = createProgram() captureConsole('log') - await program.parseAsync(['node', 'tdc', 'thread', 'update', '500']) + await program.parseAsync(['node', 'tdc', 'thread', 'update', '500', '--stdin']) expect(client.threads.updateThread).toHaveBeenCalledWith({ id: '500', @@ -2063,7 +2036,6 @@ describe('thread mark-unread', () => { beforeEach(() => { clearWorkspaceUserCache() vi.clearAllMocks() - vi.mocked(readStdinToEnd).mockResolvedValue('') }) it('marks a read thread unread from the start without requiring --yes', async () => { @@ -2147,7 +2119,7 @@ describe('thread mark-unread', () => { }) it('rejects --from when stdin adds a second thread ref', async () => { - vi.mocked(readStdinToEnd).mockResolvedValueOnce('501\n') + mockStdin('501\n') const client = createClient({ comments: [createComment(11, 1)] }) apiMocks.getCommsClient.mockResolvedValue(client) @@ -2163,6 +2135,7 @@ describe('thread mark-unread', () => { '--from', '11', '--yes', + '--stdin', ]), ).rejects.toHaveProperty('code', 'CONFLICTING_OPTIONS') expect(client.threads.markUnread).not.toHaveBeenCalled() @@ -2269,34 +2242,22 @@ describe('thread mark-unread', () => { }) it('previews bulk refs from stdin and asks for --yes', async () => { - vi.mocked(readStdinToEnd).mockResolvedValueOnce('# refs\n500\n501\n') - const originalIsTTY = process.stdin.isTTY - Object.defineProperty(process.stdin, 'isTTY', { value: false, configurable: true }) - - try { - const client = createClient() - client.threads.getThread.mockImplementation(async (id: string) => - createThreadFixture(id), - ) - apiMocks.getCommsClient.mockResolvedValue(client) - - const program = createProgram() - const consoleSpy = captureConsole('log') - - await program.parseAsync(['node', 'tdc', 'thread', 'mark-unread']) - - expect(readStdinToEnd).toHaveBeenCalled() - expect(client.threads.markUnread).not.toHaveBeenCalled() - expect(consoleSpy).toHaveBeenCalledWith('Would mark unread thread Test Thread (500).') - expect(consoleSpy).toHaveBeenCalledWith('Would mark unread thread Test Thread (501).') - expect(consoleSpy).toHaveBeenCalledWith('Summary: 2 previews') - expect(consoleSpy).toHaveBeenCalledWith('Use --yes to confirm.') - } finally { - Object.defineProperty(process.stdin, 'isTTY', { - value: originalIsTTY, - configurable: true, - }) - } + const stdin = mockStdin('# refs\n500\n501\n') + const client = createClient() + client.threads.getThread.mockImplementation(async (id: string) => createThreadFixture(id)) + apiMocks.getCommsClient.mockResolvedValue(client) + + const program = createProgram() + const consoleSpy = captureConsole('log') + + await program.parseAsync(['node', 'tdc', 'thread', 'mark-unread', '--stdin']) + + expect(stdin).toHaveBeenCalled() + expect(client.threads.markUnread).not.toHaveBeenCalled() + expect(consoleSpy).toHaveBeenCalledWith('Would mark unread thread Test Thread (500).') + expect(consoleSpy).toHaveBeenCalledWith('Would mark unread thread Test Thread (501).') + expect(consoleSpy).toHaveBeenCalledWith('Summary: 2 previews') + expect(consoleSpy).toHaveBeenCalledWith('Use --yes to confirm.') }) it('marks bulk refs unread with --yes', async () => { @@ -2607,3 +2568,109 @@ describe('thread create --file', () => { expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining(files.png)) }) }) + +describe('thread --stdin', () => { + beforeEach(() => { + clearWorkspaceUserCache() + vi.clearAllMocks() + configMocks.getConfig.mockResolvedValue({}) + }) + + it('reply ignores piped stdin without --stdin and posts the argument', async () => { + const client = createClient() + apiMocks.getCommsClient.mockResolvedValue(client) + captureConsole('log') + mockStdin('Piped reply') + + await createProgram().parseAsync([ + 'node', + 'tdc', + 'thread', + 'reply', + '500', + 'Argument reply', + ]) + + expect(client.comments.createComment).toHaveBeenCalledWith( + expect.objectContaining({ threadId: '500', content: 'Argument reply' }), + ) + }) + + it('reply with no content and no --stdin leaves piped input unread', async () => { + const client = createClient() + apiMocks.getCommsClient.mockResolvedValue(client) + mockStdin('Piped reply') + + await expect( + createProgram().parseAsync(['node', 'tdc', 'thread', 'reply', '500']), + ).rejects.toHaveProperty('code', 'MISSING_CONTENT') + expect(openEditor).toHaveBeenCalled() + expect(client.comments.createComment).not.toHaveBeenCalled() + }) + + it('reply --stdin trims the piped content', async () => { + const client = createClient() + apiMocks.getCommsClient.mockResolvedValue(client) + captureConsole('log') + mockStdin('\n Piped reply\n\n') + + await createProgram().parseAsync(['node', 'tdc', 'thread', 'reply', '500', '--stdin']) + + expect(client.comments.createComment).toHaveBeenCalledWith( + expect.objectContaining({ threadId: '500', content: 'Piped reply' }), + ) + }) + + it('reply --stdin with a content argument fails with CONFLICTING_OPTIONS', async () => { + const client = createClient() + apiMocks.getCommsClient.mockResolvedValue(client) + mockStdin('Piped reply') + + await expect( + createProgram().parseAsync([ + 'node', + 'tdc', + 'thread', + 'reply', + '500', + 'Argument reply', + '--stdin', + ]), + ).rejects.toMatchObject({ + code: 'CONFLICTING_OPTIONS', + message: 'Pass content as an argument or with --stdin, not both.', + }) + expect(client.comments.createComment).not.toHaveBeenCalled() + }) + + it('reply --stdin on a terminal fails with STDIN_IS_TTY', async () => { + const client = createClient() + apiMocks.getCommsClient.mockResolvedValue(client) + mockStdin('', { isTTY: true }) + + await expect( + createProgram().parseAsync(['node', 'tdc', 'thread', 'reply', '500', '--stdin']), + ).rejects.toHaveProperty('code', 'STDIN_IS_TTY') + expect(client.comments.createComment).not.toHaveBeenCalled() + }) + + it('mark-read with no refs shows help instead of reading piped refs', async () => { + const client = createClient({ + unreadThreads: [ + { threadId: '500', channelId: 'CH100', objIndex: 1, directMention: false }, + ], + }) + apiMocks.getCommsClient.mockResolvedValue(client) + const stdout = captureStream('stdout') + mockStdin('500\n') + + await createProgram() + .parseAsync(['node', 'tdc', 'thread', 'mark-read']) + .catch(() => {}) + + expect(stdout.mock.calls.map((args) => String(args[0])).join('')).toContain( + 'Usage: tdc thread mark-read', + ) + expect(client.threads.markRead).not.toHaveBeenCalled() + }) +}) diff --git a/src/commands/thread/unread.ts b/src/commands/thread/unread.ts index cb42d22..dc70a17 100644 --- a/src/commands/thread/unread.ts +++ b/src/commands/thread/unread.ts @@ -1,10 +1,10 @@ import type { CommsApi } from '@doist/comms-sdk' import { CliError } from '../../lib/errors.js' -import type { MutationOptions } from '../../lib/options.js' +import type { MutationOptions, StdinOptions } from '../../lib/options.js' import { resolveCommentId } from '../../lib/refs.js' import { runThreadReadStateMutation } from './helpers.js' -export type MarkThreadUnreadOptions = MutationOptions & { from?: string } +export type MarkThreadUnreadOptions = MutationOptions & StdinOptions & { from?: string } type MarkUnreadStatus = { id: string diff --git a/src/commands/thread/update.ts b/src/commands/thread/update.ts index d860818..13d2eb4 100644 --- a/src/commands/thread/update.ts +++ b/src/commands/thread/update.ts @@ -1,12 +1,12 @@ import { getCommsClient } from '../../lib/api.js' import { CliError } from '../../lib/errors.js' -import { openEditor, readStdin } from '../../lib/input.js' -import type { MutationOptions } from '../../lib/options.js' +import { openEditor, readContent } from '../../lib/input.js' +import type { MutationOptions, StdinOptions } from '../../lib/options.js' import { formatJson, printDryRun } from '../../lib/output.js' import { assertChannelIsPublic } from '../../lib/public-channels.js' import { resolveThreadId } from '../../lib/refs.js' -type UpdateOptions = MutationOptions +type UpdateOptions = MutationOptions & StdinOptions export async function updateThread( ref: string, @@ -15,17 +15,14 @@ export async function updateThread( ): Promise { const threadId = resolveThreadId(ref) - let newContent = await readStdin() - if (!newContent && content) { - newContent = content - } + let newContent = await readContent(content, options) if (!newContent) { newContent = await openEditor() } if (!newContent || newContent.trim() === '') { throw new CliError( 'MISSING_CONTENT', - 'No content provided. Pass content as an argument or pipe via stdin.', + 'No content provided. Pass content as an argument, or pipe it in with --stdin.', ) } diff --git a/src/lib/input.ts b/src/lib/input.ts index 2fc90b7..b957657 100644 --- a/src/lib/input.ts +++ b/src/lib/input.ts @@ -2,84 +2,44 @@ import { spawn } from 'node:child_process' import { readFile, unlink, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' +import { readStdin } from '@doist/cli-core' +import { CliError } from './errors.js' import { isNonInteractive } from './global-args.js' - -const STDIN_TIMEOUT_MS = 100 - -export async function readStdin(): Promise { - if (process.stdin.isTTY) { - return null - } - - return new Promise((resolve) => { - let data = '' - let settled = false - let timeout: ReturnType | undefined - - const settle = (value: string | null) => { - if (settled) return - settled = true - if (timeout) clearTimeout(timeout) - process.stdin.removeListener('data', onData) - process.stdin.removeListener('end', onEnd) - process.stdin.removeListener('error', onError) - resolve(value) - } - - const onData = (chunk: string) => { - data += chunk - // Data arrived — clear any non-interactive timeout and wait for end - if (timeout) { - clearTimeout(timeout) - timeout = undefined - } - } - const onEnd = () => settle(data.trim() || null) - const onError = () => settle(null) - - process.stdin.setEncoding('utf8') - process.stdin.on('data', onData) - process.stdin.on('end', onEnd) - process.stdin.on('error', onError) - - // In non-interactive mode, don't wait indefinitely for a pipe that may never close - if (isNonInteractive()) { - timeout = setTimeout(() => { - settle(data.trim() || null) - }, STDIN_TIMEOUT_MS) +import type { StdinOptions } from './options.js' + +/** + * Input for a command that takes it as a positional argument or, with + * `--stdin`, from piped stdin. Stdin is only read when `--stdin` is passed. + * Returns null when neither gave any input, so the caller can fall back to + * `$EDITOR` or report it missing. `label` names the input in the + * conflicting-options error (e.g. `'URLs'`). + */ +export async function readContent( + content: string | undefined, + options: StdinOptions, + label = 'content', +): Promise { + if (options.stdin) { + if (content !== undefined) { + throw new CliError( + 'CONFLICTING_OPTIONS', + `Pass ${label} as an argument or with --stdin, not both.`, + ) } - }) -} - -export async function readStdinToEnd(): Promise { - if (process.stdin.isTTY) { - return null + return (await readStdin()).trim() || null } + return content || null +} - return new Promise((resolve) => { - let data = '' - let settled = false - - const settle = (value: string | null) => { - if (settled) return - settled = true - process.stdin.removeListener('data', onData) - process.stdin.removeListener('end', onEnd) - process.stdin.removeListener('error', onError) - resolve(value) - } - - const onData = (chunk: string) => { - data += chunk - } - const onEnd = () => settle(data.trim() || null) - const onError = () => settle(null) - - process.stdin.setEncoding('utf8') - process.stdin.on('data', onData) - process.stdin.on('end', onEnd) - process.stdin.on('error', onError) - }) +/** + * Non-empty lines piped to stdin for a `--stdin` flag, trimmed, skipping + * `#` comment lines. + */ +export async function readStdinLines(): Promise { + return (await readStdin()) + .split(/\r?\n/) + .map((line) => line.trim()) + .filter((line) => line !== '' && !line.startsWith('#')) } export async function openEditor(): Promise { diff --git a/src/lib/options.ts b/src/lib/options.ts index 00ef6f5..8cb58b4 100644 --- a/src/lib/options.ts +++ b/src/lib/options.ts @@ -18,6 +18,11 @@ export type MutationOptions = { yes?: boolean } +/** Commands that read their input from piped stdin only when `--stdin` is passed. */ +export type StdinOptions = { + stdin?: boolean +} + /** Converts an optional Commander date argument without applying boundary semantics. */ export function toDate(value?: string): Date | undefined { return value ? new Date(value) : undefined diff --git a/src/lib/skills/content.ts b/src/lib/skills/content.ts index 1919db6..606227f 100644 --- a/src/lib/skills/content.ts +++ b/src/lib/skills/content.ts @@ -127,10 +127,10 @@ tdc thread undone --yes # Unarchive thread (move it back to your i tdc thread undone --yes --json # Unarchive and return status as JSON tdc thread mark-read # Mark a thread read tdc thread mark-read --yes # Mark multiple threads read -printf "id:CbT8n2Kp4Qx6Rz9Lm3Va\\nid:CbT9m4Qr7Vz2Nx8Lp5Sa\\n" | tdc thread mark-read --dry-run # Preview bulk mark-read from stdin +printf "id:CbT8n2Kp4Qx6Rz9Lm3Va\\nid:CbT9m4Qr7Vz2Nx8Lp5Sa\\n" | tdc thread mark-read --stdin --dry-run # Preview bulk mark-read from stdin tdc thread mark-unread # Mark a whole thread unread; inverse of mark-read tdc thread mark-unread --from # Mark unread from that comment onward (single thread only) -tdc thread mark-unread --yes # Mark multiple threads unread (also accepts refs on stdin) +tdc thread mark-unread --yes # Mark multiple threads unread (also accepts refs on stdin with --stdin) tdc thread mute # Mute thread for 60 minutes (default) tdc thread mute --minutes 480 # Mute for custom duration tdc thread mute --json # Mute and return { id, mutedUntil } as JSON @@ -144,7 +144,7 @@ tdc thread rename "New title" # Rename a thread (change its title) tdc thread rename "New title" --json # Rename and return { id, title } as JSON tdc thread rename "New title" --json --full # Rename and return full thread as JSON tdc thread update "New body" # Update a thread's body (the first post) -echo "New body" | tdc thread update # Update body from stdin +echo "New body" | tdc thread update --stdin # Update body from stdin tdc thread update "New body" --dry-run # Preview without updating tdc thread update "New body" --json # Update and return { id, content } as JSON tdc thread update "New body" --json --full # Update and return full thread as JSON @@ -416,8 +416,8 @@ Translate old \`twist.com\` URLs to their Comms equivalents (e.g. for rewriting # Comma-separated list as an argument (token from the environment) TWIST_AUTH_TOKEN="$(tw auth token view)" tdc migrate urls "https://twist.com/a/1/ch/2/t/3,https://twist.com/a/1/ch/2/t/4" -# Or pipe URLs via stdin (comma- or newline-separated) -cat old-urls.txt | TWIST_AUTH_TOKEN="$(tw auth token view)" tdc migrate urls +# Or pipe URLs in with --stdin (comma- or newline-separated) +cat old-urls.txt | TWIST_AUTH_TOKEN="$(tw auth token view)" tdc migrate urls --stdin # --twist-token overrides the env var (visible in process lists — prefer the env var) tdc migrate urls "https://twist.com/a/1/ch/2/t/3" --twist-token @@ -471,20 +471,20 @@ Commands accept flexible references: ## Piping Input -Commands that accept content (\`thread create\`, \`thread reply\`, \`comment update\`, \`conversation reply\`, \`msg update\`) auto-detect piped stdin: +Commands that accept content (\`thread create\`, \`thread reply\`, \`thread update\`, \`comment update\`, \`conversation reply\`, \`msg update\`) read it from stdin only with \`--stdin\`; without the flag, piped input is ignored. \`--stdin\` can't be combined with a content argument, and with nothing piped in (stdin is a terminal) it fails with \`STDIN_IS_TTY\` instead of waiting: \`\`\`bash -cat notes.md | tdc thread reply -tdc thread create "Title" < body.md -echo "Quick reply" | tdc conversation reply +cat notes.md | tdc thread reply --stdin +tdc thread create "Title" --stdin < body.md +echo "Quick reply" | tdc conversation reply --stdin \`\`\` -If no content argument is provided and no stdin is piped, the CLI opens \`$EDITOR\` for interactive input. In non-TTY environments (e.g. when called by an agent or in a pipeline), the editor is automatically skipped and the command fails fast with an actionable error message. Use \`--non-interactive\` to force this behavior even in a TTY, or \`--interactive\` to override auto-detection. +If neither a content argument nor \`--stdin\` is given, the CLI opens \`$EDITOR\` for interactive input. In non-TTY environments (e.g. when called by an agent or in a pipeline), the editor is automatically skipped and the command fails fast with an actionable error message. Use \`--non-interactive\` to force this behavior even in a TTY, or \`--interactive\` to override auto-detection. -\`tdc thread mark-read\` and \`tdc thread mark-unread\` also accept thread refs from stdin, one per line: +\`tdc thread mark-read\` and \`tdc thread mark-unread\` read thread refs from stdin with \`--stdin\`, one per line (\`#\` lines are skipped), added to any refs passed as arguments: \`\`\`bash -printf "id:CbT8n2Kp4Qx6Rz9Lm3Va\\nid:CbT9m4Qr7Vz2Nx8Lp5Sa\\n" | tdc thread mark-read --yes +printf "id:CbT8n2Kp4Qx6Rz9Lm3Va\\nid:CbT9m4Qr7Vz2Nx8Lp5Sa\\n" | tdc thread mark-read --stdin --yes \`\`\` ## Common Workflows