List of usage examples for org.eclipse.jgit.lib StoredConfig save
public abstract void save() throws IOException;
From source file:io.fabric8.openshift.agent.CartridgeGitRepository.java
License:Apache License
/** * Clones or pulls the remote repository and returns the directory with the checkout *//*from ww w .j av a 2 s. com*/ public void cloneOrPull(final String repo, final CredentialsProvider credentials) throws Exception { if (!localRepo.exists() && !localRepo.mkdirs()) { throw new IOException("Failed to create local repository"); } File gitDir = new File(localRepo, ".git"); if (!gitDir.exists()) { LOG.info("Cloning remote repo " + repo); CloneCommand command = Git.cloneRepository().setCredentialsProvider(credentials).setURI(repo) .setDirectory(localRepo).setRemote(remoteName); git = command.call(); } else { FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repository = builder.setGitDir(gitDir).readEnvironment() // scan environment GIT_* variables .findGitDir() // scan up the file system tree .build(); git = new Git(repository); // update the remote repo just in case StoredConfig config = repository.getConfig(); config.setString("remote", remoteName, "url", repo); config.setString("remote", remoteName, "fetch", "+refs/heads/*:refs/remotes/" + remoteName + "/*"); String branch = "master"; config.setString("branch", branch, "remote", remoteName); config.setString("branch", branch, "merge", "refs/heads/" + branch); try { config.save(); } catch (IOException e) { LOG.error("Failed to save the git configuration to " + localRepo + " with remote repo: " + repo + ". " + e, e); } // now pull LOG.info("Pulling from remote repo " + repo); git.pull().setCredentialsProvider(credentials).setRebase(true).call(); } }
From source file:jetbrains.buildServer.buildTriggers.vcs.git.agent.UpdaterImpl.java
License:Apache License
private void addSubmoduleUsernames(@NotNull File repositoryDir, @NotNull Config gitModules) throws IOException, ConfigInvalidException, VcsException { if (!myPluginConfig.isUseMainRepoUserForSubmodules()) return;/*from w w w .j ava 2 s . c om*/ Loggers.VCS.info("Update submodules credentials"); AuthSettings auth = myRoot.getAuthSettings(); final String userName = auth.getUserName(); if (userName == null) { Loggers.VCS.info("Username is not specified in the main VCS root settings, skip updating credentials"); return; } Repository r = new RepositoryBuilder().setBare().setGitDir(getGitDir(repositoryDir)).build(); StoredConfig gitConfig = r.getConfig(); Set<String> submodules = gitModules.getSubsections("submodule"); if (submodules.isEmpty()) { Loggers.VCS.info("No submodule sections found in " + new File(repositoryDir, ".gitmodules").getCanonicalPath() + ", skip updating credentials"); return; } File modulesDir = new File(r.getDirectory(), Constants.MODULES); for (String submoduleName : submodules) { String url = gitModules.getString("submodule", submoduleName, "url"); Loggers.VCS.info("Update credentials for submodule with url " + url); if (url == null || !isRequireAuth(url)) { Loggers.VCS.info("Url " + url + " does not require authentication, skip updating credentials"); continue; } try { URIish uri = new URIish(url); String updatedUrl = uri.setUser(userName).toASCIIString(); gitConfig.setString("submodule", submoduleName, "url", updatedUrl); String submodulePath = gitModules.getString("submodule", submoduleName, "path"); if (submodulePath != null && myPluginConfig.isUpdateSubmoduleOriginUrl()) { File submoduleDir = new File(modulesDir, submodulePath); if (submoduleDir.isDirectory() && new File(submoduleDir, Constants.CONFIG).isFile()) updateOriginUrl(submoduleDir, updatedUrl); } Loggers.VCS.debug("Submodule url " + url + " changed to " + updatedUrl); } catch (URISyntaxException e) { Loggers.VCS.warn("Error while parsing an url " + url + ", skip updating submodule credentials", e); } catch (Exception e) { Loggers.VCS.warn("Error while updating the '" + submoduleName + "' submodule url", e); } } gitConfig.save(); }
From source file:jetbrains.buildServer.buildTriggers.vcs.git.agent.UpdaterImpl.java
License:Apache License
private void updateOriginUrl(@NotNull File repoDir, @NotNull String url) throws IOException { Repository r = new RepositoryBuilder().setBare().setGitDir(repoDir).build(); StoredConfig config = r.getConfig(); config.setString("remote", "origin", "url", url); config.save(); }
From source file:jetbrains.buildServer.buildTriggers.vcs.git.agent.UpdaterImpl.java
License:Apache License
protected void removeUrlSections() throws VcsException { Repository r = null;/*from w ww .j av a2s . c om*/ try { r = new RepositoryBuilder().setWorkTree(myTargetDirectory).build(); StoredConfig config = r.getConfig(); Set<String> urlSubsections = config.getSubsections("url"); for (String subsection : urlSubsections) { config.unsetSection("url", subsection); } config.save(); } catch (IOException e) { String msg = "Error while remove url.* sections"; LOG.error(msg, e); throw new VcsException(msg, e); } finally { if (r != null) r.close(); } }
From source file:jetbrains.buildServer.buildTriggers.vcs.git.GitServerUtil.java
License:Apache License
/** * Ensures that a bare repository exists at the specified path. * If it does not, the directory is attempted to be created. * * @param dir the path to the directory to init * @param remote the remote URL//from w w w . j a v a 2 s .com * @return a connection to repository * @throws VcsException if the there is a problem with accessing VCS */ public static Repository getRepository(@NotNull final File dir, @NotNull final URIish remote) throws VcsException { if (dir.exists() && !dir.isDirectory()) { throw new VcsException("The specified path is not a directory: " + dir); } try { ensureRepositoryIsValid(dir); Repository r = new RepositoryBuilder().setBare().setGitDir(dir).build(); if (!new File(dir, "config").exists()) { r.create(true); final StoredConfig config = r.getConfig(); config.setString("teamcity", null, "remote", remote.toString()); config.save(); } else { final StoredConfig config = r.getConfig(); final String existingRemote = config.getString("teamcity", null, "remote"); if (existingRemote != null && !remote.toString().equals(existingRemote)) { throw getWrongUrlError(dir, existingRemote, remote); } else if (existingRemote == null) { config.setString("teamcity", null, "remote", remote.toString()); config.save(); } } return r; } catch (Exception ex) { if (ex instanceof NullPointerException) LOG.warn("The repository at directory '" + dir + "' cannot be opened or created", ex); throw new VcsException("The repository at directory '" + dir + "' cannot be opened or created, reason: " + ex.toString(), ex); } }
From source file:jetbrains.buildServer.buildTriggers.vcs.git.tests.AgentVcsSupportTest.java
License:Apache License
public void stop_use_any_mirror_if_agent_property_changed_to_false() throws Exception { AgentRunningBuild build2 = createRunningBuild(false); GitVcsRoot root = new GitVcsRoot(myBuilder.getMirrorManager(), myRoot); myVcsSupport.updateSources(myRoot, new CheckoutRules(""), GitVcsSupportTest.VERSION_TEST_HEAD, myCheckoutDir, build2, false); //add some mirror Repository r = new RepositoryBuilder().setWorkTree(myCheckoutDir).build(); StoredConfig config = r.getConfig(); config.setString("url", "/some/path", "insteadOf", root.getRepositoryFetchURL().toString()); config.save(); myVcsSupport.updateSources(myRoot, new CheckoutRules(""), GitVcsSupportTest.VERSION_TEST_HEAD, myCheckoutDir, build2, false); config = new RepositoryBuilder().setWorkTree(myCheckoutDir).build().getConfig(); assertTrue(config.getSubsections("url").isEmpty()); }
From source file:jetbrains.buildServer.buildTriggers.vcs.git.tests.HttpAuthTest.java
License:Apache License
@RequiredGitVersion(min = "2.9.0") @TestFor(issues = { "TW-46668", "TW-45991", "TW-46391" }) public void disable_credential_helpers(@NotNull GitExec git) throws Exception { //Test checks that we disable credential helpers configured on machine File repo = copyRepository(myTempFiles, dataFile("repo_for_fetch.1"), "repo.git"); Random r = new Random(); final String user = "user"; final String password = String.valueOf(r.nextInt(100)); myServer = new GitHttpServer(git.getPath(), repo); myServer.setCredentials(user, password); myServer.start();/*from w ww. j a v a 2 s . co m*/ VcsRootImpl root = vcsRoot().withFetchUrl(myServer.getRepoUrl()) .withAuthMethod(AuthenticationMethod.PASSWORD).withUsername(user).withPassword(password) .withBranch("master").build(); File buildDir = myTempFiles.createTempDir(); AgentRunningBuild build = runningBuild().sharedEnvVariable(Constants.TEAMCITY_AGENT_GIT_PATH, git.getPath()) .sharedConfigParams(PluginConfigImpl.USE_ALTERNATES, "true").build(); //run first build to initialize mirror: Checkout checkout = new Checkout(root, "add81050184d3c818560bdd8839f50024c188586", buildDir, build); checkout.run(TimeUnit.SECONDS.toMillis(10)); assertTrue(checkout.success()); //update remote repo with new commits: FileUtil.delete(repo); copyRepository(dataFile("repo_for_fetch.2"), repo); //configure hanging credential helper for mirror: File mirrorDir = myBuilder.getMirrorManager() .getMirrorDir(myServer.getRepoUrl().replaceAll("http://", "http://" + user + "@")); Repository mirror = new RepositoryBuilder().setGitDir(mirrorDir).build(); StoredConfig config = mirror.getConfig(); config.setString("credential", null, "helper", createHangingCredProvider(100).getCanonicalPath()); config.save(); //run build requiring a mirror update, hanging helper should be disabled and checkout should finish successfully checkout = new Checkout(root, "d47dda159b27b9a8c4cee4ce98e4435eb5b17168", buildDir, build); checkout.run(TimeUnit.SECONDS.toMillis(10)); assertTrue(checkout.success()); }
From source file:me.seeber.gradle.repository.git.ConfigureLocalGitRepository.java
License:Open Source License
/** * Run task/*from w w w . j a va 2s . c o m*/ * * @throws IOException if something really bad happens */ @TaskAction public void configure() throws IOException { FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder(); repositoryBuilder.addCeilingDirectory(getProject().getProjectDir()); repositoryBuilder.findGitDir(getProject().getProjectDir()); boolean create = (repositoryBuilder.getGitDir() == null); repositoryBuilder.setWorkTree(getProject().getProjectDir()); Repository repository = repositoryBuilder.build(); if (create) { repository.create(); } try (Git git = new Git(repository)) { StoredConfig config = git.getRepository().getConfig(); getRemoteRepositories().forEach((name, url) -> { config.setString("remote", name, "url", url); }); config.save(); } File ignoreFile = getProject().file(".gitignore"); SortedSet<@NonNull String> remainingIgnores = new TreeSet<>(getIgnores()); List<String> lines = new ArrayList<>(); if (ignoreFile.exists()) { Files.lines(ignoreFile.toPath()).forEach(l -> { lines.add(l); if (!l.trim().startsWith("#")) { remainingIgnores.remove(unescapePattern(l)); } }); } if (!remainingIgnores.isEmpty()) { List<@NonNull String> escapedIgnores = remainingIgnores.stream().map(l -> escapePattern(l)) .collect(Collectors.toList()); lines.addAll(escapedIgnores); Files.write(ignoreFile.toPath(), lines, StandardOpenOption.CREATE); } }
From source file:net.morimekta.gittool.cmd.Branch.java
License:Apache License
@Override public void execute(GitTool gt) throws IOException { this.gt = gt; ArrayList<InputSelection.Command<BranchInfo>> actions = new ArrayList<>(5); actions.add(new InputSelection.Command<>(Char.CR, "select", this::onSelect, true)); actions.add(new InputSelection.Command<>('D', "delete", this::onDelete)); actions.add(new InputSelection.Command<>('q', "quit", this::onExit)); actions.add(new InputSelection.Command<>('d', "set diffbase", this::onSetDiffbase)); actions.add(new InputSelection.Command<>('m', "move", this::onRename)); STTY tty = new STTY(); try (Terminal terminal = new Terminal(tty)) { try (Repository repositoryResource = gt.getRepository()) { this.repository = repositoryResource; this.git = new Git(repositoryResource); BranchInfo tmp = refreshBranchList(null); prompt = "Manage branches from '" + currentInfo.name + "':"; while (true) { action = null;//from w w w . j a v a2s. com try { InputSelection<BranchInfo> selection = new InputSelection<>(terminal, prompt, branches, actions, BranchInfo::branchLine); tmp = selection.select(tmp); } catch (UncheckedIOException e) { // Most likely: User interrupted: // <ESC>, <CTRL-C> etc. System.out.println(e.getMessage()); return; } if (tmp == null) { // command action EXIT. return; } if (action == null) { continue; } final BranchInfo selected = tmp; switch (action) { case CHECKOUT: { Ref ref = git.checkout().setName(selected.name).call(); if (ref == null) { terminal.error("No ref from checkout op..."); break; } return; } case DELETE: { if (selected.commits == 0 || terminal .confirm("Do you really want to delete branch " + YELLOW + selected.name + CLEAR + " with " + GREEN + "+" + selected.commits + CLEAR + " commits?")) { git.branchDelete().setBranchNames(selected.name).call(); terminal.info("Deleted branch " + RED + selected.name + CLEAR + "!"); tmp = currentInfo; } else { terminal.info("Delete canceled."); return; } tmp = refreshBranchList(tmp.name); terminal.println(); break; } case RENAME: { String name; try { InputLine input = new InputLine(terminal, "New name for " + YELLOW + selected.name + CLEAR); name = input.readLine(selected.name); } catch (UncheckedIOException e) { // Most likely user interruption. terminal.info(e.getMessage()); terminal.println(); break; } if (selected.name.equals(name)) { terminal.info("Same same same..."); terminal.println(); break; } Ref ref = git.branchRename().setOldName(selected.name).setNewName(name).call(); if (ref == null) { terminal.error("No ref from branch rename operation..."); return; } terminal.println(); tmp = refreshBranchList(selected.name); break; } case SET_DIFFBASE: { if (selected.name.equals(gt.getDefaultBranch())) { // TODO: Replace list with remotes only... terminal.warn(format("Setting diffbase on %s%s%s branch!", Color.BOLD, selected.name, Color.CLEAR)); terminal.println(); break; } List<BranchInfo> options = new LinkedList<>(branches).stream().filter(b -> { // cannot have self as diffbase if (b == selected) return false; // avoid circular diffs. return !selected.name.equals(b.diffbase); }).collect(Collectors.toList()); if (options.size() == 0) { terminal.info("No possible diffbase branches for " + selected.name); break; } terminal.println(); ArrayList<InputSelection.Command<BranchInfo>> diffbaseActions = new ArrayList<>(5); diffbaseActions.add(new InputSelection.Command<>(Char.CR, "select", (br, lp) -> InputSelection.Reaction.SELECT, true)); diffbaseActions.add(new InputSelection.Command<>('c', "clear", (br, lp) -> { try { StoredConfig config = git.getRepository().getConfig(); config.unset("branch", selected.name, "diffbase"); config.save(); return InputSelection.Reaction.EXIT; } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } })); diffbaseActions.add(new InputSelection.Command<>('q', "quit", (br, lp) -> InputSelection.Reaction.EXIT)); InputSelection<BranchInfo> selection = new InputSelection<>(terminal, "Select diffbase for '" + selected.name + "':", options, diffbaseActions, BranchInfo::selectionLine); BranchInfo oldDiffbase = branches.stream().filter(b -> b.name.equals(selected.diffbase)) .findFirst().orElse(null); BranchInfo newDiffbase = selection.select(oldDiffbase); if (newDiffbase != null) { StoredConfig config = git.getRepository().getConfig(); config.setString("branch", selected.name, "diffbase", newDiffbase.name); config.save(); tmp = refreshBranchList(selected.name); } terminal.println(); break; } default: { terminal.warn("Not implemented: " + action.name()); terminal.println(); break; } } } } catch (GitAPIException e) { terminal.fatal("GIT: " + e.getMessage()); throw new IllegalStateException(e.getMessage(), e); } } }
From source file:net.polydawn.mdm.commands.MdmAddCommand.java
License:Open Source License
public MdmExitMessage call() throws ConfigInvalidException, IOException, MdmException { assertInRepoRoot();//from w ww . j av a2 s . c o m // load other config (so we can error early on in case there's a problem) StoredConfig gitmodulesCfg = new FileBasedConfig(new File(repo.getWorkTree(), Constants.DOT_GIT_MODULES), repo.getFS()); try { gitmodulesCfg.load(); } catch (ConfigInvalidException e) { throw new MdmExitInvalidConfig(Constants.DOT_GIT_MODULES); } // git's behavior of assuming relative urls should be relative to the remote origin instead of relative to the local filesystem is almost certainly not what you want. if (url.startsWith("../") || url.startsWith("./")) os.println( "hey, heads up: when you use a relative url to describe a submodule location, git assumes it's relative to the remote origin of the parent project (NOT relative to the project location on the local filesystem, which is what you might have expected). this... works, but it's not recommended because of the potential it has to surprise."); // give a look at the remote url and see what versions are physically available. List<String> versions = fetchVersions(); if (versions.size() == 0) throw new MdmExitMessage(":(", "no releases could be found at the url you gave for a releases repository -- it doesn't look like releases that mdm understands are there.\nare you sure this is the releases repo? keep in mind that the release repo and the source repo isn't the same for most projects -- check the project readme for the location of their release repo."); // if we didn't get a name argument yet, prompt for one. // note that this is *after* we tried to check that something at least exists on the far side of the url, in order to minimize bother. if (name == null) name = inputPrompt(os, "dependency name: "); File path = new File(pathLibs, name); // check for presence of other crap here already. (`git submodule add` will also do this, but it's a more pleasant user experience to check this before popping up a prompt for version name.) if (path.exists()) throw new MdmExitMessage(":'(", "there are already files at " + path + " !\nWe can't pull down a dependency there until this conflict is cleared away."); if (SubmoduleWalk.forIndex(repo).setFilter(PathFilter.create(path.getPath())).next()) throw new MdmExitMessage(":'(", "there is already a submodule in the git index at " + path + " !\nWe can't pull down a dependency there until this conflict is cleared away."); // if a specific version name was given, we'll just go straight at it; otherwise we present options interactively from the manifest of versions the remote reported. if (version == null) version = Loco.promptForVersion(os, versions); // check yourself before you wreck yourself if (!versions.contains(version)) throw new MdmExitMessage(":(", "no version labelled " + version + " available from the provided remote url."); // finally, let's actually do the submodule/dependency adding doSubmoduleConfig(gitmodulesCfg, path); gitmodulesCfg.save(); doSubmoduleFetch(path, gitmodulesCfg); // commit the changes doGitStage(path); doGitCommit(path); return new MdmExitMessage(":D", "added dependency on " + name + "-" + version + " successfully!"); }