Search in sources :

Example 16 with FetchResult

use of org.eclipse.jgit.transport.FetchResult in project archi-modelrepository-plugin by archi-contribs.

the class FetchJob method run.

@Override
protected IStatus run(IProgressMonitor monitor) {
    // Check first thing on entry
    if (!canRun()) {
        return Status.OK_STATUS;
    }
    boolean needsRefresh = false;
    for (IArchiRepository repo : fViewer.getRepositories(fViewer.getRootFolder())) {
        // Check also in for loop
        if (!canRun()) {
            return Status.OK_STATUS;
        }
        try {
            UsernamePassword npw = null;
            String url = repo.getOnlineRepositoryURL();
            if (GraficoUtils.isHTTP(url)) {
                // Get credentials. In some public repos we can still fetch without needing a password so we try anyway
                EncryptedCredentialsStorage cs = EncryptedCredentialsStorage.forRepository(repo);
                npw = cs.getUsernamePassword();
            }
            // Update ProxyAuthenticator
            ProxyAuthenticator.update();
            // Fetch
            FetchResult fetchResult = repo.fetchFromRemote(npw, null, false);
            // We got here, so the tree can be refreshed later
            needsRefresh = true;
            // Remote branches might have been deleted or added
            if (!fetchResult.getTrackingRefUpdates().isEmpty() && !fViewer.getControl().isDisposed()) {
                fViewer.getControl().getDisplay().asyncExec(() -> {
                    RepositoryListenerManager.INSTANCE.fireRepositoryChangedEvent(IRepositoryListener.BRANCHES_CHANGED, repo);
                });
            }
        } catch (IOException | GitAPIException ex) {
            ex.printStackTrace();
            if (ex instanceof TransportException) {
                disablePreference();
                // Show message
                Display.getDefault().syncExec(() -> {
                    // $NON-NLS-1$
                    String message = Messages.FetchJob_0 + " ";
                    // $NON-NLS-1$
                    message += Messages.FetchJob_1 + "\n\n";
                    try {
                        // $NON-NLS-1$
                        message += repo.getName() + "\n";
                        // $NON-NLS-1$
                        message += repo.getOnlineRepositoryURL() + "\n";
                    } catch (IOException ex1) {
                        ex1.printStackTrace();
                    }
                    MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.FetchJob_2, message);
                });
                return Status.OK_STATUS;
            }
        }// Encrypted password key error
         catch (GeneralSecurityException ex) {
            ex.printStackTrace();
            // Disable background fetch
            disablePreference();
            Display.getDefault().syncExec(() -> {
                // $NON-NLS-1$
                String message = Messages.FetchJob_0 + "\n";
                MessageDialog.openError(Display.getCurrent().getActiveShell(), Messages.FetchJob_2, message + ex.getMessage());
            });
            return Status.OK_STATUS;
        } finally {
            // Clear ProxyAuthenticator
            ProxyAuthenticator.clear();
        }
    }
    if (needsRefresh) {
        fViewer.refreshInBackground();
    }
    if (canRun()) {
        int seconds = ModelRepositoryPlugin.INSTANCE.getPreferenceStore().getInt(IPreferenceConstants.PREFS_FETCH_IN_BACKGROUND_INTERVAL);
        // Schedule again in x milliseconds if possible
        schedule(seconds * 1000);
    }
    return Status.OK_STATUS;
}
Also used : GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) FetchResult(org.eclipse.jgit.transport.FetchResult) EncryptedCredentialsStorage(org.archicontribs.modelrepository.authentication.EncryptedCredentialsStorage) GeneralSecurityException(java.security.GeneralSecurityException) IArchiRepository(org.archicontribs.modelrepository.grafico.IArchiRepository) IOException(java.io.IOException) TransportException(org.eclipse.jgit.api.errors.TransportException) UsernamePassword(org.archicontribs.modelrepository.authentication.UsernamePassword)

Example 17 with FetchResult

