Example usage for org.eclipse.jgit.transport RefSpec getSource

List of usage examples for org.eclipse.jgit.transport RefSpec getSource

Introduction

In this page you can find the example usage for org.eclipse.jgit.transport RefSpec getSource.

Prototype

public String getSource() 

Source Link

Document

Get the source ref description.

Usage

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

License:Apache License

private List<RemoteRefUpdate> generateUpdates(final Transport tn) throws IOException {
    final ProjectControl pc;
    try {/*  w ww.j  av  a  2 s .  co m*/
        pc = pool.controlFor(projectName);
    } catch (NoSuchProjectException e) {
        return Collections.emptyList();
    }

    Map<String, Ref> local = db.getAllRefs();
    if (!pc.allRefsAreVisible()) {
        if (!mirror) {
            // If we aren't mirroring, reduce the space we need to filter
            // to only the references we will update during this operation.
            //
            Map<String, Ref> n = new HashMap<String, Ref>();
            for (String src : delta) {
                Ref r = local.get(src);
                if (r != null) {
                    n.put(src, r);
                }
            }
            local = n;
        }

        final ReviewDb meta;
        try {
            meta = schema.open();
        } catch (OrmException e) {
            log.error("Cannot read database to replicate to " + projectName, e);
            return Collections.emptyList();
        }
        try {
            local = new VisibleRefFilter(db, pc, meta, true).filter(local);
        } finally {
            meta.close();
        }
    }

    final List<RemoteRefUpdate> cmds = new ArrayList<RemoteRefUpdate>();
    if (mirror) {
        final Map<String, Ref> remote = listRemote(tn);

        for (final Ref src : local.values()) {
            final RefSpec spec = matchSrc(src.getName());
            if (spec != null) {
                final Ref dst = remote.get(spec.getDestination());
                if (dst == null || !src.getObjectId().equals(dst.getObjectId())) {
                    // Doesn't exist yet, or isn't the same value, request to push.
                    //
                    send(cmds, spec, src);
                }
            }
        }

        for (final Ref ref : remote.values()) {
            if (!Constants.HEAD.equals(ref.getName())) {
                final RefSpec spec = matchDst(ref.getName());
                if (spec != null && !local.containsKey(spec.getSource())) {
                    // No longer on local side, request removal.
                    //
                    delete(cmds, spec);
                }
            }
        }

    } else {
        for (final String src : delta) {
            final RefSpec spec = matchSrc(src);
            if (spec != null) {
                // If the ref still exists locally, send it, otherwise delete it.
                //
                Ref srcRef = local.get(src);
                if (srcRef != null) {
                    send(cmds, spec, srcRef);
                } else {
                    delete(cmds, spec);
                }
            }
        }
    }

    return cmds;
}

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();
    }/*from w w  w .  j  a v  a  2  s .c  o  m*/
    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 ww  .j  a v a  2s.c  o 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.PushOne.java

License:Apache License

