org.eclipse.jgit.internal.JGitText Java Examples

The following examples show how to use org.eclipse.jgit.internal.JGitText. 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: Merger.java    From onedev with MIT License 6 votes vote down vote up
/**
 * Return the merge base of two commits.
 *
 * @param a
 *            the first commit in {@link #sourceObjects}.
 * @param b
 *            the second commit in {@link #sourceObjects}.
 * @return the merge base of two commits
 * @throws org.eclipse.jgit.errors.IncorrectObjectTypeException
 *             one of the input objects is not a commit.
 * @throws java.io.IOException
 *             objects are missing or multiple merge bases were found.
 * @since 3.0
 */
protected RevCommit getBaseCommit(RevCommit a, RevCommit b)
		throws IncorrectObjectTypeException, IOException {
	walk.reset();
	walk.setRevFilter(RevFilter.MERGE_BASE);
	walk.markStart(a);
	walk.markStart(b);
	final RevCommit base = walk.next();
	if (base == null)
		return null;
	final RevCommit base2 = walk.next();
	if (base2 != null) {
		throw new NoMergeBaseException(
				MergeBaseFailureReason.MULTIPLE_MERGE_BASES_NOT_SUPPORTED,
				MessageFormat.format(
				JGitText.get().multipleMergeBasesFor, a.name(), b.name(),
				base.name(), base2.name()));
	}
	return base;
}
 
Example #2
Source File: RevWalk.java    From onedev with MIT License 6 votes vote down vote up
/**
 * Locate a reference to any object without loading it.
 * <p>
 * The object may or may not exist in the repository. It is impossible to
 * tell from this method's return value.
 *
 * @param id
 *            name of the object.
 * @param type
 *            type of the object. Must be a valid Git object type.
 * @return reference to the object. Never null.
 */
@NonNull
public RevObject lookupAny(AnyObjectId id, int type) {
	RevObject r = objects.get(id);
	if (r == null) {
		switch (type) {
		case Constants.OBJ_COMMIT:
			r = createCommit(id);
			break;
		case Constants.OBJ_TREE:
			r = new RevTree(id);
			break;
		case Constants.OBJ_BLOB:
			r = new RevBlob(id);
			break;
		case Constants.OBJ_TAG:
			r = new RevTag(id);
			break;
		default:
			throw new IllegalArgumentException(MessageFormat.format(
					JGitText.get().invalidGitType, Integer.valueOf(type)));
		}
		objects.add(r);
	}
	return r;
}
 
Example #3
Source File: GitUtils.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
private static File getSymRef(File workTree, File dotGit, FS fs)
		throws IOException {
	byte[] content = IO.readFully(dotGit);
	if (!isSymRef(content))
		throw new IOException(MessageFormat.format(
				JGitText.get().invalidGitdirRef, dotGit.getAbsolutePath()));

	int pathStart = 8;
	int lineEnd = RawParseUtils.nextLF(content, pathStart);
	if (content[lineEnd - 1] == '\n')
		lineEnd--;
	if (lineEnd == pathStart)
		throw new IOException(MessageFormat.format(
				JGitText.get().invalidGitdirRef, dotGit.getAbsolutePath()));

	String gitdirPath = RawParseUtils.decode(content, pathStart, lineEnd);
	File gitdirFile = fs.resolve(workTree, gitdirPath);
	if (gitdirFile.isAbsolute())
		return gitdirFile;
	else
		return new File(workTree, gitdirPath).getCanonicalFile();
}
 
Example #4
Source File: GitSkipSslValidationCredentialsProviderTest.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetSslTrustItems() throws URISyntaxException {
	URIish uri = new URIish("https://example.com/repo.git");
	CredentialItem message = new CredentialItem.InformationalMessage(
			JGitText.get().sslFailureTrustExplanation);
	CredentialItem.YesNoType trustNow = new CredentialItem.YesNoType(
			JGitText.get().sslTrustNow);
	CredentialItem.YesNoType trustAlways = new CredentialItem.YesNoType(
			JGitText.get().sslTrustAlways);

	boolean getSuccessful = this.skipSslValidationCredentialsProvider.get(uri,
			message, trustNow, trustAlways);

	assertThat(getSuccessful).as(
			"SkipSSlValidationCredentialsProvider must successfully get the types required for SSL validation skipping")
			.isTrue();
	assertThat(trustNow.getValue()).as(
			"SkipSSlValidationCredentialsProvider should trust the current repo operation")
			.isTrue();
	assertThat(trustAlways.getValue())
			.as("We should not globally skip all SSL validation").isFalse();
}
 
