示例#1
0
  @Test
  public void dontPackHEAD_nonBare() throws Exception {
    BranchBuilder bb = tr.branch("refs/heads/side");
    RevCommit first = bb.commit().add("A", "A").add("B", "B").create();
    bb.commit().add("A", "A2").add("B", "B2").create();
    Git git = Git.wrap(repo);

    // check for the unborn branch master. HEAD should point to master and
    // master doesn't exist.
    assertEquals(repo.exactRef("HEAD").getTarget().getName(), "refs/heads/master");
    assertNull(repo.exactRef("HEAD").getTarget().getObjectId());
    gc.packRefs();
    assertSame(repo.exactRef("HEAD").getStorage(), Storage.LOOSE);
    assertEquals(repo.exactRef("HEAD").getTarget().getName(), "refs/heads/master");
    assertNull(repo.exactRef("HEAD").getTarget().getObjectId());

    git.checkout().setName("refs/heads/side").call();
    gc.packRefs();
    assertSame(repo.exactRef("HEAD").getStorage(), Storage.LOOSE);

    // check for detached HEAD
    git.checkout().setName(first.getName()).call();
    gc.packRefs();
    assertSame(repo.exactRef("HEAD").getStorage(), Storage.LOOSE);
  }
示例#2
0
文件: GitUtils.java 项目: snjeza/core
  public static Iterable<RevCommit> getLogForBranch(final Git repo, String branchName)
      throws GitAPIException, IOException {
    String oldBranch = repo.getRepository().getBranch();
    repo.checkout().setName(branchName).call();

    Iterable<RevCommit> commits = repo.log().call();

    repo.checkout().setName(oldBranch).call();

    return commits;
  }
示例#3
0
  private void completeUndo(Git git) {
    try {
      if (isUndo(git)) {
        git.checkout().setName("master").call();
        git.merge()
            .setStrategy(MergeStrategy.THEIRS)
            .include(git.getRepository().resolve("undo"))
            .setCommit(true)
            .call();
        git.branchDelete().setBranchNames("undo").call();
      }
    } catch (RuntimeException ex) {

    } catch (CheckoutConflictException e) {
      throw new RuntimeException(e);
    } catch (RefAlreadyExistsException e) {
      throw new RuntimeException(e);
    } catch (IOException e) {
      throw new RuntimeException(e);
    } catch (InvalidRefNameException e) {
      throw new RuntimeException(e);
    } catch (RefNotFoundException e) {
      throw new RuntimeException(e);
    } catch (GitAPIException e) {
      throw new RuntimeException(e);
    }
  }
示例#4
0
 public Document undoLastChange(Document document) {
   try {
     final File docDir = getDirForDoc(document.getId());
     if (!docDir.exists()) {
       return null;
     } else {
       Git git = Git.open(docDir);
       Iterator<RevCommit> it = git.log().setMaxCount(2).call().iterator();
       if (it.hasNext()) {
         final RevCommit c = it.next(); // current version
       }
       if (it.hasNext()) {
         RevCommit c = it.next(); // previous version
         if (isUndo(git)) {
           git.reset().setMode(ResetCommand.ResetType.HARD).setRef("HEAD~1").call();
         } else {
           git.branchCreate().setName("undo").setStartPoint(c).call();
           git.checkout().setName("undo").call();
         }
         return getDocument(document.getId());
       }
       return null;
     }
   } catch (IOException e) {
     throw new RuntimeException(e);
   } catch (NoHeadException e) {
     throw new RuntimeException(e);
   } catch (GitAPIException e) {
     throw new RuntimeException(e);
   }
 }
示例#5
0
  @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();
  }
 /**
  * Checkout to a valid tree-ish object example: "5c15e8", "master", "HEAD",
  * "21d5a96070353d01c0f30bc0559ab4de4f5e3ca0"
  *
  * @param name the tree-ish object
  * @return {@link org.eclipse.jgit.lib.Ref} object
  * @throws RefAlreadyExistsException
  * @throws RefNotFoundException
  * @throws InvalidRefNameException
  * @throws CheckoutConflictException
  * @throws GitAPIException
  */
 public Ref checkout(String name)
     throws RefAlreadyExistsException, RefNotFoundException, InvalidRefNameException,
         CheckoutConflictException, GitAPIException {
   CheckoutCommand checkoutCommand = git.checkout();
   checkoutCommand.setName(name);
   return checkoutCommand.call();
 }
