├── .bumpversion.cfg ├── .codecov.yml ├── .editorconfig ├── .github └── ISSUE_TEMPLATE.md ├── .gitignore ├── .idea ├── encodings.xml ├── inspectionProfiles │ └── Project_Default.xml ├── misc.xml ├── modules.xml ├── python-humble-utils.iml ├── shellcheckPlugin.xml └── vcs.xml ├── .travis.yml ├── AUTHORS.rst ├── CONTRIBUTING.rst ├── HISTORY.rst ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.rst ├── docs ├── Makefile ├── authors.rst ├── conf.py ├── contributing.rst ├── developing-locally.rst ├── history.rst ├── includes │ └── execution_context_notice.rst ├── index.rst ├── installation.rst ├── make.bat ├── modules.rst ├── project-makefile.rst ├── python_humble_utils.rst ├── python_humble_utils.vendor.rst ├── readme.rst └── usage.rst ├── pyproject.toml ├── python_humble_utils ├── __init__.py ├── classes.py ├── filesystem.py ├── objects.py ├── strings.py └── vendor │ ├── __init__.py │ └── pytest.py ├── requirements.code-style.txt ├── requirements.coverage.txt ├── requirements.docs.txt ├── requirements.txt ├── setup.cfg ├── setup.py ├── tests ├── __init__.py ├── conftest.py ├── test_classes.py ├── test_filesystem.py ├── test_objects.py ├── test_strings.py └── vendor │ ├── __init__.py │ └── test_pytest.py ├── tox.ini └── travis_pypi_setup.py /.bumpversion.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | current_version = 3.1.0 3 | commit = True 4 | tag = True 5 | 6 | [bumpversion:file:setup.py] 7 | search = version="{current_version}" 8 | replace = version="{new_version}" 9 | 10 | [bumpversion:file:python_humble_utils/__init__.py] 11 | search = __version__ = "{current_version}" 12 | replace = __version__ = "{new_version}" 13 | 14 | -------------------------------------------------------------------------------- /.codecov.yml: -------------------------------------------------------------------------------- 1 | codecov: 2 | notify: 3 | require_ci_to_pass: yes 4 | 5 | coverage: 6 | precision: 2 7 | round: down 8 | range: "90...100" 9 | status: 10 | project: yes 11 | patch: yes 12 | changes: no 13 | 14 | parsers: 15 | gcov: 16 | branch_detection: 17 | conditional: yes 18 | loop: yes 19 | method: no 20 | macro: no 21 | 22 | comment: 23 | layout: "header, diff" 24 | behavior: default 25 | require_changes: no 26 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | indent_style = space 7 | indent_size = 4 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | charset = utf-8 11 | end_of_line = lf 12 | 13 | [*.bat] 14 | indent_style = tab 15 | end_of_line = crlf 16 | 17 | [LICENSE] 18 | insert_final_newline = false 19 | 20 | [Makefile] 21 | indent_style = tab 22 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | [//]: # (Inspired by https://gitlab.com/gitlab-org/gitlab-ce/blob/9e1d8542533bf09623d790413ff2872921efda7e/.gitlab/issue_templates/Bug.md) 2 | 3 | > *To avoid issue duplication, make sure to [lookup the same or similar one labelled with `bug`](https://github.com/webyneter/python-humble-utils/issues?q=label%3bug). 4 | Please, remove this notice if you are confident the issue is original.* 5 | 6 | ### Summary 7 | 8 | *Briefly elaborate on the issue you have encountered.* 9 | 10 | 11 | ### Reproducibility 12 | 13 | #### Prerequisites 14 | 15 | * Project version (or `/` non-releases): 16 | * Python version: 17 | * Platform: 18 | 19 | #### Steps 20 | 21 | *Enumerate steps to be taken for the bug to be reproduced.* 22 | 23 | 24 | ### Current Behavior 25 | 26 | *Briefly describe, what actually happens.* 27 | 28 | 29 | ### Expected Behavior 30 | 31 | *Briefly describe, what is declared to happen.* 32 | 33 | 34 | ### Relevant Artifacts 35 | 36 | *(**Optional**.) Provide any extra data you think might help resolve the issue faster (logs, screenshots etc.)* 37 | 38 | 39 | ### Proposed Solution 40 | 41 | *(**Optional**.) What is in your opinion the best way to fix this? (By the way, if you have a solution, why not make a PR? :) )* 42 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | 55 | # Sphinx documentation 56 | docs/_build/ 57 | 58 | # PyBuilder 59 | target/ 60 | 61 | # pyenv python configuration file 62 | .python-version 63 | ### JetBrains template 64 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 65 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 66 | 67 | # User-specific stuff: 68 | .idea/**/workspace.xml 69 | .idea/**/tasks.xml 70 | .idea/dictionaries 71 | 72 | # Sensitive or high-churn files: 73 | .idea/**/dataSources/ 74 | .idea/**/dataSources.ids 75 | .idea/**/dataSources.xml 76 | .idea/**/dataSources.local.xml 77 | .idea/**/sqlDataSources.xml 78 | .idea/**/dynamic.xml 79 | .idea/**/uiDesigner.xml 80 | 81 | # Gradle: 82 | .idea/**/gradle.xml 83 | .idea/**/libraries 84 | 85 | # Mongo Explorer plugin: 86 | .idea/**/mongoSettings.xml 87 | 88 | ## File-based project format: 89 | *.iws 90 | 91 | ## Plugin-specific files: 92 | 93 | # IntelliJ 94 | /out/ 95 | 96 | # mpeltonen/sbt-idea plugin 97 | .idea_modules/ 98 | 99 | # JIRA plugin 100 | atlassian-ide-plugin.xml 101 | 102 | # Crashlytics plugin (for Android Studio and IntelliJ) 103 | com_crashlytics_export_strings.xml 104 | crashlytics.properties 105 | crashlytics-build.properties 106 | fabric.properties 107 | ### VisualStudioCode template 108 | .vscode/* 109 | !.vscode/settings.json 110 | !.vscode/tasks.json 111 | !.vscode/launch.json 112 | !.vscode/extensions.json 113 | ### Windows template 114 | # Windows thumbnail cache files 115 | Thumbs.db 116 | ehthumbs.db 117 | ehthumbs_vista.db 118 | 119 | # Folder config file 120 | Desktop.ini 121 | 122 | # Recycle Bin used on file shares 123 | $RECYCLE.BIN/ 124 | 125 | # Windows Installer files 126 | *.cab 127 | *.msi 128 | *.msm 129 | *.msp 130 | 131 | # Windows shortcuts 132 | *.lnk 133 | ### Vim template 134 | # swap 135 | [._]*.s[a-v][a-z] 136 | [._]*.sw[a-p] 137 | [._]s[a-v][a-z] 138 | [._]sw[a-p] 139 | # session 140 | Session.vim 141 | # temporary 142 | .netrwhist 143 | *~ 144 | # auto-generated tag files 145 | tags 146 | ### macOS template 147 | *.DS_Store 148 | .AppleDouble 149 | .LSOverride 150 | 151 | # Icon must end with two \r 152 | Icon 153 | 154 | 155 | # Thumbnails 156 | ._* 157 | 158 | # Files that might appear in the root of a volume 159 | .DocumentRevisions-V100 160 | .fseventsd 161 | .Spotlight-V100 162 | .TemporaryItems 163 | .Trashes 164 | .VolumeIcon.icns 165 | .com.apple.timemachine.donotpresent 166 | 167 | # Directories potentially created on remote AFP share 168 | .AppleDB 169 | .AppleDesktop 170 | Network Trash Folder 171 | Temporary Items 172 | .apdisk 173 | ### SublimeText template 174 | # cache files for sublime text 175 | *.tmlanguage.cache 176 | *.tmPreferences.cache 177 | *.stTheme.cache 178 | 179 | # workspace files are user-specific 180 | *.sublime-workspace 181 | 182 | # project files should be checked into the repository, unless a significant 183 | # proportion of contributors will probably not be using SublimeText 184 | # *.sublime-project 185 | 186 | # sftp configuration file 187 | sftp-config.json 188 | 189 | # Package control specific files 190 | Package Control.last-run 191 | Package Control.ca-list 192 | Package Control.ca-bundle 193 | Package Control.system-ca-bundle 194 | Package Control.cache/ 195 | Package Control.ca-certs/ 196 | Package Control.merged-ca-bundle 197 | Package Control.user-ca-bundle 198 | oscrypto-ca-bundle.crt 199 | bh_unicode_properties.cache 200 | 201 | # Sublime-github package stores a github token in this file 202 | # https://packagecontrol.io/packages/sublime-github 203 | GitHub.sublime-settings 204 | ### Linux template 205 | 206 | # temporary files which can be created if a process still has a handle open of a deleted file 207 | .fuse_hidden* 208 | 209 | # KDE directory preferences 210 | .directory 211 | 212 | # Linux trash folder which might appear on any partition or disk 213 | .Trash-* 214 | 215 | # .nfs files are created when an open file is removed but is still being accessed 216 | .nfs* 217 | ### VirtualEnv template 218 | # Virtualenv 219 | # http://iamzed.com/2009/05/07/a-primer-on-virtualenv/ 220 | [Bb]in 221 | [Ii]nclude 222 | [Ll]ib 223 | [Ll]ib64 224 | [Ll]ocal 225 | [Ss]cripts 226 | pyvenv.cfg 227 | .venv 228 | pip-selfcheck.json 229 | 230 | .pytest_cache/ 231 | -------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/python-humble-utils.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 14 | -------------------------------------------------------------------------------- /.idea/shellcheckPlugin.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # This file was autogenerated and will overwrite each time you run travis_pypi_setup.py 2 | 3 | 4 | language: python 5 | python: 6 | - 3.6 7 | - 3.7 8 | - 3.8 9 | 10 | install: 11 | - pip install -r ./requirements.code-style.txt 12 | - pip install -U tox-travis 13 | 14 | before_script: 15 | - black --check . 16 | - pip install -r ./requirements.coverage.txt 17 | 18 | script: 19 | - tox -e codecov 20 | 21 | deploy: 22 | on: 23 | repo: webyneter/python-humble-utils 24 | tags: true 25 | python: 3.6 26 | user: webyneter 27 | password: 28 | secure: !!binary | 29 | R3ZybmhDSHRCUUN5SGQ2dnd0RmlBR2tKM1BSeEtCNWpRWVMxRFNWZElXYXpNUVhCNVJPeEE0Q2p5 30 | U1JmNnRaVWRWb0Y0NGd6U2lYMmlNSzVvNGJ3dlBKRlBWakE5WEU2UENab002ZVVZTXZuaVlhNGs1 31 | M2NKa08xWk9FL2ZyM1NHREFMdkxWTVBGM2t6ZVdjQmhMcnNVOE85MmlPQ01vemtHM0dqUlB6WnpN 32 | alR4WGNwNVlRSWpLd1RwNmVpTFE3dU1IN3M2b3ZBU3NjM0N2N3FRUTY1VURmZExzOUhvVExRcGNO 33 | WnlGRzJLcVJwSTF5WlpTWUQ1dVN0SS9UUFZZUkE2RkNPYVg5ZjhGVTZXWXRSd0NxblpMdGtLQUtT 34 | cTJUbjhMWVowUzVTM0ZUQzg3TnBiL0ozTm0wNzY4czlZWmdvQklnSis5eGsvcXBJdjJkb1pTUDM1 35 | MzIyclRtcEZUV2p0ODR5RG5lK2FGeno1L1JxRkJrVzBFdEdudEc2R0RyOWkrT0QvaWxmelpSRy83 36 | Rk5DZVlMcnY5T3ZRRVJMRi80cERjUHZkREFKUGx5eFhtV0I4NjBxQ3M3Z1lCUzJHY3o0UFVQbTd4 37 | N1AvOEhtblFhZHo1RTllaC96dG9mcUxZV25hSm0wVFJtbUxMb09yeWl4MmRyTEhYUkpMNmt6R0xi 38 | cXBNWXVNZ3h4TXNlTFRKRmEwM1ZsL3N2Rmx1MGp3c3craFZNVE00N3ZTUHVKMHpjSHJpR3pyaGRB 39 | VUpyQmRxS0x6OC9USUhzQlZzM09NNUlQYit0cExMRXNEUEJOa01ySFh0RHN0UHdaNTRySXNINWlm 40 | c1lyTEZQV1JZV2ZiRGlzN2xCVktzTWcyUC9yOTBqOGlqN1g4RlFuak9kTHpTaFRvZktNbUJKcDA9 41 | provider: pypi 42 | distributions: sdist bdist_wheel 43 | -------------------------------------------------------------------------------- /AUTHORS.rst: -------------------------------------------------------------------------------- 1 | Credits 2 | ======= 3 | 4 | Development Lead 5 | ---------------- 6 | 7 | * Nikita P. Shupeyko 8 | 9 | Contributors 10 | ------------ 11 | 12 | None yet. Why not be the first? 13 | -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | .. highlight:: shell 2 | 3 | .. _contributing: 4 | 5 | Contributing 6 | ============ 7 | 8 | Contributions are welcome, and they are greatly appreciated! Every 9 | little bit helps, and credit will always be given. 10 | 11 | .. include:: ./includes/execution_context_notice.rst 12 | 13 | 14 | Ways You Can Help Us 15 | -------------------- 16 | 17 | Report Bugs 18 | ~~~~~~~~~~~ 19 | 20 | `Create an issue`_ corresponding to the bug you have found complying with 21 | the project's issue template. 22 | 23 | .. _`Create an issue`: https://github.com/webyneter/python-humble-utils/issues/new 24 | 25 | 26 | Fix Bugs 27 | ~~~~~~~~ 28 | 29 | Look through the GitHub issues: Anything tagged with ``bug`` and without an ``Assignee`` 30 | is open to whoever wants to implement it. 31 | 32 | Make sure to submit clean, concise, well-tested pull requests only, so it is easier 33 | for contributors to review it; strive to deliver as short and atomic pull requests 34 | as possible as this will dramatically increase the likelihood of those being merged. 35 | 36 | 37 | Implement Features 38 | ~~~~~~~~~~~~~~~~~~ 39 | 40 | Look through the GitHub issues for features. Anything tagged with ``enhancement`` 41 | and/or ``help wanted`` and/or without an ``Assignee`` is open to whoever 42 | wants to implement it. 43 | 44 | 45 | Write Documentation 46 | ~~~~~~~~~~~~~~~~~~~ 47 | 48 | We could always use more documentation, whether as part of the official docs, 49 | in docstrings, or even on the web in blog posts, articles, and such. 50 | 51 | 52 | Submit Feedback 53 | ~~~~~~~~~~~~~~~ 54 | 55 | The best way to send feedback is to `file an issue`_. 56 | 57 | .. _`file an issue`: https://github.com/webyneter/python-humble-utils/issues/new 58 | 59 | If you are proposing a feature, 60 | 61 | * explain in detail how it would work; 62 | * keep the scope as narrow as possible, to make it easier to implement; 63 | * remember that this is a volunteer-driven project, so contributions are welcome! 64 | 65 | 66 | 67 | Workflow 68 | -------- 69 | 70 | See :ref:`developing-locally` for detailed instructions on setting up local environment. 71 | 72 | Oncer you are all set up, 73 | 74 | #. create a branch:: 75 | 76 | $ git checkout -b - 77 | 78 | #. make the contribution; 79 | 80 | #. follow :ref:`developing-locally-tox` to run tests comprehensively; 81 | 82 | #. commit changes to the branch:: 83 | 84 | $ git add . 85 | $ git commit -m "" 86 | 87 | #. push the branch to GitHub:: 88 | 89 | $ git push origin - 90 | 91 | #. submit a pull request via GitHub or any other git GUI tool you prefer. 92 | 93 | .. _`virtualenv`: https://virtualenv.pypa.io/en/stable/ 94 | .. _`virtualenvwrapper`: https://virtualenvwrapper.readthedocs.io/en/stable/ 95 | 96 | 97 | 98 | Guidelines 99 | ---------- 100 | 101 | Upon submission, make sure the PR meets these guidelines: 102 | 103 | #. the PR does not decrease code coverage (unless there is a very specific reason to); 104 | #. the docs (both programmatic and manual) are updated, if needed. 105 | -------------------------------------------------------------------------------- /HISTORY.rst: -------------------------------------------------------------------------------- 1 | History 2 | ======= 3 | 4 | 5 | v3.0.1 6 | ------ 7 | 8 | `v3.0.1 `_. 9 | 10 | * `Sync usage guides `_. 11 | * `Update `HISTORY.rst `_. 12 | 13 | 14 | v3.0.0 15 | ------ 16 | 17 | `v3.0.0 `_. 18 | 19 | Breaking changes: 20 | 21 | * The following functions have been removed as part of the `Remove redundant utilities/utilities making no sense `_ effort: 22 | * `extract_file_name_with_extension` 23 | * `extract_file_name_and_extension` 24 | * `extract_file_dir_path` 25 | * `parse_tuple_from_string` 26 | * `generate_hex_uuid_4` 27 | * `generate_random_file_name_with_extension` 28 | * `get_class_name` 29 | * `get_class_qualname` 30 | * Package structure has been altered. 31 | * `Drop support for Python 3.5 `_. 32 | 33 | Other changes: 34 | 35 | * `Update the docs `_. 36 | * `Switch from Python 3.6+ typing.Collection back to typing.Sequence for backward compatibility with Python 3.5 `_. 37 | * `Support Python 3.8 `_. 38 | * `Switch to native Python paths `_. 39 | * `Support Python 3.7 `_. 40 | * Upgrade all dependencies to the latest versions to date. 41 | 42 | 43 | v2.0.0 44 | ------ 45 | 46 | `v2.0.0 `_. 47 | 48 | * `Move tests to the root `_. 49 | * `Pick another naming scheme for tests `_. 50 | * `Convert NamedTuple's to classes and document them `_. 51 | * `Clean up docstrings `_. 52 | * `Stop indexing tests in docs `_. 53 | 54 | 55 | v1.0.4 56 | ------ 57 | 58 | `v1.0.4 `_. 59 | 60 | * `Update HISTORY `_. 61 | 62 | 63 | v1.0.3 64 | ------ 65 | 66 | `v1.0.3 `_. 67 | 68 | * `Fix deployment to the new PyPI `_. 69 | * `Mention python-humble-utils in "Open Source Projects using Hypothesis" `_. 70 | * `Move bumpversion configuration from setup.cfg to .bumpversion.cfg `_. 71 | * `Enclose notes in Note blocks `_. 72 | * `Remove entrypoint section from setup.py `_. 73 | * `Add insert utility `_. 74 | 75 | 76 | v1.0.2 77 | ------ 78 | 79 | `v1.0.2 `_. 80 | 81 | * `Add Code Climate badge to README `_. 82 | 83 | 84 | v1.0.1 85 | ------ 86 | 87 | `v1.0.1 `_. 88 | 89 | * `Fix README not rendered properly on PyPI `_. 90 | 91 | 92 | v1.0.0 93 | ------ 94 | 95 | `v1.0.0 `_. 96 | 97 | * `Bump package Development Status `_. 98 | * `Test package deployment locally `_. 99 | * `Fix relative paths notice `_. 100 | * `Add Gitter badge `_. 101 | * `Fill in HISTORY `_. 102 | 103 | 104 | v0.5.0 105 | ------ 106 | 107 | `v0.5.0 `_. 108 | 109 | * `Document python_humble_utils package `_. 110 | * `Introduce local requirements `_. 111 | * `Stop using pip-tools `_. 112 | * `Point out that all paths in docs are relative to the project root `_. 113 | * `Prevent pip-tools from injecting indirect requirements `_. 114 | * `Target stable docs version only `_. 115 | * `Fix README not rendered on PyPI `_. 116 | * `Ensure codecov evaluates coverage against payload files only `_. 117 | 118 | 119 | v0.4.0 120 | ------ 121 | 122 | `v0.4.0 `_. 123 | 124 | * `Support Python 3.6 `_. 125 | 126 | 127 | v0.3.0 128 | ------ 129 | 130 | `v0.3.0 `_. 131 | 132 | * `Setup ReadTheDocs `_. 133 | 134 | 135 | v0.2.0 136 | ------ 137 | 138 | `v0.2.0 `_. 139 | 140 | * First release on PyPI. 141 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017-2020 Nikita P. Shupeyko 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include AUTHORS.rst 2 | include CONTRIBUTING.rst 3 | include HISTORY.rst 4 | include LICENSE 5 | include README.rst 6 | 7 | recursive-include python_humble_utils/tests * 8 | recursive-exclude * __pycache__ 9 | recursive-exclude * *.py[co] 10 | 11 | recursive-include docs *.rst conf.py Makefile make.bat *.jpg *.png *.gif 12 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: help docs synclocal clean clean-test clean-pyc clean-build 2 | .DEFAULT_GOAL := help 3 | define BROWSER_PYSCRIPT 4 | import os, webbrowser, sys 5 | try: 6 | from urllib import pathname2url 7 | except: 8 | from urllib.request import pathname2url 9 | 10 | webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1]))) 11 | endef 12 | export BROWSER_PYSCRIPT 13 | 14 | define PRINT_HELP_PYSCRIPT 15 | import re, sys 16 | 17 | for line in sys.stdin: 18 | match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line) 19 | if match: 20 | target, help = match.groups() 21 | print("%-20s %s" % (target, help)) 22 | endef 23 | export PRINT_HELP_PYSCRIPT 24 | BROWSER := python -c "$$BROWSER_PYSCRIPT" 25 | 26 | help: 27 | @python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST) 28 | 29 | clean: clean-build clean-pyc clean-test ## remove all build, test, coverage and Python artifacts 30 | 31 | 32 | clean-build: ## remove build artifacts 33 | rm -fr build/ 34 | rm -fr dist/ 35 | rm -fr .eggs/ 36 | find . -name '*.egg-info' -exec rm -fr {} + 37 | find . -name '*.egg' -exec rm -f {} + 38 | 39 | clean-pyc: ## remove Python file artifacts 40 | find . -name '*.pyc' -exec rm -f {} + 41 | find . -name '*.pyo' -exec rm -f {} + 42 | find . -name '*~' -exec rm -f {} + 43 | find . -name '__pycache__' -exec rm -fr {} + 44 | 45 | clean-test: ## remove test and coverage artifacts 46 | rm -fr .tox/ 47 | rm -f .coverage 48 | rm -fr htmlcov/ 49 | 50 | lint: ## check style with flake8 51 | flake8 python_humble_utils tests 52 | 53 | test: ## run tests quickly with the default Python 54 | pytest --hypothesis-show-statistics 55 | 56 | test-all: ## run tests on every Python version with tox 57 | tox 58 | 59 | coverage: ## check code coverage quickly with the default Python 60 | coverage run --source python_humble_utils -m pytest 61 | coverage report -m 62 | coverage html 63 | $(BROWSER) htmlcov/index.html 64 | 65 | docs: ## generate Sphinx HTML documentation, including API docs 66 | rm -f docs/python_humble_utils.rst 67 | rm -f docs/modules.rst 68 | sphinx-apidoc -o docs/ python_humble_utils 69 | $(MAKE) -C docs clean 70 | $(MAKE) -C docs html 71 | $(BROWSER) docs/_build/html/index.html 72 | 73 | servedocs: docs ## compile the docs watching for changes 74 | watchmedo shell-command -p '*.rst' -c '$(MAKE) -C docs html' -R -D . 75 | 76 | setup-release: clean ## package and upload a release 77 | python setup.py sdist upload 78 | python setup.py bdist_wheel upload 79 | 80 | setup-dist: clean ## builds source and wheel package 81 | python setup.py sdist 82 | python setup.py bdist_wheel 83 | ls -l dist 84 | 85 | setup-install: clean ## install the package to the active Python's site-packages 86 | python setup.py install 87 | 88 | install: 89 | $(pip freeze | xargs pip uninstall -y) 90 | pip install -r ./requirements.txt 91 | pip install -r ./requirements.docs.txt 92 | pip install -r ./requirements.coverage.txt 93 | pip install -r ./requirements.code-style.txt 94 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | Python Humble Utils 2 | =================== 3 | 4 | .. image:: https://travis-ci.org/webyneter/python-humble-utils.svg?branch=master 5 | :target: https://travis-ci.org/webyneter/python-humble-utils 6 | :alt: Build Status 7 | 8 | .. image:: https://badgen.net/dependabot/webyneter/python-humble-utils/?icon=dependabot 9 | :target: https://badgen.net/dependabot/webyneter/python-humble-utils/?icon=dependabot 10 | :alt: dependabot 11 | 12 | .. image:: https://codecov.io/gh/webyneter/python-humble-utils/branch/master/graph/badge.svg 13 | :target: https://codecov.io/gh/webyneter/python-humble-utils 14 | :alt: Coverage 15 | 16 | .. image:: https://codeclimate.com/github/webyneter/python-humble-utils/badges/gpa.svg 17 | :target: https://codeclimate.com/github/webyneter/python-humble-utils 18 | :alt: Code Climate 19 | 20 | .. image:: https://badge.fury.io/py/python-humble-utils.svg 21 | :target: https://pypi.python.org/pypi/python-humble-utils 22 | :alt: Latest Version 23 | 24 | .. image:: https://img.shields.io/pypi/pyversions/python-humble-utils.svg 25 | :target: https://pypi.python.org/pypi/python-humble-utils 26 | :alt: Supported Python Versions 27 | 28 | .. image:: https://readthedocs.org/projects/python-humble-utils/badge/?version=stable 29 | :target: http://python-humble-utils.readthedocs.io/en/stable/?badge=stable 30 | :alt: Documentation Status 31 | 32 | .. image:: https://img.shields.io/badge/License-MIT-green.svg 33 | :target: https://opensource.org/licenses/MIT 34 | :alt: MIT License 35 | 36 | .. image:: https://img.shields.io/gitter/room/webyneter/python-humble-utils.svg 37 | :target: https://gitter.im/webyneter/python-humble-utils?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge 38 | :alt: Join the chat at https://gitter.im/webyneter/python-humble-utils 39 | 40 | 41 | Python utils for everyday use. 42 | 43 | * `Documentation`_. 44 | * Please, `open issues`_ before sending emails to the maintainers: You will get a much faster response! 45 | 46 | .. _`open issues`: https://github.com/webyneter/python-humble-utils/issues/new 47 | .. _`Documentation`: https://python-humble-utils.readthedocs.io/en/stable/installation.html 48 | 49 | 50 | 51 | Feature Areas 52 | ------------- 53 | 54 | * File operations. 55 | * File/directory paths extraction. 56 | * File/directory paths randomization. 57 | * String case conversions. 58 | * Python class convenience shortcuts. 59 | * `py.test`_ fixtures and helpers. 60 | 61 | .. _`py.test`: https://docs.pytest.org/en/stable/ 62 | 63 | 64 | 65 | Installation 66 | ------------ 67 | 68 | .. code-block:: console 69 | 70 | $ pip install python-humble-utils 71 | 72 | or install from sources: 73 | 74 | .. code-block:: console 75 | 76 | $ python setup.py install 77 | 78 | Refer to `Installation`_ for detailed instructions. 79 | 80 | .. _`Installation`: https://python-humble-utils.readthedocs.io/en/stable/installation.html 81 | 82 | 83 | Usage 84 | ----- 85 | 86 | .. code-block:: python 87 | 88 | import os 89 | from pathlib import Path 90 | 91 | from python_humble_utils.filesystem import yield_file_paths 92 | from python_humble_utils.strings import camel_or_pascal_case_to_snake_case 93 | 94 | 95 | # ... 96 | 97 | file_paths = yield_file_paths( 98 | dir_path=Path("dir") / "with" / "scripts", 99 | allowed_file_extensions=(".sh", ".bash"), 100 | recursively=True 101 | ) 102 | assert set(file_paths) == set(("s1.sh", "s2.bash", "s3.bash")) 103 | 104 | s = camel_or_pascal_case_to_snake_case("camelCasedString") 105 | assert s == "camel_cased_string" 106 | 107 | s = camel_or_pascal_case_to_snake_case("PascalCasedString") 108 | assert s == "pascal_cased_string" 109 | 110 | # ... 111 | 112 | 113 | Contributing 114 | ------------ 115 | 116 | Your contributions are very much welcome! Refer to `Contributing`_ for more details. 117 | 118 | .. _`Contributing`: https://python-humble-utils.readthedocs.io/en/stable/contributing.html 119 | 120 | 121 | 122 | Code of Conduct 123 | --------------- 124 | 125 | All those using ``python-humble-utils``, including its codebase and project management ecosystem are expected to follow the `Python Community Code of Conduct`_. 126 | 127 | .. _`Python Community Code of Conduct`: https://www.python.org/psf/codeofconduct/ 128 | 129 | 130 | 131 | Acknowledgements 132 | ---------------- 133 | 134 | This package was initially scaffolded via `Cookiecutter`_ with `audreyr/cookiecutter-pypackage`_ template. 135 | 136 | .. _`Cookiecutter`: https://github.com/audreyr/cookiecutter 137 | .. _`audreyr/cookiecutter-pypackage`: https://github.com/audreyr/cookiecutter-pypackage 138 | 139 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " devhelp to make HTML files and a Devhelp project" 34 | @echo " epub to make an epub" 35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 36 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 38 | @echo " text to make text files" 39 | @echo " man to make manual pages" 40 | @echo " texinfo to make Texinfo files" 41 | @echo " info to make Texinfo files and run them through makeinfo" 42 | @echo " gettext to make PO message catalogs" 43 | @echo " changes to make an overview of all changed/added/deprecated items" 44 | @echo " xml to make Docutils-native XML files" 45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 46 | @echo " linkcheck to check all external links for integrity" 47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 48 | 49 | clean: 50 | rm -rf $(BUILDDIR)/* 51 | 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | dirhtml: 58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 59 | @echo 60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 61 | 62 | singlehtml: 63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 64 | @echo 65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 66 | 67 | pickle: 68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 69 | @echo 70 | @echo "Build finished; now you can process the pickle files." 71 | 72 | json: 73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 74 | @echo 75 | @echo "Build finished; now you can process the JSON files." 76 | 77 | htmlhelp: 78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 79 | @echo 80 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 81 | ".hhp project file in $(BUILDDIR)/htmlhelp." 82 | 83 | qthelp: 84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 85 | @echo 86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/python_humble_utils.qhcp" 89 | @echo "To view the help file:" 90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/python_humble_utils.qhc" 91 | 92 | devhelp: 93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 94 | @echo 95 | @echo "Build finished." 96 | @echo "To view the help file:" 97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/python_humble_utils" 98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/python_humble_utils" 99 | @echo "# devhelp" 100 | 101 | epub: 102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 103 | @echo 104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 105 | 106 | latex: 107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 108 | @echo 109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 111 | "(use \`make latexpdf' here to do that automatically)." 112 | 113 | latexpdf: 114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 115 | @echo "Running LaTeX files through pdflatex..." 116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 118 | 119 | latexpdfja: 120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 121 | @echo "Running LaTeX files through platex and dvipdfmx..." 122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 124 | 125 | text: 126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 127 | @echo 128 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 129 | 130 | man: 131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 132 | @echo 133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 134 | 135 | texinfo: 136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 137 | @echo 138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 139 | @echo "Run \`make' in that directory to run these through makeinfo" \ 140 | "(use \`make info' here to do that automatically)." 141 | 142 | info: 143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 144 | @echo "Running Texinfo files through makeinfo..." 145 | make -C $(BUILDDIR)/texinfo info 146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 147 | 148 | gettext: 149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 150 | @echo 151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 152 | 153 | changes: 154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 155 | @echo 156 | @echo "The overview file is in $(BUILDDIR)/changes." 157 | 158 | linkcheck: 159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 160 | @echo 161 | @echo "Link check complete; look for any errors in the above output " \ 162 | "or in $(BUILDDIR)/linkcheck/output.txt." 163 | 164 | doctest: 165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 166 | @echo "Testing of doctests in the sources finished, look at the " \ 167 | "results in $(BUILDDIR)/doctest/output.txt." 168 | 169 | xml: 170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 171 | @echo 172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 173 | 174 | pseudoxml: 175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 176 | @echo 177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 178 | -------------------------------------------------------------------------------- /docs/authors.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../AUTHORS.rst 2 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # python_humble_utils documentation build configuration file, created by 4 | # sphinx-quickstart on Tue Jul 9 22:26:36 2013. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | import os 16 | import sys 17 | 18 | # If extensions (or modules to document with autodoc) are in another 19 | # directory, add these directories to sys.path here. If the directory is 20 | # relative to the documentation root, use os.path.abspath to make it 21 | # absolute, like shown here. 22 | # sys.path.insert(0, os.path.abspath('.')) 23 | 24 | # Get the project root dir, which is the parent dir of this 25 | cwd = os.getcwd() 26 | project_root = os.path.dirname(cwd) 27 | 28 | # Insert the project root dir as the first element in the PYTHONPATH. 29 | # This lets us ensure that the source package is imported, and that its 30 | # version is used. 31 | sys.path.insert(0, project_root) 32 | 33 | import python_humble_utils 34 | 35 | # -- General configuration --------------------------------------------- 36 | 37 | # If your documentation needs a minimal Sphinx version, state it here. 38 | # needs_sphinx = '1.0' 39 | 40 | # Add any Sphinx extension module names here, as strings. They can be 41 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 42 | extensions = ["sphinx.ext.autodoc", "sphinx.ext.viewcode"] 43 | 44 | # Add any paths that contain templates here, relative to this directory. 45 | templates_path = ["_templates"] 46 | 47 | # The suffix of source filenames. 48 | source_suffix = ".rst" 49 | 50 | # The encoding of source files. 51 | # source_encoding = 'utf-8-sig' 52 | 53 | # The master toctree document. 54 | master_doc = "index" 55 | 56 | # General information about the project. 57 | project = u"Python Humble Utils" 58 | copyright = u"2017-2020, Nikita P. Shupeyko" 59 | 60 | # The version info for the project you're documenting, acts as replacement 61 | # for |version| and |release|, also used in various other places throughout 62 | # the built documents. 63 | # 64 | # The short X.Y version. 65 | version = python_humble_utils.__version__ 66 | # The full version, including alpha/beta/rc tags. 67 | release = python_humble_utils.__version__ 68 | 69 | # The language for content autogenerated by Sphinx. Refer to documentation 70 | # for a list of supported languages. 71 | # language = None 72 | 73 | # There are two options for replacing |today|: either, you set today to 74 | # some non-false value, then it is used: 75 | # today = '' 76 | # Else, today_fmt is used as the format for a strftime call. 77 | # today_fmt = '%B %d, %Y' 78 | 79 | # List of patterns, relative to source directory, that match files and 80 | # directories to ignore when looking for source files. 81 | exclude_patterns = ["_build"] 82 | 83 | # The reST default role (used for this markup: `text`) to use for all 84 | # documents. 85 | # default_role = None 86 | 87 | # If true, '()' will be appended to :func: etc. cross-reference text. 88 | # add_function_parentheses = True 89 | 90 | # If true, the current module name will be prepended to all description 91 | # unit titles (such as .. function::). 92 | # add_module_names = True 93 | 94 | # If true, sectionauthor and moduleauthor directives will be shown in the 95 | # output. They are ignored by default. 96 | # show_authors = False 97 | 98 | # The name of the Pygments (syntax highlighting) style to use. 99 | pygments_style = "sphinx" 100 | 101 | # A list of ignored prefixes for module index sorting. 102 | # modindex_common_prefix = [] 103 | 104 | # If true, keep warnings as "system message" paragraphs in the built 105 | # documents. 106 | # keep_warnings = False 107 | 108 | 109 | # -- Options for HTML output ------------------------------------------- 110 | 111 | # The theme to use for HTML and HTML Help pages. See the documentation for 112 | # a list of builtin themes. 113 | html_theme = "default" 114 | 115 | # Theme options are theme-specific and customize the look and feel of a 116 | # theme further. For a list of options available for each theme, see the 117 | # documentation. 118 | # html_theme_options = {} 119 | 120 | # Add any paths that contain custom themes here, relative to this directory. 121 | # html_theme_path = [] 122 | 123 | # The name for this set of Sphinx documents. If None, it defaults to 124 | # " v documentation". 125 | # html_title = None 126 | 127 | # A shorter title for the navigation bar. Default is the same as 128 | # html_title. 129 | # html_short_title = None 130 | 131 | # The name of an image file (relative to this directory) to place at the 132 | # top of the sidebar. 133 | # html_logo = None 134 | 135 | # The name of an image file (within the static path) to use as favicon 136 | # of the docs. This file should be a Windows icon file (.ico) being 137 | # 16x16 or 32x32 pixels large. 138 | # html_favicon = None 139 | 140 | # Add any paths that contain custom static files (such as style sheets) 141 | # here, relative to this directory. They are copied after the builtin 142 | # static files, so a file named "default.css" will overwrite the builtin 143 | # "default.css". 144 | html_static_path = ["_static"] 145 | 146 | # If not '', a 'Last updated on:' timestamp is inserted at every page 147 | # bottom, using the given strftime format. 148 | # html_last_updated_fmt = '%b %d, %Y' 149 | 150 | # If true, SmartyPants will be used to convert quotes and dashes to 151 | # typographically correct entities. 152 | # html_use_smartypants = True 153 | 154 | # Custom sidebar templates, maps document names to template names. 155 | # html_sidebars = {} 156 | 157 | # Additional templates that should be rendered to pages, maps page names 158 | # to template names. 159 | # html_additional_pages = {} 160 | 161 | # If false, no module index is generated. 162 | # html_domain_indices = True 163 | 164 | # If false, no index is generated. 165 | # html_use_index = True 166 | 167 | # If true, the index is split into individual pages for each letter. 168 | # html_split_index = False 169 | 170 | # If true, links to the reST sources are added to the pages. 171 | # html_show_sourcelink = True 172 | 173 | # If true, "Created using Sphinx" is shown in the HTML footer. 174 | # Default is True. 175 | # html_show_sphinx = True 176 | 177 | # If true, "(C) Copyright ..." is shown in the HTML footer. 178 | # Default is True. 179 | # html_show_copyright = True 180 | 181 | # If true, an OpenSearch description file will be output, and all pages 182 | # will contain a tag referring to it. The value of this option 183 | # must be the base URL from which the finished HTML is served. 184 | # html_use_opensearch = '' 185 | 186 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 187 | # html_file_suffix = None 188 | 189 | # Output file base name for HTML help builder. 190 | htmlhelp_basename = "python_humble_utilsdoc" 191 | 192 | # -- Options for LaTeX output ------------------------------------------ 193 | 194 | latex_elements = { 195 | # The paper size ('letterpaper' or 'a4paper'). 196 | # 'papersize': 'letterpaper', 197 | # The font size ('10pt', '11pt' or '12pt'). 198 | # 'pointsize': '10pt', 199 | # Additional stuff for the LaTeX preamble. 200 | # 'preamble': '', 201 | } 202 | 203 | # Grouping the document tree into LaTeX files. List of tuples 204 | # (source start file, target name, title, author, documentclass 205 | # [howto/manual]). 206 | latex_documents = [ 207 | ( 208 | "index", 209 | "python_humble_utils.tex", 210 | u"Python Humble Utils Documentation", 211 | u"Nikita P. Shupeyko", 212 | "manual", 213 | ) 214 | ] 215 | 216 | # The name of an image file (relative to this directory) to place at 217 | # the top of the title page. 218 | # latex_logo = None 219 | 220 | # For "manual" documents, if this is true, then toplevel headings 221 | # are parts, not chapters. 222 | # latex_use_parts = False 223 | 224 | # If true, show page references after internal links. 225 | # latex_show_pagerefs = False 226 | 227 | # If true, show URL addresses after external links. 228 | # latex_show_urls = False 229 | 230 | # Documents to append as an appendix to all manuals. 231 | # latex_appendices = [] 232 | 233 | # If false, no module index is generated. 234 | # latex_domain_indices = True 235 | 236 | 237 | # -- Options for manual page output ------------------------------------ 238 | 239 | # One entry per manual page. List of tuples 240 | # (source start file, name, description, authors, manual section). 241 | man_pages = [ 242 | ( 243 | "index", 244 | "python_humble_utils", 245 | u"Python Humble Utils Documentation", 246 | [u"Nikita P. Shupeyko"], 247 | 1, 248 | ) 249 | ] 250 | 251 | # If true, show URL addresses after external links. 252 | # man_show_urls = False 253 | 254 | 255 | # -- Options for Texinfo output ---------------------------------------- 256 | 257 | # Grouping the document tree into Texinfo files. List of tuples 258 | # (source start file, target name, title, author, 259 | # dir menu entry, description, category) 260 | texinfo_documents = [ 261 | ( 262 | "index", 263 | "python_humble_utils", 264 | u"Python Humble Utils Documentation", 265 | u"Nikita P. Shupeyko", 266 | "python_humble_utils", 267 | "Python utils for everyday use.", 268 | "Miscellaneous", 269 | ) 270 | ] 271 | 272 | # Documents to append as an appendix to all manuals. 273 | # texinfo_appendices = [] 274 | 275 | # If false, no module index is generated. 276 | # texinfo_domain_indices = True 277 | 278 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 279 | # texinfo_show_urls = 'footnote' 280 | 281 | # If true, do not generate a @detailmenu in the "Top" node's menu. 282 | # texinfo_no_detailmenu = False 283 | -------------------------------------------------------------------------------- /docs/contributing.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../CONTRIBUTING.rst 2 | -------------------------------------------------------------------------------- /docs/developing-locally.rst: -------------------------------------------------------------------------------- 1 | .. highlight:: shell 2 | 3 | .. _developing-locally: 4 | 5 | Developing Locally 6 | ================== 7 | 8 | .. include:: ./includes/execution_context_notice.rst 9 | 10 | 11 | Environment Setup 12 | ----------------- 13 | 14 | #. Fork us on `GitHub`_. 15 | 16 | #. Clone your fork locally:: 17 | 18 | $ git clone git@github.com:/python-humble-utils.git 19 | 20 | #. Create a `virtualenv`_ ; assuming you have `virtualenvwrapper`_ installed, this is how you do it:: 21 | 22 | $ mkvirtualenv python_humble_utils 23 | $ cd 24 | $ setvirtualenvproject 25 | 26 | #. Initialize environment:: 27 | 28 | $ python setup.py develop 29 | 30 | 31 | .. _`GitHub`: https://github.com/webyneter/python-humble-utils/ 32 | .. _`virtualenv`: https://virtualenv.pypa.io/en/stable/ 33 | .. _`virtualenvwrapper`: https://virtualenvwrapper.readthedocs.io/en/stable/ 34 | 35 | 36 | 37 | Scenarios 38 | --------- 39 | 40 | 41 | Updating Requirements 42 | ~~~~~~~~~~~~~~~~~~~~~ 43 | 44 | Project requirements must be declared and pinned in ``./requirements*.txt``. 45 | 46 | To install/upgrade/uninstall dependencies into/in/from the environment:: 47 | 48 | $ make install 49 | 50 | 51 | .. _developing-locally-tox: 52 | 53 | Running ``tox`` with Multiple Python Distributions 54 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 55 | 56 | Running ``tox`` locally requires a number of Python distributions to be available, 57 | which is a challenge, to say the least. `pyenv`_ helps overcome this major obstacle. 58 | 59 | #. Follow `pyenv installation instructions`_ to install ``pyenv`` system-wide. 60 | 61 | #. Install all versions of Python the project is tested against by ``tox`` (see ``./tox.ini``). 62 | 63 | #. Run ``tox``:: 64 | 65 | $ make test-all 66 | 67 | 68 | .. _`pyenv`: https://github.com/pyenv/pyenv 69 | .. _`pyenv installation instructions`: https://github.com/pyenv/pyenv#installation 70 | -------------------------------------------------------------------------------- /docs/history.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../HISTORY.rst 2 | -------------------------------------------------------------------------------- /docs/includes/execution_context_notice.rst: -------------------------------------------------------------------------------- 1 | .. note:: *The commands below are presumed to be run relative to the project root 2 | unless explicitly stated otherwise.* ``./`` *also refers to the project root.* 3 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | Python Humble Utils Documentation 2 | ================================= 3 | 4 | Contents: 5 | 6 | .. toctree:: 7 | :maxdepth: 2 8 | 9 | readme 10 | python_humble_utils 11 | installation 12 | usage 13 | contributing 14 | developing-locally 15 | project-makefile 16 | authors 17 | history 18 | 19 | Indices and tables 20 | ================== 21 | 22 | * :ref:`genindex` 23 | * :ref:`modindex` 24 | * :ref:`search` 25 | -------------------------------------------------------------------------------- /docs/installation.rst: -------------------------------------------------------------------------------- 1 | .. highlight:: shell 2 | 3 | .. _installation: 4 | 5 | Installation 6 | ============ 7 | 8 | .. include:: ./includes/execution_context_notice.rst 9 | 10 | 11 | From PyPI 12 | --------- 13 | 14 | To install the latest release, run 15 | 16 | .. code-block:: console 17 | 18 | $ pip install python-humble-utils 19 | 20 | Or, install a specific version via 21 | 22 | .. code-block:: console 23 | 24 | $ pip install python-humble-utils== 25 | 26 | If you don't have `pip`_ installed, this `Python installation guide`_ can guide 27 | you through the process. 28 | 29 | .. _pip: https://pip.pypa.io 30 | .. _Python installation guide: http://docs.python-guide.org/en/stable/starting/installation/ 31 | 32 | 33 | From Sources 34 | ------------ 35 | 36 | #. Obtain sources 37 | 38 | * cloning the repository:: 39 | 40 | $ git clone git://github.com/webyneter/python-humble-utils 41 | 42 | * or, downloading a `tarball`_:: 43 | 44 | $ curl -OL https://github.com/webyneter/python-humble-utils/tarball/master 45 | 46 | #. Install via:: 47 | 48 | $ python setup.py install 49 | 50 | .. _Github repo: https://github.com/webyneter/python-humble-utils 51 | .. _tarball: https://github.com/webyneter/python-humble-utils/tarball/master 52 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. xml to make Docutils-native XML files 37 | echo. pseudoxml to make pseudoxml-XML files for display purposes 38 | echo. linkcheck to check all external links for integrity 39 | echo. doctest to run all doctests embedded in the documentation if enabled 40 | goto end 41 | ) 42 | 43 | if "%1" == "clean" ( 44 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 45 | del /q /s %BUILDDIR%\* 46 | goto end 47 | ) 48 | 49 | 50 | %SPHINXBUILD% 2> nul 51 | if errorlevel 9009 ( 52 | echo. 53 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 54 | echo.installed, then set the SPHINXBUILD environment variable to point 55 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 56 | echo.may add the Sphinx directory to PATH. 57 | echo. 58 | echo.If you don't have Sphinx installed, grab it from 59 | echo.http://sphinx-doc.org/ 60 | exit /b 1 61 | ) 62 | 63 | if "%1" == "html" ( 64 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 68 | goto end 69 | ) 70 | 71 | if "%1" == "dirhtml" ( 72 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 76 | goto end 77 | ) 78 | 79 | if "%1" == "singlehtml" ( 80 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 84 | goto end 85 | ) 86 | 87 | if "%1" == "pickle" ( 88 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can process the pickle files. 92 | goto end 93 | ) 94 | 95 | if "%1" == "json" ( 96 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 97 | if errorlevel 1 exit /b 1 98 | echo. 99 | echo.Build finished; now you can process the JSON files. 100 | goto end 101 | ) 102 | 103 | if "%1" == "htmlhelp" ( 104 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 105 | if errorlevel 1 exit /b 1 106 | echo. 107 | echo.Build finished; now you can run HTML Help Workshop with the ^ 108 | .hhp project file in %BUILDDIR%/htmlhelp. 109 | goto end 110 | ) 111 | 112 | if "%1" == "qthelp" ( 113 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 114 | if errorlevel 1 exit /b 1 115 | echo. 116 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 117 | .qhcp project file in %BUILDDIR%/qthelp, like this: 118 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\python_humble_utils.qhcp 119 | echo.To view the help file: 120 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\python_humble_utils.ghc 121 | goto end 122 | ) 123 | 124 | if "%1" == "devhelp" ( 125 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished. 129 | goto end 130 | ) 131 | 132 | if "%1" == "epub" ( 133 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 137 | goto end 138 | ) 139 | 140 | if "%1" == "latex" ( 141 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 145 | goto end 146 | ) 147 | 148 | if "%1" == "latexpdf" ( 149 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 150 | cd %BUILDDIR%/latex 151 | make all-pdf 152 | cd %BUILDDIR%/.. 153 | echo. 154 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 155 | goto end 156 | ) 157 | 158 | if "%1" == "latexpdfja" ( 159 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 160 | cd %BUILDDIR%/latex 161 | make all-pdf-ja 162 | cd %BUILDDIR%/.. 163 | echo. 164 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 165 | goto end 166 | ) 167 | 168 | if "%1" == "text" ( 169 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 170 | if errorlevel 1 exit /b 1 171 | echo. 172 | echo.Build finished. The text files are in %BUILDDIR%/text. 173 | goto end 174 | ) 175 | 176 | if "%1" == "man" ( 177 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 178 | if errorlevel 1 exit /b 1 179 | echo. 180 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 181 | goto end 182 | ) 183 | 184 | if "%1" == "texinfo" ( 185 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 186 | if errorlevel 1 exit /b 1 187 | echo. 188 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 189 | goto end 190 | ) 191 | 192 | if "%1" == "gettext" ( 193 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 194 | if errorlevel 1 exit /b 1 195 | echo. 196 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 197 | goto end 198 | ) 199 | 200 | if "%1" == "changes" ( 201 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 202 | if errorlevel 1 exit /b 1 203 | echo. 204 | echo.The overview file is in %BUILDDIR%/changes. 205 | goto end 206 | ) 207 | 208 | if "%1" == "linkcheck" ( 209 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 210 | if errorlevel 1 exit /b 1 211 | echo. 212 | echo.Link check complete; look for any errors in the above output ^ 213 | or in %BUILDDIR%/linkcheck/output.txt. 214 | goto end 215 | ) 216 | 217 | if "%1" == "doctest" ( 218 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 219 | if errorlevel 1 exit /b 1 220 | echo. 221 | echo.Testing of doctests in the sources finished, look at the ^ 222 | results in %BUILDDIR%/doctest/output.txt. 223 | goto end 224 | ) 225 | 226 | if "%1" == "xml" ( 227 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 228 | if errorlevel 1 exit /b 1 229 | echo. 230 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 231 | goto end 232 | ) 233 | 234 | if "%1" == "pseudoxml" ( 235 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 236 | if errorlevel 1 exit /b 1 237 | echo. 238 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 239 | goto end 240 | ) 241 | 242 | :end 243 | -------------------------------------------------------------------------------- /docs/modules.rst: -------------------------------------------------------------------------------- 1 | python_humble_utils 2 | =================== 3 | 4 | .. toctree:: 5 | :maxdepth: 4 6 | 7 | python_humble_utils 8 | -------------------------------------------------------------------------------- /docs/project-makefile.rst: -------------------------------------------------------------------------------- 1 | .. highlight:: shell 2 | 3 | .. _project-makefile: 4 | 5 | Project Makefile 6 | ================ 7 | 8 | .. include:: ./includes/execution_context_notice.rst 9 | 10 | To facilitate smooth development workflow, we provide a ``Makefile`` 11 | defining a number of convenience commands. 12 | 13 | * ``clean`` running 14 | 15 | #. ``clean-build`` (build artifact removal); 16 | 17 | #. ``clean-pyc`` (compilation artifact removal); 18 | 19 | #. ``clean-test`` (test and coverage artifact removal). 20 | 21 | Specifically:: 22 | 23 | $ make clean 24 | $ make clean-build 25 | $ make clean-pyc 26 | $ make clean-test 27 | 28 | 29 | * ``lint`` checking codebase compliance with `PEP8`_ via `flake8`_:: 30 | 31 | $ make lint 32 | 33 | * ``test`` running `py.test`_:: 34 | 35 | $ make test 36 | 37 | * ``test-all`` running `tox`_:: 38 | 39 | $ make test-all 40 | 41 | * ``coverage`` running `coverage`_:: 42 | 43 | $ make coverage 44 | 45 | * ``docs`` generating project docs via `Sphinx`_:: 46 | 47 | $ make docs 48 | 49 | * ``servedocs`` serving docs live via `watchdog`_:: 50 | 51 | $ make servedocs 52 | 53 | * ``setup-release`` packaging and releasing the project to PyPI:: 54 | 55 | $ make setup-release 56 | 57 | * ``setup-dist`` builds source and wheel packages via `setuptools`_:: 58 | 59 | $ make setup-dist 60 | 61 | * ``setup-install`` installing the package to the current environment:: 62 | 63 | $ make setup-install 64 | 65 | * ``install`` keeping local environment dependencies in sync with those defined in ``./requirements*.txt``:: 66 | 67 | $ make install 68 | 69 | 70 | .. _`PEP8`: https://www.python.org/dev/peps/pep-0008/ 71 | .. _`flake8`: http://flake8.pycqa.org/en/stable/ 72 | .. _`py.test`: https://docs.pytest.org/en/stable/ 73 | .. _`tox`: https://tox.readthedocs.io/en/stable/ 74 | .. _`coverage`: https://coverage.readthedocs.io/en/stable/ 75 | .. _`Sphinx`: http://www.sphinx-doc.org/en/stable/ 76 | .. _`watchdog`: https://github.com/gorakhargosh/watchdog 77 | .. _`setuptools`: https://setuptools.readthedocs.io/en/stable/ 78 | -------------------------------------------------------------------------------- /docs/python_humble_utils.rst: -------------------------------------------------------------------------------- 1 | python\_humble\_utils package 2 | ============================= 3 | 4 | Subpackages 5 | ----------- 6 | 7 | .. toctree:: 8 | 9 | python_humble_utils.vendor 10 | 11 | Submodules 12 | ---------- 13 | 14 | python\_humble\_utils.classes module 15 | ------------------------------------ 16 | 17 | .. automodule:: python_humble_utils.classes 18 | :members: 19 | :undoc-members: 20 | :show-inheritance: 21 | 22 | python\_humble\_utils.filesystem module 23 | --------------------------------------- 24 | 25 | .. automodule:: python_humble_utils.filesystem 26 | :members: 27 | :undoc-members: 28 | :show-inheritance: 29 | 30 | python\_humble\_utils.objects module 31 | ------------------------------------ 32 | 33 | .. automodule:: python_humble_utils.objects 34 | :members: 35 | :undoc-members: 36 | :show-inheritance: 37 | 38 | python\_humble\_utils.strings module 39 | ------------------------------------ 40 | 41 | .. automodule:: python_humble_utils.strings 42 | :members: 43 | :undoc-members: 44 | :show-inheritance: 45 | 46 | 47 | Module contents 48 | --------------- 49 | 50 | .. automodule:: python_humble_utils 51 | :members: 52 | :undoc-members: 53 | :show-inheritance: 54 | -------------------------------------------------------------------------------- /docs/python_humble_utils.vendor.rst: -------------------------------------------------------------------------------- 1 | python\_humble\_utils.vendor package 2 | ==================================== 3 | 4 | Submodules 5 | ---------- 6 | 7 | python\_humble\_utils.vendor.pytest module 8 | ------------------------------------------ 9 | 10 | .. automodule:: python_humble_utils.vendor.pytest 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | 16 | Module contents 17 | --------------- 18 | 19 | .. automodule:: python_humble_utils.vendor 20 | :members: 21 | :undoc-members: 22 | :show-inheritance: 23 | -------------------------------------------------------------------------------- /docs/readme.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../README.rst 2 | -------------------------------------------------------------------------------- /docs/usage.rst: -------------------------------------------------------------------------------- 1 | Usage 2 | ===== 3 | 4 | .. code-block:: python 5 | 6 | import os 7 | from pathlib import Path 8 | 9 | from python_humble_utils.filesystem import yield_file_paths 10 | from python_humble_utils.strings import camel_or_pascal_case_to_snake_case 11 | 12 | 13 | # ... 14 | 15 | file_paths = yield_file_paths( 16 | dir_path=Path("dir") / "with" / "scripts", 17 | allowed_file_extensions=(".sh", ".bash"), 18 | recursively=True 19 | ) 20 | assert set(file_paths) == set(("s1.sh", "s2.bash", "s3.bash")) 21 | 22 | s = camel_or_pascal_case_to_snake_case("camelCasedString") 23 | assert s == "camel_cased_string" 24 | 25 | s = camel_or_pascal_case_to_snake_case("PascalCasedString") 26 | assert s == "pascal_cased_string" 27 | 28 | # ... 29 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.black] 2 | line-length = 100 # 100 fits precisely on FullHD screen, with file structure pane open to the left at all times 3 | -------------------------------------------------------------------------------- /python_humble_utils/__init__.py: -------------------------------------------------------------------------------- 1 | __author__ = """Nikita P. Shupeyko""" 2 | __email__ = "webyneter@gmail.com" 3 | __version__ = "3.1.0" 4 | -------------------------------------------------------------------------------- /python_humble_utils/classes.py: -------------------------------------------------------------------------------- 1 | from typing import Collection, Type 2 | 3 | 4 | def get_all_subclasses(cls: Type, including_self: bool = False) -> Collection[Type]: 5 | """Get all subclasses. 6 | 7 | :param cls: class to lookup subclasses of. 8 | :param including_self: whether or not the the :param cls: itself is to be accounted for. 9 | :return: :param cls: subclasses. 10 | """ 11 | all_subclasses = [cls] if including_self else [] 12 | for c in cls.__subclasses__(): 13 | all_subclasses += get_all_subclasses(c, True) 14 | return all_subclasses 15 | -------------------------------------------------------------------------------- /python_humble_utils/filesystem.py: -------------------------------------------------------------------------------- 1 | import os 2 | from pathlib import Path 3 | from typing import Iterable, Optional, Callable, Collection 4 | from uuid import uuid4 5 | 6 | 7 | def generate_random_dir_path( 8 | root_dir_path: Optional[Path] = None, 9 | subdir_count: int = 0, 10 | random_string_generator: Optional[Callable[[], str]] = None, 11 | ) -> Path: 12 | """Generate a random directory path. 13 | 14 | :param root_dir_path: root dir path; by default, the current dir path is used 15 | :param subdir_count: a number of subdirectories to generate in the directory root. 16 | :param random_string_generator: random number generator; by default, the UUID4 hex is used 17 | :return: directory root path. 18 | """ 19 | root_dir_path = root_dir_path or Path() 20 | random_string_generator = random_string_generator or (lambda: uuid4().hex) 21 | 22 | path = root_dir_path or Path() 23 | for __ in range(1 + subdir_count): 24 | path /= random_string_generator() 25 | return path 26 | 27 | 28 | def read_file(file_path: str, as_single_line: bool = False) -> str: 29 | """Read file content. 30 | 31 | :param file_path: path to the file. 32 | :param as_single_line: whether or not the file is to be read as a single line. 33 | :return: file content. 34 | """ 35 | with open(file_path, "r") as file: 36 | lines = [] 37 | for line in file.readlines(): 38 | if as_single_line: 39 | line = line.replace(os.linesep, "") 40 | lines.append(line) 41 | return "".join(lines) 42 | 43 | 44 | def yield_file_paths( 45 | dir_path: Path, allowed_file_extensions: Collection[str], recursively: bool = False 46 | ) -> Iterable[Path]: 47 | """Yield file paths. 48 | 49 | :param dir_path: path to the containing directory. 50 | :param allowed_file_extensions: file extensions to match against e.g. `['.abc', '.def']`. 51 | :param recursively: whether or not the directory is to be recursively traversed. 52 | :return: file paths. 53 | """ 54 | 55 | def filter_allowed_file_paths( 56 | dp: Path, fbns: Collection[str], afes: Collection[str] 57 | ) -> Iterable[Path]: 58 | for fbn in fbns: 59 | p = dp / Path(fbn) 60 | if p.suffix in afes: 61 | yield p 62 | 63 | if recursively: 64 | for root_dir_path, _, file_basenames in os.walk(dir_path): 65 | yield from filter_allowed_file_paths(dir_path, file_basenames, allowed_file_extensions) 66 | else: 67 | file_basenames = os.listdir(dir_path) 68 | yield from filter_allowed_file_paths(dir_path, file_basenames, allowed_file_extensions) 69 | 70 | 71 | def create_or_update_file( 72 | file_path: str, file_content: str = "", file_content_encoding: str = "utf-8" 73 | ) -> None: 74 | """Create or update file. 75 | 76 | :param file_path: path to the file. 77 | :param file_content: file content. 78 | :param file_content_encoding: file content encoding e.g. `latin-1`. 79 | """ 80 | with open(file_path, "wb+") as file: 81 | file.write(file_content.encode(file_content_encoding)) 82 | -------------------------------------------------------------------------------- /python_humble_utils/objects.py: -------------------------------------------------------------------------------- 1 | import gc 2 | from typing import TypeVar, Any, Optional, Callable, Iterable, Type, Sequence 3 | 4 | T = TypeVar("T") 5 | M = TypeVar("M") 6 | 7 | 8 | def flatten( 9 | obj: Any, flatten_dicts_by_values: bool = True, coerce: Optional[Callable[[T], M]] = None 10 | ) -> Iterable[M]: 11 | """Flatten an arbitrarily complex object. 12 | 13 | :param obj: an obj to flatten. 14 | :param flatten_dicts_by_values: if True, mapping will be flattened by values, otherwise by keys. 15 | :param coerce: a callable used to coerce items of the resulting iterable to 16 | :return: a recursively-constructed iterable of the object's constituents. 17 | """ 18 | if isinstance(obj, dict): 19 | if flatten_dicts_by_values: 20 | items = obj.values() 21 | else: 22 | items = obj.keys() 23 | items = list(items) 24 | yield from flatten(items, flatten_dicts_by_values=flatten_dicts_by_values, coerce=coerce) 25 | elif isinstance(obj, list): 26 | for item in obj: 27 | yield from flatten(item, flatten_dicts_by_values=flatten_dicts_by_values, coerce=coerce) 28 | else: 29 | if coerce is not None: 30 | yield coerce(obj) 31 | else: 32 | yield obj 33 | 34 | 35 | def get_all_instances(cls: Type[T]) -> Sequence[T]: 36 | """Get all class instances. 37 | 38 | :type cls: class whose instances need to be looked up. 39 | """ 40 | all_instances = [] 41 | 42 | all_objects = gc.get_objects() 43 | for obj in all_objects: 44 | if isinstance(obj, cls): 45 | all_instances.append(obj) 46 | 47 | return all_instances 48 | -------------------------------------------------------------------------------- /python_humble_utils/strings.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | def camel_or_pascal_case_to_snake_case(s: str) -> str: 5 | """Convert `camelCased` or `PascalCased` string to `snake_case`. 6 | 7 | Based on https://stackoverflow.com/a/1176023/1557013. 8 | 9 | :param s: string in `camelCase` or `PascalCase`. 10 | :return: string in `snake_case`. 11 | """ 12 | snake_case = re.sub("([a-z0-9])([A-Z])", r"\1_\2", re.sub("(.)([A-Z][a-z]+)", r"\1_\2", s)) 13 | snake_case = snake_case.lower() 14 | return snake_case 15 | 16 | 17 | def camel_or_pascal_case_to_space_delimited(s: str) -> str: 18 | """Convert `camelCased` or `PascalCased` string to space-delimited. 19 | 20 | Based on https://stackoverflow.com/a/9283563/1557013. 21 | 22 | :param s: string in `camelCase` or `PascalCase`. 23 | :return: space-delimited string. 24 | """ 25 | space_delimited = re.sub(r"((?<=[a-z])[A-Z]|(? Path: 9 | """Generate file path relative to a temporary directory. 10 | 11 | :param tmpdir_factory: py.test's `tmpdir_factory` fixture. 12 | :param file_name_with_extension: file name with extension e.g. `file_name.ext`. 13 | :param tmp_dir_path: path to directory (relative to the temporary one created by `tmpdir_factory`) where the generated file path should reside. # noqa 14 | :return: file path. 15 | """ 16 | basetemp = tmpdir_factory.getbasetemp() 17 | 18 | if tmp_dir_path is not None: 19 | if os.path.isabs(tmp_dir_path): 20 | raise ValueError("tmp_dir_path is not a relative path!") 21 | # http://stackoverflow.com/a/16595356/1557013 22 | for tmp_file_dir_path_part in os.path.normpath(tmp_dir_path).split(os.sep): 23 | # Accounting for possible path separator at the end. 24 | if tmp_file_dir_path_part: 25 | tmpdir_factory.mktemp(tmp_file_dir_path_part) 26 | return Path(basetemp) / tmp_dir_path / file_name_with_extension 27 | return Path(basetemp.join(file_name_with_extension)) 28 | -------------------------------------------------------------------------------- /requirements.code-style.txt: -------------------------------------------------------------------------------- 1 | black==19.10b0 2 | flake8==3.7.9 3 | -------------------------------------------------------------------------------- /requirements.coverage.txt: -------------------------------------------------------------------------------- 1 | coverage==5.0.4 2 | codecov==2.0.15 3 | -------------------------------------------------------------------------------- /requirements.docs.txt: -------------------------------------------------------------------------------- 1 | Sphinx==2.4.4 2 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | wheel==0.34.2 2 | ipython==7.12.0 3 | bumpversion==0.5.3 4 | watchdog==0.10.2 5 | PyYAML==5.4 6 | cryptography==3.3.2 7 | 8 | # Testing 9 | tox==3.14.5 10 | pytest==5.3.5 11 | pytest-runner==5.2 12 | pytest-cov==2.8.1 13 | pytest-mock==2.0.0 14 | hypothesis==5.7.2 15 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_wheel] 2 | universal = 1 3 | 4 | [flake8] 5 | exclude = docs 6 | max-line-length = 120 7 | 8 | [aliases] 9 | test = pytest 10 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from setuptools import setup, find_packages 4 | 5 | with open("README.rst") as readme_file: 6 | readme = readme_file.read() 7 | 8 | with open("HISTORY.rst") as history_file: 9 | history = history_file.read() 10 | 11 | setup_requirements = ["pytest-runner"] 12 | 13 | setup( 14 | name="python-humble-utils", 15 | version="3.1.0", 16 | url="https://github.com/webyneter/python-humble-utils", 17 | description="Python utils for everyday use.", 18 | long_description=readme + "\n\n" + history, 19 | author="Nikita P. Shupeyko", 20 | author_email="webyneter@gmail.com", 21 | packages=find_packages(include=["python_humble_utils"]), 22 | include_package_data=True, 23 | setup_requires=setup_requirements, 24 | zip_safe=False, 25 | license="MIT", 26 | classifiers=[ 27 | "Development Status :: 5 - Production/Stable", 28 | "Intended Audience :: Developers", 29 | "License :: OSI Approved :: MIT License", 30 | "Natural Language :: English", 31 | "Programming Language :: Python :: 3", 32 | "Programming Language :: Python :: 3.6", 33 | "Programming Language :: Python :: 3.7", 34 | "Programming Language :: Python :: 3.8", 35 | ], 36 | keywords=["python", "humble", "utility", "utilities", "util", "utils", "helper", "helpers"], 37 | ) 38 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/webyneter/python-humble-utils/38043f248ba1cbca0116e00c08390775d784cc79/tests/__init__.py -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | import os 2 | from pathlib import Path 3 | 4 | from pytest import fixture 5 | 6 | 7 | class FileMeta: 8 | """A container for file meta.""" 9 | 10 | def __init__( 11 | self, 12 | dir_path: str, 13 | name: str, 14 | extension: str, 15 | name_with_extension: str, 16 | path: str, 17 | content: str, 18 | content_encoding: str, 19 | ): 20 | super().__init__() 21 | self.dir_path = dir_path 22 | self.name = name 23 | self.extension = extension 24 | self.name_with_extension = name_with_extension 25 | self.path = path 26 | self.content = content 27 | self.content_encoding = content_encoding 28 | 29 | 30 | class Foo: 31 | class InsideFoo: 32 | pass 33 | 34 | 35 | class BooFoo(Foo): 36 | pass 37 | 38 | 39 | class MooBooFoo(BooFoo): 40 | pass 41 | 42 | 43 | @fixture 44 | def file_meta() -> FileMeta: 45 | dir_path = Path("path") / "to" / "dir" / "with" 46 | file_content = os.linesep.join(["Behold,", "this", "is", "multiline", "content!"]) 47 | file_content_encoding = "utf-8" 48 | file_name = "name" 49 | file_extension = ".ext" 50 | file_name_with_extension = file_name + file_extension 51 | file_path = dir_path / file_name_with_extension 52 | return FileMeta( 53 | dir_path=dir_path, 54 | name=file_name, 55 | extension=file_extension, 56 | name_with_extension=file_name_with_extension, 57 | path=file_path, 58 | content=file_content, 59 | content_encoding=file_content_encoding, 60 | ) 61 | -------------------------------------------------------------------------------- /tests/test_classes.py: -------------------------------------------------------------------------------- 1 | from python_humble_utils.classes import get_all_subclasses 2 | from tests.conftest import Foo, BooFoo, MooBooFoo 3 | 4 | 5 | def test_no_subclasses_given__get_all_subclasses_succeeds(): 6 | assert set(get_all_subclasses(MooBooFoo, False)) == set() 7 | assert set(get_all_subclasses(MooBooFoo, True)) == {MooBooFoo} 8 | 9 | 10 | def test_self_included__get_all_subclasses_succeeds(): 11 | assert set(get_all_subclasses(Foo, True)) == {Foo, BooFoo, MooBooFoo} 12 | 13 | 14 | def test_self_excluded__get_all_subclasses_succeeds(): 15 | assert set(get_all_subclasses(Foo, False)) == {BooFoo, MooBooFoo} 16 | -------------------------------------------------------------------------------- /tests/test_filesystem.py: -------------------------------------------------------------------------------- 1 | import os 2 | from pathlib import Path 3 | from typing import Optional, Callable, Sequence 4 | 5 | import pytest 6 | from hypothesis import given 7 | from hypothesis._strategies import one_of, none, sampled_from, integers 8 | 9 | from python_humble_utils.filesystem import ( 10 | generate_random_dir_path, 11 | create_or_update_file, 12 | read_file, 13 | yield_file_paths, 14 | ) 15 | from python_humble_utils.vendor.pytest import generate_tmp_file_path 16 | from tests.conftest import FileMeta 17 | 18 | 19 | @given( 20 | root_dir_path=one_of(none(), sampled_from((Path(".."), Path("..") / Path("test")))), 21 | subdir_count=integers(min_value=0, max_value=2), 22 | ) 23 | def test_generate_random_dir_path(root_dir_path: Optional[Path], subdir_count: int): 24 | path = generate_random_dir_path(root_dir_path=root_dir_path, subdir_count=subdir_count) 25 | assert len(path.parts) == (len(root_dir_path.parts) if root_dir_path else 0) + 1 + subdir_count 26 | 27 | subdir_names = [str(i ** 2) for i in range(1 + subdir_count)] 28 | subdir_names_iter = iter(subdir_names) 29 | path = generate_random_dir_path( 30 | root_dir_path=root_dir_path, 31 | subdir_count=subdir_count, 32 | random_string_generator=lambda: next(subdir_names_iter), 33 | ) 34 | assert len(path.parts) == (len(root_dir_path.parts) if root_dir_path else 0) + 1 + subdir_count 35 | assert path.parts[len(path.parts) - (1 + subdir_count) :] == tuple(subdir_names) 36 | 37 | 38 | @pytest.mark.parametrize( 39 | "as_single_line,verifier", 40 | [ 41 | (True, lambda file_content: os.linesep not in file_content), 42 | (False, lambda file_content: os.linesep in file_content), 43 | ], 44 | ) 45 | def test_read_file( 46 | tmpdir_factory, file_meta: FileMeta, as_single_line: bool, verifier: Callable[[str], bool] 47 | ): 48 | tmp_file_path = generate_tmp_file_path(tmpdir_factory, file_meta.name_with_extension) 49 | create_or_update_file(tmp_file_path, file_meta.content, file_meta.content_encoding) 50 | 51 | file_content = read_file(tmp_file_path, as_single_line) 52 | 53 | assert verifier(file_content) 54 | 55 | 56 | @pytest.mark.parametrize( 57 | "allowed_file_extensions,max_subdir_count", 58 | [ 59 | ([], 0), 60 | ([".a"], 0), 61 | ([".a", ".b"], 0), 62 | ([], 1), 63 | ([], 2), 64 | ([".a"], 1), 65 | ([".a"], 2), 66 | ([".a", ".b"], 1), 67 | ([".a", ".b"], 2), 68 | ], 69 | ) 70 | def test_yield_file_paths( 71 | tmpdir_factory, allowed_file_extensions: Sequence[str], max_subdir_count: int 72 | ): 73 | recursively = max_subdir_count > 0 74 | 75 | for subdir_count in range(max_subdir_count + 1): 76 | dir_path = Path(tmpdir_factory.getbasetemp()) / generate_random_dir_path( 77 | subdir_count=subdir_count 78 | ) 79 | 80 | # Generate paths to files... 81 | # ...with a disallowed extension: 82 | file_extension_suffix = "z" 83 | if len(allowed_file_extensions) > 0: 84 | disallowed_file_extension = allowed_file_extensions[-1] + file_extension_suffix 85 | else: 86 | disallowed_file_extension = f".{file_extension_suffix}" 87 | disallowed_file_path = dir_path / Path(f"file{disallowed_file_extension}") 88 | # ...with allowed extensions: 89 | allowed_file_names_with_extension = [f"file{e}" for e in allowed_file_extensions] 90 | allowed_file_paths = [dir_path / Path(fne) for fne in allowed_file_names_with_extension] 91 | 92 | # Create files in respective dirs: 93 | os.makedirs(dir_path, exist_ok=True) 94 | open(disallowed_file_path, "w+").close() 95 | for p in allowed_file_paths: 96 | open(p, "w+").close() 97 | 98 | # Assert: 99 | assert set(yield_file_paths(dir_path, allowed_file_extensions, recursively)) == set( 100 | allowed_file_paths 101 | ) 102 | 103 | 104 | def test_file_not_exists__create_or_update_file_creates_file(tmpdir_factory, file_meta: FileMeta): 105 | tmp_dir_path = tmpdir_factory.getbasetemp() / file_meta.dir_path 106 | tmp_file_path = tmp_dir_path / file_meta.name_with_extension 107 | os.makedirs(tmp_dir_path, exist_ok=True) 108 | 109 | create_or_update_file(tmp_file_path, file_meta.content, file_meta.content_encoding) 110 | 111 | with open(tmp_file_path, "rb") as file: 112 | assert file.read().decode(file_meta.content_encoding) == file_meta.content 113 | 114 | 115 | def test_file_exists__create_or_update_file_updates_file(tmpdir_factory, file_meta: FileMeta): 116 | tmp_dir_path = tmpdir_factory.getbasetemp() / file_meta.dir_path 117 | tmp_file_path = tmp_dir_path / file_meta.name_with_extension 118 | 119 | os.makedirs(tmp_dir_path, exist_ok=True) 120 | with open(tmp_file_path, "wb") as file: 121 | file.write(file_meta.content.encode(file_meta.content_encoding)) 122 | 123 | updated_file_content = file_meta.content + " (+ this update)" 124 | create_or_update_file(tmp_file_path, updated_file_content, file_meta.content_encoding) 125 | 126 | with open(tmp_file_path, "rb") as file: 127 | assert file.read().decode(file_meta.content_encoding) == updated_file_content 128 | -------------------------------------------------------------------------------- /tests/test_objects.py: -------------------------------------------------------------------------------- 1 | import gc 2 | from typing import Optional, Callable, TypeVar 3 | 4 | import pytest 5 | 6 | from python_humble_utils.objects import flatten, get_all_instances 7 | from tests.conftest import BooFoo, Foo, MooBooFoo 8 | 9 | T = TypeVar("T") 10 | M = TypeVar("M") 11 | 12 | 13 | @pytest.mark.parametrize("flatten_dicts_by_values", [False, True]) 14 | @pytest.mark.parametrize("coerce", [None, str]) 15 | def test_flatten(flatten_dicts_by_values: bool, coerce: Optional[Callable[[T], M]]): 16 | obj = [ 17 | "something", 18 | 1, 19 | [2, bytes(range(3))], 20 | 4, 21 | ["5", {"6": 7, 7: [8], "9": [10, "11", 12, ["13", "14", 15]]}], 22 | ] 23 | 24 | flattened_obj = list( 25 | flatten(obj, flatten_dicts_by_values=flatten_dicts_by_values, coerce=coerce) 26 | ) 27 | 28 | if flatten_dicts_by_values: 29 | expected = ["something", 1, 2, bytes(range(3)), 4, "5", 7, 8, 10, "11", 12, "13", "14", 15] 30 | else: 31 | expected = ["something", 1, 2, bytes(range(3)), 4, "5", "6", 7, "9"] 32 | if coerce is not None: 33 | expected = [coerce(e) for e in expected] 34 | assert flattened_obj == expected 35 | 36 | 37 | @pytest.mark.parametrize("num_instances", range(3)) 38 | @pytest.mark.parametrize("num_spoiler_instances", range(3)) 39 | def test_get_all_instances(num_instances: int, num_spoiler_instances: int): 40 | expected_foo_instances = [Foo() for __ in range(num_instances)] 41 | for i in range(num_spoiler_instances): 42 | if i % 2 == 0: 43 | BooFoo() 44 | else: 45 | MooBooFoo() 46 | 47 | actual_foo_instances = get_all_instances(Foo) 48 | 49 | assert len(actual_foo_instances) == num_instances 50 | assert all(fi in expected_foo_instances for fi in actual_foo_instances) 51 | gc.collect() 52 | -------------------------------------------------------------------------------- /tests/test_strings.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from python_humble_utils.strings import ( 4 | camel_or_pascal_case_to_snake_case, 5 | camel_or_pascal_case_to_space_delimited, 6 | ) 7 | 8 | 9 | @pytest.mark.parametrize( 10 | "s,expected", 11 | [ 12 | ( 13 | "IAmInCamelCase_but_i_am_not_AndHereAmIOnceAgain", 14 | "i_am_in_camel_case_but_i_am_not__and_here_am_i_once_again", 15 | ), 16 | ( 17 | "iAmInPascalCase_but_i_am_not_andHereAmIOnceAgain", 18 | "i_am_in_pascal_case_but_i_am_not_and_here_am_i_once_again", 19 | ), 20 | ], 21 | ) 22 | def test_convert_camel_or_pascal_case_to_snake_case(s: str, expected: str): 23 | assert camel_or_pascal_case_to_snake_case(s) == expected 24 | 25 | 26 | @pytest.mark.parametrize( 27 | "s,expected", 28 | [ 29 | ("iAmASTRANGECamelCase", "i Am ASTRANGE Camel Case"), 30 | ( 31 | "YetAnotherOneBUTNOWWhilebeingastrangeOneIamStillAProperPascalCase", 32 | "Yet Another One BUTNOW Whilebeingastrange One Iam Still A Proper Pascal Case", 33 | ), 34 | ], 35 | ) 36 | def test_convert_camel_or_pascal_case_to_space_delimited(s: str, expected: str): 37 | assert camel_or_pascal_case_to_space_delimited(s) == expected 38 | -------------------------------------------------------------------------------- /tests/vendor/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/webyneter/python-humble-utils/38043f248ba1cbca0116e00c08390775d784cc79/tests/vendor/__init__.py -------------------------------------------------------------------------------- /tests/vendor/test_pytest.py: -------------------------------------------------------------------------------- 1 | from pytest import raises 2 | 3 | from python_humble_utils.vendor.pytest import generate_tmp_file_path 4 | from tests.conftest import FileMeta 5 | 6 | 7 | def test_relative_tmp_dir_path_given__generate_tmp_file_path_succeeds( 8 | tmpdir_factory, file_meta: FileMeta 9 | ): 10 | assert ( 11 | generate_tmp_file_path( 12 | tmpdir_factory, file_meta.name_with_extension, tmp_dir_path=file_meta.dir_path 13 | ) 14 | == tmpdir_factory.getbasetemp() / file_meta.dir_path / file_meta.name_with_extension 15 | ) 16 | 17 | 18 | def test_absolute_tmp_dir_path_given__generate_tmp_file_path_succeeds( 19 | tmpdir_factory, file_meta: FileMeta 20 | ): 21 | with raises(ValueError): 22 | generate_tmp_file_path( 23 | tmpdir_factory, 24 | file_meta.name_with_extension, 25 | tmp_dir_path=(tmpdir_factory.getbasetemp() / file_meta.dir_path), 26 | ) 27 | 28 | 29 | def test_no_tmp_dir_path_given__generate_tmp_file_path_succeeds( 30 | tmpdir_factory, file_meta: FileMeta 31 | ): 32 | assert ( 33 | generate_tmp_file_path(tmpdir_factory, file_meta.name_with_extension) 34 | == tmpdir_factory.getbasetemp() / file_meta.name_with_extension 35 | ) 36 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = flake8, py36, py37, py38 3 | 4 | [travis] 5 | python = 6 | 3.6: py36 7 | 3.7: py37 8 | 3.8: py38 9 | 10 | [testenv] 11 | setenv = 12 | PYTHONPATH = {toxinidir} 13 | deps = 14 | -r{toxinidir}/requirements.txt 15 | commands = 16 | py.test --basetemp={envtmpdir} 17 | 18 | [testenv:flake8] 19 | commands = 20 | flake8 python_humble_utils 21 | 22 | [testenv:codecov] 23 | passenv = 24 | CI TRAVIS TRAVIS_* 25 | commands = 26 | py.test --basetemp={envtmpdir} --cov={toxinidir}/python_humble_utils 27 | codecov 28 | -------------------------------------------------------------------------------- /travis_pypi_setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """Update encrypted deploy password in Travis config file.""" 4 | 5 | from __future__ import print_function 6 | 7 | import base64 8 | import json 9 | import os 10 | from getpass import getpass 11 | 12 | import yaml 13 | from cryptography.hazmat.backends import default_backend 14 | from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 15 | from cryptography.hazmat.primitives.serialization import load_pem_public_key 16 | 17 | try: 18 | from urllib import urlopen 19 | except ImportError: 20 | from urllib.request import urlopen 21 | 22 | GITHUB_REPO = "webyneter/python-humble-utils" 23 | TRAVIS_CONFIG_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".travis.yml") 24 | 25 | 26 | def load_key(pubkey): 27 | """Load public RSA key. 28 | 29 | Work around keys with incorrect header/footer format. 30 | 31 | Read more about RSA encryption with cryptography: 32 | https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/ 33 | """ 34 | try: 35 | return load_pem_public_key(pubkey.encode(), default_backend()) 36 | except ValueError: 37 | # workaround for https://github.com/travis-ci/travis-api/issues/196 38 | pubkey = pubkey.replace("BEGIN RSA", "BEGIN").replace("END RSA", "END") 39 | return load_pem_public_key(pubkey.encode(), default_backend()) 40 | 41 | 42 | def encrypt(pubkey, password): 43 | """Encrypt password using given RSA public key and encode it with base64. 44 | 45 | The encrypted password can only be decrypted by someone with the 46 | private key (in this case, only Travis). 47 | """ 48 | key = load_key(pubkey) 49 | encrypted_password = key.encrypt(password, PKCS1v15()) 50 | return base64.b64encode(encrypted_password) 51 | 52 | 53 | def fetch_public_key(repo): 54 | """Download RSA public key Travis will use for this repo. 55 | 56 | Travis API docs: http://docs.travis-ci.com/api/#repository-keys 57 | """ 58 | keyurl = "https://api.travis-ci.org/repos/{0}/key".format(repo) 59 | data = json.loads(urlopen(keyurl).read().decode()) 60 | if "key" not in data: 61 | errmsg = "Could not find public key for repo: {}.\n".format(repo) 62 | errmsg += "Have you already added your GitHub repo to Travis?" 63 | raise ValueError(errmsg) 64 | return data["key"] 65 | 66 | 67 | def prepend_line(filepath, line): 68 | """Rewrite a file adding a line to its beginning.""" 69 | with open(filepath) as f: 70 | lines = f.readlines() 71 | 72 | lines.insert(0, line) 73 | 74 | with open(filepath, "w") as f: 75 | f.writelines(lines) 76 | 77 | 78 | def load_yaml_config(filepath): 79 | """Load yaml config file at the given path.""" 80 | with open(filepath) as f: 81 | return yaml.load(f) 82 | 83 | 84 | def save_yaml_config(filepath, config): 85 | """Save yaml config file at the given path.""" 86 | with open(filepath, "w") as f: 87 | yaml.dump(config, f, default_flow_style=False) 88 | 89 | 90 | def update_travis_deploy_password(encrypted_password): 91 | """Put `encrypted_password` into the deploy section of .travis.yml.""" 92 | config = load_yaml_config(TRAVIS_CONFIG_FILE) 93 | 94 | config["deploy"]["password"] = dict(secure=encrypted_password) 95 | 96 | save_yaml_config(TRAVIS_CONFIG_FILE, config) 97 | 98 | line = ( 99 | "# This file was autogenerated and will overwrite" 100 | " each time you run travis_pypi_setup.py\n" 101 | ) 102 | prepend_line(TRAVIS_CONFIG_FILE, line) 103 | 104 | 105 | def main(args): 106 | """Add a PyPI password to .travis.yml so that Travis can deploy to PyPI. 107 | 108 | Fetch the Travis public key for the repo, and encrypt the PyPI password 109 | with it before adding, so that only Travis can decrypt and use the PyPI 110 | password. 111 | """ 112 | public_key = fetch_public_key(args.repo) 113 | password = args.password or getpass("PyPI password: ") 114 | update_travis_deploy_password(encrypt(public_key, password.encode())) 115 | print("Wrote encrypted password to .travis.yml -- you're ready to deploy") 116 | 117 | 118 | if "__main__" == __name__: 119 | import argparse 120 | 121 | parser = argparse.ArgumentParser(description=__doc__) 122 | parser.add_argument( 123 | "--repo", default=GITHUB_REPO, help="GitHub repo (default: %s)" % GITHUB_REPO 124 | ) 125 | parser.add_argument("--password", help="PyPI password (will prompt if not provided)") 126 | 127 | args = parser.parse_args() 128 | main(args) 129 | --------------------------------------------------------------------------------