use of org.eclipse.jgit.transport.FetchResult in project archi-modelrepository-plugin by archi-contribs.

the class RefreshModelAction method pull.

protected int pull(UsernamePassword npw, ProgressMonitorDialog pmDialog) throws IOException, GitAPIException {
    PullResult pullResult = null;
    pmDialog.getProgressMonitor().subTask(Messages.RefreshModelAction_6);
    // update dialog
    Display.getCurrent().readAndDispatch();
    try {
        pullResult = getRepository().pullFromRemote(npw, new ProgressMonitorWrapper(pmDialog.getProgressMonitor()));
    } catch (Exception ex) {
        // So quietly absorb this and return OK
        if (ex instanceof RefNotAdvertisedException) {
            return PULL_STATUS_OK;
        }
        throw ex;
    }
    // Check for tracking updates
    FetchResult fetchResult = pullResult.getFetchResult();
    boolean newTrackingRefUpdates = fetchResult != null && !fetchResult.getTrackingRefUpdates().isEmpty();
    // Merge is already up to date...
    if (pullResult.getMergeResult().getMergeStatus() == MergeStatus.ALREADY_UP_TO_DATE) {
        // Check if any tracked refs were updated
        if (newTrackingRefUpdates) {
            return PULL_STATUS_OK;
        }
        return PULL_STATUS_UP_TO_DATE;
    }
    pmDialog.getProgressMonitor().subTask(Messages.RefreshModelAction_7);
    BranchStatus branchStatus = getRepository().getBranchStatus();
    // Setup the Graphico Model Loader
    GraficoModelLoader loader = new GraficoModelLoader(getRepository());
    // Merge failure
    if (!pullResult.isSuccessful() && pullResult.getMergeResult().getMergeStatus() == MergeStatus.CONFLICTING) {
        // Get the remote ref name
        String remoteRef = branchStatus.getCurrentRemoteBranch().getFullName();
        // Try to handle the merge conflict
        MergeConflictHandler handler = new MergeConflictHandler(pullResult.getMergeResult(), remoteRef, getRepository(), fWindow.getShell());
        try {
            handler.init(pmDialog.getProgressMonitor());
        } catch (IOException | GitAPIException ex) {
            // Clean up
            handler.resetToLocalState();
            if (ex instanceof CanceledException) {
                return PULL_STATUS_MERGE_CANCEL;
            }
            throw ex;
        }
        String dialogMessage = NLS.bind(Messages.RefreshModelAction_4, branchStatus.getCurrentLocalBranch().getShortName());
        pmDialog.getShell().setVisible(false);
        boolean result = handler.openConflictsDialog(dialogMessage);
        pmDialog.getShell().setVisible(true);
        if (result) {
            handler.merge();
        } else // User cancelled - we assume they committed all changes so we can reset
        {
            handler.resetToLocalState();
            return PULL_STATUS_MERGE_CANCEL;
        }
        // We now have to check if model can be reloaded
        pmDialog.getProgressMonitor().subTask(Messages.RefreshModelAction_8);
        // Reload the model from the Grafico XML files
        try {
            loader.loadModel();
        } catch (IOException ex) {
            // Clean up
            handler.resetToLocalState();
            throw ex;
        }
    } else {
        // Reload the model from the Grafico XML files
        pmDialog.getProgressMonitor().subTask(Messages.RefreshModelAction_8);
        loader.loadModel();
    }
    // Do a commit if needed
    if (getRepository().hasChangesToCommit()) {
        pmDialog.getProgressMonitor().subTask(Messages.RefreshModelAction_9);
        String commitMessage = NLS.bind(Messages.RefreshModelAction_1, branchStatus.getCurrentLocalBranch().getShortName());
        // Did we restore any missing objects?
        String restoredObjects = loader.getRestoredObjectsAsString();
        // Add to commit message
        if (restoredObjects != null) {
            // $NON-NLS-1$ //$NON-NLS-2$
            commitMessage += "\n\n" + Messages.RefreshModelAction_3 + "\n" + restoredObjects;
        }
        // TODO - not sure if amend should be false or true here?
        getRepository().commitChanges(commitMessage, false);
    }
    return PULL_STATUS_OK;
}
Also used : CanceledException(org.eclipse.jgit.api.errors.CanceledException) FetchResult(org.eclipse.jgit.transport.FetchResult) MergeConflictHandler(org.archicontribs.modelrepository.merge.MergeConflictHandler) IOException(java.io.IOException) PullResult(org.eclipse.jgit.api.PullResult) RefNotAdvertisedException(org.eclipse.jgit.api.errors.RefNotAdvertisedException) GeneralSecurityException(java.security.GeneralSecurityException) CanceledException(org.eclipse.jgit.api.errors.CanceledException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) RefNotAdvertisedException(org.eclipse.jgit.api.errors.RefNotAdvertisedException) GraficoModelLoader(org.archicontribs.modelrepository.grafico.GraficoModelLoader) BranchStatus(org.archicontribs.modelrepository.grafico.BranchStatus)

