Search in sources :

Example 1 with CanceledException

use of org.eclipse.jgit.api.errors.CanceledException in project omegat by omegat-org.

the class GITExternalGpgSigner method signWithGpg.

private byte[] signWithGpg(byte[] data, String keySpec, String gpgProgram) throws IOException, CanceledException {
    // Sign an object with an external GPG executable. GPG handles
    // passphrase entry, including gpg-agent and native keychain
    // integration.
    String program = gpgProgram;
    if (StringUtils.isEmptyOrNull(program)) {
        program = FROM_PATH.getGpg();
        if (StringUtils.isEmptyOrNull(program)) {
            throw new IOException(OStrings.getString(ExternalGpgSigner_gpgNotFound));
        }
    }
    ProcessBuilder process = new ProcessBuilder();
    process.command(program, // $NON-NLS-1$
    "-bsau", keySpec, // $NON-NLS-1$
    "--batch", // $NON-NLS-1$
    "--no-tty", // $NON-NLS-1$
    "--status-fd", // $NON-NLS-1$
    "2", // $NON-NLS-1$
    "--output", // $NON-NLS-1$
    "-");
    gpgEnvironment(process);
    try (ByteArrayInputStream dataIn = new ByteArrayInputStream(data)) {
        class Holder {

            byte[] rawData;
        }
        Holder result = new Holder();
        runProcess(process, dataIn, b -> {
            // Sanity check: do we have a signature?
            GpgSignatureVerifierFactory factory = GpgSignatureVerifierFactory.getDefault();
            boolean isValid;
            if (factory == null) {
                byte[] fromGpg = b.toByteArray(SIGNATURE_START.length);
                isValid = Arrays.equals(fromGpg, SIGNATURE_START);
                if (isValid) {
                    result.rawData = b.toByteArray();
                }
            } else {
                byte[] fromGpg = b.toByteArray();
                GpgSignatureVerifier verifier = factory.getVerifier();
                try {
                    GpgSignatureVerifier.SignatureVerification verification = verifier.verify(data, fromGpg);
                    isValid = verification != null && verification.getVerified();
                    if (isValid) {
                        result.rawData = fromGpg;
                    }
                } catch (JGitInternalException e) {
                    throw new IOException(e.getLocalizedMessage(), e);
                } finally {
                    verifier.clear();
                }
            }
            if (!isValid) {
                throw new IOException(MessageFormat.format(OStrings.getString(ExternalGpgSigner_noSignature), toString(b)));
            }
        }, e -> {
            // https://github.com/gpg/gnupg/blob/master/doc/DETAILS
            try (BufferedReader r = new BufferedReader(new InputStreamReader(e.openInputStream(), StandardCharsets.UTF_8))) {
                String line;
                boolean pinentry = false;
                while ((line = r.readLine()) != null) {
                    if (!pinentry && line.startsWith("[GNUPG:] PINENTRY_LAUNCHED")) {
                        pinentry = true;
                    } else if (pinentry) {
                        if (line.startsWith("[GNUPG:] FAILURE sign")) {
                            throw new CanceledException(OStrings.getString(ExternalGpgSigner_signingCanceled));
                        }
                        if (line.startsWith("[GNUPG:]")) {
                            pinentry = false;
                        }
                    }
                }
            } catch (IOException ex) {
            // Swallow it here; runProcess will raise one anyway.
            }
        });
        return result.rawData;
    }
}
Also used : CanceledException(org.eclipse.jgit.api.errors.CanceledException) GpgSignatureVerifierFactory(org.eclipse.jgit.lib.GpgSignatureVerifierFactory) GpgSignatureVerifier(org.eclipse.jgit.lib.GpgSignatureVerifier) InputStreamReader(java.io.InputStreamReader) IOException(java.io.IOException) ByteArrayInputStream(java.io.ByteArrayInputStream) BufferedReader(java.io.BufferedReader) JGitInternalException(org.eclipse.jgit.api.errors.JGitInternalException)