private List<RemoteRefUpdate> doPushAll(Transport tn, Map<String, Ref> local)
        throws NotSupportedException, TransportException, IOException {
    List<RemoteRefUpdate> cmds = new ArrayList<>();
    boolean noPerms = !pool.isReplicatePermissions();
    Map<String, Ref> remote = listRemote(tn);
    for (Ref src : local.values()) {
        if (!canPushRef(src.getName(), noPerms)) {
            continue;
        }//from w  w w. j  a v a 2 s. c  o m

        RefSpec spec = matchSrc(src.getName());
        if (spec != null) {
            Ref dst = remote.get(spec.getDestination());
            if (dst == null || !src.getObjectId().equals(dst.getObjectId())) {
                // Doesn't exist yet, or isn't the same value, request to push.
                push(cmds, spec, src);
            }
        }
    }

    if (config.isMirror()) {
        for (Ref ref : remote.values()) {
            if (!Constants.HEAD.equals(ref.getName())) {
                RefSpec spec = matchDst(ref.getName());
                if (spec != null && !local.containsKey(spec.getSource())) {
                    // No longer on local side, request removal.
                    delete(cmds, spec);
                }
            }
        }
    }
    return cmds;
}

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();
    }/* w  w w. j a  va 2s.co  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:org.eclipse.che.git.impl.jgit.JGitConnection.java

License:Open Source License

@Override
public PullResponse pull(PullRequest request) throws GitException, UnauthorizedException {
    String remoteName = request.getRemote();
    String remoteUri;/* w  ww. j a v  a 2  s.co  m*/
    try {
        if (repository.getRepositoryState().equals(RepositoryState.MERGING)) {
            throw new GitException(ERROR_PULL_MERGING);
        }
        String fullBranch = repository.getFullBranch();
        if (!fullBranch.startsWith(Constants.R_HEADS)) {
            throw new DetachedHeadException(ERROR_PULL_HEAD_DETACHED);
        }

        String branch = fullBranch.substring(Constants.R_HEADS.length());

        StoredConfig config = repository.getConfig();
        if (remoteName == null) {
            remoteName = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branch,
                    ConfigConstants.CONFIG_KEY_REMOTE);
            if (remoteName == null) {
                remoteName = Constants.DEFAULT_REMOTE_NAME;
            }
        }
        remoteUri = config.getString(ConfigConstants.CONFIG_REMOTE_SECTION, remoteName,
                ConfigConstants.CONFIG_KEY_URL);

        String remoteBranch;
        RefSpec fetchRefSpecs = null;
        String refSpec = request.getRefSpec();
        if (refSpec != null) {
            fetchRefSpecs = (refSpec.indexOf(':') < 0) //
                    ? new RefSpec(Constants.R_HEADS + refSpec + ":" + fullBranch) //
                    : new RefSpec(refSpec);
            remoteBranch = fetchRefSpecs.getSource();
        } else {
            remoteBranch = config.getString(ConfigConstants.CONFIG_BRANCH_SECTION, branch,
                    ConfigConstants.CONFIG_KEY_MERGE);
        }

        if (remoteBranch == null) {
            remoteBranch = fullBranch;
        }

        FetchCommand fetchCommand = getGit().fetch();
        fetchCommand.setRemote(remoteName);
        if (fetchRefSpecs != null) {
            fetchCommand.setRefSpecs(fetchRefSpecs);
        }
        int timeout = request.getTimeout();
        if (timeout > 0) {
            fetchCommand.setTimeout(timeout);
        }

        FetchResult fetchResult = (FetchResult) executeRemoteCommand(remoteUri, fetchCommand);

        Ref remoteBranchRef = fetchResult.getAdvertisedRef(remoteBranch);
        if (remoteBranchRef == null) {
            remoteBranchRef = fetchResult.getAdvertisedRef(Constants.R_HEADS + remoteBranch);
        }
        if (remoteBranchRef == null) {
            throw new GitException(String.format(ERROR_PULL_REF_MISSING, remoteBranch));
        }
        org.eclipse.jgit.api.MergeResult mergeResult = getGit().merge().include(remoteBranchRef).call();
        if (mergeResult.getMergeStatus()
                .equals(org.eclipse.jgit.api.MergeResult.MergeStatus.ALREADY_UP_TO_DATE)) {
            return newDto(PullResponse.class).withCommandOutput("Already up-to-date");
        }

        if (mergeResult.getConflicts() != null) {
            StringBuilder message = new StringBuilder(ERROR_PULL_MERGE_CONFLICT_IN_FILES);
            message.append(lineSeparator());
            Map<String, int[][]> allConflicts = mergeResult.getConflicts();
            for (String path : allConflicts.keySet()) {
                message.append(path).append(lineSeparator());
            }
            message.append(ERROR_PULL_AUTO_MERGE_FAILED);
            throw new GitException(message.toString());
        }
    } catch (CheckoutConflictException exception) {
        StringBuilder message = new StringBuilder(ERROR_CHECKOUT_CONFLICT);
        message.append(lineSeparator());
        for (String path : exception.getConflictingPaths()) {
            message.append(path).append(lineSeparator());
        }
        message.append(ERROR_PULL_COMMIT_BEFORE_MERGE);
        throw new GitException(message.toString(), exception);
    } catch (IOException | GitAPIException exception) {
        String errorMessage;
        if (exception.getMessage().equals("Invalid remote: " + remoteName)) {
            errorMessage = ERROR_NO_REMOTE_REPOSITORY;
        } else {
            errorMessage = exception.getMessage();
        }
        throw new GitException(errorMessage, exception);
    }
    return newDto(PullResponse.class).withCommandOutput("Successfully pulled from " + remoteUri);
}

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

License:Open Source License

