-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit-commands.txt
More file actions
298 lines (203 loc) · 13.9 KB
/
Copy pathgit-commands.txt
File metadata and controls
298 lines (203 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
https://www.coursera.org/learn/introduction-git-github
https://learngitbranching.js.org/?locale=uk
https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/incorporating-changes-from-a-pull-request/about-pull-request-merges
VCS (Version Control System)
commitId = Hash (algoritm SHA1) 40character string, keeps data consistent
git init //empty git repository in current directory
git status //info about working tree and pending changes
git config --global user.email "email@mail.com"
git config user.name "myname"
git config --global credential.helper cache
git config --list
git config --list --show-origin
git config user.name
git add index.html
git add .
git add -p // which changes will be staged, review patches
git commit -m "commit comment" //short message
git commit -a -m "comment" // -a skip staging area
git commit --amend // owerwrites previous LOCAL commit, add changes to files and comment without new commit, changes commitID
git log -p // produces patch text
git log -2
git log -p -2 // -p lets see the patch created by the commit, -2 limits the output to two last entries
git log --stat // how many lines added or remowed
git log --graph --oneline // summarized view of the commit history for a repo
git show commitID // shows various objects
git log origin/master
git diff // difference in various commits
git diff --staged // show all staged files compared to the named commit
git rm file //delete unneeded file
git mv old_file new_file //rename file
echo .DS_Store > .gitignore // add file to .gitignore
git branch // list of branches
git branch branchName //create new branch
git checkout -b branchName // crate new branch and checkout to it
git branch -d branchName // delete branch
git branch -r // look at remote branches that Git repo is currently tracking
origin/HEAD -> origin/main
origin/main
git merge branchName // combines current branch and brunchName in new commit
git merge --abort // stop merge and reset files
git clone url // get local copy of remote repo
git push
git push -f // forced an update
git pull = git fetch + git merge // of curretn branch
git fetch // downloads cpecific objects
git remote // list remote repos
git remote -v // look for the configuration for remote repo in directory with repo
origin https://github.com/natata-tutorial/kottans-frontend.git (fetch)
origin https://github.com/natata-tutorial/kottans-frontend.git (push)
git remote show origin // show info about repo
git remote update // fetchs the most up to date objects
git remote add origin URL
git push origin HEAD
Перемещение по дереву коммитов
git checkout branchName //switcha to a branch
git checkout filename //discarding changes in working directory
git checkout main^ //Перемещение на один коммит назад ^, main^ означает "первый родитель ветки main"
git checkout main^2 - второй родитель мерджевого коммита
git checkout HEAD~4 //Перемещение на несколько коммитов назад ~<num>
Перемещение ветки (branch forcing)
git branch -f main HEAD~3 // относительная ссылка, Переместит (принудительно) ветку main на три родителя назад от HEAD.
git checkout HEAD~^2~2
Отмена изменений
git clean -f #untracked
git restore . #modified
git restore --staged . #staged
git reset #staged
git reset HEAD fileName // unstage file
git reset HEAD~ #commited
git reset //отменяет изменения, перенося ссылку на ветку назад, на более старый коммит. Это своего рода "переписывание истории"; git reset перенесёт ветку назад, как будто некоторых коммитов вовсе и не было. На локальных ветках!!!
git reset HEAD~1
git revert // Чтобы отменить изменения и поделиться отменёнными изменениями с остальными, надо использовать git revert. Появился новый коммит. Дело в том, что новый коммит C2' просто содержит изменения, полностью противоположные тем, что сделаны в коммите C2. После revert можно сделать push и поделиться изменениями с остальными.
git revert HEAD
Перемещение изменений
git cherry-pick <Commit1> <Commit2> <...> //способ сказать, что ты хочешь копировать несколько коммитов на место, где сейчас находишься (HEAD). когда точно известно, какие коммиты нужны (и известны их точные хеши)
Git Interactive Rebase
опция -i - Git откроет интерфейс просмотра того, какие коммиты готовы к копированию на цель rebase (target). Также показываются хеши коммитов и комментарии к ним, так что можно легко понять что к чему.
git rebase -i HEAD~4
git rebase main bugFix
Таг
git tag v1 C1 //назвали тег v1 и заставили его ссылаться на C1 явным образом. Если конкретный коммит не указан, гит пометит тегом HEAD
git describe <ref> //Где ref — это что-либо, что указывает на конкретный коммит. Если не указать ref, то git будет считать, что указано текущее положение (HEAD).
<tag>_<numCommits>_g<hash>
Где tag – это ближайший тег в истории изменений, numCommits – это на сколько далеко мы от этого тега, а hash – это хеш коммита, который описывается.
Git Fetch
связывается с указанным удалённым репозиторием и забирает все те данные проекта, которых у вас ещё нет, при этом...
у вас должны появиться ссылки на все ветки из этого удалённого репозитория (например, o/main)
Фактически, git fetch синхронизирует локальное представление удалённых репозиториев с тем, что является актуальным на текущий момент времени.
Важно отметить, что команда git fetch забирает данные в ваш локальный репозиторий, но не сливает их с какими-либо вашими наработками и не модифицирует то, над чем вы работаете в данный момент.
git fetch
git cherry-pick o/main
git rebase o/main
git merge o/main
Процедура скачивания (fetching) изменений с удалённой ветки и объединения (merging) настолько частая и распространённая, что git предоставляет вместо двух команд - одну! Эта команда - git pull.
git fetch
git rebase origin/main
git push
git pull
git push
git fetch
git merge origin/main
git push
git pull --rebase
git push
Мы выполним checkout для новой ветки foo и укажем ей, чтобы она отслеживала main с удалённого репозитория.
git checkout -b foo original/main
git pull
git branch -u o/main foo // Другой способ указать ветке отслеживать удалённую ветку — это просто использовать команду git branch -u.
вы укажете ветке foo следить за o/main. А если вы ещё при этом находитесь на ветке foo, то её можно не указывать:
git branch -u o/main
git branch -u o/main foo
git commit
git push
git push <удалённый_репозиторий> <целевая_ветка>
git push origin main
дословный перевод с английского будет таким:
Перейди в ветку с именем "main" в моём локальном репозитории, возьми все коммиты и затем перейди на ветку "main" на удалённом репозитории "origin.". На эту удалённую ветку скопируй все отсутствующие коммиты, которые есть у меня, и скажи, когда ты закончишь.
git push origin <источник>:<получатель>
git push origin foo^:main //git видит в foo^ не что иное, как местоположение, закачивает все коммиты, которые не присутствуют на удалённом репозитории, и затем обновляет получателя.
git push origin main:newBranch
git fetch origin foo
Git отправится в ветку foo на удалённом репозитории, соберёт с собой все коммиты, которые не присутствуют локально, и затем поместит их в локальную ветку под названием o/foo. мы скачиваем только коммиты с ветки foo и помещаем их в o/foo.
git fetch origin foo~1:bar
Теперь у нас <источник> - это место на удалённом репозитории, а <получатель> - место в локальном репозитории, в который следует помещать коммиты. Аргументы в точности до наоборот повторяют git push, и немудрено, ведь теперь мы переносим данные в обратном направлении!
git push origin :foo //мы удалили ветку foo в удаленном репозитории, попытавшить протолкнуть(git push) в неё "ничего"
git fetch origin :bar //мы попытаемся притянуть изменения(git fetch) из "ничего" к нам в локальный репозиторий, то это создаст у нас новую ветку
Как мы помним, git pull сначала выполняет git fetch, а следом сразу git merge с той веткой, в которую притянулись обновления командой fetch. Другими словами, это все равно, что выполнить git fetch с теми же аргументами, которые вы указали для pull, а затем выполнить git merge с веткой, указанной в аргументе <приемник> команды pull.
git pull origin bar~1:bugFix то же, что:
git fetch origin bar~1:bugFix; git merge bugFix
git pull origin main:foo //Мы создали новую ветку foo в локальном репозитории, скачали на неё изменения с ветки main удаленного репозитория, а затем слили эту ветку с веткой bar, на которой мы находились!
git remote -v
git remote show origin
git branch -r // read only branches
git config --global credential-helper cache
pull-merge-push workflow
git add -p
git commit -m "message"
git push // rejected
git pull // conflict
git log --graph --oneline --all // three-way merge
git log -p origin/master // resolve conflict, save and close
git add file
git commit
git push // success
git log --graph --oneline
pushing remote branches
git checkout -b refactor
//file edits
git commit -a -m "changes in branch"
git push -u origin refactor // push as separate branch to let others check how changes work
rebasing changes (feature branch)
git checkout master
git pull // came college changes
git log --graph --oneline --all // don't whant three-way merge, whant linear history
git checkout refactor
git rebase master //success
git log --graph --oneline // linear history
git checkot master
git git merge refactor // fast-forward merge
git push --delete origin refactor // get rid of remote branch
git branch -d refactor // get rid of local branch
git push
rebase 2 (changes on master)
git commit -a -m "msg"
git fetch // get college changes
git rebase origin/master // conflict
//fix conflict
git add file
git rebase --continue
git log --graph --oneline
git push
Best Practices for Collaborating
- synchronize branches before start any work, pull before doing any work
- avoid having very large changes
- use separate feature branch
- merge master to feature branch to reduce the difference
- latest version of the project in master branch, stable version on a separate branch
- don't rebase changes that were pushed to remote repos
- good commit messages
Pull Request Workflow
- create a fork in GitHub
- git clone forkURL
cd forkname
git checkout -b newBranchName
create file
git add Readme.md
git commit -m "Add readme"
gi push -u origin add-readme
Squashing changes
we have two commits
git rebase -i main
in VSCode change pick to squash
save and close
Select and edit message, save and close
git show // two chnges combined in one commit
git status
On branch add-readme
Your branch and 'origin/add-readme' have diverged,
and have 1 and 2 different commits each, respectively.
git log --graph --oneline --all -4
git push // rejected
git push -f // replace old commits with the new one
git log --graph --oneline --all -4 // only one commit left