@sous-io/sous 0.2.16 → 0.2.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,25 +1,49 @@
1
- import { Command, Flags } from "@oclif/core";
2
- import { findRepoRoot, submitRepo } from "../../lib/repos/release/index.js";
1
+ import { Args, Command, Flags } from "@oclif/core";
2
+ import { discoverConfig, refreshDiscoveredConfig } from "../../lib/config-discovery.js";
3
+ import { loadEnvFiles } from "../../lib/env-local.js";
4
+ import { isInteractive } from "../../lib/interactive.js";
5
+ import { enabledRepos } from "../../lib/repos/defaults.js";
6
+ import {
7
+ findRepoRoot,
8
+ renderChangelog,
9
+ submitRepo,
10
+ type SubmitResult,
11
+ } from "../../lib/repos/release/index.js";
12
+ import {
13
+ findSubmitCheckout,
14
+ type SubmitProject,
15
+ } from "../../lib/repos/release/submit-checkout.js";
16
+ import { submitQuestions } from "../../lib/repos/release/submit-questions.js";
17
+ import type { ProposalStatus } from "../../lib/repos/providers/provider.js";
18
+ import { loadSettings } from "../../lib/settings.js";
3
19
  import { reportCommandError } from "../../utils/command-errors.js";
4
- import { nonInteractiveFlag } from "../../utils/flags.js";
20
+ import { confirmationFlag, nonInteractiveFlag } from "../../utils/flags.js";
5
21
  import {
22
+ BULLET,
6
23
  blankLine,
7
24
  dryRunNotice,
8
25
  footer,
9
26
  header,
10
27
  log,
28
+ note,
29
+ paragraph,
11
30
  section,
12
31
  showCommandVars,
13
32
  showVariables,
33
+ warning,
14
34
  } from "../../utils/formatting.js";
15
35
 
16
36
  /**
17
- * `sous repo submit` proposes the committed changes in a recipe repository to
18
- * that repository's maintainers.
37
+ * `sous repo submit` carries a proposed change to a recipe repository's
38
+ * maintainers through its whole life: it opens the proposal, updates it when
39
+ * there is more to send, reports where it stands, and starts the next one once
40
+ * it was merged.
19
41
  *
20
42
  * Like `sous repo init` and `sous repo release`, this command does NOT extend
21
- * BaseCommand: it runs inside a RECIPE repository, which is not a sous project
22
- * and has no `.sous/` directory of its own.
43
+ * BaseCommand: it runs inside a RECIPE repository, which is not a sous project.
44
+ * It can also be run from a project, naming a repository the project links, and
45
+ * then looks for the project's config itself, optionally: finding none is not a
46
+ * failure while the working directory is inside a recipe repository.
23
47
  *
24
48
  * Submitting never publishes and never writes to a repository directly. Sous
25
49
  * validates first, then hands the fork, branch and pull request mechanics to the
@@ -29,7 +53,7 @@ import {
29
53
  */
