org.eclipse.jgit.diff.DiffEntry Java Examples

The following examples show how to use org.eclipse.jgit.diff.DiffEntry. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Commit.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
protected URI createContentLocation(final DiffEntry entr, String path) throws URISyntaxException {
	// remove /gitapi/clone from the start of path
	IPath clonePath = new Path(cloneLocation.getPath()).removeFirstSegments(2);
	IPath result;
	if (path == null) {
		result = clonePath;
	} else if (isRoot) {
		result = clonePath.append(path);
	} else {
		// need to start from the project root
		// project path is of the form /file/{workspaceId}/{projectName}
		result = clonePath.uptoSegment(3).append(path);
	}
	return new URI(cloneLocation.getScheme(), cloneLocation.getUserInfo(), cloneLocation.getHost(), cloneLocation.getPort(), result.makeAbsolute()
			.toString(), cloneLocation.getQuery(), cloneLocation.getFragment());
}
 
Example #2
Source File: JGitDiscoveryTest.java    From multi-module-maven-release-plugin with MIT License 6 votes vote down vote up
@Test public void name() throws IOException, GitAPIException {
    ObjectId head = repo.resolve("HEAD^{tree}");
    ObjectId oldHead = repo.resolve("HEAD^^{tree}");


    ObjectReader reader = repo.newObjectReader();

    CanonicalTreeParser prevParser = new CanonicalTreeParser();
    prevParser.reset(reader, oldHead);

    CanonicalTreeParser headParser = new CanonicalTreeParser();
    headParser.reset(reader, head);

    List<DiffEntry> diffs = new Git(repo).diff()
            .setNewTree(headParser)
            .setOldTree(prevParser)
            .call();

    for (DiffEntry entry : diffs)
        System.out.println(entry);
}
 
Example #3
Source File: OldGitNotebookRepo.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@Override
public Revision checkpoint(String pattern, String commitMessage, AuthenticationInfo subject) {
  Revision revision = Revision.EMPTY;
  try {
    List<DiffEntry> gitDiff = git.diff().call();
    if (!gitDiff.isEmpty()) {
      LOG.debug("Changes found for pattern '{}': {}", pattern, gitDiff);
      DirCache added = git.add().addFilepattern(pattern).call();
      LOG.debug("{} changes are about to be commited", added.getEntryCount());
      RevCommit commit = git.commit().setMessage(commitMessage).call();
      revision = new Revision(commit.getName(), commit.getShortMessage(), commit.getCommitTime());
    } else {
      LOG.debug("No changes found {}", pattern);
    }
  } catch (GitAPIException e) {
    LOG.error("Failed to add+commit {} to Git", pattern, e);
  }
  return revision;
}
 
Example #4
Source File: GitNotebookRepo.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@Override
public Revision checkpoint(String noteId,
                           String notePath,
                           String commitMessage,
                           AuthenticationInfo subject) throws IOException {
  String noteFileName = buildNoteFileName(noteId, notePath);
  Revision revision = Revision.EMPTY;
  try {
    List<DiffEntry> gitDiff = git.diff().call();
    boolean modified = gitDiff.parallelStream().anyMatch(diffEntry -> diffEntry.getNewPath().equals(noteFileName));
    if (modified) {
      LOGGER.debug("Changes found for pattern '{}': {}", noteFileName, gitDiff);
      DirCache added = git.add().addFilepattern(noteFileName).call();
      LOGGER.debug("{} changes are about to be commited", added.getEntryCount());
      RevCommit commit = git.commit().setMessage(commitMessage).call();
      revision = new Revision(commit.getName(), commit.getShortMessage(), commit.getCommitTime());
    } else {
      LOGGER.debug("No changes found {}", noteFileName);
    }
  } catch (GitAPIException e) {
    LOGGER.error("Failed to add+commit {} to Git", noteFileName, e);
  }
  return revision;
}
 
