Debian Codegraph @

docs/style_guide.md

raw
1 # Style guide
2
3 ## Panics
4
5 Panics are not allowed, especially in code that may run on a server. Calling
6 `.unwrap()` is okay if it's guaranteed to be safe by previous checks or
7 documented invariants. For example, if a function is documented as requiring a
8 non-empty slice as input, it's fine to call `slice[0]` and panic.
9
10 ## Markdown
11
12 Try to wrap at 80 columns. We don't have a formatter yet.
13
14 ## Prefer lower-level tests to end-to-end tests
15
16 When possible, prefer lower-level tests that don't use the `jj` binary.
17 End-to-end tests are much slower than similar tests that create a repo using
18 `jj-lib` (roughly 100x slower). It's also often easier to test edge cases in
19 lower-level tests.
20
21 It can still be useful to add a test case or two to check that the lower-level
22 functionality is correctly hooked up in the CLI. For example, the end-to-end
23 tests for `jj log` don't need to test that all kinds of revsets are evaluated
24 correctly (we have tests in `jj-lib` for that), but they should check that the
25 `-r` flag is respected.
26
27 Use end-to-end tests for testing the CLI commands themselves.
28
29 ## Logging messages
30
31 When messages are logged, such as with `writeln!(ui.status(), "Message...")?;`,
32 prefer to end the message with a period as if it were a full sentence. For
33 example:
34
35 ```rust
36 // CORRECT:
37 writeln!(ui.status(), "Rebased {num_rebased} descendant commits.")?;
38 // INCORRECT:
39 writeln!(ui.status(), "Rebased {num_rebased} descendant commits")?;
40 ```
41
42 There are of course exceptions to this, such as messages that are printing
43 interpolated values at the end, or need to print some templated value:
44
45 ```rust
46 // These are fine:
47 writeln!(
48 ui.status(),
49 "Operation left uncommitted because --no-integrate-operation was requested: {}",
50 short_operation_hash(self.repo().op_id())
51 )?;
52 writeln!(ui.warning_default(), "No matching entries for paths: {paths}")?;
53 ```
54
55 Also try not to put periods right after any printed IDs or symbols (such as
56 commit IDs), since users may double click to copy the value, which may include
57 the period.
58
59 ## Documentation comments
60
61 ### General
62
63 In general, try to follow [`rust-lang/rfcs` 1574][rust-lang/rfcs-1574]. The
64 important points are:
65
66 - Use documentation comments (`///`) on types, functions, and fields.
67
68 - Use Markdown where appropriate, such as for symbols, code blocks, headings,
69 etc.
70
71 - The first line of a doc comment should be a single-line short sentence that
72 summarizes the element being described. There is no hard rule for "short", but
73 try to make it both clear and succinct.
74 - Since doc comments are interpreted as Markdown, there must be a blank
75 comment line between this first line and the rest of the comment:
76
77 ```rust
78 // CORRECT:
79
80 /// Foos the given `bar` and `baz`.
81 ///
82 /// More description about this very important function.
83 fn foo(bar: &Bar, baz: &Baz) { ... }
84 ```
85
86 ```rust
87 // INCORRECT: This entire comment will be interpreted as the "first line".
88
89 /// Foos the given `bar` and `baz`.
90 /// More description about this very important function.
91 fn foo(bar: &Bar, baz: &Baz) { ... }
92 ```
93
94 - For functions, this summary line should be written in third-person singular
95 present indicative form ("Returns ..." instead of "Return ..."). You can
96 imagine an implicit "This function..." or the function's name before the
97 summary line.
98
99 - The rest of the comment after the first line should generally be written in
100 complete sentences. But use your own judgment too; for example a sentence that
101 says "Returns blah blah." would be fine.
102
103 - Prefer Itertools `collect_vec()` and `try_collect()` over annotated
104 `.collect::<Vec<...>>()` calls.
105
106 ```rust
107 // CORRECT:
108
109 let commits = workspace_helper.parse_union_revsets(&revs)
110 .ids()
111 .collect_vec();
112
113 let fallible_commits = commits.iter().map(|c| store.get(c))
114 .try_collect()?;
115 ```
116
117 ```rust
118 // INCORRECT: The annotation is used
119
120 let commits: Vec<_> = workspace_helper.parse_union_revsets(&revs)
121 .ids()
122 .collect();
123
124 let fallible_commits = commits.iter().map(|c| store.get(c))
125 .collect::<Vec<_, CommandError>>()?;
126 ```
127 [rust-lang/rfcs-1574]:
128 https://github.com/rust-lang/rfcs/blob/master/text/1574-more-api-documentation-conventions.md
129
130 ### Subcommand comments
131
132 Specifically for `jj` subcommands:
133
134 - Doc comments for subcommands should describe its corresponding `*Args` struct.
135 For example, documentation for `jj new` goes on `struct NewArgs`.
136
137 - As above, write an appropriate short first line for the command, but do not
138 include a trailing period / full stop. See `jj -h` for examples (`--help` will
139 show the full doc comment for each command, while the short form `-h` will
140 only show the first line).
141 - Use imperative mood, as if you are telling the command what to do (giving it
142 a command, if you will).
143
144 - If the subcommand is actually a "collection" of subcommands (such as
145 `jj config` or `jj bookmark`), prefer to use the format "Manage ...", such
146 as "Manage config options" or "Manage bookmarks". But use your own judgment;
147 if it sounds awkward, "Commands for ..." or whatever you come up with would
148 probably be fine.
149
150 ```
151 CORRECT:
152 $ jj new -h
153 Create a new, empty change and (by default) edit it in the working copy
154
155 $ jj bookmark create -h
156 Create a new bookmark
157 ```
158
159 ```
160 INCORRECT:
161 $ jj new -h
162 Creates a new, empty change. The default behavior is to immediately edit this new change, but pass `--no-edit` to avoid this.
163
164 $ jj bookmark create -h
165 Creates new bookmarks with the given names and assigns them to the given target revision, which defaults to `@`.
166 ```
167
168 - The rest of the command documentation should be written in complete sentences.
169
170 - If the command requires complex explanation, such as `jj rebase`, prefer to
171 fully explain it in the command's doc comment rather than in some other online
172 documentation page so that all the relevant info can still be accessed via the
173 CLI.
174 - For example, `jj rebase --help`.
175 - Markdown can be used, but make sure to use at least level 3 headings (`###`
176 or more). The CLI reference page uses level 2 headings for each command
177 (e.g., `## jj root`), so the Table of Contents might break if any command
178 documentation uses level 1 or level 2 headings.
179
180 - Default aliases (i.e., those defined in [`misc.toml`][misc.toml]) are not
181 automatically shown by `clap`, since it doesn't know about them. Mention these
182 at the end of the first line for the command in question in the format
183 `[default alias: <alias>]`. For example, the first line of `jj describe` is:
184
185 ```
186 Update the change description or other metadata [default alias: desc]
187 ```
188
189 - Very loose guidance, but if you are adding a new command, prefer single
190 "action" words (e.g., verbs) over compound words or portmanteaus. It can be a
191 good idea to add a new subcommand instead. Please ask for feedback on names if
192 you are struggling to come up with something or are unsure about a name.
193
194 - If you are unsure how your comment will look after being processed, run the
195 `test_generate_markdown_docs_in_docs_dir` test to generate
196 `[email protected]`.
197
198 [misc.toml]: https://github.com/jj-vcs/jj/blob/main/cli/src/config/misc.toml
199
200 ### Command argument / option comments
201
202 Specifically for `jj` command arguments / options:
203
204 - As above, write an appropriate short first line for the arg, but do not
205 include a trailing period / full stop. See `jj <command> -h` for examples
206 (`--help` will show the full doc comment for each arg, while the short form
207 `-h` will only show the first line).
208 - Since arguments can be things or actions or whatever, there is no hard rule
209 for the form of the first line. If it is a noun, such as `-R`/`--repository`
210 or `--config`, a good first line could be the answer to the question "What
211 is `<arg>`?" If it is a verb, such as `--quiet`, try to stick with
212 imperative mood (as if you're telling the command how to behave if this flag
213 is present). Use your own judgment for what might be clearest for users.
214
215 - If the argument can be repeated, append "(can be repeated)" to the end of
216 the first line.
217
218 - If the argument can be repeated, prefer to make the argument name singular
219 instead of plural, but speak about the "things" in the plural in the
220 documentation. This makes the experience of specifying the values on the
221 command line simpler and more consistent.
222 - Note that the name of the struct field can be different from the name of
223 the argument according to `clap`:
224 ```rust
225 #[arg(long = "flag")]
226 my_values: MyType,
227 ```
228 This section is mostly discussing the user-facing argument / option names;
229 how you name variables is up to you.
230
231 ```
232 CORRECT / PREFERRED:
233 --ignore-working-copy Don't snapshot the working copy, and don't update it
234 --quiet Silence non-primary command output
235 --no-pager Disable the pager
236 --config <NAME=VALUE> Additional configuration options (can be repeated)
237 ```
238
239 ```
240 INCORRECT / LESS PREFERRED:
241 --ignore-working-copy No snapshotting (so working copy is ignored).
242 --quiet Provide this option to skip non-primary command output.
243 --no-pager Disables the pager.
244 --configs <NAME=VALUE> Override some configuration options.
245 ```
246
247 - Short options and visible aliases are automatically shown by `clap`, so no
248 need to mention them explicitly (for simple cases). However, it may be good to
249 mention conflicting arguments / options or how options interact with each
250 other if applicable.
251
252 - If an argument has a default value, mention what it is, probably in the full
253 description (i.e., not the first line).
254 - In cases where this default comes from a configurable setting, such as
255 `revsets.log` for `--revisions` in `jj log`, mention the setting. Prefer not
256 to also spell out the default value of the setting, since that introduces
257 toil and potential inconsistency if the default ever changes in the future.
258
259 - If you are unsure how your comment will look after being processed, run the
260 `test_generate_markdown_docs_in_docs_dir` test to generate
261 `[email protected]`.
262
263 ### Fileset / revset / templating language functions
264
265 (Note: In the templating language, this guidance also applies to all type
266 methods.)
267
268 #### Function signatures
269
270 - Function signatures are written similar to Rust:
271
272 ```
273 function_name(arg1: Type1, arg2: Type2) -> ReturnType
274 ```
275
276 (Note that types are only applicable to the templating language and can be
277 omitted from the fileset and revset language documentation.)
278
279 - For optional parameters, put square brackets around the `arg: Type` part;
280 importantly, do not put the brackets around any surrounding commas.
281
282 ```
283 CORRECT:
284 parents(x, [depth])
285 if(condition: Boolean, then: Template, [else: Template]) -> Template
286 ```
287
288 ```
289 INCORRECT:
290 parents(x[, depth])
291 if(condition: Boolean, then: Template[, else]) -> Template
292 ```
293
294 - For named parameters (rare), put the parameter name in the format `[name=]`
295 before the `arg: Type` part, with no spaces. Note that this should also be
296 included in the square brackets indicating that the parameter is optional.
297 `name` and `arg` may be the same, but they don't have to be.
298
299 (Note that currently, named parameters must be optional, since they are
300 intended as a way for users to skip previous optional parameters and provide a
301 later one instead. However, this may change in the future, especially if named
302 parameters make their way to the templating language.)
303
304 ```
305 CORRECT:
306 remote_bookmarks([name_pattern], [[remote=]remote_pattern])
307 ```
308
309 ```
310 INCORRECT:
311 remote_bookmarks([name_pattern], [remote] = [remote_pattern])
312 remote_bookmarks([name_pattern], [remote=remote_pattern])
313 ```
314
315 - For variadic parameters, add an ellipsis (`...`) after the `arg: Type` part.
316
317 ```
318 CORRECT:
319 coalesce(revsets...)
320 concat(content: Template...) -> Template
321 ```
322
323 ```
324 INCORRECT:
325 coalesce(...revsets)
326 concat(*content: Template) -> Template
327 ```
328
329 #### Descriptions
330
331 - For the first sentence:
332 - In the fileset language, "functions" act as "filters for files". Follow the
333 general Rust style of writing the first sentence in third-person singular
334 present indicative form.
335
336 - In the revset language, "functions" evaluate to "a set of revisions".
337 Writing a "Returns" prefix for every function is redundant and unnecessary;
338 instead, write the first sentence as if there is an implicit "The return
339 value is..." or "The return values are..." in front of the first sentence.
340
341 - In the templating language, "functions" will "accept inputs, do things, and
342 return an output". Follow the general Rust style of writing the first
343 sentence in third-person singular present indicative form.
344
345 ```
346 CORRECT:
347 all(): Matches all files.
348
349 root(): The virtual commit that is the oldest ancestor of all other commits.
350 none(): No commits.
351 none(): Nothing.
352
353 json(value: Serialize) -> String: Serializes `value` in JSON format.
354 ```
355
356 ```
357 INCORRECT:
358 all(): All files.
359
360 root(): Returns the virtual commit that is the oldest ancestor of all other commits.
361 none(): Returns nothing.
362
363 json(value: Serialize) -> String: Serialize `value` in JSON format.
364 json(value: Serialize) -> String: The `value` in JSON format.
365 ```
366
367 - All following sentences should be written as complete sentences.
368
369 - We tend to write the entire description as a single paragraph following the
370 function signature, but add line breaks for any examples of usages.
371
372 - Use `backticks` to reference arguments of the function instead of simply
373 saying "the content" or "the width".
374
375 - If a parameter's purpose is obvious, it does not need to be explicitly
376 mentioned in the description, but try to make sure it is clear what all
377 parameters do.
378
379 - Mention default values for optional parameters, or what happens if not given.
380
381 - Call out edge cases if applicable.
382
383 - For type methods in the templating language, try to document every method,
384 even if obvious. This will give you the chance to mention any edge cases,
385 default behaviors, or differences from other methods.