Here are the examples of the java api org.eclipse.jgit.lib.Constants.HEAD taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
89 Examples
19
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;
}
19
Source : JGitRepository.java
with MIT License
from factsmission
with MIT License
from factsmission
@Override
public String getCommitURL() throws IOException {
// something like https://github.com/factsmission/staging-website/commit/4467dc315fd80d4b98ad669e601b614d96e23041
try {
ObjectId id = git.getRepository().resolve(Constants.HEAD);
String hexString = ObjectId.toString(id);
return "https://github.com/" + repoName + "/commit/" + hexString;
} catch (IncorrectObjectTypeException | RevisionSyntaxException ex) {
throw new IOException(ex);
}
}
19
Source : Status.java
with Eclipse Public License 1.0
from eclipse
with Eclipse Public License 1.0
from eclipse
@PropertyDescription(name = GitConstants.KEY_COMMIT)
private URI getCommitLocation() throws URISyntaxException {
return statusToCommitLocation(baseLocation, Constants.HEAD);
}
19
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;
}
19
Source : UIGitTest.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
@Test
public void testCreateDeleteBranchTag() throws Exception {
initialCommit();
// create a tag
uiGit.createTag("test");
List<String> tags = uiGit.getTags();
replacedertTrue(tags.contains("test"));
// create a branch (and checkout that branch)
uiGit.createBranch("test");
List<String> branches = uiGit.getLocalBranches();
replacedertTrue(branches.contains("test"));
replacedertEquals("test", uiGit.getBranch());
// Checkout master
uiGit.checkout(Constants.MASTER);
// delete the branch
uiGit.deleteBranch("test", true);
branches = uiGit.getLocalBranches();
replacedertEquals(1, branches.size());
replacedertFalse(branches.contains("test"));
uiGit.checkout(uiGit.getExpandedName("test", VCS.TYPE_TAG));
replacedertTrue(uiGit.getBranch().contains(Constants.HEAD));
// delete the tag
uiGit.deleteTag("test");
tags = uiGit.getTags();
replacedertEquals(0, tags.size());
replacedertFalse(tags.contains("test"));
}
18
Source : Repository.java
with Eclipse Public License 1.0
from sonatype-nexus-community
with Eclipse Public License 1.0
from sonatype-nexus-community
@Override
public void create(boolean bare) throws IOException {
String master = Constants.R_HEADS + Constants.MASTER;
RefUpdate.Result result = updateRef(Constants.HEAD, true).link(master);
if (result != RefUpdate.Result.NEW)
throw new IOException(result.name());
}
18
Source : GitHeadModifier.java
with MIT License
from scm-manager
with MIT License
from scm-manager
private boolean modify(org.eclipse.jgit.lib.Repository gitRepository, String newHead) throws IOException {
RefUpdate refUpdate = gitRepository.getRefDatabase().newUpdate(Constants.HEAD, true);
refUpdate.setForceUpdate(true);
RefUpdate.Result result = refUpdate.link(Constants.R_HEADS + newHead);
return result == RefUpdate.Result.FORCED;
}
18
Source : JGitUtils.java
with MIT License
from refactoring-ai
with MIT License
from refactoring-ai
public static String getHead(Git git) throws IOException {
return git.getRepository().resolve(Constants.HEAD).getName();
}
18
Source : QuestionnaireGitRepo.java
with Apache License 2.0
from OpenChain-Project
with Apache License 2.0
from OpenChain-Project
/**
* @param language Language for the logged in user
* @return The hash of the head commit for the repository
* @throws GitRepoException
*/
public String getHeadCommit(String language) throws GitRepoException {
try {
return this.repo.resolve(Constants.HEAD).getName();
} catch (RevisionSyntaxException e) {
// $NON-NLS-1$
logger.error("Invalid syntax getting commit head information", e);
// $NON-NLS-1$
throw new GitRepoException(I18N.getMessage("QuestionnaireGitRepo.34", language));
} catch (AmbiguousObjectException e) {
// $NON-NLS-1$
logger.error("Ambiguous object exception getting commit head information", e);
// $NON-NLS-1$
throw new GitRepoException(I18N.getMessage("QuestionnaireGitRepo.34", language));
} catch (IncorrectObjectTypeException e) {
// $NON-NLS-1$
logger.error("Incorrect object type exception getting commit head information", e);
// $NON-NLS-1$
throw new GitRepoException(I18N.getMessage("QuestionnaireGitRepo.34", language));
} catch (IOException e) {
// $NON-NLS-1$
logger.error("I/O error getting commit head information", e);
// $NON-NLS-1$
throw new GitRepoException(I18N.getMessage("QuestionnaireGitRepo.34", language));
}
}
18
Source : GitUtil.java
with Apache License 2.0
from exactpro
with Apache License 2.0
from exactpro
public static List<GitResetBean> gitUnpushingCommits(CredentialBean credentialBean) throws Exception {
try (Git git = git(credentialBean)) {
LogCommand log = git.log();
Repository repo = git.getRepository();
log.addRange(repo.exactRef(R_REMOTES + DEFAULT_REMOTE_NAME + "/" + MASTER).getObjectId(), repo.exactRef(Constants.HEAD).getObjectId());
Iterable<RevCommit> call = log.call();
List<GitResetBean> list = new ArrayList<>();
for (RevCommit revCommit : call) {
list.add(new GitResetBean(revCommit, credentialBean));
}
return list;
}
}
18
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();
}
}
18
Source : Diff.java
with Eclipse Public License 1.0
from eclipse
with Eclipse Public License 1.0
from eclipse
private URI getBaseLocation(URI location, Repository db, IPath path) throws URISyntaxException, IOException {
String scope = path.segment(0);
if (scope.contains("..")) {
// $NON-NLS-1$
// $NON-NLS-1$
String[] commits = scope.split("\\.\\.");
if (commits.length != 2) {
throw new IllegalArgumentException(NLS.bind("Illegal scope format, expected {old}..{new}, was {0}", scope));
}
ThreeWayMerger merger = new ResolveMerger(db) {
};
// use #merge to set sourceObjects
String tip0 = GitUtils.decode(commits[0]);
String tip1 = GitUtils.decode(commits[1]);
merger.merge(new ObjectId[] { db.resolve(tip0), db.resolve(tip1) });
IPath p = new Path(GitServlet.GIT_URI + '/' + Commit.RESOURCE).append(merger.getBaseCommitId().getName()).append(path.removeFirstSegments(1));
// $NON-NLS-1$
return new URI(location.getScheme(), location.getUserInfo(), location.getHost(), location.getPort(), p.toString(), "parts=body", null);
} else if (scope.equals(GitConstants.KEY_DIFF_CACHED)) {
// HEAD is the base
IPath p = new Path(GitServlet.GIT_URI + '/' + Commit.RESOURCE).append(Constants.HEAD).append(path.removeFirstSegments(1));
// $NON-NLS-1$
return new URI(location.getScheme(), location.getUserInfo(), location.getHost(), location.getPort(), p.toString(), "parts=body", null);
} else {
// index is the base
IPath p = new Path(GitServlet.GIT_URI + '/' + Index.RESOURCE).append(path.removeFirstSegments(1));
return new URI(location.getScheme(), location.getUserInfo(), location.getHost(), location.getPort(), p.toString(), null, null);
}
}
18
Source : Diff.java
with Eclipse Public License 1.0
from eclipse
with Eclipse Public License 1.0
from eclipse
private URI getOldLocation(URI location, IPath path) throws URISyntaxException {
String scope = path.segment(0);
if (scope.contains("..")) {
// $NON-NLS-1$
// $NON-NLS-1$
String[] commits = scope.split("\\.\\.");
if (commits.length != 2) {
throw new IllegalArgumentException(NLS.bind("Illegal scope format, expected {old}..{new}, was {0}", scope));
}
IPath p = new Path(GitServlet.GIT_URI + '/' + Commit.RESOURCE).append(commits[0]).append(path.removeFirstSegments(1));
// $NON-NLS-1$
return new URI(location.getScheme(), location.getUserInfo(), location.getHost(), location.getPort(), p.toString(), "parts=body", null);
} else if (scope.equals(GitConstants.KEY_DIFF_CACHED)) {
IPath p = new Path(GitServlet.GIT_URI + '/' + Commit.RESOURCE).append(Constants.HEAD).append(path.removeFirstSegments(1));
// $NON-NLS-1$
return new URI(location.getScheme(), location.getUserInfo(), location.getHost(), location.getPort(), p.toString(), "parts=body", null);
} else if (scope.equals(GitConstants.KEY_DIFF_DEFAULT)) {
IPath p = new Path(GitServlet.GIT_URI + '/' + Index.RESOURCE).append(path.removeFirstSegments(1));
return new URI(location.getScheme(), location.getUserInfo(), location.getHost(), location.getPort(), p.toString(), null, null);
} else {
IPath p = new Path(GitServlet.GIT_URI + '/' + Commit.RESOURCE).append(scope).append(path.removeFirstSegments(1));
// $NON-NLS-1$
return new URI(location.getScheme(), location.getUserInfo(), location.getHost(), location.getPort(), p.toString(), "parts=body", null);
}
}
18
Source : LogCommand.java
with Eclipse Public License 1.0
from eclipse
with Eclipse Public License 1.0
from eclipse
/**
* Executes the {@code Log} command with all the options and parameters collected by the setter methods (e.g. {@link #add(AnyObjectId)},
* {@link #not(AnyObjectId)}, ..) of this clreplaced. Each instance of this clreplaced should only be used for one invocation of the command. Don't call this method
* twice on an instance.
*
* @return an iteration over RevCommits
* @throws NoHeadException
* of the references ref cannot be resolved
*/
@Override
public Iterable<RevCommit> call() throws GitAPIException, NoHeadException {
checkCallable();
ArrayList<RevFilter> filters = new ArrayList<RevFilter>();
if (pathFilters.size() > 0)
walk.setTreeFilter(AndTreeFilter.create(PathFilterGroup.create(pathFilters), TreeFilter.ANY_DIFF));
if (msgFilter != null)
filters.add(msgFilter);
if (authorFilter != null)
filters.add(authorFilter);
if (committerFilter != null)
filters.add(committerFilter);
if (sha1Filter != null)
filters.add(sha1Filter);
if (dateFilter != null)
filters.add(dateFilter);
if (skip > -1)
filters.add(SkipRevFilter.create(skip));
if (maxCount > -1)
filters.add(MaxCountRevFilter.create(maxCount));
RevFilter filter = null;
if (filters.size() > 1) {
filter = AndRevFilter.create(filters);
} else if (filters.size() == 1) {
filter = filters.get(0);
}
if (filter != null)
walk.setRevFilter(filter);
if (!startSpecified) {
try {
ObjectId headId = repo.resolve(Constants.HEAD);
if (headId == null)
throw new NoHeadException(JGitText.get().noHEADExistsAndNoExplicitStartingRevisionWreplacedpecified);
add(headId);
} catch (IOException e) {
// all exceptions thrown by add() shouldn't occur and represent
// severe low-level exception which are therefore wrapped
throw new JGitInternalException(JGitText.get().anExceptionOccurredWhileTryingToAddTheIdOfHEAD, e);
}
}
setCallable(false);
return walk;
}
18
Source : CachingRepositoryService.java
with MIT License
from ataraxie
with MIT License
from ataraxie
@Override
public Commit findCommitByName(String commitName) throws IOException {
ObjectId objectId;
if (Constants.HEAD.equals(commitName)) {
objectId = this.repository.resolve(Constants.HEAD);
} else {
objectId = ObjectId.fromString(commitName);
}
return new Commit(findRevCommitById(objectId));
}
18
Source : CherryPickCommand.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private ObjectId getHead() throws GitException {
return Utils.findCommit(getRepository(), Constants.HEAD);
}
18
Source : UIGitTest.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
@Test
public void testCommit() throws Exception {
replacedertFalse(uiGit.hreplacedtagedFiles());
writeTrashFile("Test.txt", "Hello world");
uiGit.add("Test.txt");
PersonIdent author = new PersonIdent("author", "[email protected]");
String message = "Initial commit";
replacedertTrue(uiGit.hreplacedtagedFiles());
uiGit.commit(author.toExternalString(), message);
String commitId = uiGit.getCommitId(Constants.HEAD);
replacedertTrue(uiGit.isClean());
replacedertTrue(author.toExternalString().contains(uiGit.getAuthorName(commitId)));
replacedertEquals(message, uiGit.getCommitMessage(commitId));
}
18
Source : UIGit.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public boolean rollback(String name) {
if (hasUncommittedChanges()) {
showMessageBox(BaseMessages.getString(PKG, "Dialog.Error"), BaseMessages.getString(PKG, "Git.Dialog.UncommittedChanges.Message"));
return false;
}
String commit = resolve(Constants.HEAD).getName();
RevertCommand cmd = git.revert();
for (int i = 0; i < getRevisions().size(); i++) {
String commitId = getRevisions().get(i).getRevisionId();
/*
* Revert commits from HEAD to the specified commit in reverse order.
*/
cmd.include(resolve(commitId));
if (commitId.equals(name)) {
break;
}
}
try {
cmd.call();
git.reset().setRef(commit).call();
return true;
} catch (Exception e) {
showMessageBox(BaseMessages.getString(PKG, "Dialog.Error"), e.getMessage());
}
return false;
}
18
Source : UIGit.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public String getBranch() {
try {
Ref head = git.getRepository().exactRef(Constants.HEAD);
String branch = git.getRepository().getBranch();
if (head.getLeaf().getName().equals(Constants.HEAD)) {
// if detached
return Constants.HEAD + " detached at " + branch.substring(0, 7);
} else {
return branch;
}
} catch (Exception e) {
return "";
}
}
18
Source : UIGit.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public void revertPath(String path) throws HopException {
try {
// Revert files to HEAD state
Status status = git.status().addPath(path).call();
if (status.getUntracked().size() != 0 || status.getAdded().size() != 0) {
resetPath(path);
org.apache.commons.io.FileUtils.deleteQuietly(new File(directory, path));
}
/*
* This is a work-around to discard changes of conflicting files
* Git CLI `git checkout -- conflicted.txt` discards the changes, but jgit does not
*/
git.add().addFilepattern(path).call();
git.checkout().setStartPoint(Constants.HEAD).addPath(path).call();
org.apache.commons.io.FileUtils.deleteQuietly(new File(directory, path + ".ours"));
org.apache.commons.io.FileUtils.deleteQuietly(new File(directory, path + ".theirs"));
} catch (Exception e) {
throw new HopException("Git: error reverting path '" + path + "'", e);
}
}
17
Source : GitHeadModifier.java
with MIT License
from scm-manager
with MIT License
from scm-manager
private String resolve(org.eclipse.jgit.lib.Repository gitRepository) throws IOException {
Ref ref = gitRepository.getRefDatabase().getRef(Constants.HEAD);
if (ref.isSymbolic()) {
ref = ref.getTarget();
}
return GitUtil.getBranch(ref);
}
17
Source : LogServlet.java
with Apache License 2.0
from google
with Apache License 2.0
from google
private static GitilesView getView(HttpServletRequest req, Repository repo) throws IOException {
GitilesView view = ViewFilter.getView(req);
if (!Revision.isNull(view.getRevision())) {
return view;
}
Ref headRef = repo.exactRef(Constants.HEAD);
if (headRef == null) {
return null;
}
try (RevWalk walk = new RevWalk(repo)) {
return GitilesView.log().copyFrom(view).setRevision(Revision.peel(Constants.HEAD, walk.parseAny(headRef.getObjectId()), walk)).build();
}
}
17
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();
}
}
17
Source : CurioGenericCiPlugin.java
with MIT License
from curioswitch
with MIT License
from curioswitch
private static Set<String> computeAffectedFilesForBranch(Git git, String branch, Project rootProject) throws IOException {
String masterRemote = git.getRepository().getRemoteNames().contains("upstream") ? "upstream" : "origin";
CanonicalTreeParser oldTreeParser = parserForBranch(git, git.getRepository().exactRef("refs/remotes/" + masterRemote + "/master"));
CanonicalTreeParser newTreeParser = parserForBranch(git, git.getRepository().exactRef(Constants.HEAD));
return computeAffectedFiles(git, oldTreeParser, newTreeParser, rootProject);
}
17
Source : CatTest.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public void testCatRemoved() throws Exception {
File f = new File(workDir, "removed");
copyFile(getGoldenFile(), f);
replacedertFile(getGoldenFile(), f);
add(f);
commit(f);
GitClient client = getClient(workDir);
String revision = new Git(repository).log().call().iterator().next().getId().getName();
// remove and commit
client.remove(new File[] { f }, false, NULL_PROGRESS_MONITOR);
commit(f);
replacedertTrue(client.catFile(f, revision, new FileOutputStream(f), NULL_PROGRESS_MONITOR));
replacedertFile(f, getGoldenFile());
replacedertFalse(client.catFile(f, Constants.HEAD, new FileOutputStream(f), NULL_PROGRESS_MONITOR));
}
17
Source : Utils.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
/**
* Transforms references into GitBranches
* @param allRefs all references found
* @param prefix prefix denoting heads amongst references
* @return
*/
public static Map<String, GitBranch> refsToBranches(Collection<Ref> allRefs, String prefix, GitClreplacedFactory factory) {
Map<String, GitBranch> branches = new LinkedHashMap<String, GitBranch>();
// try to find the head first - it usually is the active remote branch
Ref head = null;
for (final Ref ref : allRefs) {
if (ref.getLeaf().getName().equals(Constants.HEAD)) {
head = ref;
break;
}
}
// get all refs/heads
for (final Ref ref : RefComparator.sort(allRefs)) {
String refName = ref.getLeaf().getName();
if (refName.startsWith(prefix)) {
String name = refName.substring(prefix.length());
ObjectId id = ref.getLeaf().getObjectId();
if (id == null) {
// can happen, e.g. when the repository has no HEAD yet
// NOI18N
Logger.getLogger(Utils.clreplaced.getName()).log(// NOI18N
Level.INFO, // NOI18N
"Null object id for ref: {0}, {1}:{2}, {3}", new Object[] { ref.toString(), ref.getName(), ref.getObjectId(), ref.getLeaf() });
continue;
}
branches.put(name, factory.createBranch(name, false, head != null && ref.getObjectId().equals(head.getObjectId()), id));
}
}
return branches;
}
17
Source : StatusCommand.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
@Override
protected String getCommandDescription() {
// NOI18N
StringBuilder sb = new StringBuilder("git ");
if (Constants.HEAD.equals(revision)) {
// NOI18N
sb.append("status");
} else {
// NOI18N
sb.append("diff --raw");
}
for (File root : roots) {
sb.append(" ").append(root.getAbsolutePath());
}
return sb.toString();
}
17
Source : UIGit.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private boolean mergeBranch(String value, String mergeStrategy) throws HopException {
try {
ObjectId obj = git.getRepository().resolve(value);
MergeResult result = git.merge().include(obj).setStrategy(MergeStrategy.get(mergeStrategy)).call();
if (result.getMergeStatus().isSuccessful()) {
return true;
} else {
// TODO: get rid of message box
//
showMessageBox(BaseMessages.getString(PKG, "Dialog.Error"), result.getMergeStatus().toString());
if (result.getMergeStatus() == MergeStatus.CONFLICTING) {
Map<String, int[][]> conflicts = result.getConflicts();
for (String path : conflicts.keySet()) {
checkout(path, Constants.HEAD, ".ours");
checkout(path, getExpandedName(value, VCS.TYPE_BRANCH), ".theirs");
}
return true;
}
}
return false;
} catch (Exception e) {
throw new HopException("Error merging branch '" + value + "' with strategy '" + mergeStrategy + "'", e);
}
}
16
Source : GitCoreRepository.java
with MIT License
from VirtusLab
with MIT License
from VirtusLab
@Override
public IGitCoreHeadSnapshot deriveHead() throws GitCoreException {
Ref ref = Try.of(() -> jgitRepo.getRefDatabase().findRef(Constants.HEAD)).getOrElseThrow(e -> new GitCoreException("Cannot get current branch", e));
if (ref == null) {
throw new GitCoreException("Error occurred while getting current branch ref");
}
val reflog = deriveReflogByRefFullName(Constants.HEAD);
String currentBranchName = null;
if (ref.isSymbolic()) {
currentBranchName = Repository.shortenRefName(ref.getTarget().getName());
} else {
Option<Path> headNamePath = Stream.of("rebase-apply", "rebase-merge").map(dir -> jgitRepo.getDirectory().toPath().resolve(dir).resolve("head-name")).find(path -> path.toFile().isFile());
if (headNamePath.isDefined()) {
currentBranchName = Try.of(() -> Stream.ofAll(Files.readAllLines(headNamePath.get()))).getOrElseThrow(e -> new GitCoreException("Error occurred while getting current branch ref", e)).headOption().map(Repository::shortenRefName).getOrNull();
}
}
IGitCoreLocalBranchSnapshot targetBranch;
if (currentBranchName != null) {
targetBranch = deriveLocalBranchByName(currentBranchName).getOrNull();
} else {
targetBranch = null;
}
return new GitCoreHeadSnapshot(targetBranch, reflog);
}
16
Source : RefServlet.java
with Apache License 2.0
from google
with Apache License 2.0
from google
static List<Map<String, Object>> getBranchesSoyData(HttpServletRequest req, int limit) throws IOException {
RefDatabase refdb = ServletUtils.getRepository(req).getRefDatabase();
Ref head = refdb.exactRef(Constants.HEAD);
Ref headLeaf = head != null && head.isSymbolic() ? head.getLeaf() : null;
return getRefsSoyData(refdb, ViewFilter.getView(req), Constants.R_HEADS, branchComparator(headLeaf), headLeaf, limit);
}
16
Source : GitilesView.java
with Apache License 2.0
from google
with Apache License 2.0
from google
/**
* @param hreplacedingleTree list of booleans, one per path entry in this view's path excluding the
* leaf. True entries indicate the tree at that path only has a single entry that is another
* tree.
* @return a list of maps with "text" and "url" keys for all file paths leading up to the path
* represented by this view. URLs whose corresponding entry in {@code hreplacedingleTree} is true
* will disable auto-diving into one-entry subtrees.
*/
public List<Map<String, String>> getBreadcrumbs(List<Boolean> hreplacedingleTree) {
checkArgument(!NON_HTML_TYPES.contains(type), "breadcrumbs for %s view not supported", type);
checkArgument(type != Type.REFS || Strings.isNullOrEmpty(path), "breadcrumbs for REFS view with path not supported");
checkArgument(hreplacedingleTree == null || type == Type.PATH, "hreplacedingleTree must be null for %s view", type);
String path = this.path;
ImmutableList.Builder<Map<String, String>> breadcrumbs = ImmutableList.builder();
breadcrumbs.add(breadcrumb(hostName, hostIndex().copyFrom(this).setRepositoryPrefix(null)));
if (repositoryPrefix != null) {
breadcrumbs.addAll(hostIndexBreadcrumbs(repositoryPrefix));
} else if (repositoryName != null) {
breadcrumbs.addAll(hostIndexBreadcrumbs(repositoryName));
}
if (type == Type.DIFF) {
// TODO(dborowitz): Tweak the breadcrumbs template to allow us to render
// separate links in "old..new".
breadcrumbs.add(breadcrumb(getRevisionRange(), diff().copyFrom(this).setPathPart("")));
} else if (type == Type.LOG) {
if (!Revision.isNull(revision)) {
// TODO(dborowitz): Add something in the navigation area (probably not
// a breadcrumb) to allow switching between /+log/ and /+/.
if (Revision.isNull(oldRevision)) {
breadcrumbs.add(breadcrumb(revision.getName(), log().copyFrom(this).setPathPart(null)));
} else {
breadcrumbs.add(breadcrumb(getRevisionRange(), log().copyFrom(this).setPathPart(null)));
}
} else {
breadcrumbs.add(breadcrumb(Constants.HEAD, log().copyFrom(this)));
}
path = Strings.emptyToNull(path);
} else if (!Revision.isNull(revision)) {
breadcrumbs.add(breadcrumb(revision.getName(), revision().copyFrom(this)));
}
if (path != null) {
if (type != Type.LOG && type != Type.REFS) {
// The "." breadcrumb would be no different for LOG or REFS.
breadcrumbs.add(breadcrumb(".", copyWithPath(false).setPathPart("")));
}
StringBuilder cur = new StringBuilder();
List<String> parts = PathUtil.SPLITTER.omitEmptyStrings().splitToList(path);
checkArgument(hreplacedingleTree == null || (parts.isEmpty() && hreplacedingleTree.isEmpty()) || hreplacedingleTree.size() == parts.size() - 1, "hreplacedingleTree has wrong number of entries");
for (int i = 0; i < parts.size(); i++) {
String part = parts.get(i);
cur.append(part).append('/');
String curPath = cur.toString();
boolean isLeaf = i == parts.size() - 1;
Builder builder = copyWithPath(isLeaf).setPathPart(curPath);
if (hreplacedingleTree != null && i < parts.size() - 1 && hreplacedingleTree.get(i)) {
builder.replaceParam(PathServlet.AUTODIVE_PARAM, PathServlet.NO_AUTODIVE_VALUE);
}
breadcrumbs.add(breadcrumb(part, builder));
}
}
return breadcrumbs.build();
}
16
Source : RemoteBranch.java
with Eclipse Public License 1.0
from eclipse
with Eclipse Public License 1.0
from eclipse
@PropertyDescription(name = GitConstants.KEY_HEAD)
private URI getHeadLocation() throws IOException, URISyntaxException {
return BaseToCommitConverter.getCommitLocation(cloneLocation, Constants.HEAD, BaseToCommitConverter.REMOVE_FIRST_2);
}
16
Source : Clone.java
with Eclipse Public License 1.0
from eclipse
with Eclipse Public License 1.0
from eclipse
// TODO: expandable?
@PropertyDescription(name = GitConstants.KEY_HEAD)
private URI getHeadLocation() throws URISyntaxException {
IPath np = new Path(GitServlet.GIT_URI).append(Commit.RESOURCE).append(Constants.HEAD).append(getId());
return createUriWithPath(np);
}
16
Source : Branch.java
with Eclipse Public License 1.0
from eclipse
with Eclipse Public License 1.0
from eclipse
// TODO: expandable
@PropertyDescription(name = GitConstants.KEY_HEAD)
private URI getHeadLocation() throws IOException, URISyntaxException {
return BaseToCommitConverter.getCommitLocation(cloneLocation, Constants.HEAD, BaseToCommitConverter.REMOVE_FIRST_2);
}
16
Source : CheckoutTest.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
private void checkoutJGitTestNestedAddedRoot(Repository repository, String revision) throws Exception {
try {
ObjectId headTree = Utils.findCommit(repository, Constants.HEAD).getTree();
DirCache cache = repository.lockDirCache();
DirCacheCheckout dco = null;
RevCommit commit;
try {
commit = Utils.findCommit(repository, revision);
dco = new DirCacheCheckout(repository, headTree, cache, commit.getTree());
dco.setFailOnConflict(true);
dco.checkout();
} catch (CheckoutConflictException ex) {
List<String> conflicts = dco.getConflicts();
throw new GitException.CheckoutConflictException(conflicts.toArray(new String[conflicts.size()]));
} finally {
cache.unlock();
}
} catch (IOException ex) {
throw new GitException(ex);
}
}
16
Source : CatTest.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public void testCat() throws Exception {
File folder = new File(workDir, "folder");
folder.mkdirs();
File f = new File(folder, "testcat1");
copyFile(getGoldenFile(), f);
replacedertFile(getGoldenFile(), f);
add(f);
GitClient client = getClient(workDir);
try {
client.catFile(f, Constants.HEAD, new FileOutputStream(f), NULL_PROGRESS_MONITOR);
fail();
} catch (GitException.MissingObjectException ex) {
replacedertEquals(GitObjectType.COMMIT, ex.getObjectType());
replacedertEquals(Constants.HEAD, ex.getObjectName());
}
commit(f);
replacedertTrue(client.catFile(f, Constants.HEAD, new FileOutputStream(f), NULL_PROGRESS_MONITOR));
replacedertFile(f, getGoldenFile());
String revision = new Git(repository).log().call().iterator().next().getId().getName();
replacedertTrue(client.catFile(f, revision, new FileOutputStream(f), NULL_PROGRESS_MONITOR));
replacedertFile(f, getGoldenFile());
write(f, "blablabla");
add(f);
commit(f);
replacedertTrue(client.catFile(f, revision, new FileOutputStream(f), NULL_PROGRESS_MONITOR));
replacedertFile(f, getGoldenFile());
}
16
Source : ListBranchCommand.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
@Override
protected void run() throws GitException {
Repository repository = getRepository();
Map<String, Ref> refs;
try {
refs = repository.getAllRefs();
} catch (IllegalArgumentException ex) {
// NOI18N
throw new GitException("Corrupted repository metadata at " + repository.getWorkTree().getAbsolutePath(), ex);
}
Ref head = refs.get(Constants.HEAD);
branches = new LinkedHashMap<String, GitBranch>();
Config cfg = repository.getConfig();
if (head != null) {
String current = head.getLeaf().getName();
if (current.equals(Constants.HEAD)) {
String name = GitBranch.NO_BRANCH;
branches.put(name, getClreplacedFactory().createBranch(name, false, true, head.getLeaf().getObjectId()));
}
branches.putAll(getRefs(refs.values(), Constants.R_HEADS, false, current, cfg));
}
Map<String, GitBranch> allBranches = getRefs(refs.values(), Constants.R_REMOTES, true, null, cfg);
allBranches.putAll(branches);
setupTracking(branches, allBranches, repository.getConfig());
if (all) {
branches.putAll(allBranches);
}
}
16
Source : CheckoutRevisionCommand.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 headRef = repository.findRef(Constants.HEAD);
if (headRef == null) {
throw new GitException("Corrupted repository, missing HEAD file in .git folder.");
}
ObjectId headTree = null;
try {
headTree = Utils.findCommit(repository, Constants.HEAD).getTree();
} catch (GitException.MissingObjectException ex) {
}
Ref ref = repository.findRef(revision);
if (ref != null && !ref.getName().startsWith(Constants.R_HEADS) && !ref.getName().startsWith(Constants.R_REMOTES)) {
ref = null;
}
String fromName = headRef.getTarget().getName();
if (fromName.startsWith(Constants.R_HEADS)) {
fromName = fromName.substring(Constants.R_HEADS.length());
}
// NOI18N
String refLogMessage = "checkout: moving from " + fromName;
cache = repository.lockDirCache();
DirCacheCheckout dco = null;
RevCommit commit = null;
try {
commit = Utils.findCommit(repository, revision);
dco = headTree == null ? new DirCacheCheckout(repository, cache, commit.getTree()) : new DirCacheCheckout(repository, headTree, cache, commit.getTree());
// JGit WA
if (!failOnConflict) {
dco.preScanTwoTrees();
cacheContents(dco.getConflicts());
dco = headTree == null ? new DirCacheCheckout(repository, cache, commit.getTree()) : new DirCacheCheckout(repository, headTree, cache, commit.getTree());
}
// End of JGit WA
dco.setFailOnConflict(failOnConflict);
dco.checkout();
cache.lock();
File workDir = repository.getWorkTree();
notify(workDir, dco.getRemoved());
notify(workDir, dco.getConflicts());
notify(workDir, dco.getUpdated().keySet());
// JGit WA
if (!failOnConflict && dco.getConflicts().size() > 0) {
mergeConflicts(dco.getConflicts(), cache);
}
// End of JGit WA
} catch (org.eclipse.jgit.dircache.InvalidPathException ex) {
throw new GitException("Commit " + commit.name() + " cannot be checked out because an invalid file name in one of the files.\n" + "Please remove the file from repository with an external tool and try again.\n\n" + ex.getMessage());
} catch (CheckoutConflictException ex) {
List<String> conflicts = dco.getConflicts();
throw new GitException.CheckoutConflictException(conflicts.toArray(new String[conflicts.size()]), ex);
} finally {
cache.unlock();
}
if (!monitor.isCanceled()) {
String toName;
boolean detach = true;
if (ref == null) {
toName = commit.getName();
} else {
toName = ref.getName();
if (toName.startsWith(Constants.R_HEADS)) {
detach = false;
toName = toName.substring(Constants.R_HEADS.length());
} else if (toName.startsWith(Constants.R_REMOTES)) {
toName = toName.substring(Constants.R_REMOTES.length());
}
}
RefUpdate refUpdate = repository.updateRef(Constants.HEAD, detach);
refUpdate.setForceUpdate(false);
// NOI18N
refUpdate.setRefLogMessage(refLogMessage + " to " + toName, false);
RefUpdate.Result updateResult;
if (!detach)
updateResult = refUpdate.link(ref.getName());
else {
refUpdate.setNewObjectId(commit);
updateResult = refUpdate.forceUpdate();
}
boolean ok = false;
switch(updateResult) {
case NEW:
ok = true;
break;
case NO_CHANGE:
case FAST_FORWARD:
case FORCED:
ok = true;
break;
default:
break;
}
if (!ok) {
throw new GitException("Unexpected result: " + updateResult.name());
}
}
} catch (IOException ex) {
throw new GitException(ex);
}
}
15
Source : GitRepo.java
with Apache License 2.0
from spring-cloud
with Apache License 2.0
from spring-cloud
/**
* Look for a tag with the given name, and if not found looks for a branch.
*/
private Optional<Ref> findTagOrBranchHeadRevision(Git git, String tagOrBranch) throws GitAPIException, IOException {
if (tagOrBranch.equals("HEAD")) {
return Optional.of(git.getRepository().exactRef(Constants.HEAD).getTarget());
}
final Optional<Ref> tag = git.tagList().call().stream().filter(ref -> ref.getName().equals("refs/tags/" + tagOrBranch)).findFirst();
if (tag.isPresent()) {
return tag;
}
return git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call().stream().filter(ref -> ref.getName().equals("refs/heads/" + tagOrBranch)).findFirst();
}
15
Source : CommitCollector.java
with MIT License
from jenkinsci
with MIT License
from jenkinsci
List<RevCommit> findAllCommits(final Repository repository, final Git git, final String latestCommitId, final FilteredLog logger) throws IOException, GitAPIException {
ObjectId head = repository.resolve(Constants.HEAD);
if (head == null) {
logger.logError("No HEAD commit found in " + repository);
return Collections.emptyList();
}
Iterator<RevCommit> commits = git.log().add(head).call().iterator();
return StreamEx.of(commits).takeWhile(commit -> !latestCommitId.equals(commit.getName())).toList();
}
15
Source : GitUtil.java
with Apache License 2.0
from exactpro
with Apache License 2.0
from exactpro
public static List<Chunk> getConflicts(CredentialBean bean, String fileName) throws Exception {
try (Git git = git(bean)) {
Repository repo = git.getRepository();
ThreeWayMerger merger = new StrategyResolve().newMerger(repo, true);
merger.merge(repo.resolve(Constants.HEAD), repo.resolve(Constants.FETCH_HEAD));
ResolveMerger resolveMerger = (ResolveMerger) merger;
Map<String, org.eclipse.jgit.merge.MergeResult<?>> mergeResults = resolveMerger.getMergeResults();
org.eclipse.jgit.merge.MergeResult<?> mergeChunks = mergeResults.get(fileName);
if (mergeChunks == null) {
return null;
}
if (!mergeChunks.containsConflicts()) {
return null;
}
List<Chunk> lines = new ArrayList<>();
for (MergeChunk mergeChunk : mergeChunks) {
MergeChunk.ConflictState conflictState = mergeChunk.getConflictState();
switch(conflictState) {
case NO_CONFLICT:
lines.add(new Chunk(false, mergeChunk.getBegin(), mergeChunk.getEnd(), null));
break;
case FIRST_CONFLICTING_RANGE:
lines.add(new Chunk(true, mergeChunk.getBegin(), mergeChunk.getEnd(), Chunk.ChunkState.Your));
break;
case NEXT_CONFLICTING_RANGE:
lines.add(new Chunk(true, mergeChunk.getBegin(), mergeChunk.getEnd(), Chunk.ChunkState.Their));
break;
}
}
return lines;
}
}
15
Source : StashApplyCommand.java
with Eclipse Public License 1.0
from eclipse
with Eclipse Public License 1.0
from eclipse
/**
* Apply the changes in a stashed commit to the working directory and index
*
* @return id of stashed commit that was applied TODO: Does anyone depend on this, or could we make it more like Merge/CherryPick/Revert?
* @throws GitAPIException
* @throws WrongRepositoryStateException
* @throws NoHeadException
* @throws StashApplyFailureException
*/
@Override
public ObjectId call() throws GitAPIException, WrongRepositoryStateException, NoHeadException, StashApplyFailureException {
checkCallable();
if (!ignoreRepositoryState && repo.getRepositoryState() != RepositoryState.SAFE)
throw new WrongRepositoryStateException(MessageFormat.format(JGitText.get().stashApplyOnUnsafeRepository, repo.getRepositoryState()));
ObjectReader reader = repo.newObjectReader();
try {
RevWalk revWalk = new RevWalk(reader);
ObjectId headCommit = repo.resolve(Constants.HEAD);
if (headCommit == null)
throw new NoHeadException(JGitText.get().stashApplyWithoutHead);
final ObjectId stashId = getStashId();
RevCommit stashCommit = revWalk.parseCommit(stashId);
if (stashCommit.getParentCount() < 2 || stashCommit.getParentCount() > 3)
throw new JGitInternalException(MessageFormat.format(JGitText.get().stashCommitIncorrectNumberOfParents, stashId.name(), Integer.valueOf(stashCommit.getParentCount())));
// $NON-NLS-1$
ObjectId headTree = repo.resolve(Constants.HEAD + "^{tree}");
ObjectId stashIndexCommit = revWalk.parseCommit(stashCommit.getParent(1));
ObjectId stashHeadCommit = stashCommit.getParent(0);
ObjectId untrackedCommit = null;
if (applyUntracked && stashCommit.getParentCount() == 3)
untrackedCommit = revWalk.parseCommit(stashCommit.getParent(2));
ResolveMerger merger = (ResolveMerger) strategy.newMerger(repo);
merger.setCommitNames(new String[] { "stashed HEAD", "HEAD", "stash" });
merger.setBase(stashHeadCommit);
merger.setWorkingTreeIterator(new FileTreeIterator(repo));
if (merger.merge(headCommit, stashCommit)) {
DirCache dc = repo.lockDirCache();
DirCacheCheckout dco = new DirCacheCheckout(repo, headTree, dc, merger.getResultTreeId());
dco.setFailOnConflict(true);
// Ignoring failed deletes....
dco.checkout();
if (applyIndex) {
ResolveMerger ixMerger = (ResolveMerger) strategy.newMerger(repo, true);
ixMerger.setCommitNames(new String[] { "stashed HEAD", "HEAD", "stashed index" });
ixMerger.setBase(stashHeadCommit);
boolean ok = ixMerger.merge(headCommit, stashIndexCommit);
if (ok) {
resetIndex(revWalk.parseTree(ixMerger.getResultTreeId()));
} else {
throw new StashApplyFailureException(JGitText.get().stashApplyConflict);
}
}
if (untrackedCommit != null) {
ResolveMerger untrackedMerger = (ResolveMerger) strategy.newMerger(repo, true);
// $NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
untrackedMerger.setCommitNames(new String[] { "stashed HEAD", "HEAD", "untracked files" });
untrackedMerger.setBase(stashHeadCommit);
boolean ok = untrackedMerger.merge(stashHeadCommit, untrackedCommit);
if (ok)
try {
RevTree untrackedTree = revWalk.parseTree(untrackedMerger.getResultTreeId());
resetUntracked(untrackedTree);
} catch (CheckoutConflictException e) {
throw new StashApplyFailureException(JGitText.get().stashApplyConflict);
}
else
throw new StashApplyFailureException(JGitText.get().stashApplyConflict);
}
} else {
throw new StashApplyFailureException(JGitText.get().stashApplyConflict);
}
return stashId;
} catch (JGitInternalException e) {
throw e;
} catch (IOException e) {
throw new JGitInternalException(JGitText.get().stashApplyFailed, e);
} finally {
reader.close();
}
}
14
Source : ShGitProvider.java
with GNU General Public License v3.0
from ShioCMS
with GNU General Public License v3.0
from ShioCMS
public synchronized String get(String revId) throws IOException {
RevCommit stash = null;
String shObjectFileName = "<<DEFINE>>";
try {
List<DiffEntry> gitDiff = git.diff().setPathFilter(PathFilter.create(shObjectFileName)).call();
boolean modified = !gitDiff.isEmpty();
if (modified) {
stash = git.stashCreate().call();
Collection<RevCommit> stashes = git.stashList().call();
logger.debug("Created stash : {}, stash size : {}", stash, stashes.size());
}
ObjectId head = git.getRepository().resolve(Constants.HEAD);
git.checkout().setStartPoint(revId).addPath(shObjectFileName).call();
git.checkout().setStartPoint(head.getName()).addPath(shObjectFileName).call();
if (modified && stash != null) {
ObjectId applied = git.stashApply().setStashRef(stash.getName()).call();
ObjectId dropped = git.stashDrop().setStashRef(0).call();
Collection<RevCommit> stashes = git.stashList().call();
logger.debug("Stash applied as : {}, and dropped : {}, stash size: {}", applied, dropped, stashes.size());
}
} catch (GitAPIException e) {
logger.error("Failed to return shObject from revision \"{}\"", revId, e);
}
return null;
}
14
Source : GitDiffTest.java
with Eclipse Public License 1.0
from eclipse
with Eclipse Public License 1.0
from eclipse
@Test
public void testDiffPost() throws Exception {
createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME);
String projectName = getMethodName().concat("Project");
JSONObject project = createProjectOrLink(workspaceLocation, projectName, gitDir.toString());
JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
JSONObject testTxt = getChild(project, "test.txt");
modifyFile(testTxt, "change");
addFile(testTxt);
commitFile(testTxt, "commit1", false);
String testTxtHeadLocation = testTxt.getJSONObject(GitConstants.KEY_GIT).getString(GitConstants.KEY_HEAD);
JSONObject testTxtInitialCommit = findCommitByMessage(testTxtHeadLocation, "Initial commit");
String location = getDiffLocation(testTxtInitialCommit.getString(GitConstants.KEY_DIFF), Constants.HEAD);
String diffScope = URLEncoder.encode(testTxtInitialCommit.getString(ProtocolConstants.KEY_NAME) + ".." + Constants.HEAD, "UTF-8");
String expectedLocation = gitSection.getString(GitConstants.KEY_DIFF).replaceAll(GitConstants.KEY_DIFF_DEFAULT, diffScope);
expectedLocation += "test.txt";
replacedertEquals(expectedLocation, location);
WebRequest request = getGetRequest(location);
WebResponse response = webConversation.getResponse(request);
replacedertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
String[] parts = parseMultiPartResponse(response);
replacedertDiffUris(expectedLocation, new String[] { "test", "change", "test" }, new JSONObject(parts[0]));
StringBuilder sb = new StringBuilder();
sb.append("diff --git a/test.txt b/test.txt").append("\n");
sb.append("index 30d74d2..8013df8 100644").append("\n");
sb.append("--- a/test.txt").append("\n");
sb.append("+++ b/test.txt").append("\n");
sb.append("@@ -1 +1 @@").append("\n");
sb.append("-test").append("\n");
sb.append("\\ No newline at end of file").append("\n");
sb.append("+change").append("\n");
sb.append("\\ No newline at end of file").append("\n");
replacedertEquals(sb.toString(), parts[1]);
}
14
Source : GitBranchTest.java
with Eclipse Public License 1.0
from eclipse
with Eclipse Public License 1.0
from eclipse
@Test
public void testCheckoutAmbiguousName() throws Exception {
createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME);
IPath[] clonePaths = createTestProjects(workspaceLocation);
for (IPath clonePath : clonePaths) {
// clone a repo
JSONObject clone = clone(clonePath);
String cloneLocation = clone.getString(ProtocolConstants.KEY_LOCATION);
String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);
String branchesLocation = clone.getString(GitConstants.KEY_BRANCH);
// get project/folder metadata
WebRequest request = getGetRequest(cloneContentLocation);
WebResponse response = webConversation.getResponse(request);
replacedertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
JSONObject folder = new JSONObject(response.getText());
JSONObject testTxt = getChild(folder, "test.txt");
modifyFile(testTxt, "tagged");
addFile(testTxt);
commitFile(testTxt, "tagged", false);
// tag HEAD with 'tag'
JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT);
String gitTagUri = gitSection.getString(GitConstants.KEY_TAG);
tag(gitTagUri, "tag", Constants.HEAD);
modifyFile(testTxt, "branched");
addFile(testTxt);
commitFile(testTxt, "branched", false);
// use the same name for the new branch
branch(branchesLocation, "tag");
modifyFile(testTxt, "head");
addFile(testTxt);
commitFile(testTxt, "head", false);
// checkout branch
response = checkoutBranch(cloneLocation, "tag");
replacedertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
replacedertEquals("branched", getFileContent(testTxt));
// checkout tag
response = checkoutTag(cloneLocation, "tag");
replacedertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
replacedertEquals("tagged", getFileContent(testTxt));
}
}
14
Source : CompareCommitTest.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public void testCompareRevertModification() throws Exception {
File file = new File(workDir, "file");
File[] files = new File[] { file };
write(file, "init\n");
add(files);
commit(files);
GitClient client = getClient(workDir);
String revision1 = client.getBranches(false, NULL_PROGRESS_MONITOR).get(Constants.MASTER).getId();
write(file, "modification\n");
add(files);
GitRevisionInfo revision2 = client.commit(files, "my commit message", null, null, NULL_PROGRESS_MONITOR);
write(file, "init\n");
add(files);
GitRevisionInfo revision3 = client.commit(files, "my commit 3 message", null, null, NULL_PROGRESS_MONITOR);
Map<File, GitRevisionInfo.GitFileInfo> statuses = client.getStatus(files, revision1, Constants.HEAD, NULL_PROGRESS_MONITOR);
replacedertTrue(statuses.isEmpty());
}
13
Source : GitMergeTest.java
with Eclipse Public License 1.0
from eclipse
with Eclipse Public License 1.0
from eclipse
@Test
public void testMergeIntoLocalFailedDirtyWorkTree() throws Exception {
// clone a repo
createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME);
String workspaceId = workspaceIdFromLocation(workspaceLocation);
JSONObject project = createProjectOrLink(workspaceLocation, getMethodName().concat("Project"), null);
IPath clonePath = getClonePath(workspaceId, project);
clone(clonePath);
// get project metadata
WebRequest request = getGetRequest(project.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
WebResponse response = webConversation.getResponse(request);
replacedertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
project = new JSONObject(response.getText());
JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);
String gitRemoteUri = gitSection.getString(GitConstants.KEY_REMOTE);
// add a parallel commit in secondary clone and push it to the remote
JSONObject project2 = createProjectOrLink(workspaceLocation, getMethodName().concat("Project2"), null);
IPath clonePath2 = getClonePath(workspaceId, project2);
clone(clonePath2);
// get project2 metadata
request = getGetRequest(project2.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
response = webConversation.getResponse(request);
replacedertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
project2 = new JSONObject(response.getText());
JSONObject gitSection2 = project2.getJSONObject(GitConstants.KEY_GIT);
String gitRemoteUri2 = gitSection2.getString(GitConstants.KEY_REMOTE);
JSONObject testTxt = getChild(project2, "test.txt");
modifyFile(testTxt, "change in secondary");
addFile(testTxt);
commitFile(testTxt, "commit on branch", false);
ServerStatus pushStatus = push(gitRemoteUri2, 1, 0, Constants.MASTER, Constants.HEAD, false);
replacedertEquals(true, pushStatus.isOK());
// modify on master and try to merge
testTxt = getChild(project, "test.txt");
modifyFile(testTxt, "dirty");
JSONObject masterDetails = getRemoteBranch(gitRemoteUri, 1, 0, Constants.MASTER);
String masterLocation = masterDetails.getString(ProtocolConstants.KEY_LOCATION);
fetch(masterLocation);
JSONObject merge = merge(gitHeadUri, Constants.DEFAULT_REMOTE_NAME + "/" + Constants.MASTER);
MergeStatus mergeResult = MergeStatus.valueOf(merge.getString(GitConstants.KEY_RESULT));
replacedertEquals(MergeStatus.FAILED, mergeResult);
JSONObject failingPaths = merge.getJSONObject(GitConstants.KEY_FAILING_PATHS);
replacedertEquals(1, failingPaths.length());
replacedertEquals(MergeFailureReason.DIRTY_WORKTREE, MergeFailureReason.valueOf(failingPaths.getString("test.txt")));
}
13
Source : GitMergeSquashTest.java
with Eclipse Public License 1.0
from eclipse
with Eclipse Public License 1.0
from eclipse
@Test
public void testMergeSquashIntoLocalFailedDirtyWorkTree() throws Exception {
// clone a repo
createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME);
String workspaceId = workspaceIdFromLocation(workspaceLocation);
JSONObject project = createProjectOrLink(workspaceLocation, getMethodName().concat("Project"), null);
IPath clonePath = getClonePath(workspaceId, project);
clone(clonePath);
// get project metadata
WebRequest request = getGetRequest(project.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
WebResponse response = webConversation.getResponse(request);
replacedertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
project = new JSONObject(response.getText());
JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);
String gitRemoteUri = gitSection.getString(GitConstants.KEY_REMOTE);
// add a parallel commit in secondary clone and push it to the remote
JSONObject project2 = createProjectOrLink(workspaceLocation, getMethodName().concat("Project2"), null);
IPath clonePath2 = getClonePath(workspaceId, project2);
clone(clonePath2);
// get project2 metadata
request = getGetRequest(project2.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
response = webConversation.getResponse(request);
replacedertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
project2 = new JSONObject(response.getText());
JSONObject gitSection2 = project2.getJSONObject(GitConstants.KEY_GIT);
String gitRemoteUri2 = gitSection2.getString(GitConstants.KEY_REMOTE);
JSONObject testTxt = getChild(project2, "test.txt");
modifyFile(testTxt, "change in secondary");
addFile(testTxt);
commitFile(testTxt, "commit on branch", false);
ServerStatus pushStatus = push(gitRemoteUri2, 1, 0, Constants.MASTER, Constants.HEAD, false);
replacedertEquals(true, pushStatus.isOK());
// modify on master and try to merge
testTxt = getChild(project, "test.txt");
modifyFile(testTxt, "dirty");
JSONObject masterDetails = getRemoteBranch(gitRemoteUri, 1, 0, Constants.MASTER);
String masterLocation = masterDetails.getString(ProtocolConstants.KEY_LOCATION);
fetch(masterLocation);
JSONObject merge = merge(gitHeadUri, Constants.DEFAULT_REMOTE_NAME + "/" + Constants.MASTER, true);
MergeStatus mergeResult = MergeStatus.valueOf(merge.getString(GitConstants.KEY_RESULT));
replacedertEquals(MergeStatus.FAILED, mergeResult);
JSONObject failingPaths = merge.getJSONObject(GitConstants.KEY_FAILING_PATHS);
replacedertEquals(1, failingPaths.length());
replacedertEquals(MergeFailureReason.DIRTY_WORKTREE, MergeFailureReason.valueOf(failingPaths.getString("test.txt")));
}
13
Source : GitLogTest.java
with Eclipse Public License 1.0
from eclipse
with Eclipse Public License 1.0
from eclipse
@Test
public void testLog() throws Exception {
createWorkspace(SimpleMetaStore.DEFAULT_WORKSPACE_NAME);
IPath[] clonePaths = createTestProjects(workspaceLocation);
for (IPath clonePath : clonePaths) {
// clone a repo
JSONObject clone = clone(clonePath);
String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);
// get project/folder metadata
WebRequest request = getGetRequest(cloneContentLocation);
WebResponse response = webConversation.getResponse(request);
replacedertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
JSONObject folder = new JSONObject(response.getText());
JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT);
String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);
// modify
JSONObject testTxt = getChild(folder, "test.txt");
modifyFile(testTxt, "first change");
addFile(testTxt);
// commit1
request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "commit1", false);
response = webConversation.getResponse(request);
replacedertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
// modify again
modifyFile(testTxt, "second change");
addFile(testTxt);
// commit2
request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "commit2", false);
response = webConversation.getResponse(request);
replacedertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
// get the full log
JSONArray commitsArray = log(gitHeadUri);
replacedertEquals(3, commitsArray.length());
JSONObject commit = commitsArray.getJSONObject(0);
replacedertEquals("commit2", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
commit = commitsArray.getJSONObject(1);
replacedertEquals("commit1", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
commit = commitsArray.getJSONObject(2);
replacedertEquals("Initial commit", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
String initialGitCommitName = commit.getString(ProtocolConstants.KEY_NAME);
String initialGitCommitURI = gitHeadUri.replaceAll(Constants.HEAD, initialGitCommitName);
// get log for given page size
commitsArray = log(gitHeadUri, 1, 1, false, true);
replacedertEquals(1, commitsArray.length());
commit = commitsArray.getJSONObject(0);
replacedertEquals("commit2", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
// get log for second page
commitsArray = log(gitHeadUri, 2, 1, true, true);
replacedertEquals(1, commitsArray.length());
commit = commitsArray.getJSONObject(0);
replacedertEquals("commit1", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
// prepare a scoped log location
request = getPostForScopedLogRequest(initialGitCommitURI, Constants.HEAD);
response = webConversation.getResponse(request);
replacedertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
String newGitCommitUri = response.getHeaderField(ProtocolConstants.KEY_LOCATION);
replacedertEquals(newGitCommitUri, new JSONObject(response.getText()).getString(ProtocolConstants.KEY_LOCATION));
// get a scoped log
commitsArray = log(newGitCommitUri);
replacedertEquals(2, commitsArray.length());
commit = commitsArray.getJSONObject(0);
replacedertEquals("commit2", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
commit = commitsArray.getJSONObject(1);
replacedertEquals("commit1", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
}
}
13
Source : CompareCommitTest.java
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public void testCompareSimple() throws Exception {
File file = new File(workDir, "file");
File[] files = new File[] { file };
write(file, "init\n");
add(files);
commit(files);
GitClient client = getClient(workDir);
String revision1 = client.getBranches(false, NULL_PROGRESS_MONITOR).get(Constants.MASTER).getId();
write(file, "modification\n");
add(files);
GitRevisionInfo revision2 = client.commit(files, "my commit message", null, null, NULL_PROGRESS_MONITOR);
Map<File, GitRevisionInfo.GitFileInfo> statuses = client.getStatus(files, Constants.HEAD, revision1, NULL_PROGRESS_MONITOR);
replacedertEquals(1, statuses.size());
replacedertEquals(Status.MODIFIED, statuses.get(file).getStatus());
write(file, "modification 2\n");
add(files);
GitRevisionInfo revision3 = client.commit(files, "my commit 3 message", null, null, NULL_PROGRESS_MONITOR);
statuses = client.getStatus(files, revision1, Constants.HEAD, NULL_PROGRESS_MONITOR);
replacedertEquals(1, statuses.size());
replacedertEquals(Status.MODIFIED, statuses.get(file).getStatus());
statuses = client.getStatus(files, revision1, revision3.getRevision(), NULL_PROGRESS_MONITOR);
replacedertEquals(1, statuses.size());
replacedertEquals(Status.MODIFIED, statuses.get(file).getStatus());
statuses = client.getStatus(files, revision2.getRevision(), revision3.getRevision(), NULL_PROGRESS_MONITOR);
replacedertEquals(1, statuses.size());
replacedertEquals(Status.MODIFIED, statuses.get(file).getStatus());
}
See More Examples