Example usage for org.eclipse.jgit.lib Repository getConfig

List of usage examples for org.eclipse.jgit.lib Repository getConfig

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Repository getConfig.

Prototype

@NonNull
public abstract StoredConfig getConfig();

Source Link

Document

Get the configuration of this repository.

Usage

From source file:ch.uzh.ifi.seal.permo.history.git.core.model.jgit.util.JGitUtil.java

License:Apache License

/**
 * Returns a list of all remote references (e.g. 'refs/remotes/origin') of the given repository.
 * /*from  w w  w .  j a  v  a 2s.co m*/
 * @param repository
 *          the repository
 * @return the list of all remote references of the given repository.
 */
public static Set<String> getRemotes(final Repository repository) {
    final Config storedConfig = repository.getConfig();
    return storedConfig.getSubsections(REMOTE);
}

From source file:com.cloudbees.eclipse.dev.scm.egit.ForgeEGitSync.java

License:Open Source License

private boolean openRemoteFile_(final String repo, final ChangeSetPathItem item,
        final IProgressMonitor monitor) {
    try {//from  www  .j a  v  a 2 s .c o  m
        // TODO extract repo search into separate method
        RepositoryCache repositoryCache = org.eclipse.egit.core.Activator.getDefault().getRepositoryCache();
        Repository repository = null;
        URIish proposal = new URIish(repo);
        List<String> reps = Activator.getDefault().getRepositoryUtil().getConfiguredRepositories();
        all: for (String rep : reps) {
            try {

                Repository fr = repositoryCache.lookupRepository(new File(rep));
                List<RemoteConfig> allRemotes = RemoteConfig.getAllRemoteConfigs(fr.getConfig());
                for (RemoteConfig remo : allRemotes) {
                    List<URIish> uris = remo.getURIs();
                    for (URIish uri : uris) {
                        CloudBeesDevCorePlugin.getDefault().getLogger()
                                .info("Checking URI: " + uri + " - " + proposal.equals(uri));
                        if (proposal.equals(uri)) {
                            repository = fr;
                            break all;
                        }
                    }
                }
            } catch (Exception e) {
                CloudBeesDevCorePlugin.getDefault().getLogger().error(e);
            }
        }

        CloudBeesDevCorePlugin.getDefault().getLogger().info("Repo: " + repository);

        if (repository == null) {
            throw new CloudBeesException("Failed to find mapped repository for " + repo);
        }

        ObjectId commitId = ObjectId.fromString(item.parent.id);
        RevWalk rw = new RevWalk(repository);
        RevCommit rc = rw.parseCommit(commitId);
        final IFileRevision rev = CompareUtils.getFileRevision(item.path, rc, repository, null);

        final IEditorPart[] editor = new IEditorPart[1];

        PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
            @Override
            public void run() {
                IWorkbenchPage activePage = CloudBeesUIPlugin.getActiveWindow().getActivePage();
                try {
                    editor[0] = Utils.openEditor(activePage, rev, monitor);
                } catch (CoreException e) {
                    e.printStackTrace(); // TODO
                }
            }
        });

        return editor[0] != null;
    } catch (Exception e) {
        CloudBeesDevCorePlugin.getDefault().getLogger().error(e); // TODO handle better?
        return false;
    }
}

From source file:com.diffplug.gradle.spotless.GitAttributesLineEndingPolicy.java

License:Apache License

public static GitAttributesLineEndingPolicy create(File rootFolder) {
    return Errors.rethrow().get(() -> {
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        builder.findGitDir(rootFolder);//from  w w w.  j  a va2 s .  c om
        if (builder.getGitDir() != null) {
            // we found a repository, so we can grab all the values we need from it
            Repository repo = builder.build();
            AttributesNodeProvider nodeProvider = repo.createAttributesNodeProvider();
            Function<AttributesNode, List<AttributesRule>> getRules = node -> node == null
                    ? Collections.emptyList()
                    : node.getRules();
            return new GitAttributesLineEndingPolicy(repo.getConfig(),
                    getRules.apply(nodeProvider.getInfoAttributesNode()), repo.getWorkTree(),
                    getRules.apply(nodeProvider.getGlobalAttributesNode()));
        } else {
            // there's no repo, so it takes some work to grab the system-wide values
            Config systemConfig = SystemReader.getInstance().openSystemConfig(null, FS.DETECTED);
            Config userConfig = SystemReader.getInstance().openUserConfig(systemConfig, FS.DETECTED);
            if (userConfig == null) {
                userConfig = new Config();
            }

            List<AttributesRule> globalRules = Collections.emptyList();
            // copy-pasted from org.eclipse.jgit.lib.CoreConfig
            String globalAttributesPath = userConfig.getString(ConfigConstants.CONFIG_CORE_SECTION, null,
                    ConfigConstants.CONFIG_KEY_ATTRIBUTESFILE);
            // copy-pasted from org.eclipse.jgit.internal.storage.file.GlobalAttributesNode
            if (globalAttributesPath != null) {
                FS fs = FS.detect();
                File attributesFile;
                if (globalAttributesPath.startsWith("~/")) { //$NON-NLS-1$
                    attributesFile = fs.resolve(fs.userHome(), globalAttributesPath.substring(2));
                } else {
                    attributesFile = fs.resolve(null, globalAttributesPath);
                }
                globalRules = parseRules(attributesFile);
            }
            return new GitAttributesLineEndingPolicy(userConfig,
                    // no git info file
                    Collections.emptyList(), null, globalRules);
        }
    });
}

