Example usage for org.eclipse.jgit.internal.storage.file FileRepository FileRepository

List of usage examples for org.eclipse.jgit.internal.storage.file FileRepository FileRepository

Introduction

In this page you can find the example usage for org.eclipse.jgit.internal.storage.file FileRepository FileRepository.

Prototype

public FileRepository(BaseRepositoryBuilder options) throws IOException 

Source Link

Document

Create a repository using the local file system.

Usage

From source file:at.nonblocking.maven.nonsnapshot.impl.ScmHandlerGitImpl.java

License:Apache License

@Override
public void init(File baseDir, String scmUser, String scmPassword, Properties properties) {
    this.baseDir = findGitRepo(baseDir);
    if (this.baseDir == null) {
        LOG.error("Project seems not be within a GIT repository!");
        return;//from  www . ja  va  2 s.com
    }

    LOG.info("Using GIT repository: {}", this.baseDir.getAbsolutePath());

    try {
        FileRepository localRepo = new FileRepository(this.baseDir + "/.git");
        this.git = new Git(localRepo);
        if (scmPassword != null && !scmPassword.trim().isEmpty()) {
            this.credentialsProvider = new UsernamePasswordAndPassphraseCredentialProvider(scmUser,
                    scmPassword);
        }
        if (properties != null && "false".equals(properties.getProperty("gitDoPush"))) {
            this.doPush = false;
            LOG.info("GIT push is disabled");
        }

    } catch (Exception e) {
        LOG.error("Project seems not be within a GIT repository!", e);
    }
}

From source file:com.addthis.hydra.job.store.JobStoreGit.java

License:Apache License

/**
 * Set up a git repository in a directory.
 *
 * @param baseDir The directory that will store the files.
 * @throws IOException If there is a problem writing to the directory
 *//*from   w ww  .j a v a 2  s . c  o  m*/
public JobStoreGit(File baseDir) throws Exception {
    this.baseDir = baseDir;
    this.gitDir = new File(baseDir, ".git");
    this.jobDir = new File(baseDir, "jobs");
    repository = new FileRepository(gitDir);
    git = new Git(repository);
    initialize();
}

From source file:com.centurylink.mdw.dataaccess.file.VersionControlGit.java

License:Apache License

public void connect(String repositoryUrl, String user, String password, File localDir) throws IOException {

    if (repositoryUrl != null && !repositoryUrl.isEmpty()) {
        if (user == null) {
            this.repositoryUrl = repositoryUrl;
        } else {/*from   w  w w  .  j  a  v a 2 s .c  o  m*/
            int slashSlash = repositoryUrl.indexOf("//");
            this.repositoryUrl = repositoryUrl.substring(0, slashSlash + 2) + user + ":" + password + "@"
                    + repositoryUrl.substring(slashSlash + 2);
        }
    }

    this.localDir = localDir;
    localRepo = new FileRepository(new File(localDir + "/.git"));
    git = new Git(localRepo);
    if (credentialsProvider == null) {
        if (user != null && password != null)
            credentialsProvider = new UsernamePasswordCredentialsProvider(user, password);
    }

    file2id = new HashMap<File, Long>();
    id2file = new HashMap<Long, File>();
    pkg2versions = new HashMap<>();

    String idLengthProp = System.getProperty("com.centurylink.mdw.abbreviated.id.length");
    if (idLengthProp != null)
        ABBREVIATED_ID_LENGTH = Integer.parseInt(idLengthProp);
}

From source file:com.centurylink.mdw.dataaccess.file.VersionControlGit.java

License:Apache License

public synchronized void reconnect() throws IOException {
    Repository newLocalRepo = new FileRepository(new File(localDir + "/.git"));
    git = new Git(newLocalRepo);
    localRepo.close();//from w  w  w.ja  v a 2 s.  c  o m
    localRepo = newLocalRepo;
}

From source file:com.centurylink.mdw.plugin.project.assembly.ProjectInflator.java

License:Apache License

