org.eclipse.jgit.lib.ProgressMonitor Java Examples

The following examples show how to use org.eclipse.jgit.lib.ProgressMonitor. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ResourcePackRepository.java    From I18nUpdateMod with MIT License 6 votes vote down vote up
public void reset(ProgressMonitor monitor) {
    try {
        // create branch and set upstream
        gitRepo.branchCreate()
                .setName(branch)
                .setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM)
                .setStartPoint("origin/" + branch)
                .setForce(true)
                .call();
        
        // reset to remote head
        gitRepo.reset()
                .setProgressMonitor(monitor)
                .setMode(ResetType.SOFT)
                .setRef("refs/remotes/origin/" + branch)
                .call();
    } catch (Exception e) {
        logger.error("Exception caught while reseting to remote head: ", e);
    }
}
 
Example #2
Source File: JGitWrapper.java    From mOrgAnd with GNU General Public License v2.0 6 votes vote down vote up
private void createNewRepo(ProgressMonitor monitor) throws GitAPIException, IllegalArgumentException {
    File localRepo = new File(localPath);
    if (localRepo.exists()) // Safety check so we don't accidentally delete directory
        throw new IllegalStateException("Directory already exists");

    try {
        CloneCommand cloneCommand = Git.cloneRepository()
                .setCredentialsProvider(credentialsProvider)
                .setURI(remotePath)
                .setBranch(branch)
                .setDirectory(localRepo)
                .setBare(false);
        if (monitor != null)
            cloneCommand.setProgressMonitor(monitor);
        cloneCommand.call();
    } catch (GitAPIException e) {
        FileUtils.deleteDirectory(localRepo);
        throw e;
    }
}
 
Example #3
Source File: ResourcePackRepository.java    From I18nUpdateMod with MIT License 5 votes vote down vote up
public void sparseCheckout(Collection<String> subPathSet, ProgressMonitor monitor) {
    try {
        // sparse checkout
        CheckoutCommand checkoutCommand = gitRepo.checkout();

        checkoutCommand.setProgressMonitor(monitor)
                .setName(branch)
                .setStartPoint(branch);

        subPathSet.forEach(checkoutCommand::addPath);
        checkoutCommand.call();
    } catch (Exception e) {
        logger.error("Exception caught while checking out: ", e);
    }
}
 
Example #4
Source File: ResourcePackRepository.java    From I18nUpdateMod with MIT License 5 votes vote down vote up
public void sparseCheckout(String subPath, ProgressMonitor monitor) {
    try {
        // sparse checkout
        gitRepo.checkout()
                .setProgressMonitor(monitor)
                .setName(branch)
                .setStartPoint(branch)
                .addPath(subPath)
                .call();
    } catch (Exception e) {
        logger.error("Exception caught while checking out: ", e);
    }
}
 
Example #5
Source File: RevWalkUtils.java    From onedev with MIT License 5 votes vote down vote up
/**
 * Find the list of branches a given commit is reachable from when following
 * parents.
 * <p>
 * Note that this method calls
 * {@link org.eclipse.jgit.revwalk.RevWalk#reset()} at the beginning.
 * <p>
 * In order to improve performance this method assumes clock skew among
 * committers is never larger than 24 hours.
 *
 * @param commit
 *            the commit we are looking at
 * @param revWalk
 *            The RevWalk to be used.
 * @param refs
 *            the set of branches we want to see reachability from
 * @param monitor
 *            the callback for progress and cancellation
 * @return the list of branches a given commit is reachable from
 * @throws org.eclipse.jgit.errors.MissingObjectException
 * @throws org.eclipse.jgit.errors.IncorrectObjectTypeException
 * @throws java.io.IOException
 * @since 5.4
 */
public static List<Ref> findBranchesReachableFrom(RevCommit commit,
		RevWalk revWalk, Collection<Ref> refs, ProgressMonitor monitor)
		throws MissingObjectException, IncorrectObjectTypeException,
		IOException {

	// Make sure commit is from the same RevWalk
	commit = revWalk.parseCommit(commit.getId());
	revWalk.reset();
	List<Ref> result = new ArrayList<>();
	monitor.beginTask(JGitText.get().searchForReachableBranches,
			refs.size());
	final int SKEW = 24*3600; // one day clock skew

	for (Ref ref : refs) {
		if (monitor.isCancelled())
			return result;
		monitor.update(1);
		RevObject maybehead = revWalk.parseAny(ref.getObjectId());
		if (!(maybehead instanceof RevCommit))
			continue;
		RevCommit headCommit = (RevCommit) maybehead;

		// if commit is in the ref branch, then the tip of ref should be
		// newer than the commit we are looking for. Allow for a large
		// clock skew.
		if (headCommit.getCommitTime() + SKEW < commit.getCommitTime())
			continue;

		if (revWalk.isMergedInto(commit, headCommit))
			result.add(ref);
	}
	monitor.endTask();
	return result;
}
 
