Here are the examples of the java api org.eclipse.jgit.lib.Repository.resolve() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
87 Examples
19
Source : GitCoreRepository.java
with MIT License
from VirtusLab
with MIT License
from VirtusLab
private Option<ObjectId> convertRevisionToObjectId(String revision) throws GitCoreException {
try {
return Option.of(jgitRepo.resolve(revision));
} catch (IOException e) {
throw new GitCoreException(e);
}
}
19
Source : GitUtils.java
with MIT License
from theonedev
with MIT License
from theonedev
@Nullable
public static ObjectId resolve(Repository repository, String revision) {
try {
return repository.resolve(revision);
} catch (RevisionSyntaxException | AmbiguousObjectException | IncorrectObjectTypeException e) {
return null;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
19
Source : GitUtil.java
with GNU General Public License v3.0
from qoomon
with GNU General Public License v3.0
from qoomon
public static String revParse(Repository repository, String revstr) throws IOException {
ObjectId rev = repository.resolve(revstr);
if (rev == null) {
return NO_COMMIT;
}
return rev.getName();
}
19
Source : JGitVersionStore.java
with Apache License 2.0
from projectnessie
with Apache License 2.0
from projectnessie
@Override
public WithHash<Ref> toRef(String refOfUnknownType) throws ReferenceNotFoundException {
try {
org.eclipse.jgit.lib.Ref jgitRef;
jgitRef = repository.findRef(Constants.R_HEADS + refOfUnknownType);
// branch first.
if (jgitRef != null) {
return WithHash.of(Hash.of(jgitRef.getObjectId().name()), BranchName.of(refOfUnknownType));
}
// then tag.
jgitRef = repository.findRef(Constants.R_TAGS + refOfUnknownType);
if (jgitRef != null) {
return WithHash.of(Hash.of(jgitRef.getObjectId().name()), TagName.of(refOfUnknownType));
}
// hash last.
try {
ObjectId hash = repository.resolve(refOfUnknownType + "^{tree}");
if (hash == null) {
throw ReferenceNotFoundException.forReference(refOfUnknownType);
}
return WithHash.of(Hash.of(refOfUnknownType), Hash.of(refOfUnknownType));
} catch (IllegalArgumentException | AmbiguousObjectException | IncorrectObjectTypeException e) {
throw new ReferenceNotFoundException(String.format("Unable to find the requested reference %s.", refOfUnknownType));
}
} catch (IOException e) {
throw new RuntimeException("Error talking to git repo", e);
}
}
19
Source : GitRepo.java
with BSD 2-Clause "Simplified" License
from kangta123
with BSD 2-Clause "Simplified" License
from kangta123
public RevCommit log(String branch) {
try {
sync();
Git git = getGit();
final Repository repository = git.getRepository();
Iterable<RevCommit> call = git.log().add(repository.resolve("remotes/origin/" + branch)).setMaxCount(1).call();
if (call != null) {
return call.iterator().next();
}
} catch (Exception e) {
log.error("Cannot open a connection to git repo", e);
throw new AppBusinessException("连接git仓库失败");
}
return null;
}
19
Source : CloneCheckoutBranchRepository.java
with MIT License
from eclipse
with MIT License
from eclipse
private List<RevCommit> getBranchCommits(Repository repository, String path) {
String treeName = null;
try {
treeName = repository.getBranch();
} catch (IOException e1) {
e1.printStackTrace();
}
List<RevCommit> commitList = new ArrayList<>();
try {
Git git = Git.open(new File(path));
git.log().add(repository.resolve(treeName)).call().forEach(commitList::add);
} catch (RevisionSyntaxException | GitAPIException | IOException e) {
e.printStackTrace();
}
return commitList;
}
19
Source : GitDiffHandlerV1.java
with Eclipse Public License 1.0
from eclipse
with Eclipse Public License 1.0
from eclipse
private AbstractTreeIterator getTreeIterator(Repository db, String name) throws IOException {
final ObjectId id = db.resolve(name);
if (id == null)
throw new IllegalArgumentException(name);
final CanonicalTreeParser p = new CanonicalTreeParser();
final ObjectReader or = db.newObjectReader();
try {
p.reset(or, new RevWalk(db).parseTree(id));
return p;
} finally {
or.close();
}
}
19
Source : GitCommitHandlerV1.java
with Eclipse Public License 1.0
from eclipse
with Eclipse Public License 1.0
from eclipse
private boolean merge(HttpServletRequest request, HttpServletResponse response, Repository db, String commitToMerge, boolean squash) throws ServletException, JSONException {
try {
ObjectId objectId = db.resolve(commitToMerge);
Git git = Git.wrap(db);
MergeResult mergeResult = git.merge().setSquash(squash).include(objectId).call();
JSONObject result = new JSONObject();
result.put(GitConstants.KEY_RESULT, mergeResult.getMergeStatus().name());
if (mergeResult.getFailingPaths() != null && !mergeResult.getFailingPaths().isEmpty()) {
result.put(GitConstants.KEY_FAILING_PATHS, mergeResult.getFailingPaths());
}
OrionServlet.writeJSONResponse(request, response, result, JsonURIUnqualificationStrategy.ALL_NO_GIT);
return true;
} catch (CheckoutConflictException e) {
return workaroundBug356918(request, response, e);
} catch (IOException e) {
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred when merging.", e));
} catch (GitAPIException e) {
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred when merging.", e));
}
}
19
Source : GitFlowMetaData.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
byte[] getContent(String objectId) throws IOException {
final ObjectId flowSnapshotObjectId = gitRepo.resolve(objectId);
return gitRepo.newObjectReader().open(flowSnapshotObjectId).getBytes();
}
19
Source : Utils.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public static ObjectId parseObjectId(Repository repository, String objectId) throws GitException {
try {
return repository.resolve(objectId);
} catch (RevisionSyntaxException ex) {
throw new GitException.MissingObjectException(objectId, GitObjectType.COMMIT, ex);
} catch (AmbiguousObjectException ex) {
// NOI18N
throw new GitException(MessageFormat.format(Utils.getBundle(Utils.clreplaced).getString("MSG_Exception_IdNotACommit"), objectId), ex);
} catch (IOException ex) {
throw new GitException(ex);
}
}
18
Source : AbstractGitCommand.java
with MIT License
from scm-manager
with MIT License
from scm-manager
static ObjectId resolveRevisionOrThrowNotFound(Repository repository, String revision, sonia.scm.repository.Repository scmRepository) throws IOException {
ObjectId resolved = repository.resolve(revision);
if (resolved == null) {
throw notFound(enreplacedy("Revision", revision).in(scmRepository));
} else {
return resolved;
}
}
18
Source : GitUtil.java
with GNU General Public License v3.0
from qoomon
with GNU General Public License v3.0
from qoomon
public static List<String> tag_pointsAt(Repository repository, String revstr) throws IOException {
ObjectId revObjectId = repository.resolve(revstr);
List<String> tagNames = new ArrayList<>();
for (Ref ref : repository.getRefDatabase().getRefsByPrefix(R_TAGS)) {
Ref peeledRef = repository.getRefDatabase().peel(ref);
ObjectId targetObjectId = peeledRef.getPeeledObjectId() != null ? peeledRef.getPeeledObjectId() : peeledRef.getObjectId();
if (targetObjectId.equals(revObjectId)) {
String tagName = ref.getName().replaceFirst("^" + R_TAGS, "");
tagNames.add(tagName);
}
}
return tagNames;
}
18
Source : GitUtil.java
with GNU General Public License v3.0
from qoomon
with GNU General Public License v3.0
from qoomon
public static long revTimestamp(Repository repository, String revstr) throws IOException {
ObjectId rev = repository.resolve(revstr);
if (rev == null) {
return 0;
}
// The timestamp is expressed in seconds since epoch...
return repository.parseCommit(rev).getCommitTime();
}
18
Source : JGitVersionStore.java
with Apache License 2.0
from projectnessie
with Apache License 2.0
from projectnessie
private Optional<ObjectId> commitTreeWithTwoWayMerge(BranchName branch, Optional<Hash> expectedHash, ObjectId newTree, List<String> unchanged) throws IOException {
ObjectId currentTreeId = repository.resolve(branch.getName() + "^{tree}");
ObjectId expectedId = repository.resolve(expectedHash.map(Hash::replacedtring).orElse(currentTreeId.name()) + "^{tree}");
Optional<ObjectId> mergedTree = tryTwoWayMerge(currentTreeId, newTree, repository.newObjectInserter(), expectedId, unchanged);
return mergedTree;
}
18
Source : JGitVersionStore.java
with Apache License 2.0
from projectnessie
with Apache License 2.0
from projectnessie
@Override
public void commit(BranchName branch, Optional<Hash> expectedHash, METADATA metadata, List<Operation<TABLE>> operations) throws ReferenceNotFoundException, ReferenceConflictException {
toHash(branch);
try {
testExpectedHash(branch, expectedHash);
ObjectId commits = TreeBuilder.commitObjects(operations, repository, storeWorker.getValueSerializer(), emptyObject);
ObjectId treeId = repository.resolve(expectedHash.map(Hash::replacedtring).orElse(branch.getName()) + "^{tree}");
if (treeId == null) {
throw ReferenceNotFoundException.forReference(expectedHash.map(x -> (Ref) x).orElse(branch));
}
ObjectId newTree = TreeBuilder.merge(treeId, commits, repository);
List<String> unchanged = operations.stream().filter(e -> e instanceof Unchanged).map(Operation::getKey).map(JGitVersionStore::stringFromKey).collect(Collectors.toList());
Optional<ObjectId> mergedTree = commitTreeWithTwoWayMerge(branch, expectedHash, newTree, unchanged);
ObjectId currentCommitId = repository.resolve(branch.getName() + "^{commit}");
ObjectId currentTreeId = repository.resolve(branch.getName() + "^{tree}");
ObjectId mergedHash = mergedTree.orElseThrow(() -> ReferenceConflictException.forReference(branch, expectedHash, Optional.of(currentCommitId).map(ObjectId::name).map(Hash::of)));
commitTree(branch, mergedHash, Optional.of(currentCommitId).map(ObjectId::name).map(Hash::of), metadata, ObjectId.isEqual(currentTreeId, mergedHash), false);
} catch (IOException e) {
throw new RuntimeException("Unknown error", e);
}
}
18
Source : JGitVersionStore.java
with Apache License 2.0
from projectnessie
with Apache License 2.0
from projectnessie
@Override
public Stream<Key> getKeys(Ref ref) {
try {
List<Key> tables = new ArrayList<>();
try (TreeWalk treeWalk = new TreeWalk(repository)) {
ObjectId treeId = repository.resolve(refName(ref) + "^{tree}");
treeWalk.addTree(treeId);
treeWalk.setRecursive(true);
while (treeWalk.next()) {
tables.add(keyFromUrlString(treeWalk.getPathString()));
}
}
return tables.stream();
} catch (IOException e) {
throw new RuntimeException("Unknown error", e);
}
}
18
Source : JGitVersionStore.java
with Apache License 2.0
from projectnessie
with Apache License 2.0
from projectnessie
private void testLinearTransplantList(List<Hash> sequenceToTransplant) throws ReferenceNotFoundException {
try (RevWalk rw = new RevWalk(repository)) {
RevCommit start = null;
for (Hash hash : sequenceToTransplant) {
RevCommit commit;
try {
ObjectId obj = repository.resolve(hash.replacedtring() + "^{commit}");
commit = rw.parseCommit(obj);
} catch (IOException | NullPointerException e) {
throw ReferenceNotFoundException.forReference(hash);
}
if (start == null) {
start = commit;
continue;
}
try {
if (!rw.isMergedInto(start, commit)) {
throw new IllegalArgumentException(format("Hash %s is not the ancestor for commit %s", start, hash));
} else {
start = commit;
}
} catch (IOException e) {
throw new IllegalArgumentException(format("Hash %s is not the ancestor for commit %s", start, hash));
}
}
}
}
18
Source : JGitVersionStore.java
with Apache License 2.0
from projectnessie
with Apache License 2.0
from projectnessie
private void updateRef(NamedRef ref, Hash targetHash, Optional<Hash> expectedHash, boolean force) throws IOException, ReferenceConflictException, ReferenceNotFoundException {
ObjectId target = repository.resolve(targetHash.replacedtring());
if (target == null) {
throw ReferenceNotFoundException.forReference(ref);
}
updateRef(ref, target, expectedHash, force);
}
18
Source : ExtractRepoHeads.java
with Apache License 2.0
from mast-group
with Apache License 2.0
from mast-group
public static String getHeadName(Repository repo) {
String result = null;
try {
ObjectId id = repo.resolve(Constants.HEAD);
result = id.getName();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
18
Source : CommitDiffTask.java
with GNU General Public License v3.0
from maks
with GNU General Public License v3.0
from maks
private AbstractTreeIterator getTreeIterator(Repository repo, String commit) throws IOException {
if (commit.equals("dircache")) {
return new DirCacheIterator(repo.readDirCache());
}
if (commit.equals("filetree")) {
return new FileTreeIterator(repo);
}
ObjectId treeId = repo.resolve(commit + "^{tree}");
if (treeId == null) {
throw new NullPointerException();
}
CanonicalTreeParser treeIter = new CanonicalTreeParser();
ObjectReader reader = repo.newObjectReader();
treeIter.reset(reader, treeId);
return treeIter;
}
18
Source : CommitDiffTask.java
with GNU General Public License v3.0
from maks
with GNU General Public License v3.0
from maks
public boolean getCommitDiff() {
try {
Repository repo = mRepo.getGit().getRepository();
mDiffOutput = new ByteArrayOutputStream();
mDiffFormatter = new DiffFormatter(mDiffOutput);
mDiffFormatter.setRepository(repo);
AbstractTreeIterator mOldCommitTreeIterator = mRepo.isInitialCommit(mNewCommit) ? new EmptyTreeIterator() : getTreeIterator(repo, mOldCommit);
AbstractTreeIterator mNewCommitTreeIterator = getTreeIterator(repo, mNewCommit);
mDiffEntries = mDiffFormatter.scan(mOldCommitTreeIterator, mNewCommitTreeIterator);
if (mShowDescription) {
ObjectId newCommitId = repo.resolve(mNewCommit);
mCommits = mRepo.getGit().log().add(newCommitId).setMaxCount(1).call();
} else {
mCommits = new ArrayList<RevCommit>();
}
return true;
} catch (GitAPIException e) {
setException(e);
} catch (IncorrectObjectTypeException e) {
setException(e, R.string.error_diff_failed);
} catch (AmbiguousObjectException e) {
setException(e, R.string.error_diff_failed);
} catch (IOException e) {
setException(e, R.string.error_diff_failed);
} catch (IllegalStateException e) {
setException(e, R.string.error_diff_failed);
} catch (NullPointerException e) {
setException(e, R.string.error_diff_failed);
} catch (StopTaskException e) {
}
return false;
}
18
Source : Repo.java
with GNU General Public License v3.0
from maks
with GNU General Public License v3.0
from maks
private RevCommit getCommitByRevStr(String commitRevStr) {
try {
Repository repository = getGit().getRepository();
ObjectId id = repository.resolve(commitRevStr);
RevWalk revWalk = new RevWalk(getGit().getRepository());
return (id != null) ? revWalk.parseCommit(id) : null;
} catch (StopTaskException | IOException e) {
Timber.e(e, "error parsing commit id: %s", commitRevStr);
return null;
}
}
18
Source : RevisionParser.java
with Apache License 2.0
from google
with Apache License 2.0
from google
private RevObject resolve(String name, RevWalk walk) throws IOException {
try {
ObjectId id = repo.resolve(name);
return id != null ? walk.parseAny(id) : null;
} catch (AmbiguousObjectException e) {
// TODO(dborowitz): Render a helpful disambiguation page.
return null;
} catch (RevisionSyntaxException | MissingObjectException e) {
return null;
}
}
18
Source : DescribeServlet.java
with Apache License 2.0
from google
with Apache License 2.0
from google
private ObjectId resolve(Repository repo, GitilesView view) throws IOException {
String rev = view.getPathPart();
try {
return repo.resolve(rev);
} catch (RevisionSyntaxException e) {
throw new GitilesRequestFailureException(FailureReason.INCORECT_PARAMETER, e).withPublicErrorMessage("Invalid revision syntax: %s", RefServlet.sanitizeRefForText(rev));
} catch (AmbiguousObjectException e) {
throw new GitilesRequestFailureException(FailureReason.AMBIGUOUS_OBJECT).withPublicErrorMessage("Ambiguous short SHA-1 %s (%s)", e.getAbbreviatedObjectId(), Joiner.on(", ").join(e.getCandidates()));
}
}
18
Source : ExportDiffCommand.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private AbstractTreeIterator getHeadIterator(ObjectReader or) throws IOException {
Repository repository = getRepository();
AbstractTreeIterator headIterator;
ObjectId headId = repository.resolve(Constants.HEAD);
if (headId != null) {
headIterator = new CanonicalTreeParser(null, or, new RevWalk(repository).parseTree(headId).getId());
} else {
headIterator = new EmptyTreeIterator();
}
return headIterator;
}
17
Source : GitMergeCommandTest.java
with MIT License
from scm-manager
with MIT License
from scm-manager
@Test(expected = NoChangesMadeException.clreplaced)
public void shouldNotMergeTwice() throws IOException, GitAPIException {
GitMergeCommand command = createCommand();
MergeCommandRequest request = new MergeCommandRequest();
request.setTargetBranch("master");
request.setBranchToMerge("mergeable");
request.setAuthor(new Person("Dirk Gently", "[email protected]"));
request.setMergeStrategy(MergeStrategy.MERGE_COMMIT);
MergeCommandResult mergeCommandResult = command.merge(request);
replacedertThat(mergeCommandResult.isSuccess()).isTrue();
Repository repository = createContext().open();
new Git(repository).log().add(repository.resolve("master")).setMaxCount(1).call().iterator().next().getId();
command.merge(request);
}
17
Source : JGitVersionStore.java
with Apache License 2.0
from projectnessie
with Apache License 2.0
from projectnessie
private void commitTree(BranchName branch, ObjectId newTree, Optional<Hash> expectedHash, METADATA metadata, boolean force, boolean empty) throws IOException, ReferenceConflictException {
ObjectInserter inserter = repository.newObjectInserter();
CommitBuilder commitBuilder = fromUser(metadata, empty);
commitBuilder.setTreeId(newTree);
ObjectId parentId = fromHash(branch, expectedHash).orElse(repository.resolve(Constants.R_HEADS + branch.getName()));
if (parentId != null) {
commitBuilder.setParentId(parentId);
}
ObjectId newCommitId = inserter.insert(commitBuilder);
inserter.flush();
updateRef(branch, newCommitId, expectedHash, force);
}
17
Source : JGitVersionStore.java
with Apache License 2.0
from projectnessie
with Apache License 2.0
from projectnessie
@Override
public Stream<WithHash<METADATA>> getCommits(Ref ref) throws ReferenceNotFoundException {
final String hashName = refName(ref);
try {
ObjectId objectId = repository.resolve(hashName);
if (objectId == null) {
throw new ReferenceNotFoundException(String.format("Ref %s not found", ref));
}
RevWalk walk = new RevWalk(repository);
walk.markStart(repository.parseCommit(objectId));
Serializer<METADATA> serializer = storeWorker.getMetadataSerializer();
// note: skipLastElement doesn't return the absolute base commit. This is because other version stores don't consider that a commit.
return StreamSupport.stream(skipLastElement(walk.spliterator()), false).map(r -> {
Hash hash = Hash.of(r.name());
METADATA metadata = serializer.fromBytes(ByteString.copyFrom(r.getFullMessage(), StandardCharsets.UTF_8));
return WithHash.of(hash, metadata);
});
} catch (IOException e) {
throw new RuntimeException("Unknown error", e);
}
}
17
Source : JGitVersionStore.java
with Apache License 2.0
from projectnessie
with Apache License 2.0
from projectnessie
@Override
public void transplant(BranchName targetBranch, Optional<Hash> expectedHash, List<Hash> sequenceToTransplant) throws ReferenceNotFoundException, ReferenceConflictException {
testLinearTransplantList(sequenceToTransplant);
try {
ObjectId targetTreeId = repository.resolve(targetBranch.getName() + "^{tree}");
if (targetTreeId == null) {
throw ReferenceNotFoundException.forReference(expectedHash.map(x -> (Ref) x).orElse(targetBranch));
}
testExpectedHash(targetBranch, expectedHash);
ObjectId newTree = null;
for (Hash hash : sequenceToTransplant) {
ObjectId transplantTree = TreeBuilder.transplant(hash, repository);
if (newTree == null) {
newTree = transplantTree;
} else {
newTree = TreeBuilder.merge(newTree, transplantTree, repository);
}
}
Optional<ObjectId> mergeTree = commitTreeWithTwoWayMerge(targetBranch, expectedHash, newTree, Collections.emptyList());
ObjectId currentCommitId = repository.resolve(targetBranch.getName() + "^{commit}");
ObjectId currentTreeId = repository.resolve(targetBranch.getName() + "^{tree}");
if (!mergeTree.isPresent()) {
throw ReferenceConflictException.forReference(targetBranch, expectedHash, Optional.of(currentCommitId).map(ObjectId::name).map(Hash::of));
}
for (Hash hash : sequenceToTransplant) {
ObjectId transplantTree = TreeBuilder.merge(currentTreeId, TreeBuilder.transplant(hash, repository), repository);
commitTree(targetBranch, transplantTree, Optional.of(currentCommitId).map(ObjectId::name).map(Hash::of), getCommit(hash), false, false);
currentCommitId = repository.resolve(targetBranch.getName() + "^{commit}");
currentTreeId = repository.resolve(targetBranch.getName() + "^{tree}");
}
} catch (IOException e) {
throw new RuntimeException("Unknown error", e);
}
}
17
Source : JGitVersionStore.java
with Apache License 2.0
from projectnessie
with Apache License 2.0
from projectnessie
@Override
public TABLE getValue(Ref ref, Key key) throws ReferenceNotFoundException {
final String hashName = refName(ref);
String table = stringFromKey(key);
try {
try (TreeWalk treeWalk = new TreeWalk(repository)) {
ObjectId treeId = repository.resolve(hashName + "^{tree}");
treeWalk.addTree(treeId);
treeWalk.setRecursive(true);
treeWalk.setFilter(PathFilter.create(table));
while (treeWalk.next()) {
byte[] bytes = getTable(treeWalk, repository);
return storeWorker.getValueSerializer().fromBytes(ByteString.copyFrom(bytes));
}
}
return null;
} catch (IOException e) {
throw new ReferenceNotFoundException(String.format("reference for ref %s and key %s not found", ref, key), e);
}
}
17
Source : TreeWalkResolver.java
with GNU General Public License v3.0
from jpmorganchase
with GNU General Public License v3.0
from jpmorganchase
private RevCommit getRevCommit() throws IOException {
try (RevWalk walk = new RevWalk(repository)) {
walk.sort(COMMIT_TIME_DESC);
return walk.parseCommit(repository.resolve(commitId));
}
}
17
Source : GitCommitHandlerV1.java
with Eclipse Public License 1.0
from eclipse
with Eclipse Public License 1.0
from eclipse
private boolean revert(HttpServletRequest request, HttpServletResponse response, Repository db, String commitToRevert) throws ServletException, JSONException {
RevWalk revWalk = new RevWalk(db);
try {
Ref headRef = db.getRef(Constants.HEAD);
if (headRef == null)
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred when reverting.", null));
ObjectId objectId = db.resolve(commitToRevert);
Git git = Git.wrap(db);
RevertCommand revertCommand = git.revert().include(objectId);
RevCommit revertedCommit = revertCommand.call();
if (revertedCommit == null) {
JSONObject result = new JSONObject();
// $NON-NLS-1$
result.put(GitConstants.KEY_RESULT, "FAILURE");
OrionServlet.writeJSONResponse(request, response, result, JsonURIUnqualificationStrategy.ALL_NO_GIT);
return true;
}
JSONObject result = new JSONObject();
// $NON-NLS-1$
result.put(GitConstants.KEY_RESULT, "OK");
OrionServlet.writeJSONResponse(request, response, result, JsonURIUnqualificationStrategy.ALL_NO_GIT);
return true;
} catch (IOException e) {
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred when reverting.", e));
} catch (GitAPIException e) {
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred when reverting.", e));
} finally {
revWalk.close();
}
}
17
Source : GitServiceImpl.java
with MIT License
from aserg-ufmg
with MIT License
from aserg-ufmg
@Override
public RevCommit createRevCommitByCommitId(final Repository repository, final String commitId) throws Exception {
RevWalk walk = new RevWalk(repository);
RevCommit commit = walk.parseCommit(repository.resolve(commitId));
walk.parseCommit(commit.getParent(0));
return commit;
}
17
Source : UIGitTest.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
@Test
public void testPush() throws Exception {
// Set remote
Git git2 = new Git(db2);
UIGit uiGit2 = new UIGit();
uiGit2.setGit(git2);
URIish uri = new URIish(db2.getDirectory().toURI().toURL());
RemoteAddCommand cmd = git.remoteAdd();
cmd.setName(Constants.DEFAULT_REMOTE_NAME);
cmd.setUri(uri);
cmd.call();
replacedertTrue(uiGit.hasRemote());
// create some refs via commits and tag
RevCommit commit = git.commit().setMessage("initial commit").call();
Ref tagRef = git.tag().setName("tag").call();
try {
db2.resolve(commit.getId().getName() + "^{commit}");
fail("id shouldn't exist yet");
} catch (MissingObjectException e) {
// we should get here
}
boolean success = uiGit.push();
replacedertTrue(success);
replacedertEquals(commit.getId(), db2.resolve(commit.getId().getName() + "^{commit}"));
replacedertEquals(tagRef.getObjectId(), db2.resolve(tagRef.getObjectId().getName()));
// Push a tag
EnterSelectionDialog esd = mock(EnterSelectionDialog.clreplaced);
doReturn("tag").when(esd).open();
doReturn(esd).when(uiGit).getEnterSelectionDialog(any(), anyString(), anyString());
uiGit.push(VCS.TYPE_TAG);
replacedertTrue(success);
replacedertTrue(uiGit2.getTags().contains("tag"));
// Another commit and push a branch again
writeTrashFile("Test2.txt", "Hello world");
git.add().addFilepattern("Test2.txt").call();
commit = git.commit().setMessage("second commit").call();
doReturn(Constants.MASTER).when(esd).open();
uiGit.push(VCS.TYPE_BRANCH);
replacedertTrue(success);
replacedertEquals(commit.getId(), db2.resolve(commit.getId().getName() + "^{commit}"));
replacedertEquals("refs/remotes/origin/master", uiGit.getExpandedName("origin/master", "branch"));
}
16
Source : GitMergeCommandTest.java
with MIT License
from scm-manager
with MIT License
from scm-manager
@Test
public void shouldUseConfiguredCommitMessageTemplate() throws IOException, GitAPIException {
GitMergeCommand command = createCommand();
MergeCommandRequest request = new MergeCommandRequest();
request.setTargetBranch("master");
request.setBranchToMerge("mergeable");
request.setMergeStrategy(MergeStrategy.MERGE_COMMIT);
request.setAuthor(new Person("Dirk Gently", "[email protected]"));
request.setMessageTemplate("simple");
MergeCommandResult mergeCommandResult = command.merge(request);
replacedertThat(mergeCommandResult.isSuccess()).isTrue();
Repository repository = createContext().open();
Iterable<RevCommit> commits = new Git(repository).log().add(repository.resolve("master")).setMaxCount(1).call();
RevCommit mergeCommit = commits.iterator().next();
String message = mergeCommit.getFullMessage();
replacedertThat(message).isEqualTo("simple");
}
16
Source : JGitUtils.java
with MIT License
from refactoring-ai
with MIT License
from refactoring-ai
public static RevWalk getReverseWalk(Repository repo, String mainBranch) throws IOException {
RevWalk walk = new RevWalk(repo);
walk.markStart(walk.parseCommit(repo.resolve(mainBranch)));
walk.sort(RevSort.REVERSE);
return walk;
}
16
Source : GitProperties.java
with Apache License 2.0
from pascalgn
with Apache License 2.0
from pascalgn
private void addProperties(Map<String, String> map) throws IOException {
File gitDir = new FileRepositoryBuilder().setWorkTree(new File(".")).readEnvironment().findGitDir().getGitDir();
Repository repository = new FileRepositoryBuilder().setGitDir(gitDir).setMustExist(true).build();
logger.debug("Using git repository: " + repository.getDirectory());
ObjectId head = repository.resolve("HEAD");
if (head == null) {
throw new IllegalStateException("No such revision: HEAD");
}
String branch = nullToEmpty(repository.getBranch());
map.put("git.branch", branch);
String commitId = head.name();
map.put("git.commit.id", commitId);
map.put("git.tag.last", getLastTag(repository));
String commitIdAbbrev = repository.newObjectReader().abbreviate(head).name();
map.put("git.commit.id.abbrev", commitIdAbbrev);
RevWalk walk = new RevWalk(repository);
walk.setRetainBody(false);
RevCommit headCommit = walk.parseCommit(head);
int count = RevWalkUtils.count(walk, headCommit, null);
map.put("git.count", Integer.toString(count));
String color = commitId.substring(0, 6);
map.put("git.commit.color.value", color);
map.put("git.commit.color.name", ColorHelper.getColorName(color));
map.put("git.commit.color.lightness", Integer.toString(ColorHelper.getLightness(color)));
map.put("git.commit.color.foreground", ColorHelper.getForeground(color));
map.put("git.build.datetime.simple", getFormattedDate());
map.put("git.dir.git", repository.getDirectory().getAbsolutePath());
map.put("git.dir.worktree", repository.getWorkTree().getAbsolutePath());
}
16
Source : LocalGit.java
with GNU General Public License v2.0
from ia-toki
with GNU General Public License v2.0
from ia-toki
@Override
public void resetToParent(Path rootDirPath) {
File root = fs.getFile(rootDirPath);
try {
Repository repo = FileRepositoryBuilder.create(new File(root, ".git"));
new org.eclipse.jgit.api.Git(repo).reset().setRef(repo.resolve("HEAD^").getName()).call();
repo.close();
} catch (IOException | GitAPIException e) {
throw new RuntimeException(e);
}
}
16
Source : GitCommitHandlerV1.java
with Eclipse Public License 1.0
from eclipse
with Eclipse Public License 1.0
from eclipse
private boolean tag(HttpServletRequest request, HttpServletResponse response, Repository db, String commitId, String tagName, boolean isRoot, boolean isTagAnnotated, String annotatedTagMessage) throws JSONException, URISyntaxException, ServletException {
Git git = Git.wrap(db);
RevWalk walk = new RevWalk(db);
try {
ObjectId objectId = db.resolve(commitId);
RevCommit revCommit = walk.lookupCommit(objectId);
walk.parseBody(revCommit);
GitTagHandlerV1.tag(git, revCommit, tagName, isTagAnnotated, annotatedTagMessage);
URI cloneLocation = BaseToCloneConverter.getCloneLocation(getURI(request), BaseToCloneConverter.COMMIT_REFRANGE);
Commit commit = new Commit(cloneLocation, db, revCommit, null);
JSONObject result = commit.toJSON();
OrionServlet.writeJSONResponse(request, response, result, JsonURIUnqualificationStrategy.ALL_NO_GIT);
return true;
} catch (IOException e) {
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred when tagging.", e));
} catch (GitAPIException e) {
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred when tagging.", e));
} catch (CoreException e) {
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred when tagging.", e));
} finally {
walk.dispose();
}
}
16
Source : GitCommitHandlerV1.java
with Eclipse Public License 1.0
from eclipse
with Eclipse Public License 1.0
from eclipse
private boolean rebase(HttpServletRequest request, HttpServletResponse response, Repository db, String commitToRebase, String rebaseOperation) throws ServletException, JSONException, AmbiguousObjectException, IOException {
JSONObject result = new JSONObject();
try {
Git git = Git.wrap(db);
RebaseCommand rebase = git.rebase();
Operation operation;
if (rebaseOperation != null) {
operation = Operation.valueOf(rebaseOperation);
} else {
operation = Operation.BEGIN;
}
if (commitToRebase != null && !commitToRebase.isEmpty()) {
ObjectId objectId = db.resolve(commitToRebase);
rebase.setUpstream(objectId);
} else if (operation.equals(Operation.BEGIN)) {
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Missing commit refId.", null));
}
rebase.setOperation(operation);
RebaseResult rebaseResult = rebase.call();
result.put(GitConstants.KEY_RESULT, rebaseResult.getStatus().name());
} catch (UnmergedPathsException e) {
// this error should be handled by client, so return a proper status
result.put(GitConstants.KEY_RESULT, AdditionalRebaseStatus.FAILED_UNMERGED_PATHS.name());
} catch (WrongRepositoryStateException e) {
// this error should be handled by client, so return a proper status
result.put(GitConstants.KEY_RESULT, AdditionalRebaseStatus.FAILED_WRONG_REPOSITORY_STATE.name());
} catch (IllegalArgumentException e) {
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Invalid rebase operation.", e));
} catch (GitAPIException e) {
// get cause and try to handle
if (e.getCause() instanceof org.eclipse.jgit.errors.CheckoutConflictException) {
// this error should be handled by client, so return a proper
// status
result.put(GitConstants.KEY_RESULT, AdditionalRebaseStatus.FAILED_PENDING_CHANGES.name());
} else {
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred when rebasing.", e));
}
}
OrionServlet.writeJSONResponse(request, response, result, JsonURIUnqualificationStrategy.ALL_NO_GIT);
return true;
}
16
Source : GitCommitHandlerV1.java
with Eclipse Public License 1.0
from eclipse
with Eclipse Public License 1.0
from eclipse
private boolean cherryPick(HttpServletRequest request, HttpServletResponse response, Repository db, String commitToCherryPick) throws ServletException, JSONException {
RevWalk revWalk = new RevWalk(db);
try {
Ref headRef = db.getRef(Constants.HEAD);
if (headRef == null)
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred when cherry-picking.", null));
RevCommit head = revWalk.parseCommit(headRef.getObjectId());
ObjectId objectId = db.resolve(commitToCherryPick);
Git git = Git.wrap(db);
CherryPickResult cherryPickResult = git.cherryPick().include(objectId).call();
RevCommit newHead = cherryPickResult.getNewHead();
JSONObject result = new JSONObject();
result.put(GitConstants.KEY_RESULT, cherryPickResult.getStatus().name());
result.put(GitConstants.KEY_HEAD_UPDATED, !head.equals(newHead));
OrionServlet.writeJSONResponse(request, response, result, JsonURIUnqualificationStrategy.ALL_NO_GIT);
return true;
} catch (IOException e) {
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred when cherry-picking.", e));
} catch (GitAPIException e) {
return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred when cherry-picking.", e));
} finally {
revWalk.close();
}
}
16
Source : UIGitTest.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
@Test
public void testShouldPushOnlyToOrigin() throws Exception {
// origin for db2
URIish uri = new URIish(db2.getDirectory().toURI().toURL());
RemoteAddCommand cmd = git.remoteAdd();
cmd.setName(Constants.DEFAULT_REMOTE_NAME);
cmd.setUri(uri);
cmd.call();
// upstream for db3
Repository db3 = createWorkRepository();
uri = new URIish(db3.getDirectory().toURI().toURL());
cmd = git.remoteAdd();
cmd.setName("upstream");
cmd.setUri(uri);
cmd.call();
// create some refs via commits and tag
RevCommit commit = git.commit().setMessage("initial commit").call();
Ref tagRef = git.tag().setName("tag").call();
try {
db3.resolve(commit.getId().getName() + "^{commit}");
fail("id shouldn't exist yet");
} catch (MissingObjectException e) {
// we should get here
}
uiGit.push();
// The followings should throw MissingObjectException
thrown.expect(MissingObjectException.clreplaced);
db3.resolve(commit.getId().getName() + "^{commit}");
db3.resolve(tagRef.getObjectId().getName());
}
15
Source : JGitRepository.java
with Apache License 2.0
from xm-online
with Apache License 2.0
from xm-online
@SneakyThrows
public String getBlobContent(Repository repository, String revision, String path) {
ObjectId lastCommitId = repository.resolve(revision);
try (RevWalk revWalk = new RevWalk(repository)) {
RevCommit commit = revWalk.parseCommit(lastCommitId);
RevTree tree = commit.getTree();
TreeWalk treeWalk = new TreeWalk(repository);
treeWalk.addTree(tree);
treeWalk.setRecursive(true);
treeWalk.setFilter(PathFilter.create(path));
if (!treeWalk.next()) {
return null;
}
ObjectId objectId = treeWalk.getObjectId(0);
ObjectLoader loader = repository.open(objectId);
byte[] content = loader.getBytes();
revWalk.dispose();
return new String(content, UTF_8);
}
}
15
Source : GitMergeCommandTest.java
with MIT License
from scm-manager
with MIT License
from scm-manager
@Test
public void shouldRejectRebaseMergeIfBranchCannotBeRebased() throws IOException, GitAPIException {
GitMergeCommand command = createCommand();
MergeCommandRequest request = new MergeCommandRequest();
request.setTargetBranch("master");
request.setBranchToMerge("not-rebasable");
request.setMergeStrategy(MergeStrategy.REBASE);
request.setAuthor(new Person("Dirk Gently", "[email protected]"));
MergeCommandResult mergeCommandResult = command.merge(request);
replacedertThat(mergeCommandResult.isSuccess()).isFalse();
Repository repository = createContext().open();
Iterable<RevCommit> commits = new Git(repository).log().add(repository.resolve("master")).setMaxCount(1).call();
RevCommit headCommit = commits.iterator().next();
replacedertThat(headCommit.getName()).isEqualTo("fcd0ef1831e4002ac43ea539f4094334c79ea9ec");
}
15
Source : GitMergeCommandTest.java
with MIT License
from scm-manager
with MIT License
from scm-manager
@Test
public void shouldAllowEmptyMergeCommit() throws IOException, GitAPIException {
GitMergeCommand command = createCommand();
MergeCommandRequest request = new MergeCommandRequest();
request.setTargetBranch("master");
request.setBranchToMerge("empty_merge");
request.setMergeStrategy(MergeStrategy.MERGE_COMMIT);
request.setAuthor(new Person("Dirk Gently", "[email protected]"));
MergeCommandResult mergeCommandResult = command.merge(request);
replacedertThat(mergeCommandResult.isSuccess()).isTrue();
Repository repository = createContext().open();
Iterable<RevCommit> commits = new Git(repository).log().add(repository.resolve("master")).setMaxCount(1).call();
RevCommit mergeCommit = commits.iterator().next();
replacedertThat(mergeCommit.getParentCount()).isEqualTo(2);
replacedertThat(mergeCommit.getParent(0).name()).isEqualTo("fcd0ef1831e4002ac43ea539f4094334c79ea9ec");
replacedertThat(mergeCommit.getParent(1).name()).isEqualTo("d81ad6c63d7e2162308d69637b339dedd1d9201c");
}
15
Source : GitMergeCommandTest.java
with MIT License
from scm-manager
with MIT License
from scm-manager
@Test
public void shouldNotSignMergeCommitIfSigningIsDisabled() throws IOException, GitAPIException {
GitMergeCommand command = createCommand();
MergeCommandRequest request = new MergeCommandRequest();
request.setTargetBranch("master");
request.setBranchToMerge("empty_merge");
request.setMergeStrategy(MergeStrategy.MERGE_COMMIT);
request.setAuthor(new Person("Dirk Gently", "[email protected]"));
request.setSign(false);
MergeCommandResult mergeCommandResult = command.merge(request);
replacedertThat(mergeCommandResult.isSuccess()).isTrue();
Repository repository = createContext().open();
Iterable<RevCommit> commits = new Git(repository).log().add(repository.resolve("master")).setMaxCount(1).call();
RevCommit mergeCommit = commits.iterator().next();
replacedertThat(mergeCommit.getRawGpgSignature()).isNullOrEmpty();
}
15
Source : RootedDocServlet.java
with Apache License 2.0
from google
with Apache License 2.0
from google
@Override
public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
try (Repository repo = resolver.open(req, null);
RevWalk rw = new RevWalk(repo)) {
ObjectId id = repo.resolve(BRANCH);
if (id == null) {
throw new GitilesRequestFailureException(FailureReason.OBJECT_NOT_FOUND);
}
RevObject obj = rw.peel(rw.parseAny(id));
if (!(obj instanceof RevCommit)) {
throw new GitilesRequestFailureException(FailureReason.INCORRECT_OBJECT_TYPE);
}
req.setAttribute(ATTRIBUTE_REPOSITORY, repo);
ViewFilter.setView(req, GitilesView.rootedDoc().setHostName(req.getServerName()).setServletPath(req.getContextPath() + req.getServletPath()).setRevision(BRANCH, obj).setPathPart(req.getPathInfo()).build());
docServlet.service(req, res);
} catch (ServiceNotAuthorizedException e) {
throw new GitilesRequestFailureException(FailureReason.NOT_AUTHORIZED, e);
} catch (ServiceNotEnabledException e) {
throw new GitilesRequestFailureException(FailureReason.SERVICE_NOT_ENABLED, e);
} finally {
ViewFilter.removeView(req);
req.removeAttribute(ATTRIBUTE_REPOSITORY);
}
}
15
Source : GitChangeResolver.java
with Apache License 2.0
from arquillian
with Apache License 2.0
from arquillian
private Set<Change> retrieveCommitsChanges(String previous, String head, File repoRoot) {
final Repository repository = git.getRepository();
try (ObjectReader reader = repository.newObjectReader()) {
final ObjectId oldHead = repository.resolve(previous + ENSURE_TREE);
final ObjectId newHead = repository.resolve(head + ENSURE_TREE);
validateCommitExists(oldHead, previous, repository);
validateCommitExists(newHead, head, repository);
final CanonicalTreeParser oldTree = new CanonicalTreeParser();
oldTree.reset(reader, oldHead);
final CanonicalTreeParser newTree = new CanonicalTreeParser();
newTree.reset(reader, newHead);
final List<DiffEntry> commitDiffs = git.diff().setNewTree(newTree).setOldTree(oldTree).call();
return transformToChangeSet(reduceToRenames(commitDiffs), repoRoot);
} catch (MissingObjectException e) {
throw new IllegalArgumentException(format(WRONG_COMMIT_ID_EXCEPTION, e.getObjectId().getName(), repository.getDirectory().getAbsolutePath()));
} catch (IOException | GitAPIException e) {
throw new IllegalStateException(e);
}
}
15
Source : UpdateRefCommand.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
@Override
protected void run() throws GitException {
Repository repository = getRepository();
try {
Ref ref = repository.findRef(refName);
if (ref == null || ref.isSymbolic()) {
// currently unable to update symbolic references
result = GitRefUpdateResult.valueOf(RefUpdate.Result.NOT_ATTEMPTED.name());
return;
}
Ref newRef = repository.findRef(revision);
String name;
if (newRef == null) {
ObjectId id = repository.resolve(revision);
newRef = new ObjectIdRef.Unpeeled(Ref.Storage.LOOSE, id.name(), id.copy());
name = newRef.getName();
} else {
name = revision;
}
RefUpdate u = repository.updateRef(ref.getName());
newRef = repository.peel(newRef);
ObjectId srcObjectId = newRef.getPeeledObjectId();
if (srcObjectId == null) {
srcObjectId = newRef.getObjectId();
}
u.setNewObjectId(srcObjectId);
// NOI18N
u.setRefLogMessage("merge " + name + ": Fast-forward", false);
u.update();
result = GitRefUpdateResult.valueOf((u.getResult() == null ? RefUpdate.Result.NOT_ATTEMPTED : u.getResult()).name());
} catch (IOException ex) {
throw new GitException(ex);
}
}
14
Source : GitMergeCommandTest.java
with MIT License
from scm-manager
with MIT License
from scm-manager
@Test
public void shouldSquashThreeCommitsIntoOne() throws IOException, GitAPIException {
GitMergeCommand command = createCommand();
MergeCommandRequest request = new MergeCommandRequest();
request.setAuthor(new Person("Dirk Gently", "[email protected]"));
request.setBranchToMerge("squash");
request.setTargetBranch("master");
request.setMessageTemplate("squash three commits");
request.setMergeStrategy(MergeStrategy.SQUASH);
Repository gitRepository = createContext().open();
MergeCommandResult mergeCommandResult = command.merge(request);
replacedertThat(mergeCommandResult.isSuccess()).isTrue();
Iterable<RevCommit> commits = new Git(gitRepository).log().add(gitRepository.resolve("master")).setMaxCount(1).call();
RevCommit mergeCommit = commits.iterator().next();
PersonIdent mergeAuthor = mergeCommit.getAuthorIdent();
String message = mergeCommit.getFullMessage();
replacedertThat(mergeAuthor.getName()).isEqualTo("Dirk Gently");
replacedertThat(message).isEqualTo("squash three commits");
GitModificationsCommand modificationsCommand = new GitModificationsCommand(createContext());
List<Added> changes = modificationsCommand.getModifications("master").getAdded();
replacedertThat(changes.size()).isEqualTo(3);
}
See More Examples