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

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

Introduction

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

Prototype

public static Git open(File dir) throws IOException 

Source Link

Document

Open repository

Usage

From source file:com.maiereni.sling.sources.git.GitProjectDownloader.java

License:Apache License

private Git getProjectRepository(final Repository repository, final String branchName) throws Exception {
    Git ret = null;/*  ww  w .  j a v  a  2  s  . c  o  m*/
    File fRepo = new File(root, repository.getName());
    listener.notify(repository, "projectRoot", fRepo.getPath());

    if (fRepo.isDirectory()) {
        ret = Git.open(fRepo);
        listener.notify(repository, "update", "Update project");
    } else {
        if (!fRepo.mkdirs()) {
            throw new Exception("Cannot create folders at " + fRepo);
        }
        listener.notify(repository, "clone", "Clone remote repository to " + fRepo.getPath());
        ret = cloneRepository(fRepo, repository.getUrl(), branchName);
    }
    logger.debug("The repository is ready");
    return ret;
}

From source file:com.maiereni.synchronizer.git.utils.GitDownloaderImpl.java

License:Apache License

/**
 * Downloads artifacts from the Git Repository defined by the argument
 * @param properties// w  w w. ja va  2  s.  com
 * @return the result
 * @throws Exception
 */
@Override
public GitResults download(@Nonnull final GitProperties properties) throws Exception {
    Git git = null;
    if (StringUtils.isBlank(properties.getLocalRepo())) {
        throw new Exception("The local repository cannot be null");
    }
    File fRepo = new File(properties.getLocalRepo());
    if (fRepo.isFile()) {
        throw new Exception("The local repo setting points to a file. It needs to be a directory");
    }
    boolean isCreated = false;
    if (isRepository(fRepo)) {
        git = Git.open(fRepo);
    } else {
        git = createRepository(fRepo, properties);
        isCreated = true;
    }
    GitResults res = downloadProject(git, properties);
    res.setContentPath(new File(fRepo, properties.getContentPath()).toString());
    res.setCreated(isCreated);
    LayoutRules layoutRules = getLayoutRules(res);
    res.setLayoutRules(layoutRules);
    git.close();
    return res;
}

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

License:Apache License

@SuppressWarnings("unused")
public static GitLib of(File workingDir) throws IOException {
    return new GitLib(Git.open(workingDir));
}

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  va2s .  c  o m
        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.osbitools.ws.shared.prj.web.BasicLangSetWebIT.java

License:LGPL

@Test
public void testGoodReadWrite() throws Exception {
    // Open git/* w ww.  j a v  a 2 s . c o m*/
    _git = Git.open(new File(FUTILS.getProjWorkDir() + File.separator + ".git"));

    String stoken = login();

    String fname1 = "test/" + LsConstants.LANG_SET_FILE;

    testWebResponse(new WebResponse("{}"), readGet(_ll_set_mname_path, stoken));

    // Empty lang set and commit it to see the changes
    GenericUtils.saveFile(new File(
            FUTILS.getProjWorkDir() + File.separator + "test" + File.separator + LsConstants.LANG_SET_FILE),
            "");

    GitUtils.commitFile(_git, fname1, "Reseting file", "test");

    testLangSetFile(fname1, LsTestConstants.LANG_SET_RES_PATH, "First Demo Load at " + (new Date()).getTime(),
            LangSetFileTest.LL_SET_JSON, stoken);

    // Upload ll_set_test and check
    testLangSetFile(fname1, LsTestConstants.LANG_SET_RES_PATH + "_test",
            "Second Demo Load at " + (new Date()).getTime(), LangSetFileTest.LL_SET_TEST_JSON, stoken);
}

From source file:com.photon.phresco.framework.impl.SCMManagerImpl.java

License:Apache License

public boolean updateProject(RepoDetail repodetail, File updateDir) throws Exception {
    if (debugEnabled) {
        S_LOGGER.debug("Entering Method  SCMManagerImpl.updateproject()");
    }//from  w w  w  . j a  va2s  . co m
    com.photon.phresco.framework.impl.util.FrameworkUtil.saveCredential(repodetail, null);
    if (SVN.equals(repodetail.getType())) {
        if (debugEnabled) {
            S_LOGGER.debug("SVN type");
        }
        DAVRepositoryFactory.setup();
        SVNClientManager svnClientManager = getSVNClientManager(repodetail.getUserName(),
                repodetail.getPassword());
        if (debugEnabled) {
            S_LOGGER.debug("update SCM Connection " + repodetail.getRepoUrl());
        }
        //          updateSCMConnection(appInfo, repodetail.getRepoUrl());
        // revision = HEAD_REVISION.equals(revision) ? revision
        // : revisionVal;
        if (debugEnabled) {
            S_LOGGER.debug("updateDir SVN... " + updateDir);
            S_LOGGER.debug("Updating...");
        }
        SVNUpdateClient uc = svnClientManager.getUpdateClient();
        uc.doUpdate(updateDir, SVNRevision.parse(repodetail.getRevision()), SVNDepth.UNKNOWN, true, true);
        if (debugEnabled) {
            S_LOGGER.debug("Updated!");
        }
        return true;
    } else if (GIT.equals(repodetail.getType())) {
        if (debugEnabled) {
            S_LOGGER.debug("GIT type");
        }
        //         updateSCMConnection(appInfo, repodetail.getRepoUrl());
        if (debugEnabled) {
            S_LOGGER.debug("updateDir GIT... " + updateDir);
        }
        //for https and ssh
        additionalAuthentication(repodetail.getPassPhrase());

        UsernamePasswordCredentialsProvider userCredential = new UsernamePasswordCredentialsProvider(
                repodetail.getUserName(), repodetail.getPassword());
        Git git = Git.open(updateDir); // checkout is the folder with .git
        git.pull().setCredentialsProvider(userCredential).call(); // succeeds
        git.getRepository().close();
        if (debugEnabled) {
            S_LOGGER.debug("Updated!");
        }
        return true;
    } else if (BITKEEPER.equals(repodetail.getType())) {
        if (debugEnabled) {
            S_LOGGER.debug("BITKEEPER type");
        }
        updateFromBitKeeperRepo(repodetail.getRepoUrl(), updateDir.getPath());
    } else if (PERFORCE.equals(repodetail.getType())) {
        if (debugEnabled) {
            S_LOGGER.debug("PERFORCE type");
        }
        String baseDir = updateDir.getAbsolutePath();
        perforceSync(repodetail, baseDir, updateDir.getName(), "update");
        //         updateSCMConnection(appInfo, repodetail.getRepoUrl()+repodetail.getStream());
    } else if (TFS.equals(repodetail.getType())) {
        int responseCode = getProjectFromTFS(repodetail, updateDir.getCanonicalPath());
        if (responseCode == -1) {
            return true;
        }
    }

    return false;
}

