Skip to content

Latest commit

 

History

History
966 lines (691 loc) · 41.6 KB

README.ru.md

File metadata and controls

966 lines (691 loc) · 41.6 KB

Шпаргалка по GitHub

Этот репозиторий содержит список скрытых и не очень функций Git и GitHub. A collection of cool hidden and not so hidden features of Git and GitHub. This cheat sheet was inspired by Zach Holman's Git and GitHub Secrets talk at Aloha Ruby Conference 2012 (slides) and his More Git and GitHub Secrets talk at WDCNZ 2013 (slides).

Короткая ссылка: http://git.io/sheet

На других языках: English, Русский, 한국어, 日本語, 简体中文.

Содержание

Замечания к переводу

Некоторые термины и названия переводились следующим образом:

English Русский
branch ветка
collaborator помощник (владельца репозитория)
commit коммит
compare сравнить
diff изменения
fork форк
Gist не переводится
Issue пока не переводится
merge объединить
Pull Request запрос на изменение
pull забирать (изменения)
push загружать (изменения)

Перевод не является дословным, т.к. основная задача была — передать лишь общий смысл. Поэтому переводчик не претендует на безальтернативную точку зрения по правильности некоторых формулировок. Наоборот приветвуется всякая конструктивная критика, а ещё лучше — сделайте посильный вклад в перевод текста с английского языка.

GitHub

Игнорирование пробелов

Добавив при просмотре изменений ?w=1 к URL страницы, вы скроете изменение пробелов. Это позволит сконцентрироваться на изменёном коде.

Diff without whitespace

Узнайте больше о секретах GitHub.

Настройка отступов

Чтобы задать собственную ширину табуляции, добавьте ?ts=4 к URL страницы при просмотре изменений. Ширина по умолчанию 8 пробелов. Число после ts может быть изменено с учётом ваших предпочтений. Это не работает с Gists и сырыми файлами. Чтобы исправить это вы можете установить расширение для Chrome или Opera.

Так выгдядит исходный код на Go до добавления ?ts=4:

Before, tab space example

...а так после добавления ?ts=4:

After, tab space example

История коммитов от одного автора

Чтобы просмотреть в репозитории все коммиты от одного автора, добавьте ?author={user} к URL.

https://github.com/rails/rails/commits/master?author=dhh

DHH commit history

Узнайте больше о различиях в представлении коммитов.

Клонирование репозиториев

При клонировании репозитория .git в конце можно опустить.

$ git clone https://github.com/tiimgreen/github-cheat-sheet

Узнайте больше о команде Git clone.

Ветки

Сравнение всех веток с другой

Если вы перейдёте на страницу Branches, ссылка на которую находится рядом с кнопкой Commits:

https://github.com/{user}/{repo}/branches

... то увидите список всех веток, которые ещё не объединены с главной.

Здесь вы можете перейти к странице сравнения или удалить ветку, нажав на соответсвующую кнопку.

Compare branches not merged into master in rails/rails repo - https://github.com/rails/rails/branches

Сравнение веток

Чтобы сравнить ветки, используя GitHub, измените URL следующим образом:

https://github.com/{user}/{repo}/compare/{range}

Где {range} = master...4-1-stable

Например:

https://github.com/rails/rails/compare/master...4-1-stable

Rails branch compare example

Также {range} может быть таким:

https://github.com/rails/rails/compare/master@{1.day.ago}...master
https://github.com/rails/rails/compare/master@{2014-10-04}...master

Все даты в формате YYYY-DD-MM

Another compare example

Ветки также можно сравнивать в представлениях diff или patch

https://github.com/rails/rails/compare/master...4-1-stable.diff
https://github.com/rails/rails/compare/master...4-1-stable.patch

Узнайте больше о сравнении коммитов за определённые периоды.

Сравнение веток между форками

Чтобы сравнить ветки из различных форкнутых репозиториев, измените URL следующим образом:

https://github.com/{user}/{repo}/compare/{foreign-user}:{branch}...{own-branch}

Например:

https://github.com/rails/rails/compare/byroot:master...master

Forked branch compare