Example 2 with CanceledException

use of org.eclipse.jgit.api.errors.CanceledException in project archi-modelrepository-plugin by archi-contribs.

the class MergeConflictHandler method extractModel.

/**
 * Extract a model from either our latest commit or their latest online commit
 * ref = "refs/head/master" or "origin/master"
 * @throws CanceledException
 */
private IArchimateModel extractModel(String ref) throws IOException, CanceledException {
    // $NON-NLS-1$ //$NON-NLS-2$
    File tmpFolder = new File(System.getProperty("java.io.tmpdir"), "org.archicontribs.modelrepository.tmp");
    FileUtils.deleteFolder(tmpFolder);
    tmpFolder.mkdirs();
    try (Repository repository = Git.open(fArchiRepo.getLocalRepositoryFolder()).getRepository()) {
        RevCommit commit = null;
        // A RevWalk walks over commits based on some filtering that is defined
        try (RevWalk revWalk = new RevWalk(repository)) {
            // We are interested in the origin master branch
            ObjectId objectID = repository.resolve(ref);
            if (objectID != null) {
                commit = revWalk.parseCommit(objectID);
            }
            revWalk.dispose();
        }
        if (commit == null) {
            throw new IOException(Messages.MergeConflictHandler_1);
        }
        // Walk the tree and get the contents of the commit
        try (TreeWalk treeWalk = new TreeWalk(repository)) {
            treeWalk.addTree(commit.getTree());
            treeWalk.setRecursive(true);
            while (treeWalk.next()) {
                if (fProgressMonitor != null && fProgressMonitor.isCanceled()) {
                    throw new CanceledException(Messages.MergeConflictHandler_2);
                }
                ObjectId objectId = treeWalk.getObjectId(0);
                ObjectLoader loader = repository.open(objectId);
                File file = new File(tmpFolder, treeWalk.getPathString());
                file.getParentFile().mkdirs();
                try (FileOutputStream out = new FileOutputStream(file)) {
                    loader.copyTo(out);
                }
            }
        }
    }
    // Load it
    GraficoModelImporter importer = new GraficoModelImporter(tmpFolder);
    IArchimateModel model = importer.importAsModel();
    FileUtils.deleteFolder(tmpFolder);
    return model;
}
Also used : CanceledException(org.eclipse.jgit.api.errors.CanceledException) IArchiRepository(org.archicontribs.modelrepository.grafico.IArchiRepository) Repository(org.eclipse.jgit.lib.Repository) ObjectId(org.eclipse.jgit.lib.ObjectId) FileOutputStream(java.io.FileOutputStream) ObjectLoader(org.eclipse.jgit.lib.ObjectLoader) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) File(java.io.File) TreeWalk(org.eclipse.jgit.treewalk.TreeWalk) GraficoModelImporter(org.archicontribs.modelrepository.grafico.GraficoModelImporter) IArchimateModel(com.archimatetool.model.IArchimateModel) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 3 with CanceledException

use of org.eclipse.jgit.api.errors.CanceledException in project archi-modelrepository-plugin by archi-contribs.

the class MergeBranchAction method merge.

