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

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

Introduction

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

Prototype

public static CloneCommand cloneRepository() 

Source Link

Document

Return a command object to execute a clone command

Usage

From source file:org.eclipse.ice.client.widgets.moose.actions.ForkStorkHandler.java

License:Open Source License

/**
 * (non-Javadoc)//w  ww  .  j  a  v a  2 s .  c  o m
 *
 * @see org.eclipse.core.commands.AbstractHandler#execute(org.eclipse.core.commands.ExecutionEvent)
 */
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {

    // Local Declarations
    Shell shell = HandlerUtil.getActiveWorkbenchWindow(event).getShell();

    // Create a new ForkStorkWizard and Dialog
    final ForkStorkWizard wizard = new ForkStorkWizard();
    WizardDialog dialog = new WizardDialog(shell, wizard);

    // Open the dialog
    if (dialog.open() != 0) {
        return null;
    }

    // Create a File reference to the repo in the Eclipse workspace
    final Job job = new Job("Forking the MOOSE Stork!") {

        @Override
        protected IStatus run(IProgressMonitor monitor) {
            monitor.beginTask("Attempting to Fork the Stork with supplied credentials", 100);

            // Local Declarations
            IWorkspace workspace = ResourcesPlugin.getWorkspace();
            ArrayList<String> cmdList = new ArrayList<String>();
            ProcessBuilder jobBuilder = null;
            String os = System.getProperty("os.name");
            String sep = System.getProperty("file.separator");

            // Get the user specified data
            String appName = wizard.getMooseAppName();
            String gitHubUser = wizard.getGitUsername();
            String password = wizard.getGitPassword();

            // Construct the Remote URI for the repo
            String remoteURI = "https://github.com/" + gitHubUser + "/" + appName;

            // Create the workspace file
            File workspaceFile = new File(
                    ResourcesPlugin.getWorkspace().getRoot().getLocation().toOSString() + sep + appName);

            // Set the pyton command
            cmdList.add("/bin/bash");
            cmdList.add("-c");
            cmdList.add("python make_new_application.py");

            // Create a EGit-GitHub RepositoryService and Id to
            // connect and create our Fork
            RepositoryService service = new RepositoryService();
            RepositoryId id = new RepositoryId("idaholab", "stork");

            // Set the user's GitHub credentials
            service.getClient().setCredentials(gitHubUser, password);
            monitor.subTask("Connecting to GitHub...");
            monitor.worked(20);

            // Fork the Repository!!!
            try {
                // Fork and get the repo
                Repository repo = service.forkRepository(id);

                // Reset the project name to the provided app name
                Map<String, Object> fields = new HashMap<String, Object>();
                fields.put("name", appName);

                // Edit the name
                service.editRepository(repo, fields);
            } catch (IOException e) {
                logger.error(getClass().getName() + " Exception!", e);
                String errorMessage = "ICE failed in forking the new stork.";
                return new Status(IStatus.ERROR, "org.eclipse.ice.client.widgets.moose", 1, errorMessage, null);
            }

            monitor.subTask("Stork Forked, cloning to local machine...");
            monitor.worked(40);

            // Now that it is all set on the GitHub end,
            // Let's pull it down into our workspace
            try {
                Git result = Git.cloneRepository().setURI(remoteURI).setDirectory(workspaceFile).call();
            } catch (GitAPIException e) {
                logger.error(getClass().getName() + " Exception!", e);
                String errorMessage = "ICE failed in cloning the new application.";
                return new Status(IStatus.ERROR, "org.eclipse.ice.client.widgets.moose", 1, errorMessage, null);
            }

            monitor.subTask("Executing make_new_application.py...");
            monitor.worked(60);

            // We can only run the python script on Linux or Mac
            // And Moose devs only use Linux or Macs to build their apps
            if (os.contains("Linux") || os.contains("Mac")) {
                // Create the ProcessBuilder and change to the project dir
                jobBuilder = new ProcessBuilder(cmdList);
                jobBuilder.directory(new File(workspaceFile.getAbsolutePath()));

                // Do not direct the error to stdout. Catch it separately.
                jobBuilder.redirectErrorStream(false);
                try {
                    // Execute the python script!
                    jobBuilder.start();
                } catch (IOException e) {
                    logger.error(getClass().getName() + " Exception!", e);
                    String errorMessage = "ICE could not execute the make_new_application python script.";
                    return new Status(IStatus.ERROR, "org.eclipse.ice.client.widgets.moose", 1, errorMessage,
                            null);
                }
            }

            /*------------ The rest is about importing the C++ project correctly ---------*/

            // Get the project and project description handles
            IProject project = workspace.getRoot().getProject(appName);
            IProjectDescription description = workspace.newProjectDescription(appName);

            monitor.subTask("Converting application to CDT C++ Project...");
            monitor.worked(80);

            try {
                // Create the CDT Project
                CCorePlugin.getDefault().createCDTProject(description, project, new NullProgressMonitor());

                // Add the CPP nature
                CCProjectNature.addCCNature(project, new NullProgressMonitor());

                // Set up build information
                ICProjectDescriptionManager pdMgr = CoreModel.getDefault().getProjectDescriptionManager();
                ICProjectDescription projDesc = pdMgr.createProjectDescription(project, false);
                ManagedBuildInfo info = ManagedBuildManager.createBuildInfo(project);
                ManagedProject mProj = new ManagedProject(projDesc);
                info.setManagedProject(mProj);

                // Grab the correct toolchain
                // FIXME this should be better...
                IToolChain toolChain = null;
                for (IToolChain tool : ManagedBuildManager.getRealToolChains()) {
                    if (os.contains("Mac") && tool.getName().contains("Mac")
                            && tool.getName().contains("GCC")) {
                        toolChain = tool;
                        break;
                    } else if (os.contains("Linux") && tool.getName().contains("Linux")
                            && tool.getName().contains("GCC")) {
                        toolChain = tool;
                        break;
                    } else if (os.contains("Windows") && tool.getName().contains("Cygwin")) {
                        toolChain = tool;
                        break;
                    } else {
                        toolChain = null;
                    }
                }

                // Set up the Build configuratino
                CfgHolder cfgHolder = new CfgHolder(toolChain, null);
                String s = toolChain == null ? "0" : toolChain.getId(); //$NON-NLS-1$
                IConfiguration config = new Configuration(mProj,
                        (org.eclipse.cdt.managedbuilder.internal.core.ToolChain) toolChain,
                        ManagedBuildManager.calculateChildId(s, null), cfgHolder.getName());
                IBuilder builder = config.getEditableBuilder();
                builder.setManagedBuildOn(false);
                CConfigurationData data = config.getConfigurationData();
                projDesc.createConfiguration(ManagedBuildManager.CFG_DATA_PROVIDER_ID, data);
                pdMgr.setProjectDescription(project, projDesc);

                // Now create a default Make Target for the Moose user to
                // use to
                // build the new app
                IProject cProject = projDesc.getProject();
                IMakeTargetManager manager = MakeCorePlugin.getDefault().getTargetManager();
                String[] ids = manager.getTargetBuilders(cProject);
                IMakeTarget target = manager.createTarget(cProject, "make all", ids[0]);
                target.setStopOnError(false);
                target.setRunAllBuilders(false);
                target.setUseDefaultBuildCmd(false);
                target.setBuildAttribute(IMakeCommonBuildInfo.BUILD_COMMAND, "make");
                target.setBuildAttribute(IMakeCommonBuildInfo.BUILD_LOCATION,
                        cProject.getLocation().toOSString());
                target.setBuildAttribute(IMakeCommonBuildInfo.BUILD_ARGUMENTS, "");
                target.setBuildAttribute(IMakeTarget.BUILD_TARGET, "all");
                manager.addTarget(cProject, target);

                // Set the include and src folders as actual CDT source
                // folders
                ICProjectDescription cDescription = CoreModel.getDefault().getProjectDescriptionManager()
                        .createProjectDescription(cProject, false);
                ICConfigurationDescription cConfigDescription = cDescription.createConfiguration(
                        ManagedBuildManager.CFG_DATA_PROVIDER_ID, config.getConfigurationData());
                cDescription.setActiveConfiguration(cConfigDescription);
                cConfigDescription.setSourceEntries(null);
                IFolder srcFolder = cProject.getFolder("src");
                IFolder includeFolder = cProject.getFolder("include");
                ICSourceEntry srcFolderEntry = new CSourceEntry(srcFolder, null, ICSettingEntry.RESOLVED);
                ICSourceEntry includeFolderEntry = new CSourceEntry(includeFolder, null,
                        ICSettingEntry.RESOLVED);
                cConfigDescription.setSourceEntries(new ICSourceEntry[] { srcFolderEntry, includeFolderEntry });

                // Add the Moose include paths
                ICProjectDescription projectDescription = CoreModel.getDefault().getProjectDescription(cProject,
                        true);
                ICConfigurationDescription configDecriptions[] = projectDescription.getConfigurations();
                for (ICConfigurationDescription configDescription : configDecriptions) {
                    ICFolderDescription projectRoot = configDescription.getRootFolderDescription();
                    ICLanguageSetting[] settings = projectRoot.getLanguageSettings();
                    for (ICLanguageSetting setting : settings) {
                        List<ICLanguageSettingEntry> includes = getIncludePaths();
                        includes.addAll(setting.getSettingEntriesList(ICSettingEntry.INCLUDE_PATH));
                        setting.setSettingEntries(ICSettingEntry.INCLUDE_PATH, includes);
                    }
                }
                CoreModel.getDefault().setProjectDescription(cProject, projectDescription);

                // Add a MOOSE Project Nature
                IProjectDescription desc = project.getDescription();
                String[] prevNatures = desc.getNatureIds();
                String[] newNatures = new String[prevNatures.length + 1];
                System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
                newNatures[prevNatures.length] = MooseNature.NATURE_ID;
                desc.setNatureIds(newNatures);
                project.setDescription(desc, new NullProgressMonitor());

            } catch (CoreException e) {
                logger.error(getClass().getName() + " Exception!", e);
                String errorMessage = "ICE could not import the new MOOSE application as a C++ project.";
                return new Status(IStatus.ERROR, "org.eclipse.ice.client.widgets.moose", 1, errorMessage, null);
            }

            monitor.subTask("Importing into ICE.");
            monitor.worked(100);
            monitor.done();
            return Status.OK_STATUS;
        }

    };

    job.schedule();

    // FIXME SHOULD WE CHECK IF MOOSE IS IN THE WORKSPACE
    // AND CLONE IT IF ITS NOT

    return null;
}

