Exemple #1
0
  @Test
  public void testUnauthorizedLoginClone() throws Exception {
    // restrict repository access
    RepositoryModel model = GitBlit.self().getRepositoryModel("ticgit.git");
    model.accessRestriction = AccessRestrictionType.CLONE;
    model.authorizationControl = AuthorizationControl.NAMED;
    UserModel user = new UserModel("james");
    user.password = "******";
    GitBlit.self().updateUserModel(user.username, user, true);
    GitBlit.self().updateRepositoryModel(model.name, model, false);

    FileUtils.delete(ticgit2Folder, FileUtils.RECURSIVE);

    // delete any existing working folder
    boolean cloned = false;
    try {
      CloneCommand clone = Git.cloneRepository();
      clone.setURI(MessageFormat.format("{0}/git/ticgit.git", url));
      clone.setDirectory(ticgit2Folder);
      clone.setBare(false);
      clone.setCloneAllBranches(true);
      clone.setCredentialsProvider(
          new UsernamePasswordCredentialsProvider(user.username, user.password));
      close(clone.call());
      cloned = true;
    } catch (Exception e) {
      // swallow the exception which we expect
    }

    assertFalse("Unauthorized login cloned a repository?!", cloned);

    FileUtils.delete(ticgit2Folder, FileUtils.RECURSIVE);

    // switch to authenticated
    model.authorizationControl = AuthorizationControl.AUTHENTICATED;
    GitBlit.self().updateRepositoryModel(model.name, model, false);

    // try clone again
    cloned = false;
    CloneCommand clone = Git.cloneRepository();
    clone.setURI(MessageFormat.format("{0}/git/ticgit.git", url));
    clone.setDirectory(ticgit2Folder);
    clone.setBare(false);
    clone.setCloneAllBranches(true);
    clone.setCredentialsProvider(
        new UsernamePasswordCredentialsProvider(user.username, user.password));
    close(clone.call());
    cloned = true;

    assertTrue("Authenticated login could not clone!", cloned);

    FileUtils.delete(ticgit2Folder, FileUtils.RECURSIVE);

    // restore anonymous repository access
    model.accessRestriction = AccessRestrictionType.NONE;
    model.authorizationControl = AuthorizationControl.NAMED;
    GitBlit.self().updateRepositoryModel(model.name, model, false);
    GitBlit.self().deleteUser(user.username);
  }
  public static void updateRepository(String localPath, String remotePath) throws Exception {
    Repository localRepo;
    try {
      localRepo = new FileRepository(localPath + "/.git");

      Git git = new Git(localRepo);
      {
        AsposeConstants.println("Cloning Repository [" + remotePath + "]....");
      }

      // First try to clone the repository
      try {
        Git.cloneRepository().setURI(remotePath).setDirectory(new File(localPath)).call();
      } catch (Exception ex) {
        // If clone fails, try to pull the changes
        try {
          git.pull().call();
        } catch (Exception exPull) {
          // Pull also failed. Throw this exception to caller
          {
            AsposeConstants.println("Pull also failed.");
          }
          throw exPull; // throw it
        }
      }
    } catch (Exception ex) {
      throw new Exception("Could not download Repository from Github. Error: " + ex.getMessage());
    }
  }
Exemple #3
0
  /**
   * This will create or refresh the working copy. If the working copy cannot be pulled cleanly this
   * method will fail.
   *
   * @param gitRepositoryUri remote git repository URI string
   * @return git
   * @throws GitAPIException
   * @throws IOException
   * @throws URISyntaxException
   */
  private Git getGit(final String gitRepositoryUri)
      throws GitAPIException, IOException, URISyntaxException {
    final Git cachedGit = gitCache.get(gitRepositoryUri);
    if (cachedGit != null) {
      return cachedGit;
    }
    final File gitDir =
        File.createTempFile(
            gitRepositoryUri.replaceAll("[^A-Za-z]", "_"), "wagon-git"); // $NON-NLS-1$
    gitDir.delete();
    gitDir.mkdir();

    credentialsProvider =
        new UsernamePasswordCredentialsProvider(
            getAuthenticationInfo().getUserName(),
            getAuthenticationInfo().getPassword() == null
                ? "" //$NON-NLS-1$
                : getAuthenticationInfo().getPassword());
    final Git git =
        Git.cloneRepository()
            .setURI(gitRepositoryUri)
            .setCredentialsProvider(credentialsProvider)
            .setBranch(gitUri.getBranchName())
            .setDirectory(gitDir)
            .call();
    if (!gitUri.getBranchName().equals(git.getRepository().getBranch())) {
      LOG.log(Level.INFO, "missingbranch", gitUri.getBranchName());
      final RefUpdate refUpdate =
          git.getRepository().getRefDatabase().newUpdate(Constants.HEAD, true);
      refUpdate.setForceUpdate(true);
      refUpdate.link("refs/heads/" + gitUri.getBranchName()); // $NON-NLS-1$
    }
    gitCache.put(gitRepositoryUri, git);
    return git;
  }
