コード例 #1
0
  public Repository call() throws JGitInternalException {
    checkCallable();
    if (path == null || path.length() == 0)
      throw new IllegalArgumentException(JGitText.get().pathNotConfigured);
    if (uri == null || uri.length() == 0)
      throw new IllegalArgumentException(JGitText.get().uriNotConfigured);

    try {
      if (submoduleExists())
        throw new JGitInternalException(MessageFormat.format(JGitText.get().submoduleExists, path));
    } catch (IOException e) {
      throw new JGitInternalException(e.getMessage(), e);
    }

    // Clone submodule repository
    File moduleDirectory = SubmoduleWalk.getSubmoduleDirectory(repo, path);
    CloneCommand clone = Git.cloneRepository();
    clone.setDirectory(moduleDirectory);
    clone.setURI(uri);
    if (monitor != null) clone.setProgressMonitor(monitor);
    if (credentialsProvider != null) clone.setCredentialsProvider(credentialsProvider);
    Repository subRepo = clone.call().getRepository();

    // Save submodule URL to parent repository's config
    StoredConfig config = repo.getConfig();
    config.setString(
        ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants.CONFIG_KEY_URL, uri);
    try {
      config.save();
    } catch (IOException e) {
      throw new JGitInternalException(e.getMessage(), e);
    }

    // Save path and URL to parent repository's .gitmodules file
    FileBasedConfig modulesConfig =
        new FileBasedConfig(new File(repo.getWorkTree(), Constants.DOT_GIT_MODULES), repo.getFS());
    modulesConfig.setString(
        ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants.CONFIG_KEY_PATH, path);
    modulesConfig.setString(
        ConfigConstants.CONFIG_SUBMODULE_SECTION, path, ConfigConstants.CONFIG_KEY_URL, uri);
    try {
      modulesConfig.save();
    } catch (IOException e) {
      throw new JGitInternalException(e.getMessage(), e);
    }

    AddCommand add = new AddCommand(repo);
    // Add .gitmodules file to parent repository's index
    add.addFilepattern(Constants.DOT_GIT_MODULES);
    // Add submodule directory to parent repository's index
    add.addFilepattern(path);
    try {
      add.call();
    } catch (NoFilepatternException e) {
      throw new JGitInternalException(e.getMessage(), e);
    }

    return subRepo;
  }
コード例 #2
0
 @Test
 public void testCloneRepository() {
   try {
     File directory = createTempDirectory("testCloneRepository");
     CloneCommand command = Git.cloneRepository();
     command.setDirectory(directory);
     command.setURI("file://" + git.getRepository().getWorkTree().getPath());
     Git git2 = command.call();
     assertNotNull(git2);
   } catch (Exception e) {
     fail(e.getMessage());
   }
 }
コード例 #3
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();
    }
  }
コード例 #4
0
  /**
   * Execute the SubmoduleUpdateCommand command.
   *
   * @return a collection of updated submodule paths
   * @throws ConcurrentRefUpdateException
   * @throws CheckoutConflictException
   * @throws InvalidMergeHeadsException
   * @throws InvalidConfigurationException
   * @throws NoHeadException
   * @throws NoMessageException
   * @throws RefNotFoundException
   * @throws WrongRepositoryStateException
   * @throws GitAPIException
   */
  public Collection<String> call()
      throws InvalidConfigurationException, NoHeadException, ConcurrentRefUpdateException,
          CheckoutConflictException, InvalidMergeHeadsException, WrongRepositoryStateException,
          NoMessageException, NoHeadException, RefNotFoundException, GitAPIException {
    checkCallable();

    try {
      SubmoduleWalk generator = SubmoduleWalk.forIndex(repo);
      if (!paths.isEmpty()) generator.setFilter(PathFilterGroup.createFromStrings(paths));
      List<String> updated = new ArrayList<String>();
      while (generator.next()) {
        // Skip submodules not registered in .gitmodules file
        if (generator.getModulesPath() == null) continue;
        // Skip submodules not registered in parent repository's config
        String url = generator.getConfigUrl();
        if (url == null) continue;

        Repository submoduleRepo = generator.getRepository();
        // Clone repository is not present
        if (submoduleRepo == null) {
          CloneCommand clone = Git.cloneRepository();
          configure(clone);
          clone.setURI(url);
          clone.setDirectory(generator.getDirectory());
          clone.setGitDir(
              new File(new File(repo.getDirectory(), Constants.MODULES), generator.getPath()));
          if (monitor != null) clone.setProgressMonitor(monitor);
          submoduleRepo = clone.call().getRepository();
        }

        try {
          RevWalk walk = new RevWalk(submoduleRepo);
          RevCommit commit = walk.parseCommit(generator.getObjectId());

          String update = generator.getConfigUpdate();
          if (ConfigConstants.CONFIG_KEY_MERGE.equals(update)) {
            MergeCommand merge = new MergeCommand(submoduleRepo);
            merge.include(commit);
            merge.setStrategy(strategy);
            merge.call();
          } else if (ConfigConstants.CONFIG_KEY_REBASE.equals(update)) {
            RebaseCommand rebase = new RebaseCommand(submoduleRepo);
            rebase.setUpstream(commit);
            rebase.setStrategy(strategy);
            rebase.call();
          } else {
            // Checkout commit referenced in parent repository's
            // index as a detached HEAD
            DirCacheCheckout co =
                new DirCacheCheckout(submoduleRepo, submoduleRepo.lockDirCache(), commit.getTree());
            co.setFailOnConflict(true);
            co.checkout();
            RefUpdate refUpdate = submoduleRepo.updateRef(Constants.HEAD, true);
            refUpdate.setNewObjectId(commit);
            refUpdate.forceUpdate();
          }
        } finally {
          submoduleRepo.close();
        }
        updated.add(generator.getPath());
      }
      return updated;
    } catch (IOException e) {
      throw new JGitInternalException(e.getMessage(), e);
    } catch (ConfigInvalidException e) {
      throw new InvalidConfigurationException(e.getMessage(), e);
    }
  }