List of usage examples for org.eclipse.jgit.lib StoredConfig setString
public void setString(final String section, final String subsection, final String name, final String value)
From source file:org.moxie.ant.Main.java
License:Apache License
private void initGit() throws GitAPIException { // create the repository InitCommand init = Git.init();//from w w w . ja va2s.c om init.setBare(false); init.setDirectory(newProject.dir); Git git = init.call(); if (!StringUtils.isEmpty(newProject.gitOrigin)) { // set the origin and configure the master branch for merging StoredConfig config = git.getRepository().getConfig(); config.setString("remote", "origin", "url", getGitUrl()); config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*"); config.setString("branch", "master", "remote", "origin"); config.setString("branch", "master", "merge", "refs/heads/master"); try { config.save(); } catch (IOException e) { throw new MoxieException(e); } } // prepare a common gitignore file StringBuilder sb = new StringBuilder(); sb.append("/.directory\n"); sb.append("/.DS_STORE\n"); sb.append("/.DS_Store\n"); sb.append("/.settings\n"); sb.append("/bin\n"); sb.append("/build\n"); sb.append("/ext\n"); sb.append("/target\n"); sb.append("/tmp\n"); sb.append("/temp\n"); if (!newProject.eclipse.includeClasspath()) { // ignore hard-coded .classpath sb.append("/.classpath\n"); } FileUtils.writeContent(new File(newProject.dir, ".gitignore"), sb.toString()); AddCommand add = git.add(); add.addFilepattern("build.xml"); add.addFilepattern("build.moxie"); add.addFilepattern(".gitignore"); if (newProject.eclipse.includeProject()) { add.addFilepattern(".project"); } if (newProject.eclipse.includeClasspath()) { // MOXIE_HOME relative dependencies in .classpath add.addFilepattern(".classpath"); } if (newProject.idea.includeProject()) { add.addFilepattern(".project"); } if (newProject.idea.includeClasspath()) { // MOXIE_HOME relative dependencies in .iml add.addFilepattern("*.iml"); } try { add.call(); CommitCommand commit = git.commit(); PersonIdent moxie = new PersonIdent("Moxie", "moxie@localhost"); commit.setAuthor(moxie); commit.setCommitter(moxie); commit.setMessage("Project structure created"); commit.call(); } catch (Exception e) { throw new MoxieException(e); } }
From source file:org.ms123.common.git.GitServiceImpl.java
License:Open Source License
public void addRemoteOrigin(@PName("name") String name, @PName("url") String url) { try {//from w w w .jav a 2 s . co m String gitSpace = System.getProperty("git.repos"); File dir = new File(gitSpace, name); if (!dir.exists()) { throw new RpcException(ERROR_FROM_METHOD, 100, "GitService.setAddRemoteOrigin:Repo(" + name + ") not exists"); } Git git = Git.open(dir); StoredConfig config = git.getRepository().getConfig(); config.setString("remote", "origin", "url", url); config.save(); } catch (Exception e) { throw new RpcException(ERROR_FROM_METHOD, INTERNAL_SERVER_ERROR, "GitService.addRemoteOrigin:", e); } finally { } }
From source file:org.omegat.core.team.GITRemoteRepository.java
License:Open Source License
public void checkoutFullProject(String repositoryURL) throws Exception { Log.logInfoRB("GIT_START", "clone"); CloneCommand c = Git.cloneRepository(); c.setURI(repositoryURL);//from w w w. jav a 2s .c o m c.setDirectory(localDirectory); try { c.call(); } catch (InvalidRemoteException e) { FileUtil.deleteTree(localDirectory); Throwable cause = e.getCause(); if (cause != null && cause instanceof org.eclipse.jgit.errors.NoRemoteRepositoryException) { BadRepositoryException bre = new BadRepositoryException( ((org.eclipse.jgit.errors.NoRemoteRepositoryException) cause).getLocalizedMessage()); bre.initCause(e); throw bre; } throw e; } repository = Git.open(localDirectory).getRepository(); new Git(repository).submoduleInit().call(); new Git(repository).submoduleUpdate().call(); //Deal with line endings. A normalized repo has LF line endings. //OmegaT uses line endings of OS for storing tmx files. //To do auto converting, we need to change a setting: StoredConfig config = repository.getConfig(); if ("\r\n".equals(FileUtil.LINE_SEPARATOR)) { //on windows machines, convert text files to CRLF config.setBoolean("core", null, "autocrlf", true); } else { //on Linux/Mac machines (using LF), don't convert text files //but use input format, unchanged. //NB: I don't know correct setting for OS'es like MacOS <= 9, // which uses CR. Git manual only speaks about converting from/to //CRLF, so for CR, you probably don't want conversion either. config.setString("core", null, "autocrlf", "input"); } config.save(); myCredentialsProvider.saveCredentials(); Log.logInfoRB("GIT_FINISH", "clone"); }
From source file:org.omegat.core.team2.impl.GITRemoteRepository2.java
License:Open Source License
@Override public void init(RepositoryDefinition repo, File dir, ProjectTeamSettings teamSettings) throws Exception { repositoryURL = repo.getUrl();// ww w .j a v a 2s.c o m localDirectory = dir; String predefinedUser = repo.getOtherAttributes().get(new QName("gitUsername")); String predefinedPass = repo.getOtherAttributes().get(new QName("gitPassword")); String predefinedFingerprint = repo.getOtherAttributes().get(new QName("gitFingerprint")); ((GITCredentialsProvider) CredentialsProvider.getDefault()).setPredefinedCredentials(repositoryURL, predefinedUser, predefinedPass, predefinedFingerprint); ((GITCredentialsProvider) CredentialsProvider.getDefault()).setTeamSettings(teamSettings); File gitDir = new File(localDirectory, ".git"); if (gitDir.exists() && gitDir.isDirectory()) { // already cloned repository = Git.open(localDirectory).getRepository(); } else { Log.logInfoRB("GIT_START", "clone"); CloneCommand c = Git.cloneRepository(); c.setURI(repositoryURL); c.setDirectory(localDirectory); try { c.call(); } catch (InvalidRemoteException e) { if (localDirectory.exists()) { deleteDirectory(localDirectory); } Throwable cause = e.getCause(); if (cause != null && cause instanceof org.eclipse.jgit.errors.NoRemoteRepositoryException) { BadRepositoryException bre = new BadRepositoryException( ((org.eclipse.jgit.errors.NoRemoteRepositoryException) cause).getLocalizedMessage()); bre.initCause(e); throw bre; } throw e; } repository = Git.open(localDirectory).getRepository(); try (Git git = new Git(repository)) { git.submoduleInit().call(); git.submoduleUpdate().call(); } // Deal with line endings. A normalized repo has LF line endings. // OmegaT uses line endings of OS for storing tmx files. // To do auto converting, we need to change a setting: StoredConfig config = repository.getConfig(); if ("\r\n".equals(System.lineSeparator())) { // on windows machines, convert text files to CRLF config.setBoolean("core", null, "autocrlf", true); } else { // on Linux/Mac machines (using LF), don't convert text files // but use input format, unchanged. // NB: I don't know correct setting for OS'es like MacOS <= 9, // which uses CR. Git manual only speaks about converting from/to // CRLF, so for CR, you probably don't want conversion either. config.setString("core", null, "autocrlf", "input"); } config.save(); Log.logInfoRB("GIT_FINISH", "clone"); } // cleanup repository try (Git git = new Git(repository)) { git.reset().setMode(ResetType.HARD).call(); } }
From source file:org.springframework.cloud.config.server.environment.JGitEnvironmentRepositoryIntegrationTests.java
License:Apache License
/** * Tests a special use case where the remote repository has been updated with a forced * push conflicting with the local repo of the Config Server. The Config Server has to * reset hard on the new reference because a simple pull operation could result in a * conflicting local repository./*from ww w. j a va 2s . c o m*/ */ @Test public void pullDirtyRepo() throws Exception { ConfigServerTestUtils.prepareLocalRepo(); String uri = ConfigServerTestUtils.copyLocalRepo("config-copy"); // Create a remote bare repository. Repository remote = ConfigServerTestUtils.prepareBareRemote(); Git git = Git.open(ResourceUtils.getFile(uri).getAbsoluteFile()); StoredConfig config = git.getRepository().getConfig(); config.setString("remote", "origin", "url", remote.getDirectory().getAbsolutePath()); config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*"); config.save(); // Pushes the raw branch to remote repository. git.push().call(); String commitToRevertBeforePull = git.log().setMaxCount(1).call().iterator().next().getName(); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(false) .run("--spring.cloud.config.server.git.uri=" + uri); JGitEnvironmentRepository repository = this.context.getBean(JGitEnvironmentRepository.class); // Fetches the repository for the first time. SearchPathLocator.Locations locations = repository.getLocations("bar", "test", "raw"); assertEquals(locations.getVersion(), commitToRevertBeforePull); // Resets to the original commit. git.reset().setMode(ResetType.HARD).setRef("master").call(); // Generate a conflicting commit who will be forced on the origin. Path applicationFilePath = Paths.get(ResourceUtils.getFile(uri).getAbsoluteFile() + "/application.yml"); Files.write(applicationFilePath, Arrays.asList("info:", " foo: bar", "raw: false"), StandardCharsets.UTF_8, StandardOpenOption.TRUNCATE_EXISTING); git.add().addFilepattern(".").call(); git.commit().setMessage("Conflicting commit.").call(); git.push().setForce(true).call(); String conflictingCommit = git.log().setMaxCount(1).call().iterator().next().getName(); // Reset to the raw branch. git.reset().setMode(ResetType.HARD).setRef(commitToRevertBeforePull).call(); // Triggers the repository refresh. locations = repository.getLocations("bar", "test", "raw"); assertEquals(locations.getVersion(), conflictingCommit); assertTrue("Local repository is not cleaned after retrieving resources.", git.status().call().isClean()); }
From source file:org.srcdeps.core.impl.scm.JGitScm.java
License:Apache License
void fetchAndReset(BuildRequest request) throws ScmException { final Path dir = request.getProjectRootDirectory(); /* Forget local changes */ try (Git git = Git.open(dir.toFile())) { Set<String> removedFiles = git.clean().setCleanDirectories(true).call(); for (String removedFile : removedFiles) { log.debug("Srcdeps removed an unstaged file {}", removedFile); }//w ww.j av a2 s. co m git.reset().setMode(ResetType.HARD).call(); /* make sure the srcdeps-working-branch exists */ git.branchCreate().setName(SRCDEPS_WORKING_BRANCH).setForce(true).call(); git.checkout().setName(SRCDEPS_WORKING_BRANCH).call(); } catch (Exception e) { log.warn(String.format("Srcdeps could not forget local changes in [%s]", dir), e); } final SrcVersion srcVersion = request.getSrcVersion(); ScmException lastException = null; int i = 0; for (String url : request.getScmUrls()) { String useUrl = stripUriPrefix(url); log.info("Srcdeps attempting to fetch version {} from SCM URL {}", request.getSrcVersion(), useUrl); String remoteAlias = i == 0 ? "origin" : "origin" + i; try (Git git = Git.open(dir.toFile())) { StoredConfig config = git.getRepository().getConfig(); config.setString("remote", remoteAlias, "url", useUrl); config.save(); final String startPoint; final String refToFetch; FetchCommand fetch = git.fetch().setRemote(remoteAlias); switch (srcVersion.getWellKnownType()) { case branch: refToFetch = "refs/heads/" + srcVersion.getScmVersion(); fetch.setRefSpecs(new RefSpec(refToFetch)); startPoint = remoteAlias + "/" + srcVersion.getScmVersion(); break; case tag: refToFetch = "refs/tags/" + srcVersion.getScmVersion(); fetch.setRefSpecs(new RefSpec(refToFetch)); startPoint = srcVersion.getScmVersion(); break; case revision: refToFetch = null; startPoint = srcVersion.getScmVersion(); break; default: throw new IllegalStateException("Unexpected " + WellKnownType.class.getName() + " value '" + srcVersion.getWellKnownType() + "'."); } FetchResult fetchResult = fetch.call(); /* * Let's check that the desired startPoint was really fetched from the current URL. Otherwise, the * startPoint may come from an older fetch of the same repo URL (but was removed in between) or it may * come from an older fetch of another URL. These cases may introduce situations when one developer can * see a successful srcdep build (because he still has the outdated ref in his local git repo) but * another dev with exectly the same setup cannot checkout because the ref is not there in any of the * remote repos anymore. */ Collection<Ref> advertisedRefs = fetchResult.getAdvertisedRefs(); switch (srcVersion.getWellKnownType()) { case branch: case tag: assertRefFetched(advertisedRefs, refToFetch, url); break; case revision: assertRevisionFetched(git.getRepository(), advertisedRefs, srcVersion.getScmVersion(), url); break; default: throw new IllegalStateException("Unexpected " + WellKnownType.class.getName() + " value '" + srcVersion.getWellKnownType() + "'."); } git.reset().setMode(ResetType.HARD).setRef(startPoint).call(); return; } catch (ScmException e) { log.warn("Srcdeps could not checkout version {} from SCM URL {}: {}: {}", request.getSrcVersion(), useUrl, e.getClass().getName(), e.getMessage()); lastException = e; } catch (Exception e) { log.warn("Srcdeps could not checkout version {} from SCM URL {}: {}: {}", request.getSrcVersion(), useUrl, e.getClass().getName(), e.getMessage()); lastException = new ScmException(String.format("Could not checkout from URL [%s]", useUrl), e); } i++; } throw lastException; }
From source file:org.uberfire.java.nio.fs.jgit.util.JGitUtil.java
License:Apache License
public static void pushRepository(final Git git, final CredentialsProvider credentialsProvider, final String origin, boolean force) throws InvalidRemoteException { if (origin != null && !origin.isEmpty()) { try {//from w w w.j a v a 2 s . com final StoredConfig config = git.getRepository().getConfig(); config.setString("remote", "upstream", "url", origin); config.save(); } catch (final Exception ex) { throw new RuntimeException(ex); } final List<RefSpec> specs = new ArrayList<RefSpec>(); specs.add(new RefSpec("+refs/heads/*:refs/remotes/upstream/*")); specs.add(new RefSpec("+refs/tags/*:refs/tags/*")); specs.add(new RefSpec("+refs/notes/*:refs/notes/*")); try { git.push().setCredentialsProvider(credentialsProvider).setRefSpecs(specs).setRemote(origin) .setForce(force).setPushAll().call(); } catch (final InvalidRemoteException e) { throw e; } catch (final Exception ex) { throw new RuntimeException(ex); } } }
From source file:org.wandora.application.tools.git.AbstractGitTool.java
License:Open Source License
public void setGitRemoteUrl(String remoteUrl) { try {//from w w w.ja v a 2 s .c om StoredConfig config = getGit().getRepository().getConfig(); config.setString("remote", "origin", "url", remoteUrl); config.save(); } catch (Exception e) { } }
From source file:org.wso2.carbon.deployment.synchronizer.git.util.GitUtilities.java
License:Open Source License
/** * Adds the remote repository at remoteUrl to the given local repository * * @param repository Repository instance representing local repo * @param remoteUrl remote repository url * @return true if remote successfully added, else false *//*from w w w.j a va2 s . c o m*/ public static boolean addRemote(Repository repository, String remoteUrl) { boolean remoteAdded = false; StoredConfig config = repository.getConfig(); config.setString(GitDeploymentSynchronizerConstants.REMOTE, GitDeploymentSynchronizerConstants.ORIGIN, GitDeploymentSynchronizerConstants.URL, remoteUrl); config.setString(GitDeploymentSynchronizerConstants.REMOTE, GitDeploymentSynchronizerConstants.ORIGIN, GitDeploymentSynchronizerConstants.FETCH, GitDeploymentSynchronizerConstants.FETCH_LOCATION); config.setString(GitDeploymentSynchronizerConstants.BRANCH, GitDeploymentSynchronizerConstants.MASTER, GitDeploymentSynchronizerConstants.REMOTE, GitDeploymentSynchronizerConstants.ORIGIN); config.setString(GitDeploymentSynchronizerConstants.BRANCH, GitDeploymentSynchronizerConstants.MASTER, GitDeploymentSynchronizerConstants.MERGE, GitDeploymentSynchronizerConstants.GIT_REFS_HEADS_MASTER); try { config.save(); remoteAdded = true; } catch (IOException e) { log.error( "Error in adding remote origin " + remoteUrl + " for local repository " + repository.toString(), e); } return remoteAdded; }
From source file:org.z2env.impl.helper.GitTools.java
License:Apache License
/** * Clones the given remote repository into the given destination folder. The method clones all branches but doesn't perform a checkout. * /*from ww w .j a v a 2s . c o m*/ * @param remoteUri URI of the remote repository * @param destFolder local destination folder * @param credentials user credentials * @return the cloned repository * @throws IOException if something went wrong */ public static Repository cloneRepository(URIish remoteUri, File destFolder, CredentialsProvider credentials, int timeout) throws IOException { // workaround for http://redmine.z2-environment.net/issues/902: // split clone into its piece in order to get the chance to set "core.autocrlf" Git gitResult; try { gitResult = Git.init().setBare(false).setDirectory(destFolder).call(); } catch (Exception e) { throw new IOException("Failed to initialize a new Git repository at " + destFolder.getAbsolutePath(), e); } Repository repo = gitResult.getRepository(); // setting "core.autocrlf=false" helps to solve http://redmine.z2-environment.net/issues/902 StoredConfig config = repo.getConfig(); config.setString(ConfigConstants.CONFIG_CORE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOCRLF, String.valueOf(false)); // add origin - clone all branches RemoteConfig remoteCfg = null; try { remoteCfg = new RemoteConfig(config, "origin"); } catch (URISyntaxException e) { throw new IOException("Failed to configure origin repository", e); } remoteCfg.addURI(remoteUri); remoteCfg.addFetchRefSpec(new RefSpec("+refs/heads/*:refs/remotes/origin/*")); remoteCfg.update(config); config.save(); // fetch all branches from origin try { gitResult.fetch().setRemote("origin").setCredentialsProvider(credentials).setTimeout(timeout).call(); } catch (Exception e) { throw new IOException("Failed to fetch from origin!", e); } return repo; }