Example #5
Source File: GitNotebookRepoTest.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@Test
public void initNonemptyNotebookDir() throws IOException, GitAPIException {
  //given - .git does not exit
  File dotGit = new File(Joiner.on(File.separator).join(notebooksDir, ".git"));
  assertThat(dotGit.exists()).isEqualTo(false);

  //when
  notebookRepo = new GitNotebookRepo(conf);

  //then
  Git git = notebookRepo.getGit();
  Truth.assertThat(git).isNotNull();

  assertThat(dotGit.exists()).isEqualTo(true);
  assertThat(notebookRepo.list(null)).isNotEmpty();

  List<DiffEntry> diff = git.diff().call();
  // no commit, diff isn't empty
  Truth.assertThat(diff).isNotEmpty();
}
 
Example #6
Source File: GitConfigMonitor.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * remove a {@link FlowSpec} for a deleted or renamed flow config
 * @param change
 */
@Override
public void removeChange(DiffEntry change) {
  if (checkConfigFilePath(change.getOldPath())) {
    Path configFilePath = new Path(this.repositoryDir, change.getOldPath());
    String flowName = FSSpecStore.getSpecName(configFilePath);
    String flowGroup = FSSpecStore.getSpecGroup(configFilePath);

    // build a dummy config to get the proper URI for delete
    Config dummyConfig = ConfigBuilder.create()
        .addPrimitive(ConfigurationKeys.FLOW_GROUP_KEY, flowGroup)
        .addPrimitive(ConfigurationKeys.FLOW_NAME_KEY, flowName)
        .build();

    FlowSpec spec = FlowSpec.builder()
        .withConfig(dummyConfig)
        .withVersion(SPEC_VERSION)
        .withDescription(SPEC_DESCRIPTION)
        .build();

      this.flowCatalog.remove(spec.getUri());
  }
}
 
Example #7
Source File: GitConfigMonitor.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Add a {@link FlowSpec} for an added, updated, or modified flow config
 * @param change
 */
@Override
public void addChange(DiffEntry change) {
  if (checkConfigFilePath(change.getNewPath())) {
    Path configFilePath = new Path(this.repositoryDir, change.getNewPath());

    try {
      Config flowConfig = loadConfigFileWithFlowNameOverrides(configFilePath);

      this.flowCatalog.put(FlowSpec.builder()
          .withConfig(flowConfig)
          .withVersion(SPEC_VERSION)
          .withDescription(SPEC_DESCRIPTION)
          .build());
    } catch (IOException e) {
      log.warn("Could not load config file: " + configFilePath);
    }
  }
}
 
Example #8
Source File: UpdaterGenerator.java    From neembuu-uploader with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Populate all the files to update, if the system should update.
 */
