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

前端 未结 15 1216
庸人自扰
庸人自扰 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

    If you go to the graphs/contributors page, you can see a list of all the contributors to the repo and how many lines they've added and removed.

    Unless I'm missing something, subtracting the aggregate number of lines deleted from the aggregate number of lines added among all contributors should yield the total number of lines of code in the repo. (EDIT: it turns out I was missing something after all. Take a look at orbitbot's comment for details.)

    UPDATE:

    This data is also available in GitHub's API. So I wrote a quick script to fetch the data and do the calculation:

    'use strict';
    
    function countGithub(repo) {
    fetch('https://api.github.com/repos/'+repo+'/stats/contributors')
        .then(response => response.json())
        .then(contributors => contributors
            .map(contributor => contributor.weeks
                .reduce((lineCount, week) => lineCount + week.a - week.d, 0)))
        .then(lineCounts => lineCounts.reduce((lineTotal, lineCount) => lineTotal + lineCount))
        .then(lines => window.alert(lines));
    }
    
    countGithub('jquery/jquery'); // or count anything you like

    Just paste it in a Chrome DevTools snippet, change the repo and click run.

    Disclaimer (thanks to lovasoa):

    Take the results of this method with a grain of salt, because for some repos (sorich87/bootstrap-tour) it results in negative values, which might indicate there's something wrong with the data returned from GitHub's API.

    UPDATE:

    Looks like this method to calculate total line numbers isn't entirely reliable. Take a look at orbitbot's comment for details.

提交回复
热议问题