Search in sources :

Example 16 with GitHub

use of org.kohsuke.github.GitHub in project repairnator by Spirals-Team.

the class EvaluatePotentialBug method computeScore.

private int computeScore(RepairInfo repairInfo) throws IOException {
    int score = 0;
    GitHub gitHub = GitHubBuilder.fromEnvironment().withOAuthToken(this.githubToken, this.githubLogin).build();
    GHRepository ghRepo = gitHub.getRepository(repairInfo.getGithubProject());
    String commitMsg = ghRepo.getCommit(repairInfo.getPatchCommit()).getCommitShortInfo().getMessage();
    score += this.computeScoreForMessage(commitMsg, 10, 20);
    if (repairInfo.getPrId() != null) {
        GHPullRequest pullRequest = ghRepo.getPullRequest(Integer.parseInt(repairInfo.getPrId()));
        score += this.computeScoreForMessage(pullRequest.getTitle(), 100, 120);
        try {
            for (GHLabel label : pullRequest.getLabels()) {
                score += this.computeScoreForMessage(label.getName(), 100, 120);
            }
        } catch (HttpException e) {
        }
        for (GHIssueComment comment : pullRequest.getComments()) {
            if (comment.getUser().equals(pullRequest.getUser())) {
                score += this.computeScoreForMessage(commitMsg, 10, 20);
            } else {
                score += this.computeScoreForMessage(commitMsg, 1, 2);
            }
        }
    }
    Matcher matcher = ISSUE_PATTERN.matcher(commitMsg);
    List<Integer> issuesOrPr = new ArrayList<>();
    while (matcher.find()) {
        int newIssueOrPRId = Integer.parseInt(matcher.group().substring(1));
        issuesOrPr.add(newIssueOrPRId);
    }
    for (int issueOrPRId : issuesOrPr) {
        GHIssue prOrIssue;
        try {
            prOrIssue = ghRepo.getPullRequest(issueOrPRId);
            if (prOrIssue == null) {
                prOrIssue = ghRepo.getIssue(issueOrPRId);
            }
        } catch (Exception e) {
            prOrIssue = ghRepo.getIssue(issueOrPRId);
        }
        if (prOrIssue != null) {
            score += this.computeScoreForMessage(prOrIssue.getTitle(), 80, 100);
            for (GHIssueComment comment : prOrIssue.getComments()) {
                if (comment.getUserName().equals(prOrIssue.getUser().getLogin())) {
                    score += this.computeScoreForMessage(commitMsg, 10, 20);
                } else {
                    score += this.computeScoreForMessage(commitMsg, 1, 2);
                }
            }
            try {
                for (GHLabel label : prOrIssue.getLabels()) {
                    score += this.computeScoreForMessage(label.getName(), 100, 120);
                }
            } catch (HttpException e) {
            }
        }
    }
    return score;
}
Also used : GHLabel(org.kohsuke.github.GHLabel) GHRepository(org.kohsuke.github.GHRepository) Matcher(java.util.regex.Matcher) PathMatcher(java.nio.file.PathMatcher) GitHub(org.kohsuke.github.GitHub) ArrayList(java.util.ArrayList) GHIssue(org.kohsuke.github.GHIssue) ParseException(org.json.simple.parser.ParseException) HttpException(org.kohsuke.github.HttpException) IOException(java.io.IOException) GHPullRequest(org.kohsuke.github.GHPullRequest) HttpException(org.kohsuke.github.HttpException) GHIssueComment(org.kohsuke.github.GHIssueComment)

Example 17 with GitHub

use of org.kohsuke.github.GitHub in project blueocean-plugin by jenkinsci.

the class GithubScm method getOrganizations.

