@Override
  public void open(String repositoryPath) {

    FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder();
    try {
      repository =
          repositoryBuilder
              .setGitDir(new File(repositoryPath))
              .readEnvironment() // read git environment variables
              .findGitDir()
              .build();
    } catch (IOException e) {
      throw new VisMinerAPIException(e.getMessage(), e);
    }

    git = new Git(repository);
    revWalk = new RevWalk(repository);
    treeWalk = new TreeWalk(repository);
    reader = repository.newObjectReader();

    processBuilder = new ProcessBuilder();
    processBuilder.directory(new File(repository.getDirectory().toString()));

    commands = Arrays.asList("git", "log", "--numstat", "--oneline", "--max-count=1", "");

    this.repositoryPath = repository.getWorkTree().getAbsolutePath();
  }
Example #2
0
  /**
   * Obtain the Git respository that contains the specified project. The repository can either be in
   * the project's directory or in its hierarchy.
   *
   * @param project
   * @return
   * @throws IOException
   */
  private static Git getGitRepository(final IJavaProject project) throws IOException {
    Git returnValue;
    File gitDirectory;
    File currentDirectory;
    Repository repository;
    FileRepositoryBuilder repositoryBuilder;

    // Check whether the project or one of its ancestors hosts a Git
    // repository
    returnValue = null;
    if (project.getProject().getRawLocation() != null) {
      repositoryBuilder = new FileRepositoryBuilder();
      currentDirectory = project.getProject().getRawLocation().toFile();
      repository =
          repositoryBuilder.setGitDir(currentDirectory).readEnvironment().findGitDir().build();
      while (currentDirectory != null) {
        gitDirectory = new File(currentDirectory, ".git");
        if (gitDirectory.exists()) {
          repositoryBuilder = new FileRepositoryBuilder();
          repository =
              repositoryBuilder.setGitDir(gitDirectory).readEnvironment().findGitDir().build();
          break;
        } else {
          currentDirectory = currentDirectory.getParentFile();
        }
      }

      // If possible, reference the Git repository
      if (repository != null) {
        returnValue = new Git(repository);
      }
    }

    return returnValue;
  }
  @Before
  public void setUp() throws Exception {

    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();

    FileUtils.mkdir(new File(root.getLocation().toFile(), "Sub"), true);
    gitDir = new File(new File(root.getLocation().toFile(), "Sub"), Constants.DOT_GIT);

    repository = FileRepositoryBuilder.create(gitDir);
    repository.create();

    project = root.getProject(TEST_PROJECT);
    project.create(null);
    project.open(null);
    IProjectDescription description = project.getDescription();
    description.setLocation(root.getLocation().append(TEST_PROJECT_LOC));
    project.move(description, IResource.FORCE, null);

    project2 = root.getProject(TEST_PROJECT2);
    project2.create(null);
    project2.open(null);
    gitDir2 = new File(project2.getLocation().toFile().getAbsoluteFile(), Constants.DOT_GIT);
    repository2 = FileRepositoryBuilder.create(gitDir2);
    repository2.create();

    RepositoryMapping mapping = RepositoryMapping.create(project, gitDir);
    RepositoryMapping mapping2 = RepositoryMapping.create(project2, gitDir2);

    GitProjectData projectData = new GitProjectData(project);
    GitProjectData projectData2 = new GitProjectData(project2);
    projectData.setRepositoryMappings(Collections.singletonList(mapping));
    projectData.store();
    projectData2.setRepositoryMappings(Collections.singletonList(mapping2));
    projectData2.store();
    GitProjectData.add(project, projectData);
    GitProjectData.add(project2, projectData2);

    RepositoryProvider.map(project, GitProvider.class.getName());
    RepositoryProvider.map(project2, GitProvider.class.getName());

    JGitTestUtil.write(
        new File(repository.getWorkTree(), TEST_PROJECT + "/" + TEST_FILE), "Some data");
    JGitTestUtil.write(new File(repository2.getWorkTree(), TEST_FILE2), "Some other data");
    project.refreshLocal(IResource.DEPTH_INFINITE, null);
    project2.refreshLocal(IResource.DEPTH_INFINITE, null);
    git = new Git(repository);
    git.add().addFilepattern(".").call();
    git.commit().setMessage("Initial commit").call();

    git = new Git(repository2);
    git.add().addFilepattern(".").call();
    git.commit().setMessage("Initial commit").call();
    git.branchRename().setNewName("main").call();
  }
  /** Clones or pulls the remote repository and returns the directory with the checkout */
  public void cloneOrPull(final String repo, final CredentialsProvider credentials)
      throws Exception {
    if (!localRepo.exists() && !localRepo.mkdirs()) {
      throw new IOException("Failed to create local repository");
    }
    File gitDir = new File(localRepo, ".git");
    if (!gitDir.exists()) {
      LOG.info("Cloning remote repo " + repo);
      CloneCommand command =
          Git.cloneRepository()
              .setCredentialsProvider(credentials)
              .setURI(repo)
              .setDirectory(localRepo)
              .setRemote(remoteName);
      git = command.call();
    } else {
      FileRepositoryBuilder builder = new FileRepositoryBuilder();
      Repository repository =
          builder
              .setGitDir(gitDir)
              .readEnvironment() // scan environment GIT_* variables
              .findGitDir() // scan up the file system tree
              .build();

      git = new Git(repository);

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

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

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

      // now pull
      LOG.info("Pulling from remote repo " + repo);
      git.pull().setCredentialsProvider(credentials).setRebase(true).call();
    }
  }
  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");
  }
  public JGitFlowSemver(File dir, GitflowVersioningConfiguration conf) throws IOException {
    this.dir = dir;
    this.conf = conf;

    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    repository =
        builder
            .setGitDir(dir)
            .readEnvironment() // scan environment GIT_* variables
            .findGitDir() // scan up the file system tree
            .build();
    this.git = Git.wrap(repository);
  }
  public ZeusManager(File root) throws IOException {

    if (root.canRead() && root.isDirectory()) {
      this.root = root;
      this.baseServiceUrl = SVC_BASE_URL;

      // get the repository name.
      FileRepositoryBuilder repobuiler = new FileRepositoryBuilder();
      this.sourceRepository = repobuiler.findGitDir(root).build();

      ghClient = new GitHubClient();
    } else {
      // TODO: throw exception
    }
  }
  @SuppressWarnings("resource" /* java 7 */)
  @Test
  public void absoluteGitDirRef() throws Exception {
    Repository repo1 = createWorkRepository();
    File dir = createTempDirectory("dir");
    File dotGit = new File(dir, Constants.DOT_GIT);
    new FileWriter(dotGit).append("gitdir: " + repo1.getDirectory().getAbsolutePath()).close();
    FileRepositoryBuilder builder = new FileRepositoryBuilder();

    builder.setWorkTree(dir);
    builder.setMustExist(true);
    Repository repo2 = builder.build();

    assertEquals(repo1.getDirectory(), repo2.getDirectory());
    assertEquals(dir, repo2.getWorkTree());
  }
  @Test
  public void testKeyToSegmentsMethod() throws Exception {
    Object configOption =
        ReflectionUtils.callConstructor(
            ConfigOption.class,
            new Object[] {new URI(""), FileRepositoryBuilder.create(new File(""))});

    String[] segments =
        (String[])
            ReflectionUtils.callMethod(configOption, "keyToSegments", new Object[] {"a.b.c"});
    assertArrayEquals(new String[] {"a", "b", "c"}, segments);

    segments =
        (String[]) ReflectionUtils.callMethod(configOption, "keyToSegments", new Object[] {"a.c"});
    assertArrayEquals(new String[] {"a", null, "c"}, segments);

    segments =
        (String[])
            ReflectionUtils.callMethod(configOption, "keyToSegments", new Object[] {"a.b.c.d"});
    assertArrayEquals(new String[] {"a", "b.c", "d"}, segments);

    segments =
        (String[]) ReflectionUtils.callMethod(configOption, "keyToSegments", new Object[] {"a"});
    assertArrayEquals(null, segments);
  }