Gists

Gists позволяют легко работать с небольшими кусками кода без необходимости создания полноценного репозитория.

Gist

Добавьте .pibb в конец URL Gist'а (как здесь), чтобы получить HTML версию, подходящую для вставки на другие сайты.

С Gist'ом можно обращаться также как и с репозиторием, поэтому его можно клонировать следующей коммандой:

$ git clone https://gist.github.com/tiimgreen/10545817

Gists

Это означает, что вы также можете редакировать и загружать изменения на сервер.

$ git commit
$ git push
Username for 'https://gist.github.com': 
Password for 'https://[email protected]': 

Однако Gist не поддерживает создание каталогов — все файлы хранятся в корне репозитория. Узнайте больше о создании Gist.

Git.io

Git.io — это простой сокращатель ссылок на GitHub.

Git.io

Вы также можете использовать его с помощью чистого HTTP, используюя Curl:

$ curl -i http://git.io -F "url=https://github.com/..."
HTTP/1.1 201 Created
Location: http://git.io/abc123

$ curl -i http://git.io/abc123
HTTP/1.1 302 Found
Location: https://github.com/...

Узнайте больше о Git.io.

Быстрые клавиши

Когда вы находитесь в репозитории, быстрые клавиши позволют лекго перемещаться по коду.

  • Нажмите t, чтобы открыть файловый менеджер.
  • Нажмите w, чтобы открыть список веток.
  • Нажмите s, чтобы прейти к строке поиска по текущему репозиторию. Нажмите Backspace, чтобы убрать плашку "This repository" и осуществить поиск по всему сайту.
  • Нажмите l, чтобы изменить метку существующего Issue.
  • Pressing y when looking at a file (e.g. https://github.com/tiimgreen/github-cheat-sheet/blob/master/README.md) will change your URL to one which, in effect, freezes the page you are looking at. If this code changes, you will still be able to see what you saw at that current time.

Чтобы узнать, какие быстрые клавиши доступны на текущей странице, нажмите ?:

Keyboard shortcuts

Узнайте больше о синтаксисе поисковой строки.

Выделение строк кода

Либо добавьте #L52 в конец URL страницы с кодом, либо просто щёлкните на номер строки, чтобы выделить строку с этим номером.

Это работает также и с диапазонами, например, #L53-L60. Чтобы выбрать диапазон, щёлкните на двух строчках, удерживая Shift:

https://github.com/rails/rails/blob/master/activemodel/lib/active_model.rb#L53-L60

Line Highlighting

Закрытие Issue через комментарии к коммитам

Иногда коммиты могут исправлять некоторые Issue. Ключевые слова fix/fixes/fixed, close/closes/closed или resolve/resolves/resolved, за которыми следует номер Issue, закрывают соответсвующий Issue, если они были в комментарии к коммиту в ветке master.

$ git commit -m "Fix screwup, fixes #12"

This closes the issue and references the closing commit.

Closing Repo

Узнайте больше о закрытии Issue через комментарии к коммитам. Read more about closing Issues via commit messages.

Перекрёстные ссылки на Issues

Если вы хотите прикрепить ссылку на другой Issue в том же самом репозитории, просто напишите номер этого Issue, предварив его решёткой #.

Чтобы прикрепить ссылку на Issue в другом репозитории, напишите {user}/{repo}#ISSUE_NUMBER, например, tiimgreen/toc#12.

Cross-Link Issues

Отключение обсуждений

Обсуждение запросов на изменение и Issue может быть выключено владельцем репозитория или его помощниками.

Lock conversation

Это означает, что непривелигированные пользователи больше не смогут оствалять комментарии в обсуждениях этого репозитория.

Comments locked

Узнайте больше о выключении обсуждений.

CI Status on Pull Requests

If set up correctly, every time you receive a Pull Request, Travis CI will build that Pull Request just like it would every time you make a new commit. Read more about how to get started with Travis CI.

Travis CI status

Read more about the commit status API.

Подсветка синтаксиса в Markdown файлах

Блоки исходного кода с подсветкой синтаксиса в Markdown файлах оформляются так:

```ruby
require 'tabbit'
table = Tabbit.new('Name', 'Email')
table.add_row('Tim Green', '[email protected]')
puts table.to_s
```

Результат:

require 'tabbit'
table = Tabbit.new('Name', 'Email')
table.add_row('Tim Green', '[email protected]')
puts table.to_s

GitHub испльзует Linguist для определения языка и подсветки синтаксиса. GitHub uses Linguist to perform language detection and syntax highlighting. You can find out which keywords are valid by perusing the languages YAML file.

Узнайте больше о Markdown.

Смайлы

В запросах на изменение, в Issues, в сообщениях к коммитам, в описаниях репозиториев и т.п. можно изпользовать смайлы вида :name_of_emoji:.

Польный список смайлов, поддерживаемых GitHub, можно найти здесь или здесь.

5 самых популярных смайлов на GitHub:

  1. :shipit:
  2. :sparkles:
  3. :-1:
  4. :+1:
  5. :clap:

Изображения

Изображения (в т.ч. и gif-анимацию) можно вставить вот так:

![Подсказка](http://www.sheawong.com/wp-content/uploads/2013/08/keephatin.gif)

Изображения напрямую из репозитория можно вставить так:

![Подсказка](https://github.com/{user}/{repo}/raw/master/path/to/image.gif)

Peter don't care

Все изображения кэшируются, поэтому, если сервер с картинкой упадёт, она всё равно будет видна на GitHub.

Embedding Images in GitHub Wiki

There are multiple ways of embedding images in Wiki pages. There's the standard Markdown syntax (shown above). But there's also a syntax that allows things like specifying the height or width of the image:

[[ http://www.sheawong.com/wp-content/uploads/2013/08/keephatin.gif | height = 100px ]]

Which produces:

Just a screenshot

Быстрое цитирование

В ленте комментариев можно выделить текст и нажать r, тогда этот текст скопируется в поле ответа как цитата. When on a comment thread and you want to quote something someone previously said, highlight the text and press r, this will copy it into your text box in the block-quote format.

Quick Quote

Узнайте больше о быстром цитировании.

Pasting Clipboard Image to Comments

(Works on Chrome browsers only)

After taking a screenshot and adding it to the clipboard (mac: cmd-ctrl-shift-4), you can simply paste (cmd-v / ctrl-v) the image into the comment section and it will be auto-uploaded to github.

Pasting Clipboard Image to Comments

Read more about issue attachments.

Быстрое добавление лицензии

При создании репозитория, GitHub даёт возможность добавить готовую лицензию:

License

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

License

Также работает для .gitignore.

Узнайте больше о лицензировании открытого кода.

Task Lists

In Issues and Pull requests check boxes can be added with the following syntax (notice the space):

- [ ] Be awesome
- [ ] Prepare dinner
  - [ ] Research recipe
  - [ ] Buy ingredients
  - [ ] Cook recipe
- [ ] Sleep

Task List

When they are clicked, they will be updated in the pure Markdown:

- [x] Be awesome
- [ ] Prepare dinner
  - [x] Research recipe
  - [x] Buy ingredients
  - [ ] Cook recipe
- [ ] Sleep

Read more about task lists.

Task Lists in Markdown Documents

In full Markdown documents read-only checklists can now be added using the following syntax:

- [ ] Mercury
- [x] Venus
- [x] Earth
  - [x] Moon
- [x] Mars
  - [ ] Deimos
  - [ ] Phobos
  • Mercury
  • Venus
  • Earth
    • Moon
  • Mars
    • Deimos
    • Phobos

Read more about task lists in markdown documents.

Relative Links

Relative links are recommended in your Markdown files when linking to internal content.

[Link to a header](#awesome-section)
[Link to a file](docs/readme)

Absolute links have to be updated whenever the URL changes (e.g. repository renamed, username changed, project forked). Using relative links makes your documentation easily stand on its own.

Read more about relative links.

Metadata and Plugin Support for GitHub Pages

Within Jekyll pages and posts, repository information is available within the site.github namespace, and can be displayed, for example, using {{ site.github.project_title }}.

The Jemoji and jekyll-mentions plugins enable emoji and @mentions in your Jekyll posts and pages to work just like you'd expect when interacting with a repository on GitHub.com.

Read more about repository metadata and plugin support for GitHub Pages.

Viewing YAML Metadata in your Documents

Many blogging websites, like Jekyll with GitHub Pages, depend on some YAML-formatted metadata at the beginning of your post. GitHub will render this metadata as a horizontal table, for easier reading

YAML metadata

Read more about viewing YAML metadata in your documents.

Rendering Tabular Data

GitHub supports rendering tabular data in the form of .csv (comma-separated) and .tsv (tab-separated) files.

Tabular data

Read more about rendering tabular data.

###Revert a Pull Request After a pull request is merged, you may find it does not help anything or it was a bad decision to merge the pull request.

You can revert it by clicking the Revert button on the right side of a commit in the pull request page to create a pull request with reverted changes to this specific pull request.

Revert button

Read more about reverting pull requests

Diffs

Rendered Prose Diffs

Commits and pull requests, including rendered documents supported by GitHub (e.g. Markdown), feature source and rendered views.

Source / Rendered view

Click the "rendered" button to see the changes as they'll appear in the rendered document. Rendered prose view is handy when you're adding, removing, and editing text:

Rendered Prose Diffs

Read more about rendered prose diffs.

Diffable Maps

Any time you view a commit or pull request on GitHub that includes geodata, GitHub will render a visual representation of what was changed.

Diffable Maps

Read more about diffable maps.

Expanding Context in Diffs

Using the unfold button in the gutter of a diff, you can reveal additional lines of context with a click. You can keep clicking unfold until you've revealed the whole file, and the feature is available anywhere GitHub renders diffs.

Expanding Context in Diffs

Read more about expanding context in diffs.

Diff or Patch of Pull Request

You can get the diff of a Pull Request by adding a .diff or .patch extension to the end of the URL. For example:

https://github.com/tiimgreen/github-cheat-sheet/pull/15
https://github.com/tiimgreen/github-cheat-sheet/pull/15.diff
https://github.com/tiimgreen/github-cheat-sheet/pull/15.patch

The .diff extension would give you this in plain text:

diff --git a/README.md b/README.md
index 88fcf69..8614873 100644
--- a/README.md
+++ b/README.md
@@ -28,6 +28,7 @@ All the hidden and not hidden features of Git and GitHub. This cheat sheet was i
 - [Merged Branches](#merged-branches)
 - [Quick Licensing](#quick-licensing)
 - [TODO Lists](#todo-lists)
+- [Relative Links](#relative-links)
 - [.gitconfig Recommendations](#gitconfig-recommendations)
     - [Aliases](#aliases)
     - [Auto-correct](#auto-correct)
@@ -381,6 +382,19 @@ When they are clicked, they will be updated in the pure Markdown:
 - [ ] Sleep

(...)

Rendering and diffing images

GitHub can display several common image formats, including PNG, JPG, GIF, and PSD. In addition, there are several ways to compare differences between versions of those image formats.

Diffable PSD

Read more about rendering and diffing images.

Hub

Hub is a command line Git wrapper that gives you extra features and commands that make working with GitHub easier.

This allows you to do things like:

$ hub clone tiimgreen/toc

Check out some more cool commands Hub has to offer.

Contributing Guidelines

Adding a CONTRIBUTING file to the root of your repository will add a link to your file when a contributor creates an Issue or opens a Pull Request.

Contributing Guidelines

Read more about contributing guidelines.

Octicons

GitHubs icons (Octicons) have now been open sourced.

Octicons

Read more about GitHub's Octicons

GitHub Resources

Title Link
GitHub Explore https://github.com/explore
GitHub Blog https://github.com/blog
GitHub Help https://help.github.com/
GitHub Training https://training.github.com/
GitHub Developer https://developer.github.com/

GitHub Talks

Title Link
How GitHub Uses GitHub to Build GitHub https://www.youtube.com/watch?v=qyz3jkOBbQY
Introduction to Git with Scott Chacon of GitHub https://www.youtube.com/watch?v=ZDR433b0HJY
How GitHub No Longer Works https://www.youtube.com/watch?v=gXD1ITW7iZI
Git and GitHub Secrets https://www.youtube.com/watch?v=Foz9yvMkvlA
More Git and GitHub Secrets https://www.youtube.com/watch?v=p50xsL-iVgU

Git

Remove All Deleted Files from the Working Tree

When you delete a lot of files using /bin/rm you can use the following command to remove them from the working tree and from the index, eliminating the need to remove each one individually:

$ git rm $(git ls-files -d)

For example:

$ git status
On branch master
Changes not staged for commit:
	deleted:    a
	deleted:    c

$ git rm $(git ls-files -d)
rm 'a'
rm 'c'

$ git status
On branch master
Changes to be committed:
	deleted:    a
	deleted:    c

Previous Branch

To move to the previous branch in Git:

$ git checkout -
# Switched to branch 'master'

$ git checkout -
# Switched to branch 'next'

$ git checkout -
# Switched to branch 'master'

Read more about Git branching.

Stripspace

Git Stripspace:

  • Strips trailing whitespace
  • Collapses newlines
  • Adds newline to end of file

A file must be passed when calling the command, e.g.:

$ git stripspace < README.md

Read more about the Git stripspace command.

Checking out Pull Requests

Pull Requests are special branches on the GitHub repository which can be retrieved locally in several ways:

Retrieve a specific Pull Request and store it temporarily in FETCH_HEAD for quickly diffing or mergeing:

$ git fetch origin refs/pull/[PR-Number]/head

Acquire all Pull Request branches as local remote branches by refspec:

$ git fetch origin '+refs/pull/*/head:refs/remotes/origin/pr/*'

Or setup the remote to fetch Pull Requests automatically by adding these corresponding lines in your repository's .git/config:

[remote "origin"]
    fetch = +refs/heads/*:refs/remotes/origin/*
    url = git@github.com:tiimgreen/github-cheat-sheet.git
[remote "origin"]
    fetch = +refs/heads/*:refs/remotes/origin/*
    url = git@github.com:tiimgreen/github-cheat-sheet.git
    fetch = +refs/pull/*/head:refs/remotes/origin/pr/*

For Fork-based Pull Request contributions, it's useful to checkout a remote branch representing the Pull Request and create a local branch from it:

$ git checkout pr/42 pr-42

Or should you work on more repositories, you can globally configure fetching pull requests in the global git config instead.

git config --global --add remote.origin.fetch "+refs/pull/*/head:refs/remotes/origin/pr/*"

This way, you can use the following short commands in all your repositories:

git fetch origin
git checkout pr/42

Read more about checking out pull requests locally.

Empty Commits

Commits can be pushed with no code changes by adding --allow-empty:

$ git commit -m "Big-ass commit" --allow-empty

Some use-cases for this (that make sense), include:

  • Annotating the start of a new bulk of work or a new feature.
  • Documenting when you make changes to the project that aren't code related.
  • Communicating with people using your repository.
  • The first commit of a repo, as the first commit cannot be rebased later: git commit -m "init repo" --allow-empty.

It ain't even that trolololol...

Styled Git Status

Running:

$ git status

Produces:

git status

By adding -sb:

$ git status -sb

This is produced:

git status -sb

Read more about the Git status command.

Styled Git Log

Running:

$ git log --all --graph --pretty=format:'%Cred%h%Creset -%C(auto)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --date=relative

Produces:

git log --all --graph --pretty=format:'%Cred%h%Creset -%C(auto)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --date=relative

Credit to Palesz

This can be aliased using the instructions found here.

Read more about the Git log command.

Git Query

A Git query allows you to search all your previous commit messages and find the most recent one matching the query.

$ git show :/query

Where query (case-sensitive) is the term you want to search, this then finds the last one and gives details on the lines that were changed.

$ git show :/typo

git show :/query

Press q to quit.

Merged Branches

Running:

$ git branch --merged

Will give you a list of all branches that have been merged into your current branch.

Conversely:

$ git branch --no-merged

Will give you a list of branches that have not been merged into your current branch.

Read more about the Git branch command.

Fixup and Autosquash

If there is something wrong with a previous commit (can be one or more from HEAD), for example abcde, run the following command after you've amended the problem:

$ git commit --fixup=abcde
$ git rebase abcde^ --autosquash -i

Read more about the Git commit command. Read more about the Git rebase command.

Web Server for Browsing Local Repositories

Use the Git instaweb command to instantly browse your working repository in gitweb. This command is a simple script to set up gitweb and a web server for browsing the local repository.

$ git instaweb

Opens:

Git instaweb

Read more about the Git instaweb command.

Git Configurations

Your .gitconfig file contains all your Git configurations.

Aliases

Aliases are helpers that let you define your own git calls. For example you could set git a to run git add --all.

To add an alias, either navigate to ~/.gitconfig and fill it out in the following format:

[alias]
  co = checkout
  cm = commit
  p = push
  # Show verbose output about tags, branches or remotes
  tags = tag -l
  branches = branch -a
  remotes = remote -v

...or type in the command-line:

$ git config --global alias.new_alias git_function

For example:

$ git config --global alias.cm commit

For an alias with multiple functions use quotes:

$ git config --global alias.ac 'add -A . && commit'

Some useful aliases include:

Alias Command What to Type
git cm git commit git config --global alias.cm commit
git co git checkout git config --global alias.co checkout
git ac git add . -A git commit git config --global alias.ac '!git add -A && git commit'
git st git status -sb git config --global alias.st 'status -sb'
git tags git tag -l git config --global alias.tags 'tag -l'
git branches git branch -a git config --global alias.branches 'branch -a'
git cleanup `git branch --merged grep -v '*'
git remotes git remote -v git config --global alias.remotes 'remote -v'
git lg git log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit -- git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --"

Some Aliases are taken from @mathiasbynens dotfiles: https://github.com/mathiasbynens/dotfiles/blob/master/.gitconfig

Auto-Correct

If you type git comit you will get this:

$ git comit -m "Message"
# git: 'comit' is not a git command. See 'git --help'.

# Did you mean this?
#   commit

To call commit when comit is typed, just enable auto-correct:

$ git config --global help.autocorrect 1

So now you will get this:

$ git comit -m "Message"
# WARNING: You called a Git command named 'comit', which does not exist.
# Continuing under the assumption that you meant 'commit'
# in 0.1 seconds automatically...

Color

To add more color to your Git output:

$ git config --global color.ui 1

Read more about the Git config command.

Git Resources

Title Link
Official Git Site http://git-scm.com/
Official Git Video Tutorials http://git-scm.com/videos
Code School Try Git http://try.github.com/
Introductory Reference & Tutorial for Git http://gitref.org/
Official Git Tutorial http://git-scm.com/docs/gittutorial
Everyday Git http://git-scm.com/docs/everyday
Git Immersion http://gitimmersion.com/
Ry's Git Tutorial http://rypress.com/tutorials/git/index.html
Git for Designers http://hoth.entp.com/output/git_for_designers.html
Git for Computer Scientists http://eagain.net/articles/git-for-computer-scientists/
Git Magic http://www-cs-students.stanford.edu/~blynn/gitmagic/
GitHub Training Kit http://training.github.com/kit
Git Visualization Playground http://onlywei.github.io/explain-git-with-d3/#freeplay

Git Books

Title Link
Pragmatic Version Control Using Git http://www.pragprog.com/titles/tsgit/pragmatic-version-control-using-git
Pro Git http://git-scm.com/book
Git Internals PluralSight https://github.com/pluralsight/git-internals-pdf
Git in the Trenches http://cbx33.github.com/gitt/
Version Control with Git http://www.amazon.com/Version-Control-Git-collaborative-development/dp/1449316387
Pragmatic Guide to Git http://www.pragprog.com/titles/pg_git/pragmatic-guide-to-git
Git: Version Control for Everyone http://www.packtpub.com/git-version-control-for-everyone/book