List of usage examples for org.eclipse.jgit.api Git add
public AddCommand add()
From source file:org.openengsb.connector.git.internal.GitServiceImplTest.java
License:Apache License
@Test public void removeDirectoryFromRepository_shouldReturnNewCommitRefAndDeleteFiles() throws Exception { localRepository = RepositoryFixture.createRepository(localDirectory); String dir = "testDirectory"; String file = "testFile"; File parent = new File(localDirectory, dir); parent.mkdirs();//w ww. j av a 2 s . c om File child = new File(parent, file); FileWriter fw = new FileWriter(child); fw.write(file + "\n"); fw.close(); assertThat(child.exists(), is(true)); Git git = new Git(localRepository); git.add().addFilepattern(dir + "/" + file).call(); git.commit().setMessage("comment").call(); AnyObjectId headId = localRepository.resolve(Constants.HEAD); RevWalk rw = new RevWalk(localRepository); RevCommit head = rw.parseCommit(headId); rw.release(); CommitRef ref = service.remove("remove", new File(localDirectory, dir)); assertThat(head.name(), not(ref.getStringRepresentation())); File removed = new File(localDirectory, dir + "/" + file); assertThat(removed.exists(), is(false)); }
From source file:org.openengsb.connector.git.internal.RepositoryFixture.java
License:Apache License
public static void addFile(Git git, String filename) throws IOException, NoFilepatternException { FileWriter writer = new FileWriter(new File(git.getRepository().getWorkTree(), filename)); writer.write(filename + "\n"); writer.close();/*from www. j a v a2 s. c om*/ AddCommand add = git.add(); add.addFilepattern(filename).call(); }
From source file:org.sourcepit.b2.its.util.GitSCM.java
License:Apache License
private static Git create(File repoDir) throws GitAPIException, NoFilepatternException, NoHeadException, NoMessageException, UnmergedPathsException, ConcurrentRefUpdateException, WrongRepositoryStateException { final Git git = Git.init().setDirectory(repoDir).call(); git.add().addFilepattern(".").call(); git.commit().setAll(true).setMessage("Initial commit").call(); return git;/*from w w w .j ava 2 s.co m*/ }
From source file:org.spdx.tools.LicenseListPublisher.java
License:Apache License
/** * Publish a license list to the license data git repository * @param release license list release name (must be associatd with a tag in the license-list-xml repo) * @param gitUserName github username to be used - must have commit access to the license-xml-data repo * @param gitPassword github password/* ww w . ja va2 s . c o m*/ * @throws LicensePublisherException * @throws LicenseGeneratorException */ private static void publishLicenseList(String release, String gitUserName, String gitPassword, boolean ignoreWarnings) throws LicensePublisherException, LicenseGeneratorException { CredentialsProvider githubCredentials = new UsernamePasswordCredentialsProvider(gitUserName, gitPassword); File licenseXmlDir = null; File licenseDataDir = null; Git licenseXmlGit = null; Git licenseDataGit = null; try { licenseXmlDir = Files.createTempDirectory("LicenseXML").toFile(); System.out.println("Cloning the license XML repository - this could take a while..."); licenseXmlGit = Git.cloneRepository().setCredentialsProvider(githubCredentials) .setDirectory(licenseXmlDir).setURI(LICENSE_XML_URI).call(); Ref releaseTag = licenseXmlGit.getRepository().getTags().get(release); if (releaseTag == null) { throw new LicensePublisherException( "Release " + release + " not found as a tag in the License List XML repository"); } licenseXmlGit.checkout().setName(releaseTag.getName()).call(); licenseDataDir = Files.createTempDirectory("LicenseData").toFile(); System.out.println("Cloning the license data repository - this could take a while..."); licenseDataGit = Git.cloneRepository().setCredentialsProvider(githubCredentials) .setDirectory(licenseDataDir).setURI(LICENSE_DATA_URI).call(); Ref dataReleaseTag = licenseDataGit.getRepository().getTags().get(release); boolean dataReleaseTagExists = false; if (dataReleaseTag != null) { dataReleaseTagExists = true; licenseDataGit.checkout().setName(releaseTag.getName()).call(); } cleanLicenseDataDir(licenseDataDir); String todayDate = new SimpleDateFormat("dd-MMM-yyyy").format(Calendar.getInstance().getTime()); List<String> warnings = LicenseRDFAGenerator.generateLicenseData( new File(licenseXmlDir.getPath() + File.separator + "src"), licenseDataDir, release, todayDate); if (warnings.size() > 0 && !ignoreWarnings) { throw new LicensePublisherException( "There are some skipped or invalid license input data. Publishing aborted. To ignore, add the --ignore option as the first parameter"); } licenseDataGit.add().addFilepattern(".").call(); licenseDataGit.commit().setAll(true) .setCommitter("SPDX License List Publisher", "spdx-tech@lists.spdx.org") .setMessage("License List Publisher for " + gitUserName + ". License list version " + release) .call(); if (!dataReleaseTagExists) { licenseDataGit.tag().setName(release).setMessage("SPDX License List release " + release).call(); } licenseDataGit.push().setCredentialsProvider(githubCredentials).setPushTags().call(); } catch (IOException e) { throw new LicensePublisherException("I/O Error publishing license list", e); } catch (InvalidRemoteException e) { throw new LicensePublisherException("Invalid remote error trying to access the git repositories", e); } catch (TransportException e) { throw new LicensePublisherException("Transport error trying to access the git repositories", e); } catch (GitAPIException e) { throw new LicensePublisherException("GIT API error trying to access the git repositories", e); } finally { if (licenseXmlGit != null) { licenseXmlGit.close(); } if (licenseDataGit != null) { licenseDataGit.close(); } if (licenseXmlDir != null) { deleteDir(licenseXmlDir); } if (licenseDataDir != null) { deleteDir(licenseDataDir); } } }
From source file:org.springframework.cloud.config.server.environment.JGitEnvironmentRepositoryIntegrationTests.java
License:Apache License
@Test public void pull() throws Exception { ConfigServerTestUtils.prepareLocalRepo(); String uri = ConfigServerTestUtils.copyLocalRepo("config-copy"); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(false) .run("--spring.cloud.config.server.git.uri=" + uri); EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); repository.findOne("bar", "staging", "master"); Environment environment = repository.findOne("bar", "staging", "master"); assertEquals("bar", environment.getPropertySources().get(0).getSource().get("foo")); Git git = Git.open(ResourceUtils.getFile(uri).getAbsoluteFile()); git.checkout().setName("master").call(); StreamUtils.copy("foo: foo", Charset.defaultCharset(), new FileOutputStream(ResourceUtils.getFile(uri + "/bar.properties"))); git.add().addFilepattern("bar.properties").call(); git.commit().setMessage("Updated for pull").call(); environment = repository.findOne("bar", "staging", "master"); assertEquals("foo", environment.getPropertySources().get(0).getSource().get("foo")); }
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./* www . 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.springframework.cloud.config.server.environment.JGitEnvironmentRepositoryIntegrationTests.java
License:Apache License
@Test public void findOne_FileAddedToRepo_FindOneSuccess() throws Exception { ConfigServerTestUtils.prepareLocalRepo(); String uri = ConfigServerTestUtils.copyLocalRepo("config-copy"); this.context = new SpringApplicationBuilder(TestConfiguration.class).web(false).run( "--spring.cloud.config.server.git.uri=" + uri, "--spring.cloud.config.server.git.cloneOnStart=true"); EnvironmentRepository repository = this.context.getBean(EnvironmentRepository.class); repository.findOne("bar", "staging", "master"); Environment environment = repository.findOne("bar", "staging", "master"); assertEquals("bar", environment.getPropertySources().get(0).getSource().get("foo")); Git git = Git.open(ResourceUtils.getFile(uri).getAbsoluteFile()); git.checkout().setName("master").call(); StreamUtils.copy("foo: foo", Charset.defaultCharset(), new FileOutputStream(ResourceUtils.getFile(uri + "/bar.properties"))); git.add().addFilepattern("bar.properties").call(); git.commit().setMessage("Updated for pull").call(); environment = repository.findOne("bar", "staging", "master"); assertEquals("foo", environment.getPropertySources().get(0).getSource().get("foo")); }
From source file:org.wandora.application.tools.git.Commit.java
License:Open Source License
@Override public void execute(Wandora wandora, Context context) { try {//from w ww.j a v a 2 s . com Git git = getGit(); if (git != null) { if (commitUI == null) { commitUI = new CommitUI(); } commitUI.openInDialog(); if (commitUI.wasAccepted()) { setDefaultLogger(); setLogTitle("Git commit"); log("Saving project."); saveWandoraProject(); log("Removing deleted files from local repository."); org.eclipse.jgit.api.Status status = git.status().call(); Set<String> missing = status.getMissing(); if (missing != null && !missing.isEmpty()) { for (String missingFile : missing) { git.rm().addFilepattern(missingFile).call(); } } log("Adding new files to local repository."); git.add().addFilepattern(".").call(); log("Committing changes to local repository."); String commitMessage = commitUI.getMessage(); if (commitMessage == null || commitMessage.length() == 0) { commitMessage = getDefaultCommitMessage(); log("No commit message provided. Using default message."); } git.commit().setMessage(commitMessage).call(); log("Ready."); } } else { logAboutMissingGitRepository(); } } catch (GitAPIException gae) { log(gae.toString()); } catch (NoWorkTreeException nwte) { log(nwte.toString()); } catch (IOException ioe) { log(ioe.toString()); } catch (TopicMapException tme) { log(tme.toString()); } catch (Exception e) { log(e); } setState(WAIT); }
From source file:org.wandora.application.tools.git.CommitPush.java
License:Open Source License
@Override public void execute(Wandora wandora, Context context) { try {//from w w w.j a va 2 s. c o m Git git = getGit(); if (git != null) { if (isNotEmpty(getGitRemoteUrl())) { if (commitPushUI == null) { commitPushUI = new CommitPushUI(); } commitPushUI.setPassword(getPassword()); commitPushUI.setUsername(getUsername()); commitPushUI.openInDialog(); if (commitPushUI.wasAccepted()) { setDefaultLogger(); setLogTitle("Git commit and push"); saveWandoraProject(); log("Removing deleted files from local repository."); org.eclipse.jgit.api.Status status = git.status().call(); Set<String> missing = status.getMissing(); if (missing != null && !missing.isEmpty()) { for (String missingFile : missing) { git.rm().addFilepattern(missingFile).call(); } } log("Adding new files to the local repository."); git.add().addFilepattern(".").call(); log("Committing changes to the local repository."); String commitMessage = commitPushUI.getMessage(); if (commitMessage == null || commitMessage.length() == 0) { commitMessage = getDefaultCommitMessage(); log("No commit message provided. Using default message."); } git.commit().setMessage(commitMessage).call(); String username = commitPushUI.getUsername(); String password = commitPushUI.getPassword(); setUsername(username); setPassword(password); PushCommand push = git.push(); if (isNotEmpty(username)) { log("Setting push credentials."); CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider( username, password); push.setCredentialsProvider(credentialsProvider); } log("Pushing upstream."); push.call(); log("Ready."); } } else { log("Repository has no remote origin and can't be pushed. " + "Commit changes to the local repository using Commit to local... " + "To push changes to a remote repository initialize repository by cloning."); } } else { logAboutMissingGitRepository(); } } catch (GitAPIException gae) { log(gae.toString()); } catch (NoWorkTreeException nwte) { log(nwte.toString()); } catch (IOException ioe) { log(ioe.toString()); } catch (TopicMapException tme) { log(tme.toString()); } catch (Exception e) { log(e); } setState(WAIT); }
From source file:org.webcat.core.git.GitUtilities.java
License:Open Source License
@SuppressWarnings("deprecation") public static RevCommit pushWorkingCopyImmediately(Repository workingCopy, String authorName, String emailAddress, String commitMessage) { try {// w w w .j a v a 2 s . c om boolean amend = false; GitRepository gitRepo = new GitRepository(workingCopy); GitRef ref = gitRepo.refWithName(Constants.R_HEADS + Constants.MASTER); NSArray<GitCommit> commits = ref.commits(); if (commits != null && !commits.isEmpty()) { GitCommit commit = commits.objectAtIndex(0); if (commitMessage.equals(commit.shortMessage()) && commit.commitTime().timeIntervalSinceNow() > -3 * 60 * 60) { amend = true; } } Git git = new Git(workingCopy); git.add().addFilepattern(".").setUpdate(false).call(); RevCommit commit = git.commit().setAuthor(authorName, emailAddress) .setCommitter(authorName, emailAddress).setMessage(commitMessage).setAmend(amend).call(); RefSpec allHeadsSpec = new RefSpec().setForceUpdate(true).setSourceDestination( Constants.R_HEADS + Constants.MASTER, Constants.R_HEADS + Constants.MASTER); git.push().setRefSpecs(allHeadsSpec).call(); return commit; } catch (Exception e) { log.error("Error updating repository: ", e); } return null; }