Example #5
Source File: GitSkipSslValidationCredentialsProviderTest.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
@Test
public void testSupportsSslValidationYesNoTypes() {
	CredentialItem yesNoType = new CredentialItem.YesNoType(
			JGitText.get().sslTrustNow);
	assertThat(this.skipSslValidationCredentialsProvider.supports(yesNoType)).as(
			"GitSkipSslValidationCredentialsProvider should always support the trust now YesNoType item")
			.isTrue();

	yesNoType = new CredentialItem.YesNoType(
			MessageFormat.format(JGitText.get().sslTrustForRepo, "/a/path.git"));
	assertThat(this.skipSslValidationCredentialsProvider.supports(yesNoType)).as(
			"GitSkipSslValidationCredentialsProvider should always support the trust repo YesNoType item")
			.isTrue();

	yesNoType = new CredentialItem.YesNoType(JGitText.get().sslTrustAlways);
	assertThat(this.skipSslValidationCredentialsProvider.supports(yesNoType)).as(
			"GitSkipSslValidationCredentialsProvider should always support the trust always YesNoType item")
			.isTrue();

	yesNoType = new CredentialItem.YesNoType("unrelated");
	assertThat(this.skipSslValidationCredentialsProvider.supports(yesNoType)).as(
			"GitSkipSslValidationCredentialsProvider should not support unrelated YesNoType items")
			.isFalse();
}
 
Example #6
Source File: RevWalk.java    From onedev with MIT License 6 votes vote down vote up
/**
 * Reads the "shallow" file and applies it by setting the parents of shallow
 * commits to an empty array.
 * <p>
 * There is a sequencing problem if the first commit being parsed is a
 * shallow commit, since {@link RevCommit#parseCanonical(RevWalk, byte[])}
 * calls this method before its callers add the new commit to the
 * {@link RevWalk#objects} map. That means a call from this method to
 * {@link #lookupCommit(AnyObjectId)} fails to find that commit and creates
 * a new one, which is promptly discarded.
 * <p>
 * To avoid that, {@link RevCommit#parseCanonical(RevWalk, byte[])} passes
 * its commit to this method, so that this method can apply the shallow
 * state to it directly and avoid creating the duplicate commit object.
 *
 * @param rc
 *            the initial commit being parsed
 * @throws IOException
 *             if the shallow commits file can't be read
 */
void initializeShallowCommits(RevCommit rc) throws IOException {
	if (shallowCommitsInitialized) {
		throw new IllegalStateException(
				JGitText.get().shallowCommitsAlreadyInitialized);
	}

	shallowCommitsInitialized = true;

	if (reader == null) {
		return;
	}

	for (ObjectId id : reader.getShallowCommits()) {
		if (id.equals(rc.getId())) {
			rc.parents = RevCommit.NO_PARENTS;
		} else {
			lookupCommit(id).parents = RevCommit.NO_PARENTS;
		}
	}
}
 
Example #7
Source File: OrRevFilter.java    From onedev with MIT License 5 votes vote down vote up
/**
 * Create a filter around many filters, one of which must match.
 *
 * @param list
 *            list of filters to match against. Must contain at least 2
 *            filters.
 * @return a filter that must match at least one input filter.
 */
public static RevFilter create(RevFilter[] list) {
	if (list.length == 2)
		return create(list[0], list[1]);
	if (list.length < 2)
		throw new IllegalArgumentException(JGitText.get().atLeastTwoFiltersNeeded);
	final RevFilter[] subfilters = new RevFilter[list.length];
	System.arraycopy(list, 0, subfilters, 0, list.length);
	return new List(subfilters);
}
 
Example #8
Source File: Merger.java    From onedev with MIT License 5 votes vote down vote up
/**
 * Create a new merge instance for a repository.
 *
 * @param local
 *            the repository this merger will read and write data on.
 */
