Example usage for org.eclipse.jgit.lib Constants OBJ_BLOB

List of usage examples for org.eclipse.jgit.lib Constants OBJ_BLOB

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Constants OBJ_BLOB.

Prototype

int OBJ_BLOB

To view the source code for org.eclipse.jgit.lib Constants OBJ_BLOB.

Click Source Link

Document

In-pack object type: blob.

Usage

From source file:org.kuali.student.git.importer.GitImporterParseOptions.java

License:Educational Community License

private void flushPendingBranchCommits() {

    try {/*from   www .  j  a va  2s  .co  m*/

        RevWalk rw = new RevWalk(repo);

        List<GitBranchData> externalsAwareOrdering = ExternalsUtils
                .computeExternalsAwareOrdering(knownBranchMap.values());

        for (GitBranchData data : externalsAwareOrdering) {

            String branchName = data.getBranchName();

            if (data.getExternals().size() > 0) {
                ObjectInserter objectInserter = repo.newObjectInserter();

                String fusionPluginDataString = ExternalModuleUtils.createFusionMavenPluginDataFileString(
                        currentRevision, repo, data.getExternals(), revisionMapper);

                ObjectId id = objectInserter.insert(Constants.OBJ_BLOB, fusionPluginDataString.getBytes());

                try {
                    data.addBlob(data.getBranchPath() + "/" + "fusion-maven-plugin.dat", id, blobLog);
                } catch (VetoBranchException e) {
                    // should never happen
                    log.error("failed to add fusion-maven-plugin.dat to the branch skipping. branchName = "
                            + data.getBranchName(), e);
                }

                objectInserter.flush();
                objectInserter.release();
            } else {
                // check for and remove if present.
                ObjectId blobId = data.findPath(repo, "fusion-maven-plugin.dat");

                if (blobId != null)
                    data.deletePath(data.getBranchPath() + "/" + "fusion-maven-plugin.dat", currentRevision);
            }

            Set<ObjectId> parentSet = new HashSet<ObjectId>();

            ObjectId parentId = data.getParentId();

            if (parentId != null)
                parentSet.add(parentId);

            parentSet.addAll(computeSvnMergeInfoParentIds(currentRevision, data));

            parentSet.addAll(data.getMergeParentIds());

            if (data.getBlobsAdded() == 0 && !data.isBlobsDeleted() && !data.isCreated()
                    && !data.isTreeDirty()) {

                // check the parentId is the same
                Ref existingRef = repo.getRef(Constants.R_HEADS + data.getBranchName());

                if (existingRef != null) {

                    if (parentSet.size() > 0 && parentSet.contains(existingRef.getObjectId())) {
                        /*
                         * Directory changes can cause a branch data object
                         * to be created but we really only want to save it
                         * if blob's have been added or deleted.
                         */
                        log.info("skipped commit on branch " + branchName + " at " + currentRevision
                                + " due to no blob changes present.");
                        continue;
                    }

                } else {
                    // existing Ref is null
                    if (parentSet.size() == 0) {
                        log.info("skipped commit on branch " + branchName + " at " + currentRevision
                                + " due to no blob changes present.");
                        continue;
                    }

                    // else fall through
                }

                // else fall through

            }

            // only flush if the branch has data to
            // commit for the current revision
            log.debug("branch = " + branchName + " has data to commit");

            // create the commit
            CommitBuilder commitBuilder = new CommitBuilder();

            ObjectInserter inserter = repo.newObjectInserter();

            // create the tree

            ObjectId treeId = data.buildTree(inserter);

            log.debug("create new tree id = " + treeId.name());

            commitBuilder.setTreeId(treeId);

            commitBuilder.setParentIds(Arrays.asList(parentSet.toArray(new ObjectId[] {})));

            commitBuilder.setAuthor(commitData.getPersonIdent());

            commitBuilder.setCommitter(commitData.getPersonIdent());

            if (printGitSvnIds) {
                StringBuilder commitMessageBuilder = new StringBuilder();

                commitMessageBuilder.append(commitData.getCommitMessage());

                appendGitSvnId(commitMessageBuilder, repositoryBaseUrl, data.getBranchPath(), currentRevision,
                        repositoryUUID);

                commitBuilder.setMessage(commitMessageBuilder.toString());
            } else {
                // just the commit message
                commitBuilder.setMessage(commitData.getCommitMessage());
            }

            ObjectId commitId = inserter.insert(commitBuilder);

            inserter.flush();

            inserter.release();

            // post commit update the branch reference.

            // create the branch in git

            String fullBranchNameReference = Constants.R_HEADS + data.getBranchName();

            if (fullBranchNameReference.length() >= GitBranchUtils.FILE_SYSTEM_NAME_LIMIT) {

                fullBranchNameReference = Constants.R_HEADS
                        + revisionMapper.storeLargeBranchName(fullBranchNameReference, currentRevision);
            }

            if (repo.getRefDatabase().isNameConflicting(fullBranchNameReference)) {
                log.warn(fullBranchNameReference + " is conflicting with an existing reference.");
            }

            Ref ref = GitRefUtils.createOrUpdateBranch(repo, fullBranchNameReference, commitId);

            ObjectId refObjectId = ref.getObjectId();

            log.info(String.format("updated %s to %s", fullBranchNameReference, commitId.name()));

            if (!commitId.equals(refObjectId)) {
                log.warn("failed to update ref for " + branchName);
            }

            List<BranchMergeInfo> accumulatedMergeData = data.getAccumulatedBranchMergeData();

            if (accumulatedMergeData.size() > 0)
                revisionMapper.createMergeData(currentRevision, data.getBranchPath(), accumulatedMergeData);

            repo.getRefDatabase().refresh();

        }

        Map<String, Ref> headRefs = repo.getRefDatabase().getRefs(Constants.R_HEADS);

        List<Ref> refs = new ArrayList<Ref>(headRefs.values());

        revisionMapper.createRevisionMap(currentRevision, refs);

        knownBranchMap.clear();

        rw.release();

    } catch (IOException e) {
        throw new RuntimeException("flushPendingBranchCommits failed on rev = " + currentRevision, e);
    }
}

