Category Archives: General

Mis­cel­la­neous

Minimal Gradle Post | What you need to know

I’ve been using Gra­dle for some­time at the work­place and I find it to be a good build tool. In the past I’ve SBT, Maven and Nant as well as, well, MSBuild. It was only MSBuild that I grew much famil­iar with back in my .net days.

This is a min­i­mal Gra­dle post for who­ev­er wants to get start­ed with it with little/no fuss. Let’s get right into it.

What’s Gra­dle used for — It’s a build man­age­ment tool. What this means is that you can use Gra­dle to man­age build­ing your projects, man­age depen­den­cies with­in projects and exter­nal to them, man­age how tests are run, write pre/post build tasks/targets, and so on. You get the idea.

Two main ideas in Gra­dleProjects and tasks

A gra­dle build can con­sist of one or more projects and each project can have one more more tasks. Tasks are noth­ing but units of work need to be done. A gra­dle project needs to have at least one build.gradle file. If there is only one such file it needs to be present in the root direc­to­ry of the project. But you can addi­tion­al­ly have build.gradle for each project in your project. Gra­dle build files con­tain DSL code and can also con­tain Groovy or Kotlin code. The DSL is basi­cal­ly a declar­a­tive kind of lan­guage.

At this point, let’s dive into code and see a few things first hand. I will be using Intel­liJ IDEA to set up a Gra­dle project. You are free to use any edi­tor of your choice as long as it has sup­port for Gra­dle.

Down­load Intel­liJ, install Gra­dle plu­g­in (it would be checked by default), Set­up a new ‘Gra­dle’ project. You will see a build.gradle file set­up for you as well as a settings.gradle file.

Note that you will also see a few more things — gradlewrap­per, gradlew.sh and gradlew.bat files

So, what’s gradlewrap­per?
Say you run mul­ti­ple projects on your lap­top. Some might be using SBT, some Maven, some Gra­dle, etc. Gradlewrap­per let’s you use Gra­dle local to your project by pro­vid­ing Gra­dle jars that don’t need to be avail­able sys­tem wide. Mean­ing that you won’t need to install Gra­dle on your sys­tem. You can use the Gra­dle jars and scripts that come with Gradlewrap­per and that’s the end of sto­ry. To use Gra­dle through Gradlewrap­per you will need to sub­mit your Gra­dle com­mands to the scripts that ship with Gradlewrap­per — gradlew.bat for win­dows and gradlew.sh for *nix, much the same way as you would use the ‘gra­dle’ com­mand from com­mand line.

so, for exam­ple a nor­mal gra­dle com­mand could look some­thing like


gradle 

but if you don’t want to install Gra­dle on your sys­tem and rather just use Gradlewrap­per, you will write some­thing like


./gradlew 

Project list­ing goes in settings.gradle
settings.gradle will con­tain at least one project name — the root project, by default it’s the name of the direc­to­ry con­tain­ing the main/root project of your set­up. You can of course, change this name to any­thing of your lik­ing. Over time, if you have more projects, their names also go in settings.gradle file.

The Gra­dle sys­tem is rich with plu­g­ins. All plu­g­ins avail­able can be seen at this url. Plu­g­ins pro­vide addi­tion­al func­tion­al­i­ty to your Gra­dle set­up. Plu­g­ins might have pre-writ­ten tasks that you might not want/have to write your­self, apart from lot more func­tion­al­i­ties.
For exam­ple, if you want Scala to be the lan­guage for your project and you’d like Gra­dle to make src/test direc­to­ries for the same, you can use the ‘scala’ plu­g­in and ‘refresh’ your build.gradle and you will see the scala relat­ed direc­to­ries in your project struc­ture.
(By the way, you can also do a ‘refresh’ by exe­cut­ing gra­dle –refresh-depen­den­cies task from com­mand line)

For instance, my build.gradle file for this exer­cise looks like this —


group 'org.practice'
version '1.0-SNAPSHOT' //when version is set you will have a jar file with 
//name like mylibName-1.0-SNAPSHOT.jar, in this case

apply plugin: 'scala'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    //example on how to target jars in a specific local directory
    //compile files('/home/vaibhav/spark/spark-2.1.0/core/target/spark-core_2.11-2.1.0.jar')
    compile group: 'org.apache.spark',name: 'spark-core_2.11', version: '2.1.0'
    testCompile group: 'junit', name: 'junit', version: '4.11'
}

