org.eclipse.jgit.lib.ObjectInserter Java Examples

The following examples show how to use org.eclipse.jgit.lib.ObjectInserter. 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: SubtreeMerger.java    From git-merge-repos with Apache License 2.0 6 votes vote down vote up
public ObjectId createMergeCommit(Map<SubtreeConfig, RevCommit> parentCommits, String message)
		throws IOException {
	PersonIdent latestIdent = getLatestPersonIdent(parentCommits.values());
	DirCache treeDirCache = createTreeDirCache(parentCommits, message);
	List<? extends ObjectId> parentIds = new ArrayList<>(parentCommits.values());
	try (ObjectInserter inserter = repository.newObjectInserter()) {
		ObjectId treeId = treeDirCache.writeTree(inserter);

		PersonIdent repositoryUser = new PersonIdent(repository);
		PersonIdent ident = new PersonIdent(repositoryUser, latestIdent.getWhen().getTime(),
				latestIdent.getTimeZoneOffset());
		CommitBuilder commitBuilder = new CommitBuilder();
		commitBuilder.setTreeId(treeId);
		commitBuilder.setAuthor(ident);
		commitBuilder.setCommitter(ident);
		commitBuilder.setMessage(message);
		commitBuilder.setParentIds(parentIds);
		ObjectId mergeCommit = inserter.insert(commitBuilder);
		inserter.flush();
		return mergeCommit;
	}
}
 
Example #2
Source File: GitTreeUpdate.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
@NotNull ObjectId buildTree(@NotNull ObjectInserter inserter) throws IOException {
  final TreeFormatter treeBuilder = new TreeFormatter();
  final List<GitTreeEntry> sortedEntries = new ArrayList<>(entries.values());
  Collections.sort(sortedEntries);
  for (GitTreeEntry entry : sortedEntries) {
    treeBuilder.append(entry.getFileName(), entry.getFileMode(), entry.getObjectId().getObject());
  }
  new ObjectChecker().checkTree(treeBuilder.toByteArray());
  return inserter.insert(treeBuilder);
}
 
Example #3
Source File: ObjectSnapshot.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Nonnull
public ObjectId save(Repository repo) throws IOException {
  try(ObjectInserter inserter = repo.newObjectInserter()) {
    ObjectId ret = save(inserter);
    inserter.flush();
    return ret;
  }
}
 
Example #4
Source File: AppraiseGitReviewClient.java    From git-appraise-eclipse with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a merged notes commit.
 */
private RevCommit createNotesCommit(NoteMap map, ObjectInserter inserter, RevWalk revWalk,
    String message, RevCommit... parents) throws IOException {
  CommitBuilder commitBuilder = new CommitBuilder();
  commitBuilder.setTreeId(map.writeTree(inserter));
  commitBuilder.setAuthor(author);
  commitBuilder.setCommitter(author);
  if (parents.length > 0) {
    commitBuilder.setParentIds(parents);
  }
  commitBuilder.setMessage(message);
  ObjectId commitId = inserter.insert(commitBuilder);
  inserter.flush();
  return revWalk.parseCommit(commitId);
}
 
Example #5
Source File: ObjectSnapshot.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Nonnull
public ObjectId save(Repository repo) throws IOException {
  try(ObjectInserter inserter = repo.newObjectInserter()) {
    ObjectId ret = save(inserter);
    inserter.flush();
    return ret;
  }
}
 
