List of usage examples for org.eclipse.jgit.api Git getRepository
public Repository getRepository()
From source file:io.fabric8.itests.basic.git.GitUtils.java
License:Apache License
public static void configureBranch(Git git, String remote, String remoteUrl, String branch) { if (git != null && remoteUrl != null && !remoteUrl.isEmpty()) { Repository repository = git.getRepository(); if (repository != null) { StoredConfig config = repository.getConfig(); config.setString("remote", remote, "url", remoteUrl); config.setString("remote", remote, "fetch", "+refs/heads/*:refs/remotes/" + branch + "/*"); config.setString("branch", branch, "merge", "refs/heads/" + branch); config.setString("branch", branch, "remote", "origin"); try { config.save();/*from w w w . j a v a 2 s. c om*/ } catch (IOException e) { //Ignore } } } }
From source file:io.fabric8.itests.basic.git.GitUtils.java
License:Apache License
/** * Returns the name of the current branch. * @param git/*w w w . j a v a 2s. c o m*/ * @return */ public static String currentBranch(Git git) { try { return git.getRepository().getBranch(); } catch (IOException e) { return null; } }
From source file:io.fabric8.itests.basic.git.GitUtils.java
License:Apache License
public static String getRemote(Git git, String remote) throws GitAPIException { StoredConfig config = git.getRepository().getConfig(); return config.getString("remote", remote, "url"); }
From source file:io.fabric8.itests.smoke.embedded.RemoteGitRepositoryTest.java
License:Apache License
/** * Test that the remote repo can diverge in a non-conflicting way * We rebase local canges on to of remote changes in case of non-fast-forward pull *//*from w w w . j ava 2 s.c o m*/ @Test public void rebaseOnFailedPull() throws Exception { final String versionId = "1.0"; Assert.assertFalse(profileRegistry.hasProfile(versionId, "prfE")); Assert.assertFalse(profileRegistry.hasProfile(versionId, "prfF")); checkoutRequiredBranch(versionId); RevCommit head = CommitUtils.getHead(git.getRepository()); ProfileBuilder pbuilder = ProfileBuilder.Factory.create(versionId, "prfE"); profileRegistry.createProfile(pbuilder.getProfile()); Assert.assertTrue(remoteProfileExists("1.0", "prfE")); // Remove the last commit from the remote repository git.reset().setMode(ResetType.HARD).setRef(head.getName()).call(); Assert.assertFalse(remoteProfileExists("1.0", "prfE")); createProfileRemote(versionId, "prfF", null); Assert.assertTrue(remoteProfileExists("1.0", "prfF")); GitOperation<Profile> gitop = new GitOperation<Profile>() { public Profile call(Git git, GitContext context) throws Exception { return profileRegistry.getProfile(versionId, "prfF"); } }; GitContext context = new GitContext().requirePull(); gitDataStore.gitOperation(context, gitop, null); Assert.assertTrue(profileRegistry.hasProfile(versionId, "prfE")); Assert.assertTrue(profileRegistry.hasProfile(versionId, "prfF")); profileRegistry.deleteProfile(versionId, "prfE"); profileRegistry.deleteProfile(versionId, "prfF"); Assert.assertFalse(profileRegistry.hasProfile(versionId, "prfE")); Assert.assertFalse(profileRegistry.hasProfile(versionId, "prfF")); }
From source file:io.fabric8.itests.smoke.embedded.RemoteGitRepositoryTest.java
License:Apache License
/** * Test that repomote content overrides local content in case of a conflicting pull *///from w w w. ja v a 2 s . co m @Test public void rejectOnFailedPull() throws Exception { final String versionId = "1.0"; Assert.assertFalse(profileRegistry.hasProfile(versionId, "prfG")); checkoutRequiredBranch(versionId); RevCommit head = CommitUtils.getHead(git.getRepository()); ProfileBuilder pbuilder = ProfileBuilder.Factory.create(versionId, "prfG"); profileRegistry.createProfile(pbuilder.addAttribute("foo", "aaa").getProfile()); Profile profile = profileRegistry.getRequiredProfile(versionId, "prfG"); Assert.assertEquals("aaa", profile.getAttributes().get("foo")); // Remove the last commit from the remote repository git.reset().setMode(ResetType.HARD).setRef(head.getName()).call(); Assert.assertFalse(remoteProfileExists("1.0", "prfG")); createProfileRemote(versionId, "prfG", Collections.singletonMap("foo", "bbb")); Assert.assertTrue(remoteProfileExists("1.0", "prfG")); GitOperation<Profile> gitop = new GitOperation<Profile>() { public Profile call(Git git, GitContext context) throws Exception { return profileRegistry.getProfile(versionId, "prfG"); } }; GitContext context = new GitContext().requirePull(); gitDataStore.gitOperation(context, gitop, null); Profile prfG = profileRegistry.getProfile(versionId, "prfG"); Assert.assertEquals("bbb", prfG.getAttributes().get("foo")); profileRegistry.deleteProfile(versionId, "prfG"); Assert.assertFalse(profileRegistry.hasProfile(versionId, "prfG")); }
From source file:io.fabric8.profiles.containers.GitRemoteProcessor.java
License:Apache License
@Override public void process(String name, Properties config, Path containerDir) throws IOException { // get or create remote repo URL String remoteUri = config.getProperty(GIT_REMOTE_URI_PROPERTY); if (remoteUri == null || remoteUri.isEmpty()) { remoteUri = getRemoteUri(config, name); }/*w w w .j a v a 2 s.c o m*/ // try to clone remote repo in temp dir String remote = config.getProperty(GIT_REMOTE_NAME_PROPERTY, Constants.DEFAULT_REMOTE_NAME); Path tempDirectory = null; try { tempDirectory = Files.createTempDirectory(containerDir, "cloned-remote-"); } catch (IOException e) { throwException("Error creating temp directory while cloning ", remoteUri, e); } final String userName = config.getProperty("gogsUsername"); final String password = config.getProperty("gogsPassword"); final UsernamePasswordCredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider( userName, password); Git clonedRepo = null; try { try { clonedRepo = Git.cloneRepository().setDirectory(tempDirectory.toFile()).setBranch(currentVersion) .setRemote(remote).setURI(remoteUri).setCredentialsProvider(credentialsProvider).call(); } catch (InvalidRemoteException e) { // TODO handle creating new remote repo in github, gogs, etc. using fabric8 devops connector if (e.getCause() instanceof NoRemoteRepositoryException) { final String address = "http://" + config.getProperty("gogsServiceHost", "gogs.vagrant.f8"); GitRepoClient client = new GitRepoClient(address, userName, password); CreateRepositoryDTO request = new CreateRepositoryDTO(); request.setName(name); request.setDescription("Fabric8 Profiles generated project for container " + name); RepositoryDTO repository = client.createRepository(request); // create new repo with Gogs clone URL clonedRepo = Git.init().setDirectory(tempDirectory.toFile()).call(); final RemoteAddCommand remoteAddCommand = clonedRepo.remoteAdd(); remoteAddCommand.setName(remote); try { remoteAddCommand.setUri(new URIish(repository.getCloneUrl())); } catch (URISyntaxException e1) { throwException("Error creating remote repo ", repository.getCloneUrl(), e1); } remoteAddCommand.call(); // add currentVersion branch clonedRepo.add().addFilepattern(".").call(); clonedRepo.commit().setMessage("Adding version " + currentVersion).call(); try { clonedRepo.branchRename().setNewName(currentVersion).call(); } catch (RefAlreadyExistsException ignore) { // ignore } } else { throwException("Error cloning ", remoteUri, e); } } // handle missing remote branch if (!clonedRepo.getRepository().getBranch().equals(currentVersion)) { clonedRepo.branchCreate().setName(currentVersion) .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).call(); } // move .git dir to parent and drop old source altogether // TODO things like .gitignore, etc. need to be handled, perhaps through Profiles?? Files.move(tempDirectory.resolve(".git"), containerDir.resolve(".git")); } catch (GitAPIException e) { throwException("Error cloning ", remoteUri, e); } catch (IOException e) { throwException("Error copying files from ", remoteUri, e); } finally { // close clonedRepo if (clonedRepo != null) { try { clonedRepo.close(); } catch (Exception ignored) { } } // cleanup tempDirectory try { ProfilesHelpers.deleteDirectory(tempDirectory); } catch (IOException e) { // ignore } } try (Git containerRepo = Git.open(containerDir.toFile())) { // diff with remote List<DiffEntry> diffEntries = containerRepo.diff().call(); if (!diffEntries.isEmpty()) { // add all changes containerRepo.add().addFilepattern(".").call(); // with latest Profile repo commit ID in message // TODO provide other identity properties containerRepo.commit().setMessage("Container updated for commit " + currentCommitId).call(); // push to remote containerRepo.push().setRemote(remote).setCredentialsProvider(credentialsProvider).call(); } else { LOG.debug("No changes to container" + name); } } catch (GitAPIException e) { throwException("Error processing container Git repo ", containerDir, e); } catch (IOException e) { throwException("Error reading container Git repo ", containerDir, e); } }
From source file:io.fabric8.project.support.GitUtils.java
License:Apache License
/** * Returns the remote git URL for the given branch *///ww w. j av a 2 s . co m public static String getRemoteURL(Git git, String branch) { Repository repository = git.getRepository(); return getRemoteURL(repository, branch); }
From source file:io.fabric8.vertx.maven.plugin.it.ExtraManifestInfoIT.java
License:Apache License
@Test public void testGITSCM() throws IOException, VerificationException, GitAPIException { File testDir = initProject(GIT_PROJECT_ROOT); assertThat(testDir).isDirectory();/* w ww .j a va 2s .co m*/ initVerifier(testDir); prepareProject(testDir, verifier); File gitFolder = GitUtil.findGitFolder(testDir); assertThat(testDir).isNotNull(); assertThat(testDir.getName()).endsWith("manifest-git-it"); assertThat(gitFolder).isNull(); Git git = prepareGitSCM(testDir, verifier); gitFolder = git.getRepository().getDirectory(); assertThat(gitFolder.getParentFile().getName()).isEqualTo(testDir.getName()); assertThat(git.status().call().getUntracked()).contains("pom.xml", "src/main/java/demo/SimpleVerticle.java"); //Now add and commit the file DirCache index = git.add().addFilepattern(".").call(); assertThat(index.getEntryCount()).isEqualTo(2); git.commit().setMessage("First Import").call(); runPackage(verifier); assertManifest(testDir, "git"); }
From source file:io.github.thefishlive.updater.Updater.java
License:Open Source License
public void run() { System.out.println("-------------------------"); System.out.println(gitDir.getAbsolutePath()); File updateFile = new File(basedir, "UPDATE"); Git git = null; try {//from w ww . j av a2 s . c o m if (!gitDir.exists()) { git = Git.cloneRepository().setDirectory(basedir).setURI(GitUpdater.remote) .setProgressMonitor(buildProgressMonitor()).call(); System.out.println("Repository cloned"); } else { updateFile.createNewFile(); FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repo = builder.setGitDir(gitDir).readEnvironment() // scan environment GIT_* variables .findGitDir() // scan up the file system tree .build(); git = new Git(repo); PullResult result = git.pull().setProgressMonitor(buildProgressMonitor()).call(); if (!result.isSuccessful() || result.getMergeResult().getMergeStatus().equals(MergeStatus.MERGED)) { System.out.println("Update Failed"); FileUtils.deleteDirectory(basedir); basedir.mkdir(); System.out.println("Re-cloning repository"); git = Git.cloneRepository().setDirectory(basedir).setURI(GitUpdater.remote) .setProgressMonitor(buildProgressMonitor()).call(); System.out.println("Repository cloned"); } System.out.println("State: " + result.getMergeResult().getMergeStatus()); } File configdir = new File("config"); if (configdir.exists()) { FileUtils.copyDirectory(configdir, new File(basedir, "config")); } } catch (Exception e) { e.printStackTrace(); } finally { git.getRepository().close(); } updateFile.delete(); System.out.println("-------------------------"); }
From source file:io.hawkcd.materials.materialservices.GitService.java
License:Apache License
@Override public GitMaterial fetchLatestCommit(GitMaterial gitMaterial) { try {/* w w w.j a v a 2 s.c om*/ Git git = Git.open(new File(gitMaterial.getDestination() + File.separator + ".git")); CredentialsProvider credentials = this.handleCredentials(gitMaterial); git.fetch().setCredentialsProvider(credentials).setCheckFetchedObjects(true) .setRefSpecs(new RefSpec( "refs/heads/" + gitMaterial.getBranch() + ":refs/heads/" + gitMaterial.getBranch())) .call(); ObjectId objectId = git.getRepository().getRef(gitMaterial.getBranch()).getObjectId(); RevWalk revWalk = new RevWalk(git.getRepository()); RevCommit commit = revWalk.parseCommit(objectId); gitMaterial.setCommitId(commit.getId().getName()); gitMaterial.setAuthorName(commit.getAuthorIdent().getName()); gitMaterial.setAuthorEmail(commit.getAuthorIdent().getEmailAddress()); gitMaterial.setComments(commit.getFullMessage()); gitMaterial.setErrorMessage(""); git.close(); return gitMaterial; } catch (IOException | GitAPIException e) { gitMaterial.setErrorMessage(e.getMessage()); return gitMaterial; } }