Cou­ple of things to note above -
1. You can see how to apply a plu­g­in.
2. When you might have set­up your sam­ple project(as men­tioned above) as a gra­dle project, you would have been asked to sup­ply groupId and arti­fac­tId. GroupId, Arti­fac­tId and Ver­sion, also called GAV, is a pret­ty stan­dard way in the mvn world to iden­ti­fy a library. Gra­dle fol­lows the same mvn con­ven­tion and in fact, the gra­dle project struc­ture by con­ven­tion, you will find, is much like mvn project struc­ture.

src/main/scala
src/test/scala

3. There would be a source­Com­pat­i­bil­i­ty option mean­ing that you com­pile your code to be com­pat­i­ble with a cer­tain ver­sion of java run time.
4. Under ‘repos­i­to­ries’, you can list the repos Gra­dle will hit to search for the depen­den­cies men­tioned under ‘depen­den­cies’. You can men­tion any num­ber of repos by pro­vid­ing a url. Maven­Cen­tral is avail­able by default.
You can also spec­i­fy local file sys­tem path to load depen­den­cies from, some­thing like

run­time files(‘lib/project1.jar’,‘lib2/project2.jar’)
There are many ways to spec­i­fy how to pick, from where to pick, and what to exclude. I am sure you can find the right syn­tax when you need it.

5. You can see that // works for com­ments, as well as /* .… */
6. When men­tion­ing what depen­den­cies to down­load, you pro­vide their GAV. By the way, if you don’t tell gra­dle where to down­load your depen­den­cies, it will do so by default at ~/.gradle/caches/
7. You can group your depen­den­cies — above you can see that I don’t need junit in my main project but I need it in my test project. So I use a pre-built group ‘test­Com­pile’. Sim­i­lar­ly, for the ‘com­pile’ group.

If you’d rather not use gradlewrap­per, you can install gra­dle using brew in Mac or apt-get install on Ubun­tu, etc. You might need to set GRADLE_HOME if the instal­la­tion does not already does that for you.

gradle.properties
You can spec­i­fy your gra­dle spe­cif­ic set­tings like what jvm to use, whether to keep gra­dle dae­mon alive(recommended set­ting), etc. in a gradle.properties file. If you are using gradlewrap­per, you should already have gradle-wrapper.properties file for you.

Gra­dle Tasks
So far, we’ve talked about set­ting up gra­dle and about projects. Let’s take a look at tasks now.
A build.gradle file can have many tasks, these tasks can be grouped or not grouped. When not grouped, a task is con­sid­ered a ‘pri­vate’ task and will show up under ‘Oth­er tasks’ when see­ing the out­put of com­mand ‘gra­dle tasks’, which lists all tasks. Here’s an exam­ple of a grouped task and an ungrouped task-


task calledOnce {
    println("I will get printed first")
}

task helloworld {
    group 'some group name'
    description 'this is desc for task helloworld'

    doFirst {
        println("hello world task begins")
    }

    doLast {
        println("hello world task ends")
    }
}

> gradle helloworld

> I will get printed first
> hello world task begins
> hello world task ends

doFirst, doLast are phas­es with­in a task. State­ments in task clo­sure not under any phase by default go into con­fig­u­ra­tion phase and are exe­cut­ed once before any oth­er phas­es, no mat­ter whether you call that par­tic­u­lar task or not.

Tasks can depend on each oth­er
This is a nor­mal pro­ce­dure for most build scripts. Exe­cu­tion order of tasks depends on which tasks depend on which ones.

exam­ple,


defaultTasks 'compile' //since a default task has been specified, on the command line it will suffice to just type 'gradle'

apply plugin: 'scala'

task compile(dependsOn: 'compileScala') {
   doLast { 
       println("compile task")
   }
}

//shorter syntax for defining doLast, doFirst
compileScala.doLast(dependsOn: 'clean') {
    println("compileScala task given by scala plugin")
}

task clean {
    doLast { 
       println("clean task")
   }
}

Note that you can also cre­ate your own tasks by extend­ing the Default­Task class, but this is not some­thing we are going to try in this post.

Mul­ti-project build struc­ture
Usu­al­ly you would have a few sub-projects or mod­ules in your project and they also need to be built, tests exe­cut­ed for them and there might be depen­den­cies among these sub-projects. Of course, gra­dle gives you option here. Let’s say you have project struc­ture like this —

root_project
— Web
— Core
— Util

In this case, your settings.gradle would con­tain ‘include’ some­thing like this —


include 'Core', 'Web', 'Util' //telling gradle we have sub projects

Now, the build.gradle file needs to cater for these sub-projects as well. There will be some tasks that are spe­cif­ic to sub-projects, some tasks com­mon for all, etc. Take a look —



//will be called once for each project, including root
allprojects {
    //groupId: ....
    //version: ....
}

//does not apply to root
subprojects {
    //apply specific plugins, etc.
}