From source file:org.eclipse.ice.client.widgets.moose.wizards.ForkStorkHandler.java

License:Open Source License

/**
 * (non-Javadoc)/*from  ww w  .  j  ava  2s .  c  o  m*/
 * 
 * @see org.eclipse.core.commands.AbstractHandler#execute(org.eclipse.core.commands.ExecutionEvent)
 */
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {

    // Local Declarations
    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    Shell shell = HandlerUtil.getActiveWorkbenchWindow(event).getShell();
    String sep = System.getProperty("file.separator"), appName = "", gitHubUser = "", password = "",
            remoteURI = "";
    ArrayList<String> cmdList = new ArrayList<String>();
    ProcessBuilder jobBuilder = null;
    String os = System.getProperty("os.name");

    // Set the pyton command
    cmdList.add("/bin/bash");
    cmdList.add("-c");
    cmdList.add("python make_new_application.py");

    // Create a new ForkStorkWizard and Dialog
    ForkStorkWizard wizard = new ForkStorkWizard();
    WizardDialog dialog = new WizardDialog(shell, wizard);

    // Open the dialog
    if (dialog.open() != 0) {
        return null;
    }

    // Get the User Input Data
    appName = wizard.getMooseAppName();
    gitHubUser = wizard.getGitUsername();
    password = wizard.getGitPassword();

    // Construct the Remote URI for the repo
    remoteURI = "https://github.com/" + gitHubUser + "/" + appName;

    // Create a File reference to the repo in the Eclipse workspace
    File workspaceFile = new File(
            ResourcesPlugin.getWorkspace().getRoot().getLocation().toOSString() + sep + appName);

    // Create a EGit-GitHub RepositoryService and Id to
    // connect and create our Fork
    RepositoryService service = new RepositoryService();
    RepositoryId id = new RepositoryId("idaholab", "stork");

    // Set the user's GitHub credentials
    service.getClient().setCredentials(gitHubUser, password);

    // Fork the Repository!!!
    try {
        // Fork and get the repo
        Repository repo = service.forkRepository(id);

        // Reset the project name to the provided app name
        Map<String, Object> fields = new HashMap<String, Object>();
        fields.put("name", appName);

        // Edit the name
        service.editRepository(repo, fields);
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    // Now that it is all set on the GitHub end,
    // Let's pull it down into our workspace
    try {
        Git result = Git.cloneRepository().setURI(remoteURI).setDirectory(workspaceFile).call();
    } catch (InvalidRemoteException e1) {
        e1.printStackTrace();
    } catch (TransportException e1) {
        e1.printStackTrace();
    } catch (GitAPIException e1) {
        e1.printStackTrace();
    }

    // We can only run the python script on Linux or Mac
    // And Moose devs only use Linux or Macs to build their apps
    if (os.contains("Linux") || os.contains("Mac")) {
        // Create the ProcessBuilder and change to the project dir
        jobBuilder = new ProcessBuilder(cmdList);
        jobBuilder.directory(new File(workspaceFile.getAbsolutePath()));

        // Do not direct the error to stdout. Catch it separately.
        jobBuilder.redirectErrorStream(false);
        try {
            // Execute the python script!
            jobBuilder.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*------------ The rest is about importing the C++ project correctly ---------*/

    // Get the project and project description handles
    IProject project = workspace.getRoot().getProject(appName);
    IProjectDescription description = workspace.newProjectDescription(appName);

    try {
        // Create the CDT Project
        CCorePlugin.getDefault().createCDTProject(description, project, new NullProgressMonitor());

        // Add the CPP nature
        CCProjectNature.addCCNature(project, new NullProgressMonitor());

        // Set up build information
        ICProjectDescriptionManager pdMgr = CoreModel.getDefault().getProjectDescriptionManager();
        ICProjectDescription projDesc = pdMgr.createProjectDescription(project, false);
        ManagedBuildInfo info = ManagedBuildManager.createBuildInfo(project);
        ManagedProject mProj = new ManagedProject(projDesc);
        info.setManagedProject(mProj);

        // Grab the correct toolchain
        // FIXME this should be better...
        IToolChain toolChain = null;
        for (IToolChain tool : ManagedBuildManager.getRealToolChains()) {
            if (os.contains("Mac") && tool.getName().contains("Mac") && tool.getName().contains("GCC")) {
                toolChain = tool;
                break;
            } else if (os.contains("Linux") && tool.getName().contains("Linux")
                    && tool.getName().contains("GCC")) {
                toolChain = tool;
                break;
            } else if (os.contains("Windows") && tool.getName().contains("Cygwin")) {
                toolChain = tool;
                break;
            } else {
                toolChain = null;
            }
        }

        // Set up the Build configuratino
        CfgHolder cfgHolder = new CfgHolder(toolChain, null);
        String s = toolChain == null ? "0" : toolChain.getId(); //$NON-NLS-1$
        IConfiguration config = new Configuration(mProj,
                (org.eclipse.cdt.managedbuilder.internal.core.ToolChain) toolChain,
                ManagedBuildManager.calculateChildId(s, null), cfgHolder.getName());
        IBuilder builder = config.getEditableBuilder();
        builder.setManagedBuildOn(false);
        CConfigurationData data = config.getConfigurationData();
        projDesc.createConfiguration(ManagedBuildManager.CFG_DATA_PROVIDER_ID, data);
        pdMgr.setProjectDescription(project, projDesc);

        // Now create a default Make Target for the Moose user to use to
        // build the new app
        IProject cProject = projDesc.getProject();
        IMakeTargetManager manager = MakeCorePlugin.getDefault().getTargetManager();
        String[] ids = manager.getTargetBuilders(cProject);
        IMakeTarget target = manager.createTarget(cProject, "make all", ids[0]);
        target.setStopOnError(false);
        target.setRunAllBuilders(false);
        target.setUseDefaultBuildCmd(false);
        target.setBuildAttribute(IMakeCommonBuildInfo.BUILD_COMMAND, "make");
        target.setBuildAttribute(IMakeTarget.BUILD_LOCATION, cProject.getLocation().toOSString());
        target.setBuildAttribute(IMakeTarget.BUILD_ARGUMENTS, "");
        target.setBuildAttribute(IMakeTarget.BUILD_TARGET, "all");
        manager.addTarget(cProject, target);

        // Set the include and src folders as actual CDT source folders
        ICProjectDescription cDescription = CoreModel.getDefault().getProjectDescriptionManager()
                .createProjectDescription(cProject, false);
        ICConfigurationDescription cConfigDescription = cDescription
                .createConfiguration(ManagedBuildManager.CFG_DATA_PROVIDER_ID, config.getConfigurationData());
        cDescription.setActiveConfiguration(cConfigDescription);
        cConfigDescription.setSourceEntries(null);
        IFolder srcFolder = cProject.getFolder("src");
        IFolder includeFolder = cProject.getFolder("include");
        ICSourceEntry srcFolderEntry = new CSourceEntry(srcFolder, null, ICSettingEntry.RESOLVED);
        ICSourceEntry includeFolderEntry = new CSourceEntry(includeFolder, null, ICSettingEntry.RESOLVED);
        cConfigDescription.setSourceEntries(new ICSourceEntry[] { srcFolderEntry, includeFolderEntry });

        // Add the Moose include paths
        ICProjectDescription projectDescription = CoreModel.getDefault().getProjectDescription(cProject, true);
        ICConfigurationDescription configDecriptions[] = projectDescription.getConfigurations();
        for (ICConfigurationDescription configDescription : configDecriptions) {
            ICFolderDescription projectRoot = configDescription.getRootFolderDescription();
            ICLanguageSetting[] settings = projectRoot.getLanguageSettings();
            for (ICLanguageSetting setting : settings) {
                List<ICLanguageSettingEntry> includes = getIncludePaths();
                includes.addAll(setting.getSettingEntriesList(ICSettingEntry.INCLUDE_PATH));
                setting.setSettingEntries(ICSettingEntry.INCLUDE_PATH, includes);
            }
        }
        CoreModel.getDefault().setProjectDescription(cProject, projectDescription);

    } catch (CoreException e) {
        e.printStackTrace();
    }

    // FIXME SHOULD WE CHECK IF MOOSE IS IN THE WORKSPACE 
    // AND CLONE IT IF ITS NOT

    return null;
}

From source file:org.eclipse.mylyn.gerrit.tests.support.GerritProject.java

License:Open Source License

public Git getGitProject(PrivilegeLevel privilegeLevel) throws Exception {
    if (git == null) {
        String url = fixture.getRepositoryUrl() + PROJECT;
        AuthenticationCredentials credentials = fixture.location(privilegeLevel)
                .getCredentials(AuthenticationType.REPOSITORY);
        url = url.replace("://", "://" + getGitUsername(credentials) + ":" + credentials.getPassword() + "@"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
        git = Git.cloneRepository().setDirectory(getFolder()).setURI(url).call();
    }/* w w w  .j a v  a2 s. co m*/
    return git;
}

From source file:org.eclipse.oomph.setup.git.impl.GitCloneTaskImpl.java

License:Open Source License

private static Git cloneRepository(SetupTaskContext context, File workDir, String checkoutBranch,
        String remoteName, String remoteURI, boolean recursive, IProgressMonitor monitor) throws Exception {
    context.log("Cloning Git repo " + remoteURI + " to " + workDir);

    CloneCommand command = Git.cloneRepository();
    command.setNoCheckout(true);//  ww w.  ja v  a  2 s  .c  om
    command.setURI(remoteURI);
    command.setRemote(remoteName);
    command.setBranchesToClone(Collections.singleton(checkoutBranch));
    command.setDirectory(workDir);
    command.setTimeout(60);
    command.setProgressMonitor(new EclipseGitProgressTransformer(monitor));
    return command.call();
}

From source file:org.eclipse.orion.server.git.jobs.CloneJob.java

License:Open Source License

private IStatus doClone() {
    try {//from   w ww.j a v a  2 s.c o m
        File cloneFolder = new File(clone.getContentLocation().getPath());
        if (!cloneFolder.exists()) {
            cloneFolder.mkdir();
        }
        CloneCommand cc = Git.cloneRepository();
        cc.setBare(false);
        cc.setCredentialsProvider(credentials);
        cc.setDirectory(cloneFolder);
        cc.setRemote(Constants.DEFAULT_REMOTE_NAME);
        cc.setURI(clone.getUrl());
        Git git = cc.call();

        // Configure the clone, see Bug 337820
        GitCloneHandlerV1.doConfigureClone(git, user);
        git.getRepository().close();
    } catch (IOException e) {
        return new Status(IStatus.ERROR, GitActivator.PI_GIT, "Error cloning git repository", e);
    } catch (CoreException e) {
        return e.getStatus();
    } catch (GitAPIException e) {
        return getGitAPIExceptionStatus(e, "Error cloning git repository");
    } catch (JGitInternalException e) {
        return getJGitInternalExceptionStatus(e, "Error cloning git repository");
    } catch (Exception e) {
        return new Status(IStatus.ERROR, GitActivator.PI_GIT, "Error cloning git repository", e);
    }
    JSONObject jsonData = new JSONObject();
    try {
        jsonData.put(ProtocolConstants.KEY_LOCATION, URI.create(this.cloneLocation));
    } catch (JSONException e) {
        // Should not happen
    }
    return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, jsonData);
}

From source file:org.eclipse.orion.server.git.servlets.CloneJob.java

License:Open Source License

private IStatus doClone() {
    try {/*from w  w w  .j  a v a 2 s  .  co m*/
        File cloneFolder = new File(clone.getContentLocation().getPath());
        if (!cloneFolder.exists()) {
            cloneFolder.mkdir();
        }
        CloneCommand cc = Git.cloneRepository();
        cc.setBare(false);
        cc.setCredentialsProvider(credentials);
        cc.setDirectory(cloneFolder);
        cc.setRemote(Constants.DEFAULT_REMOTE_NAME);
        cc.setURI(clone.getUrl());
        Git git = cc.call();

        // Configure the clone, see Bug 337820
        task.setMessage(NLS.bind("Configuring {0}...", clone.getUrl()));
        updateTask(task);
        GitCloneHandlerV1.doConfigureClone(git, user);
        git.getRepository().close();
    } catch (IOException e) {
        return new Status(IStatus.ERROR, GitActivator.PI_GIT, "Error cloning git repository", e);
    } catch (CoreException e) {
        return e.getStatus();
    } catch (JGitInternalException e) {
        return getJGitInternalExceptionStatus(e, "An internal git error cloning git repository");
    } catch (Exception e) {
        return new Status(IStatus.ERROR, GitActivator.PI_GIT, "Error cloning git repository", e);
    }
    return Status.OK_STATUS;
}

From source file:org.eclipse.thym.core.plugin.CordovaPluginManager.java

License:Open Source License

/**
 * Installs a Cordova plug-in from a git repository. 
 * This method delegates to {@link #doInstallPlugin(File)} after cloning the
 * repository to a temporary location to complete the installation of the 
 * plug-in. //from w  w  w .j ava2  s. c om
 * <br/>
 * If commit is not null the cloned repository will be checked out to 
 * commit. 
 * <br/>
 * If subdir is not null it is assumed that the subdir path exists and installation 
 * will be done from that location. 
 * 
 * @param uri
 * @param overwrite
 * @param isDependency 
 * @param monitor 
 * @param commit 
 * @param subdir
 * @throws CoreException
 */
public void installPlugin(URI uri, FileOverwriteCallback overwrite, boolean isDependency,
        IProgressMonitor monitor) throws CoreException {
    File tempRepoDirectory = new File(FileUtils.getTempDirectory(),
            "cordova_plugin_tmp_" + Long.toString(System.currentTimeMillis()));
    tempRepoDirectory.deleteOnExit();
    try {
        if (monitor.isCanceled())
            return;
        monitor.subTask("Clone plugin repository");
        String gitUrl = uri.getScheme() + ":" + uri.getSchemeSpecificPart();
        Git git = Git.cloneRepository().setDirectory(tempRepoDirectory).setURI(gitUrl).call();
        File pluginDirectory = tempRepoDirectory;
        String fragment = uri.getFragment();
        String commit = null;
        String subdir = null;

        if (fragment != null) {
            int idx = fragment.indexOf(':');
            if (idx < 0) {
                idx = fragment.length();
            }
            commit = fragment.substring(0, idx);
            subdir = fragment.substring(Math.min(idx + 1, fragment.length()));
            if (monitor.isCanceled()) {
                throw new CanceledException("Plug-in installation cancelled");
            }
            if (commit != null && !commit.isEmpty()) {
                git.checkout().setName(commit).call();
            }
            monitor.worked(1);

            if (subdir != null && !subdir.isEmpty()) {
                pluginDirectory = new File(tempRepoDirectory, subdir);
                if (!pluginDirectory.isDirectory()) {
                    throw new CoreException(new Status(IStatus.ERROR, HybridCore.PLUGIN_ID,
                            NLS.bind("{0} directory does not exist in this git repository", subdir)));
                }
            }
        }
        SubProgressMonitor sm = new SubProgressMonitor(monitor, 1);

        Document doc = readPluginXML(pluginDirectory);
        this.doInstallPlugin(pluginDirectory, doc, overwrite, sm);
        String id = CordovaPluginXMLHelper.getAttributeValue(doc.getDocumentElement(), "id");
        JsonObject source = new JsonObject();
        source.addProperty("type", "git");
        source.addProperty("url", gitUrl);
        if (subdir != null && !subdir.isEmpty()) {
            source.addProperty("subdir", subdir);
        }
        if (commit != null && !commit.isEmpty()) {
            source.addProperty("ref", commit);
        }
        this.saveFetchMetadata(source, id, monitor);
        if (!isDependency) {//update config.xml 
            List<IPluginInstallationAction> actions = new ArrayList<IPluginInstallationAction>(1);
            Map<String, String> params = new HashMap<String, String>();
            params.put("url", uri.toString());
            actions.add(getPluginInstallRecordAction(doc, params));
            runActions(actions, false, overwrite, monitor);
        }
    } catch (GitAPIException e) {
        throw new CoreException(
                new Status(IStatus.ERROR, HybridCore.PLUGIN_ID, "Error cloning the plugin repository", e));
    } finally {
        monitor.done();
    }
}

From source file:org.eclipse.winery.repository.backend.filebased.GitBasedRepository.java

License:Open Source License

private Git cloneRepository(String repoUrl, String branch) throws GitAPIException {
    Git git = Git.cloneRepository().setURI(repoUrl).setDirectory(this.getRepositoryDep().toFile()).call();
    if (!"master".equals(branch)) {
        git.checkout().setCreateBranch(true).setName(branch)
                .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).setStartPoint("origin/" + branch)
                .call();//www .  j av a2  s .  c om
    }

    return git;
}

From source file:org.eclipse.winery.repository.export.CsarExporter.java

License:Open Source License

/**
 * Special handling for artifact template directories source and files
 *
 * @param zos            Output stream for the archive that should contain the file
 * @param csarEntry      Reference to the file that should be added to the archive
 * @param fileProperties Describing the path to the file inside the archive
 * @throws IOException thrown when the temporary directory can not be created
 */// www  . j  ava 2 s  .  c  om
private void addArtifactTemplateToZipFile(ZipOutputStream zos, RepositoryRefBasedCsarEntry csarEntry,
        CsarContentProperties fileProperties) throws IOException {
    GitInfo gitInfo = BackendUtils.getGitInformation((DirectoryId) csarEntry.getReference().getParent());

    if (gitInfo == null) {
        addCsarEntryToArchive(zos, csarEntry, fileProperties);
        return;
    }

    // TODO: This is not quite correct. The files should reside checked out at "source/"
    // TODO: Hash all these git files (to be included in the provenance)
    Path tempDir = Files.createTempDirectory(WINERY_TEMP_DIR_PREFIX);
    try {
        Git git = Git.cloneRepository().setURI(gitInfo.URL).setDirectory(tempDir.toFile()).call();
        git.checkout().setName(gitInfo.BRANCH).call();
        String path = "artifacttemplates/"
                + Util.URLencode(((ArtifactTemplateId) csarEntry.getReference().getParent().getParent())
                        .getQName().getNamespaceURI())
                + "/" + ((ArtifactTemplateId) csarEntry.getReference().getParent().getParent()).getQName()
                        .getLocalPart()
                + "/files/";
        TArtifactTemplate template = BackendUtils
                .getTArtifactTemplate((DirectoryId) csarEntry.getReference().getParent());
        addWorkingTreeToArchive(zos, template, tempDir, path);
    } catch (GitAPIException e) {
        CsarExporter.LOGGER
                .error(String.format("Error while cloning repo: %s / %s", gitInfo.URL, gitInfo.BRANCH), e);
    } finally {
        deleteDirectory(tempDir);
    }
}

From source file:org.eclipse.winery.repository.PrefsTestEnabledGitBackedRepository.java

License:Open Source License

public PrefsTestEnabledGitBackedRepository() throws Exception {
    super(false);

    Path repositoryPath = Paths.get(System.getProperty("java.io.tmpdir")).resolve("test-repository");
    if (!Files.exists(repositoryPath)) {
        Files.createDirectory(repositoryPath);
    }//w  w  w  .  ja v  a  2  s . c  o m

    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    if (!Files.exists(repositoryPath.resolve(".git"))) {
        this.git = Git.cloneRepository().setURI("https://github.com/winery/test-repository.git").setBare(false)
                .setCloneAllBranches(true).setDirectory(repositoryPath.toFile()).call();
    } else {
        Repository gitRepo = builder.setWorkTree(repositoryPath.toFile()).setMustExist(false).build();
        this.git = new Git(gitRepo);
        try {
            this.git.fetch().call();
        } catch (TransportException e) {
            // we ignore it to enable offline testing
            LOGGER.debug("Working in offline mode", e);
        }
    }

    this.repository = new GitBasedRepository(repositoryPath.toString());
}