├── .github └── workflows │ ├── pythonpackage.yml │ └── pythonpublish.yml ├── .gitignore ├── GNUv3.txt ├── LICENSE ├── Makefile ├── README.md ├── compute_sha.py ├── git-remote-rclone ├── pyproject.toml ├── setup.cfg ├── setup.py └── test.sh /.github/workflows/pythonpackage.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 | fail-fast: false 18 | matrix: 19 | python-version: ["3.9", "3.10", "3.11"] 20 | 21 | steps: 22 | - uses: actions/checkout@v3 23 | - name: Set up Python ${{ matrix.python-version }} 24 | uses: actions/setup-python@v3 25 | with: 26 | python-version: ${{ matrix.python-version }} 27 | - name: Install dependencies 28 | run: | 29 | python -m pip install --upgrade pip 30 | python -m pip install flake8 pytest 31 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 32 | # - name: Lint with flake8 33 | # run: | 34 | # stop the build if there are Python syntax errors or undefined names 35 | # flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 36 | # flake8 . --count --max-complexity=14 --max-line-length=127 --show-source --statistics 37 | # - name: Test with pytest 38 | # run: | 39 | # pytest 40 | -------------------------------------------------------------------------------- /.github/workflows/pythonpublish.yml: -------------------------------------------------------------------------------- 1 | # This workflows 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@v1 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_PASSWORD }} 29 | run: | 30 | python setup.py sdist bdist_wheel 31 | twine upload dist/* 32 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | dist 3 | *.egg-info 4 | *.swp 5 | **/__pycache__ 6 | pip-wheel-metadata/ 7 | test 8 | -------------------------------------------------------------------------------- /GNUv3.txt: -------------------------------------------------------------------------------- 1 | Preamble 2 | The GNU General Public License is a free, copyleft license for software and other kinds of works. 3 | 4 | The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. 5 | 6 | When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. 7 | 8 | To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. 9 | 10 | For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. 11 | 12 | Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. 13 | 14 | For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. 15 | 16 | Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. 17 | 18 | Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. 19 | 20 | The precise terms and conditions for copying, distribution and modification follow. 21 | 22 | TERMS AND CONDITIONS 23 | 0. Definitions. 24 | “This License” refers to version 3 of the GNU General Public License. 25 | 26 | “Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. 27 | 28 | “The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. 29 | 30 | To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. 31 | 32 | A “covered work” means either the unmodified Program or a work based on the Program. 33 | 34 | To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. 35 | 36 | To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. 37 | 38 | An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 39 | 40 | 1. Source Code. 41 | The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. 42 | 43 | A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. 44 | 45 | The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. 46 | 47 | The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. 48 | 49 | The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. 50 | 51 | The Corresponding Source for a work in source code form is that same work. 52 | 53 | 2. Basic Permissions. 54 | All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. 55 | 56 | You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. 57 | 58 | Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 59 | 60 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 61 | No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. 62 | 63 | When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 64 | 65 | 4. Conveying Verbatim Copies. 66 | You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. 67 | 68 | You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 69 | 70 | 5. Conveying Modified Source Versions. 71 | You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: 72 | 73 | a) The work must carry prominent notices stating that you modified it, and giving a relevant date. 74 | b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. 75 | c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. 76 | d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. 77 | A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 78 | 79 | 6. Conveying Non-Source Forms. 80 | You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: 81 | 82 | a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. 83 | b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. 84 | c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. 85 | d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. 86 | e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. 87 | A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. 88 | 89 | A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. 90 | 91 | “Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. 92 | 93 | If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). 94 | 95 | The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. 96 | 97 | Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 98 | 99 | 7. Additional Terms. 100 | “Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. 101 | 102 | When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. 103 | 104 | Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: 105 | 106 | a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or 107 | b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or 108 | c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or 109 | d) Limiting the use for publicity purposes of names of licensors or authors of the material; or 110 | e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or 111 | f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. 112 | All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. 113 | 114 | If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. 115 | 116 | Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 117 | 118 | 8. Termination. 119 | You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). 120 | 121 | However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. 122 | 123 | Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. 124 | 125 | Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 126 | 127 | 9. Acceptance Not Required for Having Copies. 128 | You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 129 | 130 | 10. Automatic Licensing of Downstream Recipients. 131 | Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. 132 | 133 | An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. 134 | 135 | You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 136 | 137 | 11. Patents. 138 | A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. 139 | 140 | A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. 141 | 142 | Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. 143 | 144 | In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. 145 | 146 | If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. 147 | 148 | If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. 149 | 150 | A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. 151 | 152 | Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 153 | 154 | 12. No Surrender of Others' Freedom. 155 | If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 156 | 157 | 13. Use with the GNU Affero General Public License. 158 | Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 159 | 160 | 14. Revised Versions of this License. 161 | The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. 162 | 163 | Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. 164 | 165 | If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. 166 | 167 | Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 168 | 169 | 15. Disclaimer of Warranty. 170 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 171 | 172 | 16. Limitation of Liability. 173 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 174 | 175 | 17. Interpretation of Sections 15 and 16. 176 | If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. 177 | 178 | END OF TERMS AND CONDITIONS 179 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2007 Red S 3 | * 4 | * This file is free software: you may copy, redistribute and/or modify it 5 | * under the terms of the GNU General Public License as published by the 6 | * Free Software Foundation, either version 3 of the License, or (at your 7 | * option) any later version. 8 | * 9 | * This file is distributed in the hope that it will be useful, but 10 | * WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | * General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with this program. If not, see 16 | * https://www.gnu.org/licenses/gpl-3.0.en.html#license-text 17 | * 18 | * This file incorporates work covered by the following copyright and 19 | * permission notice: 20 | * 21 | * Copyright (c) 2020-2023 Michael Hanke 22 | * 23 | * Permission is hereby granted, free of charge, to any person obtaining a copy 24 | * of this software and associated documentation files (the "Software"), to deal 25 | * in the Software without restriction, including without limitation the rights 26 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 27 | * copies of the Software, and to permit persons to whom the Software is 28 | * furnished to do so, subject to the following conditions: 29 | * 30 | * The above copyright notice and this permission notice shall be included in 31 | * all copies or substantial portions of the Software. 32 | * 33 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 34 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 35 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 36 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 37 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 38 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 39 | * THE SOFTWARE. 40 | */ 41 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | PYTHON ?= python3 2 | 3 | clean: 4 | $(PYTHON) setup.py clean 5 | -find . -name '*.pyc' -delete 6 | -find . -name '__pycache__' -type d -delete 7 | 8 | release-pypi: clean 9 | # better safe than sorry 10 | test ! -e dist 11 | python setup.py sdist 12 | python setup.py bdist_wheel --universal 13 | twine upload dist/* 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Git remote helper for rclone-supported services 2 | 3 | _**TL;DR: Turn most cloud storage services (eg: Dropbox) into remote git services, with 4 | optional encryption.**_ 5 | 6 | This is a [Git remote helper](https://git-scm.com/docs/git-remote-helpers) for 7 | backends supported by [rclone](https://rclone.org). 8 | 9 | This enables using `git pull` or `git push` with a remote git repository stored on 10 | popular cloud services with no native Git support. Optionally, it enables using 11 | zero-knowledge encryption via [rclone's crypt](https://rclone.org/crypt/). 12 | 13 | ## Installation and Usage 14 | 15 | - Visit the [rclone website](https://rclone.org) and follow the instructions for 16 | installation of `rclone`, and configuration of access to the desired service(s). 17 | 18 | - Install this package: 19 | ``` 20 | pip3 install git-remote-rclone-reds 21 | ``` 22 | or place the `git-remote-rclone` executable provided here into the system path, such 23 | that Git can find it. 24 | 25 | Now it is possible to use URLs like 26 | `rclone:///` as push and pull URLs for Git. 27 | 28 | For example, if access to a DropBox account has been configured as an rclone-remote 29 | named `mydropbox`, the URL `rclone://mydropbox/myrepository` identifies a remote 30 | in a directory `myrepository/` under this DropBox account. 31 | 32 | ## Configuration 33 | 34 | `git-remote-rclone` can be configured to get git to prune the repo aggressively before 35 | uploading via rclone. This comes in handy to minimize the uploaded file size, at the 36 | cost of the time taken to prune. This can be a good tradeoff for low-bandwidth 37 | situations. To configure it, run this in your git repo: 38 | 39 | ``` 40 | git config --add git-remote-rclone.pruneaggressively "true" 41 | ``` 42 | `git-gc` is run only on the repo that is uploaded. The local repo is left untouched. 43 | 44 | ## Example 45 | ``` 46 | mkdir testrepo; cd testrepo 47 | git init . 48 | echo "Hello world." > xyz 49 | git add xyz 50 | git commit -m "Initial commit." 51 | rclone mkdir mydropbox:test # Assuming 'mydropbox' has been configured 52 | git remote add rclone://mydropbox/test 53 | git remote add origin rclone://mydropbox/test 54 | git push origin -u main 55 | ``` 56 | 57 | ## Technical details 58 | 59 | At the remote end, `git-remote-rclone` maintains a directory with two files: 60 | 61 | - `refs`: a small text file listing the refs provided by the remote 62 | - `repo-.tar.gz`: an archive of a bare Git repository 63 | 64 | When interacting with a remote, `git-remote-rclone` obtains and extracts a copy 65 | of the remote repository archive (placed at `.git/rclone/` in the 66 | local Git repository). All Git operations are performed locally. Whenever the 67 | state of the mirror repository has changed, it is compacted to minimize transfer 68 | size and uploaded to the remote storage service. Likewise, the remote storage 69 | service is checked for updates before the local mirror repository is updated. 70 | 71 | `git-remote-rclone` aims to minimize API usage of remote storage services. Per 72 | invocation, it only queries for the filenames in the remote repository archive, 73 | downloads two files (if needed), and uploads two files (if needed, and on push only). 74 | 75 | ### Tested with 76 | 77 | - `rclone` 1.63.1 78 | - Google Drive 79 | - Onedrive 80 | - DropBox 81 | - [Rclone crypt](https://rclone.org/crypt/) 82 | 83 | ### Repo migration 84 | 85 | `git-remote-rclone-reds` is *not* backward compatible with (cannot directly read/write) existing remotes created by [datalad/git-remote-rclone](https://github.com/datalad/git-remote-rclone). Migrating a repo is required. 86 | 87 | However, migrating a repo back and forth between `git-remote-rclone` and 88 | `git-remote-rclone-reds` is very easy. A small one-time change is required. Instead of 89 | `repo.7z`, `git-remote-rclone-reds` uses `repo-SHA.tar.gz`. So in theory, you could 90 | unpack, repack, and rename, using the 91 | [`compute_sha.py`](https://github.com/redstreet/git-remote-rclone/blob/main/compute_sha.py) 92 | that ships with `git-remote-rclone-reds`, and that works fine. 93 | 94 | But there's a much easier way, which is to get git to do all the work: 95 | 96 | ``` 97 | # Upgrade to git-remote-rclone-reds 98 | pip3 uninstall git-remote-rclone 99 | pip3 install git-remote-rclone-reds 100 | 101 | # Upgrade the repo. 102 | git remote -v 103 | origin rclone://cloud/old (fetch) 104 | origin rclone://cloud/old (push) 105 | 106 | git remote add new rclone://cloud/new 107 | git push -u new main 108 | 109 | # You can now verify rclone://cloud/new looks right, and then rename it to `origin` 110 | ``` 111 | This works for migrations in the opposite direction too. 112 | 113 | ## Acknowledgements 114 | 115 | This work is based on [datalad/git-remote-rclone](https://github.com/datalad/git-remote-rclone). This work changes the 116 | design for compatibility with rclone backends like crypt that do not support file 117 | [hashes](https://github.com/datalad/git-remote-rclone/issues/6). 118 | -------------------------------------------------------------------------------- /compute_sha.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import hashlib 4 | from pathlib import Path 5 | 6 | # compute sha for repo.7z file in current directory 7 | # use this if you want to convert a file from a previous verison of git-remote-rclone to the 8 | # current version. Compute its hash with this script, and then rename it like so: 9 | # 10 | # mv repo.7z repo-.7z 11 | # 12 | # Then, uncompress repo-.7z and recompress with tar, so you have repo-.tar.gz: 13 | # 7z e repo-.7z 14 | # tar -czf repo-.tar.gz repo 15 | 16 | repo_file = Path("repo.7z") 17 | repo_hash = hashlib.sha1(repo_file.read_bytes()).hexdigest() 18 | print(repo_hash) 19 | -------------------------------------------------------------------------------- /git-remote-rclone: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import json 4 | import os 5 | from pathlib import Path 6 | from shutil import rmtree 7 | import subprocess 8 | import sys 9 | import hashlib 10 | from urllib.parse import urlparse 11 | import tarfile 12 | import inspect 13 | 14 | 15 | # .tar.gz based compression 16 | def uncompress(repo_archive, cwd): 17 | with tarfile.open(str(repo_archive), 'r:gz') as tar: 18 | tar.extractall(cwd) 19 | 20 | def compress(repo_file, dir_to_compress, cwd): 21 | """compress dir_to_compress into repo_file.tar.gz""" 22 | with tarfile.open(str(repo_file), 'w:gz') as tar: 23 | tar.add(str(cwd / dir_to_compress), arcname=dir_to_compress) 24 | 25 | class RCloneRemote(object): 26 | """git-remote-helper implementation to interface rclone remotes.""" 27 | def __init__(self, 28 | gitdir: str, 29 | remote: str, 30 | url: str, 31 | instream=sys.stdin, 32 | outstream=sys.stdout, 33 | errstream=sys.stderr): 34 | """ 35 | gitdir: Path to the GITDIR of the repository to operate on (provided by Git). 36 | remote: Remote label to use (provided by Git). 37 | url: rclone: //-type URL of the remote (provided by Git). 38 | instream: Stream to read communication from Git from. 39 | outstream: Stream to communicate outcomes to Git. 40 | errstream: Stream for logging. 41 | """ 42 | self.parsed_url = urlparse(url) 43 | self.remote = remote 44 | # internal logic relies on workdir to be an absolute path 45 | self.gitdir = gitdir 46 | self.workdir = Path(gitdir, 'rclone', remote).resolve() 47 | self.repodir = self.workdir / 'repo' 48 | self.marks_git = self.workdir / "git.marks" 49 | self.marks_rclone = self.workdir / "rclone.marks" 50 | self.refspec = "refs/heads/*:refs/rclone/{}/*".format(remote) 51 | self.instream = instream 52 | self.outstream = outstream 53 | self.errstream = errstream 54 | 55 | # TODO delay 56 | self.workdir.mkdir(parents=True, exist_ok=True) 57 | self.marks_git.touch() 58 | self.marks_rclone.touch() 59 | 60 | def PrintFrame(self): 61 | """Helps debug""" 62 | callerframerecord = inspect.stack()[1] # 0 represents this line 63 | # 1 represents line at caller 64 | frame = callerframerecord[0] 65 | info = inspect.getframeinfo(frame) 66 | 67 | self.log(f"{info.function} :{info.lineno}") 68 | # print(info.filename) 69 | 70 | def log(self, *args): 71 | print("[GCR]", *args, file=self.errstream) 72 | 73 | def send(self, msg=''): 74 | print(msg, end='\n', file=self.outstream, flush=True) 75 | 76 | def get_remote_refs(self): 77 | """Report remote refs 78 | There are kept in a dedicated "refs" file at the remote. 79 | Returns str 80 | """ 81 | self.PrintFrame() 82 | url = self.parsed_url 83 | cat = subprocess.run([ 84 | 'rclone', 'cat', '{}:{}/refs'.format(url.netloc, url.path)], 85 | stdout=subprocess.PIPE, 86 | stderr=subprocess.PIPE, # capture errors, not having refs is a normal thing 87 | text=True) 88 | return cat.stdout if (not cat.returncode) and cat.stdout else '' 89 | 90 | def get_remote_state(self): 91 | """Return a hash for the remote repo archive or '' 92 | 93 | Raises 94 | ------ 95 | RuntimeError 96 | If no connection to the rclone remote could be made, or an unkown 97 | error occurred. 98 | """ 99 | url = self.parsed_url 100 | # request listing of the remote dir with the repo archive 101 | lsjson = subprocess.run(['rclone', 'lsjson', '{}:{}'.format(url.netloc, url.path), 102 | '--files-only', '--no-modtime'], 103 | stdout=subprocess.PIPE, 104 | stderr=subprocess.PIPE) 105 | if lsjson.returncode == 3: # no repo on remote (but remote is accessible) 106 | self.log('Remote is accessible but no repo found') 107 | return '' 108 | elif lsjson.returncode: 109 | raise RuntimeError('Accesing rclone remote failed: {}'.format(lsjson.stderr)) 110 | 111 | files = {i['Path']: i for i in json.loads(lsjson.stdout)} 112 | # get filename of the file that looks like repo-SHA.tar.gz 113 | repo_file = [i for i in files.keys() if i.startswith('repo') and i.endswith('.tar.gz')] 114 | 115 | # We should never have more than one repo file 116 | if len(repo_file) > 1: 117 | raise RuntimeError('Multiple repo files found: {}'.format(repo_file)) 118 | 119 | # extract SHA from repo-SHA.tar.gz 120 | if not repo_file: 121 | self.log('No repo file found') 122 | return repo_file[0][5:-len('.tar.gz')] if repo_file else '' 123 | 124 | def mirror_repo_if_needed(self): 125 | """Ensure a local Git repo mirror of the one archived at the remote. 126 | """ 127 | # TODO acquire and release lock 128 | url = self.parsed_url 129 | # stamp file with last syncronization IDs 130 | synced = self.workdir / 'synced' 131 | repo_hash = self.get_remote_state() 132 | 133 | if synced.exists() and not repo_hash: 134 | # we had it sync'ed before, but now it is gone from the remote 135 | # remove sync stamp, but leave any local mirror untouched as it's the only copy 136 | synced.unlink() 137 | return 138 | 139 | if synced.exists(): 140 | # compare states, try to be robust and take any hash match 141 | # unclear when which hash is available, but any should be good 142 | 143 | # read single line string from synced file 144 | with open(synced, 'r') as f: 145 | last_hash = f.readline().strip() 146 | if last_hash == repo_hash: # local sync matches remote 147 | self.log(f'Local hash matches remote hash ({last_hash}). No need to re-mirror.') 148 | return 149 | 150 | if not repo_hash: # there is nothing at the remote end, nothing to sync 151 | return 152 | 153 | # mirror the repo 154 | self.log('Downloading repository archive') 155 | sync_dir = self.workdir / 'sync' 156 | subprocess.run(['rclone', 'copy', '--verbose', '--include', 'repo-*.tar.gz', '{}:{}/'.format( 157 | url.netloc, url.path), 158 | str(sync_dir)], 159 | check=True) 160 | repo_archive = list(sync_dir.glob('repo-*.tar.gz'))[0] 161 | 162 | self.log('Extracting repository archive') 163 | rmtree(str(self.repodir), ignore_errors=True) # clean left-overs 164 | uncompress(repo_archive, self.workdir) 165 | self.log(f"Uncompress done of {repo_archive} into {self.workdir}.") 166 | rmtree(str(sync_dir), ignore_errors=True) 167 | synced.write_text(repo_hash) # update sync stamp only after everything else was successful 168 | 169 | def import_refs_from_mirror(self, refs): 170 | """Uses fast-export to pull refs from the local repository mirror 171 | The mirror must exist, when this functional is called. 172 | """ 173 | if not self.repodir.exists(): 174 | # this should not happen.If we get here, it means that Git 175 | # was promised some refs to be available, but there the mirror 176 | # to pull them from did not materialize. Crash at this point, 177 | # any recovery form such a situation should have happened 178 | # before 179 | raise RuntimeError('rclone repository mirror not found') 180 | env = os.environ.copy() 181 | env['GIT_DIR'] = str(self.repodir) 182 | subprocess.run([ 183 | 'git', 'fast-export', 184 | '--import-marks={}'.format(str(self.marks_rclone)), 185 | '--export-marks={}'.format(str(self.marks_rclone)), 186 | '--refspec', self.refspec] + refs, 187 | env=env, check=True) 188 | 189 | def run_cmd(self, cmd, env=None, check=True): 190 | """Run command and return stdout""" 191 | if not env: 192 | env = os.environ.copy() 193 | env['GIT_DIR'] = str(self.repodir) 194 | return subprocess.run(cmd, env=env, check=check, stdout=subprocess.PIPE, text=True).stdout 195 | 196 | def format_refs_in_mirror(self): 197 | """Format a report on refs in the mirror like LIST wants it 198 | 199 | If the mirror is empty, the report will be empty. 200 | """ 201 | refs = '' 202 | if not self.repodir.exists(): 203 | return refs 204 | refs += self.run_cmd(['git', 'for-each-ref', "--format=%(objectname) %(refname)"]) 205 | HEAD_ref = self.run_cmd(['git', 'symbolic-ref', 'HEAD']) 206 | refs += '@{} HEAD\n'.format(HEAD_ref.strip()) 207 | return refs 208 | 209 | def gitgc(self): 210 | """Prune the remote repo aggressively if configured via: 211 | git config --add git-remote-rclone.pruneaggressively "true" 212 | """ 213 | env_orig = os.environ.copy() 214 | env_orig['GIT_DIR'] = str(self.gitdir) 215 | 216 | gc_cmd = ['git', 'gc'] 217 | prune = self.run_cmd(['git', 'config', 'git-remote-rclone.pruneaggressively'], 218 | env=env_orig, check=False).strip().lower() 219 | if prune == "true": 220 | self.log("Running git-gc with aggressive pruning") 221 | gc_cmd += ['--prune=now', '--aggressive'] 222 | self.run_cmd(gc_cmd, check=False) 223 | 224 | def export_to_rclone(self): 225 | """Export a fast-export stream to rclone. 226 | 227 | The stream is fast-import'ed into a local repository mirror first. 228 | If not mirror repository exists, an empty one is created. The mirror 229 | is then compressed and uploaded. 230 | """ 231 | # TODO acquire and release lock 232 | url = self.parsed_url 233 | env = os.environ.copy() 234 | env['GIT_DIR'] = str(self.repodir) 235 | if not self.repodir.exists(): 236 | # ensure we have a repo 237 | self.repodir.mkdir() 238 | subprocess.run(['git', 'init', '--bare', '--quiet'], env=env, check=True) 239 | 240 | # which refs did we have in the mirror before the import? 241 | before = self.run_cmd(['git', 'for-each-ref', "--format= %(refname) %(objectname) "]) 242 | 243 | # perform actual import 244 | subprocess.run([ 245 | 'git', 'fast-import', '--quiet', 246 | '--import-marks={}'.format(str(self.marks_rclone)), 247 | '--export-marks={}'.format(str(self.marks_rclone))], 248 | env=env, check=True) 249 | 250 | # which refs do we have now? 251 | after = self.run_cmd(['git', 'for-each-ref', "--format= %(refname) %(objectname) "]) 252 | 253 | # figure out if anything happened 254 | upload_failed_marker = (self.workdir / 'upload_failed') 255 | updated_refs = [] 256 | need_sync = False 257 | if upload_failed_marker.exists(): # we have some unsync'ed data from a previous attempt 258 | updated_refs = json.load(upload_failed_marker.open()) 259 | need_sync = True 260 | upload_failed_marker.unlink() 261 | 262 | for line in after.splitlines(): 263 | if line not in before: # change in ref 264 | updated_refs.append(line.strip().split()[0]) 265 | need_sync = True 266 | 267 | # TODO acknowledge a failed upload 268 | if not need_sync: 269 | return 270 | 271 | self.gitgc() 272 | 273 | # prepare upload pack 274 | sync_dir = self.workdir / 'sync' 275 | if not sync_dir.exists(): 276 | sync_dir.mkdir() 277 | repo_file = sync_dir / 'repotmp.tar.gz' 278 | compress(repo_file, 'repo', self.workdir) 279 | 280 | # repo_file to include the file's sha1 (so we don't depend the rclone backend being able to 281 | # provide the files's hash to us. Backends like crypt don't support this) 282 | repo_hash = hashlib.sha1(repo_file.read_bytes()).hexdigest() 283 | repo_file.rename(sync_dir / f'repo-{repo_hash}.tar.gz') 284 | 285 | # dump refs for a later LIST of the remote 286 | (sync_dir / 'refs').write_text(self.format_refs_in_mirror()) 287 | 288 | self.log('Upload repository archive') 289 | sync_repo = subprocess.run(['rclone', 'sync', str(sync_dir), 290 | '{}:{}'.format(url.netloc, url.path)]) 291 | if sync_repo.returncode: 292 | # make a record which refs failed to update/upload 293 | # to not report refs as successfully updated 294 | upload_failed_marker.write_text(json.dumps(updated_refs)) 295 | return 296 | 297 | rmtree(str(sync_dir), ignore_errors=True) # don't need the archive (still have the mirror) 298 | self.log(f"Upload was successful. updated_refs: {updated_refs}") 299 | for ref in updated_refs: 300 | self.log('ok {}'.format(ref)) 301 | 302 | # lastly update the sync stamp to avoid redownload of what was just uploaded 303 | synced = self.workdir / 'synced' 304 | repo_hash = self.get_remote_state() 305 | if not repo_hash: 306 | self.log('Failed to update sync stamp after successful upload') 307 | return 308 | 309 | self.log(f'Updating sync stamp to repo_hash: {repo_hash}') 310 | synced.write_text(repo_hash) 311 | 312 | 313 | def send_capabilities(self): 314 | self.PrintFrame() 315 | caps = ['import', 316 | 'export', 317 | f'refspec {self.refspec}', 318 | f'*import-marks {self.marks_git}', 319 | f'*export-marks {self.marks_git}', 320 | 'signed-tags'] 321 | for i in caps: 322 | self.send(i) 323 | self.send() 324 | 325 | def import_from_rclone(self, line): 326 | self.mirror_repo_if_needed() 327 | refs = [line[7:].strip()] 328 | while True: 329 | line = self.instream.readline() 330 | if not line.startswith('import '): 331 | break 332 | refs.append(line[7:].strip()) 333 | self.send(f'feature import-marks={self.marks_git}') 334 | self.send(f'feature export-marks={self.marks_git}') 335 | self.send('feature done') 336 | self.import_refs_from_mirror(refs) 337 | self.send('done') 338 | 339 | def communicate(self): 340 | """Implement the necessary pieces of the git-remote-helper protocol 341 | Uses the input, output and error streams from the object 342 | """ 343 | for rawline in self.instream: 344 | line = rawline.rstrip() 345 | if not line: # exit command 346 | return 347 | elif line == 'capabilities': 348 | self.send_capabilities() 349 | elif line == 'list': 350 | self.send(f'{self.get_remote_refs()}') 351 | elif line.startswith('import '): # data is being imported from rclone 352 | self.import_from_rclone(line) 353 | elif line == 'export': # data is being exported to rclone 354 | self.mirror_repo_if_needed() 355 | self.export_to_rclone() 356 | self.send('') 357 | else: 358 | self.log('UNKNOWN COMMAND', line) # unrecoverable error 359 | return 360 | 361 | 362 | def main(): 363 | if len(sys.argv) < 3: 364 | raise ValueError("Usage: git-remote-rclone REMOTE-NAME URL") 365 | 366 | remote, url = sys.argv[1:3] 367 | gitdir = os.environ['GIT_DIR'] # no fallback, must be present 368 | 369 | rclone = RCloneRemote(gitdir, remote, url) 370 | rclone.communicate() 371 | 372 | 373 | if __name__ == '__main__': 374 | main() 375 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools >= 30.3.0", "wheel"] 3 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | url = https://github.com/redstreet/git-remote-rclone-reds 3 | version = 0.3 4 | author = Red S 5 | author_email = redstreet@users.noreply.github.com 6 | maintainer = Red S 7 | maintainer_email = redstreet@users.noreply.github.com 8 | description = Git remote helper for rclone-supported services 9 | long_description = file:README.md 10 | long_description_content_type = text/markdown; charset=UTF-8; variant=GFM 11 | license = GPL-3.0 12 | classifiers = 13 | Programming Language :: Python 14 | License :: OSI Approved :: GNU General Public License v3 (GPLv3) 15 | Programming Language :: Python :: 3 16 | 17 | [options] 18 | python_requires = >= 3.5 19 | scripts = 20 | git-remote-rclone 21 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import sys 3 | from setuptools import setup 4 | 5 | # Give setuptools a hint to complain if it's too old a version 6 | # 30.3.0 allows us to put most metadata in setup.cfg 7 | # Should match pyproject.toml 8 | SETUP_REQUIRES = ['setuptools >= 30.3.0'] 9 | # This enables setuptools to install wheel on-the-fly 10 | SETUP_REQUIRES += ['wheel'] if 'bdist_wheel' in sys.argv else [] 11 | 12 | 13 | if __name__ == '__main__': 14 | setup(name='git_remote_rclone_reds', 15 | setup_requires=SETUP_REQUIRES, 16 | ) 17 | -------------------------------------------------------------------------------- /test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | readonly base="$(cd "$(dirname "${0}")" && pwd)" 4 | 5 | readonly TEST_DIR="${base}/test" 6 | readonly FIRST_REPO="${TEST_DIR}/LOCAL1" 7 | readonly REMOTE_REPO="${TEST_DIR}/REMOTE" 8 | readonly SECOND_REPO="${TEST_DIR}/LOCAL2" 9 | readonly RCLONE_REMOTE_PLAIN="test-remote-plain" 10 | readonly RCLONE_REMOTE_CRYPT="test-remote-crypt" 11 | readonly GIT_PLAIN_REMOTE_URL="rclone://${RCLONE_REMOTE_PLAIN}/${REMOTE_REPO}" 12 | readonly GIT_CRYPT_REMOTE_URL="rclone://${RCLONE_REMOTE_CRYPT}" 13 | readonly TEST_FILE1="testfile1" 14 | readonly TEST_FILE2="testfile2" 15 | 16 | cleanup() 17 | { 18 | if [ -d "${TEST_DIR}" ]; then 19 | rm -rf "${TEST_DIR}" 20 | fi 21 | } 22 | 23 | setup_rclone_config() 24 | { 25 | export RCLONE_CONFIG="${TEST_DIR}/rclone.conf" 26 | rclone config create "${RCLONE_REMOTE_PLAIN}" local 27 | rclone config create "${RCLONE_REMOTE_CRYPT}" crypt "password=$(rclone obscure git-remote-rclone)" "remote=${REMOTE_REPO}" 28 | } 29 | 30 | setup_test_dir() 31 | { 32 | mkdir -p "${TEST_DIR}" 33 | } 34 | 35 | setup_remote_repo() 36 | { 37 | if [ -d "${REMOTE_REPO}" ]; then 38 | rm -rvf "${REMOTE_REPO}" 39 | fi 40 | mkdir -p "${REMOTE_REPO}" 41 | } 42 | 43 | setup_repo() 44 | { 45 | local remote_url="${1?missing remote_url}" 46 | rm -rvf "${FIRST_REPO}" "${SECOND_REPO}" 47 | mkdir -p "${FIRST_REPO}" 48 | git -C "${FIRST_REPO}" init --initial-branch master 49 | git -C "${FIRST_REPO}" remote add origin "${remote_url}" 50 | } 51 | 52 | prepend_data() 53 | { 54 | local repo="${1?missing repo}" 55 | local file="${2-${TEST_FILE1}}" 56 | local data="${3-$(date -Ins)}" 57 | local new_data="$(echo "${data}"; cat "${repo}/${file}")" 58 | echo "${new_data}" > "${repo}/${file}" 59 | } 60 | 61 | append_data() 62 | { 63 | local repo="${1?missing repo}" 64 | local file="${2-${TEST_FILE1}}" 65 | local data="${3-$(date -Ins)}" 66 | echo "${data}" >> "${repo}/${file}" 67 | } 68 | 69 | replace_data() 70 | { 71 | local repo="${1?missing repo}" 72 | local file="${2-${TEST_FILE1}}" 73 | local data="${3-$(date -Ins)}" 74 | echo "${data}" > "${repo}/${file}" 75 | } 76 | 77 | create_commit() 78 | { 79 | local repo="${1?missing repo}" 80 | git -C "${repo}" add "${repo}" 81 | git -C "${repo}" commit -m "$(date -Ins)" 82 | return "${?}" 83 | } 84 | 85 | push_repo() 86 | { 87 | local repo="${1?missing repo}" 88 | git -C "${repo}" push -u origin master 89 | return "${?}" 90 | } 91 | 92 | pull_repo() 93 | { 94 | local repo="${1?missing repo}" 95 | git -C "${repo}" pull origin master 96 | return "${?}" 97 | } 98 | 99 | fetch_repo() 100 | { 101 | local repo="${1?missing repo}" 102 | git -C "${repo}" fetch 103 | return "${?}" 104 | } 105 | 106 | merge_repo() 107 | { 108 | local repo="${1?missing repo}" 109 | git -C "${repo}" merge origin/master 110 | return "${?}" 111 | } 112 | 113 | reset_repo() 114 | { 115 | local repo="${1?missing repo}" 116 | git -C "${repo}" reset --hard origin/master 117 | return "${?}" 118 | } 119 | 120 | test_push_new_repo() 121 | { 122 | set -xe 123 | local remote_url="${1?missing remote_url}" 124 | setup_repo "${remote_url}" 125 | append_data "${FIRST_REPO}" 126 | create_commit "${FIRST_REPO}" 127 | push_repo "${FIRST_REPO}" 128 | } 129 | 130 | test_clone_repo() 131 | { 132 | set -xe 133 | local remote_url="${1?missing remote_url}" 134 | git -C "${TEST_DIR}" clone -b master "${remote_url}" "${SECOND_REPO}" 135 | } 136 | 137 | test_pull_repo() 138 | { 139 | set -xe 140 | append_data "${FIRST_REPO}" 141 | create_commit "${FIRST_REPO}" 142 | push_repo "${FIRST_REPO}" 143 | pull_repo "${SECOND_REPO}" 144 | } 145 | 146 | test_3way_merge() 147 | { 148 | set -xe 149 | append_data "${FIRST_REPO}" 150 | create_commit "${FIRST_REPO}" 151 | push_repo "${FIRST_REPO}" 152 | append_data "${SECOND_REPO}" "${TEST_FILE2}" 153 | create_commit "${SECOND_REPO}" 154 | fetch_repo "${SECOND_REPO}" 155 | merge_repo "${SECOND_REPO}" 156 | push_repo "${SECOND_REPO}" 157 | pull_repo "${FIRST_REPO}" 158 | } 159 | 160 | test_conflict() 161 | { 162 | set -xe 163 | replace_data "${FIRST_REPO}" 164 | create_commit "${FIRST_REPO}" 165 | push_repo "${FIRST_REPO}" 166 | append_data "${SECOND_REPO}" 167 | create_commit "${SECOND_REPO}" 168 | push_repo "${SECOND_REPO}" && false || true 169 | fetch_repo "${SECOND_REPO}" 170 | reset_repo "${SECOND_REPO}" 171 | } 172 | 173 | print_test_started() 174 | { 175 | local test="${1?missing test}" 176 | local type="${2?missing type}" 177 | printf "TEST ${test} (${type}): " 178 | } 179 | 180 | print_test_passed() 181 | { 182 | echo "PASSED" 183 | } 184 | 185 | print_test_failed() 186 | { 187 | echo "FAILED" 188 | } 189 | 190 | run_test() 191 | { 192 | local test="${1?missing test}" 193 | local type="${2?missing type}" 194 | shift 2 195 | print_test_started "${test}" "${type}" 196 | output=$(eval "${test}" "${@}" 2>&1) 197 | if [ "${?}" -ne 0 ]; then 198 | print_test_failed "${test}" "${type}" 199 | echo "Test logs:" 200 | echo "${output}" 1>&2 201 | print_test_started "${test}" "${type}" 202 | print_test_failed "${test}" "${type}" 203 | exit 1 204 | fi 205 | print_test_passed "${test}" "${type}" 206 | } 207 | 208 | tests() 209 | { 210 | local remote_url="${1?missing remote_url}" 211 | local remote_type="${2?missing remote_type}" 212 | run_test test_push_new_repo "${remote_type}" "${remote_url}" 213 | run_test test_clone_repo "${remote_type}" "${remote_url}" 214 | run_test test_pull_repo "${remote_type}" 215 | run_test test_3way_merge "${remote_type}" 216 | run_test test_conflict "${remote_type}" 217 | run_test test_pull_repo "${remote_type}" 218 | } 219 | 220 | main() 221 | { 222 | cleanup 223 | setup_test_dir 224 | setup_rclone_config 225 | setup_remote_repo 226 | tests "${GIT_PLAIN_REMOTE_URL}" "plain" 227 | tests "${GIT_CRYPT_REMOTE_URL}" "crypt" 228 | echo "PASSED ALL TESTS SUCCESSFULLY" 229 | } 230 | 231 | main 232 | --------------------------------------------------------------------------------