Настройка и работа с Git в Linux/Debian


Файл .gitignore:
=============
# environment *nix
.*
!.gitignore
*~

# environment Windows
# Windows
Thumbs.db
Desktop.ini

# composer
vendor/*
composer.phar
composer.lock

# netbeanse
nbproject

#Yii files
assets/*
------------------git-ignore-----------------
# environment *nix
!.htaccess
.*
!.gitignore
*~

# environment Windows
# Windows
Thumbs.db
Desktop.ini

# composer
vendor/*
composer.phar
composer.lock

# netbeans
nbproject
*.swp
*/*.swp
nbactions.xml
nb-configuration.xml
.nb-gradle/

#Yii files
protected/runtime/*
=============
> ~/.gitexcludes && vim ~/.gitexcludes
>>>>>>>add to file:>>>>>>>>>
...
/nbproject/*
...
<<<<<<<<<<<<<<<<<<<<<<<<<<<<
git config --global core.excludesfile ~/.gitexcludes
git rm --cached nbproject/ -r
 git push origin --force --tags
----------Установка GIT:---------------------
sudo apt-get update;
sudo apt-get install dirmngr --install-recommends
sudo apt-get install -y python-software-properties
sudo apt-get install -y software-properties-common
#sudo apt-get install -y python-software-properties
sudo add-apt-repository ppa:git-core/ppa;
sudo apt-get update;
sudo apt-get install -y git git-gui gitk git-svn tig;
#install bash completetion:
 Copy this file to your home directory, and add this to your .bashrc file:
source ~/git-completion.bash
OR:
[https://git-scm.com/book/en/v1/Git-Basics-Tips-and-Tricks]
download script: https://github.com/git/git/blob/master/contrib/completion/git-completion.bash
to /etc/bash_completion.d/
Ready!
----------------Начальные настройки:-----------
#Просмотр настроек:
git config --list
git config global core.editor vim
git config user.name "Your Name"
git config user.email "your_email@whatever.com"
git config --global core.autocrlf input
git config --global core.safecrlf false
# Чтобы git игнорировать изменения разрешений, выполните(повторно-помогает):
git config --global core.filemode false
git config core.fileMode false
#Игнор всех типов пробельных символов:
git config core.whitespace -trailing-space,-space-before-tab,-indent-with-non-tab
git config core.editor vim
git config color.diff.meta 'blue black bold'
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.bl blame
git config --global alias.l "log --oneline --graph"
git config --global alias.last 'log -1 HEAD'
git config user.signingkey E2DB448(some-my-key-id form command output: gpg --list-keys)
##If you do that, you'll never need to use core.fileMode
find . -type d -exec chmod a+rwx {} \; # Make folders traversable and read/write
find . -type f -exec chmod a+rw {} \;  # Make files read/write
-----------------Работа:-----------------------
OFFICIAL CASE:
…or create a new repository on the command line:
echo "# infohits" >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/tvcom/infohits.git
git push -u origin master
---
…or push an existing repository from the command line:
git remote add origin https://github.com/tvcom/infohits.git
git push -u origin master
Клонируем (например почти пустой - меньше проблем потом с github'ом)
репозиторий в текущую папку:(Иногда вываливает ошибки но делать нужно именно так!!)
git clone https://github.com/tvcom/some-dispatcher.git .
---
MY OWN CASE:
Делаем начальные настройки (см. пункт "Начальные настройки" выше)
Добавим все и свои файлы в папку и пометим их для отслеживания git'ом:
git add .
Сделаем коммит:
git commit -m "Final Commit"
Проверяем состояние:
git status
Отменяем иземения в рабочей копии к состоянию на последнем коммите(!!!все что наваяли будет утеряно.):
git stash;git stash clear
git pull
и если неизменный удаленный каталог то:
git push origin master
-------способ-2(от GITHUB.com):-------------------------
echo "# parser" >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin git@github.com:gitusername/parser.git
git branch --set-upstream-to=origin/master master
git push -u origin master
--------способ-3(от GITHUB.com):-------------------------
git remote add origin git@github.com:gitusername/parser.git
git push -u origin master
#Переименование ORIGIN:
git remote rename origin oldrepo
#редактировать текст сообщения к последнему коммиту:
git commit --amend -m "New commit message"
откат к коммиту:
git reset --hard id_long_коммита
#Yet add file in last commit:
git add file6
git commit --amend --no-edit
Экспортирование исходников, аналогично svn export:
git archive --format zip --output /путь/к/файлу/файл.zip master 
----------------Для удаления папки (рекурсивно действует только для локального репозитория):------
git rm -r --cached folderName
-----select branches:----------
git br -r //Show remote branches
git co --track origin/some_branches
git checkout -b megacompany --track origin/megacompany
OR:git co --track origin/develop
git branch
git push origin HEAD
git status
//Создаем новую ветку и переключаемся на неё:
git checkout -b megacompany
git status
vim -d ../product_modify.php include/product_modify.php 
git status
git add include/product_modify.php 
git branch
git commit -m "add feature: mapped supplier codes in admin backend"
git pull
git pull origin somemegabranch
git status
git push origin somemegabranch
git stash
git stash pop
git stash clear
-------MERGE:-----------------
git fetch origin //Забрать изменения с удаленного master.
git branch -r//Выводит список веток в том числе и удаленных.
git checkout -b "some-newbranch" //Создаем и переключимся на новую ветку.
(....делаем чтото в ней....)
git checkout master //Переключимся на мастер
git merge --no-ff some-feature-branch // сливаем сделанные изменения в текущую: мастер от myfeature с созданием коммита.
git checkout some-branch file-paths... //Мержим с файлов из какойто ветки.
вернуться к состоянию до слияния :
git reset --hard HEAD
Или, если вы уже зафиксировали слияние коммитом, что вы хотите его отменить:
git reset --hard ORIG_HEAD
git branch -d develope //удаление ветки develop.
git push origin :serverfix //удаление ветки serverfix на удаленном репозитории origin.
-----------MERGE Resolve conflict:---------------
git mergetool -t vimdiff
------------FROM DIFFMERGE SITE:-----------------
Settings for Linux

The following commands will update your .gitconfig to let GIT use DiffMerge:

$ git config --global diff.tool diffmerge
$ git config --global difftool.diffmerge.cmd "/usr/bin/diffmerge \"\$LOCAL\" \"\$REMOTE\""
---variant2:---
$ git config --global merge.tool diffmerge
$ git config --global mergetool.diffmerge.trustExitCode true
$ git config --global mergetool.diffmerge.cmd 
    "/usr/bin/diffmerge --merge --result=\"\$MERGED\"
        \"\$LOCAL\" \"\$BASE\" \"\$REMOTE\""
   
----------Deleting nbproject from git history and then delete fisical folder from remoterepo:----------
git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch -r nbproject' --prune-empty --tag-name-filter cat -- --all
git rm -r --cached nbproject
git commit -m "Removed nbproject from repository"
git pull
git push origin develop
---ETC:--------
//Переименование ветки:
git branch -m future-brunch feature-branch
//origin адрес репозитория:
git remote -v
git remote rm origin-example-one
git remote add origin git@bitbucket.org:bathsomeproject/bigline.git
git branch --set-upstream-to=origin/develop develop
//May be need add key to current bash-session:
ssh-add ~/.ssh/id_mykey_repository
git pull
//Поиск во всех локальных коммитах по условию:
git log --all --pretty=oneline | grep СловоВНазвании
//Отображение всех коммитов определенного автора.
git log --oneline --graph --author="Vasya Pupkin"
//Отображение всех файлов в истории коммитов в древе:
git log --name-status --graph --oneline
git show cfca68cf
git show --stat --pretty=full c76c4066e100394991e71e87bc82910f6f6ef542
//Только какие файлы затронуты:
git show cfca68cf --stat
//Поиск ветки по хешу коммита:
git branch --contains c76c4066e100394991e71e87bc82910f6f6ef542
git blame -L 12,22 products.php
git checkout -- <файл>
файл можно восстановить вот так:
git checkout myfile
Add file in last commit:
git add changelog.md
And amend it:
git commit --amend --no-edit
git commit --amend -m "Новое название" //исправление текста последнего коммита.
git clone file:///opt/git/project.git //клонирования с локальной ФС.
!!!git reset --hard HEAD~1 //Отмена последнего коммита !!!Пропадают папки с закомиченными новыми файлами и все наработки в файлах!!!)
Восстанавливать коммит так:
git reflog;git reset --hard be8fccf
git rm --cached themes/furniture/img/email/caret-rigth.png
git rm -r --cached themes/furniture/img/email
git reset HEAD  //for removing a particular file from the index.
git reset HEAD // and reset all file from index stage.
git co -- . //Revert all files in curr dir
git branch testing && git checkout testing //Создание и  переключение на новую ветку.
git checkout -b iss53 //Быстрое создание и переключение на новую ветку.
git branch -D SomeBranchName //Быстрое удаление.
//удалить удалённую ветку:
git push origin --delete 
//или:
git push origin :
//Пуш на текущую ветку как remote-ветку:
git push --set-upstream origin `git rev-parse --abbrev-ref HEAD`
git push origin `git rev-parse --abbrev-ref HEAD`:`git rev-parse --abbrev-ref HEAD`
git push origin serverfix:serverfix //Отправка своей ветки serverfix в origin репозиторий с созданием там такой-же ветки serverfix.
git push origin current-branch-now
git pull --rebase //Если в апстриме уже есть изменения а у нас другие.
git log --pretty=oneline //list pretty tags.
git tag -l '*' //list tags with any names.
git tag -a v1.4 -m 'my version 1.4' //create tag with annotation.
git push origin --tags //отправка с метками.
---revert to work version:-----
git stash //спрятать текущие изменения в буфер git
//сделать какието дела на другой ветке.переключится обратно и:
git stash apply //извлечь обратно спрятанные изменения из буфера git.
---how-to-merge-specific-files-from-another-branch:-------
???not working - nedd test two!!!git checkout branch_name_from_changeOf path/fromFilename/avatar.rb
//rename of branch:
git branch -m future-brunch feature-branch
//удаление веток:
git br -D help-branch
//Проверка целостности репы:
git fsck
Сейчас на всех проектах на которых гит выполнить:
find .git/ -type f -name "index.php" -delete

Комментариев нет :

Отправить комментарий

Благодарю за ваше участие!