protected void doPull(Exchange exchange, String operation) throws Exception { PullResult result = null; try { if (ObjectHelper.isEmpty(endpoint.getRemotePath())) { throw new IllegalArgumentException("Remote path must be specified to execute " + operation); } if (ObjectHelper.isNotEmpty(endpoint.getBranchName())) { git.checkout().setCreateBranch(false).setName(endpoint.getBranchName()).call(); } if (ObjectHelper.isNotEmpty(endpoint.getUsername()) && ObjectHelper.isNotEmpty(endpoint.getPassword())) { UsernamePasswordCredentialsProvider credentials = new UsernamePasswordCredentialsProvider(endpoint.getUsername(), endpoint.getPassword()); result = git.pull().setCredentialsProvider(credentials).setRemote(endpoint.getRemotePath()).call(); } else { result = git.pull().setRemote(endpoint.getRemotePath()).call(); } } catch (Exception e) { LOG.error("There was an error in Git " + operation + " operation"); throw e; } exchange.getOut().setBody(result); }
@Test public void testPull() throws Exception { // source: db2, target: db setupRemote(); Git git2 = new Git( db2 ); // put some file in the source repo and sync File sourceFile = new File( db2.getWorkTree(), "SomeFile.txt" ); FileUtils.writeStringToFile( sourceFile, "Hello world" ); git2.add().addFilepattern( "SomeFile.txt" ).call(); git2.commit().setMessage( "Initial commit for source" ).call(); PullResult pullResult = git.pull().call(); // change the source file FileUtils.writeStringToFile( sourceFile, "Another change" ); git2.add().addFilepattern( "SomeFile.txt" ).call(); git2.commit().setMessage( "Some change in remote" ).call(); git2.close(); assertTrue( uiGit.pull() ); }
private void update(Git git) throws GitAPIException { PullResult pullResult = git.pull().setRebase(true).call(); RebaseResult rebaseResult = pullResult.getRebaseResult(); if(!pullResult.isSuccessful()) { if(rebaseResult.getStatus() == RebaseResult.Status.CONFLICTS) { logger.warn("Git `pull` reported conflicts - will reset and try again next pass!"); git.reset().setMode(ResetCommand.ResetType.HARD).call(); return; } logger.warn("Git `pull` was unsuccessful :("); return; } if(rebaseResult.getStatus() == RebaseResult.Status.UP_TO_DATE) { logger.debug("Git `pull` reported that repository is already up-to-date"); return; } logger.debug("Git repo is now at commit '{}'", rebaseResult.getCurrentCommit()); }
private static void visit( File directory ) throws IOException, RefNotFoundException, DetachedHeadException, WrongRepositoryStateException, InvalidRemoteException, InvalidConfigurationException, CanceledException { for ( final File child : directory.listFiles() ) { if ( child.isDirectory() ) { visit( child ); } final String name = child.getName(); if ( name.equals( ".git" ) ) { Thread t = new Thread( new Runnable() { public void run() { try { Git git = Git.open( child.getParentFile() ); PullResult pullResult = git.pull().call(); System.out.println( "pulled on " + child.getParentFile().getName() + ", pullResult = " + pullResult.isSuccessful() + ", " + pullResult.getFetchedFrom() + ", fetch messages: " + pullResult.getFetchResult().getMessages() ); } catch ( Exception e ) { e.printStackTrace(); } } } ); t.start(); } } }
protected Git useLocalGitRepository(Path repository) throws IOException { Git git; git = this.gitOperations.openGitRepository(repository); if (this.gitOperations.hasAtLeastOneReference(git.getRepository())) { final PullResult pullResult = executePull(git); if (!pullResult.isSuccessful()) { // Merge conflicts throw new IllegalArgumentException( "There are merge conflicts into an existing git repo. Provider should not deal with merge conflicts. Correct them or delete the repo and execute again the test."); } } else { throw new IllegalArgumentException(String.format("Git repository %s was not cloned correctly.", git.getRepository().getDirectory().getAbsolutePath())); } return git; }
private PullResult executePull(Git git) { final PullResult pullResult; if (isSet(this.contractsGit.username()) && isSet(this.contractsGit.password())) { pullResult = this.gitOperations.pullFromRepository(git, getResolvedValue(this.contractsGit.remote()), getResolvedValue(this.contractsGit.branch()), getResolvedValue(this.contractsGit.username()), getResolvedValue(this.contractsGit.password())); } else { if (isSet(this.contractsGit.passphrase())) { pullResult = this.gitOperations.pullFromRepository(git, getResolvedValue(this.contractsGit.remote()), getResolvedValue(this.contractsGit.branch()), getResolvedValue(this.contractsGit.passphrase()), getPrivateKey()); } else { pullResult = this.gitOperations.pullFromRepository(git, getResolvedValue(this.contractsGit.remote()), getResolvedValue(this.contractsGit.branch())); } } return pullResult; }
/** * Pull repository from current branch and remote branch with same name as current * * @param git * instance. * @param remote * to be used. * @param remoteBranch * to use. * @param passphrase * to access private key. * @param privateKey * file location. */ public PullResult pullFromRepository(final Git git, final String remote, String remoteBranch, final String passphrase, final Path privateKey) { SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() { @Override protected void configure(OpenSshConfig.Host host, Session session) { session.setUserInfo(new PassphraseUserInfo(passphrase)); } @Override protected JSch createDefaultJSch(FS fs) throws JSchException { if (privateKey != null) { JSch defaultJSch = super.createDefaultJSch(fs); defaultJSch.addIdentity(privateKey.toFile().getAbsolutePath()); return defaultJSch; } else { return super.createDefaultJSch(fs); } } }; try { return git.pull() .setRemote(remote) .setRemoteBranchName(remoteBranch) .setTransportConfigCallback(transport -> { SshTransport sshTransport = (SshTransport) transport; sshTransport.setSshSessionFactory(sshSessionFactory); }) .call(); } catch (GitAPIException e) { throw new IllegalStateException(e); } }
protected IStatus updateRepository(IProgressMonitor monitor) { String repoURL = getPreference(ExamplesPreferenceConstants.REMOTE_LOCATION); try { java.nio.file.Path storageLocation = getStorageLocation(); PullResult result = Git.open(storageLocation.toFile()).pull() .setProgressMonitor(new EclipseGitProgressTransformer(monitor)).call(); if (!result.isSuccessful()) { return new Status(IStatus.ERROR, ExampleActivator.PLUGIN_ID, "Unable to update repository " + repoURL + "!"); } } catch (GitAPIException | IOException e) { return new Status(IStatus.ERROR, ExampleActivator.PLUGIN_ID, "Unable to update repository " + repoURL + "!"); } return Status.OK_STATUS; }
@Override public void run() { workspaceProvider.synchronizedOperation(new Callable<Void>() { @Override public Void call() { try { final PullResult result = gitProctorCore.getGit() .pull() .setProgressMonitor(PROGRESS_MONITOR) .setRebase(true) .setCredentialsProvider(user) .setTimeout(GitProctorUtils.DEFAULT_GIT_PULL_PUSH_TIMEOUT_SECONDS) .call(); if (!result.isSuccessful()) { /** if git pull failed, use git reset **/ gitProctorCore.undoLocalChanges(); } } catch (final Exception e) { LOGGER.error("Error when refreshing git directory " + getDirectoryPath(), e); } return null; } }); }
public void refresh() { workspaceProvider.synchronizedOperation(new Callable<Void>() { @Override public Void call() { try { /** git pull is preferable since it's more efficient **/ LOGGER.debug("Started refresh with git pull"); final PullResult result = getGit().pull().setProgressMonitor(PROGRESS_MONITOR).setRebase(true).setCredentialsProvider(user).call(); if (!result.isSuccessful()) { /** if git pull failed, use git reset **/ LOGGER.info("refresh failed. Running undo local changes"); undoLocalChanges(); } LOGGER.debug("Finished refresh"); } catch (final Exception e) { LOGGER.error("Error when refreshing git directory " + workspaceProvider.getRootDirectory(), e); } return null; } }); }
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); } }
public static void main(String[] args) throws IOException, GitAPIException { try (Repository repository = cloneRepository()) { System.out.println("Having repository: " + repository.getDirectory() + " with head: " + repository.findRef(Constants.HEAD) + "/" + repository.resolve("HEAD") + "/" + repository.resolve("refs/heads/master")); // TODO: why do we get null here for HEAD?!? See also // http://stackoverflow.com/questions/17979660/jgit-pull-noheadexception try (Git git = new Git(repository)) { PullResult call = git.pull().call(); System.out.println("Pulled from the remote repository: " + call); } } }
/** * pulls the remote git repository to receive changes. */ public void pullRemoteRepo() { String method = "pullRemoteRepo"; LOGGER.info("Trying to pull remote repository..."); localGit = LocalRepoCreater.getLocalGit(); if (localGit != null) { Repository repository = localGit.getRepository(); try (Git git = new Git(repository)) { /* * Getting The Commit Information of the Remote Repository */ RevWalk walker = new RevWalk(repository); RevCommit commit = walker.parseCommit(repository.getRef("HEAD").getObjectId()); Date commitTime = commit.getAuthorIdent().getWhen(); String commiterName = commit.getAuthorIdent().getName(); String commitEmail = commit.getAuthorIdent().getEmailAddress(); String commitID = repository.getRef("HEAD").getObjectId().getName(); PullResult pullResult = git.pull().setStrategy(MergeStrategy.THEIRS).call(); LOGGER.info("Fetch result: " + pullResult.getFetchResult().getMessages()); LOGGER.info("Merge result: " + pullResult.getMergeResult().toString()); LOGGER.info("Merge status: " + pullResult.getMergeResult().getMergeStatus()); repoDiffer.checkForUpdates(git, commiterName, commitEmail, commitTime, commitID); } catch (Exception e) { LOGGER.error("In method " + method + ": Error while pulling remote git repository.", e); } localGit.close(); } else { LOGGER.warn("Repository not cloned yet"); } }
/** * Update a {@link Git} {@link Repository}. * * @param git the {@link Git} instance to update */ protected static void update(Git git) throws RouterException { PullResult pullResult; try { pullResult = git.pull().call(); // Todo: log some stuff?? } catch (GitAPIException e) { throw new RouterException("Failed to update Git repository: " + e.getMessage(), e); } }
/** * Push git changes from remote git repository * * @param git Local git repository * @param name Remote Git name * @param url Remote Git url * @return pull result * @throws WsSrvException */ public static boolean pullFromRemote(Git git, String name, String url) throws WsSrvException { checkRemoteGitConfig(name, url); try { PullResult pres = git.pull().setRemote(name).call(); return pres.isSuccessful(); } catch (GitAPIException e) { //-- 250 throw new WsSrvException(250, e, "Error pull from remote [" + name + "]"); } }
/** * 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(); }
private Git initializeGit() throws IOException, GitAPIException { if (path.isDirectory()) { Git git = Git.open(path); String current = git.getRepository().getBranch(); if (branch.equalsIgnoreCase(current)) { PullResult pull = git.pull().setRemote(remote).call(); if (!pull.isSuccessful()) { LOGGER.warn("Unable to pull the branch + '" + branch + "' from the remote repository '" + remote + "'"); } return git; } else { git.checkout(). setName(branch). setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK). setStartPoint(remote + "/" + branch). call(); return git; } } else { return Git.cloneRepository() .setURI(url) .setBranch(branch) .setRemote(remote) .setDirectory(path) .call(); } }
private Future<Void> update() { Future<Void> result = Future.future(); vertx.executeBlocking( future -> { PullResult call = null; try { call = git.pull().setRemote(remote).setRemoteBranchName(branch).call(); } catch (GitAPIException e) { future.fail(e); return; } if (call.isSuccessful()) { future.complete(); } else { if (call.getMergeResult() != null) { future.fail("Unable to merge repository - Conflicts: " + call.getMergeResult().getCheckoutConflicts()); } else { future.fail("Unable to rebase repository - Conflicts: " + call.getRebaseResult().getConflicts()); } } }, result.completer() ); return result; }
private PullResult executePull(Git git) { final PullResult pullResult; if (isSet(USERNAME, String.class, this.configuration) && isSet(PASSWORD, String.class, this.configuration)) { pullResult = this.gitOperations.pullFromRepository(git, getResolvedValue((String) this.configuration.get(REMOTE)), getResolvedValue((String) this.configuration.get(BRANCH)), getResolvedValue((String) this.configuration.get(USERNAME)), getResolvedValue((String) this.configuration.get(PASSWORD)) ); } else { if (isSet(PASSPHRASE, String.class, this.configuration)) { pullResult = this.gitOperations.pullFromRepository(git, getResolvedValue((String) this.configuration.get(REMOTE)), getResolvedValue((String) this.configuration.get(BRANCH)), getResolvedValue((String) this.configuration.get(PASSPHRASE)), getPrivateKey()); } else { pullResult = this.gitOperations.pullFromRepository(git, getResolvedValue((String) this.configuration.get(REMOTE)), getResolvedValue((String) this.configuration.get(BRANCH))); } } return pullResult; }
/** * Pull repository from current branch and remote branch with same name as current * * @param git * instance. * @param remote * to be used. * @param remoteBranch * to use. */ public PullResult pullFromRepository(Git git, String remote, String remoteBranch) { try { return git.pull() .setRemote(remote) .setRemoteBranchName(remoteBranch) .call(); } catch (GitAPIException e) { throw new IllegalStateException(e); } }
private Future<Void> update() { Future<Void> result = Future.future(); vertx.executeBlocking( future -> { PullResult call; try { call = git.pull().setRemote(remote).setRemoteBranchName(branch).call(); } catch (GitAPIException e) { future.fail(e); return; } if (call.isSuccessful()) { future.complete(); } else { if (call.getMergeResult() != null) { future.fail("Unable to merge repository - Conflicts: " + call.getMergeResult().getCheckoutConflicts()); } else { future.fail("Unable to rebase repository - Conflicts: " + call.getRebaseResult().getConflicts()); } } }, result.completer() ); return result; }
protected void synchronize() { // // Grab our working repository // Path repoPath = ((XacmlAdminUI)getUI()).getUserGitPath(); try { final Git git = Git.open(repoPath.toFile()); PullResult result = git.pull().call(); // FetchResult fetch = result.getFetchResult(); // MergeResult merge = result.getMergeResult(); // RebaseResult rebase = result.getRebaseResult(); if (result.isSuccessful()) { // // TODO add more notification // this.textAreaResults.setValue("Successful!"); } else { // // TODO // this.textAreaResults.setValue("Failed."); } } catch (IOException | GitAPIException e) { e.printStackTrace(); } this.buttonSynchronize.setCaption("Ok"); }
@SneakyThrows public boolean contemAtualizacoes() { if (caminhoLocal == null) { caminhoLocal = clonarRepositorio(criarDiretorioTemporario()); caminhoLocal.deleteOnExit(); return true; } log.debug("Atualizando repositório de cartas de serviço de {} para {}", urlRepositorio, caminhoLocal); try (Git repositorio = Git.open(caminhoLocal)) { String oldHead = repositorio.getRepository().getRef(R_HEADS + MASTER).getObjectId().getName(); PullResult result = repositorio.pull() .setProgressMonitor(new LogstashProgressMonitor(log)) .setStrategy(THEIRS) .call(); if (!result.isSuccessful()) { log.error("Erro ao atualizar repositório: {}", result); return false; } String head = repositorio.reset() .setMode(HARD) .setRef("refs/remotes/origin/master") .call() .getObjectId() .getName(); if (oldHead.equals(head)) { log.info("Repositório de cartas de serviço em {} já está na versão mais recente: {}", caminhoLocal, head); return false; } log.info("Repositório de cartas de serviço em {} atualizado da versão {} para {}", caminhoLocal, oldHead, head); return true; } }
protected void synchronize() { // // Grab our working repository // Path repoPath = ((XacmlAdminUI)getUI()).getUserGitPath(); try { final Git git = Git.open(repoPath.toFile()); PullResult result = git.pull().call(); FetchResult fetch = result.getFetchResult(); MergeResult merge = result.getMergeResult(); RebaseResult rebase = result.getRebaseResult(); if (result.isSuccessful()) { // // TODO add more notification // this.textAreaResults.setValue("Successful!"); } else { // // TODO // this.textAreaResults.setValue("Failed."); } } catch (IOException | GitAPIException e) { e.printStackTrace(); } this.buttonSynchronize.setCaption("Ok"); }
public Git pull(File file) { try { Git gitHandle = Git.open(file); PullResult result = gitHandle.pull().call(); Preconditions.checkState(result.isSuccessful(), "Pull was not succesfull"); return gitHandle; } catch (GitAPIException | IOException e) { throw new RuntimeException("Problem pulling " + file.getPath(), e); } }
public static ArrayMemory valueOf(PullResult call) { ArrayMemory memory = new ArrayMemory(); memory.refOfIndex("success").assign(call.isSuccessful()); memory.refOfIndex("fetchedFrom").assign(call.getFetchedFrom()); memory.refOfIndex("fetch").assign(valueOf(call.getFetchResult())); memory.refOfIndex("merge").assign(call.getMergeResult() == null ? Memory.NULL : valueOf(call.getMergeResult())); return memory; }
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; }
protected String upgrade(String path) throws Exception{ //staticDir.mkdirs(); Repository repository = null; try { String logFile = "output.log"; File installLogDir = new File(staticDir,"logs"); installLogDir.mkdirs(); // File destDir = new File(staticDir,SLASH+path); destDir.mkdirs(); File output = new File(installLogDir,logFile); String gitPath = github+path+".git"; logger.debug("Updating from " + gitPath + " to " + destDir.getAbsolutePath()); FileUtils.writeStringToFile(output, "Updating from " + gitPath + " to " + destDir.getAbsolutePath()+"\n",false); Git git = null; try{ FileRepositoryBuilder builder = new FileRepositoryBuilder(); repository = builder.setGitDir(new File(destDir,"/.git")) .readEnvironment() // scan environment GIT_* variables .findGitDir() // scan up the file system tree .build(); git = new Git(repository); PullResult result = git.pull().call(); FileUtils.writeStringToFile(output, result.getMergeResult().toString(),true); logger.debug("DONE: Updated "+gitPath+" repository: " + result.getMergeResult().toString()); //now run npm install //runNpmInstall(output, destDir); }catch(Exception e){ FileUtils.writeStringToFile(output, e.getMessage(),true); FileUtils.writeStringToFile(output, e.getStackTrace().toString(),true); logger.debug("Error updating "+gitPath+" repository: " + e.getMessage(),e); }finally{ if(git!=null) git.close(); if(repository!=null)repository.close(); } return logFile; } finally { if(repository!=null)repository.close(); } }
@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()); }
/** * Pull repository from current branch and remote branch with same name as current * * @param git * instance. * @param remote * to be used. * @param remoteBranch * to use. * @param username * to connect * @param password * to connect */ public PullResult pullFromRepository(Git git, String remote, String remoteBranch, String username, String password) { try { return git.pull() .setRemote(remote) .setRemoteBranchName(remoteBranch) .setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password)) .call(); } catch (GitAPIException e) { throw new IllegalStateException(e); } }
/** * Get git repertory status. * * @param repoDir * @return * @throws SysException */ PullResult pullRepo(File repoDir) throws SysException;
/** * Using the currently checked-out branch' configuration, pulls from the repository and merges changes from * tracked branch into the local checked-out branch using the {@link MergeStrategy#RESOLVE} merge strategy. * @param git the git repository * @return result of the pull * @throws GitAPIException */ public static PullResult pullWithMerge(Git git) throws GitAPIException { return pullWithMerge(git, MergeStrategy.RESOLVE); }
/** * Pulls from the "origin" repository and merges changes from the tracked branch into * the local checked-out branch using the given strategy * @param git the git repository * @param strategy the merge strategy: * @return result of the pull * @throws GitAPIException */ public static PullResult pullWithMerge(Git git, MergeStrategy strategy) throws GitAPIException { return pullWithMerge(git, strategy, null); }