Example usage for org.eclipse.jgit.transport RemoteConfig addPushRefSpec

List of usage examples for org.eclipse.jgit.transport RemoteConfig addPushRefSpec

Introduction

In this page you can find the example usage for org.eclipse.jgit.transport RemoteConfig addPushRefSpec.

Prototype

public boolean addPushRefSpec(RefSpec s) 

Source Link

Document

Add a new push RefSpec to this remote.

Usage

From source file:com.google.gerrit.server.git.PushReplication.java

License:Apache License

private List<ReplicationConfig> allConfigs(final SitePaths site) throws ConfigInvalidException, IOException {
    final FileBasedConfig cfg = new FileBasedConfig(site.replication_config, FS.DETECTED);

    if (!cfg.getFile().exists()) {
        log.warn("No " + cfg.getFile() + "; not replicating");
        return Collections.emptyList();
    }//  www .  j  av a  2  s  .c om
    if (cfg.getFile().length() == 0) {
        log.info("Empty " + cfg.getFile() + "; not replicating");
        return Collections.emptyList();
    }

    try {
        cfg.load();
    } catch (ConfigInvalidException e) {
        throw new ConfigInvalidException("Config file " + cfg.getFile() + " is invalid: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new IOException("Cannot read " + cfg.getFile() + ": " + e.getMessage(), e);
    }

    final List<ReplicationConfig> r = new ArrayList<ReplicationConfig>();
    for (final RemoteConfig c : allRemotes(cfg)) {
        if (c.getURIs().isEmpty()) {
            continue;
        }

        for (final URIish u : c.getURIs()) {
            if (u.getPath() == null || !u.getPath().contains("${name}")) {
                throw new ConfigInvalidException("remote." + c.getName() + ".url" + " \"" + u
                        + "\" lacks ${name} placeholder in " + cfg.getFile());
            }
        }

        // In case if refspec destination for push is not set then we assume it is
        // equal to source
        for (RefSpec ref : c.getPushRefSpecs()) {
            if (ref.getDestination() == null) {
                ref.setDestination(ref.getSource());
            }
        }

        if (c.getPushRefSpecs().isEmpty()) {
            RefSpec spec = new RefSpec();
            spec = spec.setSourceDestination("refs/*", "refs/*");
            spec = spec.setForceUpdate(true);
            c.addPushRefSpec(spec);
        }

        r.add(new ReplicationConfig(injector, workQueue, c, cfg, database, replicationUserFactory));
    }
    return Collections.unmodifiableList(r);
}

From source file:com.googlesource.gerrit.plugins.github.replication.GitHubDestinations.java

License:Apache License

private List<Destination> getDestinations(File cfgPath) throws ConfigInvalidException, IOException {
    FileBasedConfig cfg = new FileBasedConfig(cfgPath, FS.DETECTED);
    if (!cfg.getFile().exists() || cfg.getFile().length() == 0) {
        return Collections.emptyList();
    }//from  w  w w .j a va2  s  .  co  m

    try {
        cfg.load();
    } catch (ConfigInvalidException e) {
        throw new ConfigInvalidException(
                String.format("Config file %s is invalid: %s", cfg.getFile(), e.getMessage()), e);
    } catch (IOException e) {
        throw new IOException(String.format("Cannot read %s: %s", cfg.getFile(), e.getMessage()), e);
    }

    ImmutableList.Builder<Destination> dest = ImmutableList.builder();
    for (RemoteConfig c : allRemotes(cfg)) {
        if (c.getURIs().isEmpty()) {
            continue;
        }

        for (URIish u : c.getURIs()) {
            if (u.getPath() == null || !u.getPath().contains("${name}")) {
                throw new ConfigInvalidException(String.format(
                        "remote.%s.url \"%s\" lacks ${name} placeholder in %s", c.getName(), u, cfg.getFile()));
            }
        }

        // If destination for push is not set assume equal to source.
        for (RefSpec ref : c.getPushRefSpecs()) {
            if (ref.getDestination() == null) {
                ref.setDestination(ref.getSource());
            }
        }

        if (c.getPushRefSpecs().isEmpty()) {
            c.addPushRefSpec(new RefSpec().setSourceDestination("refs/*", "refs/*").setForceUpdate(true));
        }

        dest.add(new Destination(injector, c, cfg, database, replicationUserFactory, pluginUser,
                gitRepositoryManager, groupBackend));
    }
    return dest.build();
}

From source file:com.googlesource.gerrit.plugins.replication.ReplicationFileBasedConfig.java

License:Apache License

private List<Destination> allDestinations() throws ConfigInvalidException, IOException {
    if (!config.getFile().exists()) {
        log.warn("Config file " + config.getFile() + " does not exist; not replicating");
        return Collections.emptyList();
    }//from w w w  . j ava  2 s .c  o m
    if (config.getFile().length() == 0) {
        log.info("Config file " + config.getFile() + " is empty; not replicating");
        return Collections.emptyList();
    }

    try {
        config.load();
    } catch (ConfigInvalidException e) {
        throw new ConfigInvalidException(
                String.format("Config file %s is invalid: %s", config.getFile(), e.getMessage()), e);
    } catch (IOException e) {
        throw new IOException(String.format("Cannot read %s: %s", config.getFile(), e.getMessage()), e);
    }

    replicateAllOnPluginStart = config.getBoolean("gerrit", "replicateOnStartup", true);

    defaultForceUpdate = config.getBoolean("gerrit", "defaultForceUpdate", false);

    ImmutableList.Builder<Destination> dest = ImmutableList.builder();
    for (RemoteConfig c : allRemotes(config)) {
        if (c.getURIs().isEmpty()) {
            continue;
        }

        // If destination for push is not set assume equal to source.
        for (RefSpec ref : c.getPushRefSpecs()) {
            if (ref.getDestination() == null) {
                ref.setDestination(ref.getSource());
            }
        }

        if (c.getPushRefSpecs().isEmpty()) {
            c.addPushRefSpec(
                    new RefSpec().setSourceDestination("refs/*", "refs/*").setForceUpdate(defaultForceUpdate));
        }

        Destination destination = new Destination(injector, new DestinationConfiguration(c, config),
                replicationUserFactory, pluginUser, gitRepositoryManager, groupBackend, stateLog,
                groupIncludeCache);

        if (!destination.isSingleProjectMatch()) {
            for (URIish u : c.getURIs()) {
                if (u.getPath() == null || !u.getPath().contains("${name}")) {
                    throw new ConfigInvalidException(
                            String.format("remote.%s.url \"%s\" lacks ${name} placeholder in %s", c.getName(),
                                    u, config.getFile()));
                }
            }
        }

        dest.add(destination);
    }
    return dest.build();
}

From source file:com.rimerosolutions.ant.git.tasks.PushTask.java

License:Apache License

@Override
protected void doExecute() {
    try {//www .ja  v a2  s . c  o  m
        StoredConfig config = git.getRepository().getConfig();
        List<RemoteConfig> remoteConfigs = RemoteConfig.getAllRemoteConfigs(config);

        if (remoteConfigs.isEmpty()) {
            URIish uri = new URIish(getUri());

            RemoteConfig remoteConfig = new RemoteConfig(config, Constants.DEFAULT_REMOTE_NAME);

            remoteConfig.addURI(uri);
            remoteConfig.addFetchRefSpec(new RefSpec(DEFAULT_REFSPEC_STRING));
            remoteConfig.addPushRefSpec(new RefSpec(DEFAULT_REFSPEC_STRING));
            remoteConfig.update(config);

            config.save();
        }

        String currentBranch = git.getRepository().getBranch();
        List<RefSpec> specs = Arrays.asList(new RefSpec(currentBranch + ":" + currentBranch));

        if (deleteRemoteBranch != null) {
            specs = Arrays.asList(new RefSpec(":" + Constants.R_HEADS + deleteRemoteBranch));
        }

        PushCommand pushCommand = git.push().setPushAll().setRefSpecs(specs).setDryRun(false);

        if (getUri() != null) {
            pushCommand.setRemote(getUri());
        }

        setupCredentials(pushCommand);

        if (includeTags) {
            pushCommand.setPushTags();
        }

        if (getProgressMonitor() != null) {
            pushCommand.setProgressMonitor(getProgressMonitor());
        }

        Iterable<PushResult> pushResults = pushCommand.setForce(true).call();

        for (PushResult pushResult : pushResults) {
            log(pushResult.getMessages());
            GitTaskUtils.validateRemoteRefUpdates(PUSH_FAILED_MESSAGE, pushResult.getRemoteUpdates());
            GitTaskUtils.validateTrackingRefUpdates(PUSH_FAILED_MESSAGE, pushResult.getTrackingRefUpdates());
        }
    } catch (Exception e) {
        if (pushFailedProperty != null) {
            getProject().setProperty(pushFailedProperty, e.getMessage());
        }

        throw new GitBuildException(PUSH_FAILED_MESSAGE, e);
    }
}

From source file:org.commonjava.gitwrap.BareGitRepository.java

License:Open Source License

public BareGitRepository setPushTarget(final String name, final String uri, final boolean heads,
        final boolean tags) throws GitWrapException {
    try {/* w  w w.j  ava  2s . c o m*/
        final RemoteConfig remote = new RemoteConfig(repository.getConfig(), name);

        final URIish uriish = new URIish(uri);

        final List<URIish> uris = remote.getURIs();
        if (uris == null || !uris.contains(uriish)) {
            remote.addURI(uriish);
        }

        final List<URIish> pushURIs = remote.getPushURIs();
        if (pushURIs == null || !pushURIs.contains(uriish)) {
            remote.addPushURI(uriish);
        }

        final List<RefSpec> pushRefSpecs = remote.getPushRefSpecs();
        if (heads) {
            final RefSpec headSpec = new RefSpec("+" + Constants.R_HEADS + "*:" + Constants.R_HEADS + "*");
            if (pushRefSpecs == null || !pushRefSpecs.contains(headSpec)) {
                remote.addPushRefSpec(headSpec);
            }
        }

        if (tags) {
            final RefSpec tagSpec = new RefSpec("+" + Constants.R_TAGS + "*:" + Constants.R_TAGS + "*");
            if (pushRefSpecs == null || !pushRefSpecs.contains(tagSpec)) {
                remote.addPushRefSpec(tagSpec);
            }
        }

        remote.update(repository.getConfig());
        repository.getConfig().save();
    } catch (final URISyntaxException e) {
        throw new GitWrapException("Invalid URI-ish: %s. Nested error: %s", e, uri, e.getMessage());
    } catch (final IOException e) {
        throw new GitWrapException("Failed to write Git config: %s", e, e.getMessage());
    }

    return this;
}

From source file:org.eclipse.egit.core.internal.gerrit.GerritUtil.java

License:Open Source License

/**
 * Configure the gerrit push refspec HEAD:refs/for/<gerritBranch>
 *
 * @param remoteConfig/*from   w w w .  ja  v a 2 s. c o  m*/
 *            the remote configuration to configure this in
 * @param gerritBranch
 *            the branch to push to review for
 */
public static void configurePushRefSpec(RemoteConfig remoteConfig, String gerritBranch) {
    List<RefSpec> pushRefSpecs = new ArrayList<RefSpec>(remoteConfig.getPushRefSpecs());
    for (RefSpec refSpec : pushRefSpecs) {
        remoteConfig.removePushRefSpec(refSpec);
    }
    remoteConfig.addPushRefSpec(new RefSpec("HEAD:" + GerritUtil.REFS_FOR + gerritBranch)); //$NON-NLS-1$
}

From source file:org.eclipse.egit.core.op.ConfigurePushAfterCloneTask.java

License:Open Source License

/**
 * @param repository/*from  ww w  . j ava 2 s .c  o  m*/
 * @param monitor
 * @throws CoreException
 */
public void execute(Repository repository, IProgressMonitor monitor) throws CoreException {
    try {
        RemoteConfig configToUse = new RemoteConfig(repository.getConfig(), remoteName);
        if (pushRefSpec != null)
            configToUse.addPushRefSpec(new RefSpec(pushRefSpec));
        if (pushURI != null)
            configToUse.addPushURI(pushURI);
        configToUse.update(repository.getConfig());
        repository.getConfig().save();
    } catch (Exception e) {
        throw new CoreException(Activator.error(e.getMessage(), e));
    }

}

From source file:org.eclipse.egit.ui.internal.synchronize.action.PushAction.java

License:Open Source License

private void runPushOperation(final int timeout) {
    GitSynchronizeDataSet gsds = (GitSynchronizeDataSet) getConfiguration().getProperty(SYNCHRONIZATION_DATA);

    for (GitSynchronizeData gsd : gsds) {
        String remoteName = gsd.getSrcRemoteName();
        if (remoteName == null)
            continue;

        RemoteConfig rc;
        Repository repo = gsd.getRepository();
        StoredConfig config = repo.getConfig();
        try {//from w w  w.  java 2  s  . c o  m
            rc = new RemoteConfig(config, remoteName);
        } catch (URISyntaxException e) {
            Activator.logError("Unable to create RemoteConfiguration for remote: " + remoteName, e); //$NON-NLS-1$
            continue;
        }

        if (rc.getPushRefSpecs().isEmpty())
            rc.addPushRefSpec(new RefSpec(HEAD + ":" + gsd.getDstMerge())); //$NON-NLS-1$
        PushOperationUI push = new PushOperationUI(repo, rc, timeout, false);
        push.setCredentialsProvider(new EGitCredentialsProvider());
        push.start();
    }
}

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

License:Open Source License

private static boolean addGerritPushRefSpec(SetupTaskContext context, StoredConfig config,
        String checkoutBranch, String remoteName) throws Exception {
    for (RemoteConfig remoteConfig : RemoteConfig.getAllRemoteConfigs(config)) {
        if (remoteName.equals(remoteConfig.getName())) {
            RefSpec refSpec = new RefSpec("HEAD:refs/for/" + checkoutBranch);
            if (remoteConfig.addPushRefSpec(refSpec) && context.isPerforming()) {
                context.log("Adding push ref spec: " + refSpec);
            }/*from w ww  .j a  v  a 2 s .  c om*/

            remoteConfig.update(config);
            return true;
        }
    }

    return false;
}

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

License:Open Source License

private boolean addRemote(HttpServletRequest request, HttpServletResponse response, String path)
        throws IOException, JSONException, ServletException, CoreException, URISyntaxException {
    // expected path: /git/remote/file/{path}
    Path p = new Path(path);
    JSONObject toPut = OrionServlet.readJSONRequest(request);
    String remoteName = toPut.optString(GitConstants.KEY_REMOTE_NAME, null);
    // remoteName is required
    if (remoteName == null || remoteName.isEmpty()) {
        return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                HttpServletResponse.SC_BAD_REQUEST, "Remote name must be provided", null));
    }//from   w w w .j  a va 2s .  c o  m
    String remoteURI = toPut.optString(GitConstants.KEY_REMOTE_URI, null);
    // remoteURI is required
    if (remoteURI == null || remoteURI.isEmpty()) {
        return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                HttpServletResponse.SC_BAD_REQUEST, "Remote URI must be provided", null));
    }
    String fetchRefSpec = toPut.optString(GitConstants.KEY_REMOTE_FETCH_REF, null);
    String remotePushURI = toPut.optString(GitConstants.KEY_REMOTE_PUSH_URI, null);
    String pushRefSpec = toPut.optString(GitConstants.KEY_REMOTE_PUSH_REF, null);

    File gitDir = GitUtils.getGitDir(p);
    Repository db = new FileRepository(gitDir);
    StoredConfig config = db.getConfig();

    RemoteConfig rc = new RemoteConfig(config, remoteName);
    rc.addURI(new URIish(remoteURI));
    // FetchRefSpec is required, but default version can be generated
    // if it isn't provided
    if (fetchRefSpec == null || fetchRefSpec.isEmpty()) {
        fetchRefSpec = String.format("+refs/heads/*:refs/remotes/%s/*", remoteName); //$NON-NLS-1$
    }
    rc.addFetchRefSpec(new RefSpec(fetchRefSpec));
    // pushURI is optional
    if (remotePushURI != null && !remotePushURI.isEmpty())
        rc.addPushURI(new URIish(remotePushURI));
    // PushRefSpec is optional
    if (pushRefSpec != null && !pushRefSpec.isEmpty())
        rc.addPushRefSpec(new RefSpec(pushRefSpec));

    rc.update(config);
    config.save();

    URI baseLocation = getURI(request);
    JSONObject result = toJSON(remoteName, baseLocation);
    OrionServlet.writeJSONResponse(request, response, result);
    response.setHeader(ProtocolConstants.HEADER_LOCATION, result.getString(ProtocolConstants.KEY_LOCATION));
    response.setStatus(HttpServletResponse.SC_CREATED);
    return true;
}