Example usage for org.eclipse.jgit.api Git getRepository

List of usage examples for org.eclipse.jgit.api Git getRepository

Introduction

In this page you can find the example usage for org.eclipse.jgit.api Git getRepository.

Prototype

public Repository getRepository() 

Source Link

Document

Get repository

Usage

From source file:com.mangosolutions.rcloud.rawgist.repository.git.ForkGistOperation.java

private void removeRemotes(Grgit git) throws GitAPIException {
    Git jgit = git.getRepository().getJgit();
    Collection<String> remotes = jgit.getRepository().getRemoteNames();
    for (String remote : remotes) {
        RemoteRemoveCommand remoteRemoveCommand = jgit.remoteRemove();
        remoteRemoveCommand.setName(remote);
        remoteRemoveCommand.call();/*from www.ja v a  2 s.  c o m*/
    }
}

From source file:com.mooregreatsoftware.gitprocess.lib.GitLib.java

License:Apache License

private GitLib(Git jgit) {
    this.jgit = jgit;

    storedConfig = jgit.getRepository().getConfig();
    v(storedConfig::load);/*from www.  ja v  a  2s  .  co m*/
    this.remoteConfig = new StoredRemoteConfig(storedConfig, (remoteName, uri) -> {
        final RemoteAddCommand remoteAdd = jgit.remoteAdd();
        remoteAdd.setName(remoteName);
        remoteAdd.setUri(uri);
        return remoteAdd.call();
    });
    this.generalConfig = new StoredGeneralConfig(storedConfig);
}

From source file:com.mortardata.project.EmbeddedMortarProject.java

License:Apache License

void setupGitMirror(Git gitMirror, CredentialsProvider cp, String committer)
        throws IOException, GitAPIException {

    // checkout master as base branch
    this.gitUtil.checkout(gitMirror, "master");

    // touch .gitkeep to ensure we have something in the repo
    File gitKeep = new File(gitMirror.getRepository().getWorkTree(), ".gitkeep");
    logger.debug("Touching " + gitKeep);
    Files.touch(gitKeep);/* ww  w.  j  av  a2s .c o m*/

    // add it
    logger.debug("git add .");
    gitMirror.add().addFilepattern(".").call();

    // commit it
    logger.debug("git commit");
    gitMirror.commit().setCommitter(committer, committer).setMessage("mortar development initial commit")
            .call();

    // push it
    logger.info("Pushing initialization commit to mortar github mirror repo " + getGitMirrorURL());
    gitMirror.push().setRemote(getGitMirrorURL()).setCredentialsProvider(cp).setRefSpecs(new RefSpec("master"))
            .call();
}

From source file:com.mortardata.project.EmbeddedMortarProject.java

License:Apache License

String syncEmbeddedProjectWithMirror(Git gitMirror, CredentialsProvider cp, String targetBranch,
        String committer) throws GitAPIException, IOException {

    // checkout the target branch
    gitUtil.checkout(gitMirror, targetBranch);

    // clear out the mirror directory contents (except .git and .gitkeep)
    File localBackingGitRepoPath = gitMirror.getRepository().getWorkTree();
    for (File f : FileUtils.listFilesAndDirs(localBackingGitRepoPath,
            FileFilterUtils.notFileFilter(FileFilterUtils.nameFileFilter(".gitkeep")),
            FileFilterUtils.notFileFilter(FileFilterUtils.nameFileFilter(".git")))) {
        if (!f.equals(localBackingGitRepoPath)) {
            logger.debug("Deleting existing mirror file" + f.getAbsolutePath());
            FileUtils.deleteQuietly(f);//from  w  w  w . j a v  a2 s  .  com
        }
    }

    // copy everything from the embedded project
    List<File> manifestFiles = getFilesAndDirsInManifest();
    for (File fileToCopy : manifestFiles) {
        if (!fileToCopy.exists()) {
            logger.warn("Can't find file or directory " + fileToCopy.getCanonicalPath()
                    + " referenced in manifest file.  Ignoring.");
        } else if (fileToCopy.isDirectory()) {
            FileUtils.copyDirectoryToDirectory(fileToCopy, localBackingGitRepoPath);
        } else {
            FileUtils.copyFileToDirectory(fileToCopy, localBackingGitRepoPath);
        }
    }

    // add everything
    logger.debug("git add .");
    gitMirror.add().addFilepattern(".").call();

    // remove missing files (deletes)
    logger.debug("git add -u .");
    gitMirror.add().setUpdate(true).addFilepattern(".").call();

    // commit it
    logger.debug("git commit");
    RevCommit revCommit = gitMirror.commit().setCommitter(committer, committer)
            .setMessage("mortar development snapshot commit").call();
    return ObjectId.toString(revCommit);
}

From source file:com.osbitools.ws.shared.prj.utils.GitUtils.java

License:Open Source License