private void populateDiff() {
    try {
        git.fetch().call();
        Repository repo = git.getRepository();
        ObjectId fetchHead = repo.resolve("FETCH_HEAD^{tree}");
        ObjectId head = repo.resolve("HEAD^{tree}");
        
        ObjectReader reader = repo.newObjectReader();
        CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
        oldTreeIter.reset(reader, head);
        CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
        newTreeIter.reset(reader, fetchHead);
        List<DiffEntry> diffs = git.diff().setShowNameAndStatusOnly(true)
                .setNewTree(newTreeIter)
                .setOldTree(oldTreeIter)
                .call();
        
        pluginsToUpdate = new ArrayList<PluginToUpdate>();
        
        checkDiffEmpty(diffs);
        
    } catch (GitAPIException | IOException ex) {
        Logger.getLogger(UpdaterGenerator.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example #9
Source File: GitCommit.java    From Getaviz with Apache License 2.0 6 votes vote down vote up
private void addDiff(DiffImplementation returnable, RevCommit parent) throws IOException {
	RevWalk revWalk = new RevWalk(repository);
	parent = revWalk.parseCommit(parent.getId());
	revWalk.close();
	ByteArrayOutputStream put = new ByteArrayOutputStream(BUFFER_SIZE);
	DiffFormatter df = new DiffFormatter(put);
	df.setRepository(repository);
	df.setDiffComparator(RawTextComparator.DEFAULT);
	df.setDetectRenames(true);
	List<DiffEntry> diffs = df.scan(parent.getTree(), commit.getTree());
	for(DiffEntry e : diffs){
		df.format(e);
		String diffText = put.toString(DEFAULT_ENCODING); //TODO make encoding insertable
		returnable.addOperation(e.getOldPath(), new GitOperation(diffText, e.getOldPath(), e.getNewPath(), e.getChangeType()));
		put.reset();
	}
	df.close();
}
 
Example #10
Source File: CommitUtil.java    From SZZUnleashed with MIT License 6 votes vote down vote up
/**
 * Parse the lines a commit recently made changes to compared to its parent.
 *
 * @param revc the current revision.
 * @return a commit object containing all differences.
 */
public Commit getCommitDiffingLines(RevCommit revc, RevCommit... revother)
    throws IOException, GitAPIException {

  if (revc.getId() == revc.zeroId()) return null;

  RevCommit parent = null;
  if (revother.length > 0) parent = revother[0];
  else if (revc.getParents().length > 0) parent = revc.getParent(0);
  else parent = revc;

  if (parent.getId() == ObjectId.zeroId()) return null;

  List<DiffEntry> diffEntries = diffRevisions(parent, revc);

  Commit commit = new Commit(revc);

  for (DiffEntry entry : diffEntries) {
    DiffLines changedLines = diffFile(entry);

    commit.diffWithParent.put(entry.getNewPath(), changedLines);
    commit.changeTypes.put(entry.getNewPath(), entry.getChangeType());
  }
  return commit;
}
 
Example #11
Source File: GitRepoMetaData.java    From GitFx with Apache License 2.0 6 votes vote down vote up
public String getDiffBetweenCommits(int commitIndex) throws IOException,GitAPIException{
    if(commitIndex+1==commitCount)
        return "Nothing to Diff. This is first commit";
    AbstractTreeIterator current = prepareTreeParser(repository,commitSHA.get(commitIndex));
    AbstractTreeIterator parent = prepareTreeParser(repository,commitSHA.get(++commitIndex));
    ObjectReader reader = repository.newObjectReader();
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    // finally get the list of changed files
    Git git = new Git(repository) ;
    List<DiffEntry> diff = git.diff().
            setOldTree(parent).
            setNewTree(current).
            //TODO Set the path filter to filter out the selected file
            //setPathFilter(PathFilter.create("README.md")).
            call();
    for (DiffEntry entry : diff) {
        System.out.println("Entry: " + entry + ", from: " + entry.getOldId() + ", to: " + entry.getNewId());
        DiffFormatter formatter = new DiffFormatter(byteStream) ;
            formatter.setRepository(repository);
            formatter.format(entry);
        }
   // System.out.println(byteStream.toString());
    String diffContent = byteStream.toString();
    return byteStream.toString();
}
 
Example #12
Source File: GitFlowGraphMonitor.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Add a {@link FlowEdge} to the {@link FlowGraph}. The method uses the {@link FlowEdgeFactory} instance
 * provided by the {@link FlowGraph} to build a {@link FlowEdge} from the edge config file.
 * @param change
 */
private void addFlowEdge(DiffEntry change) {
  if (checkFilePath(change.getNewPath(), EDGE_FILE_DEPTH)) {
    Path edgeFilePath = new Path(this.repositoryDir, change.getNewPath());
    try {
      Config edgeConfig = loadEdgeFileWithOverrides(edgeFilePath);
      List<SpecExecutor> specExecutors = getSpecExecutors(edgeConfig);
      Class flowEdgeFactoryClass = Class.forName(ConfigUtils.getString(edgeConfig, FlowGraphConfigurationKeys.FLOW_EDGE_FACTORY_CLASS,
          FlowGraphConfigurationKeys.DEFAULT_FLOW_EDGE_FACTORY_CLASS));
      FlowEdgeFactory flowEdgeFactory = (FlowEdgeFactory) GobblinConstructorUtils.invokeLongestConstructor(flowEdgeFactoryClass, edgeConfig);
      if (flowTemplateCatalog.isPresent()) {
        FlowEdge edge = flowEdgeFactory.createFlowEdge(edgeConfig, flowTemplateCatalog.get(), specExecutors);
        if (!this.flowGraph.addFlowEdge(edge)) {
          log.warn("Could not add edge {} to FlowGraph; skipping", edge.getId());
        } else {
          log.info("Added edge {} to FlowGraph", edge.getId());
        }
      } else {
        log.warn("Could not add edge defined in {} to FlowGraph as FlowTemplateCatalog is absent", change.getNewPath());
      }
    } catch (Exception e) {
      log.warn("Could not add edge defined in {} due to exception {}", change.getNewPath(), e.getMessage());
    }
  }
}
 
Example #13
Source File: PGA.java    From coming with MIT License 6 votes vote down vote up
private DiffEntry diffFile(Repository repo, String oldCommit, String newCommit, String path) throws IOException, GitAPIException {
//        Config config = new Config();
//        config.setBoolean("diff", null, "renames", true);
//        DiffConfig diffConfig = config.get(DiffConfig.KEY);
        Git git = new Git(repo);
        List<DiffEntry> diffList = git.diff().
                setOldTree(prepareTreeParser(repo, oldCommit)).
                setNewTree(prepareTreeParser(repo, newCommit)).
//                setPathFilter(FollowFilter.create(path, diffConfig)).
        call();
        if (diffList.size() == 0)
            return null;
        if (diffList.size() > 1)
            throw new RuntimeException("invalid diff");
        return diffList.get(0);
    }
 
Example #14
Source File: GitParser.java    From SZZUnleashed with MIT License 6 votes vote down vote up
/**
 * With each revision, check all files and build their line mapping graphs for each changed line.
 *
 * @param commits list of commits that should be traced.
 * @return the map containing annotation graphs for each file change by a commit.
 */
private AnnotationMap<String, List<FileAnnotationGraph>> buildLineMappingGraph(
    List<Commit> commits) throws IOException, GitAPIException {

  AnnotationMap<String, List<FileAnnotationGraph>> fileGraph = new AnnotationMap<>();
  for (Commit commit : commits) {
    List<FileAnnotationGraph> graphs = new LinkedList<>();
    for (Map.Entry<String, DiffEntry.ChangeType> file : commit.changeTypes.entrySet()) {
      FileAnnotationGraph tracedCommits = traceFileChanges(file.getKey(), commit, this.depth);

      graphs.add(tracedCommits);
    }

    fileGraph.put(commit.getHashString(), graphs);
  }

  return fileGraph;
}
 
Example #15
Source File: Commit.java    From SZZUnleashed with MIT License 6 votes vote down vote up
/**
 * Helper method to convert a Commit object to a JSON object.
 *
 * @return a JSONObject containing the commit. Omits the RevCommit.
 */
public JSONObject toJson() {
  JSONObject tree = new JSONObject();

  JSONObject diffing = new JSONObject();
  for (Map.Entry<String, DiffLines> diff : diffWithParent.entrySet()) {
    String file = diff.getKey();

    JSONArray lines = new JSONArray();
    DiffLines line = diff.getValue();

    lines.add(line.getJSON());

    diffing.put(file, lines);
  }
  tree.put("diff", diffing);

  JSONObject changes = new JSONObject();
  for (Map.Entry<String, DiffEntry.ChangeType> changeType : changeTypes.entrySet()) {
    changes.put(changeType.getKey(), changeType.getValue().toString());
  }

  tree.put("changes", changes);

  return tree;
}
 
Example #16
Source File: UIGit.java    From hop with Apache License 2.0 6 votes vote down vote up
@Override
public List<UIFile> getStagedFiles( String oldCommitId, String newCommitId ) {
  List<UIFile> files = new ArrayList<UIFile>();
  try {
    List<DiffEntry> diffs = getDiffCommand( oldCommitId, newCommitId )
      .setShowNameAndStatusOnly( true )
      .call();
    RenameDetector rd = new RenameDetector( git.getRepository() );
    rd.addAll( diffs );
    diffs = rd.compute();
    diffs.forEach( diff -> {
      files.add( new UIFile( diff.getChangeType() == ChangeType.DELETE ? diff.getOldPath() : diff.getNewPath(),
        diff.getChangeType(), false ) );
    } );
  } catch ( Exception e ) {
    e.printStackTrace();
  }
  return files;
}
 
Example #17
Source File: HopGitPerspective.java    From hop with Apache License 2.0 6 votes vote down vote up
@GuiToolbarElement(
  root = GUI_PLUGIN_FILES_TOOLBAR_PARENT_ID,
  id = FILES_TOOLBAR_ITEM_FILES_STAGE,
  label = "Stage",
  toolTip = "Stage the selected changed files (add to index)"
)
public void stage() {
  List<UIFile> contents = getSelectedChangedFiles();
  for ( UIFile content : contents ) {
    if ( content.getChangeType() == DiffEntry.ChangeType.DELETE ) {
      vcs.rm( content.getName() );
    } else {
      vcs.add( content.getName() );
    }
  }
  refresh();
}
 
Example #18
Source File: GitHistoryParser.java    From proctor with Apache License 2.0 6 votes vote down vote up
private Set<String> getModifiedTests(final RevCommit commit) throws IOException {
    final RevCommit[] parents = commit.getParents();
    final Set<String> result = new HashSet<>();
    if (parents.length == 1) { // merge commit if length > 1
        final RevCommit parent = revWalk.parseCommit(parents[0].getId());
        // get diff of this commit to its parent, as list of paths
        final List<DiffEntry> diffs = getDiffEntries(commit, parent);
        for (final DiffEntry diff : diffs) {
            final String changePath = diff.getChangeType().equals(DiffEntry.ChangeType.DELETE) ? diff.getOldPath() : diff.getNewPath();
            final Matcher testNameMatcher = testNamePattern.matcher(changePath);

            if (testNameMatcher.matches()) {
                final String testName = testNameMatcher.group(1);
                result.add(testName);
            }
        }
    }
    return result;
}
 
Example #19
Source File: SMAGit.java    From salesforce-migration-assistant with MIT License 6 votes vote down vote up
/**
 * Returns all of the updated changes in the current commit.
 *
 * @return The ArrayList containing the items that were modified (new paths) and added to the repository.
 * @throws IOException
 */
public Map<String, byte[]> getUpdatedMetadata() throws Exception
{
    Map<String, byte[]> modifiedMetadata = new HashMap<String, byte[]>();

    for (DiffEntry diff : diffs)
    {
        if (diff.getChangeType().toString().equals("MODIFY"))
        {
            String item = SMAUtility.checkMeta(diff.getNewPath());
            if (!modifiedMetadata.containsKey(item) && item.contains(SOURCEDIR))
            {
                modifiedMetadata.put(diff.getNewPath(), getBlob(diff.getNewPath(), curCommit));
            }
        }
    }
    return modifiedMetadata;
}
 
Example #20
Source File: SMAGit.java    From salesforce-migration-assistant with MIT License 6 votes vote down vote up
/**
 * Returns all of the items that were deleted in the current commit.
 *
 * @return The ArrayList containing all of the items that were deleted in the current commit.
 */
public Map<String, byte[]> getDeletedMetadata() throws Exception
{
    Map<String, byte[]> deletions = new HashMap<String, byte[]>();

    for (DiffEntry diff : diffs)
    {
        if (diff.getChangeType().toString().equals("DELETE"))
        {
            String item = SMAUtility.checkMeta(diff.getOldPath());
            if (!deletions.containsKey(item) && item.contains(SOURCEDIR))
            {
                deletions.put(diff.getOldPath(), getBlob(diff.getOldPath(), prevCommit));
            }
        }
    }

    return deletions;
}
 
Example #21
Source File: AppraiseReviewsTaskDataHandler.java    From git-appraise-eclipse with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Fills the diffs into the given task data.
 */
private void populateDiffs(TaskRepository repository, List<DiffEntry> diffs, TaskData taskData) {
  int diffCount = 1;
  for (DiffEntry diffEntry : diffs) {
    TaskAttribute diffAttribute =
        taskData.getRoot().createAttribute(AppraiseReviewTaskSchema.PREFIX_DIFF + diffCount);
    diffAttribute.getMetaData().setType(AppraiseReviewTaskSchema.TYPE_DIFF);

    TaskAttribute diffNewPathAttribute =
        diffAttribute.createAttribute(AppraiseReviewTaskSchema.DIFF_NEWPATH);
    setAttributeValue(diffNewPathAttribute, diffEntry.getNewPath());

    TaskAttribute diffOldPathAttribute =
        diffAttribute.createAttribute(AppraiseReviewTaskSchema.DIFF_OLDPATH);
    setAttributeValue(diffOldPathAttribute, diffEntry.getNewPath());

    TaskAttribute diffTypeAttribute =
        diffAttribute.createAttribute(AppraiseReviewTaskSchema.DIFF_TYPE);
    setAttributeValue(diffTypeAttribute, diffEntry.getChangeType().name());

    TaskAttribute diffTextAttribute =
        diffAttribute.createAttribute(AppraiseReviewTaskSchema.DIFF_TEXT);
    ByteArrayOutputStream diffOutputStream = new ByteArrayOutputStream();
    try (DiffFormatter formatter = new DiffFormatter(diffOutputStream)) {
      formatter.setRepository(AppraisePluginUtils.getGitRepoForRepository(repository));
      try {
        formatter.format(diffEntry);
        String diffText = new String(diffOutputStream.toByteArray(), "UTF-8");
        setAttributeValue(diffTextAttribute, diffText);
      } catch (IOException e) {
        AppraiseConnectorPlugin.logWarning(
            "Failed to load a diff for " + taskData.getTaskId(), e);
      }
    }
    diffCount++;
  }
}
 
Example #22
Source File: GitChangeResolver.java    From smart-testing with Apache License 2.0 5 votes vote down vote up
private Set<Change> transformToChangeSet(List<DiffEntry> diffs, File repoRoot) {
    return diffs.stream()
        .map(diffEntry -> {
            final Path classLocation = Paths.get(repoRoot.getAbsolutePath(), diffEntry.getNewPath());
            final ChangeType changeType = ChangeType.valueOf(diffEntry.getChangeType().name());

            return new Change(classLocation, changeType);
        })
        .collect(Collectors.toSet());
}
 
Example #23
Source File: CommitTreeInfo.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
public CommitTreeInfo(String path, String name, long size, int mode, String id, String commitId, DiffEntry.ChangeType changeType) {
    this.path = path;
    this.name = name;
    this.size = size;
    this.mode = mode;
    this.id = id;
    this.commitId = commitId;
    this.changeType = changeType;
}
 
Example #24
Source File: GitHistoryParser.java    From proctor with Apache License 2.0 5 votes vote down vote up
private List<DiffEntry> getDiffEntries(final RevCommit commit, final RevCommit parent) throws IOException {
    try {
        return DIFF_ENTRIES_CACHE.get(commit.getName(), () -> diffFormatter.scan(parent.getTree(), commit.getTree()));
    } catch (final ExecutionException e) {
        Throwables.propagateIfInstanceOf(e.getCause(), IOException.class);
        throw Throwables.propagate(e.getCause());
    }
}
 
Example #25
Source File: DiffHelper.java    From diff-check with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static DiffEntry createAddDiffEntry(String path, AnyObjectId id) {
    try {
        return (DiffEntry) DIFF_ENTRY_ADD_METHOD.invoke(null, path, id);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #26
Source File: GitDiffHandlerV1.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
private URI createContentLocation(URI cloneLocation, final DiffEntry entr, String path) throws URISyntaxException {
	// remove /gitapi/clone from the start of path
	IPath clonePath = new Path(cloneLocation.getPath()).removeFirstSegments(2);
	IPath result;
	if (path == null) {
		result = clonePath;
	} else {
		// need to start from the project root
		// project path is of the form /file/{workspaceId}/{projectName}
		result = clonePath.uptoSegment(3).append(path);
	}
	return new URI(cloneLocation.getScheme(), cloneLocation.getUserInfo(), cloneLocation.getHost(), cloneLocation.getPort(), result.makeAbsolute()
			.toString(), cloneLocation.getQuery(), cloneLocation.getFragment());
}
 
Example #27
Source File: GitRepository.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
private void notifyWatchers(Revision newRevision, List<DiffEntry> diffEntries) {
    for (DiffEntry entry : diffEntries) {
        switch (entry.getChangeType()) {
            case ADD:
                commitWatchers.notify(newRevision, entry.getNewPath());
                break;
            case MODIFY:
            case DELETE:
                commitWatchers.notify(newRevision, entry.getOldPath());
                break;
            default:
                throw new Error();
        }
    }
}
 
Example #28
Source File: GitRepository.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
private List<DiffEntry> blockingCompareTreesUncached(@Nullable RevTree treeA,
                                                     @Nullable RevTree treeB,
                                                     TreeFilter filter) {
    readLock();
    try (DiffFormatter diffFormatter = new DiffFormatter(null)) {
        diffFormatter.setRepository(jGitRepository);
        diffFormatter.setPathFilter(filter);
        return ImmutableList.copyOf(diffFormatter.scan(treeA, treeB));
    } catch (IOException e) {
        throw new StorageException("failed to compare two trees: " + treeA + " vs. " + treeB, e);
    } finally {
        readUnlock();
    }
}
 
Example #29
Source File: JGitOperator.java    From verigreen with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isThereAnyDifs() {
    
    boolean ans = false;
    try {
        List<DiffEntry> list = _git.diff().call();
        if (list.size() > 0) {
            ans = true;
        }
    } catch (GitAPIException e) {
        throw new RuntimeException("Failed to get diffs", e);
    }
    
    return ans;
}
 
Example #30
Source File: JGitHelper.java    From go-plugins with Apache License 2.0 5 votes vote down vote up
private Revision getRevisionObj(Repository repository, RevCommit commit) throws IOException {
    String commitSHA = commit.getName();
    Date commitTime = commit.getAuthorIdent().getWhen();
    String comment = commit.getFullMessage().trim();
    String user = commit.getAuthorIdent().getName();
    String emailId = commit.getAuthorIdent().getEmailAddress();
    List<ModifiedFile> modifiedFiles = new ArrayList<ModifiedFile>();
    if (commit.getParentCount() == 0) {
        TreeWalk treeWalk = new TreeWalk(repository);
        treeWalk.addTree(commit.getTree());
        treeWalk.setRecursive(false);
        while (treeWalk.next()) {
            modifiedFiles.add(new ModifiedFile(treeWalk.getPathString(), "added"));
        }
    } else {
        RevWalk rw = new RevWalk(repository);
        RevCommit parent = rw.parseCommit(commit.getParent(0).getId());
        DiffFormatter diffFormatter = new DiffFormatter(DisabledOutputStream.INSTANCE);
        diffFormatter.setRepository(repository);
        diffFormatter.setDiffComparator(RawTextComparator.DEFAULT);
        diffFormatter.setDetectRenames(true);
        List<DiffEntry> diffEntries = diffFormatter.scan(parent.getTree(), commit.getTree());
        for (DiffEntry diffEntry : diffEntries) {
            modifiedFiles.add(new ModifiedFile(diffEntry.getNewPath(), getAction(diffEntry.getChangeType().name())));
        }
    }

    return new Revision(commitSHA, commitTime, comment, user, emailId, modifiedFiles);
}