예제 #1
0
 private void commit(Git git, String message) throws GitAPIException {
   Status status = git.status().call();
   if (!status.getAdded().isEmpty()
       || !status.getChanged().isEmpty()
       || !status.getRemoved().isEmpty()) {
     git.commit().setMessage(message).call();
   }
 }
예제 #2
0
  /**
   * @param gitConfigFolder e.g. /your/project/root/.git
   * @return Returns true if 'git status' has modified files inside the 'Changes to be committed'
   *     section
   */
  public static boolean isCommitNecessary(String gitConfigFolder) throws MojoExecutionException {
    try {
      Repository repo = new FileRepository(gitConfigFolder);
      Git git = new Git(repo);

      Status status = git.status().call();
      Set<String> modified = status.getModified();

      return (modified.size() != 0);
    } catch (Exception e) {
      throw new MojoExecutionException("Error trying to find out if git commit is needed", e);
    }
  }
예제 #3
0
  @Override
  protected void executeCustom(Git git) throws Exception {
    StatusCommand sc = git.status();

    Status status = sc.call();

    if (isclean != null && status.isClean()) {
      PropertyHelper.getPropertyHelper(getProject()).setNewProperty(isclean, "true");
    }

    if (isdirty != null && !status.isClean()) {
      PropertyHelper.getPropertyHelper(getProject()).setNewProperty(isdirty, "true");
    }

    if (untracked != null) {
      ResourceCollection resources = buildResourcesCollection(status.getUntracked());
      getProject().addReference(untracked, resources);
    }

    if (added != null) {
      ResourceCollection resources = buildResourcesCollection(status.getAdded());
      getProject().addReference(added, resources);
    }

    if (modified != null) {
      ResourceCollection resources = buildResourcesCollection(status.getModified());
      getProject().addReference(modified, resources);
    }

    if (changed != null) {
      ResourceCollection resources = buildResourcesCollection(status.getChanged());
      getProject().addReference(changed, resources);
    }

    if (missing != null) {
      ResourceCollection resources = buildResourcesCollection(status.getMissing());
      getProject().addReference(missing, resources);
    }

    if (removed != null) {
      ResourceCollection resources = buildResourcesCollection(status.getRemoved());
      getProject().addReference(removed, resources);
    }
  }
예제 #4
0
 /**
  * Returns <code>true</code> if the given repository has uncommitted changes. Uncommitted changes
  * taken into account are
  *
  * <ul>
  *   <li>freshly added (but uncommitted resources)
  *   <li>changed (but uncommitted)
  *   <li>modified (but uncommitted resources)
  *   <li>removed (but uncommitted resources)
  * </ul>
  *
  * @param repository the repository to check for uncommitted changes
  * @return
  * @throws IOException
  * @throws NoWorkTreeException
  * @throws GitAPIException
  */
 public static boolean isDirty(Repository repository)
     throws NoWorkTreeException, IOException, GitAPIException {
   boolean hasChanges = false;
   org.eclipse.jgit.api.Status repoStatus = new Git(repository).status().call();
   hasChanges |= !repoStatus.getAdded().isEmpty();
   hasChanges |= !repoStatus.getChanged().isEmpty();
   hasChanges |= !repoStatus.getModified().isEmpty();
   hasChanges |= !repoStatus.getRemoved().isEmpty();
   hasChanges |= !repoStatus.getConflicting().isEmpty();
   hasChanges |= !repoStatus.getMissing().isEmpty();
   return hasChanges;
 }
예제 #5
0
 public void commitAllChanges(final String message) {
   final Repository repository = getRepository();
   try {
     final Git git = new Git(repository);
     git.add().addFilepattern(".").call();
     final Status status = git.status().call();
     if (status.getChanged().size() > 0
         || status.getAdded().size() > 0
         || status.getModified().size() > 0
         || status.getRemoved().size() > 0) {
       final RevCommit rev =
           git.commit()
               .setAll(true)
               .setCommitter(person)
               .setAuthor(person)
               .setMessage(message)
               .call();
       LOGGER.info("Git commit " + rev.getName() + " [" + message + "]");
     }
   } catch (final Exception e) {
     throw new IllegalStateException("Could not commit changes to local Git repository", e);
   }
 }
  @Test
  public void markAsMerged() throws Exception {
    GitSynchronizeData gsd = new GitSynchronizeData(repo, HEAD, HEAD, false);
    GitSynchronizeDataSet gsds = new GitSynchronizeDataSet(gsd);
    GitResourceVariantTreeSubscriber subscriber = new GitResourceVariantTreeSubscriber(gsds);

    String fileName = "src/Main.java";
    File file = testRepo.createFile(iProject, fileName);
    testRepo.appendContentAndCommit(iProject, file, "class Main {}", "some file");
    testRepo.addToIndex(iProject.getFile(".classpath"));
    testRepo.addToIndex(iProject.getFile(".project"));
    testRepo.commit("project files");

    IFile workspaceFile = testRepo.getIFile(iProject, file);

    ResourceMapping mapping = AdapterUtils.adapt(workspaceFile, ResourceMapping.class);
    ResourceMapping[] inputMappings = new ResourceMapping[] {mapping};
    SubscriberScopeManager manager =
        new SubscriberScopeManager("Scope", inputMappings, subscriber, true);

    testRepo.appendFileContent(file, "some changes");
    Status status = new Git(repo).status().call();
    assertEquals(0, status.getAdded().size());
    assertEquals(1, status.getModified().size());
    String repoRelativePath =
        testRepo.getRepoRelativePath(workspaceFile.getLocation().toPortableString());
    assertTrue(status.getModified().contains(repoRelativePath));

    GitSubscriberMergeContext mergeContext =
        new GitSubscriberMergeContext(subscriber, manager, gsds);
    IDiff node = new ResourceDiff(iProject.getFolder("src"), IDiff.CHANGE);
    mergeContext.markAsMerged(node, true, null);

    status = new Git(repo).status().call();
    assertEquals(1, status.getChanged().size());
    assertEquals(0, status.getModified().size());
    assertTrue(status.getChanged().contains(repoRelativePath));
  }
