Project

General

Profile

Coding Standards » History » Version 44

Peter Amstutz, 09/11/2024 08:38 PM

1 1 Tom Clegg
h1. Coding Standards
2
3 41 Peter Amstutz
The rules are always up for debate. However, when debate is needed, it should happen outside the source tree. In other words, if the rules are wrong, first debate the rules at sprint retrospective, then fix the rules, then follow the new rules.
4 1 Tom Clegg
5 2 Tom Clegg
{{toc}}
6 1 Tom Clegg
7 41 Peter Amstutz
h2. Ready to implement checklist
8
9
Before starting full implementation, please fill out this template with information about pre-planning:
10
11
<pre>
12
* Goals and scope of the ticket are clear to the assigned developer and assigned reviewer.
13
** _comments_
14 44 Peter Amstutz
* New or changed UX/UX has a mockup and has gotten feedback from stakeholders.
15 41 Peter Amstutz
** _comments_
16 42 Peter Amstutz
* If part of a larger project, ticket is linked to upstream and downstream tasks.
17 41 Peter Amstutz
** _comments_
18
</pre>
19
20 44 Peter Amstutz
UX/UX stands for "User Interface / User Experience".  This includes new or modified GUI elements in workbench and as well as usability elements of command line tools.
21 41 Peter Amstutz
22
Mockups can consist of a wireframe sketched using a drawing tool (e.g. https://excalidraw.com/) or a coding a non-functional prototype focusing on visual design and avoiding implement behavior and uses hardcoded values.
23
24 44 Peter Amstutz
Stakeholders include the rest of the engineering team, as well as designers, salespeople, customers and other end users as appropriate.  In this process, the assigned developer presents the mockup, makes note of any feedback, and then based on their judgement either: alters the mockup, iterates on feedback, or begins implementation.
25 41 Peter Amstutz
26 32 Peter Amstutz
h2. Ready to merge checklist
27
28
Before asking for a branch review, please fill out this template with information about the branch.
29
30 33 Peter Amstutz
+template begins below, replace the bits between < >+
31 32 Peter Amstutz
32
<pre>
33
<00000-branch-title> @ commit:<git hash>
34
35
<https://ci.arvados.org/... (link to developer test job on jenkins)>
36
37 1 Tom Clegg
_Note each item completed with additional detail if necessary.  If an item is irrelevant to a specific branch, briefly explain why._
38 32 Peter Amstutz
39 43 Peter Amstutz
* All agreed upon points are implemented / addressed.  Describe changes from pre-implementation design.
40 1 Tom Clegg
** _comments_
41 32 Peter Amstutz
* Anything not implemented (discovered or discussed during work) has a follow-up story.
42 1 Tom Clegg
** _comments_
43 41 Peter Amstutz
* Code is tested and passing, both automated and manual, what manual testing was done is described.
44 32 Peter Amstutz
** _comments_
45 44 Peter Amstutz
* New or changed UX/UX and has gotten feedback from stakeholders.
46 41 Peter Amstutz
** _comments_
47 32 Peter Amstutz
* Documentation has been updated.
48
** _comments_
49
* Behaves appropriately at the intended scale (describe intended scale).
50
** _comments_
51
* Considered backwards and forwards compatibility issues between client and server.
52 1 Tom Clegg
** _comments_
53 32 Peter Amstutz
* Follows our "coding standards":https://dev.arvados.org/projects/arvados/wiki/Coding_Standards and "GUI style guidelines.":https://dev.arvados.org/projects/arvados/wiki/Coding_Standards#GUI-Workbench-2
54 1 Tom Clegg
** _comments_
55
56
<Additional detail about what, why and how this branch changes the code>
57
</pre>
58 44 Peter Amstutz
59
UX/UX stands for "User Interface / User Experience".  This includes new or modified GUI elements in workbench and as well as usability elements of command line tools.
60
61
Stakeholders include the rest of the engineering team, as well as designers, salespeople, customers and other end users as appropriate.  In this process, the assigned developer demos the new feature, makes note of any feedback, and then based on their judgement either: implements the changes, provides a reason why the feedback cannot be acted on, or discusses how to handle the feedback with the assigned reviewer and/or product manager.
62 32 Peter Amstutz
63 2 Tom Clegg
h2. Git commits
64
65 1 Tom Clegg
Make sure your name and email address are correct.
66
67
* Use @git config --global user.email foo@example.com@ et al.
68
* It's a little unfortunate to have commits with author @foo@myworkstation.local@ but not bad enough to rewrite history, so fix this before you push!
69
70 19 Tom Clegg
Refer to a story number in the first (summary) line of each commit comment. This first line should be <80 chars long, and should be followed by a blank line.
71 9 Tom Clegg
72
* @1234: Remove useless button.@
73
74
*When merging/committing to master,* refer to the story number in a way Redmine will notice. Redmine will list these commits/merges on the story page itself.
75
76 1 Tom Clegg
* @closes #1234@, or
77 19 Tom Clegg
* @refs #1234@, or
78
* @no issue #@ if no Redmine issue is especially relevant.
79 9 Tom Clegg
80 1 Tom Clegg
Use descriptive commit comments.
81
82
* Describe the delta between the old and new tree. If possible, describe the delta in *behavior* rather than the source code itself.
83 9 Tom Clegg
* Good: "1234: Support use of spaces in filenames."
84
* Good: "1234: Fix crash when user_id is nil."
85 1 Tom Clegg
* Less good: "Add some controller methods." (What do they do?)
86
* Less good: "More progress on UI branch." (What is different?)
87
* Less good: "Incorporate Tom's suggestions." (Who cares whose suggestions -- what changed?)
88
89
If further background or explanation is needed, separate it from the summary with a blank line.
90
91
* Example: "Users found it confusing that the boxes had different colors even though they represented the same kinds of things."
92
93 18 Tom Clegg
*Every commit* (even merge commits) must have a DCO sign-off. See [[Developer Certificate Of Origin]].
94 1 Tom Clegg
95
* Example: <code>Arvados-DCO-1.1-Signed-off-by: Joe Smith <joe.smith@example.com></code>
96 19 Tom Clegg
97
Full examples:
98
99
<pre>
100
commit 9c6540b9d42adc4a397a28be1ac23f357ba14ab5
101
Author: Tom Clegg <tom@curoverse.com>
102
Date:   Mon Aug 7 09:58:04 2017 -0400
103
104
    12027: Recognize a new "node failed" error message.
105
    
106
    "srun: error: Cannot communicate with node 0.  Aborting job."
107
    
108
    Arvados-DCO-1.1-Signed-off-by: Tom Clegg <tom@curoverse.com>
109
</pre>
110
111
<pre>
112
commit 0b4800608e6394d66deec9cecea610c5fbbd75ad
113
Merge: 6f2ce94 3a356c4
114
Author: Tom Clegg <tom@curoverse.com>
115
Date:   Thu Aug 17 13:16:36 2017 -0400
116
117
    Merge branch '12081-crunch-job-retry'
118
    
119
    refs #12080
120
    refs #12081
121
    refs #12108
122
    
123
    Arvados-DCO-1.1-Signed-off-by: Tom Clegg <tom@curoverse.com>
124
</pre>
125
126 21 Ward Vandewege
h2. Copyright headers
127
128 23 Ward Vandewege
Each Arvados component is released either under the AGPL 3.0 license or the Apache 2.0 license. Documentation is licensed under CC-BY-SA-3.0. See the [[Arvados Licenses FAQ]] for the rationale behind this system.
129 21 Ward Vandewege
130 22 Ward Vandewege
Every file must start with a copyright header that follows this format:
131 21 Ward Vandewege
132
Code under the "AGPLv3 license":http://www.gnu.org/licenses/agpl-3.0.en.html (this example uses Go formatting):
133
134
<pre>
135
// Copyright (C) The Arvados Authors. All rights reserved.
136
//
137
// SPDX-License-Identifier: AGPL-3.0
138
</pre>
139
140
Code under the "Apache 2.0 license":http://www.apache.org/licenses/LICENSE-2.0 (this example uses Python formatting):
141
142
<pre>
143
# Copyright (C) The Arvados Authors. All rights reserved.
144
#
145
# SPDX-License-Identifier: Apache-2.0
146
</pre>
147
148
Documentation under the "Creative Commons Attribution-Share Alike 3.0 United States license":https://creativecommons.org/licenses/by-sa/3.0/us/ (this example uses textile formatting):
149
150
<pre>
151
###. Copyright (C) The Arvados Authors. All rights reserved.
152
....
153
.... SPDX-License-Identifier: CC-BY-SA-3.0
154
</pre>
155
156 1 Tom Clegg
When adding a new file to a component, use the same license as the other files of the component.
157
158 22 Ward Vandewege
When adding a new component, choose either the AGPL or Apache license. Generally speaking, the Apache license is only used for components where integrations in proprietary code must be possible (e.g. our SDKs), though this is not a hard rule. When uncertain which license to choose for a new component, ask on the IRC channel or mailing list.
159 21 Ward Vandewege
160 22 Ward Vandewege
When adding a file in a format that does not support the addition of a copyright header (e.g. in a binary format like an image), add the path to the .licenseignore file in the root of the source tree. This should be done sparingly, and must be discussed explicitly as part of code review. The file must be available under a license that is compatible with the rest of the Arvados code base.
161 21 Ward Vandewege
162 22 Ward Vandewege
When adding a file that originates from an external source under a different license, add the appropriate SPDX line for that license. This is exceptional, and must be discussed explicitly as part of code review. Not every license is compatible with the rest of the Arvados code base.
163 16 Tom Clegg
164 28 Ward Vandewege
There is a helper script at https://github.com/arvados/arvados/blob/master/build/check-copyright-notices that can be used to check - and optionally, fix - the copyright headers in the Arvados source tree.
165 24 Ward Vandewege
166 29 Ward Vandewege
The actual git hook that enforces the copyright headers lives at https://github.com/arvados/arvados-dev/blob/master/git/hooks/check-copyright-headers.rb
167 25 Ward Vandewege
168 13 Tom Clegg
h2. Source code formatting
169 1 Tom Clegg
170 13 Tom Clegg
(Unless otherwise specified by style guide...)
171
172 10 Tom Clegg
No TAB characters in source files. "Except go programs.":https://golang.org/cmd/gofmt/
173 1 Tom Clegg
174 6 Tom Clegg
* Emacs: add to @~/.emacs@ &rarr; @(setq-default indent-tabs-mode nil)@
175
* Vim: add to @~/.vimrc@ &rarr; @:set expandtab@
176 8 Tom Clegg
* See [[Coding Standards#Git setup|Git setup]] below
177 4 Ward Vandewege
178 37 Tom Clegg
No long (>80 column) lines, except
179
* when the alternative is really clunky
180
* in Go where Google style guide prevails, and e.g., "function and method calls should not be separated based solely on line length":https://google.github.io/styleguide/go/decisions#function-formatting
181 6 Tom Clegg
182 4 Ward Vandewege
No whitespace at the end of lines. Make git-diff show you:
183 5 Ward Vandewege
184
  git config color.diff.whitespace "red reverse"
185 6 Tom Clegg
git diff --check
186 1 Tom Clegg
187 13 Tom Clegg
h2. What to include
188
189 1 Tom Clegg
No commented-out blocks of code that have been replaced or obsoleted.
190
191
* It is in the git history if we want it back.
192
* If its absence would confuse someone reading the new code (despite never having read the old code), explain its absence in an English comment. If the old code is really still needed to support the English explanation, then go ahead -- now we know why it's there.
193
194
No commented-out debug statements.
195
196
* If the debug statements are likely to be needed in the future, use a logging facility that can be enabled at run time. @logger.debug "foo"@
197
198 13 Tom Clegg
h2. Style mismatch
199
200 1 Tom Clegg
Adopt indentation style of surrounding lines or (when starting a new file) the nearest existing source code in this tree/language.
201
202
If you fix up existing indentation/formatting, do that in a separate commit.
203
* If you bundle formatting changes with functional changes, it makes functional changes hard to find in the diff.
204
205 13 Tom Clegg
h2. Go
206
207
gofmt, golint, etc., and https://github.com/golang/go/wiki/CodeReviewComments
208
209 40 Tom Clegg
Use @%w@ when wrapping an error with fmt.Errorf(), so errors.As() can access the wrapped error.
210
211
<pre><code class="go">
212
        if err != nil {
213
                return fmt.Errorf("could not swap widgets: %w", err)
214
        }
215
</code></pre>
216
217
Use @(logrus.FieldLogger)WithError()@ (instead of @Logf("blah: %s", err)@) when logging an error.
218
219
<pre><code class="go">
220
        if err != nil {
221
                logger.WithError(err).Warn("error swapping widgets")
222
        }
223
</code></pre>
224
225
226 13 Tom Clegg
h2. Ruby
227
228
https://github.com/bbatsov/ruby-style-guide
229
230 1 Tom Clegg
h2. Python
231 13 Tom Clegg
232 30 Brett Smith
h3. Python code
233 12 Tom Clegg
234 30 Brett Smith
For code, follow "PEP 8":https://peps.python.org/pep-0008/.
235 1 Tom Clegg
236 30 Brett Smith
When you add functions, methods, or attributes that SDK users should not use, their name should start with a leading underscore. This is a common convention to signal that an interface is not intended to be public. Anything named this way will be excluded from our SDK web documentation by default.
237
238 39 Brett Smith
You're encouraged to add type annotations to functions and methods. As of May 2024 these are purely for documentation: we are not type checking any of our Python. Note that your annotations must be understood by the oldest version of Python we currently support (3.8).
239 36 Brett Smith
240 30 Brett Smith
h3. Python docstrings
241
242
Public classes, methods, and functions should all have docstrings. The content of the docstring should follow "PEP 257":https://peps.python.org/pep-0257/.
243
244 1 Tom Clegg
Format docstrings with Markdown and follow these style rules:
245
246 36 Brett Smith
* Document function argument lists after the high-level description following this format for each argument: <pre>* name: type --- Description</pre>Use exactly three minus-hyphens to get an em dash in the web rendering. Provide a helpful type hint whenever practical. The type hint should be written in "modern" style:
247
** Use builtin subscripting from PEP 585/Python 3.9, like @dict[str, str]@, @list[tuple[int, str]]@
248
** Use type union syntax from PEP 604/Python 3.10, like @int | None@, @list[str | bytes]@
249
** Use fully qualified names for custom types. This way pdoc hyperlinks them.
250 34 Brett Smith
* When something is deprecated, write a @.. WARNING:: Deprecated@ admonition immediately after the first line. Its text should explain that the thing is deprecated, and suggest what to use instead. For example:<pre>def add(a, b):
251
    """Add two things.
252
253 1 Tom Clegg
    .. WARNING:: Deprecated
254
       This function is deprecated. Use the `+` operator instead.
255 30 Brett Smith
256
257 36 Brett Smith
    """</pre>You can similarly note private methods with @.. ATTENTION:: Internal@.
258
* Mark up all identifiers outside the type hint with backticks. When the identifier exists in the current module, use the short name. Otherwise, use the fully-qualified name. Our web documentation will automatically link these identifiers to their corresponding documentation.
259 30 Brett Smith
* Mark up links using Markdown's footnote style. For example:<pre>"""Python docstring following [PEP 257][pep257].
260
261
[pep257]: https://peps.python.org/pep-0257/
262
"""</pre>This looks best in plaintext. A descriptive identifier is nice if you can keep it short, but if that's challenging, plain ordinals are fine too.
263
* Mark up headers (e.g., in a module docstring) using underline style. For example:<pre>"""Generic utility module
264
265
Filesystem functions
266
--------------------
267
268
269
270
Regular expressions
271
-------------------
272
273
274
"""</pre>This looks best in plaintext.
275
276
The goal of these style rules is to provide a readable, consistent appearance whether people read the documentation in plain text (e.g., using @pydoc@) or their browser (as rendered by @pdoc@).
277 12 Tom Clegg
278 11 Brett Smith
h2. JavaScript
279
280 20 Tom Clegg
Follow the Airbnb Javascript coding style guide unless otherwise stated:
281 14 Tom Morris
https://github.com/airbnb/javascript
282 20 Tom Clegg
283
We already have 4-space indents everywhere, though, so do that.
284
285 14 Tom Morris
286 7 Tom Clegg
h2. Git setup
287 6 Tom Clegg
288 7 Tom Clegg
Configure git to prevent you from committing whitespace errors.
289 1 Tom Clegg
290 6 Tom Clegg
<pre>
291 7 Tom Clegg
git config --global core.whitespace tab-in-indent,trailing-space
292 1 Tom Clegg
git config --global apply.whitespace error
293 17 Tom Clegg
</pre>
294
295
Add a DCO sign-off to the default commit message.
296
297
<pre>
298
cd .../arvados
299
printf '\n\nArvados-DCO-1.1-Signed-off-by: %s <%s>\n' "$(git config user.name)" "$(git config user.email)" >~/.arvados-dco.txt
300
git config commit.template ~/.arvados-dco.txt
301
</pre>
302
303
Add a DCO sign-off and "refs #xxxx" comment (referencing the issue# in the name of the branch being merged) to the default merge commit message.
304
305
<pre>
306
cd .../arvados
307 26 Eric Biagiotti
cat >.git/hooks/prepare-commit-msg <<'EOF'
308 17 Tom Clegg
#!/bin/sh
309
310
case "$2,$3" in
311
    merge,)
312
        br=$(head -n1 ${1})
313
        n=$(echo "${br}" | egrep -o '[0-9]+')
314
        exec >${1}
315
        echo "${br}"
316
        echo
317
        echo "refs #${n}"
318
        echo
319 27 Eric Biagiotti
        echo "Arvados-DCO-1.1-Signed-off-by: $(git config user.name) <$(git config user.email)>"
320 17 Tom Clegg
        ;;
321
    *)
322
        ;;
323
esac
324
EOF
325 26 Eric Biagiotti
chmod +x .git/hooks/prepare-commit-msg
326 6 Tom Clegg
</pre>
327 31 Brett Smith
328 38 Stephen Smith
h2. GUI Design Guidelines (Workbench 2)
329 31 Brett Smith
330
h3. Font Sizes
331
332
* Minimum 12pt (16px) 
333
* Minimum 9 pt (12px) for things like by copyright, footer
334
335
This should be able to be-resized up to 200% without loss of content or functionality.
336
337
h3. Color
338
339
* Text and images of text have a color contrast ratio of at least 4.5:1 You can use "this contrast tool":https://snook.ca/technical/colour_contrast/colour.html#fg=1F7EA1,bg=FFFFFF to check.
340
* Non-text icon, controls, etc - 3:1 must have a color contrast ratio of 3:1.
341
* Avoid hard-coding colors. Use theme colors. If a new color is needed, add it to the theme.  
342
* Used defined grays when possible using RGB value and changing the a value to indicate different meanings (i.e. Active icons have an opacity of 87%, Inactive icons have an opacity of 60%, Disabled icons have an opacity of 38%)
343
344
h3. Icons
345
346
h4. General
347
348
* Interaction target size of at least 44 x 44 pixels
349
* Label should be on right, icon on left for maximum readability
350
* Use minimum 3:1 color contrast (see Color above)
351
* User appropriate concise alt text for people using screen readers 
352
353
h4. Menu/Navigation 
354
355
* No navigation should only supported via breadcrumbs
356
* If less than 5 menu options, consider visible navigation options
357
* If more than 5 menu options, consider a combination navigation where some options are visible and some are hidden
358
* Use the following menu consistently:	
359
** Hamburger (three bars stacked vertically): Used to indicate navigation bar/menu that toggles between being collapsed behind the button or displayed on the screen, often used for global/site-wide/whole application navigation
360
** Döner (three bars that narrow vertically):  Indicates a group filtering menu
361
** Bento (3×3 grid of squares):  Indicates a menu presenting a grid of options (not currently applicable to WB)
362
** Kebab (three dots stacked vertically): Indicates a smaller inline-menu or an overflow/combination menu
363
** Meatballs (three dots stacked horizontally):  Used to indicate a smaller inline-menu.  Often used to indicate action on a related item (i.e. item next to the meatball), good for repeated use in tables, or horizontal elements
364
* If component is an accordion window,  use caret(‸)
365
366
Preferred Icon Repositories:
367
* https://v4.mui.com/components/material-icons/
368
* https://materialdesignicons.com/
369
* https://fontawesome.com/v5/search
370
371
h3. Buttons
372
373
* Label button with action for usability/to reduce ambiguity (avoid generic button labels for actions)
374
* Buttons vs Links
375
** Buttons should cause change in current context
376
** Links should navigate to a different content or a new resource (e.g. different page)
377
* If text on button - color contract should be 4.5 :1 between button and text
378
* Button color and background color contrast should be 3:1
379
380
h3. Arvados Specific Components
381
382 1 Tom Clegg
Use chips for displaying tokenized values/arrays
383 38 Stephen Smith
384
h3. Loading Indicators
385
386
h4. Page Navigation
387
388
* Navigation between pages should be indicated using @progressIndicatorActions.START_WORKING@ and @progressIndicatorActions.STOP_WORKING@ to show the global top-of-page pulser
389
* Only the initial load or refresh of the full page (eg. triggered by the upper right refresh button) should use this indicator. Partial refreshes should use a more local indicator.
390
** Refreshes of only one section of a page should only show its own loading indicator in that section
391
* Full page refreshes where the location is unchanged should avoid using the initial full-page spinner in favor of the top-of-page spinner, with updated values substituting in the UI when loaded
392
393
h4. User Actions
394
395
* Form submissions or user actions should be indicated by both the @progressIndicatorActions.START_WORKING@ and by enabling the spinner on the submit button of the form (if the action takes place through a form AND if the form stays open for the duration of the action in order to show errors). If the form closes immediately then the page spinner is the only indicator.
396
* Toasts should not be used to notify the user of an in-progress action but only completion / error
397
398
h4. Lazy-loaded fields
399
400
* Fields that load or update (eg. with extra info) after the main view should wait 3-5 seconds before showing a spinner/pulser icon while loading - if the request for extra data fails, a placeholder icon should show with a hint (text or tooltip) indicating that the data failed to load.
401
** The delayed indicator should be implemented as a reusable component (tbd)
402
* Suggested loading indicator for inline fields: https://mhnpd.github.io/react-loader-spinner/docs/components/three-dots)
403 31 Brett Smith
404
h3. References
405
406
"WCAG2.1":https://www.w3.org/WAI/WCAG21/Understanding/
407
408
"Sarah’s talk for references":https://docs.google.com/presentation/d/1HNrhvK7zVZ7jgH3ELbX7KB97SdXCZXrvov_I4Oe1l2c/edit?usp=sharing