Esempio n. 1
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);
   }
 }
Esempio n. 2
0
  /*
   * Use the binary git repo and/or the remote service to figure out
   * the new commits made since the last pull on source repository.
   */
  public void findNewCommits() throws GitException {

    // get the history from binary repository
    Git bingit = Git.wrap(binaryRepository);
    RevWalk binwalk = new RevWalk(binaryRepository);

    Iterable<RevCommit> logs;
    try {
      logs = bingit.log().call();
      Iterator<RevCommit> i = logs.iterator();

      while (i.hasNext()) {
        RevCommit commit = binwalk.parseCommit(i.next());
        System.out.println(commit.getFullMessage());
      }

    } catch (NoHeadException e) {
      // TODO Auto-generated catch block
      throw new GitException(e);
    } catch (GitAPIException e) {
      throw new GitException(e);
    } catch (MissingObjectException e) {
      throw new GitException(e);
    } catch (IncorrectObjectTypeException e) {
      throw new GitException(e);
    } catch (IOException e) {
      throw new GitException(e);
    }
  }
Esempio n. 3
0
  @Override
  public List<CommitDB> getCommits() {

    try {

      Iterable<RevCommit> revCommits;
      revCommits = git.log().all().call();
      List<CommitDB> commits = new ArrayList<CommitDB>();

      for (RevCommit revCommit : revCommits) {

        PersonIdent author = revCommit.getAuthorIdent();
        CommitDB commit =
            new CommitDB(0, author.getWhen(), revCommit.getFullMessage(), revCommit.getName());
        CommitterDB committerDb = new CommitterDB(0, author.getEmailAddress(), author.getName());
        commit.setCommitter(committerDb);
        commits.add(commit);
      }

      return commits;

    } catch (GitAPIException e) {
      throw new VisMinerAPIException(e.getMessage(), e);
    } catch (IOException e) {
      throw new VisMinerAPIException(e.getMessage(), e);
    }
  }
Esempio n. 4
0
  /** Performs the given operations on a clean git repository */
  protected <T> T gitOperation(PersonIdent personIdent, Callable<T> callable) {
    synchronized (lock) {
      try {
        // lets check if we have done a commit yet...
        boolean hasHead = true;
        try {
          git.log().all().call();
        } catch (NoHeadException e) {
          hasHead = false;
        }

        // TODO pull if we have a remote repo

        if (hasHead) {
          // lets stash any local changes just in case..
          git.stashCreate()
              .setPerson(personIdent)
              .setWorkingDirectoryMessage("Stash before a write")
              .setRef("HEAD")
              .call();
        }
        return callable.call();
      } catch (Exception e) {
        throw new RuntimeIOException(e);
      }
    }
  }
Esempio n. 5
0
  private Iterable<RevCommit> getCommitsFromTag(String treeName) {

    try {

      List<Ref> call = git.tagList().call();
      Iterable<RevCommit> logs = null;

      for (Ref ref : call) {

        if (ref.getName().equals(treeName)) {

          LogCommand log = git.log();
          Ref peeledRef = repository.peel(ref);

          if (peeledRef.getPeeledObjectId() != null) {
            log.add(peeledRef.getPeeledObjectId());
          } else {
            log.add(ref.getObjectId());
          }

          logs = log.call();
          return logs;
        }
      }

      return null;

    } catch (GitAPIException e) {
      throw new VisMinerAPIException(e.getMessage(), e);
    } catch (MissingObjectException e) {
      throw new VisMinerAPIException(e.getMessage(), e);
    } catch (IncorrectObjectTypeException e) {
      throw new VisMinerAPIException(e.getMessage(), e);
    }
  }
