├── .github └── workflows │ ├── build.yml │ ├── build_matrix.yml │ └── docs.yml ├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── docs ├── Makefile ├── about.rst ├── api.rst ├── conf.py ├── getting_started.rst ├── index.rst └── make.bat ├── getting_started.rst ├── grabbags ├── __init__.py ├── __main__.py ├── bags.py ├── grabbags.py └── utils.py ├── setup.py ├── sonar-project.properties ├── tests ├── test_bags.py ├── test_grabbags.py └── test_utils.py └── tox.ini /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | on: [push] 2 | name: Main Workflow 3 | jobs: 4 | sonarCloudTrigger: 5 | name: SonarCloud Trigger 6 | runs-on: ubuntu-latest 7 | steps: 8 | - uses: actions/checkout@v2 9 | - run: | 10 | git fetch --prune --unshallow 11 | - name: Setup python 12 | uses: actions/setup-python@v1 13 | with: 14 | python-version: 3.7 15 | - name: Install dependencies 16 | run: | 17 | python -m pip install --upgrade pip 18 | pip install pytest pytest-cov pylint bagit 19 | - name: Pytest 20 | run: | 21 | pip install pytest pytest-cov 22 | python -m pytest --junitxml xunit-reports/xunit-result-python.xml --cov=grabbags --cov-report=xml:coverage-reports/pythoncoverage-pytest.xml 23 | sed -i 's/\/home\/runner\/work\/grabbags\/grabbags\//\/github\/workspace\//g' coverage-reports/pythoncoverage-pytest.xml 24 | sed -i 's/\/home\/runner\/work\/grabbags\/grabbags\//\/github\/workspace\//g' xunit-reports/xunit-result-python.xml 25 | cat coverage-reports/pythoncoverage-pytest.xml 26 | - name: Pylint 27 | run: | 28 | pip install pylint 29 | mkdir -p reports 30 | pylint grabbags -r n --msg-template="{path}:{line}: [{msg_id}({symbol}), {obj}] {msg}" --exit-zero > reports/pylint.log 31 | - name: SonarCloud Scan 32 | uses: sonarsource/sonarcloud-github-action@master 33 | with: 34 | args: > 35 | -Dsonar.organization=${{ secrets.SONAR_ORGANIZATION }} 36 | -Dsonar.projectKey=${{ secrets.SONAR_PROJECTKEY }} 37 | env: 38 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 39 | SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} 40 | -------------------------------------------------------------------------------- /.github/workflows/build_matrix.yml: -------------------------------------------------------------------------------- 1 | on: [push, pull_request] 2 | name: Multi-platform Compatibility Test 3 | jobs: 4 | build: 5 | runs-on: ${{ matrix.os }} 6 | strategy: 7 | matrix: 8 | os: [ubuntu-latest, macos-latest, windows-latest] 9 | python-version: ['3.6', '3.7', '3.8' ,'3.9'] 10 | fail-fast: false 11 | name: Python ${{ matrix.python-version }} ${{ matrix.os }} build 12 | steps: 13 | - uses: actions/checkout@v2 14 | - name: Setup python 15 | uses: actions/setup-python@v2 16 | with: 17 | python-version: ${{ matrix.python-version }} 18 | architecture: x64 19 | - run: pip install tox; tox -e py 20 | -------------------------------------------------------------------------------- /.github/workflows/docs.yml: -------------------------------------------------------------------------------- 1 | name: "Docs Check" 2 | on: [push, pull_request] 3 | 4 | jobs: 5 | docs: 6 | runs-on: ubuntu-latest 7 | steps: 8 | - uses: actions/checkout@v1 9 | - uses: ammaraskar/sphinx-action@master 10 | with: 11 | docs-folder: "docs/" -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /grabbags.egg-info/ 2 | venv/ 3 | .eggs* 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | 2 | language: python 3 | python: 4 | - "3.6" 5 | - "3.7" 6 | # command to install dependencies 7 | install: 8 | - pip install tox pytest 9 | # - pip install -r requirements.txt 10 | # command to run tests 11 | script: 12 | # - python -m pytest 13 | - tox -e py -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Grabbags 2 | 3 | [![Build Status](https://travis-ci.org/amiaopensource/grabbags.svg?branch=master)](https://travis-ci.org/amiaopensource/grabbags) 4 | [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=amiaopensource_grabbags&metric=alert_status)](https://sonarcloud.io/dashboard?id=amiaopensource_grabbags) 5 | 6 | ## Introduction 7 | 8 | Grabbags is an enhanced implementation of the Library of Congress's BagIt Library. Grabbags allows users to do bulk creation and validation of bags. Grabbags can also eliminate system files before bagging. Even better, it can delete system files automatically in existing bags if they haven't been written to the bag manifest. 9 | 10 | ## Installing grabbags 11 | 12 | Grabbags can be installed on a Mac via the package manager [Homebrew](https://brew.sh/). Once Homebrew is installed on your system run the following commands: 13 | 1. `brew update` This makes sure Homebrew and all of its information about formulae are up to date. 14 | 3. `brew tap amiaopensource/amiaos` This will allow you to start using the [AMIA Open Source tap](https://github.com/amiaopensource/homebrew-amiaos). 15 | 4. `brew install grabbags` Installs the script. 16 | 17 | For installation on Windows or to install in development mode, see [getting_started.rst](getting_started.rst) 18 | 19 | ## Using grabbags 20 | To run grabbags, use the command: 21 | `grabbags (optional flags) (target directory path)` 22 | 23 | By default, grabbags will do bulk creation of bags. It assumes that a target directory contains many other subdirectories inside of it that will be turned into bags. So set up your directories accordingly. You can also give the command multiple target directories 24 | `grabbags (optional flags) (target directory path 1) (target directory path 2)` 25 | 26 | Since grabbags uses the bagit Python library, all the functionality of bagit (including adding metadata fields and choosing checksum algorithms) should be available for bag creation. 27 | 28 | ### Eliminating System Files Before Bag Creation 29 | Using the `--no-system-files` flag when creating bags will find and remove any system files before bagging. The current system files that the script can find are: 30 | * .DS_Store 31 | * Thumbs.db 32 | * ._ files (AppleDoubles) 33 | * Icon files (Apple custom icons) 34 | 35 | Please send a pull request or issue if you have additional information about new system files that users would want to delete. 36 | 37 | ### Validate Flags 38 | Validation of bags has two possible options: 39 | 40 | The default behavior of `grabbags --validate` is to validate the bag by comparing the checksums of all files with the checksums contained in the manifest. 41 | Users can optionally use the flags `--validate --no-checksums`. This only validates the Oxsum of the bag, the number of files, and the proper files according to the bagit specification. Using the --no-checksums flag is equivalent to running `--validate --completeness-only` 42 | 43 | ## Cleaning Bags 44 | Grabbags can delete system files within existing bags if they haven't already been written to the bag manifest. To use this feature, run the following: 45 | 46 | `grabbags --clean (target directory path)` 47 | 48 | Remember, that all of your bags should be in subdirectories inside of the target directory. 49 | 50 | ## Enhanced Logging 51 | Just as in bagit python, users can use the `--log (path to place log file)` flag to create a log when creating or validating bags. At the end of the output grabbags will display summary data about the numbers of bags created or validated (number of successes, number of failures and path to all failures). 52 | 53 | ## Credits 54 | Grabbags was originally produced as part of [AMIA/DLF Hack Day 2019](https://wiki.curatecamp.org/index.php/Association_of_Moving_Image_Archivists_&_Digital_Library_Federation_Hack_Day_2019) 55 | 56 | The initial project team was: 57 | 58 | * Henry Borchers 59 | * Helyx Chase Scearce Horwitz 60 | * Jonathan Farbowitz 61 | * Nıck Krabbenhöft 62 | 63 | As part of [AMIA/DLF Hack Day 2021](https://wiki.diglib.org/AMIA-DLF_Hack_Day_2021), Grabbags was given a little more love. 64 | 65 | The 2021 Project Team was: 66 | 67 | * Henry Borchers 68 | * Jonathan Farbowitz 69 | * Bryn Knowles 70 | * Milo Thiesen 71 | 72 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line, and also 5 | # from the environment for the first two. 6 | SPHINXOPTS ?= 7 | SPHINXBUILD ?= sphinx-build 8 | SOURCEDIR = . 9 | BUILDDIR = _build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /docs/about.rst: -------------------------------------------------------------------------------- 1 | About 2 | ===== 3 | 4 | .. include:: ../README.md 5 | -------------------------------------------------------------------------------- /docs/api.rst: -------------------------------------------------------------------------------- 1 | API 2 | === 3 | 4 | .. automodule:: grabbags 5 | :members: 6 | 7 | .. automodule:: grabbags.utils 8 | :members: 9 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # Configuration file for the Sphinx documentation builder. 2 | # 3 | # This file only contains a selection of the most common options. For a full 4 | # list see the documentation: 5 | # https://www.sphinx-doc.org/en/master/usage/configuration.html 6 | 7 | # -- Path setup -------------------------------------------------------------- 8 | 9 | # If extensions (or modules to document with autodoc) are in another directory, 10 | # add these directories to sys.path here. If the directory is relative to the 11 | # documentation root, use os.path.abspath to make it absolute, like shown here. 12 | # 13 | import os 14 | import sys 15 | sys.path.insert(0, os.path.abspath('..')) 16 | 17 | 18 | # -- Project information ----------------------------------------------------- 19 | 20 | project = 'grabbags' 21 | copyright = '2019, AMIA Open-source' 22 | author = 'AMIA Open-source' 23 | 24 | 25 | # -- General configuration --------------------------------------------------- 26 | 27 | # Add any Sphinx extension module names here, as strings. They can be 28 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 29 | # ones. 30 | extensions = [ 31 | 'sphinx.ext.autodoc', 32 | 'sphinx.ext.githubpages', 33 | 'sphinx.ext.napoleon', 34 | ] 35 | 36 | napoleon_google_docstring = True 37 | 38 | # Add any paths that contain templates here, relative to this directory. 39 | templates_path = ['_templates'] 40 | 41 | # List of patterns, relative to source directory, that match files and 42 | # directories to ignore when looking for source files. 43 | # This pattern also affects html_static_path and html_extra_path. 44 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', "recommonmark"] 45 | 46 | 47 | # -- Options for HTML output ------------------------------------------------- 48 | 49 | # The theme to use for HTML and HTML Help pages. See the documentation for 50 | # a list of builtin themes. 51 | # 52 | html_theme = 'alabaster' 53 | 54 | # Add any paths that contain custom static files (such as style sheets) here, 55 | # relative to this directory. They are copied after the builtin static files, 56 | # so a file named "default.css" will overwrite the builtin "default.css". 57 | html_static_path = ['_static'] -------------------------------------------------------------------------------- /docs/getting_started.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../getting_started.rst 2 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. grabbags documentation master file, created by 2 | sphinx-quickstart on Thu Nov 14 16:51:38 2019. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to grabbags's documentation! 7 | ==================================== 8 | 9 | .. toctree:: 10 | :maxdepth: 2 11 | :caption: Contents: 12 | 13 | about 14 | getting_started 15 | api 16 | 17 | 18 | Indices and tables 19 | ================== 20 | 21 | * :ref:`genindex` 22 | * :ref:`modindex` 23 | * :ref:`search` 24 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=sphinx-build 9 | ) 10 | set SOURCEDIR=. 11 | set BUILDDIR=_build 12 | 13 | if "%1" == "" goto help 14 | 15 | %SPHINXBUILD% >NUL 2>NUL 16 | if errorlevel 9009 ( 17 | echo. 18 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 19 | echo.installed, then set the SPHINXBUILD environment variable to point 20 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 21 | echo.may add the Sphinx directory to PATH. 22 | echo. 23 | echo.If you don't have Sphinx installed, grab it from 24 | echo.http://sphinx-doc.org/ 25 | exit /b 1 26 | ) 27 | 28 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 29 | goto end 30 | 31 | :help 32 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 33 | 34 | :end 35 | popd 36 | -------------------------------------------------------------------------------- /getting_started.rst: -------------------------------------------------------------------------------- 1 | =============== 2 | Getting started 3 | =============== 4 | 5 | Installing on the System Python 6 | =============================== 7 | 8 | 1. Download the source (or clone the repository) to your computer 9 | 2. Open a terminal in the directory of the source 10 | 3. Install with setup.py 11 | 12 | On Mac or Linux: 13 | 14 | .. code-block:: 15 | 16 | python3 setup.py install 17 | 18 | On Windows: 19 | 20 | .. code-block:: 21 | 22 | py setup.py install 23 | 24 | 25 | 26 | Setting up a Development Environment 27 | ==================================== 28 | 1. Create a new Python 3 virtual environment 29 | 30 | On Mac or Linux: 31 | 32 | .. code-block:: 33 | 34 | python3 -m venv venv 35 | 36 | On Windows: 37 | 38 | .. code-block:: 39 | 40 | py -m venv venv 41 | 42 | 43 | 2. Activate Python virtual environment 44 | 45 | On Mac or Linux: 46 | 47 | .. code-block:: 48 | 49 | source venv/bin/activate 50 | 51 | On Windows: 52 | 53 | .. code-block:: 54 | 55 | venv/Scripts/activate 56 | 57 | 3. Install the grabbags in development mode 58 | 59 | .. code-block:: 60 | 61 | python -m pip install -e . 62 | 63 | 4. Start hacking 64 | 65 | Building the documentation 66 | ========================== 67 | 68 | 1. Follow the instructions above and install and activate the development 69 | virtual environment 70 | 71 | 2. Install sphinx 72 | 73 | .. code-block:: 74 | 75 | python -m pip install sphinx 76 | 77 | 78 | 3. Run sphinx build target from setup.py 79 | 80 | .. code-block:: 81 | 82 | python setup.py build_sphinx 83 | 84 | By default, the documentation is generated into build/sphinx/html 85 | -------------------------------------------------------------------------------- /grabbags/__init__.py: -------------------------------------------------------------------------------- 1 | from .bags import is_bag 2 | from . import utils 3 | 4 | __all__ = [ 5 | "is_bag", 6 | "utils" 7 | ] 8 | -------------------------------------------------------------------------------- /grabbags/__main__.py: -------------------------------------------------------------------------------- 1 | from grabbags import grabbags 2 | 3 | 4 | if __name__ == '__main__': 5 | grabbags.main() 6 | -------------------------------------------------------------------------------- /grabbags/bags.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | 4 | def is_bag(path) -> bool: 5 | """Check if the directory path given is a bag directory 6 | 7 | Args: 8 | path: path to potential bag root folder 9 | 10 | Returns: 11 | True if determined it's a bag directory, or False if it's not 12 | 13 | """ 14 | 15 | if not os.path.exists(os.path.join(path, "bagit.txt")): 16 | return False 17 | 18 | if not os.path.exists(os.path.join(path, "data")): 19 | return False 20 | 21 | return True 22 | -------------------------------------------------------------------------------- /grabbags/grabbags.py: -------------------------------------------------------------------------------- 1 | import abc 2 | import argparse 3 | import gettext 4 | import logging 5 | import os 6 | import re 7 | import sys 8 | import typing 9 | import warnings 10 | 11 | import bagit 12 | 13 | from grabbags.bags import is_bag 14 | import grabbags.utils 15 | 16 | SUMMARY_REPORT_HEADER = "Summary Report:" 17 | 18 | successes = [] 19 | failures = [] 20 | not_a_bag = [] 21 | 22 | 23 | def find_locale_dir(): 24 | for prefix in (os.path.dirname(__file__), sys.prefix): 25 | locale_dir = os.path.join(prefix, "locale") 26 | if os.path.isdir(locale_dir): 27 | return locale_dir 28 | 29 | 30 | TRANSLATION_CATALOG = gettext.translation( 31 | "bagit-python", localedir=find_locale_dir(), fallback=True 32 | ) 33 | if sys.version_info < (3,): 34 | _ = TRANSLATION_CATALOG.ugettext 35 | else: 36 | _ = TRANSLATION_CATALOG.gettext 37 | 38 | MODULE_NAME = "grabbags" if __name__ == "__main__" else __name__ 39 | 40 | LOGGER = logging.getLogger(MODULE_NAME) 41 | 42 | __doc__ = ( 43 | _( 44 | """ 45 | grabbag.py is an enhancement on the bagit-python for dealing with lots of bags. 46 | Command-Line Usage: 47 | Basic usage is to give bagit.py a directory to bag up: 48 | $ grabbag.py my_directory 49 | This does a bag-in-place operation for each sub-folder of my_directory. 50 | You can bag sub-folders from multiple directories if you wish: 51 | $ grabbag.py directory1 directory2 52 | Optionally you can provide metadata which will be stored in bag-info.txt: 53 | $ grabbag.py --source-organization "Library of Congress" directory 54 | You can also select which manifest algorithms will be used: 55 | $ grabbag.py --sha1 --md5 --sha256 --sha512 directory 56 | """ 57 | ) 58 | % globals() 59 | ) 60 | 61 | 62 | class BagArgumentParser(argparse.ArgumentParser): 63 | def __init__(self, *args, **kwargs): 64 | argparse.ArgumentParser.__init__(self, *args, **kwargs) 65 | self.set_defaults(bag_info={}) 66 | 67 | 68 | def _make_parser(): 69 | parser = BagArgumentParser( 70 | formatter_class=argparse.RawDescriptionHelpFormatter, 71 | description="grabbags!!!", 72 | ) 73 | parser.add_argument( 74 | '--version', "-v", 75 | action='version', 76 | version=grabbags.utils.current_version() 77 | ) 78 | 79 | parser.add_argument( 80 | "--processes", 81 | type=int, 82 | dest="processes", 83 | default=1, 84 | help=_( 85 | "Use multiple processes to calculate checksums faster" 86 | " (default: %(default)s)" 87 | ), 88 | ) 89 | parser.add_argument( 90 | "--log", 91 | help=_("The name of the log file (default: stdout)") 92 | ) 93 | parser.add_argument( 94 | "--quiet", 95 | action="store_true", 96 | help=_("Suppress all progress information other than errors"), 97 | ) 98 | command_group = parser.add_mutually_exclusive_group() 99 | command_group.add_argument( 100 | "--clean", 101 | dest="action_type", 102 | action="store_const", 103 | const="clean", 104 | help=_( 105 | "Remove remove any system files not in manifest of a bag." 106 | " The following files will be deleted: .DS_Store, Thumbs.db, " 107 | " Appledoubles (._*), Icon files" 108 | ), 109 | ) 110 | command_group.add_argument( 111 | "--validate", 112 | dest="action_type", 113 | action="store_const", 114 | const="validate", 115 | help=_( 116 | "Validate existing bags in the provided directories instead of" 117 | " creating new ones" 118 | ), 119 | ) 120 | parser.set_defaults(action_type='create') 121 | parser.add_argument( 122 | "--fast", 123 | action="store_true", 124 | help=_( 125 | "Modify --validate behaviour to only test if the bag directory" 126 | " has the number of files and total size specified in Payload-Oxum" 127 | " without performing checksum validation to detect corruption." 128 | ), 129 | ) 130 | parser.add_argument( 131 | "--no-checksums", 132 | "--completeness-only", 133 | action="store_true", 134 | help=_( 135 | "Modify --validate behaviour to test whether the bag directory" 136 | " has the expected payload specified in the checksum manifests" 137 | " without performing checksum validation to detect corruption." 138 | ), 139 | ) 140 | 141 | parser.add_argument( 142 | "--no-system-files", 143 | action="store_true", 144 | help=_( 145 | "Modify bag creation to delete any system files before bagging" 146 | " The following files will be deleted: .DS_Store, Thumbs.db, " 147 | " Appledoubles (._*), Icon files" 148 | ), 149 | ) 150 | 151 | checksum_args = parser.add_argument_group( 152 | _("Checksum Algorithms"), 153 | _( 154 | "Select the manifest algorithms to be used when creating bags" 155 | " (default=%s)" 156 | ) 157 | % ", ".join(bagit.DEFAULT_CHECKSUMS), 158 | ) 159 | 160 | for i in bagit.CHECKSUM_ALGOS: 161 | alg_name = re.sub(r"^([A-Z]+)(\d+)$", r"\1-\2", i.upper()) 162 | checksum_args.add_argument( 163 | "--%s" % i, 164 | action="append_const", 165 | dest="checksums", 166 | const=i, 167 | help=_("Generate %s manifest when creating a bag") % alg_name, 168 | ) 169 | 170 | metadata_args = parser.add_argument_group(_("Optional Bag Metadata")) 171 | for header in bagit.STANDARD_BAG_INFO_HEADERS: 172 | metadata_args.add_argument( 173 | "--%s" % header.lower(), type=str, 174 | action=bagit.BagHeaderAction, default=argparse.SUPPRESS 175 | ) 176 | 177 | parser.add_argument( 178 | "directories", 179 | nargs="+", 180 | help=_( 181 | "Parent directory of directory which will be converted" 182 | " into a bag in place by moving any existing files into" 183 | " the BagIt structure and creating the manifests and" 184 | " other metadata." 185 | ), 186 | ) 187 | 188 | return parser 189 | 190 | 191 | def _configure_logging(opts): 192 | log_format = "%(asctime)s - %(levelname)s - %(message)s" 193 | if opts.quiet: 194 | level = logging.WARN 195 | else: 196 | level = logging.INFO 197 | if opts.log: 198 | logging.basicConfig(filename=opts.log, level=level, format=log_format) 199 | else: 200 | logging.basicConfig(level=level, format=log_format) 201 | 202 | 203 | def validate_bag(bag_dir, args): 204 | warnings.warn( 205 | "Use GrabbagsRunner.validate_bag() instead", DeprecationWarning 206 | ) 207 | if not is_bag(bag_dir.path): 208 | LOGGER.warning(_("%s is not a bag. Skipped."), bag_dir.path) 209 | not_a_bag.append(bag_dir.path) 210 | return 211 | 212 | bag = bagit.Bag(bag_dir.path) 213 | # validate throws a BagError or BagValidationError 214 | bag.validate( 215 | processes=args.processes, 216 | fast=args.fast, 217 | completeness_only=args.no_checksums, 218 | ) 219 | successes.append(bag_dir.path) 220 | if args.fast: 221 | LOGGER.info(_("%s valid according to Payload-Oxum"), bag_dir.path) 222 | elif args.no_checksums: 223 | LOGGER.info( 224 | _("%s valid according to Payload-Oxum and file manifest"), 225 | bag_dir.path 226 | ) 227 | else: 228 | LOGGER.info(_("%s is valid"), bag_dir.path) 229 | 230 | 231 | def clean_bag(bag_dir): 232 | warnings.warn( 233 | "Use GrabbagsRunner.clean_bag() instead", 234 | DeprecationWarning 235 | ) 236 | if not is_bag(bag_dir.path): 237 | LOGGER.warning(_("%s is not a bag. Not cleaning."), bag_dir.path) 238 | return 239 | 240 | bag = bagit.Bag(bag_dir.path) 241 | if bag.compare_manifests_with_fs()[1]: 242 | for payload_file in bag.compare_manifests_with_fs()[1]: 243 | if grabbags.utils.is_system_file(payload_file): 244 | LOGGER.info( 245 | "Removing system files from {}".format(bag_dir.path) 246 | ) 247 | os.remove(os.path.join(bag_dir.path, payload_file)) 248 | else: 249 | LOGGER.warning("Found file not in manifest: %s", payload_file) 250 | else: 251 | LOGGER.info("No system files located in %s", bag_dir.path) 252 | 253 | 254 | def make_bag(bag_dir: "os.DirEntry[str]", args): 255 | warnings.warn( 256 | "Use GrabbagsRunner.make_bag() instead", 257 | DeprecationWarning 258 | ) 259 | if len(os.listdir(bag_dir.path)) == 0: 260 | LOGGER.warning(_("%s is an empty directory. Skipped."), bag_dir.path) 261 | return 262 | 263 | if is_bag(bag_dir.path): 264 | LOGGER.warning(_("%s is already a bag. Skipped."), bag_dir.path) 265 | return 266 | 267 | if args.no_system_files is True: 268 | LOGGER.info(_("Cleaning %s of system files"), bag_dir.path) 269 | grabbags.utils.remove_system_files(root=bag_dir.path) 270 | 271 | bag = bagit.make_bag( 272 | bag_dir.path, 273 | bag_info=args.bag_info, 274 | processes=args.processes, 275 | checksums=args.checksums 276 | ) 277 | successes.append(bag_dir.path) 278 | LOGGER.info(_("Bagged %s"), bag.path) 279 | 280 | 281 | class GrabbagsRunner: 282 | 283 | def __init__(self) -> None: 284 | self.successes: typing.List[str] = [] 285 | self.failures: typing.List[str] = [] 286 | # self.not_a_bag: typing.List[str] = [] 287 | self.skipped: typing.List[str] = [] 288 | self.results: typing.List[typing.Dict[str, typing.Any]] = [] 289 | 290 | @staticmethod 291 | def find_bag_dirs(search_root: str) -> "typing.Iterable[os.DirEntry[str]]": 292 | yield from filter(lambda i: i.is_dir(), os.scandir(search_root)) 293 | 294 | def get_report(self, args) -> str: 295 | actions: typing.Dict[str, AbsAction] = { 296 | "validate": ValidateBag(args, LOGGER), 297 | "clean": CleanBag(args, LOGGER), 298 | "create": MakeBag(args, LOGGER) 299 | } 300 | action = actions[args.action_type] 301 | return action.create_report(args, self) 302 | 303 | def _run_action(self, 304 | action_type: str, 305 | bag_dir: 'os.DirEntry[str]', 306 | args: argparse.Namespace) -> None: 307 | 308 | actions: typing.Dict[str, AbsAction] = { 309 | "validate": ValidateBag(args, LOGGER), 310 | "clean": CleanBag(args, LOGGER), 311 | "create": MakeBag(args, LOGGER) 312 | } 313 | 314 | action: AbsAction = actions[action_type] 315 | try: 316 | action.execute(bag_dir=bag_dir.path) 317 | except bagit.BagError as error: 318 | if action_type == "clean": 319 | LOGGER.error( 320 | _("%(bag)s cannot be cleaned: %(error)s"), 321 | {"bag": bag_dir.path, "error": error} 322 | ) 323 | elif action_type == "create": 324 | LOGGER.error( 325 | _("%(bag)s could not be bagged: %(error)s"), 326 | {"bag": bag_dir.path, "error": error} 327 | ) 328 | elif action_type == "validate": 329 | # This will be removed as soon as the other actions are ready 330 | pass 331 | else: 332 | raise ValueError( 333 | f"args contain invalid action_type: {args.action_type}" 334 | ) 335 | finally: 336 | self.successes += action.successes 337 | self.failures += action.failures 338 | self.skipped += action.skipped 339 | self.results.append(action.results) 340 | 341 | def run(self, args: argparse.Namespace) -> None: 342 | """Run the grabbags jobs based on the given user arguments. 343 | 344 | Args: 345 | args: Parsed user arguments. 346 | 347 | """ 348 | for bag_parent in args.directories: 349 | for bag_dir in self.find_bag_dirs(bag_parent): 350 | 351 | self._run_action(action_type=args.action_type, 352 | bag_dir=bag_dir, 353 | args=args) 354 | 355 | 356 | def run2(args: argparse.Namespace) -> None: 357 | """Run grabbags process with the parsed arguments provided. 358 | 359 | Args: 360 | args: Parsed arguments 361 | 362 | """ 363 | runner = GrabbagsRunner() 364 | runner.run(args) 365 | report = runner.get_report(args) 366 | 367 | LOGGER.info(report) 368 | # ========================================================================== 369 | 370 | action: str = { 371 | 'validate': 'validated', 372 | 'clean': 'cleaned', 373 | 'create': 'created' 374 | }.get(args.action_type, "") 375 | 376 | LOGGER.info( 377 | _("%(count)s bags %(action)s successfully"), 378 | {"count": len(runner.successes), "action": action} 379 | ) 380 | if runner.failures and len(runner.failures) > 0: 381 | LOGGER.warning( 382 | _("%(count)s bags not %(action)s"), 383 | {"count": len(runner.failures), "action": action} 384 | ) 385 | LOGGER.warning( 386 | _("Failed for the following folders: %s"), 387 | ", ".join(runner.failures) 388 | ) 389 | 390 | not_a_bag_results = [ 391 | result for result in runner.results 392 | if 'not_a_bag' in result and result['not_a_bag'] is True 393 | ] 394 | 395 | if not_a_bag_results: 396 | LOGGER.warning( 397 | _("%(count)s folders are not bags"), 398 | {"count": len(not_a_bag_results)} 399 | ) 400 | LOGGER.warning( 401 | _("The following folders are not bags: %s"), 402 | ", ".join(not_a_bag_results) 403 | ) 404 | 405 | 406 | def run(args: argparse.Namespace): 407 | warnings.warn("Use run2 instead", PendingDeprecationWarning) 408 | for bag_parent in args.directories: 409 | for bag_dir in filter(lambda i: i.is_dir(), os.scandir(bag_parent)): 410 | if args.action_type == "validate": 411 | try: 412 | validate_bag(bag_dir, args) 413 | except bagit.BagError as error: 414 | LOGGER.error( 415 | _("%(bag)s is invalid: %(error)s"), 416 | {"bag": bag_dir.path, "error": error} 417 | ) 418 | failures.append(bag_dir.path) 419 | elif args.action_type == "clean": 420 | try: 421 | clean_bag(bag_dir) 422 | successes.append(bag_dir.path) 423 | except bagit.BagError as error: 424 | LOGGER.error( 425 | _("%(bag)s cannot be cleaned: %(error)s"), 426 | {"bag": bag_dir.path, "error": error} 427 | ) 428 | failures.append(bag_dir.path) 429 | elif args.action_type == "create": 430 | try: 431 | make_bag(bag_dir, args) 432 | # successes.append(bag_dir.path) 433 | except bagit.BagError as error: 434 | LOGGER.error( 435 | _("%(bag)s could not be bagged: %(error)s"), 436 | {"bag": bag_dir.path, "error": error} 437 | ) 438 | failures.append(bag_dir.path) 439 | else: 440 | raise ValueError( 441 | f"args contain invalid action_type: {args.action_type}" 442 | ) 443 | 444 | action: str = { 445 | 'validate': 'validated', 446 | 'clean': 'cleaned', 447 | 'create': 'created' 448 | }.get(args.action_type, "") 449 | 450 | LOGGER.info( 451 | _("%(count)s bags %(action)s successfully"), 452 | {"count": len(successes), "action": action} 453 | ) 454 | if failures and len(failures) > 0: 455 | LOGGER.warning( 456 | _("%(count)s bags not %(action)s"), 457 | {"count": len(failures), "action": action} 458 | ) 459 | LOGGER.warning( 460 | _("Failed for the following folders: %s"), 461 | ", ".join(failures) 462 | ) 463 | if not_a_bag and len(not_a_bag) > 0: 464 | LOGGER.warning( 465 | _("%(count)s folders are not bags"), 466 | {"count": len(not_a_bag)} 467 | ) 468 | LOGGER.warning( 469 | _("The following folders are not bags: %s"), 470 | ", ".join(not_a_bag) 471 | ) 472 | 473 | 474 | class AbsAction(abc.ABC): 475 | """Abstract base class for creating actions.""" 476 | 477 | def __init__( 478 | self, 479 | args: argparse.Namespace, logger: logging.Logger = None 480 | ) -> None: 481 | 482 | self.logger = logger or logging.getLogger(__name__) 483 | self.args = args 484 | self.successes = [] 485 | self.failures = [] 486 | 487 | # skipped is used in the context of new bag creation 488 | # ex. i'm makin' new bags but i'm skippin' empty directories and 489 | # things that are already bags- 490 | self.skipped = [] 491 | 492 | # successful tells if the action was successful or not. False if failed 493 | # True if succeeded. None if not run at all 494 | self.successful: typing.Optional[bool] = None 495 | 496 | self.results = {} 497 | # not a bag is used in the context when you expect that bags are 498 | # already present 499 | # ex. i'm validating bags and i want to skip things that aren't bags 500 | # AND i want a count of directories that are not bags and their paths 501 | 502 | 503 | @abc.abstractmethod 504 | def create_report(self, args, runner): 505 | """Create a string report""" 506 | 507 | @abc.abstractmethod 508 | def execute(self, bag_dir: str): 509 | """Run the command.""" 510 | 511 | 512 | class ValidateBag(AbsAction): 513 | """Validate bag action.""" 514 | 515 | def execute(self, bag_dir: str): 516 | self.results['path'] = bag_dir 517 | if not is_bag(bag_dir): 518 | self.logger.warning(_("%s is not a bag. Skipped."), bag_dir) 519 | self.results['not_a_bag'] = True 520 | self.successful = True 521 | return 522 | 523 | self.validate(bag_dir) 524 | 525 | def validate(self, bag_dir: str) -> None: 526 | """Validate directory.""" 527 | bag = bagit.Bag(bag_dir) 528 | 529 | # validate throws a BagError or BagValidationError 530 | try: 531 | 532 | bag.validate( 533 | processes=self.args.processes, 534 | fast=self.args.fast, 535 | completeness_only=self.args.no_checksums, 536 | ) 537 | self.successes.append(bag_dir) 538 | if self.args.fast: 539 | self.logger.info( 540 | _("%s valid according to Payload-Oxum (Bag size)"), 541 | bag_dir) 542 | elif self.args.no_checksums: 543 | self.logger.info( 544 | _("%s valid according to Payload-Oxum (Bag size), and all " 545 | "paths in manifest correct"), 546 | bag_dir 547 | ) 548 | else: 549 | self.logger.info(_("%s is valid"), bag_dir) 550 | self.successful = True 551 | except bagit.BagError as error: 552 | self.failures.append(bag_dir) 553 | self.logger.error( 554 | _("%(bag)s is invalid: %(error)s"), 555 | {"bag": bag_dir, "error": error} 556 | ) 557 | self.successful = False 558 | 559 | def create_report(self, args, runner): 560 | 561 | not_a_bag_results = { 562 | result["path"] 563 | for result in runner.results 564 | if "not_a_bag" in result and result["not_a_bag"] 565 | } 566 | 567 | report = [ 568 | SUMMARY_REPORT_HEADER, 569 | f"{len(runner.successes)} bags validated successfully", 570 | f"{len(runner.failures)} failures", 571 | f"{len(not_a_bag_results)} directories are not bags", 572 | "" 573 | ] 574 | return "\n".join(report) 575 | 576 | 577 | class CleanBag(AbsAction): 578 | """CleanBag cleans directory containing bag. 579 | 580 | A successful 'clean' is defined by hidden files that are not included in a 581 | manifest being deleted from the bag without error. 582 | 583 | A successful 'clean' is also defined by a directory that is not a bag and 584 | is skipped. This is the desired behavior. We do not clean directories 585 | that are not bags. 586 | """ 587 | 588 | def execute(self, bag_dir: str): 589 | """Clean bag at given directory. 590 | 591 | Args: 592 | bag_dir: File path to a directory 593 | 594 | """ 595 | self.results['path'] = bag_dir 596 | if not is_bag(bag_dir): 597 | self.logger.warning(_("%s is not a bag. Not cleaning."), bag_dir) 598 | self.results['not_a_bag'] = True 599 | self.successful = True 600 | return 601 | 602 | self.clean(bag_dir) 603 | self.successful = True 604 | 605 | def clean(self, bag_dir: str): 606 | """Clean directory.""" 607 | bag = bagit.Bag(bag_dir) 608 | if bag.compare_manifests_with_fs()[1]: 609 | for payload_file in bag.compare_manifests_with_fs()[1]: 610 | if grabbags.utils.is_system_file(payload_file): 611 | self.logger.info( 612 | "Removing system files from %s", bag_dir 613 | ) 614 | os.remove(os.path.join(bag_dir, payload_file)) 615 | else: 616 | 617 | self.logger.warning( 618 | "Found file not in manifest: %s", payload_file 619 | ) 620 | else: 621 | self.skipped.append(bag_dir) 622 | self.logger.info("No system files located in %s", bag_dir) 623 | # TODO: error handling for cleaning bags 624 | 625 | def create_report(self, args, runner): 626 | 627 | cleaned = set() 628 | for success in runner.successes: 629 | cleaned.add(success) 630 | 631 | failed = set() 632 | for failure in runner.failures: 633 | failed.add(failure) 634 | 635 | already_cleaned = set() 636 | for skipped in runner.skipped: 637 | already_cleaned.add(skipped) 638 | 639 | not_bags = set() 640 | for result in runner.results: 641 | if 'not_a_bag' in result and result['not_a_bag'] is True: 642 | not_bags.add(result['path']) 643 | 644 | report = [ 645 | SUMMARY_REPORT_HEADER, 646 | f"{len(cleaned)} bags cleaned successfully", 647 | f"{len(failed)} failures", 648 | f"{len(already_cleaned)} bags are already clean", 649 | f"{len(not_bags)} directories are not bags", 650 | "" 651 | ] 652 | return "\n".join(report) 653 | 654 | 655 | class MakeBag(AbsAction): 656 | """Bag creation action.""" 657 | 658 | def execute(self, bag_dir: str): 659 | """Generate a bag for the given directory. 660 | 661 | Args: 662 | bag_dir: File path to a directory 663 | 664 | """ 665 | self.results["path"] = bag_dir 666 | if len(os.listdir(bag_dir)) == 0: 667 | self.logger.warning( 668 | _("%s is an empty directory. Skipped."), bag_dir) 669 | self.skipped.append(bag_dir) 670 | self.results["empty_dir"] = True 671 | self.results["skipped"] = True 672 | self.successful = True 673 | return 674 | 675 | if is_bag(bag_dir): 676 | self.logger.warning(_("%s is already a bag. Skipped."), bag_dir) 677 | self.skipped.append(bag_dir) 678 | self.results["already_a_bag"] = True 679 | self.results["skipped"] = True 680 | self.successful = True 681 | return 682 | 683 | if self.args.no_system_files is True: 684 | self.logger.info(_("Cleaning %s of system files"), bag_dir) 685 | grabbags.utils.remove_system_files(root=bag_dir) 686 | 687 | bag = bagit.make_bag( 688 | bag_dir, 689 | bag_info=self.args.bag_info, 690 | processes=self.args.processes, 691 | checksums=self.args.checksums 692 | ) 693 | self.successes.append(bag_dir) 694 | self.logger.info(_("Bagged %s"), bag.path) 695 | self.successful = True 696 | 697 | def create_report(self, args, runner): 698 | already_bags = 0 699 | 700 | for result in runner.results: 701 | if "already_a_bag" in result and result['already_a_bag'] is True: 702 | already_bags += 1 703 | 704 | empty_dirs = 0 705 | 706 | for result in runner.results: 707 | if "empty_dir" in result and result['empty_dir'] is True: 708 | empty_dirs += 1 709 | 710 | report_lines = [ 711 | SUMMARY_REPORT_HEADER, 712 | f"{len(runner.successes)} bags created successfully", 713 | f"{len(runner.failures)} failures", 714 | f"{empty_dirs} empty directories skipped", 715 | f"{already_bags} directories are already a bag" 716 | ] 717 | # TODO: add paths of empty directories 718 | # TODO: add paths of already_bags 719 | return "\n".join(report_lines) + "\n" 720 | 721 | 722 | def main( 723 | argv: typing.List[str] = None, 724 | runner: typing.Callable[[argparse.Namespace], None] = None 725 | ) -> None: 726 | """Run the main command line entry point. 727 | 728 | Args: 729 | argv: command line arguments 730 | runner: Callback function for processing after the cli args are parsed. 731 | 732 | """ 733 | argv = argv or sys.argv[1:] 734 | parser: argparse.ArgumentParser = _make_parser() 735 | args: argparse.Namespace = parser.parse_args(args=argv) 736 | 737 | if args.processes < 0: 738 | parser.error(_("The number of processes must be 0 or greater")) 739 | 740 | if args.no_checksums and args.action_type != "validate": 741 | parser.error( 742 | _("--no-checksums is only allowed as an option with --validate") 743 | ) 744 | if args.action_type == "clean" and args.no_system_files: 745 | parser.error( 746 | _("Can't run --clean and --no-system-files at the same time") 747 | ) 748 | if args.action_type == "validate" and args.checksums is not None: 749 | parser.error(_("Can't specify a checksum algorithm and " 750 | "run --validate at the same time")) 751 | 752 | if args.action_type == "clean" and args.checksums is not None: 753 | parser.error(_("Can't specify a checksum algorithm and " 754 | "run --clean at the same time")) 755 | 756 | if args.fast and args.action_type != "validate": 757 | parser.error(_("--fast is only allowed as an option with --validate")) 758 | 759 | _configure_logging(args) 760 | 761 | runner = runner or run2 762 | runner(args) 763 | 764 | 765 | if __name__ == "__main__": 766 | main() 767 | -------------------------------------------------------------------------------- /grabbags/utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | import re 3 | import logging 4 | import abc 5 | import shutil 6 | import typing 7 | import subprocess 8 | try: 9 | from importlib import metadata 10 | except ImportError: 11 | import importlib_metadata as metadata # type: ignore 12 | 13 | MODULE_NAME = "grabbags" if __name__ == "__main__" else __name__ 14 | 15 | LOGGER = logging.getLogger(MODULE_NAME) 16 | 17 | SYSTEM_FILES = [ 18 | ".DS_Store", 19 | "Thumbs.db", 20 | "Icon\r" 21 | ] 22 | 23 | APPLE_DOUBLE_REGEX = re.compile(r"^\._.*$") 24 | 25 | 26 | def is_system_file(file_path) -> bool: 27 | """Check if a given file is a system file 28 | 29 | This should be helpful for iterating over files and determine if a file in 30 | a packing can be removed. 31 | 32 | Note: 33 | Files that are identified as a system file are: 34 | 35 | * .DS_Store 36 | * Thumbs.db 37 | * `AppleDouble files `_ 38 | * `Icon resource forks `_ 39 | 40 | Returns: 41 | True if the file a system file, 42 | False if it's not 43 | 44 | """ # noqa 45 | 46 | if os.path.isdir(file_path): 47 | return False 48 | 49 | root_path, filename = os.path.split(file_path) 50 | 51 | if filename in SYSTEM_FILES: 52 | return True 53 | 54 | res = APPLE_DOUBLE_REGEX.findall(filename) 55 | if len(res) > 0: 56 | return True 57 | 58 | return False 59 | 60 | 61 | def remove_system_files(root) -> None: 62 | """ 63 | Remove system nested within a directory. Files such as DS_Store & Thumbs.db 64 | 65 | Note: 66 | 67 | This function works recursively. 68 | 69 | Args: 70 | root: path to a folder 71 | 72 | """ 73 | for root, dirs, files in os.walk(root): 74 | for file_ in files: 75 | full_path = os.path.join(root, file_) 76 | 77 | if is_system_file(full_path): 78 | LOGGER.warn("Removing {}".format(full_path)) 79 | os.remove(full_path) 80 | 81 | 82 | class InvalidStrategy(Exception): 83 | """Invalid strategy for the current situation.""" 84 | 85 | 86 | class VersionStrategy(abc.ABC): 87 | """Base class for determining version information.""" 88 | 89 | @abc.abstractmethod 90 | def get_version(self) -> str: 91 | """Get version information. 92 | 93 | If unable to do so, an InvalidStrategy exception is raised. 94 | 95 | Returns: 96 | Version info as a string. 97 | """ 98 | 99 | 100 | class VersionFromMetadata(VersionStrategy): 101 | """Gets version info from the package metadata""" 102 | def get_version(self) -> str: 103 | try: 104 | return self.get_package_metadata() 105 | except metadata.PackageNotFoundError as error: 106 | raise InvalidStrategy from error 107 | 108 | @staticmethod 109 | def get_package_metadata() -> str: 110 | """Read version info from the package metadata.""" 111 | return metadata.version(__package__) 112 | 113 | 114 | class VersionFromGitCommit(VersionStrategy): 115 | """Gets version info from git commit.""" 116 | 117 | def get_version(self) -> str: 118 | git_exec = shutil.which('git') 119 | if git_exec is None: 120 | raise InvalidStrategy("Git not available") 121 | return self.get_git_hash(git_exec) 122 | 123 | @staticmethod 124 | def get_git_hash(git_exec: str) -> str: 125 | """Get the version hash value of the git 126 | 127 | Args: 128 | git_exec: path to git executable 129 | 130 | Returns: Returns a hash value from the head 131 | 132 | """ 133 | try: 134 | git_commit_hash_command = [ 135 | git_exec, 136 | 'rev-parse', '--short', 'HEAD' 137 | ] 138 | git_hash = subprocess.check_output(git_commit_hash_command) 139 | except subprocess.CalledProcessError as error: 140 | raise InvalidStrategy( 141 | f"Unable to determine git hash, reason: {error}" 142 | ) from error 143 | return f"git: {git_hash.decode('ascii')}" 144 | 145 | 146 | def current_version(strategies: typing.List[VersionStrategy] = None) -> str: 147 | """Get the current version number of Grabbags. 148 | 149 | This runs through the various strategies to determine grabbags's version. 150 | The first strategy to produce a value is used. 151 | 152 | By default the strategies order is as follows: 153 | 154 | 1) Check if there is package metadata (usually .egg-info) 155 | file which is generated when grabbags is installed. 156 | 157 | 2) Check if the current version is a git repo and if so, get the short 158 | commit hash value for the HEAD. 159 | 160 | When all else fails. The return value is 'Unknown' 161 | 162 | Args: 163 | strategies: List of strategies to determine the version. 164 | 165 | Returns: 166 | Returns the version number as a string or "Unknown" 167 | 168 | """ 169 | strategies = strategies if strategies is not None else [ 170 | VersionFromMetadata(), 171 | VersionFromGitCommit() 172 | ] 173 | for strategy in strategies: 174 | try: 175 | return strategy.get_version() 176 | except InvalidStrategy: 177 | continue 178 | return "Unknown" 179 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | setup( 4 | name='grabbags', 5 | version='0.0.3.dev0', 6 | packages=['grabbags'], 7 | url='https://github.com/amiaopensource/grabbags', 8 | license='GPLv3', 9 | author='AMIA', 10 | author_email='', 11 | description='', 12 | test_suite='tests', 13 | entry_points={ 14 | 'console_scripts': [ 15 | 'grabbags = grabbags.grabbags:main' 16 | ] 17 | }, 18 | install_requires=[ 19 | "bagit" 20 | ], 21 | tests_require=[ 22 | 'pytest', 23 | ], 24 | setup_requires=[ 25 | 'pytest' 26 | ], 27 | 28 | 29 | ) 30 | -------------------------------------------------------------------------------- /sonar-project.properties: -------------------------------------------------------------------------------- 1 | sonar.organization=amiaopensource 2 | sonar.projectKey=amiaopensource_grabbags 3 | sonar.host.url=https://sonarcloud.io 4 | sonar.sources=. 5 | sonar.exclusions=**/__pycache__/**,venv/**,build/**,dist/**,.tox/**,coverage-reports/**,xunit-reports/**,docs/**,*.xml 6 | sonar.tests=tests 7 | sonar.test.inclusions=tests/test*.py 8 | sonar.python.pylint.reportPath=reports/pylint.log 9 | sonar.python.coverage.reportPaths=coverage-reports/pythoncoverage-pytest.xml 10 | -------------------------------------------------------------------------------- /tests/test_bags.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import pytest 4 | import shutil 5 | import grabbags.bags 6 | import pathlib 7 | 8 | 9 | @pytest.fixture() 10 | def sample_bags(tmpdir_factory): 11 | data_dir = tmpdir_factory.mktemp("data") 12 | bags = { 13 | "valid": [ 14 | { 15 | "root": "1", 16 | "dirs": [ 17 | 18 | ["data"], 19 | ["data", "preservation"], 20 | ["data", "service"], 21 | ], 22 | "files": [ 23 | ["bagit.txt"], 24 | ["data", "preservation", "napl0154.mov"], 25 | ["data", "service", "napl0154.mp4"], 26 | ["manifest-sha256.txt"], 27 | ["manifest-sha512.txt"], 28 | ["tagmanifest-sha256.txt"], 29 | ["tagmanifest-sha512.txt"], 30 | ] 31 | }, 32 | ], 33 | "invalid": [ 34 | { 35 | "root": "b1", 36 | "dirs": [ 37 | ["sample"] 38 | ], 39 | "files":[ 40 | ["sample", "dummy.txt"] 41 | ] 42 | } 43 | ] 44 | } 45 | for bag in (bags['valid'] + bags['invalid']): 46 | os.mkdir(os.path.join(data_dir, bag["root"])) 47 | for dir_ in bag['dirs']: 48 | os.mkdir(os.path.join(data_dir, bag["root"], *dir_)) 49 | 50 | for file_path in bag['files']: 51 | sample_file_path = os.path.join(data_dir, bag["root"], *file_path) 52 | pathlib.Path(sample_file_path).touch() 53 | 54 | yield data_dir, bags 55 | shutil.rmtree(data_dir) 56 | 57 | 58 | def test_validate_bag(sample_bags): 59 | data_dir, bags = sample_bags 60 | 61 | for valid in bags["valid"]: 62 | bag_dir = os.path.join(data_dir, valid['root']) 63 | assert os.path.exists(bag_dir) 64 | assert grabbags.bags.is_bag(bag_dir) is True 65 | 66 | for invalid in bags["invalid"]: 67 | bag_dir = os.path.join(data_dir, invalid['root']) 68 | assert os.path.exists(bag_dir) 69 | assert grabbags.bags.is_bag(bag_dir) is False 70 | -------------------------------------------------------------------------------- /tests/test_grabbags.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import logging 3 | import os 4 | from unittest.mock import Mock, ANY 5 | 6 | import grabbags.utils 7 | import pytest 8 | import bagit 9 | 10 | 11 | def test_batch_validate(): 12 | # provide a directory 13 | pass 14 | 15 | 16 | def test_bulk_creation(): 17 | pass 18 | 19 | 20 | def test_delete_annoying_files(): 21 | sample_file = os.path.join(os.getcwd(), "dummy.txt") 22 | 23 | assert grabbags.utils.is_system_file(sample_file) is False 24 | 25 | 26 | @pytest.mark.parametrize("entry,", [ 27 | "._somethingsomething", 28 | "._f", 29 | "._~", 30 | "._something", 31 | ]) 32 | def test_apple_doubles_valid(entry): 33 | assert grabbags.utils.is_system_file(entry) is True 34 | 35 | 36 | @pytest.mark.parametrize("entry,", [ 37 | ".s", 38 | "asdfa.yes", 39 | "_.fdjlkdfj", 40 | "something._something", 41 | "fdjklfj ._ dklj", 42 | ".dj_djfklj" 43 | ]) 44 | def test_not_apple_doubles(entry): 45 | assert grabbags.utils.is_system_file(entry) is False 46 | 47 | 48 | class TestCliArgs: 49 | 50 | @pytest.mark.parametrize("cli_args", [ 51 | ["--help"], 52 | ["-h"], 53 | ['--version'], 54 | ['-v'], 55 | ]) 56 | def test_single_shot_commands(self, cli_args): 57 | # Test commands that don't actually run bags but quit with return code 58 | # of zero before, such as help 59 | from grabbags import grabbags 60 | 61 | with pytest.raises(SystemExit) as e: 62 | grabbags.main(cli_args, runner=Mock()) 63 | 64 | assert \ 65 | e.value.args[0] == 0, \ 66 | "if system exit is called with anything other than zero, the " \ 67 | "grabbags did not close successfully" 68 | 69 | def test_invalid_processes(self): 70 | from grabbags import grabbags 71 | with pytest.raises(SystemExit) as e: 72 | grabbags.main(['somedir', '--processes=-1']) 73 | assert e.value.args[0] != 0 74 | 75 | def test_invalid_fast_without_valid(self): 76 | from grabbags import grabbags 77 | with pytest.raises(SystemExit) as e: 78 | grabbags.main(['somedir', '--fast']) 79 | assert e.value.args[0] != 0 80 | 81 | def test_main_calls_callback(self): 82 | from grabbags import grabbags 83 | run = Mock() 84 | grabbags.main(['somedir'], runner=run) 85 | assert run.called is True 86 | 87 | 88 | @pytest.mark.parametrize("system_file", 89 | [ 90 | 'Thumbs.db', 91 | '.DS_Store', 92 | '._test' 93 | ]) 94 | def test_clean_bags_system_files(tmpdir, system_file): 95 | from grabbags import grabbags 96 | 97 | (tmpdir / "bag" / "text.txt").ensure() 98 | grabbags.main([tmpdir.strpath]) 99 | (tmpdir / "bag" / "data" / system_file).ensure() 100 | grabbags.main([tmpdir.strpath, "--clean"]) 101 | assert (tmpdir / "bag" / "data" / system_file).exists() is False 102 | assert (tmpdir / "bag" / "data" / "text.txt").exists() 103 | 104 | 105 | def test_clean_bags_no_system_files(tmpdir): 106 | from grabbags import grabbags 107 | 108 | (tmpdir / "bag" / "text.txt").ensure() 109 | grabbags.main([tmpdir.strpath]) 110 | grabbags.main([tmpdir.strpath, "--clean"]) 111 | assert (tmpdir / "bag" / "data" / "text.txt").exists() 112 | 113 | 114 | @pytest.mark.parametrize( 115 | "arguments", 116 | [ 117 | ["--fast", "fakepath"], 118 | ['--no-checksums', "fakepath"], 119 | ['--no-checksums', '--no-system-files', "fakepath"], 120 | ['--validate', '--clean', "fakepath"], 121 | ['--clean', '--no-checksums', "fakepath"], 122 | ['--processes', 'j', "fakepath"], 123 | ['--validate', '--sha256', "fakepath"], 124 | ['--clean', '--no-system-files', "fakepath"], 125 | ['--clean', '--md5', "fakepath"], 126 | ['--clean'], 127 | ]) 128 | def test_invalid_cli_args(arguments): 129 | from grabbags import grabbags 130 | with pytest.raises(SystemExit): 131 | run = Mock() 132 | grabbags.main(arguments, runner=run) 133 | run.assert_not_called() 134 | 135 | 136 | @pytest.mark.parametrize("arguments", [ 137 | ['--validate', 'fakepath'], 138 | ['--validate', '--fast', 'fakepath'], 139 | ["fakepath"], 140 | ]) 141 | def test_valid_cli_args(tmpdir, arguments): 142 | from grabbags import grabbags 143 | run = Mock() 144 | grabbags.main(arguments, runner=run) 145 | run.assert_called() 146 | 147 | 148 | @pytest.fixture() 149 | def fake_bag_path(monkeypatch): 150 | fake_path_name = "fakepath" 151 | 152 | def scandir(path): 153 | if path == fake_path_name: 154 | for b in [ 155 | Mock(is_dir=Mock(return_value=True), 156 | path=os.path.join(path, "bag") 157 | ) 158 | ]: 159 | yield b 160 | monkeypatch.setattr(os, "scandir", scandir) 161 | return fake_path_name 162 | 163 | 164 | @pytest.mark.filterwarnings("ignore::PendingDeprecationWarning") 165 | def test_run_validate(monkeypatch, fake_bag_path): 166 | from grabbags import grabbags 167 | from argparse import Namespace 168 | args = Namespace( 169 | action_type='validate', 170 | directories=[ 171 | fake_bag_path 172 | ] 173 | ) 174 | validate_bag = Mock() 175 | monkeypatch.setattr(grabbags, "validate_bag", validate_bag) 176 | grabbags.run(args) 177 | validate_bag.assert_called() 178 | 179 | 180 | @pytest.mark.filterwarnings("ignore::PendingDeprecationWarning") 181 | def test_run_cleaned(monkeypatch, fake_bag_path): 182 | from grabbags import grabbags 183 | from argparse import Namespace 184 | args = Namespace( 185 | action_type='clean', 186 | directories=[ 187 | fake_bag_path 188 | ] 189 | ) 190 | clean_bag = Mock() 191 | monkeypatch.setattr(grabbags, "clean_bag", clean_bag) 192 | grabbags.run(args) 193 | clean_bag.assert_called() 194 | 195 | 196 | @pytest.mark.filterwarnings("ignore::PendingDeprecationWarning") 197 | def test_run_create(monkeypatch, fake_bag_path): 198 | from grabbags import grabbags 199 | from argparse import Namespace 200 | args = Namespace( 201 | action_type='create', 202 | directories=[ 203 | fake_bag_path 204 | ] 205 | ) 206 | make_bag = Mock() 207 | monkeypatch.setattr(grabbags, "make_bag", make_bag) 208 | grabbags.run(args) 209 | make_bag.assert_called() 210 | 211 | 212 | @pytest.mark.filterwarnings("ignore::PendingDeprecationWarning") 213 | def test_run_create_invalid_bag_error(monkeypatch, fake_bag_path, caplog): 214 | from grabbags import grabbags 215 | from bagit import BagError 216 | from argparse import Namespace 217 | make_bag = Mock(side_effect=BagError) 218 | monkeypatch.setattr(grabbags, "make_bag", make_bag) 219 | args = Namespace( 220 | action_type='create', 221 | directories=[ 222 | fake_bag_path 223 | ] 224 | ) 225 | grabbags.run(args) 226 | assert any("could not be bagged" in m for m in caplog.messages) 227 | 228 | 229 | @pytest.mark.filterwarnings("ignore::PendingDeprecationWarning") 230 | def test_run_validate_invalid_bag_error(monkeypatch, fake_bag_path, caplog): 231 | from grabbags import grabbags 232 | from bagit import BagError 233 | from argparse import Namespace 234 | validate_bag = Mock(side_effect=BagError) 235 | monkeypatch.setattr(grabbags, "validate_bag", validate_bag) 236 | args = Namespace( 237 | action_type='validate', 238 | directories=[ 239 | fake_bag_path 240 | ] 241 | ) 242 | grabbags.run(args) 243 | assert any("is invalid" in m for m in caplog.messages) 244 | 245 | 246 | @pytest.mark.filterwarnings("ignore::PendingDeprecationWarning") 247 | def test_run_clean_invalid_bag_error(monkeypatch, fake_bag_path, caplog): 248 | from grabbags import grabbags 249 | from bagit import BagError 250 | from argparse import Namespace 251 | clean_bag = Mock(side_effect=BagError) 252 | monkeypatch.setattr(grabbags, "clean_bag", clean_bag) 253 | args = Namespace( 254 | action_type='clean', 255 | directories=[ 256 | fake_bag_path 257 | ] 258 | ) 259 | grabbags.run(args) 260 | assert any("cannot be cleaned" in m for m in caplog.messages) 261 | 262 | 263 | @pytest.mark.filterwarnings("ignore::DeprecationWarning", 264 | "ignore::PendingDeprecationWarning" 265 | ) 266 | def test_run_create_empty_bag(monkeypatch, tmpdir, caplog): 267 | from argparse import Namespace 268 | from grabbags import grabbags 269 | 270 | (tmpdir / "empty_bag").ensure_dir() 271 | 272 | args = Namespace( 273 | action_type='create', 274 | no_system_files=True, 275 | bag_info={}, 276 | processes=1, 277 | checksums=[], 278 | directories=[ 279 | tmpdir.strpath 280 | ] 281 | ) 282 | 283 | grabbags.run(args) 284 | assert (tmpdir / "empty_bag" / "data").exists() is False 285 | assert any("is an empty directory" in m for m in caplog.messages) 286 | 287 | 288 | @pytest.mark.filterwarnings("ignore::DeprecationWarning", 289 | "ignore::PendingDeprecationWarning" 290 | ) 291 | def test_run_clean_no_system_files_message(monkeypatch, tmpdir, caplog): 292 | 293 | from grabbags import grabbags 294 | from argparse import Namespace 295 | caplog.set_level(logging.INFO) 296 | 297 | (tmpdir / "bag" / "text.txt").ensure() 298 | run_args = Namespace( 299 | action_type='create', 300 | no_system_files=True, 301 | bag_info={}, 302 | processes=1, 303 | checksums=["md5"], 304 | directories=[ 305 | tmpdir 306 | ] 307 | ) 308 | grabbags.run(run_args) 309 | 310 | args = Namespace( 311 | action_type='clean', 312 | directories=[ 313 | tmpdir 314 | ] 315 | ) 316 | grabbags.run(args) 317 | assert any("No system files located" in m for m in caplog.messages) 318 | 319 | 320 | @pytest.mark.filterwarnings("ignore::DeprecationWarning", 321 | "ignore::PendingDeprecationWarning" 322 | ) 323 | def test_run_clean_not_found(monkeypatch, tmpdir, caplog): 324 | 325 | from grabbags import grabbags 326 | from argparse import Namespace 327 | 328 | (tmpdir / "bag" / "text.txt").ensure() 329 | run_args = Namespace( 330 | action_type='create', 331 | no_system_files=True, 332 | bag_info={}, 333 | processes=1, 334 | checksums=["md5"], 335 | directories=[ 336 | tmpdir 337 | ] 338 | ) 339 | 340 | grabbags.run(run_args) 341 | (tmpdir / "bag" / "data" / "unexpected_file.txt").ensure() 342 | args = Namespace( 343 | action_type='clean', 344 | directories=[ 345 | tmpdir 346 | ] 347 | ) 348 | grabbags.run(args) 349 | assert any("Found file not in manifest" in m for m in caplog.messages) 350 | 351 | 352 | class TestGrabbagsRunner: 353 | def test_run_validate(self, fake_bag_path, monkeypatch): 354 | from grabbags import grabbags 355 | from argparse import Namespace 356 | args = Namespace( 357 | action_type='validate', 358 | directories=[ 359 | fake_bag_path 360 | ] 361 | ) 362 | runner = grabbags.GrabbagsRunner() 363 | execute = Mock() 364 | monkeypatch.setattr(grabbags.ValidateBag, "execute", execute) 365 | runner.run(args) 366 | execute.assert_called() 367 | 368 | def test_run_cleaned(self, fake_bag_path, monkeypatch): 369 | from grabbags import grabbags 370 | from argparse import Namespace 371 | args = Namespace( 372 | action_type='clean', 373 | directories=[ 374 | fake_bag_path 375 | ] 376 | ) 377 | runner = grabbags.GrabbagsRunner() 378 | execute = Mock() 379 | monkeypatch.setattr(grabbags.CleanBag, "execute", execute) 380 | runner.run(args) 381 | execute.assert_called() 382 | 383 | def test_run_create(self, fake_bag_path, monkeypatch): 384 | from grabbags import grabbags 385 | from argparse import Namespace 386 | args = Namespace( 387 | action_type='create', 388 | directories=[ 389 | fake_bag_path 390 | ] 391 | ) 392 | runner = grabbags.GrabbagsRunner() 393 | execute = Mock() 394 | monkeypatch.setattr(grabbags.MakeBag, "execute", execute) 395 | runner.run(args) 396 | execute.assert_called() 397 | 398 | def test_run_create_invalid_bag_error( 399 | self, fake_bag_path, caplog, monkeypatch): 400 | 401 | from grabbags import grabbags 402 | from bagit import BagError 403 | from argparse import Namespace 404 | runner = grabbags.GrabbagsRunner() 405 | execute = Mock(side_effect=BagError) 406 | monkeypatch.setattr(grabbags.MakeBag, "execute", execute) 407 | args = Namespace( 408 | action_type='create', 409 | directories=[ 410 | fake_bag_path 411 | ] 412 | ) 413 | runner.run(args) 414 | assert any("could not be bagged" in m for m in caplog.messages) 415 | 416 | def test_run_validate_invalid_bag_error( 417 | self, fake_bag_path, caplog, monkeypatch): 418 | 419 | from grabbags import grabbags 420 | from bagit import BagError 421 | from argparse import Namespace 422 | runner = grabbags.GrabbagsRunner() 423 | execute = Mock(side_effect=BagError) 424 | monkeypatch.setattr(grabbags, "is_bag", lambda x: True) 425 | monkeypatch.setattr(grabbags.bagit.Bag, "_open", Mock()) 426 | monkeypatch.setattr(grabbags.bagit.Bag, "validate", execute) 427 | args = Namespace( 428 | processes=1, 429 | fast=False, 430 | no_checksums=False, 431 | action_type='validate', 432 | directories=[ 433 | fake_bag_path 434 | ] 435 | ) 436 | runner.run(args) 437 | assert any("is invalid" in m for m in caplog.messages) 438 | 439 | def test_run_clean_invalid_bag_error(self, fake_bag_path, caplog, 440 | monkeypatch): 441 | from grabbags import grabbags 442 | from bagit import BagError 443 | from argparse import Namespace 444 | runner = grabbags.GrabbagsRunner() 445 | execute = Mock(side_effect=BagError) 446 | monkeypatch.setattr(grabbags.CleanBag, "execute", execute) 447 | args = Namespace( 448 | action_type='clean', 449 | directories=[ 450 | fake_bag_path 451 | ] 452 | ) 453 | 454 | runner.run(args) 455 | assert any("cannot be cleaned" in m for m in caplog.messages) 456 | 457 | def test_run_create_empty_bag(self, tmpdir, caplog): 458 | from argparse import Namespace 459 | from grabbags import grabbags 460 | (tmpdir / "empty_bag").ensure_dir() 461 | 462 | args = Namespace( 463 | action_type='create', 464 | no_system_files=True, 465 | bag_info={}, 466 | processes=1, 467 | checksums=[], 468 | directories=[ 469 | tmpdir.strpath 470 | ] 471 | ) 472 | runner = grabbags.GrabbagsRunner() 473 | runner.run(args) 474 | assert (tmpdir / "empty_bag" / "data").exists() is False 475 | assert any("is an empty directory" in m for m in caplog.messages) 476 | 477 | def test_run_clean_no_system_files_message(self, tmpdir, caplog): 478 | from grabbags import grabbags 479 | from argparse import Namespace 480 | caplog.set_level(logging.INFO) 481 | 482 | (tmpdir / "bag" / "text.txt").ensure() 483 | run_args = Namespace( 484 | action_type='create', 485 | no_system_files=True, 486 | bag_info={}, 487 | processes=1, 488 | checksums=["md5"], 489 | directories=[ 490 | tmpdir 491 | ] 492 | ) 493 | runner = grabbags.GrabbagsRunner() 494 | runner.run(run_args) 495 | 496 | args = Namespace( 497 | action_type='clean', 498 | directories=[ 499 | tmpdir 500 | ] 501 | ) 502 | runner.run(args) 503 | assert any("No system files located" in m for m in caplog.messages) 504 | 505 | def test_run_clean_not_found(self, tmpdir, caplog): 506 | from grabbags import grabbags 507 | from argparse import Namespace 508 | 509 | (tmpdir / "bag" / "text.txt").ensure() 510 | run_args = Namespace( 511 | action_type='create', 512 | no_system_files=True, 513 | bag_info={}, 514 | processes=1, 515 | checksums=["md5"], 516 | directories=[ 517 | tmpdir 518 | ] 519 | ) 520 | runner = grabbags.GrabbagsRunner() 521 | runner.run(run_args) 522 | (tmpdir / "bag" / "data" / "unexpected_file.txt").ensure() 523 | args = Namespace( 524 | action_type='clean', 525 | directories=[ 526 | tmpdir 527 | ] 528 | ) 529 | runner.run(args) 530 | assert any("Found file not in manifest" in m for m in caplog.messages) 531 | 532 | def test_run_clean_counting(self, monkeypatch, tmpdir, caplog): 533 | 534 | from grabbags import grabbags 535 | from argparse import Namespace 536 | caplog.set_level(logging.INFO) 537 | 538 | (tmpdir / "valid_bag" / "text.txt").ensure() 539 | (tmpdir / "empty_bag").ensure_dir() 540 | 541 | run_args = Namespace( 542 | action_type='create', 543 | no_system_files=True, 544 | bag_info={}, 545 | processes=1, 546 | checksums=["md5"], 547 | directories=[ 548 | tmpdir 549 | ] 550 | ) 551 | create_runner = grabbags.GrabbagsRunner() 552 | create_runner.run(run_args) 553 | assert \ 554 | len(create_runner.successes) == 1 and \ 555 | len(create_runner.skipped) == 1 556 | 557 | files = [ 558 | "sdadfasdfdsaf.mp4", 559 | "asdfasdfasdffasdfasdf.mp4", 560 | "still_image_1.jpg", 561 | "still_image_2.jpg", 562 | "is_this_an_evil_confusing_access_copy.mp4" 563 | ] 564 | for f in files: 565 | (tmpdir / "skipped" / f).ensure() 566 | 567 | for num in range(20): 568 | (tmpdir / "skipped" / f"evil_file{num}.mp4").ensure() 569 | 570 | args = Namespace( 571 | action_type='clean', 572 | directories=[ 573 | tmpdir 574 | ] 575 | ) 576 | cleaning_runner = grabbags.GrabbagsRunner() 577 | cleaning_runner.run(args) 578 | 579 | assert any("No system files located" in m for m in caplog.messages) 580 | assert len(cleaning_runner.successes) == 0, "wrong successes" 581 | assert len(cleaning_runner.skipped) == 1, "wrong skipped" 582 | not_a_bag = [ 583 | x for x in cleaning_runner.results 584 | if 'not_a_bag' in x and x['not_a_bag'] is True 585 | ] 586 | assert len(not_a_bag) == 2 587 | 588 | def test_run_clean_counting_only(self, monkeypatch, tmpdir): 589 | 590 | from grabbags import grabbags 591 | from argparse import Namespace 592 | 593 | (tmpdir / "valid_bag" / "text.txt").ensure() 594 | (tmpdir / "empty_bag").ensure_dir() 595 | 596 | run_args = Namespace( 597 | action_type='create', 598 | no_system_files=True, 599 | bag_info={}, 600 | processes=1, 601 | checksums=["md5"], 602 | directories=[ 603 | tmpdir 604 | ] 605 | ) 606 | create_runner = grabbags.GrabbagsRunner() 607 | create_runner.run(run_args) 608 | assert \ 609 | len(create_runner.successes) == 1 and \ 610 | len(create_runner.skipped) == 1 611 | 612 | def test_run_clean_only(self, monkeypatch, tmpdir): 613 | from grabbags import grabbags 614 | from argparse import Namespace 615 | 616 | for f in [ 617 | "sdadfasdfdsaf.mp4", 618 | "asdfasdfasdffasdfasdf.mp4", 619 | "still_image_1.jpg", 620 | "still_image_2.jpg", 621 | "is_this_an_evil_confusing_access_copy.mp4" 622 | ]: 623 | (tmpdir / "skipped" / f).ensure() 624 | 625 | for num in range(20): 626 | (tmpdir / "skipped" / f"evil_file{num}.mp4").ensure() 627 | 628 | args = Namespace( 629 | action_type='clean', 630 | directories=[ 631 | tmpdir 632 | ] 633 | ) 634 | cleaning_runner = grabbags.GrabbagsRunner() 635 | cleaning_runner.run(args) 636 | 637 | assert len(cleaning_runner.successes) == 0, "wrong successes" 638 | assert len(cleaning_runner.skipped) == 0, "wrong skipped" 639 | not_a_bag = [ 640 | x for x in cleaning_runner.results 641 | if 'not_a_bag' in x and x['not_a_bag'] is True 642 | ] 643 | assert len(not_a_bag) == 1 644 | 645 | 646 | class TestValidateBag: 647 | def test_fails_is_bag(self, monkeypatch): 648 | from grabbags import grabbags 649 | args = argparse.Namespace() 650 | 651 | logger = logging.getLogger(__name__) 652 | runner = grabbags.ValidateBag(args, logger) 653 | some_directory = "something" 654 | 655 | with monkeypatch.context() as mp: 656 | mp.setattr(grabbags, "is_bag", lambda x: False) 657 | runner.execute(some_directory) 658 | assert runner.results['not_a_bag'] is True and \ 659 | runner.results['path'] == some_directory 660 | assert len(runner.successes) == 0 661 | 662 | def test_success(self, monkeypatch): 663 | from grabbags import grabbags 664 | some_directory = "something" 665 | run_args = argparse.Namespace( 666 | action_type='validate', 667 | no_system_files=True, 668 | bag_info={}, 669 | processes=1, 670 | checksums=[], 671 | fast=False, 672 | no_checksums=False, 673 | directories=[ 674 | some_directory 675 | ] 676 | ) 677 | 678 | logger = logging.getLogger(__name__) 679 | runner = grabbags.ValidateBag(run_args, logger) 680 | 681 | with monkeypatch.context() as mp: 682 | mp.setattr(grabbags, "is_bag", lambda x: True) 683 | 684 | bag = Mock() 685 | mp.setattr(grabbags.bagit, "Bag", bag) 686 | 687 | runner.execute(some_directory) 688 | 689 | assert len(runner.successes) == 1 and \ 690 | runner.successes[0] == some_directory 691 | 692 | @pytest.mark.parametrize( 693 | "exception_type, exception_message", 694 | [ 695 | (bagit.BagValidationError, "somethings is wrong with your bag"), 696 | (bagit.ChecksumMismatch, "somethings is wrong with your checksum"), 697 | (bagit.FileMissing, "a file missing YO!!!"), 698 | (bagit.UnexpectedFile, "You have an unexpected file"), 699 | ] 700 | ) 701 | def test_bag_validation_failure(self, monkeypatch, 702 | exception_type, 703 | exception_message): 704 | from grabbags import grabbags 705 | some_directory = "something" 706 | run_args = argparse.Namespace( 707 | action_type='validate', 708 | no_system_files=True, 709 | bag_info={}, 710 | processes=1, 711 | checksums=[], 712 | fast=False, 713 | no_checksums=False, 714 | directories=[ 715 | some_directory 716 | ] 717 | ) 718 | 719 | logger = logging.getLogger(__name__) 720 | runner = grabbags.ValidateBag(run_args, logger) 721 | 722 | with monkeypatch.context() as mp: 723 | mp.setattr(grabbags, "is_bag", lambda x: True) 724 | 725 | mp.setattr(grabbags.bagit.Bag, "_open", Mock()) 726 | mp.setattr( 727 | grabbags.bagit.Bag, "validate", 728 | Mock( 729 | side_effect=exception_type(exception_message) 730 | ) 731 | ) 732 | 733 | runner.execute(some_directory) 734 | 735 | assert len(runner.successes) == 0 and \ 736 | len(runner.failures) == 1 737 | 738 | def test_no_checks_completeness_only(self, monkeypatch): 739 | from grabbags import grabbags 740 | some_directory = "something" 741 | run_args = argparse.Namespace( 742 | action_type='validate', 743 | no_system_files=True, 744 | bag_info={}, 745 | processes=1, 746 | checksums=[], 747 | fast=False, 748 | no_checksums=True, 749 | directories=[ 750 | some_directory 751 | ] 752 | ) 753 | 754 | logger = logging.getLogger(__name__) 755 | 756 | with monkeypatch.context() as mp: 757 | runner = grabbags.ValidateBag(run_args, logger) 758 | mp.setattr(grabbags, "is_bag", lambda x: True) 759 | 760 | bag = Mock(validate=Mock()) 761 | 762 | def mock_bag(*args, **kwargs): 763 | return bag 764 | 765 | mp.setattr(grabbags.bagit, "Bag", mock_bag) 766 | 767 | runner.execute(some_directory) 768 | 769 | bag.validate.assert_any_call( 770 | processes=ANY, 771 | fast=ANY, 772 | completeness_only=True 773 | ) 774 | 775 | assert len(runner.successes) == 1 and \ 776 | runner.successes[0] == some_directory 777 | 778 | def test_report_not_a_bag(self): 779 | from argparse import Namespace 780 | from grabbags import grabbags 781 | args = Namespace( 782 | action_type='validate', 783 | directories=[ 784 | "directory1", 785 | "directory2", 786 | ] 787 | ) 788 | runner = grabbags.GrabbagsRunner() 789 | runner.successes = [] 790 | runner.failures = [] 791 | runner.results = [ 792 | { 793 | 'not_a_bag': True, 794 | "path": "directory1", 795 | }, 796 | { 797 | 'not_a_bag': True, 798 | "path": "directory2", 799 | } 800 | ] 801 | 802 | report = runner.get_report(args) 803 | assert report == """Summary Report: 804 | 0 bags validated successfully 805 | 0 failures 806 | 2 directories are not bags 807 | """ 808 | 809 | def test_report_basic(self): 810 | from argparse import Namespace 811 | from grabbags import grabbags 812 | args = Namespace( 813 | action_type='validate', 814 | directories=[ 815 | "directory_root", 816 | ] 817 | ) 818 | 819 | runner = grabbags.GrabbagsRunner() 820 | runner.successes = [ 821 | "directory1", 822 | "directory2", 823 | "directory3", 824 | "directory4", 825 | ] 826 | runner.failures = [] 827 | runner.skipped = [] 828 | runner.results = [] 829 | report = runner.get_report(args) 830 | assert report == """Summary Report: 831 | 4 bags validated successfully 832 | 0 failures 833 | 0 directories are not bags 834 | """ 835 | 836 | def test_report_empty(self): 837 | from argparse import Namespace 838 | from grabbags import grabbags 839 | args = Namespace( 840 | action_type='validate', 841 | directories=[ 842 | "directory_root", 843 | ] 844 | ) 845 | 846 | runner = grabbags.GrabbagsRunner() 847 | runner.successes = [] 848 | runner.failures = [] 849 | runner.skipped = [] 850 | runner.results = [ 851 | # { 852 | # "not_a_bag": False, 853 | # "path": "directory1", 854 | # }, 855 | # { 856 | # "not_a_bag": False, 857 | # "path": "directory2", 858 | # }, 859 | # { 860 | # "not_a_bag": False, 861 | # "path": "directory3", 862 | # }, 863 | # { 864 | # "not_a_bag": False, 865 | # "path": "directory4", 866 | # } 867 | ] 868 | report = runner.get_report(args) 869 | assert report == """Summary Report: 870 | 0 bags validated successfully 871 | 0 failures 872 | 0 directories are not bags 873 | """ 874 | 875 | def test_report_failed(self): 876 | from argparse import Namespace 877 | from grabbags import grabbags 878 | args = Namespace( 879 | action_type='validate', 880 | directories=[ 881 | "directory_root", 882 | ] 883 | ) 884 | 885 | runner = grabbags.GrabbagsRunner() 886 | runner.successes = [] 887 | runner.failures = [ 888 | "directory1", 889 | "directory2", 890 | "directory3", 891 | "directory4", 892 | ] 893 | 894 | runner.skipped = [] 895 | runner.results = [ 896 | # { 897 | # "not_a_bag": False, 898 | # "path": "directory1", 899 | # }, 900 | # { 901 | # "not_a_bag": False, 902 | # "path": "directory2", 903 | # }, 904 | # { 905 | # "not_a_bag": False, 906 | # "path": "directory3", 907 | # }, 908 | # { 909 | # "not_a_bag": False, 910 | # "path": "directory4", 911 | # } 912 | ] 913 | report = runner.get_report(args) 914 | assert report == """Summary Report: 915 | 0 bags validated successfully 916 | 4 failures 917 | 0 directories are not bags 918 | """ 919 | 920 | 921 | class TestClean: 922 | 923 | @pytest.fixture() 924 | def empty_bag_path(self, tmpdir): 925 | source_dir = tmpdir.ensure_dir() 926 | 927 | (tmpdir / "bag-info.txt").write_text( 928 | """Bag-Software-Agent: bagit.py v1.8.1 929 | Bagging-Date: 2021-05-04 930 | Payload-Oxum: 13864945.6 931 | """, 932 | encoding="utf-8") 933 | 934 | (tmpdir / "bagit.txt").write_text( 935 | """BagIt-Version: 0.97 936 | Tag-File-Character-Encoding: UTF-8 937 | """, 938 | encoding="utf-8") 939 | 940 | (tmpdir / "manifest-md5.txt").ensure() 941 | (tmpdir / "tagmanifest-md5.txt").ensure() 942 | (tmpdir / "data").ensure_dir() 943 | 944 | return source_dir 945 | 946 | def test_empty_clean(self, empty_bag_path): 947 | from grabbags import grabbags 948 | some_directory = empty_bag_path.strpath 949 | run_args = argparse.Namespace( 950 | action_type='clean', 951 | no_system_files=True, 952 | bag_info={}, 953 | processes=1, 954 | checksums=[], 955 | fast=False, 956 | no_checksums=True, 957 | directories=[ 958 | some_directory 959 | ] 960 | ) 961 | 962 | runner = grabbags.CleanBag(run_args) 963 | runner.execute(some_directory) 964 | assert runner.successful is True 965 | 966 | def test_clean_manifest_includes_hidden_file(self, empty_bag_path): 967 | # skips a directory that is not a bag and contains hidden files 968 | # skips a directory that is not a bag and contains NO hidden files 969 | # creates a test bag that contains a manifest file that INCLUDES hidden 970 | # files 971 | from grabbags import grabbags 972 | new_bag_path = empty_bag_path 973 | some_directory = new_bag_path.strpath 974 | run_args = argparse.Namespace( 975 | action_type='clean', 976 | no_system_files=True, 977 | bag_info={}, 978 | processes=1, 979 | checksums=[], 980 | fast=False, 981 | no_checksums=True, 982 | directories=[ 983 | some_directory 984 | ] 985 | ) 986 | 987 | (new_bag_path / "manifest-md5.txt").write_text( 988 | """4990c459b26dd57fc4aac9d918ac61b4 data/DSC_0068.JPG 989 | 4990c459b26dd57fc4aac9d918ac61b4 data/.DS_Store 990 | """, 991 | encoding="utf-8" 992 | ) 993 | 994 | (new_bag_path / "data" / "DSC_0068.JPG").ensure() 995 | (new_bag_path / "data" / ".DS_Store").ensure() 996 | 997 | runner = grabbags.CleanBag(run_args) 998 | runner.execute(some_directory) 999 | assert runner.successful is True and \ 1000 | (new_bag_path / "data" / ".DS_Store").exists() and \ 1001 | (new_bag_path / "data" / "DSC_0068.JPG").exists() 1002 | 1003 | def test_clean_manifest_does_not_include_hidden_file(self, empty_bag_path): 1004 | # creates a test bag that contains a manifest with NO hidden files, but 1005 | # hidden files are present in the data folder 1006 | from grabbags import grabbags 1007 | new_bag_path = empty_bag_path 1008 | some_directory = new_bag_path.strpath 1009 | run_args = argparse.Namespace( 1010 | action_type='clean', 1011 | no_system_files=True, 1012 | bag_info={}, 1013 | processes=1, 1014 | checksums=[], 1015 | fast=False, 1016 | no_checksums=True, 1017 | directories=[ 1018 | some_directory 1019 | ] 1020 | ) 1021 | 1022 | (new_bag_path / "manifest-md5.txt").write_text( 1023 | """4990c459b26dd57fc4aac9d918ac61b4 data/DSC_0068.JPG 1024 | """, 1025 | encoding="utf-8" 1026 | ) 1027 | 1028 | (new_bag_path / "data" / "DSC_0068.JPG").ensure() 1029 | (new_bag_path / "data" / ".DS_Store").ensure() 1030 | 1031 | runner = grabbags.CleanBag(run_args) 1032 | runner.execute(some_directory) 1033 | assert runner.successful is True and \ 1034 | not (new_bag_path / "data" / ".DS_Store").exists() and \ 1035 | (new_bag_path / "data" / "DSC_0068.JPG").exists() 1036 | 1037 | def test_clean_manifest_includes_hidden_file_and_extra_hidden_file( 1038 | self, empty_bag_path): 1039 | 1040 | # EDGE CASE creates a test bag that contains a manifest file that 1041 | # INCLUDES hidden files in the manifest AND additional hidden files NOT 1042 | # in the manifest. 1043 | from grabbags import grabbags 1044 | new_bag_path = empty_bag_path 1045 | some_directory = new_bag_path.strpath 1046 | run_args = argparse.Namespace( 1047 | action_type='clean', 1048 | no_system_files=True, 1049 | bag_info={}, 1050 | processes=1, 1051 | checksums=[], 1052 | fast=False, 1053 | no_checksums=True, 1054 | directories=[ 1055 | some_directory 1056 | ] 1057 | ) 1058 | 1059 | (new_bag_path / "manifest-md5.txt").write_text( 1060 | """4990c459b26dd57fc4aac9d918ac61b4 data/DSC_0068.JPG 1061 | 4990c459b26dd57fc4aac9d918ac61b4 data/.DS_Store 1062 | """, 1063 | encoding="utf-8" 1064 | ) 1065 | 1066 | (new_bag_path / "data" / "DSC_0068.JPG").ensure() 1067 | (new_bag_path / "data" / ".DS_Store").ensure() 1068 | (new_bag_path / "data" / "images" / ".DS_Store").ensure() 1069 | 1070 | runner = grabbags.CleanBag(run_args) 1071 | runner.execute(some_directory) 1072 | assert runner.successful is True and \ 1073 | (new_bag_path / "data" / ".DS_Store").exists() and \ 1074 | (new_bag_path / "data" / "DSC_0068.JPG").exists() and \ 1075 | not (new_bag_path / "data" / "images" / ".DS_Store").exists() 1076 | 1077 | def test_report_basic(self): 1078 | from argparse import Namespace 1079 | from grabbags import grabbags 1080 | args = Namespace( 1081 | action_type='clean', 1082 | directories=[ 1083 | "directory_root", 1084 | ] 1085 | ) 1086 | 1087 | runner = grabbags.GrabbagsRunner() 1088 | runner.successes = [ 1089 | "directory1", 1090 | "directory2", 1091 | "directory3", 1092 | "directory4", 1093 | ] 1094 | runner.failures = [] 1095 | runner.skipped = [] 1096 | runner.results = [ 1097 | # { 1098 | # "not_a_bag": False, 1099 | # "path": "directory1", 1100 | # }, 1101 | # { 1102 | # "not_a_bag": False, 1103 | # "path": "directory2", 1104 | # }, 1105 | # { 1106 | # "not_a_bag": False, 1107 | # "path": "directory3", 1108 | # }, 1109 | # { 1110 | # "not_a_bag": False, 1111 | # "path": "directory4", 1112 | # } 1113 | ] 1114 | report = runner.get_report(args) 1115 | assert report == """Summary Report: 1116 | 4 bags cleaned successfully 1117 | 0 failures 1118 | 0 bags are already clean 1119 | 0 directories are not bags 1120 | """ 1121 | 1122 | def test_report_failures(self): 1123 | from argparse import Namespace 1124 | from grabbags import grabbags 1125 | args = Namespace( 1126 | action_type='clean', 1127 | directories=[ 1128 | "directory_root", 1129 | ] 1130 | ) 1131 | 1132 | runner = grabbags.GrabbagsRunner() 1133 | runner.successes = [] 1134 | runner.failures = [ 1135 | "directory1", 1136 | "directory2", 1137 | "directory3", 1138 | "directory4", 1139 | ] 1140 | runner.skipped = [] 1141 | runner.results = [ 1142 | 1143 | # { 1144 | # "not_a_bag": False, 1145 | # "path": "directory1", 1146 | # }, 1147 | # { 1148 | # "not_a_bag": False, 1149 | # "path": "directory2", 1150 | # }, 1151 | # { 1152 | # "not_a_bag": False, 1153 | # "path": "directory3", 1154 | # }, 1155 | # { 1156 | # "not_a_bag": False, 1157 | # "path": "directory4", 1158 | # } 1159 | ] 1160 | report = runner.get_report(args) 1161 | assert report == """Summary Report: 1162 | 0 bags cleaned successfully 1163 | 4 failures 1164 | 0 bags are already clean 1165 | 0 directories are not bags 1166 | """ 1167 | 1168 | def test_report_already_cleaned(self): 1169 | from argparse import Namespace 1170 | from grabbags import grabbags 1171 | args = Namespace( 1172 | action_type='clean', 1173 | directories=[ 1174 | "directory_root", 1175 | ] 1176 | ) 1177 | 1178 | runner = grabbags.GrabbagsRunner() 1179 | runner.successes = [] 1180 | runner.failures = [ 1181 | ] 1182 | runner.skipped = [ 1183 | "directory1", 1184 | "directory2", 1185 | "directory3", 1186 | "directory4", 1187 | ] 1188 | runner.results = [ 1189 | 1190 | # { 1191 | # "not_a_bag": False, 1192 | # "path": "directory1", 1193 | # }, 1194 | # { 1195 | # "not_a_bag": False, 1196 | # "path": "directory2", 1197 | # }, 1198 | # { 1199 | # "not_a_bag": False, 1200 | # "path": "directory3", 1201 | # }, 1202 | # { 1203 | # "not_a_bag": False, 1204 | # "path": "directory4", 1205 | # } 1206 | ] 1207 | report = runner.get_report(args) 1208 | assert report == """Summary Report: 1209 | 0 bags cleaned successfully 1210 | 0 failures 1211 | 4 bags are already clean 1212 | 0 directories are not bags 1213 | """ 1214 | 1215 | def test_report_not_bags(self): 1216 | from argparse import Namespace 1217 | from grabbags import grabbags 1218 | args = Namespace( 1219 | action_type='clean', 1220 | directories=[ 1221 | "directory_root", 1222 | ] 1223 | ) 1224 | 1225 | runner = grabbags.GrabbagsRunner() 1226 | runner.successes = [] 1227 | runner.failures = [] 1228 | runner.skipped = [] 1229 | runner.results = [ 1230 | { 1231 | "not_a_bag": True, 1232 | "path": "directory1", 1233 | }, 1234 | { 1235 | "not_a_bag": True, 1236 | "path": "directory2", 1237 | }, 1238 | { 1239 | "not_a_bag": True, 1240 | "path": "directory3", 1241 | }, 1242 | { 1243 | "not_a_bag": True, 1244 | "path": "directory4", 1245 | } 1246 | ] 1247 | report = runner.get_report(args) 1248 | assert report == """Summary Report: 1249 | 0 bags cleaned successfully 1250 | 0 failures 1251 | 0 bags are already clean 1252 | 4 directories are not bags 1253 | """ 1254 | 1255 | 1256 | class TestMakeBag: 1257 | @pytest.mark.parametrize("checksum_algorithm", [ 1258 | "sha224", 1259 | "md5", 1260 | "sha384", 1261 | "sha1", 1262 | "sha256", 1263 | "sha3_384", 1264 | "sha3_256", 1265 | "sha3_512", 1266 | "blake2b", 1267 | "blake2s", 1268 | "sha3_224", 1269 | "sha512" 1270 | ]) 1271 | def test_make_bag_with_various_checksums(self, tmpdir, checksum_algorithm): 1272 | from grabbags import grabbags 1273 | new_bag_path = tmpdir / "bagroot" 1274 | new_bag_path.ensure_dir() 1275 | (new_bag_path / "somefile.txt").ensure() 1276 | 1277 | run_args = argparse.Namespace( 1278 | action_type='make', 1279 | no_system_files=False, 1280 | bag_info={}, 1281 | processes=1, 1282 | checksums=[ 1283 | checksum_algorithm 1284 | ], 1285 | fast=False, 1286 | directories=[ 1287 | new_bag_path.strpath 1288 | ] 1289 | ) 1290 | runner = grabbags.MakeBag(run_args) 1291 | runner.execute(new_bag_path.strpath) 1292 | 1293 | assert (new_bag_path / "data").exists() 1294 | assert (new_bag_path / "data" / "somefile.txt").exists() 1295 | 1296 | assert (new_bag_path / "bagit.txt").exists() 1297 | assert (new_bag_path / "bag-info.txt").exists() 1298 | assert ( 1299 | new_bag_path / f"tagmanifest-{checksum_algorithm}.txt" 1300 | ).exists() 1301 | assert (new_bag_path / f"manifest-{checksum_algorithm}.txt").exists() 1302 | assert runner.successful is True 1303 | 1304 | def test_empty_bag(self, tmpdir): 1305 | from argparse import Namespace 1306 | from grabbags import grabbags 1307 | 1308 | empty_bag_dir = (tmpdir / "empty_bag") 1309 | empty_bag_dir.ensure_dir() 1310 | 1311 | args = Namespace( 1312 | action_type='create', 1313 | no_system_files=True, 1314 | bag_info={}, 1315 | processes=1, 1316 | checksums=[], 1317 | directories=[ 1318 | empty_bag_dir.strpath 1319 | ] 1320 | ) 1321 | runner = grabbags.MakeBag(args) 1322 | runner.execute(empty_bag_dir) 1323 | 1324 | assert (tmpdir / "empty_bag" / "data").exists() is False 1325 | assert len(runner.skipped) == 1 1326 | assert runner.successful is True 1327 | assert runner.results['skipped'] is True 1328 | 1329 | def test_already_a_bag(self, tmpdir): 1330 | from argparse import Namespace 1331 | from grabbags import grabbags 1332 | 1333 | bag_dir = tmpdir / "bag" 1334 | (bag_dir / "data").ensure_dir() 1335 | (bag_dir / "bagit.txt").ensure() 1336 | 1337 | args = Namespace( 1338 | action_type='create', 1339 | no_system_files=True, 1340 | bag_info={}, 1341 | processes=1, 1342 | checksums=[], 1343 | directories=[ 1344 | bag_dir.strpath 1345 | ] 1346 | ) 1347 | runner = grabbags.MakeBag(args) 1348 | runner.execute(bag_dir.strpath) 1349 | 1350 | assert len(runner.skipped) == 1 1351 | assert runner.successful is True 1352 | assert runner.results['skipped'] is True 1353 | 1354 | # TODO: Make tests to test whether proper "skipping" message appears when 1355 | # something is already a bag or is an empty directory 1356 | 1357 | def test_report_basic(self): 1358 | from argparse import Namespace 1359 | from grabbags import grabbags 1360 | args = Namespace( 1361 | action_type='create', 1362 | no_system_files=True, 1363 | bag_info={}, 1364 | processes=1, 1365 | checksums=[], 1366 | directories=[ 1367 | "fakedir" 1368 | ] 1369 | ) 1370 | 1371 | runner = grabbags.GrabbagsRunner() 1372 | runner.successes = [ 1373 | "directory1", 1374 | "directory2", 1375 | "directory3", 1376 | "directory4", 1377 | ] 1378 | runner.failures = [] 1379 | runner.skipped = [] 1380 | runner.results = [] 1381 | 1382 | report = runner.get_report(args) 1383 | assert report == """Summary Report: 1384 | 4 bags created successfully 1385 | 0 failures 1386 | 0 empty directories skipped 1387 | 0 directories are already a bag 1388 | """ 1389 | 1390 | def test_report_skipped_direc(self): 1391 | from argparse import Namespace 1392 | from grabbags import grabbags 1393 | args = Namespace( 1394 | action_type='create', 1395 | no_system_files=True, 1396 | bag_info={}, 1397 | processes=1, 1398 | checksums=[], 1399 | directories=[ 1400 | "fakedir" 1401 | ] 1402 | ) 1403 | 1404 | runner = grabbags.GrabbagsRunner() 1405 | runner.successes = [ 1406 | "directory1", 1407 | "directory2", 1408 | "directory3", 1409 | "directory4", 1410 | ] 1411 | runner.failures = [] 1412 | runner.skipped = [] 1413 | runner.results = [ 1414 | { 1415 | "already_a_bag": True, 1416 | "path": "directory5", 1417 | "skipped": True 1418 | }, 1419 | { 1420 | "empty_dir": True, 1421 | "path": "directory6", 1422 | "skipped": True 1423 | } 1424 | ] 1425 | 1426 | report = runner.get_report(args) 1427 | assert report == """Summary Report: 1428 | 4 bags created successfully 1429 | 0 failures 1430 | 1 empty directories skipped 1431 | 1 directories are already a bag 1432 | """ 1433 | -------------------------------------------------------------------------------- /tests/test_utils.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from unittest.mock import Mock 3 | 4 | from grabbags import utils 5 | 6 | 7 | class TestVersionStrategies: 8 | def test_importlib_metadata_success(self, monkeypatch): 9 | version = Mock() 10 | monkeypatch.setattr(utils.metadata, 'version', version) 11 | utils.VersionFromMetadata().get_version() 12 | assert version.called is True 13 | 14 | def test_importlib_metadata_not_found(self, monkeypatch): 15 | try: 16 | from importlib import metadata 17 | except ImportError: 18 | import importlib_metadata as metadata 19 | 20 | monkeypatch.setattr( 21 | utils.metadata, 'version', 22 | Mock(side_effect=metadata.PackageNotFoundError) 23 | ) 24 | with pytest.raises(utils.InvalidStrategy): 25 | utils.VersionFromMetadata().get_version() 26 | 27 | def test_version_from_git_commit_no_git(self, monkeypatch): 28 | import shutil 29 | which = Mock(return_value=None) 30 | monkeypatch.setattr(shutil, 'which', which) 31 | with pytest.raises(utils.InvalidStrategy): 32 | utils.VersionFromGitCommit().get_version() 33 | 34 | def test_version_from_git_commit_subprocess_error(self, monkeypatch): 35 | import shutil 36 | import subprocess 37 | monkeypatch.setattr(shutil, 'which', lambda x: 'git') 38 | check_output = Mock( 39 | side_effect=subprocess.CalledProcessError( 40 | returncode=1, 41 | cmd=['git', 'rev-parse', '--short', 'HEAD'] 42 | ) 43 | ) 44 | monkeypatch.setattr(subprocess, 'check_output', check_output) 45 | with pytest.raises(utils.InvalidStrategy): 46 | utils.VersionFromGitCommit().get_version() 47 | 48 | def test_version_from_git_commit_success(self, monkeypatch): 49 | import shutil 50 | import subprocess 51 | monkeypatch.setattr(shutil, 'which', lambda x: 'git') 52 | check_output = Mock(return_value=b'0bdfa12') 53 | monkeypatch.setattr(subprocess, 'check_output', check_output) 54 | 55 | assert utils.VersionFromGitCommit().get_version() == 'git: 0bdfa12' 56 | 57 | def test_current_version_no_strategies(self): 58 | assert utils.current_version(strategies=[]) == "Unknown" 59 | 60 | def test_current_version_no_valid_strategies(self): 61 | # This test checks that when running out of version getting strategies, 62 | # it returns with the string 'Unknown' and not an exception or None 63 | 64 | class NotValidStrategy(utils.VersionStrategy): 65 | def get_version(self) -> str: 66 | raise utils.InvalidStrategy 67 | 68 | assert utils.current_version( 69 | strategies=[NotValidStrategy()] 70 | ) == "Unknown" 71 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py36, py37 3 | 4 | [testenv] 5 | deps = 6 | pytest 7 | commands= pytest {posargs} 8 | 9 | [testenv:flake8] 10 | deps = flake8 11 | skipsdist=True 12 | skip_install=True 13 | commands = flake8 grabbags --------------------------------------------------------------------------------