Search in sources :

Example 1 with FileMode

use of org.eclipse.jgit.lib.FileMode in project gitblit by gitblit.

the class BugtraqConfig method getBaseConfig.

// Utils ==================================================================
@Nullable
private static Config getBaseConfig(@NotNull Repository repository, @NotNull String configFileName) throws IOException, ConfigInvalidException {
    final Config baseConfig;
    if (repository.isBare()) {
        // read bugtraq config directly from the repository
        String content = null;
        RevWalk rw = new RevWalk(repository);
        TreeWalk tw = new TreeWalk(repository);
        tw.setFilter(PathFilterGroup.createFromStrings(configFileName));
        try {
            final Ref ref = repository.getRef(Constants.HEAD);
            if (ref == null) {
                return null;
            }
            ObjectId headId = ref.getTarget().getObjectId();
            if (headId == null || ObjectId.zeroId().equals(headId)) {
                return null;
            }
            RevCommit commit = rw.parseCommit(headId);
            RevTree tree = commit.getTree();
            tw.reset(tree);
            while (tw.next()) {
                ObjectId entid = tw.getObjectId(0);
                FileMode entmode = tw.getFileMode(0);
                if (FileMode.REGULAR_FILE == entmode) {
                    ObjectLoader ldr = repository.open(entid, Constants.OBJ_BLOB);
                    content = new String(ldr.getCachedBytes(), commit.getEncoding());
                    break;
                }
            }
        } finally {
            rw.dispose();
            tw.close();
        }
        if (content == null) {
            // config not found
            baseConfig = null;
        } else {
            // parse the config
            Config config = new Config();
            config.fromText(content);
            baseConfig = config;
        }
    } else {
        // read bugtraq config from work tree
        final File baseFile = new File(repository.getWorkTree(), configFileName);
        if (baseFile.isFile()) {
            FileBasedConfig fileConfig = new FileBasedConfig(baseFile, repository.getFS());
            fileConfig.load();
            baseConfig = fileConfig;
        } else {
            baseConfig = null;
        }
    }
    return baseConfig;
}
Also used : FileMode(org.eclipse.jgit.lib.FileMode) Ref(org.eclipse.jgit.lib.Ref) ObjectId(org.eclipse.jgit.lib.ObjectId) Config(org.eclipse.jgit.lib.Config) FileBasedConfig(org.eclipse.jgit.storage.file.FileBasedConfig) ObjectLoader(org.eclipse.jgit.lib.ObjectLoader) RevWalk(org.eclipse.jgit.revwalk.RevWalk) FileBasedConfig(org.eclipse.jgit.storage.file.FileBasedConfig) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) File(java.io.File) RevTree(org.eclipse.jgit.revwalk.RevTree) RevCommit(org.eclipse.jgit.revwalk.RevCommit) Nullable(org.jetbrains.annotations.Nullable)

Example 2 with FileMode

use of org.eclipse.jgit.lib.FileMode in project gitblit by gitblit.

the class CompressionUtils method tar.

/**
	 * Compresses/archives the contents of the tree at the (optionally)
	 * specified revision and the (optionally) specified basepath to the
	 * supplied outputstream.
	 *
	 * @param algorithm
	 *            compression algorithm for tar (optional)
	 * @param repository
	 * @param basePath
	 *            if unspecified, entire repository is assumed.
	 * @param objectId
	 *            if unspecified, HEAD is assumed.
	 * @param os
	 * @return true if repository was successfully zipped to supplied output
	 *         stream
	 */