Exemple #4
0
 public static Git clone(final DirectoryResource dir, final String repoUri)
     throws GitAPIException {
   CloneCommand clone =
       Git.cloneRepository().setURI(repoUri).setDirectory(dir.getUnderlyingResourceObject());
   Git git = clone.call();
   return git;
 }
Exemple #5
0
  @Test
  public void testBogusLoginClone() throws Exception {
    // restrict repository access
    RepositoryModel model = GitBlit.self().getRepositoryModel("ticgit.git");
    model.accessRestriction = AccessRestrictionType.CLONE;
    GitBlit.self().updateRepositoryModel(model.name, model, false);

    // delete any existing working folder
    boolean cloned = false;
    try {
      CloneCommand clone = Git.cloneRepository();
      clone.setURI(MessageFormat.format("{0}/git/ticgit.git", url));
      clone.setDirectory(ticgit2Folder);
      clone.setBare(false);
      clone.setCloneAllBranches(true);
      clone.setCredentialsProvider(new UsernamePasswordCredentialsProvider("bogus", "bogus"));
      close(clone.call());
      cloned = true;
    } catch (Exception e) {
      // swallow the exception which we expect
    }

    // restore anonymous repository access
    model.accessRestriction = AccessRestrictionType.NONE;
    GitBlit.self().updateRepositoryModel(model.name, model, false);

    assertFalse("Bogus login cloned a repository?!", cloned);
  }
Exemple #6
0
  @Test
  public void testPushToNonBareRepository() throws Exception {
    CloneCommand clone = Git.cloneRepository();
    clone.setURI(MessageFormat.format("{0}/git/working/jgit", url));
    clone.setDirectory(jgit2Folder);
    clone.setBare(false);
    clone.setCloneAllBranches(true);
    clone.setCredentialsProvider(new UsernamePasswordCredentialsProvider(account, password));
    close(clone.call());
    assertTrue(true);

    Git git = Git.open(jgit2Folder);
    File file = new File(jgit2Folder, "NONBARE");
    OutputStreamWriter os =
        new OutputStreamWriter(new FileOutputStream(file, true), Constants.CHARSET);
    BufferedWriter w = new BufferedWriter(os);
    w.write("// " + new Date().toString() + "\n");
    w.close();
    git.add().addFilepattern(file.getName()).call();
    git.commit().setMessage("test commit followed by push to non-bare repository").call();
    try {
      git.push().setPushAll().call();
      assertTrue(false);
    } catch (Exception e) {
      assertTrue(e.getCause().getMessage().contains("git-receive-pack not permitted"));
    }
    close(git);
  }
  @Test(expected = BranchOutOfDateException.class)
  public void finishHotfixMasterBehindRemoteWithFetch() throws Exception {
    Git git = null;
    Git remoteGit = null;
    remoteGit = RepoUtil.createRepositoryWithMasterAndTag(newDir());

    git =
        Git.cloneRepository()
            .setDirectory(newDir())
            .setURI("file://" + remoteGit.getRepository().getWorkTree().getPath())
            .call();

    JGitFlowInitCommand initCommand = new JGitFlowInitCommand();
    JGitFlow flow = initCommand.setDirectory(git.getRepository().getWorkTree()).call();

    flow.hotfixStart("1.1").call();

    // do a commit to the remote develop branch
    remoteGit.checkout().setName(flow.getDevelopBranchName());
    File junkFile = new File(remoteGit.getRepository().getWorkTree(), "junk.txt");
    FileUtils.writeStringToFile(junkFile, "I am junk");
    remoteGit.add().addFilepattern(junkFile.getName()).call();
    remoteGit.commit().setMessage("adding junk file").call();

    flow.hotfixFinish("1.1").setFetch(true).call();
  }
