Example usage for org.eclipse.jgit.lib StoredConfig save

List of usage examples for org.eclipse.jgit.lib StoredConfig save

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib StoredConfig save.

Prototype

public abstract void save() throws IOException;

Source Link

Document

Save the configuration to the persistent store.

Usage

From source file:org.eclipse.recommenders.snipmatch.GitSnippetRepository.java

License:Open Source License

private void configureGitBranch(String remoteBranch) throws IOException {
    Git git = Git.open(gitFile);//from w  w w  .  j a  v  a  2  s  . com
    StoredConfig config = git.getRepository().getConfig();
    String pushBranch = "HEAD:" + pushBranchPrefix + "/" + remoteBranch;
    config.setString("remote", "origin", "push", pushBranch);

    config.setString("branch", remoteBranch, "remote", "origin");
    String branch = "refs/heads/" + remoteBranch;
    config.setString("branch", remoteBranch, "merge", branch);
    config.save();
}

From source file:org.flowerplatform.web.git.GitService.java

License:Open Source License

@RemoteInvocation
public boolean deleteRemote(ServiceInvocationContext context, List<PathFragment> path) {
    try {//from w w  w. j a  v a  2  s  . c o  m
        RemoteNode remoteNode = (RemoteNode) GenericTreeStatefulService.getNodeByPathFor(path, null);
        Repository repository = remoteNode.getRepository();
        GenericTreeStatefulService service = GenericTreeStatefulService.getServiceFromPathWithRoot(path);
        NodeInfo remoteNodeInfo = service.getVisibleNodes().get(remoteNode);

        if (repository == null) {
            context.getCommunicationChannel()
                    .appendOrSendCommand(new DisplaySimpleMessageClientCommand(
                            CommonPlugin.getInstance().getMessage("error"),
                            "Cannot find repository for node " + remoteNode,
                            DisplaySimpleMessageClientCommand.ICON_ERROR));
            return false;
        }

        StoredConfig config = repository.getConfig();
        config.unsetSection("remote", remoteNode.getRemote());
        config.save();

        dispatchContentUpdate(remoteNodeInfo.getParent().getNode());

        return true;
    } catch (Exception e) {
        logger.debug(GitPlugin.getInstance().getMessage("git.deleteRemote.error"), e);
        context.getCommunicationChannel().appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        GitPlugin.getInstance().getMessage("git.deleteRemote.error"), e.getMessage(),
                        DisplaySimpleMessageClientCommand.ICON_ERROR));
        return false;
    }
}

From source file:org.flowerplatform.web.git.GitService.java

License:Open Source License

@RemoteInvocation
public boolean configBranch(ServiceInvocationContext context, List<PathFragment> path, GitRef upstreamBranch,
        RemoteConfig remote, boolean rebase) {
    try {/* www.ja v  a  2 s  .  c  om*/
        RefNode node = (RefNode) GenericTreeStatefulService.getNodeByPathFor(path, null);
        Repository repository = node.getRepository();
        StoredConfig config = repository.getConfig();

        Ref ref;
        if (node instanceof Ref) {
            ref = node.getRef();
        } else {
            // get remote branch
            String dst = Constants.R_REMOTES + remote.getName();
            String remoteRefName = dst + "/" + upstreamBranch.getShortName();
            ref = repository.getRef(remoteRefName);
            if (ref == null) { // doesn't exist, fetch it
                RefSpec refSpec = new RefSpec();
                refSpec = refSpec.setForceUpdate(true);
                refSpec = refSpec.setSourceDestination(upstreamBranch.getName(), remoteRefName);

                new Git(repository).fetch().setRemote(new URIish(remote.getUri()).toPrivateString())
                        .setRefSpecs(refSpec).call();

                ref = repository.getRef(remoteRefName);
            }
        }

        String branchName = node.getRef().getName().substring(Constants.R_HEADS.length());
        if (upstreamBranch.getName().length() > 0) {
            config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
                    ConfigConstants.CONFIG_KEY_MERGE, upstreamBranch.getName());
        } else {
            config.unset(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_MERGE);
        }
        if (remote.getName().length() > 0) {
            config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
                    ConfigConstants.CONFIG_KEY_REMOTE, remote.getName());
        } else {
            config.unset(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_REMOTE);
        }
        if (rebase) {
            config.setBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, branchName,
                    ConfigConstants.CONFIG_KEY_REBASE, true);
        } else {
            config.unset(ConfigConstants.CONFIG_BRANCH_SECTION, branchName, ConfigConstants.CONFIG_KEY_REBASE);
        }

        config.save();

        return true;
    } catch (Exception e) {
        logger.debug(CommonPlugin.getInstance().getMessage("error"), path, e);
        context.getCommunicationChannel().appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        e.getMessage(), DisplaySimpleMessageClientCommand.ICON_ERROR));
        return false;
    }
}

