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:hudson.plugins.git.util.GitUtilsTest.java

License:Open Source License

@BeforeClass
public static void createSampleOriginRepo() throws Exception {
    String fileName = "README";
    originRepo.init();//from   www. ja  v a 2s .co  m
    originRepo.git("config", "user.name", "Author User Name");
    originRepo.git("config", "user.email", "author.user.name@mail.example.com");
    originRepo.git("tag", PRIOR_TAG_NAME_1);
    originRepo.git("tag", "-a", PRIOR_TAG_NAME_2, "-m", "Annotated tag " + PRIOR_TAG_NAME_2);
    priorHeadId = ObjectId.fromString(originRepo.head());

    originRepo.git("checkout", "-b", OLDER_BRANCH_NAME);
    branchList = new ArrayList<>();
    branchList.add(new Branch(OLDER_BRANCH_NAME, priorHeadId));
    branchList.add(new Branch("refs/tags/" + PRIOR_TAG_NAME_1, priorHeadId));
    branchList.add(new Branch("refs/tags/" + PRIOR_TAG_NAME_2, priorHeadId));
    priorRevision = new Revision(priorHeadId, branchList);
    priorBranchSpecList = new ArrayList<>();
    priorBranchSpecList.add(new BranchSpec(OLDER_BRANCH_NAME));

    originRepo.git("checkout", "master");
    originRepo.write(fileName, "This is the " + HEAD_TAG_NAME_0 + " README file " + RANDOM.nextInt());
    originRepo.git("add", fileName);
    originRepo.git("commit", "-m", "Adding " + fileName + " tagged " + HEAD_TAG_NAME_0, fileName);
    originRepo.git("tag", HEAD_TAG_NAME_0);
    headTag0Id = ObjectId.fromString(originRepo.head());
    headTag0Revision = new Revision(headTag0Id);

    originRepo.write(fileName, "This is the README file " + RANDOM.nextInt());
    originRepo.git("add", fileName);
    originRepo.git("commit", "-m", "Adding " + fileName, fileName);
    originRepo.git("tag", HEAD_TAG_NAME_1);
    originRepo.git("tag", "-a", HEAD_TAG_NAME_2, "-m", "Annotated tag " + HEAD_TAG_NAME_2);
    headId = ObjectId.fromString(originRepo.head());
    branchSpecList = new ArrayList<>();
    branchList = new ArrayList<>();
    branchSpecList.add(new BranchSpec("master"));
    branchSpecList.add(new BranchSpec("refs/tags/" + HEAD_TAG_NAME_0));
    branchSpecList.add(new BranchSpec("refs/tags/" + HEAD_TAG_NAME_1));
    branchSpecList.add(new BranchSpec("refs/tags/" + HEAD_TAG_NAME_2));
    branchList.add(new Branch("master", headId));
    branchList.add(new Branch("refs/tags/" + HEAD_TAG_NAME_0, headId));
    branchList.add(new Branch("refs/tags/" + HEAD_TAG_NAME_1, headId));
    branchList.add(new Branch("refs/tags/" + HEAD_TAG_NAME_2, headId));
    for (String branchName : HEAD_BRANCH_NAMES) {
        if (!branchName.equals("master")) {
            originRepo.git("checkout", "-b", branchName);
            branchSpecList.add(new BranchSpec(branchName));
            branchList.add(new Branch(branchName, headId));
        }
    }
    originRepo.git("checkout", "master"); // Master branch as current branch in origin repo
    headRevision = new Revision(headId, branchList);

    File gitDir = repoParentFolder.newFolder("test-repo");
    gitClient = Git.with(NULL_LISTENER, ENV).in(gitDir).using("git").getClient();
    gitClient.init();
    gitClient.clone_().url(originRepo.fileUrl()).repositoryName("origin").execute();
    gitClient.checkout("origin/master", "master");
}

From source file:hudson.plugins.git.util.GitUtilsTest.java