public void inflateCloudProject(final IRunnableContext container) {
    getProject().setCloudProject(true);//from  w w w .jav a2  s .  c  o  m

    // get a project handle
    final IProject newProjectHandle = ResourcesPlugin.getWorkspace().getRoot()
            .getProject(workflowProject.getName());

    // get a project descriptor
    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    final IProjectDescription description = workspace.newProjectDescription(newProjectHandle.getName());

    // create the new project operation
    IRunnableWithProgress op = new IRunnableWithProgress() {
        public void run(IProgressMonitor monitor) throws InvocationTargetException {
            Repository newRepo = null;
            try {
                if (workflowProject.getPersistType() == PersistType.Git) {
                    File localDir = new File(ResourcesPlugin.getWorkspace().getRoot().getLocation().toFile()
                            + "/" + workflowProject.getName());
                    if (workflowProject.getMdwVcsRepository().hasRemoteRepository()) {
                        monitor.subTask("Cloning Git repository");
                        VcsRepository gitRepo = workflowProject.getMdwVcsRepository();
                        Git.cloneRepository().setURI(gitRepo.getRepositoryUrlWithCredentials())
                                .setDirectory(localDir).call();
                    } else {
                        newRepo = new FileRepository(new File(localDir + "/.git"));
                        newRepo.create();
                    }

                    // .gitignore
                    Generator generator = new Generator(shell);
                    JetAccess jet = getJet("source/.ignorejet", getProject().getSourceProject(), ".gitignore",
                            null);
                    generator.createFile(jet, monitor);
                }

                CreateProjectOperation op = new CreateProjectOperation(description, "MDW Cloud Project");
                PlatformUI.getWorkbench().getOperationSupport().getOperationHistory().execute(op, monitor,
                        WorkspaceUndoUtil.getUIInfoAdapter(shell));
            } catch (Exception ex) {
                throw new InvocationTargetException(ex);
            } finally {
                if (newRepo != null)
                    newRepo.close();
            }
        }
    };

    // run the new project creation operation
    try {
        container.run(false, false, op);
        ProgressMonitorDialog pmDialog = new MdwProgressMonitorDialog(MdwPlugin.getShell());
        pmDialog.run(true, false, new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                monitor.beginTask("Inflating Workflow Project", 250);
                monitor.worked(5);
                // configure as Java project
                ProjectConfigurator projConf = new ProjectConfigurator(getProject(), MdwPlugin.getSettings());
                projConf.setJava(new SubProgressMonitor(monitor, 3));

                ProjectUpdater updater = new ProjectUpdater(getProject(), MdwPlugin.getSettings());
                updater.updateMappingFiles(new SubProgressMonitor(monitor, 3)); // bootstrap
                                                                                // versions
                                                                                // of
                                                                                // the
                                                                                // property
                                                                                // files
                updater.updateFrameworkJars(new SubProgressMonitor(monitor, 150));
                updater.updateWebProjectJars(new SubProgressMonitor(monitor, 50));

                try {
                    if (getProject().isOsgi())
                        projConf.addJavaProjectSourceFolder(getProject().getOsgiSettings().getSourceDir(),
                                new SubProgressMonitor(monitor, 3));
                    else if (!getProject().isWar())
                        projConf.addJavaProjectSourceFolder("src", monitor);
                    projConf.setJavaBuildOutputPath("build/classes", new SubProgressMonitor(monitor, 5));
                    projConf.addFrameworkJarsToClasspath(monitor);

                    // add the workflow facet
                    getProject().setSkipFacetPostInstallUpdates(true); // already
                                                                       // did
                                                                       // framework
                                                                       // updates
                    IFacetedProject facetedProject = ProjectFacetsManager
                            .create(getProject().getSourceProject(), true, new SubProgressMonitor(monitor, 3));
                    IProjectFacetVersion javaFacetVersion = ProjectFacetsManager.getProjectFacet("java")
                            .getDefaultVersion();
                    if (Float.parseFloat(javaFacetVersion.getVersionString()) < 1.6)
                        javaFacetVersion = ProjectFacetsManager.getProjectFacet("java").getVersion("1.6");
                    if (workflowProject.isCloudOnly())
                        javaFacetVersion = ProjectFacetsManager.getProjectFacet("java").getVersion("1.7");
                    facetedProject.installProjectFacet(javaFacetVersion, null,
                            new SubProgressMonitor(monitor, 3));
                    IProjectFacetVersion mdwFacet = ProjectFacetsManager.getProjectFacet("mdw.workflow")
                            .getDefaultVersion();
                    facetedProject.installProjectFacet(mdwFacet, getProject(),
                            new SubProgressMonitor(monitor, 3));
                    if (workflowProject.isOsgi()) {
                        IProjectFacet utilFacet = ProjectFacetsManager.getProjectFacet("jst.utility");
                        IProjectFacetVersion facetVer = utilFacet.getDefaultVersion();
                        IActionDefinition def = facetVer.getActionDefinition(null,
                                IFacetedProject.Action.Type.INSTALL);
                        Object cfg = def.createConfigObject();
                        facetedProject.installProjectFacet(
                                ProjectFacetsManager.getProjectFacet("jst.utility").getDefaultVersion(), cfg,
                                new SubProgressMonitor(monitor, 3));
                    } else if (workflowProject.isWar()) {
                        // add the facet to the xml file
                        IFile facetsFile = workflowProject.getSourceProject()
                                .getFile(".settings/org.eclipse.wst.common.project.facet.core.xml");
                        if (facetsFile.exists()) {
                            String content = new String(PluginUtil.readFile(facetsFile));
                            int insert = content.indexOf("</faceted-project>");
                            content = content.substring(0, insert)
                                    + "  <installed facet=\"jst.web\" version=\"3.0\"/>\n"
                                    + content.substring(insert);
                            PluginUtil.writeFile(facetsFile, content, new SubProgressMonitor(monitor, 3));
                        }
                    }

                    final ProjectConfigurator configurator = new ProjectConfigurator(getProject(),
                            MdwPlugin.getSettings());
                    if (!workflowProject.isOsgi() && !workflowProject.isWar()) {
                        MdwPlugin.getDisplay().syncExec(new Runnable() {
                            public void run() {
                                try {
                                    configurator.createFrameworkSourceCodeAssociations(MdwPlugin.getShell(),
                                            new NullProgressMonitor());
                                } catch (CoreException ex) {
                                    PluginMessages.log(ex);
                                }
                            }
                        });
                    }

                    if (workflowProject.isOsgi()) {
                        generateOsgiArtifacts(new SubProgressMonitor(monitor, 10));
                        configurator.configureOsgiProject(shell, new SubProgressMonitor(monitor, 5));
                    } else if (workflowProject.isWar()) {
                        generateWarCloudArtifacts(new SubProgressMonitor(monitor, 10));
                        configurator.addMavenNature(new SubProgressMonitor(monitor, 5)); // force
                                                                                         // maven
                                                                                         // refresh
                    }
                } catch (Exception ex) {
                    throw new InvocationTargetException(ex);
                }
            }
        });
    } catch (Exception ex) {
        PluginMessages.uiError(ex, "Create Cloud Project", workflowProject);
    }
}