From source file:org.flowerplatform.web.git.GitUtils.java

License:Open Source License

/**
 * This method must be used to set user configuration before running
 * some GIT commands that uses it.//w w w .  j a  v a2s  .c o  m
 * 
 * <p>
 * A lock/unlock on repository is done before/after the command is executed
 * because the configuration modifies the same file and this will not be
 * thread safe any more.
 */
public Object runGitCommandInUserRepoConfig(Repository repo, GitCommand<?> command) throws Exception {
    namedLockPool.lock(repo.getDirectory().getPath());

    try {
        StoredConfig c = repo.getConfig();
        c.load();
        User user = (User) CommunicationPlugin.tlCurrentPrincipal.get().getUser();

        c.setString(ConfigConstants.CONFIG_USER_SECTION, null, ConfigConstants.CONFIG_KEY_NAME, user.getName());
        c.setString(ConfigConstants.CONFIG_USER_SECTION, null, ConfigConstants.CONFIG_KEY_EMAIL,
                user.getEmail());

        c.save();

        return command.call();
    } catch (Exception e) {
        throw e;
    } finally {
        namedLockPool.unlock(repo.getDirectory().getPath());
    }
}

From source file:org.flowerplatform.web.git.operation.CheckoutOperation.java

License:Open Source License

public boolean execute() {
    ProgressMonitor monitor = ProgressMonitor
            .create(GitPlugin.getInstance().getMessage("git.checkout.monitor.title"), channel);

    try {/*from  w w w .ja v a  2s  .c om*/
        monitor.beginTask(
                GitPlugin.getInstance().getMessage("git.checkout.monitor.message", new Object[] { name }), 4);
        monitor.setTaskName("Getting remote branch...");
        Git git = new Git(repository);
        Ref ref;
        if (node instanceof Ref) {
            ref = (Ref) node;
        } else {
            // get remote branch
            String dst = Constants.R_REMOTES + remote.getName();
            String remoteRefName = dst + "/" + upstreamBranch.getShortName();
            ref = repository.getRef(remoteRefName);
            if (ref == null) { // doesn't exist, fetch it
                RefSpec refSpec = new RefSpec();
                refSpec = refSpec.setForceUpdate(true);
                refSpec = refSpec.setSourceDestination(upstreamBranch.getName(), remoteRefName);

                git.fetch().setRemote(new URIish(remote.getUri()).toPrivateString()).setRefSpecs(refSpec)
                        .call();

                ref = repository.getRef(remoteRefName);
            }
        }
        monitor.worked(1);
        monitor.setTaskName("Creating local branch...");

        // create local branch
        git.branchCreate().setName(name).setStartPoint(ref.getName())
                .setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM).call();

        if (!(node instanceof Ref)) {
            // save upstream configuration
            StoredConfig config = repository.getConfig();

            config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, name, ConfigConstants.CONFIG_KEY_MERGE,
                    upstreamBranch.getName());

            config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, name, ConfigConstants.CONFIG_KEY_REMOTE,
                    remote.getName());

            if (rebase) {
                config.setBoolean(ConfigConstants.CONFIG_BRANCH_SECTION, name,
                        ConfigConstants.CONFIG_KEY_REBASE, true);
            } else {
                config.unset(ConfigConstants.CONFIG_BRANCH_SECTION, name, ConfigConstants.CONFIG_KEY_REBASE);
            }
            config.save();
        }
        monitor.worked(1);
        monitor.setTaskName("Creating working directory");

        // create working directory for local branch
        File mainRepoFile = repository.getDirectory().getParentFile();
        File wdirFile = new File(mainRepoFile.getParentFile(), GitUtils.WORKING_DIRECTORY_PREFIX + name);
        if (wdirFile.exists()) {
            GitPlugin.getInstance().getUtils().delete(wdirFile);
        }
        GitPlugin.getInstance().getUtils().run_git_workdir_cmd(mainRepoFile.getAbsolutePath(),
                wdirFile.getAbsolutePath());
        monitor.worked(1);
        monitor.setTaskName("Checkout branch");

        // checkout local branch
        Repository wdirRepo = GitPlugin.getInstance().getUtils().getRepository(wdirFile);
        git = new Git(wdirRepo);

        CheckoutCommand cc = git.checkout().setName(name).setForce(true);
        cc.call();

        // show checkout result
        if (cc.getResult().getStatus() == CheckoutResult.Status.CONFLICTS)
            channel.appendOrSendCommand(new DisplaySimpleMessageClientCommand(
                    GitPlugin.getInstance().getMessage("git.checkout.checkoutConflicts.title"),
                    GitPlugin.getInstance().getMessage("git.checkout.checkoutConflicts.message"),
                    cc.getResult().getConflictList().toString(),
                    DisplaySimpleMessageClientCommand.ICON_INFORMATION));

        else if (cc.getResult().getStatus() == CheckoutResult.Status.NONDELETED) {
            // double-check if the files are still there
            boolean show = false;
            List<String> pathList = cc.getResult().getUndeletedList();
            for (String path1 : pathList) {
                if (new File(wdirRepo.getWorkTree(), path1).exists()) {
                    show = true;
                    break;
                }
            }
            if (show) {
                channel.appendOrSendCommand(new DisplaySimpleMessageClientCommand(
                        GitPlugin.getInstance().getMessage("git.checkout.nonDeletedFiles.title"),
                        GitPlugin.getInstance().getMessage("git.checkout.nonDeletedFiles.message",
                                Repository.shortenRefName(name)),
                        cc.getResult().getUndeletedList().toString(),
                        DisplaySimpleMessageClientCommand.ICON_ERROR));
            }
        } else if (cc.getResult().getStatus() == CheckoutResult.Status.OK) {
            if (ObjectId.isId(wdirRepo.getFullBranch()))
                channel.appendOrSendCommand(new DisplaySimpleMessageClientCommand(
                        GitPlugin.getInstance().getMessage("git.checkout.detachedHead.title"),
                        GitPlugin.getInstance().getMessage("git.checkout.detachedHead.message"),
                        DisplaySimpleMessageClientCommand.ICON_ERROR));
        }
        monitor.worked(1);
        return true;
    } catch (Exception e) {
        channel.appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        e.getMessage(), DisplaySimpleMessageClientCommand.ICON_ERROR));
        return false;
    } finally {
        monitor.done();
    }
}

