Difference between revisions of "FPC git/ru"
Line 145: | Line 145: | ||
git add newfile.pas | git add newfile.pas | ||
</pre> | </pre> | ||
− | Затем вы должны (как и в Subversion) зафиксировать | + | Затем вы должны (как и в Subversion) сделать commit(зафиксировать) этот только что добавленный файл. |
=== rm (Удаление файлов) === | === rm (Удаление файлов) === |
Revision as of 16:27, 8 August 2021
│
English (en) │
русский (ru) │
Настройка Git
Расположение репозитория Git
Репозитории Git размещены на Gitlab:
Компилятор FPC, RTL, пакеты и утилиты находятся здесь:
URL-адрес для клонирования репозитория:
git clone https://gitlab.com/freepascal.org/fpc/source.git
Репозиторий документации Git находится здесь:
URL-адрес для клонирования репозитория документации:
git clone https://gitlab.com/freepascal.org/fpc/documentation.git
Репозиторий Git на сайте находится здесь:
URL-адрес для клонирования репозитория веб-сайта:
git clone https://gitlab.com/freepascal.org/fpc/website.git
Ваша идентификация в git
Чтобы ваши коммиты были распознаны, настройте локальный (а еще лучше глобальный) git Установка, чтобы использовать адрес, связанный с вашей учетной записью gitlab.
git config --global user.email your.email.user@youremail.host
Это установит ваш адрес электронной почты для всех репозиториев git, которые вы используете, и позволит интерфейсу gitlab правильно связывать коммиты с пользователями в своем HTML-интерфейсе.
Если у вас несколько учетных записей gitlab (или даже github), вы можете предпочесть установить этот адрес электронной почты только локально:
git config --local user.email your.email.user@youremail.host
эта команда должна выполняться в определенном репозитории и устанавливает адрес электронной почты только для этого репозитория.
HTTP-доступ и учетные данные
Если вы получаете доступ к репозиторию с помощью HTTPS, по умолчанию git запрашивает имя пользователя и пароль. Вы можете указать git хранить их постоянно, введите следующую команду:
git config --global credential.helper store
Есть и другие возможности для хранения этой информации. Более подробную информацию можно найти на
Использование токенов доступа
Вы можете использовать токен доступа и доступ по протоколу HTTPS, это имеет некоторые преимущества. Это поддерживается большинством современных клиентов git:
и здесь вы можете увидеть, как это сделать на gitlab:
Преимущество использования токена доступа заключается в том, что ему могут быть предоставлены ограниченные права на gitlab, например, только доступ к репозиторию. Это также означает, что вы можете легко включить 2FA (двухфакторная аутентификация) для своей учетной записи gitlab.
Модель ветвления
На первом этапе будет использоваться модель ветвления, используемая в Subversion: исправления вносятся в основной ветке, а затем объединяются в ветку исправлений.
На более позднем этапе модель ветвления может быть изменена на одну из многих схем ветвления git.
Git-клиенты Windows
В macOS, Linux и BSD команда git устанавливается вместе с системным диспетчером пакетов (в macOS необходимо установить инструменты командной строки XCode). В Windows необходимо установить отдельный клиент git. Их много, но наиболее популярными являются следующие:
- Git для Windows: клиент командной строки с оболочкой bash, поэтому вы можете копировать и вставлять команды, которые вы найдете в Интернете:
- TortoiseGit интегрируется с проводником Windows, как и TortoiseSVN:
- https://tortoisegit.org/
- если у вас уже установлен TortoisSVN, оба могут работать бок о бок.
- Sourcetree - бесплатный клиент для Windows и macOS:
- https://www.sourcetreeapp.com/
- сделано людьми из bitbucket.
- Smartgit работает в Windows, Linux и macOS:
- Редакторы VSCode и Atom имеют встроенную поддержку git.
Понятия и различия между SVN и GIT
Несколько "полезных" отличий: FPC_git_concepts
Общие операции SVN в Git
Check out
Получение новой копии репозитория в git называется «клонированием».
git clone https://gitlab.com/freepascal.org/testconversion
Как и в случае с Subversion, вы можете дать ему другое имя:
git clone https://gitlab.com/freepascal.org/testconversion myconversion
Эта операция может занять некоторое время, исходная база FPC большая.
Update
Обновление исходного кода с учетом изменений в удаленном репозитории в git называется 'pulling'(вытягивание, извлечение):
git pull
Обратите внимание, что в отличие от subversion, git всегда обновляет весь репозиторий.
Чтобы история коммитов была как можно более линейной и избегала коммитов слиянием (merge commits), рекомендуется выполнять rebase (перебазирование) при извлечении.
git pull --rebase
Вы можете использовать перебазирование для каждого извлечения по умолчанию, выполнив:
git config pull.rebase true
Resolve
Если у вас есть конфликты в svn после обновления или слияния, вы исправляете конфликты, а затем сообщаете svn, что все в порядке, с помощью команды resolved(урегулировано, разрешено).
В git конфликты обычно возникают при merging (слиянии) или при применении shelved/stashed (отложенных/спрятанных) изменений.
Когда возникают конфликты, то
- Изменения в файлах, которые не конфликтуют, будут staged (поэтапными).
- Изменения в файлах, которые конфликтуют, будут применены без промежуточной обработки к рабочей копии (так что простой diff будет показывать только конфликтующие изменения)
Чтобы разрешить конфликты,
- Если вы хотите зафиксировать урегулированную версию файла, отметьте ее как resolved (разрешенную), также сделав ее staging/adding.
- Если вы хотите просто избавиться от статуса "оба изменены" (= конфликтуют) без добавления файла, используйте git reset file
После того, как все файлы были поставлены или помечены как не конфликтующие, вы можете сделать commit (зафиксировать) (будут зафиксированы только промежуточные файлы).
add (добавление новых файлов)
Subversion использует команду add для добавления файла в систему управления версиями. В git это не исключение: Если вы хотите добавить файл, вы должны сначала добавить его, например:
git add newfile.pas
Затем вы должны (как и в Subversion) сделать commit(зафиксировать) этот только что добавленный файл.
rm (Удаление файлов)
Subversion использует команду rm для удаления файла из системы управления версиями. В git это не исключение:
git rm nolongerneededfile.pas
Затем вы должны (как и в Subversion) сделать commit (зафиксировать) этот удаленный файл.
mv (переименование файлов)
Subversion использует команду rm для переименования файла в системе управления версиями. В git это не исключение:
git mv oldfile.pas newfile.pas
После этого вы должны (как и в Subversion) сделать commit (зафиксировать) это изменение.
Как и в Subversion, вы можете переместить один или несколько файлов в другой каталог:
git mv file1.pas file2.pas somesubdir
commit
If you have made some changes locally and wish to commit them, this is a 2-step process:
git add myfile.pas
This schedules the file to be committed (called staging in git, so the changes are now staged). You can add as many files as you want like this.
When you are ready to commit what you have staged, you can commit:
git commit -m '* Some nice comment telling what you did'
In fact, if you're in a hurry and know you want to commit a file, you can combine the 2 commands;
git commit -m '* Some nice comment telling what you did' myfile.pas
If you are really in a hurry, you can commit all changed files in one fell swoop:
git commit -m '* Some nice comment telling what you did' -a
But it is not really recommended to use this, as it will commit all changes in your local copy, not just the ones in the current working directory.
At this point, your changes have been saved locally, but have not yet been sent to the remote repository. To do that, you must additionally send the changes to the remote repository. This is called pushing:
git push
That will send all locally committed changes to the server. Obviously only changes that have not yet been sent previously are sent.
diff (show changes to working copy)
In svn, you can see the changes that have been made but have not yet been committed with diff. This is also correct in git:
git diff
This will show all changes in your working copy that are not yet staged (scheduled for committing).
You can view this for a single file as well:
git diff myfile.pas
This will show unstaged changes made to your working copy of myfile.pas.
If you have already staged one or more files (i.e. marked for inclusion in the next commit), the above will not show them in the generated diff. If you wish to see the staged changes (and only the staged changed), use the --cached command-line option:
git diff --cached
diff (show changes performed in a commit)
In svn, you can see the changes that a commit did through svn diff -c <revision>. In git, you use the show command instead:
git show -p <commit_hash_or_branch_or_tag>
If you omit the commit hash, the last commit to the current branch will be shown instead.
log (show commits in a branch)
In svn, you can see the commits in a branch with svn log. The same works in git:
git log
This will list the commit hashes (the string that git uses to identify commits, similar to revision numbers in svn) followed by the log messages. If you also want to see which files were changed, use
git log --stat
ls (listing branches)
To get a list of branches in Subversion, you use the 'ls' command with a server URL. By convention, all directories under '/branches' are the names of branches. Branches always exist both on the client(s) and server.
In git, branches are formalised as part of the version control system: commands deal specifically with branches rather than with paths that are treated as branches. Additionally, git differentiates between remote branches (branches that exist in the repository that you cloned, i.e., in this case on the gitlab server), and local branches (branches that you created on your machine after cloning). The repository that you cloned is referenced using the alias "origin" by default, and the names of remote branches are prepended by this alias.
The list of local branches can be obtained using:
git branch
By default, the only local branch you will have is main, which corresponds to svn trunk. This local branch is automatically created when performing the initial clone operation.
The list of remote branches can be obtained using:
git branch -r
By default, the remote branches are the branches that exist in the repository on the gitlab server, whose alias is "origin". The local main branch automatically tracks (~ is linked to) the remote origin/main branch. Because of this tracking, executing git pull resp. git push commands while you have your local main branch checked out will synchronise the two from resp. to gitlab. See switch on how to create more local branches and how to link them to remote branches.
copy (creating a branch)
To create a branch from the current working directory situation, you can create a branch like this:
git branch mybugfix
this will create a branch mybugfix from the currently checked out branch at the current commit. But it does not yet make this the active branch.
You need to check out the newly made branch first:
git checkout mybugfix
The two operations can also be combined with one command:
git checkout -b mybugfix
switch (checking out a branch)
To switch to an existing local branch mybugfix, you can use the checkout command:
git checkout mybugfix
this will check out branch mybugfix. If there are any uncommitted changes which would cause a conflict, git will refuse the checkout.
To switch to a remote branch `mybugfix2`, which does not exist yet locally, you can also use the checkout command:
git checkout mybugfix2
this will check out branch mybugfix2 and automatically set it up to track the remote branch. Here again, if there are any uncommitted changes which would cause a conflict, git will refuse the checkout.
Note that if the branch does not exist remotely, this will simply create a new branch locally. It is better to be explicit:
git checkout -b mybugfix2 --track origin/mybugfix2
If you created a branch locally which does not yet exist on the server, made some modifications, and you wish to push this branch to the server, you must tell this to git when pushing:
git push -u origin/mybugfix mybugfix
the -u origin/mybugfix tells git all it needs to know to connect the local with the remote branch.
revert
Revert the entire working tree
If you have made some changes locally and wish to undo them, you can do a hard reset in git:
git reset --hard
This will undo any changes you made in the entire checkout, including any staged changes.
Revert changes to specific files/directories
You cannot undo changes to individual files with git reset --hard. Instead, use
git checkout <pathspec>
pathspec can be any combination of files and directories. Note that if the files had staged changes, this command will restore the staged version rather than the last committed version.
merge (merging the changes in 2 branches)
To merge changes in 2 branches, you use the merge command. If we want to merge the changes in mybugfix to fixes then we do:
git checkout fixes git merge mybugfix
blame (check who made modifications)
To see who changes what line (and in what commit) svn offers you the 'blame' command. The same command exists in git.
git blame yourfile.pas
status (check status of files)
To see whether there are any changed files in your working repository, svn offers the 'status' command. The same command exists in git.
git status
will present you with all changed, staged and new files in the repository.
If you want only the status of files below a certain directory, you can specify the name of the directory. So to get the changes in the current working directory (or below) that would be:
git status .
will present you with all changed, staged and new files in the current directory. This is the default behaviour of svn.
shelve (temporarily undo changes)
Subversion has an (experimental) feature that allows to temporarily set aside changes to your working copy : shelve. This feature exists since a long time in git and is called stash:
git stash
will set aside any changes to the working copy, and restore the working copy to the state it would be in if you did a 'git pull' (or svn update).
To reapply the changes you set aside to the working copy, and to remove them from the list of stashes at the same time, you can execute the following command:
git stash pop
If any conflicts occur, you can
- resolve them, or
- use git reset --hard to revert all files again
In either case, the stash will not be touched when conflicts occurred while applying it. If you still with to remove it, you can do so with
git stash drop
info (get working dir and server info)
In subversion, you can get information about the current working directory and remote server configuration using svn info. Since git is a distributed system, no direct equivalent of the info command exists: there is no single server, and the revision number as known in subversion does not exist.
The following script attempts to display similar information as the svn info command:
#!/bin/bash # author: Duane Johnson # email: duane.johnson@gmail.com # date: 2008 Jun 12 # license: MIT # # Based on discussion at http://kerneltrap.org/mailarchive/git/2007/11/12/406496 pushd . >/dev/null # Find base of git directory while [ ! -d .git ] && [ ! `pwd` = "/" ]; do cd ..; done # Show various information about this git directory if [ -d .git ]; then echo "== Remote URL: `git remote -v`" echo "== Remote Branches: " git branch -r echo echo "== Local Branches:" git branch echo echo "== Configuration (.git/config)" cat .git/config echo echo "== Most Recent Commit" git --no-pager log -n1 echo echo "Type 'git log' for more commits, or 'git show' for full commit details." else echo "Not a git repository." fi popd >/dev/null
Note that this script will also work in the Windows environment if you have the windows git client installed, because it comes with a minimal unix environment.
file properties (EOL handling etc.)
Subversion allows you to set some properties on files. There are 'reserved' properties that svn itself uses, for example to handle EOL handling and file type. Because git operates on diffs and not on files, no similar concept exists.
However, git does allow you to set global or local attributes for classes of files. These are in the .gitattributes file. That file should be located in the root of your repository, and can contain some attributes. For example:
* text=auto *.txt text *.vcproj text eol=crlf *.sh text eol=lf *.jpg -text
This is a regular file which you can (and must) add with git add so it is saved for all users.