//root_project specific dependencies
project(':org.practice.root_project').dependencies {
    compile project(':org.practice.Core'), project(':Util') 
    compile 'some lib'
}

or,


allprojects {
...
}

subprojects {
...
}

//Core specific stuff
project(':Core') {
    dependencies {
    ...
    }
}

//Util specific stuff
project(':Util') {
...
}

//Web specific stuff
project(':Web') {
...
}

Note that sub-project spe­cif­ic stuff could also go under their own sep­a­rate build.gradle files.

Pub­lish­ing arti­facts
Pub­lished files are called arti­facts. Pub­lish­ing is usu­al­ly done with the help of some plu­g­in, like maven.


apply plugin: 'maven'

uploadArchives { //maybe some nexus repo or local
    repositories {
        mavenDeployer {
            repository(url:"some url")
        }
    }
}

Hope the above gives you nec­es­sary infor­ma­tion to get going with gra­dle! Thanks for read­ing!

All you need to know about Unit Testing | Minimal Post

Unit/Integration test­ing is some­thing most devel­op­ers do on a dai­ly basis. I had always want­ed to write a blog on this sub­ject — some­thing min­i­mal but that cov­ers the essen­tials and gives one the nec­es­sary ter­mi­nol­o­gy and tools to get going in the begin­ning. This post is tar­get­ed towards junior devel­op­ers. So, here we go -

Rec­om­mend­ed Book — The Art of Unit Test­ing, 2nd Edi­tion

What is Inte­gra­tion Test­ing and what is Unit Test­ing?

Well, soft­ware test­ing comes in two fla­vors, if you will — Unit test­ing and Inte­gra­tion test­ing. What’s the basic dif­fer­ence, you ask? Let’s say you want to test some com­po­nent X of the soft­ware. Most­ly, this X is some method/function. X might depend on some db calls, file sys­tem, etc. If you use real exter­nal resources like a real db call, etc. to test X then you are doing Inte­gra­tion test­ing but instead, if you are fak­ing or stub­bing these exter­nal resources then you are doing Unit test­ing — basi­cal­ly test­ing just that unit X and fak­ing most things it depends on. And it makes sense, you want to test just one sin­gle func­tion­al­i­ty and not depend on any­thing for that.

Using stubs to break depen­den­cies

Your code X ———> depends on some exter­nal depen­den­cy (any object like file sys­tem, threads, db calls, etc.)

But when you want to Unit test X, it would be some­thing like this -

Your code X ———> stub in place of exter­nal depen­den­cy

You might have heard about Mocks, stubs, etc. Don’t get bogged down by ter­mi­nol­o­gy — stubs and mocks are both fakes. And, from The Art of Unit Test­ing — Mocks are like stubs but you assert against a mock but you don’t assert against a stub. We’ll see all this soon.

exam­ple,


public bool IsValidFileName(String fn)
{
    //read some conf file from file system
    //to see if extension is supported by your company or not.
}

What­ev­er code is there in place of com­ments above would qual­i­fy as exter­nal depen­den­cy. So, how do we test the above?
One way would be to actu­al­ly read a conf file and use it for test­ing and then destroy it. Of course, this would be time con­sum­ing and would be an inte­gra­tion test and not a Unit test.

So, how to test with­out resort­ing to inte­gra­tion test — The code at hand is direct­ly tied to exter­nal depen­den­cy. It is call­ing the fs direct­ly, we need to first decou­ple this. Some­thing like this,

 

If we do this, our code would not direct­ly depend on fs but on some­thing else that is direct­ly depen­dent on fs. This some­thing else, the fileSys­tem­Man­ag­er in our code is some­thing we that can use for a real fs in case of actu­al code and a fake fs in case of test­ing.

Anoth­er ter­mi­nol­o­gy — Seams

Oppor­tu­ni­ties in code where a dif­fer­ent func­tion­al­i­ty can be plugged in. This can be done through inter­faces (fileSys­tem­Man­ag­er above) so that it can be over­rid­den. Seams are imple­ment­ed through what’s called an Open-Closed prin­ci­ple — class should be open for exten­sion but closed for mod­i­fi­ca­tion.

So, for exam­ple, from the above we can have -


    public class FileSystemManager: IFileSystemManager
    {
        public bool IsValid(String fileName)
        {
         ..some production code interacting with real fs 
        }
    }

So, now your code looks something like this - 

    public bool IsValidFileName(String fileName)
    {
        IFileSystemManager mgr = new FileSystemManager();
        return mrg.IsValid(fileName);
    }

So, that is your code but what to use in tests? — a stub!


    public class FakeFileSystemManager: IFileSystemManager
    {
        public bool IsValid(String fileName)
        {
            return true; //no need to interact with real fs
        }
    }