Esempio n. 6
0
  @Override
  public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    try {
      String localPath = args[0].getStringValue();
      if (!(localPath.endsWith("/"))) localPath += File.separator;

      //	        Repository localRepo = new FileRepository(localPath + ".git");
      //	        Git git = new Git(localRepo);

      Git git = Git.open(new Resource(localPath), FS);

      MemTreeBuilder builder = context.getDocumentBuilder();

      AttributesImpl attribs = new AttributesImpl();
      attribs.addAttribute(NAMESPACE_URI, "local-path", PREFIX + ":local-path", "CDATA", localPath);

      int nodeNr = builder.startElement(LOG_ELEMENT, attribs);

      for (RevCommit commit : git.log().call()) {
        //                commit.getParentCount();
        //                commit.getParents();

        attribs = new AttributesImpl();
        attribs.addAttribute(NAMESPACE_URI, "id", PREFIX + ":id", "CDATA", commit.name());

        attribs.addAttribute(
            NAMESPACE_URI,
            "time",
            PREFIX + ":time",
            "CDATA",
            String.valueOf(commit.getCommitTime()));

        builder.startElement(COMMIT_ELEMENT, attribs);

        PersonIdent authorIdent = commit.getAuthorIdent();
        builder.startElement(AUTHOR_ELEMENT, null);
        builder.startElement(AUTHOR_NAME_ELEMENT, null);
        builder.characters(authorIdent.getName());
        builder.endElement();
        builder.startElement(AUTHOR_EMAIL_ELEMENT, null);
        builder.characters(authorIdent.getEmailAddress());
        builder.endElement();
        builder.endElement();

        builder.startElement(MESSAGE_ELEMENT, null);
        builder.characters(commit.getFullMessage());
        builder.endElement();

        builder.endElement();
      }

      builder.endElement();

      return builder.getDocument().getNode(nodeNr);
    } catch (Throwable e) {
      throw new XPathException(this, Module.EXGIT001, e);
    }
  }
Esempio n. 7
0
 @Override
 protected IStatus performJob() {
   try {
     // list all tags
     File gitDir = GitUtils.getGitDir(path);
     Repository db = new FileRepository(gitDir);
     Git git = new Git(db);
     List<Ref> refs = git.tagList().call();
     JSONObject result = new JSONObject();
     List<Tag> tags = new ArrayList<Tag>();
     for (Ref ref : refs) {
       Tag tag = new Tag(cloneLocation, db, ref);
       tags.add(tag);
     }
     Collections.sort(tags, Tag.COMPARATOR);
     JSONArray children = new JSONArray();
     int firstTag = pageSize > 0 ? pageSize * (pageNo - 1) : 0;
     int lastTag = pageSize > 0 ? firstTag + pageSize - 1 : tags.size() - 1;
     lastTag = lastTag > tags.size() - 1 ? tags.size() - 1 : lastTag;
     if (pageNo > 1 && baseLocation != null) {
       String prev = baseLocation + "?page=" + (pageNo - 1) + "&pageSize=" + pageSize;
       if (commitsSize > 0) {
         prev += "&" + GitConstants.KEY_TAG_COMMITS + "=" + commitsSize;
       }
       result.put(ProtocolConstants.KEY_PREVIOUS_LOCATION, prev);
     }
     if (lastTag < tags.size() - 1) {
       String next = baseLocation + "?page=" + (pageNo + 1) + "&pageSize=" + pageSize;
       if (commitsSize > 0) {
         next += "&" + GitConstants.KEY_TAG_COMMITS + "=" + commitsSize;
       }
       result.put(ProtocolConstants.KEY_NEXT_LOCATION, next);
     }
     for (int i = firstTag; i <= lastTag; i++) {
       Tag tag = tags.get(i);
       if (this.commitsSize == 0) {
         children.put(tag.toJSON());
       } else {
         // add info about commits if requested
         LogCommand lc = git.log();
         String toCommitName = tag.getRevCommitName();
         ObjectId toCommitId = db.resolve(toCommitName);
         Ref toCommitRef = db.getRef(toCommitName);
         toCommitId = getCommitObjectId(db, toCommitId);
         lc.add(toCommitId);
         lc.setMaxCount(this.commitsSize);
         Iterable<RevCommit> commits = lc.call();
         Log log = new Log(cloneLocation, db, commits, null, null, toCommitRef);
         children.put(tag.toJSON(log.toJSON(1, commitsSize)));
       }
     }
     result.put(ProtocolConstants.KEY_CHILDREN, children);
     result.put(ProtocolConstants.KEY_TYPE, Tag.TYPE);
     return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result);
   } catch (Exception e) {
     String msg = NLS.bind("An error occured when listing tags for {0}", path);
     return new Status(IStatus.ERROR, GitActivator.PI_GIT, msg, e);
   }
 }
Esempio n. 8
0
 @SuppressWarnings("UnusedDeclaration") // debugging
 private void printLog() {
   try {
     printAll(repository, git.log().call());
   } catch (GitAPIException e) {
     throw new SvcFailedException(e);
   }
 }
