@Test(expected = MissingObjectException.class) public void testRemoteRepositoryHasNoCommitst() throws URISyntaxException, IOException, InvalidRemoteException, TransportException, GitAPIException, NoRepositorySelected { gitAccess.setRepository(LOCAL_TEST_REPOSITPRY); final StoredConfig config = gitAccess.getRepository().getConfig(); RemoteConfig remoteConfig = new RemoteConfig(config, "origin"); URIish uri = new URIish(db2.getDirectory().toURI().toURL()); remoteConfig.addURI(uri); remoteConfig.update(config); config.save(); gitAccess.add(new FileStatus(GitChangeType.ADD, "test.txt")); gitAccess.commit("file test added"); // throws missingObjectException db2.resolve(gitAccess.getLastLocalCommit().getName() + "^{commit}"); }
@Test public void testPushOK() throws URISyntaxException, IOException, InvalidRemoteException, TransportException, GitAPIException, NoRepositorySelected { gitAccess.setRepository(LOCAL_TEST_REPOSITPRY); final StoredConfig config = gitAccess.getRepository().getConfig(); RemoteConfig remoteConfig = new RemoteConfig(config, "origin"); URIish uri = new URIish(db2.getDirectory().toURI().toURL()); remoteConfig.addURI(uri); remoteConfig.update(config); config.save(); gitAccess.add(new FileStatus(GitChangeType.ADD, "test.txt")); gitAccess.commit("file test added"); gitAccess.push("", ""); assertEquals(db1.resolve(gitAccess.getLastLocalCommit().getName() + "^{commit}"), db2.resolve(gitAccess.getLastLocalCommit().getName() + "^{commit}")); }
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(); } } }
private void cloneRepository() throws IOException, InvalidRemoteException, TransportException, GitAPIException { File localPath = File.createTempFile("TestGitRepository", ""); localPath.delete(); System.out.println("Cloning from " + repository_url + " to " + localPath); Git result = Git.cloneRepository() .setURI(repository_url) .setDirectory(localPath) .call(); // Note: the call() returns an opened repository already which needs to be closed to avoid file handle leaks! System.out.println("Having repository: " + result.getRepository().getDirectory()); repositoryPath = result.getRepository().getDirectory().getAbsolutePath(); @SuppressWarnings("deprecation") Preferences preferences = new InstanceScope().getNode(ModularityCheck.PLUGIN_ID); preferences.put(REPOSITORY_PATH, repositoryPath); }
public void openRepository() throws IOException, GitAPIException, InvalidRemoteException, TransportException { // Now open the created repository FileRepositoryBuilder builder = new FileRepositoryBuilder(); String directory = System.getProperty("user.home") + Properties.SEPARATOR + "TestGit\\";///.git if(new File(directory).mkdir() || new File(directory).exists()){ directory = directory + "/.git"; repository = builder .setGitDir( new File( directory)).readEnvironment() // scan // environment // GIT_* // variables .findGitDir() // scan up the file system tree .build(); }else System.out.println("Error during repository clonage. Permission denied for creating files at user home"); }
public void execute() throws InvalidRemoteException { try { final List<RefSpec> specs = git.updateRemoteConfig(remote, refSpecs); git._fetch() .setCredentialsProvider(credentialsProvider) .setRemote(remote.getK1()) .setRefSpecs(specs) .call(); } catch (final InvalidRemoteException e) { throw e; } catch (final Exception ex) { throw new RuntimeException(ex); } }
public Git execute() throws InvalidRemoteException { if (logger.isDebugEnabled()) { logger.debug("Forking repository <{}> to <{}>", source, target); } final File origin = new File(parentFolder, source + DOT_GIT_EXT); final File destination = new File(parentFolder, target + DOT_GIT_EXT); if (destination.exists()) { String message = String.format("Cannot fork because destination repository <%s> already exists", target); logger.error(message); throw new GitException(message); } return Git.clone(destination, origin.toPath().toUri().toString(), false, credentialsProvider, leaders); }
public void execute() throws InvalidRemoteException { try { final List<RefSpec> specs = new UpdateRemoteConfig(git, remote, refSpecs).execute(); git._push() .setCredentialsProvider(credentialsProvider) .setRefSpecs(specs) .setRemote(remote.getK1()) .setForce(force) .setPushAll() .call(); } catch (final InvalidRemoteException e) { throw e; } catch (final Exception ex) { throw new RuntimeException(ex); } }
@Test public void testToForkWrongSource() throws IOException, GitAPIException { final File parentFolder = createTempDirectory(); try { new Fork(parentFolder, SOURCE_GIT, TARGET_GIT, CredentialsProvider.getDefault(), null).execute(); fail("If got here is because it could for the repository"); } catch (InvalidRemoteException e) { assertThat(e).isNotNull(); logger.info(e.getMessage(), e); } }
public static void main(String[] args) throws IOException, InvalidRemoteException, TransportException, GitAPIException { // prepare a new folder for the cloned repository File localPath = File.createTempFile("TestGitRepository", ""); localPath.delete(); // then clone System.out.println("Cloning from " + REMOTE_URL + " to " + localPath); Git.cloneRepository() .setURI(REMOTE_URL) .setDirectory(localPath) .call(); // now open the created repository FileRepositoryBuilder builder = new FileRepositoryBuilder(); Repository repository = builder.setGitDir(localPath) .readEnvironment() // scan environment GIT_* variables .findGitDir() // scan up the file system tree .build(); System.out.println("Having repository: " + repository.getDirectory()); repository.close(); }
public Git call(final GitOperationsStep gitOperationsStep, Git git, CredentialsProvider cp, String gitRepoUrl, File gitRepoFolder) throws InvalidRemoteException, TransportException, GitAPIException { CloneCommand cc = Git.cloneRepository().setURI(gitRepoUrl) .setDirectory(gitRepoFolder); if (!Const.isEmpty(this.branchName)) { cc = cc.setBranch(gitOperationsStep .environmentSubstitute(this.branchName)); } cc.setCloneAllBranches(this.cloneAllBranches).setCloneSubmodules( this.cloneSubModules); if (cp != null) { cc.setCredentialsProvider(cp); } return cc.setBare(false).call(); }
private void execute() throws InvalidRemoteException, TransportException, GitAPIException, IOException { setProxy(); CloneCommand cmd = Git.cloneRepository() .setURI(config.getRemoteUrl()); if (config.getLocalPath() != "") { cmd.setDirectory(new File(config.getLocalPath())); } Git git = cmd.call(); // Set proxy setting to repository config. StoredConfig gitConfig = git.getRepository().getConfig(); gitConfig.setString("remote", "origin", "proxy", config.getProxyAddress()); gitConfig.save(); git.getRepository().close(); }
public void cloneRepo(final String gitUri, final Path repoDir) throws InvalidRemoteException, GitAPIException, IOException { if (Files.exists(repoDir)) { LOGGER.debug("Deleting left-over repo dir" + repoDir.toAbsolutePath().toString()); com.sap.cloud.lm.sl.cf.core.util.FileUtils.deleteDirectory(repoDir); } configureGitSslValidation(); if (shoudlUseToken(gitServiceUrlString, gitUri)) { cloneCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(userName, token)); } if (refName != null && !refName.isEmpty()) { String fullRefName = refName.startsWith("refs/") ? refName : "refs/heads/" + refName; cloneCommand.setBranchesToClone(Arrays.asList(new String[] { fullRefName })); cloneCommand.setBranch(fullRefName); } cloneCommand.setTimeout(290); cloneCommand.setDirectory(repoDir.toAbsolutePath().toFile()); cloneCommand.setURI(gitUri); LOGGER.debug( MessageFormat.format("cloning repo with url {0} in repo dir {1} ref '{2}'", gitUri, repoDir.toAbsolutePath().toString())); try (Git callInstance = cloneCommand.call()) { Repository repo = callInstance.getRepository(); repo.close(); } catch (TransportException e) { Throwable cause1 = e.getCause(); if (cause1 != null && cause1.getCause() instanceof SSLHandshakeException) { throw new SLException(cause1.getCause(), "Failed to establish ssl connection"); // NOSONAR } throw e; } }
@Test public void testNoPushesAhead() throws RepositoryNotFoundException, IOException, URISyntaxException, NoRepositorySelected, InvalidRemoteException, TransportException, GitAPIException{ gitAccess.setRepository(LOCAL_TEST_REPOSITPRY); final StoredConfig config = gitAccess.getRepository().getConfig(); RemoteConfig remoteConfig = new RemoteConfig(config, "origin"); URIish uri = new URIish(db2.getDirectory().toURI().toURL()); remoteConfig.addURI(uri); remoteConfig.update(config); config.save(); int actual = gitAccess.getPushesAhead(); int expected = 0; assertEquals(expected, actual); }
protected void pushOneFileToRemote(String message) throws IOException, RepositoryNotFoundException, FileNotFoundException, InvalidRemoteException, TransportException, GitAPIException, InterruptedException { gitAccess.setRepository(LOCAL_TEST_REPOSITPRY); OptionsManager.getInstance().saveSelectedRepository(LOCAL_TEST_REPOSITPRY); PrintWriter out = new PrintWriter(LOCAL_TEST_REPOSITPRY + "/test.txt"); out.println(message); out.close(); gitAccess.addAll(gitAccess.getUnstagedFiles()); gitAccess.commit(message); gitAccess.push("", ""); }
public void cloneAll(String host) throws InvalidRemoteException, TransportException, GitAPIException{ Git git = Git.cloneRepository().setURI(host).setNoCheckout(true).setCloneAllBranches(true).call(); List<Ref> branches = git.branchList().setListMode( ListMode.REMOTE ).call(); for(Ref r:branches){ System.out.println(r.getName()); } }
private void pushAndLogResult(final PushCommand pushCommand) throws GitAPIException, InvalidRemoteException, TransportException { for (final PushResult result : pushCommand.call()) { for (final RemoteRefUpdate upd : result.getRemoteUpdates()) { log.info(upd.toString()); } } }
/** * Initializes a user's git repository. * * * @param workspacePath * @param userId * @param email * @return * @throws IOException * @throws InvalidRemoteException * @throws TransportException * @throws GitAPIException */ private static Path initializeUserRepository(Path workspacePath, String userId, URI email) throws IOException, InvalidRemoteException, TransportException, GitAPIException { Path gitPath = null; // // Initialize the User's Git repository // if (Files.notExists(workspacePath)) { logger.info("Creating user workspace: " + workspacePath.toAbsolutePath().toString()); // // Create our user's directory // Files.createDirectory(workspacePath); } gitPath = Paths.get(workspacePath.toString(), XacmlAdminUI.repositoryPath.getFileName().toString()); if (Files.notExists(gitPath)) { // // It doesn't exist yet, so Clone it and check it out // logger.info("Cloning user git directory: " + gitPath.toAbsolutePath().toString()); Git.cloneRepository().setURI(XacmlAdminUI.repositoryPath.toUri().toString()) .setDirectory(gitPath.toFile()) .setNoCheckout(false) .call(); // // Set userid // Git git = Git.open(gitPath.toFile()); StoredConfig config = git.getRepository().getConfig(); config.setString("user", null, "name", userId); if (email != null && email.getPath() != null) { config.setString("user", null, "email", email.toString()); } config.save(); } return gitPath; }
private void fetchFromUpstream() throws InvalidRemoteException, TransportException, GitAPIException { final boolean fetchAutomatically = Preferences.getStore().getBoolean(Preferences.PERMO__FETCH_AUTOMATICALLY); if (fetchAutomatically) { final Git git = new Git(repository); git.fetch().setRemote(JGitUtil.getDefaultRemote(repository)).call(); } }
private void cloneRemoteRepository() throws IOException, InvalidRemoteException, TransportException, GitAPIException{ loadPreferences(); //repositoryPath="C:\\Users\\Luciana\\AppData\\Local\\Temp\\TestGitRepository8482929131009567265"; if(repositoryPath.isEmpty()) cloneRepository(); else if(!last_repository_url.equals(repository_url) || new File(repositoryPath).listFiles().length == 0) cloneRepository(); if(!repositoryPath.endsWith("/.git")) repositoryPath = repositoryPath + Properties.SEPARATOR + "/.git"; openRepository(new File(repositoryPath)); }
/** * pushes only the current branch * @throws MissingRepoException * @throws GitAPIException * @throws PushToAheadRemoteError */ public PushCommand prepareToPushCurrentBranch(boolean isTest) throws MissingRepoException, GitAPIException, PushToAheadRemoteError, IOException, NoCommitsToPushException { BranchHelper branchToPush = this.getBranchModel().getCurrentBranch(); logger.info("attempting to push current branch"); if (!exists()) throw new MissingRepoException(); if (!hasRemote()) throw new InvalidRemoteException("No remote repository"); String remote = getRemote(); if (remote.equals("cancel")) throw new InvalidRemoteException("No remote selected."); Git git = new Git(this.repo); PushCommand push = git.push().setRemote(remote).add(branchToPush.getRefPathString()); ProgressMonitor progress = new SimpleProgressMonitor(); push.setProgressMonitor(progress); if(this.getBranchModel().getCurrentRemoteBranch() == null) { if(isTest || PopUpWindows.trackCurrentBranchRemotely(branchToPush.getRefName())){ setUpstreamBranch(branchToPush, remote); }else { throw new NoCommitsToPushException(); } } return push; //pushCurrentBranch(git, push); }
/** * Pushes all tags in /refs/tags/. * * @throws GitAPIException if the `git push --tags` call fails. */ public Iterable<PushResult> pushTags() throws GitAPIException, MissingRepoException, PushToAheadRemoteError, IOException { logger.info("Attempting push tags"); if (!exists()) throw new MissingRepoException(); if (!hasRemote()) throw new InvalidRemoteException("No remote repository"); Git git = new Git(this.repo); PushCommand push = git.push(); myWrapAuthentication(push); ProgressMonitor progress = new SimpleProgressMonitor(); push.setProgressMonitor(progress); Iterable<PushResult> pushResult = push.setPushTags().call(); boolean allPushesWereRejected = true; boolean anyPushWasRejected = false; for (PushResult result : pushResult) { for (RemoteRefUpdate remoteRefUpdate : result.getRemoteUpdates()) { if (remoteRefUpdate.getStatus() != (RemoteRefUpdate.Status.REJECTED_NONFASTFORWARD)) { allPushesWereRejected = false; } else { anyPushWasRejected = true; System.out.println(remoteRefUpdate); } } } if (allPushesWereRejected || anyPushWasRejected) { throw new PushToAheadRemoteError(allPushesWereRejected); } git.close(); this.tagModel.updateTags(); return pushResult; }
/** * Merges the current branch with the remote branch that this is tracking, as * found in the config for the repo * * @throws IOException * @throws GitAPIException * @throws MissingRepoException * @return the merge status merging these two branches */ public MergeResult.MergeStatus mergeFromFetch() throws IOException, GitAPIException, MissingRepoException, ConflictingFilesException, NoTrackingException { logger.info("Attempting merge from fetch"); if (!exists()) throw new MissingRepoException(); if (!hasRemote()) throw new InvalidRemoteException("No remote repository"); // Get the remote branch the current branch is tracking // and merge the current branch with the just fetched remote branch MergeResult result; Config config = repo.getConfig(); // Check if this branch is being tracked locally if (config.getSubsections("branch").contains(this.repo.getBranch())) { String remote = config.getString("branch", this.repo.getBranch(), "remote")+"/"; String remote_tracking = config.getString("branch", this.repo.getBranch(), "merge"); result = branchModel.mergeWithBranch(this.branchModel.getBranchByName(BranchModel.BranchType.REMOTE, remote+this.repo.shortenRefName(remote_tracking))); } else { throw new NoTrackingException(); } try { this.localCommits = parseAllLocalCommits(); } catch (IOException e) { // This shouldn't occur once we have the repo up and running. } MergeResult.MergeStatus status = result.getMergeStatus(); if (status == MergeResult.MergeStatus.CONFLICTING) throw new ConflictingFilesException(result.getConflicts()); //return result.getMergeStatus().isSuccessful(); return status; }
private void fetchGitHubPullRequest(Repository gitRepo, GHPullRequest pr) throws GitAPIException, InvalidRemoteException, TransportException { status.update(Code.SYNC, "Fetching", "Fetching PullRequests from GitHub"); try (Git git = Git.wrap(gitRepo)) { FetchCommand fetch = git.fetch(); fetch.setRemote(ghRepository.getCloneUrl()); fetch.setRefSpecs( new RefSpec( "+refs/pull/" + pr.getNumber() + "/head:refs/remotes/origin/pr/" + pr.getNumber())); fetch.setProgressMonitor(this); fetch.setCredentialsProvider(ghRepository.getCredentialsProvider()); fetch.call(); } }
public void clone(int from, int to) throws InvalidRemoteException, TransportException, IOException, GitAPIException { String urlHeader = "https://github.com/"; String urlFooter = ".git"; String outFilePath = ""; File dir = new File(inPath); File[] files = dir.listFiles(); for (int i = from; i < to; i++) { // System.out.println("Processing file number " + i ); if (!files[i].getName().endsWith(".json")) { continue; } String content = FileIO.readFileContents(files[i]); Gson parser = new Gson(); JsonArray repos = parser.fromJson(content, JsonElement.class).getAsJsonArray(); for (int j = 0; j < repos.size(); j++) { JsonObject repo = repos.get(j).getAsJsonObject(); String name = repo.get("full_name").getAsString(); boolean forked = repo.get("fork").getAsBoolean(); if (forked) continue; outFilePath = outPath + "/" + name; //File file = new File(outFilePath); if (names.contains(name)){ names.remove(name); continue; } String[] args = { urlHeader + name + urlFooter, outFilePath }; RepositoryCloner.clone(args); FileIO.writeFileContents(recovory, name + "/n" , true); } } }
public static void clone(String[] args) throws IOException, InvalidRemoteException, TransportException, GitAPIException { // prepare a new folder for the cloned repository String localpaths = args[1]; String url = args[0]; REMOTE_URL = url; File localPath = new File(localpaths); if (!localPath.exists()) localPath.mkdir(); else return; // then clone Git result = null; try { result = Git.cloneRepository().setURI(REMOTE_URL).setBare(true).setDirectory(localPath).call(); // Note: the call() returns an opened repository already which needs // to be closed to avoid file handle leaks! // workaround for // https://bugs.eclipse.org/bugs/show_bug.cgi?id=474093 result.getRepository().close(); } catch (Exception e) { e.printStackTrace(); } finally { if (result != null && result.getRepository() != null) result.getRepository().close(); } }
static Git fork(final File gitRepoContainerDir, final String origin, final String name, final CredentialsProvider credential, final KetchLeaderCache leaders) throws InvalidRemoteException { return new Fork(gitRepoContainerDir, origin, name, credential, leaders).execute(); }
static Git clone(final File repoDest, final String origin, final boolean isMirror, final CredentialsProvider credential, final KetchLeaderCache leaders) throws InvalidRemoteException { return new Clone(repoDest, origin, isMirror, credential, leaders).execute().get(); }
@Override public void push(final CredentialsProvider credentialsProvider, final Pair<String, String> remote, final boolean force, final Collection<RefSpec> refSpecs) throws InvalidRemoteException { new Push(this, credentialsProvider, remote, force, refSpecs).execute(); }
@Override public void fetch(final CredentialsProvider credential, final Pair<String, String> remote, final Collection<RefSpec> refSpecs) throws InvalidRemoteException { new Fetch(this, credential, remote, refSpecs).execute(); }
public static void main(String args[]) throws InvalidRemoteException, TransportException, GitAPIException, IOException, ClassNotFoundException { new Settings(); //Write to inititate R. As no servlet here DataStatistics ds = new DataStatistics(); ds.init(); DownloadRepo dr = new DownloadRepo(); //dr.cloneRepo("libgdx", "libgdx"); File f = new File("E://githubrepos.txt"); List<String> ReposName = FileUtils.readLines(f); for(String reponame: ReposName) { String[] temp = reponame.split("/"); if(temp.length == 2) { dr.cloneRepo(temp[0], temp[1]); } } /*File f = new File("E://githubrepos.txt"); List<String> CommitsData = FileUtils.readLines(f); FileWriter f1 = new FileWriter("E://githubreposfin.txt"); Set<String> s = new HashSet<String>(); for(String str: CommitsData) { s.add(str.toLowerCase()); } for(String str1: s) { f1.append(str1 +"\n"); } f1.flush(); f1.close();*/ }
public static void gitSync() throws IOException, InvalidRemoteException, org.eclipse.jgit.api.errors.TransportException, GitAPIException { SshSessionFactory.setInstance(new JschConfigSessionFactory() { public void configure(Host hc, Session session) { session.setConfig("StrictHostKeyChecking", "no"); }; } ); if (openRepository()) { pullRepository(); } else cloneRepository(); }
public Git call(final GitOperationsStep gitOperationsStep, Git git, CredentialsProvider cp, String gitRepoUrl, File gitRepoFolder) throws IllegalArgumentException, IOException, InvalidRemoteException, TransportException, GitAPIException { PushCommand pc = git.push().setDryRun(dryRun).setForce(force) .setThin(thin); if (cp != null) { pc = pc.setCredentialsProvider(cp); } if (!Const.isEmpty(this.receivePack)) { pc = pc.setReceivePack(gitOperationsStep .environmentSubstitute(receivePack)); } if (!Const.isEmpty(this.referenceToPush)) { pc = pc.add(gitOperationsStep .environmentSubstitute(this.referenceToPush)); } if (!Const.isEmpty(this.remote)) { pc = pc.setRemote(gitOperationsStep .environmentSubstitute(this.remote)); } if (this.pushAllBranches) { pc = pc.setPushAll(); } if (this.pushAllTags) { pc = pc.setPushTags(); } pc.call(); return git; }
public Git call(final GitOperationsStep gitOperationsStep, Git git, CredentialsProvider cp, String gitRepoUrl, File gitRepoFolder) throws IllegalArgumentException, IOException, WrongRepositoryStateException, InvalidConfigurationException, DetachedHeadException, InvalidRemoteException, CanceledException, RefNotFoundException, NoHeadException, TransportException, GitAPIException { git.pull().setCredentialsProvider(cp).setRebase(rebase).call(); return git; }
private void pushClonedRepoToOurRepository(String repositoryUrl, Git git) throws IOException, InvalidRemoteException { log.debug("Changing remote to {}", repositoryUrl); StoredConfig config = git.getRepository().getConfig(); config.setString("remote", "origin", "url", repositoryUrl); config.unset("remote", "origin", "fetch"); config.save(); git.push().setPushAll().setRemote("origin").call(); log.debug("Push complete"); }
public static void main( String[] args ) throws IOException, RefNotFoundException, DetachedHeadException, WrongRepositoryStateException, InvalidRemoteException, InvalidConfigurationException, CanceledException { visit( new File( "C:\\workingcopy\\phet-little-gits" ) ); }
static RepoHelper cloneRepositoryWithChecks(String remoteURL, Path destinationPath, RepoHelperBuilder.AuthDialogResponse response, UserInfo userInfo) throws GitAPIException, IOException, CancelledAuthorizationException, NoRepoSelectedException { // Always use authentication. If authentication is unneeded (HTTP), it will still work even if the wrong // username password is used. This is what Eclipse does; in fact, it asks for username/password in the // same dialog box that the URL is entered. // // Set up both sets of credentials (username/password pair, as well // as just password. Only one of these will be used, but that is determined automatically via the JGit // callback mechanism. UsernamePasswordCredentialsProvider credentials = new UsernamePasswordCredentialsProvider(response.username, response.password); String sshPassword = response.password; // Try calling `git ls-remote ___` on the remote URL to see if it's valid TransportCommand command = Git.lsRemoteRepository().setRemote(remoteURL); ClonedRepoHelper repoHelper = new ClonedRepoHelper(destinationPath, remoteURL, sshPassword, userInfo); repoHelper.wrapAuthentication(command, credentials); try { command.call(); } catch (TransportException e) { // If the URL doesn't have a repo, a Transport Exception is thrown when this command is called. // We want the SessionController to report an InvalidRemoteException, though, because // that's the issue. System.out.println(e.getMessage()); System.out.println(e.getMessage().endsWith("not authorized") || e.getMessage().endsWith("not authorized.")); System.out.println(e.getMessage().endsWith("not found") || e.getMessage().endsWith("not found.")); /*Throwable exception = e; while (exception != null) { System.err.println("======================"); exception.printStackTrace(); exception = exception.getCause(); }*/ if (e.getMessage().endsWith("not found") || e.getMessage().endsWith("not found.")) { logger.error("Invalid remote exception thrown"); throw new InvalidRemoteException("Caught invalid repository when building a ClonedRepoHelper."); } else if (e.getMessage().endsWith("not authorized") || e.getMessage().endsWith("not authorized.")) { logger.error("Authentication error"); } } // Without the above try/catch block, the next line would run and throw the desired InvalidRemoteException, // but it would create a destination folder for the repo before stopping. By catching the error above, // we prevent unnecessary folder creation. By making it to this point, we've verified that the repo // is valid and that we can authenticate to it. if (response.protocol == AuthMethod.SSH) { repoHelper.obtainRepository(remoteURL); } else { repoHelper.setUsernamePasswordCredentials(credentials); repoHelper.obtainRepository(remoteURL); } return repoHelper; }
Git createNewGitRepo(Map<String, ?> env, String fsName) { final Git git; String envUsername = extractEnvProperty(GIT_ENV_KEY_USER_NAME, env); String envPassword = extractEnvProperty(GIT_ENV_KEY_PASSWORD, env); Boolean envMirror = (Boolean) env.get(GIT_ENV_KEY_MIRROR); boolean isMirror = envMirror == null ? true : envMirror; CredentialsProvider credential = buildCredential(envUsername, envPassword); final String outPath = (String) env.get(GIT_ENV_KEY_DEST_PATH); final File repoDest; if (outPath != null) { repoDest = new File(outPath, fsName + DOT_GIT_EXT); } else { repoDest = new File(config.getGitReposParentDir(), fsName + DOT_GIT_EXT); } if (env.containsKey(GIT_ENV_KEY_DEFAULT_REMOTE_NAME)) { final String origin = env.get(GIT_ENV_KEY_DEFAULT_REMOTE_NAME).toString(); try { if (this.isForkOrigin(origin)) { git = Git.fork(this.getGitRepoContainerDir(), origin, fsName, credential, config.isEnableKetch() ? leaders : null); } else { git = Git.clone(repoDest, origin, isMirror, credential, config.isEnableKetch() ? leaders : null); } } catch (InvalidRemoteException e) { throw new RuntimeException(e); } } else { git = Git.createRepository(repoDest, config.getHookDir(), config.isEnableKetch() ? leaders : null); } return git; }