dsp-site/wiki/Prog/Git/Git основные команды.md

293 lines
11 KiB
Markdown
Raw Normal View History

2019-05-24 04:56:12 +00:00
---
title: "Git: основные команды"
category: Программирование
tags: программирование, git
monofontoptions:
- Scale=0.8
...
2019-05-27 05:45:29 +00:00
## Ссылки
* [GitHowTo](https://githowto.com/ru/changes_not_files)
* [ProGit](https://git-scm.com/book/ru/v2)
* [Git Pocket Guide](https://github.com/maxliscia/git-pocket)
## Установка
В Debian/Ubuntu:
2019-05-24 04:56:12 +00:00
```sh
sudo apt-get install git
```
2019-05-27 05:45:29 +00:00
Подробнее: https://help.github.com/articles/set-up-git/
2019-05-24 04:56:12 +00:00
2019-05-27 05:45:29 +00:00
## Термины
2019-05-24 04:56:12 +00:00
2019-05-27 05:45:29 +00:00
| Термин | Определение |
|--------------------|-------------|
| Рабочий каталог | Набор файлов в текущем каталоге |
| Индекс | Область с файлами, подготовленными для фиксации |
| SHA-1 | Уникальный идентификатор, отражающий информацию об истории |
| Ветка | Именованная последовательность в истории изменений |
| Коммит \| Фиксация | Набор файлов, записанных в историю одновременно |
| `HEAD` | Имя ссылки на последнюю фиксацию в текущей ветке |
| Метка | Именованная ссылка на некоторую фиксацию в истории |
2019-05-24 04:56:12 +00:00
2019-05-27 05:45:29 +00:00
## Состояния
2019-05-24 04:56:12 +00:00
Файлы в рабочем каталоге могут отслеживаться системой контроля версий
(tracked) или нет (untracked). Отслеживаемые файлы, которые на диаграмме
обозначены зелёным фоном, могут быть неизменёнными (unmodified),
изменёнными (modified) или подготовленными к фиксации (staged).
```plantuml
@startuml
participant untracked as "Неотслеживамые\n(untracked)"
participant unmodified as "Неизменённые\n(unmodified)" #99FF99
participant modified as "Изменённые\n(modified)" #77FF77
participant staged as "Подготовленные к фиксации\n(staged)" #55FF55
untracked -> staged : git add
unmodified -> modified : редактирование
modified -> staged : git add
staged -> unmodified : git commit
modified -> untracked: git rm --cached
unmodified -> untracked: git rm --cached
staged -> untracked: git rm --cached
@enduml
```
2019-05-27 05:45:29 +00:00
## $getting-started
| Command | Options | Description |
|------------|--------------|---------------------------------------------------------|
| `git config` | `--global user.name "Cooper Black"` | Set global user name |
| `git config` | `--global user.email "cooper@black.com"` | Set global user email |
| `git config` | `--list` | Display configuration |
| `git config` | `--global --list` | Display global configuration |
| `git init` | | Make current directory a git repository |
| `git remote` | `add origin <url>`| Set remote origin |
| `git ls-tree` | `-r <branch> --name-only` | List files being tracked |
Reference: https://git-scm.com/docs/git-config
## $clone
| Command | Options | Description |
|-------------|-------------|---------------------------------------------------------|
| `git clone` | `<giturl>` | Clone remote repository into current directory |
| `git clone` | `--recursive <giturl>` | Clone remote repository with submodules |
Reference: https://git-scm.com/docs/git-clone
## $submodule
| Command | Options | Description |
|-------------|-------------|---------------------------------------------------------|
| `git clone` | `--recursive <giturl>` | Clone remote repository with submodules |
| `git submodule` | `add <giturl>` | Add submodule |
| `git submodule` | `update --remote` | Update submodules |
| `git submodule` | `status --recursive` | List submodules |
**Remove submodule:**
```shell
$ git submodule deinit <path/to/submodule>
$ git rm <path/to/submodule>
```
Reference: https://git-scm.com/docs/git-submodule
## $commit
| Command | Options | Description |
|-------------|-------------|---------------------------------------------------------|
| `git add` | `<filename>` | Add files to staging area |
| `git commit` | `-m "<title>" -m "<body>"` | Commit with message (includes "added" files only) |
| `git rm` | `<filenama>` | Remove files from the working tree and from the index |
| | `-f` | Force deletion of files from disk |
| `git rm` | `-r --cached <filename>` | Untrack file (without deleting) |
Reference: https://git-scm.com/docs/git-commit
**Untrack hidden files, or update list of tracked files, after adding `.gitignore`:**
```shell
# remove all
$ git rm -r --cached .
# add all again, now gitignore will take effect (try to add .gitignore from the start next time)
$ git add .
```
## $push branches (see tags for pushing tags)
| Command | Options | Description |
|-------------|-------------|---------------------------------------------------------|
| `git push` | `<remotename> <branchname>` | Push branch to remote |
| `git push` | `<remotename> --all` | Push all branches to remote |
| `git push` | `--d <remotename> <branchname>` | `--delete` remote branch |
Reference: https://git-scm.com/docs/git-push
## $remote
- Remote connections are like bookmarks named after remote repos
- `git clone` automatically creates a remote connection usually called `origin`
| Command | Options | Description |
|-------------|-------------|---------------------------------------------------------|
| `git remote` | `-v` | List remote repository endpoints |
| `git branch` | `-r` | List remote repository branches |
| `git remote` | `add <name> <url>` | Create namespaced connection to a remote repository |
| `git remote` | `rename <oldname> <newname>` | Rename connection |
| `git remote` | `rm <name>` | Remove connection |
Reference: https://git-scm.com/docs/git-remote
**Remove remote origin:**
```shell
# Remove `origin` settings from .git/config
git remote rm origin
# Remove `FETCH_HEAD` which still points to remote
git rm .git/FETCH_HEAD
```
## $fetch-pull
| Command | Options | Description |
|-------------|-------------|---------------------------------------------------------|
| `git fetch` | `<remote>` | Fetch all branches from remote (without merge) |
| `git fetch` | `<remote> <branch>` | Fetch specific branch |
| `git merge` | `<remote>/<branch>` | Merge fetched remote |
| `git pull` | `<remote>` | Fetch and merge in one command |
Reference: https://git-scm.com/docs/git-fetch, https://git-scm.com/docs/git-pull
## $branch
| Command | Options | Description |
|-------------|-------------|---------------------------------------------------------|
| `git branch` | | List branches |
| `git branch` | `<branchname>` | Create new branch |
| `git checkout` | `<sha-1>` | Switch to branch, or commit |
| `git branch` | `-m <branchname> <newname>` | Rename branch |
| `git merge` | `<branchname>` | Merge changes from `<branchname>` to current branch |
| `git branch` | `-d <branchname>` | `--delete` branch |
Reference: https://git-scm.com/docs/git-branch
## $status
| Command | Options | Description |
|-------------|-------------|---------------------------------------------------------|
| `git status` | `-s` | Show the working tree status, with `--short` format |
| `git log` | `--oneline` | Show commit logs, with `--oneline` format |
| `git ls-files`| | Show information about files in the index and the working tree |
Reference: https://git-scm.com/docs/git-status
## $diff
| Command | Options | Description |
|-------------|-------------|---------------------------------------------------------|
| `git diff` | | Compare **`working directory`** and **`index`** |
| | `-cached` | Compare **`index`** and **`latest commit`** |
| | `HEAD` | Compare **`latest commit`** and **`working directory`** |
| | `--stat` | Optional short format |
| | `<sha-1> <sha-1>` | 2 points in time to compare |
| | `<dir> | <file>` | Compare whole directory or limit to file |
Reference: https://git-scm.com/docs/git-diff
**Examples:**
```shell
## compare changes made to README.md between working tree (default) and latest commit (HEAD)
$ git diff --stat HEAD ./path/README.md
## compare changes made to README.md between 2 specific points in time (e.g. 2 commits)
$ git diff --stat a649900 24bdd58 ./path/README.md
```
## $tag
| Command | Options | Description |
|-------------|-------------|---------------------------------------------------------|
| `git tag` | | List tags |
| `git tag` | `<v1.0.0>` | Create tag, from latest commit, lightweight |
| `git tag` | `-a <v1.0.0> -m "<msg>"` | Create tag, with `--annotate`, from latest commit |
| `git tag` | `-a <v1.0.0> -m "<msg>" <SHA-1>` | Create tag, with `--annotate`, from specific commit |
| `git tag` | `-d <v1.1.0>` | `--delete` tag |
| `git show` | `<v1.0.0>` | Show tag data and message |
| `git checkout` | `<v1.0.0>` | Switch to specific point tag (not editable) |
| `git push` | `<remote> <tag>` | Push specific tag to `<remote>` (recommended) |
| `git push` | `<remote> --tags` | Push all tags to `<remote>` (only if necessary) |
Инициализация репозитория в каталоге `dir`:
```sh
git init dir
```
Клонирование репозитория `repo`, принадлежащего пользователю `user`,
с сервера `gitlab.2` в каталог `dir`:
```sh
git clone git@gitlab.2:user/repo.git dir
```
2019-05-24 04:56:12 +00:00
Просмотр состояния рабочего каталога и репозитория:
```sh
git status
```
Краткая форма вывода состояния:
```sh
git status -s
```
Добавление файла `README.md` под версионный контроль и подготовка
к фиксации:
```sh
git add README.md
```
Удаление файла `README.md` из индекса репозитория:
```sh
git rm --cached README.md
```
Зафиксировать файлы, подготовленные к фиксации:
```sh
git commit
```
Зафиксировать все отслеживаемые файлы, которые были изменены:
```sh
git commit -a
```
Отправить все ветки репозитория на сервер с меткой `origin`:
```sh
git push origin
```