protected Merger(Repository local) {
	if (local == null) {
		throw new NullPointerException(JGitText.get().repositoryIsRequired);
	}
	db = local;
	inserter = local.newObjectInserter();
	reader = inserter.newReader();
	walk = new RevWalk(reader);
}
 
Example #9
Source File: StashApplyCommand.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
private ObjectId getStashId() throws GitAPIException {
	final String revision = stashRef != null ? stashRef : DEFAULT_REF;
	final ObjectId stashId;
	try {
		stashId = repo.resolve(revision);
	} catch (IOException e) {
		throw new InvalidRefNameException(MessageFormat.format(JGitText.get().stashResolveFailed, revision), e);
	}
	if (stashId == null)
		throw new InvalidRefNameException(MessageFormat.format(JGitText.get().stashResolveFailed, revision));
	return stashId;
}
 
Example #10
Source File: StashApplyCommand.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
private void checkoutPath(DirCacheEntry entry, ObjectReader reader) {
	try {
		DirCacheCheckout.checkoutEntry(repo, entry, reader);
	} catch (IOException e) {
		throw new JGitInternalException(MessageFormat.format(JGitText.get().checkoutConflictWithFile, entry.getPathString()), e);
	}
}
 
Example #11
Source File: TransportAmazonLambdaS3.java    From github-bucket with ISC License 5 votes vote down vote up
private void readLooseRefs(final TreeMap<String, Ref> avail) throws TransportException {
    try {
        // S3 limits the size of the response to 1000 entries. Batch the requests.
        String prefix = resolveKey(ROOT_DIR + "refs");
        List<S3ObjectSummary> refs = getS3ObjectSummaries(prefix);
        for (final S3ObjectSummary ref : refs) {
            readRef(avail, "refs/" + ref.getKey().substring(prefix.length() + 1));
        }
    }
    catch (IOException e) {
        throw new TransportException(getURI(), JGitText.get().cannotListRefs, e);
    }
}
 
Example #12
Source File: TransportAmazonLambdaS3.java    From github-bucket with ISC License 5 votes vote down vote up
private void readLooseRefs(final TreeMap<String, Ref> avail) throws TransportException {
    try {
        // S3 limits the size of the response to 1000 entries. Batch the requests.
        String prefix = resolveKey(ROOT_DIR + "refs");
        List<S3ObjectSummary> refs = getS3ObjectSummaries(prefix);
        for (final S3ObjectSummary ref : refs) {
            readRef(avail, "refs/" + ref.getKey().substring(prefix.length() + 1));
        }
    }
    catch (IOException e) {
        throw new TransportException(getURI(), JGitText.get().cannotListRefs, e);
    }
}
 
Example #13
Source File: AndRevFilter.java    From onedev with MIT License 5 votes vote down vote up
/**
 * Create a filter around many filters, all of which must match.
 *
 * @param list
 *            list of filters to match against. Must contain at least 2
 *            filters.
 * @return a filter that must match all input filters.
 */
public static RevFilter create(Collection<RevFilter> list) {
	if (list.size() < 2)
		throw new IllegalArgumentException(JGitText.get().atLeastTwoFiltersNeeded);
	final RevFilter[] subfilters = new RevFilter[list.size()];
	list.toArray(subfilters);
	if (subfilters.length == 2)
		return create(subfilters[0], subfilters[1]);
	return new List(subfilters);
}
 
Example #14
Source File: AndRevFilter.java    From onedev with MIT License 5 votes vote down vote up
/**
 * Create a filter around many filters, all of which must match.
 *
 * @param list
 *            list of filters to match against. Must contain at least 2
 *            filters.
 * @return a filter that must match all input filters.
 */
public static RevFilter create(RevFilter[] list) {
	if (list.length == 2)
		return create(list[0], list[1]);
	if (list.length < 2)
		throw new IllegalArgumentException(JGitText.get().atLeastTwoFiltersNeeded);
	final RevFilter[] subfilters = new RevFilter[list.length];
	System.arraycopy(list, 0, subfilters, 0, list.length);
	return new List(subfilters);
}
 
