From dbeb46223e42296031e123b5a01cd4b4985f3d7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tilo=20K=C3=B6rner?= <70266685+tiloKo@users.noreply.github.com> Date: Fri, 13 Sep 2024 14:00:11 +0200 Subject: [PATCH] CONTRIBUTING.md (#5042) Updated CONTRIBUTING.md with Code of Conduct and Guidelines for GenAI and general content restructuring --- .github/CONTRIBUTING.md | 217 ------------------ CONTRIBUTING.md | 38 +++ README.md | 2 +- documentation/CODE_OF_CONDUCT.md | 86 +++++++ documentation/CONTRIBUTING_USING_GENAI.md | 12 + .../DEVELOPMENT.md | 179 +++++++++++++++ documentation/docs/index.md | 2 +- 7 files changed, 317 insertions(+), 219 deletions(-) delete mode 100644 .github/CONTRIBUTING.md create mode 100644 CONTRIBUTING.md create mode 100644 documentation/CODE_OF_CONDUCT.md create mode 100644 documentation/CONTRIBUTING_USING_GENAI.md rename DEVELOPMENT.md => documentation/DEVELOPMENT.md (75%) diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md deleted file mode 100644 index d7ecdb0bc7..0000000000 --- a/.github/CONTRIBUTING.md +++ /dev/null @@ -1,217 +0,0 @@ -# Guidance on How to Contribute - -**Table of Contents:** - -1. [Using the issue tracker](#using-the-issue-tracker) -1. [Changing the code-base](#changing-the-code-base) -1. [Jenkins credential handling](#jenkins-credential-handling) -1. [Code Style](#code-style) -1. [References](#references) - -There are two primary ways to help: - -* Using the issue tracker, and -* Changing the code-base. - -## Using the issue tracker - -Use the issue tracker to suggest feature requests, report bugs, and ask questions. This is also a great way to connect with the developers of the project as well as others who are interested in this solution. - -Use the issue tracker to find ways to contribute. Find a bug or a feature, mention in the issue that you will take on that effort, then follow the "Changing the code-base" guidance below. - -## Changing the code-base - -Generally speaking, you should fork this repository, make changes in your own fork, and then submit a pull-request. All new code should have been thoroughly tested end-to-end in order to validate implemented features and the presence or lack of defects. - -### Working with forks - -* [Configure this repository as a remote for your own fork](https://help.github.com/articles/configuring-a-remote-for-a-fork/), and -* [Sync your fork with this repository](https://help.github.com/articles/syncing-a-fork/) before beginning to work on a new pull-request. - -### Tests - -All pipeline library coding _must_ come with automated unit tests. - -Besides that, we have an integration test suite, which is not triggered during normal pull request builds. However, integration tests are mandatory before a change can be merged. It is the duty of a team member of the SAP/jenkins-library project to execute these tests. -To trigger the integration test suite, the `HEAD` commit of the branch associated with the pull request must be pushed under the branch pattern `it/.*` (recommended naming convention: `it/`). As a result, the status `integration-tests` is updated in the pull request. - -### Documentation - -The contract of functionality exposed by a library functionality needs to be documented, so it can be properly used. -Implementation of a functionality and its documentation shall happen within the same commit(s). - -### Coding pattern - -Pipeline steps must not make use of return values. The pattern for sharing parameters between pipeline steps or between a pipeline step and a pipeline script is sharing values via the [`commonPipelineEnvironment`](../vars/commonPipelineEnvironment.groovy). Since there is no return value from a pipeline step the return value of a pipeline step is already `void` rather than `def`. - -#### EditorConfig - -To ensure a common file format, there is a `.editorConfig` file [in place](../.editorconfig). To respect this file, [check](http://editorconfig.org/#download) if your editor does support it natively or you need to download a plugin. - -### Commit Message Style - -Write [meaningful commit messages](http://who-t.blogspot.de/2009/12/on-commit-messages.html) and [adhere to standard formatting](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html). - -Good commit messages speed up the review process and help to keep this project maintainable in the long term. - -## Developer Certificate of Origin (DCO) - -Due to legal reasons, contributors will be asked to accept a DCO when they create their first pull request to this project. This happens in an automated fashion during the submission process. SAP uses [the standard DCO text of the Linux Foundation](https://developercertificate.org/). - -## Jenkins credential handling - -References to Jenkins credentials should have meaningful names. - -We are using the following approach for naming Jenkins credentials: - -For username/password credentials: -`CredentialsId` like e.g. `neoCredentialsId` - -For other cases we add further information to the name like: - -* `gitSshCredentialsId` for ssh credentials -* `githubTokenCredentialsId`for token/string credentials -* `gcpFileCredentialsId` for file credentials - -## Code Style - -Generally, the code should follow any stylistic and architectural guidelines prescribed by the project. In the absence of guidelines, mimic the styles and patterns in the existing code-base. - -The intention of this section is to describe the code style for this project. As reference document, the [Groovy's style guide](http://groovy-lang.org/style-guide.html) was taken. For further reading about Groovy's syntax and examples, please refer to this guide. - -This project is intended to run in Jenkins [[2]](https://jenkins.io/doc/book/getting-started/) as part of a Jenkins Pipeline [[3]](https://jenkins.io/doc/book/pipeline/). It is composed by Jenkins Pipeline's syntax, Groovy's syntax and Java's syntax. - -Some Groovy's syntax is not yet supported by Jenkins. It is also the intention of this section to remark which Groovy's syntax is not yet supported by Jenkins. - -As Groovy supports 99% of Java’s syntax [[1]](http://groovy-lang.org/style-guide.html), many Java developers tend to write Groovy code using Java's syntax. Such a developer should also consider the following code style for this project. - -### General remarks - -Variables, methods, types and so on shall have meaningful self describing names. Doing so makes understanding code easier and requires less commenting. It helps people who did not write the code to understand it better. - -Code shall contain comments to explain the intention of the code when it is unclear what the intention of the author was. In such cases, comments should describe the "why" and not the "what" (that is in the code already). - -### Omit semicolons - -### Use the return keyword - -In Groovy it is optional to use the _return_ keyword. Use explicitly the _return_ keyword for better readability. - -### Use def - -When using _def_ in Groovy, the type is Object. Using _def_ simplifies the code, for example imports are not needed, and therefore the development is faster. - -### Do not use a visibility modifier for public classes and methods - -By default, classes and methods are public, the use of the public modifier is not needed. - -### Do not omit parentheses for Groovy methods - -In Groovy is possible to omit parentheses for top-level expressions, but [Jenkins Pipeline's syntax](https://jenkins.io/doc/book/pipeline/syntax/) use a block, specifically `pipeline { }` as top-level expression [[4]](https://jenkins.io/doc/book/pipeline/syntax/). Do not omit parenthesis for Groovy methods because Jenkins will interpret the method as a Pipeline Step. Conversely, do omit parenthesis for Jenkins Pipeline's Steps. - -### Omit the .class suffix - -In Groovy, the .class suffix is not needed. Omit the .class suffix for simplicity and better readability. - -e.g. `new ExpectedException().expect(AbortException.class)` - ---> `new ExpectedException().expect(AbortException)` - -### Omit getters and setters - -When declaring a field without modifier inside a Groovy bean, the Groovy compiler generates a private field and a getter and setter. - -### Do not initialize beans with named parameters - -Do not initialize beans with named parameters, because it is not supported by Jenkins: - -e.g. `Version javaVersion = new Version( major: 1, minor: 8)` - -Initialize beans using Java syntax: - -e.g. `Version javaVersion = new Version(1, 8)` - -Use named parameters for Jenkins Pipeline Steps: - -e.g. `sh returnStdout: true, script: command` - -### Do not use _with()_ operator - -The _with_ operator is not yet supported by Jenkins, and it must not be used or encapsulated in a @NonCPS method. - -### Use _==_ operator - -Use Groovy’s `==` instead of Java `equals()` to avoid NullPointerExceptions. To compare the references of objects, instead of `==`, you should use `a.is(b)` [[1]](http://groovy-lang.org/style-guide.html). - -### Use GStrings - -In Groovy, single quotes create Java Strings, and double quotes can create Java Strings or GStrings, depending if there is or not interpolation of variables [[1]](http://groovy-lang.org/style-guide.html). Using GStrings variable and string concatenation is more simple. - -#### Do not use curly braces {} for variables or variable.property - -For variables, or variable.property, drop the curly braces: - -e.g. `echo "[INFO] ${name} version ${version.version} is installed."` - ---> `echo "[INFO] $name version $version.version is installed."` - -#### Use 'single quotes' for Strings and constants - -#### Use "double quotes" for GStrings - -#### Use '''triple single quotes''' for multiline Strings - -#### Use """triple double quotes""" for multiline GStrings - -#### Use /slash/ for regular expressions - -This notation avoids to double escape backslashes, making easier working with regex. - -### Use native syntax for data structures - -Use the native syntax for data structures provided by Groovy like lists, maps, regex, or ranges of values. - -### Use aditional Groovy methods - -Use the additional methods provided by Groovy to manipulate String, Files, Streams, Collections, and other classes. -For a complete description of all available methods, please read the GDK API [[5]](http://groovy-lang.org/groovy-dev-kit.html). - -### Use Groovy's switch - -Groovy’s switch accepts any kind of type, thereby is more powerful. In this case, the use of _def_ instead of a type is necessary. - -### Use alias for import - -In Groovy, it is possible to assign an alias to imported packages. Use alias for imported packages to avoid the use of fully-qualified names and increase readability. - -### Use Groovy syntax to check objects - -In Groovy a null, void, equal to zero, or empty object evaluates to false, and if not, evaluates to true. Instead of writing null and size checks e.g. `if (name != null && name.length > 0) {}`, use just the object `if (name) {}`. - -### Use _?._ operator - -Use the safe dereference operator _?._, to simplify the code for accessing objects and object members safely. Using this operator, the Groovy compiler checks null objects and null object members, and returns _null_ if the object or the object member is null and never throws a NullPointerException. - -### Use _?:_ operator - -Use Elvis operator _?:_ to simplify default value validations. - -### Use _any_ keyword - -If the type of the exception thrown inside a try block is not important, catch any exception using the _any_ keyword. - -### Use _assert_ - -To check parameters, return values, and more, use the assert statement. - -## References - -[1] Groovy's syntax: [http://groovy-lang.org/style-guide.html](http://groovy-lang.org/style-guide.html) - -[2] Jenkins: [https://jenkins.io/doc/book/getting-started/](https://jenkins.io/doc/book/getting-started/) - -[3] Jenkins Pipeline: [https://jenkins.io/doc/book/pipeline/](https://jenkins.io/doc/book/pipeline/) - -[4] Jenkins Pipeline's syntax: [https://jenkins.io/doc/book/pipeline/syntax/](https://jenkins.io/doc/book/pipeline/syntax/) - -[5] GDK: Groovy Development Kit: [http://groovy-lang.org/groovy-dev-kit.html](http://groovy-lang.org/groovy-dev-kit.html) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000000..af4a1830ed --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,38 @@ +# Contributing to an SAP Open Source Project + +## General Remarks + +You are welcome to contribute content (code, documentation etc.) to this open source project. + +There are some important things to know: + +1. You must **comply to the license of this project**, **accept the Developer Certificate of Origin** (see below) before being able to contribute. The acknowledgement to the DCO will usually be requested from you as part of your first pull request to this project. +2. Please **adhere to our [Code of Conduct](documentation/CODE_OF_CONDUCT.md)**. +3. If you plan to use **generative AI for your contribution**, please see our guideline below. +4. **Not all proposed contributions can be accepted**. Some features may fit another project better or doesn't fit the general direction of this project. Of course, this doesn't apply to most bug fixes, but a major feature implementation for instance needs to be discussed with one of the maintainers first. Possibly, one who touched the related code or module recently. The more effort you invest, the better you should clarify in advance whether the contribution will match the project's direction. The best way would be to just open an issue to discuss the feature you plan to implement (make it clear that you intend to contribute). We will then forward the proposal to the respective code owner. This avoids disappointment. + +## Developer Certificate of Origin (DCO) + +Contributors will be asked to accept a DCO before they submit the first pull request to this projects, this happens in an automated fashion during the submission process. SAP uses [the standard DCO text of the Linux Foundation](https://developercertificate.org/). + +## Contributing with AI-generated code + +As artificial intelligence evolves, AI-generated code is becoming valuable for many software projects, including open-source initiatives. While we recognize the potential benefits of incorporating AI-generated content into our open-source projects there a certain requirements that need to be reflected and adhered to when making contributions. + +Please see our [guideline for AI-generated code contributions to SAP Open Source Software Projects](documentation/CONTRIBUTING_USING_GENAI.md) for these requirements. + +## How to Contribute + +1. Make sure the change is welcome (see [General Remarks](#general-remarks)). +2. Create a branch by forking the repository and apply your change. +3. Commit and push your change on that branch. +4. Create a pull request in the repository using this branch. +5. Follow the link posted by the CLA assistant to your pull request and accept it, as described above. +6. Wait for our code review and approval, possibly enhancing your change on request. + - Note that the maintainers have many duties. So, depending on the required effort for reviewing, testing, and clarification, this may take a while. +7. Once the change has been approved and merged, we will inform you in a comment. +8. Celebrate! + +## Development Guidelines + +See our [Development Guidelines](documentation/DEVELOPMENT.md) diff --git a/README.md b/README.md index 20963e5142..6e0e340b81 100644 --- a/README.md +++ b/README.md @@ -29,5 +29,5 @@ before opening a pull request. [piper-library-user-doc]: https://sap.github.io/jenkins-library/ [piper-library-issues]: https://github.com/SAP/jenkins-library/issues -[piper-library-contribution]: .github/CONTRIBUTING.md +[piper-library-contribution]: CONTRIBUTING.md [google-group]: https://groups.google.com/forum/#!forum/project-piper diff --git a/documentation/CODE_OF_CONDUCT.md b/documentation/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000..84ded8eca4 --- /dev/null +++ b/documentation/CODE_OF_CONDUCT.md @@ -0,0 +1,86 @@ +# SAP Open Source Code of Conduct + +SAP adopts the [Contributor's Covenant 2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/) +across our open source projects to ensure a welcoming and open culture for everyone involved. + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [ospo@sap.com](mailto:ospo@sap.com) (SAP Open Source Program Office). All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of actions. + +**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations diff --git a/documentation/CONTRIBUTING_USING_GENAI.md b/documentation/CONTRIBUTING_USING_GENAI.md new file mode 100644 index 0000000000..1ed02c31e2 --- /dev/null +++ b/documentation/CONTRIBUTING_USING_GENAI.md @@ -0,0 +1,12 @@ +# Guideline for AI-generated code contributions to SAP Open Source Software Projects + +As artificial intelligence evolves, AI-generated code is becoming valuable for many software projects, including open-source initiatives. While we recognize the potential benefits of incorporating AI-generated content into our open-source projects there are certain requirements that need to be reflected and adhered to when making contributions. + +When using AI-generated code contributions in OSS Projects, their usage needs to align with Open-Source Software values and legal requirements. We have established these essential guidelines to help contributors navigate the complexities of using AI tools while maintaining compliance with open-source licenses and the broader [Open-Source Definition](https://opensource.org/osd). + +AI-generated code or content can be contributed to SAP Open Source Software projects if the following conditions are met: + +1. **Compliance with AI Tool Terms and Conditions**: Contributors must ensure that the AI tool's terms and conditions do not impose any restrictions on the tool's output that conflict with the project's open-source license or intellectual property policies. This includes ensuring that the AI-generated content adheres to the [Open-Source Definition](https://opensource.org/osd). +2. **Filtering Similar Suggestions**: Contributors must use features provided by AI tools to suppress responses that are similar to third-party materials or flag similarities. We only accept contributions from AI tools with such filtering options. If the AI tool flags any similarities, contributors must review and ensure compliance with the licensing terms of such materials before including them in the project. +3. **Management of Third-Party Materials**: If the AI tool's output includes pre-existing copyrighted materials, including open-source code authored or owned by third parties, contributors must verify that they have the necessary permissions from the original owners. This typically involves ensuring that there is an open-source license or public domain declaration that is compatible with the project's licensing policies. Contributors must also provide appropriate notice and attribution for these third-party materials, along with relevant information about the applicable license terms. +4. **Employer Policies Compliance**: If AI-generated content is contributed in the context of employment, contributors must also adhere to their employer’s policies. This ensures that all contributions are made with proper authorization and respect for relevant corporate guidelines. diff --git a/DEVELOPMENT.md b/documentation/DEVELOPMENT.md similarity index 75% rename from DEVELOPMENT.md rename to documentation/DEVELOPMENT.md index 8ef0ed8a79..8ff87b8874 100644 --- a/DEVELOPMENT.md +++ b/documentation/DEVELOPMENT.md @@ -11,6 +11,7 @@ 1. [Release](#release) 1. [Pipeline Configuration](#pipeline-configuration) 1. [Security Setup](#security-setup) +1. [Best practices for writing groovy](#best-practices-for-writing-groovy) ## Getting started @@ -19,6 +20,8 @@ 1. Create [a GitHub account](https://github.com/join) 1. Setup [GitHub access via SSH](https://help.github.com/articles/connecting-to-github-with-ssh/) 1. [Create and checkout a repo fork](#checkout-your-fork) +1. [Editorconfig](#editorconfig) +1. [Commit message style](#commit-message-style) 1. Optional: [Get Jenkins related environment](#jenkins-environment) 1. Optional: [Get familiar with Jenkins Pipelines as Code](#jenkins-pipelines) @@ -59,6 +62,16 @@ git remote add upstream git@github.com:sap/jenkins-library.git git remote set-url --push upstream no_push ``` +### EditorConfig + +To ensure a common file format, there is a `.editorConfig` file [in place](../.editorconfig). To respect this file, [check](http://editorconfig.org/#download) if your editor does support it natively or you need to download a plugin. + +### Commit Message Style + +Write [meaningful commit messages](http://who-t.blogspot.de/2009/12/on-commit-messages.html) and [adhere to standard formatting](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html). + +Good commit messages speed up the review process and help to keep this project maintainable in the long term. + ### Jenkins environment If you want to contribute also to the Jenkins-specific parts like @@ -694,3 +707,169 @@ All parts that are not relevant for signing were removed. ``` Add the three to four lines to you git config and this will do the necessary such that all your commits will be signed. + +## Best practices for writing groovy + +New steps should be written in go. + +### Coding pattern + +Pipeline steps must not make use of return values. The pattern for sharing parameters between pipeline steps or between a pipeline step and a pipeline script is sharing values via the [`commonPipelineEnvironment`](../vars/commonPipelineEnvironment.groovy). Since there is no return value from a pipeline step the return value of a pipeline step is already `void` rather than `def`. + +### Jenkins credential handling + +References to Jenkins credentials should have meaningful names. + +We are using the following approach for naming Jenkins credentials: + +For username/password credentials: +`CredentialsId` like e.g. `neoCredentialsId` + +For other cases we add further information to the name like: + +* `gitSshCredentialsId` for ssh credentials +* `githubTokenCredentialsId`for token/string credentials +* `gcpFileCredentialsId` for file credentials + +### Code Style + +Generally, the code should follow any stylistic and architectural guidelines prescribed by the project. In the absence of guidelines, mimic the styles and patterns in the existing code-base. + +The intention of this section is to describe the code style for this project. As reference document, the [Groovy's style guide](http://groovy-lang.org/style-guide.html) was taken. For further reading about Groovy's syntax and examples, please refer to this guide. + +This project is intended to run in Jenkins [[2]](https://jenkins.io/doc/book/getting-started/) as part of a Jenkins Pipeline [[3]](https://jenkins.io/doc/book/pipeline/). It is composed by Jenkins Pipeline's syntax, Groovy's syntax and Java's syntax. + +Some Groovy's syntax is not yet supported by Jenkins. It is also the intention of this section to remark which Groovy's syntax is not yet supported by Jenkins. + +As Groovy supports 99% of Java’s syntax [[1]](http://groovy-lang.org/style-guide.html), many Java developers tend to write Groovy code using Java's syntax. Such a developer should also consider the following code style for this project. + +#### General remarks + +Variables, methods, types and so on shall have meaningful self describing names. Doing so makes understanding code easier and requires less commenting. It helps people who did not write the code to understand it better. + +Code shall contain comments to explain the intention of the code when it is unclear what the intention of the author was. In such cases, comments should describe the "why" and not the "what" (that is in the code already). + +#### Omit semicolons + +#### Use the return keyword + +In Groovy it is optional to use the *return* keyword. Use explicitly the *return* keyword for better readability. + +#### Use def + +When using *def* in Groovy, the type is Object. Using *def* simplifies the code, for example imports are not needed, and therefore the development is faster. + +#### Do not use a visibility modifier for public classes and methods + +By default, classes and methods are public, the use of the public modifier is not needed. + +#### Do not omit parentheses for Groovy methods + +In Groovy is possible to omit parentheses for top-level expressions, but [Jenkins Pipeline's syntax](https://jenkins.io/doc/book/pipeline/syntax/) use a block, specifically `pipeline { }` as top-level expression [[4]](https://jenkins.io/doc/book/pipeline/syntax/). Do not omit parenthesis for Groovy methods because Jenkins will interpret the method as a Pipeline Step. Conversely, do omit parenthesis for Jenkins Pipeline's Steps. + +#### Omit the .class suffix + +In Groovy, the .class suffix is not needed. Omit the .class suffix for simplicity and better readability. + +e.g. `new ExpectedException().expect(AbortException.class)` + +--> `new ExpectedException().expect(AbortException)` + +#### Omit getters and setters + +When declaring a field without modifier inside a Groovy bean, the Groovy compiler generates a private field and a getter and setter. + +#### Do not initialize beans with named parameters + +Do not initialize beans with named parameters, because it is not supported by Jenkins: + +e.g. `Version javaVersion = new Version( major: 1, minor: 8)` + +Initialize beans using Java syntax: + +e.g. `Version javaVersion = new Version(1, 8)` + +Use named parameters for Jenkins Pipeline Steps: + +e.g. `sh returnStdout: true, script: command` + +#### Do not use *with()* operator + +The *with* operator is not yet supported by Jenkins, and it must not be used or encapsulated in a @NonCPS method. + +#### Use *==* operator + +Use Groovy’s `==` instead of Java `equals()` to avoid NullPointerExceptions. To compare the references of objects, instead of `==`, you should use `a.is(b)` [[1]](http://groovy-lang.org/style-guide.html). + +#### Use GStrings + +In Groovy, single quotes create Java Strings, and double quotes can create Java Strings or GStrings, depending if there is or not interpolation of variables [[1]](http://groovy-lang.org/style-guide.html). Using GStrings variable and string concatenation is more simple. + +#### Do not use curly braces {} for variables or variable.property + +For variables, or variable.property, drop the curly braces: + +e.g. `echo "[INFO] ${name} version ${version.version} is installed."` + +--> `echo "[INFO] $name version $version.version is installed."` + +#### Use 'single quotes' for Strings and constants + +#### Use "double quotes" for GStrings + +#### Use '''triple single quotes''' for multiline Strings + +#### Use """triple double quotes""" for multiline GStrings + +#### Use /slash/ for regular expressions + +This notation avoids to double escape backslashes, making easier working with regex. + +#### Use native syntax for data structures + +Use the native syntax for data structures provided by Groovy like lists, maps, regex, or ranges of values. + +#### Use aditional Groovy methods + +Use the additional methods provided by Groovy to manipulate String, Files, Streams, Collections, and other classes. +For a complete description of all available methods, please read the GDK API [[5]](http://groovy-lang.org/groovy-dev-kit.html). + +#### Use Groovy's switch + +Groovy’s switch accepts any kind of type, thereby is more powerful. In this case, the use of *def* instead of a type is necessary. + +#### Use alias for import + +In Groovy, it is possible to assign an alias to imported packages. Use alias for imported packages to avoid the use of fully-qualified names and increase readability. + +#### Use Groovy syntax to check objects + +In Groovy a null, void, equal to zero, or empty object evaluates to false, and if not, evaluates to true. Instead of writing null and size checks e.g. `if (name != null && name.length > 0) {}`, use just the object `if (name) {}`. + +#### Use *?.* operator + +Use the safe dereference operator *?.*, to simplify the code for accessing objects and object members safely. Using this operator, the Groovy compiler checks null objects and null object members, and returns *null* if the object or the object member is null and never throws a NullPointerException. + +#### Use *?:* operator + +Use Elvis operator *?:* to simplify default value validations. + +#### Use *any* keyword + +If the type of the exception thrown inside a try block is not important, catch any exception using the *any* keyword. + +#### Use *assert* + +To check parameters, return values, and more, use the assert statement. + +### References + +[1] Groovy's syntax: [http://groovy-lang.org/style-guide.html](http://groovy-lang.org/style-guide.html) + +[2] Jenkins: [https://jenkins.io/doc/book/getting-started/](https://jenkins.io/doc/book/getting-started/) + +[3] Jenkins Pipeline: [https://jenkins.io/doc/book/pipeline/](https://jenkins.io/doc/book/pipeline/) + +[4] Jenkins Pipeline's syntax: [https://jenkins.io/doc/book/pipeline/syntax/](https://jenkins.io/doc/book/pipeline/syntax/) + +[5] GDK: Groovy Development Kit: [http://groovy-lang.org/groovy-dev-kit.html](http://groovy-lang.org/groovy-dev-kit.html) diff --git a/documentation/docs/index.md b/documentation/docs/index.md index 081ce6d45a..e63e739e92 100644 --- a/documentation/docs/index.md +++ b/documentation/docs/index.md @@ -26,7 +26,7 @@ If you don't need to care about the underlying infrastructure of your pipelines, ![SAP CI/CD vs Project "Piper"](images/CICD_Piper.png "Solution Comparison") -The support infrastructure for SAP Continuous Integration and Delivery is provided by SAP according to the Service Level Agreements (SLAs). Project "Piper" offers community support using GitHub issues and pull requests. Users are free to contribute to the repository independently. See [Contributing](https://github.com/SAP/jenkins-library/blob/master/.github/CONTRIBUTING.md). +The support infrastructure for SAP Continuous Integration and Delivery is provided by SAP according to the Service Level Agreements (SLAs). Project "Piper" offers community support using GitHub issues and pull requests. Users are free to contribute to the repository independently. See [Contributing](https://github.com/SAP/jenkins-library/blob/master/CONTRIBUTING.md). For more information about the CI/CD solutions offered by SAP, see [SAP Solutions for Continuous Integration and Delivery](https://help.sap.com/docs/CICD_OVERVIEW/8cacec64ed854b2a88e9a0973e0f97a2/e9fa320181124fa9808d4446a1bf69dd.html).