List of usage examples for org.eclipse.jgit.api Git branchCreate
public CreateBranchCommand branchCreate()
From source file:io.fabric8.itests.basic.git.GitUtils.java
License:Apache License
public static void checkoutBranch(Git git, CredentialsProvider credentialsProvider, String remote, String branch) throws GitAPIException { String current = currentBranch(git); if (Objects.equal(current, branch)) { return;//from w w w . j a va 2 s . c o m } boolean localExists = localBranchExists(git, branch); boolean remoteExists = remoteBranchExists(git, remote, branch); if (localExists) { git.checkout().setName(branch).call(); } else if (remoteExists) { git.checkout().setName(branch).setCreateBranch(true).setForce(true) .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK) .setStartPoint(remote + "/" + branch).call(); } else { git.branchCreate().setName(branch).setForce(true).call(); git.checkout().setName(branch).call(); git.push().setCredentialsProvider(credentialsProvider).setRemote(remote) .setRefSpecs(new RefSpec(branch)).setForce(true).call(); } configureBranch(git, remote, getRemote(git, remote), branch); }
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); }//www . ja va 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.hawt.git.GitFacadeSupport.java
License:Apache License
protected void doCreateBranch(Git git, String fromBranch, String newBranch) throws GitAPIException { checkoutBranch(git, fromBranch);/* w ww.j ava 2s . co m*/ git.branchCreate().setName(newBranch).call(); checkoutBranch(git, newBranch); }
From source file:models.PullRequestTest.java
License:Apache License
@Before public void initRepositories() throws Exception { GitRepository.setRepoPrefix(REPO_PREFIX); app = support.Helpers.makeTestApplication(); Helpers.start(app);/*w w w. j a v a2 s . c o m*/ Project project = Project.findByOwnerAndProjectName("yobi", "projectYobi"); forkedProject = Project.findByOwnerAndProjectName("yobi", "projectYobi-1"); // 1. projectYobi RepositoryService.createRepository(project); // 2. projectYobi ? { String localRepoPath = LOCAL_REPO_PREFIX + project.name; Git git = Git.cloneRepository().setURI(GitRepository.getGitDirectoryURL(project)) .setDirectory(new File(localRepoPath)).call(); Repository repo = git.getRepository(); baseCommit = support.Git.commit(repo, "test.txt", "apple\nbanana\ncat\n", "commit 1"); git.push().setRefSpecs(new RefSpec("+refs/heads/master:refs/heads/master")).call(); } // 3. ??? ? ?? GitRepository.cloneLocalRepository(project, forkedProject); // 4. ??? ? ? ? ? { String localRepoPath = LOCAL_REPO_PREFIX + forkedProject.name; Git git = Git.cloneRepository().setURI(GitRepository.getGitDirectoryURL(forkedProject)) .setDirectory(new File(localRepoPath)).call(); git.branchCreate().setName("fix/1").call(); git.checkout().setName("fix/1").call(); Repository repo = git.getRepository(); assertThat(repo.isBare()).describedAs("projectYobi-1 must be non-bare").isFalse(); firstCommit = support.Git.commit(repo, "test.txt", "apple\nbanana\ncorn\n", "commit 1"); secondCommit = support.Git.commit(repo, "test.txt", "apple\nbanana\ncake\n", "commit 2"); git.push().setRefSpecs(new RefSpec("+refs/heads/fix/1:refs/heads/fix/1")).call(); } // 5. projectYobi? pullrequest . pullRequest = PullRequest.createNewPullRequest(forkedProject, project, "refs/heads/fix/1", "refs/heads/master"); pullRequest.save(); // 6. attempt merge boolean isConflict = pullRequest.updateMerge().conflicts(); assertThat(isConflict).isFalse(); }
From source file:org.apache.maven.scm.provider.git.jgit.command.branch.JGitBranchCommand.java
License:Apache License
/** * {@inheritDoc}//from w ww.ja v a 2s. com */ @Override protected ScmResult executeBranchCommand(ScmProviderRepository repo, ScmFileSet fileSet, String branch, String message) throws ScmException { if (branch == null || StringUtils.isEmpty(branch.trim())) { throw new ScmException("branch name must be specified"); } if (!fileSet.getFileList().isEmpty()) { throw new ScmException("This provider doesn't support branching subsets of a directory"); } Git git = null; try { git = Git.open(fileSet.getBasedir()); Ref branchResult = git.branchCreate().setName(branch).call(); getLogger().info("created [" + branchResult.getName() + "]"); if (getLogger().isDebugEnabled()) { for (String branchName : getShortLocalBranchNames(git)) { getLogger().debug("local branch available: " + branchName); } } if (repo.isPushChanges()) { getLogger().info("push branch [" + branch + "] to remote..."); JGitUtils.push(getLogger(), git, (GitScmProviderRepository) repo, new RefSpec(Constants.R_HEADS + branch)); } // search for the tagged files final RevWalk revWalk = new RevWalk(git.getRepository()); RevCommit commit = revWalk.parseCommit(branchResult.getObjectId()); revWalk.release(); final TreeWalk walk = new TreeWalk(git.getRepository()); walk.reset(); // drop the first empty tree, which we do not need here walk.setRecursive(true); walk.addTree(commit.getTree()); List<ScmFile> files = new ArrayList<ScmFile>(); while (walk.next()) { files.add(new ScmFile(walk.getPathString(), ScmFileStatus.CHECKED_OUT)); } walk.release(); return new BranchScmResult("JGit branch", files); } catch (Exception e) { throw new ScmException("JGit branch failed!", e); } finally { JGitUtils.closeRepo(git); } }
From source file:org.basinmc.maven.plugins.minecraft.patch.InitializeRepositoryMojo.java
License:Apache License
/** * Initializes the local repository with its default state. */// www . j av a 2 s . c o m private void initializeRepository() throws ArtifactResolutionException, MojoFailureException { final Path sourceArtifact; { Artifact a = this.createArtifactWithClassifier(MINECRAFT_GROUP_ID, this.getModule(), this.getMappingArtifactVersion(), "source"); sourceArtifact = this.findArtifact(a).orElseThrow(() -> new MojoFailureException( "Could not locate artifact " + this.getArtifactCoordinateString(a))); } try { Files.createDirectories(this.getSourceDirectory().toPath()); Git git = Git.init().setDirectory(this.getSourceDirectory()).call(); AccessTransformationMap transformationMap = null; Formatter formatter = null; if (this.getAccessTransformation() != null) { transformationMap = AccessTransformationMap.read(this.getAccessTransformation().toPath()); formatter = new Formatter(); } try (ZipFile file = new ZipFile(sourceArtifact.toFile())) { Enumeration<? extends ZipEntry> enumeration = file.entries(); while (enumeration.hasMoreElements()) { ZipEntry entry = enumeration.nextElement(); String name = entry.getName(); if (!name.endsWith(".java")) { continue; } Path outputPath = this.getSourceDirectory().toPath().resolve(name); if (!Files.isDirectory(outputPath.getParent())) { Files.createDirectories(outputPath.getParent()); } try (InputStream inputStream = file.getInputStream(entry)) { try (FileChannel outputChannel = FileChannel.open(outputPath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) { if (transformationMap != null && transformationMap.getTypeMappings(name).isPresent()) { JavaClassSource classSource = Roaster.parse(JavaClassSource.class, inputStream); this.applyAccessTransformation(transformationMap, classSource); outputChannel.write(ByteBuffer.wrap(formatter.formatSource(classSource.toString()) .getBytes(StandardCharsets.UTF_8))); } else { try (ReadableByteChannel channel = Channels.newChannel(inputStream)) { ByteStreams.copy(channel, outputChannel); } } } } git.add().addFilepattern(name).call(); } } git.commit().setAuthor(ROOT_COMMIT_AUTHOR_NAME, ROOT_COMMIT_AUTHOR_EMAIL) .setCommitter(ROOT_COMMIT_AUTHOR_NAME, ROOT_COMMIT_AUTHOR_EMAIL) .setMessage("Added decompiled sources.").call(); git.branchCreate().setName("upstream").call(); } catch (FormatterException ex) { throw new MojoFailureException("Failed to format one or more source files: " + ex.getMessage(), ex); } catch (GitAPIException ex) { throw new MojoFailureException("Failed to execute Git command: " + ex.getMessage(), ex); } catch (IOException ex) { throw new MojoFailureException( "Failed to access source artifact or write target file: " + ex.getMessage(), ex); } }
From source file:org.eclipse.egit.core.op.CreateLocalBranchOperation.java
License:Open Source License
public void execute(IProgressMonitor m) throws CoreException { IProgressMonitor monitor;// w ww . j a v a2s . co m if (m == null) monitor = new NullProgressMonitor(); else monitor = m; IWorkspaceRunnable action = new IWorkspaceRunnable() { public void run(IProgressMonitor actMonitor) throws CoreException { String taskName = NLS.bind(CoreText.CreateLocalBranchOperation_CreatingBranchMessage, name); actMonitor.beginTask(taskName, 1); Git git = new Git(repository); try { if (ref != null) git.branchCreate().setName(name).setStartPoint(ref.getName()) .setUpstreamMode(SetupUpstreamMode.TRACK).call(); else git.branchCreate().setName(name).setStartPoint(commit) .setUpstreamMode(SetupUpstreamMode.NOTRACK).call(); } catch (Exception e) { throw new CoreException(Activator.error(e.getMessage(), e)); } actMonitor.worked(1); actMonitor.done(); } }; // lock workspace to protect working tree changes ResourcesPlugin.getWorkspace().run(action, monitor); }
From source file:org.eclipse.egit.core.synchronize.dto.GitSynchronizeDataTest.java
License:Open Source License
@Test public void shouldReturnSourceMergeForSymbolicRef() throws Exception { // given// ww w .j a v a 2 s. c o m Git git = new Git(repo); git.branchCreate().setName("test").setStartPoint("refs/heads/master") .setUpstreamMode(SetupUpstreamMode.TRACK).call(); git.checkout().setName("test").call(); GitSynchronizeData gsd = new GitSynchronizeData(repo, HEAD, HEAD, false); // when String srcMerge = gsd.getSrcMerge(); // then assertThat(srcMerge, is("refs/heads/master")); }
From source file:org.eclipse.egit.core.synchronize.dto.GitSynchronizeDataTest.java
License:Open Source License
@Test public void shouldReturnSourceMergeForLocalRef() throws Exception { // given/*from w ww . java 2s.c o m*/ Git git = new Git(repo); git.branchCreate().setName("test2").setStartPoint("refs/heads/master") .setUpstreamMode(SetupUpstreamMode.TRACK).call(); git.checkout().setName("test2").call(); GitSynchronizeData gsd = new GitSynchronizeData(repo, R_HEADS + "test2", HEAD, false); // when String srcMerge = gsd.getSrcMerge(); // then assertThat(srcMerge, is("refs/heads/master")); }
From source file:org.eclipse.egit.core.synchronize.dto.GitSynchronizeDataTest.java
License:Open Source License
@Test public void shouldReturnSourceMergeForRemoteBranch() throws Exception { // given//w w w. j a v a 2 s .c o m Git git = new Git(repo); git.branchCreate().setName("test3").setStartPoint("refs/heads/master") .setUpstreamMode(SetupUpstreamMode.TRACK).call(); git.checkout().setName("test3").call(); repo.renameRef(R_HEADS + "test3", Constants.R_REMOTES + "origin/master").rename(); GitSynchronizeData gsd = new GitSynchronizeData(repo, "refs/remotes/origin/master", HEAD, false); // when String srcMerge = gsd.getSrcMerge(); // then assertThat(srcMerge, is("refs/heads/master")); }