Java Code Examples for org.kohsuke.github.GitHub#getRepository()

The following examples show how to use org.kohsuke.github.GitHub#getRepository() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LauncherUpdater.java    From TerasologyLauncher with Apache License 2.0 6 votes vote down vote up
/**
 * This method indicates if a new launcher version is available.
 * <br>
 * Compares the current launcher version number to the upstream version number if an internet connection is available.
 *
 * @return a {@link GHRelease} if an update is available, null otherwise
 */
//TODO: return Option<GitHubRelease>
public GHRelease updateAvailable() {
    //TODO: only check of both version are defined and valid semver?
    try {
        final GitHub github = GitHub.connectAnonymously();
        final GHRepository repository = github.getRepository("MovingBlocks/TerasologyLauncher");
        final GHRelease latestRelease = repository.getLatestRelease();
        final Semver latestVersion = versionOf(latestRelease);

        if (latestVersion.isGreaterThan(currentVersion)) {
            return latestRelease;
        }
    } catch (IOException e) {
        logger.warn("Update check failed: {}", e.getMessage());
    }
    return null;
}
 
Example 2
Source File: AbstractRepairStep.java    From repairnator with MIT License 6 votes vote down vote up
protected void createPullRequest(String baseBranch,String newBranch) throws IOException, GitAPIException, URISyntaxException {
    GitHub github = RepairnatorConfig.getInstance().getGithub();

    GHRepository originalRepository = github.getRepository(this.getInspector().getRepoSlug());
    GHRepository ghForkedRepo = originalRepository.fork();

    String base = baseBranch;
    String head = ghForkedRepo.getOwnerName() + ":" + newBranch;

    System.out.println("base: " + base + " head:" + head);
    String travisURL = this.getInspector().getBuggyBuild() == null ? "" : Utils.getTravisUrl(this.getInspector().getBuggyBuild().getId(), this.getInspector().getRepoSlug());
    Map<String, String> values = new HashMap<String, String>();
    values.put("travisURL", travisURL);
    values.put("tools", String.join(",", this.getConfig().getRepairTools()));
    values.put("slug", this.getInspector().getRepoSlug());

    if (prText == null) {
        StrSubstitutor sub = new StrSubstitutor(values, "%(", ")");
        this.prText = sub.replace(DEFAULT_TEXT_PR);
    }

    GHPullRequest pullRequest = originalRepository.createPullRequest(prTitle, head, base, this.prText);
    String prURL = "https://github.com/" + this.getInspector().getRepoSlug() + "/pull/" + pullRequest.getNumber();
    this.getLogger().info("Pull request created on: " + prURL);
    this.getInspector().getJobStatus().addPRCreated(prURL);
}
 
Example 3
Source File: GitHubPluginRepoProvider2.java    From github-integration-plugin with MIT License 6 votes vote down vote up
private NullSafePredicate<GitHub> withPermission(final GitHubRepositoryName name, GHPermission permission) {
    return new NullSafePredicate<GitHub>() {
        @Override
        protected boolean applyNullSafe(@Nonnull GitHub gh) {
            try {
                final GHRepository repo = gh.getRepository(name.getUserName() + "/" + name.getRepositoryName());
                if (permission == GHPermission.ADMIN) {
                    return repo.hasAdminAccess();
                } else if (permission == GHPermission.PUSH) {
                    return repo.hasPushAccess();
                } else {
                    return repo.hasPullAccess();
                }
            } catch (IOException e) {
                return false;
            }
        }
    };
}
 
Example 4
Source File: GitHubPluginRepoProvider.java    From github-integration-plugin with MIT License 6 votes vote down vote up
private NullSafePredicate<GitHub> withPermission(final GitHubRepositoryName name, GHPermission permission) {
    return new NullSafePredicate<GitHub>() {
        @Override
        protected boolean applyNullSafe(@Nonnull GitHub gh) {
            try {
                final GHRepository repo = gh.getRepository(name.getUserName() + "/" + name.getRepositoryName());
                if (permission == GHPermission.ADMIN) {
                    return repo.hasAdminAccess();
                } else if (permission == GHPermission.PUSH) {
                    return repo.hasPushAccess();
                } else {
                    return repo.hasPullAccess();
                }
            } catch (IOException e) {
                return false;
            }
        }
    };
}
 