private static boolean tar(String algorithm, Repository repository, IFilestoreManager filestoreManager, String basePath, String objectId, OutputStream os) {
    RevCommit commit = JGitUtils.getCommit(repository, objectId);
    if (commit == null) {
        return false;
    }
    OutputStream cos = os;
    if (!StringUtils.isEmpty(algorithm)) {
        try {
            cos = new CompressorStreamFactory().createCompressorOutputStream(algorithm, os);
        } catch (CompressorException e1) {
            error(e1, repository, "{0} failed to open {1} stream", algorithm);
        }
    }
    boolean success = false;
    RevWalk rw = new RevWalk(repository);
    TreeWalk tw = new TreeWalk(repository);
    try {
        tw.reset();
        tw.addTree(commit.getTree());
        TarArchiveOutputStream tos = new TarArchiveOutputStream(cos);
        tos.setAddPaxHeadersForNonAsciiNames(true);
        tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
        if (!StringUtils.isEmpty(basePath)) {
            PathFilter f = PathFilter.create(basePath);
            tw.setFilter(f);
        }
        tw.setRecursive(true);
        MutableObjectId id = new MutableObjectId();
        long modified = commit.getAuthorIdent().getWhen().getTime();
        while (tw.next()) {
            FileMode mode = tw.getFileMode(0);
            if (mode == FileMode.GITLINK || mode == FileMode.TREE) {
                continue;
            }
            tw.getObjectId(id, 0);
            ObjectLoader loader = repository.open(id);
            if (FileMode.SYMLINK == mode) {
                TarArchiveEntry entry = new TarArchiveEntry(tw.getPathString(), TarArchiveEntry.LF_SYMLINK);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                loader.copyTo(bos);
                entry.setLinkName(bos.toString());
                entry.setModTime(modified);
                tos.putArchiveEntry(entry);
                tos.closeArchiveEntry();
            } else {
                TarArchiveEntry entry = new TarArchiveEntry(tw.getPathString());
                entry.setMode(mode.getBits());
                entry.setModTime(modified);
                FilestoreModel filestoreItem = null;
                if (JGitUtils.isPossibleFilestoreItem(loader.getSize())) {
                    filestoreItem = JGitUtils.getFilestoreItem(tw.getObjectReader().open(id));
                }
                final long size = (filestoreItem == null) ? loader.getSize() : filestoreItem.getSize();
                entry.setSize(size);
                tos.putArchiveEntry(entry);
                if (filestoreItem == null) {
                    //Copy repository stored file
                    loader.copyTo(tos);
                } else {
                    //Copy filestore file
                    try (FileInputStream streamIn = new FileInputStream(filestoreManager.getStoragePath(filestoreItem.oid))) {
                        IOUtils.copyLarge(streamIn, tos);
                    } catch (Throwable e) {
                        LOGGER.error(MessageFormat.format("Failed to archive filestore item {0}", filestoreItem.oid), e);
                        //Handle as per other errors 
                        throw e;
                    }
                }
                tos.closeArchiveEntry();
            }
        }
        tos.finish();
        tos.close();
        cos.close();
        success = true;
    } catch (IOException e) {
        error(e, repository, "{0} failed to {1} stream files from commit {2}", algorithm, commit.getName());
    } finally {
        tw.close();
        rw.dispose();
    }
    return success;
}
Also used : FileMode(org.eclipse.jgit.lib.FileMode) PathFilter(org.eclipse.jgit.treewalk.filter.PathFilter) FilestoreModel(com.gitblit.models.FilestoreModel) ByteArrayOutputStream(java.io.ByteArrayOutputStream) TarArchiveOutputStream(org.apache.commons.compress.archivers.tar.TarArchiveOutputStream) ZipArchiveOutputStream(org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream) OutputStream(java.io.OutputStream) CompressorStreamFactory(org.apache.commons.compress.compressors.CompressorStreamFactory) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) TarArchiveEntry(org.apache.commons.compress.archivers.tar.TarArchiveEntry) FileInputStream(java.io.FileInputStream) MutableObjectId(org.eclipse.jgit.lib.MutableObjectId) CompressorException(org.apache.commons.compress.compressors.CompressorException) ObjectLoader(org.eclipse.jgit.lib.ObjectLoader) TarArchiveOutputStream(org.apache.commons.compress.archivers.tar.TarArchiveOutputStream) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 3 with FileMode

use of org.eclipse.jgit.lib.FileMode in project gitblit by gitblit.

the class RawServlet method streamFromRepo.

protected boolean streamFromRepo(HttpServletRequest request, HttpServletResponse response, Repository repository, RevCommit commit, String requestedPath) throws IOException {
    boolean served = false;
    RevWalk rw = new RevWalk(repository);
    TreeWalk tw = new TreeWalk(repository);
    try {
        tw.reset();
        tw.addTree(commit.getTree());
        PathFilter f = PathFilter.create(requestedPath);
        tw.setFilter(f);
        tw.setRecursive(true);
        MutableObjectId id = new MutableObjectId();
        ObjectReader reader = tw.getObjectReader();
        while (tw.next()) {
            FileMode mode = tw.getFileMode(0);
            if (mode == FileMode.GITLINK || mode == FileMode.TREE) {
                continue;
            }
            tw.getObjectId(id, 0);
            String filename = StringUtils.getLastPathElement(requestedPath);
            try {
                String userAgent = request.getHeader("User-Agent");
                if (userAgent != null && userAgent.indexOf("MSIE 5.5") > -1) {
                    response.setHeader("Content-Disposition", "filename=\"" + URLEncoder.encode(filename, Constants.ENCODING) + "\"");
                } else if (userAgent != null && userAgent.indexOf("MSIE") > -1) {
                    response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(filename, Constants.ENCODING) + "\"");
                } else {
                    response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(filename.getBytes(Constants.ENCODING), "latin1") + "\"");
                }
            } catch (UnsupportedEncodingException e) {
                response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
            }
            long len = reader.getObjectSize(id, org.eclipse.jgit.lib.Constants.OBJ_BLOB);
            setContentType(response, "application/octet-stream");
            response.setIntHeader("Content-Length", (int) len);
            ObjectLoader ldr = repository.open(id);
            ldr.copyTo(response.getOutputStream());
            served = true;
        }
    } finally {
        tw.close();
        rw.dispose();
    }
    response.flushBuffer();
    return served;
}
Also used : FileMode(org.eclipse.jgit.lib.FileMode) MutableObjectId(org.eclipse.jgit.lib.MutableObjectId) PathFilter(org.eclipse.jgit.treewalk.filter.PathFilter) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ObjectReader(org.eclipse.jgit.lib.ObjectReader) ObjectLoader(org.eclipse.jgit.lib.ObjectLoader) RevWalk(org.eclipse.jgit.revwalk.RevWalk) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk)

