示例#1
0
 private boolean isLocalBranch(Git git, String branch) throws GitAPIException {
   List<Ref> branches = git.branchList().call();
   for (Ref ref : branches) {
     if (Repository.shortenRefName(ref.getName()).equals(branch)) return true;
   }
   return false;
 }
示例#2
0
  // build both the allBranches sorted arrayList and the branches map
  private void buildBranchesMap(int size) throws GitAPIException {

    if (branches != null) {
      System.err.println(
          "GitMIner ( "
              + name
              + " -- "
              + id
              + " ) ERROR : the map of the branches has already been built!");
      return;
    }
    branches = new LinkedHashMap<String, ArrayList<BranchRef>>(size, 1);
    allBranches = new ArrayList<BranchRef>();

    ArrayList<BranchRef> temp = null;
    BranchRef br;
    Ref r;
    ArrayList<Ref> all = (ArrayList<Ref>) git.branchList().setListMode(ListMode.REMOTE).call();
    Iterator<Ref> allBs = all.iterator();
    String bName = "";
    allBranches.ensureCapacity(all.size()); // int j = 0;
    while (allBs.hasNext()) {
        /**/
      // System.err.println("###### Iteration " + (++j));
      r = allBs.next();
      if (!(r.getName().split("/")[2]).equals(bName)) {
        bName = r.getName().split("/")[2]; // getName() format:
        // refs/remotes/<remote-name>/<branch-name>
        if (temp != null) temp.trimToSize();
        temp = new ArrayList<BranchRef>();
        branches.put(bName, temp);
      }
      br = new BranchRef(r);
      temp.add(br);
      allBranches.add(br);
    }
    allBranches.trimToSize();
    Collections.sort(allBranches);
    for (int i = 0; i < allBranches.size(); i++) {
      allBranches.get(i).index = i;
    }
    //  Entry<String, ArrayList<BranchRef>> e;
    //  Iterator<Entry<String, ArrayList<BranchRef>>> eit = branches.entrySet().iterator();
    //  while (eit.hasNext()) {
    //    e = eit.next();
    //    System.out.println("\t" + e.getKey() + ":\n");
    //    printAny(e.getValue(), System.out);
    //  }
    //  printArray(allBranches, System.out);
  }
示例#3
0
 protected List<String> doListBranches(Git git) throws GitAPIException {
   SortedSet<String> names = new TreeSet<String>();
   List<Ref> call = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();
   for (Ref ref : call) {
     String name = ref.getName();
     int idx = name.lastIndexOf('/');
     if (idx >= 0) {
       name = name.substring(idx + 1);
     }
     if (name.length() > 0) {
       names.add(name);
     }
   }
   return new ArrayList<String>(names);
 }