License:Open Source License

@Test
public void testGetRevisionForSHA1UnknownRevision() throws Exception {
    ObjectId unknown = ObjectId.fromString("a422d10c6dc4262effb12f9e7a64911111000000");
    Revision unknownRevision = new Revision(unknown);
    Revision revision = gitUtils.getRevisionForSHA1(unknown);
    assertThat(revision, is(unknownRevision));
}

From source file:it.com.atlassian.labs.speakeasy.util.jgit.FixedTransportHttp.java

License:Eclipse Distribution License

private FetchConnection newDumbConnection(InputStream in) throws IOException, PackProtocolException {
    HttpObjectDB d = new HttpObjectDB(objectsUrl);
    BufferedReader br = toBufferedReader(in);
    Map<String, Ref> refs;
    try {/*from www .j  a v a2 s . c  o m*/
        refs = d.readAdvertisedImpl(br);
    } finally {
        br.close();
    }

    if (!refs.containsKey(Constants.HEAD)) {
        // If HEAD was not published in the info/refs file (it usually
        // is not there) download HEAD by itself as a loose file and do
        // the resolution by hand.
        //
        HttpURLConnection conn = httpOpen(new URL(baseUrl, Constants.HEAD));
        int status = HttpSupport.response(conn);
        switch (status) {
        case HttpURLConnection.HTTP_OK: {
            br = toBufferedReader(openInputStream(conn));
            try {
                String line = br.readLine();
                if (line != null && line.startsWith(RefDirectory.SYMREF)) {
                    String target = line.substring(RefDirectory.SYMREF.length());
                    Ref r = refs.get(target);
                    if (r == null)
                        r = new ObjectIdRef.Unpeeled(Ref.Storage.NEW, target, null);
                    r = new SymbolicRef(Constants.HEAD, r);
                    refs.put(r.getName(), r);
                } else if (line != null && ObjectId.isId(line)) {
                    Ref r = new ObjectIdRef.Unpeeled(Ref.Storage.NETWORK, Constants.HEAD,
                            ObjectId.fromString(line));
                    refs.put(r.getName(), r);
                }
            } finally {
                br.close();
            }
            break;
        }

        case HttpURLConnection.HTTP_NOT_FOUND:
            break;

        default:
            throw new TransportException(uri,
                    MessageFormat.format(JGitText.get().cannotReadHEAD, status, conn.getResponseMessage()));
        }
    }

    WalkFetchConnection wfc = new WalkFetchConnection(this, d);
    wfc.available(refs);
    return wfc;
}

From source file:it.com.atlassian.labs.speakeasy.util.jgit.WalkRemoteObjectDatabase.java

License:Eclipse Distribution License

private void readPackedRefsImpl(final Map<String, Ref> avail, final BufferedReader br) throws IOException {
    Ref last = null;// w ww .ja  v a2  s. co  m
    boolean peeled = false;
    for (;;) {
        String line = br.readLine();
        if (line == null)
            break;
        if (line.charAt(0) == '#') {
            if (line.startsWith(RefDirectory.PACKED_REFS_HEADER)) {
                line = line.substring(RefDirectory.PACKED_REFS_HEADER.length());
                peeled = line.contains(RefDirectory.PACKED_REFS_PEELED);
            }
            continue;
        }
        if (line.charAt(0) == '^') {
            if (last == null)
                throw new TransportException(JGitText.get().peeledLineBeforeRef);
            final ObjectId id = ObjectId.fromString(line.substring(1));
            last = new ObjectIdRef.PeeledTag(Ref.Storage.PACKED, last.getName(), last.getObjectId(), id);
            avail.put(last.getName(), last);
            continue;
        }

        final int sp = line.indexOf(' ');
        if (sp < 0)
            throw new TransportException(MessageFormat.format(JGitText.get().unrecognizedRef, line));
        final ObjectId id = ObjectId.fromString(line.substring(0, sp));
        final String name = line.substring(sp + 1);
        if (peeled)
            last = new ObjectIdRef.PeeledNonTag(Ref.Storage.PACKED, name, id);
        else
            last = new ObjectIdRef.Unpeeled(Ref.Storage.PACKED, name, id);
        avail.put(last.getName(), last);
    }
}