Example #6
Source File: CheckoutRevisionCommand.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void cacheContents (List<String> conflicts) throws IOException {
    File workTree = getRepository().getWorkTree();
    WorkingTreeOptions opt = getRepository().getConfig().get(WorkingTreeOptions.KEY);
    boolean autocrlf = opt.getAutoCRLF() != CoreConfig.AutoCRLF.FALSE;
    try (ObjectInserter inserter = getRepository().newObjectInserter();) {
        for (String path : conflicts) {
            File f = new File(workTree, path);
            Path p = null;
            try {
                p = f.toPath();
            } catch (InvalidPathException ex) {
                Logger.getLogger(CheckoutRevisionCommand.class.getName()).log(Level.FINE, null, ex);
            }
            if (p != null && Files.isSymbolicLink(p)) {
                Path link = Utils.getLinkPath(p);                                
                cachedContents.put(path, inserter.insert(Constants.OBJ_BLOB, Constants.encode(link.toString())));
            } else if (f.isFile()) {
                long sz = f.length();
                try (FileInputStream in = new FileInputStream(f)) {
                    if (autocrlf) {
                        ByteBuffer buf = IO.readWholeStream(in, (int) sz);
                        cachedContents.put(path, inserter.insert(Constants.OBJ_BLOB, buf.array(), buf.position(), buf.limit() - buf.position()));
                    } else {
                        cachedContents.put(path, inserter.insert(Constants.OBJ_BLOB, sz, in));
                    }
                }
            }
        }
        inserter.flush();
    }
}
 
Example #7
Source File: GitUtils.java    From onedev with MIT License 5 votes vote down vote up
@Nullable
  public static ObjectId merge(Repository repository, ObjectId targetCommitId, ObjectId sourceCommitId, 
  		boolean squash, PersonIdent committer, PersonIdent author, String commitMessage, 
  		boolean useOursOnConflict) {
  	boolean prevUseOursOnConflict = UseOursOnConflict.get();
  	UseOursOnConflict.set(useOursOnConflict);
  	try (	RevWalk revWalk = new RevWalk(repository);
  			ObjectInserter inserter = repository.newObjectInserter();) {
  		RevCommit sourceCommit = revWalk.parseCommit(sourceCommitId);
  		RevCommit targetCommit = revWalk.parseCommit(targetCommitId);
  		Merger merger = MergeStrategy.RECURSIVE.newMerger(repository, true);
  		if (merger.merge(targetCommit, sourceCommit)) {
        CommitBuilder mergedCommit = new CommitBuilder();
        mergedCommit.setAuthor(author);
        mergedCommit.setCommitter(committer);
        if (squash)
        	mergedCommit.setParentId(targetCommit);
        else
        	mergedCommit.setParentIds(targetCommit, sourceCommit);
        mergedCommit.setMessage(commitMessage);
        mergedCommit.setTreeId(merger.getResultTreeId());
        ObjectId mergedCommitId = inserter.insert(mergedCommit);
        inserter.flush();
        return mergedCommitId;
  		} else {
  			return null;
  		}
  	} catch (IOException e) {
  		throw new RuntimeException(e);
} finally {
	UseOursOnConflict.set(prevUseOursOnConflict);
}
  }
 
Example #8
Source File: GitUtils.java    From onedev with MIT License 5 votes vote down vote up
@Nullable
  public static ObjectId rebase(Repository repository, ObjectId source, ObjectId target, PersonIdent committer) {
  	try (	RevWalk revWalk = new RevWalk(repository);
  			ObjectInserter inserter = repository.newObjectInserter();) {
  		RevCommit sourceCommit = revWalk.parseCommit(source);
  		RevCommit targetCommit = revWalk.parseCommit(target);
  		revWalk.setRevFilter(RevFilter.NO_MERGES);
  		List<RevCommit> commits = RevWalkUtils.find(revWalk, sourceCommit, targetCommit);
  		Collections.reverse(commits);
  		RevCommit headCommit = targetCommit;
  		for (RevCommit commit: commits) {
      		ResolveMerger merger = (ResolveMerger) MergeStrategy.RECURSIVE.newMerger(repository, true);
      		merger.setBase(commit.getParent(0));
      		if (merger.merge(headCommit, commit)) {
			if (!headCommit.getTree().getId().equals(merger.getResultTreeId())) {
				if (!commit.getTree().getId().equals(merger.getResultTreeId()) 
						|| !commit.getParent(0).equals(headCommit)) {
			        CommitBuilder commitBuilder = new CommitBuilder();
			        commitBuilder.setAuthor(commit.getAuthorIdent());
			        commitBuilder.setCommitter(committer);
			        commitBuilder.setParentId(headCommit);
			        commitBuilder.setMessage(commit.getFullMessage());
			        commitBuilder.setTreeId(merger.getResultTreeId());
			        headCommit = revWalk.parseCommit(inserter.insert(commitBuilder));
				} else {
					headCommit = commit;
				}
			}
      		} else {
      			return null;
      		}
  		}
  		inserter.flush();
  		return headCommit.copy();
  	} catch (IOException e) {
  		throw new RuntimeException(e);
}
  }
 