From source file:org.kuali.student.git.importer.ModuleMergeToolMain.java

License:Educational Community License

/**
 * @param args//from w  ww  .ja  v a2 s . c  om
 */
public static void main(String[] args) {

    if (args.length != 6 && args.length != 7) {
        System.err.println(
                "USAGE: <git repository> <mode> <bare> <object id> <svn:externals containing file> <svn revision> [<ref prefix>]");
        System.err.println("\t<mode> : commit or branch");
        System.err.println("\t<bare> : 0 (false) or 1 (true)");
        System.err.println("\t<object id> : the sha1 of the commit or the name of the branch in branch mode");
        System.err.println(
                "\t<svn:externals file> : contains the content of the svn:externals property for the target");

        System.err.println("\t<ref prefix> : refs/heads (default) or say refs/remotes/origin (test clone)");
        System.exit(-1);
    }

    boolean bare = false;

    if (args[2].trim().equals("1")) {
        bare = true;
    }

    boolean branchMode = false;
    boolean commitMode = false;

    if (args[1].equals("branch"))
        branchMode = true;
    else if (args[1].equals("commit"))
        commitMode = true;

    String reference = args[3].trim();

    String svnExternalsDataFile = args[4].trim();

    Long svnRevision = Long.parseLong(args[5].trim());

    String refPrefix = Constants.R_HEADS;

    if (args.length == 7)
        refPrefix = args[6].trim();

    try {

        Repository repo = GitRepositoryUtils.buildFileRepository(new File(args[0]).getAbsoluteFile(), false,
                bare);

        SvnRevisionMapper revisionMapper = new SvnRevisionMapper(repo);

        if (commitMode) {

            /*
             * 
             */

            List<ExternalModuleInfo> externals = ExternalModuleUtils
                    .extractExternalModuleInfoFromSvnExternalsInputStream(svnRevision,
                            "https://svn.kuali.org/repos/student", new FileInputStream(svnExternalsDataFile));

            /*
             * Take the existing content of the commit pointed at and then materialize the externals within it.
             */

            RevWalk rw = new RevWalk(repo);

            ObjectInserter inserter = repo.newObjectInserter();

            RevCommit commit = rw.parseCommit(ObjectId.fromString(reference));

            TreeWalk tw = new TreeWalk(repo);

            tw.setRecursive(false);

            while (tw.next()) {

                if (tw.getNameString().equals("fusion-maven-plugin.dat")) {
                    ObjectId blobId = tw.getObjectId(0);

                    ObjectLoader loader = repo.newObjectReader().open(blobId, Constants.OBJ_BLOB);

                    List<String> lines = IOUtils.readLines(loader.openStream());

                    // pull out and use the sha1's from the stream to fuse the externals.

                }
            }
            CommitBuilder commitBuilder = new CommitBuilder();

            ObjectReader or;
            commitBuilder.setTreeId(ExternalModuleUtils.createFusedTree(or = repo.newObjectReader(), inserter,
                    rw, commit, externals));

            List<ObjectId> parentIds = new LinkedList<>();

            for (int i = 0; i < commit.getParentCount(); i++) {

                RevCommit parent = commit.getParent(i);

                parentIds.add(parent.getId());

            }

            commitBuilder.setParentIds(parentIds);

            commitBuilder.setAuthor(commit.getAuthorIdent());

            commitBuilder.setCommitter(commit.getCommitterIdent());

            commitBuilder.setMessage(commit.getFullMessage());

            ObjectId commitId = inserter.insert(commitBuilder);

            log.info("new commit id = " + commitId);

            rw.release();

            inserter.release();

            or.release();
        }

    } catch (Exception e) {

        log.error("unexpected Exception ", e);
    }
}