From source file:com.denimgroup.threadfix.service.repository.GitServiceImpl.java

License:Mozilla Public License

@Override
public File cloneRepoToDirectory(Application application, File dirLocation) {

    if (dirLocation.exists()) {
        File gitDirectoryFile = new File(dirLocation.getAbsolutePath() + File.separator + ".git");

        try {//  ww  w . ja  v  a  2s.c o m
            if (!gitDirectoryFile.exists()) {
                Git newRepo = clone(application, dirLocation);
                if (newRepo != null)
                    return newRepo.getRepository().getWorkTree();
            } else {
                Repository localRepo = new FileRepository(gitDirectoryFile);
                Git git = new Git(localRepo);

                if (application.getRepositoryRevision() != null
                        && !application.getRepositoryRevision().isEmpty()) {
                    //remote checkout
                    git.checkout().setCreateBranch(true).setStartPoint(application.getRepositoryRevision())
                            .setName(application.getRepositoryRevision()).call();
                } else {

                    List<Ref> refs = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();

                    String repoBranch = (application.getRepositoryBranch() != null
                            && !application.getRepositoryBranch().isEmpty()) ? application.getRepositoryBranch()
                                    : "master";

                    boolean localCheckout = false;

                    for (Ref ref : refs) {
                        String refName = ref.getName();
                        if (refName.contains(repoBranch) && !refName.contains(Constants.R_REMOTES)) {
                            localCheckout = true;
                        }
                    }

                    String HEAD = localRepo.getFullBranch();

                    if (HEAD.contains(repoBranch)) {
                        git.pull().setRemote("origin").setRemoteBranchName(repoBranch)
                                .setCredentialsProvider(getApplicationCredentials(application)).call();
                    } else {
                        if (localCheckout) {
                            //local checkout
                            git.checkout().setName(application.getRepositoryBranch()).call();
                            git.pull().setRemote("origin").setRemoteBranchName(repoBranch)
                                    .setCredentialsProvider(getApplicationCredentials(application)).call();
                        } else {
                            //remote checkout
                            git.checkout().setCreateBranch(true).setName(repoBranch)
                                    .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.SET_UPSTREAM)
                                    .setStartPoint("origin/" + repoBranch).call();
                        }
                    }
                }

                return git.getRepository().getWorkTree();
            }
        } catch (JGitInternalException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (IOException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (WrongRepositoryStateException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (InvalidConfigurationException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (DetachedHeadException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (InvalidRemoteException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (CanceledException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (RefNotFoundException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (NoHeadException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (RefAlreadyExistsException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (CheckoutConflictException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (InvalidRefNameException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (TransportException e) {
            log.error(EXCEPTION_MESSAGE, e);
        } catch (GitAPIException e) {
            log.error(EXCEPTION_MESSAGE, e);
        }
    } else {
        try {
            log.info("Attempting to clone application from repository.");
            Git result = clone(application, dirLocation);
            if (result != null) {
                log.info("Application was successfully cloned from repository.");
                return result.getRepository().getWorkTree();
            }
            log.error(EXCEPTION_MESSAGE);
        } catch (JGitInternalException e) {
            log.error(EXCEPTION_MESSAGE, e);
        }
    }
    return null;
}

From source file:com.google.gerrit.pgm.init.AccountsOnInit.java

License:Apache License

public void insert(ReviewDb db, Account account) throws OrmException, IOException {
    db.accounts().insert(ImmutableSet.of(account));

    File path = getPath();//from   ww w  .java  2  s.  com
    if (path != null) {
        try (Repository repo = new FileRepository(path); ObjectInserter oi = repo.newObjectInserter()) {
            PersonIdent serverIdent = new GerritPersonIdentProvider(flags.cfg).get();
            AccountsUpdate.createUserBranch(repo, oi, serverIdent, serverIdent, account);
        }
    }
}

From source file:com.google.gerrit.pgm.init.AllProjectsConfig.java

License:Apache License

public Config load() throws IOException, ConfigInvalidException {
    File path = getPath();/*from   w  w w  .  j  av a  2s. co m*/
    if (path == null) {
        return null;
    }

    Repository repo = new FileRepository(path);
    try {
        load(repo);
    } finally {
        repo.close();
    }
    return cfg;
}

From source file:com.google.gerrit.pgm.init.AllProjectsConfig.java

License:Apache License

private void save(PersonIdent ident, String msg) throws IOException {
    File path = getPath();//from  ww w  .ja  v a  2 s . c  o m
    if (path == null) {
        throw new IOException("All-Projects does not exist.");
    }

    Repository repo = new FileRepository(path);
    try {
        inserter = repo.newObjectInserter();
        reader = repo.newObjectReader();
        try {
            RevWalk rw = new RevWalk(reader);
            try {
                RevTree srcTree = revision != null ? rw.parseTree(revision) : null;
                newTree = readTree(srcTree);
                saveConfig(ProjectConfig.PROJECT_CONFIG, cfg);
                ObjectId res = newTree.writeTree(inserter);
                if (res.equals(srcTree)) {
                    // If there are no changes to the content, don't create the commit.
                    return;
                }

                CommitBuilder commit = new CommitBuilder();
                commit.setAuthor(ident);
                commit.setCommitter(ident);
                commit.setMessage(msg);
                commit.setTreeId(res);
                if (revision != null) {
                    commit.addParentId(revision);
                }
                ObjectId newRevision = inserter.insert(commit);
                updateRef(repo, ident, newRevision, "commit: " + msg);
                revision = newRevision;
            } finally {
                rw.release();
            }
        } finally {
            if (inserter != null) {
                inserter.release();
                inserter = null;
            }
            if (reader != null) {
                reader.release();
                reader = null;
            }
        }
    } finally {
        repo.close();
    }
}

From source file:com.google.gerrit.pgm.init.api.AllProjectsConfig.java

License:Apache License

public AllProjectsConfig load() throws IOException, ConfigInvalidException {
    File path = getPath();/* w w  w  .j  a v a  2s .  c  o  m*/
    if (path != null) {
        try (Repository repo = new FileRepository(path)) {
            load(repo);
        }
    }
    return this;
}