示例#7
0
 public static void checkout(File directory, String hash) throws GitException {
   Git git = openRepository(directory);
   try {
     git.checkout().setName(hash).call();
   } catch (GitAPIException e) {
     throw new GitException("Checkout in directory " + directory + " failed", e);
   }
 }
  @Override
  public void checkoutToTree(String treeName) {

    try {
      git.checkout().setName(treeName).call();
    } catch (GitAPIException e) {
      throw new VisMinerAPIException(e.getMessage(), e);
    }
  }
示例#9
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);
   }
 }
示例#10
0
文件: GitUtils.java 项目: snjeza/core
  public static Ref switchBranch(final Git repo, final String branchName) {
    Ref switchedBranch = null;
    try {
      switchedBranch = repo.checkout().setName(branchName).call();
      if (switchedBranch == null)
        throw new RuntimeException("Couldn't switch to branch " + branchName);
    } catch (GitAPIException e) {
      e.printStackTrace();
    }

    return switchedBranch;
  }
示例#11
0
  public static void main(final String[] args) throws Exception {

    logger.debug("init");

    final FileRepositoryBuilder builder = new FileRepositoryBuilder();
    builder.setGitDir(FILE);
    builder.readEnvironment();
    builder.findGitDir();

    final Repository repo = builder.build();

    // logger.debug("branch=" + repo.getBranch());
    // logger.debug("state=" + repo.getRepositoryState());

    switch (repo.getRepositoryState()) {
      case BARE:
        break;
      case SAFE:
        break;
      default:
        logger.error("wrong state");
    }

    final Git git = make();
    logger.debug("state=" + git.getRepository().getRepositoryState());

    // git.checkout().setName(Constants.MASTER).call();
    // git.pull().setTimeout(10).call();

    git.fetch().call();

    git.checkout().setName("current-config").call();

    // runClone();

    // final Git git = Git.open(FILE);
    // final StatusCommand status = git.status();
    // final Status result = status.call();
    // logger.debug("result=" + result);

    // final Git git = new Git(repo);

    // final RevCommit commit =
    // git.commit().setMessage("test commit").call();

    // final RevTag tag = git.tag().setName("test_tag").call();

    // logger.debug("branch=" + repo.getBranch());
    // logger.debug("state=" + repo.getRepositoryState());

    logger.debug("done");
  }
示例#12
0
文件: GitUtils.java 项目: snjeza/core
 public static Ref checkout(
     final Git git,
     final Ref localRef,
     final boolean createBranch,
     final SetupUpstreamMode mode,
     final boolean force)
     throws GitAPIException {
   CheckoutCommand checkout = git.checkout();
   checkout.setName(Repository.shortenRefName(localRef.getName()));
   checkout.setForce(force);
   checkout.setUpstreamMode(mode);
   return checkout.call();
 }
示例#13
0
文件: GitUtils.java 项目: snjeza/core
 public static Ref checkout(
     final Git git,
     final String remote,
     final boolean createBranch,
     final SetupUpstreamMode mode,
     final boolean force)
     throws GitAPIException {
   CheckoutCommand checkout = git.checkout();
   checkout.setCreateBranch(createBranch);
   checkout.setName(remote);
   checkout.setForce(force);
   checkout.setUpstreamMode(mode);
   return checkout.call();
 }
示例#14
0
  @Test
  public void selectionWithProj1AndReflog() throws Exception {
    File gitDir = createProjectAndCommitToRepository();

    // create additional reflog entries
    Git git = new Git(lookupRepository(gitDir));
    git.checkout().setName("stable").call();
    git.checkout().setName("master").call();

    selectionWithProj1Common();

    // delete reflog again to not confuse other tests
    new File(gitDir, Constants.LOGS + "/" + Constants.HEAD).delete();
  }