So, ok, good, we have cre­at­ed a way to bifur­cate between actu­al pro­duc­tion code and tests code. But wait! Remem­ber that we need­ed to test IsValid­File­Name method. The issue is the fol­low­ing line of code -

IFileSys­tem­Man­ag­er mgr = new FileSys­tem­Man­ag­er();
We need to remove this instan­ti­at­ing of a con­crete class that’s using ‘new’ right now. Because if we don’t, no mat­ter where we call IsValid­File­Name from(tests or actu­al code), it will always try to new up FileSys­tem­Man­ag­er. This is where DI con­tain­ers come in but we won’t be going into details of DI here, so let’s take a look at some­thing called ‘con­struc­tor lev­el injec­tion’.


    public classUnderTest
    {
        private IFileSystemManager _mgr;
        public classUnderTest(IFileSystemManager mgr)
        {
            _mgr = mgr 
        }

        public IsValidFileName(String fileName)
        {
            return _mgr.IsValid(fileName); //so just like that we got rid of new! and this
            //code is ready for testing - we will send in fake fileSystemManager in case of tests and
            //'real' fileSystem in case of production code
        }
    }

So, the actu­al test now would look some­thing like -


    [TestFixture]
    public class ClassUnderTest_Tests
    {

     [Test]
     public void
     IsValidFileName_NameSupportedExtension_ReturnsTrue()
     {
         IFileSystemManager myFakeManager =
                 new FakeFileSystemManager();
         myFakeManager.WillBeValid = true;
         ClassUnderTest obj = new ClassUnderTest (myFakeManager);
         bool result = obj.IsValidFileName("short.ext");
         Assert.True(result);
     }
    }
    internal class FakeFileSystemManager : IFileSystemManager
    {
        public bool WillBeValid = false;
        public bool IsValid(string fileName)
        {
            return WillBeValid;
        } 
     }

Once you’ve under­stood the above basic con­cept, oth­er stuff will come eas­i­ly. So for instance, here’s one way to make your fakes return an excep­tion -


    class FakeFileSystemManager: IFileSystemManager
    {
        public bool WillBeValid = false;
        public Exception WillThrow = null;

        public bool IsValid(String fileName)
        {
            if(WillThrow != null) //where WillThrow can be configured from the calling code.
                throw WillThrow;
            return WillBeValid;
        }
    }

Till now we have seen how to write our own fakes but let’s see how to avoid hand­writ­ten fakes.

But before that, I would like to broad­ly say that test­ing can be of three types (from Art of Unit Test­ing) -
1. Val­ue based — When you want to check whether the val­ue returned is good or not
2. State based — When you want to check whether the code being test­ed has expect­ed state or not (cer­tain vari­ables have been set cor­rect­ly or not)
3. Inter­ac­tion based — When you need to know if code in one object called anoth­er objec­t’s method cor­rect­ly or not. You use it when call­ing anoth­er object is the end result of your unit being test­ed. This is some­thing that you will encounter a lot in real life cod­ing.

Let’s make for­mal dis­tinc­tion between mocks, fakes and stubs now. I will be quot­ing from The Art of Unit Test­ing.
“mock object is a fake object in the sys­tem that decides whether the unit test has passed or failed. It does so by ver­i­fy­ing whether the object under test called the fake object as expect­ed”

A fake is a gener­ic term that can be used to describe either a stub or a mock object (hand­writ­ten or oth­er­wise), because they both look like the real object. Whether a fake is a stub or a mock depends on how it’s used in the cur­rent test. If it’s used to check an inter­ac­tion (assert­ed against), it’s a mock object. Oth­er­wise, it’s a stub.”

Let’s con­sid­er an exam­ple,


//an interface
public interface IWebService
{
    void LogError(string message);
}

and a hand-written fake

//note that this will only be a mock once we use it in some assert in some test
public class FakeWebService:IWebService
{
    public string LastError;
    public void LogError(string message)
    {
        LastError = message;
    }
}

What we want to test — When we encounter an error and post the mes­sage to our web ser­vice, the mes­sage should be saved as ‘LastEr­ror’. This means that we want to test whether our fake ser­vices’ LogEr­ror method appro­pri­ate­ly updates the ‘LastEr­ror’ or not.


[Test]
 public void Analyze_TooShortFileName_CallsWebService()
  {
     FakeWebService mockService = new FakeWebService();
     LogAnalyzer log = new LogAnalyzer(mockService);
     string tooShortFileName="abc.ext";
     log.Analyze(tooShortFileName);
     StringAssert.Contains("Filename too short:abc.ext",
                        mockService.LastError); // now mockService is a 'mock'
}
 public class LogAnalyzer
 {
    private IWebService service;
 
    public LogAnalyzer(IWebService service)
    {
        this.service = service;
    }
    public void Analyze(string fileName)
    {
        if(fileName.Length<8)
        {
           service.LogError("Filename too short:"
           + fileName);
        }  
    }
}