From source file:org.kuali.student.git.model.ExternalModuleUtils.java

License:Educational Community License

/**
 * Look at the given commit and if there is a fusion-maven-plugin.dat in the root of its tree then load and return the contents.
 * // w  ww .  j a v a2 s. c  o m
 * @param commit
 * @return the ExternalsModuleInfo's found, an empty list if none are found.
 * @throws IOException 
 * @throws CorruptObjectException 
 * @throws IncorrectObjectTypeException 
 * @throws MissingObjectException 
 */
public static List<ExternalModuleInfo> findExternalModulesForCommit(Repository repo, RevCommit commit)
        throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException {

    List<ExternalModuleInfo> modules = new LinkedList<ExternalModuleInfo>();

    GitTreeProcessor treeProcessor = new GitTreeProcessor(repo);

    GitTreeNodeData tree = treeProcessor.extractExistingTreeData(commit.getTree().getId(), "");

    ObjectId fusionDataBlobId = tree.find(repo, "fusion-maven-plugin.dat");

    if (fusionDataBlobId == null)
        return modules;

    ObjectReader reader = repo.newObjectReader();

    modules = ExternalModuleUtils
            .extractFusionMavenPluginData(reader.open(fusionDataBlobId, Constants.OBJ_BLOB).openStream());

    reader.release();

    return modules;

}

From source file:org.kuali.student.git.model.NodeProcessor.java

License:Educational Community License

@Override
public GitBranchData getBranchData(String branchName, long revision) {

    GitBranchData data = knownBranchMap.get(branchName);

    if (data == null) {
        data = new GitBranchData(repo, branchName, revision, revisionMapper, treeProcessor,
                treeProcessor.getNodeInitializer());

        /*/*from  w  w  w. j  av  a  2  s .  c o m*/
         * Notice if there is already a branch of the same name (it should be the parent of this new commit).
         */
        try {

            ObjectId parentId = revisionMapper.getRevisionBranchHead((revision - 1), data.getBranchName());

            if (parentId != null) {
                data.setParentId(parentId);

                /*
                 * Check for the existense of a fusion-maven-plugin.dat file in the root of this commit load in the externals if they exist.
                 */
                GitTreeData parentTree = treeProcessor.extractExistingTreeDataFromCommit(parentId);

                ObjectId fusionData = parentTree.find(repo, "fusion-maven-plugin.dat");

                if (fusionData != null) {

                    ObjectReader reader = repo.newObjectReader();

                    List<ExternalModuleInfo> existingExternals = ExternalModuleUtils
                            .extractFusionMavenPluginData(
                                    reader.open(fusionData, Constants.OBJ_BLOB).openStream());

                    data.setExternals(existingExternals);

                }
            }

        } catch (Exception e) {
            log.debug("no existing reference for branch = " + data.getBranchName());
        }

        knownBranchMap.put(branchName, data);
    }

    return data;
}

From source file:org.kuali.student.git.model.NodeProcessor.java

License:Educational Community License

private ObjectId storeBlob(GitBranchData gbd, String path, long contentLength, long propContentLength) {

    try {//from w  w  w.jav  a  2  s. c o m

        long adjustedContentLength = contentLength - propContentLength;

        if (propContentLength > 0) {
            getInputStream().skip(propContentLength);
        }

        /*
         * We want to replace the contents of the path file with the content
         * that we read from the input stream.
         */

        ObjectInserter objectInserter = repo.newObjectInserter();

        ObjectId id = objectInserter.insert(Constants.OBJ_BLOB, adjustedContentLength,
                new BoundedInputStream(getInputStream(), adjustedContentLength));

        objectInserter.flush();
        objectInserter.release();

        return id;

    } catch (Exception e) {

        log.error("onNodeContentChanged failed: ", e);
        throw new RuntimeException("onNodeContentLength failed", e);
    }
}

From source file:org.kuali.student.git.model.TestKSRevision27974.java

License:Educational Community License

