Git config где находится windows
Перейти к содержимому

Git config где находится windows

  • автор:

1.6 Введение — Первоначальная настройка Git

Теперь, когда Git установлен в вашей системе, самое время настроить среду для работы с Git под себя. Это нужно сделать только один раз — при обновлении версии Git настройки сохранятся. Но, при необходимости, вы можете поменять их в любой момент, выполнив те же команды снова.

В состав Git входит утилита git config , которая позволяет просматривать и настраивать параметры, контролирующие все аспекты работы Git, а также его внешний вид. Эти параметры могут быть сохранены в трёх местах:

Файл [path]/etc/gitconfig содержит значения, общие для всех пользователей системы и для всех их репозиториев. Если при запуске git config указать параметр —system , то параметры будут читаться и сохраняться именно в этот файл. Так как этот файл является системным, то вам потребуются права суперпользователя для внесения изменений в него.

/.config/git/config хранит настройки конкретного пользователя. Этот файл используется при указании параметра —global и применяется ко всем репозиториям, с которыми вы работаете в текущей системе.

Файл config в каталоге Git (т. е. .git/config ) репозитория, который вы используете в данный момент, хранит настройки конкретного репозитория. Вы можете заставить Git читать и писать в этот файл с помощью параметра —local , но на самом деле это значение по умолчанию. Неудивительно, что вам нужно находиться где-то в репозитории Git, чтобы эта опция работала правильно.

Настройки на каждом следующем уровне подменяют настройки из предыдущих уровней, то есть значения в .git/config перекрывают соответствующие значения в [path]/etc/gitconfig .

В системах семейства Windows Git ищет файл .gitconfig в каталоге $HOME ( C:\Users\$USER для большинства пользователей). Кроме того, Git ищет файл [path]/etc/gitconfig , но уже относительно корневого каталога MSys, который находится там, куда вы решили установить Git при запуске инсталлятора.

Если вы используете Git для Windows версии 2.х или новее, то так же обрабатывается файл конфигурации уровня системы, который имеет путь C:\Documents and Settings\All Users\Application Data\Git\config в Windows XP или C:\ProgramData\Git\config в Windows Vista и новее. Этот файл может быть изменён только командой git config -f <file> , запущенной с правами администратора.

Чтобы посмотреть все установленные настройки и узнать где именно они заданы, используйте команду:

Имя пользователя

Первое, что вам следует сделать после установки Git — указать ваше имя и адрес электронной почты. Это важно, потому что каждый коммит в Git содержит эту информацию, и она включена в коммиты, передаваемые вами, и не может быть далее изменена:

Опять же, если указана опция —global , то эти настройки достаточно сделать только один раз, поскольку в этом случае Git будет использовать эти данные для всего, что вы делаете в этой системе. Если для каких-то отдельных проектов вы хотите указать другое имя или электронную почту, можно выполнить эту же команду без параметра —global в каталоге с нужным проектом.

Многие GUI-инструменты предлагают сделать это при первом запуске.

Выбор редактора

Теперь, когда вы указали своё имя, самое время выбрать текстовый редактор, который будет использоваться, если будет нужно набрать сообщение в Git. По умолчанию Git использует стандартный редактор вашей системы, которым обычно является Vim. Если вы хотите использовать другой текстовый редактор, например, Emacs, можно проделать следующее:

В системе Windows следует указывать полный путь к исполняемому файлу при установке другого текстового редактора по умолчанию. Пути могут отличаться в зависимости от того, как работает инсталлятор.

В случае с Notepad++, популярным редактором, скорее всего вы захотите установить 32-битную версию, так как 64-битная версия ещё не поддерживает все плагины. Если у вас 32-битная Windows или 64-битный редактор с 64-битной системой, то выполните следующее:

Vim, Emacs и Notepad++ — популярные текстовые редакторы, которые часто используются разработчиками как в Unix-подобных системах, таких как Linux и Mac, так и в Windows. Если вы используете другой редактор или его 32-битную версию, то обратитесь к разделу Команды git config core.editor за дополнительными инструкциями как использовать его совместно с Git.

В случае, если вы не установили свой редактор и не знакомы с Vim или Emacs, вы можете попасть в затруднительное положение, когда какой-либо из них будет запущен. Например, в Windows может произойти преждевременное прерывание команды Git при попытке вызова редактора.

Настройка ветки по умолчанию

Когда вы инициализируете репозиторий командой git init , Git создаёт ветку с именем master по умолчанию. Начиная с версии 2.28, вы можете задать другое имя для создания ветки по умолчанию.

Например, чтобы установить имя main для вашей ветки по умолчанию, выполните следующую команду:

Проверка настроек