Example #6
Source File: JGitWrapper.java    From mOrgAnd with GNU General Public License v2.0 5 votes vote down vote up
public void updateChanges(ProgressMonitor monitor) throws Exception {
    Git git = getGit(monitor);

    FetchCommand fetch = git.fetch();
    fetch.setCredentialsProvider(credentialsProvider);
    if (monitor != null)
        fetch.setProgressMonitor(monitor);
    fetch.call();

    SyncState state = getSyncState(git);
    Ref fetchHead = git.getRepository().getRef("FETCH_HEAD");
    switch (state) {
        case Equal:
            // Do nothing
            Log.d("Git", "Local branch is up-to-date");
            break;

        case Ahead:
            Log.d("Git", "Local branch ahead, pushing changes to remote");
            git.push().setCredentialsProvider(credentialsProvider).setRemote(remotePath).call();
            break;

        case Behind:
            Log.d("Git", "Local branch behind, fast forwarding changes");
            MergeResult result = git.merge().include(fetchHead).setFastForward(MergeCommand.FastForwardMode.FF_ONLY).call();
            if (result.getMergeStatus().isSuccessful() == false)
                throw new IllegalStateException("Fast forward failed on behind merge");
            break;

        case Diverged:
            Log.d("Git", "Branches are diverged, merging with strategy " + mergeStrategy.getName());
            MergeResult mergeResult = git.merge().include(fetchHead).setStrategy(mergeStrategy).call();
            if (mergeResult.getMergeStatus().isSuccessful()) {
                git.push().setCredentialsProvider(credentialsProvider).setRemote(remotePath).call();
            } else
                throw new IllegalStateException("Merge failed for diverged branches using strategy " + mergeStrategy.getName());
            break;
    }
}
 
Example #7
Source File: JGitWrapper.java    From mOrgAnd with GNU General Public License v2.0 5 votes vote down vote up
public Git getGit(ProgressMonitor monitor) throws Exception {
    if (this.git == null)
        this.git = initGitRepo(monitor);

    boolean hasConflicts = false;

    try {
        hasConflicts = this.git.status().call().getConflicting().isEmpty() == false;
    } catch (Exception ex) {}

    if (hasConflicts)
        throw new IllegalStateException("Unresolved conflict(s) in git repository");

    return this.git;
}
 
Example #8
Source File: GitUtils.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Update the submodules with the given repository-relative <code>submodulePaths</code> inside the Git repository at
 * the given clone path. Throws exceptions in case of error.
 *
 * @param submodulePaths
 *            repository-relative paths of the submodules to update; if empty, all submodules will be updated.
 */
public static void updateSubmodules(final Path localClonePath, final Iterable<String> submodulePaths,
		final IProgressMonitor monitor) {

	if (!isValidLocalClonePath(localClonePath)) {
		throw new IllegalArgumentException("invalid localClonePath: " + localClonePath);
	}

	@SuppressWarnings("restriction")
	final ProgressMonitor gitMonitor = null == monitor ? createMonitor()
			: new org.eclipse.egit.core.EclipseGitProgressTransformer(monitor);

	try (final Git git = open(localClonePath.toFile())) {
		final SubmoduleUpdateCommand cmd = git.submoduleUpdate();
		for (String submodulePath : submodulePaths) {
			cmd.addPath(submodulePath);
		}
		cmd.setProgressMonitor(gitMonitor);
		cmd.setTransportConfigCallback(TRANSPORT_CALLBACK);
		cmd.call();
	} catch (Exception e) {
		LOGGER.error(e.getClass().getSimpleName()
				+ " while trying to update submodules " + Iterables.toString(submodulePaths)
				+ " of repository '" + localClonePath
				+ "':" + e.getLocalizedMessage());
		Throwables.throwIfUnchecked(e);
		throw new RuntimeException(e);
	}
}
 
Example #9
Source File: GitUtils.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private static void pull(final Git git, IProgressMonitor monitor)
		throws GitAPIException, WrongRepositoryStateException,
		InvalidConfigurationException, InvalidRemoteException, CanceledException, RefNotFoundException,
		RefNotAdvertisedException, NoHeadException, TransportException {

	@SuppressWarnings("restriction")
	ProgressMonitor gitMonitor = (null == monitor) ? createMonitor()
			: new org.eclipse.egit.core.EclipseGitProgressTransformer(monitor);
	pull(git, gitMonitor);
}
 