Example #9
Source File: StrategyRecursive.java    From onedev with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public ThreeWayMerger newMerger(ObjectInserter inserter, Config config) {
	return new RecursiveMerger(inserter, config);
}
 
Example #10
Source File: ObjectSnapshot.java    From ParallelGit with Apache License 2.0 4 votes vote down vote up
@Nonnull
public abstract ObjectId save(ObjectInserter inserter) throws IOException;
 
Example #11
Source File: ObjectSnapshot.java    From ParallelGit with Apache License 2.0 4 votes vote down vote up
@Nonnull
public abstract ObjectId save(ObjectInserter inserter) throws IOException;
 
Example #12
Source File: GitIndexEntry.java    From git-code-format-maven-plugin with MIT License 4 votes vote down vote up
private void doFormat(DirCacheEntry dirCacheEntry, CodeFormatter formatter) {
  LineRanges lineRanges = computeLineRanges(dirCacheEntry);
  if (lineRanges.isAll()) {
    log.info("Formatting '" + dirCacheEntry.getPathString() + "'");
  } else {
    log.info("Formatting lines " + lineRanges + " of '" + dirCacheEntry.getPathString() + "'");
  }

  try (TemporaryFile temporaryFormattedFile =
      TemporaryFile.create(log, dirCacheEntry.getPathString() + ".formatted")) {
    ObjectId unformattedObjectId = dirCacheEntry.getObjectId();
    log.debug("Unformatted object id is '" + unformattedObjectId + "'");
    ObjectDatabase objectDatabase = repository.getObjectDatabase();
    ObjectLoader objectLoader = objectDatabase.open(unformattedObjectId);

    logObjectContent(objectLoader, dirCacheEntry.getPathString() + ".unformatted");

    try (InputStream content = objectLoader.openStream();
        OutputStream formattedContent = temporaryFormattedFile.newOutputStream()) {
      formatter.format(content, lineRanges, formattedContent);
    }

    long formattedSize = temporaryFormattedFile.size();
    ObjectId formattedObjectId;
    try (InputStream formattedContent = temporaryFormattedFile.newInputStream();
        ObjectInserter objectInserter = objectDatabase.newInserter()) {
      formattedObjectId = objectInserter.insert(OBJ_BLOB, formattedSize, formattedContent);
      objectInserter.flush();
    }

    log.debug("Formatted size is " + formattedSize);
    dirCacheEntry.setLength(formattedSize);
    log.debug("Formatted object id is '" + formattedObjectId + "'");
    dirCacheEntry.setObjectId(formattedObjectId);
  } catch (IOException e) {
    throw new MavenGitCodeFormatException(e);
  }

  if (lineRanges.isAll()) {
    log.info("Formatted '" + dirCacheEntry.getPathString() + "'");
  } else {
    log.info("Formatted lines " + lineRanges + " of '" + dirCacheEntry.getPathString() + "'");
  }
}
 
Example #13
Source File: GitRepository.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
InsertJson(String entryPath, ObjectInserter inserter, JsonNode jsonNode) {
    super(entryPath);
    this.inserter = inserter;
    this.jsonNode = jsonNode;
}
 
