Chapter03 - Version Control
Chapter03 - Version Control
(SE 4091)
Chapter 03
Version Control
Dileep Kumar G. 1
Chapter Outline
Introduction to Version Control
SE 4091 2
Dileep Kumar G.
The stages of developing a
software application
Requirements Analysis
High-level Design
Low-level Design
Implementation
Integration
Deploy (SDL)
Maintain (SDL)
Dileep Kumar G.
3
In many cases, multiple projects
run concurrently
SE 4091 4
Dileep Kumar G.
On a single project, a team of
software engineers work together
toward a release
An engineer may be
responsible for an entire class
USB/SD drive
Cloud drive
Google drive
Dropbox
iCloud
‘’
‘’
Dileep Kumar G.
11
Revision/Version History might help
…but USB/SD, private network drives do not
maintain revision history
Dileep Kumar G.
13
Special-purpose Revision Control
Systems have been around a lot
longer than Google Drive or Dropbox
SCCS, 1972 (IBM)
RCS, 1982 (Unix)
SourceSafe 1995 (Microsoft)
CVS, 1986 (multi-platform)
SVN, 2000 (multi-platform)
Git and Mercurial, 2005 (multi-platform)
Dileep Kumar G.
15
The Lock-Modify-Unlock
solution Early systems followed this model
(RCS, SourceSafe)
Image documents
Dileep Kumar G.
24
Subversion is an open-source version
control system that is available and
still supported for many platforms
Windows
Mac
Linux
Dileep Kumar G.
25
Subversion’s main drawback is the
centralized nature of the Repository
Dileep Kumar G.
31
Repositories can also manage and
track differences between parallel
revisions of a document
Dileep Kumar G.
33
Git uses checksums
Git generates a unique SHA-1 hash – 40
character string of hex digits, for every
commit.
Often we only see the first 7 characters:
1677b2d Edited first line of readme
258efa7 Added line to readme
0e52da7 Initial commit
Dileep Kumar G.
34
A Local Git project has three
areas
Note: working directory sometimes called the “working tree”, staging area sometimes called the “index”.
35
Git file lifecycle
Dileep Kumar G.
36
Basic Workflow
Basic Git workflow:
1. Modify files in your working directory.
You can call git config --list to verify these are set.
These will be set globally for all Git projects you work
with.
You can also set variables on a project-only basis by not
using the
--global flag.
You can also set the editor that is used for writing commit
messages:
$ git config --global core.editor emacs (it is vim by
default) 39
Create a local copy of a repo
2. Two common scenarios: (only do one of these)
a) To clone an already existing repo to your current directory:
$ git clone <url> [local-dir-name]
This will create a directory named local-dir-name, containing a
working copy of the files from the repo, and a .git directory
(used to hold the staging area and your actual repo)
Dileep Kumar G.
40
Git commands
command description
git clone url [dir] copy a git repository so you can add to it
git add files adds file contents to the staging area
git commit records a snapshot of the staging area
git status view the status of your files in the working
directory and staging area
git diff shows diff of what is staged and what is
modified but unstaged
git help [command] get help info about a particular command
git pull fetch from a remote repo and try to merge
into the current branch
git push push your new branches and data to a
remote repository
others: init, reset, branch, checkout, merge, log, tag
Dileep Kumar G.
41
Init a repository
zachary@zachary-desktop:~/code/gitdemo$ git init
Initialized empty Git repository in /home/zachary/code/gitdemo/.git/
zachary@zachary-desktop:~/code/gitdemo$ ls -l .git/
total 32
drwxr-xr-x 2 zachary zachary 4096 2011-08-28 14:51 branches
-rw-r--r-- 1 zachary zachary 92 2011-08-28 14:51 config
-rw-r--r-- 1 zachary zachary 73 2011-08-28 14:51 description
-rw-r--r-- 1 zachary zachary 23 2011-08-28 14:51 HEAD
drwxr-xr-x 2 zachary zachary 4096 2011-08-28 14:51 hooks
drwxr-xr-x 2 zachary zachary 4096 2011-08-28 14:51 info
drwxr-xr-x 4 zachary zachary 4096 2011-08-28 14:51 objects
drwxr-xr-x 4 zachary zachary 4096 2011-08-28 14:51 refs
Dileep Kumar G.
42
Stage the Changes
zachary@zachary-desktop:~/code/gitdemo$ git status
# On branch master
# Changes not staged for commit:
# (use "git add <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified: hello.txt
#
no changes added to commit (use "git add" and/or "git commit -a")
Dileep Kumar G.
43
Review Changes
zachary@zachary-desktop:~/code/gitdemo$ git add hello.txt
zachary@zachary-desktop:~/code/gitdemo$ git status
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# modified: hello.txt
#
Dileep Kumar G.
44
Committing files
The first time we ask a file to be tracked, and every time
before we commit a file we must add it to the staging area:
$ git add README.txt hello.java
This takes a snapshot of these files at this point in time and adds
it to the staging area.
Note: These commands are just acting on your local version of repo. 45
Status and Diff
To view the status of your files in the working directory
and staging area:
$ git status or
$ git status –s
(-s shows a short one line version similar to svn)
Dileep Kumar G.
46
Viewing logs
To see a log of all changes in your local repo:
$ git log or
Dileep Kumar G.
47
Pulling and Pushing
Good practice:
1. Add and Commit your changes to your local repo
2. Pull from remote repo to get most recent changes (fix conflicts if
necessary, add and commit them to your local repo)
3. Push your changes to the remote repo
To fetch the most recent updates from the remote repo into your local repo,
and put them into your working directory:
$ git pull origin master
To push your changes from your local repo to the remote repo:
$ git push origin master
Notes: origin = an alias for the URL you cloned from
master = the remote branch you are pulling from/pushing to,
(the local branch you are pulling to/pushing from is your current branch)
Note: On attu you will get a Gtk-warning, you can ignore this.
Dileep Kumar G.
48
Branching
To create a branch called experimental:
$ git branch experimental
To list all branches: (* shows which one you are currently on)
$ git branch
Then try:
1. $ git log, $ git log --oneline
Dileep Kumar G.
52
Consider an Eclipse project
-cp <classpath> specifies the base directory where the .class file(s) for
the packages are located
Not including the package subdirectories
Dileep Kumar G.
54
If your class files are in multiple file folders, you
must include them all:
java –cp “D:\My Docs\se4091\JARDemo\bin;
D:\MyDocs\Documents\ASTU\Courses\Example
Programs\se4091\UIHelper\bin” demo.app/JARDemoApp
-cp <classpath> specifies ALL base directories where the .class file(s)
for the packages are located
Note that each directory is separated by a semicolon
With NO space between directories
Dileep Kumar G.
55
A Java Archive (JAR) file enables you
to bundle multiple files into a single
archive file
A JAR file is essentially a ZIP file with specific
contents:
The files you want to zip into the file
.class files
Source files (.java) if you want to enable debugging
Javadoc files if you want to provide context-sensitive
help for the classes in the JAR file
A manifest file (MANIFEST.MF)
Which specifies what’s in the JAR file
Dileep Kumar G.
56
The jar utility can be used to
create JAR files
jar cfm <jarfile> <manifest> -C <bin>
<classfiles>
jar is the command that runs the jar utility
Same as C:\Program Files\Java\jdk1.6.0_03\bin\jar.exe
classfiles specifies the files you want to place in the JAR file
Separated by spaces
Must include the full package folder path
Dileep Kumar G.
57
To bundle files in the same
directory into a JAR file:
jar cfm JARDemoApp.jar manifest.txt –C ./bin
demo/app/JARDemoApp.class –C ./bin
demo/data/MyData.class
This assumes:
you are issuing the jar command from within the directory of
D:\My Docs\se4091\JARDemo
manifest.txt is in the same directory
Demo/app and demo/data are the names of the packages such that all
class files are located in
D:\My Docs\se4091\JARDemo\bin\demo\app
or D:\My Docs\se4091\JARDemo\bin\demo\data
the capitalization of the class filename is identical to the capitalization of the
class itself (be careful on Windows because the OS is case-insensitive but
Java is NOT)
Dileep Kumar G.
58
Manifest details
Manifest.txt is an text file containing the following text:
Manifest-Version: 1.0
Created-By: 1.6.0_03-b05 (Sun Microsystems Inc.)
Main-Class: demo.app.JARDemoApp
Dileep Kumar G.
59
To deploy your application, you just
have to copy the JAR file to
someplace (e.g. C:\temp) on the
target PC
Dileep Kumar G.
60
If your JAR file references other
JAR files (like Helper.jar)…
Manifest-Version: 1.0
Created-By: 1.6.0_03-b05 (Sun Microsystems Inc.)
Main-Class: demo.app.JARDemoApp
Class-Path: ./Helper.jar
Note that ./ specifies that Helper.jar in this case can be found in the same
directory folder as JARDemoApp.jar (i.e. they are both in C:\temp).
Dileep Kumar G.
61
Online tutorial
“Packaging Programs in JAR files”
http://java.sun.com/docs/books/tutorial/deploy
ment/jar/index.html
Dileep Kumar G.
62
Automating the Build Process
using ANT
Dileep Kumar G.
63
ANT is used in the Verification
phases of the SW lifecycle
The stages of developing a software application
Requirements Analysis
High-level Design
Plan
Low-level Design
Implementation
Unit Test
Integration
System Test
Deploy
Maintain
Dileep Kumar G.
64
What is ANT?
ANT (Another Neat Tool) is a utility that
automates the process of compiling and
building (jarring) Java project files
Dileep Kumar G.
66
For a standalone ANT engine, you
can Install ANT from www.apache.org
Targets contain statements and rules that the Ant engine executes
in order to perform some task or achieve some goal.
<target name="dosomething" description="Prints a message.">
Dileep Kumar G.
69
Demonstration
Dileep Kumar G.
70
Creating Ant Buildfiles
Typically, Ant's build file, called build.xml should
reside in the base directory of the project.
However there is no restriction on the file name or its
location.
Create a file called build.xml anywhere in your
computer with the following contents in it:
71
Ant Buildfiles
The XML element project has three attributes :
72
Ant Buildfiles
The target element has following attributes :
73
Running Ant Buildfiles
Select HelloWorld.xml in one of the navigation views and
choose Run As > Ant Build... from its context menu.
The launch configuration dialog is opened on a launch
configuration for this Ant buildfile.
This dialog allows the configuration of many aspects of
the way an Ant buildfile is run, but for now concentrate on
the Targets tab which allows the selection of which Ant
targets to run and their order. Select both targets and
leave the order as the default.
Click the Run button.
The Ant buildfile is run, and the output is sent to
the Console view.
Dileep Kumar G.
74
Creating a project builder Ant
buildfile in Eclipse
Create a Java project named HW.
1. Create a Java source file named HelloWorld with a
main method.
2. Put a single System.out.println() statement in the main
method, and make it print a greeting of your choice.
3. Save changes.
Create a file named projectBuilder.xml
<?xml version="1.0" encoding="UTF-8"?>
<project name="HW.makejar" default="makejar" basedir=".">
<target name="makejar" description="Create a jar for HW project">
<jar jarfile="HelloWorld.jar" includes="*.class" basedir="bin" />
</target>
</project>
75
In one of the navigation views, select the HW project
and choose Properties from its context menu.
In the project properties dialog, select Builders, then
click New....
In the Choose configuration type dialog, select Ant
build, and click OK.
The External Tools dialog appears. Set the name
to Makejar.
In the Main tab, click the Buildfile Browse
Workspace... and set the Location to be
the projectBuilder.xml buildfile created above.
Then click the Base Directory Browse Workspace... and
set the Base Directory to be the HW project.
76
77
In the Refresh tab, we want to be sure that when
our HelloWorld.jar is created, we see it in Eclipse. So
check Refresh resource upon completion, then
select The project containing the selected resource in
the list of scoped variables.
In the Targets tab, you can specify when this project
builder is executed and which targets. By default,
the default target is set to run After a "Clean"and Manual
Build.
Apply the changes and click OK.
Back in the project properties dialog, you will now see a
project builder named Makejar that is set to run after the
default Java builder. Click OK to save the project builder
and close the dialog.
78
Intoduction to Unit Testing
Dileep Kumar G.
79
How can you test your code?
Dileep Kumar G.
80
How can you test your app?
Run the app with inputs that should produce a
known output, and verify the actual output
One problem with this approach may be that you can’t make
your app accept “bad” inputs; thus you may not be able to
force all possible if-then-else blocks of the app’s classes’
methods to execute
It is built in to Eclipse.
Like Ant, it can also run standalone
Dileep Kumar G.
84
Analyzer.java
//This class analyzes Strings and determines various metrics such as vowel count.
package stringAnalyzer;
import java.util.regex.Pattern;
@SuppressWarnings("unused")
/**
* The public constructor for this class
* @param s the String to be analyzed
* @throws an Exception if s is null
*/
public Analyzer(String s) throws Exception {
if( s == null )
throw new NullPointerException("null argument!");
text = s;
numVowels = 0;
numConsonants = 0;
numBlanks = 0;
// These are the vowel and consonant patterns used for matching characters in the String
being analyzed.
String vowels = new String("[aeiou]");
// [aeiou] is called a *regular expression*; means "any character within the brackets"
String consonants = new String("[bcdfghjklmnpqrtvwxyz]");
if( Character.isSpaceChar(text.charAt(i)) )
// check for space character
numBlanks++;
/**
* retrieves the number of consonants in the specified string
* @return number of consonants (>=0)
*/
public int getConsonantCount() throws RuntimeException {
return numConsonants;
}
/**
* retrieves the number of blanks in the specified string
* @return number of blanks (>=0)
*/
public int getSpaceCount() throws RuntimeException {
return numBlanks;
}
}
Dileep Kumar G.
87
AnalyzerApp.java
/**
* An application for demonstrating how to use JUnit for testing
*/
package stringAnalyzer;
/**
* @author Dileep
* This is the main class that controls the program
*/
public class AnalyzerApp {
/**
* @param args
* - not used
*/
public static void main(String[] args) throws Exception {
Analyzer a = new Analyzer("a b c d e");
System.out.println("Number of consonants= " + a.getConsonantCount());
System.out.println("Number of vowels= " + a.getVowelCount());
System.out.println("Number of blank spaces= " + a.getSpaceCount());
}
Output:
Number of consonants= 3
Number of vowels= 2
Number of blank spaces= 4 88
AnalyzerTests.java
package tests;
import static org.junit.Assert.*;
import java.io.IOException;
import org.junit.*;
import org.junit.rules.ExpectedException;
import stringAnalyzer.Analyzer;
// This class is responsible for testing the Analyzer class. Requires JUnit 4.
public class AnalyzerTests {
// This is an example JUnit test method.
@Test
public void testABCDE() throws Exception {
System.out.println("\t testing for input 'a b c d e' ");
Analyzer a = new Analyzer("a b c d e");
final int nExpectedConsonants = 3;
int nActualConsonants = a.getConsonantCount();
assertEquals(nExpectedConsonants, nActualConsonants);
}
// @Test, it verifies the operation of the analyze method for an empty string
public void testEmptyStringAnalysis() throws Exception {
Analyzer a = new Analyzer(""); The @Test annotation tells JUnit that the public void method
final int nExpectedVowels = 0; to which it is attached can be run as a test case. Before
final int nExpectedConsonants = 0; running the method, Junit first runs the setUpBeforeClass()
method, then constructs a fresh instance of this class, then
final int nExpectedSpaces = 0; runs the setUp() method, and then finally invokes the
int nVowels = a.getVowelCount(); annotated method. Any exceptions thrown by the test will be
int nConsonants = a.getConsonantCount(); reported by JUnit as a failure. If no exceptions are thrown,
the test is assumed to have succeeded. After running each
int nBlanks = a.getSpaceCount(); @Test method, JUnit calls the tearDown() method. After all
assertEquals(nExpectedVowels, nVowels); @Test methods are run, JUnit calls tearDownAfterClass().
assertEquals(nExpectedConsonants, nConsonants);
Dileep Kumar G.
assertEquals(nExpectedSpaces, nBlanks);
89
}
// @Test , it verifies the operation of the analyze method for an string
// containing all possible vowels and consonants
public void testFullStringAnalysis() throws Exception {
Analyzer a = new Analyzer(
"abc def ghi jkl mno pqr stu vwx yz ABC DEF GHI JKL MNO PQR STU VWX YZ");
final int nExpectedVowels = 10;
final int nExpectedConsonants = 42;
final int nExpectedSpaces = 17;
int nVowels = a.getVowelCount();
int nConsonants = a.getConsonantCount();
int nBlanks = a.getSpaceCount();
assertEquals(nExpectedVowels, nVowels);
assertEquals(nExpectedConsonants, nConsonants);
assertEquals(nExpectedSpaces, nBlanks);
}
Dileep Kumar G.
90
// @Test(expected= Exception.class)
// this test expects an Exception to be thrown somewhere
public void testNullStringConstruction2() throws Exception {
System.out.println("\t testing for null-arg Exception using
@Test(expected=Exception.class) ");
Analyzer a = new Analyzer(null);// null arg should cause an Exception
}
@Rule
public ExpectedException thrown = ExpectedException.none();
@Before
// This method is called right before each individual @Test method,
// but AFTER the class constructor is called.
public void setUp() throws Exception {
System.out.println(">>setUp test number " + testNumber);
}
@After
// This method is called right after each individual @Test method.
public void tearDown() throws Exception {
System.out.println("<<tearDown test number " + testNumber + "\n");
testNumber++;
}
// This constructor is called once for each @Test, before the setUp() method is called
public AnalyzerTests() {
System.out.println("AnalyzerTests constructor called...");
}
Dileep Kumar G.
92
Self-Review Questions
1. List out tools that exist for version control?
2. What are the features of distributed version
control?
3. List out Git commands?
4. Write code snippet for creating a jar file?
5. Write code snippet to demonstrate the
concept of unit testing using JUnit?
Dileep Kumar G.
93