Example 18 with FetchResult

use of org.eclipse.jgit.transport.FetchResult in project egit by eclipse.

the class SimpleConfigureFetchDialog method dryRun.

@Override
protected void dryRun(IProgressMonitor monitor) {
    int timeout = Activator.getDefault().getPreferenceStore().getInt(UIPreferences.REMOTE_CONNECTION_TIMEOUT);
    final FetchOperationUI op = new FetchOperationUI(getRepository(), getConfig(), timeout, true);
    try {
        final FetchResult result = op.execute(monitor);
        getShell().getDisplay().asyncExec(new Runnable() {

            @Override
            public void run() {
                FetchResultDialog dlg;
                dlg = new FetchResultDialog(getShell(), getRepository(), result, op.getSourceString());
                dlg.showConfigureButton(false);
                dlg.open();
            }
        });
    } catch (CoreException e) {
        Activator.handleError(e.getMessage(), e, true);
    }
}
Also used : FetchResult(org.eclipse.jgit.transport.FetchResult) CoreException(org.eclipse.core.runtime.CoreException)

Example 19 with FetchResult

use of org.eclipse.jgit.transport.FetchResult in project gerrit by GerritCodeReview.

the class AbstractDaemonTest method fetchFromBundles.

/**
 * Fetches each bundle into a newly cloned repository, then it applies the bundle, and returns the
 * resulting tree id.
 *
 * <p>Omits NoteDb meta refs.
 */
protected Map<BranchNameKey, ObjectId> fetchFromBundles(BinaryResult bundles) throws Exception {
    assertThat(bundles.getContentType()).isEqualTo("application/x-zip");
    FileSystem fs = Jimfs.newFileSystem();
    Path previewPath = fs.getPath("preview.zip");
    try (OutputStream out = Files.newOutputStream(previewPath)) {
        bundles.writeTo(out);
    }
    Map<BranchNameKey, ObjectId> ret = new HashMap<>();
    try (FileSystem zipFs = FileSystems.newFileSystem(previewPath, (ClassLoader) null);
        DirectoryStream<Path> dirStream = Files.newDirectoryStream(Iterables.getOnlyElement(zipFs.getRootDirectories()))) {
        for (Path p : dirStream) {
            if (!Files.isRegularFile(p)) {
                continue;
            }
            String bundleName = p.getFileName().toString();
            int len = bundleName.length();
            assertThat(bundleName).endsWith(".git");
            String repoName = bundleName.substring(0, len - 4);
            Project.NameKey proj = Project.nameKey(repoName);
            TestRepository<?> localRepo = cloneProject(proj);
            try (InputStream bundleStream = Files.newInputStream(p);
                TransportBundleStream tbs = new TransportBundleStream(localRepo.getRepository(), new URIish(bundleName), bundleStream)) {
                FetchResult fr = tbs.fetch(NullProgressMonitor.INSTANCE, Arrays.asList(new RefSpec("refs/*:refs/preview/*")));
                for (Ref r : fr.getAdvertisedRefs()) {
                    String refName = r.getName();
                    if (RefNames.isNoteDbMetaRef(refName)) {
                        continue;
                    }
                    RevCommit c = localRepo.getRevWalk().parseCommit(r.getObjectId());
                    ret.put(BranchNameKey.create(proj, refName), c.getTree().copy());
                }
            }
        }
    }
    assertThat(ret).isNotEmpty();
    return ret;
}
Also used : Path(java.nio.file.Path) URIish(org.eclipse.jgit.transport.URIish) FetchResult(org.eclipse.jgit.transport.FetchResult) ObjectId(org.eclipse.jgit.lib.ObjectId) HashMap(java.util.HashMap) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) IdString(com.google.gerrit.extensions.restapi.IdString) Project(com.google.gerrit.entities.Project) Ref(org.eclipse.jgit.lib.Ref) RefSpec(org.eclipse.jgit.transport.RefSpec) BranchNameKey(com.google.gerrit.entities.BranchNameKey) FileSystem(java.nio.file.FileSystem) TransportBundleStream(org.eclipse.jgit.transport.TransportBundleStream) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 20 with FetchResult