Example 4 with FileMode

use of org.eclipse.jgit.lib.FileMode in project gitiles by GerritCodeReview.

the class PathServlet method writeTreeText.

private void writeTreeText(HttpServletRequest req, HttpServletResponse res, WalkResult wr) throws IOException {
    setTypeHeader(res, wr.type.mode.getObjectType());
    setModeHeader(res, wr.type);
    try (Writer writer = startRenderText(req, res);
        OutputStream out = BaseEncoding.base64().encodingStream(writer)) {
        // Match git ls-tree format.
        while (wr.tw.next()) {
            FileMode mode = wr.tw.getFileMode(0);
            out.write(Constants.encode(String.format("%06o", mode.getBits())));
            out.write(' ');
            out.write(Constants.encode(Constants.typeString(mode.getObjectType())));
            out.write(' ');
            wr.tw.getObjectId(0).copyTo(out);
            out.write('\t');
            out.write(Constants.encode(QuotedString.GIT_PATH.quote(wr.tw.getNameString())));
            out.write('\n');
        }
    }
}
Also used : FileMode(org.eclipse.jgit.lib.FileMode) OutputStream(java.io.OutputStream) Writer(java.io.Writer)

Example 5 with FileMode

use of org.eclipse.jgit.lib.FileMode in project gitblit by gitblit.

the class JGitUtils method getByteContent.

/**
	 * Retrieves the raw byte content of a file in the specified tree.
	 *
	 * @param repository
	 * @param tree
	 *            if null, the RevTree from HEAD is assumed.
	 * @param path
	 * @return content as a byte []
	 */
public static byte[] getByteContent(Repository repository, RevTree tree, final String path, boolean throwError) {
    RevWalk rw = new RevWalk(repository);
    TreeWalk tw = new TreeWalk(repository);
    tw.setFilter(PathFilterGroup.createFromStrings(Collections.singleton(path)));
    byte[] content = null;
    try {
        if (tree == null) {
            ObjectId object = getDefaultBranch(repository);
            if (object == null)
                return null;
            RevCommit commit = rw.parseCommit(object);
            tree = commit.getTree();
        }
        tw.reset(tree);
        while (tw.next()) {
            if (tw.isSubtree() && !path.equals(tw.getPathString())) {
                tw.enterSubtree();
                continue;
            }
            ObjectId entid = tw.getObjectId(0);
            FileMode entmode = tw.getFileMode(0);
            if (entmode != FileMode.GITLINK) {
                ObjectLoader ldr = repository.open(entid, Constants.OBJ_BLOB);
                content = ldr.getCachedBytes();
            }
        }
    } catch (Throwable t) {
        if (throwError) {
            error(t, repository, "{0} can't find {1} in tree {2}", path, tree.name());
        }
    } finally {
        rw.dispose();
        tw.close();
    }
    return content;
}
Also used : FileMode(org.eclipse.jgit.lib.FileMode) AnyObjectId(org.eclipse.jgit.lib.AnyObjectId) ObjectId(org.eclipse.jgit.lib.ObjectId) ObjectLoader(org.eclipse.jgit.lib.ObjectLoader) RevWalk(org.eclipse.jgit.revwalk.RevWalk) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Aggregations

FileMode (org.eclipse.jgit.lib.FileMode)7 ObjectLoader (org.eclipse.jgit.lib.ObjectLoader)5 RevWalk (org.eclipse.jgit.revwalk.RevWalk)5 TreeWalk (org.eclipse.jgit.treewalk.TreeWalk)5 RevCommit (org.eclipse.jgit.revwalk.RevCommit)4 MutableObjectId (org.eclipse.jgit.lib.MutableObjectId)3 PathFilter (org.eclipse.jgit.treewalk.filter.PathFilter)3 FilestoreModel (com.gitblit.models.FilestoreModel)2 FileInputStream (java.io.FileInputStream)2 IOException (java.io.IOException)2 OutputStream (java.io.OutputStream)2 ZipArchiveOutputStream (org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream)2 ObjectId (org.eclipse.jgit.lib.ObjectId)2 ObjectReader (org.eclipse.jgit.lib.ObjectReader)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 File (java.io.File)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 Writer (java.io.Writer)1 TarArchiveEntry (org.apache.commons.compress.archivers.tar.TarArchiveEntry)1 TarArchiveOutputStream (org.apache.commons.compress.archivers.tar.TarArchiveOutputStream)1