public static ByteArrayOutputStream getRevEntityEx(Git git, String base, String name, String rev,
        IEntityUtils eut, boolean minified) throws WsSrvException {
    checkFile(base, name, eut.getExt());
    String fp = getLocalPath(name);

    Iterable<RevCommit> logs;

    try {//  www .ja  v  a2s  .  c o  m
        logs = git.log().addPath(fp).call();
    } catch (GitAPIException e) {
        throw new WsSrvException(242, e);
    }

    RevCommit r = null;
    for (RevCommit rc : logs) {
        if (rc.getName().equals(rev)) {
            r = rc;
            break;
        }
    }

    if (r == null)
        throw new WsSrvException(243, "Revision " + rev + " not found for entry " + fp);

    // now try to find a specific file
    ByteArrayOutputStream entity = new ByteArrayOutputStream();
    TreeWalk tw = new TreeWalk(git.getRepository());

    try {
        tw.addTree(r.getTree());
        tw.setRecursive(true);
        tw.setFilter(PathFilter.create(fp));
        if (!tw.next())
            throw new WsSrvException(244, "Entry " + fp + " not found in revision " + rev);

        ObjectId objectId = tw.getObjectId(0);
        ObjectLoader loader = git.getRepository().open(objectId);

        // and then one can the loader to read the file
        loader.copyTo(entity);
    } catch (Exception e) {
        throw new WsSrvException(245, "Error retrieving revision " + rev + " for entry " + fp);
    }

    // ByteArrayInputStream in = new ByteArrayInputStream(dse.toByteArray());

    // return eut.get(in, name, minified);

    return entity;
}

From source file:com.osbitools.ws.shared.prj.utils.GitUtils.java

License:Open Source License

public static void getLastRevision(Git git, String base, String name, String rev, OutputStream out, String ext)
        throws WsSrvException, IOException {

    checkFile(base, name, ext);//  www . j  ava  2s  .  co m
    String fp = getLocalPath(name);

    // find the HEAD
    ObjectId lastCommitId = git.getRepository().resolve(Constants.HEAD);

    // a RevWalk allows to walk over commits based on 
    //                            some filtering that is defined
    RevWalk revWalk = new RevWalk(git.getRepository());
    RevCommit commit = revWalk.parseCommit(lastCommitId);
    // and using commit's tree find the path
    RevTree tree = commit.getTree();
    System.out.println("Having tree: " + tree);

    // now try to find a specific file
    TreeWalk treeWalk = new TreeWalk(git.getRepository());
    treeWalk.addTree(tree);
    treeWalk.setRecursive(true);
    treeWalk.setFilter(PathFilter.create(fp));

    if (!treeWalk.next()) {
        throw new IllegalStateException("Did not find expected file 'README.md'");
    }

    ObjectId objectId = treeWalk.getObjectId(0);
    System.out.println("ObjectId: " + objectId.toString());
    ObjectLoader loader = git.getRepository().open(objectId);

    // and then one can the loader to read the file
    loader.copyTo(System.out);

    revWalk.dispose();

}

From source file:com.osbitools.ws.shared.prj.utils.GitUtils.java

License:Open Source License

public static String getDiff(Git git, String base, String name, String ext) throws WsSrvException {
    checkFile(base, name, ext).getAbsolutePath();

    // Prepare path for git save
    String fp = getLocalPath(name);

    List<DiffEntry> diff;/*  w  w  w. ja  v  a 2s  . c o  m*/
    try {
        diff = git.diff().setPathFilter(PathFilter.create(fp)).call();
    } catch (GitAPIException e) {
        throw new WsSrvException(260, "Unable retrieve git diff", e);
    }

    ByteArrayOutputStream res = new ByteArrayOutputStream();

    for (DiffEntry entry : diff) {
        DiffFormatter formatter = new DiffFormatter(res);
        formatter.setRepository(git.getRepository());
        try {
            formatter.format(entry);
        } catch (IOException e) {
            throw new WsSrvException(261, "Unable format diff", e);
        }
    }

    return res.toString();
}

From source file:com.osbitools.ws.shared.prj.web.AbstractWsPrjInit.java

License:LGPL