@Test
public void testRevision27974() throws IOException {
    File gitRepository = new File("target/ks-r27974");

    FileUtils.deleteDirectory(gitRepository);

    Repository repository = GitRepositoryUtils.buildFileRepository(gitRepository, true);

    GitImporterMain//from   ww  w . ja  va  2 s . c o m
            .main(new String[] { "src/test/resources/ks-r27974.dump.bz2", gitRepository.getAbsolutePath(),
                    "target/ks-r27974-ks-veto.log", "target/ks-r27974-ks-copyFrom-skipped.log",
                    "target/ks-r27974-blob.log", "0", "https://svn.kuali.org/repos/student", "uuid" });

    // get the fusion-maven-plugin.dat file and check its contents are what we expect.

    SvnRevisionMapper revisionMapper = new SvnRevisionMapper(repository);

    revisionMapper.initialize();

    List<SvnRevisionMap> heads = revisionMapper.getRevisionHeads(27974L);

    Assert.assertNotNull(heads);

    Assert.assertEquals(1, heads.size());

    SvnRevisionMap revMap = heads.get(0);

    ObjectId branchHead = ObjectId.fromString(revMap.getCommitId());

    RevWalk rw = new RevWalk(repository);

    RevCommit commit = rw.parseCommit(branchHead);

    TreeWalk tw = new TreeWalk(repository);

    tw.addTree(commit.getTree().getId());

    Assert.assertTrue("should have been one file", tw.next());

    Assert.assertEquals(FileMode.REGULAR_FILE, tw.getFileMode(0));

    ObjectId blobId = tw.getObjectId(0);

    ObjectLoader loader = repository.newObjectReader().open(blobId, Constants.OBJ_BLOB);

    List<String> lines = IOUtils.readLines(loader.openStream(), "UTF-8");

    Assert.assertEquals(2, lines.size());

    String firstLine = lines.get(0);

    Assert.assertEquals(
            "# module = ks-api branch Path = sandbox/ks-1.3-core-slice-demo/modules/ks-api/trunk revision = 27974",
            firstLine);

    String secondLine = lines.get(1);

    Assert.assertEquals("ks-api::sandbox_ks-1.3-core-slice-demo_modules_ks-api_trunk::UNKNOWN", secondLine);

    tw.release();

    rw.release();

    revisionMapper.shutdown();

}

From source file:org.kuali.student.git.model.tree.utils.GitTreeProcessor.java

License:Educational Community License

public ObjectLoader getBlob(ObjectId blobId)
        throws MissingObjectException, IncorrectObjectTypeException, IOException {

    return objectReader.open(blobId, Constants.OBJ_BLOB);
}

From source file:org.kuali.student.git.model.tree.utils.JGitTreeUtils.java

License:Educational Community License

/**
 * Helper to load the mutable tree data (at the root level) for the indicated tree and to then insert the blob and content provided.
 * //from   w w  w. j a v  a  2s . c om
 * @param or
 * @param inserter
 * @param treeId
 * @param blobName
 * @param blobContent
 * @return
 * @throws MissingObjectException
 * @throws IncorrectObjectTypeException
 * @throws CorruptObjectException
 * @throws IOException
 */
public static List<JGitTreeData> insertBlob(ObjectReader or, ObjectInserter inserter, ObjectId treeId,
        String blobName, String blobContent)
        throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException {

    List<JGitTreeData> data = extractBaseTreeLevel(or, treeId);

    ObjectId blobId = inserter.insert(Constants.OBJ_BLOB, blobContent.getBytes());

    data.add(new JGitTreeData(blobName, FileMode.REGULAR_FILE, blobId));

    return data;
}

From source file:org.kuali.student.git.model.utils.GitTestUtils.java

License:Educational Community License

public static void createBranch(Repository repository, String branchName, String fileName, String fileContent)
        throws IOException, BranchRefExistsException {

    ObjectInserter inserter = repository.newObjectInserter();

    // store the blob
    ObjectId blobId = inserter.insert(Constants.OBJ_BLOB, fileContent.getBytes());

    // create the tree
    TreeFormatter tf = new TreeFormatter();

    tf.append(fileName, FileMode.REGULAR_FILE, blobId);

    ObjectId treeId = inserter.insert(tf);

    // make the commit
    CommitBuilder cb = new CommitBuilder();

    PersonIdent pi;// w  w w .java  2 s  .c om
    cb.setAuthor(pi = new PersonIdent("admin", "admin@kuali.org"));

    cb.setCommitter(pi);

    cb.setMessage("committed " + fileName);

    cb.setTreeId(treeId);

    cb.setEncoding("UTF-8");

    // save the branch

    ObjectId commit = inserter.insert(cb);

    GitRefUtils.createBranch(repository, branchName, commit);

    inserter.flush();
    inserter.release();
}

From source file:org.kuali.student.svn.model.AbstractGitRespositoryTestCase.java

License:Educational Community License

protected List<String> getBlobContents(ObjectId blobId)
        throws MissingObjectException, IncorrectObjectTypeException, IOException {

    ObjectLoader loader = repo.newObjectReader().open(blobId, Constants.OBJ_BLOB);

    List<String> lines = IOUtils.readLines(loader.openStream(), "UTF-8");

    return lines;
}