| 1 | Like other projects, we also have some guidelines for our code. For |
| 2 | 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. https://lore.kernel.org/all/20100126160632.3bdbe172.akpm@linux-foundation.org/ |
| 28 | |
| 29 | - Log messages to explain your changes are as important as the |
| 30 | changes themselves. Clearly written code and in-code comments |
| 31 | explain how the code works and what is assumed from the surrounding |
| 32 | context. The log messages explain what the changes wanted to |
| 33 | achieve and why the changes were necessary (more on this in the |
| 34 | accompanying SubmittingPatches document). |
| 35 | |
| 36 | - A label "NEEDSWORK:" followed by a description of the things to |
| 37 | be done is a way to leave in-code comments to document design |
| 38 | decisions yet to be made. 80% of the work to resolve a NEEDSWORK |
| 39 | comment is to decide if it still makes sense to do so, since the |
| 40 | situation around the codebase may have changed since the comment |
| 41 | was written. It can be a very valid change to remove an existing |
| 42 | NEEDSWORK comment without doing anything else, with the commit log |
| 43 | message describing a good argument why it does not make sense to do |
| 44 | the thing the NEEDSWORK comment mentioned. |
| 45 | |
| 46 | Make your code readable and sensible, and don't try to be clever. |
| 47 | |
| 48 | As for more concrete guidelines, just imitate the existing code |
| 49 | (this is a good guideline, no matter which project you are |
| 50 | contributing to). It is always preferable to match the _local_ |
| 51 | convention. New code added to Git suite is expected to match |
| 52 | the overall style of existing code. Modifications to existing |
| 53 | code are expected to match the style the surrounding code already |
| 54 | uses (even if it doesn't match the overall style of existing code). |
| 55 | |
| 56 | But if you must have a list of rules, here are some language |
| 57 | specific ones. Note that Documentation/ToolsForGit.adoc document |
| 58 | has a collection of tips to help you use some external tools |
| 59 | to conform to these guidelines. |
| 60 | |
| 61 | For shell scripts specifically (not exhaustive): |
| 62 | |
| 63 | - We use tabs for indentation. |
| 64 | |
| 65 | - Case arms are indented at the same depth as case and esac lines, |
| 66 | like this: |
| 67 | |
| 68 | case "$variable" in |
| 69 | pattern1) |
| 70 | do this |
| 71 | ;; |
| 72 | pattern2) |
| 73 | do that |
| 74 | ;; |
| 75 | esac |
| 76 | |
| 77 | - Redirection operators should be written with space before, but no |
| 78 | space after them. In other words, write 'echo test >"$file"' |
| 79 | instead of 'echo test> $file' or 'echo test > $file'. Note that |
| 80 | even though it is not required by POSIX to double-quote the |
| 81 | redirection target in a variable (as shown above), our code does so |
| 82 | because some versions of bash issue a warning without the quotes. |
| 83 | |
| 84 | (incorrect) |
| 85 | cat hello > world < universe |
| 86 | echo hello >$world |
| 87 | |
| 88 | (correct) |
| 89 | cat hello >world <universe |
| 90 | echo hello >"$world" |
| 91 | |
| 92 | - We prefer $( ... ) for command substitution; unlike ``, it |
| 93 | properly nests. It should have been the way Bourne spelled |
| 94 | it from day one, but unfortunately isn't. |
| 95 | |
| 96 | - If you want to find out if a command is available on the user's |
| 97 | $PATH, you should use 'type <command>', instead of 'which <command>'. |
| 98 | The output of 'which' is not machine parsable and its exit code |
| 99 | is not reliable across platforms. |
| 100 | |
| 101 | - We use POSIX compliant parameter substitutions and avoid bashisms; |
| 102 | namely: |
| 103 | |
| 104 | - We use ${parameter-word} and its [-=?+] siblings, and their |
| 105 | colon'ed "unset or null" form. |
| 106 | |
| 107 | - We use ${parameter#word} and its [#%] siblings, and their |
| 108 | doubled "longest matching" form. |
| 109 | |
| 110 | - No "Substring Expansion" ${parameter:offset:length}. |
| 111 | |
| 112 | - No shell arrays. |
| 113 | |
| 114 | - No pattern replacement ${parameter/pattern/string}. |
| 115 | |
| 116 | - We use Arithmetic Expansion $(( ... )). |
| 117 | |
| 118 | - We do not use Process Substitution <(list) or >(list). |
| 119 | |
| 120 | - Do not write control structures on a single line with semicolon. |
| 121 | "then" should be on the next line for if statements, and "do" |
| 122 | should be on the next line for "while" and "for". |
| 123 | |
| 124 | (incorrect) |
| 125 | if test -f hello; then |
| 126 | do this |
| 127 | fi |
| 128 | |
| 129 | (correct) |
| 130 | if test -f hello |
| 131 | then |
| 132 | do this |
| 133 | fi |
| 134 | |
| 135 | - If a command sequence joined with && or || or | spans multiple |
| 136 | lines, put each command on a separate line and put && and || and | |
| 137 | operators at the end of each line, rather than the start. This |
| 138 | means you don't need to use \ to join lines, since the above |
| 139 | operators imply the sequence isn't finished. |
| 140 | |
| 141 | (incorrect) |
| 142 | grep blob verify_pack_result \ |
| 143 | | awk -f print_1.awk \ |
| 144 | | sort >actual && |
| 145 | ... |
| 146 | |
| 147 | (correct) |
| 148 | grep blob verify_pack_result | |
| 149 | awk -f print_1.awk | |
| 150 | sort >actual && |
| 151 | ... |
| 152 | |
| 153 | - We prefer "test" over "[ ... ]". |
| 154 | |
| 155 | - We do not write the noiseword "function" in front of shell |
| 156 | functions. |
| 157 | |
| 158 | - We prefer a space between the function name and the parentheses, |
| 159 | and no space inside the parentheses. The opening "{" should also |
| 160 | be on the same line. |
| 161 | |
| 162 | (incorrect) |
| 163 | my_function(){ |
| 164 | ... |
| 165 | |
| 166 | (correct) |
| 167 | my_function () { |
| 168 | ... |
| 169 | |
| 170 | - As to use of grep, stick to a subset of BRE (namely, no \{m,n\}, |
| 171 | [::], [==], or [..]) for portability. |
| 172 | |
| 173 | - We do not use \{m,n\}; |
| 174 | |
| 175 | - We do not use ? or + (which are \{0,1\} and \{1,\} |
| 176 | respectively in BRE) but that goes without saying as these |
| 177 | are ERE elements not BRE (note that \? and \+ are not even part |
| 178 | of BRE -- making them accessible from BRE is a GNU extension). |
| 179 | |
| 180 | - Use Git's gettext wrappers in git-sh-i18n to make the user |
| 181 | interface translatable. See "Marking strings for translation" in |
| 182 | po/README. |
| 183 | |
| 184 | - We do not write our "test" command with "-a" and "-o" and use "&&" |
| 185 | or "||" to concatenate multiple "test" commands instead, because |
| 186 | the use of "-a/-o" is often error-prone. E.g. |
| 187 | |
| 188 | test -n "$x" -a "$a" = "$b" |
| 189 | |
| 190 | is buggy and breaks when $x is "=", but |
| 191 | |
| 192 | test -n "$x" && test "$a" = "$b" |
| 193 | |
| 194 | does not have such a problem. |
| 195 | |
| 196 | - Even though "local" is not part of POSIX, we make heavy use of it |
| 197 | in our test suite. We do not use it in scripted Porcelains, and |
| 198 | hopefully nobody starts using "local" before all shells that matter |
| 199 | support it (notably, ksh from AT&T Research does not support it yet). |
| 200 | |
| 201 | - Some versions of shell do not understand "export variable=value", |
| 202 | so we write "variable=value" and then "export variable" on two |
| 203 | separate lines. |
| 204 | |
| 205 | - Some versions of dash have broken variable assignment when prefixed |
| 206 | with "local", "export", and "readonly", in that the value to be |
| 207 | assigned goes through field splitting at $IFS unless quoted. |
| 208 | |
| 209 | (incorrect) |
| 210 | local variable=$value |
| 211 | local variable=$(command args) |
| 212 | |
| 213 | (correct) |
| 214 | local variable="$value" |
| 215 | local variable="$(command args)" |
| 216 | |
| 217 | - The common construct |
| 218 | |
| 219 | VAR=VAL command args |
| 220 | |
| 221 | to temporarily set and export environment variable VAR only while |
| 222 | "command args" is running is handy, but this triggers an |
| 223 | unspecified behaviour according to POSIX when used for a command |
| 224 | that is not an external command (like shell functions). Indeed, |
| 225 | dash 0.5.10.2-6 on Ubuntu 20.04, /bin/sh on FreeBSD 13, and AT&T |
| 226 | ksh all make a temporary assignment without exporting the variable, |
| 227 | in such a case. As it does not work portably across shells, do not |
| 228 | use this syntax for shell functions. A common workaround is to do |
| 229 | an explicit export in a subshell, like so: |
| 230 | |
| 231 | (incorrect) |
| 232 | VAR=VAL func args |
| 233 | |
| 234 | (correct) |
| 235 | ( |
| 236 | VAR=VAL && |
| 237 | export VAR && |
| 238 | func args |
| 239 | ) |
| 240 | |
| 241 | but be careful that the effect "func" makes to the variables in the |
| 242 | current shell will be lost across the subshell boundary. |
| 243 | |
| 244 | - Use octal escape sequences (e.g. "\302\242"), not hexadecimal (e.g. |
| 245 | "\xc2\xa2") in printf format strings, since hexadecimal escape |
| 246 | sequences are not portable. |
| 247 | |
| 248 | |
| 249 | For C programs: |
| 250 | |
| 251 | - We use tabs to indent, and interpret tabs as taking up to |
| 252 | 8 spaces. |
| 253 | |
| 254 | - Nested C preprocessor directives are indented after the hash by one |
| 255 | space per nesting level. |
| 256 | |
| 257 | #if FOO |
| 258 | # include <foo.h> |
| 259 | # if BAR |
| 260 | # include <bar.h> |
| 261 | # endif |
| 262 | #endif |
| 263 | |
| 264 | - We try to keep to at most 80 characters per line. |
| 265 | |
| 266 | - As a Git developer we assume you have a reasonably modern compiler |
| 267 | and we recommend you to enable the DEVELOPER makefile knob to |
| 268 | ensure your patch is clear of all compiler warnings we care about, |
| 269 | by e.g. "echo DEVELOPER=1 >>config.mak". |
| 270 | |
| 271 | - When using DEVELOPER=1 mode, you may see warnings from the compiler |
| 272 | like "error: unused parameter 'foo' [-Werror=unused-parameter]", |
| 273 | which indicates that a function ignores its argument. If the unused |
| 274 | parameter can't be removed (e.g., because the function is used as a |
| 275 | callback and has to match a certain interface), you can annotate |
| 276 | the individual parameters with the UNUSED (or MAYBE_UNUSED) |
| 277 | keyword, like "int foo UNUSED". |
| 278 | |
| 279 | - We try to support a wide range of C compilers to compile Git with, |
| 280 | including old ones. As of Git v2.35.0 Git requires C99 (we check |
| 281 | "__STDC_VERSION__"). You should not use features from a newer C |
| 282 | standard, even if your compiler groks them. |
| 283 | |
| 284 | New C99 features have been phased in gradually, if something's new |
| 285 | in C99 but not used yet don't assume that it's safe to use, some |
| 286 | compilers we target have only partial support for it. These are |
| 287 | considered safe to use: |
| 288 | |
| 289 | . since around 2007 with 2b6854c863a, we have been using |
| 290 | initializer elements which are not computable at load time. E.g.: |
| 291 | |
| 292 | const char *args[] = { "constant", variable, NULL }; |
| 293 | |
| 294 | . since early 2012 with e1327023ea, we have been using an enum |
| 295 | definition whose last element is followed by a comma. This, like |
| 296 | an array initializer that ends with a trailing comma, can be used |
| 297 | to reduce the patch noise when adding a new identifier at the end. |
| 298 | |
| 299 | . since mid 2017 with cbc0f81d, we have been using designated |
| 300 | initializers for struct (e.g. "struct t v = { .val = 'a' };"). |
| 301 | |
| 302 | . since mid 2017 with 512f41cf, we have been using designated |
| 303 | initializers for array (e.g. "int array[10] = { [5] = 2 }"). |
| 304 | |
| 305 | . since early 2021 with 765dc168882, we have been using variadic |
| 306 | macros, mostly for printf-like trace and debug macros. |
| 307 | |
| 308 | . since late 2021 with 44ba10d6, we have had variables declared in |
| 309 | the for loop "for (int i = 0; i < 10; i++)". |
| 310 | |
| 311 | . since late 2023 with 8277dbe987 we have been using the bool type |
| 312 | from <stdbool.h>. |
| 313 | |
| 314 | C99 features we have test balloons for: |
| 315 | |
| 316 | . since late 2024 with v2.48.0-rc0~20, we have test balloons for |
| 317 | compound literal syntax, e.g., (struct foo){ .member = value }; |
| 318 | our hope is that no platforms we care about have trouble using |
| 319 | them, and officially adopt its wider use in mid 2026. Do not add |
| 320 | more use of the syntax until that happens. |
| 321 | |
| 322 | New C99 features that we cannot use yet: |
| 323 | |
| 324 | . %z and %zu as a printf() argument for a size_t (the %z being for |
| 325 | the POSIX-specific ssize_t). Instead you should use |
| 326 | printf("%"PRIuMAX, (uintmax_t)v). These days the MSVC version we |
| 327 | rely on supports %z, but the C library used by MinGW does not. |
| 328 | |
| 329 | . Shorthand like ".a.b = *c" in struct initializations is known to |
| 330 | trip up an older IBM XLC version, use ".a = { .b = *c }" instead. |
| 331 | See the 33665d98 (reftable: make assignments portable to AIX xlc |
| 332 | v12.01, 2022-03-28). |
| 333 | |
| 334 | - Variables have to be declared at the beginning of the block, before |
| 335 | the first statement (i.e. -Wdeclaration-after-statement). It is |
| 336 | encouraged to have a blank line between the end of the declarations |
| 337 | and the first statement in the block. |
| 338 | |
| 339 | - Do not explicitly initialize global variables to 0 or NULL; |
| 340 | instead, let BSS take care of the zero initialization. |
| 341 | |
| 342 | - NULL pointers shall be written as NULL, not as 0. |
| 343 | |
| 344 | - When declaring pointers, the star sides with the variable |
| 345 | name, i.e. "char *string", not "char* string" or |
| 346 | "char * string". This makes it easier to understand code |
| 347 | like "char *string, c;". |
| 348 | |
| 349 | - Use whitespace around operators and keywords, but not inside |
| 350 | parentheses and not around functions. So: |
| 351 | |
| 352 | while (condition) |
| 353 | func(bar + 1); |
| 354 | |
| 355 | and not: |
| 356 | |
| 357 | while( condition ) |
| 358 | func (bar+1); |
| 359 | |
| 360 | - A binary operator (other than ",") and ternary conditional "?:" |
| 361 | have a space on each side of the operator to separate it from its |
| 362 | operands. E.g. "A + 1", not "A+1". |
| 363 | |
| 364 | - A unary operator (other than "." and "->") have no space between it |
| 365 | and its operand. E.g. "(char *)ptr", not "(char *) ptr". |
| 366 | |
| 367 | - Do not explicitly compare an integral value with constant 0 or '\0', |
| 368 | or a pointer value with constant NULL. For instance, to validate that |
| 369 | counted array <ptr, cnt> is initialized but has no elements, write: |
| 370 | |
| 371 | if (!ptr || cnt) |
| 372 | BUG("empty array expected"); |
| 373 | |
| 374 | and not: |
| 375 | |
| 376 | if (ptr == NULL || cnt != 0); |
| 377 | BUG("empty array expected"); |
| 378 | |
| 379 | - We avoid using braces unnecessarily. I.e. |
| 380 | |
| 381 | if (bla) { |
| 382 | x = 1; |
| 383 | } |
| 384 | |
| 385 | is frowned upon. But there are a few exceptions: |
| 386 | |
| 387 | - When the statement extends over a few lines (e.g., a while loop |
| 388 | with an embedded conditional, or a comment). E.g.: |
| 389 | |
| 390 | while (foo) { |
| 391 | if (x) |
| 392 | one(); |
| 393 | else |
| 394 | two(); |
| 395 | } |
| 396 | |
| 397 | if (foo) { |
| 398 | /* |
| 399 | * This one requires some explanation, |
| 400 | * so we're better off with braces to make |
| 401 | * it obvious that the indentation is correct. |
| 402 | */ |
| 403 | doit(); |
| 404 | } |
| 405 | |
| 406 | - When there are multiple arms to a conditional and some of them |
| 407 | require braces, enclose even a single line block in braces for |
| 408 | consistency. E.g.: |
| 409 | |
| 410 | if (foo) { |
| 411 | doit(); |
| 412 | } else { |
| 413 | one(); |
| 414 | two(); |
| 415 | three(); |
| 416 | } |
| 417 | |
| 418 | - We try to avoid assignments in the condition of an "if" statement. |
| 419 | |
| 420 | - Try to make your code understandable. You may put comments |
| 421 | in, but comments invariably tend to stale out when the code |
| 422 | they were describing changes. Often splitting a function |
| 423 | into two makes the intention of the code much clearer. |
| 424 | |
| 425 | - Multi-line comments include their delimiters on separate lines from |
| 426 | the text. E.g. |
| 427 | |
| 428 | /* |
| 429 | * A very long |
| 430 | * multi-line comment. |
| 431 | */ |
| 432 | |
| 433 | Note however that a comment that explains a translatable string to |
| 434 | translators uses a convention of starting with a magic token |
| 435 | "TRANSLATORS: ", e.g. |
| 436 | |
| 437 | /* |
| 438 | * TRANSLATORS: here is a comment that explains the string to |
| 439 | * be translated, that follows immediately after it. |
| 440 | */ |
| 441 | _("Here is a translatable string explained by the above."); |
| 442 | |
| 443 | We do not use // comments. |
| 444 | |
| 445 | - Double negation is often harder to understand than no negation |
| 446 | at all. |
| 447 | |
| 448 | - There are two schools of thought when it comes to comparison, |
| 449 | especially inside a loop. Some people prefer to have the less stable |
| 450 | value on the left hand side and the more stable value on the right hand |
| 451 | side, e.g. if you have a loop that counts variable i down to the |
| 452 | lower bound, |
| 453 | |
| 454 | while (i > lower_bound) { |
| 455 | do something; |
| 456 | i--; |
| 457 | } |
| 458 | |
| 459 | Other people prefer to have the textual order of values match the |
| 460 | actual order of values in their comparison, so that they can |
| 461 | mentally draw a number line from left to right and place these |
| 462 | values in order, i.e. |
| 463 | |
| 464 | while (lower_bound < i) { |
| 465 | do something; |
| 466 | i--; |
| 467 | } |
| 468 | |
| 469 | Both are valid, and we use both. However, the more "stable" the |
| 470 | stable side becomes, the more we tend to prefer the former |
| 471 | (comparison with a constant, "i > 0", is an extreme example). |
| 472 | Just do not mix styles in the same part of the code and mimic |
| 473 | existing styles in the neighbourhood. |
| 474 | |
| 475 | - There are two schools of thought when it comes to splitting a long |
| 476 | logical line into multiple lines. Some people push the second and |
| 477 | subsequent lines far enough to the right with tabs and align them: |
| 478 | |
| 479 | if (the_beginning_of_a_very_long_expression_that_has_to || |
| 480 | span_more_than_a_single_line_of || |
| 481 | the_source_text) { |
| 482 | ... |
| 483 | |
| 484 | while other people prefer to align the second and the subsequent |
| 485 | lines with the column immediately inside the opening parenthesis, |
| 486 | with tabs and spaces, following our "tabstop is always a multiple |
| 487 | of 8" convention: |
| 488 | |
| 489 | if (the_beginning_of_a_very_long_expression_that_has_to || |
| 490 | span_more_than_a_single_line_of || |
| 491 | the_source_text) { |
| 492 | ... |
| 493 | |
| 494 | Both are valid, and we use both. Again, just do not mix styles in |
| 495 | the same part of the code and mimic existing styles in the |
| 496 | neighbourhood. |
| 497 | |
| 498 | - When splitting a long logical line, some people change line before |
| 499 | a binary operator, so that the result looks like a parse tree when |
| 500 | you turn your head 90-degrees counterclockwise: |
| 501 | |
| 502 | if (the_beginning_of_a_very_long_expression_that_has_to |
| 503 | || span_more_than_a_single_line_of_the_source_text) { |
| 504 | |
| 505 | while other people prefer to leave the operator at the end of the |
| 506 | line: |
| 507 | |
| 508 | if (the_beginning_of_a_very_long_expression_that_has_to || |
| 509 | span_more_than_a_single_line_of_the_source_text) { |
| 510 | |
| 511 | Both are valid, but we tend to use the latter more, unless the |
| 512 | expression gets fairly complex, in which case the former tends to |
| 513 | be easier to read. Again, just do not mix styles in the same part |
| 514 | of the code and mimic existing styles in the neighbourhood. |
| 515 | |
| 516 | - When splitting a long logical line, with everything else being |
| 517 | equal, it is preferable to split after the operator at higher |
| 518 | level in the parse tree. That is, this is more preferable: |
| 519 | |
| 520 | if (a_very_long_variable * that_is_used_in + |
| 521 | a_very_long_expression) { |
| 522 | ... |
| 523 | |
| 524 | than |
| 525 | |
| 526 | if (a_very_long_variable * |
| 527 | that_is_used_in + a_very_long_expression) { |
| 528 | ... |
| 529 | |
| 530 | - Some clever tricks, like using the !! operator with arithmetic |
| 531 | constructs, can be extremely confusing to others. Avoid them, |
| 532 | unless there is a compelling reason to use them. |
| 533 | |
| 534 | - Use the API. No, really. We have a strbuf (variable length |
| 535 | string), several arrays with the ALLOC_GROW() macro, a |
| 536 | string_list for sorted string lists, a hash map (mapping struct |
| 537 | objects) named "struct decorate", amongst other things. |
| 538 | |
| 539 | - When you come up with an API, document its functions and structures |
| 540 | in the header file that exposes the API to its callers. Use what is |
| 541 | in "strbuf.h" as a model for the appropriate tone and level of |
| 542 | detail. |
| 543 | |
| 544 | - The first #include in C files, except in platform specific compat/ |
| 545 | implementations and sha1dc/, must be <git-compat-util.h>. This |
| 546 | header file insulates other header files and source files from |
| 547 | platform differences, like which system header files must be |
| 548 | included in what order, and what C preprocessor feature macros must |
| 549 | be defined to trigger certain features we expect out of the system. |
| 550 | A collorary to this is that C files should not directly include |
| 551 | system header files themselves. |
| 552 | |
| 553 | There are some exceptions, because certain group of files that |
| 554 | implement an API all have to include the same header file that |
| 555 | defines the API and it is convenient to include <git-compat-util.h> |
| 556 | there. Namely: |
| 557 | |
| 558 | - the implementation of the built-in commands in the "builtin/" |
| 559 | directory that include "builtin.h" for the cmd_foo() prototype |
| 560 | definition, |
| 561 | |
| 562 | - the test helper programs in the "t/helper/" directory that include |
| 563 | "t/helper/test-tool.h" for the cmd__foo() prototype definition, |
| 564 | |
| 565 | - the xdiff implementation in the "xdiff/" directory that includes |
| 566 | "xdiff/xinclude.h" for the xdiff machinery internals, |
| 567 | |
| 568 | - the unit test programs in "t/unit-tests/" directory that include |
| 569 | "t/unit-tests/test-lib.h" that gives them the unit-tests |
| 570 | framework, and |
| 571 | |
| 572 | - the source files that implement reftable in the "reftable/" |
| 573 | directory that include "reftable/system.h" for the reftable |
| 574 | internals, |
| 575 | |
| 576 | are allowed to assume that they do not have to include |
| 577 | <git-compat-util.h> themselves, as it is included as the first |
| 578 | '#include' in these header files. These headers must be the first |
| 579 | header file to be "#include"d in them, though. |
| 580 | |
| 581 | - A C file must directly include the header files that declare the |
| 582 | functions and the types it uses, except for the functions and types |
| 583 | that are made available to it by including one of the header files |
| 584 | it must include by the previous rule. |
| 585 | |
| 586 | - If you are planning a new command, consider writing it in shell |
| 587 | or perl first, so that changes in semantics can be easily |
| 588 | changed and discussed. Many Git commands started out like |
| 589 | that, and a few are still scripts. |
| 590 | |
| 591 | - Avoid introducing a new dependency into Git. This means you |
| 592 | usually should stay away from scripting languages not already |
| 593 | used in the Git core command set (unless your command is clearly |
| 594 | separate from it, such as an importer to convert random-scm-X |
| 595 | repositories to Git). |
| 596 | |
| 597 | - When we pass <string, length> pair to functions, we should try to |
| 598 | pass them in that order. |
| 599 | |
| 600 | - Use Git's gettext wrappers to make the user interface |
| 601 | translatable. See "Marking strings for translation" in po/README. |
| 602 | |
| 603 | - Variables and functions local to a given source file should be marked |
| 604 | with "static". Variables that are visible to other source files |
| 605 | must be declared with "extern" in header files. However, function |
| 606 | declarations should not use "extern", as that is already the default. |
| 607 | |
| 608 | - You can launch gdb around your program using the shorthand GIT_DEBUGGER. |
| 609 | Run `GIT_DEBUGGER=1 ./bin-wrappers/git foo` to simply use gdb as is, or |
| 610 | run `GIT_DEBUGGER="<debugger> <debugger-args>" ./bin-wrappers/git foo` to |
| 611 | use your own debugger and arguments. Example: `GIT_DEBUGGER="ddd --gdb" |
| 612 | ./bin-wrappers/git log` (See `bin-wrappers/wrap-for-bin.sh`.) |
| 613 | |
| 614 | - The primary data structure that a subsystem 'S' deals with is called |
| 615 | `struct S`. Functions that operate on `struct S` are named |
| 616 | `S_<verb>()` and should generally receive a pointer to `struct S` as |
| 617 | first parameter. E.g. |
| 618 | |
| 619 | struct strbuf; |
| 620 | |
| 621 | void strbuf_add(struct strbuf *buf, ...); |
| 622 | |
| 623 | void strbuf_reset(struct strbuf *buf); |
| 624 | |
| 625 | is preferred over: |
| 626 | |
| 627 | struct strbuf; |
| 628 | |
| 629 | void add_string(struct strbuf *buf, ...); |
| 630 | |
| 631 | void reset_strbuf(struct strbuf *buf); |
| 632 | |
| 633 | - There are several common idiomatic names for functions performing |
| 634 | specific tasks on a structure `S`: |
| 635 | |
| 636 | - `S_init()` initializes a structure without allocating the |
| 637 | structure itself. |
| 638 | |
| 639 | - `S_release()` releases a structure's contents without reinitializing |
| 640 | the structure for immediate reuse, and without freeing the structure |
| 641 | itself. |
| 642 | |
| 643 | - `S_clear()` is equivalent to `S_release()` followed by `S_init()` |
| 644 | such that the structure is directly usable after clearing it. When |
| 645 | `S_clear()` is provided, `S_init()` shall not allocate resources |
| 646 | that need to be released again. |
| 647 | |
| 648 | - `S_free()` releases a structure's contents and frees the |
| 649 | structure. |
| 650 | |
| 651 | - Function names should be clear and descriptive, accurately reflecting |
| 652 | their purpose or behavior. Arbitrary suffixes that do not add meaningful |
| 653 | context can lead to confusion, particularly for newcomers to the codebase. |
| 654 | |
| 655 | Historically, the '_1' suffix has been used in situations where: |
| 656 | |
| 657 | - A function handles one element among a group that requires similar |
| 658 | processing. |
| 659 | - A recursive function has been separated from its setup phase. |
| 660 | |
| 661 | The '_1' suffix can be used as a concise way to indicate these specific |
| 662 | cases. However, it is recommended to find a more descriptive name wherever |
| 663 | possible to improve the readability and maintainability of the code. |
| 664 | |
| 665 | - Bit fields should be defined without a space around the colon. E.g. |
| 666 | |
| 667 | unsigned my_field:1; |
| 668 | unsigned other_field:1; |
| 669 | unsigned field_with_longer_name:1; |
| 670 | |
| 671 | - When a function `F` accepts flags, those flags should be defined as `enum |
| 672 | F_flags`. Individual flag definitions should start with `F` and be in |
| 673 | all-uppercase letters. Flag values should be represented via bit shifts. |
| 674 | E.g. |
| 675 | |
| 676 | enum frobnicate_flags { |
| 677 | FROBNICATE_FOO = (1 << 0), |
| 678 | FROBNICATE_BAR = (1 << 1), |
| 679 | }; |
| 680 | |
| 681 | int frobnicate(enum frobnicate_flags flags); |
| 682 | |
| 683 | - Array names should be named in the singular form if the individual items are |
| 684 | subject of use. E.g.: |
| 685 | |
| 686 | char *dog[] = ...; |
| 687 | walk_dog(dog[0]); |
| 688 | walk_dog(dog[1]); |
| 689 | |
| 690 | Cases where the array is employed as a whole rather than as its unit parts, |
| 691 | the plural form is preferable. E.g: |
| 692 | |
| 693 | char *dogs[] = ...; |
| 694 | walk_all_dogs(dogs); |
| 695 | |
| 696 | - For file timestamps, do not use "st_mtim" (and other timestamp |
| 697 | members in "struct stat") unconditionally; not everybody is POSIX |
| 698 | (grep for USE_ST_TIMESPEC). If you only need a timestamp in whole |
| 699 | second resolution, "st_mtime" should work fine everywhere. |
| 700 | |
| 701 | |
| 702 | For Perl programs: |
| 703 | |
| 704 | - Most of the C guidelines above apply. |
| 705 | |
| 706 | - We try to support Perl 5.8.1 and later ("use Perl 5.008001"). |
| 707 | |
| 708 | - use strict and use warnings are strongly preferred. |
| 709 | |
| 710 | - Don't overuse statement modifiers unless using them makes the |
| 711 | result easier to follow. |
| 712 | |
| 713 | ... do something ... |
| 714 | do_this() unless (condition); |
| 715 | ... do something else ... |
| 716 | |
| 717 | is more readable than: |
| 718 | |
| 719 | ... do something ... |
| 720 | unless (condition) { |
| 721 | do_this(); |
| 722 | } |
| 723 | ... do something else ... |
| 724 | |
| 725 | *only* when the condition is so rare that do_this() will be almost |
| 726 | always called. |
| 727 | |
| 728 | - We try to avoid assignments inside "if ()" conditions. |
| 729 | |
| 730 | - Learn and use Git.pm if you need that functionality. |
| 731 | |
| 732 | For Python scripts: |
| 733 | |
| 734 | - We follow PEP-8 (https://peps.python.org/pep-0008/). |
| 735 | |
| 736 | - As a minimum, we aim to be compatible with Python 2.7. |
| 737 | |
| 738 | - Where required libraries do not restrict us to Python 2, we try to |
| 739 | also be compatible with Python 3.1 and later. |
| 740 | |
| 741 | |
| 742 | Program Output |
| 743 | |
| 744 | We make a distinction between a Git command's primary output and |
| 745 | output which is merely chatty feedback (for instance, status |
| 746 | messages, running transcript, or progress display), as well as error |
| 747 | messages. Roughly speaking, a Git command's primary output is that |
| 748 | which one might want to capture to a file or send down a pipe; its |
| 749 | chatty output should not interfere with these use-cases. |
| 750 | |
| 751 | As such, primary output should be sent to the standard output stream |
| 752 | (stdout), and chatty output should be sent to the standard error |
| 753 | stream (stderr). Examples of commands which produce primary output |
| 754 | include `git log`, `git show`, and `git branch --list` which generate |
| 755 | output on the stdout stream. |
| 756 | |
| 757 | Not all Git commands have primary output; this is often true of |
| 758 | commands whose main function is to perform an action. Some action |
| 759 | commands are silent, whereas others are chatty. An example of a |
| 760 | chatty action commands is `git clone` with its "Cloning into |
| 761 | '<path>'..." and "Checking connectivity..." status messages which it |
| 762 | sends to the stderr stream. |
| 763 | |
| 764 | Error messages from Git commands should always be sent to the stderr |
| 765 | stream. |
| 766 | |
| 767 | |
| 768 | Error Messages |
| 769 | |
| 770 | - Do not end a single-sentence error message with a full stop. |
| 771 | |
| 772 | - Do not capitalize the first word, only because it is the first word |
| 773 | in the message ("unable to open '%s'", not "Unable to open '%s'"). But |
| 774 | "SHA-3 not supported" is fine, because the reason the first word is |
| 775 | capitalized is not because it is at the beginning of the sentence, |
| 776 | but because the word would be spelled in capital letters even when |
| 777 | it appeared in the middle of the sentence. |
| 778 | |
| 779 | - Say what the error is first ("cannot open '%s'", not "%s: cannot open"). |
| 780 | |
| 781 | - Enclose the subject of an error inside a pair of single quotes, |
| 782 | e.g. `die(_("unable to open '%s'"), path)`. |
| 783 | |
| 784 | - Unless there is a compelling reason not to, error messages from |
| 785 | porcelain commands should be marked for translation, e.g. |
| 786 | `die(_("bad revision %s"), revision)`. |
| 787 | |
| 788 | - Error messages from the plumbing commands are sometimes meant for |
| 789 | machine consumption and should not be marked for translation, |
| 790 | e.g., `die("bad revision %s", revision)`. |
| 791 | |
| 792 | - BUG("message") are for communicating the specific error to developers, |
| 793 | thus should not be translated. |
| 794 | |
| 795 | |
| 796 | Externally Visible Names |
| 797 | |
| 798 | - For configuration variable names, follow the existing convention: |
| 799 | |
| 800 | . The section name indicates the affected subsystem. |
| 801 | |
| 802 | . The subsection name, if any, indicates which of an unbounded set |
| 803 | of things to set the value for. |
| 804 | |
| 805 | . The variable name describes the effect of tweaking this knob. |
| 806 | |
| 807 | The section and variable names that consist of multiple words are |
| 808 | formed by concatenating the words without punctuation marks (e.g. `-`), |
| 809 | and are broken using bumpyCaps in documentation as a hint to the |
| 810 | reader. |
| 811 | |
| 812 | When choosing the variable namespace, do not use variable name for |
| 813 | specifying possibly unbounded set of things, most notably anything |
| 814 | an end user can freely come up with (e.g. branch names). Instead, |
| 815 | use subsection names or variable values, like the existing variable |
| 816 | branch.<name>.description does. |
| 817 | |
| 818 | |
| 819 | Writing Documentation: |
| 820 | |
| 821 | Most (if not all) of the documentation pages are written in the |
| 822 | AsciiDoc format in *.adoc files (e.g. Documentation/git.adoc), and |
| 823 | processed into HTML and manpages (e.g. git.html and git.1 in the |
| 824 | same directory). |
| 825 | |
| 826 | The documentation liberally mixes US and UK English (en_US/UK) |
| 827 | norms for spelling and grammar, which is somewhat unfortunate. |
| 828 | In an ideal world, it would have been better if it consistently |
| 829 | used only one and not the other, and we would have picked en_US |
| 830 | (if you wish to correct the English of some of the existing |
| 831 | documentation, please see the documentation-related advice in the |
| 832 | Documentation/SubmittingPatches file). |
| 833 | |
| 834 | In order to ensure the documentation is inclusive, avoid assuming |
| 835 | that an unspecified example person is male or female, and think |
| 836 | twice before using "he", "him", "she", or "her". Here are some |
| 837 | tips to avoid use of gendered pronouns: |
| 838 | |
| 839 | - Prefer succinctness and matter-of-factly describing functionality |
| 840 | in the abstract. E.g. |
| 841 | |
| 842 | `--short`:: Emit output in the short-format. |
| 843 | |
| 844 | and avoid something like these overly verbose alternatives: |
| 845 | |
| 846 | `--short`:: Use this to emit output in the short-format. |
| 847 | `--short`:: You can use this to get output in the short-format. |
| 848 | `--short`:: A user who prefers shorter output could.... |
| 849 | `--short`:: Should a person and/or program want shorter output, he |
| 850 | she/they/it can... |
| 851 | |
| 852 | This practice often eliminates the need to involve human actors in |
| 853 | your description, but it is a good practice regardless of the |
| 854 | avoidance of gendered pronouns. |
| 855 | |
| 856 | - When it becomes awkward to stick to this style, prefer "you" when |
| 857 | addressing the hypothetical user, and possibly "we" when |
| 858 | discussing how the program might react to the user. E.g. |
| 859 | |
| 860 | You can use this option instead of `--xyz`, but we might remove |
| 861 | support for it in future versions. |
| 862 | |
| 863 | while keeping in mind that you can probably be less verbose, e.g. |
| 864 | |
| 865 | Use this instead of `--xyz`. This option might be removed in future |
| 866 | versions. |
| 867 | |
| 868 | - If you still need to refer to an example person that is |
| 869 | third-person singular, you may resort to "singular they" to avoid |
| 870 | "he/she/him/her", e.g. |
| 871 | |
| 872 | A contributor asks their upstream to pull from them. |
| 873 | |
| 874 | Note that this sounds ungrammatical and unnatural to those who |
| 875 | learned that "they" is only used for third-person plural, e.g. |
| 876 | those who learn English as a second language in some parts of the |
| 877 | world. |
| 878 | |
| 879 | Every user-visible change should be reflected in the documentation. |
| 880 | The same general rule as for code applies -- imitate the existing |
| 881 | conventions. |
| 882 | |
| 883 | |
| 884 | Markup: |
| 885 | |
| 886 | Literal parts (e.g. use of command-line options, command names, |
| 887 | branch names, URLs, pathnames (files and directories), configuration and |
| 888 | environment variables) must be typeset as verbatim (i.e. wrapped with |
| 889 | backticks): |
| 890 | `--pretty=oneline` |
| 891 | `git rev-list` |
| 892 | `remote.pushDefault` |
| 893 | `http://git.example.com` |
| 894 | `.git/config` |
| 895 | `GIT_DIR` |
| 896 | `HEAD` |
| 897 | `umask`(2) |
| 898 | |
| 899 | An environment variable must be prefixed with "$" only when referring to its |
| 900 | value and not when referring to the variable itself, in this case there is |
| 901 | nothing to add except the backticks: |
| 902 | `GIT_DIR` is specified |
| 903 | `$GIT_DIR/hooks/pre-receive` |
| 904 | |
| 905 | Word phrases enclosed in `backtick characters` are rendered literally |
| 906 | and will not be further expanded. The use of `backticks` to achieve the |
| 907 | previous rule means that literal examples should not use AsciiDoc |
| 908 | escapes. |
| 909 | Correct: |
| 910 | `--pretty=oneline` |
| 911 | Incorrect: |
| 912 | `\--pretty=oneline` |
| 913 | |
| 914 | Placeholders are spelled in lowercase and enclosed in |
| 915 | angle brackets surrounded by underscores: |
| 916 | _<file>_ |
| 917 | _<commit>_ |
| 918 | |
| 919 | If a placeholder has multiple words, they are separated by dashes: |
| 920 | _<new-branch-name>_ |
| 921 | _<template-directory>_ |
| 922 | |
| 923 | When needed, use a distinctive identifier for placeholders, usually |
| 924 | made of a qualification and a type: |
| 925 | _<git-dir>_ |
| 926 | _<key-id>_ |
| 927 | |
| 928 | Characters are also surrounded by underscores: |
| 929 | _LF_, _CR_, _CR_/_LF_, _NUL_, _EOF_ |
| 930 | |
| 931 | Git's Asciidoc processor has been tailored to treat backticked text |
| 932 | as complex synopsis. When literal and placeholders are mixed, you can |
| 933 | use the backtick notation which will take care of correctly typesetting |
| 934 | the content. |
| 935 | `--jobs <n>` |
| 936 | `--sort=<key>` |
| 937 | `<directory>/.git` |
| 938 | `remote.<name>.mirror` |
| 939 | `ssh://[<user>@]<host>[:<port>]/<path-to-git-repo>` |
| 940 | |
| 941 | As a side effect, backquoted placeholders are correctly typeset, but |
| 942 | this style is not recommended. |
| 943 | |
| 944 | When documenting multiple related `git config` variables, place them on |
| 945 | a separate line instead of separating them by commas. For example, do |
| 946 | not write this: |
| 947 | `core.var1`, `core.var2`:: |
| 948 | Description common to `core.var1` and `core.var2`. |
| 949 | |
| 950 | Instead write this: |
| 951 | `core.var1`:: |
| 952 | `core.var2`:: |
| 953 | Description common to `core.var1` and `core.var2`. |
| 954 | |
| 955 | Synopsis Syntax |
| 956 | |
| 957 | The synopsis (a paragraph with [synopsis] attribute) is automatically |
| 958 | formatted by the toolchain and does not need typesetting. |
| 959 | |
| 960 | A few commented examples follow to provide reference when writing or |
| 961 | modifying command usage strings and synopsis sections in the manual |
| 962 | pages: |
| 963 | |
| 964 | Possibility of multiple occurrences is indicated by three dots: |
| 965 | <file>... |
| 966 | (One or more of <file>.) |
| 967 | |
| 968 | Optional parts are enclosed in square brackets: |
| 969 | [<file>...] |
| 970 | (Zero or more of <file>.) |
| 971 | |
| 972 | An optional parameter needs to be typeset with unconstrained pairs |
| 973 | [<repository>] |
| 974 | |
| 975 | --exec-path[=<path>] |
| 976 | (Option with an optional argument. Note that the "=" is inside the |
| 977 | brackets.) |
| 978 | |
| 979 | [<patch>...] |
| 980 | (Zero or more of <patch>. Note that the dots are inside, not |
| 981 | outside the brackets.) |
| 982 | |
| 983 | Multiple alternatives are indicated with vertical bars: |
| 984 | [-q | --quiet] |
| 985 | [--utf8 | --no-utf8] |
| 986 | |
| 987 | Use spacing around "|" token(s), but not immediately after opening or |
| 988 | before closing a [] or () pair: |
| 989 | Do: [-q | --quiet] |
| 990 | Don't: [-q|--quiet] |
| 991 | |
| 992 | Don't use spacing around "|" tokens when they're used to separate the |
| 993 | alternate arguments of an option: |
| 994 | Do: --track[=(direct|inherit)] |
| 995 | Don't: --track[=(direct | inherit)] |
| 996 | |
| 997 | Parentheses are used for grouping: |
| 998 | [(<rev>|<range>)...] |
| 999 | (Any number of either <rev> or <range>. Parens are needed to make |
| 1000 | it clear that "..." pertains to both <rev> and <range>.) |
| 1001 | |
| 1002 | [(-p <parent>)...] |
| 1003 | (Any number of option -p, each with one <parent> argument.) |
| 1004 | |
| 1005 | git remote set-head <name> (-a|-d|<branch>) |
| 1006 | (One and only one of "-a", "-d" or "<branch>" _must_ (no square |
| 1007 | brackets) be provided.) |
| 1008 | |
| 1009 | And a somewhat more contrived example: |
| 1010 | --diff-filter=[(A|C|D|M|R|T|U|X|B)...[*]] |
| 1011 | Here "=" is outside the brackets, because "--diff-filter=" is a |
| 1012 | valid usage. "*" has its own pair of brackets, because it can |
| 1013 | (optionally) be specified only when one or more of the letters is |
| 1014 | also provided. |
| 1015 | |
| 1016 | A note on notation: |
| 1017 | Use 'git' (all lowercase) when talking about commands i.e. something |
| 1018 | the user would type into a shell and use 'Git' (uppercase first letter) |
| 1019 | when talking about the version control system and its properties. |
| 1020 | |
| 1021 | If some place in the documentation needs to typeset a command usage |
| 1022 | example with inline substitutions, it is fine to use +monospaced and |
| 1023 | inline substituted text+ instead of `monospaced literal text`, and with |
| 1024 | the former, the part that should not get substituted must be |
| 1025 | quoted/escaped. |