@Override
public void contextInitialized(ServletContextEvent evt) {
    super.contextInitialized(evt);
    ServletContext ctx = evt.getServletContext();

    // First - Load Custom Error List 
    try {/*from  w  ww  .  j  a  va 2  s .com*/
        Class.forName("com.osbitools.ws.shared.prj.CustErrorList");
    } catch (ClassNotFoundException e) {
        // Ignore Error 
    }

    // Initialize Entity Utils
    IEntityUtils eut = getEntityUtils();
    ctx.setAttribute("entity_utils", eut);

    // Initiate LangSetFileUtils
    ctx.setAttribute("ll_set_utils", new LangSetUtils());

    // Check if git repository exists and create one
    // Using ds subdirectory as git root repository 
    File drepo = new File(
            getConfigDir(ctx) + File.separator + eut.getPrjRootDirName() + File.separator + ".git");
    Git git;
    try {

        if (!drepo.exists()) {
            if (!drepo.mkdirs())
                throw new RuntimeErrorException(
                        new Error("Unable create directory '" + drepo.getAbsolutePath() + "'"));

            try {
                git = createGitRepo(drepo);
            } catch (Exception e) {
                throw new RuntimeErrorException(new Error(
                        "Unable create new repo on path: " + drepo.getAbsolutePath() + ". " + e.getMessage()));
            }

            getLogger(ctx).info("Created new git repository '" + drepo.getAbsolutePath() + "'");
        } else if (!drepo.isDirectory()) {
            throw new RuntimeErrorException(
                    new Error(drepo.getAbsolutePath() + " is regular file and not a directory"));
        } else {
            git = Git.open(drepo);
            getLogger(ctx).debug("Open existing repository " + drepo.getAbsolutePath());
        }
    } catch (IOException e) {
        // Something unexpected and needs to be analyzed
        e.printStackTrace();

        throw new RuntimeErrorException(new Error(e));
    }

    // Save git handler
    ctx.setAttribute("git", git);

    // Check if remote destination set/changed
    StoredConfig config = git.getRepository().getConfig();
    String rname = (String) ctx.getAttribute(PrjMgrConstants.PREMOTE_GIT_NAME);
    String rurl = (String) ctx.getAttribute("git_remote_url");

    if (!Utils.isEmpty(rname) && !Utils.isEmpty(rurl)) {
        String url = config.getString("remote", rname, "url");
        if (!rurl.equals(url)) {
            config.setString("remote", rname, "url", rurl);
            try {
                config.save();
            } catch (IOException e) {
                getLogger(ctx).error("Error saving git remote url. " + e.getMessage());
            }
        }
    }

    // Temp directory for files upload
    String tname = System.getProperty("java.io.tmpdir");
    getLogger(ctx).info("Using temporarily directory '" + tname + "' for file uploads");
    File tdir = new File(tname);

    if (!tdir.exists())
        throw new RuntimeErrorException(
                new Error("Temporarily directory for file upload '" + tname + "' is not found"));
    if (!tdir.isDirectory())
        throw new RuntimeErrorException(
                new Error("Temporarily directory for file upload '" + tname + "' is not a directory"));

    DiskFileItemFactory dfi = new DiskFileItemFactory();
    dfi.setSizeThreshold(
            ((Integer) ctx.getAttribute(PrjMgrConstants.SMAX_FILE_UPLOAD_SIZE_NAME)) * 1024 * 1024);
    dfi.setRepository(tdir);
    evt.getServletContext().setAttribute("dfi", dfi);

    // Save entity utils in context
    evt.getServletContext().setAttribute("entity_utils", getEntityUtils());
}

From source file:com.passgit.app.PassGit.java

License:Open Source License

public boolean newRepository(char[] password, File keyFile, Format fileFormat, Cryptography cryptographer,
        boolean init) {

    byte[] key;//from ww w  . ja  va2  s  .  c om

    if (init) {
        try {
            Git git = Git.init().setDirectory(rootPath.toFile()).call();
            gitRepository = git.getRepository();
        } catch (GitAPIException ex) {
            Logger.getLogger(PassGit.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    key = passwordPreparer.getKey(password, keyFile);

    if (key != null) {

        initCryptography(key);

        properties = saveProperties();

        preferences.put("root", rootPath.toString());

        if (keyFile != null) {
            preferences.put("keyfile", keyFile.getAbsolutePath());
        } else {
            preferences.remove("keyfile");
        }

        newRepositoryDialog.setVisible(false);

        return true;
    }

    return false;

}

From source file:com.passgit.app.PassGit.java

License:Open Source License

public boolean initializeRepository(char[] password, File keyFile) {
    InitializeRepositoryPanel initializeRepositoryPanel = new InitializeRepositoryPanel(this);

    int newRepositoryPanelResult = JOptionPane.showConfirmDialog(repositoryDialog, initializeRepositoryPanel,
            "Initialize Repository", JOptionPane.OK_CANCEL_OPTION);

    if (newRepositoryPanelResult == JOptionPane.OK_OPTION) {

        fileFormat = initializeRepositoryPanel.getFileFormat();
        cryptographer = initializeRepositoryPanel.getCryptographer();

        if (initializeRepositoryPanel.getInit()) {
            try {
                Git git = Git.init().setDirectory(rootPath.toFile()).call();
                gitRepository = git.getRepository();
            } catch (GitAPIException ex) {
                Logger.getLogger(PassGit.class.getName()).log(Level.SEVERE, null, ex);
            }/* w ww . ja v  a 2 s .  c o m*/
        }

        byte[] key = passwordPreparer.getKey(password, keyFile);

        if (key != null) {
            initCryptography(key);

            properties = saveProperties();

            preferences.put("root", rootPath.toString());

            if (keyFile != null) {
                preferences.put("keyfile", keyFile.getAbsolutePath());
            } else {
                preferences.remove("keyfile");
            }

            repositoryDialog.setVisible(false);

            return true;
        }

    }

    return false;
}