30
54
  export default class RepoSubmit extends Command {
31
55
  static description =
32
- "Propose this recipe repository's committed changes to its maintainers";
56
+ "Propose a recipe repository's changes to its maintainers, and follow the proposal through";
33
57
 
34
58
  /**
35
59
  * The other spelling of the topic. It lives under a hidden topic, so it is
@@ -38,25 +62,46 @@ export default class RepoSubmit extends Command {
38
62
  static aliases = ["repos:submit"];
39
63
 
40
64
  static examples = [
41
- "<%= config.bin %> repo submit",
42
- '<%= config.bin %> repo submit --title "Add a linting recipe"',
43
- "<%= config.bin %> repo submit --draft",
65
+ '<%= config.bin %> repo submit --title "Add a linting recipe" --body "Adds lint rules."',
66
+ "<%= config.bin %> repo submit sous-recipes",
67
+ "<%= config.bin %> repo submit --status",
68
+ "<%= config.bin %> repo submit --commit --yes --title \"Fix a typo\" --body \"Fixes it.\"",
44
69
  "<%= config.bin %> repo submit --dry-run",
45
70
  ];
46
71
 
72
+ static args = {
73
+ repo: Args.string({
74
+ description: "The linked repository to propose a change from, when run inside a project",
75
+ required: false,
76
+ }),
77
+ };
78
+
47
79
  static flags = {
48
80
  title: Flags.string({
49
- description: "Title for the proposal. Defaults to the last commit's subject.",
81
+ description: "The proposal's title; required for a new proposal, and replaces an open one's",
50
82
  }),
51
83
  body: Flags.string({
52
- description: "Body for the proposal. Defaults to a summary sous writes.",
84
+ description:
85
+ "The proposal's description; required for a new proposal, and replaces an open one's",
86
+ }),
87
+ branch: Flags.string({
88
+ description: "The branch to work with, instead of the one that is checked out",
89
+ }),
90
+ status: Flags.boolean({
91
+ description: "Only report where the branch's proposal stands",
92
+ default: false,
93
+ }),
94
+ commit: Flags.boolean({
95
+ description: "Commit uncommitted changes for you, after listing them and asking once",
96
+ default: false,
53
97
  }),
54
98
  draft: Flags.boolean({
55
- description: "Open the proposal as a draft",
99
+ description: "Open a new proposal as a draft",
56
100
  default: false,
57
101
  }),
102
+ yes: confirmationFlag(),
58
103
  "dry-run": Flags.boolean({
59
- description: "Check everything and print the plan without sending anything",
104
+ description: "Check everything and print the plan without writing or sending anything",
60
105
  default: false,
61
106
  }),
62
107
  // This command does not extend BaseCommand, so it declares the global
@@ -70,30 +115,121 @@ export default class RepoSubmit extends Command {
70
115
  }
71
116
 
72
117
  async run(): Promise<void> {
73
- const { flags } = await this.parse(RepoSubmit);
118
+ const { args, flags } = await this.parse(RepoSubmit);
74
119
  const dryRun = flags["dry-run"];
75
- const rootDir = findRepoRoot(process.cwd());
120
+ const interactive = isInteractive();
121
+ const cwd = process.cwd();
76
122
 
77
123
  showCommandVars({
78
- Repository: rootDir,
79
- Title: flags.title ?? "(the last commit's subject)",
80
- Draft: flags.draft,
81
- "Dry Run": dryRun,
124
+ "Working directory": cwd,
125
+ Repository: args.repo ?? "(the one the working directory is in)",
126
+ Branch: flags.branch ?? "(the one that is checked out)",
127
+ Mode: flags.status ? "Status only" : dryRun ? "Dry run" : "Propose",
128
+ });
129
+
130
+ const checkout = await findSubmitCheckout({
131
+ cwd,
132
+ ...(args.repo === undefined ? {} : { repo: args.repo }),
133
+ ...(await this.projectFor(cwd, args.repo)),
134
+ interactive,
135
+ });
136
+
137
+ section("The checkout");
138
+ showVariables({
139
+ Checkout: checkout.rootDir,
140
+ ...(checkout.repo === undefined ? {} : { Repository: checkout.repo }),
82
141
  });
142
+ blankLine();
143
+ note(checkout.reason);
144
+ for (const entry of checkout.notes) note(entry);
83
145
 
84
- section("Proposing a change");
146
+ section(flags.status ? "Looking the proposal up" : "Proposing a change");
85
147
 
86
148
  const result = await submitRepo({
87
- rootDir,
88
- title: flags.title,
89
- body: flags.body,
149
+ rootDir: checkout.rootDir,
150
+ ...(flags.title === undefined ? {} : { title: flags.title }),
151
+ ...(flags.body === undefined ? {} : { body: flags.body }),
152
+ ...(flags.branch === undefined ? {} : { branch: flags.branch }),
153
+ statusOnly: flags.status,
154
+ commit: flags.commit,
90
155
  draft: flags.draft,
91
156
  dryRun,
157
+ questions: submitQuestions({ interactive, yes: flags.yes }),
92
158
  onStep: (message) => log(` ${message}`),
93
- onNotice: (message) => (dryRun ? dryRunNotice(message) : log(` ${message}`)),
159
+ onNotice: (message) => (dryRun ? dryRunNotice(message) : note(message)),
160
+ onWarning: (message) => warning(message),
94
161
  });
95
162
 
96
- section(dryRun ? "What would be proposed" : "What was proposed");
163
+ this.report(result);
164
+ footer();
165
+ }
166
+
167
+ /**
168
+ * The project around the working directory, when the run needs one: always
169
+ * when a repository was named, and otherwise only when the working directory
170
+ * is not a recipe repository itself (the checkout finder decides that; a
171
+ * project found here is simply handed to it). A project whose config does not
172
+ * load is an error, because the run cannot say what the argument names.
173
+ *
174
+ * @param cwd - The working directory.
175
+ * @param repo - The repository the command line named, when it named one.
176
+ */
177
+ private async projectFor(
178
+ cwd: string,
179
+ repo: string | undefined
180
+ ): Promise<{ project?: SubmitProject }> {
181
+ const discovered = discoverConfig(cwd, undefined);
182
+ if (discovered === null) return {};
183
+ if (repo === undefined && insideRecipeRepo(cwd)) return {};
184
+
185
+ loadEnvFiles(discovered.sousDir);
186
+ const refreshed = refreshDiscoveredConfig(discovered);
187
+ const settings = await loadSettings(refreshed);
188
+ return { project: { sousDir: refreshed.sousDir, repos: enabledRepos(settings) } };
189
+ }
190
+
191
+ /**
192
+ * Prints what the run did, or would do, as a key and value list followed by
193
+ * one sentence, and the changelog when one was generated.
194
+ *
195
+ * @param result - What the submission reported.
196
+ */
197
+ private report(result: SubmitResult): void {
198
+ const noun = result.proposalNoun;
199
+
200
+ if (result.outcome === "cancelled") {
201
+ blankLine();
202
+ log(" Nothing was written and nothing was sent.");
203
+ return;
204
+ }
205
+
206
+ if (result.outcome === "status") {
207
+ section(`The ${noun} for '${result.branch}'`);
208
+ if (result.status === undefined) {
209
+ showVariables({ Repository: `${result.repo.owner}/${result.repo.name}`, Branch: result.branch });
210
+ blankLine();
211
+ paragraph(`The branch '${result.branch}' has no ${noun}.`);
212
+ return;
213
+ }
214
+ showVariables(statusFacts(result, result.status));
215
+ return;
216
+ }
217
+
218
+ if (result.changelog !== undefined) {
219
+ section("What merging this changes");
220
+ printChangelog(renderChangelog(result.changelog));
221
+ }
222
+
223
+ const heading =
224
+ result.outcome === "created"
225
+ ? result.dryRun
226
+ ? `The ${noun} this would open`
227
+ : `The ${noun} that was opened`
228
+ : result.dryRun
229
+ ? `The ${noun} this would update`
230
+ : `The ${noun} for '${result.branch}'`;
231
+ section(heading);
232
+
97
233
  showVariables({
98
234
  Provider: result.provider,
99
235
  Repository: `${result.repo.owner}/${result.repo.name}`,
@@ -101,20 +237,29 @@ export default class RepoSubmit extends Command {
101
237
  "Target branch": result.baseBranch,
102
238
  "Pushed to": result.dryRun ? "(nothing was pushed)" : result.pushedTo,
103
239
  "Through a fork": result.usedFork,
104
- Title: result.title,
105
- Proposal: result.url ?? "(the provider printed no address)",
240
+ ...(result.title === undefined ? {} : { Title: result.title }),
241
+ ...(result.committed === undefined ? {} : { Committed: result.committed.join(", ") }),
242
+ Address: result.url ?? (result.dryRun ? "(not opened yet)" : "(the provider printed no address)"),
106
243
  });
107
244
 
245
+ if (result.status !== undefined && !result.dryRun) {
246
+ blankLine();
247
+ showVariables(statusFacts(result, result.status));
248
+ }
249
+
108
250
  blankLine();
109
251
  if (result.dryRun) {
110
- log(" Nothing was sent. Run the command again without --dry-run to propose it.");
252
+ log(" Nothing was written and nothing was sent.");
253
+ } else if (result.outcome === "created") {
254
+ paragraph(
255
+ `The ${noun} is open for review. The maintainers decide what happens next; sous ` +
256
+ `never publishes on their behalf.`
257
+ );
258
+ } else if (result.outcome === "updated") {
259
+ paragraph(`The ${noun} was updated with what this run sent.`);
111
260
  } else {
112
- log(" The maintainers decide what happens next; sous never publishes on their");
113
- log(" behalf. Anything they ask for goes on the same branch, and the proposal");
114
- log(" updates itself when you push again.");
261
+ paragraph(`There was nothing new to send, so the ${noun} was left as it was.`);
115
262
  }
116
-
117
- footer();
118
263
  }
119
264
 
120
265
  /**
@@ -129,3 +274,68 @@ export default class RepoSubmit extends Command {
129
274
  return this.exit(exitCode);
130
275
  }
131
276
  }
277
+
278
+ /**
279
+ * Prints the Markdown changelog for a terminal: the heading is already the
280
+ * section's, emphasis and code marks are dropped, a list item becomes a real
281
+ * bullet, and every line is wrapped.
282
+ *
283
+ * @param markdown - The changelog as it goes into the proposal.
284
+ */
285
+ function printChangelog(markdown: string): void {
286
+ const lines = markdown.split("\n").slice(2);
287
+ for (const raw of lines) {
288
+ const line = raw.replace(/\*\*/g, "").replace(/`/g, "");
289
+ if (line.trim().length === 0) {
290
+ blankLine();
291
+ } else if (line.startsWith("- ")) {
292
+ paragraph(`${BULLET} ${line.slice(2)}`, { indent: 4, hangingIndent: 2 });
293
+ } else {
294
+ paragraph(line);
295
+ }
296
+ }
297
+ }
298
+
299
+ /** True when the directory is inside a recipe repository. */
300
+ function insideRecipeRepo(cwd: string): boolean {
301
+ try {
302
+ findRepoRoot(cwd);
303
+ return true;
304
+ } catch {
305
+ return false;
306
+ }
307
+ }
308
+
309
+ /**
310
+ * The facts about where a proposal stands, as a key and value list.
311
+ *
312
+ * @param result - The submission, for the repository and the noun.
313
+ * @param status - What the provider reported.
314
+ */
315
+ function statusFacts(result: SubmitResult, status: ProposalStatus): Record<string, unknown> {
316
+ const { proposal } = status;
317
+ const state =
318
+ proposal.state === "open"
319
+ ? proposal.draft
320
+ ? "open, as a draft"
321
+ : "open"
322
+ : proposal.state === "merged"
323
+ ? "merged"
324
+ : "closed without being merged";
325
+ return {
326
+ [`The ${result.proposalNoun}`]: proposal.title,
327
+ State: state,
328
+ ...(status.review === undefined ? {} : { Review: status.review }),
329
+ ...(status.checks === undefined
330
+ ? {}
331
+ : {
332
+ Checks:
333
+ `${status.checks.passed} passed, ${status.checks.failed} failed, ` +
334
+ `${status.checks.pending} still running`,
335
+ }),
336
+ ...(status.mergeable === undefined
337
+ ? {}
338
+ : { Mergeable: status.mergeable ? "yes" : "no, it conflicts with its target branch" }),
339
+ ...(proposal.url === undefined ? {} : { Address: proposal.url }),
340
+ };
341
+ }
@@ -313,6 +313,26 @@ export function extensibleObject<Shape extends z.ZodRawShape>(shape: Shape) {
313
313
  return z.preprocess(stripExtensionKeys, z.strictObject(shape));
314
314
  }
315
315
 
316
+ /**
317
+ * The `submissions` block a repo manifest and a recipe manifest may both carry:
318
+ * whether the recipes it covers take proposed changes, and where to send a
319
+ * change instead when they do not. On a repo manifest it covers every recipe;
320
+ * on a recipe manifest it covers that recipe, and wins over the repository's.
321
+ *
322
+ * submissions:
323
+ * allowed: false
324
+ * instead: Propose changes in sous-io/sous, under recipes/core/sous-skills/.
325
+ */
326
+ export const submissionsSchema = extensibleObject({
327
+ /** Whether a proposed change to the covered recipes is accepted. Defaults to true. */
328
+ allowed: z.boolean().default(true),
329
+ /** Where a change should go instead, printed when one is proposed anyway. */
330
+ instead: z.string().min(1, "must not be empty").optional(),
331
+ });
332
+
333
+ /** A validated `submissions` block. */
334
+ export type Submissions = z.infer<typeof submissionsSchema>;
335
+
316
336
  // --- Error reporting ----------------------------------------------------------------------------
317
337
 
318
338
  /** Renders a zod issue path (`["variables",0,"name"]`) as `variables[0].name`. */
@@ -34,6 +34,7 @@ import {
34
34
  recipeNameSchema,
35
35
  relativePathSchema,
36
36
  semverVersionSchema,
37
+ submissionsSchema,
37
38
  variableNameSchema,
38
39
  } from "./common.js";
39
40
  import { parseDependencyRef } from "../ref.js";
@@ -301,6 +302,12 @@ export const recipeManifestSchema = extensibleObject({
301
302
  version: semverVersionSchema,
302
303
  /** One-paragraph summary, shown by `sous repo search` and `sous repo list`. */
303
304
  description: z.string().optional(),
305
+ /**
306
+ * Whether this recipe takes proposed changes, winning over the repository's
307
+ * own `submissions` block. A recipe whose files are copied in from somewhere
308
+ * else sets `allowed: false` and says where to go instead.
309
+ */
310
+ submissions: submissionsSchema.optional(),
304
311
  /**
305
312
  * Build dependencies: fetched and addressable here, but not added to the
306
313
  * project. Each entry is a bare ref naming a sibling recipe in this same
@@ -17,6 +17,7 @@ import {
17
17
  parseFormat,
18
18
  relativePathSchema,
19
19
  repoNameSchema,
20
+ submissionsSchema,
20
21
  } from "./common.js";
21
22
 
22
23
  /** A namespace declaration. Namespaces group recipes and are not versioned. */
@@ -48,6 +49,13 @@ export const repoManifestSchema = extensibleObject({
48
49
  * contributor is never left without a route.
49
50
  */
50
51
  contribute: z.string().min(1, "must not be empty").optional(),
52
+ /**
53
+ * Whether the repository's recipes take proposed changes. A recipe's own
54
+ * `submissions` block wins over this one. `sous repo submit` warns before
55
+ * proposing a change to a recipe that does not, and `sous repo release
56
+ * --check` fails a pull request that changes one.
57
+ */
58
+ submissions: submissionsSchema.optional(),
51
59
  /** Every namespace the repo publishes, keyed by namespace name. */
52
60
  namespaces: z.record(namespaceNameSchema, repoNamespaceSchema),
53
61
  /**
@@ -10,7 +10,8 @@
10
10
  * declare the `submit` feature (the local one, for instance) inherits four
11
11
  * methods that raise a ConfigError naming the provider and what was asked of
12
12
  * it, so a caller that skips the feature check gets a sentence rather than a
13
- * `TypeError`.
13
+ * `TypeError`. The three calls behind the `proposals` feature are refused the
14
+ * same way.
14
15
  */
15
16
 
16
17
  import { ConfigError } from "../../errors.js";
@@ -26,6 +27,10 @@ import type {
26
27
  ChangeProposal,
27
28
  FetchedIndex,
28
29
  ForkedRepo,
30
+ ProposalQuery,
31
+ ProposalStatus,
32
+ ProposalSummary,
33
+ ProposalUpdate,
29
34
  ProposedChange,
30
35
  ProviderCli,
31
36
  ProviderFeature,
@@ -187,6 +192,33 @@ export abstract class ProviderBase implements RepoProvider {
187
192
  throw this.unsupported("submit", "propose a change to it");
188
193
  }
189
194
 
195
+ // --- Proposals after the fact, refused unless a provider overrides them ----
196
+
197
+ async findProposal(
198
+ _repo: CanonicalRepo,
199
+ _query: ProposalQuery,
200
+ _options: ProviderOptions = {}
201
+ ): Promise<ProposalSummary | undefined> {
202
+ throw this.unsupported("proposals", "look for a proposal that is already open");
203
+ }
204
+
205
+ async proposalStatus(
206
+ _repo: CanonicalRepo,
207
+ _id: string,
208
+ _options: ProviderOptions = {}
209
+ ): Promise<ProposalStatus> {
210
+ throw this.unsupported("proposals", "report where a proposal stands");
211
+ }
212
+
213
+ async updateProposal(
214
+ _repo: CanonicalRepo,
215
+ _id: string,
216
+ _update: ProposalUpdate,
217
+ _options: ProviderOptions = {}
218
+ ): Promise<ProposedChange> {
219
+ throw this.unsupported("proposals", "change a proposal's title or body");
220
+ }
221
+
190
222
  /**
191
223
  * The refusal a provider gives when it is asked for something it never
192
224
  * claimed. It names the provider and the feature, so the caller learns why