Example #10
Source File: GitUtils.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
private static void pull(final Git git, ProgressMonitor monitor)
		throws GitAPIException, WrongRepositoryStateException,
		InvalidConfigurationException, InvalidRemoteException, CanceledException, RefNotFoundException,
		RefNotAdvertisedException, NoHeadException, TransportException {

	git.pull().setTransportConfigCallback(TRANSPORT_CALLBACK).setProgressMonitor(monitor).call();
}
 
Example #11
Source File: JGitWrapper.java    From mOrgAnd with GNU General Public License v2.0 5 votes vote down vote up
private Git initGitRepo(ProgressMonitor monitor) throws Exception {
    if (new File(localPath).exists() == false)
        createNewRepo(monitor);

    FileRepository fileRepository = new FileRepository(localPath + "/.git");
    return new Git(fileRepository);
}
 
Example #12
Source File: ResourcePackRepository.java    From I18nUpdateMod with MIT License 5 votes vote down vote up
private boolean fetchFromRemote(String remoteName, ProgressMonitor monitor) {
    try {
        // fetch
        gitRepo.fetch()
                .setProgressMonitor(monitor)
                .setRemote(remoteName)
                .call();
        return true;
    } catch (Exception e) {
        logger.error("Invalid remote repository: ", e);
        return false;
    }
}
 
Example #13
Source File: GitJobUtils.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Calls pack refs for a given repository
 * 
 * @param Repository
 *            the git repository
 */
public static void packRefs(Repository repo, ProgressMonitor monitor) {
	if (repo != null && repo instanceof FileRepository) {
		GC gc = new GC(((FileRepository) repo));
		gc.setProgressMonitor(monitor);
		try {
			gc.packRefs();
		} catch (IOException ex) {
			// ignore IOException since packing is an optimization (not essential for the callers doClone/doFetch) 
		}
	}
}
 
Example #14
Source File: GitWithAuth.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
private ProgressMonitor progressMonitor(String name) {
    return progressMonitors.computeIfAbsent(name, MirrorProgressMonitor::new);
}
 
Example #15
Source File: PullJob.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
private IStatus doPull(IProgressMonitor monitor) throws IOException, GitAPIException, CoreException {
	ProgressMonitor gitMonitor = new EclipseGitProgressTransformer(monitor);
	Repository db = null;
	try {
		db = FileRepositoryBuilder.create(GitUtils.getGitDir(path));
		Git git = Git.wrap(db);
		PullCommand pc = git.pull();
		pc.setProgressMonitor(gitMonitor);
		pc.setCredentialsProvider(credentials);
		pc.setTransportConfigCallback(new TransportConfigCallback() {
			@Override
			public void configure(Transport t) {
				credentials.setUri(t.getURI());
				if (t instanceof TransportHttp && cookie != null) {
					HashMap<String, String> map = new HashMap<String, String>();
					map.put(GitConstants.KEY_COOKIE, cookie.getName() + "=" + cookie.getValue());
					((TransportHttp) t).setAdditionalHeaders(map);
				}
			}
		});
		PullResult pullResult = pc.call();

		if (monitor.isCanceled()) {
			return new Status(IStatus.CANCEL, GitActivator.PI_GIT, "Cancelled");
		}

		// handle result
		if (pullResult.isSuccessful()) {
			return Status.OK_STATUS;
		}
		FetchResult fetchResult = pullResult.getFetchResult();

		IStatus fetchStatus = FetchJob.handleFetchResult(fetchResult);
		if (!fetchStatus.isOK()) {
			return fetchStatus;
		}

		MergeStatus mergeStatus = pullResult.getMergeResult().getMergeStatus();
		if (!mergeStatus.isSuccessful())
			return new Status(IStatus.ERROR, GitActivator.PI_GIT, mergeStatus.name());
	} finally {
		if (db != null) {
			db.close();
		}
	}
	return Status.OK_STATUS;
}
 