示例#15
0
  @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);
  }
  @Test
  public void shouldReturnSourceMergeForLocalRef() throws Exception {
    // given
    Git git = new Git(repo);
    git.branchCreate()
        .setName("test2")
        .setStartPoint("refs/heads/master")
        .setUpstreamMode(SetupUpstreamMode.TRACK)
        .call();
    git.checkout().setName("test2").call();
    GitSynchronizeData gsd = new GitSynchronizeData(repo, R_HEADS + "test2", HEAD, false);

    // when
    String srcMerge = gsd.getSrcMerge();

    // then
    assertThat(srcMerge, is("refs/heads/master"));
  }
  @Test
  public void shouldReturnSourceMergeForRemoteBranch() throws Exception {
    // given
    Git git = new Git(repo);
    git.branchCreate()
        .setName("test3")
        .setStartPoint("refs/heads/master")
        .setUpstreamMode(SetupUpstreamMode.TRACK)
        .call();
    git.checkout().setName("test3").call();
    repo.renameRef(R_HEADS + "test3", Constants.R_REMOTES + "origin/master").rename();
    GitSynchronizeData gsd =
        new GitSynchronizeData(repo, "refs/remotes/origin/master", HEAD, false);

    // when
    String srcMerge = gsd.getSrcMerge();

    // then
    assertThat(srcMerge, is("refs/heads/master"));
  }
示例#18
0
  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();
    }
  }