Example #10
0
  public void initialiseGitRepo() throws IOException, GitAPIException {
    File confDir = getConfigDirectory();
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    File gitDir = new File(confDir, ".git");
    if (!gitDir.exists()) {
      InitCommand initCommand = Git.init();
      initCommand.setDirectory(confDir);
      git = initCommand.call();
    } else {
      Repository repository =
          builder
              .setGitDir(gitDir)
              .readEnvironment() // scan environment GIT_* variables
              .findGitDir() // scan up the file system tree
              .build();

      git = new Git(repository);
    }
  }
Example #11
0
  private void reload(String botName) throws IOException, GitAPIException {
    log.info("Starting bot reload");
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository =
        builder.setGitDir(new File(arguments.getBasePath() + "/.git")).readEnvironment().build();
    log.info("Starting repository update");
    Git git = new Git(repository);
    git.reset().setMode(ResetCommand.ResetType.HARD).call();
    log.info("Reset complete");
    git.clean().call();
    log.info("Clean compete");
    git.fetch().call();
    log.info("Fetch complete");
    git.pull().call();
    log.info("Repository update finished");

    initBot(botName);
    log.info("Bot reloaded");
  }
Example #12
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;
 }
Example #13
0
  // import a git repo in jgit data structures or create a new one
  private Repository createRepo(String repoDir, String gitDir) throws IOException {

    File gd = new File(gitDir);
    File rd = new File(repoDir);
    if (GitWorks.anew) {
      if (rd.exists()) FileUtils.delete(rd, FileUtils.RECURSIVE);
      if (!GitWorks.bare) rd.mkdirs();
      if (gd.exists()) FileUtils.delete(gd, FileUtils.RECURSIVE);
      gd.mkdirs();
    }
    FileRepositoryBuilder frb = new FileRepositoryBuilder();
    if (!GitWorks.bare) frb.setWorkTree(rd);
    Repository repository =
        frb.setGitDir(gd)
            .readEnvironment() // scan environment GIT_* variables
            .findGitDir() // scan up the file system tree
            .setMustExist(!GitWorks.anew)
            .build();
    if (GitWorks.anew) repository.create(GitWorks.bare);

    return repository;
  }
  @Test
  public void test() throws Exception {
    // prepare a new folder
    File localPath = File.createTempFile("TestGitRepository", "");
    localPath.delete();

    // create the directory
    Repository repository = FileRepositoryBuilder.create(new File(localPath, ".git"));
    repository.create(false);

    System.out.println("Having repository: " + repository.getDirectory());

    repository.close();
  }
  @Test
  public void testSegmentsToKeyMethod() throws Exception {
    Object configOption =
        ReflectionUtils.callConstructor(
            ConfigOption.class,
            new Object[] {new URI(""), FileRepositoryBuilder.create(new File(""))});

    String key =
        (String)
            ReflectionUtils.callMethod(
                configOption, "segmentsToKey", new Object[] {new String[] {"a", "b", "c"}});
    assertEquals("a.b.c", key);

    key =
        (String)
            ReflectionUtils.callMethod(
                configOption, "segmentsToKey", new Object[] {new String[] {"a", null, "c"}});
    assertEquals("a.c", key);

    key =
        (String)
            ReflectionUtils.callMethod(
                configOption, "segmentsToKey", new Object[] {new String[] {"a", "b.c", "d"}});
    assertEquals("a.b.c.d", key);

    key =
        (String)
            ReflectionUtils.callMethod(
                configOption, "segmentsToKey", new Object[] {new String[] {"a", "b"}});
    assertEquals(null, key);

    key =
        (String)
            ReflectionUtils.callMethod(
                configOption, "segmentsToKey", new Object[] {new String[] {"a", "b", "c", "d"}});
    assertEquals(null, key);
  }
