diff --git a/.github/workflows/changelog.yml b/.github/workflows/changelog.yml new file mode 100644 index 0000000..c521d36 --- /dev/null +++ b/.github/workflows/changelog.yml @@ -0,0 +1,27 @@ +name: Changelog + +on: + pull_request: + types: [labeled, unlabeled, opened, reopened, synchronize] + +permissions: + contents: read + +env: + PR_NUMBER: ${{ github.event.number }} + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - name: Check for file + if: ${{ + hashFiles(format('docs/changes/{0}.*.rst', github.event.number)) == '' && + ! contains( github.event.pull_request.labels.*.name, 'skip-changelog') + }} + run: | + ls docs/changes + echo ERROR: No changelog file found for pull request \#"$PR_NUMBER"! + exit 1 + diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7844163..8692666 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,6 +1,3 @@ -# This workflow will install Python dependencies, run tests and lint with a single version of Python -# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python - name: CI on: @@ -21,7 +18,7 @@ jobs: python-version: ["3.12", "3.13", "3.14"] steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v5 with: @@ -31,7 +28,7 @@ jobs: - name: Install dependencies run: | pip install --upgrade pip - pip install -e ".[tests]" + pip install -e . --group tests pip freeze - name: Test with pytest @@ -43,18 +40,24 @@ jobs: with: token: ${{ secrets.CODECOV_TOKEN }} - # pre-commit: - # runs-on: ubuntu-latest - # strategy: - # matrix: - # python-version: ["3.14"] - # - # steps: - # - uses: actions/checkout@v4 - # - name: Set up Python ${{ matrix.python-version }} - # uses: actions/setup-python@v5 - # with: - # python-version: ${{ matrix.python-version }} - # - name: Display Python version - # run: python -c "import sys; print(sys.version)" - # - uses: pre-commit/action@v3.0.1 + test_docs: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v5 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.14' + architecture: 'x64' + - name: Display Python version + run: python -c "import sys; print(sys.version)" + - name: Install documentation dependencies + run: | + pip install --upgrade pip + pip install -e . --group docs + pip freeze + - name: Build documentation + run: | + make -C docs html diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 0000000..ff9fdc4 --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,90 @@ +name: Docs + +on: + release: + types: [published] + +permissions: + contents: write + +jobs: + build_and_release: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.14' + architecture: 'x64' + - name: Display Python version + run: python -c "import sys; print(sys.version)" + - name: Install dependencies + run: | + pip install --upgrade pip + pip install -e . --group docs + pip freeze + - name: Build towncrier + run: | + towncrier build --yes + + - name: Build sphinx docs + run: | + make -C docs html + - name: Compress build + run: | + sudo apt update --yes && sudo apt install zip --yes + cd docs/_build/html && zip -r ../html.zip ./* + cd ../../../ + + # The App Token creation and git config setup were adapted from: + # - create-github-app-token (https://github.com/actions/create-github-app-token) + # Originally licensed under MIT License. Copyright (c) 2023 Gregor Martynus, Parker Brown. + - name: Create GitHub App token + id: app-token + uses: actions/create-github-app-token@v2 + with: + app-id: ${{ secrets.APP_ID }} + private-key: ${{ secrets.APP_PRIVATE_KEY }} + - name: Get GitHub App User ID + id: get-user-id + run: echo "user-id=$(gh api "/users/${{ steps.app-token.outputs.app-slug }}[bot]" --jq .id)" >> "$GITHUB_OUTPUT" + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + - name: Setup git config + run: | + set +x + git config --global user.name '${{ steps.app-token.outputs.app-slug }}[bot]' + git config --global user.email '${{ steps.get-user-id.outputs.user-id }}+${{ steps.app-token.outputs.app-slug }}[bot]@users.noreply.github.com' + - name: Commit and Push + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + run: | + set +x + git add -u docs/changes/ + git add docs/changes/*.rst + git commit -m "Create Changelog for ${{ github.event.release.tag_name }}" || exit 0 + + git push "https://x-access-token:${GH_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" HEAD:${{ github.event.release.target_commitish }} + + # Inspired by: https://stackoverflow.com/a/60479844 and https://stackoverflow.com/a/70447517 + - name: Create SSH key + run: | + install -m 600 -D /dev/null ~/.ssh/id_key + echo "$SSH_PRIVATE_KEY" > ~/.ssh/id_key + ssh-keyscan -H "$SSH_HOSTNAME" > ~/.ssh/known_hosts + env: + SSH_PRIVATE_KEY: ${{secrets.SSH_PRIVATE_KEY}} + SSH_HOSTNAME: ${{secrets.SSH_HOSTNAME}} + - name: Upload to server + run: | + ssh -v -i ~/.ssh/id_key "$SSH_USER@$SSH_HOSTNAME" "rm -rf '$SSH_TARGET_DIR/' && mkdir -p '$SSH_TARGET_DIR'" + scp -v -i ~/.ssh/id_key -r docs/_build/html.zip "$SSH_USER"@"$SSH_HOSTNAME":"$SSH_TARGET_DIR"/html.zip + ssh -v -i ~/.ssh/id_key "$SSH_USER@$SSH_HOSTNAME" "unzip -o '$SSH_TARGET_DIR/html.zip' -d '$SSH_TARGET_DIR' && rm -rf '$SSH_TARGET_DIR/html.zip'" + env: + SSH_USER: ${{secrets.SSH_USER}} + SSH_HOSTNAME: ${{secrets.SSH_HOSTNAME}} + SSH_TARGET_DIR: ${{secrets.SSH_TARGET_DIR}} diff --git a/.gitignore b/.gitignore index 633597b..6c51ea9 100644 --- a/.gitignore +++ b/.gitignore @@ -80,7 +80,7 @@ instance/ # Sphinx documentation docs/_build/ -docs/build +docs/_generated # PyBuilder .pybuilder/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index b7b9436..ef4a302 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -2,6 +2,12 @@ # - pyvisgen (https://github.com/radionets-project/pyvisgen/blob/main/.pre-commit-config.yaml) # Originally licensed under MIT License. Copyright (c) 2021 radionets-project. +default_install_hook_types: + - pre-commit + - commit-msg + +default_stages: [pre-commit] + repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v6.0.0 @@ -31,3 +37,9 @@ repos: rev: v2.4.1 hooks: - id: codespell + - repo: https://github.com/compilerla/conventional-pre-commit + rev: v4.3.0 + hooks: + - id: conventional-pre-commit + stages: [ commit-msg ] + args: [--verbose] \ No newline at end of file diff --git a/ASSETS_LEGAL.rst b/ASSETS_LEGAL.rst index 5d14269..f1d08cf 100644 --- a/ASSETS_LEGAL.rst +++ b/ASSETS_LEGAL.rst @@ -1,17 +1,16 @@ -============== Asset Licenses -============== +-------------- This file documents the sources and licenses of additional media used within this repository, which is not inside of the main source code of the module. **Backpy Logo and Icon** - =================== =================================================================================================================================================================== - **File** ``_ ``_ + =================== ========================================================================================================================================================================================================================================================================================== + **File** ``_ ``_ ``_ ``_ ``_ ``_ **Author** ``_ **Used Elements** | `Font Awesome 'database' icon `_ (License: `CC-4.0-BY `_) | `Catppuccin Colors `_ (License: `MIT License `_) - =================== =================================================================================================================================================================== + =================== ========================================================================================================================================================================================================================================================================================== diff --git a/LICENSE b/LICENSE index b7a4139..0d99044 100644 --- a/LICENSE +++ b/LICENSE @@ -1,681 +1,172 @@ - GNU GENERAL PUBLIC LICENSE + GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - 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. - - 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. - - 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. - - 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. - - 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. - - 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. - - 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. - - 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. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "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. - - 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. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - 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. - - 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. - - 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. - - 1. Source Code. - - 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. - - 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. - - 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. - - 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. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - 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. - - 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. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - 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. - - 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. - - 4. Conveying Verbatim Copies. - - 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. - - 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. - - 5. Conveying Modified Source Versions. - - 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: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - 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". - - 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. - - 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. - - 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. - - 6. Conveying Non-Source Forms. - - 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: - - 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. - - 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. - - 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. - - 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. - - 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. - - 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. - - 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. - - "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. - - 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). - - 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. - - 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. - - 7. Additional Terms. - - "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. - - 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. - - 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: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - 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 - - 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 - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - 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. - - 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. - - 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. - - 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. - - 8. Termination. - - 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). - - 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. - - 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. - - 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. - - 9. Acceptance Not Required for Having Copies. - - 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. - - 10. Automatic Licensing of Downstream Recipients. - - 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. - - 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. - - 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. - - 11. Patents. - - 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". - - 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. - - 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. - - 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. - - 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. - - 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. - - 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. - - 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. - - 12. No Surrender of Others' Freedom. - - 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. - - 13. Use with the GNU Affero General Public License. - - 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. - - 14. Revised Versions of this License. - - 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. - - 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. - - 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. - - 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. - - 15. Disclaimer of Warranty. - - 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. - - 16. Limitation of Liability. - - 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. - - 17. Interpretation of Sections 15 and 16. - - 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. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser 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. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. ### Third-party code notice -This project includes adapted code from the following sources: +This project includes adapted code or assets from the following sources: - pyvisgen (https://github.com/radionets-project/pyvisgen) Licensed under the MIT License. @@ -685,7 +176,15 @@ This project includes adapted code from the following sources: Licensed under the BSD 3-Clause License. Copyright (c) 2011-2024, Astropy Developers -The original MIT License and BSD 3-Clause License texts are included below: +- Fira Sans Font (https://fonts.google.com/specimen/Fira+Sans) + Licensed under the SIL Open Font License, Version 1.1. + Copyright (c) 2012-2015, The Mozilla Foundation and Telefonica S.A. + +- JetBrains Mono Font (https://fonts.google.com/specimen/JetBrains+Mono) + Licensed under the SIL Open Font License, Version 1.1. + Copyright (c) 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono) + +The original MIT License, BSD 3-Clause License and SIL Open Font License, Version 1.1 texts are included below: -------------------- @@ -738,4 +237,93 @@ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PRO OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, -EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file +EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +-------------------- + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/README.md b/README.md index 0347b88..226d99a 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ -# backpy [![CI Status](https://github.com/tgross03/backpy/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/tgross03/backpy/actions/workflows/ci.yml?branch=main) [![codecov](https://codecov.io/gh/tgross03/backpy/graph/badge.svg?token=NSQD951ZPJ)](https://codecov.io/gh/tgross03/backpy) [![pre-commit.ci status](https://results.pre-commit.ci/badge/github/tgross03/backpy/main.svg)](https://results.pre-commit.ci/latest/github/tgross03/backpy/main) [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) +# backpy [![CI Status](https://github.com/tgross03/backpy/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/tgross03/backpy/actions/workflows/ci.yml?branch=main) [![codecov](https://codecov.io/gh/tgross03/backpy/graph/badge.svg?token=NSQD951ZPJ)](https://codecov.io/gh/tgross03/backpy) [![pre-commit.ci status](https://results.pre-commit.ci/badge/github/tgross03/backpy/main.svg)](https://results.pre-commit.ci/latest/github/tgross03/backpy/main) [![License: GPL v3](https://img.shields.io/badge/License-LGPLv3-blue.svg)](https://www.gnu.org/licenses/lgpl-3.0) -[![BackPy Logo](./assets/backpy_logo.png)](https://github.com/tgross03/backpy) +[![BackPy Logo](./docs/_static/logos/backpy_logo_dark.png)](https://github.com/tgross03/backpy) > [!CAUTION] > This package is still in development and not stable at this time! Features and functionalities might not work as expected. diff --git a/assets/backpy_icon.png b/assets/backpy_icon.png deleted file mode 100644 index b0a0d7f..0000000 Binary files a/assets/backpy_icon.png and /dev/null differ diff --git a/assets/backpy_logo.png b/assets/backpy_logo.png deleted file mode 100644 index 1d3975f..0000000 Binary files a/assets/backpy_logo.png and /dev/null differ diff --git a/backpy/__init__.py b/backpy/__init__.py index e8662c8..035c351 100644 --- a/backpy/__init__.py +++ b/backpy/__init__.py @@ -1,29 +1,19 @@ from __future__ import annotations -from backpy.core.config.configuration import TOMLConfiguration +from backpy.core.config import TOMLConfiguration from backpy.core.config.variables import VariableLibrary -VariableLibrary() +from backpy import version + +from rich import traceback -from backpy.core.backup import compression -from backpy.core.utils.times import TimeObject -from backpy.core.remote import Remote, Protocol +VariableLibrary() -# Import in the correct order to avoid circular imports -from backpy.core.backup.types import BackupSpaceType -from backpy.core.backup.backup_space import BackupSpace -from backpy.core.backup.backup import Backup -from backpy.core.backup.file_backup_space import FileBackupSpace +traceback.install(show_locals=VariableLibrary.get_variable("exceptions.show_locals")) __all__ = [ - "FileBackupSpace", - "TOMLConfiguration", "VariableLibrary", - "BackupSpace", - "BackupSpaceType", - "Backup", - "compression", - "TimeObject", - "Remote", - "Protocol", + "TOMLConfiguration", ] + +__version__ = version.__version__ diff --git a/backpy/cli/backup/create_command.py b/backpy/cli/backup/create_command.py index 56a889d..0f172ba 100644 --- a/backpy/cli/backup/create_command.py +++ b/backpy/cli/backup/create_command.py @@ -1,6 +1,5 @@ import rich_click as click -from backpy import BackupSpace from backpy.cli.colors import RESET, get_default_palette from backpy.cli.elements import ( BackupSpaceInput, @@ -9,6 +8,7 @@ TextInput, print_error_message, ) +from backpy.core.space import BackupSpace from backpy.core.utils.exceptions import ( BackupLimitExceededError, InvalidBackupSpaceError, diff --git a/backpy/cli/backup/delete_command.py b/backpy/cli/backup/delete_command.py index bb7a82c..f1fd3e4 100644 --- a/backpy/cli/backup/delete_command.py +++ b/backpy/cli/backup/delete_command.py @@ -1,7 +1,6 @@ import rich_click as click from rich.console import Console -from backpy import Backup, BackupSpace from backpy.cli.colors import RESET, get_default_palette from backpy.cli.elements import ( BackupInput, @@ -9,6 +8,8 @@ ConfirmInput, print_error_message, ) +from backpy.core.backup import Backup +from backpy.core.space import BackupSpace from backpy.core.utils.exceptions import InvalidBackupError, InvalidBackupSpaceError palette = get_default_palette() diff --git a/backpy/cli/backup/info_command.py b/backpy/cli/backup/info_command.py index c083f17..ae91a0c 100644 --- a/backpy/cli/backup/info_command.py +++ b/backpy/cli/backup/info_command.py @@ -1,7 +1,6 @@ import rich_click as click from rich.console import Console -from backpy import Backup, BackupSpace from backpy.cli.colors import RESET, get_default_palette from backpy.cli.elements import ( BackupInput, @@ -9,6 +8,8 @@ ConfirmInput, print_error_message, ) +from backpy.core.backup import Backup +from backpy.core.space import BackupSpace from backpy.core.utils.exceptions import InvalidBackupError, InvalidBackupSpaceError palette = get_default_palette() diff --git a/backpy/cli/backup/list_command.py b/backpy/cli/backup/list_command.py index bcc5c8e..cb8a638 100644 --- a/backpy/cli/backup/list_command.py +++ b/backpy/cli/backup/list_command.py @@ -2,9 +2,9 @@ from rich.console import Console from rich.tree import Tree -from backpy import BackupSpace from backpy.cli.colors import RESET, get_default_palette from backpy.cli.elements import print_error_message +from backpy.core.space import BackupSpace from backpy.core.utils import bytes2str from backpy.core.utils.exceptions import InvalidBackupSpaceError diff --git a/backpy/cli/backup/lock_command.py b/backpy/cli/backup/lock_command.py index 22c93b5..146ccdf 100644 --- a/backpy/cli/backup/lock_command.py +++ b/backpy/cli/backup/lock_command.py @@ -1,7 +1,6 @@ import rich_click as click from rich.console import Console -from backpy import Backup, BackupSpace from backpy.cli.colors import RESET, get_default_palette from backpy.cli.elements import ( BackupInput, @@ -9,6 +8,8 @@ ConfirmInput, print_error_message, ) +from backpy.core.backup import Backup +from backpy.core.space import BackupSpace from backpy.core.utils.exceptions import InvalidBackupError, InvalidBackupSpaceError palette = get_default_palette() diff --git a/backpy/cli/backup/restore_command.py b/backpy/cli/backup/restore_command.py index 3977d9b..3b4dc84 100644 --- a/backpy/cli/backup/restore_command.py +++ b/backpy/cli/backup/restore_command.py @@ -1,7 +1,6 @@ import rich_click as click from rich.console import Console -from backpy import Backup, BackupSpace from backpy.cli.colors import RESET, get_default_palette from backpy.cli.elements import ( BackupInput, @@ -10,6 +9,8 @@ TextInput, print_error_message, ) +from backpy.core.backup import Backup +from backpy.core.space import BackupSpace from backpy.core.utils.exceptions import ( InvalidBackupError, InvalidBackupSpaceError, diff --git a/backpy/cli/backup/unlock_command.py b/backpy/cli/backup/unlock_command.py index 00d9a90..511523c 100644 --- a/backpy/cli/backup/unlock_command.py +++ b/backpy/cli/backup/unlock_command.py @@ -1,7 +1,6 @@ import rich_click as click from rich.console import Console -from backpy import Backup, BackupSpace from backpy.cli.colors import RESET, get_default_palette from backpy.cli.elements import ( BackupInput, @@ -9,6 +8,8 @@ ConfirmInput, print_error_message, ) +from backpy.core.backup import Backup +from backpy.core.space import BackupSpace from backpy.core.utils.exceptions import InvalidBackupError, InvalidBackupSpaceError palette = get_default_palette() diff --git a/backpy/cli/cli.py b/backpy/cli/cli.py index d7fc221..79d1bdd 100644 --- a/backpy/cli/cli.py +++ b/backpy/cli/cli.py @@ -24,7 +24,6 @@ def _print_version(ctx, param, value): - if not value or ctx.resilient_parsing: return @@ -44,7 +43,6 @@ def _print_version(ctx, param, value): def _print_info(ctx, param, value): - if not value or ctx.resilient_parsing: return @@ -94,7 +92,7 @@ def _create_epilog(short): # Structure of the entry_point group and adding of the subcommands -# taken from https://stackoverflow.com/a/39228156 +# inspired by the discussion https://stackoverflow.com/a/39228156 @click.group(epilog=_create_epilog(short=True)) @click.option( "--version", diff --git a/backpy/cli/colors.py b/backpy/cli/colors.py index 903d15b..35cb62d 100644 --- a/backpy/cli/colors.py +++ b/backpy/cli/colors.py @@ -4,6 +4,8 @@ from backpy import VariableLibrary +__all__ = ["get_default_palette", "rgb_to_ansi"] + # RGB to ANSI guide from # https://jakob-bagterp.github.io/colorist-for-python/ansi-escape-codes/rgb-colors/ diff --git a/backpy/cli/config/list_command.py b/backpy/cli/config/list_command.py index d3da1de..fbb0d4d 100644 --- a/backpy/cli/config/list_command.py +++ b/backpy/cli/config/list_command.py @@ -27,7 +27,7 @@ def list_variables(key: str | None, debug: bool) -> None: try: if key is None: - value = VariableLibrary.get_config().as_dict() + value = VariableLibrary.get_config().asdict() else: value = VariableLibrary.get_variable(key=key) except InvalidTOMLConfigurationError: diff --git a/backpy/cli/config/set_command.py b/backpy/cli/config/set_command.py index e46ac24..34c70c5 100644 --- a/backpy/cli/config/set_command.py +++ b/backpy/cli/config/set_command.py @@ -33,6 +33,39 @@ def set_value(key: str, value: str, force: bool, debug: bool) -> None: try: prev_value = VariableLibrary.get_variable(key=key) + if isinstance(prev_value, bool): + if value.lower() == "true": + value = True + elif value.lower() == "false": + value = False + else: + return print_error_message( + error=TypeError( + "The given value has to be boolean type (e.g. 'true' or 'false')!" + ), + debug=debug, + ) + elif isinstance(prev_value, int): + try: + value = int(value) + except ValueError: + return print_error_message( + error=TypeError( + "The given value has to be integer type (e.g. '1')." + ), + debug=debug, + ) + elif isinstance(prev_value, float): + try: + value = float(value) + except ValueError: + print_error_message( + error=TypeError( + "The given value has to be float type (e.g. '1.0')." + ), + debug=debug, + ) + if prev_value == value: print( f"{palette.red}ERROR: {palette.maroon}The variable is already set " diff --git a/backpy/cli/elements.py b/backpy/cli/elements.py index c7cadc6..ca8554f 100644 --- a/backpy/cli/elements.py +++ b/backpy/cli/elements.py @@ -4,16 +4,55 @@ from fuzzyfinder import fuzzyfinder -from backpy import Backup, BackupSpace from backpy.cli.colors import EFFECTS, RESET, get_default_palette -from backpy.core.backup import Schedule +from backpy.core.backup import Backup, Schedule from backpy.core.remote import Remote +from backpy.core.space import BackupSpace from backpy.core.utils.utils import str2bytes palette = get_default_palette() +__all__ = [ + "print_error_message", + "ConfirmInput", + "TextInput", + "PasswordInput", + "BackupSpaceInput", + "BackupInput", + "RemoteInput", + "ScheduleInput", + "EnumerationInput", + "FilePathInput", + "DirectoryPathInput", + "IntegerInput", + "FloatInput", + "MemorySizeInput", + "_validate_always", + "_validate_not_none", + "_validate_file_path", + "_validate_directory_path", + "_validate_memory", + "_validate_integer", + "_validate_float", +] + def print_error_message(error: Exception, debug: bool) -> None: + """ + Print error messages depending on the debug mode. + If the debug mode is enabled, the exception is raised, + resulting in a stack trace. Otherwise, an error message is printed. + + Parameters + ---------- + + error: Exception + The exception to raise / print. + + debug: bool + Whether debug mode is enabled. + + """ if debug: raise error else: diff --git a/backpy/cli/remote/create_command.py b/backpy/cli/remote/create_command.py index 5b6ad58..a4030b7 100644 --- a/backpy/cli/remote/create_command.py +++ b/backpy/cli/remote/create_command.py @@ -2,7 +2,7 @@ import rich_click as click -from backpy import Protocol, Remote, VariableLibrary +from backpy import VariableLibrary from backpy.cli.colors import RESET, get_default_palette from backpy.cli.elements import ( ConfirmInput, @@ -12,13 +12,11 @@ TextInput, print_error_message, ) -from backpy.core.remote.remote import protocols +from backpy.core.remote import Protocol, Remote from backpy.core.utils.exceptions import InvalidRemoteError palette = get_default_palette() -protocol_names = [protocol.name for protocol in protocols] - def create_interactive(verbosity_level: int, debug: bool) -> None: @@ -41,13 +39,13 @@ def create_interactive(verbosity_level: int, debug: bool) -> None: protocol = TextInput( message=f"{palette.base}> Enter the desired transfer protocol " - f"({palette.overlay1}available: {', '.join(protocol_names)}{palette.base}):{RESET}", + f"({palette.overlay1}available: {', '.join(Protocol.names())}{palette.base}):{RESET}", suggest_matches=True, - suggestible_values=protocol_names, + suggestible_values=Protocol.names(), invalid_error_message=f"{palette.maroon}Invalid protocol! Please try again.{RESET}", ).prompt() - protocol = Protocol.from_name(name=protocol) + protocol = Protocol[protocol] hostname = TextInput( message=f"{palette.base}> Enter the hostname of the remote:{RESET}", @@ -143,7 +141,7 @@ def create_interactive(verbosity_level: int, debug: bool) -> None: @click.option( "--protocol", "-p", - type=click.types.Choice(protocol_names), + type=click.types.Choice(Protocol.names()), default="scp", help="The transfer protocol to use for the file up- and download.", ) @@ -286,10 +284,11 @@ def create( try: remote.test_connection(verbosity_level=verbose) except Exception as e: - print_error_message(error=e, debug=debug) + remote.delete(delete_files=False, verbosity_level=verbose) print( - f"{palette.red}HINT:{palette.maroon} If you are experiencing connection problems " - "due to wrong settings of the remote, edit or remove it via the CLI." + f"{palette.red}ERROR:{palette.maroon} An error occurred while testing the connection! " + f"The remote has been deleted." ) + return print_error_message(error=e, debug=debug) return None diff --git a/backpy/cli/remote/edit_command.py b/backpy/cli/remote/edit_command.py index 582526a..0fcca68 100644 --- a/backpy/cli/remote/edit_command.py +++ b/backpy/cli/remote/edit_command.py @@ -2,15 +2,12 @@ import rich_click as click -from backpy import Protocol, Remote from backpy.cli.colors import RESET, get_default_palette from backpy.cli.elements import PasswordInput, print_error_message -from backpy.core.remote.password import encrypt -from backpy.core.remote.remote import protocols +from backpy.core.encryption.password import encrypt +from backpy.core.remote import Protocol, Remote from backpy.core.utils.exceptions import InvalidRemoteError -protocol_names = [protocol.name for protocol in protocols] - palette = get_default_palette() @@ -23,7 +20,7 @@ @click.option( "--protocol", "-p", - type=click.types.Choice(protocol_names), + type=click.types.Choice(Protocol.names()), default=None, help="The transfer protocol to use for the file up- and download.", ) @@ -127,7 +124,7 @@ def edit( debug=debug, ) - prev_config = remote._config.as_dict().copy() + prev_config = remote._config.asdict().copy() remote.disconnect(verbosity_level=verbose) @@ -135,7 +132,7 @@ def edit( remote._name = name if protocol is not None: - remote._protocol = Protocol.from_name(protocol) + remote._protocol = Protocol[protocol] if hostname is not None: remote._hostname = hostname @@ -180,7 +177,7 @@ def edit( remote.update_config() - if remote._config.as_dict() == prev_config and verbose >= 1: + if remote._config.asdict() == prev_config and verbose >= 1: print(f"{palette.flamingo}Nothing to update. No changes applied.{RESET}") elif verbose >= 1: print( diff --git a/backpy/cli/schedule/activate_command.py b/backpy/cli/schedule/activate_command.py index b57a0ea..e0db45a 100644 --- a/backpy/cli/schedule/activate_command.py +++ b/backpy/cli/schedule/activate_command.py @@ -1,7 +1,6 @@ import rich_click as click from rich.console import Console -from backpy import BackupSpace from backpy.cli.colors import RESET, get_default_palette from backpy.cli.elements import ( BackupSpaceInput, @@ -10,6 +9,7 @@ print_error_message, ) from backpy.core.backup.scheduling import Schedule +from backpy.core.space import BackupSpace from backpy.core.utils.exceptions import InvalidBackupSpaceError, InvalidScheduleError palette = get_default_palette() diff --git a/backpy/cli/schedule/create_command.py b/backpy/cli/schedule/create_command.py index c1390af..6cceae0 100644 --- a/backpy/cli/schedule/create_command.py +++ b/backpy/cli/schedule/create_command.py @@ -10,7 +10,8 @@ TextInput, print_error_message, ) -from backpy.core.backup import BackupSpace, Schedule +from backpy.core.backup import Schedule +from backpy.core.space import BackupSpace from backpy.core.utils.exceptions import InvalidBackupSpaceError palette = get_default_palette() diff --git a/backpy/cli/schedule/deactivate_command.py b/backpy/cli/schedule/deactivate_command.py index d0d9afe..ac52ed4 100644 --- a/backpy/cli/schedule/deactivate_command.py +++ b/backpy/cli/schedule/deactivate_command.py @@ -1,7 +1,6 @@ import rich_click as click from rich.console import Console -from backpy import BackupSpace from backpy.cli.colors import RESET, get_default_palette from backpy.cli.elements import ( BackupSpaceInput, @@ -10,6 +9,7 @@ print_error_message, ) from backpy.core.backup.scheduling import Schedule +from backpy.core.space import BackupSpace from backpy.core.utils.exceptions import InvalidBackupSpaceError, InvalidScheduleError palette = get_default_palette() diff --git a/backpy/cli/schedule/delete_command.py b/backpy/cli/schedule/delete_command.py index 0587eb4..97fa49f 100644 --- a/backpy/cli/schedule/delete_command.py +++ b/backpy/cli/schedule/delete_command.py @@ -1,7 +1,6 @@ import rich_click as click from rich.console import Console -from backpy import BackupSpace from backpy.cli.colors import RESET, get_default_palette from backpy.cli.elements import ( BackupSpaceInput, @@ -10,6 +9,7 @@ print_error_message, ) from backpy.core.backup.scheduling import Schedule +from backpy.core.space import BackupSpace from backpy.core.utils.exceptions import InvalidBackupSpaceError, InvalidScheduleError palette = get_default_palette() diff --git a/backpy/cli/schedule/list_command.py b/backpy/cli/schedule/list_command.py index aa71db7..b38361e 100644 --- a/backpy/cli/schedule/list_command.py +++ b/backpy/cli/schedule/list_command.py @@ -2,10 +2,10 @@ from rich.console import Console from rich.tree import Tree -from backpy import BackupSpace from backpy.cli.colors import RESET, get_default_palette from backpy.cli.elements import print_error_message from backpy.core.backup import Schedule +from backpy.core.space import BackupSpace from backpy.core.utils.exceptions import InvalidBackupSpaceError, InvalidScheduleError palette = get_default_palette() diff --git a/backpy/cli/space/clear_command.py b/backpy/cli/space/clear_command.py index 45e90cc..d5277ea 100644 --- a/backpy/cli/space/clear_command.py +++ b/backpy/cli/space/clear_command.py @@ -2,7 +2,7 @@ from backpy.cli.colors import RESET, get_default_palette from backpy.cli.elements import ConfirmInput, print_error_message -from backpy.core.backup import BackupSpace +from backpy.core.space import BackupSpace from backpy.core.utils.exceptions import InvalidBackupSpaceError palette = get_default_palette() diff --git a/backpy/cli/space/common/create.py b/backpy/cli/space/common/create.py index ce88f92..eefaa2a 100644 --- a/backpy/cli/space/common/create.py +++ b/backpy/cli/space/common/create.py @@ -3,7 +3,7 @@ import rich_click as click from click_params import FirstOf -from backpy import BackupSpace, BackupSpaceType, Remote, VariableLibrary +from backpy import VariableLibrary from backpy.cli.colors import RESET, get_default_palette from backpy.cli.elements import ( ConfirmInput, @@ -15,6 +15,8 @@ print_error_message, ) from backpy.core.backup import compression +from backpy.core.remote import Remote +from backpy.core.space import BackupSpace, BackupSpaceType from backpy.core.utils.exceptions import InvalidRemoteError from backpy.core.utils.utils import str2bytes @@ -165,7 +167,7 @@ def create_backup_space( ) -> None: verbose += 1 - backup_space_type = BackupSpaceType.from_name(name=space_type) + backup_space_type = BackupSpaceType[space_type] if interactive: return create_backup_space_interactive( diff --git a/backpy/cli/space/common/edit.py b/backpy/cli/space/common/edit.py index c1267d3..eb29002 100644 --- a/backpy/cli/space/common/edit.py +++ b/backpy/cli/space/common/edit.py @@ -3,11 +3,12 @@ import rich_click as click from click_params import FirstOf -from backpy import BackupSpace, BackupSpaceType, Remote from backpy.cli.colors import RESET, get_default_palette from backpy.cli.elements import ConfirmInput, print_error_message from backpy.core.backup import compression from backpy.core.backup.compression import CompressionAlgorithm +from backpy.core.remote import Remote +from backpy.core.space import BackupSpace, BackupSpaceType from backpy.core.utils import bytes2str from backpy.core.utils.exceptions import InvalidBackupSpaceError, InvalidRemoteError from backpy.core.utils.utils import str2bytes @@ -90,7 +91,7 @@ def edit_backup_space( if isinstance(max_size, str): max_size = str2bytes(max_size) - if current_size > max_size: + if max_size != -1 and current_size > max_size: return print_error_message( error=ValueError( f"The given maximum disk usage of the backup space ({bytes2str(max_size)}) " diff --git a/backpy/cli/space/delete_command.py b/backpy/cli/space/delete_command.py index 1657f56..ae8ff8a 100644 --- a/backpy/cli/space/delete_command.py +++ b/backpy/cli/space/delete_command.py @@ -2,7 +2,7 @@ from backpy.cli.colors import RESET, get_default_palette from backpy.cli.elements import ConfirmInput, print_error_message -from backpy.core.backup import BackupSpace +from backpy.core.space import BackupSpace from backpy.core.utils.exceptions import InvalidBackupSpaceError palette = get_default_palette() diff --git a/backpy/cli/space/file_system/create_command.py b/backpy/cli/space/file_system/create_command.py index 689f8cf..fc33c68 100644 --- a/backpy/cli/space/file_system/create_command.py +++ b/backpy/cli/space/file_system/create_command.py @@ -2,10 +2,10 @@ import rich_click as click -from backpy import BackupSpaceType from backpy.cli.colors import RESET, get_default_palette from backpy.cli.elements import DirectoryPathInput from backpy.cli.space.common.create import common_options, create_backup_space +from backpy.core.space import BackupSpaceType palette = get_default_palette() @@ -25,7 +25,7 @@ def interactive() -> dict[str, Path]: help=f"Create a backup space with a {palette.sky}'NAME'{RESET} for a " f"file system at a {palette.sky}'FILE_PATH'{RESET}.", ) -@common_options(space_type=BackupSpaceType.from_name("FILE_SYSTEM")) +@common_options(space_type=BackupSpaceType.FILE_SYSTEM) @click.argument( "file_path", default="./", diff --git a/backpy/cli/space/file_system/edit_command.py b/backpy/cli/space/file_system/edit_command.py index f37b903..9c11f80 100644 --- a/backpy/cli/space/file_system/edit_command.py +++ b/backpy/cli/space/file_system/edit_command.py @@ -2,10 +2,10 @@ import rich_click as click -from backpy import BackupSpaceType from backpy.cli.colors import RESET, get_default_palette from backpy.cli.elements import ConfirmInput from backpy.cli.space.common.edit import common_options, edit_backup_space +from backpy.core.space import BackupSpaceType palette = get_default_palette() @@ -20,7 +20,7 @@ type=click.Path(exists=True, file_okay=False, dir_okay=True), help="The path to the directory that should be backed up.", ) -@common_options(space_type=BackupSpaceType.from_name("FILE_SYSTEM")) +@common_options(space_type=BackupSpaceType.FILE_SYSTEM) def edit_file_system(file_path: str | None, **kwargs) -> None: force = kwargs["force"] diff --git a/backpy/cli/space/info_command.py b/backpy/cli/space/info_command.py index 8767d84..7bbe4d6 100644 --- a/backpy/cli/space/info_command.py +++ b/backpy/cli/space/info_command.py @@ -3,7 +3,7 @@ from backpy.cli.colors import RESET, get_default_palette from backpy.cli.elements import print_error_message -from backpy.core.backup import BackupSpace +from backpy.core.space import BackupSpace from backpy.core.utils.exceptions import InvalidBackupSpaceError palette = get_default_palette() diff --git a/backpy/cli/space/list_command.py b/backpy/cli/space/list_command.py index c812af3..93e690a 100644 --- a/backpy/cli/space/list_command.py +++ b/backpy/cli/space/list_command.py @@ -4,7 +4,7 @@ from backpy.cli.colors import RESET, get_default_palette from backpy.cli.elements import print_error_message -from backpy.core.backup import BackupSpace +from backpy.core.space import BackupSpace from backpy.core.utils import bytes2str palette = get_default_palette() diff --git a/backpy/core/backup/__init__.py b/backpy/core/backup/__init__.py index 8186638..fca3f20 100644 --- a/backpy/core/backup/__init__.py +++ b/backpy/core/backup/__init__.py @@ -1,18 +1,12 @@ from __future__ import annotations from backpy.core.backup import compression -from backpy.core.backup.backup import Backup -from backpy.core.backup.backup_space import BackupSpace -from backpy.core.backup.file_backup_space import FileBackupSpace +from backpy.core.backup.backup import Backup, RestoreMode from backpy.core.backup.scheduling import Schedule -from backpy.core.backup.types import BackupSpaceType __all__ = [ "Backup", - "BackupSpace", - "BackupSpaceType", - "FileBackupSpace", - "compression", + "RestoreMode", "Schedule", - "BackupSpaceType", + "compression", ] diff --git a/backpy/core/backup/backup.py b/backpy/core/backup/backup.py index ad95ffc..41cf093 100644 --- a/backpy/core/backup/backup.py +++ b/backpy/core/backup/backup.py @@ -15,15 +15,29 @@ from backpy.cli.colors import EFFECTS, RESET, get_default_palette from backpy.core.backup import compression from backpy.core.config import TOMLConfiguration +from backpy.core.config.configuration import MissingKeyPolicy from backpy.core.remote import Remote from backpy.core.utils import TimeObject, bytes2str, calculate_sha256sum +from backpy.core.utils.enum import Enum from backpy.core.utils.exceptions import InvalidBackupError, InvalidChecksumError if TYPE_CHECKING: - from backpy import BackupSpace + from backpy.core.space import BackupSpace palette = get_default_palette() +__all__ = ["Backup", "RestoreMode"] + + +class RestoreMode(Enum): + OVERWRITE = "Replaces existing objects and add missing" + MERGE = "Preserves existing objects and adds missing" + REPLACE = "Replaces existing objects and does not add missing" + CLEAN = "Deletes all existing objects and replaces with backup" + + def __init__(self, description: str): + self.description = description + class Backup: def __init__( @@ -144,7 +158,7 @@ def unlock(self, verbosity_level: int = 1): self.update_config(verbosity_level=verbosity_level) def update_config(self, verbosity_level: int = 1): - current_content = self._config.as_dict() + current_content = self._config.asdict() content = { "uuid": str(self._uuid), @@ -158,10 +172,10 @@ def update_config(self, verbosity_level: int = 1): "locked": self._locked, } - self._config.dump_dict(dict(merge({}, current_content, content))) + self._config.dump(dict(merge({}, current_content, content))) if self.has_remote_archive(): - with self._remote(): + with self._remote(context_verbosity=verbosity_level): self._remote.remove( target=self.get_remote_config_path(), verbosity_level=verbosity_level, @@ -171,11 +185,11 @@ def update_config(self, verbosity_level: int = 1): ) def restore( - self, incremental: bool, source: str, force: bool, verbosity_level: int = 1 + self, mode: RestoreMode, source: str, force: bool, verbosity_level: int = 1 ) -> None: self._backup_space.get_as_child_class().restore_backup( unique_id=str(self._uuid), - incremental=incremental, + mode=mode, source=source, force=force, verbosity_level=verbosity_level, @@ -286,9 +300,11 @@ def load_by_uuid( f"The Backup with UUID '{unique_id}' does not exist." ) - config = TOMLConfiguration(config_path, none_if_unknown_key=True) + config = TOMLConfiguration( + config_path, missing_key_policy=MissingKeyPolicy.RETURN_NONE + ) - if not config.is_valid(): + if not config.exists(): raise InvalidBackupError( f"The Backup with UUID '{unique_id}' could not be loaded because its" "'config.toml' is invalid!" @@ -418,7 +434,6 @@ def new( cls._config.create() cls.update_config() - cls._config.prepend_no_edit_warning() if cls._backup_space.is_backup_limit_reached(post_creation=True): if cls._backup_space.is_auto_deletion_active(): @@ -523,7 +538,7 @@ def get_created_at(self) -> TimeObject: return self._created_at def get_config(self) -> dict: - return self._config.as_dict() + return self._config.asdict() def get_file_size(self, verbosity_level: int = 1) -> int: if self.has_local_archive(): diff --git a/backpy/core/backup/compression.py b/backpy/core/backup/compression.py index 970ebba..b2c5ac9 100644 --- a/backpy/core/backup/compression.py +++ b/backpy/core/backup/compression.py @@ -10,6 +10,15 @@ from backpy.core.utils.exceptions import UnsupportedCompressionAlgorithmError +__all__ = [ + "compress", + "unpack", + "is_algorithm_available", + "filter_paths", + "CompressionAlgorithm", + "_compression_methods", +] + @dataclass class CompressionAlgorithm: diff --git a/backpy/core/backup/scheduling.py b/backpy/core/backup/scheduling.py index 67a8328..df1f03e 100644 --- a/backpy/core/backup/scheduling.py +++ b/backpy/core/backup/scheduling.py @@ -17,10 +17,12 @@ COMMENT_SUFFIX = "(MANAGED BY BACKPY)" if TYPE_CHECKING: - from backpy.core.backup.backup_space import BackupSpace + from backpy.core.space.backup_space import BackupSpace palette = get_default_palette() +__all__ = ["Schedule"] + class Schedule: def __init__( @@ -68,7 +70,7 @@ def delete(self, verbosity_level: int = 1): print(f"Deleted config for schedule {self._uuid}") def update_config(self): - current_content = self._config.as_dict() + current_content = self._config.asdict() content = { "uuid": str(self._uuid), @@ -80,7 +82,7 @@ def update_config(self): "description": self._description, } - self._config.dump_dict(dict(merge({}, current_content, content))) + self._config.dump(dict(merge({}, current_content, content))) def get_info_table(self, include_command: bool = False) -> Table: table = Table( @@ -137,13 +139,13 @@ def _get_comment(self) -> str: @classmethod def load_by_uuid(cls, unique_id: str) -> "Schedule": - from backpy.core.backup.backup_space import BackupSpace + from backpy.core.space.backup_space import BackupSpace config = TOMLConfiguration( path=Path(VariableLibrary.get_variable("paths.schedule_directory")) / (unique_id + ".toml") ) - if not config.is_valid(): + if not config.exists(): raise InvalidScheduleError("There is no schedule with this UUID.") return cls( diff --git a/backpy/core/backup/types.py b/backpy/core/backup/types.py deleted file mode 100644 index 29e348f..0000000 --- a/backpy/core/backup/types.py +++ /dev/null @@ -1,42 +0,0 @@ -from __future__ import annotations - -from dataclasses import dataclass -from typing import TYPE_CHECKING, Type - -if TYPE_CHECKING: - from backpy import BackupSpace - - -@dataclass -class BackupSpaceType: - name: str - full_name: str - description: str - use_exclusion: bool - use_inclusion: bool - child_class: Type[BackupSpace] - - @classmethod - def from_name(cls, name): - for backup_space_type in _get_backups_space_type(): - if backup_space_type.name == name: - return backup_space_type - return None - - -def _get_backups_space_type(): - from .file_backup_space import FileBackupSpace - - return [ - # BackupSpaceType( - # "SQL_DATABASE", "Backup-Space of a MariaDB or MySQL database and its tables." - # ), - BackupSpaceType( - name="FILE_SYSTEM", - full_name="File System Backup Space", - description="Backup-Space of one or more files and/or directories.", - use_inclusion=True, - use_exclusion=True, - child_class=FileBackupSpace, - ), - ] diff --git a/backpy/core/config/__init__.py b/backpy/core/config/__init__.py index 5d5535c..b29d1f5 100644 --- a/backpy/core/config/__init__.py +++ b/backpy/core/config/__init__.py @@ -1,4 +1,6 @@ -from backpy.core.config.configuration import TOMLConfiguration +from __future__ import annotations + +from backpy.core.config.configuration import TOMLConfiguration, MissingKeyPolicy from backpy.core.config.variables import VariableLibrary -__all__ = ["TOMLConfiguration", "VariableLibrary"] +__all__ = ["TOMLConfiguration", "MissingKeyPolicy", "VariableLibrary"] diff --git a/backpy/core/config/configuration.py b/backpy/core/config/configuration.py index 779e4cb..1db400e 100644 --- a/backpy/core/config/configuration.py +++ b/backpy/core/config/configuration.py @@ -1,136 +1,171 @@ +import tomllib +from enum import Enum +from os import PathLike from pathlib import Path +from typing import Any -import toml +import tomli_w from backpy.core.utils.exceptions import InvalidTOMLConfigurationError +__all__ = ["TOMLConfiguration", "MissingKeyPolicy"] -def _parse_key(key: str): - key_components = key.split(".") - return key_components + +class MissingKeyPolicy(Enum): + ERROR = 1 + RETURN_NONE = 2 class TOMLConfiguration: def __init__( self, - path: str | Path, + path: PathLike | str, create_if_not_exists: bool = False, - none_if_unknown_key: bool = False, + missing_key_policy: MissingKeyPolicy = MissingKeyPolicy.ERROR, ): - self._path: Path = Path(path) if isinstance(path, str) else path - self._none_if_unknown_key: bool = none_if_unknown_key + """ + Initializes a new TOML configuration. + + Parameters + ---------- + + path : PathLike | str + The path to the toml file. + + create_if_not_exists : bool, optional + Whether to create the corresponding file if it does not exist. + Default is ``False``. + + missing_key_policy : MissingKeyPolicy | str, optional + The policy to react to missing keys. + Default is ``MissingKeyPolicy.ERROR`` meaning that an error will be raised. + + """ - if self._path.suffix != ".toml": + self._path: Path = Path(path) + + if self._path.suffix.lower() != ".toml": raise InvalidTOMLConfigurationError( - "The given configuration file has to be a TOML file!" + "The given file has an incorrect file suffix " + f"(is '{self._path.suffix}')! Has to be 'toml'" ) - if create_if_not_exists: + if not self.exists() and create_if_not_exists: self.create() - def is_valid(self) -> bool: - return self._path.is_file() and self._path.suffix == ".toml" + self._missing_key_policy: MissingKeyPolicy = ( + missing_key_policy + if isinstance(missing_key_policy, MissingKeyPolicy) + else MissingKeyPolicy[missing_key_policy] + ) - def __getitem__(self, item: str): - if not self.is_valid(): - raise InvalidTOMLConfigurationError( - "The given configuration file is not valid!" - ) + def create(self) -> None: + """ + Creates an empty TOML file at the config path. + """ - keys = _parse_key(item) - content_dict = toml.load(self._path) + self._path.parent.mkdir(exist_ok=True, parents=True) + self._path.touch(exist_ok=True) - content = content_dict - for key in keys: - if isinstance(content, dict): - try: - content = content[key] - except KeyError as error: - if self._none_if_unknown_key: - return None - else: - raise error - else: - raise KeyError( - f"The key component '{key}' is set to a non-dict value and " - "therefore there cannot be a child value!" - ) + def exists(self) -> bool: + """ + Checks whether the file exists. - return content + Returns + ------- - def __setitem__(self, key: str, value: object): - if not self.is_valid(): - raise InvalidTOMLConfigurationError( - "The variable configuration could not " - f"be found at location {str(self._path)}!" - ) + bool : Whether the file exists. + """ + return self._path.exists() and self._path.is_file() - keys = _parse_key(key) - content_dict = toml.load(self._path) + def __getitem__(self, key: str) -> Any: + content = self.asdict() - content = content_dict - for i in range(len(keys)): - key = keys[i] - if i < len(keys) - 1: + keys = key.split(".") - if key not in content: - content[key] = dict() - content = content[key] - else: - if isinstance(content[key], dict): - content = content[key] - else: - raise KeyError( - f"The key component '{key}' is already " - "set to a non-dict value!" + for key in keys: + if not isinstance(content, dict) or key not in content: + return self._handle_missing_key(key=key) + + content = content[key] + + return content + + def _handle_missing_key(self, key: str) -> None: + match self._missing_key_policy: + case MissingKeyPolicy.ERROR: + raise KeyError(f"Invalid key: '{key}'") + case MissingKeyPolicy.RETURN_NONE: + return None + + def __setitem__(self, key: str, value: Any) -> None: + content = self.asdict() + + keys = key.split(".") + + content_dict = content + for kidx, key in zip(range(len(keys)), keys): + if not isinstance(content_dict, dict): + raise KeyError(f"Invalid key: '{key}'") + + if kidx == len(keys) - 1: + if key in content_dict: + if ( + isinstance(content_dict[key], dict) + and not isinstance(value, dict) + ) or ( + isinstance(value, dict) + and not isinstance(content_dict[key], dict) + ): + raise TypeError( + "The type of the value that to be set must be the " + "same of the current value!" ) + + if value is not None: + content_dict[key] = value + else: + del content_dict[key] else: - content[key] = value + content_dict = content_dict[key] - with open(self._path, "w") as file: - toml.dump(o=content_dict, f=file) + with open(self._path, "wb") as tomlf: + tomli_w.dump(content, tomlf) - def __contains__(self, item: str): - try: - value = self[item] + def __contains__(self, key: str) -> bool: + if not self.exists(): + return False + + content = self.asdict() + keys = key.split(".") - if value is None: + for key in keys: + if key not in content: return False - except KeyError: - return False + content = content[key] + return True - def create(self, create_parents: bool = True) -> None: - if create_parents: - self._path.parent.mkdir(exist_ok=True, parents=True) + def get_keys(self, non_dict_only: bool = False) -> list[str]: + """ + Provides a list of all keys in the configuration file. - self._path.touch(exist_ok=True) + Parameters + ---------- - def dump_dict(self, content: dict) -> None: - with open(self._path, "w") as file: - toml.dump(o=content, f=file) - - def as_dict(self) -> dict: - return toml.load(self._path) - - def prepend_comments( - self, comments: list[str] | str, linebreak: bool = True - ) -> None: - if isinstance(comments, str): - comments = [comments] - - # Adapted from https://stackoverflow.com/a/5917395 - with open(self._path, "r+") as file: - content = file.read() - file.seek(0, 0) - file.write( - "\n".join([("# " + comment) for comment in comments]) - + "\n" * (2 if linebreak else 1) - + content - ) + non_dict_only : bool, optional + Whether only to show the keys for variables and not for + sections of the configuration file. + Default is ``True``. + + Returns + ------- + + list[str] : A list of keys in the file. + + """ - def get_keys(self, non_dict_only: bool = False): def recursive_keys(dictionary: dict, parent: str | None = None) -> list[str]: keys = [] for key, value in dictionary.items(): @@ -143,19 +178,31 @@ def recursive_keys(dictionary: dict, parent: str | None = None) -> list[str]: keys.append(parent_key) return keys - return recursive_keys(dictionary=self.as_dict()) - - def prepend_no_edit_warning(self): - self.prepend_comments( - [ - "======================================" - "======================================", - " WARNING! DO NOT EDIT THIS FILE MANUALLY! " - "THIS COULD BREAK YOUR BACKPY!", - "======================================" - "======================================", - ] - ) + return recursive_keys(dictionary=self.asdict()) + + def asdict(self) -> dict[str, Any]: + """ + Provides the content of the TOML file as a dictionary. + + Returns + ------- + + dict : The content of the TOML file. + """ + with open(self._path, "rb") as tomlf: + content = tomllib.load(tomlf) + + return content + + def dump(self, content: dict[str, Any]) -> None: + """ + Dumps the given dictionary as content into the TOML file. + + Parameters + ---------- - def get_path(self) -> Path: - return self._path + content : dict + The content to dump into the file. + """ + with open(self._path, "wb") as tomlf: + tomli_w.dump(content, tomlf) diff --git a/backpy/core/config/variables.py b/backpy/core/config/variables.py index cab073e..057b876 100644 --- a/backpy/core/config/variables.py +++ b/backpy/core/config/variables.py @@ -1,4 +1,5 @@ from pathlib import Path +from typing import Any from mergedeep import merge @@ -7,7 +8,6 @@ class VariableLibrary: - _instance = None def __new__(cls): @@ -35,7 +35,7 @@ def generate(self, regenerate: bool = False) -> None: if not self.exists(): self._path.touch() - current_content = self._config.as_dict() + current_content = self._config.asdict() content = { "paths": { @@ -44,6 +44,9 @@ def generate(self, regenerate: bool = False) -> None: "schedule_directory": str(Path.home() / ".backpy/schedules"), "temporary_directory": str(Path.home() / ".backpy/.temp"), }, + "database": { + "mysql_directory": str(Path.home() / ".backpy/databases/mysql"), + }, "backup": { "states": { "default_compression_algorithm": "zip", @@ -54,14 +57,19 @@ def generate(self, regenerate: bool = False) -> None: }, "cli": { "color_palette": "latte", - "rich": {"palette": "solarized", "style": "box"}, + "rich": { + "palette": "solarized", + "style": "box", + }, + }, + "exceptions": { + "show_locals": False, }, } - self._config.dump_dict( + self._config.dump( content if regenerate else dict(merge({}, content, current_content)) ) - self._config.prepend_no_edit_warning() @classmethod def get_config(cls) -> TOMLConfiguration: @@ -74,16 +82,16 @@ def get_path(cls) -> Path: return instance._path @classmethod - def get_variable(cls, key: str): + def get_variable(cls, key: str) -> Any: instance = cls() return instance._config[key] @classmethod - def set_variable(cls, key: str, value: str) -> None: + def set_variable(cls, key: str, value: Any) -> None: instance = cls() instance._config[key] = value @classmethod def exists(cls) -> bool: instance = cls() - return instance._config.is_valid() + return instance._config.exists() diff --git a/backpy/core/database/__init__.py b/backpy/core/database/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backpy/core/database/mysql.py b/backpy/core/database/mysql.py new file mode 100644 index 0000000..d43e517 --- /dev/null +++ b/backpy/core/database/mysql.py @@ -0,0 +1,254 @@ +import subprocess +import uuid +from pathlib import Path + +from mergedeep import merge +from mysql.connector.connection import MySQLConnection + +from backpy import TOMLConfiguration, VariableLibrary +from backpy.core.encryption.password import decrypt, encrypt + +__all__ = ["MySQLServer", "test_mysqldump"] + +from backpy.core.utils.exceptions import InvalidDatabaseException + + +def test_mysqldump(verbosity_level: int = 1) -> bool: + try: + result = subprocess.run( + ["mysqldump --version"], + shell=True, + check=True, + capture_output=True, + text=True, + ) + except subprocess.CalledProcessError as e: + if verbosity_level > 0: + print( + "'mysqldump' command not found or not working properly. Return code:", + e.returncode, + ) + return False + + if verbosity_level > 1: + print("Found 'mysqldump' command with version info:", result.stdout) + + return True + + +class MySQLServer: + def __init__( + self, + unique_id: str | uuid.UUID, + name: str, + hostname: str, + port: int, + user: str, + token: str, + database: str | None, + ): + self._uuid: uuid.UUID = ( + unique_id if isinstance(unique_id, uuid.UUID) else uuid.UUID(unique_id) + ) + self._name: str = name + self._hostname: str = hostname + self._port: int = port + self._user: str = user + self._token: str = token + self._database: str = database if database is not None else "" + self._connection = None + + self._config: TOMLConfiguration = TOMLConfiguration( + path=Path(VariableLibrary.get_variable("database.mysql_directory")) + / f"{self._uuid}.toml", + create_if_not_exists=True, + ) + + def update_config(self) -> None: + + current_content = self._config.asdict() + + content = { + "uuid": str(self._uuid), + "name": self._name, + "hostname": self._hostname, + "port": self._port, + "user": self._user, + "token": self._token, + "database": self._database, + } + + self._config.dump(content=dict(merge({}, current_content, content))) + + def connect(self, verbosity_level: int = 1) -> MySQLConnection: + if self.is_connected(): + self.disconnect() + + if verbosity_level > 1: + print( + f"Connecting to MySQL server at {self._hostname}:{self._port} " + f"as user '{self._user}'..." + ) + + self._connection = MySQLConnection( + host=self._hostname, + port=self._port, + user=self._user, + password=decrypt(self._token), + database=self._database, + ) + return self._connection + + def disconnect(self, verbosity_level: int = 1) -> None: + if self.is_connected(): + print( + f"Closing MySQL connection for server '{self._hostname}:{self._port}'..." + ) + self._connection.close() + + if verbosity_level > 1: + print(f"Disconnected from MySQL server '{self._hostname}:{self._port}'.") + + self._connection = None + + def test_connection(self, verbosity_level: int = 1) -> bool: + try: + self.connect(verbosity_level=verbosity_level) + except Exception: + return False + + if not self._connection.is_connected or self._connection is None: + return False + + self.disconnect(verbosity_level=verbosity_level) + return True + + def create_dump( + self, + output_directory: Path | str, + databases: list[str], + tables: list[str], + include_data: bool, + include_routines: bool, + verbosity_level: int = 1, + ) -> None: + + output_directory = ( + Path(output_directory) + if isinstance(output_directory, str) + else output_directory + ) + + ##################### + # CLASSMETHODS # + ##################### + + @classmethod + def load_by_name(cls, name: str) -> "MySQLServer": + + for tomlf in Path( + VariableLibrary.get_variable("database.mysql_directory") + ).rglob("*.toml"): + config = TOMLConfiguration(path=tomlf, create_if_not_exists=False) + + if not config.exists(): + continue + + if name != config["name"]: + continue + + try: + return MySQLServer.load_by_uuid(unique_id=config["uuid"]) + except InvalidDatabaseException: + break + + raise InvalidDatabaseException( + f"There is no valid MySQL server presentwith the name '{name}'." + ) + + @classmethod + def load_by_uuid(cls, unique_id: str | uuid.UUID) -> "MySQLServer": + + unique_id = uuid.UUID(unique_id) if isinstance(unique_id, str) else unique_id + config = TOMLConfiguration( + path=Path(VariableLibrary.get_variable("database.mysql_directory")) + / f"{unique_id}.toml", + create_if_not_exists=False, + ) + + if not config.exists(): + raise InvalidDatabaseException( + f"The MySQL server with UUID '{unique_id}' could not be found." + ) + + instance = cls( + unique_id=unique_id, + name=config["name"], + hostname=config["hostname"], + port=config["port"], + user=config["user"], + token=config["token"], + database=config["database"], + ) + + return instance + + @classmethod + def new( + cls, + name: str, + user: str, + password: str, + hostname: str = "127.0.0.1", + port: int = 3306, + database: str | None = None, + test_connection: bool = True, + verbosity_level: int = 1, + ) -> "MySQLServer": + + unique_id = uuid.uuid4() + + instance = cls( + unique_id=unique_id, + name=name, + hostname=hostname, + port=port, + user=user, + token=encrypt(password), + database=database, + ) + + if test_connection and not instance.test_connection( + verbosity_level=verbosity_level + ): + raise ConnectionError( + f"Could not connect to MySQL server at {hostname}:{port} " + f"as user '{user}'." + ) + + return instance + + ##################### + # GETTER # + ##################### + + def is_connected(self) -> bool: + return self._connection is not None and self._connection.is_connected() + + def get_connection(self) -> MySQLConnection | None: + return self._connection + + def get_hostname(self) -> str: + return self._hostname + + def get_port(self) -> int: + return self._port + + def get_user(self) -> str: + return self._user + + def get_uuid(self) -> uuid.UUID: + return self._uuid + + def get_database(self) -> str: + return self._database diff --git a/backpy/core/encryption/__init__.py b/backpy/core/encryption/__init__.py new file mode 100644 index 0000000..579c594 --- /dev/null +++ b/backpy/core/encryption/__init__.py @@ -0,0 +1,5 @@ +from __future__ import annotations + +from backpy.core.encryption import password + +__all__ = ["password"] diff --git a/backpy/core/remote/password.py b/backpy/core/encryption/password.py similarity index 96% rename from backpy/core/remote/password.py rename to backpy/core/encryption/password.py index 6e3af61..7ce6e50 100644 --- a/backpy/core/remote/password.py +++ b/backpy/core/encryption/password.py @@ -2,6 +2,8 @@ from cryptography.fernet import Fernet +__all__ = ["encrypt", "decrypt"] + def _get_fernet() -> Fernet: key_file = Path.home() / ".backpy/config/.key" diff --git a/backpy/core/remote/__init__.py b/backpy/core/remote/__init__.py index 62930fe..1fcbf1e 100644 --- a/backpy/core/remote/__init__.py +++ b/backpy/core/remote/__init__.py @@ -1,4 +1,5 @@ -from backpy.core.remote import password +from __future__ import annotations + from backpy.core.remote.remote import Remote, Protocol -__all__ = ["password", "Remote", "Protocol"] +__all__ = ["Remote", "Protocol"] diff --git a/backpy/core/remote/remote.py b/backpy/core/remote/remote.py index e1fcd5d..827c012 100644 --- a/backpy/core/remote/remote.py +++ b/backpy/core/remote/remote.py @@ -22,7 +22,9 @@ from backpy import TOMLConfiguration, VariableLibrary from backpy.cli.colors import RESET, get_default_palette -from backpy.core.remote.password import decrypt, encrypt +from backpy.core.config.configuration import MissingKeyPolicy +from backpy.core.encryption.password import decrypt, encrypt +from backpy.core.utils import Enum from backpy.core.utils.exceptions import ( InvalidChecksumError, InvalidRemoteError, @@ -33,6 +35,8 @@ _DEFAULT_CONTEXT_VERBOSITY: int = 1 +__all__ = ["Remote", "Protocol"] + def _calculate_hash(path: Path) -> str: with open(path, "rb") as f: @@ -41,32 +45,21 @@ def _calculate_hash(path: Path) -> str: @dataclass -class Protocol: - name: str +class ProtocolData: description: str supports_ssh_keys: bool - @classmethod - def from_name(cls, name: str): - for protocol in protocols: - if protocol.name == name: - return protocol - return None - - -protocols = [ - Protocol( - name="scp", - description="Uses the the 'scp.py' module to transfer files using scp (Secure Copy).", - supports_ssh_keys=True, - ), - Protocol( - name="sftp", - description="Uses the 'paramiko' module to transfer files using SFTP " + +class Protocol(ProtocolData, Enum): + SCP = ( + "Uses the the 'scp.py' module to transfer files using scp (Secure Copy).", + True, + ) + SFTP = ( + "Uses the 'paramiko' module to transfer files using SFTP " "(Safe File Transport Protocol).", - supports_ssh_keys=True, - ), -] + True, + ) class Remote: @@ -109,7 +102,7 @@ def __init__( self._context_managed: bool = False self._context_verbosity: int = _DEFAULT_CONTEXT_VERBOSITY - def __call__(self, context_verbosity: int, *args, **kwargs): + def __call__(self, context_verbosity: int = 1, *args, **kwargs): self._context_verbosity = context_verbosity return self @@ -122,7 +115,6 @@ def __enter__(self) -> "Remote": return self def __exit__(self, exc_type, exc_val, exc_tb) -> bool: - if not self._context_managed: return False @@ -132,8 +124,7 @@ def __exit__(self, exc_type, exc_val, exc_tb) -> bool: return False def update_config(self): - - current_content = self._config.as_dict() + current_content = self._config.asdict() content = { "name": self._name, @@ -151,10 +142,9 @@ def update_config(self): "sha256_cmd": self._sha256_cmd, } - self._config.dump_dict(dict(merge({}, current_content, content))) + self._config.dump(dict(merge({}, current_content, content))) def connect(self, verbosity_level: int = 1) -> None: - if self._client is not None: self._client.close() @@ -195,7 +185,6 @@ def connect(self, verbosity_level: int = 1) -> None: print(f"Connected to {self._hostname} with user {self._username}.") def disconnect(self, verbosity_level: int = 1) -> None: - if self._client is not None: self._client.close() @@ -203,7 +192,6 @@ def disconnect(self, verbosity_level: int = 1) -> None: print(f"Connection to {self._hostname} was closed.") def test_connection(self, verbosity_level: int = 1) -> None: - if self._context_managed: raise RuntimeError( "The connection of the remote may not be tested while " @@ -247,7 +235,6 @@ def upload( max_retries: int = 3, verbosity_level: int = 1, ) -> None: - if isinstance(source, str): source = Path(source) @@ -257,13 +244,12 @@ def upload( with Progress( *Progress.get_default_columns(), DownloadColumn(), TransferSpeedColumn() ) as progress: - task = progress.add_task( f"Uploading {source.name}", visible=verbosity_level >= 1 ) match self._protocol.name: - case "sftp": + case "SFTP": sftp_client = self._client.open_sftp() if source.is_file(): @@ -306,7 +292,6 @@ def upload( for root, dirs, files in Path(source).walk( follow_symlinks=False ): - self.mkdir( target=str(target / root), parents=True, @@ -323,8 +308,7 @@ def upload( callback=_progress, ) - case "scp": - + case "SCP": _progress = lambda filename, total, sent: progress.update( task, total=total, completed=sent ) @@ -384,7 +368,6 @@ def download( max_retries: int = 3, verbosity_level: int = 1, ) -> None: - if isinstance(target, str): target = Path(target) @@ -457,7 +440,6 @@ def mkdir( client: SFTPClient | SCPClient | None = None, verbosity_level: int = 1, ) -> None: - if not client and not self._context_managed: self.connect(verbosity_level=verbosity_level) @@ -532,7 +514,6 @@ def is_dir( sftp_client: SFTPClient | None = None, close_afterwards: bool = True, ) -> bool: - if not sftp_client and not self._context_managed: self.connect() sftp_client = self._client.open_sftp() @@ -557,7 +538,6 @@ def exists( sftp_client: SFTPClient | None = None, close_afterwards: bool = True, ) -> bool: - if not sftp_client and not self._context_managed: self.connect() sftp_client = self._client.open_sftp() @@ -583,7 +563,6 @@ def remove( close_afterwards: bool = True, verbosity_level: int = 1, ) -> None: - if not sftp_client and not self._context_managed: self.connect(verbosity_level=verbosity_level) sftp_client = self._client.open_sftp() @@ -624,8 +603,7 @@ def remove( self.disconnect(verbosity_level=verbosity_level) def delete(self, delete_files: bool, verbosity_level: int = 1): - - from backpy.core.backup.backup_space import BackupSpace + from backpy.core.space.backup_space import BackupSpace if self._context_managed: raise RuntimeError( @@ -645,7 +623,6 @@ def delete(self, delete_files: bool, verbosity_level: int = 1): space.get_remote() is not None and space.get_remote().get_uuid() == self.get_uuid() ): - if delete_files: self.remove( target=space.get_remote_path(), verbosity_level=verbosity_level @@ -672,7 +649,6 @@ def delete(self, delete_files: bool, verbosity_level: int = 1): print(f"Remote with UUID {self._uuid} was deleted.") def get_hash(self, target: str, verbosity_level: int = 1) -> str: - if not self._context_managed: self.connect(verbosity_level=verbosity_level) @@ -697,7 +673,6 @@ def get_file_size( sftp_client: SFTPClient | None = None, verbosity_level: int = 1, ) -> int: - if not sftp_client and not self._context_managed: self.connect(verbosity_level=verbosity_level) sftp_client = self._client.open_sftp() @@ -713,7 +688,6 @@ def get_file_size( return info.st_size def get_info_table(self) -> Table: - table = Table( title=f"{palette.peach}REMOTE INFORMATION{RESET}", show_header=False, @@ -776,7 +750,6 @@ def get_remotes(cls): @classmethod def load_by_uuid(cls, unique_id: str) -> "Remote": - unique_id = uuid.UUID(unique_id) config = TOMLConfiguration( @@ -785,17 +758,17 @@ def load_by_uuid(cls, unique_id: str) -> "Remote": create_if_not_exists=False, ) - if not config.is_valid(): + if not config.exists(): raise InvalidRemoteError( f"The remote with UUID '{str(unique_id)}' could not be found!" ) - config._none_if_unknown_key = True + config._missing_key_policy = MissingKeyPolicy.RETURN_NONE cls = cls( name=config["name"], unique_id=unique_id, - protocol=Protocol.from_name(config["protocol"]), + protocol=Protocol[config["protocol"]], hostname=config["hostname"], username=config["username"], token=config["token"] if config["token"] != "" else None, @@ -812,7 +785,7 @@ def load_by_uuid(cls, unique_id: str) -> "Remote": cls._config = config - config._none_if_unknown_key = False + config._missing_key_policy = MissingKeyPolicy.ERROR cls.update_config() return cls @@ -824,7 +797,7 @@ def load_by_name(cls, name: str) -> "Remote": ): config = TOMLConfiguration(tomlf, create_if_not_exists=False) - if not config.is_valid(): + if not config.exists(): continue if name != config["name"]: @@ -859,7 +832,6 @@ def new( verbosity_level: int = 1, test_connection: bool = True, ) -> "Remote": - if name == "None": raise NameError("Remotes may not be named 'None'.") diff --git a/backpy/core/space/__init__.py b/backpy/core/space/__init__.py new file mode 100644 index 0000000..49d770a --- /dev/null +++ b/backpy/core/space/__init__.py @@ -0,0 +1,13 @@ +from __future__ import annotations + +from backpy.core.space.backup_space import BackupSpace +from backpy.core.space.file_backup_space import FileBackupSpace +from backpy.core.space.mysql_backup_space import MySQLBackupSpace +from backpy.core.space.types import BackupSpaceType + +__all__ = [ + "BackupSpace", + "BackupSpaceType", + "FileBackupSpace", + "MySQLBackupSpace", +] diff --git a/backpy/core/backup/backup_space.py b/backpy/core/space/backup_space.py similarity index 95% rename from backpy/core/backup/backup_space.py rename to backpy/core/space/backup_space.py index 6d95d7d..fa029b1 100644 --- a/backpy/core/backup/backup_space.py +++ b/backpy/core/space/backup_space.py @@ -12,8 +12,10 @@ from backpy.cli.colors import RESET, get_default_palette from backpy.core.backup import compression +from backpy.core.backup.backup import RestoreMode from backpy.core.backup.scheduling import Schedule from backpy.core.config import TOMLConfiguration, VariableLibrary +from backpy.core.config.configuration import MissingKeyPolicy from backpy.core.remote import Remote from backpy.core.utils import bytes2str from backpy.core.utils.exceptions import ( @@ -22,7 +24,8 @@ ) if TYPE_CHECKING: - from backpy import Backup, BackupSpaceType + from backpy.core.backup import Backup + from backpy.core.space import BackupSpaceType palette = get_default_palette() @@ -85,7 +88,7 @@ def create_backup( def restore_backup( self, unique_id: str, - incremental: bool, + mode: RestoreMode, source: str = "local", force: bool = False, verbosity_level: int = 1, @@ -100,7 +103,7 @@ def get_backups( verbosity_level: int = 1, ) -> list[Backup]: - from backpy import Backup + from backpy.core.backup import Backup configurations = [ file if file.is_file() else None for file in self._backup_dir.glob("*.toml") @@ -134,7 +137,7 @@ def get_backups( return backups def update_config(self): - current_content = self._config.as_dict() + current_content = self._config.asdict() content = { "general": { @@ -155,7 +158,7 @@ def update_config(self): }, } - self._config.dump_dict(dict(merge({}, current_content, content))) + self._config.dump(dict(merge({}, current_content, content))) def clear(self, verbosity_level: int = 1): if self._remote is not None: @@ -306,7 +309,7 @@ def get_backup_spaces(cls) -> list["BackupSpace"]: VariableLibrary.get_variable("paths.backup_directory") ).glob("*"): tomlf = directory / "config.toml" - if directory.is_dir() and TOMLConfiguration(tomlf).is_valid(): + if directory.is_dir() and TOMLConfiguration(tomlf).exists(): spaces.append(BackupSpace.load_by_uuid(directory.name)) return spaces @@ -327,9 +330,11 @@ def load_by_uuid(cls, unique_id: str) -> "BackupSpace": f"There is no BackupSpace present with the UUID '{unique_id}'." ) - config = TOMLConfiguration(path=path / "config.toml", none_if_unknown_key=True) + config = TOMLConfiguration( + path=path / "config.toml", missing_key_policy=MissingKeyPolicy.RETURN_NONE + ) - if not config.is_valid(): + if not config.exists(): raise InvalidBackupSpaceError( "The BackupSpace could not be loaded because its" "'config.toml' is invalid or missing!" @@ -344,7 +349,7 @@ def load_by_uuid(cls, unique_id: str) -> "BackupSpace": cls = cls( name=config["general.name"], unique_id=unique_id, - space_type=BackupSpaceType.from_name(config["general.type"]), + space_type=BackupSpaceType[config["general.type"]], compression_algorithm=compression.CompressionAlgorithm.from_name( config["general.compression_algorithm"] ), @@ -366,7 +371,7 @@ def load_by_name(cls, name: str) -> "BackupSpace": ): config = TOMLConfiguration(tomlf, create_if_not_exists=False) - if not config.is_valid(): + if not config.exists(): continue if name != config["general.name"]: @@ -426,7 +431,6 @@ def new( cls._config.create() cls.update_config() - cls._config.prepend_no_edit_warning() if cls._remote: with cls._remote(context_verbosity=verbosity_level): @@ -504,7 +508,7 @@ def get_backup_dir(self) -> Path: return self._backup_dir def get_config(self) -> dict: - return self._config.as_dict() + return self._config.asdict() def get_disk_usage(self, verbosity_level: int = 1) -> int: if self._remote is not None: diff --git a/backpy/core/backup/file_backup_space.py b/backpy/core/space/file_backup_space.py similarity index 93% rename from backpy/core/backup/file_backup_space.py rename to backpy/core/space/file_backup_space.py index 4b4a18e..67b6ecc 100644 --- a/backpy/core/backup/file_backup_space.py +++ b/backpy/core/space/file_backup_space.py @@ -9,8 +9,9 @@ from rich.table import Table -from backpy.core.backup import BackupSpace, compression +from backpy.core.backup import RestoreMode, compression from backpy.core.config import VariableLibrary +from backpy.core.space.backup_space import BackupSpace from backpy.core.utils.exceptions import ( InvalidBackupError, InvalidBackupSpaceError, @@ -18,7 +19,7 @@ ) if TYPE_CHECKING: - from backpy import Backup + from backpy.core.backup import Backup class FileBackupSpace(BackupSpace): @@ -32,7 +33,7 @@ def create_backup( verbosity_level: int = 1, ) -> Backup: - from backpy import Backup + from backpy.core.backup import Backup if exclude is None: exclude = [] @@ -53,13 +54,13 @@ def create_backup( def restore_backup( self, unique_id: str, - incremental: bool, + mode: RestoreMode, source: str = "local", force: bool = False, verbosity_level: int = 1, ) -> None: - from backpy import Backup + from backpy.core.backup import Backup backup = Backup.load_by_uuid( backup_space=self, @@ -98,12 +99,12 @@ def restore_backup( start_time = time.time() - if not incremental: + if mode == RestoreMode.CLEAN: if backup.is_full_backup(): if verbosity_level > 1: print( - "Mode is non-incremental and is full backup ... Attempting to " + f"Restore mode is '{mode.name}' and is full backup ... Attempting to " "delete all files ..." ) @@ -154,7 +155,6 @@ def restore_backup( "because its SHA256 sum could not be verified. " "Use --force / -f flag to force the restoring." ) - else: archive_path = backup.get_path() @@ -229,10 +229,10 @@ def new( **kwargs, ) -> "FileBackupSpace": - from backpy import BackupSpaceType + from backpy.core.space import BackupSpaceType parent = super(FileBackupSpace, cls).new( - name=name, space_type=BackupSpaceType.from_name("FILE_SYSTEM"), **kwargs + name=name, space_type=BackupSpaceType.FILE_SYSTEM, **kwargs ) cls = cls.__new__(cls) cls.__dict__.update(parent.__dict__) diff --git a/backpy/core/space/mysql_backup_space.py b/backpy/core/space/mysql_backup_space.py new file mode 100644 index 0000000..4d9805b --- /dev/null +++ b/backpy/core/space/mysql_backup_space.py @@ -0,0 +1,117 @@ +from __future__ import annotations + +from pathlib import Path +from typing import TYPE_CHECKING + +from rich.table import Table + +from backpy.core.encryption.password import encrypt +from backpy.core.space.backup_space import BackupSpace +from backpy.core.utils.exceptions import InvalidBackupSpaceError + +if TYPE_CHECKING: + from backpy.core.backup import Backup + + +class MySQLBackupSpace(BackupSpace): + def create_backup( + self, + comment: str = "", + include: list[str] | None = None, + exclude: list[str] | None = None, + lock: bool = False, + location: str = "all", + verbosity_level: int = 1, + ) -> Backup: + pass + + def restore_backup( + self, + unique_id: str, + incremental: bool, + source: str = "local", + force: bool = False, + verbosity_level: int = 1, + ) -> None: + pass + + def get_info_table(self, verbosity_level: int = 1) -> Table: + return super()._get_info_table( + additional_info_idx=[3], + additional_info={}, + verbosity_level=verbosity_level, + ) + + ##################### + # CLASSMETHODS # + ##################### + + @classmethod + def load_by_uuid(cls, unique_id: str) -> "MySQLBackupSpace": + + parent = super(MySQLBackupSpace, cls).load_by_uuid(unique_id=unique_id) + cls = cls.__new__(cls) + cls.__dict__.update(parent.__dict__) + + if cls._type.name != "MySQL_DATABASE": + raise InvalidBackupSpaceError( + "The loaded BackupSpace is not a MySQLBackupSpace!" + ) + + cls._file_path = Path(cls._config["file_system.path"]) + + return cls + + @classmethod + def load_by_name(cls, name: str) -> "MySQLBackupSpace": + + parent = super(MySQLBackupSpace, cls).load_by_name(name=name) + cls = cls.__new__(cls) + cls.__dict__.update(parent.__dict__) + + if cls._type.name != "MySQL_DATABASE": + raise InvalidBackupSpaceError( + "The loaded BackupSpace is not a MySQLBackupSpace!" + ) + + cls._file_path = Path(cls._config["file_system.path"]) + + return cls + + @classmethod + def new( + cls, + name: str, + hostname: str, + port: int, + username: str, + password: str, + databases: list[str], + tables: list[str], + **kwargs, + ) -> "MySQLBackupSpace": + + from backpy.core.space import BackupSpaceType + + parent = super(MySQLBackupSpace, cls).new( + name=name, + space_type=BackupSpaceType.MYSQL_DATABASE, + **kwargs, + ) + cls = cls.__new__(cls) + cls.__dict__.update(parent.__dict__) + + cls._hostname = hostname + cls._config["mysql.hostname"] = hostname + cls._port = port + cls._config["mysql.port"] = port + cls._username = username + cls._config["mysql.username"] = username + cls._password = password + cls._config["mysql.password"] = encrypt(password) + cls._databases = databases + cls._config["mysql.databases"] = tables + cls._tables = tables + cls._config["mysql.tables"] = tables + + return cls diff --git a/backpy/core/space/types.py b/backpy/core/space/types.py new file mode 100644 index 0000000..1e912bc --- /dev/null +++ b/backpy/core/space/types.py @@ -0,0 +1,49 @@ +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING, Type + +from backpy.core.backup import RestoreMode +from backpy.core.space.file_backup_space import FileBackupSpace +from backpy.core.space.mysql_backup_space import MySQLBackupSpace +from backpy.core.utils.enum import Enum + +if TYPE_CHECKING: + from backpy.core.space import BackupSpace + +__all__ = ["BackupSpaceType"] + + +@dataclass +class BackupSpaceTypeData: + full_name: str + description: str + use_exclusion: bool + use_inclusion: bool + supported_restore_modes: list[RestoreMode] + child_class: Type[BackupSpace] + + +class BackupSpaceType(BackupSpaceTypeData, Enum): + + MYSQL_DATABASE = ( + "MySQL/MariaDB Database Backup Space", + "Backup-Space of a MariaDB or MySQL database and its tables.", + True, + True, + [RestoreMode.OVERWRITE, RestoreMode.CLEAN], + MySQLBackupSpace, + ) + FILE_SYSTEM = ( + "File System Backup Space", + "Backup-Space of one or more files and/or directories.", + True, + True, + [ + RestoreMode.OVERWRITE, + RestoreMode.CLEAN, + RestoreMode.REPLACE, + RestoreMode.MERGE, + ], + FileBackupSpace, + ) diff --git a/backpy/core/utils/__init__.py b/backpy/core/utils/__init__.py index 88cc39b..357d8c2 100644 --- a/backpy/core/utils/__init__.py +++ b/backpy/core/utils/__init__.py @@ -1,5 +1,15 @@ +from __future__ import annotations + from backpy.core.utils import exceptions from backpy.core.utils.times import TimeObject -from backpy.core.utils.utils import bytes2str, calculate_sha256sum +from backpy.core.utils.utils import bytes2str, str2bytes, calculate_sha256sum +from backpy.core.utils.enum import Enum -__all__ = ["exceptions", "TimeObject", "bytes2str", "calculate_sha256sum"] +__all__ = [ + "exceptions", + "TimeObject", + "bytes2str", + "str2bytes", + "calculate_sha256sum", + "Enum", +] diff --git a/backpy/core/utils/enum.py b/backpy/core/utils/enum.py new file mode 100644 index 0000000..c0a16ce --- /dev/null +++ b/backpy/core/utils/enum.py @@ -0,0 +1,28 @@ +from enum import Enum as PyEnum +from enum import EnumMeta as PyEnumMeta + + +# Based on the concept from https://stackoverflow.com/a/24717640 +class EnumMeta(PyEnumMeta): + def __getitem__(self, item: str): + try: + return super().__getitem__(item) + except KeyError: + try: + return super().__getitem__(item.upper()) + except KeyError: + raise KeyError(item) + + +class Enum(PyEnum, metaclass=EnumMeta): + @classmethod + def names(cls): + return list(cls.__members__.keys()) + + @classmethod + def values(cls): + return list(cls.__members__.values()) + + @classmethod + def has_member(cls, member: str): + return member in cls.__members__ diff --git a/backpy/core/utils/exceptions.py b/backpy/core/utils/exceptions.py index fec4767..2633f60 100644 --- a/backpy/core/utils/exceptions.py +++ b/backpy/core/utils/exceptions.py @@ -46,3 +46,8 @@ def __init__(self, message: str) -> None: class BackupLimitExceededError(Exception): def __init__(self, message: str) -> None: super().__init__(message) + + +class InvalidDatabaseException(Exception): + def __init__(self, message: str) -> None: + super().__init__(message) diff --git a/docs/Makefile b/docs/Makefile index d0c3cbf..d4bb2cb 100644 --- a/docs/Makefile +++ b/docs/Makefile @@ -5,8 +5,8 @@ # from the environment for the first two. SPHINXOPTS ?= SPHINXBUILD ?= sphinx-build -SOURCEDIR = source -BUILDDIR = build +SOURCEDIR = . +BUILDDIR = _build # Put it first so that "make" without argument is like "make help". help: diff --git a/docs/_extensions/no_ansi.py b/docs/_extensions/no_ansi.py new file mode 100644 index 0000000..f504b08 --- /dev/null +++ b/docs/_extensions/no_ansi.py @@ -0,0 +1,39 @@ +# Transparency notice: +# A substantial amount of this extension's code was generated +# by the generative AI ChatGPT 5.1 and modified by the +# developer. + +import re + +from docutils import nodes +from sphinx.application import Sphinx + +COLOR_RE = re.compile(r"\x1b\[38;2;\d+;\d+;\d+m") +ANSI_RE = re.compile(r"\x1b\[[0-9;]*m") + + +def clean_ansi(text: str) -> str: + text = COLOR_RE.sub("", text) + return ANSI_RE.sub("", text) + + +def strip_ansi_from_nodes(node): + for child in node.traverse(nodes.Text): + original = child.astext() + cleaned = clean_ansi(original) + + if cleaned != original: + child.parent.replace(child, nodes.Text(cleaned)) + + +def on_doctree_resolved(app, doctree, docname): + strip_ansi_from_nodes(doctree) + + +def setup(app: Sphinx): + app.connect("doctree-resolved", on_doctree_resolved) + return { + "version": "2.0", + "parallel_read_safe": True, + "parallel_write_safe": True, + } diff --git a/docs/_static/custom.css b/docs/_static/custom.css new file mode 100644 index 0000000..d86b033 --- /dev/null +++ b/docs/_static/custom.css @@ -0,0 +1,38 @@ +/* + Transparency notice: + A substantial amount of this CSS code was generated + by the generative AI Claude Sonnet 4.5 and modified by the + developer. +*/ + +div.sd-card { + border-radius: 10px; +} + +div.sd-card.principle { + border-left: 3px solid #4a4a95; +} + +div.sd-card.phase-1 { + border-left: 4px solid #d20f39; +} + +div.sd-card.phase-2 { + border-left: 4px solid #e64553; +} + +div.sd-card.phase-3 { + border-left: 4px solid #df8e1d; +} + +div.sd-card.phase-4 { + border-left: 4px solid #df8e1d; +} + +div.sd-card.phase-5 { + border-left: 4px solid #40a02b; +} + +div.sd-card.phase-6 { + border-left: 4px solid #7287fd; +} diff --git a/docs/_static/fonts/fira_sans/FiraSans-Bold.ttf b/docs/_static/fonts/fira_sans/FiraSans-Bold.ttf new file mode 100644 index 0000000..e3593fb Binary files /dev/null and b/docs/_static/fonts/fira_sans/FiraSans-Bold.ttf differ diff --git a/docs/_static/fonts/fira_sans/FiraSans-BoldItalic.ttf b/docs/_static/fonts/fira_sans/FiraSans-BoldItalic.ttf new file mode 100644 index 0000000..305b0b8 Binary files /dev/null and b/docs/_static/fonts/fira_sans/FiraSans-BoldItalic.ttf differ diff --git a/docs/_static/fonts/fira_sans/FiraSans-Italic.ttf b/docs/_static/fonts/fira_sans/FiraSans-Italic.ttf new file mode 100644 index 0000000..27d32ed Binary files /dev/null and b/docs/_static/fonts/fira_sans/FiraSans-Italic.ttf differ diff --git a/docs/_static/fonts/fira_sans/FiraSans-Regular.ttf b/docs/_static/fonts/fira_sans/FiraSans-Regular.ttf new file mode 100644 index 0000000..6f80647 Binary files /dev/null and b/docs/_static/fonts/fira_sans/FiraSans-Regular.ttf differ diff --git a/docs/_static/fonts/jetbrains_mono/JetBrainsMono-Regular.ttf b/docs/_static/fonts/jetbrains_mono/JetBrainsMono-Regular.ttf new file mode 100644 index 0000000..436c982 Binary files /dev/null and b/docs/_static/fonts/jetbrains_mono/JetBrainsMono-Regular.ttf differ diff --git a/docs/_static/logos/backpy_header_dark.png b/docs/_static/logos/backpy_header_dark.png new file mode 100644 index 0000000..a354bb7 Binary files /dev/null and b/docs/_static/logos/backpy_header_dark.png differ diff --git a/docs/_static/logos/backpy_header_light.png b/docs/_static/logos/backpy_header_light.png new file mode 100644 index 0000000..5e5de5b Binary files /dev/null and b/docs/_static/logos/backpy_header_light.png differ diff --git a/docs/_static/logos/backpy_icon_dark.png b/docs/_static/logos/backpy_icon_dark.png new file mode 100644 index 0000000..a399b11 Binary files /dev/null and b/docs/_static/logos/backpy_icon_dark.png differ diff --git a/docs/_static/logos/backpy_icon_light.png b/docs/_static/logos/backpy_icon_light.png new file mode 100644 index 0000000..1ec3a3e Binary files /dev/null and b/docs/_static/logos/backpy_icon_light.png differ diff --git a/docs/_static/logos/backpy_logo_dark.png b/docs/_static/logos/backpy_logo_dark.png new file mode 100644 index 0000000..8c32a0d Binary files /dev/null and b/docs/_static/logos/backpy_logo_dark.png differ diff --git a/docs/_static/logos/backpy_logo_light.png b/docs/_static/logos/backpy_logo_light.png new file mode 100644 index 0000000..2a90639 Binary files /dev/null and b/docs/_static/logos/backpy_logo_light.png differ diff --git a/docs/_templates/partials/webfonts.html b/docs/_templates/partials/webfonts.html new file mode 100644 index 0000000..8aecdee --- /dev/null +++ b/docs/_templates/partials/webfonts.html @@ -0,0 +1,51 @@ + diff --git a/docs/about/acknowledgements.rst b/docs/about/acknowledgements.rst new file mode 100644 index 0000000..de40db6 --- /dev/null +++ b/docs/about/acknowledgements.rst @@ -0,0 +1,21 @@ +.. _acknowledgements: + +**************** +Acknowledgements +**************** + + +Documentation +------------- + +This documentation is partially inspired by the documentation of +the documentations of the Python packages `pyvisgen `_, +`astropy `_. + +While no substantial code segments were adapted, this documentation makes use of +packages and tools (e.g. ``automodapi`` or ``towncrier``) which are also used +in these projects. +Especially the page structure of the :ref:`api-reference`'s source code, is inspired by +the `pyvisgen `_ package. + +All of their licenses are listed on our :ref:`license` page. diff --git a/docs/about/changelog.rst b/docs/about/changelog.rst new file mode 100644 index 0000000..30a8362 --- /dev/null +++ b/docs/about/changelog.rst @@ -0,0 +1,7 @@ +.. _changelog: + +********* +Changelog +********* + +.. include:: ../changes/CHANGELOG.rst diff --git a/docs/about/index.rst b/docs/about/index.rst new file mode 100644 index 0000000..778a029 --- /dev/null +++ b/docs/about/index.rst @@ -0,0 +1,56 @@ +.. _about: + +**************** +About ``backpy`` +**************** + +.. grid:: 2 + :class-row: surface + + .. grid-item-card:: :octicon:`project-roadmap` Roadmap + :link: roadmap + :link-type: ref + + Want to know what is planned for the future? Find out here! + + .. grid-item-card:: :octicon:`law` License + :link: license + :link-type: ref + + Here you find the license for backpy and its assets. + +.. grid:: 2 + :class-row: surface + + .. grid-item-card:: :octicon:`heart` Acknowledgements + :link: acknowledgements + :link-type: ref + + Here you can find the acknowledgements of other works + that inspired parts of this project. + + .. grid-item-card:: :iconify:`mingcute:ai-line` Usage of Generative AI + :link: use-of-gen-ai + :link-type: ref + + Here you can find a statement and several principles about the usage of generative + artificial intelligence in this project. + +.. grid:: 1 + :class-row: surface + + .. grid-item-card:: :octicon:`history` Changelog + :link: changelog + :link-type: ref + + Here you can track the changes of the package over the course + of time. + +.. toctree:: + :hidden: + + roadmap + license + acknowledgements + usage-of-generative-ai + changelog diff --git a/docs/about/license.rst b/docs/about/license.rst new file mode 100644 index 0000000..1246d00 --- /dev/null +++ b/docs/about/license.rst @@ -0,0 +1,18 @@ +.. _license: + +******* +License +******* + +.. note:: + This project is primarily licensed under the ``GNU LGPL-3.0`` license. + However, certain files are licensed under the ``MIT`` license. The + corresponding copyright notice is included in those file's headers. + +Main License +------------ + +.. include:: ../../LICENSE + :literal: + +.. include:: ../../ASSETS_LEGAL.rst diff --git a/docs/about/roadmap.rst b/docs/about/roadmap.rst new file mode 100644 index 0000000..70c9a3d --- /dev/null +++ b/docs/about/roadmap.rst @@ -0,0 +1,56 @@ +.. _roadmap: + +******* +Roadmap +******* + +.. card:: + :class-card: phase-1 + + **Phase 1 (pre-release)** + ^^^ + - Documentation for API and CLI (via docstrings and documentation website) + - User-guides and troubleshooting pages for documentation + - Publish hosted version of documentation + + +.. card:: + :class-card: phase-2 + + **Phase 2 (pre-release)** + ^^^ + - MariaDB / MySQL-database backups + - Pytest tests and GitHub CI (mainly for on Linux-based systems) + +.. card:: + :class-card: phase-3 + + **Phase 3 (pre-release)** + ^^^ + - Publish package on PyPI + - Publish package in APT repository + +.. card:: + :class-card: phase-4 + + **Phase 4** + ^^^ + - Encryption for saved backup-archives + - Migration and export of backpy backups + - Status notifications (e.g. e-mail or SMS if backups fail) + - Logging for manual and automatic backups + +.. card:: + :class-card: phase-5 + + **Phase 5** + ^^^ + - Encryption for saved backup-archives + +.. card:: + :class-card: phase-6 + + **Phase 6 (aka. the "maybe" list)** + ^^^ + - Webinterface for monitoring backups + - Webinterface for interacting with backpy \ No newline at end of file diff --git a/docs/about/usage-of-generative-ai.rst b/docs/about/usage-of-generative-ai.rst new file mode 100644 index 0000000..27a5924 --- /dev/null +++ b/docs/about/usage-of-generative-ai.rst @@ -0,0 +1,98 @@ +.. _use-of-gen-ai: + +********************** +Usage of Generative AI +********************** + +Statement and Principles +------------------------ + +The usage of generative artificial intelligence ("GenAI") in programming has the potential to optimize the workflows +of developers, assist in debugging and testing programs and generating repetitive code. However there are inherent risks +in using GenAI without proper human supervision. +Most importantly, the ethical justifiability of using GenAI in coding is highly dependent on the transparency and responsible +behavior of the developers. [1]_ + +In this project, the following principles were applied regarding the usage of GenAI for coding: + +.. card:: + :class-card: principle + + **1st Principle** + ^^^ + If GenAI is used for generating **substantial amounts of code** (e.g. multiple lines, entire functions, classes + or files) a transparency notice has to be provided stating that + + * GenAI was used to generate the code, + * specifying which parts of the code were generated + * using which model and + * whether the code was modified by human developers. + + In any case the usage must be permitted by the *Terms of Use* (or comparable legal usage requirements) + of the used model and may not violate any current laws. If the *Terms of Use* require additional steps to + allow the usage of the code, these must be met or the code may not be used. + +.. card:: + :class-card: principle + + **2nd Principle** + ^^^ + + Since GenAI is subject to complications like biases, hallucinations and is highly dependent on the given input, + generated contents should never be used without checking the content manually. Publishing generated code without + review poses potential risks for the stability of the program and the devices used to run it. + +.. card:: + :class-card: principle + + **3rd Principle** + ^^^ + + There are certain situations in which using GenAI can be advantageous and there are situations in which + it should not be used. + In general, using GenAI should not be first solution when encountering problems. + It is a tool to help the developers but should not replace critical and analytic thinking and problem + solving. + + This project generally tries to apply the following rule of thumb for some of the most important examples: + + .. table:: Sensible vs Not Sensible - Using GenAI in Programming + + ====================================================== ========================================== + Sensible Not Sensible + ====================================================== ========================================== + Generating boilerplate / repetitive code Generating large algorithms + Additional debugging checks of code Generating entire parts of the codebase + Test development (primarily for checking edge cases) Creating safety critical parts of the code + Documenting code Documenting code + ====================================================== ========================================== + + + .. note:: + + The aspect of *Documenting code* appears in both columns of the table above since this is a debatable application + of GenAI and **should be decided from case to case**. + + On one hand documenting similar functions and wrappers is repetitive and time consuming, so it could make + sense to save time by generating this (especially using in-line completion tools). On the other hand, the person writing + the code should be the one to document it since he/she knows the functionality of the code best and therefore + should be able explain it. + +Example: Transparency Notice +---------------------------- + +.. code:: txt + + Transparency notice + ------------------- + + A substantial amount of this extension's code generated + by the generative AI and modified by the + developer. + + + +References and Further Reading +------------------------------ + +.. [1] Atemkeng, M., Hamlomo, S., Welman, B., Oyetunji, N., Ataei, P., and E Fendji, J. L. K., “Ethics of Software Programming with Generative AI: Is Programming without Generative AI always radical?”, 2024. doi:`10.48550/arXiv.2408.10554 `_. diff --git a/docs/changes/7.docs.rst b/docs/changes/7.docs.rst new file mode 100644 index 0000000..749effb --- /dev/null +++ b/docs/changes/7.docs.rst @@ -0,0 +1 @@ +Prepared docs for usage by newly added modules. diff --git a/docs/changes/tutorial-towncrier.rst b/docs/changes/tutorial-towncrier.rst new file mode 100644 index 0000000..15df174 --- /dev/null +++ b/docs/changes/tutorial-towncrier.rst @@ -0,0 +1,81 @@ +---------------------------------- +Tutorial: How to use ``towncrier`` +---------------------------------- + +We use the python package ``towncrier`` to manage our changelogs. +It can be used to create changelog files (e.g. for pull requests). +When building the docs, these files are collected and merged into +a ``changelog.rst`` file containing the entire changelog of the project. + +Therefore it is mandatory to create changelogs when creating pull requests. +There are two main ways to create a ``towncrier`` changelog. + +Variant 1: Using the ``towncrier`` CLI +-------------------------------------- + +The guided way to generate changelogs, is the CLI of ``towncrier``. +To be able to use it, you have to install the ``backpy`` package for development. +Make sure you also install the optional dependencies ``docs``. + +After just navigate to your local backpy git repository. +There you can enter the following command + +.. code-block:: bash + + towncrier create + +You will be prompted to enter the ``issue number``. +Enter the number of the **pull request** your changes are included in. + +.. code-block:: + + > Issue number (`+` if none): █ + +Then you have to enter the type of the changes: +Choose the appropriate label for your changes. If you have changes with different types, **create a changelog for every change**. + +.. code-block:: + + > Fragment type (api, cli, docs, bugfix): █ + +Now a text editor should open where you can specify your changes. +Keep the description short and concise. You can use sphinx's ``rst`` syntax. + + **Tip:** Refer to this cheat sheet to look up possible ``rst`` commands: https://sphinx-tutorial.readthedocs.io/cheatsheet/ + +Finally, save your document and commit it to the branch you created the pull request for. + +Variant 2: Manually Creating Files +---------------------------------- + +The shortest way to create your changelog files is creating them yourself. +Therefore navigate to your local ``backpy`` repository. +Inside the repository navigate to ``docs/changes``. + +.. code-block:: + + cd docs/changes + +Create a file with the following naming scheme: + +.. code-block:: + + ..rst + +The possible types are: + +============ ======================= +``api`` API Changes +``cli`` CLI Changes +``docs`` Documentation Changes +``bugfix`` Bug Fixes +============ ======================= + +Open the created file with a editor of your choice and document your changes. +Keep the description short and concise. You can use sphinx's ``rst`` syntax. + + **Tip:** Refer to this cheat sheet to look up possible ``rst`` commands: https://sphinx-tutorial.readthedocs.io/cheatsheet/ + +Finally, save your document and commit it to the branch you created the pull request for. + + diff --git a/docs/concepts/backup-spaces.rst b/docs/concepts/backup-spaces.rst new file mode 100644 index 0000000..e69de29 diff --git a/docs/concepts/backups-and-restore.rst b/docs/concepts/backups-and-restore.rst new file mode 100644 index 0000000..e69de29 diff --git a/docs/concepts/encryption.rst b/docs/concepts/encryption.rst new file mode 100644 index 0000000..2faa9e6 --- /dev/null +++ b/docs/concepts/encryption.rst @@ -0,0 +1,6 @@ +.. _concepts_encryption: + +********** +Encryption +********** + diff --git a/docs/concepts/include-exclude.rst b/docs/concepts/include-exclude.rst new file mode 100644 index 0000000..e69de29 diff --git a/docs/concepts/index.rst b/docs/concepts/index.rst new file mode 100644 index 0000000..f6f081d --- /dev/null +++ b/docs/concepts/index.rst @@ -0,0 +1,8 @@ +.. _concepts: + +************** +Basic Concepts +************** + +The following pages contain several guides + diff --git a/docs/concepts/limits-and-auto-deletion.rst b/docs/concepts/limits-and-auto-deletion.rst new file mode 100644 index 0000000..e69de29 diff --git a/docs/concepts/local-vs-remote.rst b/docs/concepts/local-vs-remote.rst new file mode 100644 index 0000000..e69de29 diff --git a/docs/concepts/schedules.rst b/docs/concepts/schedules.rst new file mode 100644 index 0000000..e69de29 diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..26a05a7 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,84 @@ +# Configuration file for the Sphinx documentation builder. +# +# For the full list of built-in configuration values, see the documentation: +# https://www.sphinx-doc.org/en/master/usage/configuration.html + +# -- Project information ----------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information + +import sys +from datetime import datetime +from pathlib import Path + +import backpy.version +from backpy import TOMLConfiguration + +pyproject = TOMLConfiguration(Path(backpy.__file__).parent.parent / "pyproject.toml") +authors = pyproject["project.authors"] +authors = ",".join([author["name"] for author in authors]) +year = datetime.now().year + +version = backpy.version.version + +project = "backpy" +copyright = f"© {year}, {authors}" +author = authors +version = version +release = version + +rst_prolog = f""" +.. |version| replace:: ``{version}`` +""" + +# -- General configuration --------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration + +sys.path.append(str(Path("_extensions").resolve())) + +extensions = [ + "sphinx_iconify", + "sphinx_design", + "sphinx_copybutton", + "sphinx_togglebutton", + "sphinx_click", + "sphinx_automodapi.automodapi", + "numpydoc", + "no_ansi", +] + +autosummary_generate = True +autodoc_typehints = "description" +numpydoc_show_class_members = False + +automodapi_toctreedirnm = "_generated" +automodapi_inheritance_diagram = False + +templates_path = ["_templates"] +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] + +# -- Options for HTMLoutput ------------------------------------------------- +# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output + +html_theme = "shibuya" +html_static_path = ["_static"] +html_css_files = ["custom.css"] + +html_favicon = "_static/logos/backpy_icon_dark.png" + +html_theme_options = { + "light_logo": "_static/logos/backpy_header_light.png", + "dark_logo": "_static/logos/backpy_header_dark.png", + "github_url": "https://github.com/tgross03/backpy", + "accent_color": "blue", + "announcement": "This package is still in development and not stable at this time! " + "Features and functionalities might not work as expected.", + "show_ai_links": False, +} + +html_context = { + "source_type": "github", + "source_user": "tgross03", + "source_repo": "backpy", + "source_version": "main", # Optional + "source_docs_path": "/docs/", # Optional +} diff --git a/docs/getting-started/index.rst b/docs/getting-started/index.rst new file mode 100644 index 0000000..891c99d --- /dev/null +++ b/docs/getting-started/index.rst @@ -0,0 +1,31 @@ +.. _getting-started: + +*************** +Getting Started +*************** + +You are new to ``backpy`` or want to read up on the first steps again? +Then you are at the right place. + +.. grid:: 2 + :class-row: surface + + .. grid-item-card:: :octicon:`move-to-bottom` Installation + :link: installation + :link-type: ref + + Here you can read up on the ways to install backpy + on your system. + + .. grid-item-card:: :octicon:`goal` First Steps + :link: quickstart + :link-type: ref + + This short guide quickly describes the first steps + to getting started with backpy. + +.. toctree:: + :hidden: + + installation + quickstart \ No newline at end of file diff --git a/docs/getting-started/installation.rst b/docs/getting-started/installation.rst new file mode 100644 index 0000000..ceead06 --- /dev/null +++ b/docs/getting-started/installation.rst @@ -0,0 +1,5 @@ +.. _installation: + +************ +Installation +************ diff --git a/docs/getting-started/quickstart.rst b/docs/getting-started/quickstart.rst new file mode 100644 index 0000000..d2c8745 --- /dev/null +++ b/docs/getting-started/quickstart.rst @@ -0,0 +1,11 @@ +.. _quickstart: + +*********** +First Steps +*********** + +.. _interactive-mode: +*Interactive Mode* +------------------ + +The ``backpy`` CLI contains many different subcommands \ No newline at end of file diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..a26bc63 --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,83 @@ +.. _backpy: + +.. image:: /_static/logos/backpy_logo_light.png + :width: 100% + :align: center + :class: light-only + :alt: Insert backpy logo here + +.. image:: /_static/logos/backpy_logo_dark.png + :width: 100% + :align: center + :class: dark-only + :alt: Insert backpy logo here + +**Version:** |version| + +``backpy`` is a Python-based package for creating backups of files, directories and +SQL databases. It features an extensive and well-documented Command-Line Interface (CLI) +to interact with the system and also an easy-to-use Python-API. + +.. warning:: + This package is still in development and not stable at this time! + Features and functionalities might not work as expected. + +Useful links +------------ + +.. grid:: 3 + :class-row: surface + + .. grid-item-card:: :octicon:`zap` Getting Started + :link: getting-started + :link-type: ref + + New to backpy? This is the place you want to go to! + + .. grid-item-card:: :octicon:`bug` Troubleshooting + :link: troubleshooting + :link-type: ref + + Having troubles with the package? You might find an answer here! + + .. grid-item-card:: :octicon:`git-compare` Workflows + :link: workflows + :link-type: ref + + Here you can find guides for typical workflows for using backpy. + +.. grid:: 3 + :class-row: surface + + .. grid-item-card:: :octicon:`repo` Basic Concepts + :link: concepts + :link-type: ref + + Want to learn more about the structure of backpy? + Then you should go here. + + .. grid-item-card:: :octicon:`gear` CLI / API Reference + :link: reference + :link-type: ref + + Here you can find the full references for the CLI and API + of backpy. + + .. grid-item-card:: :octicon:`question` About + :link: about + :link-type: ref + + Here get to know more about the developers, package and legal stuff. + + +.. toctree:: + :includehidden: + :hidden: + + getting-started/index + concepts/index + workflows/index + troubleshooting/index + reference/index + about/index + diff --git a/docs/make.bat b/docs/make.bat index 747ffb7..32bb245 100644 --- a/docs/make.bat +++ b/docs/make.bat @@ -7,8 +7,8 @@ REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) -set SOURCEDIR=source -set BUILDDIR=build +set SOURCEDIR=. +set BUILDDIR=_build %SPHINXBUILD% >NUL 2>NUL if errorlevel 9009 ( diff --git a/docs/reference/api/cli/colors.rst b/docs/reference/api/cli/colors.rst new file mode 100644 index 0000000..99f1f45 --- /dev/null +++ b/docs/reference/api/cli/colors.rst @@ -0,0 +1,14 @@ +.. _api-cli-colors: + +****************************** +Colors (``backpy.cli.colors``) +****************************** + +.. currentmodule:: backpy.cli.colors + +The :mod:`backpy.cli.colors` submodule contains the color palettes used in the :ref:`CLI `. +It uses the color palettes from `Catppuccin `_ and translates them into ANSI codes +that can be displayed as colors in the terminal. + +.. automodapi:: backpy.cli.colors + :no-heading: diff --git a/docs/reference/api/cli/elements.rst b/docs/reference/api/cli/elements.rst new file mode 100644 index 0000000..2d9f93c --- /dev/null +++ b/docs/reference/api/cli/elements.rst @@ -0,0 +1,17 @@ +.. _api-cli-elements: + +********************************** +Elements (``backpy.cli.elements``) +********************************** + +.. currentmodule:: backpy.cli.elements + +The :mod:`backpy.cli.elements` submodule contains functions and classes +used to interact with the :ref:`CLI `. + +The contained classes are used to prompt the user to enter values (e.g. in :ref:`interactive-mode`) or +to confirm a command. + + +.. automodapi:: backpy.cli.elements + :no-heading: diff --git a/docs/reference/api/cli/index.rst b/docs/reference/api/cli/index.rst new file mode 100644 index 0000000..21bf5e4 --- /dev/null +++ b/docs/reference/api/cli/index.rst @@ -0,0 +1,19 @@ +.. _api-cli: + +******************** +CLI (``backpy.cli``) +******************** + +.. currentmodule:: backpy.cli + +The :mod:`backpy.cli` module contains functions and classes +used to interact with the :ref:`CLI `. + +Submodules +---------- + +.. toctree:: + :maxdepth: 1 + + colors + elements diff --git a/docs/reference/api/core/backup/compression.rst b/docs/reference/api/core/backup/compression.rst new file mode 100644 index 0000000..91ce39c --- /dev/null +++ b/docs/reference/api/core/backup/compression.rst @@ -0,0 +1,13 @@ +.. _api-backup-compression: + +************************************************ +Compression (``backpy.core.backup.compression``) +************************************************ + +.. currentmodule:: backpy.core.backup.compression + +The :mod:`backpy.core.backup.compression` submodule contains functions and classes +to deal with file compression. + +.. automodapi:: backpy.core.backup.compression + :no-heading: diff --git a/docs/reference/api/core/backup/index.rst b/docs/reference/api/core/backup/index.rst new file mode 100644 index 0000000..7162273 --- /dev/null +++ b/docs/reference/api/core/backup/index.rst @@ -0,0 +1,21 @@ +.. _api-backup: + +******************************* +Backup (``backpy.core.backup``) +******************************* + +.. currentmodule:: backpy.core.backup + +The :mod:`backpy.core.backup` submodule contains classes dealing with the manual and +automatic creation and management of backups. + +Submodules +^^^^^^^^^^ + +.. toctree:: + :maxdepth: 1 + + compression + +.. automodapi:: backpy.core.backup + :no-heading: diff --git a/docs/reference/api/core/config/index.rst b/docs/reference/api/core/config/index.rst new file mode 100644 index 0000000..4d7af0e --- /dev/null +++ b/docs/reference/api/core/config/index.rst @@ -0,0 +1,19 @@ +.. _api-config: + +******************************* +Config (``backpy.core.config``) +******************************* + +.. currentmodule:: backpy.core.config + +The :mod:`backpy.core.config` submodule contains classes to enable the management +of configuration files for many applications like global configurations, backup +configurations and many more. + +.. toctree:: + :maxdepth: 1 + + compression + +.. automodapi:: backpy.core.config + :no-heading: diff --git a/docs/reference/api/core/encryption/index.rst b/docs/reference/api/core/encryption/index.rst new file mode 100644 index 0000000..bc7b76b --- /dev/null +++ b/docs/reference/api/core/encryption/index.rst @@ -0,0 +1,22 @@ +.. _api-encryption: + +*************************************** +Encryption (``backpy.core.encryption``) +*************************************** + +.. currentmodule:: backpy.core.encryption + +The :mod:`backpy.core.encryption` submodule contains classes and functions +to handle the encryption of passwords and passphrases. + +Submodules +^^^^^^^^^^ + +.. toctree:: + :maxdepth: 1 + + password + +.. automodapi:: backpy.core.encryption + :no-heading: + :include-all-objects: diff --git a/docs/reference/api/core/encryption/password.rst b/docs/reference/api/core/encryption/password.rst new file mode 100644 index 0000000..3d2f322 --- /dev/null +++ b/docs/reference/api/core/encryption/password.rst @@ -0,0 +1,15 @@ +.. _api-encryption-password: + +****************************************** +Password (``backpy.core.remote.password``) +****************************************** + +.. currentmodule:: backpy.core.encryption.password + +The :mod:`backpy.core.encryption.password` submodule contains functions to handle encryption +and decryption of passwords and passphrases so that they can be stored without immediate +human readability. + + +.. automodapi:: backpy.core.encryption.password + :no-heading: diff --git a/docs/reference/api/core/index.rst b/docs/reference/api/core/index.rst new file mode 100644 index 0000000..b1fc0ec --- /dev/null +++ b/docs/reference/api/core/index.rst @@ -0,0 +1,18 @@ +.. _api-core: + +********************** +Core (``backpy.core``) +********************** + +.. currentmodule:: backpy.core + +The :mod:`backpy.core` contains the core functions of ``backpy``. + +Submodules +---------- + +.. toctree:: + :glob: + :maxdepth: 2 + + */index diff --git a/docs/reference/api/core/remote/index.rst b/docs/reference/api/core/remote/index.rst new file mode 100644 index 0000000..acd1a6c --- /dev/null +++ b/docs/reference/api/core/remote/index.rst @@ -0,0 +1,15 @@ +.. _api-remote: + +******************************* +Remote (``backpy.core.remote``) +******************************* + +.. currentmodule:: backpy.core.remote + +The :mod:`backpy.core.remote` submodule contains classes to enable the management +of configuration files for many applications like global configurations, backup +configurations and many more. + +.. automodapi:: backpy.core.remote + :no-heading: + :include-all-objects: diff --git a/docs/reference/api/core/space/index.rst b/docs/reference/api/core/space/index.rst new file mode 100644 index 0000000..8eeb377 --- /dev/null +++ b/docs/reference/api/core/space/index.rst @@ -0,0 +1,14 @@ +.. _api-space: + +***************************** +Space (``backpy.core.space``) +***************************** + +.. currentmodule:: backpy.core.space + +The :mod:`backpy.core.space` submodule contains classes and functions to manage +different types of backup spaces. + +.. automodapi:: backpy.core.space + :no-heading: + :include-all-objects: diff --git a/docs/reference/api/core/utils/exceptions.rst b/docs/reference/api/core/utils/exceptions.rst new file mode 100644 index 0000000..e76819c --- /dev/null +++ b/docs/reference/api/core/utils/exceptions.rst @@ -0,0 +1,14 @@ +.. _api-utils-exceptions: + +********************************************* +Exceptions (``backpy.core.utils.exceptions``) +********************************************* + +.. currentmodule:: backpy.core.utils.exceptions + +The :mod:`backpy.core.utils.exceptions` contains the exceptions used in +the API and CLI of the package. + +.. automodapi:: backpy.core.utils.exceptions + :no-heading: + :include-all-objects: diff --git a/docs/reference/api/core/utils/index.rst b/docs/reference/api/core/utils/index.rst new file mode 100644 index 0000000..5df23c7 --- /dev/null +++ b/docs/reference/api/core/utils/index.rst @@ -0,0 +1,22 @@ +.. _api-utils: + +***************************** +Utils (``backpy.core.utils``) +***************************** + +.. currentmodule:: backpy.core.utils + +The :mod:`backpy.core.utils` submodule contains classes and functions to manage +different types of backup spaces. + +Submodules +^^^^^^^^^^ + +.. toctree:: + :maxdepth: 1 + + exceptions + +.. automodapi:: backpy.core.utils + :no-heading: + :include-all-objects: diff --git a/docs/reference/api/index.rst b/docs/reference/api/index.rst new file mode 100644 index 0000000..b792d9a --- /dev/null +++ b/docs/reference/api/index.rst @@ -0,0 +1,11 @@ +.. _api-reference: + +************* +API Reference +************* + +.. toctree:: + :maxdepth: 2 + + cli/index + core/index diff --git a/docs/reference/cli/backup.rst b/docs/reference/cli/backup.rst new file mode 100644 index 0000000..8235ce8 --- /dev/null +++ b/docs/reference/cli/backup.rst @@ -0,0 +1,9 @@ +.. _cli-backup: + +********** +``backup`` +********** + +.. click:: backpy.cli.backup.commands:command + :prog: backpy backup + :nested: full \ No newline at end of file diff --git a/docs/reference/cli/config.rst b/docs/reference/cli/config.rst new file mode 100644 index 0000000..0a73322 --- /dev/null +++ b/docs/reference/cli/config.rst @@ -0,0 +1,9 @@ +.. _cli-config: + +********** +``config`` +********** + +.. click:: backpy.cli.config.commands:command + :prog: backpy config + :nested: full \ No newline at end of file diff --git a/docs/reference/cli/index.rst b/docs/reference/cli/index.rst new file mode 100644 index 0000000..1825b36 --- /dev/null +++ b/docs/reference/cli/index.rst @@ -0,0 +1,70 @@ +.. _cli-reference: + +************* +CLI Reference +************* + + +The ``backpy`` CLI uses one general command: + +.. code-block:: + + backpy [OPTIONS] COMMAND [ARGS] ... + +Options +------- + +--version, -v Displays the current version of backpy. + +--info Displays some information about backpy. + +Subcommands +----------- + +.. grid:: 2 + :class-row: surface + + .. grid-item-card:: :octicon:`file-zip` ``backup`` + :link: cli-backup + :link-type: ref + + Actions related to creating and managing backups. + + .. grid-item-card:: :octicon:`sliders` ``config`` + :link: cli-config + :link-type: ref + + Actions related to configuring the package. + +.. grid:: 2 + :class-row: surface + + .. grid-item-card:: :octicon:`server` ``remote`` + :link: cli-remote + :link-type: ref + + Actions related to remote locations to save backups at. + + .. grid-item-card:: :octicon:`clock` ``schedule`` + :link: cli-schedule + :link-type: ref + + Actions related to scheduling for automatic backups. + +.. grid:: 1 + :class-row: surface + + .. grid-item-card:: :octicon:`archive` ``space`` + :link: cli-space + :link-type: ref + + Actions related to creating and managing backup spaces. + +.. toctree:: + :hidden: + + backup + config + remote + schedule + space \ No newline at end of file diff --git a/docs/reference/cli/remote.rst b/docs/reference/cli/remote.rst new file mode 100644 index 0000000..bacffbb --- /dev/null +++ b/docs/reference/cli/remote.rst @@ -0,0 +1,9 @@ +.. _cli-remote: + +********** +``remote`` +********** + +.. click:: backpy.cli.remote.commands:command + :prog: backpy remote + :nested: full \ No newline at end of file diff --git a/docs/reference/cli/schedule.rst b/docs/reference/cli/schedule.rst new file mode 100644 index 0000000..1105b2b --- /dev/null +++ b/docs/reference/cli/schedule.rst @@ -0,0 +1,9 @@ +.. _cli-schedule: + +************ +``schedule`` +************ + +.. click:: backpy.cli.schedule.commands:command + :prog: backpy schedule + :nested: full \ No newline at end of file diff --git a/docs/reference/cli/space.rst b/docs/reference/cli/space.rst new file mode 100644 index 0000000..d2d6056 --- /dev/null +++ b/docs/reference/cli/space.rst @@ -0,0 +1,9 @@ +.. _cli-space: + +********* +``space`` +********* + +.. click:: backpy.cli.space.commands:command + :prog: backpy space + :nested: full \ No newline at end of file diff --git a/docs/reference/index.rst b/docs/reference/index.rst new file mode 100644 index 0000000..c84c3d3 --- /dev/null +++ b/docs/reference/index.rst @@ -0,0 +1,25 @@ +.. _reference: + +********* +Reference +********* + +The following references give a technical overview for the API and CLI of ``backpy``. + +.. grid:: 2 + :class-row: surface + + .. grid-item-card:: :octicon:`command-palette` CLI Reference + :link: cli-reference + :link-type: ref + + .. grid-item-card:: :octicon:`code-square` API Reference + :link: api-reference + :link-type: ref + + +.. toctree:: + :hidden: + + api/index + cli/index \ No newline at end of file diff --git a/docs/source/conf.py b/docs/source/conf.py deleted file mode 100644 index 2b1702e..0000000 --- a/docs/source/conf.py +++ /dev/null @@ -1,26 +0,0 @@ -# Configuration file for the Sphinx documentation builder. -# -# For the full list of built-in configuration values, see the documentation: -# https://www.sphinx-doc.org/en/master/usage/configuration.html - -# -- Project information ----------------------------------------------------- -# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information - -project = "backpy" -copyright = "2025, Tom Groß" -author = "Tom Groß" - -# -- General configuration --------------------------------------------------- -# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration - -extensions = [] - -templates_path = ["_templates"] -exclude_patterns = [] - - -# -- Options for HTML output ------------------------------------------------- -# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output - -html_theme = "alabaster" -html_static_path = ["_static"] diff --git a/docs/source/index.rst b/docs/source/index.rst deleted file mode 100644 index db03ba6..0000000 --- a/docs/source/index.rst +++ /dev/null @@ -1,17 +0,0 @@ -.. backpy documentation master file, created by - sphinx-quickstart on Wed Dec 10 22:28:05 2025. - You can adapt this file completely to your liking, but it should at least - contain the root `toctree` directive. - -backpy documentation -==================== - -Add your content using ``reStructuredText`` syntax. See the -`reStructuredText `_ -documentation for details. - - -.. toctree:: - :maxdepth: 2 - :caption: Contents: - diff --git a/docs/troubleshooting/index.rst b/docs/troubleshooting/index.rst new file mode 100644 index 0000000..daaba30 --- /dev/null +++ b/docs/troubleshooting/index.rst @@ -0,0 +1,6 @@ +.. _troubleshooting: + +*************** +Troubleshooting +*************** + diff --git a/docs/workflows/automation/creating-schedules.rst b/docs/workflows/automation/creating-schedules.rst new file mode 100644 index 0000000..e69de29 diff --git a/docs/workflows/automation/index.rst b/docs/workflows/automation/index.rst new file mode 100644 index 0000000..b114173 --- /dev/null +++ b/docs/workflows/automation/index.rst @@ -0,0 +1,5 @@ +.. _workflows-automation: + +********** +Automation +********** \ No newline at end of file diff --git a/docs/workflows/automation/manage-schedules.rst b/docs/workflows/automation/manage-schedules.rst new file mode 100644 index 0000000..e69de29 diff --git a/docs/workflows/common/creating-backups.rst b/docs/workflows/common/creating-backups.rst new file mode 100644 index 0000000..e69de29 diff --git a/docs/workflows/common/index.rst b/docs/workflows/common/index.rst new file mode 100644 index 0000000..6644904 --- /dev/null +++ b/docs/workflows/common/index.rst @@ -0,0 +1,5 @@ +.. _workflows-common: + +****** +Common +****** diff --git a/docs/workflows/common/locking-backups.rst b/docs/workflows/common/locking-backups.rst new file mode 100644 index 0000000..e69de29 diff --git a/docs/workflows/common/restore-backups.rst b/docs/workflows/common/restore-backups.rst new file mode 100644 index 0000000..e69de29 diff --git a/docs/workflows/index.rst b/docs/workflows/index.rst new file mode 100644 index 0000000..f0c80f9 --- /dev/null +++ b/docs/workflows/index.rst @@ -0,0 +1,53 @@ +.. _workflows: + +********* +Workflows +********* + +The following categories contain guides about different typical workflows while using the ``backpy`` CLI. +These guides' primary motivation is helping you to get used to the basic concept and optimal usage of the package. + +.. note:: + Since the package is built for reproducibility, the guides will primarily talk about using the commands of the CLI + **without** using the ``--interactive`` flag. + Read more in the section about the :ref:`interactive-mode`. + + +.. grid:: 2 + :class-row: surface + + .. grid-item-card:: :octicon:`gear` Setup + :link: workflows-setup + :link-type: ref + + Setting up the package, remotes, backup spaces and more. + + .. grid-item-card:: :octicon:`globe` Common + :link: workflows-common + :link-type: ref + + Day-to-day operations like creating, restoring and locking of backups. + +.. grid:: 2 + :class-row: surface + + .. grid-item-card:: :octicon:`cpu` Automation + :link: workflows-automation + :link-type: ref + + Automating the creation of backups to create an autonomous backup cycle. + + .. grid-item-card:: :octicon:`tools` Maintenance + :link: workflows-maintenance + :link-type: ref + + Checking for problems, cleaning up or migrating the backups. + +.. toctree:: + :includehidden: + :hidden: + + automation/index + common/index + maintenance/index + setup/index \ No newline at end of file diff --git a/docs/workflows/maintenance/cleanup.rst b/docs/workflows/maintenance/cleanup.rst new file mode 100644 index 0000000..e69de29 diff --git a/docs/workflows/maintenance/index.rst b/docs/workflows/maintenance/index.rst new file mode 100644 index 0000000..d6b24e8 --- /dev/null +++ b/docs/workflows/maintenance/index.rst @@ -0,0 +1,5 @@ +.. _workflows-maintenance: + +*********** +Maintenance +*********** diff --git a/docs/workflows/maintenance/migrating-backpy.rst b/docs/workflows/maintenance/migrating-backpy.rst new file mode 100644 index 0000000..e69de29 diff --git a/docs/workflows/maintenance/move-remotes.rst b/docs/workflows/maintenance/move-remotes.rst new file mode 100644 index 0000000..e69de29 diff --git a/docs/workflows/setup/creating-a-remote.rst b/docs/workflows/setup/creating-a-remote.rst new file mode 100644 index 0000000..cddffd8 --- /dev/null +++ b/docs/workflows/setup/creating-a-remote.rst @@ -0,0 +1,99 @@ +.. _workflows-connect-to-remote: + +Creating a Remote +---------------------- + +Connecting to a remote is relatively simple. +You will need to know the following things before doing so: + +``name`` + The name you want to give the remote. This can be an arbitrary one-word name but it has to be exclusive for this remote. +``hostname`` + The hostname or IP of your remote storage (e.g. ``172.217.23.110`` or ``mystoragebox.mydomain.com``) +``username`` + The username of the account that can access the storage server. +``protocol`` + The protocol via which the files should be transferred. Possible values are given in the CLI-reference under :ref:`remote `. + + .. important:: + The remote server has to support the given protocol and all necessary ports (e.g. ``22`` for default SFTP transfers) have to be opened! + + Also note that not every protocol supports every authentication method. + +Authentication method + You have to know via which authentication method you want to log in. In general you can choose between **SSH-Key** or **password** based authentication. + We encourage you to use a public/private key combination to ensure maximum security for your remote storage. + + If you want to use + + 1. **Password**: You do not have to provide extra keywords. You will be asked for the password during the creation process. + 2. **SSH-Key**: You will have to know the location of your **private** keyfile. This requires the previous creation of such a key and the deployment of the public + key on the remote server. For further information on this refer to this page: https://wiki.archlinux.org/title/SSH_keys + +``key`` + This is the location of the keyfile as described above. + +.. note:: + + There are more options you can change depending on your system. Check the reference for :ref:`cli-remote` for further information. + +The next steps depend on your choice of authentication. Choose the right guide for you. + +.. tab-set:: + + .. tab-item:: :octicon:`key` With SSH-Key + + .. code-block:: bash + + backpy remote create --name --hostname --username --protocol --key + + After sending the command, you will be asked to enter the passphrase for the SSH key. + Since an SSH key does not require a passphrase this can be empty. + + .. code-block:: + + > Enter the passphrase for the SSH key (may be empty): █ + + This passphrase will only be saved in your local config for this remote. + The passphrase is not saved in clear text but as an encrypted token. + Read more about the encryption of ``backpy`` in the concept :ref:`concepts_encryption`. + + After entering the correct passphrase, you should see lines like these: + + .. code-block:: + + Created remote test (Hostname: , User: ). + Using Protocol sftp. + ⠼ Testing connection to with user using public key authentication. + Connection test to with user testuser was successful. + + .. tab-item:: :octicon:`passkey-fill` With Password + + .. code-block:: bash + + backpy remote create --name --hostname --username --protocol + + After sending the command, you will be asked to enter your password. + + .. code-block:: + + > Enter the password for the user: █ + + This password will only be saved in your local config for this remote. + The password is not saved in clear text but as an encrypted token. + Read more about the encryption of ``backpy`` in the concept :ref:`concepts_encryption`. + + If you entered the wrong password or passphrase you will receive an error message and the remote will not be created. + + After entering the correct passphrase, you should see lines like these: + + .. code-block:: + + Created remote test (Hostname: , User: ). + Using Protocol sftp. + ⠼ Testing connection to with user using password authentication. + Connection test to with user testuser was successful. + +If everything worked, you should have a working remote storage now. +You can use :code:`backpy remote edit ` to edit the remote, :code:`backpy remote test ` to test the connection and +:code:`backpy remote delete ` to delete the remote. diff --git a/docs/workflows/setup/index.rst b/docs/workflows/setup/index.rst new file mode 100644 index 0000000..70425bf --- /dev/null +++ b/docs/workflows/setup/index.rst @@ -0,0 +1,10 @@ +.. _workflows-setup: + +***** +Setup +***** + +These guides give an overview for some setup actions. + +.. toctree:: + creating-a-remote diff --git a/pyproject.toml b/pyproject.toml index cfcb1db..3ea48dc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -13,54 +13,64 @@ description = "A Python based CLI tool for backing up data and databases." readme = "README.md" authors = [{ name = "Tom Groß", email = "tom.gross@tu-dortmund.de" }] maintainers = [{ name = "Tom Groß", email = "tom.gross@tu-dortmund.de" }] -license = { text = "GPL-3.0", url = "https://www.gnu.org/licenses/gpl-3.0" } +license = { text = "LGPL-3.0", url = "https://www.gnu.org/licenses/lgpl-3.0" } classifiers = [ - "Intended Audience :: System Administrators", - "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.14", - "Programming Language :: Python :: 3.13", - "Programming Language :: Python :: 3.12", - "Environment :: Console", - "Operating System :: Unix", - "Natural Language :: English", - "Topic :: System :: Archiving :: Backup", - "Development Status :: 4 - Beta", + "Intended Audience :: System Administrators", + "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.14", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.12", + "Environment :: Console", + "Operating System :: Unix", + "Natural Language :: English", + "Topic :: System :: Archiving :: Backup", + "Development Status :: 4 - Beta", ] requires-python = ">=3.12" dependencies = [ - "numpy", - "toml", - "rich", - "pandas", - "click", - "rich-click", - "click-params", - "fuzzyfinder", - "scp", - "paramiko", - "cryptography", - "mergedeep", - "python-crontab", - "catppuccin", + "numpy", + "tomli-w", + "rich", + "click", + "rich-click", + "click-params", + "fuzzyfinder", + "scp", + "paramiko", + "cryptography", + "mergedeep", + "python-crontab", + "catppuccin", + "mysql-connector-python", ] -[project.optional-dependencies] +[dependency-groups] -dev = [ - "jupyterlab", - "pre-commit", +all = [ + { include-group = "dev" }, + { include-group = "docs" }, + { include-group = "tests" }, ] +dev = ["jupyterlab", "pre-commit"] + docs = [ "sphinx", "sphinx-autobuild", + "sphinx-iconify", + "sphinx-design", + "sphinx-copybutton", + "sphinx-togglebutton", + "sphinx-click", + "sphinx-automodapi", + "numpydoc", + "shibuya", + "towncrier", + { include-group = "dev" }, ] -tests = [ - "pytest >= 7.0", - "pytest-cov", -] +tests = ["pytest >= 7.0", "pytest-cov", { include-group = "dev" }] [project.scripts] backpy = "backpy.cli.cli:entry_point" @@ -74,3 +84,26 @@ write_to = "backpy/_version.py" [tool.setuptools.packages.find] where = ["."] + +[tool.towncrier] +directory = "docs/changes" +filename = "docs/changes/CHANGELOG.rst" +package = "backpy" +issue_format = "`#{issue} `_" +ignore = ["tutorial-towncrier.rst", "CHANGELOG.rst"] + +[[tool.towncrier.type]] +directory = "api" +name = "API Changes" + +[[tool.towncrier.type]] +directory = "cli" +name = "CLI Changes" + +[[tool.towncrier.type]] +directory = "docs" +name = "Documentation Changes" + +[[tool.towncrier.type]] +directory = "bugfix" +name = "Bug Fixes" diff --git a/tests/core/config/data/test.toml b/tests/core/config/data/test.toml new file mode 100644 index 0000000..cb99f9b --- /dev/null +++ b/tests/core/config/data/test.toml @@ -0,0 +1,80 @@ +int = 1 +float = 1.0 + +int_list = [1, 2] +float_list = [1.0, 2.0] + +string = "test" + +date = 2026-01-01T23:23:23+01:00 + +true_bool = true +false_bool = false + +dict = { a = 1.0, b = 2.0 } + +[sectionA] +int = 1 +float = 1.0 + +int_list = [1, 2] +float_list = [1.0, 2.0] + +string = "test" + +date = 2026-01-01T23:23:23+01:00 + +true_bool = true +false_bool = false + +dict = { a = 1.0, b = 2.0 } + +[sectionA.subsectionA] + +int = 1 +float = 1.0 + +int_list = [1, 2] +float_list = [1.0, 2.0] + +string = "test" + +date = 2026-01-01T23:23:23+01:00 + +true_bool = true +false_bool = false + +dict = { a = 1.0, b = 2.0 } + +[sectionA.subsectionA.subsubsectionA] + +int = 1 +float = 1.0 + +int_list = [1, 2] +float_list = [1.0, 2.0] + +string = "test" + +date = 2026-01-01T23:23:23+01:00 + +true_bool = true +false_bool = false + +dict = { a = 1.0, b = 2.0 } + +[sectionB] +int = 1 +float = 1.0 + +int_list = [1, 2] +float_list = [1.0, 2.0] + +string = "test" + +date = 2026-01-01T23:23:23+01:00 + +true_bool = true +false_bool = false + +dict = { a = 1.0, b = 2.0 } diff --git a/tests/core/config/toml_test.py b/tests/core/config/toml_test.py new file mode 100644 index 0000000..f5d81cd --- /dev/null +++ b/tests/core/config/toml_test.py @@ -0,0 +1,178 @@ +import datetime +import shutil +from pathlib import Path + +import pytest + +from backpy.core.config import MissingKeyPolicy, TOMLConfiguration +from backpy.core.utils.exceptions import InvalidTOMLConfigurationError + +_TRUE_DATA = { + "int": 1, + "float": 1.0, + "int_list": [1, 2], + "float_list": [1.0, 2.0], + "string": "test", + "date": datetime.datetime( + 2026, + 1, + 1, + 23, + 23, + 23, + tzinfo=datetime.timezone(datetime.timedelta(seconds=3600)), + ), + "true_bool": True, + "false_bool": False, + "dict": {"a": 1.0, "b": 2.0}, +} + +_ALT_DATA = { + "int": 2, + "float": 2.0, + "int_list": [3, 4], + "float_list": [3.0, 4.0], + "string": "toast", + "date": datetime.datetime( + 2025, + 2, + 2, + 22, + 22, + 22, + tzinfo=datetime.timezone(datetime.timedelta(seconds=7200)), + ), + "true_bool": False, + "false_bool": True, + "dict": {"a": 3.0, "b": 4.0}, +} + + +def equal_type_and_value(val1, val2) -> bool: + return isinstance(val1, type(val2)) and val1 == val2 + + +def test_invalid_load() -> None: + with pytest.raises(InvalidTOMLConfigurationError): + TOMLConfiguration(path="data/test.tom") + + +def test_create_on_load(tmp_path: Path) -> None: + toml = TOMLConfiguration(path=tmp_path / "test.toml", create_if_not_exists=True) + print(toml._path) + assert toml.exists() + + +def test_valid_load() -> None: + TOMLConfiguration(path="tests/core/config/data/test.toml") + + +def test_read(tmp_path: Path) -> None: + shutil.copy(src="tests/core/config/data/test.toml", dst=tmp_path / "test.toml") + + toml = TOMLConfiguration(path=tmp_path / "test.toml") + + for key, value in _TRUE_DATA.items(): + assert key in toml + assert equal_type_and_value(toml[key], value) + + assert toml["sectionA"] == _TRUE_DATA | { + "subsectionA": _TRUE_DATA | {"subsubsectionA": _TRUE_DATA} + } + assert toml["sectionA.subsectionA"] == _TRUE_DATA | {"subsubsectionA": _TRUE_DATA} + assert toml["sectionA"]["subsectionA"] == _TRUE_DATA | { + "subsubsectionA": _TRUE_DATA + } + assert toml["sectionA.subsectionA.subsubsectionA"] == _TRUE_DATA + assert toml["sectionA.subsectionA"]["subsubsectionA"] == _TRUE_DATA + assert toml["sectionA"]["subsectionA"]["subsubsectionA"] == _TRUE_DATA + assert toml["sectionB"] == _TRUE_DATA + + +def test_dump(tmp_path: Path) -> None: + full_data = _TRUE_DATA | { + "sectionA": _TRUE_DATA + | {"subsectionA": _TRUE_DATA | {"subsubsectionA": _TRUE_DATA}}, + "sectionB": _TRUE_DATA, + } + + toml = TOMLConfiguration(tmp_path / "true.toml", create_if_not_exists=True) + toml.dump(full_data) + + del toml + + true_toml = TOMLConfiguration(tmp_path / "true.toml") + assert full_data == true_toml.asdict() + + +def test_write(tmp_path: Path) -> None: + shutil.copy(src="tests/core/config/data/test.toml", dst=tmp_path / "test.toml") + + toml = TOMLConfiguration(tmp_path / "test.toml") + + for key in [ + None, + "sectionA", + "sectionA.subsectionA", + "sectionA.subsectionA.subsubsectionA", + "sectionB", + ]: + for k, v in _ALT_DATA.items(): + if key is None: + toml[k] = v + assert toml[k] == v + else: + toml[f"{key}.{k}"] = v + + true_data = _TRUE_DATA | { + "sectionA": _TRUE_DATA + | {"subsectionA": _TRUE_DATA | {"subsubsectionA": _TRUE_DATA}}, + "sectionB": _TRUE_DATA, + } + + full_data = _ALT_DATA | { + "sectionA": _ALT_DATA + | {"subsectionA": _ALT_DATA | {"subsubsectionA": _ALT_DATA}}, + "sectionB": _ALT_DATA, + } + + toml.dump(true_data) + + toml["sectionA"] = full_data["sectionA"] + assert toml["sectionA"] == full_data["sectionA"] + + toml.dump(true_data) + + toml["sectionB"] = full_data["sectionB"] + assert toml["sectionB"] == full_data["sectionB"] + + toml.dump(true_data) + + toml["sectionA.subsectionA"] = full_data["sectionA"]["subsectionA"] + assert toml["sectionA.subsectionA"] == full_data["sectionA"]["subsectionA"] + + toml.dump(true_data) + + toml["sectionA.subsectionA.subsubsectionA"] = full_data["sectionA"]["subsectionA"][ + "subsubsectionA" + ] + assert ( + toml["sectionA.subsectionA.subsubsectionA"] + == full_data["sectionA"]["subsectionA"]["subsubsectionA"] + ) + + +def test_policies() -> None: + toml = TOMLConfiguration( + path="tests/core/config/data/test.toml", + missing_key_policy=MissingKeyPolicy.ERROR, + ) + + with pytest.raises(KeyError): + toml["x"] + + toml = TOMLConfiguration( + path="tests/core/config/data/test.toml", + missing_key_policy=MissingKeyPolicy.RETURN_NONE, + ) + assert toml["x"] is None