Example #14
Source File: GitRepository.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
InsertText(String entryPath, ObjectInserter inserter, String text) {
    super(entryPath);
    this.inserter = inserter;
    this.text = text;
}
 
Example #15
Source File: AddTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testAddMixedLineEndings () throws Exception {
    File f = new File(workDir, "f");
    String content = "";
    for (int i = 0; i < 10000; ++i) {
        content += i + "\r\n";
    }
    write(f, content);
    File[] files = new File[] { f };
    GitClient client = getClient(workDir);
    client.add(files, NULL_PROGRESS_MONITOR);
    client.commit(files, "commit", null, null, NULL_PROGRESS_MONITOR);
    
    Map<File, GitStatus> statuses = client.getStatus(files, NULL_PROGRESS_MONITOR);
    assertEquals(1, statuses.size());
    assertStatus(statuses, workDir, f, true, Status.STATUS_NORMAL, Status.STATUS_NORMAL, Status.STATUS_NORMAL, false);
    
    // lets turn autocrlf on
    StoredConfig cfg = repository.getConfig();
    cfg.setString(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOCRLF, "true");
    cfg.save();
    
    // when this starts failing, remove the work around
    ObjectInserter inserter = repository.newObjectInserter();
    TreeWalk treeWalk = new TreeWalk(repository);
    treeWalk.setFilter(PathFilterGroup.createFromStrings("f"));
    treeWalk.setRecursive(true);
    treeWalk.reset();
    treeWalk.addTree(new FileTreeIterator(repository));
    while (treeWalk.next()) {
        String path = treeWalk.getPathString();
        assertEquals("f", path);
        WorkingTreeIterator fit = treeWalk.getTree(0, WorkingTreeIterator.class);
        try (InputStream in = fit.openEntryStream()) {
            inserter.insert(Constants.OBJ_BLOB, fit.getEntryLength(), in);
            fail("this should fail, remove the work around");
        } catch (EOFException ex) {
            assertEquals("Input did not match supplied length. 10.000 bytes are missing.", ex.getMessage());
        } finally {
            inserter.close();
        }
        break;
    }
    
    // no err should occur
    write(f, content + "hello");
    statuses = client.getStatus(files, NULL_PROGRESS_MONITOR);
    assertEquals(1, statuses.size());
    assertStatus(statuses, workDir, f, true, Status.STATUS_NORMAL, Status.STATUS_MODIFIED, Status.STATUS_MODIFIED, false);
    client.add(files, NULL_PROGRESS_MONITOR);
    statuses = client.getStatus(files, NULL_PROGRESS_MONITOR);
    assertEquals(1, statuses.size());
    assertStatus(statuses, workDir, f, true, Status.STATUS_MODIFIED, Status.STATUS_NORMAL, Status.STATUS_MODIFIED, false);
    client.commit(files, "message", null, null, NULL_PROGRESS_MONITOR);
    statuses = client.getStatus(files, NULL_PROGRESS_MONITOR);
    assertEquals(1, statuses.size());
    assertStatus(statuses, workDir, f, true, Status.STATUS_NORMAL, Status.STATUS_NORMAL, Status.STATUS_NORMAL, false);
}
 
Example #16
Source File: StrategyOneSided.java    From onedev with MIT License 4 votes vote down vote up
protected OneSide(ObjectInserter inserter, int index) {
	super(inserter);
	treeIndex = index;
}
 
Example #17
Source File: StrategyOneSided.java    From onedev with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public Merger newMerger(ObjectInserter inserter, Config config) {
	return new OneSide(inserter, treeIndex);
}
 
