- Настройка учетных данных для Git
- Зачем настраивать конфигурационный файл в Git?
- Пример
- Как настроить учетные данные по умолчанию для git Config?
- Задайте имя пользователя в конфигурации Git
- Настройка электронной почты пользователя в git Config
- Как просмотреть список пользовательских настроек git Config?
- Просмотреть полный список настроек в git Config
- Просмотр определенного параметра в конфигурации Git
- Git для новичков (часть 1)
- Что такое Git и зачем он нужен?
- Как работает
- Установка
- Настройка
- Создание репозитория
- Процесс работы с Git
- Визуальный интерфейс
- Создаем свой первый проект и выкладываем на GitHub
- 8.1 Customizing Git — Git Configuration
- Git Configuration
- Basic Client Configuration
- core.editor
- commit.template
- core.pager
- user.signingkey
- core.excludesfile
- help.autocorrect
- Colors in Git
- color.ui
- color.*
- External Merge and Diff Tools
- Formatting and Whitespace
- core.autocrlf
- core.whitespace
- Server Configuration
- receive.fsckObjects
- receive.denyNonFastForwards
- receive.denyDeletes
Настройка учетных данных для Git
После того, как мы установили Git, пришло время внести некоторые изменения в конфигурационный файл Git и настроить учетные данные с помощью Git Bash.
Зачем настраивать конфигурационный файл в Git?
Когда мы устанавливаем Git в нашей системе, конфигурационный файл принимает значения по умолчанию для некоторых полей. Это означает, что Git начинает с установки одинаковых файлов для каждого пользователя. Таким образом, при первом запуске Git общие файлы по умолчанию (которые являются общими для каждого пользователя) ищутся внутри файла /etc/gitconfig.
После того, как они установлены, Git должен видеть файлы, относящиеся к конкретному пользователю. Эти конкретные файлы доступны в разделе
/.config/git/config. Конкретный файл включает в себя ваше имя пользователя, ваше имя и т. д.
Откройте свой Git Bash и введите следующую команду, чтобы просмотреть личные настройки конфигурации.
vi
Нажмите enter и просмотрите файл конфигурации.
Пример
Давайте рассмотрим пример, чтобы понять, почему нам нужно настроить эти значения во время работы в проекте. Многие люди работают над одним проектом, но единственное, что может идентифицировать вас, — это ваше имя пользователя или адрес электронной почты. Если вы не настроили эти значения в файле конфигурации, эти значения (имя, адрес электронной почты и т. д.) берутся случайным образом. Поэтому, когда вы совершаете какое-либо изменение, это изменение отражается вместе с вашим именем пользователя и электронной почтой, которые являются случайными, и никто не сможет распознать или запомнить ваши учетные данные. Это создает много проблем в команде. Следовательно, мы должны изменить этот конфигурационный файл.
Как настроить учетные данные по умолчанию для git Config?
Задайте имя пользователя в конфигурации Git
Первое изменение, которое мы сделаем внутри нашего конфигурационного файла, будет изменение нашего имени пользователя в Git. Чтобы изменить имя пользователя, выполните следующие действия.
Откройте Git Bash в вашей системе. Введите следующую команду с вашим именем пользователя:
Примечание: изменение имени пользователя повлияет только на ваши будущие коммиты и ни на один из ваших прошлых коммитов.
Это изменит имя пользователя на значение, указанное в команде. Нажмите enter, и если ничего не произошло, имя было успешно изменено.
Настройка электронной почты пользователя в git Config
После успешного выполнения вышеуказанной команды мы изменим нашу электронную почту. Введите следующую команду
Это изменит идентификатор электронной почты в конфигурации Git на идентификатор электронной почты, указанный в команде.
Как просмотреть список пользовательских настроек git Config?
После того, как вы установили все значения в файле конфигурации, вы можете просмотреть все настройки также через Git Bash.
Просмотреть полный список настроек в git Config
Для этого перейдите в Git Bash и введите эту команду.
Нажмите enter, и вы увидите все настройки, включая те, которые мы только что установили в предыдущем разделе.
Просмотр определенного параметра в конфигурации Git
Вы также можете проверить наличие определенного параметра в файле конфигурации вместо того, чтобы открывать полный список. Чтобы увидеть это, выполните следующие простые шаги.
В Git Bash введите следующую команду:
здесь относится к имени параметра, который вы хотите видеть. Например user.name. Вам нужно запомнить значение ключа именно таким, как оно есть. Если вы не можете вспомнить, то всегда можете отобразить полный список конфигурационных файлов.
Нажмите клавишу enter, чтобы увидеть значение ключа.
https://git-scm.com/docs/git-config — больше информации о git-config.
В последнем уроке мы познакомились с командой Git fetch и Read more
В одной из последних статей мы узнали о команде Git Read more
Мы уже знаем, как вносить изменения в локальное хранилище и Read more
Команда git push при выполнении перемещает изменения, внесенные пользователем на Read more
«Клонирование» означает создание идентичных особей естественным или искусственным путем. Клонирование Read more
Сегодня мы узнаем, как скопировать чужой репозиторий в наш аккаунт Read more
Источник
Git для новичков (часть 1)
Что такое Git и зачем он нужен?
Git — это консольная утилита, для отслеживания и ведения истории изменения файлов, в вашем проекте. Чаще всего его используют для кода, но можно и для других файлов. Например, для картинок — полезно для дизайнеров.
С помощью Git-a вы можете откатить свой проект до более старой версии, сравнивать, анализировать или сливать свои изменения в репозиторий.
Репозиторием называют хранилище вашего кода и историю его изменений. Git работает локально и все ваши репозитории хранятся в определенных папках на жестком диске.
Так же ваши репозитории можно хранить и в интернете. Обычно для этого используют три сервиса:
Каждая точка сохранения вашего проекта носит название коммит (commit). У каждого commit-a есть hash (уникальный id) и комментарий. Из таких commit-ов собирается ветка. Ветка — это история изменений. У каждой ветки есть свое название. Репозиторий может содержать в себе несколько веток, которые создаются из других веток или вливаются в них.
Как работает
Если посмотреть на картинку, то становиться чуть проще с пониманием. Каждый кружок, это commit. Стрелочки показывают направление, из какого commit сделан следующий. Например C3 сделан из С2 и т. д. Все эти commit находятся в ветке под названием main . Это основная ветка, чаще всего ее называют master . Прямоугольник main* показывает в каком commit мы сейчас находимся, проще говоря указатель.
В итоге получается очень простой граф, состоящий из одной ветки ( main ) и четырех commit. Все это может превратиться в более сложный граф, состоящий из нескольких веток, которые сливаются в одну.
Об этом мы поговорим в следующих статьях. Для начала разберем работу с одной веткой.
Установка
Основой интерфейс для работы с Git-ом является консоль/терминал. Это не совсем удобно, тем более для новичков, поэтому предлагаю поставить дополнительную программу с графическим интерфейсом (кнопками, графиками и т.д.). О них я расскажу чуть позже.
Но для начала, все же установим сам Git.
Windows. Проходим по этой ссылке, выбираем под вашу ОС (32 или 64 битную), скачиваем и устанавливаем.
Для Mac OS. Открываем терминал и пишем:
Linux. Открываем терминал и вводим следующую команду.
Настройка
Вы установили себе Git и можете им пользоваться. Давайте теперь его настроим, чтобы когда вы создавали commit, указывался автор, кто его создал.
Открываем терминал (Linux и MacOS) или консоль (Windows) и вводим следующие команды.
Создание репозитория
Теперь вы готовы к работе с Git локально на компьютере.
Создадим наш первый репозиторий. Для этого пройдите в папку вашего проекта.
Теперь Git отслеживает изменения файлов вашего проекта. Но, так как вы только создали репозиторий в нем нет вашего кода. Для этого необходимо создать commit.
Отлично. Вы создали свой первый репозиторий и заполнили его первым commit.
Процесс работы с Git
Не стоит после каждого изменения файла делать commit. Чаще всего их создают, когда:
Создан новый функционал
Добавлен новый блок на верстке
Исправлены ошибки по коду
Вы завершили рабочий день и хотите сохранить код
Это поможет держать вашу ветки в чистоте и порядке. Тем самым, вы будете видеть историю изменений по каждому нововведению в вашем проекте, а не по каждому файлу.
Визуальный интерфейс
Как я и говорил ранее, существуют дополнительные программы для облегчения использования Git. Некоторые текстовые редакторы или полноценные среды разработки уже включают в себя вспомогательный интерфейс для работы с ним.
Но существуют и отдельные программы по работе с Git. Могу посоветовать эти:
Я не буду рассказывать как они работают. Предлагаю разобраться с этим самостоятельно.
Создаем свой первый проект и выкладываем на GitHub
Давайте разберемся как это сделать, с помощью среды разработки Visual Studio Code (VS Code).
Перед началом предлагаю зарегистрироваться на GitHub.
Создайте папку, где будет храниться ваш проект. Если такая папка уже есть, то создавать новую не надо.
После открываем VS Code .
Установите себе дополнительно анализаторы кода для JavaScript и PHP
Откройте вашу папку, которую создали ранее
После этого у вас появится вот такой интерфейс
Здесь будут располагаться все файлы вашего проекта
Здесь можно работать с Git-ом
Кнопка для создания нового файла
Кнопка для создания новой папки
Если ваш проект пустой, как у меня, то создайте новый файл и назовите его index.html . После этого откроется окно редактирование этого файла. Напишите в нем ! и нажмите кнопку Tab . Автоматически должен сгенерироваться скелет пустой HTML страницы. Не забудьте нажать ctrl+s чтобы файл сохранился.
Давайте теперь перейдем во вкладу для работы с Git-ом.
Откроется вот такое окно:
Кнопка для публикации нашего проекта на GitHub
После нажатия на кнопку 1 , появится всплывающее окно. Нужно выбрать второй вариант или там где присутствует фраза . public repository
Если вы хотите создать локальный репозиторий и опубликовать код в другой сервис, то необходимо нажать на кнопку Initialize Repository . После этого, вручную выбрать сервис куда публиковать.
После того, как выбрали «Опубликовать на GitHub публичный репозиторий» (пункт 2), программа предложит вам выбрать файлы, которые будут входить в первый commit. Проставляем галочки у всех файлов, если не проставлены и жмем ОК . Вас перекинет на сайт GitHub, где нужно будет подтвердить вход в аккаунт.
Вы создали и опубликовали репозиторий на GitHub.
Теперь сделаем изменения в коде и попробуем их снова опубликовать. Перейдите во вкладку с файлами, отредактируйте какой-нибудь файл, не забудьте нажать crtl+s (Windows) или cmd+s (MacOS), чтобы сохранить файл. Вернитесь обратно во вкладу управления Git.
Если посмотреть на значок вкладки Git, то можно увидеть цифру 1 в синем кружке. Она означает, сколько файлов у нас изменено и незакоммичено. Давайте его закоммитим и опубликуем:
Кнопка для просмотра изменений в файле. Необязательно нажимать, указал для справки
Добавляем наш файл для будущего commit
Отправляем наш commit в GitHub
Поздравляю, вы научились создавать commit и отправлять его в GitHub!
Это первая вводная статья по утилите Git. Здесь мы рассмотрели:
Как его устанавливать
Как его настраивать
Как инициализировать репозиторий и создать commit через консоль
Как на примере VS Code, опубликовать свой код на GitHub
Забегая вперед, советую вам погуглить, как работают следующие команды:
P.S. Для облегчения обучения, оставлю вам ссылку на бесплатный тренажер по Git.
В телеграмм канале Step by Step , я публикую еще больше материала и провожу обучающие стримы, для всех желающих.
Источник
8.1 Customizing Git — Git Configuration
So far, we’ve covered the basics of how Git works and how to use it, and we’ve introduced a number of tools that Git provides to help you use it easily and efficiently. In this chapter, we’ll see how you can make Git operate in a more customized fashion, by introducing several important configuration settings and the hooks system. With these tools, it’s easy to get Git to work exactly the way you, your company, or your group needs it to.
Git Configuration
As you read briefly in Getting Started, you can specify Git configuration settings with the git config command. One of the first things you did was set up your name and email address:
Now you’ll learn a few of the more interesting options that you can set in this manner to customize your Git usage.
First, a quick review: Git uses a series of configuration files to determine non-default behavior that you may want. The first place Git looks for these values is in the system-wide [path]/etc/gitconfig file, which contains settings that are applied to every user on the system and all of their repositories. If you pass the option —system to git config , it reads and writes from this file specifically.
The next place Git looks is the
/.config/git/config ) file, which is specific to each user. You can make Git read and write to this file by passing the —global option.
Finally, Git looks for configuration values in the configuration file in the Git directory ( .git/config ) of whatever repository you’re currently using. These values are specific to that single repository, and represent passing the —local option to git config . If you don’t specify which level you want to work with, this is the default.
Each of these “levels” (system, global, local) overwrites values in the previous level, so values in .git/config trump those in [path]/etc/gitconfig , for instance.
Git’s configuration files are plain-text, so you can also set these values by manually editing the file and inserting the correct syntax. It’s generally easier to run the git config command, though.
Basic Client Configuration
The configuration options recognized by Git fall into two categories: client-side and server-side. The majority of the options are client-side — configuring your personal working preferences. Many, many configuration options are supported, but a large fraction of them are useful only in certain edge cases; we’ll cover just the most common and useful options here. If you want to see a list of all the options your version of Git recognizes, you can run:
This command lists all the available options in quite a bit of detail. You can also find this reference material at https://git-scm.com/docs/git-config.
core.editor
By default, Git uses whatever you’ve set as your default text editor via one of the shell environment variables VISUAL or EDITOR , or else falls back to the vi editor to create and edit your commit and tag messages. To change that default to something else, you can use the core.editor setting:
Now, no matter what is set as your default shell editor, Git will fire up Emacs to edit messages.
commit.template
If you set this to the path of a file on your system, Git will use that file as the default initial message when you commit. The value in creating a custom commit template is that you can use it to remind yourself (or others) of the proper format and style when creating a commit message.
For instance, consider a template file at
/.gitmessage.txt that looks like this:
Note how this commit template reminds the committer to keep the subject line short (for the sake of git log —oneline output), to add further detail under that, and to refer to an issue or bug tracker ticket number if one exists.
To tell Git to use it as the default message that appears in your editor when you run git commit , set the commit.template configuration value:
Then, your editor will open to something like this for your placeholder commit message when you commit:
If your team has a commit-message policy, then putting a template for that policy on your system and configuring Git to use it by default can help increase the chance of that policy being followed regularly.
core.pager
This setting determines which pager is used when Git pages output such as log and diff . You can set it to more or to your favorite pager (by default, it’s less ), or you can turn it off by setting it to a blank string:
If you run that, Git will page the entire output of all commands, no matter how long they are.
user.signingkey
If you’re making signed annotated tags (as discussed in Signing Your Work), setting your GPG signing key as a configuration setting makes things easier. Set your key ID like so:
Now, you can sign tags without having to specify your key every time with the git tag command:
core.excludesfile
You can put patterns in your project’s .gitignore file to have Git not see them as untracked files or try to stage them when you run git add on them, as discussed in Ignoring Files.
But sometimes you want to ignore certain files for all repositories that you work with. If your computer is running macOS, you’re probably familiar with .DS_Store files. If your preferred editor is Emacs or Vim, you know about filenames that end with a
This setting lets you write a kind of global .gitignore file. If you create a
/.gitignore_global file with these contents:
…and you run git config —global core.excludesfile
/.gitignore_global , Git will never again bother you about those files.
help.autocorrect
If you mistype a command, it shows you something like this:
Git helpfully tries to figure out what you meant, but it still refuses to do it. If you set help.autocorrect to 1, Git will actually run this command for you:
Note that “0.1 seconds” business. help.autocorrect is actually an integer which represents tenths of a second. So if you set it to 50, Git will give you 5 seconds to change your mind before executing the autocorrected command.
Colors in Git
Git fully supports colored terminal output, which greatly aids in visually parsing command output quickly and easily. A number of options can help you set the coloring to your preference.
color.ui
Git automatically colors most of its output, but there’s a master switch if you don’t like this behavior. To turn off all Git’s colored terminal output, do this:
The default setting is auto , which colors output when it’s going straight to a terminal, but omits the color-control codes when the output is redirected to a pipe or a file.
You can also set it to always to ignore the difference between terminals and pipes. You’ll rarely want this; in most scenarios, if you want color codes in your redirected output, you can instead pass a —color flag to the Git command to force it to use color codes. The default setting is almost always what you’ll want.
color.*
If you want to be more specific about which commands are colored and how, Git provides verb-specific coloring settings. Each of these can be set to true , false , or always :
In addition, each of these has subsettings you can use to set specific colors for parts of the output, if you want to override each color. For example, to set the meta information in your diff output to blue foreground, black background, and bold text, you can run:
You can set the color to any of the following values: normal , black , red , green , yellow , blue , magenta , cyan , or white . If you want an attribute like bold in the previous example, you can choose from bold , dim , ul (underline), blink , and reverse (swap foreground and background).
External Merge and Diff Tools
Although Git has an internal implementation of diff, which is what we’ve been showing in this book, you can set up an external tool instead. You can also set up a graphical merge-conflict-resolution tool instead of having to resolve conflicts manually. We’ll demonstrate setting up the Perforce Visual Merge Tool (P4Merge) to do your diffs and merge resolutions, because it’s a nice graphical tool and it’s free.
If you want to try this out, P4Merge works on all major platforms, so you should be able to do so. We’ll use path names in the examples that work on macOS and Linux systems; for Windows, you’ll have to change /usr/local/bin to an executable path in your environment.
To begin, download P4Merge from Perforce. Next, you’ll set up external wrapper scripts to run your commands. We’ll use the macOS path for the executable; in other systems, it will be where your p4merge binary is installed. Set up a merge wrapper script named extMerge that calls your binary with all the arguments provided:
The diff wrapper checks to make sure seven arguments are provided and passes two of them to your merge script. By default, Git passes the following arguments to the diff program:
Because you only want the old-file and new-file arguments, you use the wrapper script to pass the ones you need.
You also need to make sure these tools are executable:
Now you can set up your config file to use your custom merge resolution and diff tools. This takes a number of custom settings: merge.tool to tell Git what strategy to use, mergetool. .cmd to specify how to run the command, mergetool. .trustExitCode to tell Git if the exit code of that program indicates a successful merge resolution or not, and diff.external to tell Git what command to run for diffs. So, you can either run four config commands:
or you can edit your
/.gitconfig file to add these lines:
After all this is set, if you run diff commands such as this:
Instead of getting the diff output on the command line, Git fires up P4Merge, which looks something like this:
If you try to merge two branches and subsequently have merge conflicts, you can run the command git mergetool ; it starts P4Merge to let you resolve the conflicts through that GUI tool.
The nice thing about this wrapper setup is that you can change your diff and merge tools easily. For example, to change your extDiff and extMerge tools to run the KDiff3 tool instead, all you have to do is edit your extMerge file:
Now, Git will use the KDiff3 tool for diff viewing and merge conflict resolution.
Git comes preset to use a number of other merge-resolution tools without your having to set up the cmd configuration. To see a list of the tools it supports, try this:
If you’re not interested in using KDiff3 for diff but rather want to use it just for merge resolution, and the kdiff3 command is in your path, then you can run:
If you run this instead of setting up the extMerge and extDiff files, Git will use KDiff3 for merge resolution and the normal Git diff tool for diffs.
Formatting and Whitespace
Formatting and whitespace issues are some of the more frustrating and subtle problems that many developers encounter when collaborating, especially cross-platform. It’s very easy for patches or other collaborated work to introduce subtle whitespace changes because editors silently introduce them, and if your files ever touch a Windows system, their line endings might be replaced. Git has a few configuration options to help with these issues.
core.autocrlf
If you’re programming on Windows and working with people who are not (or vice-versa), you’ll probably run into line-ending issues at some point. This is because Windows uses both a carriage-return character and a linefeed character for newlines in its files, whereas macOS and Linux systems use only the linefeed character. This is a subtle but incredibly annoying fact of cross-platform work; many editors on Windows silently replace existing LF-style line endings with CRLF, or insert both line-ending characters when the user hits the enter key.
Git can handle this by auto-converting CRLF line endings into LF when you add a file to the index, and vice versa when it checks out code onto your filesystem. You can turn on this functionality with the core.autocrlf setting. If you’re on a Windows machine, set it to true — this converts LF endings into CRLF when you check out code:
If you’re on a Linux or macOS system that uses LF line endings, then you don’t want Git to automatically convert them when you check out files; however, if a file with CRLF endings accidentally gets introduced, then you may want Git to fix it. You can tell Git to convert CRLF to LF on commit but not the other way around by setting core.autocrlf to input:
This setup should leave you with CRLF endings in Windows checkouts, but LF endings on macOS and Linux systems and in the repository.
If you’re a Windows programmer doing a Windows-only project, then you can turn off this functionality, recording the carriage returns in the repository by setting the config value to false :
core.whitespace
Git comes preset to detect and fix some whitespace issues. It can look for six primary whitespace issues — three are enabled by default and can be turned off, and three are disabled by default but can be activated.
The three that are turned on by default are blank-at-eol , which looks for spaces at the end of a line; blank-at-eof , which notices blank lines at the end of a file; and space-before-tab , which looks for spaces before tabs at the beginning of a line.
The three that are disabled by default but can be turned on are indent-with-non-tab , which looks for lines that begin with spaces instead of tabs (and is controlled by the tabwidth option); tab-in-indent , which watches for tabs in the indentation portion of a line; and cr-at-eol , which tells Git that carriage returns at the end of lines are OK.
You can tell Git which of these you want enabled by setting core.whitespace to the values you want on or off, separated by commas. You can disable an option by prepending a — in front of its name, or use the default value by leaving it out of the setting string entirely. For example, if you want all but space-before-tab to be set, you can do this (with trailing-space being a short-hand to cover both blank-at-eol and blank-at-eof ):
Or you can specify the customizing part only:
Git will detect these issues when you run a git diff command and try to color them so you can possibly fix them before you commit. It will also use these values to help you when you apply patches with git apply . When you’re applying patches, you can ask Git to warn you if it’s applying patches with the specified whitespace issues:
Or you can have Git try to automatically fix the issue before applying the patch:
These options apply to the git rebase command as well. If you’ve committed whitespace issues but haven’t yet pushed upstream, you can run git rebase —whitespace=fix to have Git automatically fix whitespace issues as it’s rewriting the patches.
Server Configuration
Not nearly as many configuration options are available for the server side of Git, but there are a few interesting ones you may want to take note of.
receive.fsckObjects
Git is capable of making sure every object received during a push still matches its SHA-1 checksum and points to valid objects. However, it doesn’t do this by default; it’s a fairly expensive operation, and might slow down the operation, especially on large repositories or pushes. If you want Git to check object consistency on every push, you can force it to do so by setting receive.fsckObjects to true:
Now, Git will check the integrity of your repository before each push is accepted to make sure faulty (or malicious) clients aren’t introducing corrupt data.
receive.denyNonFastForwards
If you rebase commits that you’ve already pushed and then try to push again, or otherwise try to push a commit to a remote branch that doesn’t contain the commit that the remote branch currently points to, you’ll be denied. This is generally good policy; but in the case of the rebase, you may determine that you know what you’re doing and can force-update the remote branch with a -f flag to your push command.
To tell Git to refuse force-pushes, set receive.denyNonFastForwards :
The other way you can do this is via server-side receive hooks, which we’ll cover in a bit. That approach lets you do more complex things like deny non-fast-forwards to a certain subset of users.
receive.denyDeletes
One of the workarounds to the denyNonFastForwards policy is for the user to delete the branch and then push it back up with the new reference. To avoid this, set receive.denyDeletes to true:
This denies any deletion of branches or tags — no user can do it. To remove remote branches, you must remove the ref files from the server manually. There are also more interesting ways to do this on a per-user basis via ACLs, as you’ll learn in An Example Git-Enforced Policy.
Источник