From source file:com.genuitec.eclipse.gerrit.tools.internal.changes.commands.SwitchToChangeBranchCommand.java

License:Open Source License

public void execute(final ExecutionEvent event, final Repository repository, final String branchRef) {
    BranchOperationUI op = BranchOperationUI.checkout(repository, branchRef).doneCallback(new DoneCallback() {

        public void done(CheckoutResult result) {

            if (result.getStatus() == CheckoutResult.Status.OK) {
                IPath path = new Path(branchRef);
                String stableBranch = path.segment(3);
                if (stableBranch.equals("features") && path.segmentCount() > 6) { //$NON-NLS-1$
                    stableBranch = path.removeFirstSegments(3).uptoSegment(3).toString();
                }/*w  ww  . j a v a2  s .  co m*/
                String newUpstreamRef = branchRef + ":refs/for/" + stableBranch; //$NON-NLS-1$
                repository.getConfig().setString("remote", "origin", "push", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                        newUpstreamRef);
                repository.getConfig().setBoolean("branch", //$NON-NLS-1$
                        path.removeFirstSegments(2).removeTrailingSeparator().makeRelative().toString(),
                        "rebase", true); //$NON-NLS-1$
                try {
                    repository.getConfig().save();
                } catch (IOException e) {
                    RepositoryUtils.handleException(e);
                }
            }
        }
    });
    op.start();
}

From source file:com.genuitec.eclipse.gerrit.tools.internal.fbranches.BranchingUtils.java

License:Open Source License

public static PushOperationSpecification setupPush(Repository repository, String refSpec)
        throws IOException, URISyntaxException {
    PushOperationSpecification spec = new PushOperationSpecification();
    Collection<RemoteRefUpdate> updates = Transport.findRemoteRefUpdatesFor(repository,
            Collections.singletonList(new RefSpec(refSpec)), null);

    RemoteConfig config = new RemoteConfig(repository.getConfig(), "origin");

    for (URIish uri : config.getPushURIs()) {
        spec.addURIRefUpdates(uri, updates);
        break;/*from  w  w w.  j av  a2s .  c  o m*/
    }
    if (spec.getURIsNumber() == 0) {
        for (URIish uri : config.getURIs()) {
            spec.addURIRefUpdates(uri, updates);
            break;
        }
    }
    if (spec.getURIsNumber() == 0) {
        throw new RuntimeException("Cannot find URI for push");
    }
    return spec;
}

From source file:com.genuitec.eclipse.gerrit.tools.internal.fbranches.commands.SwitchToBranchCommand.java

License:Open Source License

protected void execute(ExecutionEvent event, final Repository repository, final String branchRef)
        throws ExecutionException {
    //check if local branch exists
    final String branchName = branchRef.substring("refs/heads/".length()); //$NON-NLS-1$
    try {/*www  .ja va2s  . c o m*/
        if (repository.getRef(branchRef) == null) {
            //create local branch
            String remoteBranchRef = "refs/remotes/origin/" + branchName; //$NON-NLS-1$
            Ref remoteRef = repository.getRef(remoteBranchRef);
            if (remoteRef == null) {
                throw new RuntimeException(
                        MessageFormat.format("Remote branch {0} doesn't exist", remoteBranchRef));
            }
            new Git(repository).branchCreate().setName(branchName).setStartPoint(remoteBranchRef)
                    .setUpstreamMode(SetupUpstreamMode.TRACK).call();
            repository.getConfig().setBoolean("branch", branchName, "rebase", true); //$NON-NLS-1$//$NON-NLS-2$
        }
    } catch (Exception e1) {
        RepositoryUtils.handleException(e1);
        return;
    }

    BranchOperationUI op = BranchOperationUI.checkout(repository, branchRef).doneCallback(new DoneCallback() {

        public void done(CheckoutResult result) {

            if (result.getStatus() == CheckoutResult.Status.OK) {
                String newUpstreamRef = branchRef + ":refs/for/" + branchName; //$NON-NLS-1$
                repository.getConfig().setString("remote", "origin", "push", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                        newUpstreamRef);
                //ensure in rebase mode
                repository.getConfig().setBoolean("branch", branchName, "rebase", true); //$NON-NLS-1$//$NON-NLS-2$
                try {
                    repository.getConfig().save();
                } catch (IOException e) {
                    RepositoryUtils.handleException(e);
                }
            }
        }
    });
    op.start();
}