From source file:org.fusesource.fabric.git.internal.CachingGitDataStoreTest.java

License:Apache License

@Before
public void setUp() throws Exception {
    sfb = new ZKServerFactoryBean();
    delete(sfb.getDataDir());//ww  w .  j  a  v a2s .c  o m
    delete(sfb.getDataLogDir());
    sfb.afterPropertiesSet();

    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
            .connectString("localhost:" + sfb.getClientPortAddress().getPort())
            .retryPolicy(new RetryOneTime(1000)).connectionTimeoutMs(360000);

    curator = builder.build();
    curator.start();
    curator.getZookeeperClient().blockUntilConnectedOrTimedOut();

    // setup a local and remote git repo
    basedir = System.getProperty("basedir", ".");
    File root = new File(basedir + "/target/git").getCanonicalFile();
    delete(root);

    new File(root, "remote").mkdirs();
    remote = Git.init().setDirectory(new File(root, "remote")).call();
    remote.commit().setMessage("First Commit").setCommitter("fabric", "user@fabric").call();
    String remoteUrl = "file://" + new File(root, "remote").getCanonicalPath();

    new File(root, "local").mkdirs();
    git = Git.init().setDirectory(new File(root, "local")).call();
    git.commit().setMessage("First Commit").setCommitter("fabric", "user@fabric").call();
    StoredConfig config = git.getRepository().getConfig();
    config.setString("remote", "origin", "url", remoteUrl);
    config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*");
    config.save();

    DefaultRuntimeProperties sysprops = new DefaultRuntimeProperties();
    sysprops.setProperty(SystemProperties.KARAF_DATA, "target/data");
    FabricGitServiceImpl gitService = new FabricGitServiceImpl();
    gitService.bindRuntimeProperties(sysprops);
    gitService.activate();
    gitService.setGitForTesting(git);

    DataStoreTemplateRegistry registrationHandler = new DataStoreTemplateRegistry();
    registrationHandler.activateComponent();

    dataStore = new CachingGitDataStore();
    dataStore.bindCurator(curator);
    dataStore.bindGitService(gitService);
    dataStore.bindRegistrationHandler(registrationHandler);
    dataStore.bindRuntimeProperties(sysprops);
    Map<String, String> datastoreProperties = new HashMap<String, String>();
    datastoreProperties.put(GitDataStore.GIT_REMOTE_URL, remoteUrl);
    dataStore.activate(datastoreProperties);
}

From source file:org.fusesource.fabric.git.internal.GitDataStoreTest.java

License:Apache License

@Before
public void setUp() throws Exception {
    sfb = new ZKServerFactoryBean();
    delete(sfb.getDataDir());//from  w  ww . j  a v  a2  s  . co  m
    delete(sfb.getDataLogDir());
    sfb.afterPropertiesSet();

    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
            .connectString("localhost:" + sfb.getClientPortAddress().getPort())
            .retryPolicy(new RetryOneTime(1000)).connectionTimeoutMs(360000);

    curator = builder.build();
    curator.start();
    curator.getZookeeperClient().blockUntilConnectedOrTimedOut();

    // setup a local and remote git repo
    basedir = System.getProperty("basedir", ".");
    File root = new File(basedir + "/target/git").getCanonicalFile();
    delete(root);

    new File(root, "remote").mkdirs();
    remote = Git.init().setDirectory(new File(root, "remote")).call();
    remote.commit().setMessage("First Commit").setCommitter("fabric", "user@fabric").call();
    String remoteUrl = "file://" + new File(root, "remote").getCanonicalPath();

    new File(root, "local").mkdirs();
    git = Git.init().setDirectory(new File(root, "local")).call();
    git.commit().setMessage("First Commit").setCommitter("fabric", "user@fabric").call();
    StoredConfig config = git.getRepository().getConfig();
    config.setString("remote", "origin", "url", remoteUrl);
    config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*");
    config.save();

    FabricGitServiceImpl gitService = new FabricGitServiceImpl();
    gitService.activate(EasyMock.createMock(ComponentContext.class));
    gitService.setGitForTesting(git);

    dataStore = createDataStore();
    dataStore.bindCuratorForTesting(curator);
    dataStore.bindGitService(gitService);
    dataStore.activate(EasyMock.createMock(ComponentContext.class));
    Map<String, String> datastoreProperties = new HashMap<String, String>();
    datastoreProperties.put(GitDataStore.GIT_REMOTE_URL, remoteUrl);
    dataStore.setDataStoreProperties(datastoreProperties);
    dataStore.start();
}

From source file:org.fusesource.fabric.git.internal.GitHelpers.java

License:Apache License

protected static void configureBranch(Git git, String branch, String remote) {
    // lets update the merge config
    if (Strings.isNotBlank(branch)) {
        StoredConfig config = git.getRepository().getConfig();
        if (Strings.isNullOrBlank(config.getString("branch", branch, "remote"))
                || Strings.isNullOrBlank(config.getString("branch", branch, "merge"))) {
            config.setString("branch", branch, "remote", remote);
            config.setString("branch", branch, "merge", "refs/heads/" + branch);
            try {
                config.save();
            } catch (IOException e) {
                LOG.error("Failed to configure the branch configuration to " + getRootGitDirectory(git)
                        + " with branch " + branch + " on remote repo: " + remote + ". " + e, e);
            }/*from w w  w . j  av a2s .  c  om*/
        }
    }
}

From source file:org.jboss.as.server.controller.git.GitRepository.java

License:Apache License

public GitRepository(GitRepositoryConfiguration gitConfig)
        throws IllegalArgumentException, IOException, ConfigXMLParseException, GeneralSecurityException {
    this.basePath = gitConfig.getBasePath();
    this.branch = gitConfig.getBranch();
    this.ignored = gitConfig.getIgnored();
    this.defaultRemoteRepository = gitConfig.getRepository();
    File baseDir = basePath.toFile();
    File gitDir = new File(baseDir, DOT_GIT);
    if (gitConfig.getAuthenticationConfig() != null) {
        CredentialsProvider// w ww.  ja v a  2  s.  c  om
                .setDefault(new ElytronClientCredentialsProvider(gitConfig.getAuthenticationConfig()));
    }
    if (gitDir.exists()) {
        try {
            repository = new FileRepositoryBuilder().setWorkTree(baseDir).setGitDir(gitDir).setup().build();
        } catch (IOException ex) {
            throw ServerLogger.ROOT_LOGGER.failedToPullRepository(ex, gitConfig.getRepository());
        }
        try (Git git = Git.wrap(repository)) {
            git.clean();
            if (!isLocalGitRepository(gitConfig.getRepository())) {
                String remote = getRemoteName(gitConfig.getRepository());
                checkoutToSelectedBranch(git);
                PullResult result = git.pull().setRemote(remote).setRemoteBranchName(branch)
                        .setStrategy(MergeStrategy.RESOLVE).call();
                if (!result.isSuccessful()) {
                    throw ServerLogger.ROOT_LOGGER.failedToPullRepository(null, gitConfig.getRepository());
                }
            } else {
                if (!this.branch.equals(repository.getBranch())) {
                    CheckoutCommand checkout = git.checkout().setName(branch);
                    checkout.call();
                    if (checkout.getResult().getStatus() == CheckoutResult.Status.ERROR) {
                        throw ServerLogger.ROOT_LOGGER.failedToPullRepository(null, gitConfig.getRepository());
                    }
                }
            }
        } catch (GitAPIException ex) {
            throw ServerLogger.ROOT_LOGGER.failedToPullRepository(ex, gitConfig.getRepository());
        }
    } else {
        if (isLocalGitRepository(gitConfig.getRepository())) {
            try (Git git = Git.init().setDirectory(baseDir).call()) {
                final AddCommand addCommand = git.add();
                addCommand.addFilepattern("data/content/");
                Path configurationDir = basePath.resolve("configuration");
                try (Stream<Path> files = Files.list(configurationDir)) {
                    files.filter(configFile -> !"logging.properties".equals(configFile.getFileName().toString())
                            && Files.isRegularFile(configFile))
                            .forEach(configFile -> addCommand.addFilepattern(getPattern(configFile)));
                }
                addCommand.call();
                createGitIgnore(git, basePath);
                git.commit().setMessage(ServerLogger.ROOT_LOGGER.repositoryInitialized()).call();
            } catch (GitAPIException | IOException ex) {
                throw ServerLogger.ROOT_LOGGER.failedToInitRepository(ex, gitConfig.getRepository());
            }
        } else {
            clearExistingFiles(basePath, gitConfig.getRepository());
            try (Git git = Git.init().setDirectory(baseDir).call()) {
                String remoteName = UUID.randomUUID().toString();
                StoredConfig config = git.getRepository().getConfig();
                config.setString("remote", remoteName, "url", gitConfig.getRepository());
                config.setString("remote", remoteName, "fetch",
                        "+" + R_HEADS + "*:" + R_REMOTES + remoteName + "/*");
                config.save();
                git.clean();
                git.pull().setRemote(remoteName).setRemoteBranchName(branch).setStrategy(MergeStrategy.RESOLVE)
                        .call();
                checkoutToSelectedBranch(git);
                if (createGitIgnore(git, basePath)) {
                    git.commit().setMessage(ServerLogger.ROOT_LOGGER.addingIgnored()).call();
                }
            } catch (GitAPIException ex) {
                throw ServerLogger.ROOT_LOGGER.failedToInitRepository(ex, gitConfig.getRepository());
            }
        }
        repository = new FileRepositoryBuilder().setWorkTree(baseDir).setGitDir(gitDir).setup().build();
    }
    ServerLogger.ROOT_LOGGER.usingGit();
}

From source file:org.jboss.as.test.manualmode.management.persistence.AbstractGitRepositoryTestCase.java

License:Apache License

protected Repository createRepository() throws IOException {
    Repository repo = new FileRepositoryBuilder().setWorkTree(getJbossServerBaseDir().toFile())
            .setGitDir(getDotGitDir().toFile()).setup().build();
    StoredConfig config = repo.getConfig();
    config.setString("remote", "empty", "url",
            "file://" + emptyRemoteRoot.resolve(Constants.DOT_GIT).toAbsolutePath().toString());
    config.save();
    return repo;/*from   w  w w . j av  a  2s .c  o m*/
}