Если вы хотите проверить используемую конфигурацию, можете использовать команду git config —list , чтобы показать все настройки, которые Git найдёт:

Некоторые ключи (названия) настроек могут отображаться несколько раз, потому что Git читает настройки из разных файлов (например, из /etc/gitconfig и

/.gitconfig ). В таком случае Git использует последнее значение для каждого ключа.

Также вы можете проверить значение конкретного ключа, выполнив git config <key> :

Так как Git читает значение настроек из нескольких файлов, возможна ситуация когда Git использует не то значение что вы ожидали. В таком случае вы можете спросить Git об origin этого значения. Git выведет имя файла, из которого значение для настройки было взято последним:

Git config

The git config command is a function that sets configuration variables. It controls git look and operation.

gitconfig

The git config levels and files

The git config accepts arguments to specify on which configuration level to operate. When looking for a configuration value, Git prioritizes the following order of configuration levels:

When no configuration option is passed git config writes to a local level, by default.The repository of the .git directory has a file that stores local configuration values.

The application of the global level configuration includes the operating system user. Global configuration values can be found in a file placed in a user’s home directory.

The System-level configuration includes all users on an operating system and all repositories. System-level configuration file is located in a git config file of the system root path.

How to write a value

Here, the example writes the value «[email protected]» to the configuration name user.email. The global level is used so as to set the value for the current operating system user.

The git config usage

The basic use of git config is creating it with a configuration name that displays the set value at that name. Configuration names consist of a »section» and a »key» separated by a dot.

Here, email is a child property of the user configuration block.

The git config editor — core.editor

When your identity is set up, Git uses your system’s default editor, which is Vi or Vim. The git config sets up which editor Git will use. Here is the list of most common editors with git config commands:

Editor Config Command
Atom git config —global core.editor «atom —wait»
emacs git config —global core.editor «emacs»
nano git config —global core.editor «nano -w»
vim git config —global core.editor «vim»
Sublime Text (Mac) git config —global core.editor «subl -n -w»
Sublime Text (Win, 32-bit install) git config —global core.editor «‘c:/program files (x86)/sublime text 3/sublimetext.exe’ -w»
Sublime Text (Win, 64-bit install) git config —global core.editor «‘c:/program files/sublime text 3/sublimetext.exe’ -w»
Textmate git config —global core.editor «mate -w»

Merge tools of git config

Git uses one of the merge tools in the case of a merge conflict. Git uses an internal implementation of the Unix diff program, by default. Besides, there are a lot of external third party merge conflict resolutions used instead.

Colored outputs

Git supports colors thus simplifying the process of reading Git output. You can use your colors for customizing the output. For setting color values git config command is used.

color.ui

Git automatically colors most of its output, but there is also a master variable if you want to set another color. For disabling all Git’s colored terminal output you can do the following:

The default setting of color.ui is auto which applies colors directly to the terminal output. It omits color code output when the output is redirected to a pipe or a file.

You can also set the color.ui value to always. It applies color code output when the output is redirected to files or pipes. This can cause problems as the receiving pipe may not be expecting color-coded input.

Git color values

Besides color.ui, there are also other color settings that can be set to false, auto, or always. They can have a specific color value: normal, black, red, green, yellow, blue, magenta, cyan, white. Colors can be specified as hexadecimal color codes like #1c87c9 or ANSI 256 color values if the terminal supports it.

Git color configuration settings

The git config aliases

Aliases are custom shortcuts specifying which command will expand to longer or combined commands. There is no need for typing commonly used commands with aliases. Git has its own alias system which is mostly used to shorten git commit command. The git config command is used to configure aliases.

Aliases can create super-powerful combinations with other aliases.

In the above-mentioned example, an alias amend composes the ci alias into a new alias that uses —amend

Git config где находится windows

TOGAF offers architects a chance to learn the principles behind implementing an enterprise-grade software architecture, including.

Haskell and PureScript each provide their own unique development advantages, so how should developers choose between these two .

While not particularly prescriptive, alignment with a MACH architecture strategy can help software teams ensure application .

Is your team prepared to capture the right data so that your digital twin testing is accurate and effective? Here’s what experts .

Akita’s discovery and observability will feed undocumented APIs into Postman’s design and testing framework to bring them into .

Specification-based techniques can play a role in efficient test coverage. Choosing the right techniques can ensure thorough .

Kubernetes Cloud Controller Manager is an optional tool used to manage cluster resources. Learn how it works, why you may want to.

Monitoring and visibility are crucial when it comes to cloud security. Explore Microsoft Defender for Cloud Apps, and see how .

AWS, Google, IBM and Microsoft offer machine learning certifications that can further your career. Learn what to expect from each.