From source file:com.genuitec.eclipse.gerrit.tools.internal.gps.model.GpsGitRepositoriesConfig.java

License:Open Source License

private String getRepoUrl(Repository repository) {
    try {//from   ww  w .ja v  a  2s  . c o m
        RemoteConfig config = new RemoteConfig(repository.getConfig(), "origin"); //$NON-NLS-1$
        for (URIish uri : config.getURIs()) {
            if (uri.getUser() != null) {
                return uri.setUser("user-name").toASCIIString(); //$NON-NLS-1$
            }
            return uri.toASCIIString();
        }
    } catch (Exception e) {
        GerritToolsPlugin.getDefault().log(e);
    }
    return null;
}

From source file:com.genuitec.eclipse.gerrit.tools.internal.gps.model.GpsGitRepositoriesConfig.java

License:Open Source License

public void performConfiguration(Map<String, Object> options, SubMonitor monitor) throws CoreException {
    monitor.beginTask("", repo2branch.size() * 2);
    for (Entry<String, RepoSetup> entry : repo2branch.entrySet()) {
        if (monitor.isCanceled())
            return;

        RepoSetup repo = entry.getValue();

        String repositoryName = repo.name;
        String repositoryBranch = repo.branch;
        boolean localBranch = repositoryBranch.startsWith("refs/heads/"); //$NON-NLS-1$
        String branchName = null;
        if (localBranch) {
            branchName = repositoryBranch.substring(11);
        }//ww w  .ja  v a  2  s  .c o  m
        switch (repo.state) {
        case LOCATED:
            org.eclipse.egit.ui.Activator.getDefault().getRepositoryUtil()
                    .addConfiguredRepository(new File(repo.location, ".git")); //$NON-NLS-1$
            break;
        case CLONE:
            monitor.setTaskName("Cloning repository " + repositoryName);
            monitor.subTask("");
            try {
                URIish uri = new URIish(repo.url);
                if (repo.userName != null) {
                    uri = uri.setUser(repo.userName);
                } else {
                    uri = uri.setUser(null);
                }
                CloneOperation co = new CloneOperation(uri, true, null, repo.location, repositoryBranch,
                        "origin", 5000); //$NON-NLS-1$
                co.setCredentialsProvider(new EGitCredentialsProvider());
                co.setCloneSubmodules(true);
                co.run(new SubProgressMonitor(monitor, 0, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK));

                org.eclipse.egit.ui.Activator.getDefault().getRepositoryUtil()
                        .addConfiguredRepository(co.getGitDir());

                break;
            } catch (Throwable e) {
                if (e instanceof InvocationTargetException) {
                    e = e.getCause();
                }
                throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID,
                        (e instanceof InterruptedException) ? "Operation cancelled" : e.getMessage(), e));
            }
        default:
        }

        monitor.setTaskName("Preparing repository " + repositoryName);

        Repository repository = RepositoryUtils.getRepositoryForName(repositoryName);
        if (repository == null) {
            throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID,
                    MessageFormat.format(
                            "Cannot continue. A required git repository named {0} is not configured.",
                            repositoryName)));
        }

        monitor.subTask(MessageFormat.format("Checking out branch \"{0}\" of git repository \"{1}\"",
                repositoryBranch, repositoryName));

        if (repositoryBranch != null && repositoryBranch.length() > 0) {
            //checkout the branch
            boolean newBranch = false;
            try {
                Ref ref = repository.getRef(repositoryBranch);
                if (localBranch && ref == null) {
                    String originBranch = "refs/remotes/origin/" + branchName; //$NON-NLS-1$
                    ref = repository.getRef(originBranch);
                    if (ref == null) {
                        try {
                            new Git(repository).fetch().setRemote("origin").call(); //$NON-NLS-1$
                        } catch (Exception e) {
                            throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID,
                                    MessageFormat.format(
                                            "Cannot fetch from remote 'origin' of repository \"{0}\":\n{1}",
                                            repositoryName, e.getMessage(), e)));
                        }
                    }
                    ref = repository.getRef(originBranch);
                    if (ref == null) {
                        throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID,
                                MessageFormat.format("Cannot find branch \"{1}\" in repository \"{0}\".",
                                        repositoryName, originBranch)));
                    }
                    //we need to create the local branch based on remote branch
                    new Git(repository).branchCreate().setName(branchName).setStartPoint(originBranch)
                            .setUpstreamMode(SetupUpstreamMode.TRACK).call();
                    newBranch = true;
                }
                if (monitor.isCanceled())
                    return;

                try {
                    new Git(repository).checkout().setName(repositoryBranch).call();
                } catch (Exception e) {
                    if (options.containsKey(PROP_FORCE_CHECKOUT)
                            && (Boolean) options.get(PROP_FORCE_CHECKOUT)) {
                        //try to reset
                        new Git(repository).reset().setMode(ResetType.HARD).call();

                        //and then checkout again
                        new Git(repository).checkout().setName(repositoryBranch).call();
                    } else {
                        throw e;
                    }
                }

                int fileCount = repository.getDirectory().getParentFile().list().length;
                if (fileCount == 1) {
                    //we need to hard reset the repository - there are no files in it
                    new Git(repository).reset().setMode(ResetType.HARD).call();
                }

            } catch (Exception e) {
                throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID,
                        MessageFormat.format("Cannot checkout branch \"{1}\" of repository \"{0}\":\n{2}",
                                repositoryName, repositoryBranch, e.getMessage(), e)));
            }
            if (monitor.isCanceled())
                return;

            if (localBranch) {
                monitor.subTask(MessageFormat.format("Configuring branch \"{0}\" of git repository \"{1}\"",
                        repositoryBranch, repositoryName));
                try {
                    StoredConfig config = repository.getConfig();

                    if (options.get(PROP_CONFIGURE_PUSH_TO_UPSTREAM) != null
                            && (Boolean) options.get(PROP_CONFIGURE_PUSH_TO_UPSTREAM)) {
                        //configure push to upstream
                        config.setString("remote", "origin", "push", //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                                repositoryBranch + ":refs/for/" + branchName); //$NON-NLS-1$
                    }
                    if (newBranch || (options.get(PROP_RECONFIGURE_BRANCH) != null
                            && (Boolean) options.get(PROP_RECONFIGURE_BRANCH))) {
                        config.setString("branch", branchName, "remote", "origin"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                        config.setString("branch", branchName, "merge", repositoryBranch); //$NON-NLS-1$ //$NON-NLS-2$
                        config.setString("branch", branchName, "rebase", "true"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                    }
                    config.save();
                } catch (Exception e) {
                    throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID,
                            MessageFormat.format("Cannot configure branch \"{1}\" of repository \"{0}\":\n{2}",
                                    repositoryName, repositoryBranch, e.getMessage(), e)));
                }
            }
            if (monitor.isCanceled())
                return;

            if (options.containsKey(PROP_AUTO_PULL) && (Boolean) options.get(PROP_AUTO_PULL)) {
                monitor.subTask(MessageFormat.format("Pulling branch \"{0}\" from git repository \"{1}\"",
                        repositoryBranch, repositoryName));

                try {
                    new Git(repository).pull().call();
                } catch (Exception e) {
                    throw new CoreException(new Status(IStatus.ERROR, GerritToolsPlugin.PLUGIN_ID,
                            MessageFormat.format("Cannot pull branch \"{1}\" of repository \"{0}\":\n{2}",
                                    repositoryName, repositoryBranch, e.getMessage(), e)));
                }
            }
        }

        monitor.worked(1);
    }

}