From source file:jenkins.plugins.git.GitSCMFileSystem.java

License:Open Source License

/**
 * Constructor.//from w  w w  .  j a va 2 s  .c om
 *
 * @param client the client
 * @param remote the remote GIT URL
 * @param head   identifier for the head commit to be referenced
 * @param rev    the revision.
 * @throws IOException on I/O error
 * @throws InterruptedException on thread interruption
 */
protected GitSCMFileSystem(GitClient client, String remote, final String head,
        @CheckForNull AbstractGitSCMSource.SCMRevisionImpl rev) throws IOException, InterruptedException {
    super(rev);
    this.remote = remote;
    this.head = head;
    cacheEntry = AbstractGitSCMSource.getCacheEntry(remote);
    listener = new LogTaskListener(LOGGER, Level.FINER);
    this.client = client;
    commitId = rev == null ? invoke(new FSFunction<ObjectId>() {
        @Override
        public ObjectId invoke(Repository repository) throws IOException, InterruptedException {
            return repository.getRef(head).getObjectId();
        }
    }) : ObjectId.fromString(rev.getHash());
}

From source file:jenkins.plugins.git.GitSCMFileSystem.java

License:Open Source License

@Override
public boolean changesSince(@CheckForNull SCMRevision revision, @NonNull OutputStream changeLogStream)
        throws UnsupportedOperationException, IOException, InterruptedException {
    AbstractGitSCMSource.SCMRevisionImpl rev = getRevision();
    if (rev == null ? revision == null : rev.equals(revision)) {
        // special case where somebody is asking one of two stupid questions:
        // 1. what has changed between the latest and the latest
        // 2. what has changed between the current revision and the current revision
        return false;
    }//from w w  w.  ja  v  a  2  s.  c om
    Lock cacheLock = AbstractGitSCMSource.getCacheLock(cacheEntry);
    cacheLock.lock();
    try {
        File cacheDir = AbstractGitSCMSource.getCacheDir(cacheEntry);
        if (cacheDir == null || !cacheDir.isDirectory()) {
            throw new IOException("Closed");
        }
        boolean executed = false;
        ChangelogCommand changelog = client.changelog();
        try (Writer out = new OutputStreamWriter(changeLogStream, "UTF-8")) {
            changelog.includes(commitId);
            ObjectId fromCommitId;
            if (revision instanceof AbstractGitSCMSource.SCMRevisionImpl) {
                fromCommitId = ObjectId.fromString(((AbstractGitSCMSource.SCMRevisionImpl) revision).getHash());
                changelog.excludes(fromCommitId);
            } else {
                fromCommitId = null;
            }
            changelog.to(out).max(GitSCM.MAX_CHANGELOG).execute();
            executed = true;
            return !commitId.equals(fromCommitId);
        } catch (GitException ge) {
            throw new IOException("Unable to retrieve changes", ge);
        } finally {
            if (!executed) {
                changelog.abort();
            }
            changeLogStream.close();
        }
    } finally {
        cacheLock.unlock();
    }
}

From source file:jenkins.plugins.git.MergeWithGitSCMExtension.java

License:Open Source License