Example #16
Source File: FetchJob.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
private IStatus doFetch(IProgressMonitor monitor) throws IOException, CoreException, URISyntaxException, GitAPIException {
	ProgressMonitor gitMonitor = new EclipseGitProgressTransformer(monitor);
	Repository db = null;
	try {
		db = getRepository();
		Git git = Git.wrap(db);
		FetchCommand fc = git.fetch();
		fc.setProgressMonitor(gitMonitor);

		RemoteConfig remoteConfig = new RemoteConfig(git.getRepository().getConfig(), remote);
		credentials.setUri(remoteConfig.getURIs().get(0));
		if (this.cookie != null) {
			fc.setTransportConfigCallback(new TransportConfigCallback() {
				@Override
				public void configure(Transport t) {
					if (t instanceof TransportHttp && cookie != null) {
						HashMap<String, String> map = new HashMap<String, String>();
						map.put(GitConstants.KEY_COOKIE, cookie.getName() + "=" + cookie.getValue());
						((TransportHttp) t).setAdditionalHeaders(map);
					}
				}
			});
		}
		fc.setCredentialsProvider(credentials);
		fc.setRemote(remote);
		if (branch != null) {
			// refs/heads/{branch}:refs/remotes/{remote}/{branch}
			String remoteBranch = branch;
			if (branch.startsWith("for/")) {
				remoteBranch = branch.substring(4);
			}

			RefSpec spec = new RefSpec(Constants.R_HEADS + remoteBranch + ":" + Constants.R_REMOTES + remote + "/" + branch); //$NON-NLS-1$ //$NON-NLS-2$
			spec = spec.setForceUpdate(force);
			fc.setRefSpecs(spec);
		}
		FetchResult fetchResult = fc.call();
		if (monitor.isCanceled()) {
			return new Status(IStatus.CANCEL, GitActivator.PI_GIT, "Cancelled");
		}
		GitJobUtils.packRefs(db, gitMonitor);
		if (monitor.isCanceled()) {
			return new Status(IStatus.CANCEL, GitActivator.PI_GIT, "Cancelled");
		}
		return handleFetchResult(fetchResult);
	} finally {
		if (db != null) {
			db.close();
		}
	}
}
 
Example #17
Source File: PushJob.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
private IStatus doPush(IProgressMonitor monitor) throws IOException, CoreException, URISyntaxException, GitAPIException {
	ProgressMonitor gitMonitor = new EclipseGitProgressTransformer(monitor);
	// /git/remote/{remote}/{branch}/file/{path}
	File gitDir = GitUtils.getGitDir(path.removeFirstSegments(2));
	Repository db = null;
	JSONObject result = new JSONObject();
	try {
		db = FileRepositoryBuilder.create(gitDir);
		Git git = Git.wrap(db);

		PushCommand pushCommand = git.push();
		pushCommand.setProgressMonitor(gitMonitor);
		pushCommand.setTransportConfigCallback(new TransportConfigCallback() {
			@Override
			public void configure(Transport t) {
				credentials.setUri(t.getURI());
				if (t instanceof TransportHttp && cookie != null) {
					HashMap<String, String> map = new HashMap<String, String>();
					map.put(GitConstants.KEY_COOKIE, cookie.getName() + "=" + cookie.getValue());
					((TransportHttp) t).setAdditionalHeaders(map);
				}
			}
		});
		RemoteConfig remoteConfig = new RemoteConfig(git.getRepository().getConfig(), remote);
		credentials.setUri(remoteConfig.getURIs().get(0));
		pushCommand.setCredentialsProvider(credentials);

		boolean pushToGerrit = branch.startsWith("for/");
		RefSpec spec = new RefSpec(srcRef + ':' + (pushToGerrit ? "refs/" : Constants.R_HEADS) + branch);
		pushCommand.setRemote(remote).setRefSpecs(spec);
		if (tags)
			pushCommand.setPushTags();
		pushCommand.setForce(force);
		Iterable<PushResult> resultIterable = pushCommand.call();
		if (monitor.isCanceled()) {
			return new Status(IStatus.CANCEL, GitActivator.PI_GIT, "Cancelled");
		}
		PushResult pushResult = resultIterable.iterator().next();
		boolean error = false;
		JSONArray updates = new JSONArray();
		result.put(GitConstants.KEY_COMMIT_MESSAGE, pushResult.getMessages());
		result.put(GitConstants.KEY_UPDATES, updates);
		for (final RemoteRefUpdate rru : pushResult.getRemoteUpdates()) {
			if (monitor.isCanceled()) {
				return new Status(IStatus.CANCEL, GitActivator.PI_GIT, "Cancelled");
			}
			final String rm = rru.getRemoteName();
			// check status only for branch given in the URL or tags
			if (branch.equals(Repository.shortenRefName(rm)) || rm.startsWith(Constants.R_TAGS) || rm.startsWith(Constants.R_REFS + "for/")) {
				JSONObject object = new JSONObject();
				RemoteRefUpdate.Status status = rru.getStatus();
				if (status != RemoteRefUpdate.Status.UP_TO_DATE || !rm.startsWith(Constants.R_TAGS)) {
					object.put(GitConstants.KEY_COMMIT_MESSAGE, rru.getMessage());
					object.put(GitConstants.KEY_RESULT, status.name());
					TrackingRefUpdate refUpdate = rru.getTrackingRefUpdate();
					if (refUpdate != null) {
						object.put(GitConstants.KEY_REMOTENAME, Repository.shortenRefName(refUpdate.getLocalName()));
						object.put(GitConstants.KEY_LOCALNAME, Repository.shortenRefName(refUpdate.getRemoteName()));
					} else {
						object.put(GitConstants.KEY_REMOTENAME, Repository.shortenRefName(rru.getSrcRef()));
						object.put(GitConstants.KEY_LOCALNAME, Repository.shortenRefName(rru.getRemoteName()));
					}
					updates.put(object);
				}
				if (status != RemoteRefUpdate.Status.OK && status != RemoteRefUpdate.Status.UP_TO_DATE)
					error = true;
			}
			// TODO: return results for all updated branches once push is available for remote, see bug 352202
		}
		// needs to handle multiple
		result.put("Severity", error ? "Error" : "Ok");
	} catch (JSONException e) {
	} finally {
		if (db != null) {
			db.close();
		}
	}
	return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result);
}
 