Exemple #8
0
  private IStatus doClone() {
    try {
      File cloneFolder = new File(clone.getContentLocation().getPath());
      if (!cloneFolder.exists()) {
        cloneFolder.mkdir();
      }
      CloneCommand cc = Git.cloneRepository();
      cc.setBare(false);
      cc.setCredentialsProvider(credentials);
      cc.setDirectory(cloneFolder);
      cc.setRemote(Constants.DEFAULT_REMOTE_NAME);
      cc.setURI(clone.getUrl());
      Git git = cc.call();

      // Configure the clone, see Bug 337820
      setMessage(NLS.bind("Configuring {0}...", clone.getUrl()));
      GitCloneHandlerV1.doConfigureClone(git, user);
      git.getRepository().close();
    } catch (IOException e) {
      return new Status(IStatus.ERROR, GitActivator.PI_GIT, "Error cloning git repository", e);
    } catch (CoreException e) {
      return e.getStatus();
    } catch (GitAPIException e) {
      return getGitAPIExceptionStatus(e, "Error cloning git repository");
    } catch (JGitInternalException e) {
      return getJGitInternalExceptionStatus(e, "Error cloning git repository");
    } catch (Exception e) {
      return new Status(IStatus.ERROR, GitActivator.PI_GIT, "Error cloning git repository", e);
    }
    return Status.OK_STATUS;
  }
  private void cloneGitProject() throws GitAPIException {
    Git result =
        Git.cloneRepository()
            .setURI(MODULE_GITHUB_URL)
            .setDirectory(new File(testDirectory, OPENMRS_MODULE_IDGEN))
            .call();

    result.close();
  }
 public static boolean clone(String URL, String localpaths) throws IOException, GitAPIException {
   File localPath = new File(localpaths);
   if (!localPath.exists()) localPath.mkdir();
   try {
     Git result = Git.cloneRepository().setURI(URL).setDirectory(localPath).call();
     result.getRepository().close();
     return true;
   } catch (Exception e) {
     return false;
   }
 }
  /** Clones or pulls the remote repository and returns the directory with the checkout */
  public void cloneOrPull(final String repo, final CredentialsProvider credentials)
      throws Exception {
    if (!localRepo.exists() && !localRepo.mkdirs()) {
      throw new IOException("Failed to create local repository");
    }
    File gitDir = new File(localRepo, ".git");
    if (!gitDir.exists()) {
      LOG.info("Cloning remote repo " + repo);
      CloneCommand command =
          Git.cloneRepository()
              .setCredentialsProvider(credentials)
              .setURI(repo)
              .setDirectory(localRepo)
              .setRemote(remoteName);
      git = command.call();
    } else {
      FileRepositoryBuilder builder = new FileRepositoryBuilder();
      Repository repository =
          builder
              .setGitDir(gitDir)
              .readEnvironment() // scan environment GIT_* variables
              .findGitDir() // scan up the file system tree
              .build();

      git = new Git(repository);

      // update the remote repo just in case
      StoredConfig config = repository.getConfig();
      config.setString("remote", remoteName, "url", repo);
      config.setString(
          "remote", remoteName, "fetch", "+refs/heads/*:refs/remotes/" + remoteName + "/*");

      String branch = "master";
      config.setString("branch", branch, "remote", remoteName);
      config.setString("branch", branch, "merge", "refs/heads/" + branch);

      try {
        config.save();
      } catch (IOException e) {
        LOG.error(
            "Failed to save the git configuration to "
                + localRepo
                + " with remote repo: "
                + repo
                + ". "
                + e,
            e);
      }

      // now pull
      LOG.info("Pulling from remote repo " + repo);
      git.pull().setCredentialsProvider(credentials).setRebase(true).call();
    }
  }