Esempio n. 9
0
  public static List<String> getLogForCurrentBranch(final Git repo) throws GitAPIException {
    List<String> results = new ArrayList<String>();
    Iterable<RevCommit> commits = repo.log().call();

    for (RevCommit commit : commits) results.add(commit.getFullMessage());

    return results;
  }
Esempio n. 10
0
 @Override
 public Stream<Revision> log() {
   try {
     final LogCommand logCommand = git.log();
     return stream(logCommand.call()).map(this::asRevision);
   } catch (GitAPIException e) {
     throw new SvcFailedException(e);
   }
 }
Esempio n. 11
0
  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;
  }
Esempio n. 12
0
  private static void lastCommit(Git git, String path, AnyObjectId revId, JSONObject jsonObject) {
    JSONObject latestCommitObj = new JSONObject();
    JSONObject authorObj = new JSONObject();
    JSONObject committerObj = new JSONObject();
    Iterable<RevCommit> log = null;
    try {
      if (path != null) {
        log = git.log().addPath(path).setMaxCount(1).call();
      } else if (revId != null) {
        log = git.log().add(revId).setMaxCount(1).call();
      }
      Iterator<RevCommit> it = log.iterator();
      while (it.hasNext()) {
        RevCommit rev = (RevCommit) it.next();
        PersonIdent committer = rev.getCommitterIdent();
        committerObj.put("Name", committer.getName());
        committerObj.put("Email", committer.getEmailAddress());
        committerObj.put("Date", committer.getWhen().toString());

        PersonIdent author = rev.getAuthorIdent();
        authorObj.put("Name", author.getName());
        String authorEmail = author.getEmailAddress();
        authorObj.put("Email", authorEmail);
        authorObj.put("Date", author.getWhen().toString());

        latestCommitObj.put("Author", authorObj);
        latestCommitObj.put("Committer", committerObj);
        latestCommitObj.put("Message", rev.getFullMessage());
        latestCommitObj.put("SHA1", rev.getId().getName());
        latestCommitObj.put("AvatarURL", getImageLink(authorEmail));

        jsonObject.put("LastCommit", latestCommitObj);
      }
    } catch (GitAPIException e) {
    } catch (MissingObjectException e) {
    } catch (IncorrectObjectTypeException e) {
    } catch (JSONException e) {
    }
  }
Esempio n. 13
0
  private Iterable<RevCommit> getCommitsFromBranch(String treeName) {

    try {

      Iterable<RevCommit> revCommits = git.log().add(repository.resolve(treeName)).call();
      return revCommits;

    } catch (GitAPIException e) {
      throw new VisMinerAPIException(e.getMessage(), e);
    } catch (IOException e) {
      throw new VisMinerAPIException(e.getMessage(), e);
    }
  }
  private Collection<GitVersionInfo> history(FileSystemPage page, LogCommandSpec logCommandSpec)
      throws GitAPIException {
    Repository repository = getRepository(page);
    Git git = new Git(repository);
    String fileSystemPath = getPath(page, repository);

    Iterable<RevCommit> log = logCommandSpec.specify(git.log(), fileSystemPath).call();
    List<GitVersionInfo> versions = new ArrayList<GitVersionInfo>(historyDepth);
    for (RevCommit revCommit : log) {
      versions.add(makeVersionInfo(revCommit));
    }
    return versions;
  }
Esempio n. 15
0
 public ArrayList<RevCommit> getAllRevisions() {
   ArrayList<RevCommit> revisions = new ArrayList<>();
   Iterable<RevCommit> allRevisions = null;
   try {
     allRevisions = git.log().call();
   } catch (GitAPIException e) {
     e.printStackTrace();
   }
   for (RevCommit rev : allRevisions) {
     revisions.add(rev);
   }
   return revisions;
 }
Esempio n. 16
0
  public static void main(String[] args)
      throws IOException, InvalidRefNameException, GitAPIException {
    Repository repository = CookbookHelper.openJGitCookbookRepository();

    Git git = new Git(repository);
    Iterable<RevCommit> commits = git.log().all().call();
    int count = 0;
    for (RevCommit commit : commits) {
      System.out.println("LogCommit: " + commit);
      count++;
    }
    System.out.println(count);

    repository.close();
  }
  public static Set<String> extractJiraIssues(
      Repository repository, String sinceTagName, String untilTagName, String pattern)
      throws IOException, GitAPIException {
    Git git = new Git(repository);
    RevCommit startCommitId = resolveCommitIdByTagName(repository, sinceTagName);
    if (startCommitId == null) {
      throw new IOException("cannot resolveCommitIdByTagName by  " + sinceTagName);
    }
    ObjectId endCommitId = resolveCommitIdByTagName(repository, untilTagName);
    if (endCommitId == null) {
      endCommitId = repository.resolve(Constants.HEAD);
    }
    Iterable<RevCommit> commits = git.log().addRange(startCommitId, endCommitId).call();

    return extractJiraIssues(pattern, commits);
  }