@Override
public Container<ScmOrganization> getOrganizations() {
    StandardUsernamePasswordCredentials credential = getCredential();
    String accessToken = credential.getPassword().getPlainText();
    try {
        GitHub github = GitHubFactory.connect(accessToken, getUri());
        final Link link = getLink().rel("organizations");
        // preserve the same order that github org api returns
        Map<String, ScmOrganization> orgMap = new LinkedHashMap<>();
        for (Map.Entry<String, GHOrganization> entry : github.getMyOrganizations().entrySet()) {
            orgMap.put(entry.getKey(), new GithubOrganization(GithubScm.this, entry.getValue(), credential, link));
        }
        GHMyself user = github.getMyself();
        if (orgMap.get(user.getLogin()) == null) {
            // this is to take care of case if/when github starts reporting user login as org later on
            orgMap = new HashMap<>(orgMap);
            orgMap.put(user.getLogin(), new GithubUserOrganization(user, credential, this));
        }
        final Map<String, ScmOrganization> orgs = orgMap;
        return new Container<ScmOrganization>() {

            @Override
            public ScmOrganization get(String name) {
                ScmOrganization org = orgs.get(name);
                if (org == null) {
                    throw new ServiceException.NotFoundException(String.format("GitHub organization %s not found", name));
                }
                return org;
            }

            @Override
            public Link getLink() {
                return link;
            }

            @Override
            public Iterator<ScmOrganization> iterator() {
                return orgs.values().iterator();
            }
        };
    } catch (IOException e) {
        if (e instanceof HttpException) {
            HttpException ex = (HttpException) e;
            if (ex.getResponseCode() == 401) {
                throw new ServiceException.PreconditionRequired("Invalid GitHub accessToken", ex);
            } else if (ex.getResponseCode() == 403) {
                throw new ServiceException.PreconditionRequired("GitHub accessToken does not have required scopes. Expected scopes 'user:email, repo'", ex);
            }
        }
        throw new ServiceException.UnexpectedErrorException(e.getMessage(), e);
    }
}
Also used : GHMyself(org.kohsuke.github.GHMyself) GitHub(org.kohsuke.github.GitHub) IOException(java.io.IOException) LinkedHashMap(java.util.LinkedHashMap) StandardUsernamePasswordCredentials(com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials) ScmOrganization(io.jenkins.blueocean.rest.impl.pipeline.scm.ScmOrganization) ScmServerEndpointContainer(io.jenkins.blueocean.rest.impl.pipeline.scm.ScmServerEndpointContainer) Container(io.jenkins.blueocean.rest.model.Container) ServiceException(io.jenkins.blueocean.commons.ServiceException) GHOrganization(org.kohsuke.github.GHOrganization) HttpException(org.kohsuke.github.HttpException) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Link(io.jenkins.blueocean.rest.hal.Link)

Example 18 with GitHub

use of org.kohsuke.github.GitHub in project blueocean-plugin by jenkinsci.

the class GithubHelper method createEmptyRepository.

public String createEmptyRepository() throws IOException {
    GitHub github = getGitHub();
    String repositoryName = !useRandomSuffix ? this.repositoryName : this.repositoryName + "-" + getRandomSuffix();
    try {
        String repositoryFullname = organizationOrUsername + "/" + repositoryName;
        GHRepository repositoryToDelete = github.getRepository(repositoryFullname);
        repositoryToDelete.delete();
        logger.info("Deleted repository " + repositoryFullname);
    } catch (FileNotFoundException e) {
    // fine to ignore error if the repo doesn't exist
    }
    GHCreateRepositoryBuilder builder;
    if (organizationOrUsername.equals(github.getMyself().getLogin())) {
        builder = github.createRepository(repositoryName);
    } else {
        try {
            builder = github.getOrganization(organizationOrUsername).createRepository(repositoryName);
        } catch (FileNotFoundException e) {
            logger.error("found not find organization " + organizationOrUsername);
            throw e;
        }
    }
    githubRepository = builder.autoInit(true).create();
    logger.info("Created repository " + githubRepository.getFullName());
    return repositoryName;
}
Also used : GHRepository(org.kohsuke.github.GHRepository) GitHub(org.kohsuke.github.GitHub) FileNotFoundException(java.io.FileNotFoundException) GHCreateRepositoryBuilder(org.kohsuke.github.GHCreateRepositoryBuilder)

Example 19 with GitHub

use of org.kohsuke.github.GitHub in project Robot by fo0.

the class UpdateUtils method doUpdate.

