Example usage for org.eclipse.jgit.lib ObjectId fromString

List of usage examples for org.eclipse.jgit.lib ObjectId fromString

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib ObjectId fromString.

Prototype

public static ObjectId fromString(String str) 

Source Link

Document

Convert an ObjectId from hex characters.

Usage

From source file:jetbrains.buildServer.buildTriggers.vcs.git.tests.GitVcsSupportTest.java

License:Apache License

@Test
@TestFor(issues = "TW-24084")
public void should_retry_getCurrentState_if_it_fails() throws Exception {
    VcsRootImpl root = vcsRoot().withFetchUrl("ssh://some.org/repo.git")
            .withAuthMethod(AuthenticationMethod.PRIVATE_KEY_DEFAULT).build();

    final FetchConnection connection = myContext.mock(FetchConnection.class);
    final Ref masterRef = myContext.mock(Ref.class, "master");
    final Ref topicRef = myContext.mock(Ref.class, "topic");
    myContext.checking(new Expectations() {
        {//from   ww w.  ja  v a  2  s  .  com
            allowing(masterRef).getName();
            will(returnValue("refs/heads/master"));
            allowing(masterRef).getObjectId();
            will(returnValue(ObjectId.fromString("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")));

            allowing(topicRef).getName();
            will(returnValue("refs/heads/topic"));
            allowing(topicRef).getObjectId();
            will(returnValue(ObjectId.fromString("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb")));

            allowing(connection).getRefsMap();
            will(returnValue(map("refs/heads/master", masterRef, "refs/heads/topic", topicRef)));
            allowing(connection).close();
        }
    });

    //setup TransportFactory so that it fails to get connection several times with well known exceptions
    //and then successfully gets it on the last call
    final AtomicInteger failCount = new AtomicInteger(0);
    final List<TransportException> recoverableErrors = Arrays.asList(
            new TransportException("Session.connect: java.net.SocketException: Connection reset",
                    new JSchException("test")),
            new TransportException(
                    "Session.connect: java.net.SocketException: Software caused connection abort",
                    new JSchException("test")),
            new TransportException("com.jcraft.jsch.JSchException: connection is closed by foreign host",
                    new JSchException("test")),
            new TransportException("java.net.UnknownHostException: some.org", new JSchException("test")),
            new TransportException("com.jcraft.jsch.JSchException: verify: false", new JSchException("test")));
    ServerPluginConfig config = myConfigBuilder.withGetConnectionRetryAttempts(recoverableErrors.size() + 1)
            .withConnectionRetryIntervalMillis(0).build();
    VcsRootSshKeyManager manager = new EmptyVcsRootSshKeyManager();
    TransportFactory transportFactory = new TransportFactoryImpl(config, manager) {
        @Override
        public Transport createTransport(@NotNull Repository r, @NotNull URIish url,
                @NotNull AuthSettings authSettings, int timeoutSeconds)
                throws NotSupportedException, VcsException {
            return new Transport(r, url) {
                @Override
                public FetchConnection openFetch() throws NotSupportedException, TransportException {
                    if (failCount.get() < recoverableErrors.size()) {
                        TransportException error = recoverableErrors.get(failCount.get());
                        failCount.incrementAndGet();
                        throw error;
                    } else {
                        return connection;
                    }
                }

                @Override
                public PushConnection openPush() throws NotSupportedException, TransportException {
                    return null;
                }

                @Override
                public void close() {
                }
            };
        }
    };

    FetchCommand fetchCommand = new FetchCommandImpl(config, transportFactory, new FetcherProperties(config),
            manager);
    FetchCommandCountDecorator fetchCounter = new FetchCommandCountDecorator(fetchCommand);
    GitVcsSupport git = gitSupport().withPluginConfig(config).withTransportFactory(transportFactory)
            .withFetchCommand(fetchCounter).build();

    RepositoryStateData state = git.getCurrentState(root);
    assertEquals(state.getBranchRevisions(),
            map("refs/heads/master", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "refs/heads/topic",
                    "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"));
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.tests.SubmoduleTest.java

License:Apache License

/**
 * Test tree walk over submodules//w w  w  .  jav  a 2 s.co  m
 *
 * @throws IOException in case of test failure
 */
@Test
public void testSubmoduleTreeWalk() throws IOException {
    File masterRep = dataFile("repo.git");
    Repository rm = new RepositoryBuilder().setGitDir(masterRep).build();
    try {
        File submoduleRep = dataFile("submodule.git");
        final Repository rs = new RepositoryBuilder().setGitDir(submoduleRep).build();
        RevWalk revWalk = new RevWalk(rm);
        try {
            final RevCommit submoduleTxtAdded = revWalk.parseCommit(ObjectId
                    .fromString(GitUtils.versionRevision(GitVcsSupportTest.SUBMODULE_TXT_ADDED_VERSION)));
            final RevCommit submoduleModified = revWalk.parseCommit(ObjectId
                    .fromString(GitUtils.versionRevision(GitVcsSupportTest.SUBMODULE_MODIFIED_VERSION)));
            final RevCommit submoduleAdded = revWalk.parseCommit(
                    ObjectId.fromString(GitUtils.versionRevision(GitVcsSupportTest.SUBMODULE_ADDED_VERSION)));
            final RevCommit beforeSubmoduleAdded = revWalk.parseCommit(ObjectId
                    .fromString(GitUtils.versionRevision(GitVcsSupportTest.BEFORE_SUBMODULE_ADDED_VERSION)));
            SubmoduleResolverImpl r = new MySubmoduleResolver(
                    myGitSupport.createContext(vcsRoot().withFetchUrl("whatever").build(), "testing"),
                    myCommitLoader, rm, submoduleAdded, rs);
            TreeWalk tw = new TreeWalk(rm);
            tw.setRecursive(true);
            tw.reset();
            tw.addTree(create(rm, beforeSubmoduleAdded, r, "", "", SubmodulesCheckoutPolicy.CHECKOUT, true));
            tw.addTree(create(rm, submoduleAdded, r, "", "", SubmodulesCheckoutPolicy.CHECKOUT, true));
            tw.setFilter(TreeFilter.ANY_DIFF);
            checkElement(tw, ".gitmodules");
            assertSame(tw.getTree(1, SubmoduleAwareTreeIterator.class).getRepository(), rm);
            checkElement(tw, "submodule/file.txt");
            assertSame(tw.getTree(1, SubmoduleAwareTreeIterator.class).getRepository(), rs);
            assertFalse(tw.next());
            tw.reset();
            tw.addTree(create(rm, submoduleModified, r, "", "", SubmodulesCheckoutPolicy.CHECKOUT, true));
            tw.addTree(create(rm, submoduleTxtAdded, r, "", "", SubmodulesCheckoutPolicy.CHECKOUT, true));
            tw.setFilter(TreeFilter.ANY_DIFF);
            checkElement(tw, "submodule.txt");
            assertSame(tw.getTree(1, SubmoduleAwareTreeIterator.class).getRepository(), rm);
            checkElement(tw, "submodule/new file.txt");
            assertSame(tw.getTree(0, SubmoduleAwareTreeIterator.class).getRepository(), rs);
            assertFalse(tw.next());
        } finally {
            rs.close();
        }
    } finally {
        rm.close();
    }
}

From source file:net.riezebos.thoth.content.impl.GitContentManager.java

License:Apache License

@Override
public SourceDiff getDiff(String diffSpec) throws ContentManagerException {

    int idx = diffSpec.indexOf('/');
    if (idx == -1)
        return null;

    String id = diffSpec.substring(0, idx);
    String path = diffSpec.substring(idx + 1);

    if (id == null || ObjectId.zeroId().equals(ObjectId.fromString(id)))
        return null;

    SourceDiff result = null;//from www . j  a v a  2s . c o m

    try (Git git = getRepository();
            RevWalk revWalk = new RevWalk(git.getRepository());
            SimpleDiffFormatter df = new SimpleDiffFormatter()) {
        Repository repository = git.getRepository();

        RevCommit revCommit = revWalk.parseCommit(ObjectId.fromString(id));

        RevCommit[] parents = revCommit.getParents();
        if (parents != null && parents.length > 0) {
            RevCommit parent = revWalk.parseCommit(parents[0].getId());
            df.setRepository(repository);
            df.setDiffComparator(RawTextComparator.DEFAULT);
            df.setDetectRenames(true);
            List<DiffEntry> diffs = df.scan(parent.getTree(), revCommit.getTree());
            for (DiffEntry diff : diffs) {
                if (path.equals(diff.getNewPath())) {

                    result = createSourceDiff(repository, revCommit, diff);
                    break;
                }
            }
        }
        return result;
    } catch (Exception e) {
        throw new ContentManagerException(e);
    }
}

From source file:org.chodavarapu.jgitaws.repositories.RefRepository.java

License:Eclipse Distribution License

public Observable<Ref> getAllRefsSorted(String repositoryName) {
    return configuration.getDynamoClient()
            .getAllItems(configuration.getRefsTableName(), new QuerySpec()
                    .withHashKey(REPOSITORY_NAME_ATTRIBUTE, repositoryName).withScanIndexForward(true))
            .map(item -> {/*  w  ww  .  j  av a2  s  .  c o m*/
                String name = item.getString(NAME_ATTRIBUTE);
                String target = item.getString(TARGET_ATTRIBUTE);
                boolean isSymbolic = item.getBoolean(IS_SYMBOLIC_ATTRIBUTE);
                boolean isPeeled = item.getBoolean(IS_PEELED_ATTRIBUTE);
                String peeledTarget = item.getString(PEELED_TARGET_ATTRIBUTE);

                if (isSymbolic) {
                    return new SymbolicRef(name, new ObjectIdRef.Unpeeled(Ref.Storage.PACKED, target, null));
                } else {
                    if (isPeeled) {
                        if (peeledTarget == null) {
                            return new ObjectIdRef.PeeledNonTag(Ref.Storage.PACKED, name,
                                    ObjectId.fromString(target));
                        } else {
                            return new ObjectIdRef.PeeledTag(Ref.Storage.PACKED, name,
                                    ObjectId.fromString(target), ObjectId.fromString(peeledTarget));
                        }
                    } else {
                        return new ObjectIdRef.Unpeeled(Ref.Storage.PACKED, name, ObjectId.fromString(target));
                    }
                }
            });
}

From source file:org.cicomponents.git.impl.LatestRevisionGitBranchMonitor.java

License:Mozilla Public License

private void checkLatest() throws IOException {
    synchronized (git) {
        String headRefName = git.getRepository().findRef("refs/heads/" + branch).getObjectId().getName();
        String knownHead = (String) persistentMap.get(headRefName);
        if (knownHead != null) {
            head = ObjectId.fromString(knownHead);
        }// ww  w . jav  a  2  s  . c  o m
        RefsChangedEvent event = new RefsChangedEvent();
        event.setRepository(git.getRepository());
        git.getRepository().fireEvent(event);
    }
}

From source file:org.craftercms.deployer.impl.ProcessedCommitsStoreImpl.java

License:Open Source License

@Override
public ObjectId load(String targetId) throws DeployerException {
    File commitFile = getCommitFile(targetId);
    try {// w  w  w  .j  ava 2 s  .com
        if (commitFile.exists()) {
            String commitId = FileUtils.readFileToString(commitFile, "UTF-8").trim();
            if (StringUtils.isNotEmpty(commitId)) {
                logger.debug("Found previous processed commit ID for target '{}': {}", targetId, commitId);

                return ObjectId.fromString(commitId);
            } else {
                logger.warn("Processed commit file {} is empty, will be deleted", commitFile);

                FileUtils.deleteQuietly(commitFile);

                return null;
            }
        } else {
            return null;
        }
    } catch (IOException e) {
        throw new DeployerException("Error retrieving previous processed commit ID from " + commitFile, e);
    }
}

From source file:org.craftercms.deployer.impl.ProcessedCommitStoreImplTest.java

License:Open Source License

@Test
public void testStore() throws Exception {
    processedCommitsStore.store("barfoo-test", OBJECT_ID);

    File barfooTestCommitFile = new File(processedCommitsFolder, "barfoo-test.commit");

    assertTrue(barfooTestCommitFile.exists());
    assertEquals(OBJECT_ID,//from   w  w w .  j  av  a  2 s  .co m
            ObjectId.fromString(FileUtils.readFileToString(barfooTestCommitFile, "UTF-8").trim()));
}

From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepository.java

License:Open Source License

@Override
public void publish(String site, List<String> commitIds, String environment, String author, String comment) {
    Repository repo = helper.getRepository(site, GitRepositories.PUBLISHED);

    synchronized (helper.getRepository(site, GitRepositories.PUBLISHED)) {
        try (Git git = new Git(repo)) {
            // fetch "origin/master"
            FetchResult fetchResult = git.fetch().setRemote(Constants.DEFAULT_REMOTE_NAME).call();

            // checkout environment branch
            Ref checkoutResult = git.checkout().setCreateBranch(true).setName(environment).call();

            // cherry pick all commit ids
            CherryPickCommand cherryPickCommand = git.cherryPick().setStrategy(MergeStrategy.THEIRS);
            for (String commitId : commitIds) {
                ObjectId objectId = ObjectId.fromString(commitId);
                cherryPickCommand.include(objectId);
            }//from  w  w w  .j  a  va  2 s .co m
            CherryPickResult cherryPickResult = cherryPickCommand.call();

            // tag
            PersonIdent authorIdent = helper.getAuthorIdent(author);
            Ref tagResult = git.tag().setTagger(authorIdent).setMessage(comment).call();
        } catch (GitAPIException e) {
            logger.error("Error when publishing site " + site + " to environment " + environment, e);
        }
    }

}

From source file:org.dstadler.jgit.porcelain.ShowFileDiff.java

License:Apache License

private static AbstractTreeIterator prepareTreeParser(Repository repository, String objectId)
        throws IOException {
    // from the commit we can build the tree which allows us to construct the TreeParser
    //noinspection Duplicates
    try (RevWalk walk = new RevWalk(repository)) {
        RevCommit commit = walk.parseCommit(ObjectId.fromString(objectId));
        RevTree tree = walk.parseTree(commit.getTree().getId());

        CanonicalTreeParser oldTreeParser = new CanonicalTreeParser();
        try (ObjectReader oldReader = repository.newObjectReader()) {
            oldTreeParser.reset(oldReader, tree.getId());
        }//  w  ww .j av a  2 s  .c o  m

        walk.dispose();

        return oldTreeParser;
    }
}

From source file:org.eclipse.egit.core.internal.storage.BlobStorageTest.java

License:Open Source License

@Test
public void testFailNotFound() throws Exception {
    BlobStorage blobStorage = new BlobStorage(repository, "file",
            ObjectId.fromString("0123456789012345678901234567890123456789"));
    assertEquals("file", blobStorage.getName());
    try {/*  www .  j  a va 2s  .  co  m*/
        blobStorage.getContents();
        fail("We should not be able to read this 'blob'");
    } catch (CoreException e) {
        assertEquals("Git blob 0123456789012345678901234567890123456789 with path file not found",
                e.getMessage());
    }
}