Example #18
Source File: StrategySimpleTwoWayInCore.java    From onedev with MIT License 4 votes vote down vote up
@Override
protected boolean mergeImpl() throws IOException {
	tw.addTree(mergeBase());
	tw.addTree(sourceTrees[0]);
	tw.addTree(sourceTrees[1]);

	boolean hasConflict = false;
	builder = cache.builder();
	while (tw.next()) {
		final int modeO = tw.getRawMode(T_OURS);
		final int modeT = tw.getRawMode(T_THEIRS);
		if (modeO == modeT && tw.idEqual(T_OURS, T_THEIRS)) {
			add(T_OURS, DirCacheEntry.STAGE_0);
			continue;
		}

		final int modeB = tw.getRawMode(T_BASE);
		if (modeB == modeO && tw.idEqual(T_BASE, T_OURS))
			add(T_THEIRS, DirCacheEntry.STAGE_0);
		else if (modeB == modeT && tw.idEqual(T_BASE, T_THEIRS))
			add(T_OURS, DirCacheEntry.STAGE_0);
		else {
			if (nonTree(modeB)) {
				add(T_BASE, DirCacheEntry.STAGE_1);
				hasConflict = true;
			}
			if (nonTree(modeO)) {
				add(T_OURS, DirCacheEntry.STAGE_2);
				hasConflict = true;
			}
			if (nonTree(modeT)) {
				add(T_THEIRS, DirCacheEntry.STAGE_3);
				hasConflict = true;
			}
			if (tw.isSubtree())
				tw.enterSubtree();
		}
	}
	builder.finish();
	builder = null;

	if (hasConflict)
		return false;
	try {
		ObjectInserter odi = getObjectInserter();
		resultTree = cache.writeTree(odi);
		odi.flush();
		return true;
	} catch (UnmergedPathException upe) {
		resultTree = null;
		return false;
	}
}
 
Example #19
Source File: StrategySimpleTwoWayInCore.java    From onedev with MIT License 4 votes vote down vote up
InCoreMerger(ObjectInserter inserter) {
	super(inserter);
	tw = new NameConflictTreeWalk(null, reader);
	cache = DirCache.newInCore();
}
 
Example #20
Source File: StrategySimpleTwoWayInCore.java    From onedev with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public ThreeWayMerger newMerger(ObjectInserter inserter, Config config) {
	return new InCoreMerger(inserter);
}
 
Example #21
Source File: StrategyResolve.java    From onedev with MIT License 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public ThreeWayMerger newMerger(ObjectInserter inserter, Config config) {
	return new ResolveMerger(inserter, config);
}
 
Example #22
Source File: RevTag.java    From onedev with MIT License 3 votes vote down vote up
/**
 * Parse an annotated tag from its canonical format.
 * <p>
 * This method inserts the tag directly into the caller supplied revision
 * pool, making it appear as though the tag exists in the repository, even
 * if it doesn't. The repository under the pool is not affected.
 * <p>
 * The body of the tag (message, tagger, signature) is always retained in
 * the returned {@code RevTag}, even if the supplied {@code RevWalk} has
 * been configured with {@code setRetainBody(false)}.
 *
 * @param rw
 *            the revision pool to allocate the tag within. The tag's object
 *            pointer will be obtained from this pool.
 * @param raw
 *            the canonical formatted tag to be parsed. This buffer will be
 *            retained by the returned {@code RevTag} and must not be
 *            modified by the caller.
 * @return the parsed tag, in an isolated revision pool that is not
 *         available to the caller.
 * @throws org.eclipse.jgit.errors.CorruptObjectException
 *             the tag contains a malformed header that cannot be handled.
 */
public static RevTag parse(RevWalk rw, byte[] raw)
		throws CorruptObjectException {
	try (ObjectInserter.Formatter fmt = new ObjectInserter.Formatter()) {
		RevTag r = rw.lookupTag(fmt.idFor(Constants.OBJ_TAG, raw));
		r.parseCanonical(rw, raw);
		r.buffer = raw;
		return r;
	}
}
 
Example #23
Source File: Merger.java    From onedev with MIT License 3 votes vote down vote up
/**
 * Create a new in-core merge instance from an inserter.
 *
 * @param oi
 *            the inserter to write objects to. Will be closed at the
 *            conclusion of {@code merge}, unless {@code flush} is false.
 * @since 4.8
 */