CISA said Friday that ‘Submarine’ is a novel persistent backdoor was used in attacks against Barracuda Email Security Gateway .

Learn how to flip the script on malicious hackers with honey tokens, which act like tripwires to reveal an attacker’s presence.

The popularity of generative AI has skyrocketed in recent months. Its benefits, however, are being met with cybersecurity, .

Many organizations struggle to manage their vast collection of AWS accounts, but Control Tower can help. The service automates .

There are several important variables within the Amazon EKS pricing model. Dig into the numbers to ensure you deploy the service .

AWS users face a choice when deploying Kubernetes: run it themselves on EC2 or let Amazon do the heavy lifting with EKS. See .

git config

In this document, we’ll take an in-depth look at the git config command. We briefly discussed git config usage on our Setting up a Repository page. The git config command is a convenience function that is used to set Git configuration values on a global or local project level. These configuration levels correspond to .gitconfig text files. Executing git config will modify a configuration text file. We’ll be covering common configuration settings like email, username, and editor. We’ll discuss Git aliases, which allow you to create shortcuts for frequently used Git operations. Becoming familiar with git config and the various Git configuration settings will help you create a powerful, customized Git workflow.

Usage

The most basic use case for git config is to invoke it with a configuration name, which will display the set value at that name. Configuration names are dot delimited strings composed of a ‘section’ and a ‘key’ based on their hierarchy. For example: user.email

In this example, email is a child property of the user configuration block. This will return the configured email address, if any, that Git will associate with locally created commits.

git config levels and files

Before we further discuss git config usage, let’s take a moment to cover configuration levels. The git config command can accept arguments to specify which configuration level to operate on. The following configuration levels are available:

  • —local

By default, git config will write to a local level if no configuration option is passed. Local level configuration is applied to the context repository git config gets invoked in. Local configuration values are stored in a file that can be found in the repo’s .git directory: .git/config

  • —global

Global level configuration is user-specific, meaning it is applied to an operating system user. Global configuration values are stored in a file that is located in a user’s home directory.

/.gitconfig on unix systems and C:\Users\ \.gitconfig on windows

  • —system

System-level configuration is applied across an entire machine. This covers all users on an operating system and all repos. The system level configuration file lives in a gitconfig file off the system root path. $(prefix)/etc/gitconfig on unix systems. On windows this file can be found at C:\Documents and Settings\All Users\Application Data\Git\config on Windows XP, and in C:\ProgramData\Git\config on Windows Vista and newer.

Thus the order of priority for configuration levels is: local, global, system. This means when looking for a configuration value, Git will start at the local level and bubble up to the system level.

Writing a value

Expanding on what we already know about git config , let’s look at an example in which we write a value:

This example writes the value your_email@example.com to the configuration name user.email . It uses the —global flag so this value is set for the current operating system user.

git config editor — core.editor

Many Git commands will launch a text editor to prompt for further input. One of the most common use cases for git config is configuring which editor Git should use. Listed below is a table of popular editors and matching git config commands:

git config —global core.editor «atom —wait»

git config —global core.editor «emacs»

git config —global core.editor «nano -w»

git config —global core.editor «vim»

git config —global core.editor «subl -n -w»

git config —global core.editor «‘c:/program files (x86)/sublime text 3/sublimetext.exe’ -w»

git config —global core.editor «‘c:/program files/sublime text 3/sublimetext.exe’ -w»

git config —global core.editor «mate -w»

Merge tools

In the event of a merge conflict, Git will launch a «merge tool.» By default, Git uses an internal implementation of the common Unix diff program. The internal Git diff is a minimal merge conflict viewer. There are many external third party merge conflict resolutions that can be used instead. For an overview of various merge tools and configuration, see our guide on tips and tools to resolve conflits with Git.

Colored outputs

Git supports colored terminal output which helps with rapidly reading Git output. You can customize your Git output to use a personalized color theme. The git config command is used to set these color values.

color.ui

This is the master variable for Git colors. Setting it to false will disable all Git’s colored terminal output.

By default, color.ui is set to auto which will apply colors to the immediate terminal output stream. The auto setting will omit color code output if the output stream is redirected to a file or piped to another process.

You can set the color.ui value to always which will also apply color code output when redirecting the output stream to files or pipes. This can unintentionally cause problems since the receiving pipe may not be expecting color-coded input.

Git color values

In addition to color.ui , there are many other granular color settings. Like color.ui , these color settings can all be set to false, auto, or always. These color settings can also have a specific color value set. Some examples of supported color values are:

  • normal
  • black
  • red
  • green
  • yellow
  • blue
  • magenta
  • cyan
  • white