Let’s take anoth­er exam­ple, a bit more involved.

Say your code logs error by call­ing service.LogError, as above. But now, let’s add some more com­plex­i­ty — if service.LogError throws some kind of excep­tion you want to catch it and send an email to some­one to alert that some­thing is wrong with the ser­vice.

Some­thing like this,

 

if(fileName.Length < 8)
{
    try
    {
        service.LogError("too short " + fileName);
    }
    catch(Exception e)
    {
        email.SendEmail("something wrong with service", e.Message);
    }
}

Now, there are two ques­tions in front of us -
1. What do we want to test?
2. How do we test it?

Let’s answer them -
What do you want to test -
1.1 When there is an error like short file name then mock web ser­vice should be called
1.2 Mock ser­vice throws an error when we tell it to
1.3 When error is thrown, an email is sent

See if the fol­low­ing will work -
Your test code calls your Log­An­a­lyz­er code inject­ing it a fake web ser­vice that throws an excep­tion when you tell it to. Your log­An­a­lyz­er will also need an email ser­vice that should be called when the excep­tion is thrown.

It should work some­thing like this -

But how will we assert that the email ser­vice was called cor­rect­ly? — Set some­thing in the mock email that we can assert lat­er!


class EmailInfo
{
    public string Body;
    public string To;
    public string Subject;
}

[Test]
public void Analyze_WebServiceThrows_SendsEmail()
{
    FakeWebService stubService = new FakeWebService();
    stubService.ToThrow=  new Exception("fake exception");
    FakeEmailService mockEmail = new FakeEmailService();
    LogAnalyzer2 log = new LogAnalyzer2(stubService,mockEmail);
    string tooShortFileName="abc.ext";
    log.Analyze(tooShortFileName);

    EmailInfo expectedEmail = new EmailInfo {
                                       Body = "fake exception",
                                       To = "someone@somewhere.com",
                                       Subject = "can’t log" }

   Assert.AreEqual(expectedEmail, mockEmail.email);
}

public class FakeEmailService:IEmailService
{
    public EmailInfo email = null;
    public void SendEmail(EmailInfo emailInfo)
    {
        email = emailInfo;
    }
}

public interface IEmailService
{
    void SendEmail(string to, string subject, string body);
}

public class LogAnalyzer2
{
    public LogAnalyzer2(IWebService service, IEmailService email)
    {
         Email = email,
         Service = service;
    }
    public IWebService Service
    {
         get ;
         set ; 
    }
    public IEmailService Email
    {
        get ;
        set ; 
    }

    public void Analyze(string fileName)
    {
        if(fileName.Length<8)
        {
            try {
                  Service.LogError("Filename too short:" + fileName);
                }
                catch (Exception e)
                {
                    Email.SendEmail("someone@somewhere.com",
                                    "can’t log",e.Message);
                }            
        }
    }
}

public class FakeWebService:IWebService
{
    public Exception ToThrow;
    public void LogError(string message)
    {
        if(ToThrow!=null)
        {
            throw ToThrow;
        }
    } 
}

Rule of thumb — once mock per test. Oth­er­wise it usu­al­ly implies that you are test­ing more than one thing in a Unit test.

Let’s say you have some code like -


String connString = GlobalUtil.Configuration.DBConfiguration.ConnectionString

and you want to replace connString with one of your own dur­ing test­ing, you could set up a chain of stubs return­ing your val­ue — but that would not be so main­tain­able, would it!
On the oth­er hand, you could also make your code more testable by refac­tor­ing it to be some­thing like -


String connString = GetConnectionString();
..
..
public String GetConnectionString()
{
    return GlobalUtil.Configuration.DbConfiguration.ConnectionString;
}

Now, instead of hav­ing to fake a chain of meth­ods, you would only need to do that for Get­Con­nec­tion­String() method.

Prob­lem with hand­writ­ten mocks and stubs

1. Takes time to write
2. Dif­fi­cult to write for big or com­pli­cat­ed inter­faces and class­es
3. Main­te­nance of hand­writ­ten mocks and stubs as code changes
4. Hard to reuse in a lot of cas­es

Enter Iso­la­tion or Mock­ing frame­works

Def­i­n­i­tion — Frame­works to cre­ate and con­fig­ure fake objects at run­time (dynam­ic stubs and mocks)