Esempio n. 18
0
 public void log(final int maxHistory) {
   final Repository repository = getRepository();
   final Git git = new Git(repository);
   try {
     int counter = 0;
     LOGGER.warning("---------- Start Git log ----------");
     for (final RevCommit commit : git.log().call()) {
       LOGGER.info("commit id: " + commit.getName());
       LOGGER.info("message:   " + commit.getFullMessage());
       LOGGER.info("");
       if (++counter >= maxHistory) {
         break;
       }
     }
     LOGGER.warning("---------- End Git log ----------");
   } catch (final Exception e) {
     throw new IllegalStateException("Could not parse git log", e);
   }
 }
  @Test
  public void testRemote() throws Exception {

    File binaryRepoFolder = new File("D:\\dev\\rgiroti_search_raptor\\.search_raptor");
    Git git = Git.open(binaryRepoFolder);
    final Iterable<RevCommit> revCommits = git.log().call();
    for (RevCommit revCommit : revCommits) {
      System.out.println(
          revCommit.getName() + revCommit.getFullMessage() + revCommit.getCommitTime());
    }

    // final org.eclipse.jgit.lib.Repository binRepo = new
    // org.eclipse.jgit.storage.file.FileRepository(binaryRepoFolder);
    // final RevWalk binRepoRevWalk = new RevWalk(binRepo);

    // final ObjectId binRepoResolve = binRepo.resolve(Constants.HEAD);
    // final RevCommit binRepoResolveCommitRev = git.log().call().iterator().next();
    // final String binRepoResolveCommitHash = binRepoResolveCommitRev.getName();

    // final String binRepoBranchname = git.getRepository().getBranch();
  }
