1.. _contribute_guidelines:
2
3Contribution Guidelines
4#######################
5
6As an open-source project, we welcome and encourage the community to submit
7patches directly to the project.  In our collaborative open source environment,
8standards and methods for submitting changes help reduce the chaos that can result
9from an active development community.
10
11This document explains how to participate in project conversations, log bugs
12and enhancement requests, and submit patches to the project so your patch will
13be accepted quickly in the codebase.
14
15.. _licensing_requirements:
16
17Licensing
18*********
19
20Licensing is very important to open source projects. It helps ensure the
21software continues to be available under the terms that the author desired.
22
23.. _Apache 2.0 license:
24   https://github.com/zephyrproject-rtos/zephyr/blob/main/LICENSE
25
26.. _GitHub repo: https://github.com/zephyrproject-rtos/zephyr
27
28Zephyr uses the `Apache 2.0 license`_ (as found in the LICENSE file in
29the project's `GitHub repo`_) to strike a balance between open
30contribution and allowing you to use the software however you would like
31to.  The Apache 2.0 license is a permissive open source license that
32allows you to freely use, modify, distribute and sell your own products
33that include Apache 2.0 licensed software.  (For more information about
34this, check out articles such as `Why choose Apache 2.0 licensing`_ and
35`Top 10 Apache License Questions Answered`_).
36
37.. _Why choose Apache 2.0 licensing:
38   https://www.zephyrproject.org/faqs/#1571346989065-9216c551-f523
39
40.. _Top 10 Apache License Questions Answered:
41   https://www.whitesourcesoftware.com/whitesource-blog/top-10-apache-license-questions-answered/
42
43A license tells you what rights you have as a developer, as provided by the
44copyright holder. It is important that the contributor fully understands the
45licensing rights and agrees to them. Sometimes the copyright holder isn't the
46contributor, such as when the contributor is doing work on behalf of a
47company.
48
49Components using other Licenses
50===============================
51
52There are some imported or reused components of the Zephyr project that
53use other licensing, as described in :ref:`Zephyr_Licensing`.
54
55Importing code into the Zephyr OS from other projects that use a license
56other than the Apache 2.0 license needs to be fully understood in
57context and approved by the Zephyr governing board.
58
59By carefully reviewing potential contributions and also enforcing a
60:ref:`DCO` for contributed code, we can ensure that
61the Zephyr community can develop products with the Zephyr Project
62without concerns over patent or copyright issues.
63
64See :ref:`external-contributions` for more information about
65this contributing and review process for imported components.
66
67.. only:: latex
68
69   .. toctree::
70      :maxdepth: 1
71
72      ../LICENSING.rst
73
74.. _copyrights:
75
76Copyrights Notices
77*******************
78
79Please follow this `Community Best Practice`_ for Copyright Notices from the
80Linux Foundation.
81
82
83.. _Community Best Practice:
84   https://www.linuxfoundation.org/blog/copyright-notices-in-open-source-software-projects/
85
86.. _DCO:
87
88Developer Certification of Origin (DCO)
89***************************************
90
91To make a good faith effort to ensure licensing criteria are met, the Zephyr
92project requires the Developer Certificate of Origin (DCO) process to be
93followed.
94
95The DCO is an attestation attached to every contribution made by every
96developer. In the commit message of the contribution, (described more fully
97later in this document), the developer simply adds a ``Signed-off-by``
98statement and thereby agrees to the DCO.
99
100When a developer submits a patch, it is a commitment that the contributor has
101the right to submit the patch per the license.  The DCO agreement is shown
102below and at http://developercertificate.org/.
103
104.. code-block:: none
105
106    Developer's Certificate of Origin 1.1
107
108    By making a contribution to this project, I certify that:
109
110    (a) The contribution was created in whole or in part by me and I
111        have the right to submit it under the open source license
112        indicated in the file; or
113
114    (b) The contribution is based upon previous work that, to the
115        best of my knowledge, is covered under an appropriate open
116        source license and I have the right under that license to
117        submit that work with modifications, whether created in whole
118        or in part by me, under the same open source license (unless
119        I am permitted to submit under a different license), as
120        Indicated in the file; or
121
122    (c) The contribution was provided directly to me by some other
123        person who certified (a), (b) or (c) and I have not modified
124        it.
125
126    (d) I understand and agree that this project and the contribution
127        are public and that a record of the contribution (including
128        all personal information I submit with it, including my
129        sign-off) is maintained indefinitely and may be redistributed
130        consistent with this project or the open source license(s)
131        involved.
132
133DCO Sign-Off
134============
135
136The "sign-off" in the DCO is a "Signed-off-by:" line in each commit's log
137message. The Signed-off-by: line must be in the following format::
138
139   Signed-off-by: Your Name <your.email@example.com>
140
141For your commits, replace:
142
143- ``Your Name`` with your legal name (pseudonyms, hacker handles, and the
144  names of groups are not allowed)
145
146- ``your.email@example.com`` with the same email address you are using to
147  author the commit (CI will fail if there is no match)
148
149You can automatically add the Signed-off-by: line to your commit body using
150``git commit -s``. Use other commits in the zephyr git history as examples.
151See :ref:`git_setup` for instructions on configuring user and email settings
152in Git.
153
154Additional requirements:
155
156- If you are altering an existing commit created by someone else, you must add
157  your Signed-off-by: line without removing the existing one.
158
159- If you forget to add the Signed-off-by: line, you can add it to your previous
160  commit by running ``git commit --amend -s``.
161
162- If you've pushed your changes to GitHub already you'll need to force push
163  your branch after this with ``git push -f``.
164
165Notes
166=====
167
168Any contributions made as part of submitted pull requests are considered free
169for the Project to use. Developers are permitted to cherry-pick patches that
170are included in pull requests submitted by other contributors. It is expected
171that
172
173* the content of the patches will not be substantially modified,
174* the cherry-picked commits or portions of a commit shall preserve the original
175  sign-off messages and the author identity.
176
177:ref:`modifying_contributions` describes additional recommended policies
178around working with contributions submitted by other developers.
179
180
181Prerequisites
182*************
183
184.. _Zephyr Project website: https://zephyrproject.org
185
186As a contributor, you'll want to be familiar with the Zephyr project, how to
187configure, install, and use it as explained in the `Zephyr Project website`_
188and how to set up your development environment as introduced in the Zephyr
189:ref:`getting_started`.
190
191You should be familiar with common developer tools such as Git and CMake, and
192platforms such as GitHub.
193
194If you haven't already done so, you'll need to create a (free) GitHub account
195on https://github.com and have Git tools available on your development system.
196
197.. note::
198   The Zephyr development workflow supports all 3 major operating systems
199   (Linux, macOS, and Windows) but some of the tools used in the sections below
200   are only available on Linux and macOS. On Windows, instead of running these
201   tools yourself, you will need to rely on the Continuous Integration (CI)
202   service using Github Actions, which runs automatically on GitHub when you submit
203   your Pull Request (PR).  You can see any failure results in the workflow
204   details link near the end of the PR conversation list. See
205   `Continuous Integration`_ for more information
206
207.. _source_tree_v2:
208
209Source Tree Structure
210*********************
211
212To clone the main Zephyr Project repository use the instructions in
213:ref:`get_the_code`.
214
215This section describes the main repository's source tree. In addition to the
216Zephyr kernel itself, you'll also find the sources for technical documentation,
217sample code, supported board configurations, and a collection of subsystem
218tests.  All of these are available for developers to contribute to and enhance.
219
220Understanding the Zephyr source tree can help locate the code
221associated with a particular Zephyr feature.
222
223At the top of the tree, several files are of importance:
224
225:file:`CMakeLists.txt`
226    The top-level file for the CMake build system, containing a lot of the
227    logic required to build Zephyr.
228
229:file:`Kconfig`
230    The top-level Kconfig file, which refers to the file :file:`Kconfig.zephyr`
231    also found in the top-level directory.
232
233    See :ref:`the Kconfig section of the manual <kconfig>` for detailed Kconfig
234    documentation.
235
236:file:`west.yml`
237    The :ref:`west` manifest, listing the external repositories managed by
238    the west command-line tool.
239
240The Zephyr source tree also contains the following top-level
241directories, each of which may have one or more additional levels of
242subdirectories not described here.
243
244:file:`arch`
245    Architecture-specific kernel and system-on-chip (SoC) code.
246    Each supported architecture (for example, x86 and ARM)
247    has its own subdirectory,
248    which contains additional subdirectories for the following areas:
249
250    * architecture-specific kernel source files
251    * architecture-specific kernel include files for private APIs
252
253:file:`soc`
254    SoC related code and configuration files.
255
256:file:`boards`
257    Board related code and configuration files.
258
259:file:`doc`
260    Zephyr technical documentation source files and tools used to
261    generate the https://docs.zephyrproject.org web content.
262
263:file:`drivers`
264    Device driver code.
265
266:file:`dts`
267    :ref:`devicetree <dt-guide>` source files used to describe non-discoverable
268    board-specific hardware details.
269
270:file:`include`
271    Include files for all public APIs, except those defined under :file:`lib`.
272
273:file:`kernel`
274    Architecture-independent kernel code.
275
276:file:`lib`
277    Library code, including the minimal standard C library.
278
279:file:`misc`
280    Miscellaneous code that doesn't belong to any of the other top-level
281    directories.
282
283:file:`samples`
284    Sample applications that demonstrate the use of Zephyr features.
285
286:file:`scripts`
287    Various programs and other files used to build and test Zephyr
288    applications.
289
290:file:`cmake`
291    Additional build scripts needed to build Zephyr.
292
293:file:`subsys`
294    Subsystems of Zephyr, including:
295
296    * USB device stack code
297    * Networking code, including the Bluetooth stack and networking stacks
298    * File system code
299    * Bluetooth host and controller
300
301:file:`tests`
302    Test code and benchmarks for Zephyr features.
303
304:file:`share`
305    Additional architecture independent data. It currently contains Zephyr's CMake
306    package.
307
308Pull Requests and Issues
309************************
310
311.. _Zephyr Project Issues: https://github.com/zephyrproject-rtos/zephyr/issues
312
313.. _open pull requests: https://github.com/zephyrproject-rtos/zephyr/pulls
314
315.. _Zephyr devel mailing list: https://lists.zephyrproject.org/g/devel
316
317.. _Zephyr Discord Server: https://chat.zephyrproject.org
318
319Before starting on a patch, first check in our issues `Zephyr Project Issues`_
320system to see what's been reported on the issue you'd like to address.  Have a
321conversation on the `Zephyr devel mailing list`_ (or the `Zephyr Discord
322Server`_) to see what others think of your issue (and proposed solution).  You
323may find others that have encountered the issue you're finding, or that have
324similar ideas for changes or additions.  Send a message to the `Zephyr devel
325mailing list`_ to introduce and discuss your idea with the development
326community.
327
328It's always a good practice to search for existing or related issues before
329submitting your own. When you submit an issue (bug or feature request), the
330triage team will review and comment on the submission, typically within a few
331business days.
332
333You can find all `open pull requests`_ on GitHub and open `Zephyr Project
334Issues`_ in Github issues.
335
336.. _git_setup:
337
338Git Setup
339*********
340
341We need to know who you are, and how to contact you. To add this
342information to your Git installation, set the Git configuration
343variables ``user.name`` to your full name, and ``user.email`` to your
344email address.
345
346For example, if your name is ``Zephyr Developer`` and your email
347address is ``z.developer@example.com``:
348
349.. code-block:: console
350
351   git config --global user.name "Zephyr Developer"
352   git config --global user.email "z.developer@example.com"
353
354.. note::
355   ``user.name`` must be your full name (first and last at minimum), not a
356   pseudonym or hacker handle. The email address that you use in your Git configuration must match the email
357   address you use to sign your commits. If they don't match, the CI system will
358   fail your pull request.
359
360   If you intend to edit commits using the Github.com UI, ensure that your github profile
361   ``email address`` and profile ``name`` also match those used in your git configuration
362   (``user.name`` & ``user.email``).
363
364Pull Request Guidelines
365***********************
366When opening a new Pull Request, adhere to the following guidelines to ensure
367compliance with Zephyr standards and facilitate the review process.
368
369If in doubt, it's advisible to explore existing Pull Requests within the Zephyr
370repository. Use the search filters and labels to locate PRs related to changes
371similar to the ones you are proposing.
372
373.. _commit-guidelines:
374
375Commit Message Guidelines
376=========================
377
378Changes are submitted as Git commits. Each commit has a *commit
379message* describing the change. Acceptable commit messages look like
380this:
381
382.. code-block:: none
383
384   [area]: [summary of change]
385
386   [Commit message body (must be non-empty)]
387
388   Signed-off-by: [Your Full Name] <[your.email@address]>
389
390You need to change text in square brackets (``[like this]``) above to
391fit your commit.
392
393Examples and more details follow.
394
395Example
396-------
397
398Here is an example of a good commit message.
399
400.. code-block:: none
401
402   drivers: sensor: abcd1234: fix bus I/O error handling
403
404   The abcd1234 sensor driver is failing to check the flags field in
405   the response packet from the device which signals that an error
406   occurred. This can lead to reading invalid data from the response
407   buffer. Fix it by checking the flag and adding an error path.
408
409   Signed-off-by: Zephyr Developer <z.developer@example.com>
410
411[area]: [summary of change]
412---------------------------
413
414This line is called the commit's *title*. Titles must be:
415
416* one line
417* less than 72 characters long
418* followed by a completely blank line
419
420[area]
421  The ``[area]`` prefix usually identifies the area of code
422  being changed. It can also identify the change's wider
423  context if multiple areas are affected.
424
425  Here are some examples:
426
427  * ``doc: ...`` for documentation changes
428  * ``drivers: foo:`` for ``foo`` driver changes
429  * ``Bluetooth: Shell:`` for changes to the Bluetooth shell
430  * ``net: ethernet:`` for Ethernet-related networking changes
431  * ``dts:`` for treewide devicetree changes
432  * ``style:`` for code style changes
433
434  If you're not sure what to use, try running ``git log FILE``, where
435  ``FILE`` is a file you are changing, and using previous commits that
436  changed the same file as inspiration.
437
438[summary of change]
439  The ``[summary of change]`` part should be a quick description of
440  what you've done. Here are some examples:
441
442  * ``doc: update wiki references to new site``
443  * ``drivers: sensor: sensor_shell: fix channel name collision``
444
445Commit Message Body
446-------------------
447
448.. warning::
449
450   An empty commit message body is not permitted. Even for trivial
451   changes, please include a descriptive commit message body. Your
452   pull request will fail CI checks if you do not.
453
454This part of the commit should explain what your change does, and why
455it's needed. Be specific. A body that says ``"Fixes stuff"`` will be
456rejected. Be sure to include the following as relevant:
457
458* **what** the change does,
459* **why** you chose that approach,
460* **what** assumptions were made, and
461* **how** you know it works -- for example, which tests you ran.
462
463Each line in your commit message should usually be 75 characters or
464less. Use newlines to wrap longer lines. Exceptions include lines
465with long URLs, email addresses, etc.
466
467For examples of accepted commit messages, you can refer to the Zephyr GitHub
468`changelog <https://github.com/zephyrproject-rtos/zephyr/commits/main>`__.
469
470
471Signed-off-by: ...
472------------------
473
474.. tip::
475
476   You should have set your :ref:`git_setup`
477   already. Create your commit with ``git commit -s`` to add the
478   Signed-off-by: line automatically using this information.
479
480For open source licensing reasons, your commit must include a
481Signed-off-by: line that looks like this:
482
483.. code-block:: none
484
485   Signed-off-by: [Your Full Name] <[your.email@address]>
486
487For example, if your full name is ``Zephyr Developer`` and your email
488address is ``z.developer@example.com``:
489
490.. code-block:: none
491
492   Signed-off-by: Zephyr Developer <z.developer@example.com>
493
494This means that you have personally made sure your change complies
495with the :ref:`DCO`. For this reason, you must use your legal name.
496Pseudonyms or "hacker aliases" are not permitted.
497
498Your name and the email address you use must match the name and email
499in the Git commit's ``Author:`` field.
500
501See the :ref:`contributor-expectations` for a more complete discussion of
502contributor and reviewer expectations.
503
504Adding links
505------------
506
507.. _GitHub references:
508   https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/autolinked-references-and-urls
509
510Do not include `GitHub references`_ in the commit message directly, as it can
511lose meaning in case the repository is forked, for example. Instead, if the
512change addresses a specific GitHub issue, include in the Pull Request message a
513line of the form:
514
515.. code-block:: none
516
517   Fixes #[issue number]
518
519Where ``[issue number]`` is the relevant GitHub issue's number. For
520example:
521
522.. code-block:: none
523
524   Fixes: #1234
525
526You can point to other relevant information that can be found on the web using
527:code:`Link:` tags. This includes, for example: GitHub issues, datasheets,
528reference manuals, etc.
529
530.. code-block:: none
531
532   Link: https://github.com/zephyrproject-rtos/zephyr/issues/<issue number>
533
534.. _coding_style:
535
536Coding Style
537============
538
539.. _Linux kernel coding style:
540   https://kernel.org/doc/html/latest/process/coding-style.html
541
542In general, follow the `Linux kernel coding style`_, with the following
543exceptions:
544
545* The line length is 100 columns or fewer. In the documentation, longer lines
546  for URL references are an allowed exception.
547* Add braces to every ``if``, ``else``, ``do``, ``while``, ``for`` and
548  ``switch`` body, even for single-line code blocks.
549* Use spaces instead of tabs to align comments after declarations, as needed.
550* Use C89-style single line comments, ``/*  */``. The C99-style single line
551  comment, ``//``, is not allowed.
552* Use ``/**  */`` for doxygen comments that need to appear in the documentation.
553* Avoid using binary literals (constants starting with ``0b``).
554* Avoid using non-ASCII symbols in code, unless it significantly improves
555  clarity, avoid emojis in any case.
556
557Use these coding guidelines to ensure that your development complies with the
558project's style and naming conventions.
559
560The Linux kernel GPL-licensed tool ``checkpatch`` is used to check
561coding style conformity.
562
563.. note::
564   checkpatch does not currently run on Windows.
565
566Checkpatch is available in the scripts directory. To invoke it when committing
567code, make the file *$ZEPHYR_BASE/.git/hooks/pre-commit* executable and edit
568it to contain:
569
570.. code-block:: bash
571
572    #!/bin/sh
573    set -e exec
574    exec git diff --cached | ${ZEPHYR_BASE}/scripts/checkpatch.pl -
575
576Instead of running checkpatch at each commit, you may prefer to run it only
577before pushing on zephyr repo. To do this, make the file
578*$ZEPHYR_BASE/.git/hooks/pre-push* executable and edit it to contain:
579
580.. code-block:: bash
581
582    #!/bin/sh
583    remote="$1"
584    url="$2"
585
586    z40=0000000000000000000000000000000000000000
587
588    echo "Run push hook"
589
590    while read local_ref local_sha remote_ref remote_sha
591    do
592        args="$remote $url $local_ref $local_sha $remote_ref $remote_sha"
593        exec ${ZEPHYR_BASE}/scripts/series-push-hook.sh $args
594    done
595
596    exit 0
597
598If you want to override checkpatch verdict and push you branch despite reported
599issues, you can add option --no-verify to the git push command.
600
601A more complete alternative to this is using :ref:`check_compliance_py` script.
602
603clang-format
604------------
605
606The `clang-format tool <https://clang.llvm.org/docs/ClangFormat.html>`_ can
607be helpful to quickly reformat large amounts of new source code to our
608`Coding Style`_ standards together with the ``.clang-format`` configuration file
609provided in the repository. ``clang-format`` is well integrated into most
610editors, but you can also run it manually like this:
611
612.. code-block:: bash
613
614   clang-format -i my_source_file.c
615
616``clang-format`` is part of LLVM, which can be downloaded from the project
617`releases page <https://github.com/llvm/llvm-project/releases>`_. Note that if
618you are a Linux user, ``clang-format`` will likely be available as a package in
619your distribution repositories.
620
621When there are differences between the `Coding Style`_ guidelines and the
622formatting generated by code formatting tools, the `Coding Style`_ guidelines
623take precedence. If there is ambiguity between formatting tools and the
624guidelines, maintainers may decide which style should be adopted.
625
626.. _Continuous Integration:
627
628Continuous Integration (CI)
629===========================
630
631The Zephyr Project operates a Continuous Integration (CI) system that runs on
632every Pull Request (PR) in order to verify several aspects of the PR:
633
634* Git commit formatting
635* Coding Style
636* Twister builds for multiple architectures and boards
637* Documentation build to verify any doc changes
638
639CI is run on Github Actions and it uses the same tools described in the
640`CI Tests`_ section.  The CI results must be green indicating "All
641checks have passed" before the Pull Request can be merged.  CI is run when the
642PR is created, and again every time the PR is modified with a commit.
643
644The current status of the CI run can always be found at the bottom of the
645GitHub PR page, below the review status. Depending on the success or failure
646of the run you will see:
647
648* "All checks have passed"
649* "All checks have failed"
650
651In case of failure you can click on the "Details" link presented below the
652failure message in order to navigate to ``Github Actions`` and inspect the
653results.
654Once you click on the link you will be taken to the ``Github actions`` summary
655results page where a table with all the different builds will be shown. To see
656what build or test failed click on the row that contains the failed (i.e.
657non-green) build.
658
659.. _CI Tests:
660
661Running CI Tests Locally
662========================
663
664.. _check_compliance_py:
665
666check_compliance.py
667-------------------
668
669The ``check_compliance.py`` script serves as a valuable tool for assessing code
670compliance with Zephyr's established guidelines and best practices. The script
671acts as wrapper for a suite of tools that performs various checks, including
672linters and formatters.
673
674Developers are encouraged to run the script locally to validate their changes
675before opening a new Pull Request:
676
677.. code-block:: bash
678
679   ./scripts/ci/check_compliance.py -c upstream/main..
680
681twister
682-------
683
684.. note::
685   twister is only fully supported on Linux; on Windows and MacOS the execution
686   of tests is not supported, only building.
687
688If you think your change may break some test, you can submit your PR as a draft
689and let the project CI automatically run the :ref:`twister_script` for you.
690
691If a test fails, you can check from the CI run logs how to rerun it locally,
692for example:
693
694.. code-block:: bash
695
696   west twister -p native_sim -s tests/drivers/build_all/sensor/sensors.generic_test
697
698.. _static_analysis:
699
700Static Code Analysis
701********************
702
703Coverity Scan is a free service for static code analysis of Open Source
704projects. It is based on Coverity's commercial product and is able to analyze
705C, C++ and Java code.
706
707Coverity's static code analysis doesn't run the code. Instead of that it uses
708abstract interpretation to gain information about the code's control flow and
709data flow. It's able to follow all possible code paths that a program may take.
710For example the analyzer understands that malloc() returns a memory that must
711be freed with free() later. It follows all branches and function calls to see
712if all possible combinations free the memory. The analyzer is able to detect
713all sorts of issues like resource leaks (memory, file descriptors), NULL
714dereferencing, use after free, unchecked return values, dead code, buffer
715overflows, integer overflows, uninitialized variables, and many more.
716
717The results are available on the `Coverity Scan
718<https://scan.coverity.com/projects/zephyr>`_ website. In order to access the
719results you have to create an account yourself.  From the Zephyr project page,
720you may select "Add me to project" to be added to the project. New members must
721be approved by an admin.
722
723Static analysis of the Zephyr codebase is conducted on a bi-weekly basis. GitHub
724issues are automatically created for any issues detected by static analysis
725tools. These issues will have the same (or equivalent) priority initially
726defined by the tool.
727
728To ensure accountability and efficient issue resolution, they are assigned to
729the respective maintainer who is responsible for the affected code.
730
731A dedicated team comprising members with expertise in static analysis, code
732quality, and software security ensures the effectiveness of the static
733analysis process and verifies that identified issues are properly
734triaged and resolved in a timely manner.
735
736Workflow
737========
738
739If after analyzing the Coverity report it is concluded that it is a false
740positive please set the classification to either "False positive" or
741"Intentional", the action to "Ignore", owner to your own account and add a
742comment why the issue is considered false positive or intentional.
743
744Update the related Github issue in the zephyr project with the details, and only close
745it after completing the steps above on scan service website. Any issues
746closed without a fix or without ignoring the entry in the scan service will be
747automatically reopened if the issue continues to be present in the code.
748
749.. _Contribution workflow:
750
751Contribution Workflow
752*********************
753
754One general practice we encourage, is to make small,
755controlled changes. This practice simplifies review, makes merging and
756rebasing easier, and keeps the change history clear and clean.
757
758When contributing to the Zephyr Project, it is also important you provide as much
759information as you can about your change, update appropriate documentation,
760and test your changes thoroughly before submitting.
761
762The general GitHub workflow used by Zephyr developers uses a combination of
763command line Git commands and browser interaction with GitHub.  As it is with
764Git, there are multiple ways of getting a task done.  We'll describe a typical
765workflow here:
766
767.. _Create a Fork of Zephyr:
768   https://github.com/zephyrproject-rtos/zephyr#fork-destination-box
769
770#. `Create a Fork of Zephyr`_
771   to your personal account on GitHub. (Click on the fork button in the top
772   right corner of the Zephyr project repo page in GitHub.)
773
774#. On your development computer, change into the :file:`zephyr` folder that was
775   created when you :ref:`obtained the code <get_the_code>`::
776
777     cd zephyrproject/zephyr
778
779   Rename the default remote pointing to the `upstream repository
780   <https://github.com/zephyrproject-rtos/zephyr>`_ from ``origin`` to
781   ``upstream``::
782
783     git remote rename origin upstream
784
785   Let Git know about the fork you just created, naming it ``origin``::
786
787     git remote add origin https://github.com/<your github id>/zephyr
788
789   and verify the remote repos::
790
791     git remote -v
792
793   The output should look similar to::
794
795     origin   https://github.com/<your github id>/zephyr (fetch)
796     origin   https://github.com/<your github id>/zephyr (push)
797     upstream https://github.com/zephyrproject-rtos/zephyr (fetch)
798     upstream https://github.com/zephyrproject-rtos/zephyr (push)
799
800#. Create a topic branch (off of ``main``) for your work (if you're addressing
801   an issue, we suggest including the issue number in the branch name)::
802
803     git checkout main
804     git checkout -b fix_comment_typo
805
806   Some Zephyr subsystems do development work on a separate branch from
807   ``main`` so you may need to indicate this in your checkout::
808
809     git checkout -b fix_out_of_date_patch origin/net
810
811#. Make changes, test locally, change, test, test again, ...  (Check out the
812   prior chapter on `twister`_ as well).
813
814#. When things look good, start the pull request process by adding your changed
815   files::
816
817     git add [file(s) that changed, add -p if you want to be more specific]
818
819   You can see files that are not yet staged using::
820
821     git status
822
823#. Verify changes to be committed look as you expected::
824
825     git diff --cached
826
827#. Commit your changes to your local repo::
828
829     git commit -s
830
831   The ``-s`` option automatically adds your ``Signed-off-by:`` to your commit
832   message.  Your commit will be rejected without this line that indicates your
833   agreement with the :ref:`DCO`.  See the :ref:`commit-guidelines` section for
834   specific guidelines for writing your commit messages.
835
836#. Push your topic branch with your changes to your fork in your personal
837   GitHub account::
838
839     git push origin fix_comment_typo
840
841#. In your web browser, go to your forked repo and click on the
842   ``Compare & pull request`` button for the branch you just worked on and
843   you want to open a pull request with.
844
845#. Review the pull request changes, and verify that you are opening a pull
846   request for the ``main`` branch. The title and message from your commit
847   message should appear as well.
848
849#. A bot will assign one or more suggested reviewers (based on the
850   MAINTAINERS file in the repo). If you are a project member, you can
851   select additional reviewers now too.
852
853#. Click on the submit button and your pull request is sent and awaits
854   review.  Email will be sent as review comments are made, or you can check
855   on your pull request at https://github.com/zephyrproject-rtos/zephyr/pulls.
856
857   .. note:: As more commits are merged upstream, the GitHub PR page will show
858      a ``This branch is out-of-date with the base branch`` message and a
859      ``Update branch`` button on the PR page. That message should be ignored,
860      as the commits will be rebased as part of merging anyway, and triggering
861      a branch update from the GitHub UI will cause the PR approvals to be
862      dropped.
863
864#. While you're waiting for your pull request to be accepted and merged, you
865   can create another branch to work on another issue. (Be sure to make your
866   new branch off of ``main`` and not the previous branch.)::
867
868     git checkout main
869     git checkout -b fix_another_issue
870
871   and use the same process described above to work on this new topic branch.
872
873#. If reviewers do request changes to your patch, you can interactively rebase
874   commit(s) to fix review issues. In your development repo::
875
876     git rebase -i <offending-commit-id>^
877
878   In the interactive rebase editor, replace ``pick`` with ``edit`` to select
879   a specific commit (if there's more than one in your pull request), or
880   remove the line to delete a commit entirely.  Then edit files to fix the
881   issues in the review.
882
883   As before, inspect and test your changes. When ready, continue the
884   patch submission::
885
886     git add [file(s)]
887     git rebase --continue
888
889   Update commit comment if needed, and continue::
890
891     git push --force origin fix_comment_typo
892
893   By force pushing your update, your original pull request will be updated
894   with your changes so you won't need to resubmit the pull request.
895
896#. After pushing the requested change, check on the PR page if there is a
897   merge conflict. If so, rebase your local branch::
898
899      git fetch --all
900      git rebase --ignore-whitespace upstream/main
901
902   The ``--ignore-whitespace`` option stops ``git apply`` (called by rebase)
903   from changing any whitespace. Resolve the conflicts and push again::
904
905      git push --force origin fix_comment_typo
906
907   .. note:: While amending commits and force pushing is a common review model
908      outside GitHub, and the one recommended by Zephyr, it's not the main
909      model supported by GitHub. Forced pushes can cause unexpected behavior,
910      such as not being able to use "View Changes" buttons except for the last
911      one - GitHub complains it can't find older commits. You're also not
912      always able to compare the latest reviewed version with the latest
913      submitted version. When rewriting history GitHub only guarantees access
914      to the latest version.
915
916#. If the CI run fails, you will need to make changes to your code in order
917   to fix the issues and amend your commits by rebasing as described above.
918   Additional information about the CI system can be found in
919   `Continuous Integration`_.
920
921.. _contribution_tips:
922
923Contribution Tips
924=================
925
926The following is a list of tips to improve and accelerate the review process of
927Pull Requests. If you follow them, chances are your pull request will get the
928attention needed and it will be ready for merge sooner than later:
929
930.. _git-rebase:
931   https://git-scm.com/docs/git-rebase#Documentation/git-rebase.txt---keep-base
932
933#. When pushing follow-up changes, use the ``--keep-base`` option of
934   `git-rebase`_
935
936#. On the PR page, check if the change can still be merged with no merge
937   conflicts
938
939#. Make sure title of PR explains what is being fixed or added
940
941#. Make sure your PR has a body with more details about the content of your
942   submission
943
944#. Make sure you reference the issue you are fixing in the body of the PR
945
946#. Watch early CI results immediately after submissions and fix issues as they
947   are discovered
948
949#. Revisit PR after 1-2 hours to see the status of all CI checks, make sure all
950   is green
951
952#. If you get request for changes and submit a change to address them, make
953   sure you click the "Re-request review" button on the GitHub UI to notify
954   those who asked for the changes
955
956
957Submitting Proposals
958====================
959
960You can request a new feature or submit a proposal by submitting an issue to
961our GitHub Repository.
962If you would like to implement a new feature, please submit an issue with a
963proposal (RFC) for your work first, to be sure that we can use it. Please
964consider what kind of change it is:
965
966* For a Major Feature, first open an issue and outline your proposal so that it
967  can be discussed. This will also allow us to better coordinate our efforts,
968  prevent duplication of work, and help you to craft the change so that it is
969  successfully accepted into the project. Providing the following information
970  will increase the chances of your issue being dealt with quickly:
971
972  * Overview of the Proposal
973  * Motivation for or Use Case
974  * Design Details
975  * Alternatives
976  * Test Strategy
977
978* Small Features can be crafted and directly submitted as a Pull Request.
979
980Identifying Contribution Origin
981===============================
982
983When adding a new file to the tree, it is important to detail the source of
984origin on the file, provide attributions, and detail the intended usage. In
985cases where the file is an original to Zephyr, the commit message should
986include the following ("Original" is the assumption if no Origin tag is
987present)::
988
989      Origin: Original
990
991In cases where the file is :ref:`imported from an external project
992<external-contributions>`, the commit message shall contain details regarding
993the original project, the location of the project, the SHA-id of the origin
994commit for the file and the intended purpose.
995
996For example, a copy of a locally maintained import::
997
998      Origin: Contiki OS
999      License: BSD 3-Clause
1000      URL: http://www.contiki-os.org/
1001      commit: 853207acfdc6549b10eb3e44504b1a75ae1ad63a
1002      Purpose: Introduction of networking stack.
1003
1004For example, a copy of an externally maintained import in a module repository::
1005
1006      Origin: Tiny Crypt
1007      License: BSD 3-Clause
1008      URL: https://github.com/01org/tinycrypt
1009      commit: 08ded7f21529c39e5133688ffb93a9d0c94e5c6e
1010      Purpose: Introduction of TinyCrypt
1011
1012Contributions to External Modules
1013**********************************
1014
1015Follow the guidelines in the :ref:`modules` section for contributing
1016:ref:`new modules <submitting_new_modules>` and
1017submitting changes to :ref:`existing modules <changes_to_existing_module>`.
1018
1019.. _treewide-changes:
1020
1021Treewide Changes
1022****************
1023
1024This section describes contributions that are treewide changes and some
1025additional associated requirements that apply to them. These requirements exist
1026to try to give such changes increased review and user visibility due to their
1027large impact.
1028
1029Definition and Decision Making
1030==============================
1031
1032A *treewide change* is defined as any change to Zephyr APIs, coding practices,
1033or other development requirements that either implies required changes
1034throughout the zephyr source code repository or can reasonably be expected to
1035do so for a wide class of external Zephyr-based source code.
1036
1037This definition is informal by necessity. This is because the decision on
1038whether any particular change is treewide can be subjective and may depend on
1039additional context.
1040
1041Project maintainers should use good judgement and prioritize the Zephyr
1042developer experience when deciding when a proposed change is treewide.
1043Protracted disagreements can be resolved by the Zephyr Project's Technical
1044Steering Committee (TSC), but please avoid premature escalation to the TSC.
1045
1046Requirements for Treewide Changes
1047=================================
1048
1049- The zephyr repository must apply the 'treewide' GitHub label to any issues or
1050  pull requests that are treewide changes
1051
1052- The person proposing a treewide change must create an `RFC issue
1053  <https://github.com/zephyrproject-rtos/zephyr/issues/new?assignees=&labels=RFC&template=003_rfc-proposal.md&title=>`_
1054  describing the change, its rationale and impact, etc. before any pull
1055  requests related to the change can be merged
1056
1057- The project's `Architecture Working Group (WG)
1058  <https://github.com/zephyrproject-rtos/zephyr/wiki/Architecture-Working-Group>`_
1059  must include the issue on the agenda and discuss whether the project will
1060  accept or reject the change before any pull requests related to the change
1061  can be merged (with escalation to the TSC if consensus is not reached at the
1062  WG)
1063
1064- The Architecture WG must specify the procedure for merging any PRs associated
1065  with each individual treewide change, including any required approvals for
1066  pull requests affecting specific subsystems or extra review time requirements
1067
1068- The person proposing a treewide change must email
1069  devel@lists.zephyrproject.org about the RFC if it is accepted by the
1070  Architecture WG before any pull requests related to the change can be merged
1071
1072Examples
1073========
1074
1075Some example past treewide changes are:
1076
1077- the deprecation of version 1 of the :ref:`Logging API <logging_api>` in favor
1078  of version 2 (see commit `262cc55609
1079  <https://github.com/zephyrproject-rtos/zephyr/commit/262cc55609b73ea61b5f999c6c6daaba20bc5240>`_)
1080- the removal of support for a legacy :ref:`dt-bindings` syntax
1081  (`6bf761fc0a
1082  <https://github.com/zephyrproject-rtos/zephyr/commit/6bf761fc0a2811b037abec0c963d60b00c452acb>`_)
1083
1084Note that adding a new version of a widely used API while maintaining
1085support for the old one is not a treewide change. Deprecation and removal of
1086such APIs, however, are treewide changes.
1087
1088Specialized driver requirements
1089*******************************
1090
1091Drivers for standalone devices should use the Zephyr bus APIs (SPI, I2C...)
1092whenever possible so that the device can be used with any SoC from any vendor
1093implementing a compatible bus.
1094
1095If it is not technically possible to achieve full performance using the Zephyr
1096APIs due to specialized accelerators in a particular SoC family, one could
1097extend the support for an external device by providing a specialized path for
1098that SoC family. However, the driver must still provide a regular path (via
1099Zephyr APIs) for all other SoCs. Every exception must be approved by the
1100Architecture WG in order to be validated and potentially to be learned/improved
1101from.
1102