So, let’s use one! We will be using NSub­sti­tute on Visu­al­Stu­dio for Mac Pre­view edi­tion. This is part of VS IDE devel­oped for .Net Core com­mu­ni­ty.

The code exam­ples men­tioned below are self suf­fi­cient and easy to read. Please go through them in the fol­low­ing order-

1. LogAnalyzerTests.cs — Shows com­par­i­son between writ­ing a hand­writ­ten fake and one using NSub­sti­tute. Also shows how to ver­i­fy the call made to a mock.
2. SimulateFakeReturns.cs — Shows how to make a stub return some­thing we want when­ev­er there is some par­tic­u­lar or gener­ic input.
3. LogAnalyzer2Example.cs — Again shows com­par­i­son between code writ­ten with and with­out a mock­ing frame­work. Shows how to throw excep­tion using NSub­sti­tute.

The above are sim­ple exam­ples show­cas­ing API capa­bil­i­ties of a mock­ing frame­work — things we’ve been doing by hand­writ­ten code till now.

Gen­er­al state­ment on how mock­ing frame­works work — Much the same way you write hand­writ­ten fakes with the excep­tion that these frame­works write code dur­ing run time. At run time, they give us the oppor­tu­ni­ty to over­ride inter­face meth­ods or vir­tu­al meth­ods much the same way we’ve seen till now. Gen­er­at­ing code at run time is not some­thing new to the pro­gram­ming world. How­ev­er, some frame­works allow much more than this — they even allow you to fake con­crete class­es and over­ride their meth­ods. How? In these cas­es the mock­ing frame­works inject code that you want in the .class or .dll and use some­thing IF DEF kind of con­di­tion­al run­ning of code. Of course, this capa­bil­i­ty requires under­stand­ing how to inject or weave code at run time which fur­ther requires under­stand­ing of inter­me­di­ate code tar­get­ing the run­time or VM.

Git Cheatsheet

This prob­a­bly serves as a quick git ref­er­ence or cheat­sheet. I used to main­tain this when I was new to git. Prob­a­bly still help­ful for begin­ners out there.

Revert all for files added but not com­mit­ted
git check­out .

Adding/Staging files
git add .

Com­mit­ting with mes­sage
com­mit ‑m “my mes­sage”

Make new branch (local)
git check­out ‑b new_branch

Then make that branch on serv­er ready to push
git push ‑u ori­gin feature_branch_name
Or sim­ply
git push –all ‑u (to push all your local branch­es to serv­er and set track­ing for them too)

Change from one branch to anoth­er
git check­out another_branch_name

Merge branch­es
Sup­pose you have branched ‘mas­ter’ and ‘feature1’ and you want to bring the con­tents of ‘mas­ter’ into ‘feature1’, means you want to update your ‘feature1’ branch, then you do -

git check­out feature1
git merge mas­ter

if you want to bring in the con­tents of ‘feature1’ into ‘mas­ter’, when your ‘feature1’ work is done, then you do

git check­out mas­ter
git merge feature1

In fact, this 2 step process is the bet­ter way to merge your fea­ture branch­es into mas­ter

In order to resolve con­flicts, you might have to do
git merge­tool

After all this is done, you do a com­mit merge and push from mas­ter

Equiv­a­lent of hg out­go­ing
If you want to list com­mits that are on your local branch dev, but not the the remote branch origin/dev, do:
git fetch ori­gin # Update origin/dev if need­ed
git log origin/dev..dev

Equiv­a­lent of git incom­ing
git fetch ori­gin # Update origin/dev if need­ed
git log dev..origin/dev

See the his­to­ry of a file

gitk /pathtofile/file.java

When you want to set­up a new repo in Github and already have some code in local

Cre­ate the remote repos­i­to­ry, and get the URL such as git@github.com:/youruser/somename.git or https://github.com/youruser/somename.git, add readme or .git­ig­nore or what­ev­er you want
Local­ly, at the root direc­to­ry of your source, git init
git pull {url from step 1}
git add . then git com­mit ‑m ‘ini­tial com­mit com­ment’
git remote add ori­gin [URL From Step 1]
git pull ori­gin mas­ter
git push ori­gin mas­ter

Pull all branch­es to local

git fetch –all
git pull –all

List all branch­es

git branch ‑a –list all local branch­es
git branch ‑r –list all remote branch­es

and then do a sim­ple git check­out full­branch­name to move into that branch

Pull cer­tain branch from serv­er

git pull ori­gin brnach-name

Set­ting up git merge­tool on win­dows

down­load kdiff3 exe, install it

open git­con­fig file in C:\Program Files (x86)\Git\etc

open git­con­fig using cmd in Admin mode, by notepad git­con­fig com­mand

