/** * Execute git pull command on the given repository. * It populates an ArrayList with all the updated files. * @param localPath The path where the project is. * @return Returns true if you should update plugins, false otherwise. */ private boolean gitPull(File localPath) { try { Repository localRepo = new FileRepository(localPath.getAbsolutePath() + "/.git"); git = new Git(localRepo); populateDiff(); if(!pluginsToUpdate.isEmpty()){ PullCommand pullCmd = git.pull(); pullCmd.call(); return true; } else{ return false; } } catch (GitAPIException | IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } return true; }
/** * Execute git pull command on the given repository. * It populates an ArrayList with all the updated files. * @param localPath The path where the project is. * @return Returns true if you should update plugins, false otherwise. */ private boolean gitPull(File localPath) { try { Repository localRepo = new FileRepository(localPath.getAbsolutePath() + "/.git"); git = new Git(localRepo); if(populateDiff()){ PullCommand pullCmd = git.pull(); pullCmd.call(); return true; } else{ return false; } } catch (GitAPIException | IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } return true; }
public static Boolean applyBefore(final Git git) { Boolean result = Boolean.FALSE; try { PullCommand pc = git.pull().setRemote(REMOTE).setRebase(Boolean.TRUE); PullResult pullRes = pc.call(); RebaseResult rr = pullRes.getRebaseResult(); if (rr.getStatus().equals(RebaseResult.Status.UP_TO_DATE) || rr.getStatus().equals(RebaseResult.Status.FAST_FORWARD)) { result = Boolean.TRUE; } if (rr.getStatus().equals(RebaseResult.Status.UNCOMMITTED_CHANGES)) { PullResult pr = git.pull().call(); if (pr.isSuccessful()) { result = Boolean.TRUE; } else { result = Boolean.FALSE; } } } catch (Exception e) { logger.error(e.getMessage()); } return result; }
@Override public void doExecute() { try { PullCommand pullCommand = git.pull().setRebase(rebase); if (getProgressMonitor() != null) { pullCommand.setProgressMonitor(getProgressMonitor()); } setupCredentials(pullCommand); PullResult pullResult = pullCommand.call(); if (!pullResult.isSuccessful()) { FetchResult fetchResult = pullResult.getFetchResult(); GitTaskUtils.validateTrackingRefUpdates(MESSAGE_PULLED_FAILED, fetchResult.getTrackingRefUpdates()); MergeStatus mergeStatus = pullResult.getMergeResult().getMergeStatus(); if (!mergeStatus.isSuccessful()) { throw new BuildException(String.format(MESSAGE_PULLED_FAILED_WITH_STATUS, mergeStatus.name())); } } } catch (Exception e) { throw new GitBuildException(String.format(MESSAGE_PULLED_FAILED_WITH_URI, getUri()), e); } }
@Override public void pull(String branch, ProgressMonitor monitor) throws GitException { try (Git git = gitOpen()) { PullCommand pullCommand = pullCommand(branch, git); if (monitor != null) { pullCommand.setProgressMonitor(monitor); } else { pullCommand.setProgressMonitor(new DebugProgressMonitor()); } pullCommand.call(); } catch (Throwable e) { throw new GitException("Fail to pull with specific files: " + ExceptionUtil.findRootCause(e).getMessage()); } }
protected void doPull(Git git, GitContext context) throws GitAPIException { StopWatch watch = new StopWatch(); LOG.info("Performing a pull in git repository " + this.gitFolder + " on remote URL: " + this.remoteRepository); CredentialsProvider cp = userDetails.createCredentialsProvider(); PullCommand command = git.pull(); configureCommand(command, userDetails); command.setCredentialsProvider(cp).setRebase(true).call(); LOG.info("Took " + watch.taken() + " to complete pull in git repository " + this.gitFolder + " on remote URL: " + this.remoteRepository); }
/** * Pulls from the given repository and merges changes from the given remote branch into * the local checked-out branch using the given strategy. Progress is reported via the {@code monitor}. * @param git the git repository * @param strategy the merge strategy: * @param remoteName the name of the repository * @param branchName the name of the remote branch * @param monitor reports the progress of the pull * @return result of the pull * @throws GitAPIException */ public static PullResult pullWithMerge(Git git, MergeStrategy strategy, String remoteName, String branchName, ProgressMonitor monitor) throws GitAPIException { PullCommand pull = git.pull(); if (monitor != null) { pull.setProgressMonitor(monitor); } return pull .setStrategy(strategy) .setRemote(remoteName) // value -> current branch config -> DEFAULT_REMOTE_NAME = "origin" .setRemoteBranchName(branchName) // value -> current branch config -> current branch name .call(); }
/** * Pulls from the given repository and rebases the currently checked-out branch onto the given remote branch * and includes a report on the progress of the pull. * @param git the git repository * @param remoteName the name of the remote repository * @param branchName the name of the branch on which to rebase the current branch * @param monitor reports the progress of the pull * @return result of the pull * @throws GitAPIException */ public static PullResult pullWithRebase(Git git, String remoteName, String branchName, ProgressMonitor monitor) throws GitAPIException { PullCommand pull = git.pull(); if (monitor != null) { pull.setProgressMonitor(monitor); } return pull .setRebase(true) // when true, ignores merge strategy .setRemote(remoteName) // value -> current branch config -> DEFAULT_REMOTE_NAME = "origin" .setRemoteBranchName(branchName) // value -> current branch config -> current branch name .setProgressMonitor(monitor) .call(); }
protected void doPull(File gitFolder, CredentialsProvider cp, String branch, PersonIdent personIdent, UserDetails userDetails) { try { FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repository = builder.setGitDir(gitFolder) .readEnvironment() // scan environment GIT_* variables .findGitDir() // scan up the file system tree .build(); Git git = new Git(repository); File projectFolder = repository.getDirectory(); StoredConfig config = repository.getConfig(); String url = config.getString("remote", userDetails.getRemote(), "url"); if (Strings.isNullOrBlank(url)) { LOG.warn("No remote repository url for " + branch + " defined for the git repository at " + projectFolder.getCanonicalPath() + " so cannot pull"); //return; } String mergeUrl = config.getString("branch", branch, "merge"); if (Strings.isNullOrBlank(mergeUrl)) { LOG.warn("No merge spec for branch." + branch + ".merge in the git repository at " + projectFolder.getCanonicalPath() + " so not doing a pull"); //return; } LOG.debug("Performing a pull in git repository " + projectFolder.getCanonicalPath() + " on remote URL: " + url); PullCommand pull = git.pull(); GitHelpers.configureCommand(pull, userDetails); pull.setRebase(true).call(); } catch (Throwable e) { LOG.error("Failed to pull from the remote git repo with credentials " + cp + " due: " + e.getMessage() + ". This exception is ignored.", e); } }
@Override public void execute() { if (this.provider != null) { ((PullCommand) this.command).setCredentialsProvider(this.provider); } new GitAsyncTask(callingActivity, true, false, this).execute(this.command); }
public void initWithCredentials(File repoDir, String url, Optional<CredentialsProvider> credentialsProvider) throws Exception { this.credentialsProvider = credentialsProvider; try { repository = Git.open(repoDir); PullCommand pullCmd = repository.pull(); credentialsProvider.ifPresent(c -> pullCmd.setCredentialsProvider(c)); pullCmd.call(); } catch (IOException ex) { // failed to open, so we clone it anew CloneCommand cloneCmd = Git.cloneRepository(); credentialsProvider.ifPresent(c -> cloneCmd.setCredentialsProvider(c)); repository = cloneCmd.setDirectory(repoDir).setURI(url).call(); } }
@Override protected Long doInBackground(GitCommand<?>... params) { GitCommand<?> command = params[0]; Utils.announceSyncStart(context, projectName); if(command instanceof CloneCommand) { ((CloneCommand)command).setProgressMonitor(monitor); status = "Cloning"; } else if(command instanceof PullCommand) { ((PullCommand)command).setProgressMonitor(monitor); status = "Pulling"; } else { throw new IllegalArgumentException( "Coudln't attach progressMonitor to git command"); } publishProgress(-1); try { command.call(); } catch (Exception e) { status = e.getLocalizedMessage(); publishProgress(100); } return 0L; }
public void pullGitUpdate ( String scmUserid, String encodedPass, File sourceLocation, Writer outputWriter ) throws Exception { String message = "\n\n *** Updating existing branch on git repository: " + sourceLocation.getAbsolutePath() + "\n Optional: use service clean to delete build location to force a new clone on new branch to be created."; logger.info( "{}", message ); outputWriter.append( "\n" + message ); outputWriter.flush(); FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder(); repositoryBuilder.findGitDir( sourceLocation ); File gitLocation = repositoryBuilder.getGitDir(); ObjectId oldHead = null; try (Repository repository = repositoryBuilder.setWorkTree( gitLocation ).build()) { oldHead = repository.resolve( "HEAD^{tree}" ); } try (Git git = Git.open( gitLocation )) { // FetchCommand fetchCommand = git.fetch(); PullCommand pullCommand = git.pull(); if ( scmUserid.length() > 0 ) { pullCommand.setCredentialsProvider( new UsernamePasswordCredentialsProvider( scmUserid, encryptor.decrypt( encodedPass ) ) ); } pullCommand.setProgressMonitor( gitMonitor( outputWriter ) ); PullResult result = pullCommand.call(); logger.info( "merge results: {}", result.getMergeResult() ); outputWriter.append( "\n" + result.getMergeResult() + "\n\n Updated files:" ); outputWriter.flush(); printGitModifications( gitLocation, outputWriter, repositoryBuilder, oldHead, git ); // ResetCommand command = git.reset() ; // command.setP // command.setMode( ResetType.HARD ).call() ; } // catch (Exception e) { // logger.error( "Failed to complete pull and diff of repository: {}", // csapApp.getCsapFilteredStackTrace( e ) ); // isSuccessful = false; // } logger.info( "git sync complete" ); outputWriter.append( "\n\n ================= git sync complete =============\n\n" ); outputWriter.flush(); return; }
private PullCommand pullCommand(String branch, Git git) { if (Strings.isNullOrEmpty(branch)) { return buildCommand(git.pull()); } return buildCommand(git.pull().setRemoteBranchName(branch)).setTimeout(GIT_TRANS_TIMEOUT); }
@Override public void execute(Wandora wandora, Context context) { try { Git git = getGit(); if(git != null) { if(isNotEmpty(getGitRemoteUrl())) { PullCommand pull = git.pull(); String user = getUsername(); if(user == null) { if(pullUI == null) { pullUI = new PullUI(); } pullUI.setUsername(getUsername()); pullUI.setPassword(getPassword()); pullUI.setRemoteUrl(getGitRemoteUrl()); pullUI.openInDialog(); if(pullUI.wasAccepted()) { setUsername(pullUI.getUsername()); setPassword(pullUI.getPassword()); // setGitRemoteUrl(pullUI.getRemoteUrl()); // pull.setRemote(pullUI.getRemoteUrl()); if(isNotEmpty(getUsername())) { CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider( getUsername(), getPassword() ); pull.setCredentialsProvider(credentialsProvider); } } else { return; } } setDefaultLogger(); setLogTitle("Git pull"); log("Pulling changes from remote repository..."); PullResult result = pull.call(); FetchResult fetchResult = result.getFetchResult(); MergeResult mergeResult = result.getMergeResult(); MergeStatus mergeStatus = mergeResult.getMergeStatus(); String fetchResultMessages = fetchResult.getMessages(); if(isNotEmpty(fetchResultMessages)) { log(fetchResult.getMessages()); } log(mergeStatus.toString()); if(mergeStatus.equals(MergeStatus.MERGED)) { int a = WandoraOptionPane.showConfirmDialog(wandora, "Reload Wandora project after pull?", "Reload Wandora project after pull?", WandoraOptionPane.YES_NO_OPTION); if(a == WandoraOptionPane.YES_OPTION) { reloadWandoraProject(); } } log("Ready."); } else { log("Repository has no remote origin and can't be pulled. " + "Initialize repository by cloning remote repository to set the remote origin."); } } else { logAboutMissingGitRepository(); } } catch(GitAPIException gae) { log(gae.toString()); } catch(NoWorkTreeException nwte) { log(nwte.toString()); } catch(Exception e) { log(e); } setState(WAIT); }
@Test public void buildWithPullRebaseUberfireTest() throws Exception { //Setup origin in memory final URI originRepo = URI.create("git://repo"); final JGitFileSystem origin = (JGitFileSystem) ioService.newFileSystem(originRepo, new HashMap<String, Object>() {{ put("init", Boolean.TRUE); put("internal", Boolean.TRUE); put("listMode", "ALL"); }}); ioService.startBatch(origin); ioService.write(origin.getPath("/dummy/pom.xml"), new String(java.nio.file.Files.readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/pom.xml").toPath()))); ioService.write(origin.getPath("/dummy/dummyA/src/main/java/dummy/DummyA.java"), new String(java.nio.file.Files.readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/dummyA/src/main/java/dummy/DummyA.java").toPath()))); ioService.write(origin.getPath("/dummy/dummyB/src/main/java/dummy/DummyB.java"), new String(java.nio.file.Files.readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/dummyB/src/main/java/dummy/DummyB.java").toPath()))); ioService.write(origin.getPath("/dummy/dummyA/pom.xml"), new String(java.nio.file.Files.readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/dummyA/pom.xml").toPath()))); ioService.write(origin.getPath("/dummy/dummyB/pom.xml"), new String(java.nio.file.Files.readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/dummyB/pom.xml").toPath()))); ioService.endBatch(); // clone into a regularfs Path tmpRootCloned = Files.createTempDirectory("cloned"); Path tmpCloned = Files.createDirectories(Paths.get(tmpRootCloned.toString(), ".clone")); final Git cloned = Git.cloneRepository().setURI("git://localhost:9418/repo").setBare(false).setDirectory(tmpCloned.toFile()).call(); assertNotNull(cloned); PullCommand pc = cloned.pull().setRemote("origin").setRebase(Boolean.TRUE); PullResult pullRes = pc.call(); assertTrue(pullRes.getRebaseResult().getStatus().equals(RebaseResult.Status.UP_TO_DATE));// nothing changed yet RebaseCommand rb = cloned.rebase().setUpstream("origin/master"); RebaseResult rbResult = rb.setPreserveMerges(true).call(); assertTrue(rbResult.getStatus().isSuccessful()); //Compile the repo AFCompiler compiler = MavenCompilerFactory.getCompiler(Decorator.LOG_OUTPUT_AFTER); byte[] encoded = Files.readAllBytes(Paths.get(tmpCloned + "/dummy/pom.xml")); String pomAsAstring = new String(encoded, StandardCharsets.UTF_8); Assert.assertFalse(pomAsAstring.contains("<artifactId>takari-lifecycle-plugin</artifactId>")); Path prjFolder = Paths.get(tmpCloned + "/dummy/"); WorkspaceCompilationInfo info = new WorkspaceCompilationInfo(prjFolder); CompilationRequest req = new DefaultCompilationRequest(mavenRepo.toAbsolutePath().toString(), info, new String[]{MavenCLIArgs.CLEAN, MavenCLIArgs.COMPILE}, new HashMap<>(), Boolean.TRUE); CompilationResponse res = compiler.compileSync(req); if (res.getMavenOutput().isPresent() && !res.isSuccessful()) { TestUtil.writeMavenOutputIntoTargetFolder(res.getMavenOutput().get(), "KieDefaultMavenCompilerOnInMemoryFSTest.buildWithPullRebaseUberfireTest"); } assertTrue(res.isSuccessful()); Path incrementalConfiguration = Paths.get(prjFolder + "/target/incremental/io.takari.maven.plugins_takari-lifecycle-plugin_compile_compile"); assertTrue(incrementalConfiguration.toFile().exists()); encoded = Files.readAllBytes(Paths.get(prjFolder + "/pom.xml")); pomAsAstring = new String(encoded, StandardCharsets.UTF_8); assertTrue(pomAsAstring.contains("<artifactId>takari-lifecycle-plugin</artifactId>")); TestUtil.rm(tmpRootCloned.toFile()); }
@Test public void buildWithPullRebaseUberfireTest() throws Exception { //Setup origin in memory final URI originRepo = URI.create("git://repo"); final JGitFileSystem origin = (JGitFileSystem) ioService.newFileSystem(originRepo, new HashMap<String, Object>() {{ put("init", Boolean.TRUE); put("internal", Boolean.TRUE); put("listMode", "ALL"); }}); ioService.startBatch(origin); ioService.write(origin.getPath("/dummy/pom.xml"), new String(java.nio.file.Files.readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/pom.xml").toPath()))); ioService.write(origin.getPath("/dummy/dummyA/src/main/java/dummy/DummyA.java"), new String(java.nio.file.Files.readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/dummyA/src/main/java/dummy/DummyA.java").toPath()))); ioService.write(origin.getPath("/dummy/dummyB/src/main/java/dummy/DummyB.java"), new String(java.nio.file.Files.readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/dummyB/src/main/java/dummy/DummyB.java").toPath()))); ioService.write(origin.getPath("/dummy/dummyA/pom.xml"), new String(java.nio.file.Files.readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/dummyA/pom.xml").toPath()))); ioService.write(origin.getPath("/dummy/dummyB/pom.xml"), new String(java.nio.file.Files.readAllBytes(new File("src/test/projects/dummy_multimodule_untouched/dummyB/pom.xml").toPath()))); ioService.endBatch(); // clone into a regularfs Path tmpRootCloned = Files.createTempDirectory("cloned"); Path tmpCloned = Files.createDirectories(Paths.get(tmpRootCloned.toString(), ".clone")); final Git cloned = Git.cloneRepository().setURI("git://localhost:9418/repo").setBare(false).setDirectory(tmpCloned.toFile()).call(); assertNotNull(cloned); PullCommand pc = cloned.pull().setRemote("origin").setRebase(Boolean.TRUE); PullResult pullRes = pc.call(); assertTrue(pullRes.getRebaseResult().getStatus().equals(RebaseResult.Status.UP_TO_DATE));// nothing changed yet RebaseCommand rb = cloned.rebase().setUpstream("origin/master"); RebaseResult rbResult = rb.setPreserveMerges(true).call(); assertTrue(rbResult.getStatus().isSuccessful()); //Compile the repo AFCompiler compiler = KieMavenCompilerFactory.getCompiler(KieDecorator.LOG_OUTPUT_AFTER); byte[] encoded = Files.readAllBytes(Paths.get(tmpCloned + "/dummy/pom.xml")); String pomAsAstring = new String(encoded, StandardCharsets.UTF_8); Assert.assertFalse(pomAsAstring.contains("<artifactId>takari-lifecycle-plugin</artifactId>")); Path prjFolder = Paths.get(tmpCloned + "/dummy/"); WorkspaceCompilationInfo info = new WorkspaceCompilationInfo(prjFolder); CompilationRequest req = new DefaultCompilationRequest(mavenRepo.toAbsolutePath().toString(), info, new String[]{MavenCLIArgs.CLEAN, MavenCLIArgs.COMPILE}, new HashMap<>(), Boolean.TRUE); CompilationResponse res = compiler.compileSync(req); if (res.getMavenOutput().isPresent() && !res.isSuccessful()) { TestUtil.writeMavenOutputIntoTargetFolder(res.getMavenOutput().get(), "KieDefaultMavenCompilerTest.buildWithPullRebaseUberfireTest"); } assertTrue(res.isSuccessful()); Path incrementalConfiguration = Paths.get(prjFolder + "/target/incremental/io.takari.maven.plugins_takari-lifecycle-plugin_compile_compile"); assertTrue(incrementalConfiguration.toFile().exists()); encoded = Files.readAllBytes(Paths.get(prjFolder + "/pom.xml")); pomAsAstring = new String(encoded, StandardCharsets.UTF_8); assertTrue(pomAsAstring.contains("<artifactId>takari-lifecycle-plugin</artifactId>")); TestUtil.rm(tmpRootCloned.toFile()); }