示例#4
0
  /**
   * Get all the different versions of the specified project, represented by the existing
   * <em>Tags</em> and <em>Branches</em> in the associated Git repository.
   *
   * @param project
   * @throws IOException
   * @throws GitAPIException
   */
  public static List<Ref> getProjectVersions(final IJavaProject project)
      throws IOException, GitAPIException {
    Git gitRepository;
    List<Ref> returnValue;

    // Try to get a reference to the Git repository associated to the
    // specified project
    returnValue = new ArrayList<Ref>();
    gitRepository = GitUtil.getGitRepository(project);

    // Consider each tag/branch as a different project version
    if (gitRepository != null) {
      returnValue.addAll(gitRepository.branchList().call());
      returnValue.addAll(gitRepository.tagList().call());
    }

    return returnValue;
  }
  @Override
  public List<TreeDB> getTrees() {

    try {

      List<TreeDB> trees = new ArrayList<TreeDB>();

      Iterable<Ref> refs = git.branchList().call();
      for (Ref ref : refs) {

        if (ref.getName().equals(HEAD)) continue;

        TreeDB tree =
            new TreeDB(
                0,
                ref.getName(),
                getLastCommitDate(ref.getName()),
                ref.getName().split("/")[2],
                TreeType.BRANCH);
        trees.add(tree);
      }

      refs = git.tagList().call();
      for (Ref ref : refs) {
        TreeDB tree =
            new TreeDB(
                0,
                ref.getName(),
                getLastCommitDate(ref.getName()),
                ref.getName().split("/")[2],
                TreeType.TAG);
        trees.add(tree);
      }

      return trees;

    } catch (GitAPIException e) {
      throw new VisMinerAPIException(e.getMessage(), e);
    }
  }
  public Version infer() throws Exception {

    Ref headRef = repository.getRef(Constants.HEAD);
    if (headRef == null || headRef.getObjectId() == null) {
      LOGGER.warn("No commit yet");
    }
    final List<Ref> branches = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();

    VersionWithType versionWithType = null;
    for (Strategy strategy : Strategy.STRATEGIES) {
      if (strategy.canInfer(repository, conf)) {
        if (LOGGER.isDebugEnabled()) {
          LOGGER.debug("Applying strategy {}", strategy.getClass().getSimpleName());
        }
        versionWithType = strategy.infer(git, conf);

        if (versionWithType != null) {
          return versionWithType.getVersion();
        }
      }
    }

    return null;
  }
  // 2. Get branch/commit hash for the source repo - the actual source code
  @Test
  public void existsIn2() throws IOException {
    final String repo = "binrepo-devex";
    //  final String repo = "search_raptor_binary";
    // String githubUrl = "https://github.scm.corp.ebay.com/api/v3";
    // String accessToken = "1cf7d9792235b8592eda18bd7dcc2de37f99b3bc";

    final String path = "D:\\dev\\devex\\.binrepo-devex\\.git";

    File gitDir = new File(path);
    org.eclipse.jgit.lib.Repository repository =
        new org.eclipse.jgit.storage.file.FileRepository(gitDir);
    String branch = repository.getBranch();
    System.out.println("Branch=" + branch);
    final Map<String, Ref> allRefs = repository.getAllRefs();
    for (String s : allRefs.keySet()) {
      System.out.println("Here" + s);
    }

    RevWalk revWalk = new RevWalk(repository);
    ObjectId resolve = repository.resolve(Constants.HEAD);
    RevCommit commitRev = revWalk.parseCommit(resolve);
    String commitHash = commitRev.getName();
    System.out.println(commitHash + "\t" + commitRev.getFullMessage());

    Git binaryRepo = Git.open(gitDir);

    final ListBranchCommand listBranchCommand = binaryRepo.branchList();
    System.out.println(listBranchCommand.getRepository().getFullBranch());
    // get "status"
    final StatusCommand statusCommand = binaryRepo.status();
    Collection<String> toadd = GitUtils.getFilesToStage(statusCommand);
    for (String s : toadd) {
      System.out.println("To be added:" + s);
    }

    // add files to "staging"
    if (toadd.size() > 0) {
      AddCommand addCmd = binaryRepo.add();
      for (String file : toadd) {
        addCmd.addFilepattern(file);
      }

      try {
        addCmd.call();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    final StoredConfig config = repository.getConfig();
    String url = config.getString("remote", "origin", "url");
    if (url != null) {
      System.out.println("Origin comes from " + url);
    }

    // commit
    final CommitCommand commit = binaryRepo.commit();
    String msg = "Saving Repo:%s Branch:%s CommitHash:%s Time:%s";
    final String formattedMsg = String.format(msg, repo, branch, commitHash, new Date().toString());
    commit.setMessage(formattedMsg);
    try {
      commit.call();
    } catch (Exception e) {
      e.printStackTrace();
    }

    // push to origin now
    final PushCommand push = binaryRepo.push();
    final String remote = push.getRemote();
    System.out.println("Remote to push to:'" + remote + "'");
    try {
      push.call();
    } catch (Exception e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    }
  }
  @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();
      }
    }
  }
示例#9
0
文件: GitUtils.java 项目: snjeza/core
 public static List<Ref> getLocalBranches(final Git repo) throws GitAPIException {
   // returns only local branches by default
   return repo.branchList().call();
 }