Exemple #12
0
 @Test
 public void testClone() throws Exception {
   CloneCommand clone = Git.cloneRepository();
   clone.setURI(MessageFormat.format("{0}/git/ticgit.git", url));
   clone.setDirectory(ticgitFolder);
   clone.setBare(false);
   clone.setCloneAllBranches(true);
   clone.setCredentialsProvider(new UsernamePasswordCredentialsProvider(account, password));
   close(clone.call());
   assertTrue(true);
 }
 @Override
 public String CloneService(post post) {
   File localPath = null;
   try {
     localPath = File.createTempFile("TestGitRepository", "");
     localPath.delete();
     post.setPath(localPath.getPath());
     Git.cloneRepository().setURI(post.getUrl()).setDirectory(localPath).call();
     return post.getPath();
   } catch (GitAPIException | IOException e) {
   }
   return "";
 }
  static Git makeClone() throws Exception {

    final CloneCommand clone = Git.cloneRepository();
    clone.setBare(false);
    clone.setDirectory(FILE).setURI(URL);

    final CredentialsProvider provider = //
        new UsernamePasswordCredentialsProvider(USER, PASS);

    clone.setCredentialsProvider(provider);

    return clone.call();
  }
  @Override
  public ResourceMap generateOutputs(Map<String, List<Object>> parameters, IProgressMonitor monitor)
      throws Exception {
    File workingDir = null;
    File gitDir = null;

    // Get existing checkout if available
    synchronized (this) {
      if (checkedOut != null) {
        workingDir = checkedOut.getWorkTree();
        gitDir = new File(workingDir, ".git");
      }
    }

    if (workingDir == null) {
      // Need to do a new checkout
      workingDir = Files.createTempDirectory("checkout").toFile();
      gitDir = new File(workingDir, ".git");
      String branch = params.branch != null ? params.branch : GitCloneTemplateParams.DEFAULT_BRANCH;

      try {
        CloneCommand cloneCmd =
            Git.cloneRepository()
                .setURI(params.cloneUrl)
                .setDirectory(workingDir)
                .setNoCheckout(true);
        cloneCmd.setProgressMonitor(new EclipseGitProgressTransformer(monitor));
        cloneCmd.setBranchesToClone(Collections.singleton(branch));
        Git git = cloneCmd.call();

        git.checkout().setCreateBranch(true).setName("_tmp").setStartPoint(branch).call();
        checkedOut = git.getRepository();
      } catch (JGitInternalException e) {
        Throwable cause = e.getCause();
        if (cause instanceof Exception) throw (Exception) cause;
        throw e;
      }
    }

    final File exclude = gitDir;
    FileFilter filter =
        new FileFilter() {
          @Override
          public boolean accept(File path) {
            return !path.equals(exclude);
          }
        };
    return toResourceMap(workingDir, filter);
  }
  /*
   * (non-Javadoc)
   *
   * @see nl.minicom.gitolite.manager.git.GitManager#clone(java.lang.String)
   */
  @Override
  public void clone(String uri) throws IOException, ServiceUnavailable {
    Preconditions.checkNotNull(uri);

    CloneCommand clone = Git.cloneRepository();
    clone.setDirectory(workingDirectory);
    clone.setURI(uri);
    clone.setCredentialsProvider(credentialProvider);
    try {
      git = clone.call();
    } catch (NullPointerException e) {
      throw new ServiceUnavailable(e);
    } catch (JGitInternalException e) {
      throw new IOException(e);
    }
  }
 /**
  * Clones secured git remote repository to the file system.
  *
  * @param gitDirectory where the remote repository will be cloned
  * @param repositoryURI repository's URI example: https://qwerty.com/xyz/abc.git
  * @param username the username used for authentication
  * @param password the password used for authentication
  * @throws InvalidRemoteException
  * @throws TransportException
  * @throws GitAPIException
  */
 public static void cloneRepository(
     File gitDirectory, String repositoryURI, String username, String password)
     throws InvalidRemoteException, TransportException, GitAPIException {
   try {
     CloneCommand cloneCommand = Git.cloneRepository();
     cloneCommand.setURI(repositoryURI);
     if (!StringUtils.isEmptyOrNull(username) && !StringUtils.isEmptyOrNull(password)) {
       cloneCommand.setCredentialsProvider(
           new UsernamePasswordCredentialsProvider(username, password));
     }
     cloneCommand.setRemote(Constants.DEFAULT_REMOTE_NAME);
     cloneCommand.setDirectory(gitDirectory);
     cloneCommand.call();
   } catch (NullPointerException e) {
     throw new TransportException(INVALID_USERNAME_AND_PASSWORD);
   }
 }