@Override
public Revision decorateRevisionToBuild(GitSCM scm, Run<?, ?> build, GitClient git, TaskListener listener,
        Revision marked, Revision rev) throws IOException, InterruptedException, GitException {
    ObjectId baseObjectId;/*from ww  w . ja v  a 2  s  . c  o  m*/
    if (StringUtils.isBlank(baseHash)) {
        try {
            baseObjectId = git.revParse(Constants.R_REFS + baseName);
        } catch (GitException e) {
            listener.getLogger().printf("Unable to determine head revision of %s prior to merge with PR%n",
                    baseName);
            throw e;
        }
    } else {
        baseObjectId = ObjectId.fromString(baseHash);
    }
    listener.getLogger().printf("Merging %s commit %s into PR head commit %s%n", baseName, baseObjectId.name(),
            rev.getSha1String());
    checkout(scm, build, git, listener, rev);
    try {
        /* could parse out of JenkinsLocationConfiguration.get().getAdminAddress() but seems overkill */
        git.setAuthor("Jenkins", "nobody@nowhere");
        git.setCommitter("Jenkins", "nobody@nowhere");
        MergeCommand cmd = git.merge().setRevisionToMerge(baseObjectId);
        for (GitSCMExtension ext : scm.getExtensions()) {
            // By default we do a regular merge, allowing it to fast-forward.
            ext.decorateMergeCommand(scm, build, git, listener, cmd);
        }
        cmd.execute();
    } catch (GitException x) {
        // TODO clarify these TODO comments copied from GitHub Branch Source

        // Try to revert merge conflict markers.
        // TODO IGitAPI offers a reset(hard) method yet GitClient does not. Why?
        checkout(scm, build, git, listener, rev);
        // TODO would be nicer to throw an AbortException with just the message, but this is actually worse
        // until git-client 1.19.7+
        throw x;
    }
    build.addAction(new MergeRecord(baseName, baseObjectId.getName())); // does not seem to be used, but just in case
    ObjectId mergeRev = git.revParse(Constants.HEAD);
    listener.getLogger().println("Merge succeeded, producing " + mergeRev.name());
    return new Revision(mergeRev, rev.getBranches()); // note that this ensures Build.revision != Build.marked
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.agent.command.impl.RefImpl.java

License:Apache License

public RefImpl(String name, String commit) {
    myName = name;
    myObjectId = ObjectId.fromString(commit);
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.commitInfo.GitCommitsInfoBuilder.java

License:Apache License

private void initWalk(@NotNull final RevWalk walk, @NotNull final Map<String, String> currentState) {
    walk.sort(RevSort.TOPO);//from  w w  w  .  j a  v a2s  .c  o m

    for (String tip : new HashSet<String>(currentState.values())) {
        try {
            final RevObject obj = walk.parseAny(ObjectId.fromString(tip));
            if (obj instanceof RevCommit) {
                walk.markStart((RevCommit) obj);
            }
        } catch (MissingObjectException e) {
            //log
        } catch (IOException e) {
            //log
        }
    }
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.CommitLoaderImpl.java

License:Apache License

@NotNull
public RevCommit loadCommit(@NotNull OperationContext context, @NotNull GitVcsRoot root,
        @NotNull String revision) throws VcsException, IOException {
    String commitSHA = GitUtils.versionRevision(revision);
    Repository db = context.getRepository(root);
    ObjectId commitId = ObjectId.fromString(commitSHA);
    try {/*ww w  . j av a2s .c  om*/
        return getCommit(db, commitId);
    } catch (IOException ex) {
        //ignore error, will try to fetch
    }

    LOG.debug("Cannot find commit " + commitSHA + " in repository " + root.debugInfo() + ", fetch branch "
            + root.getRef());
    fetchBranchData(root, db);

    try {
        return getCommit(db, commitId);
    } catch (IOException e) {
        LOG.debug("Cannot find commit " + commitSHA + " in the branch " + root.getRef() + " of repository "
                + root.debugInfo() + ", fetch all branches");
        RefSpec spec = new RefSpec().setSourceDestination("refs/*", "refs/*").setForceUpdate(true);
        fetch(db, root.getRepositoryFetchURL(), asList(spec), new FetchSettings(root.getAuthSettings()));
        try {
            return getCommit(db, commitId);
        } catch (IOException e1) {
            throw new VcsException("Cannot find commit " + commitSHA + " in repository " + root.debugInfo());
        }
    }
}