Colors may also be specified as hexadecimal color codes like #ff0000, or ANSI 256 color values if your terminal supports it.

Git color configuration settings

  • Configures the output color of the Git branch command

2. color.branch. slot >

  • This value is also applicable to Git branch output. slot > is one of the following:
    • 1. current: the current branch
    • 2. local: a local branch
    • 3. remote: a remote branch ref in refs/remotes
    • 4. upstream: an upstream tracking branch
    • 5. plain: any other ref
    • Applies colors to git diff , git log , and git show output

    4. color.diff . slot >

    • Configuring a slot > value under color.diff tells git which part of the patch to use a specific color on.
      • 1. context: The context text of the diff. Git context is the lines of text content shown in a diff or patch that highlights changes.
      • 2. plain: a synonym for context
      • 3. meta: applies color to the meta information of the diff
      • 4. frag: applies color to the «hunk header» or «function in hunk header»
      • 5. old: applies a color to the removed lines in the diff
      • 6. new: colors the added lines of the diff
      • 7. commit: colors commit headers within the diff
      • 8. whitespace: sets a color for any whitespace errors in a diff

      5. color.decorate. slot >

      • Customize the color for git log —decorate output. The supported slot > values are: branch , remoteBranch , tag , stash , or HEAD . They are respectively applicable to local branches, remote-tracking branches, tags, stashed changes and HEAD .
      • Applies color to the output of git grep.

      7. color.grep. slot >

      • Also applicable to git grep. The slot > variable specifies which part of the grep output to apply color.
        • 1. context: non-matching text in context lines
        • 2. filename: filename prefix
        • 3. function: function name lines
        • 4. linenumber: line number prefix
        • 5. match: matching text
        • 6. matchContext: matching text in context lines
        • 7. matchSelected: matching text in selected lines
        • 8. selected: non-matching text in selected lines
        • 9. separator: separators between fields on a line (:, -, and =) and between hunks (—)
        • This variable applies color for interactive prompts and displays. Examples are git add —interactive and git clean —interactive

        9. color.interactive. slot >

        • The slot > variable can be specified to target more specific «interactive output». The available slot > values are: prompt, header, help, error; and each act on the corresponding interactive output.
        • Enables or disables colored output when the pager is in use
        • Enables or disables color output for the git show branch command
        • A boolean value that enables or disables color output for Git status

        13. color.status. slot >

        Used to specify custom color for specified git status elements. slot > supports the following values:

        • 1. header
          • Targets the header text of the status area
          • Both target files which are added but not committed
          • Targets files that are modified but not added to the git index
          • Targets files which are not tracked by Git
          • Applies color to the current branch
          • The color the «no branch» warning is shown in
          • Colors files which have unmerged changes

          Aliases

          You may be familiar with the concept of aliases from your operating system command-line; if not, they’re custom shortcuts that define which command will expand to longer or combined commands. Aliases save you the time and energy cost of typing frequently used commands. Git provides its own alias system. A common use case for Git aliases is shortening the commit command. Git aliases are stored in Git configuration files. This means you can use the git config command to configure aliases.

          This example creates a ci alias for the git commit command. You can then invoke git commit by executing git ci . Aliases can also reference other aliases to create powerful combos.

          This example creates an alias amend which composes the ci alias into a new alias that uses —amend flag .

          Formatting & whitespace

          Git has several «whitespace» features that can be configured to highlight whitespace issues when using git diff. The whitespace issues will be highlighted using the configured color color.diff.whitespace

          The following features are enabled by default:

          • blank-at-eol highlights orphan whitespaces at the line endings
          • space-before-tab highlights a space character that appears before a tab character when indenting a line
          • blank-at-eof highlights blank lines inserted at the end of a file

          The following features are disabled by default

          • indent-with-non-tab highlights a line that is indented with spaces instead of tabs
          • tab-in-indent highlights an initial tab indent as an error
          • trailing-space is shorthand for both blank-at-eol and blank-at-eof
          • cr-at-eol highlights a carriage-return at the line endings
          • tabwidth= defines how many character positions a tab occupies. The default value is 8. Allowed values are 1-63

          Summary

          In this article, we covered the use of the git config command . We discussed how the command is a convince method for editing raw git config files on the filesystem. We looked at basic read and write operations for configuration options. We took a look at common config patterns:

          • How to configure the Git editor
          • How to override configuration levels
          • How to reset configuration defaults
          • How to customize git colors

          Overall, git config is a helper tool that provides a shortcut to editing raw git config files on disk. We covered in depth personal customization options. Basic knowledge of git configuration options is a prerequisite for setting up a repository. See our guide there for a demonstration of the basics.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *