Example usage for org.eclipse.jgit.transport TrackingRefUpdate getResult

List of usage examples for org.eclipse.jgit.transport TrackingRefUpdate getResult

Introduction

In this page you can find the example usage for org.eclipse.jgit.transport TrackingRefUpdate getResult.

Prototype

public RefUpdate.Result getResult() 

Source Link

Document

Get the status of this update.

Usage

From source file:com.barchart.jenkins.cascade.PluginScm.java

License:BSD License

/**
 * Update from remote.//ww  w  . j  a va 2 s. c om
 */
public static void scmUpdate(final BuildContext<CascadeBuild> context, final MavenModuleSet project)
        throws IOException, InterruptedException {

    final String message = checkScm(project);

    if (message != null) {
        throw new IllegalStateException(message);
    }

    final GitSCM gitScm = (GitSCM) project.getScm();
    final FilePath workspace = workspace(context, project);

    /** Remote objects. */
    final BuildLogger logger = context.logger();
    final String localBranch = localBranchName(gitScm);
    final String remoteName = remoteName(gitScm);
    final String remoteBranch = remoteBranchName(gitScm);

    /** Remote operation. */
    final FileCallable<Void> callable = new FileCallable<Void>() {

        private static final long serialVersionUID = 1L;

        public Void invoke(final File basedir, final VirtualChannel channel)
                throws IOException, InterruptedException {

            final String localBranchCurrent = PluginScmGit.branch(basedir);

            if (!localBranchCurrent.equals(localBranch)) {
                logger.logErr("branch mismatch: " + localBranchCurrent + "/" + localBranch);
                throw new IllegalStateException("Unexpected");
            }

            /** Spec for the fetch mapping. */
            final RefSpec fetchSpec = PluginScmGit.refFetch(remoteBranch, remoteName, remoteBranch);

            final FetchResult fetchResult = PluginScmGit.doFetch(basedir, remoteName, fetchSpec);

            /** Spec of the head of the remote branch. */
            final String refHead = PluginScmGit.refHeads(remoteBranch);

            /** Spec of the head of the local remote tracking branch. */
            final String refRemote = PluginScmGit.refRemotes(remoteName, remoteBranch);

            final TrackingRefUpdate trackingUpdate = fetchResult.getTrackingRefUpdate(refRemote);

            if (trackingUpdate == null) {
                logger.logTab("fetch status: " + "no update");
                return null;
            } else {
                final RefUpdate.Result fetchStatus = trackingUpdate.getResult();
                logger.logTab("fetch status: " + fetchStatus);
                if (fetchStatus == RefUpdate.Result.NO_CHANGE) {
                    return null;
                }
            }

            /** Reference to head of the remote branch. */
            final Ref remoteHead = fetchResult.getAdvertisedRef(refHead);

            final ObjectId commit = remoteHead.getObjectId();
            // logger.logTab("commit: " + commit);

            final MergeResult mergeResult = PluginScmGit.doMerge(basedir, commit);

            final MergeStatus mergeStatus = mergeResult.getMergeStatus();
            logger.logTab("merge status: " + mergeStatus);

            if (!mergeStatus.isSuccessful()) {
                throw new IllegalStateException("Unexpected");
            }

            return null;
        }
    };

    workspace.act(callable);

}

From source file:com.gitblit.service.MirrorService.java

License:Apache License

@Override
public void run() {
    if (!isReady()) {
        return;//from   w w  w  .ja v  a2 s  .  c  o m
    }

    running.set(true);

    for (String repositoryName : repositoryManager.getRepositoryList()) {
        if (forceClose.get()) {
            break;
        }
        if (repositoryManager.isCollectingGarbage(repositoryName)) {
            logger.debug("mirror is skipping {} garbagecollection", repositoryName);
            continue;
        }
        RepositoryModel model = null;
        Repository repository = null;
        try {
            model = repositoryManager.getRepositoryModel(repositoryName);
            if (!model.isMirror && !model.isBare) {
                // repository must be a valid bare git mirror
                logger.debug("mirror is skipping {} !mirror !bare", repositoryName);
                continue;
            }

            repository = repositoryManager.getRepository(repositoryName);
            if (repository == null) {
                logger.warn(
                        MessageFormat.format("MirrorExecutor is missing repository {0}?!?", repositoryName));
                continue;
            }

            // automatically repair (some) invalid fetch ref specs
            if (!repairAttempted.contains(repositoryName)) {
                repairAttempted.add(repositoryName);
                JGitUtils.repairFetchSpecs(repository);
            }

            // find the first mirror remote - there should only be one
            StoredConfig rc = repository.getConfig();
            RemoteConfig mirror = null;
            List<RemoteConfig> configs = RemoteConfig.getAllRemoteConfigs(rc);
            for (RemoteConfig config : configs) {
                if (config.isMirror()) {
                    mirror = config;
                    break;
                }
            }

            if (mirror == null) {
                // repository does not have a mirror remote
                logger.debug("mirror is skipping {} no mirror remote found", repositoryName);
                continue;
            }

            logger.debug("checking {} remote {} for ref updates", repositoryName, mirror.getName());
            final boolean testing = false;
            Git git = new Git(repository);
            FetchResult result = git.fetch().setRemote(mirror.getName()).setDryRun(testing).call();
            Collection<TrackingRefUpdate> refUpdates = result.getTrackingRefUpdates();
            if (refUpdates.size() > 0) {
                ReceiveCommand ticketBranchCmd = null;
                for (TrackingRefUpdate ru : refUpdates) {
                    StringBuilder sb = new StringBuilder();
                    sb.append("updated mirror ");
                    sb.append(repositoryName);
                    sb.append(" ");
                    sb.append(ru.getRemoteName());
                    sb.append(" -> ");
                    sb.append(ru.getLocalName());
                    if (ru.getResult() == Result.FORCED) {
                        sb.append(" (forced)");
                    }
                    sb.append(" ");
                    sb.append(ru.getOldObjectId() == null ? "" : ru.getOldObjectId().abbreviate(7).name());
                    sb.append("..");
                    sb.append(ru.getNewObjectId() == null ? "" : ru.getNewObjectId().abbreviate(7).name());
                    logger.info(sb.toString());

                    if (BranchTicketService.BRANCH.equals(ru.getLocalName())) {
                        ReceiveCommand.Type type = null;
                        switch (ru.getResult()) {
                        case NEW:
                            type = Type.CREATE;
                            break;
                        case FAST_FORWARD:
                            type = Type.UPDATE;
                            break;
                        case FORCED:
                            type = Type.UPDATE_NONFASTFORWARD;
                            break;
                        default:
                            type = null;
                            break;
                        }

                        if (type != null) {
                            ticketBranchCmd = new ReceiveCommand(ru.getOldObjectId(), ru.getNewObjectId(),
                                    ru.getLocalName(), type);
                        }
                    }
                }

                if (ticketBranchCmd != null) {
                    repository.fireEvent(new ReceiveCommandEvent(model, ticketBranchCmd));
                }
            }
        } catch (Exception e) {
            logger.error("Error updating mirror " + repositoryName, e);
        } finally {
            // cleanup
            if (repository != null) {
                repository.close();
            }
        }
    }

    running.set(false);
}

From source file:com.rimerosolutions.ant.git.GitTaskUtils.java

License:Apache License

/**
 * Check references updates for any errors
 *
 * @param errorPrefix The error prefix for any error message
 * @param refUpdates A collection of tracking references updates
 *//*  ww w  . j a  va 2s . co m*/