Esempio n. 20
0
 public String getCommitMessage(String commitId) {
   String commitMessage = null;
   try {
     FileRepositoryBuilder builder = new FileRepositoryBuilder();
     String repoPath = VerigreenNeededLogic.properties.getProperty("git.repositoryLocation");
     Repository repo = builder.setGitDir(new File(repoPath)).setMustExist(true).build();
     Git git = new Git(repo);
     Iterable<RevCommit> log = git.log().call();
     Iterator<RevCommit> iterator = log.iterator();
     while (commitMessage == null && iterator.hasNext()) {
       RevCommit rev = iterator.next();
       String commit = rev.getName().substring(0, 7);
       if (commit.equals(commitId)) {
         commitMessage = rev.getFullMessage();
       }
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   return commitMessage;
 }
Esempio n. 21
0
  protected void addInformationForPath(
      Repository repository,
      Git git,
      DocumentWriter writer,
      RevCommit commit,
      String path,
      CallSpecification spec,
      Values values)
      throws GitAPIException, IOException {
    // Make sure the path is in the canonical form we need ...
    if (path.startsWith("/")) {
      if (path.length() == 1) path = "";
      else path = path.substring(1);
    }

    // Now see if we're actually referring to the "jcr:content" node ...
    boolean isContentNode = false;
    if (path.endsWith(JCR_CONTENT_SUFFIX)) {
      isContentNode = true;
      path = path.substring(0, path.length() - JCR_CONTENT_SUFFIX.length());
    }

    // Create the TreeWalk that we'll use to navigate the files/directories ...
    final TreeWalk tw = new TreeWalk(repository);
    tw.addTree(commit.getTree());
    if ("".equals(path)) {
      // This is the top-level directory, so we don't need to pre-walk to find anything ...
      tw.setRecursive(false);
      while (tw.next()) {
        String childName = tw.getNameString();
        String childId = spec.childId(childName);
        writer.addChild(childId, childName);
      }
    } else {
      // We need to first find our path *before* we can walk the children ...
      PathFilter filter = PathFilter.create(path);
      tw.setFilter(filter);
      while (tw.next()) {
        if (filter.isDone(tw)) {
          break;
        } else if (tw.isSubtree()) {
          tw.enterSubtree();
        }
      }
      // Now that the TreeWalk is the in right location given by the 'path', we can get the
      if (tw.isSubtree()) {
        // The object at the 'path' is a directory, so go into it ...
        tw.enterSubtree();

        // Find the commit in which this folder was last modified ...
        // This may not be terribly efficient, but it seems to work faster on subsequent runs ...
        RevCommit folderCommit = git.log().addPath(path).call().iterator().next();

        // Add folder-related properties ...
        String committer = folderCommit.getCommitterIdent().getName();
        String author = folderCommit.getAuthorIdent().getName();
        DateTime committed = values.dateFrom(folderCommit.getCommitTime());
        writer.setPrimaryType(GitLexicon.FOLDER);
        writer.addProperty(JcrLexicon.CREATED, committed);
        writer.addProperty(JcrLexicon.CREATED_BY, committer);
        writer.addProperty(GitLexicon.OBJECT_ID, folderCommit.getId().name());
        writer.addProperty(GitLexicon.AUTHOR, author);
        writer.addProperty(GitLexicon.COMMITTER, committer);
        writer.addProperty(GitLexicon.COMMITTED, committed);
        writer.addProperty(GitLexicon.TITLE, folderCommit.getShortMessage());

        // And now walk the contents of the directory ...
        while (tw.next()) {
          String childName = tw.getNameString();
          String childId = spec.childId(childName);
          writer.addChild(childId, childName);
        }
      } else {
        // The path specifies a file (or a content node) ...

        // Find the commit in which this folder was last modified ...
        // This may not be terribly efficient, but it seems to work faster on subsequent runs ...
        RevCommit fileCommit = git.log().addPath(path).call().iterator().next();

        // Add file-related properties ...
        String committer = fileCommit.getCommitterIdent().getName();
        String author = fileCommit.getAuthorIdent().getName();
        DateTime committed = values.dateFrom(fileCommit.getCommitTime());
        if (isContentNode) {
          writer.setPrimaryType(GitLexicon.RESOURCE);
          writer.addProperty(JcrLexicon.LAST_MODIFIED, committed);
          writer.addProperty(JcrLexicon.LAST_MODIFIED_BY, committer);
          writer.addProperty(GitLexicon.OBJECT_ID, fileCommit.getId().name());
          writer.addProperty(GitLexicon.AUTHOR, author);
          writer.addProperty(GitLexicon.COMMITTER, committer);
          writer.addProperty(GitLexicon.COMMITTED, committed);
          writer.addProperty(GitLexicon.TITLE, fileCommit.getShortMessage());
          // Create the BinaryValue ...
          ObjectId fileObjectId = tw.getObjectId(0);
          ObjectLoader fileLoader = repository.open(fileObjectId);
          BinaryKey key = new BinaryKey(fileObjectId.getName());
          BinaryValue value = values.binaryFor(key, fileLoader.getSize());
          if (value == null) {
            // It wasn't found in the binary store ...
            if (fileLoader.isLarge()) {
              // Too large to hold in memory, so use the binary store (which reads the file
              // immediately) ...
              value = values.binaryFrom(fileLoader.openStream());
            } else {
              // This is small enough to fit into a byte[], but it still may be pretty big ...
              value =
                  new GitBinaryValue(
                      fileObjectId,
                      fileLoader,
                      connector.getSourceName(),
                      name,
                      connector.getMimeTypeDetector());
            }
          }
          writer.addProperty(JcrLexicon.DATA, value);
          if (connector.includeMimeType()) {
            try {
              String filename =
                  spec.parameter(spec.parameterCount() - 1); // the last is 'jcr:content'
              String mimeType = value.getMimeType(filename);
              if (mimeType != null) writer.addProperty(JcrLexicon.MIMETYPE, mimeType);
            } catch (RepositoryException e) {
              // do nothing
            } catch (IOException e) {
              // do nothing
            }
          }
        } else {
          writer.setPrimaryType(GitLexicon.FILE);
          writer.addProperty(JcrLexicon.CREATED, committed);
          writer.addProperty(JcrLexicon.CREATED_BY, committer);
          writer.addProperty(GitLexicon.OBJECT_ID, fileCommit.getId().name());
          writer.addProperty(GitLexicon.AUTHOR, author);
          writer.addProperty(GitLexicon.COMMITTER, committer);
          writer.addProperty(GitLexicon.COMMITTED, committed);
          writer.addProperty(GitLexicon.TITLE, fileCommit.getShortMessage());

          // Add the "jcr:content" child node ...
          String childId = spec.childId(JCR_CONTENT);
          writer.addChild(childId, JCR_CONTENT);
        }
      }
    }
  }
Esempio n. 22
0
  @Override
  protected IStatus performJob() {
    Repository db = null;
    try {
      File gitDir = GitUtils.getGitDir(path);
      db = FileRepositoryBuilder.create(gitDir);
      Git git = Git.wrap(db);
      List<Ref> branchRefs = git.branchList().call();
      List<Branch> branches = new ArrayList<Branch>(branchRefs.size());
      for (Ref ref : branchRefs) {
        if (nameFilter != null && !nameFilter.equals("")) {
          String shortName = Repository.shortenRefName(ref.getName());
          if (shortName.toLowerCase().contains(nameFilter.toLowerCase())) {
            branches.add(new Branch(cloneLocation, db, ref));
          }
        } else {
          branches.add(new Branch(cloneLocation, db, ref));
        }
      }
      Collections.sort(branches, Branch.COMPARATOR);
      JSONObject result = new JSONObject();
      JSONArray children = new JSONArray();
      int firstBranch = pageSize > 0 ? pageSize * (pageNo - 1) : 0;
      int lastBranch = pageSize > 0 ? firstBranch + pageSize - 1 : branches.size() - 1;
      lastBranch = lastBranch > branches.size() - 1 ? branches.size() - 1 : lastBranch;
      if (pageNo > 1 && baseLocation != null) {
        String prev = baseLocation + "?page=" + (pageNo - 1) + "&pageSize=" + pageSize;
        if (nameFilter != null && !nameFilter.equals("")) {
          prev += "&filter=" + GitUtils.encode(nameFilter);
        }
        if (commitsSize > 0) {
          prev += "&" + GitConstants.KEY_TAG_COMMITS + "=" + commitsSize;
        }
        result.put(ProtocolConstants.KEY_PREVIOUS_LOCATION, prev);
      }
      if (lastBranch < branches.size() - 1) {
        String next = baseLocation + "?page=" + (pageNo + 1) + "&pageSize=" + pageSize;
        if (nameFilter != null && !nameFilter.equals("")) {
          next += "&filter=" + GitUtils.encode(nameFilter);
        }
        if (commitsSize > 0) {
          next += "&" + GitConstants.KEY_TAG_COMMITS + "=" + commitsSize;
        }
        result.put(ProtocolConstants.KEY_NEXT_LOCATION, next);
      }
      for (int i = firstBranch; i <= lastBranch; i++) {
        Branch branch = branches.get(i);
        if (commitsSize == 0) {
          children.put(branch.toJSON());
        } else {
          String branchName = branch.getName(true, false);
          ObjectId toObjectId = db.resolve(branchName);
          Ref toRefId = db.getRef(branchName);
          if (toObjectId == null) {
            String msg = NLS.bind("No ref or commit found: {0}", branchName);
            return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_FOUND, msg, null);
          }
          toObjectId = getCommitObjectId(db, toObjectId);

          Log log = null;
          // single commit is requested and we already know it, no need for LogCommand
          if (commitsSize == 1 && toObjectId instanceof RevCommit) {
            log =
                new Log(
                    cloneLocation,
                    db,
                    Collections.singleton((RevCommit) toObjectId),
                    null,
                    null,
                    toRefId);
          } else {
            LogCommand lc = git.log();
            // set the commit range
            lc.add(toObjectId);
            lc.setMaxCount(this.commitsSize);
            Iterable<RevCommit> commits = lc.call();
            log = new Log(cloneLocation, db, commits, null, null, toRefId);
          }
          log.setPaging(1, commitsSize);
          children.put(branch.toJSON(log.toJSON()));
        }
      }
      result.put(ProtocolConstants.KEY_CHILDREN, children);
      result.put(ProtocolConstants.KEY_TYPE, Branch.TYPE);
      return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result);
    } catch (Exception e) {
      String msg = NLS.bind("An error occured when listing branches for {0}", path);
      return new Status(IStatus.ERROR, GitActivator.PI_GIT, msg, e);
    } finally {
      if (db != null) {
        db.close();
      }
    }
  }
Esempio n. 23
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");
  }