Example 5
Source File: GithubApi.java    From karamel with Apache License 2.0 6 votes vote down vote up
public synchronized static void removeRepo(String owner, String repoName) throws KaramelException {

    try {
      GitHub gitHub = GitHub.connectUsingPassword(GithubApi.getUser(), GithubApi.getPassword());
      if (!gitHub.isCredentialValid()) {
        throw new KaramelException("Invalid GitHub credentials");
      }
      GHRepository repo = null;
      if (owner.compareToIgnoreCase(GithubApi.getUser()) != 0) {
        GHOrganization org = gitHub.getOrganization(owner);
        repo = org.getRepository(repoName);
      } else {
        repo = gitHub.getRepository(owner + "/" + repoName);
      }
      repo.delete();

    } catch (IOException ex) {
      throw new KaramelException("Problem authenticating with gihub-api when trying to remove a repository");
    }
  }
 
Example 6
Source File: gh_fetch_release_assets.java    From jbang with MIT License 6 votes vote down vote up
@Override
public Integer call() throws Exception { // your business logic goes here...
    GitHub github = GitHub.connectAnonymously();

    var ghRepo = github.getRepository(repo);
    ghRepo.archive();

    PagedIterator<GHRelease> releases = ghRepo.listReleases().iterator();
    if(releases.hasNext()) {
        var release = releases.next();
        for(GHAsset asset: release.getAssets()) {
            if(assetPattern.matcher(asset.getName()).matches()) {
                System.out.println(asset.getBrowserDownloadUrl());
                //System.out.println(asset.getName());
            }
        }
    } else {
        System.err.println("No releases found.");
        return CommandLine.ExitCode.SOFTWARE;
    }

    return CommandLine.ExitCode.OK;
}
 
Example 7
Source File: GitHubSCMProbeTest.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
void createProbeForPR(int number) throws IOException {
    final GitHub github = Connector.connect("http://localhost:" + githubApi.port(), null);

    final GHRepository repo = github.getRepository("cloudbeers/yolo");
    final PullRequestSCMHead head = new PullRequestSCMHead("PR-" + number, "cloudbeers", "yolo", "b", number, new BranchSCMHead("master"), new SCMHeadOrigin.Fork("rsandell"), ChangeRequestCheckoutStrategy.MERGE);
    probe = new GitHubSCMProbe(github, repo,
        head,
        new PullRequestSCMRevision(head, "a", "b"));
}
 
Example 8
Source File: NotesBuilder.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Creates the connection to the remote repository.
 *
 * @param authToken the authorization token.
 * @param remoteRepoPath path to remote git repository.
 * @return the remote repository object.
 * @throws IOException if an I/O error occurs.
 */
private static GHRepository createRemoteRepo(String authToken, String remoteRepoPath)
        throws IOException {
    final GitHub connection;
    if (authToken == null) {
        connection = GitHub.connectAnonymously();
    }
    else {
        connection = GitHub.connectUsingOAuth(authToken);
    }

    return connection.getRepository(remoteRepoPath);
}
 
Example 9
Source File: GitHistoryRefactoringMinerImpl.java    From RefactoringMiner with MIT License 5 votes vote down vote up
@Override
public void detectAtPullRequest(String cloneURL, int pullRequestId, RefactoringHandler handler, int timeout) throws IOException {
	GitHub gitHub = connectToGitHub();
	String repoName = extractRepositoryName(cloneURL);
	GHRepository repository = gitHub.getRepository(repoName);
	GHPullRequest pullRequest = repository.getPullRequest(pullRequestId);
	PagedIterable<GHPullRequestCommitDetail> commits = pullRequest.listCommits();
	for(GHPullRequestCommitDetail commit : commits) {
		detectAtCommit(cloneURL, commit.getSha(), handler, timeout);
	}
}
 