Exemple #18
0
 public static void cloneRepository(GitInput input) throws GitException {
   try {
     Git git =
         Git.cloneRepository()
             .setURI(input.url)
             .setDirectory(input.directory)
             .setCloneSubmodules(input.cloneSubmodules)
             .call();
     for (String branchName : input.branchesToClone) {
       git.checkout()
           .setCreateBranch(true)
           .setName(branchName)
           .setStartPoint("origin/" + branchName)
           .call();
     }
     git.checkout().setName(input.bound.getBound()).call();
   } catch (GitAPIException e) {
     throw new GitException("Clone of repository " + input.url + " failed", e);
   }
 }
Exemple #19
0
  @Test
  public void testSubfolderPush() throws Exception {
    CloneCommand clone = Git.cloneRepository();
    clone.setURI(MessageFormat.format("{0}/git/test/jgit.git", url));
    clone.setDirectory(jgitFolder);
    clone.setBare(false);
    clone.setCloneAllBranches(true);
    clone.setCredentialsProvider(new UsernamePasswordCredentialsProvider(account, password));
    close(clone.call());
    assertTrue(true);

    Git git = Git.open(jgitFolder);
    File file = new File(jgitFolder, "TODO");
    OutputStreamWriter os =
        new OutputStreamWriter(new FileOutputStream(file, true), Constants.CHARSET);
    BufferedWriter w = new BufferedWriter(os);
    w.write("// " + new Date().toString() + "\n");
    w.close();
    git.add().addFilepattern(file.getName()).call();
    git.commit().setMessage("test commit").call();
    git.push().setPushAll().call();
    close(git);
  }
Exemple #20
0
 /** Clones a Git repository as configured. */
 @TaskAction
 public void cloneRepo() {
   CloneCommand cmd = Git.cloneRepository();
   TransportAuthUtil.configure(cmd, this);
   cmd.setURI(getUri().toString());
   cmd.setRemote(getRemote());
   cmd.setBare(getBare());
   cmd.setNoCheckout(!getCheckout());
   cmd.setBranch(getRef());
   cmd.setBranchesToClone(getBranchesToClone());
   cmd.setCloneAllBranches(getCloneAllBranches());
   cmd.setDirectory(getDestinationDir());
   try {
     cmd.call();
   } catch (InvalidRemoteException e) {
     throw new GradleException("Invalid remote specified: " + getRemote(), e);
   } catch (TransportException e) {
     throw new GradleException("Problem with transport.", e);
   } catch (GitAPIException e) {
     throw new GradleException("Problem with clone.", e);
   }
   // TODO add progress monitor to log progress to Gradle status bar
 }
  private void registerServlet() {
    try {
      HttpContext base = httpService.get().createDefaultHttpContext();
      HttpContext secure = new SecureHttpContext(base, realm, role);
      String basePath =
          System.getProperty("karaf.data")
              + File.separator
              + "git"
              + File.separator
              + "servlet"
              + File.separator;
      String fabricGitPath = basePath + "fabric";
      File fabricRoot = new File(fabricGitPath);

      // Only need to clone once. If repo already exists, just skip.
      if (!fabricRoot.exists()) {
        Git localGit = gitService.get().get();
        Git.cloneRepository()
            .setBare(true)
            .setNoCheckout(true)
            .setCloneAllBranches(true)
            .setDirectory(fabricRoot)
            .setURI(localGit.getRepository().getDirectory().toURI().toString())
            .call();
      }

      Dictionary<String, Object> initParams = new Hashtable<String, Object>();
      initParams.put("base-path", basePath);
      initParams.put("repository-root", basePath);
      initParams.put("export-all", "true");
      httpService.get().registerServlet("/git", gitServlet, initParams, secure);
      activateComponent();
    } catch (Exception e) {
      FabricException.launderThrowable(e);
    }
  }