Example #18
Source File: DelegatingProgressMonitor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public DelegatingProgressMonitor (org.netbeans.libs.git.progress.ProgressMonitor monitor) {
    this.monitor = monitor;
}
 
Example #19
Source File: GitUtils.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
private static void pull(final Git git) throws GitAPIException, WrongRepositoryStateException,
		InvalidConfigurationException, InvalidRemoteException, CanceledException, RefNotFoundException,
		RefNotAdvertisedException, NoHeadException, TransportException {

	pull(git, (ProgressMonitor) null);
}
 
Example #20
Source File: Merger.java    From onedev with MIT License 3 votes vote down vote up
/**
 * Set a progress monitor.
 *
 * @param monitor
 *            Monitor to use, can be null to indicate no progress reporting
 *            is desired.
 * @since 4.2
 */
public void setProgressMonitor(ProgressMonitor monitor) {
	if (monitor == null) {
		this.monitor = NullProgressMonitor.INSTANCE;
	} else {
		this.monitor = monitor;
	}
}
 
Example #21
Source File: BitmapWalker.java    From onedev with MIT License 3 votes vote down vote up
/**
 * Create a BitmapWalker.
 *
 * @param walker walker to use when traversing the object graph.
 * @param bitmapIndex index to obtain bitmaps from.
 * @param pm progress monitor to report progress on.
 */
public BitmapWalker(
		ObjectWalk walker, BitmapIndex bitmapIndex, ProgressMonitor pm) {
	this.walker = walker;
	this.bitmapIndex = bitmapIndex;
	this.pm = (pm == null) ? NullProgressMonitor.INSTANCE : pm;
}
 
Example #22
Source File: DiffCommand.java    From orion.server with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * The progress monitor associated with the diff operation. By default, this is set to <code>NullProgressMonitor</code>
 *
 * @see NullProgressMonitor
 *
 * @param monitor
 *            a progress monitor
 * @return this instance
 */
public DiffCommand setProgressMonitor(ProgressMonitor monitor) {
	this.monitor = monitor;
	return this;
}
 
Example #23
Source File: GitTask.java    From ant-git-tasks with Apache License 2.0 2 votes vote down vote up
/**
 * Sets the progress monitor for the Git command
 *
 * @param pm The progress monitor
 * See {@link org.eclipse.jgit.lib.ProgressMonitor}
 */
void useProgressMonitor(ProgressMonitor pm);
 
Example #24
Source File: AbstractGitTask.java    From ant-git-tasks with Apache License 2.0 2 votes vote down vote up
/**
 * Sets the Git command progress monitor
 *
 * @param pm The progress monitor
 */
@Override
public void useProgressMonitor(ProgressMonitor pm) {
        this.progressMonitor = pm;
}
 
Example #25
Source File: AbstractGitTask.java    From ant-git-tasks with Apache License 2.0 2 votes vote down vote up
/**
 * Returns the Git command progress monitor
 *
 * @return the Git command progress monitor
 */
protected ProgressMonitor getProgressMonitor() {
        return this.progressMonitor;
}