Example 10
Source File: GitHistoryRefactoringMinerImpl.java    From RefactoringMiner with MIT License 5 votes vote down vote up
private String populateWithGitHubAPI(String cloneURL, String currentCommitId,
		List<String> filesBefore, List<String> filesCurrent, Map<String, String> renamedFilesHint) throws IOException {
	logger.info("Processing {} {} ...", cloneURL, currentCommitId);
	GitHub gitHub = connectToGitHub();
	String repoName = extractRepositoryName(cloneURL);
	GHRepository repository = gitHub.getRepository(repoName);
	GHCommit commit = repository.getCommit(currentCommitId);
	String parentCommitId = commit.getParents().get(0).getSHA1();
	List<GHCommit.File> commitFiles = commit.getFiles();
	for (GHCommit.File commitFile : commitFiles) {
		if (commitFile.getFileName().endsWith(".java")) {
			if (commitFile.getStatus().equals("modified")) {
				filesBefore.add(commitFile.getFileName());
				filesCurrent.add(commitFile.getFileName());
			}
			else if (commitFile.getStatus().equals("added")) {
				filesCurrent.add(commitFile.getFileName());
			}
			else if (commitFile.getStatus().equals("removed")) {
				filesBefore.add(commitFile.getFileName());
			}
			else if (commitFile.getStatus().equals("renamed")) {
				filesBefore.add(commitFile.getPreviousFilename());
				filesCurrent.add(commitFile.getFileName());
				renamedFilesHint.put(commitFile.getPreviousFilename(), commitFile.getFileName());
			}
		}
	}
	return parentCommitId;
}
 
Example 11
Source File: GitHubProvider.java    From gocd-build-status-notifier with Apache License 2.0 5 votes vote down vote up
void updateCommitStatus(String revision, String pipelineStage, String trackbackURL, String repository, GHCommitState state,
                        String usernameToUse, String passwordToUse, String oauthAccessTokenToUse, String endPointToUse) throws Exception {
    LOGGER.info("Updating commit status for '%s' on '%s'", revision, pipelineStage);

    GitHub github = createGitHubClient(usernameToUse, passwordToUse, oauthAccessTokenToUse, endPointToUse);
    GHRepository ghRepository = github.getRepository(repository);
    ghRepository.createCommitStatus(revision, state, trackbackURL, "", pipelineStage);
}
 
Example 12
Source File: GitHubBuildStatusNotification.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
/**
 * Returns the GitHub Repository associated to a Job.
 *
 * @param job A {@link Job}
 * @return A {@link GHRepository} or null, either if a scan credentials was not provided, or a GitHubSCMSource was not defined.
 * @throws IOException
 */
@CheckForNull
private static GHRepository lookUpRepo(GitHub github, @NonNull Job<?,?> job) throws IOException {
    if (github == null) {
        return null;
    }
    SCMSource src = SCMSource.SourceByItem.findSource(job);
    if (src instanceof GitHubSCMSource) {
        GitHubSCMSource source = (GitHubSCMSource) src;
        if (source.getScanCredentialsId() != null) {
            return github.getRepository(source.getRepoOwner() + "/" + source.getRepository());
        }
    }
    return null;
}
 
Example 13
Source File: GitHubSCMSource.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@NonNull
@Override
protected List<Action> retrieveActions(@CheckForNull SCMSourceEvent event,
                                       @NonNull TaskListener listener) throws IOException {
    // TODO when we have support for trusted events, use the details from event if event was from trusted source
    List<Action> result = new ArrayList<>();
    result.add(new GitHubRepoMetadataAction());
    String repository = this.repository;

    StandardCredentials credentials = Connector.lookupScanCredentials((Item) getOwner(), apiUri, credentialsId);
    GitHub hub = Connector.connect(apiUri, credentials);
    try {
        Connector.checkConnectionValidity(apiUri, listener, credentials, hub);
        try {
            ghRepository = hub.getRepository(getRepoOwner() + '/' + repository);
            resolvedRepositoryUrl = ghRepository.getHtmlUrl();
        } catch (FileNotFoundException e) {
            throw new AbortException(
                    String.format("Invalid scan credentials when using %s to connect to %s/%s on %s",
                            credentials == null ? "anonymous access" : CredentialsNameProvider.name(credentials), repoOwner, repository, apiUri));
        }
        result.add(new ObjectMetadataAction(null, ghRepository.getDescription(), Util.fixEmpty(ghRepository.getHomepage())));
        result.add(new GitHubLink("icon-github-repo", ghRepository.getHtmlUrl()));
        if (StringUtils.isNotBlank(ghRepository.getDefaultBranch())) {
            result.add(new GitHubDefaultBranch(getRepoOwner(), repository, ghRepository.getDefaultBranch()));
        }
        return result;
    } finally {
        Connector.release(hub);
    }
}
 