Example #15
Source File: OrRevFilter.java    From onedev with MIT License 5 votes vote down vote up
/**
 * Create a filter around many filters, one of which must match.
 *
 * @param list
 *            list of filters to match against. Must contain at least 2
 *            filters.
 * @return a filter that must match at least one input filter.
 */
public static RevFilter create(Collection<RevFilter> list) {
	if (list.size() < 2)
		throw new IllegalArgumentException(JGitText.get().atLeastTwoFiltersNeeded);
	final RevFilter[] subfilters = new RevFilter[list.size()];
	list.toArray(subfilters);
	if (subfilters.length == 2)
		return create(subfilters[0], subfilters[1]);
	return new List(subfilters);
}
 
Example #16
Source File: GitSkipSslValidationCredentialsProvider.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Override
public boolean supports(CredentialItem... items) {
	List<CredentialItem> unprocessedItems = new ArrayList<>();

	for (CredentialItem item : items) {
		if (item instanceof CredentialItem.InformationalMessage
				&& item.getPromptText() != null && item.getPromptText()
						.contains(JGitText.get().sslFailureTrustExplanation)) {
			continue;
		}

		if (item instanceof CredentialItem.YesNoType && item.getPromptText() != null
				&& (item.getPromptText().equals(JGitText.get().sslTrustNow)
						|| item.getPromptText()
								.startsWith(stripFormattingPlaceholders(
										JGitText.get().sslTrustForRepo))
						|| item.getPromptText()
								.equals(JGitText.get().sslTrustAlways))) {
			continue;
		}

		unprocessedItems.add(item);
	}

	return unprocessedItems.isEmpty() || (this.delegate != null && this.delegate
			.supports(unprocessedItems.toArray(new CredentialItem[0])));
}
 
Example #17
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 #18
Source File: RevObjectList.java    From onedev with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public void add(int index, E element) {
	if (index != size)
		throw new UnsupportedOperationException(MessageFormat.format(
				JGitText.get().unsupportedOperationNotAddAtEnd,
				Integer.valueOf(index)));
	set(index, element);
	size++;
}
 
Example #19
Source File: GitSkipSslValidationCredentialsProvider.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Override
public boolean get(URIish uri, CredentialItem... items)
		throws UnsupportedCredentialItem {
	List<CredentialItem> unprocessedItems = new ArrayList<>();

	for (CredentialItem item : items) {
		if (item instanceof CredentialItem.YesNoType) {
			CredentialItem.YesNoType yesNoItem = (CredentialItem.YesNoType) item;
			String prompt = yesNoItem.getPromptText();
			if (prompt == null) {
				unprocessedItems.add(item);
			}
			else if (prompt.equals(JGitText.get().sslTrustNow) || prompt.startsWith(
					stripFormattingPlaceholders(JGitText.get().sslTrustForRepo))) {
				yesNoItem.setValue(true);
			}
			else if (prompt.equals(JGitText.get().sslTrustAlways)) {
				yesNoItem.setValue(false);
			}
			else {
				unprocessedItems.add(item);
			}
		}
		else if (!item.getPromptText()
				.contains(JGitText.get().sslFailureTrustExplanation)) {
			unprocessedItems.add(item);
		}
	}

	if (unprocessedItems.isEmpty()) {
		return true;
	}
	if (this.delegate != null) {
		return this.delegate.get(uri,
				unprocessedItems.toArray(new CredentialItem[0]));
	}
	throw new UnsupportedCredentialItem(uri,
			unprocessedItems.size() + " credential items not supported");
}
 
Example #20
Source File: GitSkipSslValidationCredentialsProviderTest.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void testSupportsSslFailureInformationalMessage() {
	CredentialItem informationalMessage = new CredentialItem.InformationalMessage(
			"text " + JGitText.get().sslFailureTrustExplanation + " more text");
	assertThat(this.skipSslValidationCredentialsProvider
			.supports(informationalMessage)).as(
					"GitSkipSslValidationCredentialsProvider should always support SSL failure InformationalMessage")
					.isTrue();

	informationalMessage = new CredentialItem.InformationalMessage("unrelated");
	assertThat(this.skipSslValidationCredentialsProvider
			.supports(informationalMessage)).as(
					"GitSkipSslValidationCredentialsProvider should not support unrelated InformationalMessage items")
					.isFalse();
}
 
