Can you get the number of lines of code from a GitHub repository?

前端 未结 15 1230
庸人自扰
庸人自扰 2020-12-04 04:26

In a GitHub repository you can see “language statistics”, which displays the percentage of the project that’s written in a language. It doesn’t, however, display ho

15条回答
  •  孤街浪徒
    2020-12-04 05:07

    You can use GitHub API to get the sloc like the following function

    function getSloc(repo, tries) {
    
        //repo is the repo's path
        if (!repo) {
            return Promise.reject(new Error("No repo provided"));
        }
    
        //GitHub's API may return an empty object the first time it is accessed
        //We can try several times then stop
        if (tries === 0) {
            return Promise.reject(new Error("Too many tries"));
        }
    
        let url = "https://api.github.com/repos" + repo + "/stats/code_frequency";
    
        return fetch(url)
            .then(x => x.json())
            .then(x => x.reduce((total, changes) => total + changes[1] + changes[2], 0))
            .catch(err => getSloc(repo, tries - 1));
    }
    

    Personally I made an chrome extension which shows the number of SLOC on both github project list and project detail page. You can also set your personal access token to access private repositories and bypass the api rate limit.

    You can download from here https://chrome.google.com/webstore/detail/github-sloc/fkjjjamhihnjmihibcmdnianbcbccpnn

    Source code is available here https://github.com/martianyi/github-sloc

提交回复
热议问题