Gerrit/Tutorial/uk

Це посібник, який пояснює, як використовувати Git для створення та редагування змін у Gerrit.


 * Якщо ви хочете заощадити час і знаєтесь на техніці, скористайтеся натомість дуже короткими настановами:
 * Для досвідчених користувачів має додаткову документацію.
 * Якщо ви хочете лише гратися з Gerrit і не хочете писати виправлення для «справжнього» проєкту програмного забезпечення Вікімедіа, скористайтеся нашим тестовим екземпляром Gerrit.

У цьому посібнику команди, які треба ввести, починаються з символу долара в прямокутнику, наприклад:. Не вводьте префікс. Якщо команда також містить змінну, яку ви повинні змінити самостійно, тоді змінну буде вказано червоним кольором:.



Що таке Git?
Git — це безкоштовна розподілена система керування версіями з відкритим кодом. «Розподілена» означає, що центральної копії сховища (репозиторію) немає. За допомогою Git після того, як ви клонуєте репозиторій, ви отримаєте повністю функціональну копію початкового коду з усіма гілками і позначеними релізами до ваших послуг.



Створення облікового запису розробника Вікімедіа
Якщо у вас ще немає облікового запису розробника Вікімедіа, перейдіть до wikitech.wikimedia.org і створіть обліковий запис. Ті самі ім'я користувача та пароль використовуватимуться для входу в Gerrit нижче.



Встановлення Git
Ці інструкції пояснюють, як встановити Git як інструмент командного рядка (вікно термінала). Якщо ви надаєте перевагу графічному інтерфейсу користувача (GUI), а не командному рядку, тоді перевірте список клієнтів, який підтримується проєктом Git. Альтернативні інструкції зі встановлення див. офіційну документацію.

Встановлення
Follow Installing Git to learn how to install git on your operating system.



Налаштування Git
Тепер, коли ви встановили Git, настав час налаштувати вашу особисту інформацію. Ви повинні зробити це лише один раз. Ви також можете будь-коли змінити свою особисту інформацію, повторно виконавши ці команди.

Git відстежує, хто робить кожен коміт, перевіряючи ім'я та електронну адресу користувача. Крім того, ця інформація використовується для пов'язування ваших комітів із вашим обліковим записом Gerrit.

Введіть дві команди нижче, щоб установити ім'я користувача та адресу електронної пошти. Замініть на власне ім'я користувача Gerrit і замініть  на свою адресу електронної пошти:



Встановити ключі SSH у Gerrit
Ми використовуємо ключ SSH для встановлення безпечного з'єднання між вашим комп'ютером і Gerrit. Команда безпеки Вікімедіа рекомендує, щоб користувачі, які створюють ключі SSH, із серпня 2021 року використовували тип  для оптимальної безпеки та продуктивності.



Отримати свій ключ SSH
Follow SSH keys.



Додати відкритий ключ SSH до свого облікового запису Gerrit

 * Увійдіть у вебінтерфейс для Gerrit. Ім'я користувача та пароль для вашого Gerrit такі самі, як для вашого облікового запису розробника Вікімедіа.
 * Натисніть своє ім'я користувача у верхньому правому куті, а потім виберіть "Settings" (налаштування).
 * У меню ліворуч натисніть "SSH Keys" (ключі SSH).
 * Вставте відкритий ключ SSH у відповідне поле та натисніть «ADD NEW SSH KEY».



Перевірити SSH-з'єднання Gerrit
Connect to the Gerrit server via  to check if everything works as expected. Replace by your shell username as shown in your Gerrit settings:



An example Gerrit SSH connection success message looks like this:
 * Be mindful and compare that the "ed25519 key fingerprint" is the same as the SSH fingerprint for gerrit.wikimedia.org:29418. If it is the same, answer "Yes" to "Are you sure you want to continue connecting?". Then enter the passphrase for your key.
 * You should get a message "Welcome to Gerrit Code Review". The last line should show "Connection to gerrit.wikimedia.org closed."
 * If you run into problems, use (replace  by your username). The   will provide verbose output to help find problems. Then read Gerrit Troubleshooting.



Пісочниця
If you would like to practice using Gerrit you can download (also called "cloning") the repository this tutorial uses called "sandbox".

Run the following on the Git Bash command line:

(Replace by your Gerrit username.  And make sure the URL begins with   and not  ).

This will copy the entire history and the code base of the "sandbox" extension repository into your machine. You will have a working directory of the extension's main branch (usually also called "git master"). Enter the new directory (via the command ). Now you can look at the code and start editing it.



