Git training
Upcoming SlideShare
Loading in...5
×
 

Git training

on

  • 1,407 views

 

Statistics

Views

Total Views
1,407
Views on SlideShare
1,407
Embed Views
0

Actions

Likes
4
Downloads
81
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Git training Git training Presentation Transcript

    • Advanced GITConceptsby Eric Aguayo (a.k.a. ericmaster)
    • BASIC CONCEPTSWhat is GIT?● DVCSGIT Architecture● Working Copy● Staging Index (a.k.a. index)● Local Repository (a.k.a. repo or repository)● Remote Repository (a.k.a. remote)
    • GIT Architecture DEV MACHINE ORIGIN REMOTE SERVER DEV1 DEV MACHINE DEV2 DEV3 REMOTE MERGE LOCAL MACHINE INDEX WORKING REPO COPY
    • GIT ArchitectureSource: http://geeks.ms/blogs/etomas/archive/2011/01/18/git-para-dummies-pero-dummies-dummies-eh.aspx
    • GIT ARCHITECTURE git commit git add INDEX: works as a staging area between working copy and repo REPO GIT Objects ● blob: stores the dataWORKING COPY ● tree: reference other trees and blobs (directories) ● commit: references to a tree and contains all the info of a commit ● tag: mark a reference to a specific object
    • .git Directory File StructureContains all the information to recreate the treehistory|-- HEAD (pointer to the current branch)|-- config (holds the configuration preferences)|-- description (description of your project)|-- hooks/ (pre/post action hooks)|-- index (contains the index of the repo)|-- logs/ (a history of where the branches have been)|-- objects/ (the objects (commits, trees, blobs, tags)`-- refs/ (reference to important commit objects)
    • GIT most common commandsinit: Initialize a repository, initialize it empty with the --bareoption or based on existing contentbranch: Creates a new branch/Show all branchesclone: Initialize a repository and working directory from aremote repositorycheckout: This has several purposes: Change branch orrevert a file or directorystash: Temporarily saves the changes and wipe thosechanges from the index and working copy
    • GIT most common commandsstatus: Displays informational data about thelocal repository, files added to the index andcurrent branchadd: Adds changes to the staging indexcommit: Record changes into the localrepositoryrebase: Used to edit commits or join commitsinto a single commit to cleanup tree history
    • GIT most common commandsfetch: Get commits from a remote (this doesnot merge the commits or apply the commits toworking copy)merge: Merge the commits of a branch on aremotecherry-pick: Merge a specific commit from aremotepull: Merge the changes from the originrepository on the current branchpush: Push changes to a remote repository
    • GIT most common commandsrm: Deletes a file from the staging index (notdeletes the physical file by itself)reset: Remove file from index or Reset(Rollback) HEAD to a specific commitrevert: Revertir un commit (not a file)diff: Shows differences between commits orbranchesshow: Shows commit details (user, time andchanges)log: Shows commit history
    • GIT Configurationgit-config: Used to configure repository settings (/git/configfile) or global settings (.gitconfig). For example:git config --global user.name "Username"will get the following result into .gitconfig file generallylocated in your home directory[user] ... name = Username ...
    • Git ConfigurationThese are the basic settings that every developer should set in their localenvironments:git config --global user.name "Username"git config --global user.email "username@devsu.com"Also these are useful commands that will display output of some commands ina better waygit config --global color.branch autogit config --global color.diff autogit config --global color.interactive autogit config --global color.status autogit config --global format.pretty oneline
    • GIT ConfigurationIn a similar way we can set a specific repositoryconfiguration. For example, to set the remote origin as thedefault remote for the branch mastergit config branch.master.remote originwill get the following result into .git/config file[branch "master"] ... remote = origin ...
    • Create a new repositoryWe can create a new repository from any directory wherewe have write permissions. It is as simple as running thecommandgit initIn general, the origin or any repo that you want to makepublic must be a bare repository, in which case we will rungit init --bare
    • Clone a existing repositoryGIT supports different protocols to clone. Here are someexamples:git clone git@github.com:ericmaster/liquidsoapgit clone file://localhost/srv/git/liquidsoapgit clone ssh://ericmaster@192.168.1.245/srv/git/liquidsoapThe first approach we will tipically use to clone from apublic repository. Second approach we will tipically use toclone from a local machine. Third approach we will tipicallyuse to clone a repo from a server where we have anaccount set up.
    • GIT WorkflowA tipical workflow of a git repository involves the followingcommandsgit diff (see what is about to be commited)git add file1 file2 file3 (adding files to the index)git status (verify all files have been included in the staging index)git commit -m some message about this commit (record commit in therepository)You may skip "git add" if you want to add all modified files(not new created files) by running:git commit -a -m some message about this commit
    • Checking the statusThis is the info that we may get when we run the "git status"command:This line will tell us in which branch we are#On branch developmentThis line will tell us that the current branch has 12 more commit objects than what it has in its origin.#Your branch is ahead of origin/development by 12 commits.After push to the origin git status will basically say that everything is ok by the following output:#nothing to commit (working directory clean)This line will tell us that the branch at the origin branch has 10 more commit objects than what is in thecurrent branch, this may indicate that we need to pull to update our working copy#Your branch is behind of origin/development by 10 commits.In many cases we will have the following output:#Your branch and origin/development have diverged,#and have 14 and 30 different commit(s) each, respectively.This tells us that there are 14 commit objects in the current branch in your local repository that havenot been pushed yet and 30 commit objects in the same branch at its origin that has not been pulledyet.
    • Checking the statusThese lines will tell us which files have been added to the index# Changes to be committed:# (use "git reset HEAD <file>..." to unstage)## modified: file1These lines will tell us which files have been modified but not added to the index# Changes not staged for commit:# (use "git add <file>..." to update what will be committed)# (use "git checkout -- <file>..." to discard changes in workingdirectory)## modified: file1These lines will tell us that there are files that are not under tracking# Untracked files:# (use "git add <file>..." to include in what will be committed)## filex
    • Working with branchesSuppose that you have been assigned a task to create a new user profile page.You can create a separate branch for this new feature by using:git branch feature_user_profileTo list all branches usegit branch (to list all branches in the current repository)git branch -a (to list all branches including branches in tracked remotes)Output of the first command should befeature_user_profilemaster** Indicates our current branch
    • Working with branchesBesides using checkout to discard changes of a file you can use it to switchbranchesgit checkout feature_user_profileNow you can make some modifications to your working copy, add thosechanges to the index and commit, then switch back to the master branch. Youwill notice that any change you make on feature_user_profile branch will notaffect the master branch. Once we are done with the feature we can mergethose changes back to the master branch (make sure your current branch is themaster branch).git merge feature_user_profilegit cherry-pick commit_id (in case you just need to merge a specificcommit)
    • Working with remotesIn a real case, you will have to work in a feature with multiple developers (eachwith its own working copy). At some point you will need to synchronize yourcode with the rest of the developers.You could push your code to the origin so others can pull but we do not want todo that because other developers code might be affected by a work inprogress, specially if you are pushing to the "master" branch or the main branchof development. AVOID ORIGIN ORIGIN DEV1 DEV2 DEV3 DEV1 DEV2 DEV3So you will need to track each developer repository as a remote. To do this youneed to add the remote into your config.
    • Working with remotesFirst we add the remote with the following command (typically we will identifyeach remote by the owners name or a nickname easy enough to remember inthis case the remote name will be "developer2")git remote add developer2 ssh://ericmaster@devsuserver.com/home/developer2/git config remote.developer1.fetch +refs/heads/*:refs/remotes/developer2/*which will add the following entry in the .git/config file. First line adds the remoteand assigns a url so we can know where it is. Second line allows us to track theheads of the different branches of the remote.[remote "developer2"] url = ssh://ericmaster@devsuserver.com/home/developer2/ fetch = +refs/heads/*:refs/remotes/developer2/*
    • Working with RemotesNow we have everything we need to merge changes with a remote repository.First we need to get all the commit objects from the remote repo into our localrepo with the following command:git fetch developer2git fetch --all (if you want to get all the commit objects from all theremotes you are tracking)Next thing we want to do is to merge the changes into our working copy, for thiswe can use the merge commandgit merge developer2/feature_user_profilegit pull developer2/feature_user_profile (actually git pull is a shorthandfor git fetch and git merge)If everything goes right, we should see a message telling us how many fileswere changed and how many line insertions/deletions were made35 files changed, 2334 insertions(+), 309 deletions(-)
    • Dealing with conflictsAt some point you will have to deal with conflicts when you get a message likethis after running a pull or merge commandCONFLICT (content): Merge conflict in file.txtAutomatic merge failed; fix conflicts and then commit the result.There are many ways you can deal with conflicts, as well as there are manytools that will help you to deal with this. When a conflict occurs, your local repowill not be updated and the index will be left in a special state until you resolvethe conflict and push the changes. If you run git status you will see thatsuccessfully merged files are already added to the staging index ready to becommitted while conflicted files will show as# both modified: file.txtBoth modified means that there are modifications of the file in your local branchas well as the remote branch that could not be automatically merged
    • Dealing with conflictsTo resolve conflicts you need to edit the file and look for the following tags<<<< HEAD //Here goes the local code==== //Here goes the incoming remote code>>>> commit_idThere are some tools like merge-tool which can be integrated with git commandline that will display in a split screen showing the local code in the left and theremote code in the right. You can also look at the conflicts with:git diff file.txtClarity and good documentation of the code are determining factors in theprocess of resolving a commit.
    • Dealing with conflictsMany times you will be able to resolve the conflicts by simple inspection of thecode. For example, the HEAD of your branch might have a condition like thisif(c1 && c2){...}while the remote commit might have something likeif(c1 && c3){...}most likely is that this commit could be solved, depending on the case, bychanging the conflicted piece toif(c1 && c2 && c3){...} orif(c1 && c2 || c1 && c3){...}
    • Dealing with conflictsIf the case is more complex, you can run the following command get thecommit details including the author and its descriptive message and take somedecision based on that:git show commit_idSometimes, if we cannot solve the conflict by ourselves we can contact thedeveloper author of the commit to get some more information that might help usto resolve the conflict. We might even decide that is better to keep "our" or"their" modifications only. In the first case we will use the following command:git checkout --ours file.txtotherwise we can keep their changesgit checkout --theirs file.txt
    • Dealing with conflictsAfter you have resolved the conflict, you need to add the resolved file to thestaging index and commit.In the case you get stuck with the conflict and just decide to get back to thestate before the merge you can use the following commandgit reset --hard HEADbut if you already commited the merge you can usegit reset --hard ORIG_HEADwhen we add the --hard option we are discarding any changes made to index(not the working directory) while --soft option leaves the index intact
    • Checking the commit historyWhenever you find a problem or want to check for a code that was removedsome time ago, you can always check the logs to see the commit history in thecurrent branch:git loggit log file.txt (to check the log for a specific file)The git log command has many options to output the data you need in a betterway. Check the documentation for a better explanantion of these options http://schacon.github.com/git/git-log.html.You can also find which user edited a specific line of a file through the followingcommandgit blame
    • Creating aliasesThere are common aliases used in git repositories. For example I can add ashorthand for checkout withgit config --global alias.co checkoutAlso there are other common aliases that are very useful. You can add themthrough the git config command or write them directly into .gitconfig file[alias] co = checkout ci = commit st = status br = branch hist = log --pretty=format:"%h %ad | %s%d [%an]" --graph --date=short type = cat-file -t dump = cat-file -p
    • Creating TagsThe git tag command creates a static branch that we canrefer later (or revert if necessary)git tag -a v1.2 -m version 1.2To display the tags just typegit tag
    • Ignoring FilesIn most of projects there are special files, typically configuration files or contentfiles that are specific to the local working copy where they exists. We do notwant to track these files through git. To prevent these to show up in the stagingindex just add the file names to a special file named .gitignore. This special filewill typically look like this:# Ignore any file named foo.txt.foo.txt# Ignore (generated) html files,*.html# except foo.html which is maintained by hand.!foo.html# Ignore objects and archives.*.[oa]If you are already tracking a file through git you can remove it by running thefollowing command and the commit# git rm --cached foo.txt
    • Rebasinggit rebase can be used to cleanup the branches tree history. Instead of mergingyour main development branch into your current feature work branch yourebase the development branch:git rebase developmentgit rebase -i development (to interactively add commits)which will discard your commit(s) and reapply them as patches after the HEADof the development branch. If in any case you get a conflict, use the followingcommand after resolving the conflictgit rebase --continuealso you may cancel the rebase process bygit rebase --abort
    • Stashing changesIn any project, you may often want to pull to update your working copy but donot want to commit your code yet. Git will not let you pull if the incoming commit(s) belongs to a file that you are editing. In this case you can temporarily saveyour changes and "revert" to the HEAD of your repo with the followingcommandgit stashThis is also useful if you need to perform a quick fix without needing to commitor discard the changes of your current task, or even create a new branch. Onceyou are done with the changes, just run the following command to get yoursave changes backgit stash pop
    • HooksGIT allows you to implement hooks to execute certainevents occur in your repo. For example you might need tochange some setting files in your working directory beforeyou switch to another branch. This can be implemented in ahook.Under the .git/hooks directory you can find files that youcan edit to perform processing on determined events. Forexample you can use the file.git/hooks/post-committo notify to some system that a commit was made
    • GIT ToolsSet up public repositories● gitosis● gitolite (recommended by the community, see http://www.llamabyte. com/2011/upgrading-to-gitolite-from-gitosis/ for advantages)Merge tools:● Open Source ○ kdiff3 ○ tkdiff ○ xxdiff● Free from a commercial vendor ○ SourceGear DiffMerge ○ FileMerge/opendiff ○ Perforce Visual Merge Tool (P4Merge)● Commercial ○ Araxis Merge (Windows | Mac OS X) ○ Beyond Compare ○ Guiffy SureMerge
    • Common issuesI deleted a file how to commit that change to my local repo?There are two options:git add -A .git commit -morgit commit -a -m.Note: git commit -a -m does NOT add new created files to the staging index
    • Common issuesI made a commit but I want to correct the message or forgot to add myusername or emailTo correct the message of the last commit use:git commit --amend -m correct messageTo correct the message of commit previous to the HEAD commit you can use:git rebase -i commit_id^then change "pick" to "edit" in the interactive mode for commit_id, make thechanges and then rungit commit --amendgit rebase continue
    • Common issuesI need to revert a commit given by a specific commit_idJust run the following commandgit revert commit_idthis will revert the commit object and commit the revert.Add the --no-commit option to leave the changes in thestaging index for any further modification before commitNote: this might lead to conflicts if the subsequent commitshave overlapped changes.
    • Common issuesI need to work in team with a developer who created a new branch for aspecific feature. How do I clone that branch over my current workingcopy?After adding the remote "developer", just run the following commandgit checkout --track -b new_feature developer/new_featurethis will create the new repo and add the necessary branch settings in the .git/config file
    • GIT Workshopssh://gitworkshop@192.168.1.245/srv/gitworkshop/not_bare_repossh://gitworkshop@192.168.1.245/srv/gitworkshop/repo