├── .github └── workflows │ ├── gist-push.yml │ ├── python-package.yml │ └── python-publish.yml ├── .gitignore ├── .pre-commit-config.yaml ├── LICENSE ├── README.md ├── examples ├── example_sub_dir │ └── gistyc_example2.py └── gistyc_example1.py ├── gistyc ├── __init__.py ├── cli.py └── gistyc.py ├── mypy.ini ├── pylintrc ├── pyproject.toml ├── requirements.txt ├── setup.cfg ├── setup.py ├── tests ├── __init__.py ├── _resources │ ├── create │ │ └── sample.py │ ├── create_dir │ │ └── sample1 │ │ │ └── sample1.py │ ├── update │ │ └── sample.py │ └── update_dir │ │ ├── sample1 │ │ └── sample1.py │ │ └── sample2.py ├── test_cli.py └── test_gistyc.py └── tox.ini /.github/workflows/gist-push.yml: -------------------------------------------------------------------------------- 1 | # CI/CD GitHub Action YAML file 2 | # 3 | # This YAML file executes a gistyc create / update pipeline on all Python files 4 | # within the folder ./examples (after merging to the main branch) 5 | name: GIST CD on main branch and example directory change 6 | 7 | # Check if files have been pushed to ./examples 8 | on: 9 | push: 10 | paths: 11 | - examples/** 12 | 13 | # Execute the gistyc create / update pipeline 14 | jobs: 15 | 16 | build: 17 | 18 | # Execute the pipeline only on changes on the main branche 19 | if: github.ref == 'refs/heads/main' 20 | 21 | runs-on: ubuntu-latest 22 | 23 | strategy: 24 | matrix: 25 | python-version: ['3.8'] 26 | 27 | # Steps: 28 | # - Checkout the branch & use Python 29 | # - Install gistyc 30 | # - Use gistyc_dir, authenticate and use the ./examples directory as an input 31 | steps: 32 | - uses: actions/checkout@v2 33 | - name: Set up Python ${{ matrix.python-version }} 34 | uses: actions/setup-python@v2 35 | with: 36 | python-version: ${{ matrix.python-version }} 37 | - name: Install gistyc 38 | run: pip install gistyc 39 | - name: Use gistyc CLI on examples/** 40 | run: gistyc_dir --auth-token ${{ secrets.GIST_TOKEN }} --directory ./examples/ 41 | -------------------------------------------------------------------------------- /.github/workflows/python-package.yml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a variety of Python versions 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions 3 | 4 | name: Python package 5 | 6 | on: 7 | push: 8 | branches: [ main ] 9 | pull_request: 10 | branches: [ main ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | strategy: 17 | matrix: 18 | python-version: [3.9] 19 | 20 | steps: 21 | - uses: actions/checkout@v2 22 | - name: Set up Python ${{ matrix.python-version }} 23 | uses: actions/setup-python@v2 24 | with: 25 | python-version: ${{ matrix.python-version }} 26 | - name: Install Tox and any other packages 27 | run: pip install tox 28 | - name: Run Tox + PyTest 29 | env: 30 | GIST_TOKEN: ${{ secrets.GIST_TOKEN }} 31 | # Run tox using the version of Python in `PATH` 32 | run: tox -e py 33 | - name: Run Tox + Flake8 34 | run: tox -e flake8 35 | - name: Run Tox + PyLint 36 | run: tox -e pylint 37 | - name: Run Tox + MyPy 38 | run: tox -e mypy 39 | - name: Run Tox + pydocstyle 40 | run: tox -e pydocstyle 41 | - name: Run Tox + bandit 42 | run: tox -e bandit 43 | -------------------------------------------------------------------------------- /.github/workflows/python-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflow will upload a Python Package using Twine when a release is created 2 | # For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries 3 | 4 | name: Upload Python Package 5 | 6 | on: 7 | release: 8 | types: [created] 9 | 10 | jobs: 11 | deploy: 12 | 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - uses: actions/checkout@v2 17 | - name: Set up Python 18 | uses: actions/setup-python@v2 19 | with: 20 | python-version: '3.x' 21 | - name: Install dependencies 22 | run: | 23 | python -m pip install --upgrade pip 24 | pip install setuptools wheel twine 25 | - name: Build and publish 26 | env: 27 | TWINE_USERNAME: __token__ 28 | TWINE_PASSWORD: ${{ secrets.PYPI_APIKEY }} 29 | run: | 30 | python setup.py sdist bdist_wheel 31 | twine upload dist/* 32 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.tox 2 | *.pyc 3 | *.DS_Store 4 | *build 5 | *dist 6 | *.egg-info 7 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/psf/black 3 | rev: stable 4 | hooks: 5 | - id: black 6 | language_version: python3.8 7 | -------------------------------------------------------------------------------- /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 | # gistyc 2 | 3 | gistyc is a Python-based library that enables developers to create, update and delete their GitHub GISTs. CLI capabilities allow you to execute the routines from the shell and can be integrated into your project's CI/CD pipeline to automatically create or update your GISTs (e.g., via GitHub actions). Files are separated in GIST sections depending on the separation blocks. 4 | 5 | gistyc considers currently only Python files (.py ending) in a Spyder-like code block separation (code block separator: #%%) 6 | 7 | --- 8 | 9 | ## Prerequisites 10 | 11 | 1. Python 3.8 (recommendation: using a virtual environment) 12 | 2. A GitHub Personal access token with GIST access: 13 | - Click on your personal account profile (top right) 14 | - Click Settings 15 | - On the left menu bar go to Developer settings and choose Personal access tokens 16 | - Generate new token and write a name (note) of your token. The note does not affect the functionality, but choose a note that describes the purpose of the token e.g., GIST_token 17 | - Set a mark at gist (Create gists) and click on Generate token at the bottom of the page 18 | - IMPORTANT: The displayed token appears only once. Copy it and store it in your GitHub project as a secret and / or locally as an environment variable. 19 | 20 | --- 21 | 22 | ## Installation 23 | ```bash 24 | pip install gistyc 25 | ``` 26 | 27 | ... or install it from the main branch of this [repository](https://github.com/ThomasAlbin/gistyc). You can also download the entire repository to run the tests, download the CI/CD scripts etc. 28 | 29 | --- 30 | 31 | ## Python library calls 32 | 33 | Please note: ./tests provides some examples that can be reproduced / applied.
34 | We assume: 35 | - AUTH_TOKEN: is the GIST access token 36 | - FILEPATH: is the absolute or relative path of a Python file 37 | - GIST_ID: ID of a GIST.
38 | 39 | ### Create a GIST 40 | 41 | ```python 42 | # import 43 | import gistyc 44 | 45 | # Initiate the GISTyc class with the auth token 46 | gist_api = gistyc.GISTyc(auth_token=AUTH_TOKEN) 47 | 48 | # Create a GIST with the sample file 49 | response_data = gist_api.create_gist(file_name=FILEPATH) 50 | ``` 51 | 52 | ### Update a GIST 53 | 54 | Updating a GIST requires either ONLY the FILEPATH or the FILEPATH AND a corresponding GIST ID, if the GIST repository contains file names that occur more than once. Hint: keep your GIST repository clean from same-name files! 55 | 56 | Update using ONLY the FILEPATH: 57 | 58 | ```python 59 | # import 60 | import gistyc 61 | 62 | # Initiate the GISTyc class with the auth token 63 | gist_api = gistyc.GISTyc(auth_token=AUTH_TOKEN) 64 | 65 | # Update the GIST with the updated sample file (update is based on the file's name) 66 | response_update_data = gist_api.update_gist(file_name=FILEPATH) 67 | ``` 68 | 69 | Update using the FILEPATH AND GIST ID: 70 | 71 | ```python 72 | # import 73 | import gistyc 74 | 75 | # Initiate the GISTyc class with the auth token 76 | gist_api = gistyc.GISTyc(auth_token=AUTH_TOKEN) 77 | 78 | # Update the GIST based on the GISTs ID 79 | response_update_data = gist_api.update_gist(file_name=FILEPATH, 80 | gist_id=GIST_ID) 81 | ``` 82 | 83 | ## Get GISTs 84 | 85 | Please note: one can obtain a list of all GISTs via: 86 | 87 | ```python 88 | # import 89 | import gistyc 90 | 91 | # Initiate the GISTyc class with the auth token 92 | gist_api = gistyc.GISTyc(auth_token=AUTH_TOKEN) 93 | 94 | # Get a list of GISTs 95 | gist_list = gist_api.get_gists() 96 | ``` 97 | 98 | ## Delete a GIST 99 | 100 | Deletion using ONLY the FILEPATH 101 | 102 | ```python 103 | # import 104 | import gistyc 105 | 106 | # Initiate the GISTyc class with the auth token 107 | gist_api = gistyc.GISTyc(auth_token=AUTH_TOKEN) 108 | 109 | # Delete the GIST, based on the GIST ID 110 | response_data = gist_api.delete_gist(file_name=FILEPATH) 111 | ``` 112 | 113 | Deletion using ONLY the GIST ID 114 | 115 | ```python 116 | # import 117 | import gistyc 118 | 119 | # Initiate the GISTyc class with the auth token 120 | gist_api = gistyc.GISTyc(auth_token=AUTH_TOKEN) 121 | 122 | # Delete the GIST, based on the GIST ID 123 | response_data = gist_api.delete_gist(gist_id=GIST_ID) 124 | ``` 125 | 126 | 127 | --- 128 | 129 | ## CLI 130 | 131 | Please note: ./tests provides some examples that can be reproduced / applied.
132 | We assume: 133 | - AUTH_TOKEN: is the GIST access token 134 | - FILEPATH: is the absolute or relative path of a Python file 135 | - GIST_ID: ID of a GIST 136 | - DIRECTORY: A directory (with an arbitrary number of sub-directories) that contains Python files
137 | 138 | ### Create a GIST 139 | 140 | ```bash 141 | gistyc --create --auth-token AUTH_TOKEN --file-name FILEPATH 142 | ``` 143 | 144 | ### Update a GIST 145 | 146 | Update using ONLY the FILEPATH: 147 | 148 | ```bash 149 | gistyc --update --auth-token AUTH_TOKEN --file-name FILEPATH 150 | ``` 151 | 152 | Update using the FILEPATH AND GIST ID: 153 | 154 | ```bash 155 | gistyc --update --auth-token AUTH_TOKEN --file-name FILEPATH --gist-id GIST_ID 156 | ``` 157 | 158 | ### Delete a GIST 159 | 160 | Deletion using ONLY the FILEPATH 161 | 162 | ```bash 163 | gistyc --delete --auth-token AUTH_TOKEN --file-name FILEPATH 164 | ``` 165 | 166 | Deletion using ONLY the GIST ID 167 | 168 | ```bash 169 | gistyc --delete --auth-token AUTH_TOKEN --gist-id GIST_ID 170 | ``` 171 | 172 | ### Directory Create & Update 173 | 174 | A second gistyc CLI allows you to provide a directory as an input that recursively gets all Python files and creates or updates GISTs accordingly. Please Note: File names MUST be unique in GIST. 175 | 176 | ```bash 177 | gistyc_dir --auth-token AUTH_TOKEN --directory DIRECTORY 178 | ``` 179 | 180 | --- 181 | 182 | ## Example 183 | 184 | Example Python files (in a directory) can be found [here](https://github.com/ThomasAlbin/gistyc/tree/main/examples). 185 | 186 | The corresponding GISTs are embedded hereinafter: 187 | https://gist.github.com/ThomasAlbin/b18383a86cb4396a79a551a73330ce76 188 | https://gist.github.com/ThomasAlbin/caddb300ac663e60ae573b1117599fcc. 189 | 190 | --- 191 | 192 | ## GitHub Actions - CI/CD 193 | 194 | The following YAML file is used by the gistyc repository to provide an example on how to use gistyc in a CI/CD pipeline. Example Python scripts are stored, added and edited in ./examples. Changes in this directory trigger the pipeline (only after a merge with the main branch). 195 | 196 | ```YAML 197 | # CI/CD GitHub Action YAML file 198 | # 199 | # This YAML file executes a gistyc create / update pipeline on all Python files 200 | # within the folder ./examples (after merging to the main branch) 201 | name: GIST CD on main branch and example directory change 202 | 203 | # Check if files have been pushed to ./examples 204 | on: 205 | push: 206 | paths: 207 | - examples/** 208 | 209 | # Execute the gistyc create / update pipeline 210 | jobs: 211 | 212 | build: 213 | 214 | # Execute the pipeline only on changes on the main branche 215 | if: github.ref == 'refs/heads/main' 216 | 217 | runs-on: ubuntu-latest 218 | 219 | strategy: 220 | matrix: 221 | python-version: ['3.8'] 222 | 223 | # Steps: 224 | # - Checkout the branch & use Python 225 | # - Install gistyc 226 | # - Use gistyc_dir, authenticate and use the ./examples directory as an input 227 | steps: 228 | - uses: actions/checkout@v2 229 | - name: Set up Python ${{ matrix.python-version }} 230 | uses: actions/setup-python@v2 231 | with: 232 | python-version: ${{ matrix.python-version }} 233 | - name: Install gistyc 234 | run: pip install gistyc 235 | - name: Use gistyc CLI on examples/** 236 | run: gistyc_dir --auth-token ${{ secrets.GIST_TOKEN }} --directory ./examples/ 237 | ``` 238 | 239 | --- 240 | 241 | ## Support & Contributions 242 | 243 | If you have requests, issues or ideas please use the GitHub Issues. Contributions are always welcome and should be provided via a Pull Request. Please note the strict coding standards and other guidelines. These standards are checked for all PRs and can be seen [here](https://github.com/ThomasAlbin/gistyc/blob/main/.github/workflows/python-package.yml). Please note that all functions must contain a pytest. 244 | 245 | Direct messages to the author of gistyc are always welcome. Please use [Twitter](https://twitter.com/MrAstroThomas), [Reddit](https://www.reddit.com/user/MrAstroThomas) or [Medium](https://thomas-albin.medium.com/) for this purpose. 246 | 247 | Best,
248 | Thomas 249 | -------------------------------------------------------------------------------- /examples/example_sub_dir/gistyc_example2.py: -------------------------------------------------------------------------------- 1 | """A second sample example for gistyc""" 2 | 3 | # Import module 4 | import time 5 | 6 | #%% 7 | # Print the time in a more human readable format 8 | print(time.ctime()) 9 | 10 | #%% 11 | # A last code block / cell with a value 12 | TEMP = 1 13 | print(TEMP) 14 | -------------------------------------------------------------------------------- /examples/gistyc_example1.py: -------------------------------------------------------------------------------- 1 | """A sample example for the gistyc CLI v7""" 2 | 3 | # Import module 4 | import time 5 | 6 | #%% 7 | # Print the time 8 | print(time.time()) 9 | -------------------------------------------------------------------------------- /gistyc/__init__.py: -------------------------------------------------------------------------------- 1 | """Main init.""" 2 | 3 | __project__ = "GISTyc" 4 | __author__ = "Dr.-Ing. Thomas Albin" 5 | __version__ = 1.3 6 | 7 | from gistyc.gistyc import GISTyc, GISTAmbiguityError 8 | from . import cli 9 | -------------------------------------------------------------------------------- /gistyc/cli.py: -------------------------------------------------------------------------------- 1 | """CLI for the GISTyc routines.""" 2 | 3 | # Import standard libraries 4 | import pathlib 5 | import typing as t 6 | 7 | # Import installed libraries 8 | import click 9 | 10 | # Import GISTyc 11 | from . import GISTyc 12 | 13 | 14 | # Set click commands 15 | @click.command() 16 | @click.option("-C", "--create", is_flag=True, help="Flag: Create GIST") 17 | @click.option("-U", "--update", is_flag=True, help="Flag: Update GIST") 18 | @click.option("-D", "--delete", is_flag=True, help="Flag: Delete GIST") 19 | @click.option("-t", "--auth-token", help="GIST REST API token") 20 | @click.option("-f", "--file-name", help="Absolute or relative file name path") 21 | @click.option("-id", "--gist-id", default=None, help="GIST ID") 22 | def run( 23 | create: bool, update: bool, delete: bool, auth_token: str, file_name: str, gist_id: str 24 | ) -> None: 25 | """CLI routine to call the GISTyc API to create, update and delete a GIST. 26 | 27 | All public functions echo the response back to the terminal. 28 | 29 | Parameters 30 | ---------- 31 | create : bool 32 | Flag to trigger the create routine. 33 | update : bool 34 | Flag to trigger the update routine. 35 | delete : bool 36 | Flag to trigger the delete routine. 37 | auth_token : str 38 | GIST REST API token. 39 | file_name : str 40 | Absolute or relative file path. Required for create and update 41 | gist_id : str 42 | GIST ID for the update routine (if file name is ambiguous) and delete routine. 43 | 44 | Returns 45 | ------- 46 | None. 47 | 48 | """ 49 | # Set the GISTys class 50 | gist_api = GISTyc(auth_token=auth_token) 51 | 52 | # Create GIST routine 53 | if create: 54 | 55 | # Create a GIST with the sample file 56 | response_data = gist_api.create_gist(file_name=file_name) 57 | 58 | # Echo the resposen back to the terminal 59 | click.echo(str(response_data)) 60 | 61 | # Update GIST routine 62 | elif update: 63 | 64 | # If not GIST ID is provided: use only the file name 65 | if not gist_id: 66 | response_data = gist_api.update_gist(file_name=file_name) 67 | 68 | # Else, use the GIST ID 69 | else: 70 | response_data = gist_api.update_gist(file_name=file_name, gist_id=gist_id) 71 | 72 | # Echo the resposen back to the terminal 73 | click.echo(str(response_data)) 74 | 75 | # Delete GIST routine 76 | elif delete: 77 | 78 | # If not GIST ID is provided: use only the file name 79 | if not gist_id: 80 | response_int = gist_api.delete_gist(file_name=file_name) 81 | 82 | # Else, use the GIST ID 83 | else: 84 | response_int = gist_api.delete_gist(gist_id=gist_id) 85 | 86 | # Echo the resposen back to the terminal 87 | click.echo(str(response_int)) 88 | 89 | 90 | # A second CLI tool to parse directories 91 | @click.command() 92 | @click.option("-t", "--auth-token", help="GIST REST API token") 93 | @click.option("-d", "--directory", help="Directory that contains Python scripts") 94 | def dir_run(auth_token: str, directory: t.Union[pathlib.Path, str]) -> None: 95 | """CLI routine to create / update GitHub gists based on a given directory. 96 | 97 | This CLI routine takes a directory as an input and iterates recursively through it to determine 98 | all Python files. These files are then either created as a GIST or updated (if already 99 | present). Please note that GISTs must be unambiguous with respect to their file name. The 100 | update routine considers only the file name, since the directory input provides only a list 101 | of corresponding files. 102 | 103 | Parameters 104 | ---------- 105 | auth_token : str 106 | GIST REST API token. 107 | directory : t.Union[pathlib.Path, str] 108 | Direcotry containing Python files. 109 | 110 | Returns 111 | ------- 112 | None. 113 | 114 | """ 115 | # Set the GISTys class 116 | gist_api = GISTyc(auth_token=auth_token) 117 | 118 | # Set the directory as a pathlib Path 119 | dir_path = pathlib.Path(directory) 120 | 121 | # Get a list of all gists 122 | gists = gist_api.get_gists() 123 | 124 | # Create a list of all file names (since gists may contain more than 1 file one needs to 125 | # flatten the list) 126 | gist_files_dictfiles = [list(gist_item["files"].keys()) for gist_item in gists] 127 | gist_files = [x for x in gist_files_dictfiles for x in x] 128 | 129 | # Create or update the GIST based on the Python file names within the given directory 130 | # Iterate through all Python files that are being found recursively within the directory. 131 | for python_filepath in dir_path.rglob("*.py"): 132 | 133 | # Echo the currently fetched file 134 | click.echo(python_filepath) 135 | 136 | # Get the filename 137 | python_filename = python_filepath.name 138 | 139 | # If the file name exists in the GIST list, update it, otherwise create one 140 | if python_filename in gist_files: 141 | click.echo("UPDATE") 142 | _ = gist_api.update_gist(file_name=python_filepath) 143 | else: 144 | click.echo("CREATE") 145 | _ = gist_api.create_gist(file_name=python_filepath) 146 | 147 | # Return a simple echo string 148 | click.echo("DONE") 149 | -------------------------------------------------------------------------------- /gistyc/gistyc.py: -------------------------------------------------------------------------------- 1 | """Main GISTys script that contains all required parts of the module.""" 2 | 3 | # Import standard libraries 4 | import json 5 | from pathlib import Path 6 | import typing as t 7 | 8 | import requests 9 | 10 | 11 | class GISTAmbiguityError(Exception): 12 | """Exception for multiple GIST filename updates.""" 13 | 14 | def __init__( 15 | self, gist_ids_list: t.List[str], message: str = "Number of GIST IDs is too ambiguous" 16 | ) -> None: 17 | """Initiate the Exception class. 18 | 19 | Parameters 20 | ---------- 21 | gist_ids_list : list 22 | List of strings with GIST IDs. 23 | message : str, optional 24 | Default exception message. The default is "Number of GIST IDs is too ambiguous". 25 | 26 | Returns 27 | ------- 28 | None. 29 | 30 | """ 31 | # Set the instances; list of GIST IDs and message 32 | self.gist_ids_list = gist_ids_list 33 | self.message = message 34 | 35 | # Super call itself to create message 36 | super().__init__(self.message) 37 | 38 | def __str__(self) -> str: 39 | """Modify the message function. 40 | 41 | Returns 42 | ------- 43 | str 44 | Exception message. 45 | 46 | """ 47 | return f"{self.message}\nIDs: " + ", ".join(self.gist_ids_list) 48 | 49 | 50 | class GISTyc: 51 | """Access the GitHub GIST REST API functions to create, update and delete GISTs. 52 | 53 | The advantage of this class and its corresponding methods is the capability to update 54 | e.g., already existing GISTs (with multiple files) that are e.g., embedded in an online 55 | tutorial. Updateing GISTs automatically is useful if the GISTs corresponding online 56 | documentation is not valid anymore. Updating GISTs manually is tedious and erorr-prone. 57 | However, integrating GISTyc in a CI/CD pipeline (via GitHub Actions) may improve the 58 | maintainability of already exisiting GIST codes. 59 | 60 | """ 61 | 62 | def __init__(self, auth_token: str) -> None: 63 | """Initiate the GISTys class with the GitHub GIST REST API token. 64 | 65 | Parameters 66 | ---------- 67 | auth_token : str 68 | Authentication token of the GitHub GIST REST API. 69 | 70 | Returns 71 | ------- 72 | None. 73 | 74 | """ 75 | # Set the authentication token 76 | self.auth_token = auth_token 77 | 78 | # Set the default header for the REST API 79 | self._headers = {"Authorization": f"token {auth_token}"} 80 | 81 | @staticmethod 82 | def _readnparse_python_file( 83 | file_name: t.Union[Path, str], sep: str = "#%%" 84 | ) -> t.Dict[t.Any, t.Any]: 85 | """Read a Python file and returns a REST API - ready body. 86 | 87 | Parameters 88 | ---------- 89 | file_name : pathlib.Path or str 90 | Absolute or relative path name of the file to read. 91 | sep : str 92 | Python code block separator. Default is '#%%' 93 | 94 | Returns 95 | ------- 96 | data : dict 97 | Body for the REST API call. 98 | 99 | """ 100 | # Set the filename as a Path 101 | file_name = Path(file_name) 102 | 103 | # Open the file and read the content. The entire content is stored in a single string. 104 | with open(file_name, "r") as file_obj: 105 | file_content = file_obj.read() 106 | 107 | # Get the file name without the path 108 | core_file_name = file_name.name 109 | 110 | # Split the python file content at the cell separator "#%%". The resulting list contains 111 | # the code blocks as individual array elements 112 | file_content_list = file_content.split(f"{sep}\n") 113 | 114 | # The python code (blocks) must be put into a dictionary that is later used as a JSON 115 | # in the request REST API body 116 | gist_code_dict = {} 117 | 118 | # Iterate through the list of code blocks 119 | for index, k in enumerate(file_content_list): 120 | 121 | # At the first index, simply add the content with the original file name ... 122 | if index == 0: 123 | gist_code_dict[core_file_name] = {"content": k} 124 | 125 | # ... all other GIST file names get a consecutive, index depending number as a suffix 126 | else: 127 | gist_code_dict[core_file_name.replace(".py", f"_{index}.py")] = {"content": k} 128 | 129 | # Put the content in a dictionary for the REST API 130 | data = { 131 | "public": True, 132 | "files": gist_code_dict, 133 | } 134 | 135 | return data 136 | 137 | def _get_gist_id( 138 | self, file_name: t.Optional[Path] = None, gist_id: t.Optional[str] = None 139 | ) -> str: 140 | """ 141 | Get the GIST ID of a given file name (if applicable). Otherwise return the input GIST ID. 142 | 143 | Parameters 144 | ---------- 145 | file_name : pathlib.Path 146 | File name path. 147 | gist_id : str 148 | GIST ID. 149 | 150 | Raises 151 | ------ 152 | GISTAmbiguityError 153 | Exception raised if a file name has more than 1 GIST IDs. 154 | 155 | Returns 156 | ------- 157 | gist_id_ret : str 158 | file name correpsonding GIST ID (or input GIST ID). 159 | 160 | """ 161 | if isinstance(gist_id, str): 162 | gist_id_ret = gist_id 163 | 164 | # If the gist id is empty, search for it based on the file name. Otherwise, return the 165 | # gist id 166 | elif isinstance(file_name, Path): 167 | 168 | # Set a placeholder for the GIST IDs 169 | gist_ids = [] 170 | 171 | # Get all GISTs 172 | gist_list = self.get_gists() 173 | 174 | # Iterate trough all GISTs 175 | for _gist in gist_list: 176 | 177 | # Check if the file name is present in the GIST 178 | if file_name.name in _gist["files"]: 179 | 180 | # Append the corresponding GIST 181 | gist_ids.append(_gist["id"]) 182 | 183 | # If more than 1 GIST ID is present: raise an exception 184 | if len(gist_ids) > 1: 185 | raise GISTAmbiguityError(gist_ids_list=gist_ids) 186 | 187 | # Take only the first entry as the GIST ID of interest. There should only be 1 ID 188 | # present 189 | gist_id_ret = gist_ids[0] 190 | 191 | return gist_id_ret 192 | 193 | def get_gists(self) -> t.List[t.Dict]: 194 | """Get all GISTs information like e.g., ID, url, meta information, etc. 195 | 196 | Returns 197 | ------- 198 | resp_data : list 199 | List of GISTs. Each GIST is a dictionary with miscellaneous data and meta data. 200 | 201 | """ 202 | # Set the REST API url to obtain the list of GISTs. PAGE will be replace later in a loop. 203 | # Per page: a max. value of 100 GISTs is requested 204 | _query_url = "https://api.github.com/gists?page=PAGE&per_page=100" 205 | 206 | # All GISTs shall be stored in this placeholder array 207 | resp_data = [] 208 | 209 | # To iterate through the GIST pages, set an inital counter that will incrementally increase 210 | cntr = 0 211 | 212 | # While condition: Iterate trough the GIST pages, until the response is empty 213 | _resp_ansr = True 214 | while _resp_ansr: 215 | cntr += 1 216 | 217 | # Get the GISTs for a particular page 218 | resp = requests.get(_query_url.replace("PAGE", str(cntr)), headers=self._headers) 219 | resp_content = resp.json() 220 | 221 | # If the response is not empty, obtain the results and extend the placeholder array 222 | if len(resp_content) > 0: 223 | resp_data.extend(resp_content) 224 | 225 | # Otherwise set the while condition to false 226 | else: 227 | _resp_ansr = False 228 | 229 | return resp_data 230 | 231 | def create_gist(self, file_name: t.Union[Path, str], sep: str = "#%%") -> t.List: 232 | """Create a GISTs from a given file. 233 | 234 | Use "#%%" as a block separator to create sub-GISTs / files from a single input file as 235 | default. Otherwise, please specify! 236 | 237 | Parameters 238 | ---------- 239 | file_name : pathlib.Path or str 240 | Absolute or relative path name of the file to read. 241 | sep : str 242 | Python code block separator. Default is '#%%' 243 | 244 | Returns 245 | ------- 246 | resp_data : dict 247 | GIST REST API response. 248 | 249 | """ 250 | # Set the REST API url for creating a GIST 251 | _query_url = "https://api.github.com/gists" 252 | 253 | # Read the file and return the body for the REST API call 254 | rest_api_data = self._readnparse_python_file(file_name, sep=sep) 255 | 256 | # Call the REST API and obtain the response 257 | resp = requests.post(_query_url, headers=self._headers, data=json.dumps(rest_api_data)) 258 | resp_data = resp.json() 259 | 260 | return resp_data 261 | 262 | def update_gist(self, file_name: t.Union[Path, str], gist_id: t.Optional[str] = None) -> t.List: 263 | """Update a GISTs based on its file name or GIST ID. 264 | 265 | If the file name is provided it is assumed that only one GIST corresponds to the input's 266 | file name. 267 | 268 | Parameters 269 | ---------- 270 | file_name : pathlib.Path or str 271 | Absolute or relative path name of the file to read. 272 | gist_id : str, optional 273 | GIST ID that is needed if the file name appears more than once in the GIST repository. 274 | The default is None. 275 | 276 | Returns 277 | ------- 278 | resp_data : dict 279 | GIST REST API response. 280 | 281 | """ 282 | # Convert the file name to pathlib.Path 283 | file_name = Path(file_name) 284 | 285 | # Get the GIST ID 286 | gist_id = self._get_gist_id(file_name=file_name, gist_id=gist_id) 287 | 288 | # Set the REST API url to update a GIST 289 | _query_url = f"https://api.github.com/gists/{gist_id}" 290 | 291 | # Read and parse the file 292 | rest_api_data = self._readnparse_python_file(file_name) 293 | 294 | # Update the GIST and get the response 295 | resp = requests.patch(_query_url, headers=self._headers, data=json.dumps(rest_api_data)) 296 | resp_data = resp.json() 297 | 298 | return resp_data 299 | 300 | def delete_gist( 301 | self, file_name: t.Optional[t.Union[Path, str]] = None, gist_id: t.Optional[str] = None 302 | ) -> int: 303 | """Delete a GIST based on its GIST ID or file name. One input parameter MUST be provided. 304 | 305 | Parameters 306 | ---------- 307 | file_name : pathlib.Path or str, optional 308 | File name of the corresponding GIST to be deleted. The default is None. 309 | gist_id : str, optional 310 | GIST ID to delete. The default is None 311 | 312 | Returns 313 | ------- 314 | resp_status : int 315 | HTTP response code. A successful deletion shall return 204. 316 | 317 | """ 318 | # If a file name is present, search for the GIST ID of the corresponding GIST 319 | if file_name: 320 | file_name = Path(file_name) 321 | gist_id = self._get_gist_id(file_name=file_name, gist_id=gist_id) 322 | 323 | # Set the REST API url for deleting a GIST 324 | _query_url = f"https://api.github.com/gists/{gist_id}" 325 | 326 | # Delete the GIST and get the status code from the response 327 | resp = requests.delete(_query_url, headers=self._headers) 328 | resp_status = resp.status_code 329 | 330 | return resp_status 331 | -------------------------------------------------------------------------------- /mypy.ini: -------------------------------------------------------------------------------- 1 | [mypy] 2 | warn_unreachable = True 3 | warn_unused_configs = True 4 | disallow_untyped_calls = True 5 | disallow_untyped_defs = True 6 | disallow_incomplete_defs = True 7 | check_untyped_defs = True 8 | disallow_untyped_decorators = True 9 | no_implicit_optional = True 10 | warn_redundant_casts = True 11 | warn_unused_ignores = True 12 | no_implicit_reexport = False 13 | 14 | [mypy-gistyc.tests.*] 15 | ignore_errors = True 16 | 17 | [mypy-gistyc._version] 18 | ignore_errors = True -------------------------------------------------------------------------------- /pylintrc: -------------------------------------------------------------------------------- 1 | [MESSAGES CONTROL] 2 | disable = C0330, R0913, R0401 3 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.black] 2 | line-length = 100 3 | target-version = ['py38'] 4 | include = '\.pyi?$' 5 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # Communication 2 | requests 3 | 4 | # Testing 5 | pytest 6 | pydocstyle 7 | flake8 8 | mypy 9 | pyroma 10 | black 11 | bandit 12 | 13 | # CLI 14 | click 15 | 16 | # Git Pre Commit 17 | pre-commit 18 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_wheel] 2 | # This flag says that the code is written to work on both Python 2 and Python 3 | # 3. If at all possible, it is good practice to do this. If you cannot, you 4 | # will need to generate wheels for each Python version that you support. 5 | universal=1 6 | 7 | [metadata] 8 | # See https://setuptools.readthedocs.io/en/latest/setuptools.html#configuring-setup-using-setup-cfg-files 9 | name = gistyc 10 | version = attr: gistyc.__version__ 11 | url = https://github.com/ThomasAlbin/gistyc 12 | description = A CLI for creating, updating and deleting GitHub GISTs 13 | long_description = file: README.md 14 | long_description_content_type=text/markdown 15 | author = attr: gistyc.__author__ 16 | project_urls = 17 | Source = https://github.com/ThomasAlbin/gistyc 18 | Tracker = https://github.com/ThomasAlbin/gistyc/issues 19 | license= MIT License 20 | keywords = github, gist 21 | 22 | # See https://pypi.python.org/pypi?%3Aaction=list_classifiers 23 | classifiers = 24 | Development Status :: 4 - Beta 25 | Intended Audience :: Developers 26 | Intended Audience :: End Users/Desktop 27 | Topic :: Software Development :: Build Tools 28 | License :: OSI Approved :: MIT License 29 | Programming Language :: Python :: 3 30 | Programming Language :: Python :: 3.7 31 | Programming Language :: Python :: 3.8 32 | Programming Language :: Python :: 3.9 33 | 34 | platforms = unix, linux, osx, win32 35 | 36 | [options] 37 | zip_safe = True 38 | include_package_data = True 39 | packages = find: 40 | setup_requires = 41 | wheel>=0.29.0 42 | setuptools>=30.3 43 | install_requires = 44 | certifi 45 | click 46 | requests 47 | 48 | python_requires = >=3.8 49 | 50 | # [options.extras_require] 51 | # some_name = 52 | # some_package 53 | 54 | [options.entry_points] 55 | console_scripts = 56 | gistyc = gistyc.cli:run 57 | gistyc_dir = gistyc.cli:dir_run 58 | 59 | [options.packages.find] 60 | exclude = 61 | contrib 62 | docs 63 | tests 64 | examples 65 | 66 | [flake8] 67 | max-line-length = 100 68 | ignore = F401 -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # Always prefer setuptools over distutils from setuptools import setup setup(package_data={"gistyc": ["py.typed"]}) -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | from . import test_cli 2 | from . import test_gistyc 3 | 4 | from . import _resources -------------------------------------------------------------------------------- /tests/_resources/create/sample.py: -------------------------------------------------------------------------------- 1 | """ 2 | A sample example for gistyc 3 | 4 | """ 5 | 6 | # Import module 7 | import time 8 | 9 | #%% 10 | # Print the time 11 | print(time.time()) 12 | 13 | #%% 14 | # Replace this random comment block with a hash or current timestamp: 15 | # TBD 16 | -------------------------------------------------------------------------------- /tests/_resources/create_dir/sample1/sample1.py: -------------------------------------------------------------------------------- 1 | """ 2 | A sample example for gistyc 3 | 4 | """ 5 | 6 | # Import module 7 | import time 8 | 9 | #%% 10 | # Print the time 11 | print(time.time()) 12 | 13 | #%% 14 | # Replace this random comment block with a hash or current timestamp: 15 | # TBD 16 | -------------------------------------------------------------------------------- /tests/_resources/update/sample.py: -------------------------------------------------------------------------------- 1 | """ 2 | An updated sample example for gistyc 3 | 4 | """ 5 | 6 | # Import module 7 | import time 8 | 9 | #%% 10 | # Print the time with no changes! 11 | print(time.time()) 12 | 13 | #%% 14 | # Replace this random comment block with a hash or current timestamp: 15 | HASH_VALUE = 'Not a Hash at all!' 16 | -------------------------------------------------------------------------------- /tests/_resources/update_dir/sample1/sample1.py: -------------------------------------------------------------------------------- 1 | """ 2 | An updated sample example for gistyc 3 | 4 | """ 5 | 6 | # Import module 7 | import time 8 | 9 | #%% 10 | # Print the time with no changes! 11 | print(time.time()) 12 | 13 | #%% 14 | # Replace this random comment block with a hash or current timestamp: 15 | HASH_VALUE = "Not a Hash at all!" 16 | -------------------------------------------------------------------------------- /tests/_resources/update_dir/sample2.py: -------------------------------------------------------------------------------- 1 | """ 2 | A new sample example for gistyc 3 | 4 | """ 5 | 6 | # Import module 7 | import time 8 | 9 | #%% 10 | # Print the time in print-way... 11 | print(time.time()) 12 | 13 | #%% 14 | # A useless sample value 15 | TEST = 1 16 | -------------------------------------------------------------------------------- /tests/test_cli.py: -------------------------------------------------------------------------------- 1 | """Testing routine for the GISTyc CLI""" 2 | 3 | # Import standard libraries 4 | import ast 5 | import os 6 | import pathlib 7 | import time 8 | 9 | # Import installed libraries 10 | from click.testing import CliRunner 11 | 12 | # Import GISTyc 13 | import gistyc 14 | 15 | # First, set the file name paths to the sample.py for creating and update the GISTs. 16 | CORE_PATH = os.path.dirname(os.path.abspath(__file__)) 17 | 18 | CSAMPLE_FILE_NAME = "sample.py" 19 | CSAMPLE_FILE_PATH = os.path.join(CORE_PATH, "_resources/create", CSAMPLE_FILE_NAME) 20 | 21 | USAMPLE_FILE_NAME = "sample.py" 22 | USAMPLE_FILE_PATH = os.path.join(CORE_PATH, "_resources/update", USAMPLE_FILE_NAME) 23 | 24 | CDIR = os.path.join(CORE_PATH, "_resources/create_dir") 25 | UDIR = os.path.join(CORE_PATH, "_resources/update_dir") 26 | 27 | # Get the GIST authentication token from the system environment 28 | AUTH_TOKEN = os.environ["GIST_TOKEN"] 29 | 30 | 31 | def test_cli_create_n_delete_id(): 32 | """Testing the creation and deletion of a GIST, based on the ID. 33 | 34 | Returns 35 | ------- 36 | None. 37 | 38 | """ 39 | 40 | # Set up the CLI Runner and execute the create command 41 | runner = CliRunner() 42 | cresult = runner.invoke( 43 | gistyc.cli.run, ["--create", "--auth-token", AUTH_TOKEN, "--file-name", CSAMPLE_FILE_PATH] 44 | ) 45 | 46 | # Check if the CLI ran error free 47 | assert cresult.exit_code == 0 48 | 49 | # Convert the response to JSON by identifying the format automatically 50 | cresult_data = ast.literal_eval(cresult.output) 51 | 52 | # Check if the file name is in the GIST REST API response 53 | assert CSAMPLE_FILE_NAME in cresult_data["files"].keys() 54 | 55 | # Set up the CLI Runner and execute the delete command 56 | runner = CliRunner() 57 | dresult = runner.invoke( 58 | gistyc.cli.run, ["--delete", "--auth-token", AUTH_TOKEN, "--gist-id", cresult_data["id"]] 59 | ) 60 | 61 | # Check if the CLI ran error free 62 | assert dresult.exit_code == 0 63 | 64 | # Check the HTTP status code 65 | assert "204" in dresult.output 66 | 67 | 68 | def test_cli_create_n_delete(): 69 | """Testing the creation and deletion of a GIST, based on the file name. 70 | 71 | Returns 72 | ------- 73 | None. 74 | 75 | """ 76 | 77 | # Set up the CLI Runner and execute the create command 78 | runner = CliRunner() 79 | cresult = runner.invoke( 80 | gistyc.cli.run, ["--create", "--auth-token", AUTH_TOKEN, "--file-name", CSAMPLE_FILE_PATH] 81 | ) 82 | 83 | # Check if the CLI ran error free 84 | assert cresult.exit_code == 0 85 | 86 | # Convert the response to JSON by identifying the format automatically 87 | cresult_data = ast.literal_eval(cresult.output) 88 | 89 | # Check if the file name is in the GIST REST API response 90 | assert CSAMPLE_FILE_NAME in cresult_data["files"].keys() 91 | 92 | # Set up the CLI Runner and execute the delete command 93 | runner = CliRunner() 94 | dresult = runner.invoke( 95 | gistyc.cli.run, ["--delete", "--auth-token", AUTH_TOKEN, "--file-name", CSAMPLE_FILE_PATH] 96 | ) 97 | 98 | # Check if the CLI ran error free 99 | assert dresult.exit_code == 0 100 | 101 | # Check the HTTP status code 102 | assert "204" in dresult.output 103 | 104 | 105 | def test_cli_create_n_update_file(): 106 | """Testing the creation and update of a GIST (based on the pure file name). 107 | 108 | Returns 109 | ------- 110 | None. 111 | 112 | """ 113 | 114 | # Set up the CLI Runner and execute the create command 115 | runner = CliRunner() 116 | cresult = runner.invoke( 117 | gistyc.cli.run, ["--create", "--auth-token", AUTH_TOKEN, "--file-name", CSAMPLE_FILE_PATH] 118 | ) 119 | 120 | # Check if the CLI ran error free 121 | assert cresult.exit_code == 0 122 | 123 | # Convert the response to JSON by identifying the format automatically 124 | cresult_data = ast.literal_eval(cresult.output) 125 | 126 | # Check if the file name is in the GIST REST API response 127 | assert CSAMPLE_FILE_NAME in cresult_data["files"].keys() 128 | 129 | # Wait for a second, to clearly set a difference between the creation and update datetime 130 | time.sleep(1) 131 | 132 | # Set up the CLI Runner and execute the update command 133 | runner = CliRunner() 134 | uresult = runner.invoke( 135 | gistyc.cli.run, ["--update", "--auth-token", AUTH_TOKEN, "--file-name", USAMPLE_FILE_PATH] 136 | ) 137 | 138 | # Check if the CLI ran error free 139 | assert uresult.exit_code == 0 140 | 141 | # Convert the response to JSON by identifying the format automatically 142 | uresult_data = ast.literal_eval(uresult.output) 143 | 144 | # Check if the create date time is older than the update datetime 145 | assert uresult_data["updated_at"] > uresult_data["created_at"] 146 | 147 | # Set up the CLI Runner and execute the delete command 148 | dresult = runner.invoke( 149 | gistyc.cli.run, ["--delete", "--auth-token", AUTH_TOKEN, "--gist-id", uresult_data["id"]] 150 | ) 151 | # Check if the CLI ran error free 152 | assert dresult.exit_code == 0 153 | 154 | # Check the HTTP status code 155 | assert "204" in dresult.output 156 | 157 | 158 | def test_cli_create_n_update_id(): 159 | """Testing the creation and update of a GIST (based on the GIST ID). 160 | 161 | Returns 162 | ------- 163 | None. 164 | 165 | """ 166 | 167 | # Set up the CLI Runner and execute the create command 168 | runner = CliRunner() 169 | cresult = runner.invoke( 170 | gistyc.cli.run, ["--create", "--auth-token", AUTH_TOKEN, "--file-name", CSAMPLE_FILE_PATH] 171 | ) 172 | # Check if the CLI ran error free 173 | assert cresult.exit_code == 0 174 | 175 | # Convert the response to JSON by identifying the format automatically 176 | cresult_data = ast.literal_eval(cresult.output) 177 | 178 | # Check if the file name is in the GIST REST API response 179 | assert CSAMPLE_FILE_NAME in cresult_data["files"].keys() 180 | 181 | # Wait for a second, to clearly set a difference between the creation and update datetime 182 | time.sleep(1) 183 | 184 | # Set up the CLI Runner and execute the update command 185 | runner = CliRunner() 186 | uresult = runner.invoke( 187 | gistyc.cli.run, 188 | [ 189 | "--update", 190 | "--auth-token", 191 | AUTH_TOKEN, 192 | "--file-name", 193 | USAMPLE_FILE_PATH, 194 | "--gist-id", 195 | cresult_data["id"], 196 | ], 197 | ) 198 | 199 | # Check if the CLI ran error free 200 | assert uresult.exit_code == 0 201 | 202 | # Convert the response to JSON by identifying the format automatically 203 | uresult_data = ast.literal_eval(uresult.output) 204 | 205 | # Check if the create date time is older than the update datetime 206 | assert uresult_data["updated_at"] > uresult_data["created_at"] 207 | 208 | # Set up the CLI Runner and execute the delete command 209 | dresult = runner.invoke( 210 | gistyc.cli.run, ["--delete", "--auth-token", AUTH_TOKEN, "--gist-id", uresult_data["id"]] 211 | ) 212 | # Check if the CLI ran error free 213 | assert dresult.exit_code == 0 214 | 215 | # Check the HTTP status code 216 | assert "204" in dresult.output 217 | 218 | 219 | def test_cli_dir_run(): 220 | """Testing the creation and update of a GIST based on a given directory. 221 | 222 | Returns 223 | ------- 224 | None. 225 | 226 | """ 227 | 228 | # Set up the CLI Runner and execute the command 229 | runner = CliRunner() 230 | _ = runner.invoke(gistyc.cli.dir_run, ["--directory", CDIR, "--auth-token", AUTH_TOKEN]) 231 | 232 | # Sleep a second 233 | time.sleep(1) 234 | 235 | # Execute the command with the update directory 236 | _ = runner.invoke(gistyc.cli.dir_run, ["--directory", UDIR, "--auth-token", AUTH_TOKEN]) 237 | 238 | # Sleep a second 239 | time.sleep(1) 240 | 241 | # Now we need to clean up the GISTs (deleting everything) 242 | # Iterate through all directory Python files 243 | for python_filepath in pathlib.Path(UDIR).rglob("*.py"): 244 | 245 | # Get the filename 246 | python_filename = python_filepath.name 247 | 248 | # Execute the single file CLI command to delete the GIST 249 | runner.invoke( 250 | gistyc.cli.run, ["--delete", "--auth-token", AUTH_TOKEN, "--file-name", python_filename] 251 | ) 252 | -------------------------------------------------------------------------------- /tests/test_gistyc.py: -------------------------------------------------------------------------------- 1 | """Testing suite for the gistyc functionalities.""" 2 | 3 | # Import standard libraries 4 | import os 5 | import time 6 | 7 | # Import installed libraries 8 | import pytest 9 | 10 | # Import GISTyc 11 | import gistyc 12 | 13 | # First, set the file name paths to the sample.py for creating and update the GISTs. 14 | CORE_PATH = os.path.dirname(os.path.abspath(__file__)) 15 | 16 | CSAMPLE_FILE_NAME = 'sample.py' 17 | CSAMPLE_FILE_PATH = os.path.join(CORE_PATH, '_resources/create', CSAMPLE_FILE_NAME) 18 | 19 | USAMPLE_FILE_NAME = 'sample.py' 20 | USAMPLE_FILE_PATH = os.path.join(CORE_PATH, '_resources/update', USAMPLE_FILE_NAME) 21 | 22 | # Get the GIST authentication token from the system environment 23 | AUTH_TOKEN = os.environ['GIST_TOKEN'] 24 | 25 | 26 | def test_gistyc_create_n_delete_id(): 27 | """ 28 | Testing the creation and deletion of a GIST by a GIST ID. 29 | 30 | Returns 31 | ------- 32 | None. 33 | 34 | """ 35 | 36 | # Initiate the GISTyc class with the auth token 37 | gist_api = gistyc.GISTyc(auth_token=AUTH_TOKEN) 38 | 39 | # Create a GIST with the sample file 40 | response_data = gist_api.create_gist(file_name=USAMPLE_FILE_PATH) 41 | 42 | # Check whether the creation was successful by considering the response from GitHub 43 | assert 'sample.py' in response_data['files'].keys() 44 | 45 | # Delete the GIST, based on the reponse's ID and check for the status code 204 46 | response_data = gist_api.delete_gist(gist_id=response_data['id']) 47 | assert response_data == 204 48 | 49 | 50 | def test_gistyc_create_n_delete_filename(): 51 | """ 52 | Testing the creation and deletion of a GIST by the file name. 53 | 54 | Returns 55 | ------- 56 | None. 57 | 58 | """ 59 | 60 | # Initiate the GISTyc class with the auth token 61 | gist_api = gistyc.GISTyc(auth_token=AUTH_TOKEN) 62 | 63 | # Create a GIST with the sample file 64 | response_data = gist_api.create_gist(file_name=USAMPLE_FILE_PATH) 65 | 66 | # Check whether the creation was successful by considering the response from GitHub 67 | assert 'sample.py' in response_data['files'].keys() 68 | 69 | # Delete the GIST, based on the reponse's ID and check for the status code 204 70 | response_data = gist_api.delete_gist(file_name='sample.py') 71 | assert response_data == 204 72 | 73 | 74 | def test_gistyc_create_n_update(): 75 | """ 76 | Testing the creation and update of a GIST. Afterwards the GIST is deleted. The update is purely 77 | based on the test file name. 78 | 79 | Returns 80 | ------- 81 | None. 82 | 83 | """ 84 | 85 | # Initiate the GISTyc class with the auth token 86 | gist_api = gistyc.GISTyc(auth_token=AUTH_TOKEN) 87 | 88 | # Create a GIST 89 | _ = gist_api.create_gist(file_name=USAMPLE_FILE_PATH) 90 | 91 | # Wait a second 92 | time.sleep(1) 93 | 94 | # Update the GIST with the updated sample file (update is based on the file's name) 95 | response_update_data = gist_api.update_gist(file_name=USAMPLE_FILE_PATH) 96 | 97 | # Check whether the update date time is larger, respectively "more recent" than the creation 98 | # date time 99 | assert response_update_data['updated_at'] > response_update_data['created_at'] 100 | 101 | # Delete the GIST, based on the reponse's ID and check for the status code 204 102 | response_data = gist_api.delete_gist(gist_id=response_update_data['id']) 103 | assert response_data == 204 104 | 105 | 106 | def test_gistyc_create_n_update_id(): 107 | """ 108 | Testing the creation, update and deletion of a GIST. The update is based on the GIST ID. 109 | 110 | Returns 111 | ------- 112 | None. 113 | 114 | """ 115 | 116 | # Initiate the GISTyc class with the auth token 117 | gist_api = gistyc.GISTyc(auth_token=AUTH_TOKEN) 118 | 119 | # Create the GIST 120 | response_create_data = gist_api.create_gist(file_name=CSAMPLE_FILE_PATH) 121 | 122 | # Wait for a second 123 | time.sleep(1) 124 | 125 | # Update the GIST based on the GISTs ID 126 | response_update_data = gist_api.update_gist(file_name=USAMPLE_FILE_PATH, 127 | gist_id=response_create_data['id']) 128 | 129 | # Check whether the update date time is larger, respectively "more recent" than the creation 130 | # date time 131 | assert response_update_data['updated_at'] > response_update_data['created_at'] 132 | 133 | # Delete the GIST, based on the reponse's ID and check for the status code 204 134 | response_data = gist_api.delete_gist(gist_id=response_update_data['id']) 135 | assert response_data == 204 136 | 137 | 138 | @pytest.mark.xfail(raises=gistyc.GISTAmbiguityError) 139 | def test_gistyc_ambiguous(): 140 | """ 141 | Testing the custom exception GISTAmbiguityError. If only a filename is provided, but to GISTs 142 | are present with the same file name an update cannot be performed. 143 | 144 | Returns 145 | ------- 146 | None. 147 | 148 | """ 149 | 150 | # Initiate the GISTyc class with the auth token 151 | gist_api = gistyc.GISTyc(auth_token=AUTH_TOKEN) 152 | 153 | # Create a GIST with the creation sample file 154 | _ = gist_api.create_gist(file_name=CSAMPLE_FILE_PATH) 155 | 156 | # Create a second GIST with the same creation sample file 157 | _ = gist_api.create_gist(file_name=CSAMPLE_FILE_PATH) 158 | 159 | # Now, the update should not succeed, since the update is not based on a GIST ID, but a file 160 | # name. Since two GISTs have the same name (but different IDs) the test should fail. 161 | _ = gist_api.update_gist(file_name=USAMPLE_FILE_PATH) 162 | 163 | 164 | def test_gistyc_clean_ambiguous(): 165 | """ 166 | Testing the method that gets all GISTs from all pages. Afterwards, all files are deleted that 167 | correspond to the example file. 168 | 169 | Returns 170 | ------- 171 | None. 172 | 173 | """ 174 | 175 | # Initiate the GISTyc class with the auth token 176 | gist_api = gistyc.GISTyc(auth_token=AUTH_TOKEN) 177 | 178 | # Get a list of all GISTs 179 | response_gists_list = gist_api.get_gists() 180 | 181 | # Iterate through all GISTs 182 | for k in response_gists_list: 183 | 184 | # If the sample file name is present in a GIST, get the ID and delete the GIST. Check for 185 | # the status code 204 186 | if CSAMPLE_FILE_NAME in k['files']: 187 | response_data = gist_api.delete_gist(gist_id=k['id']) 188 | assert response_data == 204 189 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | minversion = 3.4.0 3 | envlist = black,py39,flake8,pylint,mypy,pydocstyle,bandit,build 4 | skip_missing_interpreters = true 5 | 6 | [testenv:black] 7 | basepython = python3 8 | deps = 9 | black 10 | commands = 11 | # Use this locally and then use git status to see the difference. 12 | black --line-length=100 gistyc 13 | 14 | [testenv] 15 | passenv = GIST_TOKEN 16 | deps = 17 | pytest 18 | -rrequirements.txt 19 | commands = 20 | pytest -vv --color=yes 21 | 22 | [testenv:flake8] 23 | deps = 24 | flake8 25 | commands = 26 | flake8 gistyc 27 | 28 | [testenv:pylint] 29 | skip_install = true 30 | deps = 31 | pylint 32 | -rrequirements.txt 33 | commands = 34 | pylint --rcfile=pylintrc --output-format=colorized gistyc 35 | 36 | [testenv:mypy] 37 | basepython = python3 38 | deps = 39 | mypy 40 | -rrequirements.txt 41 | commands = 42 | mypy --config mypy.ini gistyc 43 | 44 | [testenv:pydocstyle] 45 | deps = 46 | pydocstyle 47 | commands = 48 | pydocstyle gistyc 49 | 50 | [testenv:bandit] 51 | skip_install = true 52 | deps = 53 | bandit 54 | commands = 55 | bandit gistyc 56 | 57 | #[testenv:pyroma] 58 | #skip_install = true 59 | #deps = 60 | # pyroma 61 | #commands = 62 | # pyroma . 63 | 64 | [testenv:build] 65 | skip_install = true 66 | deps = 67 | wheel 68 | setuptools 69 | commands = 70 | python setup.py bdist_wheel 71 | --------------------------------------------------------------------------------