O Git é uma ferramenta para controle e gerenciamento de código fonte, inicialmente projetado e desenvolvido por Linus Torvalds para o desenvolvimento do kernel Linux, porém adotado por muitos outros projetos posteriormente devido a suas características. Nesta apresentação teremos uma introdução ao Git e seus principais casos de uso dentro do fluxo de trabalho de um desenvolvedor. O mínimo que você precisa saber sobre GIT, especialmente se está iniciando na área do desenvolvimento de software.
Palestra de Fabio Beneditto, apresentada no Tchelinux Bento Gonçalves 2017.
* Link original do autor: https://www.slideshare.net/fabiobeneditto/git-para-principiantes
* Link do perfil do autor no SlideShare: https://www.slideshare.net/fabiobeneditto
Fabio Beneditto é entusiasta de Software Livre desde 1999, quando se aventurou a instalar pela primeira vez um Conectiva Linux Guarani em um i486 SX 50Mhz com 4 Mb de RAM. Depois disso, nunca mais foi o mesmo.
5. Motivação
● Esse é o Git. Ele mostra nosso
trabalho em projetos através de
uma árvore distribuída.
● Legal! E como vamos usar ele?
● Não faço ideia. Apenas decore
esses comandos e digite-os para
sincronizar tudo. Se der erro,
salve seu trabalho em algum
lugar, apague o projeto e faça
uma nova cópia.
(tradução livre) - Fonte: https://xkcd.com/1597/
6. Por que usar Controle dePor que usar Controle de
Versão?Versão?
7. Por que usar Controle de Versão?
● Manter histórico de alterações no código
– Autores (Quem?)
– Data das alterações (Quando?)
– Motivo das alterações (Por que?)
● Facilitar a colaboração
– pessoas podem trabalhar juntas
● Auxiliar na identificação e resolução de
problemas
9. O que é GIT?
●
Sistema de controle de versão distribuídoSistema de controle de versão distribuído
●
Criado por Linus Torvalds em 2005Criado por Linus Torvalds em 2005
●
Simples e rápidoSimples e rápido
– ArmazenaArmazena snapshotssnapshots
●
É LivreÉ Livre
10. Utilização básica de GitUtilização básica de Git
““Talk is Cheap: show me the code”Talk is Cheap: show me the code”
11. Configurando o cliente Git
$ git config –-global user.name "John Doe"$ git config –-global user.name "John Doe"
$ git config –-global user.email "john@doe.com"$ git config –-global user.email "john@doe.com"
$ cat .gitconfig$ cat .gitconfig
[user][user]
name = John Doename = John Doe
email = john@doe.comemail = john@doe.com
12. Criando um repositório
$ mkdir Projeto$ mkdir Projeto
$ cd Projeto$ cd Projeto
$ git init$ git init
Initialized empty Git repository in Projeto/.git/Initialized empty Git repository in Projeto/.git/
13. Verificando alterações
$ vim hello.md$ vim hello.md
$ git status$ git status
On branch masterOn branch master
Initial commitInitial commit
Untracked files:Untracked files:
(use "git add <file>..." to include in what will be committed)(use "git add <file>..." to include in what will be committed)
hello.mdhello.md
nothing added to commit but untracked files present (use "git add" tonothing added to commit but untracked files present (use "git add" to
track)track)
15. Adicionando arquivos ao index
$ git add hello.md$ git add hello.md
$ git status$ git status
On branch masterOn branch master
Changes to be committed:Changes to be committed:
(use "git reset HEAD <file>..." to unstage)(use "git reset HEAD <file>..." to unstage)
modified: hello.mdmodified: hello.md
16. Adicionando arquivos ao index
““IndexIndex” é a” é a stage area:stage area:
●
um simples arquivo que armazena informações sobreum simples arquivo que armazena informações sobre
o que irá em seu próximoo que irá em seu próximo commitcommit. Você, durante o. Você, durante o
ciclo:ciclo:
– Modifica arquivos no seu diretório de trabalho.Modifica arquivos no seu diretório de trabalho.
– Seleciona os arquivos, adicionandoSeleciona os arquivos, adicionando snapshotssnapshots
deles para odeles para o indexindex..
– Faz umFaz um commitcommit, levando os arquivos como eles, levando os arquivos como eles
estão noestão no indexindex e os armazena permanentementee os armazena permanentemente
17. Fazendo seu primeiro commit
$ git commit -m "Versão Inicial de hello.md"$ git commit -m "Versão Inicial de hello.md"
[master (root-commit)[master (root-commit) f480dd9f480dd9] Versão Inicial de hello.md] Versão Inicial de hello.md
1 file changed, 3 insertions(+)1 file changed, 3 insertions(+)
create mode 100644 hello.mdcreate mode 100644 hello.md
18. Fazendo os demais commits
$ vim hello.md$ vim hello.md
$ git add hello.md$ git add hello.md
$ git commit -m "Bloco Extra em hello.md"$ git commit -m "Bloco Extra em hello.md"
[master[master 97e567d97e567d] Bloco Extra em hello.md] Bloco Extra em hello.md
1 file changed, 1 insertion(+), 1 deletion(-)1 file changed, 1 insertion(+), 1 deletion(-)
19. Fazendo os demais commits
$ vim hello.md$ vim hello.md
$ git add -p$ git add -p
diff --git a/hello.md b/hello.mddiff --git a/hello.md b/hello.md
index 9cff701..aa1314b 100644index 9cff701..aa1314b 100644
--- a/hello.md--- a/hello.md
+++ b/hello.md+++ b/hello.md
@@ -4,3 +4,5 @@ Exemplo de como fica um arquivo no Git@@ -4,3 +4,5 @@ Exemplo de como fica um arquivo no Git
## Como fazer## Como fazer
Adicionando uma segunda linha e um ponto.Adicionando uma segunda linha e um ponto.
++
+...e mais uma+...e mais uma
Stage this hunk [y,n,q,a,d,/,e,?]?Stage this hunk [y,n,q,a,d,/,e,?]?
21. Use mensagens explicativas!
$ vim hello.md$ vim hello.md
$ git add hello.md$ git add hello.md
$ git commit$ git commit
[] Descricao Curta[] Descricao Curta
Descrição Detalhada do CommitDescrição Detalhada do Commit
# Please enter the commit message for your changes. Lines starting# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.# with '#' will be ignored, and an empty message aborts the commit.
# On branch master# On branch master
# Changes to be committed:# Changes to be committed:
# modified: hello.md# modified: hello.md
##
24. Reescrevendo o último commit
$ vim hello.md$ vim hello.md
$ git add hello.md$ git add hello.md
$ git commit --amend$ git commit --amend
[master[master dd259b4dd259b4] Bloco Extra em hello.md] Bloco Extra em hello.md
Date: Sun Sep 17 15:36:51 2017 -0300Date: Sun Sep 17 15:36:51 2017 -0300
1 file changed, 3 insertions(+), 1 deletion(-)1 file changed, 3 insertions(+), 1 deletion(-)
25. Reescrevendo o último commit
$ git commit --amend$ git commit --amend
Bloco Extra em hello.mdBloco Extra em hello.md
# Please enter the commit message for your changes. Lines starting# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.# with '#' will be ignored, and an empty message aborts the commit.
##
# Date: Sun Sep 17 15:36:51 2017 -0300# Date: Sun Sep 17 15:36:51 2017 -0300
##
# On branch master# On branch master
# Changes to be committed:# Changes to be committed:
# modified: hello.md# modified: hello.md
26. Removendo o último commit
$ git reset --hard HEAD~1$ git reset --hard HEAD~1
HEAD is now atHEAD is now at f480dd9f480dd9 Versão Inicial de hello.mdVersão Inicial de hello.md
27. Descartando alterações antes do
commit
$ git checkout -p$ git checkout -p
diff --git a/hello.md b/hello.mddiff --git a/hello.md b/hello.md
index aba21ac..2cc5dc2 100644index aba21ac..2cc5dc2 100644
--- a/hello.md--- a/hello.md
+++ b/hello.md+++ b/hello.md
@@ -1,3 +1,5 @@@@ -1,3 +1,5 @@
# Hello World# Hello World
Exemplo de como fica um arquivo no GitExemplo de como fica um arquivo no Git
++
+Adicionando uma terceira linha+Adicionando uma terceira linha
Discard this hunk from worktree [y,n,q,a,d,/,e,?]?Discard this hunk from worktree [y,n,q,a,d,/,e,?]?
28. Listando commits realizados
$ git log$ git log
commitcommit f480dd9f480dd96974c5eafea736a4286db353172e960e3 (HEAD -> master)6974c5eafea736a4286db353172e960e3 (HEAD -> master)
Author: Fabio Beneditto <fabiobeneditto@gmail.com>Author: Fabio Beneditto <fabiobeneditto@gmail.com>
Date: Sun Sep 17 15:02:48 2017 -0300Date: Sun Sep 17 15:02:48 2017 -0300
Versão Inicial de hello.mdVersão Inicial de hello.md
$ git log$ git log --pretty=oneline--pretty=oneline
f480dd9f480dd96974c5eafea736a4286db353172e960e3 (HEAD -> master) Versão6974c5eafea736a4286db353172e960e3 (HEAD -> master) Versão
Inicial de hello.mdInicial de hello.md
$ git log$ git log --oneline--oneline
f480dd9f480dd9 (HEAD -> master) Versão Inicial de hello.md(HEAD -> master) Versão Inicial de hello.md
29. Visualizando detalhes de um
commit
$ git show$ git show f480dd9f480dd9
commitcommit f480dd9f480dd96974c5eafea736a4286db353172e960e3 (HEAD -> master)6974c5eafea736a4286db353172e960e3 (HEAD -> master)
Author: Fabio Beneditto <fabiobeneditto@gmail.com>Author: Fabio Beneditto <fabiobeneditto@gmail.com>
Date: Sun Sep 17 15:02:48 2017 -0300Date: Sun Sep 17 15:02:48 2017 -0300
Versão Inicial de hello.mdVersão Inicial de hello.md
diff --git a/hello.mddiff --git a/hello.md b/hello.mdb/hello.md
new file mode 100644new file mode 100644
index 0000000..aba21acindex 0000000..aba21ac
--- /dev/null--- /dev/null
+++ b/hello.md+++ b/hello.md
@@ -0,0 +1,3 @@@@ -0,0 +1,3 @@
+# Hello World+# Hello World
++
+Exemplo de como fica um arquivo no Git+Exemplo de como fica um arquivo no Git
30. Exibindo diferenças entre
commits
$ git diff$ git diff f480dd9f480dd9....cf8cc84cf8cc84
diff --git a/hello.md b/hello.mddiff --git a/hello.md b/hello.md
index aba21ac..2cc5dc2 100644index aba21ac..2cc5dc2 100644
--- a/hello.md--- a/hello.md
+++ b/hello.md+++ b/hello.md
@@ -1,3 +1,5 @@@@ -1,3 +1,5 @@
# Hello World# Hello World
Exemplo de como fica um arquivo no GitExemplo de como fica um arquivo no Git
++
+Adicionando uma terceira linha+Adicionando uma terceira linha
32. Fazendo merge de branches
$ git checkout master$ git checkout master
Switched to branch 'master'Switched to branch 'master'
$ git merge nova-feature$ git merge nova-feature
Updating 3e9fc43..ce48a52Updating 3e9fc43..ce48a52
Fast-forwardFast-forward
hello.md | 1 +hello.md | 1 +
1 file changed, 1 insertion(+)1 file changed, 1 insertion(+)
commit f480dd96974c5eafea736a4286db353172e960e3commit f480dd96974c5eafea736a4286db353172e960e3
$ git log --oneline$ git log --oneline
ce48a52 (HEAD -> master, nova-feature) Subtitulo incluidoce48a52 (HEAD -> master, nova-feature) Subtitulo incluido
3e9fc43 Descricao Curta da tarefa3e9fc43 Descricao Curta da tarefa
cf8cc84 Bloco Extra em hello.mdcf8cc84 Bloco Extra em hello.md
f480dd9 Versão Inicial de hello.mdf480dd9 Versão Inicial de hello.md
33. Utilização de repositóriosUtilização de repositórios
remotos com Gitremotos com Git
““Já tenho um repositório. #comofas ?”Já tenho um repositório. #comofas ?”
34. Clonando um repositório
$ mkdir Projeto$ mkdir Projeto
$ cd Projeto$ cd Projeto
$ git clone $ git clone
https://gitlab.com/fabiobeneditto/tchelinux-https://gitlab.com/fabiobeneditto/tchelinux-
git.git Tchelinuxgit.git Tchelinux
Cloning into 'Tchelinux'...Cloning into 'Tchelinux'...
done.done.
35. Atualizando um repositório local
$ cd Tchelinux/$ cd Tchelinux/
$ git checkout master$ git checkout master
$ git pull$ git pull --rebase--rebase
36. Listando remotes de repositório
$ cd Tchelinux/$ cd Tchelinux/
$ git remote$ git remote
37. Adicionando remotes ao
repositório
$ cd Tchelinux$ cd Tchelinux
$ git remote add origin $ git remote add origin
git@gitlab.com:fabiobeneditto/tchelinux-git.gitgit@gitlab.com:fabiobeneditto/tchelinux-git.git
38. Enviando tudo para o servidor
remoto
$ git push -u origin$ git push -u origin –all–all
Counting objects: 12, done.Counting objects: 12, done.
Delta compression using up to 4 threads.Delta compression using up to 4 threads.
Compressing objects: 100% (8/8), done.Compressing objects: 100% (8/8), done.
Writing objects: 100% (12/12), 1.28 KiB | 653.00 KiB/s, done.Writing objects: 100% (12/12), 1.28 KiB | 653.00 KiB/s, done.
Total 12 (delta 2), reused 0 (delta 0)Total 12 (delta 2), reused 0 (delta 0)
To gitlab.com:fabiobeneditto/tchelinux-git.gitTo gitlab.com:fabiobeneditto/tchelinux-git.git
* [new branch] master -> master* [new branch] master -> master
* [new branch] nova-feature -> nova-feature* [new branch] nova-feature -> nova-feature
Branch master set up to track remote branch master from origin.Branch master set up to track remote branch master from origin.
Branch nova-feature set up to track remote branch nova-feature fromBranch nova-feature set up to track remote branch nova-feature from
origin.origin.