Example #21
Source File: RevWalk.java    From onedev with MIT License 5 votes vote down vote up
int allocFlag() {
	if (freeFlags == 0)
		throw new IllegalArgumentException(MessageFormat.format(
				JGitText.get().flagsAlreadyCreated,
				Integer.valueOf(32 - RESERVED_FLAGS)));
	final int m = Integer.lowestOneBit(freeFlags);
	freeFlags &= ~m;
	return m;
}
 
Example #22
Source File: RevWalk.java    From onedev with MIT License 5 votes vote down vote up
private RevObject parseNew(AnyObjectId id, ObjectLoader ldr)
		throws LargeObjectException, CorruptObjectException,
		MissingObjectException, IOException {
	RevObject r;
	int type = ldr.getType();
	switch (type) {
	case Constants.OBJ_COMMIT: {
		final RevCommit c = createCommit(id);
		c.parseCanonical(this, getCachedBytes(c, ldr));
		r = c;
		break;
	}
	case Constants.OBJ_TREE: {
		r = new RevTree(id);
		r.flags |= PARSED;
		break;
	}
	case Constants.OBJ_BLOB: {
		r = new RevBlob(id);
		r.flags |= PARSED;
		break;
	}
	case Constants.OBJ_TAG: {
		final RevTag t = new RevTag(id);
		t.parseCanonical(this, getCachedBytes(t, ldr));
		r = t;
		break;
	}
	default:
		throw new IllegalArgumentException(MessageFormat.format(
				JGitText.get().badObjectType, Integer.valueOf(type)));
	}
	objects.add(r);
	return r;
}
 
Example #23
Source File: MergeBaseGenerator.java    From onedev with MIT License 5 votes vote down vote up
private void add(RevCommit c) {
	final int flag = walker.allocFlag();
	branchMask |= flag;
	if ((c.flags & branchMask) != 0) {
		// This should never happen. RevWalk ensures we get a
		// commit admitted to the initial queue only once. If
		// we see this marks aren't correctly erased.
		//
		throw new IllegalStateException(MessageFormat.format(JGitText.get().staleRevFlagsOn, c.name()));
	}
	c.flags |= flag;
	pending.add(c);
}
 
Example #24
Source File: GitSkipSslValidationCredentialsProviderTest.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetSslTrustItemsWithLocalRepo() throws URISyntaxException {
	URIish uri = new URIish("https://example.com/repo.git");
	CredentialItem message = new CredentialItem.InformationalMessage(
			JGitText.get().sslFailureTrustExplanation);
	CredentialItem.YesNoType trustNow = new CredentialItem.YesNoType(
			JGitText.get().sslTrustNow);
	CredentialItem.YesNoType trustForRepo = new CredentialItem.YesNoType(
			JGitText.get().sslTrustForRepo);
	CredentialItem.YesNoType trustAlways = new CredentialItem.YesNoType(
			JGitText.get().sslTrustAlways);

	boolean getSuccessful = this.skipSslValidationCredentialsProvider.get(uri,
			message, trustNow, trustForRepo, trustAlways);

	assertThat(getSuccessful).as(
			"SkipSSlValidationCredentialsProvider must successfully get the types required for SSL validation skipping")
			.isTrue();
	assertThat(trustNow.getValue()).as(
			"SkipSSlValidationCredentialsProvider should trust the current repo operation")
			.isTrue();
	assertThat(trustForRepo.getValue())
			.as("Future operations on this repository should also be trusted")
			.isTrue();
	assertThat(trustAlways.getValue())
			.as("We should not globally skip all SSL validation").isFalse();
}
 
Example #25
Source File: RevFlag.java    From onedev with MIT License 4 votes vote down vote up
@Override
public RevWalk getRevWalk() {
	throw new UnsupportedOperationException(MessageFormat.format(
			JGitText.get().isAStaticFlagAndHasNorevWalkInstance, toString()));
}
 
