├── .gitignore ├── LICENSE ├── README.rst ├── docs ├── Makefile ├── _templates │ └── layout.html ├── api.rst ├── basics.rst ├── conf.py ├── extending.rst ├── implementation.rst ├── index.rst └── requirements.txt ├── pathlab ├── __init__.py ├── core │ ├── __init__.py │ ├── accessor.py │ ├── creator.py │ ├── path.py │ └── stat.py ├── iso.py ├── rt.py ├── tar.py └── zip.py ├── setup.cfg ├── setup.py └── tests └── test_common.py /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | __pycache__ 3 | venv* 4 | *.pyc 5 | _build/ 6 | -------------------------------------------------------------------------------- /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.rst: -------------------------------------------------------------------------------- 1 | ======= 2 | Pathlab 3 | ======= 4 | 5 | |pypi| |docs| 6 | 7 | Pathlab provides an object-oriented path interface to archives, images, remote 8 | filesystems, etc. It is built upon pathlib_ and includes built-in support for: 9 | 10 | - ``tar`` archives 11 | - ``zip`` archives 12 | - ``iso`` disc images (inc Rock Ridge; exc Joliet and UDF) 13 | - JFrog Artifactory (via ``requests``) 14 | 15 | You can also define your own ``Path`` subclass with its own accessor. 16 | 17 | Installation 18 | ------------ 19 | 20 | Requires Python 3.6+. Use pip:: 21 | 22 | pip install --user pathlab 23 | 24 | Usage 25 | ----- 26 | 27 | These usage examples are adapted from the pathlib_ documentation. 28 | 29 | Getting a path type: 30 | 31 | >>> from pathlab import TarAccessor 32 | >>> TarPath = TarAccessor('project.tgz').TarPath 33 | 34 | Listing subdirectories: 35 | 36 | >>> root = TarPath('/') 37 | >>> [x for x in root.iterdir() if x.is_dir()] 38 | [TarAccessor('project.tgz').TarPath('/docs') 39 | TarAccessor('project.tgz').TarPath('/etc'), 40 | TarAccessor('project.tgz').TarPath('/project')] 41 | 42 | Listing Python source files in this directory tree: 43 | 44 | >>> list(root.glob('**/*.py')) 45 | [TarAccessor('project.tgz').TarPath('/setup.py'), 46 | TarAccessor('project.tgz').TarPath('/docs/conf.py'), 47 | TarAccessor('project.tgz').TarPath('/project/__init__.py')] 48 | 49 | Navigating inside a directory tree: 50 | 51 | >>> p = TarPath('/etc') 52 | >>> q = p / 'init.d' / 'reboot' 53 | >>> q 54 | TarAccessor('project.tgz').TarPath('/etc/init.d/reboot') 55 | >>> q.resolve() 56 | TarAccessor('project.tgz').TarPath('/etc/rc.d/init.d/halt') 57 | 58 | Querying path properties: 59 | 60 | >>> q.exists() 61 | True 62 | >>> q.is_dir() 63 | False 64 | 65 | Opening a file: 66 | 67 | >>> with q.open() as f: f.readline() 68 | ... 69 | '#!/bin/bash\n' 70 | 71 | 72 | .. _pathlib: https://docs.python.org/3/library/pathlib.html 73 | 74 | .. |pypi| image:: https://img.shields.io/pypi/v/pathlab.svg 75 | :target: https://pypi.python.org/pypi/pathlab 76 | :alt: Latest version released on PyPi 77 | 78 | .. |docs| image:: https://readthedocs.org/projects/pathlab/badge 79 | :target: http://pathlab.readthedocs.io/en/latest 80 | :alt: Documentation 81 | -------------------------------------------------------------------------------- /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/_templates/layout.html: -------------------------------------------------------------------------------- 1 | {% extends "!layout.html" %} 2 | {% block footer %} {{ super() }} 3 | 4 | 8 | 9 | {% endblock %} -------------------------------------------------------------------------------- /docs/api.rst: -------------------------------------------------------------------------------- 1 | API Reference 2 | ============= 3 | 4 | .. module:: pathlab 5 | 6 | Concrete Accessors 7 | ------------------ 8 | 9 | .. autoclass:: TarAccessor 10 | .. autoclass:: ZipAccessor 11 | .. autoclass:: IsoAccessor 12 | .. autoclass:: RtAccessor 13 | 14 | Abstract Accessor 15 | ----------------- 16 | 17 | .. autoclass:: Accessor 18 | :members: 19 | 20 | This table shows all abstract methods that should be implemented 21 | in your own :class:`Accessor` subclass. 22 | 23 | .. table:: 24 | 25 | ============================ ============================================== 26 | Abstract Method Description 27 | ============================ ============================================== 28 | :meth:`~Accessor.open` Open path and return a file object 29 | :meth:`~Accessor.stat` Return the a :class:`Stat` object for the path 30 | :meth:`~Accessor.listdir` Yield names of directory children 31 | :meth:`~Accessor.readlink` Return the target of the this symbolic link 32 | :meth:`~Accessor.create` Create the file, if it doesn't exist 33 | :meth:`~Accessor.chmod` Change file permissions 34 | :meth:`~Accessor.move` Move/rename the file 35 | :meth:`~Accessor.delete` Delete the file 36 | :meth:`~Accessor.download` Download to the *local* filesystem 37 | :meth:`~Accessor.upload` Upload from the *local* filesystem 38 | :meth:`~Accessor.fspath` Return a *local* path for this path 39 | :meth:`~Accessor.getcwd` Return the working directory 40 | :meth:`~Accessor.gethomedir` Return the user's home directory 41 | :meth:`~Accessor.close` Close this accessor object 42 | ============================ ============================================== 43 | 44 | This table shows utility methods you may call from your methods to raise 45 | an exception: 46 | 47 | .. table:: 48 | 49 | =================================== ========================= ====================== 50 | Method Raises Errno 51 | =================================== ========================= ====================== 52 | :meth:`~Accessor.not_found` :exc:`FileNotFoundError` :data:`~errno.ENOENT` 53 | :meth:`~Accessor.already_exists` :exc:`FileExistsError` :data:`~errno.EEXIST` 54 | :meth:`~Accessor.not_a_directory` :exc:`NotADirectoryError` :data:`~errno.ENOTDIR` 55 | :meth:`~Accessor.is_a_directory` :exc:`IsADirectoryError` :data:`~errno.EISDIR` 56 | :meth:`~Accessor.not_a_symlink` :exc:`OSError` :data:`~errno.EINVAL` 57 | :meth:`~Accessor.permission_denied` :exc:`PermissionError` :data:`~errno.EACCES` 58 | =================================== ========================= ====================== 59 | 60 | This table shows all methods with default implementations that you may 61 | wish to re-implement: 62 | 63 | .. table:: 64 | 65 | ====================================== ========================== ======================== 66 | Method Uses Like 67 | ====================================== ========================== ======================== 68 | :meth:`~Accessor.splitroot` 69 | :meth:`~Accessor.casefold` 70 | :meth:`~Accessor.casefold_parts` 71 | :meth:`~Accessor.is_reserved` 72 | :meth:`~Accessor.make_uri` 73 | :meth:`~Accessor.resolve` :meth:`~Accessor.readlink` :func:`os.path.abspath` 74 | :meth:`~Accessor.scandir` :meth:`~Accessor.listdir` :func:`os.scandir` 75 | :meth:`~Accessor.touch` :meth:`~Accessor.create` 76 | :meth:`~Accessor.mkdir` :meth:`~Accessor.create` :func:`os.mkdir` 77 | :meth:`~Accessor.symlink` :meth:`~Accessor.create` :func:`os.symlink` 78 | :meth:`~Accessor.unlink` :meth:`~Accessor.delete` :func:`os.unlink` 79 | :meth:`~Accessor.rmdir` :meth:`~Accessor.delete` :func:`os.rmdir` 80 | :meth:`~Accessor.rename` :meth:`~Accessor.move` :func:`os.rename` 81 | :meth:`~Accessor.replace` :meth:`~Accessor.move` :func:`os.replace` 82 | :meth:`~Accessor.lstat` :meth:`~Accessor.stat` :func:`os.lstat` 83 | :meth:`~Accessor.lchmod` :meth:`~Accessor.chmod` :func:`os.lchmod` 84 | :meth:`~Accessor.__enter__` 85 | :meth:`~Accessor.__exit__` :meth:`~Accessor.close` 86 | ====================================== ========================== ======================== 87 | 88 | Path 89 | ---- 90 | 91 | .. autoclass:: Path 92 | :show-inheritance: 93 | :members: sameaccessor, upload_from, download_to 94 | 95 | This table shows all methods and attributes available from :class:`Path` 96 | instances. You should not need to re-implement any of these methods. 97 | Methods marked as pure will work even without an accessor; other methods 98 | will call at least one method of the accessor. 99 | 100 | .. table:: 101 | :widths: 10 50 40 10 102 | 103 | ==== ===================================== ========================================= ======================= 104 | Pure Method Description Returns 105 | ==== ===================================== ========================================= ======================= 106 | ✓ :data:`~pathlib.PurePath.parts` Path components ``str`` sequence 107 | ✓ :data:`~pathlib.PurePath.drive` Drive letter, if any ``str`` 108 | ✓ :data:`~pathlib.PurePath.root` Root, e.g. ``/`` ``str`` 109 | ✓ :data:`~pathlib.PurePath.anchor` Drive letter and root ``str`` 110 | ✓ :data:`~pathlib.PurePath.name` Final path component ``str`` 111 | ✓ :data:`~pathlib.PurePath.stem` Final path component without its suffix ``str`` 112 | ✓ :data:`~pathlib.PurePath.suffix` File extension of final path component ``str`` 113 | ✓ :data:`~pathlib.PurePath.suffixes` File extensions of final path component ``str`` sequence 114 | ✓ :meth:`~pathlib.PurePath.as_posix` With forward slashes ``str`` 115 | ✓ :meth:`~pathlib.PurePath.as_uri` With ``file://`` prefix ``str`` 116 | .. :meth:`~pathlib.Path.owner` Name of file owner ``str`` 117 | .. :meth:`~pathlib.Path.group` Name of file group ``str`` 118 | .. :meth:`~pathlib.Path.stat` Status of file (follow symlinks) :class:`~Stat` 119 | .. :meth:`~pathlib.Path.lstat` Status of symlink :class:`~Stat` 120 | .. :meth:`~pathlib.Path.samefile` Paths are equivalent ``bool`` 121 | .. :meth:`~pathlab.Path.sameaccessor` Paths use the same accessor ``bool`` 122 | .. :meth:`~pathlib.Path.exists` Path exists ``bool`` 123 | .. :meth:`~pathlib.Path.is_dir` Path is a directory ``bool`` 124 | .. :meth:`~pathlib.Path.is_file` Path is a regular file ``bool`` 125 | .. :meth:`~pathlib.Path.is_mount` Path is a mount point ``bool`` 126 | .. :meth:`~pathlib.Path.is_symlink` Path is a symlink ``bool`` 127 | .. :meth:`~pathlib.Path.is_block_device` Path is a block device ``bool`` 128 | .. :meth:`~pathlib.Path.is_char_device` Path is a character device ``bool`` 129 | .. :meth:`~pathlib.Path.is_fifo` Path is a FIFO ``bool`` 130 | .. :meth:`~pathlib.Path.is_socket` Path is a socket ``bool`` 131 | ✓ :meth:`~pathlib.PurePath.is_absolute` Path is absolute ``bool`` 132 | ✓ :meth:`~pathlib.PurePath.is_reserved` Path is reserved ``bool`` 133 | ✓ :meth:`~pathlib.PurePath.match` Path matches a glob pattern ``bool`` 134 | ✓ :meth:`~pathlib.PurePath.joinpath` Append path components :class:`~Path` 135 | ✓ :data:`~pathlib.PurePath.parent` Immediate ancestor :class:`~Path` 136 | ✓ :data:`~pathlib.PurePath.parents` Ancestors :class:`~Path` sequence 137 | .. :meth:`~pathlib.Path.iterdir` Files in directory :class:`~Path` sequence 138 | .. :meth:`~pathlib.Path.glob` Files in subtree matching pattern :class:`~Path` sequence 139 | .. :meth:`~pathlib.Path.rglob` As above, but includes directories :class:`~Path` sequence 140 | ✓ :meth:`~pathlib.PurePath.relative_to` Make relative :class:`~Path` 141 | ✓ :meth:`~pathlib.PurePath.with_name` Change name :class:`~Path` 142 | ✓ :meth:`~pathlib.PurePath.with_suffix` Change suffix :class:`~Path` 143 | .. :meth:`~pathlib.Path.resolve` Resolve symlinks and make absolute :class:`~Path` 144 | .. :meth:`~pathlib.Path.expanduser` Expand ``~`` and ``~user`` :class:`~Path` 145 | .. :meth:`~pathlib.Path.touch` Create file 146 | .. :meth:`~pathlib.Path.mkdir` Create directory 147 | .. :meth:`~pathlib.Path.symlink_to` Create symlink 148 | .. :meth:`~pathlib.Path.unlink` Delete file or link 149 | .. :meth:`~pathlib.Path.rmdir` Delete directory 150 | .. :meth:`~pathlib.Path.rename` Move without clobbering 151 | .. :meth:`~pathlib.Path.replace` Move 152 | .. :meth:`~pathlib.Path.chmod` Change perms of file (follow symlinks) 153 | .. :meth:`~pathlib.Path.lchmod` Change perms of symlink0 154 | .. :meth:`~pathlib.Path.open` Open file and return file object ``fileobj`` 155 | .. :meth:`~pathlib.Path.read_bytes` Read file content as bytes ``bytes`` 156 | .. :meth:`~pathlib.Path.read_text` Read file content as text ``str`` 157 | .. :meth:`~pathlib.Path.write_bytes` Write file content as bytes 158 | .. :meth:`~pathlib.Path.write_text` Write file content as text 159 | .. :meth:`~pathlab.Path.upload_from` Upload from *local* filesystem 160 | .. :meth:`~pathlab.Path.download_to` Download to *local* filesystem 161 | ==== ===================================== ========================================= ======================= 162 | 163 | Only *additional* methods are documented here; see the :mod:`pathlib` 164 | documentation for other methods. 165 | 166 | 167 | Stat 168 | ---- 169 | 170 | .. autoclass:: Stat 171 | :members: 172 | 173 | Creator 174 | ------- 175 | 176 | .. autoclass:: Creator 177 | -------------------------------------------------------------------------------- /docs/basics.rst: -------------------------------------------------------------------------------- 1 | Using Pathlab 2 | ============= 3 | 4 | Use the Python standard library's :mod:`pathlib` module to interact with the 5 | local filesystem:: 6 | 7 | >>> import pathlib 8 | >>> etc = pathlib.Path('/etc') 9 | >>> etc.exists() 10 | True 11 | 12 | Tar Archives 13 | ~~~~~~~~~~~~ 14 | 15 | Use a :class:`pathlab.TarAccessor` object to interact with a ``tar`` file:: 16 | 17 | >>> import pathlab 18 | >>> archive = pathlab.TarAccessor('myproject.tar.gz') 19 | >>> root = archive.TarPath('/') 20 | >>> readme = root / 'readme.txt' 21 | >>> readme.exists() 22 | True 23 | 24 | Zip Archives 25 | ~~~~~~~~~~~~ 26 | 27 | Use a :class:`pathlab.ZipAccessor` object to interact with a ``zip`` file:: 28 | 29 | >>> import pathlab 30 | >>> archive = pathlab.ZipAccessor('myproject.zip') 31 | >>> root = archive.ZipPath('/') 32 | >>> readme = root / 'readme.txt' 33 | >>> readme.exists() 34 | True 35 | 36 | 37 | Iso Images 38 | ~~~~~~~~~~ 39 | 40 | Use an :class:`pathlab.IsoAccessor` object to interact with an ``iso`` file:: 41 | 42 | >>> import pathlab 43 | >>> disk = pathlab.IsoAccessor('myproject.iso') 44 | >>> root = disc.IsoPath('/') 45 | >>> readme = root / 'readme.txt' 46 | >>> readme.exists() 47 | True 48 | 49 | Artifactory Instances 50 | ~~~~~~~~~~~~~~~~~~~~~ 51 | 52 | 53 | Use an :class:`pathlab.RtAccessor` object to interact with a JFrog Artifactory 54 | instance:: 55 | 56 | >>> import pathlab 57 | >>> rt = pathlab.RtAccessor('http://artifactory/') 58 | >>> repo = rt.RtPath('/myproject/latest') 59 | >>> readme = repo / 'readme.txt' 60 | >>> readme.exists() 61 | True 62 | 63 | .. seealso:: 64 | 65 | See the :doc:`api` and :mod:`pathlib` documentation for more detail! 66 | -------------------------------------------------------------------------------- /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 = 'Pathlab' 21 | copyright = '2020, Barney Gale' 22 | author = 'Barney Gale' 23 | 24 | # The full version, including alpha/beta/rc tags 25 | release = '0.1' 26 | 27 | 28 | # -- General configuration --------------------------------------------------- 29 | 30 | import sphinx_rtd_theme 31 | 32 | # Add any Sphinx extension module names here, as strings. They can be 33 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 34 | # ones. 35 | extensions = [ 36 | 'sphinx_rtd_theme', 37 | 'sphinx.ext.autodoc', 38 | 'sphinx.ext.intersphinx', 39 | ] 40 | 41 | # Add any paths that contain templates here, relative to this directory. 42 | templates_path = ['_templates'] 43 | 44 | # List of patterns, relative to source directory, that match files and 45 | # directories to ignore when looking for source files. 46 | # This pattern also affects html_static_path and html_extra_path. 47 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 48 | 49 | 50 | # -- Options for HTML output ------------------------------------------------- 51 | 52 | # The theme to use for HTML and HTML Help pages. See the documentation for 53 | # a list of builtin themes. 54 | # 55 | html_theme = 'sphinx_rtd_theme' 56 | 57 | # Add any paths that contain custom static files (such as style sheets) here, 58 | # relative to this directory. They are copied after the builtin static files, 59 | # so a file named "default.css" will overwrite the builtin "default.css". 60 | html_static_path = ['_static'] 61 | 62 | autodoc_member_order = 'bysource' 63 | intersphinx_mapping = {'python': ('https://docs.python.org/3', None)} 64 | master_doc = 'index' 65 | 66 | -------------------------------------------------------------------------------- /docs/extending.rst: -------------------------------------------------------------------------------- 1 | Extending Pathlab 2 | ================= 3 | 4 | .. currentmodule:: pathlab 5 | 6 | Here's how you can create your own path-like class by subclassing :class:`Path` 7 | and :class:`Accessor`:: 8 | 9 | import pathlab 10 | 11 | class MyPath(pathlab.Path): 12 | __slots__ = () 13 | 14 | class MyAccessor(pathlab.Accessor): 15 | factory = MyPath 16 | 17 | def __repr__(self): 18 | return "MyAccessor()" 19 | 20 | At this point we can instantiate our accessor, which acts like a module with a 21 | ``MyPath`` class:: 22 | 23 | >>> accessor = MyAccessor() 24 | >>> accessor 25 | MyAccessor() 26 | >>> root = accessor.MyPath("/") 27 | >>> root 28 | MyAccessor().MyPath('/') 29 | 30 | Pure methods work as we'd expect, whereas impure methods raise 31 | :exc:`NotImplementedError`:: 32 | 33 | >>> docs = root / 'docs' 34 | >>> docs 35 | MyAccessor().MyPath('/docs') 36 | >>> docs.exists() 37 | Traceback (most recent call last): 38 | File "", line 1, in 39 | File ".../pathlib.py", line 1339, in exists 40 | self.stat() 41 | File ".../pathlib.py", line 1161, in stat 42 | return self._accessor.stat(self) 43 | File ".../pathlab/core/accessor.py", line 76, in stat 44 | raise NotImplementedError 45 | NotImplementedError 46 | 47 | Now we can begin adding methods to our accessor:: 48 | 49 | class MyAccessor(pathlab.Accessor): 50 | factory = MyPath 51 | 52 | def __init__(self, children): 53 | self.children = children 54 | 55 | def __repr__(self): 56 | return "MyAccessor(%r)" % self.children 57 | 58 | def stat(self, path): 59 | return pathlab.Stat(type='dir') 60 | 61 | def listdir(self, path): 62 | return self.children 63 | 64 | Refer to the :class:`Accessor` API documentation for a full list of abstract 65 | methods you may wish to implement. Refer to the pathlab source code for 66 | example accessor implementations. -------------------------------------------------------------------------------- /docs/implementation.rst: -------------------------------------------------------------------------------- 1 | Implementation Notes 2 | ==================== 3 | 4 | Using the Accessor 5 | ------------------ 6 | 7 | The standard library's :mod:`pathlib` module already includes the notion of an 8 | *accessor*, but it is bypassed in certain cases, such as: 9 | 10 | - ``str(self)`` called to get a local filesystem path 11 | - :func:`os.close` called to close file descriptors 12 | - :func:`os.getcwd` called to get the working directory 13 | - :func:`os.fsencode` called to get a ``bytes`` representation of a path 14 | - :data:`os.environ` accessed to expand ``~`` 15 | - :mod:`pwd` and :mod:`grp` used to retrieve user and group names 16 | 17 | Pathlab fixes these instances by subclassing :class:`pathlib.Path` as 18 | :class:`pathlab.Path` and re-implementing the problematic methods. This 19 | includes a few additions and changes to the accessor interface. 20 | 21 | Flavouring the Accessor 22 | ----------------------- 23 | 24 | The standard library's :mod:`pathlib` module uses a *flavour* object to handle 25 | pure path semantics. As before, this abstraction is leaky. Pathlab makes no 26 | distinction between the path accessor and flavour, and so allows methods like 27 | :meth:`~Accessor.casefold()` to be re-implemented. 28 | 29 | Binding the Accessor 30 | -------------------- 31 | 32 | The standard library's :mod:`pathlib` module provides limited means of storing 33 | state. A path instance may have its ``_accessor`` attribute customized, and 34 | in *some* cases derived path instances are initialized with 35 | ``path._init(template=self)`` to make the new path use the same accessor. 36 | However, this mechanism is used inconsistently. 37 | 38 | Pathlab solves this by creating a new path *type* per accessor *instance*. The 39 | accessor instance is bound to the new type as a class attribute. Therefore the 40 | inheritance chain of an accessor's path type is as follows: 41 | 42 | .. table:: Path inheritance chain 43 | :align: center 44 | :widths: 10 10 30 45 | 46 | ======== ==== ================================ 47 | Abstract Pure Class 48 | ======== ==== ================================ 49 | .. ✓ :class:`pathlib.PurePath` 50 | .. :class:`pathlib.Path` 51 | ✓ ✓ :class:`pathlab.Path` 52 | ✓ ✓ ``mylib.MyPath`` 53 | .. ``mylib.MyAccessor(...).MyPath`` 54 | ======== ==== ================================ 55 | 56 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../README.rst 2 | 3 | Documentation 4 | ------------- 5 | 6 | .. toctree:: 7 | :maxdepth: 2 8 | 9 | basics 10 | extending 11 | implementation 12 | api 13 | 14 | Indices and tables 15 | ------------------ 16 | 17 | * :ref:`genindex` 18 | * :ref:`modindex` 19 | * :ref:`search` 20 | -------------------------------------------------------------------------------- /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | requests 2 | -------------------------------------------------------------------------------- /pathlab/__init__.py: -------------------------------------------------------------------------------- 1 | from pathlab.core.accessor import Accessor 2 | from pathlab.core.creator import Creator 3 | from pathlab.core.path import Path 4 | from pathlab.core.stat import Stat 5 | from pathlab.iso import IsoAccessor 6 | from pathlab.rt import RtAccessor 7 | from pathlab.tar import TarAccessor 8 | from pathlab.zip import ZipAccessor -------------------------------------------------------------------------------- /pathlab/core/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/barneygale/pathlab/54a3e02619f49ebe351ffc5a83f49ebea616e60c/pathlab/core/__init__.py -------------------------------------------------------------------------------- /pathlab/core/accessor.py: -------------------------------------------------------------------------------- 1 | import errno 2 | import pathlib 3 | 4 | from pathlab.core.stat import Stat 5 | 6 | 7 | class Accessor(pathlib._Accessor, pathlib._PosixFlavour): 8 | """ 9 | An accessor object allows instances of an associated :class:`Path` type 10 | to access some kind of filesystem. 11 | 12 | Subclasses are free to define an initializer and store state, such as a 13 | socket object or file descriptor. Methods such as :meth:`listdir` may then 14 | reference that state. 15 | 16 | To create a path object, access its type as an attribute of an accessor 17 | object. 18 | """ 19 | 20 | # Path factory ------------------------------------------------------------ 21 | 22 | #: Must be set to a subclass of :class:`pathlab.Path` 23 | factory = None 24 | 25 | def __new__(cls, *args, **kwargs): 26 | if not cls.factory: 27 | raise TypeError("factory must subclass pathlab.Path") 28 | self = super(Accessor, cls).__new__(cls) 29 | name = cls.factory.__name__ 30 | self.factory = type(name, (cls.factory,), { 31 | "_accessor": self, 32 | "_flavour": self}) 33 | setattr(self, name, self.factory) 34 | return self 35 | 36 | # Open method ------------------------------------------------------------- 37 | 38 | def open(self, path, mode="r", buffering=-1): 39 | """ 40 | Open the path and return a file object, like :func:`io.open`. 41 | 42 | The underlying stream *must* be opened in binary mode (not text mode). 43 | The file mode is as in :func:`io.open`, except that it will not contain 44 | any of ``b``, ``t`` or ``U``. 45 | 46 | In ``w`` mode, you may wish to return a :class:`Creator` object. 47 | """ 48 | raise NotImplementedError 49 | 50 | # Read methods ------------------------------------------------------------ 51 | 52 | def stat(self, path, *, follow_symlinks=True): 53 | """ 54 | Return a :class:`Stat` object for the path, like :func:`os.stat`. 55 | """ 56 | raise NotImplementedError 57 | 58 | def listdir(self, path): 59 | """ 60 | Yield names of the files in the directory, a bit like 61 | :func:`os.listdir`. 62 | """ 63 | raise NotImplementedError 64 | 65 | def readlink(self, path): 66 | """ 67 | Return a string representing the path to which the symbolic link 68 | points, like :func:`os.readlink` 69 | """ 70 | raise NotImplementedError 71 | 72 | # Create/edit/delete methods ---------------------------------------------- 73 | 74 | def create(self, path, stat, fileobj=None): 75 | """ 76 | Create the file. The given :class:`Stat` object provides file metadata, 77 | and the *fileobj*, where given, provides a readable stream of the new 78 | file's content. 79 | """ 80 | raise NotImplementedError 81 | 82 | def chmod(self, path, mode, *, follow_symlinks=True): 83 | """ 84 | Change the permissions of the path. 85 | """ 86 | raise NotImplementedError 87 | 88 | def move(self, path, dest): 89 | """ 90 | Move/rename the file. 91 | """ 92 | raise NotImplementedError 93 | 94 | def delete(self, path): 95 | """ 96 | Remove the file. 97 | """ 98 | raise NotImplementedError 99 | 100 | # Interaction with the *local* filesystem --------------------------------- 101 | 102 | def fspath(self, path): 103 | """ 104 | Return an string representing the given path as a *local* filesystem 105 | path. The path need not exist. 106 | """ 107 | raise NotImplementedError 108 | 109 | def download(self, src, dst): 110 | """ 111 | Download from *src* to *dst*. *src* is an instance of your path class. 112 | """ 113 | raise NotImplementedError 114 | 115 | def upload(self, src, dst): 116 | """ 117 | Upload from *src* to *dst*. *dst* is an instance of your path class. 118 | """ 119 | raise NotImplementedError 120 | 121 | # Context methods --------------------------------------------------------- 122 | 123 | def getcwd(self): 124 | """ 125 | Return the current working directory, like :func:`os.getcwd`. 126 | """ 127 | raise NotImplementedError 128 | 129 | def gethomedir(self, username=None): 130 | """ 131 | Return the user's home directory. 132 | """ 133 | raise NotImplementedError 134 | 135 | # Close method ------------------------------------------------------------ 136 | 137 | def close(self): 138 | """ 139 | Close this accessor object. 140 | """ 141 | pass # FIXME: or NotImplementedError? 142 | 143 | # Utilities --------------------------------------------------------------- 144 | 145 | @staticmethod 146 | def not_found(path): 147 | """ 148 | Raise a :exc:`FileNotFoundError` 149 | """ 150 | raise FileNotFoundError(errno.ENOENT, "Not found", path) 151 | 152 | @staticmethod 153 | def already_exists(path): 154 | """ 155 | Raise a :exc:`FileExistsError` with :data:`~errno.EEXIST` 156 | """ 157 | raise FileExistsError(errno.EEXIST, "Already exists", path) 158 | 159 | @staticmethod 160 | def not_a_directory(path): 161 | """ 162 | Raise a :exc:`NotADirectoryError` with :data:`~errno.ENOTDIR` 163 | """ 164 | raise NotADirectoryError(errno.ENOTDIR, "Not a directory", path) 165 | 166 | @staticmethod 167 | def is_a_directory(path): 168 | """ 169 | Raise an :exc:`IsADirectoryError` with :data:`~errno.EISDIR` 170 | """ 171 | raise IsADirectoryError(errno.EISDIR, "Is a directory", path) 172 | 173 | @staticmethod 174 | def not_a_symlink(path): 175 | """ 176 | Raise an :exc:`OSError` with :data:`~errno.EINVAL` 177 | """ 178 | raise OSError(errno.EINVAL, "Invalid argument", path) 179 | 180 | @staticmethod 181 | def permission_denied(path): 182 | """ 183 | Raise a :exc:`PermissionError` with :data:`~errno.EACCES` 184 | """ 185 | raise PermissionError(errno.EACCES, "Permission denied", path) 186 | 187 | # Accessor redirects ------------------------------------------------------ 188 | 189 | encoding = 'utf-8' 190 | 191 | def scandir(self, path): 192 | for name in self.listdir(path): 193 | yield self.factory(path, name) 194 | 195 | def touch(self, path, mode=0o666, exist_ok=True): 196 | if path.exists(): 197 | if exist_ok: 198 | return 199 | return self.already_exists(path) 200 | elif not path.parent.exists(): 201 | return self.not_found(path.parent) 202 | return self.create(path, Stat(permissions=mode)) 203 | 204 | def mkdir(self, path, mode=0o777): 205 | if path.exists(): 206 | return self.already_exists(path) 207 | elif not path.parent.exists(): 208 | return self.not_found(path.parent) 209 | return self.create(path, Stat(type='dir', permissions=mode)) 210 | 211 | def symlink(self, target, path, target_is_directory=False): 212 | if path.exists(): 213 | return self.already_exists(path) 214 | elif not path.parent.exists(): 215 | return self.not_found(path.parent) 216 | target = self.factory(target) 217 | return self.create(path, Stat(type='symlink', target=target)) 218 | 219 | def unlink(self, path): 220 | return self.delete(path) 221 | 222 | def rmdir(self, path): 223 | return self.delete(path) 224 | 225 | def rename(self, path, dest): 226 | dest = self.factory(dest) 227 | if dest.exists(): 228 | return self.already_exists(dest) 229 | return self.move(path, dest) 230 | 231 | def replace(self, path, dest): 232 | return self.move(path, self.factory(dest)) 233 | 234 | def lstat(self, path): 235 | return self.stat(path, follow_symlinks=False) 236 | 237 | def lchmod(self, path, mode): 238 | return self.chmod(path, mode, follow_symlinks=False) 239 | 240 | # Flavour redirects ------------------------------------------------------- 241 | 242 | is_supported = True 243 | 244 | def resolve(self, path, strict=False): 245 | return super(Accessor, self).resolve(path.absolute(), strict) 246 | 247 | def join(self, parts): 248 | return self.sep.join(parts) 249 | 250 | # Context manager redirects ----------------------------------------------- 251 | 252 | def __enter__(self): 253 | return self 254 | 255 | def __exit__(self, exc_type, exc_val, exc_tb): 256 | self.close() -------------------------------------------------------------------------------- /pathlab/core/creator.py: -------------------------------------------------------------------------------- 1 | import io 2 | 3 | from pathlab.core.stat import Stat 4 | 5 | 6 | class Creator(io.BytesIO): 7 | """ 8 | A creator object is a :class:`~io.BytesIO` object that writes its contents 9 | to a path when closed. It calls :meth:`Accessor.create` to achieve this. 10 | 11 | A creator object may be returned from :meth:`Accessor.open` in ``w`` mode. 12 | 13 | :param target: The path to be created 14 | :param target_mode: Action to take when path exists. One of ``ignore``, 15 | ``raise``, or ``delete`` (the default). 16 | :param parent_mode: Action to take when parent doesn't exist. One of 17 | ``ignore``, ``raise`` (the default), or ``create``. 18 | :param stat: The initial :class:`Stat` object, which will have its ``size`` 19 | attribute changed. 20 | """ 21 | 22 | def __init__(self, target, target_mode="delete", parent_mode="raise", 23 | stat=None): 24 | assert target_mode in ("ignore", "raise", "delete") 25 | assert parent_mode in ("ignore", "raise", "create") 26 | self.target = target 27 | self.parent = target.parent 28 | self.target_mode = target_mode 29 | self.parent_mode = parent_mode 30 | self.accessor = target._accessor 31 | self.check() 32 | self.stat = stat or Stat() 33 | super(Creator, self).__init__() 34 | 35 | def close(self): 36 | self.check() 37 | self.stat.size = self.tell() 38 | self.seek(0) 39 | self.accessor.create(self.target, self.stat, self) 40 | 41 | def check(self): 42 | if self.parent_mode != "ignore": 43 | if not self.parent.exists(): 44 | if self.parent_mode == "create": 45 | self.parent.mkdir(parents=True) 46 | else: 47 | self.accessor.not_found(self.parent) 48 | if self.target_mode != "ignore": 49 | if self.target.exists(): 50 | if self.target_mode == "delete": 51 | self.target.unlink() 52 | else: 53 | self.accessor.already_exists(self.target) 54 | -------------------------------------------------------------------------------- /pathlab/core/path.py: -------------------------------------------------------------------------------- 1 | import io 2 | import pathlib 3 | 4 | 5 | class Path(pathlib.Path): 6 | """ 7 | Path-like object. 8 | """ 9 | 10 | __slots__ = () 11 | _flavour = pathlib._posix_flavour 12 | _accessor = None 13 | 14 | # Additional methods ------------------------------------------------------ 15 | 16 | def sameaccessor(self, other_path): 17 | """ 18 | Returns whether this path uses the same accessor as *other_path*. 19 | """ 20 | return self._accessor == getattr(other_path, "_accessor", None) 21 | 22 | def upload_from(self, source): 23 | """ 24 | Upload/add this path from the given *local* filesystem path. 25 | """ 26 | return self._accessor.upload(source, self) 27 | 28 | def download_to(self, target): 29 | """ 30 | Download/extract this path to the given *local* filesystem path. 31 | """ 32 | return self._accessor.download(self, target) 33 | 34 | @property 35 | def path(self): 36 | """ 37 | The path as a string, like ``str(path)``. Principally exists for 38 | compatibility with :class:`os.DirEntry`. 39 | """ 40 | return str(self) 41 | 42 | # Bugfixes and hacks ------------------------------------------------------ 43 | 44 | # Avoid ``os.getcwd()`` 45 | @classmethod 46 | def cwd(cls): 47 | return cls(cls._accessor.getcwd()) 48 | 49 | # Avoid Windows/Linux magic and direct instantiation 50 | def __new__(cls, *args, **kwargs): 51 | from pathlab.core.accessor import Accessor 52 | if not isinstance(cls._accessor, Accessor): 53 | raise TypeError("pathlab.Path cannot be instantiated directly") 54 | return cls._from_parts(args) 55 | 56 | # Avoid accessor changes 57 | def _init(self, template=None): 58 | self._closed = False 59 | 60 | # Avoid ``str(self)``; delegate to accessor. 61 | def __fspath__(self): 62 | target = pathlib.Path(self._accessor.fspath(self)) 63 | if not target.exists(): 64 | self._accessor.download(self, target) 65 | return str(target) 66 | 67 | def __repr__(self): 68 | return "%r.%s" % (self._accessor, super(Path, self).__repr__()) 69 | 70 | # Avoid file descriptors 71 | def open(self, mode="r", buffering=-1, encoding=None, 72 | errors=None, newline=None): 73 | if self._closed: 74 | self._raise_closed() 75 | text = 'b' not in mode 76 | mode = ''.join(c for c in mode if c not in 'btU') 77 | fileobj = self._accessor.open(self, mode, buffering) 78 | if text: 79 | return io.TextIOWrapper(fileobj, encoding, errors, newline) 80 | else: 81 | return fileobj 82 | 83 | # Avoid file descriptors 84 | def touch(self, mode=0o666, exist_ok=True): 85 | if self._closed: 86 | self._raise_closed() 87 | self._accessor.touch(self, mode, exist_ok) 88 | 89 | # Avoid ``os.fsencode()`` 90 | def __bytes__(self): 91 | return str(self).encode(self._accessor.encoding) 92 | 93 | # Avoid ``import pwd`` etc 94 | def owner(self): 95 | return self._accessor.stat(self).user 96 | 97 | # Avoid ``import grp`` etc 98 | def group(self): 99 | return self._accessor.stat(self).group 100 | 101 | # Avoid ``os.getcwd()`` 102 | def absolute(self): 103 | if self._closed: 104 | self._raise_closed() 105 | if self.is_absolute(): 106 | return self 107 | parts = [self._accessor.getcwd()] + self._parts 108 | obj = self._from_parts(parts, init=False) 109 | obj._init(template=self) 110 | return obj 111 | 112 | # Avoid ``Path()`` 113 | def is_mount(self): 114 | if not self.exists() or not self.is_dir(): 115 | return False 116 | try: 117 | stat1 = self.stat() 118 | stat2 = self.parent.stat() 119 | except OSError: 120 | return False 121 | if stat1.st_dev != stat2.st_dev: 122 | return False 123 | return stat1.st_ino == stat2.st_ino -------------------------------------------------------------------------------- /pathlab/core/stat.py: -------------------------------------------------------------------------------- 1 | import collections.abc 2 | import functools 3 | import datetime 4 | import stat 5 | 6 | 7 | default_time = datetime.datetime.fromtimestamp(0) 8 | types = { 9 | 'file': stat.S_IFREG, 10 | 'dir': stat.S_IFDIR, 11 | 'char_device': stat.S_IFCHR, 12 | 'block_device': stat.S_IFBLK, 13 | 'fifo': stat.S_IFIFO, 14 | 'symlink': stat.S_IFLNK, 15 | 'socket': stat.S_IFSOCK, 16 | } 17 | types_inv = {mode: name for name, mode in types.items()} 18 | st_fields = [ 19 | 'st_mode', 20 | 'st_ino', 21 | 'st_dev', 22 | 'st_nlink', 23 | 'st_uid', 24 | 'st_gid', 25 | 'st_size', 26 | 'st_atime', 27 | 'st_mtime', 28 | 'st_ctime', 29 | ] 30 | 31 | @functools.total_ordering 32 | class Stat(collections.abc.Sequence): 33 | """ 34 | Mutable version of :class:`os.stat_result`. The usual ``st_`` attributes 35 | are available as read-only properties. Other attributes may be passed to 36 | the initializer or set directly. 37 | 38 | Objects of this type (or a subclass) may be returned from 39 | :meth:`Accessor.stat()`. 40 | """ 41 | 42 | #: File type, for example ``file``, ``dir``, ``symlink``, ``socket``, 43 | #: ``fifo``, ``char_device`` or ``block_device``. Other values may be 44 | #: used, but will result in a ``stat.st_mode`` that indicates a regular 45 | #: file. 46 | type = "file" 47 | 48 | #: File size in bytes 49 | size = 0 50 | 51 | #: Permission bits 52 | permissions = 0 53 | 54 | #: Name of file owner 55 | user = None 56 | 57 | #: Name of file group 58 | group = None 59 | 60 | #: ID of file owner 61 | user_id = 0 62 | 63 | #: ID of file group 64 | group_id = 0 65 | 66 | #: ID of containing device 67 | device_id = 0 68 | 69 | #: ID that uniquely identifies the file on the device 70 | file_id = 0 71 | 72 | #: Number of hard links to this file 73 | hard_link_count = 0 74 | 75 | #: Time of creation 76 | create_time = default_time 77 | 78 | #: Time of last access 79 | access_time = default_time 80 | 81 | #: Time of last modification 82 | modify_time = default_time 83 | 84 | #: Time of last status modification 85 | status_time = default_time 86 | 87 | #: Link target 88 | target = None 89 | 90 | def __init__(self, **params): 91 | self.update(params) 92 | 93 | def update(self, params): 94 | for name, value in params.items(): 95 | setattr(self, name, value) 96 | 97 | def __repr__(self): 98 | name = self.__class__.__name__ 99 | fields = sorted(vars(self).items()) 100 | fields = ", ".join("%s=%r" % pair for pair in fields) 101 | return "%s(%s)" % (name, fields) 102 | 103 | # Sequence methods -------------------------------------------------------- 104 | 105 | def __getitem__(self, item): 106 | return getattr(self, st_fields[item]) 107 | 108 | def __len__(self): 109 | return len(st_fields) 110 | 111 | def __eq__(self, other): 112 | return tuple(self) == tuple(other) 113 | 114 | def __lt__(self, other): 115 | return tuple(self) < tuple(other) 116 | 117 | # File mode utilities ----------------------------------------------------- 118 | 119 | @staticmethod 120 | def pack_mode(type, permissions): 121 | return types.get(type, stat.S_IFREG) | permissions 122 | 123 | @staticmethod 124 | def unpack_mode(mode): 125 | return types_inv.get(stat.S_IFMT(mode), 'file'), stat.S_IMODE(mode) 126 | 127 | # Compatibility with ``os.stat_result`` ----------------------------------- 128 | 129 | st_mode = property(lambda self: self.pack_mode(self.type, self.permissions)) 130 | st_ino = property(lambda self: self.file_id) 131 | st_dev = property(lambda self: self.device_id) 132 | st_nlink = property(lambda self: self.hard_link_count) 133 | st_uid = property(lambda self: self.user_id) 134 | st_gid = property(lambda self: self.group_id) 135 | st_size = property(lambda self: self.size) 136 | st_atime = property(lambda self: self.access_time.timestamp()) 137 | st_mtime = property(lambda self: self.modify_time.timestamp()) 138 | st_ctime = property(lambda self: self.status_time.timestamp()) 139 | -------------------------------------------------------------------------------- /pathlab/iso.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import io 3 | import functools 4 | import struct 5 | 6 | import pathlab 7 | 8 | 9 | SECTOR = 2048 10 | ISO_IDENT = b"CD001" 11 | PVD_TYPE = 1 12 | END_TYPE = 255 13 | PX_FIELDS = ('mode', 'hard_link_count', 'user_id', 'group_id', 'file_id') 14 | TF_FIELDS = ('create_time', 'modify_time', 'access_time', 'status_time', 15 | 'backup_time', 'expiration_time', 'effective_time') 16 | 17 | 18 | class IsoPath(pathlab.Path): 19 | __slots__ = () 20 | 21 | 22 | class IsoAccessor(pathlab.Accessor): 23 | """ 24 | Accessor for ``.iso`` image. Supports plain ISOs and those with 25 | SUSP/Rock Ridge data. Does not support Joliet or UDF (yet). Does not 26 | support modification. 27 | 28 | :param file: Path to ``.iso`` file, or file object. 29 | :param ignore_susp: Whether to ignore SUSP/Rock Ridge data 30 | :param cache_size: specifies the size of the LRU cache to use for 31 | ``_load_record()`` results. Set to ``0`` to disable caching. 32 | """ 33 | 34 | fileobj = None 35 | managed = False 36 | root = None 37 | factory = IsoPath 38 | 39 | def __init__(self, file, ignore_susp=False, cache_size=1024): 40 | self.file = file 41 | self.ignore_susp = ignore_susp 42 | if cache_size: 43 | self._load_record = functools.lru_cache(cache_size)(self._load_record) 44 | 45 | if hasattr(file, "close"): 46 | self.fileobj = file 47 | self.managed = False 48 | else: 49 | self.fileobj = open(file, 'rb', buffering=SECTOR) 50 | self.managed = True 51 | 52 | # Load volume descriptors 53 | sector = 16 54 | while True: 55 | self.fileobj.seek(SECTOR * sector) 56 | type = self._unpack_byte() 57 | ident = self._unpack_bytes(5) 58 | if ident == ISO_IDENT: 59 | if type == PVD_TYPE: 60 | self.fileobj.seek(SECTOR * sector + 156) 61 | self.root = self._unpack_record() 62 | elif type == END_TYPE: 63 | break 64 | sector += 1 65 | if not self.root: 66 | raise ValueError("No valid volume descriptors") 67 | 68 | def __repr__(self): 69 | return "IsoAccessor(%r)" % self.file 70 | 71 | # Unpacking methods ------------------------------------------------------- 72 | 73 | def _unpack_byte(self): 74 | return self.fileobj.read(1)[0] 75 | 76 | def _unpack_bytes(self, count): 77 | return self.fileobj.read(count) 78 | 79 | def _unpack_to(self, end): 80 | start = self.fileobj.tell() 81 | if start == end: 82 | return b"" 83 | assert start < end 84 | return self.fileobj.read(end - start) 85 | 86 | def _unpack_to_boundary(self): 87 | return self.fileobj.read(SECTOR - self.fileobj.tell() % SECTOR) 88 | 89 | # ISO 9660:7.3.3 90 | def _unpack_both(self, fmt): 91 | l = struct.calcsize(fmt) 92 | a = struct.unpack('<' + fmt, self.fileobj.read(l))[0] 93 | b = struct.unpack('>' + fmt, self.fileobj.read(l))[0] 94 | assert a == b 95 | return a 96 | 97 | # 17 bytes (long) - ISO 9660:8.4.26.1 98 | # 7 bytes (short) - ISO 9660:9.1.5 99 | def _unpack_time(self, long=False): 100 | if long: 101 | s = self.fileobj.read(16).decode('ascii') 102 | t = datetime.datetime.strptime(s, '%Y%m%d%H%M%S%f') 103 | else: 104 | y, m, d, H, M, S = self.fileobj.read(6) 105 | t = datetime.datetime(1900 + y, m, d, H, M, S) 106 | offset = self.fileobj.read(1)[0] 107 | return t + datetime.timedelta(minutes=15*offset) 108 | 109 | # ISO 9660:9.1 110 | def _unpack_record(self): 111 | # Some notation: 112 | # i: ISO 9660 113 | # s: SUSP 114 | # b: SUSP block 115 | # r: SUSP record 116 | # c: SUSP record element 117 | 118 | # Load ISO 9660 data 119 | i_start = self.fileobj.tell() 120 | i_end = self._unpack_byte() + i_start 121 | _ = self._unpack_byte() 122 | i_sector = self._unpack_both('I') 123 | i_size = self._unpack_both('I') 124 | i_create_time = self._unpack_time() 125 | i_flags = self._unpack_byte() 126 | _ = self._unpack_bytes(6) 127 | i_name = self._unpack_bytes(self._unpack_byte()) 128 | _ = self._unpack_byte() if len(i_name) % 2 == 0 else 0 129 | 130 | # Decode name 131 | if i_name == b'\x00': 132 | i_name = '.' 133 | elif i_name == b'\x01': 134 | i_name = '..' 135 | else: 136 | i_name = i_name.decode('ascii').split(";")[0] 137 | 138 | # Create record 139 | record = { 140 | 'name': i_name, 141 | 'size': i_size, 142 | 'sector': i_sector, 143 | 'file_id': i_sector, 144 | 'device_id': id(self), 145 | 'create_time': i_create_time, 146 | 'type': 'dir' if i_flags & 2 else 'file'} 147 | 148 | # No SUSP entries? 149 | if self.fileobj.tell() == i_end: 150 | return record 151 | 152 | # Ignore SUSP entries? 153 | if self.ignore_susp: 154 | self._unpack_to(i_end) 155 | return record 156 | 157 | # Set up SUSP state 158 | s_name = [] # SUSP filename parts 159 | s_target = [] # SUSP symlink target parts 160 | s_target_tail = [] # SUSP symlink target tail parts 161 | b_start = 0 # SUSP block start offset 162 | b_end = i_end # SUSP block end offset 163 | b_next = None # SUSP block continuation info 164 | 165 | # Load SUSP entries 166 | while True: 167 | r_start = self.fileobj.tell() 168 | r_kind = self._unpack_bytes(2) 169 | r_end = self._unpack_byte() + r_start 170 | _ = self._unpack_byte() 171 | 172 | # Continuation area 173 | if r_kind == b'CE': 174 | b_next = ( 175 | self._unpack_both('I'), 176 | self._unpack_both('I'), 177 | self._unpack_both('I')) 178 | 179 | # File attributes 180 | elif r_kind == b'PX': 181 | for c_field in PX_FIELDS: 182 | c_value = self._unpack_both('I') 183 | if c_field == 'mode': 184 | c_value = pathlab.Stat.unpack_mode(c_value) 185 | record['type'], record['permissions'] = c_value 186 | else: 187 | record[c_field] = c_value 188 | if self.fileobj.tell() >= r_end: 189 | break 190 | 191 | # Symbolic link target 192 | elif r_kind == b'SL': 193 | _ = self._unpack_byte() 194 | while self.fileobj.tell() < r_end: 195 | c_flags = self._unpack_byte() 196 | c_flag_partial = c_flags & 0x01 # more to come 197 | c_flag_current = c_flags & 0x02 198 | c_flag_parent = c_flags & 0x04 199 | c_flag_root = c_flags & 0x08 200 | c_name_len = self._unpack_byte() 201 | c_name = self._unpack_bytes(c_name_len) 202 | c_name = c_name.decode(self.encoding) 203 | 204 | if c_flag_root: 205 | s_target.clear() 206 | s_target.append("") 207 | elif c_flag_current: 208 | s_target.append(".") 209 | elif c_flag_parent: 210 | s_target.append("..") 211 | else: 212 | s_target_tail.append(c_name) 213 | if not c_flag_partial: 214 | s_target.append("".join(s_target_tail)) 215 | s_target_tail.clear() 216 | 217 | # Filename 218 | elif r_kind == b'NM': 219 | c_flags = self._unpack_byte() 220 | c_flag_current = c_flags & 0x02 221 | c_flag_parent = c_flags & 0x04 222 | c_name = self._unpack_to(r_end) 223 | c_name = c_name.decode(self.encoding) 224 | 225 | if c_flag_current: 226 | s_name.append(".") 227 | elif c_flag_parent: 228 | s_name.append("..") 229 | else: 230 | s_name.append(c_name) 231 | 232 | # Timestamps 233 | elif r_kind == b'TF': 234 | c_flags = self._unpack_byte() 235 | c_flag_long = c_flags & 0x80 236 | for i, c_field in enumerate(TF_FIELDS): 237 | if c_flags & (1 << i): 238 | record[c_field] = self._unpack_time(c_flag_long) 239 | 240 | # Some other record 241 | else: 242 | self._unpack_to(r_end) 243 | 244 | # Ensure we read the entire SUSP record 245 | assert self.fileobj.tell() == r_end 246 | 247 | # Discard padding byte 248 | if self.fileobj.tell() == (b_end - 1): 249 | self._unpack_byte() 250 | 251 | # End of current block 252 | if self.fileobj.tell() == b_end: 253 | # No further block 254 | if not b_next: 255 | break 256 | 257 | # Jump to next block 258 | b_start = SECTOR * b_next[0] + b_next[1] 259 | b_end = b_start + b_next[2] 260 | b_next = None 261 | self.fileobj.seek(b_start) 262 | 263 | # Seek back to the end of the ISO record 264 | if b_start: 265 | self.fileobj.seek(i_end) 266 | 267 | # Finalize SUSP data 268 | if s_name: 269 | record['name'] = ''.join(s_name) 270 | if s_target: 271 | record['target'] = '/'.join(s_target) 272 | assert len(s_target_tail) == 0 273 | 274 | # Return our record! 275 | return record 276 | 277 | def _load_children(self, record): 278 | assert record['type'] == 'dir' 279 | start = SECTOR * record['sector'] 280 | end = start + record['size'] 281 | self.fileobj.seek(start) 282 | while self.fileobj.tell() < end: 283 | if not self.fileobj.peek(1)[0]: 284 | self._unpack_to_boundary() 285 | continue 286 | yield self._unpack_record() 287 | 288 | def _load_record(self, path): 289 | record = self.root 290 | paths = [path] + list(path.parents) 291 | for part in paths[::-1][1:]: 292 | if record['type'] != 'dir': 293 | return self.not_found(path) 294 | for child in self._load_children(record): 295 | if child['name'] == part.name: 296 | record = child 297 | break 298 | else: 299 | self.not_found(path) 300 | return record 301 | 302 | # Main accessor methods --------------------------------------------------- 303 | 304 | def stat(self, path, *, follow_symlinks=True): 305 | if not follow_symlinks: 306 | path = path.parent.resolve() / path.name 307 | else: 308 | path = path.resolve() 309 | return pathlab.Stat(**self._load_record(path)) 310 | 311 | def readlink(self, path): 312 | path = self.factory(path) 313 | record = self._load_record(path) 314 | if record['type'] != 'symlink': 315 | return self.not_a_symlink(path) 316 | target = self.factory(record['target']) 317 | if not target.is_absolute(): 318 | target = path.parent / record['target'] 319 | return str(target) 320 | 321 | def listdir(self, path): 322 | record = self._load_record(path.resolve()) 323 | if record['type'] != 'dir': 324 | return self.not_a_directory(path) 325 | for child in self._load_children(record): 326 | if child['name'] not in ('.', '..'): 327 | yield child['name'] 328 | 329 | def open(self, path, mode="r", buffering=-1): 330 | if buffering != -1: 331 | raise NotImplementedError 332 | if mode == "r": 333 | record = self._load_record(path) 334 | self.fileobj.seek(SECTOR * record['sector']) 335 | return io.BytesIO(self.fileobj.read(record['size'])) 336 | raise NotImplementedError 337 | 338 | def close(self): 339 | if self.managed: 340 | self.fileobj.close() -------------------------------------------------------------------------------- /pathlab/rt.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import functools 3 | import pathlab 4 | import requests 5 | 6 | 7 | def parse_time(string): 8 | return datetime.datetime.strptime(string, '%Y-%m-%dT%H:%M:%S.%f%z') 9 | 10 | 11 | class RtPath(pathlab.Path): 12 | __slots__ = () 13 | 14 | 15 | class RtAccessor(pathlab.Accessor): 16 | """ 17 | Accessor for JFrog Artifactory. 18 | 19 | :param url: specifies the Artifactory base URL (excluding the repo name) 20 | :param cache_size: specifies the size of the LRU cache to use for 21 | ``stat()`` results. Set to ``0`` to disable caching. 22 | """ 23 | 24 | factory = RtPath 25 | 26 | def __init__(self, url, cache_size=1024): 27 | self.url = url.rstrip("/") 28 | self.sess = requests.Session() 29 | if cache_size: 30 | self.stat = functools.lru_cache(cache_size)(self.stat) 31 | 32 | def __repr__(self): 33 | return "RtAccessor(%r)" % self.url 34 | 35 | def open(self, path, mode="r", buffering=-1): 36 | if buffering != -1: 37 | raise NotImplementedError 38 | if mode == "r": 39 | url = self.url + str(path.absolute()) 40 | response = self.sess.get(url, stream=True) 41 | if response.status_code == 404: 42 | return self.not_found(path) 43 | response.raise_for_status() 44 | return response.raw # FIXME: this isn't seekable 45 | else: 46 | raise NotImplementedError 47 | 48 | def stat(self, path, *, follow_symlinks=True): 49 | path = path.absolute() 50 | if path.anchor == str(path): 51 | url = self.url + "/api/repositories" 52 | response = self.sess.get(url) 53 | response.raise_for_status() 54 | data = response.json() 55 | return pathlab.Stat( 56 | type='dir', 57 | children=[child['key'] for child in data]) 58 | 59 | url = self.url + "/api/storage" + str(path) 60 | response = self.sess.get(url) 61 | if response.status_code == 404: 62 | return self.not_found(path) 63 | response.raise_for_status() 64 | data = response.json() 65 | return pathlab.Stat( 66 | type='file' if 'size' in data else 'dir', 67 | size=int(data.get('size', 0)), 68 | create_time=parse_time(data['created']), 69 | modify_time=parse_time(data['lastModified']), 70 | create_user=data.get('createdBy'), 71 | modify_user=data.get('modifiedBy'), 72 | children=[child['uri'][1:] for child in data.get('children', [])]) 73 | 74 | def listdir(self, path): 75 | stat = self.stat(path) 76 | if stat.type != 'dir': 77 | return self.not_a_directory(path) 78 | return stat.children 79 | 80 | # TODO: writing support -------------------------------------------------------------------------------- /pathlab/tar.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import pathlab 3 | import tarfile 4 | 5 | 6 | file_types = { 7 | tarfile.REGTYPE: 'file', 8 | tarfile.DIRTYPE: 'dir', 9 | tarfile.SYMTYPE: 'symlink', 10 | tarfile.LNKTYPE: 'link', 11 | tarfile.CHRTYPE: 'char_device', 12 | tarfile.BLKTYPE: 'block_device', 13 | tarfile.FIFOTYPE: 'fifo', 14 | } 15 | file_types_inv = {v: k for k, v in file_types.items()} 16 | 17 | 18 | class TarPath(pathlab.Path): 19 | __slots__ = () 20 | 21 | 22 | class TarAccessor(pathlab.Accessor): 23 | """ 24 | Accessor for ``.tar`` archives. Supports writing of files, but not other 25 | forms of modification. 26 | 27 | :param file: Path to ``.tar`` file, or file object. 28 | """ 29 | 30 | factory = TarPath 31 | reader = None 32 | writer = None 33 | 34 | def __init__(self, file): 35 | self.file = file 36 | self._reload() 37 | 38 | def __repr__(self): 39 | return "TarAccessor(%r)" % self.file 40 | 41 | def _reload(self): 42 | if self.writer: 43 | self.writer.close() 44 | self.reader = tarfile.open(self.file, "r") 45 | self.writer = tarfile.open(self.file, "a") 46 | 47 | def _encode(self, path): 48 | return str(path.absolute())[1:] 49 | 50 | def _decode(self, string): 51 | return self.factory("/%s" % string) 52 | 53 | def create(self, path, stat, fileobj=None): 54 | info = tarfile.TarInfo() 55 | info.name = self._encode(path) 56 | info.type = file_types_inv[stat.type] 57 | info.size = stat.size 58 | info.mode = stat.permissions 59 | info.linkname = self._encode(stat.target) if stat.target else "" 60 | self.writer.addfile(info, fileobj) 61 | self._reload() 62 | 63 | def open(self, path, mode="r", buffering=-1): 64 | if buffering != -1: 65 | raise NotImplementedError 66 | elif mode == "r": 67 | return self.reader.extractfile(self._encode(path)) 68 | elif mode == "w": 69 | return pathlab.Creator(path, target_mode="ignore") 70 | else: 71 | raise NotImplementedError 72 | 73 | def stat(self, path, *, follow_symlinks=True): 74 | # Resolve symlinks 75 | if not follow_symlinks: 76 | path = path.parent.resolve() / path.name 77 | else: 78 | path = path.resolve() 79 | 80 | # Handle the root directory 81 | if str(path) == "/": 82 | return pathlab.Stat( 83 | type='dir', 84 | device_id=id(self), 85 | file_id=1, 86 | path=self._decode('')) 87 | 88 | # Retrieve the member info 89 | try: 90 | info = self.reader.getmember(self._encode(path)) 91 | except KeyError: 92 | return self.not_found(path) 93 | 94 | # Build our stat object 95 | return pathlab.Stat( 96 | type=file_types.get(info.type, 'file'), 97 | size=info.size, 98 | permissions=info.mode, 99 | device_id=id(self), 100 | file_id=info.offset + 2, 101 | user_id=info.uid, 102 | group_id=info.gid, 103 | modify_time=datetime.datetime.fromtimestamp(info.mtime), 104 | path=self._decode(info.name), 105 | target=self._decode(info.linkname), 106 | user=info.uname, 107 | group=info.gname) 108 | 109 | def listdir(self, path): 110 | # Check directory exists 111 | stat = self.stat(path) 112 | if stat.type != 'dir': 113 | return self.not_a_directory(path) 114 | 115 | # Resolve symlinks 116 | path = stat.path 117 | 118 | # Find members with a matching parent 119 | for info in self.reader.getmembers(): 120 | p = self._decode(info.name) 121 | if p.parent == path: 122 | yield p.name 123 | 124 | def readlink(self, path): 125 | # Handle the root directory 126 | if str(path) == "/": 127 | return "/" 128 | 129 | # Retrieve the member info 130 | path = self.factory(path) 131 | try: 132 | info = self.reader.getmember(self._encode(path)) 133 | except KeyError: 134 | return self.not_found(path) 135 | 136 | # Check this is a symlink 137 | if not info.linkname: 138 | return self.not_a_symlink(path) 139 | 140 | # Return the symlink target 141 | return str(self._decode(info.linkname)) 142 | 143 | """ 144 | # TODO: test! 145 | def upload(self, src, dst): 146 | self.writer.write(src, str(dst.absolute())) 147 | self._reload() 148 | 149 | # TODO: test! 150 | def download(self, src, dst): 151 | with open(dst, "wb") as fdst: 152 | with self.reader.open(self._encode(src), "rb") as fsrc: 153 | fdst.write(fsrc.read()) 154 | """ 155 | -------------------------------------------------------------------------------- /pathlab/zip.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import pathlab 3 | import zipfile 4 | 5 | 6 | class ZipPath(pathlab.Path): 7 | __slots__ = () 8 | 9 | 10 | class ZipAccessor(pathlab.Accessor): 11 | """ 12 | Accessor for ``.zip`` archives. Supports writing of files, but not other 13 | forms of modification. 14 | 15 | :param file: Path to ``.zip`` file, or file object. 16 | """ 17 | 18 | factory = ZipPath 19 | zipobj = None 20 | 21 | def __init__(self, file): 22 | self.file = file 23 | self.zipobj = zipfile.ZipFile(file, 'a') 24 | 25 | def __repr__(self): 26 | return "ZipAccessor(%r)" % self.file 27 | 28 | def _encode(self, path, is_dir=False): 29 | string = str(path.absolute())[1:] 30 | if is_dir: 31 | string += "/" 32 | return string 33 | 34 | def _decode(self, string): 35 | return self.factory("/%s" % string) 36 | 37 | def create(self, path, stat, fileobj=None): 38 | info = zipfile.ZipInfo(self._encode(path, stat.type == 'dir')) 39 | data = fileobj.read() if fileobj else b"" 40 | self.zipobj.writestr(info, data) 41 | 42 | def open(self, path, mode="r", buffering=-1): 43 | if buffering != -1: 44 | raise NotImplementedError 45 | return self.zipobj.open(self._encode(path), mode) 46 | 47 | def stat(self, path, *, follow_symlinks=True): 48 | # Handle the root directory 49 | if str(path) == "/": 50 | return pathlab.Stat( 51 | type='dir', 52 | device_id=id(self), 53 | file_id=1, 54 | path=self._decode('')) 55 | 56 | # Retrieve the member info 57 | info = (self.zipobj.NameToInfo.get(self._encode(path, True)) or 58 | self.zipobj.NameToInfo.get(self._encode(path, False))) 59 | if info is None: 60 | return self.not_found(path) 61 | 62 | # Build our stat object 63 | return pathlab.Stat( 64 | type='dir' if info.filename[-1] == '/' else 'file', 65 | size=info.file_size, 66 | device_id=id(self), 67 | file_id=info.header_offset + 2, 68 | modify_time=datetime.datetime(*info.date_time), 69 | path=self._decode(info.filename)) 70 | 71 | def listdir(self, path): 72 | # Check directory exists 73 | stat = self.stat(path) 74 | if stat.type != 'dir': 75 | return self.not_a_directory(path) 76 | 77 | # Find members with a matching parent 78 | for info in self.zipobj.infolist(): 79 | p = self._decode(info.filename) 80 | if p.parent == path: 81 | yield p.name 82 | 83 | """ 84 | # TODO: test! 85 | def upload(self, src, dst): 86 | self.zf.write(src, str(dst.absolute())) 87 | 88 | # TODO: test! 89 | def download(self, src, dst): 90 | with open(dst, "wb") as fdst: 91 | with self.zf.open(unnormalize(src), "rb") as fsrc: 92 | fdst.write(fsrc.read()) 93 | """ -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | name = pathlab 3 | version = 0.1 4 | author = Barney Gale 5 | author-email = barney.gale@gmail.com 6 | home-page = https://github.com/barneygale/pathlab 7 | description = An object-oriented path interface to archives, images, remote filesystems, etc 8 | long-description = file: README.rst 9 | platform = any 10 | classifiers = 11 | Development Status :: 3 - Alpha 12 | Intended Audience :: Developers 13 | License :: OSI Approved :: GNU General Public License v3 (GPLv3) 14 | Operating System :: OS Independent 15 | Programming Language :: Python 16 | Programming Language :: Python :: 3.6 17 | Programming Language :: Python :: 3.7 18 | Programming Language :: Python :: 3.8 19 | Topic :: Software Development :: Libraries :: Python Modules 20 | 21 | [options] 22 | packages = 23 | pathlab 24 | pathlab.core 25 | python_requires = >= 3.6 26 | setup_requires = 27 | setuptools>=38.3.0 28 | install_requires = 29 | requests 30 | 31 | [bdist_wheel] 32 | universal = true 33 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | setup() -------------------------------------------------------------------------------- /tests/test_common.py: -------------------------------------------------------------------------------- 1 | import io 2 | import os 3 | import stat 4 | import subprocess 5 | 6 | import pathlib 7 | import pathlab 8 | 9 | import pytest 10 | 11 | support = { 12 | 'open_unbuffered': ('local'), 13 | 'create': ('local', 'tar', 'zip'), 14 | 'symlink': ('local', 'tar', 'iso'), 15 | 'chmod': ('local',), 16 | 'delete': ('local',), 17 | 'rename': ('local',) 18 | } 19 | 20 | 21 | @pytest.fixture(params=("local", "zip", "tar", "iso")) 22 | def root(request, tmp_path): 23 | fs_path = tmp_path / 'fs' 24 | os.mkdir(fs_path) 25 | os.mkdir(fs_path / 'dirA') 26 | os.mkdir(fs_path / 'dirB') 27 | os.mkdir(fs_path / 'dirC') 28 | os.mkdir(fs_path / 'dirC' / 'dirD') 29 | with open(fs_path / 'fileA', 'wb') as f: 30 | f.write(b"this is file A\n") 31 | with open(fs_path / 'dirB' / 'fileB', 'wb') as f: 32 | f.write(b"this is file B\n") 33 | with open(fs_path / 'dirC' / 'fileC', 'wb') as f: 34 | f.write(b"this is file C\n") 35 | with open(fs_path / 'dirC' / 'dirD' / 'fileD', 'wb') as f: 36 | f.write(b"this is file D\n") 37 | if has_support(request.param, "symlink"): 38 | os.symlink('fileA', fs_path / 'linkA') 39 | os.symlink('non-existing', fs_path / 'brokenLink') 40 | os.symlink('dirB', fs_path / 'linkB') 41 | os.symlink('../dirB', fs_path / 'dirA' / 'linkC') 42 | os.symlink('../dirB', fs_path / 'dirB' / 'linkD') 43 | os.symlink('brokenLinkLoop', fs_path / 'brokenLinkLoop') 44 | if request.param == 'local': 45 | yield fs_path 46 | elif request.param == 'zip': 47 | zip_path = tmp_path / 'fs.zip' 48 | subprocess.check_call('zip --symlinks -r %s .' % zip_path, cwd=fs_path, shell=True) 49 | yield pathlab.ZipAccessor(zip_path).ZipPath('/') 50 | elif request.param == 'tar': 51 | tar_path = tmp_path / 'fs.tar' 52 | subprocess.check_call('tar cf %s *' % tar_path, cwd=fs_path, shell=True) 53 | yield pathlab.TarAccessor(tar_path).TarPath('/') 54 | elif request.param == 'iso': 55 | iso_path = tmp_path / 'fs.iso' 56 | subprocess.check_call( 57 | ['genisoimage', '-r', '-o', iso_path, '.'], 58 | cwd=fs_path) 59 | yield pathlab.IsoAccessor(iso_path).IsoPath('/') 60 | 61 | 62 | def has_support(name_or_path, kind): 63 | if isinstance(name_or_path, str): 64 | name = name_or_path 65 | else: 66 | name = { 67 | pathlib._NormalAccessor: "local", 68 | pathlab.ZipAccessor: "zip", 69 | pathlab.TarAccessor: "tar", 70 | pathlab.IsoAccessor: "iso", 71 | }[type(name_or_path._accessor)] 72 | 73 | return name in support[kind] 74 | 75 | def test_samefile(root): 76 | p = root / 'fileA' 77 | pp = root / 'fileA' 78 | q = root / 'dirB' / 'fileB' 79 | r = root / 'foo' 80 | assert p.samefile(pp) 81 | assert not p.samefile(q) 82 | with pytest.raises(FileNotFoundError): 83 | p.samefile(r) 84 | with pytest.raises(FileNotFoundError): 85 | r.samefile(p) 86 | with pytest.raises(FileNotFoundError): 87 | r.samefile(r) 88 | 89 | 90 | def test_exists(root): 91 | assert root.exists() 92 | assert (root / 'dirA').exists() 93 | assert (root / 'fileA').exists() 94 | assert not (root / 'fileA' / 'bah').exists() 95 | if has_support(root, "symlink"): 96 | assert (root / 'linkA').exists() 97 | assert (root / 'linkB').exists() 98 | assert (root / 'linkB' / 'fileB').exists() 99 | assert not (root / 'linkA' / 'bah').exists() 100 | assert not (root / 'foo').exists() 101 | 102 | def test_open(root): 103 | with (root / 'fileA').open('r') as f: 104 | assert isinstance(f, io.TextIOBase) 105 | assert f.read() == "this is file A\n" 106 | 107 | def test_open_binary(root): 108 | with (root / 'fileA').open('rb') as f: 109 | assert isinstance(f, io.BufferedIOBase) 110 | assert f.read().strip() == b"this is file A" 111 | 112 | def test_open_unbuffered(root): 113 | if not has_support(root, "open_unbuffered"): 114 | pytest.skip("No support for unbuffered open") 115 | with (root / 'fileA').open('rb', buffering=0) as f: 116 | assert isinstance(f, io.RawIOBase) 117 | assert f.read().strip() == b"this is file A" 118 | 119 | 120 | def test_read_write_bytes(root): 121 | if not has_support(root, "create"): 122 | pytest.skip("No create support") 123 | (root / 'fileA').write_bytes(b'abcdefg') 124 | assert (root / 'fileA').read_bytes() == b'abcdefg' 125 | with pytest.raises(TypeError): 126 | (root / 'fileA').write_bytes('somestr') 127 | assert (root / 'fileA').read_bytes() == b'abcdefg' 128 | 129 | def test_read_write_text(root): 130 | if not has_support(root, "create"): 131 | pytest.skip("No create support") 132 | (root / 'fileA').write_text('äbcdefg', encoding='latin-1') 133 | assert (root / 'fileA').read_text(encoding='utf-8', errors='ignore') == 'bcdefg' 134 | with pytest.raises(TypeError): 135 | (root / 'fileA').write_text(b'somebytes') 136 | assert (root / 'fileA').read_text(encoding='latin-1') == 'äbcdefg' 137 | 138 | def test_iterdir(root): 139 | it = root.iterdir() 140 | paths = set(it) 141 | expected = ['dirA', 'dirB', 'dirC', 'fileA'] 142 | if has_support(root, "symlink"): 143 | expected += ['linkA', 'linkB', 'brokenLink', 'brokenLinkLoop'] 144 | assert paths == { root / q for q in expected } 145 | 146 | def test_iterdir_symlink(root): 147 | if not has_support(root, "symlink"): 148 | pytest.skip("No symlink support") 149 | path = root / 'linkB' 150 | paths = set(path.iterdir()) 151 | expected = { path / q for q in ['fileB', 'linkD'] } 152 | assert paths == expected 153 | 154 | def test_iterdir_nodir(root): 155 | path = root / 'fileA' 156 | with pytest.raises(OSError): 157 | next(path.iterdir()) 158 | 159 | """ 160 | def test_glob_common(root): 161 | def _check(glob, expected): 162 | assert set(glob) == { root / q for q in expected } 163 | 164 | it = root.glob("fileA") 165 | assert isinstance(it, collections.abc.Iterator) 166 | _check(it, ["fileA"]) 167 | 168 | _check(root.glob("fileB"), []) 169 | _check(root.glob("dir*/file*"), ["dirB/fileB", "dirC/fileC"]) 170 | _check(root.glob("*A"), ['dirA', 'fileA']) 171 | _check(root.glob("*B/*"), ['dirB/fileB']) 172 | _check(root.glob("*/fileB"), ['dirB/fileB']) 173 | 174 | 175 | def test_rglob_common(root): 176 | def _check(glob, expected): 177 | assert set(glob) == {root / q for q in expected} 178 | path = root / "dirC" 179 | 180 | it = root.rglob("fileA") 181 | assert isinstance(it, collections.abc.Iterator) 182 | _check(it, ["fileA"]) 183 | 184 | _check(root.rglob("fileB"), ["dirB/fileB"]) 185 | _check(root.rglob("*/fileA"), []) 186 | _check(root.rglob("*/fileB"), ["dirB/fileB", "dirB/linkD/fileB", "linkB/fileB", "dirA/linkC/fileB"]) 187 | _check(root.rglob("file*"), ["fileA", "dirB/fileB", "dirC/fileC", "dirC/dirD/fileD"]) 188 | _check(path.rglob("file*"), ["dirC/fileC", "dirC/dirD/fileD"]) 189 | _check(path.rglob("*/*"), ["dirC/dirD/fileD"]) 190 | 191 | 192 | def test_rglob_symlink_loop(root): 193 | if has_support(root, "symlink"): 194 | given = set(root.rglob('*')) 195 | expect = {'brokenLink', 196 | 'dirA', 'dirA/linkC', 197 | 'dirB', 'dirB/fileB', 'dirB/linkD', 198 | 'dirC', 'dirC/dirD', 'dirC/dirD/fileD', 'dirC/fileC', 199 | 'fileA', 200 | 'linkA', 201 | 'linkB', 202 | 'brokenLinkLoop', 203 | } 204 | assert given == {root / x for x in expect} 205 | 206 | 207 | def test_glob_dotdot(root): 208 | assert set(root.glob("..")) == {root / ".."} 209 | assert set(root.glob("dirA/../file*")) == {root / "dirA" / ".." / "fileA"} 210 | assert set(root.glob("../xyzzy")) == set() 211 | """ 212 | 213 | def test_resolve_common(root): 214 | if not has_support(root, "symlink"): 215 | pytest.skip("No symlink support") 216 | p = root / 'foo' 217 | with pytest.raises(OSError): 218 | p.resolve(strict=True) 219 | assert p.resolve(strict=False) == p 220 | p = root / 'foo' / 'in' / 'spam' 221 | assert p.resolve(strict=False) == p 222 | 223 | p = root / 'dirB' / 'fileB' 224 | assert p.resolve() == p 225 | 226 | p = root / 'linkA' 227 | q = root / 'fileA' 228 | assert p.resolve() == q 229 | 230 | p = root / 'dirA' / 'linkC' / 'fileB' 231 | q = root / 'dirB' / 'fileB' 232 | assert p.resolve() == q 233 | 234 | p = root / 'dirB' / 'linkD' / 'fileB' 235 | q = root / 'dirB' / 'fileB' 236 | assert p.resolve() == q 237 | 238 | p = root / 'dirA' / 'linkC' / 'fileB' / 'foo' / 'in' / 'spam' 239 | q = root / 'dirB' / 'fileB' / 'foo' / 'in' / 'spam' 240 | assert p.resolve(False) == q 241 | 242 | p = root / 'dirA' / 'linkC' / '..' / 'foo' / 'in' / 'spam' 243 | q = root / 'foo' / 'in' / 'spam' 244 | assert p.resolve(False) == q 245 | 246 | def test_with(root): 247 | it = root.iterdir() 248 | it2 = root.iterdir() 249 | next(it2) 250 | with root: 251 | pass 252 | # I/O operation on closed path. 253 | with pytest.raises(ValueError): 254 | next(it) 255 | with pytest.raises(ValueError): 256 | next(it2) 257 | with pytest.raises(ValueError): 258 | print(root.open()) 259 | with pytest.raises(ValueError): 260 | root.resolve() 261 | with pytest.raises(ValueError): 262 | root.absolute() 263 | with pytest.raises(ValueError): 264 | root.__enter__() 265 | 266 | 267 | def test_chmod(root): 268 | if not has_support(root, "chmod"): 269 | pytest.skip("No chmod support") 270 | p = root / 'fileA' 271 | mode = p.stat().st_mode 272 | # Clear writable bit. 273 | new_mode = mode & ~0o222 274 | p.chmod(new_mode) 275 | assert p.stat().st_mode == new_mode 276 | # Set writable bit. 277 | new_mode = mode | 0o222 278 | p.chmod(new_mode) 279 | assert p.stat().st_mode == new_mode 280 | 281 | 282 | def test_stat(root): 283 | p = root / 'fileA' 284 | st = p.stat() 285 | assert p.stat() == st 286 | 287 | if has_support(root, "chmod"): 288 | # Change file mode by flipping write bit. 289 | p.chmod(st.st_mode ^ 0o222) 290 | assert p.stat() != st 291 | 292 | 293 | def test_lstat(root): 294 | if not has_support(root, "symlink"): 295 | pytest.skip("No symlink support") 296 | p = root / 'linkA' 297 | st = p.stat() 298 | assert st != p.lstat() 299 | 300 | def test_lstat_nosymlink(root): 301 | p = root / 'fileA' 302 | st = p.stat() 303 | assert st == p.lstat() 304 | 305 | def test_unlink(root): 306 | if not has_support(root, "delete"): 307 | pytest.skip("No delete support") 308 | p = root / 'fileA' 309 | p.unlink() 310 | with pytest.raises(FileNotFoundError): 311 | p.stat() 312 | with pytest.raises(FileNotFoundError): 313 | p.unlink() 314 | 315 | def test_rmdir(root): 316 | if not has_support(root, "delete"): 317 | pytest.skip("No delete support") 318 | p = root / 'dirA' 319 | for q in p.iterdir(): 320 | q.unlink() 321 | p.rmdir() 322 | with pytest.raises(FileNotFoundError): 323 | p.stat() 324 | with pytest.raises(FileNotFoundError): 325 | p.unlink() 326 | """ 327 | def test_link_to(root): 328 | if not has_support(root, "symlink"): 329 | pytest.skip("No symlink support") 330 | p = root / 'fileA' 331 | size = p.stat().st_size 332 | q = root / 'dirA' / 'fileAA' 333 | p.link_to(q) 334 | assert q.stat().st_size == size 335 | assert os.path.samefile(p, q) 336 | assert p.stat() 337 | """ 338 | 339 | def test_rename(root): 340 | if not has_support(root, "rename"): 341 | pytest.skip("No rename support") 342 | p = root / 'fileA' 343 | size = p.stat().st_size 344 | q = root / 'dirA' / 'fileAA' 345 | p.rename(q) 346 | assert q.stat().st_size == size 347 | with pytest.raises(FileNotFoundError): 348 | p.stat() 349 | 350 | def test_replace(root): 351 | p = root / 'fileA' 352 | if not has_support(root, "rename"): 353 | pytest.skip("No rename support") 354 | size = p.stat().st_size 355 | q = root / 'dirA' / 'fileAA' 356 | p.replace(q) 357 | assert q.stat().st_size == size 358 | with pytest.raises(FileNotFoundError): 359 | p.stat() 360 | 361 | """ 362 | def test_readlink(root): 363 | if not has_support(root, "symlink"): 364 | pytest.skip("No symlink support") 365 | assert (root / 'linkA').readlink() == (root / 'fileA') 366 | assert (root / 'brokenLink').readlink() == (root / 'non-existing') 367 | assert (root / 'linkB').readlink() == (root / 'dirB') 368 | with pytest.raises(OSError): 369 | (root / 'fileA').readlink() 370 | """ 371 | 372 | def test_touch_common(root): 373 | if not has_support(root, "create"): 374 | pytest.skip("No create support") 375 | p = root / 'newfileA' 376 | assert not p.exists() 377 | p.touch() 378 | assert p.exists() 379 | p = root / 'newfileB' 380 | assert not p.exists() 381 | p.touch(mode=0o700, exist_ok=False) 382 | assert p.exists() 383 | with pytest.raises(OSError): 384 | p.touch(exist_ok=False) 385 | 386 | def test_touch_nochange(root): 387 | if not has_support(root, "create"): 388 | pytest.skip("No create support") 389 | p = root / 'fileA' 390 | p.touch() 391 | with p.open('rb') as f: 392 | assert f.read().strip() == b"this is file A" 393 | 394 | def test_mkdir(root): 395 | if not has_support(root, "create"): 396 | pytest.skip("No create support") 397 | p = root / 'newdirA' 398 | assert not p.exists() 399 | p.mkdir() 400 | assert p.exists() 401 | assert p.is_dir() 402 | with pytest.raises(OSError): 403 | p.mkdir() 404 | 405 | def test_mkdir_parents(root): 406 | if not has_support(root, "create"): 407 | pytest.skip("No create support") 408 | p = root / 'newdirB' / 'newdirC' 409 | assert not p.exists() 410 | with pytest.raises(FileNotFoundError): 411 | p.mkdir() 412 | p.mkdir(parents=True) 413 | assert p.exists() 414 | assert p.is_dir() 415 | with pytest.raises(FileExistsError): 416 | p.mkdir(parents=True) 417 | mode = stat.S_IMODE(p.stat().st_mode) # Default mode. 418 | p = root / 'newdirD' / 'newdirE' 419 | p.mkdir(0o555, parents=True) 420 | assert p.exists() 421 | assert p.is_dir() 422 | assert stat.S_IMODE(p.stat().st_mode) == 0o7555 & mode 423 | assert stat.S_IMODE(p.parent.stat().st_mode) == mode 424 | 425 | def test_mkdir_exist_ok(root): 426 | if not has_support(root, "create"): 427 | pytest.skip("No create support") 428 | p = root / 'dirB' 429 | st_ctime_first = p.stat().st_ctime 430 | assert p.exists() 431 | assert p.is_dir() 432 | with pytest.raises(FileExistsError): 433 | p.mkdir() 434 | p.mkdir(exist_ok=True) 435 | assert p.exists() 436 | assert p.stat().st_ctime == st_ctime_first 437 | 438 | def test_mkdir_exist_ok_with_parent(root): 439 | if not has_support(root, "create"): 440 | pytest.skip("No create support") 441 | p = root / 'dirC' 442 | assert p.exists() 443 | with pytest.raises(FileExistsError): 444 | p.mkdir() 445 | p = p / 'newdirC' 446 | p.mkdir(parents=True) 447 | st_ctime_first = p.stat().st_ctime 448 | assert p.exists() 449 | with pytest.raises(FileExistsError): 450 | p.mkdir(parents=True) 451 | p.mkdir(parents=True, exist_ok=True) 452 | assert p.exists() 453 | assert p.stat().st_ctime == st_ctime_first 454 | 455 | 456 | def test_mkdir_with_child_file(root): 457 | if not has_support(root, "create"): 458 | pytest.skip("No create support") 459 | p = root / 'dirB' / 'fileB' 460 | assert p.exists() 461 | with pytest.raises(FileExistsError): 462 | p.mkdir(parents=True) 463 | with pytest.raises(FileExistsError): 464 | p.mkdir(parents=True, exist_ok=True) 465 | 466 | 467 | def test_mkdir_no_parents_file(root): 468 | if not has_support(root, "create"): 469 | pytest.skip("No create support") 470 | p = root / 'fileA' 471 | assert p.exists() 472 | with pytest.raises(FileExistsError): 473 | p.mkdir() 474 | with pytest.raises(FileExistsError): 475 | p.mkdir(exist_ok=True) 476 | 477 | 478 | def test_symlink_to(root): 479 | if not has_support(root, "create"): 480 | pytest.skip("No create support") 481 | if not has_support(root, "symlink"): 482 | pytest.skip("No symlink support") 483 | target = root / 'fileA' 484 | # Symlinking a path target. 485 | link = root / 'dirA' / 'linkAA' 486 | link.symlink_to(target) 487 | assert link.stat() == target.stat() 488 | assert link.lstat() != target.stat() 489 | # Symlinking a str target. 490 | link = root / 'dirA' / 'linkAAA' 491 | link.symlink_to(str(target)) 492 | assert link.stat() == target.stat() 493 | assert link.lstat() != target.stat() 494 | assert not link.is_dir() 495 | # Symlinking to a directory. 496 | target = root / 'dirB' 497 | link = root / 'dirA' / 'linkAAAA' 498 | link.symlink_to(target, target_is_directory=True) 499 | assert link.stat() == target.stat() 500 | assert link.lstat() != target.stat() 501 | assert link.is_dir() 502 | assert list(link.iterdir()) 503 | 504 | 505 | def test_is_dir(root): 506 | assert (root / 'dirA').is_dir() 507 | assert not (root / 'fileA').is_dir() 508 | assert not (root / 'non-existing').is_dir() 509 | assert not (root / 'fileA' / 'bah').is_dir() 510 | if has_support(root, "symlink"): 511 | assert not (root / 'linkA').is_dir() 512 | assert (root / 'linkB').is_dir() 513 | assert not (root / 'brokenLink').is_dir() 514 | 515 | 516 | def test_is_file(root): 517 | assert (root / 'fileA').is_file() 518 | assert not (root / 'dirA').is_file() 519 | assert not (root / 'non-existing').is_file() 520 | assert not (root / 'fileA' / 'bah').is_file() 521 | if has_support(root, "symlink"): 522 | assert (root / 'linkA').is_file() 523 | assert not (root / 'linkB').is_file() 524 | assert not (root / 'brokenLink').is_file() 525 | 526 | 527 | def test_is_mount(root): 528 | assert not (root / 'fileA').is_mount() 529 | assert not (root / 'dirA').is_mount() 530 | assert not (root / 'non-existing').is_mount() 531 | assert not (root / 'fileA' / 'bah').is_mount() 532 | if has_support(root, "symlink"): 533 | assert not (root / 'linkA').is_mount() 534 | 535 | 536 | def test_is_symlink(root): 537 | assert not (root / 'fileA').is_symlink() 538 | assert not (root / 'dirA').is_symlink() 539 | assert not (root / 'non-existing').is_symlink() 540 | assert not (root / 'fileA' / 'bah').is_symlink() 541 | if has_support(root, "symlink"): 542 | assert (root / 'linkA').is_symlink() 543 | assert (root / 'linkB').is_symlink() 544 | assert (root / 'brokenLink').is_symlink() 545 | 546 | 547 | def test_is_fifo_false(root): 548 | assert not (root / 'fileA').is_fifo() 549 | assert not (root / 'dirA').is_fifo() 550 | assert not (root / 'non-existing').is_fifo() 551 | assert not (root / 'fileA' / 'bah').is_fifo() 552 | 553 | 554 | def test_is_socket_false(root): 555 | assert not (root / 'fileA').is_socket() 556 | assert not (root / 'dirA').is_socket() 557 | assert not (root / 'non-existing').is_socket() 558 | assert not (root / 'fileA' / 'bah').is_socket() 559 | 560 | 561 | def test_is_block_device_false(root): 562 | assert not (root / 'fileA').is_block_device() 563 | assert not (root / 'dirA').is_block_device() 564 | assert not (root / 'non-existing').is_block_device() 565 | assert not (root / 'fileA' / 'bah').is_block_device() 566 | 567 | 568 | def test_is_char_device_false(root): 569 | assert not (root / 'fileA').is_char_device() 570 | assert not (root / 'dirA').is_char_device() 571 | assert not (root / 'non-existing').is_char_device() 572 | assert not (root / 'fileA' / 'bah').is_char_device() 573 | --------------------------------------------------------------------------------