CodingGuidelines: once it is in, it is not worth the code churn
[git/git.git] / Documentation / CodingGuidelines
CommitLineData
6d0618a8 1Like other projects, we also have some guidelines to keep to the
2de9b711 2code. For Git in general, three rough rules are:
6d0618a8
JS
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
dd30800b
JH
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://article.gmane.org/gmane.linux.kernel/943020
28
c5e366b1 29Make your code readable and sensible, and don't try to be clever.
6d0618a8
JS
30
31As for more concrete guidelines, just imitate the existing code
32(this is a good guideline, no matter which project you are
dfb047b9 33contributing to). It is always preferable to match the _local_
2de9b711 34convention. New code added to Git suite is expected to match
dfb047b9
NS
35the overall style of existing code. Modifications to existing
36code is expected to match the style the surrounding code already
37uses (even if it doesn't match the overall style of existing code).
38
39But if you must have a list of rules, here they are.
6d0618a8
JS
40
41For shell scripts specifically (not exhaustive):
42
f36a4fa8
GB
43 - We use tabs for indentation.
44
45 - Case arms are indented at the same depth as case and esac lines.
46
48f359bf
TH
47 - Redirection operators should be written with space before, but no
48 space after them. In other words, write 'echo test >"$file"'
49 instead of 'echo test> $file' or 'echo test > $file'. Note that
50 even though it is not required by POSIX to double-quote the
51 redirection target in a variable (as shown above), our code does so
52 because some versions of bash issue a warning without the quotes.
53
6d0618a8
JS
54 - We prefer $( ... ) for command substitution; unlike ``, it
55 properly nests. It should have been the way Bourne spelled
56 it from day one, but unfortunately isn't.
57
860f70f9
TH
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 parseable and its exit code
61 is not reliable across platforms.
62
bc979945
JH
63 - We use POSIX compliant parameter substitutions and avoid bashisms;
64 namely:
6d0618a8 65
bc979945
JH
66 - We use ${parameter-word} and its [-=?+] siblings, and their
67 colon'ed "unset or null" form.
6d0618a8 68
bc979945
JH
69 - We use ${parameter#word} and its [#%] siblings, and their
70 doubled "longest matching" form.
6d0618a8 71
bc979945 72 - No "Substring Expansion" ${parameter:offset:length}.
055467dd 73
bc979945 74 - No shell arrays.
6d0618a8 75
bc979945 76 - No strlen ${#parameter}.
6d0618a8 77
bc979945 78 - No pattern replacement ${parameter/pattern/string}.
6d0618a8 79
bc979945
JH
80 - We use Arithmetic Expansion $(( ... )).
81
82 - Inside Arithmetic Expansion, spell shell variables with $ in front
83 of them, as some shells do not grok $((x)) while accepting $(($x))
84 just fine (e.g. dash older than 0.5.4).
6d0618a8
JS
85
86 - We do not use Process Substitution <(list) or >(list).
87
03b05c7d
HV
88 - Do not write control structures on a single line with semicolon.
89 "then" should be on the next line for if statements, and "do"
90 should be on the next line for "while" and "for".
91
6d0618a8
JS
92 - We prefer "test" over "[ ... ]".
93
94 - We do not write the noiseword "function" in front of shell
95 functions.
96
03b05c7d
HV
97 - We prefer a space between the function name and the parentheses. The
98 opening "{" should also be on the same line.
99 E.g.: my_function () {
100
009c98ee 101 - As to use of grep, stick to a subset of BRE (namely, no \{m,n\},
a58088ab 102 [::], [==], or [..]) for portability.
009c98ee
JH
103
104 - We do not use \{m,n\};
105
106 - We do not use -E;
107
a58088ab 108 - We do not use ? or + (which are \{0,1\} and \{1,\}
009c98ee
JH
109 respectively in BRE) but that goes without saying as these
110 are ERE elements not BRE (note that \? and \+ are not even part
111 of BRE -- making them accessible from BRE is a GNU extension).
112
5e9637c6
ÆAB
113 - Use Git's gettext wrappers in git-sh-i18n to make the user
114 interface translatable. See "Marking strings for translation" in
115 po/README.
116
6d0618a8
JS
117For C programs:
118
119 - We use tabs to indent, and interpret tabs as taking up to
120 8 spaces.
121
122 - We try to keep to at most 80 characters per line.
123
2de9b711 124 - We try to support a wide range of C compilers to compile Git with,
a26fd033
AS
125 including old ones. That means that you should not use C99
126 initializers, even if a lot of compilers grok it.
127
128 - Variables have to be declared at the beginning of the block.
129
130 - NULL pointers shall be written as NULL, not as 0.
131
6d0618a8
JS
132 - When declaring pointers, the star sides with the variable
133 name, i.e. "char *string", not "char* string" or
134 "char * string". This makes it easier to understand code
135 like "char *string, c;".
136
f57b6cfd
JK
137 - Use whitespace around operators and keywords, but not inside
138 parentheses and not around functions. So:
139
140 while (condition)
141 func(bar + 1);
142
143 and not:
144
145 while( condition )
146 func (bar+1);
147
6d0618a8
JS
148 - We avoid using braces unnecessarily. I.e.
149
150 if (bla) {
151 x = 1;
152 }
153
154 is frowned upon. A gray area is when the statement extends
155 over a few lines, and/or you have a lengthy comment atop of
156 it. Also, like in the Linux kernel, if there is a long list
157 of "else if" statements, it can make sense to add braces to
158 single line blocks.
159
0b0b8cd7
MV
160 - We try to avoid assignments inside if().
161
6d0618a8
JS
162 - Try to make your code understandable. You may put comments
163 in, but comments invariably tend to stale out when the code
164 they were describing changes. Often splitting a function
165 into two makes the intention of the code much clearer.
166
b75a6ca7 167 - Multi-line comments include their delimiters on separate lines from
168 the text. E.g.
169
170 /*
171 * A very long
172 * multi-line comment.
173 */
174
cbcfd4e3
JH
175 Note however that a comment that explains a translatable string to
176 translators uses a convention of starting with a magic token
177 "TRANSLATORS: " immediately after the opening delimiter, even when
178 it spans multiple lines. We do not add an asterisk at the beginning
179 of each line, either. E.g.
180
181 /* TRANSLATORS: here is a comment that explains the string
182 to be translated, that follows immediately after it */
183 _("Here is a translatable string explained by the above.");
184
6d0618a8
JS
185 - Double negation is often harder to understand than no negation
186 at all.
187
188 - Some clever tricks, like using the !! operator with arithmetic
189 constructs, can be extremely confusing to others. Avoid them,
190 unless there is a compelling reason to use them.
191
192 - Use the API. No, really. We have a strbuf (variable length
193 string), several arrays with the ALLOC_GROW() macro, a
c455c87c 194 string_list for sorted string lists, a hash map (mapping struct
6d0618a8
JS
195 objects) named "struct decorate", amongst other things.
196
197 - When you come up with an API, document it.
198
199 - The first #include in C files, except in platform specific
200 compat/ implementations, should be git-compat-util.h or another
201 header file that includes it, such as cache.h or builtin.h.
202
203 - If you are planning a new command, consider writing it in shell
204 or perl first, so that changes in semantics can be easily
2de9b711 205 changed and discussed. Many Git commands started out like
6d0618a8
JS
206 that, and a few are still scripts.
207
2de9b711 208 - Avoid introducing a new dependency into Git. This means you
6d0618a8 209 usually should stay away from scripting languages not already
2de9b711 210 used in the Git core command set (unless your command is clearly
6d0618a8 211 separate from it, such as an importer to convert random-scm-X
2de9b711 212 repositories to Git).
57199892
KB
213
214 - When we pass <string, length> pair to functions, we should try to
215 pass them in that order.
c455bd89 216
5e9637c6
ÆAB
217 - Use Git's gettext wrappers to make the user interface
218 translatable. See "Marking strings for translation" in po/README.
219
c5e366b1
TZ
220For Perl programs:
221
222 - Most of the C guidelines above apply.
223
224 - We try to support Perl 5.8 and later ("use Perl 5.008").
225
226 - use strict and use warnings are strongly preferred.
227
228 - Don't overuse statement modifiers unless using them makes the
229 result easier to follow.
230
231 ... do something ...
232 do_this() unless (condition);
233 ... do something else ...
234
235 is more readable than:
236
237 ... do something ...
238 unless (condition) {
239 do_this();
240 }
241 ... do something else ...
242
243 *only* when the condition is so rare that do_this() will be almost
244 always called.
245
246 - We try to avoid assignments inside "if ()" conditions.
247
248 - Learn and use Git.pm if you need that functionality.
249
250 - For Emacs, it's useful to put the following in
251 GIT_CHECKOUT/.dir-locals.el, assuming you use cperl-mode:
252
253 ;; note the first part is useful for C editing, too
254 ((nil . ((indent-tabs-mode . t)
255 (tab-width . 8)
256 (fill-column . 80)))
257 (cperl-mode . ((cperl-indent-level . 8)
258 (cperl-extra-newline-before-brace . nil)
259 (cperl-merge-trailing-else . t))))
260
9ef43dd7
JK
261For Python scripts:
262
263 - We follow PEP-8 (http://www.python.org/dev/peps/pep-0008/).
264
265 - As a minimum, we aim to be compatible with Python 2.6 and 2.7.
266
267 - Where required libraries do not restrict us to Python 2, we try to
268 also be compatible with Python 3.1 and later.
269
270 - When you must differentiate between Unicode literals and byte string
271 literals, it is OK to use the 'b' prefix. Even though the Python
272 documentation for version 2.6 does not mention this prefix, it has
273 been supported since version 2.6.0.
274
c455bd89
ŠN
275Writing Documentation:
276
48bc1755
DW
277 Most (if not all) of the documentation pages are written in the
278 AsciiDoc format in *.txt files (e.g. Documentation/git.txt), and
279 processed into HTML and manpages (e.g. git.html and git.1 in the
280 same directory).
bb9f2aec 281
42e0fae9
MB
282 The documentation liberally mixes US and UK English (en_US/UK)
283 norms for spelling and grammar, which is somewhat unfortunate.
284 In an ideal world, it would have been better if it consistently
285 used only one and not the other, and we would have picked en_US
286 (if you wish to correct the English of some of the existing
287 documentation, please see the documentation-related advice in the
288 Documentation/SubmittingPatches file).
289
c455bd89
ŠN
290 Every user-visible change should be reflected in the documentation.
291 The same general rule as for code applies -- imitate the existing
ca03c368
JSJ
292 conventions.
293
294 A few commented examples follow to provide reference when writing or
295 modifying command usage strings and synopsis sections in the manual
296 pages:
c455bd89 297
b1afe49d 298 Placeholders are spelled in lowercase and enclosed in angle brackets:
c455bd89
ŠN
299 <file>
300 --sort=<key>
301 --abbrev[=<n>]
302
469bfc96 303 Possibility of multiple occurrences is indicated by three dots:
c455bd89
ŠN
304 <file>...
305 (One or more of <file>.)
306
307 Optional parts are enclosed in square brackets:
308 [<extra>]
309 (Zero or one <extra>.)
310
311 --exec-path[=<path>]
312 (Option with an optional argument. Note that the "=" is inside the
313 brackets.)
314
315 [<patch>...]
316 (Zero or more of <patch>. Note that the dots are inside, not
317 outside the brackets.)
318
319 Multiple alternatives are indicated with vertical bar:
320 [-q | --quiet]
321 [--utf8 | --no-utf8]
322
323 Parentheses are used for grouping:
324 [(<rev>|<range>)...]
325 (Any number of either <rev> or <range>. Parens are needed to make
326 it clear that "..." pertains to both <rev> and <range>.)
327
328 [(-p <parent>)...]
329 (Any number of option -p, each with one <parent> argument.)
330
331 git remote set-head <name> (-a | -d | <branch>)
332 (One and only one of "-a", "-d" or "<branch>" _must_ (no square
333 brackets) be provided.)
334
335 And a somewhat more contrived example:
336 --diff-filter=[(A|C|D|M|R|T|U|X|B)...[*]]
337 Here "=" is outside the brackets, because "--diff-filter=" is a
338 valid usage. "*" has its own pair of brackets, because it can
339 (optionally) be specified only when one or more of the letters is
340 also provided.
48a8c26c
TA
341
342 A note on notation:
343 Use 'git' (all lowercase) when talking about commands i.e. something
344 the user would type into a shell and use 'Git' (uppercase first letter)
345 when talking about the version control system and its properties.
ca03c368
JSJ
346
347 A few commented examples follow to provide reference when writing or
348 modifying paragraphs or option/command explanations that contain options
349 or commands:
350
351 Literal examples (e.g. use of command-line options, command names, and
352 configuration variables) are typeset in monospace, and if you can use
353 `backticks around word phrases`, do so.
354 `--pretty=oneline`
355 `git rev-list`
356 `remote.pushdefault`
357
358 Word phrases enclosed in `backtick characters` are rendered literally
359 and will not be further expanded. The use of `backticks` to achieve the
360 previous rule means that literal examples should not use AsciiDoc
361 escapes.
362 Correct:
363 `--pretty=oneline`
364 Incorrect:
365 `\--pretty=oneline`
366
367 If some place in the documentation needs to typeset a command usage
368 example with inline substitutions, it is fine to use +monospaced and
369 inline substituted text+ instead of `monospaced literal text`, and with
370 the former, the part that should not get substituted must be
371 quoted/escaped.