示例#19
0
  public void createBinaryRepository() throws IOException, GitException, MapServiceException {
    // check whether "binary repository" exists
    if (isBinaryRepositoryAvailable()) throw new GitException("Repository already exists");

    // find the name of the "source repository"
    // String sourceRepoName = getRepositoryName();

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

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

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

    // create binary repository folder
    FileUtils.mkdir(binaryRepoFolder, true);

    // initialize "git" repository
    InitCommand initCmd = Git.init();
    initCmd.setDirectory(binaryRepoFolder);
    Git binaryRepo = null;
    try {
      System.out.println("initializing bare repository");
      binaryRepo = initCmd.call();
    } catch (GitAPIException e) {
      throw new GitException("unable to initialize repository", e);
    }

    System.out.println("adding readme.md file");
    createReadMeFile(binaryRepoFolder);

    // get "status"
    StatusCommand statusC = binaryRepo.status();
    Collection<String> toadd = GitUtils.getFilesToStage(statusC);

    // add "readme" file to staging
    if (toadd.size() > 0) {
      AddCommand add = binaryRepo.add();
      for (String file : toadd) {
        add.addFilepattern(file);
      }
      try {
        add.call();
        CommitCommand commit = binaryRepo.commit();
        commit.setMessage("initial commit");
        System.out.println("performing first commit");
        commit.call();
      } catch (NoFilepatternException e) {
        throw new GitException("unable to add file(s)", e);
      } catch (GitAPIException e) {
        throw new GitException("Unable to add or commit", e);
      }
    }

    // Calculate the remote url for binary repository
    String remoteUrl = calculateBinaryRepositoryUrl();

    // TODO: check whether the remote exists, if not create it, else fail
    GitHub github = new GitHubClient().getGithub();
    GHOrganization githubOrg = github.getOrganization("Binary");
    GHRepository repository = githubOrg.getRepository(GitUtils.getRepositoryName(remoteUrl));

    if (repository == null) {

      System.out.println("creating remote repository : " + remoteUrl);
      GHRepository repo =
          githubOrg.createRepository(
              GitUtils.getRepositoryName(remoteUrl),
              "Binary repository",
              "https://github.scm.corp.ebay.com",
              "Owners",
              true);

      System.out.println(repo.getUrl() + " created successfully ");

    } else {
      // fail, it shouldn't come here
    }

    // add "remote" repository
    StoredConfig config = binaryRepo.getRepository().getConfig();
    config.setString("remote", "origin", "url", remoteUrl);
    System.out.println("adding remote origin " + remoteUrl);
    config.save();

    // get "status"
    StatusCommand stat = binaryRepo.status();
    Collection<String> filesToAdd = GitUtils.getFilesToStage(stat);

    // add files to "staging"
    if (filesToAdd.size() > 0) {
      AddCommand addCmd = binaryRepo.add();
      for (String file : filesToAdd) {
        addCmd.addFilepattern(file);
      }
      try {
        addCmd.call();
      } catch (NoFilepatternException e) {
        throw new GitException("unable to add files", e);
      } catch (GitAPIException e) {
        throw new GitException("unable to add files", e);
      }
    }

    // commit
    System.out.println("commiting the files");
    CommitCommand commit = binaryRepo.commit();
    // add the 'source' repository git-url, commit-id and branch
    commit.setMessage("adding readme.md file");

    try {
      commit.call();
    } catch (NoHeadException e) {
      throw new GitException("unable to commit", e);
    } catch (NoMessageException e) {
      throw new GitException("unable to commit", e);
    } catch (UnmergedPathsException e) {
      throw new GitException("unable to commit", e);
    } catch (ConcurrentRefUpdateException e) {
      throw new GitException("unable to commit", e);
    } catch (WrongRepositoryStateException e) {
      throw new GitException("unable to commit", e);
    } catch (GitAPIException e) {
      throw new GitException("unable to commit", e);
    }

    // push
    System.out.println("pushing to remote");
    PushCommand push = binaryRepo.push();
    try {
      push.call();
    } catch (InvalidRemoteException e) {
      throw new GitException("unable to push", e);
    } catch (TransportException e) {
      throw new GitException("unable to push", e);
    } catch (GitAPIException e) {
      throw new GitException("unable to push", e);
    }

    // read the branch from "source" repository
    String branchname = sourceRepository.getBranch();

    // create a "branch"
    if (!branchname.toLowerCase().equals("master")) {
      CreateBranchCommand branchCmd = binaryRepo.branchCreate();
      branchCmd.setName(branchname);
      try {
        // create branch
        branchCmd.call();

        // checkout the branch
        CheckoutCommand checkout = binaryRepo.checkout();
        checkout.setName(branchname);
        checkout.call();
      } catch (RefAlreadyExistsException e) {
        throw new GitException("unable to create a branch", e);
      } catch (RefNotFoundException e) {
        throw new GitException("unable to create a branch", e);
      } catch (InvalidRefNameException e) {
        throw new GitException("unable to create a branch", e);
      } catch (GitAPIException e) {
        throw new GitException("unable to create a branch", e);
      }
    }

    // find the "localobr" folders and exclude them during copy
    List<String> excludes = new ArrayList<String>();
    Collection<File> excludeFiles =
        FileUtil.findDirectoriesThatEndWith(sourceRepoFolder, "localobr");
    for (File file : excludeFiles) {
      excludes.add(file.getCanonicalPath());
    }

    // copy the classes
    System.out.println("copying binary files");
    copyBinaryFolders("target", excludes, binaryRepoFolder);

    // get "status"
    StatusCommand statusCmd = binaryRepo.status();
    Collection<String> tobeAdded = GitUtils.getFilesToStage(statusCmd);

    // add files to "staging"
    if (tobeAdded.size() > 0) {
      AddCommand addCmd = binaryRepo.add();
      for (String file : tobeAdded) {
        addCmd.addFilepattern(file);
      }
      try {
        addCmd.call();
      } catch (NoFilepatternException e) {
        throw new GitException("unable to add files", e);
      } catch (GitAPIException e) {
        throw new GitException("unable to add files", e);
      }
    }

    // commit
    System.out.println("commiting the files");
    CommitCommand commit1 = binaryRepo.commit();
    commit1.setMessage("saving the files");

    try {
      commit1.call();
    } catch (NoHeadException e) {
      throw new GitException("unable to commit", e);
    } catch (NoMessageException e) {
      throw new GitException("unable to commit", e);
    } catch (UnmergedPathsException e) {
      throw new GitException("unable to commit", e);
    } catch (ConcurrentRefUpdateException e) {
      throw new GitException("unable to commit", e);
    } catch (WrongRepositoryStateException e) {
      throw new GitException("unable to commit", e);
    } catch (GitAPIException e) {
      throw new GitException("unable to commit", e);
    }

    // push
    System.out.println("pushing to remote");
    PushCommand pushCmd = binaryRepo.push();
    try {
      pushCmd.call();
    } catch (InvalidRemoteException e) {
      throw new GitException("unable to push", e);
    } catch (TransportException e) {
      throw new GitException("unable to push", e);
    } catch (GitAPIException e) {
      throw new GitException("unable to push", e);
    }

    final String repoUrl = getSourceRemoteUrl();
    // branchName was computed above
    final org.eclipse.jgit.lib.Repository repo =
        new org.eclipse.jgit.storage.file.FileRepository(f);
    final RevWalk revWalk = new RevWalk(repo);
    final ObjectId resolve = repo.resolve(Constants.HEAD);
    final RevCommit commitRev = revWalk.parseCommit(resolve);
    final String commitHash = commitRev.getName();

    Git git = Git.open(binaryRepoFolder);
    final RevCommit binRepoResolveCommitRev;
    try {
      binRepoResolveCommitRev = git.log().call().iterator().next();
    } catch (NoHeadException e) {
      throw new GitException("No head found for repo", e);
    } catch (GitAPIException e) {
      throw new GitException("No head found for repo", e);
    }
    final String binRepoResolveCommitHash = binRepoResolveCommitRev.getName();
    final String binRepoBranchName = git.getRepository().getBranch();

    System.out.println("Update Bin Repo Service with the new changes - POST new object to service");
    final BinRepoBranchCommitDO binRepoBranchCommitDO =
        newInstance(
            repoUrl,
            branchname,
            commitHash,
            remoteUrl,
            binRepoBranchName,
            binRepoResolveCommitHash);
    final WebResource resource = client.resource(getUrlForPost());

    BinRepoBranchCommitDO postedDO = null;
    try {
      postedDO =
          resource
              .accept(MediaType.APPLICATION_XML)
              .post(BinRepoBranchCommitDO.class, binRepoBranchCommitDO);
      System.out.println("Posted Object = " + postedDO.toString());
    } catch (UniformInterfaceException e) {
      int statusCode = e.getResponse().getClientResponseStatus().getStatusCode();
      System.out.println("status code: " + statusCode);
      throw new MapServiceException("Unable to register the commit details", e);
    }

    // System.out.println(postedDO != null ? postedDO.toString() : "postedDO was null");
    System.out.println("updated the map service");
  }
  @Test
  public void testMergeRemovingFolders() throws Exception {
    // see org.eclipse.jgit.api.MergeCommandTest.testMergeRemovingFolders()
    createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME);
    IPath[] clonePaths = createTestProjects(workspaceLocation);

    for (IPath clonePath : clonePaths) {
      // clone a  repo
      JSONObject clone = clone(clonePath);
      String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);

      // get project/folder metadata
      WebRequest request = getGetRequest(cloneContentLocation);
      WebResponse response = webConversation.getResponse(request);
      assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
      JSONObject folder = new JSONObject(response.getText());
      String folderChildrenLocation = folder.getString(ProtocolConstants.KEY_CHILDREN_LOCATION);
      String folderLocation = folder.getString(ProtocolConstants.KEY_LOCATION);
      JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT);
      String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);
      String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

      String folderName = "folder1";
      request =
          getPostFilesRequest(
              folderLocation + "/", getNewDirJSON(folderName).toString(), folderName);
      response = webConversation.getResponse(request);
      assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
      JSONObject folder1 = getChild(folder, "folder1");

      String fileName = "file1.txt";
      request =
          getPostFilesRequest(
              folder1.getString(ProtocolConstants.KEY_LOCATION),
              getNewFileJSON(fileName).toString(),
              fileName);
      response = webConversation.getResponse(request);
      assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());

      fileName = "file2.txt";
      request =
          getPostFilesRequest(
              folder1.getString(ProtocolConstants.KEY_LOCATION),
              getNewFileJSON(fileName).toString(),
              fileName);
      response = webConversation.getResponse(request);
      assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());

      folderName = "folder2";
      request =
          getPostFilesRequest(
              folderLocation + "/", getNewDirJSON(folderName).toString(), folderName);
      response = webConversation.getResponse(request);
      assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
      JSONObject folder2 = getChild(folder, "folder2");

      fileName = "file1.txt";
      request =
          getPostFilesRequest(
              folder2.getString(ProtocolConstants.KEY_LOCATION),
              getNewFileJSON(fileName).toString(),
              fileName);
      response = webConversation.getResponse(request);
      assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());

      fileName = "file2.txt";
      request =
          getPostFilesRequest(
              folder2.getString(ProtocolConstants.KEY_LOCATION),
              getNewFileJSON(fileName).toString(),
              fileName);
      response = webConversation.getResponse(request);
      assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());

      request = GitAddTest.getPutGitIndexRequest(gitIndexUri);
      response = webConversation.getResponse(request);
      assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

      request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "folders and files", false);
      response = webConversation.getResponse(request);
      assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

      deleteFile(folder1);

      deleteFile(folder2);

      request = GitAddTest.getPutGitIndexRequest(gitIndexUri);
      response = webConversation.getResponse(request);
      assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

      request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "removing folders", false);
      response = webConversation.getResponse(request);
      assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

      JSONArray commitsArray = log(gitHeadUri);
      assertEquals(3, commitsArray.length());
      JSONObject commit = commitsArray.getJSONObject(0);
      assertEquals("removing folders", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
      String toMerge = commit.getString(ProtocolConstants.KEY_NAME);
      commit = commitsArray.getJSONObject(1);
      assertEquals("folders and files", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
      String toCheckout = commit.getString(ProtocolConstants.KEY_NAME);

      Repository db1 = getRepositoryForContentLocation(cloneContentLocation);
      Git git = Git.wrap(db1);
      git.checkout().setName(toCheckout).call();

      JSONObject merge = merge(gitHeadUri, toMerge);
      MergeStatus mergeResult = MergeStatus.valueOf(merge.getString(GitConstants.KEY_RESULT));
      assertEquals(MergeStatus.FAST_FORWARD, mergeResult);

      request = getGetRequest(folderChildrenLocation);
      response = webConversation.getResponse(request);
      assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
      List<JSONObject> children = getDirectoryChildren(new JSONObject(response.getText()));
      assertNull(getChildByName(children, "folder1"));
      assertNull(getChildByName(children, "folder2"));
    }
  }
