List of usage examples for org.eclipse.jgit.lib StoredConfig save
public abstract void save() throws IOException;
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();//w w w . j a v a 2s . c om 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.// w ww. j ava 2 s .co 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 .ja v a 2s.c o 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.commands.Clone.java
License:Apache License
public Optional<Git> execute() throws InvalidRemoteException { final Git git = Git.createRepository(repoDir, null); if (git != null) { final Collection<RefSpec> refSpecList; if (isMirror) { refSpecList = singletonList(new RefSpec("+refs/*:refs/*")); } else {//from ww w.j ava 2 s . com refSpecList = emptyList(); } final Pair<String, String> remote = Pair.newPair("origin", origin); git.fetch(credentialsProvider, remote, refSpecList); final StoredConfig config = git.getRepository().getConfig(); config.setBoolean("remote", "origin", "mirror", true); try { config.save(); } catch (IOException e) { throw new RuntimeException(e); } git.syncRemote(remote); if (git.isKetchEnabled()) { git.convertRefTree(); git.updateLeaders(leaders); } git.setHeadAsInitialized(); return Optional.of(git); } return Optional.empty(); }
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 {// ww w .j a va 2s . c om 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 www. j ava2 s. c o m*/ StoredConfig config = getGit().getRepository().getConfig(); config.setString("remote", "origin", "url", remoteUrl); config.save(); } catch (Exception e) { } }
From source file:org.webcat.core.git.GitCloner.java
License:Open Source License
private Repository createWorkingCopyRepositoryIfNecessary(File location, File remoteDir) throws IOException { Repository wcRepository;/* ww w. j a va2 s . c o m*/ try { wcRepository = RepositoryCache.open(FileKey.lenient(location, FS.DETECTED)); } catch (RepositoryNotFoundException e) { // Create the repository from scratch. if (!location.exists()) { location.mkdirs(); } InitCommand init = Git.init(); init.setDirectory(location); init.setBare(false); wcRepository = init.call().getRepository(); StoredConfig config = wcRepository.getConfig(); config.setBoolean("core", null, "bare", false); try { RefSpec refSpec = new RefSpec().setForceUpdate(true).setSourceDestination(Constants.R_HEADS + "*", Constants.R_REMOTES + "origin" + "/*"); RemoteConfig remoteConfig = new RemoteConfig(config, "origin"); remoteConfig.addURI(new URIish(remoteDir.toString())); remoteConfig.addFetchRefSpec(refSpec); remoteConfig.update(config); } catch (URISyntaxException e2) { // Do nothing. } config.save(); } return wcRepository; }
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 *//* w w w.j ava 2 s . co 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. * // w w w .j a va 2 s.com * @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; }
From source file:ru.nikitenkogleb.androidtools.newappwizard.GitSupport.java
/** Creates new Git Support module */ public GitSupport(String login, String password, String repository, String projectPath, String tempFolder, String initBranch) {//from w ww .j ava 2 s. co m final String home = System.getProperty("user.home"); if (login == null || login.isEmpty()) { mSshConfigCallback = new SSHConfigCallback(home + Path.SEPARATOR + ".ssh" + Path.SEPARATOR + "id_rsa", new CredentialsProvider(password)); mHttpsCredentialsProvider = null; } else { mSshConfigCallback = null; mHttpsCredentialsProvider = new UsernamePasswordCredentialsProvider(login, password); } try { final CloneCommand cloneCommand = Git.cloneRepository().setURI(repository) .setDirectory(new File(tempFolder)); if (mSshConfigCallback != null) cloneCommand.setTransportConfigCallback(mSshConfigCallback); else cloneCommand.setCredentialsProvider(mHttpsCredentialsProvider); final Git mGit = cloneCommand.call(); try { mGit.checkout().setCreateBranch(true).setName(initBranch).call(); } catch (RefNotFoundException e) { e.printStackTrace(); final StoredConfig config = mGit.getRepository().getConfig(); config.setString("remote", "origin", "url", repository); config.save(); } mGit.close(); move(new File(tempFolder + "/.git"), new File(projectPath + "/.git")); move(new File(tempFolder + "/README.md"), new File(projectPath + "/README.md")); move(new File(tempFolder + "/LICENSE"), new File(projectPath + "/LICENSE")); move(new File(tempFolder + "/.gitignore"), new File(projectPath + "/.gitignore")); new File(tempFolder).delete(); mProjectPath = projectPath; } catch (GitAPIException | IOException e) { e.printStackTrace(); } }