Example 14
Source File: GitHubSCMSource.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
@NonNull
@Override
protected SCMProbe createProbe(@NonNull SCMHead head, @CheckForNull final SCMRevision revision) throws IOException {
    StandardCredentials credentials = Connector.lookupScanCredentials((Item) getOwner(), apiUri, credentialsId);
    // Github client and validation
    GitHub github = Connector.connect(apiUri, credentials);
    try {
        String fullName = repoOwner + "/" + repository;
        final GHRepository repo = github.getRepository(fullName);
        return new GitHubSCMProbe(github, repo, head, revision);
    } catch (IOException | RuntimeException | Error e) {
        Connector.release(github);
        throw e;
    }
}
 
Example 15
Source File: GitHelper.java    From repairnator with MIT License 5 votes vote down vote up
public String forkRepository(String repository, AbstractStep step) throws IOException {
    GitHub gh = RepairnatorConfig.getInstance().getGithub();
    showGitHubRateInformation(gh, step);
    if (gh.getRateLimit().remaining > 10) {
        GHRepository originalRepo = gh.getRepository(repository);
        if (originalRepo != null) {
            return originalRepo.fork().getUrl().toString();
        }
    }
    return null;
}
 
Example 16
Source File: GitHubSCMSource.java    From github-branch-source-plugin with MIT License 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@NonNull
@Override
protected Set<String> create() {
    if (collaboratorNames != null) {
        return collaboratorNames;
    }
    listener.getLogger().format("Connecting to %s to obtain list of collaborators for %s/%s%n",
            apiUri, repoOwner, repository);
    StandardCredentials credentials = Connector.lookupScanCredentials(
            (Item) getOwner(), apiUri, credentialsId
    );
    // Github client and validation
    try {
        GitHub github = Connector.connect(apiUri, credentials);
        try {
            checkApiUrlValidity(github, credentials);
            Connector.checkApiRateLimit(listener, github);

            // Input data validation
            Connector.checkConnectionValidity(apiUri, listener, credentials, github);
            // Input data validation
            String credentialsName =
                    credentials == null
                            ? "anonymous access"
                            : CredentialsNameProvider.name(credentials);
            if (credentials != null && !isCredentialValid(github)) {
                listener.getLogger().format("Invalid scan credentials %s to connect to %s, "
                                + "assuming no trusted collaborators%n",
                        credentialsName, apiUri);
                collaboratorNames = Collections.singleton(repoOwner);
            } else {
                if (!github.isAnonymous()) {
                    listener.getLogger()
                            .format("Connecting to %s using %s%n",
                                    apiUri,
                                    credentialsName);
                } else {
                    listener.getLogger()
                            .format("Connecting to %s with no credentials, anonymous access%n",
                                    apiUri);
                }

                // Input data validation
                if (isBlank(getRepository())) {
                    collaboratorNames = Collections.singleton(repoOwner);
                } else {
                    request.checkApiRateLimit();
                    String fullName = repoOwner + "/" + repository;
                    ghRepository = github.getRepository(fullName);
                    resolvedRepositoryUrl = ghRepository.getHtmlUrl();
                    return new LazyContributorNames(request, listener, github, ghRepository, credentials);
                }
            }
            return collaboratorNames;
        } finally {
            Connector.release(github);
        }
    } catch (IOException | InterruptedException e) {
        throw new WrappedException(e);
    }
}
 
Example 17
Source File: GitHubUtils.java    From oncokb with GNU Affero General Public License v3.0 4 votes vote down vote up
private static GHRepository getOncoKBDataRepo() throws IOException, NoPropertyException {
    GitHub github = getGitHubConnection();
    return github.getRepository(ONCOKB_DATA_REPO);
}
 