From source file:com.genuitec.eclipse.gerrit.tools.utils.GerritUtils.java

License:Open Source License

public static String getGerritProjectName(Repository repository) {
    try {//from w  ww  .jav  a  2 s.c o  m
        RemoteConfig config = new RemoteConfig(repository.getConfig(), "origin"); //$NON-NLS-1$

        List<URIish> urls = new ArrayList<URIish>(config.getPushURIs());
        urls.addAll(config.getURIs());

        for (URIish uri : urls) {
            if (uri.getPort() == 29418) { //Gerrit refspec
                String path = uri.getPath();
                while (path.startsWith("/")) { //$NON-NLS-1$
                    path = path.substring(1);
                }
                return path;
            }
            break;
        }
    } catch (Exception e) {
        GerritToolsPlugin.getDefault().log(e);
    }
    return null;
}

From source file:com.genuitec.eclipse.gerrit.tools.utils.GerritUtils.java

License:Open Source License

public static String getGerritURL(Repository repository) {
    String best = null;/*from   w ww .  j  ava  2 s.c  o  m*/
    try {
        RemoteConfig config = new RemoteConfig(repository.getConfig(), "origin"); //$NON-NLS-1$

        List<URIish> urls = new ArrayList<URIish>(config.getPushURIs());
        urls.addAll(config.getURIs());

        for (URIish uri : urls) {
            best = "https://" + uri.getHost(); //$NON-NLS-1$
            if (uri.getPort() == 29418) { //Gerrit refspec
                return best;
            }
            break;
        }
    } catch (Exception e) {
        GerritToolsPlugin.getDefault().log(e);
    }
    return best;
}