예제 #7
0
  @Test
  public void createFileAndListDirectory() throws Exception {
    assertConfigDirectoryExists(git);

    String readMeContent = "Hello world!";
    String anotherContent = "Something else!";
    String readMePath = "/ReadMe.md";
    String anotherPath = "/Another.md";

    git.write(branch, readMePath, "Initial commit", authorName, authorEmail, readMeContent);
    git.write(branch, anotherPath, "Second commit", authorName, authorEmail, anotherContent);

    List<FileInfo> contents = assertReadDirectory("/");
    assertNotNull("No contents!", contents);
    assertTrue("Should have some files", contents.size() > 0);

    for (FileInfo content : contents) {
      System.out.println("have file " + content);
    }

    // now lets assert that a git status has no pending files to add...
    Status status = git.status();
    assertNotNull("No status!", status);
    assertEquals("added size", 0, status.getAdded().size());
    assertEquals("untracked size", 0, status.getUntracked().size());

    // now lets read the files...
    String readMeActual = assertReadFileContents(readMePath, readMeContent);
    String anotherActual = assertReadFileContents(anotherPath, anotherContent);

    System.out.println(readMePath + " = " + readMeActual);
    System.out.println(anotherPath + " = " + anotherActual);

    // now lets try remove one of the files we created
    git.remove(branch, anotherPath, "Remove another thingy", authorName, authorEmail);

    // now lets assert that we can't find the file...
    contents = assertReadDirectory("/");
    assertNotNull("No contents!", contents);
    assertTrue("Should have some files", contents.size() > 0);
    for (FileInfo content : contents) {
      assertNotEquals("Should not still have the deleted file!", "Another.md", content.getName());
    }

    String shouldFail = null;
    try {
      shouldFail = assertReadFileContents(anotherPath);
      fail("Should have thrown an exception!");
    } catch (Throwable e) {
      // expected exception!
    }
    assertNull("Should not find any data", shouldFail);

    // lets update the file
    String readMeContent2 = "Goodbye world!";
    git.write(
        branch,
        readMePath,
        "Updating the content to goodbye",
        authorName,
        authorEmail,
        readMeContent2);
    assertReadFileContents(readMePath, readMeContent2);

    // now lets do a diff on this file
    String blobPath = trimLeadingSlash(readMePath);
    String diff = git.diff(null, null, blobPath);
    assertNotNull("Should have returned a diff!");
    System.out.println("Diff of " + readMePath);
    System.out.println(diff);
    System.out.println();

    // now lets try find the history and revert to the first version
    List<CommitInfo> readMeHistory = git.history(null, blobPath, 0, 0, false, 0);
    assertTrue(
        "Should have at least 2 items in the history but got " + readMeHistory.size(),
        readMeHistory.size() >= 2);
    String objectId = readMeHistory.get(readMeHistory.size() - 1).getName();
    git.revertTo(
        branch,
        objectId,
        blobPath,
        "Reverting to first version " + objectId,
        authorName,
        authorEmail);
    assertReadFileContents(readMePath, readMeContent);

    // now lets find out the log.
    String[] paths = {null, readMePath, anotherPath};
    for (String path : paths) {
      String name = trimLeadingSlash(path);
      List<CommitInfo> log = git.history(null, name, 0, 0, true, 0);
      System.out.println("Showing commits for path " + name);
      for (CommitInfo info : log) {
        System.out.println("  " + info);

        if (path != null) {
          String content = git.getContent(info.getName(), name);
          System.out.println("    = " + content);
        }
      }
      System.out.println();
    }

    // now lets make a new git facade to check we can work with existing repos
    GitFacade anotherGit = new GitFacade();
    anotherGit.setObjectName(new ObjectName("io.hawt.git:type=GitFacadePart2"));
    anotherGit.setConfigDirectory(git.getConfigDirectory());
    anotherGit.init();

    String path = trimLeadingSlash(anotherPath);
    List<CommitInfo> log = git.history(null, path, 0, 0, true, 0);
    assertTrue("should have more than one commit info", log.size() > 0);

    System.out.println("Using existing repo and showing commits for path " + path);
    for (CommitInfo info : log) {
      System.out.println("  " + info);

      String content = git.getContent(info.getName(), path);
      System.out.println("    = " + content);
    }
  }
    /**
     * Gets the status of this file.
     *
     * @return status of this file.
     */
    public TextArea getStatus() {
      TextArea area = null;
      try {
        Path repoPath = this.getHost().repository;
        Git git = Git.open(repoPath.toFile());

        //
        // I would like to use absolutePath, but that seems to barf when
        // we try to relativize this if a full path is not given.
        //
        Path relativePath = repoPath.relativize(Paths.get(this.file.getPath()));

        Status status = git.status().addPath(relativePath.toString()).call();
        if (logger.isDebugEnabled()) {
          logger.debug(this.file.getAbsolutePath());
          logger.debug("Added: " + status.getAdded());
          logger.debug("Changed: " + status.getChanged());
          logger.debug("Conflicting: " + status.getConflicting());
          logger.debug("Missing: " + status.getMissing());
          logger.debug("Modified: " + status.getModified());
          logger.debug("Removed: " + status.getRemoved());
          logger.debug("Uncommitted: " + status.getUncommittedChanges());
          logger.debug("Untracked: " + status.getUntracked());
          logger.debug("Untracked folders; " + status.getUntrackedFolders());
        }
        //
        // Are we a file or directory?
        //
        StringBuffer buffer = new StringBuffer();
        int length = 0;
        if (this.file.isFile()) {
          if (status.getAdded().contains(relativePath.toString())) {
            buffer.append("Added" + "\n");
            length++;
          }
          if (status.getChanged().contains(relativePath.toString())) {
            buffer.append("Changed" + "\n");
            length++;
          }
          if (status.getConflicting().contains(relativePath.toString())) {
            buffer.append("Conflicting" + "\n");
            length++;
          }
          if (status.getMissing().contains(relativePath.toString())) {
            buffer.append("Missing" + "\n");
            length++;
          }
          if (status.getModified().contains(relativePath.toString())) {
            buffer.append("Modified" + "\n");
            length++;
          }
          if (status.getRemoved().contains(relativePath.toString())) {
            buffer.append("Removed" + "\n");
            length++;
          }
          if (status.getUncommittedChanges().contains(relativePath.toString())) {
            buffer.append("Uncommitted" + "\n");
            length++;
          }
          if (status.getUntracked().contains(relativePath.toString())) {
            buffer.append("Untracked (New)" + "\n");
            length++;
          }
          if (status.getUntrackedFolders().contains(relativePath.toString())) {
            buffer.append("Untracked Folders (New)" + "\n");
            length++;
          }
        } else if (this.file.isDirectory()) {
          if (status.getUntracked().size() > 0) {
            buffer.append("Untracked (New)" + "\n");
            length++;
          }
          if (status.getUntrackedFolders().size() > 0) {
            buffer.append("Untracked Folders (New)" + "\n");
            length++;
          }
        }
        if (length > 0) {
          area = new TextArea();
          area.setValue(buffer.toString().trim());
          area.setWidth("100.0%");
          area.setRows(length);
          area.setReadOnly(true);
        }
      } catch (IOException | NoWorkTreeException | GitAPIException e) {
        logger.error(e);
      }
      return area;
    }
예제 #9
0
 private void stageMissingFilesAsDeleted(final Git git) throws GitAPIException {
   final Status status = git.status().call();
   for (final String missingFile : status.getMissing()) {
     git.rm().addFilepattern(missingFile).call();
   }
 }
예제 #10
0
 private void logStatus(final Git git) throws GitAPIException {
   final Status status = git.status().call();
   if (!status.getAdded().isEmpty()) {
     LOG.info("Added files {}", status.getAdded());
   }
   if (!status.getChanged().isEmpty()) {
     LOG.info("Changed files {}", status.getChanged());
   }
   if (!status.getRemoved().isEmpty()) {
     LOG.info("Removed files {}", status.getRemoved());
   }
   if (!status.getModified().isEmpty()) {
     LOG.info("Modified files {}", status.getModified());
   }
   if (!status.getMissing().isEmpty()) {
     LOG.info("Missing files {}", status.getMissing());
   }
 }