Optional githubStars()

in buildSrc/src/main/groovy/org/grails/gradle/PluginsTask.groovy [144:174]


    Optional<Integer> githubStars(String vcsUrl) {
        if (!vcsUrl) {
            return Optional.empty()
        }
        if (!vcsUrl.contains("github.com")) {
            return Optional.empty()
        }
        if (!System.getenv("GH_TOKEN")) {
            return Optional.empty()
        }
        try {
            log.debug("fetching github stars of " + vcsUrl)
            String url = "https://api.github.com/repos/" + vcsUrl.substring(vcsUrl.indexOf("github.com/") + "github.com/".length())
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(new URI(url))
                    .header("X-GitHub-Api-Version", "2022-11-28")
                    .header("Authorization", "Bearer ${System.getenv("GH_TOKEN")}")
                    .GET()
                    .build()
            HttpResponse<String> response = HttpClient.newBuilder().build().send(request, HttpResponse.BodyHandlers.ofString())
            if (response.statusCode() == 200) {
                String json = response.body()
                Integer stars = new JsonSlurper().parseText(json).stargazers_count as Integer
                return stars == 0 ? Optional.empty() : Optional.of(stars)
            }
        } catch (Exception e) {
            println e.message
            return Optional.empty()
        }
        return Optional.empty()
    }