Існуючі репозиторії
Cloning the Sandbox repository will not give you a development environment setup or a running MediaWiki installation. (Running will require MediaWiki Core and placing the code you checked out in a location expected by your web server.) See Download from Git for how to download MediaWiki Core, extensions, skins, or any other project repository hosted at gerrit.wikimedia.org from Git.

Vagrant
If you have downloaded MediaWiki or extensions using Vagrant, make sure you have configured Git to push code using SSH instead of HTTPS.



Підготовка до роботи з Gerrit
Gerrit requires that your commit message must have a "change ID". They look like  starting with an I (capital i). Each time you amend a commit to improve an existing patch in Gerrit, this change ID stays the same, so Gerrit understands it as a new "patch set" to address the same code change.

There's a git add-on called git-review that adds a Change-ID line to your commits. Using git-review is recommended. It makes it easier to configure your Git clone, to submit a change or to fetch an existing one.



Встановлення git-review
Note that Wikimedia Gerrit requires git-review version 1.27 or later.

For more details, please see Gerrit/git-review#Installation.

Font Awesome 5 brands linux.svg Linux

 * Use the graphical software package management tool of your Linux distribution to install the  package.
 * If git-review has not been packaged by your distribution, check git-review for other options such as installing git-review by using the pip Python package installer.
 * If you use FreeBSD, install git-review through ports.

Font Awesome 5 brands windows.svg Windows

 * Please see git-review Windows.

Apple logo black.svg macOS

 * For OS X 10.11 El Capitan and later, follow Method 1.
 * On versions prior to 10.11, use the pip Python package installer by following Method 2.



Конфігурування git-review
Git's default remote host name is "origin". This name is also used by Wikimedia projects. We need to tell git-review to use that host. Replace with your Gerrit username:

Setting up git-review
After downloading ("cloning") a repository, you need to set it up for git-review. This will automatically happen the first time you try to submit a commit, but it's generally better to do it right after cloning. Make sure that you are in the directory of the project that you cloned (otherwise you will get an error "fatal: Not a git repository"). Then run this command:

Towards the end of the output, you should see something like this:

This may ask you for your git username, if it's different from the shell username you're using.

Submit a patch
Make sure that you cloned the code repository that you are interested in (see Download code using Git above).

Make sure that you are in the directory of the code repository (the command tells you where exactly you are).

Update the main development branch
Make sure that the main development branch (the branch created when you initially cloned the repository) is up to date:

However, note that some repositories use a different name for their main development branch (for example  instead of , or the   repository has a   instead of a   branch).

Create a branch
First, create a local branch for your new change. Replace below by a short but reasonably descriptive name (e.g.   if a corresponding  task exists for your changes, , or  ). Other people will also use this name to identify your branch.

This will create a new branch (called ) from the latest 'master' and check it out for you. In the example above, we called that new branch.

Make your changes
Make changes to your local code. Use your preferred text editor and modify a file. In the example below, we edit the file  and add a word.

Then close your text editor and check the changes you have made since the last commit, within the file(s) and within the directory:

displays your changes in unified diff format: Removed lines have a minus prefix and added lines have a plus  prefix. These changes are not yet "staged" (via ) for the next commit.

Stage your changes for a commit
Run to decide which of your changes should become part of your commit. It will display a list of all file(s) that you have changed within the directory. At this point, the output will display "no changes added to commit" as the last line.

Use  to make your changed file(s) become part of your next commit. In the example above we modified the file, so the command would be:

Any files you've changed that you have not passed to  will be ignored when running   in the next step.

Commit your staged changes
Once you are happy with the list of changes added via, you can turn these changes into a commit in your local repository by using

You will then be asked in your text editor to add a descriptive summary for your commit. You must follow the Commit message guidelines. This is what other people will see when looking at the history of changes in the code repository.

Save the commit message and close your text editor. A summary (the commit ID, your subject line, the files and lines changed) will be displayed.

Prepare to push your commit to Gerrit
Synchronize your changeset with any changes that may have occurred in the master branch while you've been working ("rebasing"). From within your branch, run:

Now you are ready to push your code to Gerrit for review. If you made several related commits, consider merging them into one single commit for review.

Push your commit to Gerrit
If you followed #Prepare to work with Gerrit above and installed  and ran , then the command to push changes to Gerrit is:

The  option tells git-review not to perform a rebase before submitting the change to Gerrit.