private int merge(BranchInfo currentBranch, BranchInfo branchToMerge, ProgressMonitorDialog pmDialog) throws GitAPIException, IOException {
    pmDialog.getProgressMonitor().subTask(Messages.MergeBranchAction_13);
    // update dialog
    Display.getCurrent().readAndDispatch();
    try (Git git = Git.open(getRepository().getLocalRepositoryFolder())) {
        ObjectId mergeBase = git.getRepository().resolve(branchToMerge.getShortName());
        String mergeMessage = NLS.bind(Messages.MergeBranchAction_2, branchToMerge.getShortName(), currentBranch.getShortName());
        MergeResult mergeResult = git.merge().include(mergeBase).setCommit(true).setFastForward(FastForwardMode.FF).setStrategy(MergeStrategy.RECURSIVE).setSquash(false).setMessage(mergeMessage).call();
        MergeStatus status = mergeResult.getMergeStatus();
        // Conflict
        if (status == MergeStatus.CONFLICTING) {
            // Try to handle the merge conflict
            MergeConflictHandler handler = new MergeConflictHandler(mergeResult, branchToMerge.getShortName(), getRepository(), fWindow.getShell());
            try {
                handler.init(pmDialog.getProgressMonitor());
            } catch (IOException | GitAPIException ex) {
                // Clean up
                handler.resetToLocalState();
                if (ex instanceof CanceledException) {
                    return MERGE_STATUS_MERGE_CANCEL;
                }
                throw ex;
            }
            String dialogMessage = NLS.bind(Messages.MergeBranchAction_10, branchToMerge.getShortName(), currentBranch.getShortName());
            pmDialog.getShell().setVisible(false);
            boolean result = handler.openConflictsDialog(dialogMessage);
            pmDialog.getShell().setVisible(true);
            if (result) {
                handler.merge();
            } else // User cancelled - so we reset
            {
                handler.resetToLocalState();
                return MERGE_STATUS_MERGE_CANCEL;
            }
        }
        // Reload the model from the Grafico XML files
        GraficoModelLoader loader = new GraficoModelLoader(getRepository());
        loader.loadModel();
        // Do a commit if needed
        if (getRepository().hasChangesToCommit()) {
            mergeMessage = NLS.bind(Messages.MergeBranchAction_3, branchToMerge.getShortName(), currentBranch.getShortName());
            // Did we restore any missing objects?
            String restoredObjects = loader.getRestoredObjectsAsString();
            // Add to commit message
            if (restoredObjects != null) {
                // $NON-NLS-1$ //$NON-NLS-2$
                mergeMessage += "\n\n" + Messages.RefreshModelAction_3 + "\n" + restoredObjects;
            }
            // IMPORTANT!!! "amend" has to be false after a merge conflict or else the commit will be orphaned
            getRepository().commitChanges(mergeMessage, false);
        }
    }
    return MERGE_STATUS_OK;
}
Also used : GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) CanceledException(org.eclipse.jgit.api.errors.CanceledException) Git(org.eclipse.jgit.api.Git) GraficoModelLoader(org.archicontribs.modelrepository.grafico.GraficoModelLoader) ObjectId(org.eclipse.jgit.lib.ObjectId) MergeStatus(org.eclipse.jgit.api.MergeResult.MergeStatus) MergeResult(org.eclipse.jgit.api.MergeResult) MergeConflictHandler(org.archicontribs.modelrepository.merge.MergeConflictHandler) IOException(java.io.IOException)

Example 4 with CanceledException

use of org.eclipse.jgit.api.errors.CanceledException 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)

Aggregations

IOException (java.io.IOException)4 CanceledException (org.eclipse.jgit.api.errors.CanceledException)4 GraficoModelLoader (org.archicontribs.modelrepository.grafico.GraficoModelLoader)2 MergeConflictHandler (org.archicontribs.modelrepository.merge.MergeConflictHandler)2 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)2 ObjectId (org.eclipse.jgit.lib.ObjectId)2 IArchimateModel (com.archimatetool.model.IArchimateModel)1 BufferedReader (java.io.BufferedReader)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 File (java.io.File)1 FileOutputStream (java.io.FileOutputStream)1 InputStreamReader (java.io.InputStreamReader)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 GeneralSecurityException (java.security.GeneralSecurityException)1 BranchStatus (org.archicontribs.modelrepository.grafico.BranchStatus)1 GraficoModelImporter (org.archicontribs.modelrepository.grafico.GraficoModelImporter)1 IArchiRepository (org.archicontribs.modelrepository.grafico.IArchiRepository)1 Git (org.eclipse.jgit.api.Git)1 MergeResult (org.eclipse.jgit.api.MergeResult)1 MergeStatus (org.eclipse.jgit.api.MergeResult.MergeStatus)1