Example #26
Source File: MultiUserSshSessionFactory.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public synchronized RemoteSession getSession(URIish uri,
                                             CredentialsProvider credentialsProvider, FS fs, int tms)
        throws TransportException {

    String user = uri.getUser();
    final String pass = uri.getPass();
    String host = uri.getHost();
    int port = uri.getPort();

    try {
        if (config == null)
            config = OpenSshConfig.get(fs);

        final OpenSshConfig.Host hc = config.lookup(host);
        host = hc.getHostName();
        if (port <= 0)
            port = hc.getPort();
        if (user == null)
            user = hc.getUser();

        Session session = createSession(credentialsProvider, fs, user,
                pass, host, port, hc);

        int retries = 0;
        while (!session.isConnected()) {
            try {
                retries++;
                session.connect(tms);
            } catch (JSchException e) {
                session.disconnect();
                session = null;
                // Make sure our known_hosts is not outdated
                knownHosts(getJSch(credentialsProvider, hc, fs), fs);

                if (isAuthenticationCanceled(e)) {
                    throw e;
                } else if (isAuthenticationFailed(e)
                        && credentialsProvider != null) {
                    // if authentication failed maybe credentials changed at
                    // the remote end therefore reset credentials and retry
                    if (retries < 3) {
                        credentialsProvider.reset(uri);
                        session = createSession(credentialsProvider, fs,
                                user, pass, host, port, hc);
                    } else
                        throw e;
                } else if (retries >= hc.getConnectionAttempts()) {
                    throw e;
                } else {
                    try {
                        Thread.sleep(1000);
                        session = createSession(credentialsProvider, fs,
                                user, pass, host, port, hc);
                    } catch (InterruptedException e1) {
                        throw new TransportException(
                                JGitText.get().transportSSHRetryInterrupt,
                                e1);
                    }
                }
            }
        }

        return new JschSession(session, uri);

    } catch (JSchException je) {
        final Throwable c = je.getCause();
        if (c instanceof UnknownHostException)
            throw new TransportException(uri, JGitText.get().unknownHost);
        if (c instanceof ConnectException)
            throw new TransportException(uri, c.getMessage());
        throw new TransportException(uri, je.getMessage(), je);
    }

}
 
Example #27
Source File: LogCommand.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * 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 class. Each instance of this class 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().noHEADExistsAndNoExplicitStartingRevisionWasSpecified);
			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;
}
 
Example #28
Source File: RecursiveMerger.java    From onedev with MIT License 4 votes vote down vote up
/**
 * Get a single base commit for two given commits. If the two source commits
 * have more than one base commit recursively merge the base commits
 * together until a virtual common base commit has been found.
 *
 * @param a
 *            the first commit to be merged
 * @param b
 *            the second commit to be merged
 * @param callDepth
 *            the callDepth when this method is called recursively
 * @return the merge base of two commits. If a criss-cross merge required a
 *         synthetic merge base this commit is visible only the merger's
 *         RevWalk and will not be in the repository.
 * @throws java.io.IOException
 * @throws IncorrectObjectTypeException
 *             one of the input objects is not a commit.
 * @throws NoMergeBaseException
 *             too many merge bases are found or the computation of a common
 *             merge base failed (e.g. because of a conflict).
 */