public static void validateTrackingRefUpdates(String errorPrefix, Collection<TrackingRefUpdate> refUpdates) {
    for (TrackingRefUpdate refUpdate : refUpdates) {
        RefUpdate.Result result = refUpdate.getResult();

        if (result == RefUpdate.Result.IO_FAILURE || result == RefUpdate.Result.LOCK_FAILURE
                || result == RefUpdate.Result.REJECTED || result == RefUpdate.Result.REJECTED_CURRENT_BRANCH) {
            throw new BuildException(String.format("%s - Status '%s'", errorPrefix, result.name()));
        }
    }
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.Fetcher.java

License:Apache License

private static void logFetchResults(@NotNull FetchResult result) {
    for (TrackingRefUpdate update : result.getTrackingRefUpdates()) {
        StringBuilder msg = new StringBuilder();
        msg.append("update ref remote name: ").append(update.getRemoteName()).append(", local name: ")
                .append(update.getLocalName()).append(", old object id: ")
                .append(update.getOldObjectId().name()).append(", new object id: ")
                .append(update.getNewObjectId().name()).append(", result: ").append(update.getResult());
        System.out.println(msg);//from   w  ww .  j a v  a 2s  .  com
    }
    String additionalMsgs = result.getMessages();
    if (additionalMsgs.length() > 0) {
        System.out.println("Remote process messages: " + additionalMsgs);
    }
}

From source file:jetbrains.buildServer.buildTriggers.vcs.git.GitServerUtil.java

License:Apache License

/**
 * Check all refs successfully updated, throws exception if they are not
 * @param result fetch result//from  ww  w  . j a v a2s.  co m
 * @throws VcsException if any ref was not successfully updated
 */
public static void checkFetchSuccessful(Repository db, FetchResult result) throws VcsException {
    for (TrackingRefUpdate update : result.getTrackingRefUpdates()) {
        String localRefName = update.getLocalName();
        RefUpdate.Result status = update.getResult();
        if (status == RefUpdate.Result.REJECTED || status == RefUpdate.Result.LOCK_FAILURE
                || status == RefUpdate.Result.IO_FAILURE) {
            if (status == RefUpdate.Result.LOCK_FAILURE) {
                TreeSet<String> caseSensitiveConflicts = new TreeSet<>();
                TreeSet<String> conflicts = new TreeSet<>();
                try {
                    OSInfo.OSType os = OSInfo.getOSType();
                    if (os == OSInfo.OSType.WINDOWS || os == OSInfo.OSType.MACOSX) {
                        Set<String> refNames = db.getRefDatabase().getRefs(RefDatabase.ALL).keySet();
                        for (String ref : refNames) {
                            if (!localRefName.equals(ref) && localRefName.equalsIgnoreCase(ref))
                                caseSensitiveConflicts.add(ref);
                        }
                    }
                    conflicts.addAll(db.getRefDatabase().getConflictingNames(localRefName));
                } catch (Exception e) {
                    //ignore
                }
                String msg;
                if (!conflicts.isEmpty()) {
                    msg = "Failed to fetch ref " + localRefName + ": it clashes with "
                            + StringUtil.join(", ", conflicts)
                            + ". Please remove conflicting refs from repository.";
                } else if (!caseSensitiveConflicts.isEmpty()) {
                    msg = "Failed to fetch ref " + localRefName
                            + ": on case-insensitive file system it clashes with "
                            + StringUtil.join(", ", caseSensitiveConflicts)
                            + ". Please remove conflicting refs from repository.";
                } else {
                    msg = "Fail to update '" + localRefName + "' (" + status.name() + ")";
                }
                throw new VcsException(msg);
            } else {
                throw new VcsException("Fail to update '" + localRefName + "' (" + status.name() + ")");
            }
        }
    }
}

From source file:net.erdfelt.android.sdkfido.git.internal.GitInfo.java

License:Apache License

public static void infoFetchResults(Repository db, FetchResult result) throws IOException {
    boolean headerDisplayed = false;

    for (TrackingRefUpdate update : result.getTrackingRefUpdates()) {
        if (update.getResult() == RefUpdate.Result.NO_CHANGE) {
            // skip if not changed
            continue;
        }//  w  ww . java  2 s .  c  o m

        char idChar = asIdChar(update.getResult());
        String idLong = asIdLong(db, update);
        String remoteRef = abbreviateRef(update.getRemoteName());
        String localRef = abbreviateRef(update.getLocalName());

        if (!headerDisplayed) {
            System.out.printf("Fetch Results from URI: %s%n", result.getURI());
            headerDisplayed = true;
        }

        System.out.printf(" %c %-20s %-18s > %s%n", idChar, idLong, remoteRef, localRef);
    }

    // Now show any remote messages
    StringReader reader = null;
    BufferedReader buf = null;
    try {
        reader = new StringReader(result.getMessages());
        buf = new BufferedReader(reader);
        String line;
        while ((line = buf.readLine()) != null) {
            System.out.printf("[remote] %s%n", line);
        }
    } finally {
        IOUtils.closeQuietly(buf);
        IOUtils.closeQuietly(reader);
    }
}

From source file:net.erdfelt.android.sdkfido.git.internal.GitInfo.java

License:Apache License

public static String asIdLong(Repository db, TrackingRefUpdate update) {
    RefUpdate.Result result = update.getResult();

    // Fast IDs/*from  ww w . j a  va2s. c  o m*/
    switch (result) {
    case LOCK_FAILURE:
        return "[lock failure]";
    case IO_FAILURE:
        return "[i/o error]";
    case REJECTED:
        return "[rejected]";
    }

    // Deleted Check Next
    if (ObjectId.zeroId().equals(update.getNewObjectId())) {
        return "[deleted]";
    }

    // All other results
    switch (result) {
    case NEW:
        if (update.getRemoteName().startsWith(Constants.R_HEADS)) {
            return "[new branch]";
        }

        if (update.getLocalName().startsWith(Constants.R_TAGS)) {
            return "[new tag]";
        }

        return "[new]";
    case FORCED: {
        String oldOID = update.getOldObjectId().abbreviate(ABBREV_LEN).name();
        String newOID = update.getNewObjectId().abbreviate(ABBREV_LEN).name();
        return oldOID + "..." + newOID;
    }
    case FAST_FORWARD: {
        String oldOID = update.getOldObjectId().abbreviate(ABBREV_LEN).name();
        String newOID = update.getNewObjectId().abbreviate(ABBREV_LEN).name();
        return oldOID + ".." + newOID;
    }
    case NO_CHANGE:
        return "[up to date]";
    default:
        return "[" + result.name() + "]";
    }
}

From source file:net.mobid.codetraq.runnables.GitChecker.java

License:Open Source License

private void showFetchResult(final FetchResult r, boolean logOnly) {
    ObjectReader reader = repo.newObjectReader();
    PrintWriter out = new PrintWriter(System.out);
    try {//  www  .  j ava2s .co m
        boolean shownURI = false;
        for (final TrackingRefUpdate u : r.getTrackingRefUpdates()) {
            if (u.getResult() == RefUpdate.Result.NO_CHANGE) {
                continue;
            }
            final char type = shortTypeOf(u.getResult());
            final String longType = longTypeOf(reader, u);
            final String src = abbreviateRef(u.getRemoteName(), false);
            final String dst = abbreviateRef(u.getLocalName(), true);

            if (!shownURI) {
                out.println("jGIT::from " + r.getURI());
                shownURI = true;
            }

            if (!logOnly) {
                out.format(" %c %-17s %-10s -> %s", type, longType, src, dst);
                out.println();
            }

        }
    } finally {
        reader.release();
    }
    showRemoteMessages(r.getMessages());
}

From source file:net.mobid.codetraq.runnables.GitChecker.java

License:Open Source License

private String longTypeOf(ObjectReader reader, final TrackingRefUpdate u) {
    final RefUpdate.Result r = u.getResult();
    if (r == RefUpdate.Result.LOCK_FAILURE)
        return "[lock fail]";
    if (r == RefUpdate.Result.IO_FAILURE)
        return "[i/o error]";
    if (r == RefUpdate.Result.REJECTED)
        return "[rejected]";
    if (ObjectId.zeroId().equals(u.getNewObjectId()))
        return "[deleted]";

    if (r == RefUpdate.Result.NEW) {
        if (u.getRemoteName().startsWith(Constants.R_HEADS))
            return "[new branch]";
        else if (u.getLocalName().startsWith(Constants.R_TAGS))
            return "[new tag]";
        return "[new]";
    }//from  ww  w.  j a  va 2  s  .  com

    if (r == RefUpdate.Result.FORCED) {
        final String aOld = safeAbbreviate(reader, u.getOldObjectId());
        final String aNew = safeAbbreviate(reader, u.getNewObjectId());
        return aOld + "..." + aNew;
    }

    if (r == RefUpdate.Result.FAST_FORWARD) {
        final String aOld = safeAbbreviate(reader, u.getOldObjectId());
        final String aNew = safeAbbreviate(reader, u.getNewObjectId());
        return aOld + ".." + aNew;
    }

    if (r == RefUpdate.Result.NO_CHANGE)
        return "[up to date]";
    return "[" + r.name() + "]";
}

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

License:Open Source License

static IStatus handleFetchResult(FetchResult fetchResult) {
    // handle result
    for (TrackingRefUpdate updateRes : fetchResult.getTrackingRefUpdates()) {
        Result res = updateRes.getResult();
        switch (res) {
        case NOT_ATTEMPTED:
        case NO_CHANGE:
        case NEW:
        case FORCED:
        case FAST_FORWARD:
        case RENAMED:
            // do nothing, as these statuses are OK
            break;
        case REJECTED:
            return new Status(IStatus.WARNING, GitActivator.PI_GIT, "Fetch rejected, not a fast-forward.");
        case REJECTED_CURRENT_BRANCH:
            return new Status(IStatus.WARNING, GitActivator.PI_GIT,
                    "Rejected because trying to delete the current branch.");
        default://from w  ww . j ava  2s .c om
            return new Status(IStatus.ERROR, GitActivator.PI_GIT, res.name());
        }
    }
    return Status.OK_STATUS;
}