Upon success, you'll get a confirmation and a link to the changeset in Gerrit. In the example above, that link is: https://gerrit.wikimedia.org/r/#/c/sandbox/+/563720

Congratulations! Your patch is in Gerrit and hopefully will get reviewed soon!

If git review -R fails
If you are asked to enter your git credentials (a username and password) after running and it responds that they are invalid, it's likely that the repo was cloned using https and not ssh. You should not recieve any prompt to enter credentials if you are using ssh. To switch the repo to ssh, run and replace  with the one found in gitiles that begins with. Make sure to add your Gerrit username before. For example, the repository URL for the Echo repository would be.

If you get a, re-follow the instructions at  to make sure your ssh agent is running and your identity is added. If you close your Git Bash shell, you will be signed out and need to re-follow these instructions each time.

View the Change / Next Steps
Open the link to your Gerrit changeset in a web browser.

Under "Files", after you clicked the down arrow at the very right of any file in the list, you can see a diff of your changes per file: The old lines are shown in red color and your new lines are shown in green color.

If your commit addresses a ticket in Phabricator, a comment will be automatically added in the Phabricator task if you followed the Commit message guidelines. If you did not, you could either fix your commit message (by creating an updated patchset), or manually add a comment on that Phabricator ticket which includes a link to your changeset in Gerrit.

Other common situations
Also see Gerrit Advanced usage if your situation is not covered here.

Squash several commits into one single commit via rebase
If you made several related commits to your local repository prior to wanting to submit for review, you should squash (merge) those commits into one single commit.

The  or   option allows you to change (rewrite) your commit history. For each commit, you can modify and change the commit message, add or remove files, or perform other modifications.

First you need to tell git how far back you want to pull. To get a list of all changes in your branch:

You can also limit the displayed list of recent changes. means pull the last three commits:

After you type this command, your text editor will display your commits in reverse order and a list of available commands:

Since we only want to send one commit to review, we will squash the last two commits into the first. Hence change all but the first "pick" to "squash":

pick aa8cf1d Adding method customFilterFunctionGetRiskyCountryCodeScore to GatewayAdapter. squash 38828e2 Adding $wgDonationInterfaceCustomFiltersFunctionsRiskyCountries to donationinterface.php squash be33007 Fix a typo

When you finished picking and squashing and saved the file, another file will open in your text editor to allow you get to edit and merge your commit messages. Be careful to only keep one of the Change-Id lines and have it be at bottom of the message after one empty line.

Your messages from your previous commits will automatically be placed in this message:

Remember to put your (updated) summary message in the commit. In this case the new summary message will be:

(mingle-fr-2012-69) Adding a custom filter for risky countries.

If all goes well, you should see a successful rebase message:

Afterwards, submit your patch for review:

You should see a message like this showing your git review went to Gerrit (in this example, to https://gerrit.wikimedia.org/r/7187):

Amending a change (your own or someone else's)
Sometimes, you might need to amend a submitted change. You can amend a change as long as the change hasn't been merged yet.

You can amend your own changes. To amend changes submitted by someone else, you need to be a member of Gerrit's Trusted-Contributors group. To become a member of Trusted-Contributors, find someone who is a member and ask them to add you. The group is viral in that members can add new members, use your powers responsibly.

Rebasing
Rebase to bring your local branch up to date with the remote. It's best to make rebase updates a separate patch, so that your code reviewers have an easy time seeing what changes you've made. Assuming you are using Gerrit, you can do this by clicking the "Rebase Change" button when viewing your patch in Gerrit's web interface.

Hard reset and checkout the change with this command: (BEWARE:  performs a hard reset that destroys all local changes. Stash or commit changes first which you wish to preserve!)

For example:

You can look in Gerrit to figure out the. It is the six digit number in the URL of your code review page.

Or, if you already have the change in a branch on your local repository, you can just check it out:

For example:

Make changes and push
Next, make some changes with your favorite text editor.

the files as needed, then commit the change (ensuring you are amending the commit):

Push the change:

The  is important here. It tells git-review to not rebase your change against master, which clutters diffs between patch set 1 and 2.

Push to a branch different than master
Above, the commit was pushed to the master branch. The branch name only appeared as the topic of the commit in the Gerrit UI. If you really want to push to a different branch than master, you have to push via.

Виправлення проблем
For problems and how to solve them, see.



Див. також
Also useful are these pages:


 * Gerrit Tutorial tl;dr
 * Gerrit TortoiseGit tutorial
 * Wikimedia Gerrit Patch Uploader