List of usage examples for org.eclipse.jgit.lib Constants DEFAULT_REMOTE_NAME
String DEFAULT_REMOTE_NAME
To view the source code for org.eclipse.jgit.lib Constants DEFAULT_REMOTE_NAME.
Click Source Link
From source file:com.cloudbees.eclipse.dev.scm.egit.ForgeEGitSync.java
License:Open Source License
public static File cloneRepo(String url, URI locationURI, IProgressMonitor monitor) throws InterruptedException, InvocationTargetException, URISyntaxException { //GitScmUrlImportWizardPage //GitImportWizard // See ProjectReferenceImporter for hints on cloning and importing! /*//from w w w.java 2s .com CloneOperation clone = Utils.createInstance(CloneOperation.class, new Class[] { URIish.class, Boolean.TYPE, Collection.class, File.class, String.class, String.class, Integer.TYPE }, new Object[] { new URIish(url), true, Collections.EMPTY_LIST, new File(""), null, "origin", 5000 }); if (clone == null) { // old constructor didn't have timeout at the end clone = Utils.createInstance(CloneOperation.class, new Class[] { URIish.class, Boolean.TYPE, Collection.class, File.class, String.class, String.class }, new Object[] { new URIish(url), true, Collections.EMPTY_LIST, new File(""), null, "origin" }); }*/ if (monitor.isCanceled()) { return null; } try { int timeout = 60; // force plugin activation Activator.getDefault().getLog(); Platform.getPreferencesService().getInt("org.eclipse.egit.core", UIPreferences.REMOTE_CONNECTION_TIMEOUT, 60, null); String branch = "master"; url = reformatGitUrlToCurrent(url); URIish gitUrl = new URIish(url); File workDir = new File(locationURI); //final File repositoryPath = workDir.append(Constants.DOT_GIT_EXT).toFile(); String refName = Constants.R_HEADS + branch; GitConnectionType type = CloudBeesUIPlugin.getDefault().getGitConnectionType(); final CloneOperation cloneOperation = new CloneOperation(gitUrl, true, null, workDir, refName, Constants.DEFAULT_REMOTE_NAME, timeout); // https password if (type.equals(GitConnectionType.HTTPS)) { try { String username = CloudBeesUIPlugin.getDefault().getPreferenceStore() .getString(PreferenceConstants.P_EMAIL); String password = CloudBeesUIPlugin.getDefault().readP(); CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(username, password); // Store to secure storage to ensure the connection remains available without reentering the password UserPasswordCredentials credentials = new UserPasswordCredentials(username, password); URIish uri = new URIish(url); SecureStoreUtils.storeCredentials(credentials, uri); cloneOperation.setCredentialsProvider(credentialsProvider); } catch (StorageException e) { throw new InvocationTargetException(new Exception("Failed to read credentials!", e)); } } cloneOperation.run(monitor); return workDir; } catch (final InvocationTargetException e1) { throw e1; } catch (InterruptedException e2) { throw e2; } }
From source file:com.rimerosolutions.ant.git.tasks.CheckoutTask.java
License:Apache License
@Override protected void doExecute() throws BuildException { try {/*from ww w. ja v a 2 s . c om*/ CheckoutCommand checkoutCommand = git.checkout(); if (createBranch) { checkoutCommand.setCreateBranch(true); if (trackBranchOnCreate) { checkoutCommand.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK); } } if (!GitTaskUtils.isNullOrBlankString(branchName)) { checkoutCommand.setName(branchName); } if (!GitTaskUtils.isNullOrBlankString(startPoint)) { checkoutCommand.setStartPoint(Constants.DEFAULT_REMOTE_NAME + "/" + startPoint); } checkoutCommand.call(); CheckoutResult checkoutResult = checkoutCommand.getResult(); if (checkoutResult.getStatus().equals(CheckoutResult.Status.CONFLICTS)) { String conflicts = checkoutResult.getConflictList().toString(); throw new GitBuildException(String.format("Conflicts were found:%s.", conflicts)); } else if (checkoutResult.getStatus().equals(CheckoutResult.Status.NONDELETED)) { String undeleted = checkoutResult.getUndeletedList().toString(); throw new GitBuildException(String.format("Some files could not be deleted:%s.", undeleted)); } } catch (RefAlreadyExistsException e) { throw new GitBuildException( String.format("Cannot create branch '%s', as it already exists!", branchName), e); } catch (RefNotFoundException e) { throw new GitBuildException(String.format("The branch '%s' was not found.", branchName), e); } catch (InvalidRefNameException e) { throw new GitBuildException("An invalid branch name was specified.", e); } catch (CheckoutConflictException e) { throw new GitBuildException("Some checkout conflicts were found.", e); } catch (GitAPIException e) { throw new GitBuildException(String.format("Could not checkout branch '%s'.", branchName), e); } }
From source file:com.rimerosolutions.ant.git.tasks.FetchTask.java
License:Apache License
@Override public void doExecute() { try {/*from w w w . j a v a2 s .c o m*/ StoredConfig config = git.getRepository().getConfig(); List<RemoteConfig> remoteConfigs = RemoteConfig.getAllRemoteConfigs(config); if (remoteConfigs.isEmpty()) { URIish uri = new URIish(getUri()); RemoteConfig remoteConfig = new RemoteConfig(config, Constants.DEFAULT_REMOTE_NAME); remoteConfig.addURI(uri); remoteConfig.addFetchRefSpec(new RefSpec("+" + Constants.R_HEADS + "*:" + Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + "/*")); config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, Constants.MASTER, ConfigConstants.CONFIG_KEY_REMOTE, Constants.DEFAULT_REMOTE_NAME); config.setString(ConfigConstants.CONFIG_BRANCH_SECTION, Constants.MASTER, ConfigConstants.CONFIG_KEY_MERGE, Constants.R_HEADS + Constants.MASTER); remoteConfig.update(config); config.save(); } List<RefSpec> specs = new ArrayList<RefSpec>(3); specs.add(new RefSpec( "+" + Constants.R_HEADS + "*:" + Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + "/*")); specs.add(new RefSpec("+" + Constants.R_NOTES + "*:" + Constants.R_NOTES + "*")); specs.add(new RefSpec("+" + Constants.R_TAGS + "*:" + Constants.R_TAGS + "*")); FetchCommand fetchCommand = git.fetch().setDryRun(dryRun).setThin(thinPack).setRemote(getUri()) .setRefSpecs(specs).setRemoveDeletedRefs(removeDeletedRefs); setupCredentials(fetchCommand); if (getProgressMonitor() != null) { fetchCommand.setProgressMonitor(getProgressMonitor()); } FetchResult fetchResult = fetchCommand.call(); GitTaskUtils.validateTrackingRefUpdates(FETCH_FAILED_MESSAGE, fetchResult.getTrackingRefUpdates()); log(fetchResult.getMessages()); } catch (URISyntaxException e) { throw new GitBuildException("Invalid URI syntax: " + e.getMessage(), e); } catch (IOException e) { throw new GitBuildException("Could not save or get repository configuration: " + e.getMessage(), e); } catch (InvalidRemoteException e) { throw new GitBuildException("Invalid remote URI: " + e.getMessage(), e); } catch (TransportException e) { throw new GitBuildException("Communication error: " + e.getMessage(), e); } catch (GitAPIException e) { throw new GitBuildException("Unexpected exception: " + e.getMessage(), e); } }
From source file:com.rimerosolutions.ant.git.tasks.PushTask.java
License:Apache License
@Override protected void doExecute() { try {/* w w w .ja v a 2 s . co m*/ StoredConfig config = git.getRepository().getConfig(); List<RemoteConfig> remoteConfigs = RemoteConfig.getAllRemoteConfigs(config); if (remoteConfigs.isEmpty()) { URIish uri = new URIish(getUri()); RemoteConfig remoteConfig = new RemoteConfig(config, Constants.DEFAULT_REMOTE_NAME); remoteConfig.addURI(uri); remoteConfig.addFetchRefSpec(new RefSpec(DEFAULT_REFSPEC_STRING)); remoteConfig.addPushRefSpec(new RefSpec(DEFAULT_REFSPEC_STRING)); remoteConfig.update(config); config.save(); } String currentBranch = git.getRepository().getBranch(); List<RefSpec> specs = Arrays.asList(new RefSpec(currentBranch + ":" + currentBranch)); if (deleteRemoteBranch != null) { specs = Arrays.asList(new RefSpec(":" + Constants.R_HEADS + deleteRemoteBranch)); } PushCommand pushCommand = git.push().setPushAll().setRefSpecs(specs).setDryRun(false); if (getUri() != null) { pushCommand.setRemote(getUri()); } setupCredentials(pushCommand); if (includeTags) { pushCommand.setPushTags(); } if (getProgressMonitor() != null) { pushCommand.setProgressMonitor(getProgressMonitor()); } Iterable<PushResult> pushResults = pushCommand.setForce(true).call(); for (PushResult pushResult : pushResults) { log(pushResult.getMessages()); GitTaskUtils.validateRemoteRefUpdates(PUSH_FAILED_MESSAGE, pushResult.getRemoteUpdates()); GitTaskUtils.validateTrackingRefUpdates(PUSH_FAILED_MESSAGE, pushResult.getTrackingRefUpdates()); } } catch (Exception e) { if (pushFailedProperty != null) { getProject().setProperty(pushFailedProperty, e.getMessage()); } throw new GitBuildException(PUSH_FAILED_MESSAGE, e); } }
From source file:com.sap.dirigible.ide.jgit.connector.JGitConnector.java
License:Open Source License
/** * //from w w w.j a v a 2 s . c om * Clones secured git remote repository to the file system. * * @param gitDirectory * where the remote repository will be cloned * @param repositoryURI * repository's URI example: https://qwerty.com/xyz/abc.git * @param username * the username used for authentication * @param password * the password used for authentication * * @throws InvalidRemoteException * @throws TransportException * @throws GitAPIException */ public static void cloneRepository(File gitDirectory, String repositoryURI, String username, String password) throws InvalidRemoteException, TransportException, GitAPIException { try { CloneCommand cloneCommand = Git.cloneRepository(); cloneCommand.setURI(repositoryURI); if (!StringUtils.isEmptyOrNull(username) && !StringUtils.isEmptyOrNull(password)) { cloneCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password)); } cloneCommand.setRemote(Constants.DEFAULT_REMOTE_NAME); cloneCommand.setDirectory(gitDirectory); cloneCommand.call(); } catch (NullPointerException e) { throw new TransportException(INVALID_USERNAME_AND_PASSWORD); } }
From source file:com.tasktop.c2c.server.scm.service.GitServiceBean.java
License:Open Source License
private List<ScmRepository> getExternalRepositories() throws IOException, URISyntaxException { List<ScmRepository> result = new ArrayList<ScmRepository>(); File hostedDir = repositoryProvider.getTenantMirroredBaseDir(); if (hostedDir != null && hostedDir.exists()) { for (String repoName : hostedDir.list()) { ScmRepository repo = new ScmRepository(); repo.setName(repoName);/*from w w w . ja v a2 s . co m*/ repo.setScmLocation(ScmLocation.EXTERNAL); repo.setType(ScmType.GIT); Git git = Git.open(new File(hostedDir, repoName)); RemoteConfig config = new RemoteConfig(git.getRepository().getConfig(), Constants.DEFAULT_REMOTE_NAME); repo.setUrl(config.getURIs().get(0).toString()); setBranchesAndTags(repo, git); result.add(repo); } } return result; }
From source file:com.tasktop.c2c.server.scm.service.GitServiceBean.java
License:Open Source License
@Secured({ Role.Admin }) @Override// ww w. j av a 2 s .c o m public void addExternalRepository(String url) { try { String repoName = getRepoDirNameFromExternalUrl(url); File dir = new File(repositoryProvider.getTenantMirroredBaseDir(), repoName); Git git = Git.init().setBare(true).setDirectory(dir).call(); RemoteConfig config = new RemoteConfig(git.getRepository().getConfig(), Constants.DEFAULT_REMOTE_NAME); config.addURI(new URIish(url)); config.update(git.getRepository().getConfig()); git.getRepository().getConfig().save(); } catch (JGitInternalException e) { throw new RuntimeException(e); } catch (URISyntaxException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } catch (GitAPIException e) { throw new RuntimeException(e); } }
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); }/*from www .j av 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:org.apache.maven.scm.provider.git.jgit.command.checkout.JGitCheckOutCommand.java
License:Apache License
/** * For git, the given repository is a remote one. We have to clone it first if the working directory does not * contain a git repo yet, otherwise we have to git-pull it. * <p/>/*from w w w.jav a 2 s. c o m*/ * {@inheritDoc} */ protected CheckOutScmResult executeCheckOutCommand(ScmProviderRepository repo, ScmFileSet fileSet, ScmVersion version, boolean recursive) throws ScmException { GitScmProviderRepository repository = (GitScmProviderRepository) repo; if (GitScmProviderRepository.PROTOCOL_FILE.equals(repository.getFetchInfo().getProtocol()) && repository.getFetchInfo().getPath().indexOf(fileSet.getBasedir().getPath()) >= 0) { throw new ScmException("remote repository must not be the working directory"); } Git git = null; try { ProgressMonitor monitor = JGitUtils.getMonitor(getLogger()); String branch = version != null ? version.getName() : null; if (StringUtils.isBlank(branch)) { branch = Constants.MASTER; } getLogger().debug("try checkout of branch: " + branch); if (!fileSet.getBasedir().exists() || !(new File(fileSet.getBasedir(), ".git").exists())) { if (fileSet.getBasedir().exists()) { // git refuses to clone otherwise fileSet.getBasedir().delete(); } // FIXME only if windauze WindowCacheConfig cfg = new WindowCacheConfig(); cfg.setPackedGitMMAP(false); cfg.install(); // no git repo seems to exist, let's clone the original repo CredentialsProvider credentials = JGitUtils.getCredentials((GitScmProviderRepository) repo); getLogger().info("cloning [" + branch + "] to " + fileSet.getBasedir()); CloneCommand command = Git.cloneRepository().setURI(repository.getFetchUrl()); command.setCredentialsProvider(credentials).setBranch(branch).setDirectory(fileSet.getBasedir()); command.setProgressMonitor(monitor); git = command.call(); } JGitRemoteInfoCommand remoteInfoCommand = new JGitRemoteInfoCommand(); remoteInfoCommand.setLogger(getLogger()); RemoteInfoScmResult result = remoteInfoCommand.executeRemoteInfoCommand(repository, fileSet, null); if (git == null) { git = Git.open(fileSet.getBasedir()); } if (fileSet.getBasedir().exists() && new File(fileSet.getBasedir(), ".git").exists() && result.getBranches().size() > 0) { // git repo exists, so we must git-pull the changes CredentialsProvider credentials = JGitUtils.prepareSession(getLogger(), git, repository); if (version != null && StringUtils.isNotEmpty(version.getName()) && (version instanceof ScmTag)) { // A tag will not be pulled but we only fetch all the commits from the upstream repo // This is done because checking out a tag might not happen on the current branch // but create a 'detached HEAD'. // In fact, a tag in git may be in multiple branches. This occurs if // you create a branch after the tag has been created getLogger().debug("fetch..."); git.fetch().setCredentialsProvider(credentials).setProgressMonitor(monitor).call(); } else { getLogger().debug("pull..."); git.pull().setCredentialsProvider(credentials).setProgressMonitor(monitor).call(); } } Set<String> localBranchNames = JGitBranchCommand.getShortLocalBranchNames(git); if (version instanceof ScmTag) { getLogger().info("checkout tag [" + branch + "] at " + fileSet.getBasedir()); git.checkout().setName(branch).call(); } else if (localBranchNames.contains(branch)) { getLogger().info("checkout [" + branch + "] at " + fileSet.getBasedir()); git.checkout().setName(branch).call(); } else { getLogger().info("checkout remote branch [" + branch + "] at " + fileSet.getBasedir()); git.checkout().setName(branch).setCreateBranch(true) .setStartPoint(Constants.DEFAULT_REMOTE_NAME + "/" + branch).call(); } RevWalk revWalk = new RevWalk(git.getRepository()); RevCommit commit = revWalk.parseCommit(git.getRepository().resolve(Constants.HEAD)); 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> listedFiles = new ArrayList<ScmFile>(); while (walk.next()) { listedFiles.add(new ScmFile(walk.getPathString(), ScmFileStatus.CHECKED_OUT)); } walk.release(); getLogger().debug("current branch: " + git.getRepository().getBranch()); return new CheckOutScmResult("checkout via JGit", listedFiles); } catch (Exception e) { throw new ScmException("JGit checkout failure!", e); } finally { JGitUtils.closeRepo(git); } }
From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepository.java
License:Open Source License
@Override public void publish(String site, List<String> commitIds, String environment, String author, String comment) { Repository repo = helper.getRepository(site, GitRepositories.PUBLISHED); synchronized (helper.getRepository(site, GitRepositories.PUBLISHED)) { try (Git git = new Git(repo)) { // fetch "origin/master" FetchResult fetchResult = git.fetch().setRemote(Constants.DEFAULT_REMOTE_NAME).call(); // checkout environment branch Ref checkoutResult = git.checkout().setCreateBranch(true).setName(environment).call(); // cherry pick all commit ids CherryPickCommand cherryPickCommand = git.cherryPick().setStrategy(MergeStrategy.THEIRS); for (String commitId : commitIds) { ObjectId objectId = ObjectId.fromString(commitId); cherryPickCommand.include(objectId); }/*from w ww . j a va2s .c o m*/ CherryPickResult cherryPickResult = cherryPickCommand.call(); // tag PersonIdent authorIdent = helper.getAuthorIdent(author); Ref tagResult = git.tag().setTagger(authorIdent).setMessage(comment).call(); } catch (GitAPIException e) { logger.error("Error when publishing site " + site + " to environment " + environment, e); } } }