• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Git crash course for Visual Studio devs
 

Git crash course for Visual Studio devs

on

  • 4,577 views

Since its inception in 2005 Git gained a huge traction and passed the borders of open source well into Microsoft developer's territory, see for example the success of Github. The Visual Studio 2012 ...

Since its inception in 2005 Git gained a huge traction and passed the borders of open source well into Microsoft developer's territory, see for example the success of Github. The Visual Studio 2012 Update 2 adds native support for Git in Visual Studio, but don't think that this will be enough to master it, as it's notoriously a though subject that scares the most consumed command line wizards.

Statistics

Views

Total Views
4,577
Views on SlideShare
4,577
Embed Views
0

Actions

Likes
3
Downloads
0
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

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 crash course for Visual Studio devs Git crash course for Visual Studio devs Presentation Transcript

    • itcampro@ itcamp13# Premium conference on Microsoft technologiesGit crash course for VisualStudio devsAlessandro PilottiCloudbase SolutionsMVP ASP.Net / IIS@alexpilotti
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &MobileHuge thanks to our sponsors!
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• Why Git?• Basics• Visual Studio integration• Remote repositories• Branching• Merging and rebasing• Forks and github, bitbucket, etc• Continuous deployment• Gerrit• Azure supportAgenda
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• Why do we need an ENTIRE session on a VCSinstead of talking about code? • Previous VCS are so simple:– CVS– Subversion– Sourcesafe (D’oh)• In short, it’s because there’s way more thanthe usual commit / checkout thing Why Git?
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• Developed initially by Linus Torvalds in 2005– Used for the Linux Kernel– GPLv2– Multiplatform (Linux, Windows, OSX, FreeBSD)• Some design goals:– Fast and efficient– Support for non linear development– Distributed– Easy publishing– Garbage collectionGit
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• In most cases, you just start work on aproject using it – In my case, OpenStack• Most OSS projects are hosted on github– CodePlex supports Git as well• Ease to branch, merge, fork• Once you start using it, it’s hard to go backWhy should I use it?
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• http://msysgit.github.io/– Command line• http://windows.github.com/• Visual Studio 2012 Update 2• NetBeans• Eclipse• TortoiseGit• etcWindows clients
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• A Git repository is a directory tree containingyour project(s)– A hidden directory “.git” contains all the Git stuff• Start a repo from scratch:– git init• Cloned from an existing repo:– git clonehttps://github.com/cloudbase/cloudbase-initBasics
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• Files are either:– Staged (git knows about them)– Untracked (git doesn’t care about them)• To stage a file / directory:– git add path• To unstage and delete a file:– git rm path• To unstage w/o deleting it:– git rm –cached pathStaging files
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• As simple as:– git commit –a –m “Don’t forget the commitmsg”• To commit a file:– git commit -m msg path• Being a distributed VCS, a commit is onlylocal• Do small commits, atomic and cohesive– With a clear commit message– A VCS is not a backup tool Commit
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• You can look at the history for the currentbranch with a simple:– git log– git log --pretty=oneline• To see your staged (uncommitted) changes:– diff format– git diff• To see the differences between two commits:– git diff commit1 commit2Git log, show and diff
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• With checkout you can get a file or a workingcopy of your repository:– E.g.: to undo your work to the latest commit:– git checkout (entire repo)– git checkout file (single file only)• To checkout a file to a previous version:– git checkout commitref file– E.g.: to get the previous version:• git checkout HEAD^ file• git checkout HEAD^checkout
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• git config --global user.name ”My Name”• git config --global user.email myuser@mydomain.com• git config --global color.ui true• git config --global core.editor notepad++– Note: add the editor to your path first (elevated console):• SETX PATH “%PATH%;%ProgramFiles% (x86)Notepad++” /M– Even better, getting used to vi is not so terrible • git config --global core.autocrlf true– Values: true, input, false– Set true if you work on multiplatform projects– See .gitattributes later for this as wellGlobal settings
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &MobileGit and Visual Studio 2012
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• VS 2012 Update 2 required• Install Visual Studio Tools for Git• Tools -> Options -> Source Control– Choose “Microsoft Git provider”• Open “Team Explorer”– View -> Team Explorer• You can use also regular git commands in– Package Manager ConsoleGit and Visual Studio 2012
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• Connect to Team Projects (socket icon)– Clone– Set the remote repo URL– Specify a local pathVS 2012 Clone a repo
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• RC available now• http://blogs.msdn.com/b/visualstudioalm/archive/2013/05/07/release-candidate-to-visual-studio-update-3-now-available.aspx• Bug fixes• Git TFS continuous integration supportVS 2012 Update 3
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &MobileVS2012 U3 Git
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &MobileTFS + GitTFS supports GIT natively! http://bit.ly/Z1RkcVSignup for a free account here:https://tfs.app.visualstudio.com/_account/Signup
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesVS2012 GIT DEMO
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• git contains all the info related to your repoin “.git/”• Your files (working copy), are simply a humanreadable copy of the files – Bare repositories have no working copy• The Index contains info about staged files• File contents are stored into blobs• Other objects include trees (the filesystemrefresentation) and commits• Every object is identified with a SHA1 hashA bit of internals
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• You can refer to commits with their SHA1hash or with a shorter unique prefix, e.g.:– git log e46bf2165f29f579051b8e12ebe63e5512205610– git log e46bf2• Or you can refer to a commit using areference:– every branch has a “head” identifying the lastcommit• git checkout branchnameRefs
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• HEAD is a special symbolic link pointing to thehead of the current branch• You can do some “arithmetic” with refs:– ^ points to the previous commit– ~n points to the nth previous commit– HEAD^^^ the 3rd commit before HEAD– HEAD~3 (same as the above example)• Note: use (quotes) “HEAD^” in the Windowscmd promptRefs
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• A tag is simply a friendly name for a commit– git tag v1.0 HEAD• Annotated tags are stored as full objects:– git tag –a v1.0 –m “Version 1.0” HEAD• Don’t confuse tags with a branchesTags
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• Git is a distributed VCS• You can “sync” your local copy with remotecopies anytime, by either “pull” or “push”changes• Git has no concept of a “server”– Repos form a peer network• It’s useful anyway to elect an “authoritative”repository. E.g.:– A repo on github, bitbucket, etc– The project lead developer’s repoRemote repositories
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• A remote is simple a name and an url• List remotes:– git remote• Add a remote:– git add origin https://github.com/openstack/nova.git• Note: this will track all remote branches, use –t <branchname> tolimit• Protocols to access the remote repo can be:– Local filesystem, HTTP/HTTPS, git, rsync– Local fileystem on Windows:• file:///c/your/path/repo.gitConfiguring remotes
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• Remove a remote:– git remote rm name• Changing a remote url is a frequentoperation:– git remote set-url <newurl> <remote_name>• Cleaning stale remote tracking branches– git remote prune <remote_name>Configuring remotes
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• A bare repository doesn’t have a workingcopy of your content• Use it when you create an authoritative“server” repo• By convention bare repo folder names end it“.git” e.g.: “myrepo.git”• git init --bareBare repositories
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• A typical operation consists in cloning aremote repository (will set the proper remoteas well):– git clone <url>• To update a local repository with remotecommits:– git pull• This is a shortcut for git fetch and git mergeFETCH_HEADClone / pull
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• Updating a remote repository consists in:– git push <remote> <branch>– git push origin master• Note: you must first make sure that youpulled all the remote commits first!• More on merging / rebasing later!Push
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• Git was created to make branching andmerging as easy as possible.• “master” is the default branch• From an application lifecycle standpoint wecan define two types of branches:– Long lived• Typically major releases– Short lived• Bug fixes, dev experiments, etc• Git makes no difference of courseBranches
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• Creating a branch is simply:– git chekout –b name– Shortcut for git branch name and git checkout name• Switch to a different branch:– git checkout name– This will also change the working directory contents to reflectthe branch commits!!• To list existing branches:– git branch– The active branch is marked with “*”• To remove a branch:– git branch –d nameBranches
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &MobileHow does it look like?A BCDmasternew-featureEFexperimentmaster commits: A, B, Dnew-feature commits: A, B, C, Eexperiment commits : A, B, C, E, F
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• In most cases at some point you’d like to mergethe content of a branch into another• For example, you develop a new feature andonce it’s done tested and reviewed you want tomerge it in the master branch• git-merge merges a branch into the current one:– git checkout master– git merge new-featureMerge
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &MobileHere’s how a merge looks likeA BCDmasternew-featureEFexperimentGmaster commits: A, B, D, C, E, G
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• What happens when the same file has beenchanged in two branches?• Git is very smart in applying different commitpatches to the same source when lines donot overlap (e.g. 2 different methods)• But sometimes you just have to handleconflicts, it’s a hard life Conflicts
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobilegit merge branch_nameCONFLICT (content): Merge conflict in test.txtAutomatic merge failed; fix conflicts and thencommit the result.D’oh!Edit the conflicting files…git add filesgit commit -aConflicts
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• You can also rollback the merge with:– git merge –abort• A merge happens also when you pull a remote branch– The resolution process is the same• Once the merge succeeds, you can delete the mergedbranch if you don’t need it anymore• You can also keep on working on the merged branch andmerge it again later• When you merge a branch w/o conflicts (fast-forwarding)by default a merge commit is not created. This can bechanged with git merge –no-ff etcMerge notes
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• Rebasing a branch consists in taking thecommits of another branch and applyingthem on the current branch before anycommit added to the current branch.• Typically this is used to bring a local branchup to date with remote commits• Merge vs rebase can create a bit of confusionto usersRebase
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &MobileRebase exampleA BCDmasternew-featureEFgit checkout new-featuregit rebase masterNote: rebased commits have a new hash!
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &MobileCONFLICT (content): Merge conflict in test3.txtFailed to merge in the changes.Patch failed at 0002 asdasddThe copy of the patch that failed is found in:/Users/anorex/Downloads/testgit/.git/rebase-apply/patchWhen you have resolved this problem, run"git rebase --continue".If you prefer to skip this patch, run"git rebase --skip" instead.To check out the original branch and stop rebasing, run "git rebase --abort".Rebase conflicts• Similar to resolving a merge
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• What if you just one to pick a single commitfrom another branch without having tomerge / rebase the entire branch?• E.g. backporting a bug fix from v1.2 to v1.1• git cherry-pick commit1• git cherry-pick start..endCherry picking
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &MobileCherry-pick exampleA BCDmasternew-featureEFD’git checkout new-featuregit cherry-pick DNote: cherry-picked commits have a new hash!
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• Sometimes you might need to remove or reordercommits (locally only don’t do that after a push!)• This can be done interactively with git rebase:• git rebase –i “HEAD~4”• Just remove or reorder the lines in the editor:– pick 37c449c My first commit– pick 3982180 My second commit– pick 6055a10 My last commitReordering and removing commits
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• There’s a good chance that your dev branchcommits will be a mess • Git gives you a chance to clean them up beforepushing them upstream using git rebase, e.g.:• git rebase –i HEAD~3– pick 37c449c My first commit– squash 3982180 My second commit– squash 6055a10 My last commitSquashing
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• Changing the content of the last commit is afrequent action:– Typos– Missing files– Errors discovered after committing• Just add --amend to the commit command:• git commit –a --amendChange the last commit
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• Sometimes you might need to revert acommit• Removing a commit is in general a bad ideaunless the commit appear only locally, soreverting is a good alternative• git revert <commit>• This action will generate a new commitRevert
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• There are cases in which the only way to getout of a messy local repository is to restore itto a previous state• git reset --soft <commit>– Doesn’t modify index and working dir• git reset --mixed <commit>– Modifies the index but not the working dir• git reset --hard <commit>– Modifies the index AND the working dirgit reset
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• .gitignore is a special file in your repositorythat contains rules for files and folders thatwill not be tracked• Example:*.exe*.dll*.obj*.pdb.gitignore
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• On Window you might want to deal withCRLF / LF on a per-project base• in .gitattributes add:• text eol=lf.gitattributes
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• Git provides support for SVN repositories aswell• There’s quite a lot to discuss on the subject• Just as an introduction:• git svn clone <svn_url> <repo.git>• git svn fetch• git svn dcommitGit and Subversion
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• Hooks let you run custom code on givenevents• E.g.: for push events:– pre-receive hook– for each update ref:• update hook• update ref– post-receive hook– post-update hookHooks
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• Hooks are scripts stored in .git/hooks/• Each script has the name of the hook– Must be executable (Unix)• Parameters are passed in the command line• On Windows, you can use Powershell– But you need a MSYS script (sh, bash, etc)#!/bin/bashpowershell -executionpolicy RemoteSigned -File C:pathpost-receive.ps1 "$@" </dev/stdinWriting hooks
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobilefunction ProcessRef($old, $new, $ref) {"old {0} new {1} ref {2}" -f ($old, $new, $ref) |Out-File -append ”C:Testpost-receive.txt"}$lines = while(($line=[Console]::ReadLine())){$line}foreach($line in $lines){$values = $line.Split(" ")$old = $values[0]$new = $values[1]$ref = $values[2]ProcessRef $old $new $ref}Example Powershell post-receive
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• Github did a tremendous job in popularizing Git,becoming currently the “de facto” standard platformfor open source projects• Very intuitive and rich web interface• Fork and pull requests• Rich APIs for continuous deployment and more• BitBucket offers similar services, including a limitednumber of free private reposGithub, Bitbucket & co.
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &MobileFork
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• Anybody can fork a public repo• Users with proper access can fork a private one• In Github, forks are a good thing• After committing code to your fork, you cansend a “pull request” to the maintainer of theoriginal repository• The maintainer can review it, approve andmerge itFork and pull requests
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• A modern application lifecycle managementneeds to consider a proper framework for:– Code review– Unit testing– Continuous integration• Integration system tests– Continuous deployment• Optionally / Ideally• Git’s distributed nature helps a lotCode review, unit testing and CI
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• Gerrit is an open source code review solutionbased on Git– https://code.google.com/p/gerrit/• Written in Java• MultiplatformGerrit
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &MobileGerrit
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• Git provides a very easy model to extend theexisting command set• git review is the extension provide for Gerritintegration– https://pypi.python.org/pypi/git-review– Requires Python• Install on Windows with:– easy_install.exe git-reviewGit review workflow
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• git checkout -b newbranch• git review -s• git commit -a• git-review• Your commits is now available for review on the Gerritweb site• Jenkins and CI tools can be executed and vote• Human review and approval occurs• Jenkins and CI tools can be executed again• The commits merge into the master branch• New versions of the same patchset can be sent with:• git commit -a --amend• git reviewGerrit workflow
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &MobileGit and Azure web sites
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &MobileGit and Azure web sites
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesDevelopment &Mobile• Integrate Powershell with Git?• http://www.hanselman.com/blog/PromptsAndDirectoriesEvenBetterGitAndMercurialWithPowerShell.aspxPosh-Git
    • itcampro@ itcamp13# Premium conference on Microsoft technologiesQ & A