add the fol­low­ing there -

[merge]
tool = kdiff3

[merge­tool “kdiff3”]
path = C:/Program Files/KDiff3/kdiff3.exe
keep­Back­up = false
trustEx­it­Code = false

save it, close it

on git bash do
git con­fig –glob­al merge.tool kdiff3

OR

Just down­load and install kdiff 3
And do the fol­low­ing

$ git con­fig –glob­al –add merge.tool kdiff3
$ git con­fig –glob­al –add mergetool.kdiff3.path “C:/Program Files/KDiff3/kdiff3.exe”
$ git con­fig –glob­al –add mergetool.kdiff3.trustExitCode false
$ git con­fig –glob­al –add diff.guitool kdiff3
$ git con­fig –glob­al –add difftool.kdiff3.path “C:/Program Files/KDiff3/kdiff3.exe”
$ git con­fig –glob­al –add difftool.kdiff3.trustExitCode false
Delete a branch from local

git branch ‑D branch_name

Delete a branch from remote

git push ori­gin –delete <branch­Name>

Delete untracked file
git clean ‑f file­name­with­path
or git clean ‑f ‑d file­name­with­path

or

git clean ‑f ‑n to show what files will be removed
git clean ‑f to actu­al­ly remove those

use git clean ‑fd to remove untracked direc­to­ries

use git sta­tus to check whether some­thing left untracked or not

Reverse a com­mit­ted push
git reverse <commit’s hash> will cre­ate a new com­mit, which you’ll have to push

Cher­ry pick a com­mit
Lets say you want to cher­ry pick com­mit 6a23b56 from fea­ture branch to mas­ter. You must be in mas­ter and then do
git cher­ry-pick ‑x 6a23b56
that’s all !

Remov­ing Files
Say that u delet­ed a file from disk, now it will show as delet­ed in git sta­tus. How to make that change on serv­er also?
Do
git rm <file path and name>
git com­mit
git push
sim­ple!

Mov­ing repo from one loca­tion to anoth­er (or dupli­cat­ing repo to some new loca­tion)
git remote add new_repo_name new_repo_url
Then push the con­tent to the new loca­tion
git push new_repo_name mas­ter
Final­ly remove the old one
git remote rm ori­gin
After that edit the.git/config file to change the new_repo_name to ori­gin.

If you don’t remove the ori­gin (orig­i­nal remote repos­i­to­ry), you can sim­ply just push changes to the new repo with
git push new_repo_name mas­ter