Example #16
0
  @Test
  public void shareProjectWithAlreadyCreatedRepos()
      throws IOException, InterruptedException, JGitInternalException, GitAPIException {
    Repository repo1 =
        FileRepositoryBuilder.create(
            new File(new File(createProject(projectName1)).getParent(), ".git"));
    repo1.create();
    repo1.close();
    Repository repo2 = FileRepositoryBuilder.create(new File(createProject(projectName2), ".git"));
    repo2.create();
    repo2.close();
    Repository repo3 = FileRepositoryBuilder.create(new File(createProject(projectName3), ".git"));
    repo3.create();
    Git git = new Git(repo3);
    git.add().addFilepattern(".").call();
    git.commit()
        .setAuthor("A U Thior", "*****@*****.**")
        .setMessage("Created Project 3")
        .call();
    repo3.close();

    ExistingOrNewPage existingOrNewPage =
        sharingWizard.openWizard(projectName1, projectName2, projectName3);
    existingOrNewPage.setInternalMode(true);

    // initial state
    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    String projectPath1 = workspace.getRoot().getProject(projectName1).getLocation().toOSString();
    String projectPath2 = workspace.getRoot().getProject(projectName2).getLocation().toOSString();
    String projectPath3 = workspace.getRoot().getProject(projectName3).getLocation().toOSString();
    existingOrNewPage.assertContents(
        new Row[] {
          new Row(true, projectName1, projectPath1, ".." + File.separator + ".git"),
          new Row(
              false,
              projectName2,
              projectPath2,
              "",
              new Row[] {
                new Row(false, ".", "", ".git"),
                new Row(false, "..", "", ".." + File.separator + ".git")
              }),
          new Row(
              false,
              projectName3,
              projectPath3,
              "",
              new Row[] {
                new Row(true, ".", "", ".git"),
                new Row(false, "..", "", ".." + File.separator + ".git")
              })
        },
        "");

    bot.tree().getAllItems()[1].getItems()[0].check();
    existingOrNewPage.assertEnabling(false, false, true);
    bot.button("Finish").click();
    Thread.sleep(1000);
    assertEquals(
        repo1.getDirectory().getAbsolutePath(),
        RepositoryMapping.getMapping(workspace.getRoot().getProject(projectName1))
            .getRepository()
            .getDirectory()
            .toString());
    assertEquals(
        repo2.getDirectory().getAbsolutePath(),
        RepositoryMapping.getMapping(workspace.getRoot().getProject(projectName2))
            .getRepository()
            .getDirectory()
            .toString());
  }
  @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();
      }
    }
  }