protected Merger(ObjectInserter oi) {
	db = null;
	inserter = oi;
	reader = oi.newReader();
	walk = new RevWalk(reader);
}
 
Example #24
Source File: ResolveMerger.java    From onedev with MIT License 3 votes vote down vote up
/**
 * Constructor for ResolveMerger.
 *
 * @param inserter
 *            an {@link org.eclipse.jgit.lib.ObjectInserter} object.
 * @param config
 *            the repository configuration
 * @since 4.8
 */
protected ResolveMerger(ObjectInserter inserter, Config config) {
	super(inserter);
	mergeAlgorithm = getMergeAlgorithm(config);
	commitNames = defaultCommitNames();
	inCore = true;
	implicitDirCache = false;
	dircache = DirCache.newInCore();
}
 
Example #25
Source File: RevCommit.java    From onedev with MIT License 3 votes vote down vote up
/**
 * Parse a commit from its canonical format.
 * <p>
 * This method inserts the commit directly into the caller supplied revision
 * pool, making it appear as though the commit exists in the repository,
 * even if it doesn't. The repository under the pool is not affected.
 * <p>
 * The body of the commit (message, author, committer) is always retained in
 * the returned {@code RevCommit}, even if the supplied {@code RevWalk} has
 * been configured with {@code setRetainBody(false)}.
 *
 * @param rw
 *            the revision pool to allocate the commit within. The commit's
 *            tree and parent pointers will be obtained from this pool.
 * @param raw
 *            the canonical formatted commit to be parsed. This buffer will
 *            be retained by the returned {@code RevCommit} and must not be
 *            modified by the caller.
 * @return the parsed commit, in an isolated revision pool that is not
 *         available to the caller.
 * @throws java.io.IOException
 *             in case of RevWalk initialization fails
 */
public static RevCommit parse(RevWalk rw, byte[] raw) throws IOException {
	try (ObjectInserter.Formatter fmt = new ObjectInserter.Formatter()) {
		RevCommit r = rw.lookupCommit(fmt.idFor(Constants.OBJ_COMMIT, raw));
		r.parseCanonical(rw, raw);
		r.buffer = raw;
		return r;
	}
}
 
Example #26
Source File: ThreeWayMerger.java    From onedev with MIT License 2 votes vote down vote up
/**
 * Create a new in-core merge instance from an inserter.
 *
 * @param inserter
 *            the inserter to write objects to.
 * @since 4.8
 */
protected ThreeWayMerger(ObjectInserter inserter) {
	super(inserter);
}
 
Example #27
Source File: RecursiveMerger.java    From onedev with MIT License 2 votes vote down vote up
/**
 * Normal recursive merge, implies inCore.
 *
 * @param inserter
 *            an {@link org.eclipse.jgit.lib.ObjectInserter} object.
 * @param config
 *            the repository configuration
 * @since 4.8
 */
protected RecursiveMerger(ObjectInserter inserter, Config config) {
	super(inserter, config);
}
 
Example #28
Source File: MergeStrategy.java    From onedev with MIT License 2 votes vote down vote up
/**
 * Create a new merge instance.
 * <p>
 * The merge will happen in memory, working folder will not be modified, in
 * case of a non-trivial merge that requires manual resolution, the merger
 * will fail.
 *
 * @param inserter
 *            inserter to write results back to.
 * @param config
 *            repo config for reading diff algorithm settings.
 * @return the new merge instance which implements this strategy.
 * @since 4.8
 */
public abstract Merger newMerger(ObjectInserter inserter, Config config);
 
Example #29
Source File: Merger.java    From onedev with MIT License 2 votes vote down vote up
/**
 * Get an object writer to create objects, writing objects to
 * {@link #getRepository()}
 *
 * @return an object writer to create objects, writing objects to
 *         {@link #getRepository()} (if a repository was provided).
 */
public ObjectInserter getObjectInserter() {
	return inserter;
}