If you delete a file in one branch and don’t com­mit or stash then those files will appear delet­ed on oth­er branch­es
Switch­ing branch­es car­ries uncom­mit­ted changes with you. Either com­mit first, run git check­out . to undo them, or run git stash before switch­ing. (You can get your changes back with git stash apply

Revert a spe­cif­ic file to some ear­li­er git ver­sion
Find the com­mit where you went wrong, either using git log or git lop ‑p or gitk
Find the com­mit hash
git check­out com­mit­code filepath

Now com­mit again

Com­mit a sin­gle file
git com­mit ‑m ‘com­ments’ filepath

SSH set­up between ur machine’s repo and serv­er repo
Cd to home dir
Do
ssh-key­gen ‑t rsa ‑C “your_email@example.com”
clip < ~/.ssh/id_rsa.pub

Save on serv­er

How to see my last n com­mits
git log ‑n 5 –author=vaibhavk

How to see con­tents of a par­tic­u­lar com­mit
git show hash­val­ue

What’s A, B and C in Kdiff3
A is the orig­i­nal file, before any merge con­flicts hap­pened
B is the your cur­rent file (includ­ing any uncom­mit­ted changes)
C is the incom­ing file that caused merge con­flict

How to see uncom­mit­ted changes for a spe­cif­ic file against ear­li­er ver­sion(?)
git diff filepath

Undo git add
Git reset filepath

See if a com­mit is in a branch or its in what branch­es
git branch ‑a –con­tains 4f08c85ad (remove ‑a to see only your local branch­es)
List git com­mits not pushed yet
git log origin/master..master
Or git log <since>..<until>
You can use this with grep to check for a spe­cif­ic, known com­mit:
git log <since>..<until> | grep <com­mit-hash>

Undo last com­mit

git com­mit ‑m “Some­thing ter­ri­bly mis­guid­ed”
git reset HEAD~
« edit files as nec­es­sary »
git add <what­ev­er>
git com­mit ‑c ORIG_HEAD

Making your subdomain respect index.html, index.php, etc.

subdomains image

I am not sure about you but I faced an issue when I was try­ing to add my resume as a sep­a­rate sub­do­main on my domain. The prob­lem was that when I added the index.html page into the sub­do­main fold­er and tried to browse the site — it just did­n’t work! Although the main site panghal.com also had an index.html and it worked per­fect­ly fine, the sub­do­main was not respect­ing the spe­cial posi­tion that’s to be enjoyed by index.html. After some search­ing on the web I found that I had to mod­i­fy the .htac­cess present in my root. I just added the fol­low­ing line -

Direc­to­ryIn­dex index.html index.php

and then it all worked just fine.

Triggr and free lunch with Ahti

So got up a lit­tle late on last Sat­ur­day morn­ing and there was this event ‘Trig­gr the Prod­uct’ in sec­tor 65 Noida.…I had pre­vi­ous­ly missed ‘Trig­gr the Web’ and ‘Trig­gr the Mobile’ and I some­how con­soled myself that prob­a­bly they were not good enough. Any­ways, it was to start at 9 in the morn­ing and prob­a­bly it did because by the time we got there it was the first tea break at about 11:30am. Some of the speak­ers had already spo­ken and prob­a­bly left. So we went straight in (Gau­rav and Than­di were there with me as well) and had soft drinks, and chips and sand­wich­es! Good start! Now what?

So let me just give a brief intro to Trig­gr. So Trig­gr is this series of one day tech events done by this Noi­da based start up called Insta­me­dia. They basi­cal­ly invite devel­op­ers and start up guys to inter­act. This way some peo­ple may get some inter­est­ing oppor­tu­ni­ties and the start ups are a giv­en a sort of plat­form to advertise/speak. As for the rest, its all very inter­est­ing tech relat­ed dis­cus­sions hap­pen­ing. So its a beau­ti­ful way for a devel­op­er to spend such a day, say, once in a few months. The thing is that they call real­ly good peo­ple for the stage. And since the invi­ta­tion to this event is by mail invite only, it some­how attracts decent enough crowd, if not the best. But prob­a­bly the crowd that is inter­est­ed in doing some­thing oth­er­wise why would any­one (includ­ing me) would wake up and go to a tech event on a Sat­ur­day morn­ing !!! — the per­son is got to be a techie !

So went down­stairs and grabbed our seats. Up came the next speak­er. He was an IIT grad and had worked in Adobe for sev­er­al years and was now employed with Lava, the new Indi­an mobile com­pa­ny with high ambi­tions. He talked a lot qual­i­ty. And about how the prob­lem of brand­ing Lava as a techie’s prod­uct and not a rur­al india prod­uct was becom­ing a chal­lenge for the com­pa­ny. It re-iter­ates the notion of good adver­tiz­ing as one of the most impor­tant fac­tors for the suc­cess of a prod­uct. Then came up Piyush to speak about his start up Eko — how one will be able to trans­fer mon­ey from one account to anoth­er just by press­ing a keys on the key­pad of the cell phone itself! Bril­liant guy. Tax span­ner guy spoke. Not all speak­ers were good but ya, like, most were excel­lent. It all gave a very deep insight about prod­uct build­ing or even how to build a start up!
And in the end spoke Ahti. Now this the guy who built skype. He was the chief archi­tect at skype! Super guy I must say.

It all gave an insight as to how idea is the sin­gle most impor­tant thing in the begin­ning and not the tech­nol­o­gy or the tech­nique. How impor­tant is it to first build a demo or a sim­ple UI and show to users first before begin­ning the actu­al cod­ing. This gives you the val­ue propo­si­tion as to how much val­ue your prod­uct holds as of now. Its impor­tant to get ear­ly feed­back so that you build the right prod­uct for your tar­get users rather than build first, then keep on improv­ing. Its impor­tant to keep the main thing ‘the main thing’. Do not lose your­self in the side­lines. And its very impor­tant to ship your code fast and to start adver­tiz­ing in all ways pos­si­ble as much as you can right from the first day itself.

So, in all — a super cool expe­ri­ence. Oh and yes, there was free lunch too !!

Came back, strug­gled with Html5 video and final­ly it worked fine. Fall back mech­a­nism is not full proof yet but yes it works!

The thing with this home­page exer­cise is that I will fin­ish come what may. It’s not only a mat­ter of learn­ing html5 or javascript or any­thing. Fin­ish­ing what one starts is a mark of char­ac­ter ! It shows per­sis­tence and the will to go mad if time demands. It shows your true grit!

And any­ways, I have to also cut my beard once this thing goes online! Oh and yes, I also have to fix myself a more beau­ti­ful ver­sion.

By the way — you can view Trig­gr stuff here http://www.triggr.in/
And you can read about Ahti here http://en.wikipedia.org/wiki/Ahti_Heinla