Example #18
0
 @Override
 protected IStatus performJob() {
   Repository db = null;
   try {
     // list all tags
     File gitDir = GitUtils.getGitDir(path);
     db = FileRepositoryBuilder.create(gitDir);
     Git git = Git.wrap(db);
     List<Ref> refs = git.tagList().call();
     JSONObject result = new JSONObject();
     List<Tag> tags = new ArrayList<Tag>();
     for (Ref ref : refs) {
       if (nameFilter != null && !nameFilter.equals("")) {
         String shortName = Repository.shortenRefName(ref.getName());
         if (shortName.toLowerCase().contains(nameFilter.toLowerCase())) {
           Tag tag = new Tag(cloneLocation, db, ref);
           tags.add(tag);
         }
       } else {
         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 (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 (lastTag < tags.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 = 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);
         log.setPaging(1, commitsSize);
         children.put(tag.toJSON(log.toJSON()));
       }
     }
     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);
   } finally {
     if (db != null) {
       db.close();
     }
   }
 }
Example #19
0
  protected void initGitRepo() throws MojoExecutionException, IOException, GitAPIException {
    buildDir.mkdirs();
    File gitDir = new File(buildDir, ".git");
    if (!gitDir.exists()) {
      String repo = gitUrl;
      if (Strings.isNotBlank(repo)) {
        getLog()
            .info(
                "Cloning git repo "
                    + repo
                    + " into directory "
                    + getGitBuildPathDescription()
                    + " cloneAllBranches: "
                    + cloneAll);
        CloneCommand command =
            Git.cloneRepository()
                .setCloneAllBranches(cloneAll)
                .setURI(repo)
                .setDirectory(buildDir)
                .setRemote(remoteName);
        // .setCredentialsProvider(getCredentials()).
        try {
          git = command.call();
          return;
        } catch (Throwable e) {
          getLog().error("Failed to command remote repo " + repo + " due: " + e.getMessage(), e);
          // lets just use an empty repo instead
        }
      } else {
        InitCommand initCommand = Git.init();
        initCommand.setDirectory(buildDir);
        git = initCommand.call();
        getLog()
            .info("Initialised an empty git configuration repo at " + getGitBuildPathDescription());

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

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

      git = new Git(repository);
      if (pullOnStartup) {
        doPull();
      } else {
        getLog().info("git pull from remote config repo on startup is disabled");
      }
    }
  }
Example #20
0
  public String getDiffText(String str) {
    int filenubs = 0;
    int lines = 0;
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    File gitDir = new File("F:/work/demo-rio/.git");
    Repository repository = null;
    try {
      if (git == null) {
        git = Git.open(gitDir);
      }
    } catch (Exception e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
    try {
      String cid = str;
      repository = builder.setGitDir(gitDir).readEnvironment().findGitDir().build();
      RevWalk walk = new RevWalk(repository);
      ObjectId objId = ObjectId.fromString(cid);
      RevCommit commit = walk.parseCommit(objId);
      System.out.println(commit.getFullMessage());

      TreeWalk tw = new TreeWalk(repository);

      RevCommit[] parent_commits = commit.getParents();
      if (parent_commits.length == 0) {
        throw new Exception("当前只有一个版本");
      }

      ObjectId objId2 = parent_commits[0].toObjectId();
      RevCommit paren_commit = walk.parseCommit(objId2);
      tw.addTree(paren_commit.getTree());
      tw.addTree(commit.getTree());
      tw.setRecursive(true);

      ByteArrayOutputStream out = new ByteArrayOutputStream();
      DiffFormatter df = new DiffFormatter(out);
      df.setRepository(git.getRepository());
      RenameDetector rd = new RenameDetector(repository);
      rd.addAll(DiffEntry.scan(tw));
      List<DiffEntry> diffEntries = rd.compute();
      if (diffEntries != null || diffEntries.size() != 0) {

        Iterator<DiffEntry> iterator = new ArrayList<DiffEntry>(diffEntries).iterator();
        DiffEntry diffEntry = null;
        while (iterator.hasNext()) {
          diffEntry = iterator.next();
          String changeType = diffEntry.getChangeType().toString();
          String type = "";
          if (changeType.equals("DELETE")) {
            type = ConfigUtil.getFileType(diffEntry.getOldPath());
            filenubs++;
            System.out.println(diffEntry.getOldPath());
          } else {
            type = ConfigUtil.getFileType(diffEntry.getNewPath());
            filenubs++;
            System.out.println(diffEntry.getNewPath());
          }
          // 检查文件的后缀
          // System.out.println(type);
          if (fileTypes.contains(type)) {
            df.format(diffEntry);
            String diffText = out.toString("UTF-8");
            lines += scanDiffText(diffText);
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return filenubs + "&" + lines;
    // System.out.println("the changed file nubs: "+ filenubs);
    // System.out.println("the changed linr nubs: "+ lines);
  }