public static void doUpdate() {
    try {
        GitHub gitHub = GitHub.connectAnonymously();
        GHRepository repository = gitHub.getRepository(CONSTANTS.GITHUB_URI);
        GHRelease latest = repository.getLatestRelease();
        boolean newerVersionAvailable = new Semver(latest.getTagName().replaceAll("v", "")).isGreaterThan(new Semver(CONSTANTS.VERSION));
        if (!newerVersionAvailable) {
            Logger.info("no newer version available, skipping now");
            Logger.info("current version: " + CONSTANTS.VERSION);
            Logger.info("latest version: " + latest.getTagName().replaceAll("v", ""));
            return;
        } else {
            Logger.info("detected new version");
            Logger.info("current version: " + CONSTANTS.VERSION);
            Logger.info("latest version: " + latest.getTagName().replaceAll("v", ""));
        }
        GHAsset asset = latest.getAssets().get(0);
        Logger.info("downloading file from github: " + asset.getBrowserDownloadUrl());
        File latestFile = File.createTempFile(Random.alphanumeric(10), ".patch");
        latestFile.deleteOnExit();
        FileUtils.copyToFile(new URL(asset.getBrowserDownloadUrl()).openStream(), latestFile);
        Logger.info("download finished");
        Logger.info("applying patch...");
        File currentPath = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath());
        Utils.writeBytesToFile(IOUtils.toByteArray(new FileInputStream(latestFile)), currentPath);
        // FileUtils.moveFile(latestFile, currentPath);
        try {
            latestFile.delete();
        } catch (Exception e) {
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : GHRepository(org.kohsuke.github.GHRepository) GitHub(org.kohsuke.github.GitHub) Semver(com.vdurmont.semver4j.Semver) File(java.io.File) GHAsset(org.kohsuke.github.GHAsset) URL(java.net.URL) FileInputStream(java.io.FileInputStream) GHRelease(org.kohsuke.github.GHRelease)

Example 20 with GitHub

use of org.kohsuke.github.GitHub in project contribution by checkstyle.

the class Main method runNotesBuilder.

/**
 * Executes NotesBuilder based on passed command line options.
 * @param cliOptions command line options.
 * @return result of NotesBuilder work.
 * @throws IOException if an I/O error occurs.
 * @throws GitAPIException if an error occurs while accessing GitHub API.
 */
private static Result runNotesBuilder(CliOptions cliOptions) throws IOException, GitAPIException {
    final String localRepoPath = cliOptions.getLocalRepoPath();
    final String startRef = cliOptions.getStartRef();
    final String endRef = cliOptions.getEndRef();
    final String authToken = cliOptions.getAuthToken();
    final GitHub connection;
    if (authToken == null) {
        connection = GitHub.connectAnonymously();
    } else {
        connection = GitHub.connectUsingOAuth(authToken);
    }
    final GHRepository remoteRepo = connection.getRepository(REMOTE_REPO_PATH);
    final Result result = NotesBuilder.buildResult(remoteRepo, localRepoPath, startRef, endRef);
    if (result.hasWarnings()) {
        printListOf(result.getWarningMessages());
    }
    if (result.hasErrors()) {
        printListOf(result.getErrorMessages());
    }
    return result;
}
Also used : GHRepository(org.kohsuke.github.GHRepository) GitHub(org.kohsuke.github.GitHub)

Aggregations

GitHub (org.kohsuke.github.GitHub)21 GHRepository (org.kohsuke.github.GHRepository)17 IOException (java.io.IOException)10 Test (org.junit.Test)5 GHRelease (org.kohsuke.github.GHRelease)5 Semver (com.vdurmont.semver4j.Semver)4 File (java.io.File)3 ArrayList (java.util.ArrayList)3 GHContent (org.kohsuke.github.GHContent)3 GHIssue (org.kohsuke.github.GHIssue)3 NextProtException (org.nextprot.api.commons.exception.NextProtException)3 Cacheable (org.springframework.cache.annotation.Cacheable)3 FileInputStream (java.io.FileInputStream)2 URL (java.net.URL)2 HashMap (java.util.HashMap)2 GHAsset (org.kohsuke.github.GHAsset)2 GHUser (org.kohsuke.github.GHUser)2 HttpException (org.kohsuke.github.HttpException)2 StandardUsernamePasswordCredentials (com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials)1 ServiceException (io.jenkins.blueocean.commons.ServiceException)1