protected RevCommit getBaseCommit(RevCommit a, RevCommit b, int callDepth)
		throws IOException {
	ArrayList<RevCommit> baseCommits = new ArrayList<>();
	walk.reset();
	walk.setRevFilter(RevFilter.MERGE_BASE);
	walk.markStart(a);
	walk.markStart(b);
	RevCommit c;
	while ((c = walk.next()) != null)
		baseCommits.add(c);

	if (baseCommits.isEmpty())
		return null;
	if (baseCommits.size() == 1)
		return baseCommits.get(0);
	if (baseCommits.size() >= MAX_BASES)
		throw new NoMergeBaseException(NoMergeBaseException.MergeBaseFailureReason.TOO_MANY_MERGE_BASES, MessageFormat.format(
				JGitText.get().mergeRecursiveTooManyMergeBasesFor,
				Integer.valueOf(MAX_BASES), a.name(), b.name(),
						Integer.valueOf(baseCommits.size())));

	// We know we have more than one base commit. We have to do merges now
	// to determine a single base commit. We don't want to spoil the current
	// dircache and working tree with the results of this intermediate
	// merges. Therefore set the dircache to a new in-memory dircache and
	// disable that we update the working-tree. We set this back to the
	// original values once a single base commit is created.
	RevCommit currentBase = baseCommits.get(0);
	DirCache oldDircache = dircache;
	boolean oldIncore = inCore;
	WorkingTreeIterator oldWTreeIt = workingTreeIterator;
	workingTreeIterator = null;
	try {
		dircache = DirCache.read(reader, currentBase.getTree());
		inCore = true;

		List<RevCommit> parents = new ArrayList<>();
		parents.add(currentBase);
		for (int commitIdx = 1; commitIdx < baseCommits.size(); commitIdx++) {
			RevCommit nextBase = baseCommits.get(commitIdx);
			if (commitIdx >= MAX_BASES)
				throw new NoMergeBaseException(
						NoMergeBaseException.MergeBaseFailureReason.TOO_MANY_MERGE_BASES,
						MessageFormat.format(
						JGitText.get().mergeRecursiveTooManyMergeBasesFor,
						Integer.valueOf(MAX_BASES), a.name(), b.name(),
								Integer.valueOf(baseCommits.size())));
			parents.add(nextBase);
			RevCommit bc = getBaseCommit(currentBase, nextBase,
					callDepth + 1);
			AbstractTreeIterator bcTree = (bc == null) ? new EmptyTreeIterator()
					: openTree(bc.getTree());
			if (mergeTrees(bcTree, currentBase.getTree(),
					nextBase.getTree(), true))
				currentBase = createCommitForTree(resultTree, parents);
			else
				throw new NoMergeBaseException(
						NoMergeBaseException.MergeBaseFailureReason.CONFLICTS_DURING_MERGE_BASE_CALCULATION,
						MessageFormat.format(
								JGitText.get().mergeRecursiveConflictsWhenMergingCommonAncestors,
								currentBase.getName(), nextBase.getName()));
		}
	} finally {
		inCore = oldIncore;
		dircache = oldDircache;
		workingTreeIterator = oldWTreeIt;
		toBeCheckedOut.clear();
		toBeDeleted.clear();
		modifiedFiles.clear();
		unmergedPaths.clear();
		mergeResults.clear();
		failingPaths.clear();
	}
	return currentBase;
}
 
Example #29
Source File: RevFilter.java    From onedev with MIT License 4 votes vote down vote up
@Override
public boolean include(RevWalk walker, RevCommit c) {
	throw new UnsupportedOperationException(JGitText.get().cannotBeCombined);
}
 
Example #30
Source File: PatternMatchRevFilter.java    From onedev with MIT License 4 votes vote down vote up
/**
 * Construct a new pattern matching filter.
 *
 * @param pattern
 *            text of the pattern. Callers may want to surround their
 *            pattern with ".*" on either end to allow matching in the
 *            middle of the string.
 * @param innerString
 *            should .* be wrapped around the pattern of ^ and $ are
 *            missing? Most users will want this set.
 * @param rawEncoding
 *            should {@link #forceToRaw(String)} be applied to the pattern
 *            before compiling it?
 * @param flags
 *            flags from {@link java.util.regex.Pattern} to control how
 *            matching performs.
 */
protected PatternMatchRevFilter(String pattern, final boolean innerString,
		final boolean rawEncoding, final int flags) {
	if (pattern.length() == 0)
		throw new IllegalArgumentException(JGitText.get().cannotMatchOnEmptyString);
	patternText = pattern;

	if (innerString) {
		if (!pattern.startsWith("^") && !pattern.startsWith(".*")) //$NON-NLS-1$ //$NON-NLS-2$
			pattern = ".*" + pattern; //$NON-NLS-1$
		if (!pattern.endsWith("$") && !pattern.endsWith(".*")) //$NON-NLS-1$ //$NON-NLS-2$
			pattern = pattern + ".*"; //$NON-NLS-1$
	}
	final String p = rawEncoding ? forceToRaw(pattern) : pattern;
	compiledPattern = Pattern.compile(p, flags).matcher(""); //$NON-NLS-1$
}