CodingGuidelines 21 KB

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