Exemple #22
0
  protected void initGitRepo() throws MojoExecutionException, IOException, GitAPIException {
    buildDir.mkdirs();
    File gitDir = new File(buildDir, ".git");
    if (!gitDir.exists()) {
      String repo = gitUrl;
      if (Strings.isNotBlank(repo)) {
        getLog()
            .info(
                "Cloning git repo "
                    + repo
                    + " into directory "
                    + getGitBuildPathDescription()
                    + " cloneAllBranches: "
                    + cloneAll);
        CloneCommand command =
            Git.cloneRepository()
                .setCloneAllBranches(cloneAll)
                .setURI(repo)
                .setDirectory(buildDir)
                .setRemote(remoteName);
        // .setCredentialsProvider(getCredentials()).
        try {
          git = command.call();
          return;
        } catch (Throwable e) {
          getLog().error("Failed to command remote repo " + repo + " due: " + e.getMessage(), e);
          // lets just use an empty repo instead
        }
      } else {
        InitCommand initCommand = Git.init();
        initCommand.setDirectory(buildDir);
        git = initCommand.call();
        getLog()
            .info("Initialised an empty git configuration repo at " + getGitBuildPathDescription());

        // lets add a dummy file
        File readMe = new File(buildDir, "ReadMe.md");
        getLog().info("Generating " + readMe);
        Files.writeToFile(
            readMe,
            "fabric8 git repository created by fabric8-maven-plugin at " + new Date(),
            Charset.forName("UTF-8"));
        git.add().addFilepattern("ReadMe.md").call();
        commit("Initial commit");
      }
      String branch = git.getRepository().getBranch();
      configureBranch(branch);
    } else {
      getLog().info("Reusing existing git repository at " + getGitBuildPathDescription());

      FileRepositoryBuilder builder = new FileRepositoryBuilder();
      Repository repository =
          builder
              .setGitDir(gitDir)
              .readEnvironment() // scan environment GIT_* variables
              .findGitDir() // scan up the file system tree
              .build();

      git = new Git(repository);
      if (pullOnStartup) {
        doPull();
      } else {
        getLog().info("git pull from remote config repo on startup is disabled");
      }
    }
  }
