├── .gitattributes ├── .github └── workflows │ ├── auto_update_stat_images.yml │ ├── non_auto_generate_stat_images.yml │ └── pull_request_code_convention.yml ├── .gitignore ├── LICENSE ├── README.md ├── __init__.py ├── git_stats_imgs.py ├── requirements.txt ├── src ├── __init__.py ├── db │ ├── __init__.py │ ├── db.json │ └── db.py ├── env_vars.py ├── generate_images.py ├── github_api_queries.py ├── github_repo_stats.py └── templates │ ├── languages.svg │ └── overview.svg └── test ├── __init__.py └── git_stats_test.py /.gitattributes: -------------------------------------------------------------------------------- 1 | data export-ignore 2 | generated export-ignore 3 | -------------------------------------------------------------------------------- /.github/workflows/auto_update_stat_images.yml: -------------------------------------------------------------------------------- 1 | # This is a scheduled workflow for daily automatic updates to the actions_branch branch 2 | 3 | name: Auto Update Stats Images 4 | 5 | # Controls when the action will run. Triggers the workflow on auto-scheduled push events 6 | on: 7 | schedule: 8 | - cron: "30 0 * * 0" 9 | workflow_dispatch: 10 | 11 | permissions: 12 | contents: write 13 | 14 | # A workflow run is made up of one or more jobs that can run sequentially or in parallel 15 | jobs: 16 | 17 | # This workflow contains a single job called "build" 18 | build: 19 | 20 | # The type of runner that the job will run on 21 | runs-on: ubuntu-latest 22 | 23 | # Sequence of tasks that will be executed as part of the job 24 | steps: 25 | 26 | # Checks-out repository under $GITHUB_WORKSPACE, so the job can access it 27 | - name: Check out code 28 | uses: actions/checkout@v4 29 | 30 | # Run using Python 3.13 for consistency and aiohttp 31 | - name: Set up Python 3.13 32 | uses: actions/setup-python@v5 33 | with: 34 | python-version: '3.13' 35 | architecture: 'x64' 36 | cache: pip 37 | cache-dependency-path: '**/requirements.txt' 38 | 39 | # Switch to actions_branch if not exist, or create new actions_branch 40 | - name: Switch to actions_branch 41 | run: | 42 | git fetch 43 | git checkout actions_branch 3>/dev/null || git checkout -b actions_branch 44 | git pull origin actions_branch 45 | 46 | # Install dependencies with `pip` 47 | - name: Install requirements 48 | run: | 49 | python3 -m pip install --upgrade pip setuptools wheel 50 | python3 -m pip install -r requirements.txt 51 | 52 | # Generate all statistics images 53 | - name: Generate images 54 | run: | 55 | python3 --version 56 | python3 git_stats_imgs.py 57 | env: 58 | ACCESS_TOKEN: ${{ secrets.ACCESS_TOKEN }} 59 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 60 | EXCLUDED_REPOS: ${{ secrets.EXCLUDED_REPOS }} 61 | EXCLUDED_OWNERS: ${{ secrets.EXCLUDED_OWNERS }} 62 | EXCLUDED_LANGS: ${{ secrets.EXCLUDED_LANGS }} 63 | EXCLUDED_REPO_LANGS: ${{ secrets.EXCLUDED_REPO_LANGS }} 64 | IS_INCLUDE_FORKED_REPOS: ${{ secrets.IS_INCLUDE_FORKED_REPOS }} 65 | IS_EXCLUDE_CONTRIB_REPOS: ${{ secrets.IS_EXCLUDE_CONTRIB_REPOS }} 66 | IS_EXCLUDE_ARCHIVE_REPOS: ${{ secrets.IS_EXCLUDE_ARCHIVE_REPOS }} 67 | IS_EXCLUDE_PRIVATE_REPOS: ${{ secrets.IS_EXCLUDE_PRIVATE_REPOS }} 68 | IS_EXCLUDE_PUBLIC_REPOS: ${{ secrets.IS_EXCLUDE_PUBLIC_REPOS }} 69 | REPO_VIEWS: ${{ secrets.REPO_VIEWS }} 70 | LAST_VIEWED: ${{ secrets.LAST_VIEWED }} 71 | FIRST_VIEWED: ${{ secrets.FIRST_VIEWED }} 72 | IS_STORE_REPO_VIEWS: ${{ secrets.IS_STORE_REPO_VIEWS }} 73 | MORE_COLLABS: ${{ secrets.MORE_COLLABS }} 74 | MORE_REPOS: ${{ secrets.MORE_REPOS }} 75 | ONLY_INCLUDED_REPOS: ${{ secrets.ONLY_INCLUDED_REPOS }} 76 | ONLY_INCLUDED_OWNERS: ${{ secrets.ONLY_INCLUDED_OWNERS }} 77 | ONLY_INCLUDED_COLLAB_REPOS: ${{ secrets.ONLY_INCLUDED_COLLAB_REPOS }} 78 | ONLY_INCLUDED_COLLAB_REPO_OWNERS: ${{ secrets.ONLY_INCLUDED_COLLAB_REPO_OWNERS }} 79 | EXCLUDED_COLLAB_REPOS: ${{ secrets.EXCLUDED_COLLAB_REPOS }} 80 | EXCLUDED_COLLAB_REPO_OWNERS: ${{ secrets.EXCLUDED_COLLAB_REPO_OWNERS }} 81 | MORE_COLLAB_REPOS: ${{ secrets.MORE_COLLAB_REPOS }} 82 | MORE_COLLAB_REPO_OWNERS: ${{ secrets.MORE_COLLAB_REPO_OWNERS }} 83 | 84 | # Commits all changed files to the repository 85 | - name: Commit to the repo 86 | run: | 87 | git config user.name "GitHub Actions" 88 | git config user.email "actions@github.com" 89 | git add . 90 | # "echo" returns true so the build succeeds, even if no changed files 91 | git commit -m 'Auto Update GitHub stats images' || echo 92 | git push origin actions_branch 93 | -------------------------------------------------------------------------------- /.github/workflows/non_auto_generate_stat_images.yml: -------------------------------------------------------------------------------- 1 | # This is a workflow for when changes are pushed to the main branch 2 | 3 | name: Generate Git Stats Images 4 | 5 | # Controls when the action will run. Triggers the workflow on push events 6 | on: 7 | push: 8 | branches: 9 | - main 10 | paths: 11 | - src/** 12 | - .github/** 13 | workflow_dispatch: 14 | 15 | permissions: 16 | contents: write 17 | 18 | # A workflow run is made up of one or more jobs that can run sequentially or in parallel 19 | jobs: 20 | 21 | # This workflow contains a single job called "build" 22 | build: 23 | 24 | # The type of runner that the job will run on 25 | runs-on: ubuntu-latest 26 | 27 | # Sequence of tasks that will be executed as part of the job 28 | steps: 29 | 30 | # Checks-out repository under $GITHUB_WORKSPACE, so the job can access it 31 | - name: Check out code 32 | uses: actions/checkout@v4 33 | 34 | # Run using Python 3.13 for consistency and aiohttp 35 | - name: Set up Python 3.13 36 | uses: actions/setup-python@v5 37 | with: 38 | python-version: '3.13' 39 | architecture: 'x64' 40 | cache: pip 41 | cache-dependency-path: '**/requirements.txt' 42 | 43 | # Creates a new branch for generating images or overwrites from older edits 44 | - name: Create new branch 45 | run: | 46 | git pull 47 | git checkout -B actions_branch 48 | 49 | # Install dependencies with `pip` 50 | - name: Install requirements 51 | run: | 52 | python3 -m pip install --upgrade pip setuptools wheel 53 | python3 -m pip install -r requirements.txt 54 | 55 | # Generate all statistics images 56 | - name: Generate images 57 | run: | 58 | python3 --version 59 | python3 git_stats_imgs.py 60 | env: 61 | ACCESS_TOKEN: ${{ secrets.ACCESS_TOKEN }} 62 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 63 | EXCLUDED_REPOS: ${{ secrets.EXCLUDED_REPOS }} 64 | EXCLUDED_OWNERS: ${{ secrets.EXCLUDED_OWNERS }} 65 | EXCLUDED_LANGS: ${{ secrets.EXCLUDED_LANGS }} 66 | EXCLUDED_REPO_LANGS: ${{ secrets.EXCLUDED_REPO_LANGS }} 67 | IS_INCLUDE_FORKED_REPOS: ${{ secrets.IS_INCLUDE_FORKED_REPOS }} 68 | IS_EXCLUDE_CONTRIB_REPOS: ${{ secrets.IS_EXCLUDE_CONTRIB_REPOS }} 69 | IS_EXCLUDE_ARCHIVE_REPOS: ${{ secrets.IS_EXCLUDE_ARCHIVE_REPOS }} 70 | IS_EXCLUDE_PRIVATE_REPOS: ${{ secrets.IS_EXCLUDE_PRIVATE_REPOS }} 71 | IS_EXCLUDE_PUBLIC_REPOS: ${{ secrets.IS_EXCLUDE_PUBLIC_REPOS }} 72 | REPO_VIEWS: ${{ secrets.REPO_VIEWS }} 73 | LAST_VIEWED: ${{ secrets.LAST_VIEWED }} 74 | FIRST_VIEWED: ${{ secrets.FIRST_VIEWED }} 75 | IS_STORE_REPO_VIEWS: ${{ secrets.IS_STORE_REPO_VIEWS }} 76 | MORE_COLLABS: ${{ secrets.MORE_COLLABS }} 77 | MORE_REPOS: ${{ secrets.MORE_REPOS }} 78 | ONLY_INCLUDED_REPOS: ${{ secrets.ONLY_INCLUDED_REPOS }} 79 | ONLY_INCLUDED_OWNERS: ${{ secrets.ONLY_INCLUDED_OWNERS }} 80 | ONLY_INCLUDED_COLLAB_REPOS: ${{ secrets.ONLY_INCLUDED_COLLAB_REPOS }} 81 | ONLY_INCLUDED_COLLAB_REPO_OWNERS: ${{ secrets.ONLY_INCLUDED_COLLAB_REPO_OWNERS }} 82 | EXCLUDED_COLLAB_REPOS: ${{ secrets.EXCLUDED_COLLAB_REPOS }} 83 | EXCLUDED_COLLAB_REPO_OWNERS: ${{ secrets.EXCLUDED_COLLAB_REPO_OWNERS }} 84 | MORE_COLLAB_REPOS: ${{ secrets.MORE_COLLAB_REPOS }} 85 | MORE_COLLAB_REPO_OWNERS: ${{ secrets.MORE_COLLAB_REPO_OWNERS }} 86 | 87 | # Commits all changed files to the repository 88 | - name: Commit to the repo 89 | run: | 90 | git config user.name "GitHub Actions" 91 | git config user.email "actions@github.com" 92 | git add . 93 | git commit -m 'Generate GitHub stats images' 94 | git push origin actions_branch --force 95 | -------------------------------------------------------------------------------- /.github/workflows/pull_request_code_convention.yml: -------------------------------------------------------------------------------- 1 | name: Pull Request Code Convention Check 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - main 7 | 8 | permissions: 9 | contents: read 10 | 11 | jobs: 12 | 13 | ruff: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | 19 | - name: Check out code 20 | uses: actions/checkout@v4 21 | 22 | # Run using Python 3.13 for consistency 23 | - name: Set up Python 3.13 24 | uses: actions/setup-python@v5 25 | with: 26 | python-version: '3.13' 27 | architecture: 'x64' 28 | cache: pip 29 | cache-dependency-path: '**/requirements.txt' 30 | 31 | # Install Ruff and Black 32 | - name: Install ruff and black 33 | run: | 34 | python -m pip install --upgrade pip 35 | pip install --user ruff 36 | pip install --user black 37 | 38 | # Use Ruff to lint all files 39 | - name: Ruff lint 40 | run: ruff check --output-format=github . 41 | 42 | # Use Black to check format for all files 43 | - name: Black lint 44 | run: black --check . 45 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | # Vim swap files 132 | *.swp 133 | *.swo 134 | 135 | # PyCharm project files 136 | .idea 137 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 📈 [GitHub Stats Visualization](https://github.com/R055A/GitStats) 🔭 2 | 3 | [![Generate Git Stats Images](https://github.com/R055A/GitStats/actions/workflows/non_auto_generate_stat_images.yml/badge.svg)](https://github.com/R055A/GitStats) [![Auto Update Stats Images](https://github.com/R055A/GitStats/actions/workflows/auto_update_stat_images.yml/badge.svg)](https://github.com/R055A/GitStats) 4 | 5 | Generate regularly updated visualizations of personalized GitHub statistics. Filter by owner/organisation, repository, type, language, and more. Secure and private [GraphQL](https://docs.github.com/en/graphql) and [REST](https://docs.github.com/en/rest) API-fetching using [Actions](https://docs.github.com/en/actions) and [Secrets](https://docs.github.com/en/actions/security-guides/encrypted-secrets). Create a template [(top-right green button)](https://github.com/new?template_name=GitStats&template_owner=R055A) and follow instructions below for authorizing API-fetched user statistics. 6 | 7 | > A modification of [`jstrieb/github-stats`](https://github.com/jstrieb/github-stats) visualizations 8 | 9 | [![GitStats Overview](https://raw.githubusercontent.com/R055A/GitStats/refs/heads/actions_branch/generated_images/overview.svg)![GitStats Languages](https://raw.githubusercontent.com/R055A/GitStats/refs/heads/actions_branch/generated_images/languages.svg)](https://github.com/R055A/GitStats) 10 | 11 | > _My **Avg contributions** mostly include [uni projects](https://github.com/University-Project-Repos), and exclude non-collab, minor roles (open-source, lead), etc_ 12 | 13 | ## Description of Statistical Terminology 14 | 15 | | GitHub Statistics Term | Description | 16 | |--------------------------------|----------------------------------------------------------------------------------------------------------------| 17 | | All-time GitHub contributions | Count of all contributions ([as defined by GitHub](https://docs.github.com/en/account-and-profile/setting-up-and-managing-your-github-profile/managing-contribution-settings-on-your-profile/viewing-contributions-on-your-profile)) to any and all repositories any time for a given user | 18 | | Lines of code changes* | Sum of all code additions and deletions to all repositories contributed to for a user, measured by lines | 19 | | Avg contributions [weighted]* | Average code changes per collaborative repository for a user [weighted relative to contributor count] | 20 | | Repos contributed [% collab]* | Count of all repositories contributed to by a user [including percent in collaboration with others] | 21 | | Repo views (as of YYYY-MM-DD)* | Sum of views to all repositories since created, if owned, or contributed to (from a given date) | 22 | | Repo collaborators* | Sum of collaborator and contributor counts for all repositories contributed to or owned for a user | 23 | | Repo forks* | Sum of all-time fork counts for all repositories contributed to or owned for a user | 24 | | Repo stars* | Sum of all-time star counts for all repositories contributed to or owned for a user | 25 | | # [+#] Implemented Languages* | Listed [and hidden] percentages of implemented languages relative to sizes of files contributed to | 26 | 27 | > \* Customisable as instructed in the :closed_lock_with_key: Options section below 28 | 29 | # :rocket: Instructions 30 | 31 |
32 | Click drop-down to view step-by-step instructions for generating your own GitHub statistics visualizations 33 | 34 | 35 | ### Copy Repository 36 | 37 | 1. Click either link to start generating your own GitHub statistic visualizations: 38 | 1. [Generate your own copy of this repository without the commit history](https://github.com/R055A/GitStats/generate) 39 | * *Note: the first GitHub Actions workflow initiated at creation of the copied repository is expected to fail* 40 | 2. [Fork a copy of this repository with the commit history configured to sync changes](https://github.com/R055A/GitStats/fork) 41 | * *Note: this copies all branches including the `action_branch` with statistics, but this can be overwritten* 42 | 43 | ### Generate a New Personal Access Token 44 | 45 | 2. Generate a personal access token by following these steps: 46 | 1. If you are logged in, click this link to: [generate a new "classic" token](https://github.com/settings/tokens/new) 47 | * *Otherwise, to learn how to generate a personal access token: [read these instructions](https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token)* 48 | 2. Ensure it is a "classic" token being generated and not a "fine-grained" token 49 | 2. Name the token 50 | 3. Select your preferred '***Expiration***' date 51 | 4. Select `repo` for '**Full control of private repositories**' 52 | 5. Select `read:user` to '**Read only ALL user profile data**' 53 | 6. Click the '***Generate token***' button 54 | 7. Copy the generated token - there is only one opportunity provided for this 55 | 56 | ### Create ACCESS_TOKEN Secret 57 | 58 | 3. Create a repository secret for the personal access token by following these steps: 59 | 1. If this is your copy of the repository, click this link to: [create a new secret](../../settings/secrets/actions/new) 60 | * *Otherwise, go to repository **Settings**, click the **Secrets** option, then click **New repository secret*** 61 | 2. Name the new secret: `ACCESS_TOKEN` 62 | 3. Enter the generated **[personal access token](#generate-a-new-personal-access-token)** as the '*Value*' 63 | 64 | ### Run GitHub Actions Workflow 65 | 66 | 4. Manually generate GitHub statistics visualizations: 67 | 1. This can be done using any of the following two GitHub Actions workflows: 68 | 1. For the **first time**, or to **reset stored statistics** (although this is done with every push to the main): 69 | * Click the link to: [go to the **Generate Git Stats Images** GitHub Actions workflow](../../actions/workflows/non_auto_generate_stat_images.yml) 70 | > *This is required if the `actions_branch` branch is not created, as it is created when run* 71 | 2. Otherwise, for **updating** generated statistics visualizations (although this is automatically done ): 72 | * Click the link to: [go to the **Auto Update Stats Images** GitHub Actions workflow](../../actions/workflows/auto_update_stat_images.yml) 73 | > *This requires the `actions_branch` branch to first be created with generated statistics visualizations* 74 | 2. With the GitHub Actions page open, click the '***Run workflow***' dropdown menu button 75 | 3. Select `Branch: main` from the '***Use workflow from***' dropdown list 76 | 4. Click the '***Run workflow***' button 77 | * _Note: this could take some time_ 78 | 79 | ### View Generated Statistics 80 | 81 | 5. Following the successful completion of a workflow, generated statistics visualizations can be viewed: 82 | 1. In the `generated_images` directory in the `actions_branch` branch with the following image links: 83 | 1. [Language statistics](../../blob/actions_branch/generated_images/languages.svg) 84 | 2. [Overview statistics](../../blob/actions_branch/generated_images/overview.svg) 85 | 86 | ### Display Generated Statistics 87 | 88 | 6. To display the generated statistics, static URLs can be used for images that are updated weekly: 89 | 1. For generated language statistics visualizations (replacing `` with your GitHub username): 90 | ```md 91 | ![](https://raw.githubusercontent.com//GitStats/actions_branch/generated_images/languages.svg) 92 | ``` 93 | 2. For generated overview statistic visualizations (replacing `` with your GitHub username): 94 | ```md 95 | ![](https://raw.githubusercontent.com//GitStats/actions_branch/generated_images/overview.svg) 96 | ``` 97 | 98 |
99 | 100 | # :closed_lock_with_key: Options 101 | 102 |
103 | Click drop-down to view optional repository Secrets for customizing GitHub statistic visualizations 104 | 105 | 106 | * ### Optional Secret *Name*: `EXCLUDED_REPOS` 107 | For excluding repositories from the generated statistic visualizations. 108 | 109 | **Instructions**: 110 | * enter *Value* in the following format (separated by commas): 111 | * `[owner/repo],[owner/repo],...,[owner/repo]` 112 | * example: 113 | * `jstrieb/github-stats,rahul-jha98/github-stats-transparent,idiotWu/stats` 114 | * ### Optional Secret *Name*: `EXCLUDED_OWNERS` 115 | For excluding repositories associated with (user/organisation) owners from the generated statistic visualizations. 116 | 117 | **Instructions**: 118 | * enter *Value* in the following format (separated by commas): 119 | * `[owner],[owner],...,[owner]` 120 | * example: 121 | * `R055A,University-Project-Repos` 122 | * ### Optional Secret *Name*: `ONLY_INCLUDED_REPOS` 123 | For **ONLY** including repositories in the generated statistic visualizations 124 | - such as when there are fewer repositories to include than to exclude 125 | 126 | **Instructions**: 127 | * enter *Value* in the following format (separated by commas): 128 | * `[owner/repo],[owner/repo],...,[owner/repo]` 129 | * example: 130 | * `R055A/GitStats,R055A/R055A` 131 | * ### Optional Secret *Name*: `ONLY_INCLUDED_OWNERS` 132 | For **ONLY** including repositories associated with (user/organisation) owners in the generated statistic visualizations 133 | - such as when there are fewer owners to include than to exclude 134 | 135 | **Instructions**: 136 | * enter *Value* in the following format (separated by commas): 137 | * `[owner],[owner],...,[owner]` 138 | * example: 139 | * `R055A,University-Project-Repos` 140 | * ### Optional Secret *Name*: `EXCLUDED_LANGS` 141 | For excluding undesired languages from being included in the generated statistic visualizations 142 | 143 | **Instructions**: 144 | * enter *Value* in the following format (separated by commas): 145 | * `[language],[language],...,[language]` 146 | * example: 147 | * `HTML,Jupyter Notebook,Makefile,Dockerfile` 148 | * ### Optional Secret *Name*: `EXCLUDED_REPO_LANGS` 149 | For excluding any/all language statistics specific to a repository from being included in the generated visualizations 150 | 151 | **Instructions**: 152 | * enter *Value* in the following format (separated by commas): 153 | * `[owner/repo--language...--language],[owner/repo--language...--language],...,[owner/repo--language...--language]` 154 | * `--language` denotes a language in the repository to be excluded from stats or exclude this for all repo languages 155 | * example: 156 | * `jstrieb/github-stats--python,rahul-jha98/github-stats-transparent,idiotWu/stats--python--shell` 157 | * ### Optional Secret *Name*: `IS_INCLUDE_FORKED_REPOS` 158 | Boolean option for including forked repositories in the generated statistic visualizations. These could repeat statistical calculations 159 | - `false` by default 160 | 161 | **Instructions**: 162 | * enter *Value* in the following format: 163 | * `` 164 | * examples: 165 | * `true` 166 | * ### Optional Secret *Name*: `IS_EXCLUDE_CONTRIB_REPOS` 167 | Boolean option for excluding non-owned repositories contributed to in the generated statistic visualizations 168 | - `false` by default 169 | 170 | **Instructions**: 171 | * enter *Value* in the following format: 172 | * `` 173 | * examples: 174 | * `true` 175 | * ### Optional Secret *Name*: `IS_EXCLUDE_ARCHIVE_REPOS` 176 | Boolean option for excluding archived repositories in the generated statistic visualizations 177 | - `false` by default 178 | 179 | **Instructions**: 180 | * enter *Value* in the following format: 181 | * `` 182 | * examples: 183 | * `true` 184 | * ### Optional Secret *Name*: `IS_EXCLUDE_PRIVATE_REPOS` 185 | Boolean option for excluding private repositories in the generated statistic visualizations 186 | - for when you want to keep those secrets locked away from prying eyes 187 | - `false` by default 188 | 189 | **Instructions**: 190 | * enter *Value* in the following format: 191 | * `` 192 | * examples: 193 | * `true` 194 | * ### Optional Secret *Name*: `IS_EXCLUDE_PUBLIC_REPOS` 195 | Boolean option for excluding public repositories in the generated statistic visualizations 196 | - `false` by default 197 | 198 | **Instructions**: 199 | * enter *Value* in the following format: 200 | * `` 201 | * examples: 202 | * `true` 203 | * ### Optional Secret *Name*: `MORE_REPOS` 204 | For including repositories that are otherwise not included in generated statistic visualizations when scraping by username 205 | - such as repositories imported from, say, GitLab - hint: add emails used in imported repo commits to profile settings 206 | 207 | **Instructions**: 208 | * enter *Value* in the following format (separated by commas): 209 | * `[owner/repo],[owner/repo],...,[owner/repo]` 210 | * example: 211 | * `R055A/GitStats,R055A/R055A` 212 | * ### Optional Secret *Name*: `MORE_COLLABS` 213 | For adding a constant value to the generated repository collaborators statistic 214 | - such as for collaborators that are otherwise not represented 215 | 216 | **Instructions**: 217 | * enter *Value* in the following format: 218 | * `` 219 | * example: 220 | * `4` 221 | * ### Optional Secret *Name*: `ONLY_INCLUDED_COLLAB_REPOS` 222 | For **ONLY** including collaborative repositories in the generated average contribution statistics calculations 223 | - such as when there are fewer collaborative repositories to include than to exclude 224 | 225 | **Instructions**: 226 | * enter *Value* in the following format (separated by commas): 227 | * `[owner/repo],[owner/repo],...,[owner/repo]` 228 | * example: 229 | * `R055A/UniversityProject-A,R055A/UniversityProject-B` 230 | * ### Optional Secret *Name*: `ONLY_INCLUDED_COLLAB_REPO_OWNERS` 231 | For **ONLY** including collaborative repositories associated with owner(s) in the generated average contribution statistics calculations 232 | - such as when there are fewer collaborative repository owners to include than to exclude 233 | 234 | **Instructions**: 235 | * enter *Value* in the following format (separated by commas): 236 | * `[owner],[owner],...,[owner]` 237 | * example: 238 | * `R055A,University-Project-Repos` 239 | * ### Optional Secret *Name*: `EXCLUDED_COLLAB_REPOS` 240 | For excluding collaborative repositories from being included in the average contribution statistics calculations 241 | - for example, such as for when 242 | - contributions are made to a collaborative repo, but it is not one of your projects (open-source typo fix, etc) 243 | - someone deletes and re-adds the entire codebase a few times too many 244 | - your or someone else's performance is not fairly represented - missing data bias 245 | - pirates, ninjas, etc. 246 | 247 | **Instructions**: 248 | * enter *Value* in the following format (separated by commas): 249 | * `[owner/repo],[owner/repo],...,[owner/repo]` 250 | * example: 251 | * `tera_open_source/bit_typo_fix,peer_repo/missing_or_no_git_co_author_credit,dude_collab/email_not_reg_on_github,dog_ate/my_repo,mars/attacks` 252 | * ### Optional Secret *Name*: `EXCLUDED_COLLAB_REPO_OWNERS` 253 | For excluding collaborative repositories associated with owner(s) from being included in the average contribution statistics calculations 254 | 255 | **Instructions**: 256 | * enter *Value* in the following format (separated by commas): 257 | * `[owner],[owner],...,[owner]` 258 | * example: 259 | * `R055A,University-Project-Repos` 260 | * ### Optional Secret *Name*: `MORE_COLLAB_REPOS` 261 | For including collaborative repositories that are otherwise not included in the average contribution statistics calculations 262 | - for example, such as when 263 | - nobody even bothered to join the repository as a collaborator let alone contribute anything 264 | - the repository is imported and because it is ghosted there are no other contributions and, thus, none of the other collaborators are represented in the scraping 265 | 266 | **Instructions**: 267 | * enter *Value* in the following format (separated by commas): 268 | * `[owner/repo],[owner/repo],...,[owner/repo]` 269 | * example: 270 | * `imported_ghosted/large_A+_collab_project,slave_trade/larger_A++_project` 271 | * ### Optional Secret *Name*: `MORE_COLLAB_REPO_OWNERS` 272 | For including collaborative repositories associated with owner(s) that are otherwise not included in the average contribution statistics calculations 273 | 274 | **Instructions**: 275 | * enter *Value* in the following format (separated by commas): 276 | * `[owner],[owner],...,[owner]` 277 | * example: 278 | * `R055A,University-Project-Repos` 279 | * ### Optional Secret *Name*: `IS_STORE_REPO_VIEWS` 280 | Boolean for storing generated repository view statistic visualization data beyond the 14 day-limit GitHub API allows 281 | - `true` by default 282 | 283 | **Instructions**: 284 | * enter *Value* in the following format: 285 | * `` 286 | * examples: 287 | * `false` 288 | * ### Optional Secret *Name*: `REPO_VIEWS` 289 | For adding a constant value to the generated repository view statistics 290 | - such as for when the stored data is reset or when importing stat data from elsewhere 291 | - requires being removed within 14 days after the first workflow is run (with `LAST_VIEWED`) 292 | - requires corresponding `LAST_VIEWED` and `FIRST_VIEWED` Secrets 293 | 294 | **Instructions**: 295 | * enter *Value* in the following format: 296 | * `` 297 | * example: 298 | * `5000` 299 | * ### Optional Secret *Name*: `LAST_VIEWED` 300 | For updating the date the generated repository view statistics data is added to storage from 301 | - such as for when the stored data is reset or when importing stat data from elsewhere 302 | - requires being removed within 14 days after the first workflow is run (with `REPO_VIEWS`) 303 | - may require corresponding `REPO_VIEWS` and `FIRST_VIEWED` Secrets 304 | 305 | **Instructions**: 306 | * enter *Value* in the following format: 307 | * `YYYY-MM-DD` 308 | * example: 309 | * `2020-10-01` 310 | * ### Optional Secret *Name*: `FIRST_VIEWED` 311 | For updating the '*as of*' date the generated repository view statistics data is stored from 312 | - such as for when the stored data is reset or when importing stat data from elsewhere 313 | - may require corresponding `REPO_VIEWS` and `LAST_VIEWED` Secrets 314 | 315 | **Instructions**: 316 | * enter *Value* in the following format: 317 | * `YYYY-MM-DD` 318 | * example: 319 | * `2021-03-31` 320 |
321 | 322 | # 🤗 Support the Project :green_heart: 323 | 324 | There are a few things you can do to support the project (and that it is extended from): 325 | 326 | - ✨ Star this repository (and/or 🌠 star [`jstrieb/github-stats`](https://github.com/jstrieb/github-stats) and 🔭 follow [`jstrieb`](https://github.com/jstrieb) for more) 327 | - :memo: Report any bugs :bug:, glitches, or errors that you find :monocle_face: 328 | - :money_with_wings: Spare a donation to a worthy cause 🥹 329 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | __all__ = ["src", "test", "git_stats_imgs"] 2 | -------------------------------------------------------------------------------- /git_stats_imgs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | """ 4 | Generates images for visualizing GitHub repository statistics 5 | """ 6 | 7 | from src.generate_images import GenerateImages 8 | 9 | 10 | def main(): 11 | GenerateImages() 12 | 13 | 14 | if __name__ == "__main__": 15 | main() 16 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | requests 2 | aiohttp 3 | -------------------------------------------------------------------------------- /src/__init__.py: -------------------------------------------------------------------------------- 1 | __all__ = [ 2 | "db", 3 | "env_vars", 4 | "generate_images", 5 | "github_api_queries", 6 | "github_repo_stats", 7 | "templates", 8 | ] 9 | -------------------------------------------------------------------------------- /src/db/__init__.py: -------------------------------------------------------------------------------- 1 | __all__ = ["db"] 2 | -------------------------------------------------------------------------------- /src/db/db.json: -------------------------------------------------------------------------------- 1 | { 2 | "views": { 3 | "count": "0", 4 | "to": "0000-00-00", 5 | "from": "0000-00-00" 6 | }, 7 | "pull_requests": "0", 8 | "issues": "0" 9 | } 10 | -------------------------------------------------------------------------------- /src/db/db.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | from json import load, dumps 4 | 5 | ############################################################################### 6 | # GitRepoStatsDB class 7 | ############################################################################### 8 | 9 | 10 | class GitRepoStatsDB: 11 | def __init__(self) -> None: 12 | self.__db: dict[str, dict[str, str] | int] | None = None 13 | 14 | try: 15 | with open("src/db/db.json", "r") as db: 16 | self.__db = load(fp=db) 17 | except FileNotFoundError: 18 | with open("../src/db/db.json", "r") as db: 19 | self.__db = load(fp=db) 20 | 21 | self.views: int = int(self.__db["views"]["count"]) 22 | self.views_from_date: str = self.__db["views"]["from"] 23 | self.views_to_date: str = self.__db["views"]["to"] 24 | self.pull_requests: int = int(self.__db["pull_requests"]) 25 | self.issues: int = int(self.__db["issues"]) 26 | 27 | def __update_db(self) -> None: 28 | try: 29 | with open("src/db/db.json", "w") as db: 30 | db.write(dumps(obj=self.__db, indent=2)) 31 | except FileNotFoundError: 32 | with open("../src/db/db.json", "w") as db: 33 | db.write(dumps(obj=self.__db, indent=2)) 34 | 35 | def set_views_count(self, views_count: any) -> None: 36 | self.views = int(views_count) 37 | self.__db["views"]["count"] = str(self.views) 38 | self.__update_db() 39 | 40 | def set_views_from_date(self, date: str) -> None: 41 | self.views_from_date = date 42 | self.__db["views"]["from"] = self.views_from_date 43 | self.__update_db() 44 | 45 | def set_views_to_date(self, date: str) -> None: 46 | self.views_to_date = date 47 | self.__db["views"]["to"] = self.views_to_date 48 | self.__update_db() 49 | 50 | def set_pull_requests(self, pull_requests_count: int) -> None: 51 | self.pull_requests = pull_requests_count 52 | self.__db["pull_requests"] = str(pull_requests_count) 53 | self.__update_db() 54 | 55 | def set_issues(self, issues_count: int) -> None: 56 | self.issues = issues_count 57 | self.__db["issues"] = str(issues_count) 58 | self.__update_db() 59 | -------------------------------------------------------------------------------- /src/env_vars.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | from typing import Optional 4 | from datetime import datetime 5 | from os import getenv, environ 6 | 7 | from src.db.db import GitRepoStatsDB 8 | 9 | ############################################################################### 10 | # EnvironmentVariables class - uses GitRepoStatsDB class as second resort 11 | ############################################################################### 12 | 13 | 14 | class EnvironmentVariables: 15 | __DATE_FORMAT: str = "%Y-%m-%d" 16 | 17 | def __init__( 18 | self, 19 | username: str, 20 | access_token: str, 21 | exclude_repos: Optional[str] = getenv("EXCLUDED_REPOS"), 22 | exclude_owners: Optional[str] = getenv("EXCLUDED_OWNERS"), 23 | exclude_langs: Optional[str] = getenv("EXCLUDED_LANGS"), 24 | exclude_repo_langs: Optional[str] = getenv("EXCLUDED_REPO_LANGS"), 25 | is_include_forked_repos: str = getenv("IS_INCLUDE_FORKED_REPOS"), 26 | is_exclude_contrib_repos: str = getenv("IS_EXCLUDE_CONTRIB_REPOS"), 27 | is_exclude_archive_repos: str = getenv("IS_EXCLUDE_ARCHIVE_REPOS"), 28 | is_exclude_private_repos: str = getenv("IS_EXCLUDE_PRIVATE_REPOS"), 29 | is_exclude_public_repos: str = getenv("IS_EXCLUDE_PUBLIC_REPOS"), 30 | repo_views: Optional[str] = getenv("REPO_VIEWS"), 31 | repo_last_viewed: Optional[str] = getenv("LAST_VIEWED"), 32 | repo_first_viewed: Optional[str] = getenv("FIRST_VIEWED"), 33 | is_store_repo_view_count: str = getenv("IS_STORE_REPO_VIEWS"), 34 | more_collaborators: Optional[str] = getenv("MORE_COLLABS"), 35 | manually_added_repos: Optional[str] = getenv("MORE_REPOS"), 36 | only_included_repos: Optional[str] = getenv("ONLY_INCLUDED_REPOS"), 37 | only_included_owners: Optional[str] = getenv("ONLY_INCLUDED_OWNERS"), 38 | only_included_collab_repos: Optional[str] = getenv( 39 | "ONLY_INCLUDED_COLLAB_REPOS" 40 | ), 41 | only_included_collab_repo_owners: Optional[str] = getenv( 42 | "ONLY_INCLUDED_COLLAB_REPO_OWNERS" 43 | ), 44 | exclude_collab_repos: Optional[str] = getenv("EXCLUDED_COLLAB_REPOS"), 45 | exclude_collab_repo_owners: Optional[str] = getenv( 46 | "EXCLUDED_COLLAB_REPO_OWNERS" 47 | ), 48 | more_collab_repos: Optional[str] = getenv("MORE_COLLAB_REPOS"), 49 | more_collab_repo_owners: Optional[str] = getenv("MORE_COLLAB_REPO_OWNERS"), 50 | ) -> None: 51 | self.__db: GitRepoStatsDB = GitRepoStatsDB() 52 | 53 | self.username: str = username 54 | self.access_token: str = access_token 55 | 56 | if exclude_repos is None: 57 | self.exclude_repos: set[str] = set() 58 | else: 59 | self.exclude_repos = {x.strip() for x in exclude_repos.split(",")} 60 | 61 | if exclude_owners is None: 62 | self.exclude_owners: set[str] = set() 63 | else: 64 | self.exclude_owners = {x.strip() for x in exclude_owners.split(",")} 65 | 66 | if exclude_langs is None: 67 | self.exclude_langs: set[str] = set() 68 | else: 69 | self.exclude_langs = {x.strip() for x in exclude_langs.split(",")} 70 | 71 | if exclude_repo_langs is None: 72 | self.exclude_repo_langs: dict[str, set[str]] = dict() 73 | else: 74 | self.exclude_repo_langs = { 75 | y[0].strip(): (set(i.lower() for i in y[1:]) if len(y) > 1 else set()) 76 | for x in exclude_repo_langs.split(",") 77 | if (y := x.split("--")) 78 | } 79 | 80 | self.is_include_forked_repos: bool = ( 81 | not not is_include_forked_repos 82 | and is_include_forked_repos.strip().lower() == "true" 83 | ) 84 | 85 | self.is_exclude_contrib_repos: bool = ( 86 | not not is_exclude_contrib_repos 87 | and is_exclude_contrib_repos.strip().lower() == "true" 88 | ) 89 | 90 | self.is_exclude_archive_repos: bool = ( 91 | not not is_exclude_archive_repos 92 | and is_exclude_archive_repos.strip().lower() == "true" 93 | ) 94 | 95 | self.is_exclude_private_repos: bool = ( 96 | not not is_exclude_private_repos 97 | and is_exclude_private_repos.strip().lower() == "true" 98 | ) 99 | 100 | self.is_exclude_public_repos: bool = ( 101 | not not is_exclude_public_repos 102 | and is_exclude_public_repos.strip().lower() == "true" 103 | ) 104 | 105 | self.is_store_repo_view_count: bool = ( 106 | not is_store_repo_view_count 107 | or is_store_repo_view_count.strip().lower() != "false" 108 | ) 109 | 110 | if self.is_store_repo_view_count: 111 | try: 112 | if repo_views: 113 | self.repo_views: int = int(repo_views) 114 | self.__db.set_views_count(views_count=self.repo_views) 115 | else: 116 | self.repo_views = self.__db.views 117 | except ValueError: 118 | self.repo_views = self.__db.views 119 | 120 | if repo_last_viewed: 121 | try: 122 | if repo_last_viewed == datetime.strptime( 123 | repo_last_viewed, self.__DATE_FORMAT 124 | ).strftime(format=self.__DATE_FORMAT): 125 | self.repo_last_viewed: str = repo_last_viewed 126 | except ValueError: 127 | self.repo_last_viewed = self.__db.views_to_date 128 | else: 129 | self.repo_last_viewed = self.__db.views_to_date 130 | 131 | if repo_first_viewed: 132 | try: 133 | if repo_first_viewed == datetime.strptime( 134 | repo_first_viewed, self.__DATE_FORMAT 135 | ).strftime(format=self.__DATE_FORMAT): 136 | self.repo_first_viewed: str = repo_first_viewed 137 | except ValueError: 138 | self.repo_first_viewed = self.__db.views_from_date 139 | else: 140 | self.repo_first_viewed = self.__db.views_from_date 141 | 142 | else: 143 | self.repo_views = 0 144 | self.__db.set_views_count(views_count=self.repo_views) 145 | self.repo_last_viewed = "0000-00-00" 146 | self.repo_first_viewed = "0000-00-00" 147 | self.__db.set_views_from_date(date=self.repo_first_viewed) 148 | self.__db.set_views_to_date(date=self.repo_last_viewed) 149 | 150 | try: 151 | self.more_collaborators: int = ( 152 | int(more_collaborators) if more_collaborators else 0 153 | ) 154 | except ValueError: 155 | self.more_collaborators = 0 156 | 157 | if manually_added_repos is None: 158 | self.manually_added_repos: set[str] = set() 159 | else: 160 | self.manually_added_repos = { 161 | x.strip() for x in manually_added_repos.split(",") 162 | } 163 | 164 | if only_included_repos is None or only_included_repos == "": 165 | self.only_included_repos: set[str] = set() 166 | else: 167 | self.only_included_repos = { 168 | x.strip() for x in only_included_repos.split(",") 169 | } 170 | 171 | if only_included_owners is None or only_included_owners == "": 172 | self.only_included_owners: set[str] = set() 173 | else: 174 | self.only_included_owners = { 175 | x.strip() for x in only_included_owners.split(",") 176 | } 177 | 178 | if only_included_collab_repos is None or only_included_collab_repos == "": 179 | self.only_included_collab_repos: set[str] = set() 180 | else: 181 | self.only_included_collab_repos = { 182 | x.strip() for x in only_included_collab_repos.split(",") 183 | } 184 | 185 | if ( 186 | only_included_collab_repo_owners is None 187 | or only_included_collab_repo_owners == "" 188 | ): 189 | self.only_included_collab_repo_owners: set[str] = set() 190 | else: 191 | self.only_included_collab_repo_owners = { 192 | x.strip() for x in only_included_collab_repo_owners.split(",") 193 | } 194 | 195 | if exclude_collab_repos is None: 196 | self.exclude_collab_repos: set[str] = set() 197 | else: 198 | self.exclude_collab_repos = { 199 | x.strip() for x in exclude_collab_repos.split(",") 200 | } 201 | 202 | if exclude_collab_repo_owners is None: 203 | self.exclude_collab_repo_owners: set[str] = set() 204 | else: 205 | self.exclude_collab_repo_owners = { 206 | x.strip() for x in exclude_collab_repo_owners.split(",") 207 | } 208 | 209 | if more_collab_repos is None: 210 | self.more_collab_repos: set[str] = set() 211 | else: 212 | self.more_collab_repos = {x.strip() for x in more_collab_repos.split(",")} 213 | 214 | if more_collab_repo_owners is None: 215 | self.more_collab_repo_owners: set[str] = set() 216 | else: 217 | self.more_collab_repo_owners = { 218 | x.strip() for x in more_collab_repo_owners.split(",") 219 | } 220 | 221 | self.pull_requests_count: int = self.__db.pull_requests 222 | self.issues_count: int = self.__db.issues 223 | 224 | def set_views(self, views: any) -> None: 225 | self.repo_views += int(views) 226 | environ["REPO_VIEWS"] = str(self.repo_views) 227 | self.__db.set_views_count(views_count=self.repo_views) 228 | 229 | def set_last_viewed(self, new_last_viewed_date: str) -> None: 230 | self.repo_last_viewed = new_last_viewed_date 231 | environ["LAST_VIEWED"] = self.repo_last_viewed 232 | self.__db.set_views_to_date(date=self.repo_last_viewed) 233 | 234 | def set_first_viewed(self, new_first_viewed_date: str) -> None: 235 | self.repo_first_viewed = new_first_viewed_date 236 | environ["FIRST_VIEWED"] = self.repo_first_viewed 237 | self.__db.set_views_from_date(date=self.repo_first_viewed) 238 | 239 | def set_pull_requests(self, pull_requests_count: int) -> None: 240 | self.__db.pull_requests = pull_requests_count 241 | 242 | def set_issues(self, issues_count: int) -> None: 243 | self.__db.issues = issues_count 244 | -------------------------------------------------------------------------------- /src/generate_images.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | from aiohttp import ClientSession 4 | from asyncio import run, gather 5 | from os import mkdir, getenv 6 | from os.path import isdir 7 | from re import sub 8 | 9 | from src.github_repo_stats import GitHubRepoStats 10 | from src.env_vars import EnvironmentVariables 11 | 12 | OUTPUT_DIR: str = "generated_images" # directory for storing generated images 13 | TEMPLATE_PATH: str = "src/templates/" 14 | OVERVIEW_FILE_NAME: str = "overview.svg" 15 | LANGUAGES_FILE_NAME: str = "languages.svg" 16 | TXT_SPACER_MAX_LEN: int = 7 17 | MAX_NAME_LEN: int = 18 18 | 19 | 20 | ############################################################################### 21 | # Helper Functions 22 | ############################################################################### 23 | 24 | 25 | def generate_output_folder() -> None: 26 | """ 27 | Create the output folder if it does not already exist 28 | """ 29 | if not isdir(OUTPUT_DIR): 30 | mkdir(OUTPUT_DIR) 31 | 32 | 33 | def add_unit(num: str | int) -> str: 34 | """ 35 | Add units to large numbers to reduce length of string 36 | Example: 12,456 to 12.46K 37 | """ 38 | metric_units: list[str] = ["K", "M", "B", "T"] 39 | metric_units_index: int = -1 40 | 41 | num: int = int(num.replace(",", "")) if isinstance(num, str) else num 42 | 43 | if num >= 10000: 44 | while num >= 1000: 45 | num /= 1000 46 | metric_units_index += 1 47 | return str(num)[: TXT_SPACER_MAX_LEN - 2] + metric_units[metric_units_index] 48 | return str(num) 49 | 50 | 51 | def format_name(name: str, user_name: str) -> str: 52 | """ 53 | Format name display: user's given name first, otherwise username in any best fit variation as depicted below 54 | """ 55 | # if name too long for svg dimensions 56 | if len(name + ("'" if name[-1].lower() == "s" else "'s")) > MAX_NAME_LEN: 57 | names: list[str] = name.split(" ") 58 | # if too long name contains just one word or forename initials with full surname still too long 59 | if ( 60 | len(names) == 1 61 | or len( 62 | names[0][0] 63 | + ". " 64 | + names[-1] 65 | + ("'" if names[-1][-1].lower() == "s" else "'s") 66 | ) 67 | > MAX_NAME_LEN 68 | ): 69 | # if username also too long for svg dimensions 70 | if ( 71 | len(user_name + ("'" if user_name[-1].lower() == "s" else "'s")) 72 | > MAX_NAME_LEN 73 | ): 74 | # display forename to max possible len if name a single word, or forename initials with full surname 75 | name = ( 76 | names[0][: MAX_NAME_LEN - 4] + "..'s" 77 | if len(names) == 1 78 | else "".join( 79 | [ 80 | name[0] + ". " 81 | for i, name in enumerate(names[:-1]) 82 | if i <= (MAX_NAME_LEN - 4) / 3 83 | ] 84 | ) 85 | + names[-1][0] 86 | + ".'s" 87 | ) 88 | else: 89 | # display the username instead of user's name if forename initials with full surname still too long 90 | name = user_name + ("'" if user_name[-1].lower() == "s" else "'s") 91 | else: 92 | # display the forename initials with full surname if full name too long but not surname with initials 93 | name = ( 94 | names[0][0] 95 | + ". " 96 | + names[-1] 97 | + ("'" if names[-1][-1].lower() == "s" else "'s") 98 | ) 99 | else: 100 | # display the user's full forename and surname if when combined are not too long for the svg dimensions 101 | name += "'" if name[-1].lower() == "s" else "'s" 102 | return name 103 | 104 | 105 | ############################################################################### 106 | # GenerateImages class 107 | ############################################################################### 108 | 109 | 110 | class GenerateImages: 111 | def __init__(self) -> None: 112 | access_token: str = getenv("ACCESS_TOKEN") 113 | user: str = getenv("GITHUB_ACTOR") 114 | 115 | if not access_token: 116 | raise Exception("A personal access token is required to proceed!") 117 | 118 | if not user: 119 | raise RuntimeError("Environment variable GITHUB_ACTOR must be set") 120 | 121 | self.__environment: EnvironmentVariables = EnvironmentVariables( 122 | username=user, access_token=access_token 123 | ) 124 | self.__stats: GitHubRepoStats | None = None 125 | 126 | run(main=self.start()) 127 | 128 | async def start(self) -> None: 129 | """ 130 | Main function: generate all badges 131 | """ 132 | async with ClientSession() as session: 133 | self.__stats = GitHubRepoStats( 134 | environment_vars=self.__environment, session=session 135 | ) 136 | await gather(self.generate_languages(), self.generate_overview()) 137 | 138 | async def generate_overview(self) -> None: 139 | """ 140 | Generate an SVG badge with summary statistics 141 | """ 142 | with open("{}{}".format(TEMPLATE_PATH, OVERVIEW_FILE_NAME), "r") as f: 143 | output: str = f.read() 144 | 145 | # svg name display: user's given name first, otherwise username in any best fit variation as depicted below 146 | name: str = format_name( 147 | name=await self.__stats.name, 148 | user_name=self.__stats.environment_vars.username, 149 | ) 150 | output = sub(pattern="{{ name }}", repl=name, string=output) 151 | 152 | views: str = f"{await self.__stats.views:,}" 153 | output = sub(pattern="{{ views }}", repl=views, string=output) 154 | 155 | forks: str = f"{await self.__stats.forks:,}" 156 | forks = forks if len(str(forks)) < TXT_SPACER_MAX_LEN else add_unit(forks) 157 | stars: str = f"{await self.__stats.stargazers:,}" 158 | stars = stars if len(str(stars)) < TXT_SPACER_MAX_LEN else add_unit(stars) 159 | forks_and_stars: str = ( 160 | forks 161 | + " " * max(1, TXT_SPACER_MAX_LEN - len(str(forks)) + 1) 162 | + "| " 163 | + stars 164 | ) 165 | output = sub( 166 | pattern="{{ forks_and_stars }}", repl=forks_and_stars, string=output 167 | ) 168 | 169 | contributions: str = f"{await self.__stats.total_contributions:,}" 170 | output = sub(pattern="{{ contributions }}", repl=contributions, string=output) 171 | 172 | changed: int = (await self.__stats.lines_changed)[0] + ( 173 | await self.__stats.lines_changed 174 | )[1] 175 | output = sub(pattern="{{ lines_changed }}", repl=f"{changed:,}", string=output) 176 | 177 | avg_contribution_percent: str = ( 178 | f"{await self.__stats.avg_contribution_percent} " 179 | f"[{await self.__stats.avg_contribution_percent_weighted}]" 180 | ) 181 | output = sub( 182 | pattern="{{ avg_contribution_percent }}", 183 | repl=avg_contribution_percent, 184 | string=output, 185 | ) 186 | 187 | num_repos: int = len(await self.__stats.repos) 188 | num_collab_repos = len(await self.__stats.contributed_collab_repos) 189 | repos: int = ( 190 | num_repos 191 | if len(str(num_repos)) < TXT_SPACER_MAX_LEN 192 | else add_unit(num_repos) 193 | ) 194 | repos_str: str = ( 195 | f"{repos:,} [{'%g' % round(num_collab_repos / num_repos * 100, 2) if num_collab_repos > 0 and num_repos > 0 else 0}%]" 196 | ) 197 | output = sub(pattern="{{ repos_str }}", repl=repos_str, string=output) 198 | 199 | collaborators_and_contributors: str = f"{await self.__stats.collaborators:,}" 200 | output = sub( 201 | pattern="{{ collaborators_and_contributors }}", 202 | repl=collaborators_and_contributors, 203 | string=output, 204 | ) 205 | 206 | views_from: str = await self.__stats.views_from_date 207 | output = sub( 208 | pattern="{{ views_from_date }}", 209 | repl=f"Repo views (as of {views_from})", 210 | string=output, 211 | ) 212 | 213 | # pull_requests: str = f'{await self.__stats.pull_requests:,}' 214 | # pull_requests = ( 215 | # pull_requests 216 | # if len(str(pull_requests)) < TXT_SPACER_MAX_LEN 217 | # else add_unit(pull_requests) 218 | # ) 219 | # issues: str = f'{await self.__stats.issues:,}' 220 | # issues = issues if len(str(issues)) < TXT_SPACER_MAX_LEN else add_unit(issues) 221 | # pull_requests_and_issues: str = ( 222 | # pull_requests 223 | # + ' ' * max(1, TXT_SPACER_MAX_LEN - len(str(pull_requests)) + 1) 224 | # + '| ' 225 | # + issues 226 | # ) 227 | # output = sub('{{ pull_requests_and_issues }}', pull_requests_and_issues, output) 228 | 229 | generate_output_folder() 230 | with open("{}/{}".format(OUTPUT_DIR, OVERVIEW_FILE_NAME), "w") as f: 231 | f.write(output) 232 | 233 | async def generate_languages(self) -> None: 234 | """ 235 | Generate an SVG badge with summary languages used 236 | """ 237 | with open("{}{}".format(TEMPLATE_PATH, LANGUAGES_FILE_NAME), "r") as f: 238 | output: str = f.read() 239 | 240 | progress: str = "" 241 | lang_list: str = "" 242 | sorted_languages: list = sorted( 243 | (await self.__stats.languages).items(), 244 | reverse=True, 245 | key=lambda t: t[1].get("size"), 246 | ) 247 | 248 | lang_count: str = str(len(sorted_languages)) 249 | num_excluded_languages: int = len(await self.__stats.excluded_languages) 250 | if num_excluded_languages > 0: 251 | lang_count += " [+" + str(num_excluded_languages) + " hidden]" 252 | 253 | delay_between: int = 150 254 | 255 | for i, (lang, data) in enumerate(sorted_languages): 256 | color: str = data.get("color") 257 | color = color if color is not None else "#000000" 258 | progress += ( 259 | f'' 262 | ) 263 | lang_list += f""" 264 |
  • 265 | 272 | 274 | 275 | 276 | 277 | {lang} 278 | 279 | 280 | {data.get("prop", 0):0.2f}% 281 | 282 |
  • """ 283 | 284 | output = sub(pattern=r"{{ lang_count }}", repl=lang_count, string=output) 285 | 286 | output = sub(pattern=r"{{ progress }}", repl=progress, string=output) 287 | 288 | output = sub(pattern=r"{{ lang_list }}", repl=lang_list, string=output) 289 | 290 | generate_output_folder() 291 | with open("{}/{}".format(OUTPUT_DIR, LANGUAGES_FILE_NAME), "w") as f: 292 | f.write(output) 293 | -------------------------------------------------------------------------------- /src/github_api_queries.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | from aiohttp.client_exceptions import ClientPayloadError 4 | from requests import post, get, models 5 | from asyncio import Semaphore, sleep 6 | from aiohttp import ClientSession 7 | from http import HTTPStatus 8 | from typing import Optional 9 | from json import loads 10 | 11 | 12 | ############################################################################### 13 | # GitHubApiQueries class 14 | ############################################################################### 15 | 16 | 17 | class GitHubApiQueries(object): 18 | """ 19 | Class with functions to query the GitHub GraphQL (v4) API and the REST (v3) 20 | API. Also includes functions to dynamically generate GraphQL queries. 21 | """ 22 | 23 | __GITHUB_API_URL: str = "https://api.github.com/" 24 | __GRAPHQL_PATH: str = "graphql" 25 | __REST_QUERY_LIMIT: int = 10 26 | __ASYNCIO_SLEEP_TIME: int = 5 27 | __DEFAULT_MAX_CONNECTIONS: int = 10 28 | 29 | def __init__( 30 | self, 31 | username: str, 32 | access_token: str, 33 | session: ClientSession, 34 | max_connections: int = __DEFAULT_MAX_CONNECTIONS, 35 | ) -> None: 36 | self.username: str = username 37 | self.access_token: str = access_token 38 | self.session: ClientSession = session 39 | self.semaphore: Semaphore = Semaphore(max_connections) 40 | self.headers: dict[str, str] = { 41 | "Authorization": f"Bearer {self.access_token}", 42 | } 43 | 44 | async def query(self, generated_query: str) -> dict[str, dict]: 45 | """ 46 | Make a request to the GraphQL API using the authentication token from 47 | the environment 48 | :param generated_query: string query to be sent to the API 49 | :return: decoded GraphQL JSON output 50 | """ 51 | try: 52 | async with self.semaphore: 53 | r_async = await self.session.post( 54 | url=self.__GITHUB_API_URL + self.__GRAPHQL_PATH, 55 | headers=self.headers, 56 | json={"query": generated_query}, 57 | ) 58 | result: dict[str, dict] = await r_async.json() 59 | 60 | if result is not None: 61 | return result 62 | except (ConnectionError, ClientPayloadError) as err: 63 | print("aiohttp failed for GraphQL query. Msg:", str(err)) 64 | 65 | # Fall back on non-async requests 66 | async with self.semaphore: 67 | r_requests = post( 68 | url=self.__GITHUB_API_URL + self.__GRAPHQL_PATH, 69 | headers=self.headers, 70 | json={"query": generated_query}, 71 | ) 72 | result = r_requests.json() 73 | 74 | if result is not None: 75 | return result 76 | return dict() 77 | 78 | async def query_rest( 79 | self, path: str, params: Optional[dict] = None 80 | ) -> dict[str, str | int | dict | list[dict[str, str]]] | list[dict[str, any]]: 81 | """ 82 | Make a request to the REST API 83 | :param path: API path to query 84 | :param params: Query parameters to be passed to the API 85 | :return: deserialized REST JSON output 86 | """ 87 | for i in range(self.__REST_QUERY_LIMIT): 88 | if params is None: 89 | params = dict() 90 | if path.startswith("/"): 91 | path = path[1:] 92 | 93 | try: 94 | async with self.semaphore: 95 | r_async = await self.session.get( 96 | self.__GITHUB_API_URL + path, 97 | headers=self.headers, 98 | params=tuple(params.items()), 99 | ) 100 | 101 | if r_async.status == HTTPStatus.ACCEPTED.value: 102 | print(f"A path returned {HTTPStatus.ACCEPTED.value}. Retrying...") 103 | await sleep(self.__ASYNCIO_SLEEP_TIME) 104 | continue 105 | 106 | result: dict[str, str | dict] = await r_async.json() 107 | 108 | if result is not None: 109 | return result 110 | except (ConnectionError, ClientPayloadError) as err: 111 | print( 112 | "aiohttp failed for REST query attempt #" + str(i + 1), 113 | " msg:", 114 | str(err), 115 | ) 116 | 117 | # Fall back on non-async requests 118 | async with self.semaphore: 119 | r_requests = get( 120 | self.__GITHUB_API_URL + path, 121 | headers=self.headers, 122 | params=tuple(params.items()), 123 | ) 124 | 125 | if r_requests.status_code == HTTPStatus.ACCEPTED.value: 126 | print( 127 | f"A path returned {HTTPStatus.ACCEPTED.value}. Retrying..." 128 | ) 129 | await sleep(self.__ASYNCIO_SLEEP_TIME) 130 | continue 131 | elif r_requests.status_code == HTTPStatus.OK.value: 132 | return r_requests.json() 133 | 134 | print( 135 | f"Too many {HTTPStatus.ACCEPTED.value}s. Data for this repository will be incomplete." 136 | ) 137 | return dict() 138 | 139 | @staticmethod 140 | def get_user() -> str: 141 | """ 142 | :return: GraphQL query with user login and name 143 | """ 144 | return """ 145 | { 146 | viewer { 147 | login 148 | name 149 | } 150 | }""" 151 | 152 | @staticmethod 153 | def repos_overview( 154 | contrib_cursor: Optional[str] = None, owned_cursor: Optional[str] = None 155 | ) -> str: 156 | """ 157 | :return: GraphQL queries with overview of user repositories 158 | """ 159 | return f""" 160 | {{ 161 | viewer {{ 162 | login, 163 | repositories( 164 | first: 100, 165 | orderBy: {{ 166 | field: UPDATED_AT, 167 | direction: DESC 168 | }}, 169 | after: { 170 | 'null' if owned_cursor is None 171 | else """ + owned_cursor + """ 172 | }) {{ 173 | pageInfo {{ 174 | hasNextPage 175 | endCursor 176 | }} 177 | nodes {{ 178 | nameWithOwner 179 | stargazers {{ 180 | totalCount 181 | }} 182 | forkCount 183 | isFork 184 | isEmpty 185 | isArchived 186 | isPrivate 187 | languages(first: 20, orderBy: {{ 188 | field: SIZE, 189 | direction: DESC 190 | }}) {{ 191 | edges {{ 192 | size 193 | node {{ 194 | name 195 | color 196 | }} 197 | }} 198 | }} 199 | }} 200 | }} 201 | repositoriesContributedTo( 202 | first: 100, 203 | includeUserRepositories: false, 204 | orderBy: {{ 205 | field: UPDATED_AT, 206 | direction: DESC 207 | }}, 208 | contributionTypes: [ 209 | COMMIT, 210 | PULL_REQUEST, 211 | REPOSITORY, 212 | PULL_REQUEST_REVIEW 213 | ] 214 | after: { 215 | 'null' if contrib_cursor is None 216 | else """ + contrib_cursor + """}) {{ 217 | pageInfo {{ 218 | hasNextPage 219 | endCursor 220 | }} 221 | nodes {{ 222 | nameWithOwner 223 | stargazers {{ 224 | totalCount 225 | }} 226 | forkCount 227 | isFork 228 | isEmpty 229 | isArchived 230 | isPrivate 231 | languages(first: 20, orderBy: {{ 232 | field: SIZE, 233 | direction: DESC 234 | }}) {{ 235 | edges {{ 236 | size 237 | node {{ 238 | name 239 | color 240 | }} 241 | }} 242 | }} 243 | }} 244 | }} 245 | }} 246 | }}""" 247 | 248 | @staticmethod 249 | def contributions_all_years() -> str: 250 | """ 251 | :return: GraphQL query to get all years the user has been a contributor 252 | """ 253 | return """ 254 | query { 255 | viewer { 256 | contributionsCollection { 257 | contributionYears 258 | } 259 | } 260 | }""" 261 | 262 | @staticmethod 263 | def contributions_by_year(year: str) -> str: 264 | """ 265 | :param year: year to query for 266 | :return: portion of a GraphQL query with desired info for a given year 267 | """ 268 | return f""" 269 | year{year}: contributionsCollection( 270 | from: "{year}-01-01T00:00:00Z", 271 | to: "{int(year) + 1}-01-01T00:00:00Z" 272 | ) {{ 273 | contributionCalendar {{ 274 | totalContributions 275 | }} 276 | }}""" 277 | 278 | @classmethod 279 | def all_contributions(cls, years: list[str]) -> str: 280 | """ 281 | :param years: list of years to get contributions for 282 | :return: query to retrieve contribution information for all user years 283 | """ 284 | by_years: str = "\n".join(map(cls.contributions_by_year, years)) 285 | return f""" 286 | query {{ 287 | viewer {{ 288 | {by_years} 289 | }} 290 | }}""" 291 | 292 | @staticmethod 293 | def get_language_colors() -> dict[str, dict[str, str]]: 294 | url: models.Response = get( 295 | "https://raw.githubusercontent.com/ozh/github-colors/master/colors.json" 296 | ) 297 | return loads(url.text) 298 | -------------------------------------------------------------------------------- /src/github_repo_stats.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | from time import sleep 4 | from asyncio import Lock 5 | from typing import Optional, cast 6 | from aiohttp import ClientSession 7 | from datetime import date, timedelta 8 | 9 | from src.env_vars import EnvironmentVariables 10 | from src.github_api_queries import GitHubApiQueries 11 | 12 | ############################################################################### 13 | # GitHubRepoStats class 14 | ############################################################################### 15 | 16 | 17 | class GitHubRepoStats(object): 18 | """ 19 | Retrieve and store statistics about GitHub usage. 20 | """ 21 | 22 | _DATE_FORMAT: str = "%Y-%m-%d" 23 | _EXCLUDED_USER_NAMES: list[str] = [ 24 | "dependabot[bot]" 25 | ] # exclude bot data from being included in statistical calculations 26 | _NO_NAME: str = "Unknown" 27 | _UNLOCK_WAIT_SECONDS = 2 28 | 29 | def __init__( 30 | self, environment_vars: EnvironmentVariables, session: ClientSession 31 | ) -> None: 32 | self.environment_vars: EnvironmentVariables = environment_vars 33 | self.queries: GitHubApiQueries = GitHubApiQueries( 34 | username=self.environment_vars.username, 35 | access_token=self.environment_vars.access_token, 36 | session=session, 37 | ) 38 | 39 | self.__get_stats_lock: Lock = Lock() 40 | self.__is_stats_fetched: bool = False 41 | 42 | self._name: Optional[str] = None 43 | self._stargazers: Optional[int] = None 44 | self._forks: Optional[int] = None 45 | self._total_contributions: Optional[int] = None 46 | self._languages: Optional[dict[str, dict[str, float | str]]] = None 47 | self._excluded_languages: Optional[set[str]] = None 48 | self._exclude_repo_languages: Optional[set[str]] = None 49 | self._repos: Optional[set[str]] = None 50 | self._owned_repos: Optional[set[str]] = None 51 | self._users_lines_changed: Optional[tuple[int, int]] = None 52 | self._avg_percent: Optional[str] = None 53 | self._avg_percent_weighted: Optional[str] = None 54 | self._views: Optional[int] = None 55 | self._collaborators: Optional[int] = None 56 | self._collaborator_set: Optional[set[str]] = None 57 | self._contributors: Optional[set[str]] = None 58 | self._views_from_date: Optional[str] = None 59 | self._pull_requests: Optional[int] = None 60 | self._issues: Optional[int] = None 61 | self._empty_repos: Optional[set[str]] = None 62 | self._collab_repos: Optional[set[str]] = None 63 | self._contributed_collab_repos: Optional[set[str]] = None 64 | self._is_fetch_rate_limit_exceeded: Optional[bool] = False 65 | 66 | async def to_str(self) -> str: 67 | """ 68 | :return: summary of all available statistics 69 | """ 70 | languages: dict[str, float] = await self.languages_proportional 71 | formatted_languages: str = "\n\t\t\t- ".join( 72 | [f"{k}: {v:0.4f}%" for k, v in languages.items()] 73 | ) 74 | 75 | users_lines_changed: tuple[int, int] = await self.lines_changed 76 | avg_percent: str = await self.avg_contribution_percent 77 | avg_percent_weighted: str = await self.avg_contribution_percent_weighted 78 | contributors: int = max(len(await self.contributors) - 1, 0) 79 | 80 | return f"""GitHub Repository Statistics: 81 | Name: {await self.name} 82 | Stargazers: {await self.stargazers:,} 83 | Forks: {await self.forks:,} 84 | All-time contributions: {await self.total_contributions:,} 85 | Repositories with contributions: {len(await self.repos):,} 86 | Repositories in collaboration with at least one other user: {len(await self.contributed_collab_repos):,} 87 | Lines of code added: {users_lines_changed[0]:,} 88 | Lines of code deleted: {users_lines_changed[1]:,} 89 | Total lines of code changed: {sum(users_lines_changed):,} 90 | Avg. % of contributions (per collab repo): {avg_percent} 91 | Avg. % of contributions (per collab repo) weighted by number of contributors (max 100): {avg_percent_weighted} 92 | Project page views: {await self.views:,} 93 | Project page views from date: {await self.views_from_date} 94 | Project repository collaborators: {await self.collaborators:,} 95 | Project repository contributors: {contributors:,} 96 | Total number of languages: {len(list(languages.keys()))} (+{len(await self.excluded_languages):,}) 97 | Languages:\n\t\t\t- {formatted_languages}""" 98 | 99 | async def is_repo_name_invalid(self, repo_name: str) -> bool: 100 | """ 101 | Determines a repo name invalid if: 102 | - repo is already scraped and the name is in the list 103 | - repo name is not included in and only_include_repos is being used 104 | - repo name is included in exclude_repos 105 | :param repo_name: the name of the repo in owner/name format 106 | :return: True if repo is not to be included in self._repos 107 | """ 108 | return ( 109 | ( 110 | len(self.environment_vars.only_included_owners) > 0 111 | and repo_name.split("/")[0] 112 | not in self.environment_vars.only_included_owners 113 | ) 114 | or ( 115 | len(self.environment_vars.only_included_repos) > 0 116 | and repo_name not in self.environment_vars.only_included_repos 117 | and repo_name.split("/")[0] 118 | not in self.environment_vars.only_included_owners 119 | ) 120 | or repo_name in self.environment_vars.exclude_repos 121 | or repo_name.split("/")[0] in self.environment_vars.exclude_owners 122 | ) 123 | 124 | async def is_repo_type_excluded( 125 | self, repo_data: dict[str, str | int | dict] 126 | ) -> bool: 127 | """ 128 | Determines a repo type excluded if: 129 | - repo is a fork and forked repos are not being included 130 | - repo is archived and archived repos are being excluded 131 | - repo is private and private repos are being excluded 132 | - repo is public and public repos are being excluded 133 | :param repo_data: repo data returned from API fetch 134 | :return: True if repo type is not to be included in self._repos 135 | """ 136 | return ( 137 | not self.environment_vars.is_include_forked_repos 138 | and (repo_data.get("isFork") or repo_data.get("fork")) 139 | or self.environment_vars.is_exclude_archive_repos 140 | and (repo_data.get("isArchived") or repo_data.get("archived")) 141 | or self.environment_vars.is_exclude_private_repos 142 | and (repo_data.get("isPrivate") or repo_data.get("private")) 143 | or self.environment_vars.is_exclude_public_repos 144 | and (not repo_data.get("isPrivate") or not repo_data.get("private")) 145 | ) 146 | 147 | async def get_stats(self) -> None: 148 | """ 149 | Get lots of summary stats using one big query. Sets many attributes 150 | """ 151 | if self.__is_stats_fetched: 152 | return 153 | 154 | async with self.__get_stats_lock: 155 | if self.__is_stats_fetched: 156 | return 157 | 158 | self._stargazers: int = 0 159 | self._forks: int = 0 160 | self._excluded_languages: set[str] = set() 161 | self._exclude_repo_languages: set[str] = set() 162 | self._languages: dict[str, dict[str, float | str]] = dict() 163 | self._repos: set[str] = set() 164 | self._empty_repos: set[str] = set() 165 | 166 | next_owned: str | None = None 167 | next_contrib: str | None = None 168 | 169 | user_raw_result: dict[str, dict] = await self.queries.query( 170 | generated_query=GitHubApiQueries.get_user() 171 | ) 172 | user_raw_result = user_raw_result if user_raw_result else {} 173 | if ( 174 | user_raw_result.get("data", {}) is not None 175 | and user_raw_result.get("data", {}).get("viewer", {}) is not None 176 | and ( 177 | user_raw_result.get("data", {}).get("viewer", {}).get("name", None) 178 | is not None 179 | or user_raw_result.get("data", {}) 180 | .get("viewer", {}) 181 | .get("user", None) 182 | is not None 183 | ) 184 | ): 185 | self._name = ( 186 | user_raw_result.get("data", {}) 187 | .get("viewer", {}) 188 | .get("name", self._NO_NAME) 189 | ) 190 | elif user_raw_result.get("message", "").lower() == "bad credentials": 191 | raise ConnectionRefusedError("Unauthorized Error: Invalid Access Token") 192 | else: 193 | raise Exception(f"Error: {user_raw_result.get('message', '')}") 194 | 195 | while True: 196 | repo_overview_raw_results: dict[str, dict] = await self.queries.query( 197 | generated_query=GitHubApiQueries.repos_overview( 198 | owned_cursor=next_owned, contrib_cursor=next_contrib 199 | ) 200 | ) 201 | repo_overview_raw_results = ( 202 | repo_overview_raw_results if repo_overview_raw_results else {} 203 | ) 204 | 205 | if ( 206 | repo_overview_raw_results.get("data", {}) is not None 207 | and repo_overview_raw_results.get("data", {}).get("viewer", {}) 208 | is not None 209 | ): 210 | owned_repos: dict[str, dict | list[dict]] = ( 211 | repo_overview_raw_results.get("data", {}) 212 | .get("viewer", {}) 213 | .get("repositories", {}) 214 | ) 215 | repos: list[dict] = owned_repos.get("nodes", []) 216 | contrib_repos: dict[str, dict | list] = ( 217 | repo_overview_raw_results.get("data", {}) 218 | .get("viewer", {}) 219 | .get("repositoriesContributedTo", {}) 220 | ) 221 | else: 222 | owned_repos = {} 223 | repos = [] 224 | contrib_repos = {} 225 | 226 | if not self.environment_vars.is_exclude_contrib_repos: 227 | repos += contrib_repos.get("nodes", []) 228 | 229 | await self.repo_stats(repos=repos) 230 | 231 | is_cur_owned: bool = owned_repos.get("pageInfo", {}).get( 232 | "hasNextPage", False 233 | ) 234 | is_cur_contrib: bool = contrib_repos.get("pageInfo", {}).get( 235 | "hasNextPage", False 236 | ) 237 | 238 | if is_cur_owned or is_cur_contrib: 239 | next_owned = owned_repos.get("pageInfo", {}).get( 240 | "endCursor", next_owned 241 | ) 242 | next_contrib = contrib_repos.get("pageInfo", {}).get( 243 | "endCursor", next_contrib 244 | ) 245 | else: 246 | break 247 | 248 | await self.manually_added_repo_stats() 249 | 250 | for lang_name in self._exclude_repo_languages: 251 | if ( 252 | lang_name not in self._languages.keys() 253 | and lang_name not in self._excluded_languages 254 | ): 255 | self._excluded_languages.add(lang_name) 256 | 257 | # TODO: Improve languages to scale by number of contributions to specific filetypes 258 | langs_total: int = sum([v.get("size", 0) for v in self._languages.values()]) 259 | for k, v in self._languages.items(): 260 | v["prop"]: float = 100 * (v.get("size", 0) / langs_total) 261 | 262 | sleep(self._UNLOCK_WAIT_SECONDS) 263 | self.__is_stats_fetched = True 264 | 265 | def __exclude_repo_langs( 266 | self, 267 | repo_name: str, 268 | lang_name: str, 269 | languages: dict[str, dict[str, float | str]], 270 | ) -> bool: 271 | if repo_name in self.environment_vars.exclude_repo_langs.keys(): 272 | if ( 273 | lang_name in languages 274 | and not self.environment_vars.exclude_repo_langs[repo_name] 275 | or lang_name.lower() 276 | in self.environment_vars.exclude_repo_langs[repo_name] 277 | ): 278 | self._exclude_repo_languages.add(lang_name) 279 | return True 280 | return False 281 | 282 | async def repo_stats(self, repos: list[dict]) -> None: 283 | """ 284 | Gathers statistical data from fetches for repos user is associated with on GitHub 285 | """ 286 | for repo in repos: 287 | if not repo or await self.is_repo_type_excluded(repo_data=repo): 288 | continue 289 | 290 | repo_name: str = repo.get("nameWithOwner") 291 | if await self.is_repo_name_invalid(repo_name=repo_name): 292 | continue 293 | self._repos.add(repo_name) 294 | 295 | self._stargazers += repo.get("stargazers").get("totalCount", 0) 296 | self._forks += repo.get("forkCount", 0) 297 | 298 | if repo.get("isEmpty"): 299 | self._empty_repos.add(repo_name) 300 | continue 301 | 302 | for lang in repo.get("languages", {}).get("edges", []): 303 | lang_name: str = lang.get("node", {}).get("name", "Other") 304 | languages: dict[str, dict[str, float | str]] = await self.languages 305 | 306 | if self.__exclude_repo_langs( 307 | repo_name=repo_name, lang_name=lang_name, languages=languages 308 | ): 309 | continue 310 | 311 | if lang_name in self.environment_vars.exclude_langs: 312 | self._excluded_languages.add(lang_name) 313 | continue 314 | 315 | if lang_name in languages: 316 | languages[lang_name]["size"] += lang.get("size", 0) 317 | languages[lang_name]["occurrences"] += 1 318 | else: 319 | languages[lang_name] = { 320 | "size": lang.get("size", 0), 321 | "occurrences": 1, 322 | "color": lang.get("node", {}).get("color"), 323 | } 324 | 325 | async def manually_added_repo_stats(self) -> None: 326 | """ 327 | Gathers statistical data from fetches for manually added repos otherwise not fetched by user association 328 | """ 329 | lang_cols: dict[str, dict[str, str]] = self.queries.get_language_colors() 330 | 331 | for repo_name in self.environment_vars.manually_added_repos.union( 332 | self.environment_vars.more_collab_repos 333 | ).union(self.environment_vars.only_included_collab_repos): 334 | if await self.is_repo_name_invalid(repo_name=repo_name): 335 | continue 336 | self._repos.add(repo_name) 337 | 338 | repo_stats: dict[str, str | int | dict] = await self.queries.query_rest( 339 | path=f"/repos/{repo_name}" 340 | ) 341 | if await self.is_repo_type_excluded(repo_data=repo_stats): 342 | continue 343 | 344 | self._stargazers += repo_stats.get("stargazers_count", 0) 345 | self._forks += repo_stats.get("forks", 0) 346 | 347 | if repo_stats.get("size") == 0: 348 | self._empty_repos.add(repo_name) 349 | continue 350 | 351 | if repo_stats.get("language"): 352 | langs: dict[str, int] = await self.queries.query_rest( 353 | path=f"/repos/{repo_name}/languages" 354 | ) 355 | 356 | for lang_name, size in langs.items(): 357 | languages: dict[str, dict[str, float | str]] = await self.languages 358 | 359 | if self.__exclude_repo_langs( 360 | repo_name=repo_name, lang_name=lang_name, languages=languages 361 | ): 362 | continue 363 | 364 | if lang_name in self.environment_vars.exclude_langs: 365 | self._excluded_languages.add(lang_name) 366 | continue 367 | 368 | if lang_name in languages: 369 | languages[lang_name]["size"] += size 370 | languages[lang_name]["occurrences"] += 1 371 | else: 372 | languages[lang_name] = { 373 | "size": size, 374 | "occurrences": 1, 375 | "color": lang_cols.get(lang_name).get("color"), 376 | } 377 | 378 | @property 379 | async def name(self) -> str: 380 | """ 381 | :return: GitHub user's name 382 | """ 383 | if self._name is not None: 384 | return self._name 385 | await self.get_stats() 386 | assert self._name is not None 387 | return self._name 388 | 389 | @property 390 | async def stargazers(self) -> int: 391 | """ 392 | :return: total number of stargazers on user's repos 393 | """ 394 | if self._stargazers is not None: 395 | return self._stargazers 396 | await self.get_stats() 397 | assert self._stargazers is not None 398 | return self._stargazers 399 | 400 | @property 401 | async def forks(self) -> int: 402 | """ 403 | :return: total number of forks on user's repos 404 | """ 405 | if self._forks is not None: 406 | return self._forks 407 | await self.get_stats() 408 | assert self._forks is not None 409 | return self._forks 410 | 411 | @property 412 | async def languages(self) -> dict[str, dict[str, float | str]]: 413 | """ 414 | :return: summary of languages used by the user 415 | """ 416 | if self._languages is not None: 417 | return self._languages 418 | await self.get_stats() 419 | assert self._languages is not None 420 | return self._languages 421 | 422 | @property 423 | async def excluded_languages(self) -> set[str]: 424 | """ 425 | :return: summary of languages used by the user 426 | """ 427 | if self._excluded_languages is not None: 428 | return self._excluded_languages 429 | await self.get_stats() 430 | assert self._excluded_languages is not None 431 | return self._excluded_languages 432 | 433 | @property 434 | async def languages_proportional(self) -> dict[str, float]: 435 | """ 436 | :return: summary of languages used by the user, with proportional usage 437 | """ 438 | if self._languages is None: 439 | await self.get_stats() 440 | assert self._languages is not None 441 | return {k: v.get("prop", 0) for (k, v) in self._languages.items()} 442 | 443 | @property 444 | async def repos(self) -> set[str]: 445 | """ 446 | :return: list of names of repos user is involved with 447 | """ 448 | if self._repos is not None: 449 | return self._repos 450 | await self.get_stats() 451 | assert self._repos is not None 452 | return self._repos 453 | 454 | @property 455 | async def owned_repos(self) -> set[str]: 456 | """ 457 | :return: list of names of repos owned by user 458 | """ 459 | if self._owned_repos is not None: 460 | return self._owned_repos 461 | await self.get_stats() 462 | assert self._repos is not None 463 | self._owned_repos: set[str] = set( 464 | [ 465 | i 466 | for i in self._repos 467 | if self.environment_vars.username == i.split("/")[0] 468 | ] 469 | ) 470 | return self._owned_repos 471 | 472 | @property 473 | async def contributed_collab_repos(self) -> set[str]: 474 | """ 475 | :return: list of names of repos contributed to by user in collaborations with at least one other 476 | """ 477 | if self._contributed_collab_repos is not None: 478 | return self._contributed_collab_repos 479 | await self.lines_changed 480 | assert self._contributed_collab_repos is not None 481 | return self._contributed_collab_repos 482 | 483 | @property 484 | async def total_contributions(self) -> int: 485 | """ 486 | :return: count of user's total contributions as defined by GitHub 487 | """ 488 | if self._total_contributions is not None: 489 | return self._total_contributions 490 | self._total_contributions: int = 0 491 | 492 | years: list[str] = ( 493 | ( 494 | await self.queries.query( 495 | generated_query=GitHubApiQueries.contributions_all_years() 496 | ) 497 | ) 498 | .get("data", {}) 499 | .get("viewer", {}) 500 | .get("contributionsCollection", {}) 501 | .get("contributionYears", []) 502 | ) 503 | 504 | by_year: list[dict[str, dict[str, int]]] = list( 505 | ( 506 | await self.queries.query( 507 | generated_query=GitHubApiQueries.all_contributions(years=years) 508 | ) 509 | ) 510 | .get("data", {}) 511 | .get("viewer", {}) 512 | .values() 513 | ) 514 | 515 | for year in by_year: 516 | self._total_contributions += year.get("contributionCalendar", {}).get( 517 | "totalContributions", 0 518 | ) 519 | 520 | return cast(typ=int, val=self._total_contributions) 521 | 522 | @property 523 | async def lines_changed(self) -> tuple[int, int]: 524 | """ 525 | Fetches total lines added and deleted for user and repository total 526 | Calculates total and average line changes for user 527 | Calculates total contributors 528 | :return: count of total lines added, removed, or modified by the user 529 | """ 530 | if self._users_lines_changed is not None: 531 | return self._users_lines_changed 532 | _, collab_repos = await self.raw_collaborators() 533 | slave_status_repos: set[str] = self.environment_vars.more_collab_repos 534 | slave_status_repo_owners: set[str] = ( 535 | self.environment_vars.more_collab_repo_owners 536 | ) 537 | exclusive_collab_repos: set[str] = ( 538 | self.environment_vars.only_included_collab_repos 539 | ) 540 | exclusive_collab_repo_owners: set[str] = ( 541 | self.environment_vars.only_included_collab_repo_owners 542 | ) 543 | 544 | contributor_set: set[str] = set() 545 | repo_total_changes_arr: list[int] = [] 546 | author_contribution_percentages: list[float] = [] 547 | author_contribution_percentages_weighted: list[float] = [] 548 | author_total_additions: int = 0 549 | author_total_deletions: int = 0 550 | 551 | self._contributed_collab_repos: set[str] = collab_repos.copy().union( 552 | slave_status_repos.copy() 553 | ) 554 | 555 | for repo in await self.repos: 556 | if repo in self._empty_repos: 557 | continue 558 | repo_contributors: set[str] = set() 559 | repo_contributors.add(self.environment_vars.username) 560 | other_authors_total_changes: int = 0 561 | author_additions: int = 0 562 | author_deletions: int = 0 563 | 564 | r: list[dict[str, any]] = await self.queries.query_rest( 565 | path=f"/repos/{repo}/stats/contributors" 566 | ) 567 | 568 | for author_obj in r: 569 | # Handle malformed response from API by skipping this repo 570 | if not isinstance(author_obj, dict) or not isinstance( 571 | author_obj.get("author", {}), dict 572 | ): 573 | continue 574 | author: str = author_obj.get("author", {}).get("login", "") 575 | contributor_set.add( 576 | author 577 | ) # for count number of total other contributors 578 | 579 | if ( 580 | author != self.environment_vars.username 581 | and author not in self._EXCLUDED_USER_NAMES 582 | ): 583 | for week in author_obj.get("weeks", []): 584 | other_authors_total_changes += week.get("a", 0) 585 | other_authors_total_changes += week.get("d", 0) 586 | repo_contributors.add(author) 587 | else: 588 | for week in author_obj.get("weeks", []): 589 | author_additions += week.get("a", 0) 590 | author_deletions += week.get("d", 0) 591 | author_total_additions += author_additions 592 | author_total_deletions += author_deletions 593 | 594 | # add repo if in collaboration with at least one other to list for comparing with total repo count 595 | if other_authors_total_changes > 0: 596 | self._contributed_collab_repos.add(repo) 597 | 598 | # calculate average author's contributions to each repository with at least one other collaborator 599 | if ( 600 | repo not in self.environment_vars.exclude_collab_repos 601 | and repo.split("/")[0] 602 | not in self.environment_vars.exclude_collab_repo_owners 603 | and ( 604 | not (exclusive_collab_repos or exclusive_collab_repo_owners) 605 | or repo in exclusive_collab_repos 606 | or repo.split("/")[0] in exclusive_collab_repo_owners 607 | or repo in slave_status_repos 608 | or repo.split("/")[0] in slave_status_repo_owners 609 | ) 610 | and (author_additions + author_deletions) > 0 611 | and ( 612 | other_authors_total_changes > 0 613 | or repo 614 | in collab_repos.union( 615 | slave_status_repos 616 | ) # either collaborators are ghosting or no show in repo 617 | or repo.split("/")[0] in slave_status_repo_owners 618 | ) 619 | ): 620 | repo_total_changes: int = ( 621 | other_authors_total_changes + author_additions + author_deletions 622 | ) 623 | author_contribution_percentages.append( 624 | (author_additions + author_deletions) / repo_total_changes 625 | ) 626 | author_contribution_percentages_weighted.append( 627 | min( 628 | 1.0, 629 | author_contribution_percentages[-1] 630 | / ( 631 | 1 632 | / len(repo_contributors) 633 | * (2 if len(repo_contributors) > 1 else 1) 634 | ), 635 | ) 636 | ) 637 | repo_total_changes_arr.append(repo_total_changes) 638 | 639 | if sum(author_contribution_percentages) > 0: 640 | self._avg_percent: str = ( 641 | f"{(sum(author_contribution_percentages) / len(repo_total_changes_arr) * 100):0.2f}%" 642 | ) 643 | self._avg_percent_weighted: str = ( 644 | f"{(sum(author_contribution_percentages_weighted) / len(repo_total_changes_arr) * 100):0.2f}%" 645 | ) 646 | else: 647 | self._avg_percent_weighted = self._avg_percent = "N/A" 648 | 649 | self._contributors: set[str] = contributor_set 650 | 651 | self._users_lines_changed: tuple[int, int] = ( 652 | author_total_additions, 653 | author_total_deletions, 654 | ) 655 | return self._users_lines_changed 656 | 657 | @property 658 | async def avg_contribution_percent(self) -> str: 659 | """ 660 | :return: str representing the avg percent of user's repo contributions 661 | """ 662 | if self._avg_percent is not None: 663 | return self._avg_percent 664 | await self.lines_changed 665 | assert self._avg_percent is not None 666 | return self._avg_percent 667 | 668 | @property 669 | async def avg_contribution_percent_weighted(self) -> str: 670 | """ 671 | :return: str representing the avg percent of user's repo contributions weighted by number of contributors 672 | """ 673 | if self._avg_percent_weighted is not None: 674 | return self._avg_percent_weighted 675 | await self.lines_changed 676 | assert self._avg_percent_weighted is not None 677 | return self._avg_percent_weighted 678 | 679 | @property 680 | async def views(self) -> int: 681 | """ 682 | Note: API returns a user's repository view data for the last 14 days. 683 | This counts views as of the initial date this code is first run in repo 684 | :return: view count of user's repositories as of a given (first) date 685 | """ 686 | if self._views is not None: 687 | return self._views 688 | 689 | last_viewed: str = self.environment_vars.repo_last_viewed 690 | today: str = date.today().strftime(format=self._DATE_FORMAT) 691 | yesterday: str = (date.today() - timedelta(1)).strftime( 692 | format=self._DATE_FORMAT 693 | ) 694 | dates: set[str] = {last_viewed, yesterday} 695 | 696 | today_view_count: int = 0 697 | for repo in await self.repos: 698 | r: dict[str, str | list[dict[str, str]]] = await self.queries.query_rest( 699 | path=f"/repos/{repo}/traffic/views" 700 | ) 701 | 702 | for view in r.get("views", []): 703 | if view.get("timestamp")[:10] == today: 704 | today_view_count += view.get("count", 0) 705 | elif view.get("timestamp")[:10] > last_viewed: 706 | self.environment_vars.set_views(views=view.get("count", 0)) 707 | dates.add(view.get("timestamp")[:10]) 708 | 709 | if last_viewed == "0000-00-00": 710 | dates.remove(last_viewed) 711 | 712 | if self.environment_vars.is_store_repo_view_count: 713 | self.environment_vars.set_last_viewed(new_last_viewed_date=yesterday) 714 | 715 | if self.environment_vars.repo_first_viewed == "0000-00-00": 716 | self.environment_vars.repo_first_viewed = min(dates) 717 | self.environment_vars.set_first_viewed( 718 | new_first_viewed_date=self.environment_vars.repo_first_viewed 719 | ) 720 | self._views_from_date: str = self.environment_vars.repo_first_viewed 721 | else: 722 | self._views_from_date = min(dates) 723 | 724 | self._views: int = self.environment_vars.repo_views + today_view_count 725 | return self._views 726 | 727 | @property 728 | async def views_from_date(self) -> str: 729 | """ 730 | :return: the first date included in the repo view count 731 | """ 732 | if self._views_from_date is not None: 733 | return self._views_from_date 734 | await self.views 735 | assert self._views_from_date is not None 736 | return self._views_from_date 737 | 738 | async def raw_collaborators(self) -> tuple[set[str], set[str]]: 739 | if self._collaborator_set is not None and self._collab_repos is not None: 740 | return self._collaborator_set, self._collab_repos 741 | 742 | self._collaborator_set: set[str] = set() 743 | self._collab_repos: set[str] = set() 744 | 745 | for repo in await self.repos: 746 | r: list[dict[str, any]] = await self.queries.query_rest( 747 | path=f"/repos/{repo}/collaborators" 748 | ) 749 | collab_count: int = 0 750 | 751 | for obj in r: 752 | if isinstance(obj, dict): 753 | collab_count += 1 754 | self._collaborator_set.add(obj.get("login")) 755 | 756 | if collab_count > 1: 757 | self._collab_repos.add(repo) 758 | 759 | return self._collaborator_set, self._collab_repos 760 | 761 | @property 762 | async def collaborators(self) -> int: 763 | """ 764 | :return: count of total collaborators to user's repositories 765 | """ 766 | if self._collaborators is not None: 767 | return self._collaborators 768 | 769 | collaborator_set, _ = await self.raw_collaborators() 770 | collaborators: int = max( 771 | 0, len(collaborator_set.union(await self.contributors)) - 1 772 | ) 773 | self._collaborators: int = ( 774 | self.environment_vars.more_collaborators + collaborators 775 | ) 776 | return self._collaborators 777 | 778 | @property 779 | async def contributors(self) -> set[str]: 780 | """ 781 | :return: count of total contributors to user's repositories 782 | """ 783 | if self._contributors is not None: 784 | return self._contributors 785 | await self.lines_changed 786 | assert self._contributors is not None 787 | return self._contributors 788 | 789 | @property 790 | async def pull_requests(self) -> int: 791 | """ 792 | :return: count of pull requests in repos user has either created, reviewed, commented, been assigned... 793 | """ 794 | if self._pull_requests is not None: 795 | return self._pull_requests 796 | 797 | pull_requests: set[str] = set() 798 | 799 | if not self._is_fetch_rate_limit_exceeded: 800 | for repo in await self.repos: 801 | end_point: str = ( 802 | f"/repos/{repo}/pulls?state=all&involved={self.environment_vars.username}" 803 | ) 804 | 805 | for pr_data in await self.queries.query_rest(path=end_point): 806 | try: 807 | ( 808 | pull_requests.add(pr_data["url"]) 809 | if "url" in pr_data.keys() 810 | else None 811 | ) 812 | except AttributeError: 813 | self._is_fetch_rate_limit_exceeded = True 814 | break 815 | 816 | if self._is_fetch_rate_limit_exceeded: 817 | break 818 | 819 | self._pull_requests: int = ( 820 | len(pull_requests) 821 | if len(pull_requests) > self.environment_vars.pull_requests_count 822 | else self.environment_vars.pull_requests_count 823 | ) 824 | self.environment_vars.set_pull_requests(pull_requests_count=self._pull_requests) 825 | return self._pull_requests 826 | 827 | @property 828 | async def issues(self) -> int: 829 | """ 830 | :return: count of issues in repos user has either created, reacted to, commented, been assigned... 831 | """ 832 | if self._issues is not None: 833 | return self._issues 834 | 835 | issues: set[str] = set() 836 | 837 | if not self._is_fetch_rate_limit_exceeded: 838 | for repo in await self.repos: 839 | end_point: str = ( 840 | f"/repos/{repo}/issues?state=all&involved={self.environment_vars.username}" 841 | ) 842 | 843 | for issue_data in await self.queries.query_rest(path=end_point): 844 | try: 845 | ( 846 | issues.add(issue_data["url"]) 847 | if "url" in issue_data.keys() 848 | else None 849 | ) 850 | except AttributeError: 851 | self._is_fetch_rate_limit_exceeded = True 852 | break 853 | 854 | if self._is_fetch_rate_limit_exceeded: 855 | break 856 | 857 | self._issues: int = ( 858 | len(issues) 859 | if len(issues) > self.environment_vars.issues_count 860 | else self.environment_vars.issues_count 861 | ) 862 | self.environment_vars.set_issues(issues_count=self._issues) 863 | return self._issues 864 | -------------------------------------------------------------------------------- /src/templates/languages.svg: -------------------------------------------------------------------------------- 1 | 2 | 147 | 148 | 149 | 150 | 151 |
    152 | 153 |

    {{ lang_count }} Languages (by File Size %):

    154 | 155 |
    156 | 157 | {{ progress }} 158 | 159 |
    160 | 161 |
      162 | {{ lang_list }} 163 |
    164 |
    165 |
    166 |
    167 |
    168 |
    169 | -------------------------------------------------------------------------------- /src/templates/overview.svg: -------------------------------------------------------------------------------- 1 | 2 | 105 | 106 | 107 | 108 | 109 |
    110 | 111 | 112 | 113 | 114 | 117 | 118 | 119 | 120 | 121 | 122 | 128 | 131 | 132 | 133 | 134 | 140 | 143 | 144 | 145 | 146 | 152 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 180 | 183 | 184 | 185 | 186 | 192 | 195 | 196 | 197 | 198 | 204 | 207 | 208 | 209 | 210 | 220 | 223 | 224 | 225 | 226 |
    115 | {{ name }} GitHub Statistics 116 |
    123 | 126 | All-time GitHub contributions 127 | 129 | {{ contributions }} 130 |
    135 | 136 | 137 | 138 | Lines of code changes 139 | 141 | {{ lines_changed }} 142 |
    147 | 148 | 149 | 150 | Avg contributions [weighted] 151 | 153 | {{ avg_contribution_percent }} 154 |
    175 | 178 | Repos contributed [% collab] 179 | 181 | {{ repos_str }} 182 |
    187 | 188 | 189 | 190 | {{ views_from_date }} 191 | 193 | {{ views }} 194 |
    199 | 202 | Repo collaborators 203 | 205 | {{ collaborators_and_contributors }} 206 |
    211 | 212 | 213 | 214 | Repo forks | 215 | 216 | 217 | 218 | Stars 219 | 221 | {{ forks_and_stars }} 222 |
    227 |
    228 |
    229 |
    230 |
    231 |
    232 | -------------------------------------------------------------------------------- /test/__init__.py: -------------------------------------------------------------------------------- 1 | __all__ = ["git_stats_test"] 2 | -------------------------------------------------------------------------------- /test/git_stats_test.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | """ 4 | Prints GitHub repository statistics to console for testing 5 | """ 6 | 7 | from asyncio import run, set_event_loop_policy, WindowsSelectorEventLoopPolicy 8 | from aiohttp import ClientSession 9 | from os import getenv 10 | 11 | from src.github_repo_stats import GitHubRepoStats 12 | from src.env_vars import EnvironmentVariables 13 | 14 | # REQUIRED 15 | ACCESS_TOKEN: str = getenv("ACCESS_TOKEN") # or manually enter ACCESS_TOKEN string 16 | GITHUB_ACTOR: str = getenv("GITHUB_ACTOR") # or manually enter '' 17 | 18 | # OPTIONAL 19 | EXCLUDED_REPOS: str = getenv( 20 | "EXCLUDED_REPOS" 21 | ) # or enter: '[owner/repo],...,[owner/repo]' 22 | EXCLUDED_OWNERS: str = getenv("EXCLUDED_OWNERS") # or enter: '[owner],...,[owner]' 23 | EXCLUDED_LANGS: str = getenv("EXCLUDED_LANGS") # or enter: '[lang],...,[lang]' 24 | EXCLUDED_REPO_LANGS: str = getenv( 25 | "EXCLUDED_REPO_LANGS" 26 | ) # or enter: '[owner/repo],...,[owner/repo]' 27 | IS_INCLUDE_FORKED_REPOS: str = getenv("IS_INCLUDE_FORKED_REPOS") # or enter: '' 28 | IS_EXCLUDE_CONTRIB_REPOS: str = getenv("IS_EXCLUDE_CONTRIB_REPOS") # or enter: '' 29 | IS_EXCLUDE_ARCHIVE_REPOS: str = getenv("IS_EXCLUDE_ARCHIVE_REPOS") # or enter: '' 30 | IS_EXCLUDE_PRIVATE_REPOS: str = getenv("IS_EXCLUDE_PRIVATE_REPOS") # or enter: '' 31 | IS_EXCLUDE_PUBLIC_REPOS: str = getenv("IS_EXCLUDE_PUBLIC_REPOS") # or enter: '' 32 | REPO_VIEWS: str = getenv("REPO_VIEWS") # or enter: '' 33 | LAST_VIEWED: str = getenv("LAST_VIEWED") # or enter: 'YYYY-MM-DD' 34 | FIRST_VIEWED: str = getenv("FIRST_VIEWED") # or enter: 'YYYY-MM-DD' 35 | IS_MAINTAIN_REPO_VIEWS: str = getenv("IS_STORE_REPO_VIEWS") # or enter: '' 36 | MORE_COLLABS: str = getenv("MORE_COLLABS") # or enter: '' 37 | MORE_REPOS: str = getenv("MORE_REPOS") # or enter: '[owner/repo],...,[owner/repo]' 38 | ONLY_INCLUDED_REPOS: str = getenv( 39 | "ONLY_INCLUDED_REPOS" 40 | ) # or enter: '[owner/repo],...,[owner/repo]' 41 | ONLY_INCLUDED_OWNERS: str = getenv( 42 | "ONLY_INCLUDED_OWNERS" 43 | ) # or enter: [owner],...,[owner] 44 | ONLY_INCLUDED_COLLAB_REPOS: str = getenv( 45 | "ONLY_INCLUDED_COLLAB_REPOS" 46 | ) # or enter: [owner/repo],...,[owner/repo] 47 | ONLY_INCLUDED_COLLAB_REPO_OWNERS: str = getenv( 48 | "ONLY_INCLUDED_COLLAB_REPO_OWNERS" 49 | ) # or enter: [owner],...,[owner] 50 | EXCLUDED_COLLAB_REPOS: str = getenv( 51 | "EXCLUDED_COLLAB_REPOS" 52 | ) # or enter: [owner/repo],...,[owner/repo] 53 | EXCLUDED_COLLAB_REPO_OWNERS: str = getenv( 54 | "EXCLUDED_COLLAB_REPO_OWNERS" 55 | ) # or enter: [owner],...,[owner] 56 | MORE_COLLAB_REPOS: str = getenv( 57 | "MORE_COLLAB_REPOS" 58 | ) # or enter: [owner/repo],...,[owner/repo] 59 | 60 | 61 | async def main() -> None: 62 | """ 63 | Used for testing 64 | """ 65 | if not (ACCESS_TOKEN and GITHUB_ACTOR): 66 | raise RuntimeError( 67 | "ACCESS_TOKEN and GITHUB_ACTOR environment variables can't be None" 68 | ) 69 | 70 | async with ClientSession() as session: 71 | stats: GitHubRepoStats = GitHubRepoStats( 72 | environment_vars=EnvironmentVariables( 73 | username=GITHUB_ACTOR, 74 | access_token=ACCESS_TOKEN, 75 | exclude_repos=EXCLUDED_REPOS, 76 | exclude_owners=EXCLUDED_OWNERS, 77 | exclude_langs=EXCLUDED_LANGS, 78 | exclude_repo_langs=EXCLUDED_REPO_LANGS, 79 | is_include_forked_repos=IS_INCLUDE_FORKED_REPOS, 80 | is_exclude_contrib_repos=IS_EXCLUDE_CONTRIB_REPOS, 81 | is_exclude_archive_repos=IS_EXCLUDE_ARCHIVE_REPOS, 82 | is_exclude_private_repos=IS_EXCLUDE_PRIVATE_REPOS, 83 | is_exclude_public_repos=IS_EXCLUDE_PUBLIC_REPOS, 84 | repo_views=REPO_VIEWS, 85 | repo_last_viewed=LAST_VIEWED, 86 | repo_first_viewed=FIRST_VIEWED, 87 | is_store_repo_view_count=IS_MAINTAIN_REPO_VIEWS, 88 | more_collaborators=MORE_COLLABS, 89 | manually_added_repos=MORE_REPOS, 90 | only_included_repos=ONLY_INCLUDED_REPOS, 91 | only_included_owners=ONLY_INCLUDED_OWNERS, 92 | only_included_collab_repos=ONLY_INCLUDED_COLLAB_REPOS, 93 | only_included_collab_repo_owners=ONLY_INCLUDED_COLLAB_REPO_OWNERS, 94 | exclude_collab_repos=EXCLUDED_COLLAB_REPOS, 95 | exclude_collab_repo_owners=EXCLUDED_COLLAB_REPO_OWNERS, 96 | more_collab_repos=MORE_COLLAB_REPOS, 97 | ), 98 | session=session, 99 | ) 100 | print(await stats.to_str()) 101 | 102 | 103 | if __name__ == "__main__": 104 | set_event_loop_policy(policy=WindowsSelectorEventLoopPolicy()) 105 | run(main=main()) 106 | --------------------------------------------------------------------------------