Example 18
Source File: Utility.java    From iBioSim with Apache License 2.0 4 votes vote down vote up
public static void submitBugReport(String message) {
		JPanel reportBugPanel = new JPanel(new GridLayout(4,1));
		JLabel typeLabel = new JLabel("Type of Report:");
		JComboBox reportType = new JComboBox(Utility.bugReportTypes);
		
		if (!message.equals("")) {
			typeLabel.setEnabled(false);
			reportType.setEnabled(false);
		}
		
		JPanel typePanel = new JPanel(new GridLayout(1,2));
		typePanel.add(typeLabel);
		typePanel.add(reportType);
		JLabel emailLabel = new JLabel("Email address:");
		JTextField emailAddr = new JTextField(30);
		JPanel emailPanel = new JPanel(new GridLayout(1,2));
		emailPanel.add(emailLabel);
		emailPanel.add(emailAddr);
		JLabel bugSubjectLabel = new JLabel("Brief Description:");
		JTextField bugSubject = new JTextField(30);
		JPanel bugSubjectPanel = new JPanel(new GridLayout(1,2));
		bugSubjectPanel.add(bugSubjectLabel);
		bugSubjectPanel.add(bugSubject);
		JLabel bugDetailLabel = new JLabel("Detailed Description:");
		JTextArea bugDetail = new JTextArea(5,30);
		bugDetail.setLineWrap(true);
		bugDetail.setWrapStyleWord(true);
		JScrollPane scroll = new JScrollPane();
		scroll.setMinimumSize(new Dimension(100, 100));
		scroll.setPreferredSize(new Dimension(100, 100));
		scroll.setViewportView(bugDetail);
		JPanel bugDetailPanel = new JPanel(new GridLayout(1,2));
		bugDetailPanel.add(bugDetailLabel);
		bugDetailPanel.add(scroll);
		reportBugPanel.add(typePanel);
		reportBugPanel.add(emailPanel);
		reportBugPanel.add(bugSubjectPanel);
		reportBugPanel.add(bugDetailPanel);
		Object[] options = { "Send", "Cancel" };
		
		int value = JOptionPane.showOptionDialog(Gui.frame, reportBugPanel, "Bug Report",
				JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
		
		if (value == 0) {
			try {
                // Split the token in two to fool GitHub
				GitHub github = GitHub.connectUsingPassword("buggsley", "ibiosim3280");
				//GitHub github = new GitHubBuilder().withOAuthToken("79da2a9510ebdfa5fa2a" + "80416e1598b2ad05190f").build(); 
				GHRepository iBioSimRepository = github.getRepository("MyersResearchGroup/iBioSim");
				GHIssueBuilder issue = iBioSimRepository.createIssue(bugSubject.getText().trim());
				issue.body(System.getProperty("software.running") + "\n\nOperating system: " + 
						System.getProperty("os.name") + "\n\nBug reported by: " + emailAddr.getText().trim() + 
						"\n\nDescription:\n"+bugDetail.getText().trim()+message);
				issue.label(reportType.getSelectedItem().toString());
				issue.create();
			} catch (IOException e) {
				JOptionPane.showMessageDialog(Gui.frame, "Bug report failed, please submit manually.",
						"Bug Report Failed", JOptionPane.ERROR_MESSAGE);
				e.printStackTrace();
				Preferences biosimrc = Preferences.userRoot();
				String command = biosimrc.get("biosim.general.browser", "");
				command = command + " http://www.github.com/MyersResearchGroup/iBioSim/issues";
				Runtime exec = Runtime.getRuntime();
				
				try
				{
					exec.exec(command);
				}
				catch (IOException e1)
				{
					JOptionPane.showMessageDialog(Gui.frame, "Unable to open bug database.", "Error", JOptionPane.ERROR_MESSAGE);
				}
			}
		}
		
//		JOptionPane.showMessageDialog(Gui.frame, "Please verify that your bug report is in the incoming folder.\n" +
//				"If not, please submit your bug report manually using the web interface.\n", 
//				"Bug Report", JOptionPane.ERROR_MESSAGE);
//		submitBugReportTemp(message);
	}
 
Example 19
Source File: GithubRepoAction.java    From DotCi with MIT License 4 votes vote down vote up
protected GHRepository getGithubRepository(StaplerRequest request) throws IOException {
    String repoName = request.getParameter("fullName");

    GitHub github = getGitHub(request);
    return github.getRepository(repoName);
}
 
Example 20
Source File: TestCommon.java    From dockerfile-image-update with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static void addVersionStoreRepo(GitHub github, List<GHRepository> createdRepos, String storeName) throws IOException {
    String login = github.getMyself().getLogin();
    GHRepository storeRepo = github.getRepository(Paths.get(login, storeName).toString());
    createdRepos.add(storeRepo);
}