List of usage examples for org.eclipse.jgit.api Git remoteAdd
public RemoteAddCommand remoteAdd()
From source file:com.mooregreatsoftware.gitprocess.lib.GitLib.java
License:Apache License
private GitLib(Git jgit) { this.jgit = jgit; storedConfig = jgit.getRepository().getConfig(); v(storedConfig::load);/*from w w w. j av a 2 s . c o m*/ this.remoteConfig = new StoredRemoteConfig(storedConfig, (remoteName, uri) -> { final RemoteAddCommand remoteAdd = jgit.remoteAdd(); remoteAdd.setName(remoteName); remoteAdd.setUri(uri); return remoteAdd.call(); }); this.generalConfig = new StoredGeneralConfig(storedConfig); }
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 ww . ja v a2s . com // 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.jenkins.blueocean.blueocean_git_pipeline.GitCacheCloneReadSaveRequest.java
License:Open Source License
private @Nonnull Git getActiveRepository(Repository repository) throws IOException { try {//from www. j ava 2 s . c o m // Clone the bare repository File cloneDir = File.createTempFile("clone", ""); if (cloneDir.exists()) { if (cloneDir.isDirectory()) { FileUtils.deleteDirectory(cloneDir); } else { if (!cloneDir.delete()) { throw new ServiceException.UnexpectedErrorException("Unable to delete repository clone"); } } } if (!cloneDir.mkdirs()) { throw new ServiceException.UnexpectedErrorException("Unable to create repository clone directory"); } String url = repository.getConfig().getString("remote", "origin", "url"); Git gitClient = Git.cloneRepository().setCloneAllBranches(false) .setProgressMonitor(new CloneProgressMonitor(url)) .setURI(repository.getDirectory().getCanonicalPath()).setDirectory(cloneDir).call(); RemoteRemoveCommand remove = gitClient.remoteRemove(); remove.setName("origin"); remove.call(); RemoteAddCommand add = gitClient.remoteAdd(); add.setName("origin"); add.setUri(new URIish(gitSource.getRemote())); add.call(); if (GitUtils.isSshUrl(gitSource.getRemote())) { // Get committer info and credentials User user = User.current(); if (user == null) { throw new ServiceException.UnauthorizedException("Not authenticated"); } BasicSSHUserPrivateKey privateKey = UserSSHKeyManager.getOrCreate(user); // Make sure up-to-date and credentials work GitUtils.fetch(repository, privateKey); } else { FetchCommand fetch = gitClient.fetch(); fetch.call(); } if (!StringUtils.isEmpty(sourceBranch) && !sourceBranch.equals(branch)) { CheckoutCommand checkout = gitClient.checkout(); checkout.setStartPoint("origin/" + sourceBranch); checkout.setName(sourceBranch); checkout.setCreateBranch(true); // to create a new local branch checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK); checkout.call(); checkout = gitClient.checkout(); checkout.setName(branch); checkout.setCreateBranch(true); // this *should* be a new branch checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK); checkout.call(); } else { CheckoutCommand checkout = gitClient.checkout(); checkout.setStartPoint("origin/" + branch); checkout.setName(branch); checkout.setCreateBranch(true); // to create a new local branch checkout.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.NOTRACK); checkout.call(); } return gitClient; } catch (GitAPIException | URISyntaxException ex) { throw new ServiceException.UnexpectedErrorException("Unable to get working repository directory", ex); } }
From source file:io.syndesis.git.GitWorkflow.java
License:Apache License
/** * Creates a new remote git repository and does the initial commit&push of all the project files * the files to it./* www. ja va2s . c om*/ * * @param remoteGitRepoHttpUrl- the HTML (not ssh) url to a git repository * @param repoName - the name of the git repository * @param author author * @param message- commit message * @param files- map of file paths along with their content * @param credentials- Git credentials, for example username/password, authToken, personal access token */ public void createFiles(String remoteGitRepoHttpUrl, String repoName, User author, String message, Map<String, byte[]> files, UsernamePasswordCredentialsProvider credentials) { try { // create temporary directory Path workingDir = Files.createTempDirectory(Paths.get(gitProperties.getLocalGitRepoPath()), repoName); if (LOG.isDebugEnabled()) { LOG.debug("Created temporary directory {}", workingDir.toString()); } // git init Git git = Git.init().setDirectory(workingDir.toFile()).call(); writeFiles(workingDir, files); RemoteAddCommand remoteAddCommand = git.remoteAdd(); remoteAddCommand.setName("origin"); remoteAddCommand.setUri(new URIish(remoteGitRepoHttpUrl)); remoteAddCommand.call(); commitAndPush(git, authorName(author), author.getEmail(), message, credentials); removeWorkingDir(workingDir); } catch (IOException | GitAPIException | URISyntaxException e) { throw SyndesisServerException.launderThrowable(e); } }
From source file:net.morimekta.idltool.IdlToolTest.java
License:Apache License
@Test public void testListNoRepository() throws GitAPIException, URISyntaxException, IOException { Git.init().setDirectory(tmp.getRoot()).call(); Git git = Git.open(tmp.getRoot()); RemoteAddCommand remoteAddCommand = git.remoteAdd(); remoteAddCommand.setName("origin"); remoteAddCommand.setUri(new URIish("git@github.com/morimekta/idltool.git")); remoteAddCommand.call();//from ww w .j a v a 2 s.c o m idl.execute("list"); assertThat(exitCode, is(1)); assertThat(console.output(), is("")); assertThat(console.error(), is("I/O Error: No .idlrc file at: " + tmp.getRoot().toString() + " (recursive)\n")); }
From source file:org.archicontribs.modelrepository.grafico.GraficoUtils.java
License:Open Source License
/** * Create a new, local Git repository with name set to "origin" * @param localGitFolder/*from w ww.java 2 s. com*/ * @param URL online URL * @return The Git object * @throws GitAPIException * @throws IOException * @throws URISyntaxException */ public static Git createNewLocalGitRepository(File localGitFolder, String URL) throws GitAPIException, IOException, URISyntaxException { if (localGitFolder.exists() && localGitFolder.list().length > 0) { throw new IOException("Directory: " + localGitFolder + " is not empty."); //$NON-NLS-1$ //$NON-NLS-2$ } InitCommand initCommand = Git.init(); initCommand.setDirectory(localGitFolder); Git git = initCommand.call(); RemoteAddCommand remoteAddCommand = git.remoteAdd(); remoteAddCommand.setName("origin"); //$NON-NLS-1$ remoteAddCommand.setUri(new URIish(URL)); remoteAddCommand.call(); return git; }
From source file:replicatorg.app.ui.panels.UpdateChecker.java
License:Open Source License
private void updateFilaments() { final FileRepositoryBuilder repoBuilder = new FileRepositoryBuilder(); final Git git; final Status repoStatus; final RemoteAddCommand remoteAddCmd; ResetCommand resetCmd;//w w w .jav a 2s . c o m CheckoutCommand checkoutCmd; final String currentBranch, newBranch; final List<Ref> branchList; Repository filamentsRepo; boolean branchFoundLocally = false; RevCommit stash = null; repoBuilder.setMustExist(true); repoBuilder.setGitDir(new File(FILAMENTS_REPO_PATH + ".git")); try { try { Base.writeLog("Attempting to open repo at " + FILAMENTS_REPO_PATH, this.getClass()); filamentsRepo = repoBuilder.build(); } catch (RepositoryNotFoundException ex) { try { Base.writeLog("Repository wasn't initialized, initializing it to the given URL: " + FILAMENTS_REPO_URL, this.getClass()); repoBuilder.setMustExist(false); filamentsRepo = repoBuilder.build(); filamentsRepo.create(); } catch (IOException ex1) { Base.writeLog("IOException while attempting to initialize repository, not updating filaments", this.getClass()); return; } } currentBranch = filamentsRepo.getBranch(); } catch (IOException ex) { Base.writeLog("IOException while attempting to open repository, not updating filaments", this.getClass()); return; } git = new Git(filamentsRepo); try { // it should be only 1, but it shortens the code needed, as the call() // method returns an iterable for (RevCommit commit : git.log().setMaxCount(1).call()) { Base.writeLog("Current commit hash: " + commit, this.getClass()); } } catch (GitAPIException ex) { Base.writeLog( "GitAPIException while attempting to get current commit's hash. Not a critical error, so proceeding with update", this.getClass()); } try { remoteAddCmd = git.remoteAdd(); remoteAddCmd.setName("origin"); remoteAddCmd.setUri(new URIish(FILAMENTS_REPO_URL)); remoteAddCmd.call(); } catch (URISyntaxException ex) { Base.writeLog("Invalid git filament repo remote URL!", this.getClass()); return; } catch (GitAPIException ex) { Base.writeLog("GitAPIException thrown when adding remote to git filament repo", this.getClass()); return; } try { if (currentBranch.equals(FILAMENTS_REPO_BRANCH) == false) { Base.writeLog("Repo branch is " + currentBranch + " and it should be " + FILAMENTS_REPO_BRANCH + ", searching for it", this.getClass()); checkoutCmd = git.checkout(); checkoutCmd.setName(FILAMENTS_REPO_BRANCH); branchList = git.branchList().call(); for (Ref ref : branchList) { if (ref.getName().contains(FILAMENTS_REPO_BRANCH)) { Base.writeLog("Correct branch was found locally", this.getClass()); branchFoundLocally = true; break; } } if (branchFoundLocally == false) { Base.writeLog( "No correct branch was found locally, attempting to checkout a new branch tracking the remote", this.getClass()); checkoutCmd.setCreateBranch(true); checkoutCmd.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK); checkoutCmd.setStartPoint(FILAMENTS_REPO_BRANCH); git.fetch().call(); } RevCommit backup = null; if (git.status().call().isClean() == false) { git.add().addFilepattern(".").call(); backup = git.commit().setMessage("local backup of user modifications").call(); } newBranch = checkoutCmd.call().getName(); if (newBranch.contains(FILAMENTS_REPO_BRANCH) == false) { Base.writeLog("Unable to change to correct branch, aborting update", this.getClass()); return; } else { Base.writeLog("Changed to correct branch, " + newBranch, this.getClass()); } try { for (RevCommit commit : git.log().setMaxCount(1).call()) { Base.writeLog("Commit hash after branch change: " + commit, this.getClass()); } } catch (GitAPIException ex) { // we don't want all the process to stop just because we couldn't acquire the hash here, // hence this catch Base.writeLog( "GitAPIException while attempting to get current commit's hash, after changing branch. Not a critical error, so proceeding with update", this.getClass()); } if (backup != null) { // TODO: restore backup of user modifications //git.cherryPick().setNoCommit(true).include(backup).call(); } } repoStatus = git.status().call(); checkoutCmd = git.checkout(); checkoutCmd.setName(FILAMENTS_REPO_BRANCH); checkoutCmd.call(); git.fetch(); resetCmd = git.reset(); resetCmd.setMode(ResetType.HARD); resetCmd.call(); git.pull().call(); /* repoStatus = git.status().call(); if (repoStatus.hasUncommittedChanges()) { Base.writeLog("Repo has uncommited changes, stashing and pulling...", this.getClass()); stash = git.stashCreate().call(); git.pull().call(); git.stashApply().call(); // will apply the last stash made git.stashDrop().call(); // remove the last stash made } else { Base.writeLog("Repo has no uncommited changes, a simple pull will suffice", this.getClass()); git.pull().call(); } */ Base.writeLog("Filament update concluded successfully!", this.getClass()); try { for (RevCommit commit : git.log().setMaxCount(1).call()) { Base.writeLog("Commit hash after update process finished: " + commit, this.getClass()); } } catch (GitAPIException ex) { // we don't want all the process to stop just because we couldn't acquire the hash here, // hence this catch Base.writeLog( "GitAPIException while attempting to get current commit's hash, after the process finished with success. Not a critical error, so proceeding with update", this.getClass()); } } catch (GitAPIException ex) { Base.writeLog("GitAPIException while attempting to update filaments, aborting update", this.getClass()); try { resetCmd = git.reset(); resetCmd.setMode(ResetType.HARD); resetCmd.call(); if (stash != null) { git.stashApply().call(); git.stashDrop().call(); } } catch (GitAPIException ex1) { Base.writeLog("GitAPIException while attempting to reset after an error, uh oh...", this.getClass()); } } }