/**
 * @param rc//  w  w  w. ja va  2s  . co m
 *            the remote configuration
 * @return {@code true} if the remote configuration is configured for
 *         fetching from Gerrit
 */
public static boolean isGerritFetch(RemoteConfig rc) {
    for (RefSpec fetchSpec : rc.getFetchRefSpecs()) {
        String source = fetchSpec.getSource();
        String destination = fetchSpec.getDestination();
        if (source == null || destination == null) {
            continue;
        }
        if (source.startsWith(Constants.R_NOTES) && destination.startsWith(Constants.R_NOTES)) {
            return true;
        }
    }
    return false;
}

From source file:org.eclipse.egit.ui.internal.components.RefSpecPanel.java

License:Open Source License

private static RefSpec setRefSpecDestination(final RefSpec spec, final String dst) {
    final String src;
    if (RefSpec.isWildcard(dst))
        src = wildcardSpecComponent(spec.getSource());
    else//from   www . j a  v  a  2 s. c  o m
        src = unwildcardSpecComponent(spec.getSource(), dst);
    return spec.setSourceDestination(src, dst);
}

From source file:org.eclipse.egit.ui.internal.components.RefSpecPanel.java

License:Open Source License

private String validateSpec(final RefSpec spec) {
    final String src = spec.getSource();
    final String dst = spec.getDestination();
    final boolean wildcard = spec.isWildcard();

    // check src//from www. j  av  a 2 s .c om
    if (pushSpecs) {
        if (!isDeleteRefSpec(spec)) {
            if (src.length() == 0)
                return UIText.RefSpecPanel_validationSrcUpdateRequired;
            else if (!wildcard && !isLocalRef(src))
                return NLS.bind(UIText.RefSpecPanel_validationRefInvalidLocal, src);
            else if (wildcard && !isValidRefExpression(src))
                return NLS.bind(UIText.RefSpecPanel_validationRefInvalidExpression, src);
            // ignore non-matching wildcard specs
        }
    } else {
        if (src == null || src.length() == 0)
            return UIText.RefSpecPanel_validationSrcUpdateRequired;
        else if (!wildcard && !isRemoteRef(src))
            return NLS.bind(UIText.RefSpecPanel_validationRefNonExistingRemote, src);
        // ignore non-matching wildcard specs
    }

    // check dst
    if (dst == null || dst.length() == 0) {
        if (isDeleteRefSpec(spec))
            return UIText.RefSpecPanel_validationRefDeleteRequired;
        return UIText.RefSpecPanel_validationDstRequired;
    } else if (!isValidRefExpression(dst))
        return NLS.bind(UIText.RefSpecPanel_validationRefInvalidExpression, dst);
    else if (isDeleteRefSpec(spec) && !isRemoteRef(dst))
        return NLS.bind(UIText.RefSpecPanel_validationRefNonExistingRemoteDelete, dst);

    return null;
}

From source file:org.eclipse.egit.ui.internal.dialogs.AbstractConfigureRemoteDialog.java

License:Open Source License

private void doPaste() {
    Clipboard clipboard = new Clipboard(getShell().getDisplay());
    try {/*w  w w.j a v a2s . c  o m*/
        String content = (String) clipboard.getContents(TextTransfer.getInstance());
        if (content == null) {
            MessageDialog.openConfirm(getShell(),
                    UIText.AbstractConfigureRemoteDialog_EmptyClipboardDialogTitle,
                    UIText.AbstractConfigureRemoteDialog_EmptyClipboardDialogMessage);
        }
        try {
            RefSpec spec = new RefSpec(content);
            Ref source;
            try {
                // TODO better checks for wild-cards and such
                source = getRepository().findRef(isPush ? spec.getSource() : spec.getDestination());
            } catch (IOException e) {
                source = null;
            }
            if (source != null || MessageDialog.openQuestion(getShell(),
                    UIText.AbstractConfigureRemoteDialog_InvalidRefDialogTitle,
                    NLS.bind(UIText.AbstractConfigureRemoteDialog_InvalidRefDialogMessage, spec.toString()))) {
                addRefSpec(spec);
            }
            updateControls();
        } catch (IllegalArgumentException e) {
            MessageDialog.openError(getShell(), UIText.AbstractConfigureRemoteDialog_NoRefSpecDialogTitle,
                    UIText.AbstractConfigureRemoteDialog_NoRefSpecDialogMessage);
        }
    } finally {
        clipboard.dispose();
    }
}