Skip to content
Draft
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
59 changes: 59 additions & 0 deletions cli/src/commands/proposal/commands/update-status.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { EnumStatusCode } from '@wundergraph/cosmo-connect/dist/common/common_pb';
import { Command, InvalidArgumentError } from 'commander';
import pc from 'picocolors';
import { getBaseHeaders } from '../../../core/config.js';
import { BaseCommandOptions } from '../../../core/types/types.js';

const proposalStatuses = ['APPROVED', 'CLOSED'] as const;
type ProposalStatus = (typeof proposalStatuses)[number];

const parseProposalStatus = (value: string): ProposalStatus => {
const status = value.toUpperCase();
if (!proposalStatuses.includes(status as ProposalStatus)) {
throw new InvalidArgumentError('Allowed values are approved and closed.');
}
return status as ProposalStatus;
};

export default (opts: BaseCommandOptions) => {
const command = new Command('update-status');
command.description('Updates the status of an existing proposal for a federated graph.');
command.argument('<name>', 'The name of the proposal to update.');
command.requiredOption(
'-f, --federation-graph <federatedGraphName>',
'The name of the federated graph this proposal is for.',
);
command.requiredOption(
'-s, --status <status>',
'The status to set. Allowed values: approved, closed.',
parseProposalStatus,
);
command.option('-n, --namespace [string]', 'The namespace of the federated graph.', 'default');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -eu

printf '%s\n' '--- relevant files ---'
fd -i 'update-status|package.json|package-lock|yarn.lock|pnpm-lock' . | head -80

printf '%s\n' '--- command and documentation references ---'
rg -n -C 8 --glob 'update-status.ts' --glob 'update-status.mdx' -- '--namespace|namespace' .

printf '%s\n' '--- Commander declarations ---'
rg -n -C 3 --glob 'package.json' --glob '*lock*' '"commander"|commander@' . | head -120

printf '%s\n' '--- namespace call sites and types ---'
rg -n -C 5 --glob '*.{ts,tsx,js,jsx}' 'updateStatus|namespace' cli/src | head -240

Repository: wundergraph/cosmo

Length of output: 25824


🏁 Script executed:

#!/bin/bash
set -eu

tmpdir="$(mktemp -d)"
trap 'rm -rf "$tmpdir"' EXIT

curl -fsSL https://unpkg.com/commander@11.1.0/index.js -o "$tmpdir/index.js"
curl -fsSL https://unpkg.com/commander@11.1.0/lib/command.js -o "$tmpdir/command.js"
curl -fsSL https://unpkg.com/commander@11.1.0/lib/option.js -o "$tmpdir/option.js"
curl -fsSL https://unpkg.com/commander@11.1.0/package.json -o "$tmpdir/package.json"

printf '%s\n' '--- Commander option parsing source ---'
rg -n -C 6 'optional|required|true|argNot|parseOptions|value' "$tmpdir/command.js" "$tmpdir/option.js" | head -220

printf '%s\n' '--- standalone Commander 11.1.0 behavior probe ---'
cat > "$tmpdir/probe.mjs" <<'JS'
import { Command } from './index.js';

for (const optionSpec of ['-n, --namespace [string]', '-n, --namespace <namespace>']) {
  for (const argv of [
    ['node', 'probe', '--namespace'],
    ['node', 'probe', '--namespace', 'production'],
  ]) {
    const command = new Command();
    command.exitOverride();
    command.option(optionSpec, 'namespace', 'default');
    try {
      command.parse(argv);
      console.log(JSON.stringify({
        optionSpec,
        argv: argv.slice(2),
        namespace: command.opts().namespace,
        namespaceType: typeof command.opts().namespace,
      }));
    } catch (error) {
      console.log(JSON.stringify({
        optionSpec,
        argv: argv.slice(2),
        error: error.code ?? error.message,
      }));
    }
  }
}
JS
node "$tmpdir/probe.mjs"

printf '%s\n' '--- updateProposal declarations and tests ---'
rg -n -C 5 --glob '*.{ts,tsx}' 'updateProposal' cli/src cli/test cli/tests 2>/dev/null | head -180 || true
rg -n -C 4 --glob '*.{ts,tsx}' 'proposal update-status|update-status' cli | head -180 || true

Repository: wundergraph/cosmo

Length of output: 14478


🏁 Script executed:

#!/bin/bash
set -eu

tmpdir="$(mktemp -d)"
trap 'rm -rf "$tmpdir"' EXIT
mkdir "$tmpdir/commander"
curl -fsSL https://registry.npmjs.org/commander/-/commander-11.1.0.tgz | tar -xzf - -C "$tmpdir/commander" --strip-components=1

printf '%s\n' '--- standalone Commander 11.1.0 behavior probe ---'
cat > "$tmpdir/probe.cjs" <<'JS'
const { Command } = require('./commander');

for (const optionSpec of ['-n, --namespace [string]', '-n, --namespace <namespace>']) {
  for (const argv of [
    ['node', 'probe', '--namespace'],
    ['node', 'probe', '--namespace', 'production'],
  ]) {
    const command = new Command();
    command.exitOverride();
    command.option(optionSpec, 'namespace', 'default');
    try {
      command.parse(argv);
      const namespace = command.opts().namespace;
      console.log(JSON.stringify({
        optionSpec,
        argv: argv.slice(2),
        namespace,
        namespaceType: typeof namespace,
      }));
    } catch (error) {
      console.log(JSON.stringify({
        optionSpec,
        argv: argv.slice(2),
        error: error.code ?? error.message,
      }));
    }
  }
}
JS
(
  cd "$tmpdir"
  node probe.cjs
)

printf '%s\n' '--- relevant Commander parser branches ---'
rg -n -C 12 'optional|presetArg|processOption|missing argument|arg ===|value = true' "$tmpdir/commander/lib/command.js" "$tmpdir/commander/lib/option.js" | head -260

printf '%s\n' '--- updateProposal declarations and namespace types ---'
rg -n -C 8 --glob '*.{ts,tsx}' 'updateProposal' cli | head -220 || true
rg -n -C 5 --glob '*.{ts,tsx}' 'namespace\??: string|namespace: string|namespace\?: string' cli/src cli | head -160 || true

Repository: wundergraph/cosmo

Length of output: 34369


Require a value for --namespace. Change [string] to <namespace>. Update docs-website/cli/proposal/update-status.mdx to match.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cli/src/commands/proposal/commands/update-status.ts` at line 31, Require an
explicit value for the namespace option by changing the option declaration in
the update-status command from an optional argument to a required one, using the
existing namespace option symbol. Update the corresponding usage documentation
in update-status.mdx to show the required namespace argument.


command.action(async (name, options) => {
const resp = await opts.client.platform.updateProposal(
{
proposalName: name,
federatedGraphName: options.federationGraph,
namespace: options.namespace,
updateAction: {
case: 'state',
value: options.status,
},
},
{
headers: getBaseHeaders(),
},
);

if (resp.response?.code === EnumStatusCode.OK) {
console.log(pc.green(`Proposal '${name}' status was updated to ${options.status} successfully.`));
return;
}

console.error(pc.red(resp.response?.details || `Failed to update status for proposal '${name}'.`));
process.exitCode = 1;
});

return command;
};
2 changes: 2 additions & 0 deletions cli/src/commands/proposal/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ import { Command } from 'commander';
import { BaseCommandOptions } from '../../core/types/types.js';
import { checkAuth } from '../auth/utils.js';
import CreateProposalCommand from './commands/create.js';
import UpdateProposalStatusCommand from './commands/update-status.js';
import UpdateProposalCommand from './commands/update.js';

export default (opts: BaseCommandOptions) => {
const command = new Command('proposal');
command.description('Provides commands for creating and maintaining proposals for a federated graph');
command.addCommand(CreateProposalCommand(opts));
command.addCommand(UpdateProposalCommand(opts));
command.addCommand(UpdateProposalStatusCommand(opts));

command.hook('preAction', async (thisCmd) => {
await checkAuth();
Expand Down
128 changes: 128 additions & 0 deletions cli/test/update-proposal-status.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import { type MessageInitShape } from '@bufbuild/protobuf';
import { createClient, createRouterTransport } from '@connectrpc/connect';
import { EnumStatusCode } from '@wundergraph/cosmo-connect/dist/common/common_pb';
import {
PlatformService,
type UpdateProposalRequest,
UpdateProposalResponseSchema,
} from '@wundergraph/cosmo-connect/dist/platform/v1/platform_pb';
import { Command } from 'commander';
import { afterEach, beforeEach, describe, expect, test, vi, type MockInstance } from 'vitest';
import UpdateProposalStatusCommand from '../src/commands/proposal/commands/update-status.js';
import { Client } from '../src/core/client/client.js';

function createMockTransport(
response: MessageInitShape<typeof UpdateProposalResponseSchema>,
onUpdateProposal?: (req: UpdateProposalRequest) => void,
) {
return createRouterTransport(({ service }) => {
service(PlatformService, {
updateProposal: (req) => {
onUpdateProposal?.(req);
return response;
},
});
});
}

async function runUpdateStatus(
response: MessageInitShape<typeof UpdateProposalResponseSchema>,
args: string[] = [],
onUpdateProposal?: (req: UpdateProposalRequest) => void,
): Promise<void> {
const client: Client = {
platform: createClient(PlatformService, createMockTransport(response, onUpdateProposal)),
};
const program = new Command();
program.exitOverride();
const command = UpdateProposalStatusCommand({ client });
command.exitOverride();
program.addCommand(command);
await program.parseAsync(
['update-status', 'my-proposal', '--federation-graph', 'my-graph', '--status', 'approved', ...args],
{ from: 'user' },
);
}

describe('update proposal status', () => {
let logSpy: MockInstance<typeof console.log>;
let errorSpy: MockInstance<typeof console.error>;

beforeEach(() => {
logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
});

afterEach(() => {
process.exitCode = undefined;
vi.restoreAllMocks();
});

test('approves a proposal in the default namespace', async () => {
let request: UpdateProposalRequest | undefined;

await runUpdateStatus({ response: { code: EnumStatusCode.OK } }, [], (req) => {
request = req;
});

expect(request).toMatchObject({
proposalName: 'my-proposal',
federatedGraphName: 'my-graph',
namespace: 'default',
updateAction: {
case: 'state',
value: 'APPROVED',
},
});
expect(logSpy).toHaveBeenCalledWith(
expect.stringContaining("Proposal 'my-proposal' status was updated to APPROVED successfully."),
);
expect(errorSpy).not.toHaveBeenCalled();
expect(process.exitCode).toBeUndefined();
});

test('closes a proposal in an explicitly provided namespace', async () => {
let request: UpdateProposalRequest | undefined;

await runUpdateStatus(
{ response: { code: EnumStatusCode.OK } },
['--status', 'CLOSED', '--namespace', 'production'],
(req) => {
request = req;
},
);

expect(request).toMatchObject({
namespace: 'production',
updateAction: {
case: 'state',
value: 'CLOSED',
},
});
});

test('rejects statuses that cannot be set manually', async () => {
let updateCalled = false;

await expect(
runUpdateStatus({ response: { code: EnumStatusCode.OK } }, ['--status', 'published'], () => {
updateCalled = true;
}),
).rejects.toThrow('Allowed values are approved and closed.');

expect(updateCalled).toBe(false);
});

test('prints the control-plane error and sets a non-zero exit code', async () => {
await runUpdateStatus({
response: {
code: EnumStatusCode.ERR_NOT_FOUND,
details: 'Proposal my-proposal not found',
},
});

expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('Proposal my-proposal not found'));
expect(logSpy).not.toHaveBeenCalled();
expect(process.exitCode).toBe(1);
});
});
4 changes: 4 additions & 0 deletions docs-website/cli/proposal.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,7 @@ The `proposal` command and its subcommands provide functionality to manage propo
<Card title="Update a proposal" href="/cli/proposal/update" icon="pencil">
Update an existing proposal for a federated graph
</Card>

<Card title="Update a proposal status" href="/cli/proposal/update-status" icon="arrows-rotate">
Approve or close an existing proposal from a local or CI environment
</Card>
52 changes: 52 additions & 0 deletions docs-website/cli/proposal/update-status.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
---
title: "Update Status"
description: "Updates the status of an existing proposal for a federated graph."
icon: arrows-rotate
---

## Usage

```bash
npx wgc proposal update-status <name> --federation-graph <federated-graph-name> --status <status> [options]
```

## Description

The `npx wgc proposal update-status` command updates an existing proposal's review status. The command is non-interactive, which makes it suitable for CI workflows.

The API key used by the command must have write access to the federated graph.

## **Parameters**

- `[name]`: The name of the proposal to update.

## **Options**

- `-f, --federation-graph <federatedGraphName>` (required): The name of the federated graph this proposal is for.
- `-s, --status <status>` (required): The status to set. Accepted values are `approved` and `closed`. Values are case-insensitive.
- `-n, --namespace [namespace]`: The namespace of the federated graph (Default: `default`).

## **CI examples**

Configure an API key as a secret in your CI system and expose it as `COSMO_API_KEY` before running the command.

Approve a proposal:

```bash
export COSMO_API_KEY=<API_KEY>
npx wgc proposal update-status product-changes \
--federation-graph my-graph \
--namespace production \
--status approved
```

Close a proposal:

```bash
npx wgc proposal update-status product-changes \
--federation-graph my-graph \
--namespace production \
--status closed
```

The command exits with a non-zero status when the proposal status cannot be updated, allowing the CI job to fail immediately.
8 changes: 8 additions & 0 deletions docs-website/concepts/proposals.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,14 @@ npx wgc proposal update <name> --federation-graph <federated-graph-name> (--subg

**Note**: When updating a proposal, any subgraphs you specify will completely replace the corresponding subgraphs in the existing proposal. The update is not incremental.

### Updating a Proposal Status

Use the [`wgc proposal update-status`](/cli/proposal/update-status) command to approve or close an existing proposal. The command is non-interactive and can be used in CI with a `COSMO_API_KEY` that has write access to the federated graph:

```bash
npx wgc proposal update-status <name> --federation-graph <federated-graph-name> --status <approved|closed> [--namespace <namespace>]
```

## Configuring Proposals

<Frame>
Expand Down
2 changes: 1 addition & 1 deletion docs-website/docs.json
Original file line number Diff line number Diff line change
Expand Up @@ -672,7 +672,7 @@
{
"group": "Proposal",
"icon": "file-circle-plus",
"pages": ["cli/proposal", "cli/proposal/create", "cli/proposal/update"]
"pages": ["cli/proposal", "cli/proposal/create", "cli/proposal/update", "cli/proposal/update-status"]
}
]
}
Expand Down
Loading