]> git.ipfire.org Git - thirdparty/git.git/blob - Documentation/CodingGuidelines
Merge branch 'jc/codingstyle-compare-with-null'
[thirdparty/git.git] / Documentation / CodingGuidelines
1 Like other projects, we also have some guidelines to keep to the
2 code. For Git in general, a few rough rules are:
3
4 - Most importantly, we never say "It's in POSIX; we'll happily
5 ignore your needs should your system not conform to it."
6 We live in the real world.
7
8 - However, we often say "Let's stay away from that construct,
9 it's not even in POSIX".
10
11 - In spite of the above two rules, we sometimes say "Although
12 this is not in POSIX, it (is so convenient | makes the code
13 much more readable | has other good characteristics) and
14 practically all the platforms we care about support it, so
15 let's use it".
16
17 Again, we live in the real world, and it is sometimes a
18 judgement call, the decision based more on real world
19 constraints people face than what the paper standard says.
20
21 - Fixing style violations while working on a real change as a
22 preparatory clean-up step is good, but otherwise avoid useless code
23 churn for the sake of conforming to the style.
24
25 "Once it _is_ in the tree, it's not really worth the patch noise to
26 go and fix it up."
27 Cf. http://lkml.iu.edu/hypermail/linux/kernel/1001.3/01069.html
28
29 Make your code readable and sensible, and don't try to be clever.
30
31 As for more concrete guidelines, just imitate the existing code
32 (this is a good guideline, no matter which project you are
33 contributing to). It is always preferable to match the _local_
34 convention. New code added to Git suite is expected to match
35 the overall style of existing code. Modifications to existing
36 code is expected to match the style the surrounding code already
37 uses (even if it doesn't match the overall style of existing code).
38
39 But if you must have a list of rules, here they are.
40
41 For shell scripts specifically (not exhaustive):
42
43 - We use tabs for indentation.
44
45 - Case arms are indented at the same depth as case and esac lines,
46 like this:
47
48 case "$variable" in
49 pattern1)
50 do this
51 ;;
52 pattern2)
53 do that
54 ;;
55 esac
56
57 - Redirection operators should be written with space before, but no
58 space after them. In other words, write 'echo test >"$file"'
59 instead of 'echo test> $file' or 'echo test > $file'. Note that
60 even though it is not required by POSIX to double-quote the
61 redirection target in a variable (as shown above), our code does so
62 because some versions of bash issue a warning without the quotes.
63
64 (incorrect)
65 cat hello > world < universe
66 echo hello >$world
67
68 (correct)
69 cat hello >world <universe
70 echo hello >"$world"
71
72 - We prefer $( ... ) for command substitution; unlike ``, it
73 properly nests. It should have been the way Bourne spelled
74 it from day one, but unfortunately isn't.
75
76 - If you want to find out if a command is available on the user's
77 $PATH, you should use 'type <command>', instead of 'which <command>'.
78 The output of 'which' is not machine parsable and its exit code
79 is not reliable across platforms.
80
81 - We use POSIX compliant parameter substitutions and avoid bashisms;
82 namely:
83
84 - We use ${parameter-word} and its [-=?+] siblings, and their
85 colon'ed "unset or null" form.
86
87 - We use ${parameter#word} and its [#%] siblings, and their
88 doubled "longest matching" form.
89
90 - No "Substring Expansion" ${parameter:offset:length}.
91
92 - No shell arrays.
93
94 - No pattern replacement ${parameter/pattern/string}.
95
96 - We use Arithmetic Expansion $(( ... )).
97
98 - We do not use Process Substitution <(list) or >(list).
99
100 - Do not write control structures on a single line with semicolon.
101 "then" should be on the next line for if statements, and "do"
102 should be on the next line for "while" and "for".
103
104 (incorrect)
105 if test -f hello; then
106 do this
107 fi
108
109 (correct)
110 if test -f hello
111 then
112 do this
113 fi
114
115 - If a command sequence joined with && or || or | spans multiple
116 lines, put each command on a separate line and put && and || and |
117 operators at the end of each line, rather than the start. This
118 means you don't need to use \ to join lines, since the above
119 operators imply the sequence isn't finished.
120
121 (incorrect)
122 grep blob verify_pack_result \
123 | awk -f print_1.awk \
124 | sort >actual &&
125 ...
126
127 (correct)
128 grep blob verify_pack_result |
129 awk -f print_1.awk |
130 sort >actual &&
131 ...
132
133 - We prefer "test" over "[ ... ]".
134
135 - We do not write the noiseword "function" in front of shell
136 functions.
137
138 - We prefer a space between the function name and the parentheses,
139 and no space inside the parentheses. The opening "{" should also
140 be on the same line.
141
142 (incorrect)
143 my_function(){
144 ...
145
146 (correct)
147 my_function () {
148 ...
149
150 - As to use of grep, stick to a subset of BRE (namely, no \{m,n\},
151 [::], [==], or [..]) for portability.
152
153 - We do not use \{m,n\};
154
155 - We do not use -E;
156
157 - We do not use ? or + (which are \{0,1\} and \{1,\}
158 respectively in BRE) but that goes without saying as these
159 are ERE elements not BRE (note that \? and \+ are not even part
160 of BRE -- making them accessible from BRE is a GNU extension).
161
162 - Use Git's gettext wrappers in git-sh-i18n to make the user
163 interface translatable. See "Marking strings for translation" in
164 po/README.
165
166 - We do not write our "test" command with "-a" and "-o" and use "&&"
167 or "||" to concatenate multiple "test" commands instead, because
168 the use of "-a/-o" is often error-prone. E.g.
169
170 test -n "$x" -a "$a" = "$b"
171
172 is buggy and breaks when $x is "=", but
173
174 test -n "$x" && test "$a" = "$b"
175
176 does not have such a problem.
177
178
179 For C programs:
180
181 - We use tabs to indent, and interpret tabs as taking up to
182 8 spaces.
183
184 - We try to keep to at most 80 characters per line.
185
186 - As a Git developer we assume you have a reasonably modern compiler
187 and we recommend you to enable the DEVELOPER makefile knob to
188 ensure your patch is clear of all compiler warnings we care about,
189 by e.g. "echo DEVELOPER=1 >>config.mak".
190
191 - We try to support a wide range of C compilers to compile Git with,
192 including old ones. You should not use features from newer C
193 standard, even if your compiler groks them.
194
195 There are a few exceptions to this guideline:
196
197 . since early 2012 with e1327023ea, we have been using an enum
198 definition whose last element is followed by a comma. This, like
199 an array initializer that ends with a trailing comma, can be used
200 to reduce the patch noise when adding a new identifier at the end.
201
202 . since mid 2017 with cbc0f81d, we have been using designated
203 initializers for struct (e.g. "struct t v = { .val = 'a' };").
204
205 . since mid 2017 with 512f41cf, we have been using designated
206 initializers for array (e.g. "int array[10] = { [5] = 2 }").
207
208 These used to be forbidden, but we have not heard any breakage
209 report, and they are assumed to be safe.
210
211 - Variables have to be declared at the beginning of the block, before
212 the first statement (i.e. -Wdeclaration-after-statement).
213
214 - Declaring a variable in the for loop "for (int i = 0; i < 10; i++)"
215 is still not allowed in this codebase.
216
217 - NULL pointers shall be written as NULL, not as 0.
218
219 - When declaring pointers, the star sides with the variable
220 name, i.e. "char *string", not "char* string" or
221 "char * string". This makes it easier to understand code
222 like "char *string, c;".
223
224 - Use whitespace around operators and keywords, but not inside
225 parentheses and not around functions. So:
226
227 while (condition)
228 func(bar + 1);
229
230 and not:
231
232 while( condition )
233 func (bar+1);
234
235 - Do not explicitly compare an integral value with constant 0 or '\0',
236 or a pointer value with constant NULL. For instance, to validate that
237 counted array <ptr, cnt> is initialized but has no elements, write:
238
239 if (!ptr || cnt)
240 BUG("empty array expected");
241
242 and not:
243
244 if (ptr == NULL || cnt != 0);
245 BUG("empty array expected");
246
247 - We avoid using braces unnecessarily. I.e.
248
249 if (bla) {
250 x = 1;
251 }
252
253 is frowned upon. But there are a few exceptions:
254
255 - When the statement extends over a few lines (e.g., a while loop
256 with an embedded conditional, or a comment). E.g.:
257
258 while (foo) {
259 if (x)
260 one();
261 else
262 two();
263 }
264
265 if (foo) {
266 /*
267 * This one requires some explanation,
268 * so we're better off with braces to make
269 * it obvious that the indentation is correct.
270 */
271 doit();
272 }
273
274 - When there are multiple arms to a conditional and some of them
275 require braces, enclose even a single line block in braces for
276 consistency. E.g.:
277
278 if (foo) {
279 doit();
280 } else {
281 one();
282 two();
283 three();
284 }
285
286 - We try to avoid assignments in the condition of an "if" statement.
287
288 - Try to make your code understandable. You may put comments
289 in, but comments invariably tend to stale out when the code
290 they were describing changes. Often splitting a function
291 into two makes the intention of the code much clearer.
292
293 - Multi-line comments include their delimiters on separate lines from
294 the text. E.g.
295
296 /*
297 * A very long
298 * multi-line comment.
299 */
300
301 Note however that a comment that explains a translatable string to
302 translators uses a convention of starting with a magic token
303 "TRANSLATORS: ", e.g.
304
305 /*
306 * TRANSLATORS: here is a comment that explains the string to
307 * be translated, that follows immediately after it.
308 */
309 _("Here is a translatable string explained by the above.");
310
311 - Double negation is often harder to understand than no negation
312 at all.
313
314 - There are two schools of thought when it comes to comparison,
315 especially inside a loop. Some people prefer to have the less stable
316 value on the left hand side and the more stable value on the right hand
317 side, e.g. if you have a loop that counts variable i down to the
318 lower bound,
319
320 while (i > lower_bound) {
321 do something;
322 i--;
323 }
324
325 Other people prefer to have the textual order of values match the
326 actual order of values in their comparison, so that they can
327 mentally draw a number line from left to right and place these
328 values in order, i.e.
329
330 while (lower_bound < i) {
331 do something;
332 i--;
333 }
334
335 Both are valid, and we use both. However, the more "stable" the
336 stable side becomes, the more we tend to prefer the former
337 (comparison with a constant, "i > 0", is an extreme example).
338 Just do not mix styles in the same part of the code and mimic
339 existing styles in the neighbourhood.
340
341 - There are two schools of thought when it comes to splitting a long
342 logical line into multiple lines. Some people push the second and
343 subsequent lines far enough to the right with tabs and align them:
344
345 if (the_beginning_of_a_very_long_expression_that_has_to ||
346 span_more_than_a_single_line_of ||
347 the_source_text) {
348 ...
349
350 while other people prefer to align the second and the subsequent
351 lines with the column immediately inside the opening parenthesis,
352 with tabs and spaces, following our "tabstop is always a multiple
353 of 8" convention:
354
355 if (the_beginning_of_a_very_long_expression_that_has_to ||
356 span_more_than_a_single_line_of ||
357 the_source_text) {
358 ...
359
360 Both are valid, and we use both. Again, just do not mix styles in
361 the same part of the code and mimic existing styles in the
362 neighbourhood.
363
364 - When splitting a long logical line, some people change line before
365 a binary operator, so that the result looks like a parse tree when
366 you turn your head 90-degrees counterclockwise:
367
368 if (the_beginning_of_a_very_long_expression_that_has_to
369 || span_more_than_a_single_line_of_the_source_text) {
370
371 while other people prefer to leave the operator at the end of the
372 line:
373
374 if (the_beginning_of_a_very_long_expression_that_has_to ||
375 span_more_than_a_single_line_of_the_source_text) {
376
377 Both are valid, but we tend to use the latter more, unless the
378 expression gets fairly complex, in which case the former tends to
379 be easier to read. Again, just do not mix styles in the same part
380 of the code and mimic existing styles in the neighbourhood.
381
382 - When splitting a long logical line, with everything else being
383 equal, it is preferable to split after the operator at higher
384 level in the parse tree. That is, this is more preferable:
385
386 if (a_very_long_variable * that_is_used_in +
387 a_very_long_expression) {
388 ...
389
390 than
391
392 if (a_very_long_variable *
393 that_is_used_in + a_very_long_expression) {
394 ...
395
396 - Some clever tricks, like using the !! operator with arithmetic
397 constructs, can be extremely confusing to others. Avoid them,
398 unless there is a compelling reason to use them.
399
400 - Use the API. No, really. We have a strbuf (variable length
401 string), several arrays with the ALLOC_GROW() macro, a
402 string_list for sorted string lists, a hash map (mapping struct
403 objects) named "struct decorate", amongst other things.
404
405 - When you come up with an API, document its functions and structures
406 in the header file that exposes the API to its callers. Use what is
407 in "strbuf.h" as a model for the appropriate tone and level of
408 detail.
409
410 - The first #include in C files, except in platform specific compat/
411 implementations, must be either "git-compat-util.h", "cache.h" or
412 "builtin.h". You do not have to include more than one of these.
413
414 - A C file must directly include the header files that declare the
415 functions and the types it uses, except for the functions and types
416 that are made available to it by including one of the header files
417 it must include by the previous rule.
418
419 - If you are planning a new command, consider writing it in shell
420 or perl first, so that changes in semantics can be easily
421 changed and discussed. Many Git commands started out like
422 that, and a few are still scripts.
423
424 - Avoid introducing a new dependency into Git. This means you
425 usually should stay away from scripting languages not already
426 used in the Git core command set (unless your command is clearly
427 separate from it, such as an importer to convert random-scm-X
428 repositories to Git).
429
430 - When we pass <string, length> pair to functions, we should try to
431 pass them in that order.
432
433 - Use Git's gettext wrappers to make the user interface
434 translatable. See "Marking strings for translation" in po/README.
435
436 - Variables and functions local to a given source file should be marked
437 with "static". Variables that are visible to other source files
438 must be declared with "extern" in header files. However, function
439 declarations should not use "extern", as that is already the default.
440
441 - You can launch gdb around your program using the shorthand GIT_DEBUGGER.
442 Run `GIT_DEBUGGER=1 ./bin-wrappers/git foo` to simply use gdb as is, or
443 run `GIT_DEBUGGER="<debugger> <debugger-args>" ./bin-wrappers/git foo` to
444 use your own debugger and arguments. Example: `GIT_DEBUGGER="ddd --gdb"
445 ./bin-wrappers/git log` (See `wrap-for-bin.sh`.)
446
447 For Perl programs:
448
449 - Most of the C guidelines above apply.
450
451 - We try to support Perl 5.8 and later ("use Perl 5.008").
452
453 - use strict and use warnings are strongly preferred.
454
455 - Don't overuse statement modifiers unless using them makes the
456 result easier to follow.
457
458 ... do something ...
459 do_this() unless (condition);
460 ... do something else ...
461
462 is more readable than:
463
464 ... do something ...
465 unless (condition) {
466 do_this();
467 }
468 ... do something else ...
469
470 *only* when the condition is so rare that do_this() will be almost
471 always called.
472
473 - We try to avoid assignments inside "if ()" conditions.
474
475 - Learn and use Git.pm if you need that functionality.
476
477 - For Emacs, it's useful to put the following in
478 GIT_CHECKOUT/.dir-locals.el, assuming you use cperl-mode:
479
480 ;; note the first part is useful for C editing, too
481 ((nil . ((indent-tabs-mode . t)
482 (tab-width . 8)
483 (fill-column . 80)))
484 (cperl-mode . ((cperl-indent-level . 8)
485 (cperl-extra-newline-before-brace . nil)
486 (cperl-merge-trailing-else . t))))
487
488 For Python scripts:
489
490 - We follow PEP-8 (http://www.python.org/dev/peps/pep-0008/).
491
492 - As a minimum, we aim to be compatible with Python 2.6 and 2.7.
493
494 - Where required libraries do not restrict us to Python 2, we try to
495 also be compatible with Python 3.1 and later.
496
497 - When you must differentiate between Unicode literals and byte string
498 literals, it is OK to use the 'b' prefix. Even though the Python
499 documentation for version 2.6 does not mention this prefix, it has
500 been supported since version 2.6.0.
501
502 Error Messages
503
504 - Do not end error messages with a full stop.
505
506 - Do not capitalize ("unable to open %s", not "Unable to open %s")
507
508 - Say what the error is first ("cannot open %s", not "%s: cannot open")
509
510
511 Externally Visible Names
512
513 - For configuration variable names, follow the existing convention:
514
515 . The section name indicates the affected subsystem.
516
517 . The subsection name, if any, indicates which of an unbounded set
518 of things to set the value for.
519
520 . The variable name describes the effect of tweaking this knob.
521
522 The section and variable names that consist of multiple words are
523 formed by concatenating the words without punctuations (e.g. `-`),
524 and are broken using bumpyCaps in documentation as a hint to the
525 reader.
526
527 When choosing the variable namespace, do not use variable name for
528 specifying possibly unbounded set of things, most notably anything
529 an end user can freely come up with (e.g. branch names). Instead,
530 use subsection names or variable values, like the existing variable
531 branch.<name>.description does.
532
533
534 Writing Documentation:
535
536 Most (if not all) of the documentation pages are written in the
537 AsciiDoc format in *.txt files (e.g. Documentation/git.txt), and
538 processed into HTML and manpages (e.g. git.html and git.1 in the
539 same directory).
540
541 The documentation liberally mixes US and UK English (en_US/UK)
542 norms for spelling and grammar, which is somewhat unfortunate.
543 In an ideal world, it would have been better if it consistently
544 used only one and not the other, and we would have picked en_US
545 (if you wish to correct the English of some of the existing
546 documentation, please see the documentation-related advice in the
547 Documentation/SubmittingPatches file).
548
549 Every user-visible change should be reflected in the documentation.
550 The same general rule as for code applies -- imitate the existing
551 conventions.
552
553 A few commented examples follow to provide reference when writing or
554 modifying command usage strings and synopsis sections in the manual
555 pages:
556
557 Placeholders are spelled in lowercase and enclosed in angle brackets:
558 <file>
559 --sort=<key>
560 --abbrev[=<n>]
561
562 If a placeholder has multiple words, they are separated by dashes:
563 <new-branch-name>
564 --template=<template-directory>
565
566 Possibility of multiple occurrences is indicated by three dots:
567 <file>...
568 (One or more of <file>.)
569
570 Optional parts are enclosed in square brackets:
571 [<extra>]
572 (Zero or one <extra>.)
573
574 --exec-path[=<path>]
575 (Option with an optional argument. Note that the "=" is inside the
576 brackets.)
577
578 [<patch>...]
579 (Zero or more of <patch>. Note that the dots are inside, not
580 outside the brackets.)
581
582 Multiple alternatives are indicated with vertical bars:
583 [-q | --quiet]
584 [--utf8 | --no-utf8]
585
586 Parentheses are used for grouping:
587 [(<rev> | <range>)...]
588 (Any number of either <rev> or <range>. Parens are needed to make
589 it clear that "..." pertains to both <rev> and <range>.)
590
591 [(-p <parent>)...]
592 (Any number of option -p, each with one <parent> argument.)
593
594 git remote set-head <name> (-a | -d | <branch>)
595 (One and only one of "-a", "-d" or "<branch>" _must_ (no square
596 brackets) be provided.)
597
598 And a somewhat more contrived example:
599 --diff-filter=[(A|C|D|M|R|T|U|X|B)...[*]]
600 Here "=" is outside the brackets, because "--diff-filter=" is a
601 valid usage. "*" has its own pair of brackets, because it can
602 (optionally) be specified only when one or more of the letters is
603 also provided.
604
605 A note on notation:
606 Use 'git' (all lowercase) when talking about commands i.e. something
607 the user would type into a shell and use 'Git' (uppercase first letter)
608 when talking about the version control system and its properties.
609
610 A few commented examples follow to provide reference when writing or
611 modifying paragraphs or option/command explanations that contain options
612 or commands:
613
614 Literal examples (e.g. use of command-line options, command names,
615 branch names, URLs, pathnames (files and directories), configuration and
616 environment variables) must be typeset in monospace (i.e. wrapped with
617 backticks):
618 `--pretty=oneline`
619 `git rev-list`
620 `remote.pushDefault`
621 `http://git.example.com`
622 `.git/config`
623 `GIT_DIR`
624 `HEAD`
625
626 An environment variable must be prefixed with "$" only when referring to its
627 value and not when referring to the variable itself, in this case there is
628 nothing to add except the backticks:
629 `GIT_DIR` is specified
630 `$GIT_DIR/hooks/pre-receive`
631
632 Word phrases enclosed in `backtick characters` are rendered literally
633 and will not be further expanded. The use of `backticks` to achieve the
634 previous rule means that literal examples should not use AsciiDoc
635 escapes.
636 Correct:
637 `--pretty=oneline`
638 Incorrect:
639 `\--pretty=oneline`
640
641 If some place in the documentation needs to typeset a command usage
642 example with inline substitutions, it is fine to use +monospaced and
643 inline substituted text+ instead of `monospaced literal text`, and with
644 the former, the part that should not get substituted must be
645 quoted/escaped.