Exemple #23
0
 public CloneCommand createCloneCommand() {
   return Git.cloneRepository();
 }
  public void cloneBinaryRepository() throws GitException {

    // find the name of the "source repository"
    String srcRepoUrl = getSourceRemoteUrl();
    String org = GitUtils.getOrgName(srcRepoUrl);
    String repoName = GitUtils.getRepositoryName(srcRepoUrl);
    String binaryRepoName = calculateBinaryRepositoryName(org, repoName);

    // find where ".git" folder is found
    File f = sourceRepository.getDirectory();
    File sourceDir = f.getParentFile();

    String sourceRepoFolderName = f.getParentFile().getName();

    // construct the binary repository URL
    String giturl = "[email protected]:Binary/" + binaryRepoName + ".git";

    // calculate binary repository folder
    File parent = f.getParentFile().getParentFile();
    File binaryRepoFolder = new File(parent, ("." + sourceRepoFolderName));

    // clone the binary repository
    CloneCommand cloneCmd = Git.cloneRepository();
    cloneCmd.setURI(giturl);
    cloneCmd.setDirectory(binaryRepoFolder);
    cloneCmd.setCloneAllBranches(true);

    Git binrepository = null;

    try {

      System.out.println("cloning repository " + giturl);
      binrepository = cloneCmd.call();

      binaryRepository = new FileRepository(binrepository.getRepository().getDirectory());

    } catch (InvalidRemoteException e) {
      throw new GitException("unable to clone " + giturl, e);
    } catch (TransportException e) {
      throw new GitException("unable to clone " + giturl, e);
    } catch (GitAPIException e) {
      throw new GitException("unable to clone " + giturl, e);
    } catch (IOException e) {
      throw new GitException("unable assign " + giturl, e);
    }

    // read the branch from "source" repository
    String branchName = "master";
    try {
      branchName = sourceRepository.getBranch();
    } catch (IOException e) {
      e.printStackTrace();
    }

    // Checkout the "branch" if it is not equal to "master"
    if (!branchName.toLowerCase().equals("master")) {

      // check whether the branch exists
      boolean remoteBranchExists = GitUtils.isRemoteBranchExists(binaryRepository, branchName);

      CheckoutResult result = null;

      if (!remoteBranchExists) {

        try {

          // create branch
          Git binrepo = Git.wrap(binaryRepository);
          CreateBranchCommand branchCmd = binrepo.branchCreate();
          branchCmd.setName(branchName);
          branchCmd.call();

          // checkout the branch
          CheckoutCommand checkout = binrepo.checkout();
          checkout.setName(branchName);
          Ref ref = checkout.call();

          if (ref == null) {
            // TODO:
          } else {
            result = checkout.getResult();
          }

        } catch (RefAlreadyExistsException e) {
          throw new GitException("unable to create branch " + branchName, e);
        } catch (RefNotFoundException e) {
          throw new GitException("unable to create branch " + branchName, e);
        } catch (InvalidRefNameException e) {
          throw new GitException("unable to create branch " + branchName, e);
        } catch (GitAPIException e) {
          throw new GitException("unable to create branch " + branchName, e);
        }

      } else {

        CheckoutCommand checkoutCmd = binrepository.checkout();
        checkoutCmd.setCreateBranch(true);
        checkoutCmd.setName(branchName);
        checkoutCmd.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK);
        checkoutCmd.setStartPoint("origin/" + branchName);

        System.out.println("checking out branch " + branchName);

        try {
          // Ref branch = branchCmd.call();
          Ref ref = checkoutCmd.call();
          System.out.println("checkout is complete");
          if (ref != null) {
            // System.out.println("ref " + ref.getName() );
            result = checkoutCmd.getResult();
          }

        } catch (RefAlreadyExistsException e) {
          throw new GitException("unable to checkout branch " + branchName, e);
        } catch (RefNotFoundException e) {
          throw new GitException("unable to checkout branch " + branchName, e);
        } catch (InvalidRefNameException e) {
          throw new GitException("unable to checkout branch " + branchName, e);
        } catch (CheckoutConflictException e) {
          throw new GitException("unable to checkout branch " + branchName, e);
        } catch (GitAPIException e) {
          throw new GitException("unable to checkout branch " + branchName, e);
        }
      }

      if (result.getStatus().equals(CheckoutResult.OK_RESULT)) {
        System.out.println("checkout is OK");
      } else {
        // TODO: handle the error.
      }
    }

    // System.out.println( result.getStatus());
    // TODO: find out whether Binary is upto-date with the sources

    /*
    // call the MapSvc to find it out.
          final org.eclipse.jgit.lib.Repository repository = new org.eclipse.jgit.storage.file.FileRepository(f);
          final RevWalk revWalk = new RevWalk(repository);
          final ObjectId resolve = repository.resolve(Constants.HEAD);
          final RevCommit commit = revWalk.parseCommit(resolve);
          final String commitHash = commit.getName();
          final String url = getUrlForFindByRepoBranchCommit() + "repourl=" + URLEncoder.encode(getSourceRemoteUrl(), UTF_8) +
                  "&branch=" + URLEncoder.encode(branchName, UTF_8) + "&commitid=" + URLEncoder.encode(commitHash, UTF_8);

          final WebResource webResource = client.resource(url);
          boolean noContent = false;

          BinRepoBranchCommitDO binRepoBranchCommitDO = null;
          try {
          	System.out.println("calling mapsvc ");
              binRepoBranchCommitDO = webResource.accept(MediaType.APPLICATION_JSON_TYPE).get(BinRepoBranchCommitDO.class);
          } catch (UniformInterfaceException e) {
              int statusCode = e.getResponse().getClientResponseStatus().getStatusCode();
              noContent = (statusCode == 204);
          } catch (Exception e) { // catch-all in case there are network problems
              e.printStackTrace();
          }


          // No matching entry found in mapping service
          // TODO: RGIROTI Talk to Nambi and find out what we want to do in this case
          if (noContent) {

          } else {
              // if it matches copy the .class files from binaryrepository to source-repository
              if (binRepoBranchCommitDO != null &&
                      binRepoBranchCommitDO.getRepoUrl().equalsIgnoreCase(getSourceRemoteUrl()) &&
                      binRepoBranchCommitDO.getBranch().equalsIgnoreCase(branchName) &&
                      binRepoBranchCommitDO.getCommitId().equalsIgnoreCase(commitHash)) {

              }
          }
          */

    try {
      FileUtil.copyBinaryFolders(binaryRepoFolder, sourceDir, ".git");
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }