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:com.microsoft.gittf.core.config.ChangesetCommitMap.java

License:Open Source License

private static void copyConfigurationEntries(StoredConfig source, FileBasedConfig target) {
    Set<String> downloadedChangesetEntries = source.getNames(ConfigurationConstants.CONFIGURATION_SECTION,
            ConfigurationConstants.COMMIT_SUBSECTION);

    for (String changesetEntry : downloadedChangesetEntries) {
        String commitHash = source.getString(ConfigurationConstants.CONFIGURATION_SECTION,
                ConfigurationConstants.COMMIT_SUBSECTION, changesetEntry);

        target.setString(ConfigurationConstants.CONFIGURATION_SECTION, ConfigurationConstants.COMMIT_SUBSECTION,
                changesetEntry, commitHash);
    }// www. j a v a  2  s . c  om

    Set<String> createdCommitEntries = source.getNames(ConfigurationConstants.CONFIGURATION_SECTION,
            ConfigurationConstants.CHANGESET_SUBSECTION);

    for (String commitEntry : createdCommitEntries) {
        int changesetId = source.getInt(ConfigurationConstants.CONFIGURATION_SECTION,
                ConfigurationConstants.CHANGESET_SUBSECTION, commitEntry, -1);

        target.setInt(ConfigurationConstants.CONFIGURATION_SECTION, ConfigurationConstants.CHANGESET_SUBSECTION,
                commitEntry, changesetId);
    }

    source.unsetSection(ConfigurationConstants.CONFIGURATION_SECTION,
            ConfigurationConstants.CHANGESET_SUBSECTION);
    source.unsetSection(ConfigurationConstants.CONFIGURATION_SECTION, ConfigurationConstants.COMMIT_SUBSECTION);

    try {
        target.save();
        source.save();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.netbeetle.reboot.git.CachedRepository.java

License:Apache License

public void init() throws IOException, URISyntaxException {
    if (exists()) {
        return;/*from  w  w w .  j  ava2 s .  co  m*/
    }

    repository.create(true);
    StoredConfig config = repository.getConfig();
    RemoteConfig remoteConfig = new RemoteConfig(config, "origin");
    remoteConfig.addURI(new URIish(uri));
    remoteConfig.setMirror(true);
    remoteConfig.addFetchRefSpec(new RefSpec().setForceUpdate(true).setSourceDestination("refs/*", "refs/*"));
    remoteConfig.update(config);
    config.save();
}

From source file:com.nlbhub.nlb.vcs.GitAdapter.java

License:Open Source License

private static void enableLongPaths(final Repository repository, final boolean save) throws IOException {
    StoredConfig config = repository.getConfig();
    config.setString("core", null, "longpaths", "true");
    if (save) {/*  ww w .  j ava  2 s  . c  o m*/
        config.save();
    }
}

From source file:com.osbitools.ws.shared.prj.web.AbstractWsPrjInit.java

License:LGPL

@Override
public void contextInitialized(ServletContextEvent evt) {
    super.contextInitialized(evt);
    ServletContext ctx = evt.getServletContext();

    // First - Load Custom Error List 
    try {/*from w w w .j a  v a  2 s  .  co  m*/
        Class.forName("com.osbitools.ws.shared.prj.CustErrorList");
    } catch (ClassNotFoundException e) {
        // Ignore Error 
    }

    // Initialize Entity Utils
    IEntityUtils eut = getEntityUtils();
    ctx.setAttribute("entity_utils", eut);

    // Initiate LangSetFileUtils
    ctx.setAttribute("ll_set_utils", new LangSetUtils());

    // Check if git repository exists and create one
    // Using ds subdirectory as git root repository 
    File drepo = new File(
            getConfigDir(ctx) + File.separator + eut.getPrjRootDirName() + File.separator + ".git");
    Git git;
    try {

        if (!drepo.exists()) {
            if (!drepo.mkdirs())
                throw new RuntimeErrorException(
                        new Error("Unable create directory '" + drepo.getAbsolutePath() + "'"));

            try {
                git = createGitRepo(drepo);
            } catch (Exception e) {
                throw new RuntimeErrorException(new Error(
                        "Unable create new repo on path: " + drepo.getAbsolutePath() + ". " + e.getMessage()));
            }

            getLogger(ctx).info("Created new git repository '" + drepo.getAbsolutePath() + "'");
        } else if (!drepo.isDirectory()) {
            throw new RuntimeErrorException(
                    new Error(drepo.getAbsolutePath() + " is regular file and not a directory"));
        } else {
            git = Git.open(drepo);
            getLogger(ctx).debug("Open existing repository " + drepo.getAbsolutePath());
        }
    } catch (IOException e) {
        // Something unexpected and needs to be analyzed
        e.printStackTrace();

        throw new RuntimeErrorException(new Error(e));
    }

    // Save git handler
    ctx.setAttribute("git", git);

    // Check if remote destination set/changed
    StoredConfig config = git.getRepository().getConfig();
    String rname = (String) ctx.getAttribute(PrjMgrConstants.PREMOTE_GIT_NAME);
    String rurl = (String) ctx.getAttribute("git_remote_url");

    if (!Utils.isEmpty(rname) && !Utils.isEmpty(rurl)) {
        String url = config.getString("remote", rname, "url");
        if (!rurl.equals(url)) {
            config.setString("remote", rname, "url", rurl);
            try {
                config.save();
            } catch (IOException e) {
                getLogger(ctx).error("Error saving git remote url. " + e.getMessage());
            }
        }
    }

    // Temp directory for files upload
    String tname = System.getProperty("java.io.tmpdir");
    getLogger(ctx).info("Using temporarily directory '" + tname + "' for file uploads");
    File tdir = new File(tname);

    if (!tdir.exists())
        throw new RuntimeErrorException(
                new Error("Temporarily directory for file upload '" + tname + "' is not found"));
    if (!tdir.isDirectory())
        throw new RuntimeErrorException(
                new Error("Temporarily directory for file upload '" + tname + "' is not a directory"));

    DiskFileItemFactory dfi = new DiskFileItemFactory();
    dfi.setSizeThreshold(
            ((Integer) ctx.getAttribute(PrjMgrConstants.SMAX_FILE_UPLOAD_SIZE_NAME)) * 1024 * 1024);
    dfi.setRepository(tdir);
    evt.getServletContext().setAttribute("dfi", dfi);

    // Save entity utils in context
    evt.getServletContext().setAttribute("entity_utils", getEntityUtils());
}

From source file:com.photon.phresco.framework.impl.SCMManagerImpl.java

License:Apache License

private void importToGITRepo(RepoDetail repodetail, ApplicationInfo appInfo, File appDir) throws Exception {
    if (debugEnabled) {
        S_LOGGER.debug("Entering Method  SCMManagerImpl.importToGITRepo()");
    }//  w  w  w.j  a va 2  s  . com
    boolean gitExists = false;
    if (new File(appDir.getPath() + FORWARD_SLASH + DOT + GIT).exists()) {
        gitExists = true;
    }
    try {
        //For https and ssh
        additionalAuthentication(repodetail.getPassPhrase());

        CredentialsProvider cp = new UsernamePasswordCredentialsProvider(repodetail.getUserName(),
                repodetail.getPassword());

        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(appDir).readEnvironment().findGitDir().build();
        String dirPath = appDir.getPath();
        File gitignore = new File(dirPath + GITIGNORE_FILE);
        gitignore.createNewFile();
        if (gitignore.exists()) {
            String contents = FileUtils.readFileToString(gitignore);
            if (!contents.isEmpty() && !contents.contains(DO_NOT_CHECKIN_DIR)) {
                String source = NEWLINE + DO_NOT_CHECKIN_DIR + NEWLINE;
                OutputStream out = new FileOutputStream((dirPath + GITIGNORE_FILE), true);
                byte buf[] = source.getBytes();
                out.write(buf);
                out.close();
            } else if (contents.isEmpty()) {
                String source = NEWLINE + DO_NOT_CHECKIN_DIR + NEWLINE;
                OutputStream out = new FileOutputStream((dirPath + GITIGNORE_FILE), true);
                byte buf[] = source.getBytes();
                out.write(buf);
                out.close();
            }
        }

        Git git = new Git(repository);

        InitCommand initCommand = Git.init();
        initCommand.setDirectory(appDir);
        git = initCommand.call();

        AddCommand add = git.add();
        add.addFilepattern(".");
        add.call();

        CommitCommand commit = git.commit().setAll(true);
        commit.setMessage(repodetail.getCommitMessage()).call();
        StoredConfig config = git.getRepository().getConfig();

        config.setString(REMOTE, ORIGIN, URL, repodetail.getRepoUrl());
        config.setString(REMOTE, ORIGIN, FETCH, REFS_HEADS_REMOTE_ORIGIN);
        config.setString(BRANCH, MASTER, REMOTE, ORIGIN);
        config.setString(BRANCH, MASTER, MERGE, REF_HEAD_MASTER);
        config.save();

        try {
            PushCommand pc = git.push();
            pc.setCredentialsProvider(cp).setForce(true);
            pc.setPushAll().call();
        } catch (Exception e) {
            git.getRepository().close();
            PomProcessor appPomProcessor = new PomProcessor(new File(appDir, appInfo.getPhrescoPomFile()));
            appPomProcessor.removeProperty(Constants.POM_PROP_KEY_SRC_REPO_URL);
            appPomProcessor.save();
            throw e;
        }

        if (appInfo != null) {
            updateSCMConnection(appInfo, repodetail.getRepoUrl());
        }
        git.getRepository().close();
    } catch (Exception e) {
        Exception s = e;
        resetLocalCommit(appDir, gitExists, e);
        throw s;
    }
}

From source file:com.rimerosolutions.ant.git.tasks.FetchTask.java

License:Apache License

@Override
public void doExecute() {
    try {/* ww w.j a  v  a  2  s  .co  m*/
        StoredConfig config = git.getRepository().getConfig();
        List<RemoteConfig> remoteConfigs = RemoteConfig.getAllRemoteConfigs(config);

        if (remoteConfigs.isEmpty()) {
            URIish uri = new URIish(getUri());

            RemoteConfig remoteConfig = new RemoteConfig(config, Constants.DEFAULT_REMOTE_NAME);
            remoteConfig.addURI(uri);
            remoteConfig.addFetchRefSpec(new RefSpec("+" + Constants.R_HEADS + "*:" + Constants.R_REMOTES
                    + Constants.DEFAULT_REMOTE_NAME + "/*"));

            config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, Constants.MASTER,
                    ConfigConstants.CONFIG_KEY_REMOTE, Constants.DEFAULT_REMOTE_NAME);
            config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, Constants.MASTER,
                    ConfigConstants.CONFIG_KEY_MERGE, Constants.R_HEADS + Constants.MASTER);

            remoteConfig.update(config);
            config.save();
        }

        List<RefSpec> specs = new ArrayList<RefSpec>(3);

        specs.add(new RefSpec(
                "+" + Constants.R_HEADS + "*:" + Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + "/*"));
        specs.add(new RefSpec("+" + Constants.R_NOTES + "*:" + Constants.R_NOTES + "*"));
        specs.add(new RefSpec("+" + Constants.R_TAGS + "*:" + Constants.R_TAGS + "*"));

        FetchCommand fetchCommand = git.fetch().setDryRun(dryRun).setThin(thinPack).setRemote(getUri())
                .setRefSpecs(specs).setRemoveDeletedRefs(removeDeletedRefs);

        setupCredentials(fetchCommand);

        if (getProgressMonitor() != null) {
            fetchCommand.setProgressMonitor(getProgressMonitor());
        }

        FetchResult fetchResult = fetchCommand.call();

        GitTaskUtils.validateTrackingRefUpdates(FETCH_FAILED_MESSAGE, fetchResult.getTrackingRefUpdates());

        log(fetchResult.getMessages());

    } catch (URISyntaxException e) {
        throw new GitBuildException("Invalid URI syntax: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new GitBuildException("Could not save or get repository configuration: " + e.getMessage(), e);
    } catch (InvalidRemoteException e) {
        throw new GitBuildException("Invalid remote URI: " + e.getMessage(), e);
    } catch (TransportException e) {
        throw new GitBuildException("Communication error: " + e.getMessage(), e);
    } catch (GitAPIException e) {
        throw new GitBuildException("Unexpected exception: " + e.getMessage(), e);
    }
}

From source file:com.rimerosolutions.ant.git.tasks.PushTask.java

License:Apache License

@Override
protected void doExecute() {
    try {// w w  w  . j a  v a2 s .c  o m
        StoredConfig config = git.getRepository().getConfig();
        List<RemoteConfig> remoteConfigs = RemoteConfig.getAllRemoteConfigs(config);

        if (remoteConfigs.isEmpty()) {
            URIish uri = new URIish(getUri());

            RemoteConfig remoteConfig = new RemoteConfig(config, Constants.DEFAULT_REMOTE_NAME);

            remoteConfig.addURI(uri);
            remoteConfig.addFetchRefSpec(new RefSpec(DEFAULT_REFSPEC_STRING));
            remoteConfig.addPushRefSpec(new RefSpec(DEFAULT_REFSPEC_STRING));
            remoteConfig.update(config);

            config.save();
        }

        String currentBranch = git.getRepository().getBranch();
        List<RefSpec> specs = Arrays.asList(new RefSpec(currentBranch + ":" + currentBranch));

        if (deleteRemoteBranch != null) {
            specs = Arrays.asList(new RefSpec(":" + Constants.R_HEADS + deleteRemoteBranch));
        }

        PushCommand pushCommand = git.push().setPushAll().setRefSpecs(specs).setDryRun(false);

        if (getUri() != null) {
            pushCommand.setRemote(getUri());
        }

        setupCredentials(pushCommand);

        if (includeTags) {
            pushCommand.setPushTags();
        }

        if (getProgressMonitor() != null) {
            pushCommand.setProgressMonitor(getProgressMonitor());
        }

        Iterable<PushResult> pushResults = pushCommand.setForce(true).call();

        for (PushResult pushResult : pushResults) {
            log(pushResult.getMessages());
            GitTaskUtils.validateRemoteRefUpdates(PUSH_FAILED_MESSAGE, pushResult.getRemoteUpdates());
            GitTaskUtils.validateTrackingRefUpdates(PUSH_FAILED_MESSAGE, pushResult.getTrackingRefUpdates());
        }
    } catch (Exception e) {
        if (pushFailedProperty != null) {
            getProject().setProperty(pushFailedProperty, e.getMessage());
        }

        throw new GitBuildException(PUSH_FAILED_MESSAGE, e);
    }
}

From source file:com.surevine.gateway.scm.git.jgit.JGitGitFacade.java

License:Open Source License

@Override
public void addRemote(final LocalRepoBean repoBean, final String remoteName, final String remoteURL)
        throws GitException {
    try {// w w  w  . j a v  a 2  s  .co m
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        Repository repository = builder.setGitDir(repoBean.getGitConfigDirectory().toFile()).findGitDir()
                .build();
        Git git = new org.eclipse.jgit.api.Git(repository);
        StoredConfig config = git.getRepository().getConfig();
        config.setString("remote", remoteName, "url", remoteURL);
        config.setString("remote", remoteName, "fetch",
                String.format("+refs/heads/*:refs/remotes/%s/*", remoteName));
        config.save();

    } catch (IOException e) {
        LOGGER.error(e);
        throw new GitException(e);
    }
}

From source file:com.surevine.gateway.scm.git.jgit.TestUtility.java

License:Open Source License

public static LocalRepoBean createTestRepoMultipleBranches() throws Exception {
    final String projectKey = "test_" + UUID.randomUUID().toString();
    final String repoSlug = "testRepo";
    final String remoteURL = "ssh://fake_url";
    final Path repoPath = Paths.get(PropertyUtil.getGitDir(), "local_scm", projectKey, repoSlug);
    Files.createDirectories(repoPath);
    final Repository repo = new FileRepository(repoPath.resolve(".git").toFile());
    repo.create();//from   w ww .  j a  v a2s .c o m
    final StoredConfig config = repo.getConfig();
    config.setString("remote", "origin", "url", remoteURL);
    config.save();

    final LocalRepoBean repoBean = new LocalRepoBean();
    repoBean.setProjectKey(projectKey);
    repoBean.setSlug(repoSlug);
    repoBean.setLocalBare(false);

    final Git git = new Git(repo);

    // add some files to some branches
    for (int i = 0; i < 3; i++) {
        final String filename = "newfile" + i + ".txt";
        Files.write(repoPath.resolve(filename), Arrays.asList("Hello World"), StandardCharsets.UTF_8,
                StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        git.add().addFilepattern(filename).call();
        git.commit().setMessage("Added " + filename).call();
    }

    git.checkout().setName("branch1").setCreateBranch(true).call();
    for (int i = 0; i < 3; i++) {
        final String filename = "branch1" + i + ".txt";
        Files.write(repoPath.resolve(filename), Arrays.asList("Hello World"), StandardCharsets.UTF_8,
                StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        git.add().addFilepattern(filename).call();
        git.commit().setMessage("Added " + filename).call();
    }

    git.checkout().setName("master").call();
    git.checkout().setName("branch2").setCreateBranch(true).call();
    for (int i = 0; i < 3; i++) {
        final String filename = "branch2" + i + ".txt";
        Files.write(repoPath.resolve(filename), Arrays.asList("Hello World"), StandardCharsets.UTF_8,
                StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        git.add().addFilepattern(filename).call();
        git.commit().setMessage("Added " + filename).call();
    }

    repo.close();
    return repoBean;
}

From source file:com.surevine.gateway.scm.git.jgit.TestUtility.java

License:Open Source License

public static LocalRepoBean createTestRepo() throws Exception {
    final String projectKey = "test_" + UUID.randomUUID().toString();
    final String repoSlug = "testRepo";
    final String remoteURL = "ssh://fake_url";
    final Path repoPath = Paths.get(PropertyUtil.getGitDir(), "local_scm", projectKey, repoSlug);
    Files.createDirectories(repoPath);
    final Repository repo = new FileRepository(repoPath.resolve(".git").toFile());
    repo.create();//w ww .  j  a  v  a  2  s .c o  m
    final StoredConfig config = repo.getConfig();
    config.setString("remote", "origin", "url", remoteURL);
    config.save();

    final LocalRepoBean repoBean = new LocalRepoBean();
    repoBean.setProjectKey(projectKey);
    repoBean.setSlug(repoSlug);
    repoBean.setLocalBare(false);
    repoBean.setSourcePartner("partner");

    final Git git = new Git(repo);

    for (int i = 0; i < 3; i++) {
        final String filename = "newfile" + i + ".txt";
        Files.write(repoPath.resolve(filename), Arrays.asList("Hello World"), StandardCharsets.UTF_8,
                StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        git.add().addFilepattern(filename).call();
        git.commit().setMessage("Added " + filename).call();
    }

    git.checkout().setName("master").call();

    repo.close();
    return repoBean;
}