use of org.eclipse.jgit.transport.FetchResult in project gitblit by gitblit.

the class JGitUtils method fetchRepository.

/**
 * Fetch updates from the remote repository. If refSpecs is unspecifed,
 * remote heads, tags, and notes are retrieved.
 *
 * @param credentialsProvider
 * @param repository
 * @param refSpecs
 * @return FetchResult
 * @throws Exception
 */
public static FetchResult fetchRepository(CredentialsProvider credentialsProvider, Repository repository, RefSpec... refSpecs) throws Exception {
    Git git = new Git(repository);
    FetchCommand fetch = git.fetch();
    List<RefSpec> specs = new ArrayList<RefSpec>();
    if (refSpecs == null || refSpecs.length == 0) {
        specs.add(new RefSpec("+refs/heads/*:refs/remotes/origin/*"));
        specs.add(new RefSpec("+refs/tags/*:refs/tags/*"));
        specs.add(new RefSpec("+refs/notes/*:refs/notes/*"));
    } else {
        specs.addAll(Arrays.asList(refSpecs));
    }
    if (credentialsProvider != null) {
        fetch.setCredentialsProvider(credentialsProvider);
    }
    fetch.setRefSpecs(specs);
    FetchResult fetchRes = fetch.call();
    return fetchRes;
}
Also used : Git(org.eclipse.jgit.api.Git) RefSpec(org.eclipse.jgit.transport.RefSpec) FetchResult(org.eclipse.jgit.transport.FetchResult) FetchCommand(org.eclipse.jgit.api.FetchCommand) ArrayList(java.util.ArrayList)

Aggregations

FetchResult (org.eclipse.jgit.transport.FetchResult)22 Ref (org.eclipse.jgit.lib.Ref)8 FetchCommand (org.eclipse.jgit.api.FetchCommand)7 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)6 Git (org.eclipse.jgit.api.Git)6 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)6 StoredConfig (org.eclipse.jgit.lib.StoredConfig)6 RefSpec (org.eclipse.jgit.transport.RefSpec)6 ObjectId (org.eclipse.jgit.lib.ObjectId)5 Repository (org.eclipse.jgit.lib.Repository)5 CheckoutCommand (org.eclipse.jgit.api.CheckoutCommand)3 NoRemoteRepositoryException (org.eclipse.jgit.errors.NoRemoteRepositoryException)3 Test (org.junit.Test)3 GeneralSecurityException (java.security.GeneralSecurityException)2 CoreException (org.eclipse.core.runtime.CoreException)2 CloneCommand (org.eclipse.jgit.api.CloneCommand)2 ListBranchCommand (org.eclipse.jgit.api.ListBranchCommand)2 MergeCommand (org.eclipse.jgit.api.MergeCommand)2 Status (org.eclipse.jgit.api.Status)2