示例#21
0
  private boolean handlePut(
      HttpServletRequest request, HttpServletResponse response, String pathString)
      throws GitAPIException, CoreException, IOException, JSONException, ServletException {
    IPath path = pathString == null ? Path.EMPTY : new Path(pathString);
    if (path.segment(0).equals("file") && path.segmentCount() > 1) { // $NON-NLS-1$

      // make sure a clone is addressed
      WebProject webProject = GitUtils.projectFromPath(path);
      if (isAccessAllowed(request.getRemoteUser(), webProject)) {
        Map<IPath, File> gitDirs = GitUtils.getGitDirs(path, Traverse.CURRENT);
        if (gitDirs.isEmpty()) {
          String msg = NLS.bind("Request path is not a git repository: {0}", path);
          return statusHandler.handleRequest(
              request,
              response,
              new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
        }
        File gitDir = gitDirs.values().iterator().next();

        // make sure required fields are set
        JSONObject toCheckout = OrionServlet.readJSONRequest(request);
        JSONArray paths = toCheckout.optJSONArray(ProtocolConstants.KEY_PATH);
        String branch = toCheckout.optString(GitConstants.KEY_BRANCH_NAME, null);
        String tag = toCheckout.optString(GitConstants.KEY_TAG_NAME, null);
        boolean removeUntracked = toCheckout.optBoolean(GitConstants.KEY_REMOVE_UNTRACKED, false);
        if ((paths == null || paths.length() == 0) && branch == null && tag == null) {
          String msg =
              NLS.bind(
                  "Either '{0}' or '{1}' or '{2}' should be provided, got: {3}",
                  new Object[] {
                    ProtocolConstants.KEY_PATH,
                    GitConstants.KEY_BRANCH_NAME,
                    GitConstants.KEY_TAG_NAME,
                    toCheckout
                  });
          return statusHandler.handleRequest(
              request,
              response,
              new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
        }

        Git git = new Git(new FileRepository(gitDir));
        if (paths != null) {
          Set<String> toRemove = new HashSet<String>();
          CheckoutCommand checkout = git.checkout();
          for (int i = 0; i < paths.length(); i++) {
            String p = paths.getString(i);
            if (removeUntracked && !isInIndex(git.getRepository(), p)) toRemove.add(p);
            checkout.addPath(p);
          }
          checkout.call();
          for (String p : toRemove) {
            File f = new File(git.getRepository().getWorkTree(), p);
            f.delete();
          }
          return true;
        } else if (tag != null && branch != null) {
          CheckoutCommand co = git.checkout();
          try {
            co.setName(branch).setStartPoint(tag).setCreateBranch(true).call();
            return true;
          } catch (RefNotFoundException e) {
            String msg = NLS.bind("Tag not found: {0}", tag);
            return statusHandler.handleRequest(
                request,
                response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, e));
          } catch (GitAPIException e) {
            if (org.eclipse.jgit.api.CheckoutResult.Status.CONFLICTS.equals(
                co.getResult().getStatus())) {
              return statusHandler.handleRequest(
                  request,
                  response,
                  new ServerStatus(
                      IStatus.ERROR, HttpServletResponse.SC_CONFLICT, "Checkout aborted.", e));
            }
            // TODO: handle other exceptions
          }
        } else if (branch != null) {

          if (!isLocalBranch(git, branch)) {
            String msg = NLS.bind("{0} is not a branch.", branch);
            return statusHandler.handleRequest(
                request,
                response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
          }

          CheckoutCommand co = git.checkout();
          try {
            co.setName(Constants.R_HEADS + branch).call();
            return true;
          } catch (CheckoutConflictException e) {
            return statusHandler.handleRequest(
                request,
                response,
                new ServerStatus(
                    IStatus.ERROR, HttpServletResponse.SC_CONFLICT, "Checkout aborted.", e));
          } catch (RefNotFoundException e) {
            String msg = NLS.bind("Branch name not found: {0}", branch);
            return statusHandler.handleRequest(
                request,
                response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, e));
          } // TODO: handle other exceptions
        }
      } else {
        String msg = NLS.bind("Nothing found for the given ID: {0}", path);
        return statusHandler.handleRequest(
            request,
            response,
            new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null));
      }
    }
    String msg = NLS.bind("Invalid checkout request {0}", pathString);
    return statusHandler.handleRequest(
        request,
        response,
        new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
  }
  @Test
  public void testDataStore() throws Exception {
    String defaultVersion = dataStore.getDefaultVersion();
    assertEquals("defaultVersion", "1.0", defaultVersion);

    // now lets import some data - using the old non-git file layout...
    String importPath = basedir + "/../fabric8-karaf/src/main/resources/distro/fabric/import";
    if (useOldImportFormat) {
      assertFolderExists(importPath);
      dataStore.importFromFileSystem(importPath);
      assertHasVersion(defaultVersion);
    } else {
      String prefix = importPath + "/fabric";
      String profileImport = prefix + "/configs/versions/1.0/profiles";
      assertFolderExists(profileImport);

      dataStore.importFromFileSystem(new File(profileImport), "fabric", "1.0", true);
      assertHasVersion(defaultVersion);
    }

    remote.checkout().setName("1.0").call();
    String importedProfile = "example-dozer";
    String profile = importedProfile;
    assertProfileExists(defaultVersion, profile);

    // assertFolderExists("Should have imported an mq/ReadMe.md file!",
    // getLocalGitFile("fabric/profiles/mq/ReadMe.md"));

    String version = "1.1";
    assertCreateVersion("1.0", version);

    assertProfileConfiguration(
        version, importedProfile, Constants.AGENT_PID, "attribute.parents", "feature-camel");
    assertProfileTextFileConfigurationContains(
        version, "example-camel-mq", "camel.xml", "http://camel.apache.org/schema/blueprint");

    List<String> fileNames = dataStore.getConfigurationFileNames(version, "example-camel-mq");
    assertNotNull("Should have some file names", fileNames);
    assertTrue("Should have some file names", fileNames.size() > 0);
    assertTrue("Should contain 'came", fileNames.size() > 0);
    assertCollectionContains("configurationFileNames", fileNames, "camel.xml");

    // lets test the profile attributes
    Map<String, String> profileAttributes =
        dataStore.getProfileAttributes(version, importedProfile);
    String parent = profileAttributes.get("parents");
    assertEquals(importedProfile + ".profileAttributes[parent]", "feature-camel", parent);

    System.out.println("Profile attributes: " + profileAttributes);
    String profileAttributeKey = "myKey";
    String expectedProfileAttributeValue = "myValue";
    dataStore.setProfileAttribute(
        version, importedProfile, profileAttributeKey, expectedProfileAttributeValue);
    profileAttributes = dataStore.getProfileAttributes(version, importedProfile);
    System.out.println("Profile attributes: " + profileAttributes);
    assertMapContains(
        "Profile attribute[" + profileAttributeKey + "]",
        profileAttributes,
        profileAttributeKey,
        expectedProfileAttributeValue);

    String hawtioRepoKey = "repository.hawtio";
    Map<String, String> hawtioAttrbutes =
        dataStore.getConfiguration(version, "hawtio", Constants.AGENT_PID);
    String currentHawtRepo = hawtioAttrbutes.get(hawtioRepoKey);
    System.out.println("Current repository.hawtio: " + currentHawtRepo);

    // now lets write via the hawtio API
    FabricGitFacade hawtio = new FabricGitFacade();
    hawtio.bindGitDataStoreForTesting(dataStore);
    hawtio.activateForTesting();
    String hawtioPropertyFile =
        "/fabric/profiles/"
            + dataStore.convertProfileIdToDirectory("hawtio")
            + "/"
            + Constants.AGENT_PID
            + ".properties";
    hawtio.write(
        version,
        hawtioPropertyFile,
        "My commit message",
        "me",
        "*****@*****.**",
        "# new file\n"
            + hawtioRepoKey
            + " = "
            + "mvn\\:io.hawt/hawtio-karaf/myNewVersion/xml/features"
            + "\n");
    hawtioAttrbutes = dataStore.getConfiguration(version, "hawtio", Constants.AGENT_PID);
    String actual = hawtioAttrbutes.get(hawtioRepoKey);
    assertEquals(
        "should have found the updated hawtio repo key",
        "mvn:io.hawt/hawtio-karaf/myNewVersion/xml/features",
        actual);

    // lets check that the file configurations recurses into folders
    Map<String, byte[]> tomcatFileConfigurations =
        dataStore.getFileConfigurations("1.0", "controller-tomcat");
    assertHasFileConfiguration(tomcatFileConfigurations, "tomcat/conf/server.xml.mvel");

    Collection<String> schemas =
        dataStore.listFiles("1.0", Arrays.asList("example-dozer"), "schemas");
    assertNotNull(schemas);
    assertContainerEquals(
        "schemas for example-dozer", Arrays.asList("invoice.xsd"), new ArrayList<String>(schemas));

    // check we don't accidentally create a profile
    String profileNotCreated = "shouldNotBeCreated";
    assertEquals(
        "Should not create profile: " + profileNotCreated,
        null,
        dataStore.getProfile(version, profileNotCreated, false));
    assertProfileNotExists(defaultVersion, profileNotCreated);
    assertFolderNotExists(
        getLocalGitFile(
            "fabric/profiles/" + dataStore.convertProfileIdToDirectory(profileNotCreated)));

    // now lets create some profiles in this new version
    String newProfile = "myNewProfile";
    dataStore.createProfile(version, newProfile);
    assertProfileExists(version, newProfile);

    // lazy create a profile
    String anotherNewProfile = "anotherNewProfile";
    dataStore.getProfile(version, anotherNewProfile, true);
    assertProfileExists(version, anotherNewProfile);

    version = "1.2";
    assertCreateVersion("1.1", version);

    // check this version has the profile too
    assertProfileExists(version, newProfile);
    assertProfileExists(version, profile);

    // now lets delete a profile
    dataStore.deleteProfile(version, newProfile);
    assertProfileNotExists(version, newProfile);

    // lets check the remote repo
    remote.checkout().setName("1.1").call();

    assertProfileExists("1.1", profile);
    assertProfileExists("1.1", newProfile);
    assertFolderExists(
        getRemoteGitFile("fabric/profiles/" + dataStore.convertProfileIdToDirectory(profile)));
    assertFolderExists(
        getRemoteGitFile("fabric/profiles/" + dataStore.convertProfileIdToDirectory(newProfile)));

    remote.checkout().setName("1.2").call();

    assertProfileExists("1.2", profile);
    assertProfileNotExists("1.2", newProfile);
    assertFolderExists(
        getRemoteGitFile("fabric/profiles/" + dataStore.convertProfileIdToDirectory(profile)));
    assertFolderNotExists(
        getRemoteGitFile("fabric/profiles/" + dataStore.convertProfileIdToDirectory(newProfile)));

    remote.checkout().setName("1.0").call();
    assertFolderExists(
        getRemoteGitFile("fabric/profiles/" + dataStore.convertProfileIdToDirectory(profile)));
    assertFolderNotExists(
        getRemoteGitFile("fabric/profiles/" + dataStore.convertProfileIdToDirectory(newProfile)));

    // delete version 1.2
    assertHasVersion("1.1");
    assertHasVersion("1.2");
    dataStore.removeVersion("1.2");
    assertHasVersion("1.1");
    assertHasNotVersion("1.2");

    Collection<String> remoteBranches = RepositoryUtils.getBranches(remote.getRepository());
    System.out.println("Remote branches after delete: " + remoteBranches);
  }