From source file:com.romanenco.gitt.git.GitHelper.java

License:Open Source License

/**
 * Current branch/tag name./*w w w . j  a v  a  2  s .  c o  m*/
 * 
 * @param path
 * @return
 */
public static String currentBranchName(String localPath) {
    try {
        Git git = Git.open(new File(localPath));

        String name = git.getRepository().getBranch();

        if (name.length() == 40) {
            //detached head processing
            Map<String, Ref> refs = git.add().getRepository().getAllRefs();
            Iterator<Entry<String, Ref>> iter = refs.entrySet().iterator();
            while (iter.hasNext()) {
                Entry<String, Ref> entry = iter.next();
                if (entry.getValue().getObjectId().getName().equals(name)) {
                    if (!entry.getKey().equals("HEAD")) { // so bad, will change later...
                        name = entry.getKey();
                        break;
                    }
                }
            }
        }
        return nameReFormat(name);
    } catch (IOException e) {
        GittApp.saveErrorTrace(e);
    }
    return null;
}

From source file:com.romanenco.gitt.git.GitHelper.java

License:Open Source License

/**
 * List all branches and tags in a repo.
 * //from  www. ja  va  2 s .  c o m
 * @param branches
 * @param tags
 * @param path
 */
public static void readBranchesAndTags(List<String> refs, String localPath) {
    if (refs == null)
        return;
    try {
        Git git = Git.open(new File(localPath));

        Map<String, Ref> mm = git.getRepository().getAllRefs();
        for (String name : mm.keySet()) {
            if (name.equals("HEAD") || name.startsWith("refs/heads/"))
                continue;
            refs.add(name);
        }

    } catch (Exception e) {
        GittApp.saveErrorTrace(e);
    }
}

From source file:com.romanenco.gitt.git.GitHelper.java

License:Open Source License

/**
 * Checkout specific branch or tag./*from   w ww.  j  a  va2 s.c  om*/
 * 
 * @param localPath
 * @param name
 * @throws GitError
 */
public static void checkout(String localPath, String name) throws GitError {
    try {
        Git git = Git.open(new File(localPath));
        CheckoutCommand co = git.checkout();
        co.setName(name);
        co.call();
    } catch (Exception e) {
        GittApp.saveErrorTrace(e);
        throw new GitError();
    }
}

From source file:com.romanenco.gitt.git.GitHelper.java

License:Open Source License

/**
 * Pull repo.//ww  w . j a v a  2  s. com
 * 
 * @param localPath
 * @param user
 * @param password
 * @param pm
 * @throws GitError
 */
public static void pull(String localPath, String user, String password, ProgressMonitor pm) throws GitError {
    try {
        Git git = Git.open(new File(localPath));
        PullCommand pull = git.pull();
        pull.setProgressMonitor(pm);
        if ((user != null) && (password != null)) {
            UsernamePasswordCredentialsProvider access = new UsernamePasswordCredentialsProvider(user,
                    password);
            pull.setCredentialsProvider(access);
        }
        pull.call();
        return;
    } catch (DetachedHeadException e) {
        Log.e(TAG, "Detached head", e);
        GittApp.saveErrorTrace(e);
        throw new NoHeadError();
    } catch (InvalidRemoteException e) {
        Log.e(TAG, "InvalidRemote", e);
        GittApp.saveErrorTrace(e);
        throw new NotGitRepoError();
    } catch (TransportException e) {
        String trace = GittApp.saveErrorTrace(e);
        if (trace.indexOf("not authorized") != -1) {
            Log.e(TAG, "Auth", e);
            throw new AuthFailError();
        }
        Log.e(TAG, "Transport", e);
        throw new ConnectionError();
    } catch (GitAPIException e) {
        Log.e(TAG, "GitApi", e);
        GittApp.saveErrorTrace(e);
    } catch (IOException e) {
        Log.e(TAG, "IO", e);
        GittApp.saveErrorTrace(e);
    } catch (JGitInternalException e) {
        Log.e(TAG, "GitInternal", e);
        GittApp.saveErrorTrace(e);
        if (e.getCause() instanceof NotSupportedException) {
            throw new ConnectionError();
        }
    }
    throw new GitError();
}