pax_global_header00006660000000000000000000000064140657376140014527gustar00rootroot0000000000000052 comment=7a940493cb48c28436a68d083aed2095ddaac670 clarkperkins-click-shell-7a94049/000077500000000000000000000000001406573761400166725ustar00rootroot00000000000000clarkperkins-click-shell-7a94049/.gitignore000066400000000000000000000060241406573761400206640ustar00rootroot00000000000000### Python template # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ pip-wheel-metadata/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover *.py,cover .hypothesis/ .pytest_cache/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 db.sqlite3-journal # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # IPython profile_default/ ipython_config.py # pyenv .python-version # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # However, in case of collaboration, if having platform-specific dependencies or dependencies # having no cross-platform support, pipenv may install dependencies that don't work, or not # install all needed dependencies. #Pipfile.lock # PEP 582; used by e.g. github.com/David-OConnor/pyflow __pypackages__/ # Celery stuff celerybeat-schedule celerybeat.pid # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .dmypy.json dmypy.json # Pyre type checker .pyre/ ### macOS template # General .DS_Store .AppleDouble .LSOverride # Icon must end with two \r Icon # Thumbnails ._* # Files that might appear in the root of a volume .DocumentRevisions-V100 .fseventsd .Spotlight-V100 .TemporaryItems .Trashes .VolumeIcon.icns .com.apple.timemachine.donotpresent # Directories potentially created on remote AFP share .AppleDB .AppleDesktop Network Trash Folder Temporary Items .apdisk ### JetBrains template # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 .idea/ # CMake cmake-build-*/ # File-based project format *.iws # IntelliJ out/ # mpeltonen/sbt-idea plugin .idea_modules/ # JIRA plugin atlassian-ide-plugin.xml # Crashlytics plugin (for Android Studio and IntelliJ) com_crashlytics_export_strings.xml crashlytics.properties crashlytics-build.properties fabric.properties ### Vim template # Swap [._]*.s[a-v][a-z] !*.svg # comment out if you don't need vector files [._]*.sw[a-p] [._]s[a-rt-v][a-z] [._]ss[a-gi-z] [._]sw[a-p] # Session Session.vim Sessionx.vim # Temporary .netrwhist *~ # Auto-generated tag files tags # Persistent undo [._]*.un~ ### Extras .history reports/ clarkperkins-click-shell-7a94049/.pylintrc000066400000000000000000000416221406573761400205440ustar00rootroot00000000000000[MASTER] # A comma-separated list of package or module names from where C extensions may # be loaded. Extensions are loading into the active Python interpreter and may # run arbitrary code. extension-pkg-whitelist= # Add files or directories to the blacklist. They should be base names, not # paths. ignore=CVS,migrations # Add files or directories matching the regex patterns to the blacklist. The # regex matches against base names, not paths. ignore-patterns= # Python code to execute, usually for sys.path manipulation such as # pygtk.require(). #init-hook= # Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the # number of processors available to use. jobs=0 # Control the amount of potential inferred values when inferring a single # object. This can help the performance when dealing with large functions or # complex, nested conditions. limit-inference-results=100 # List of plugins (as comma separated values of python modules names) to load, # usually to register additional checkers. #load-plugins= # Pickle collected data for later comparisons. persistent=yes # Specify a configuration file. #rcfile= # When enabled, pylint would attempt to guess common misconfiguration and emit # user-friendly hints instead of false-positive error messages. suggestion-mode=yes # Allow loading of arbitrary C extensions. Extensions are imported into the # active Python interpreter and may run arbitrary code. unsafe-load-any-extension=no [MESSAGES CONTROL] # Only show warnings with the listed confidence levels. Leave empty to show # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED. confidence= # Disable the message, report, category or checker with the given id(s). You # can either give multiple identifiers separated by comma (,) or put this # option multiple times (only on the command line, not in the configuration # file where it should appear only once). You can also use "--disable=all" to # disable everything first and then reenable specific checks. For example, if # you want to run only the similarities checker, you can use "--disable=all # --enable=similarities". If you want to run only the classes checker, but have # no Warning level messages displayed, use "--disable=all --enable=classes # --disable=W". disable=print-statement, parameter-unpacking, unpacking-in-except, old-raise-syntax, backtick, long-suffix, old-ne-operator, old-octal-literal, import-star-module-level, non-ascii-bytes-literal, raw-checker-failed, bad-inline-option, locally-disabled, locally-enabled, file-ignored, suppressed-message, useless-suppression, deprecated-pragma, use-symbolic-message-instead, apply-builtin, basestring-builtin, buffer-builtin, cmp-builtin, coerce-builtin, execfile-builtin, file-builtin, long-builtin, raw_input-builtin, reduce-builtin, standarderror-builtin, unicode-builtin, xrange-builtin, coerce-method, delslice-method, getslice-method, setslice-method, no-absolute-import, old-division, dict-iter-method, dict-view-method, next-method-called, metaclass-assignment, indexing-exception, raising-string, reload-builtin, oct-method, hex-method, nonzero-method, cmp-method, input-builtin, round-builtin, intern-builtin, unichr-builtin, map-builtin-not-iterating, zip-builtin-not-iterating, range-builtin-not-iterating, filter-builtin-not-iterating, using-cmp-argument, eq-without-hash, div-method, idiv-method, rdiv-method, exception-message-attribute, invalid-str-codec, sys-max-int, bad-python3-import, deprecated-string-function, deprecated-str-translate-call, deprecated-itertools-function, deprecated-types-field, next-method-defined, dict-items-not-iterating, dict-keys-not-iterating, dict-values-not-iterating, deprecated-operator-function, deprecated-urllib-function, xreadlines-attribute, deprecated-sys-function, exception-escape, comprehension-escape, # Extras invalid-name, logging-fstring-interpolation, missing-docstring, no-else-return, too-few-public-methods, super-with-arguments, useless-object-inheritance, keyword-arg-before-vararg # Enable the message, report, category or checker with the given id(s). You can # either give multiple identifier separated by comma (,) or put this option # multiple time (only on the command line, not in the configuration file where # it should appear only once). See also the "--disable" option for examples. enable=c-extension-no-member [REPORTS] # Python expression which should return a note less than 10 (10 is the highest # note). You have access to the variables errors warning, statement which # respectively contain the number of errors / warnings messages and the total # number of statements analyzed. This is used by the global evaluation report # (RP0004). evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) # Template used to display messages. This is a python new-style format string # used to format the message information. See doc for all details. #msg-template= # Set the output format. Available formats are text, parseable, colorized, json # and msvs (visual studio). You can also give a reporter class, e.g. # mypackage.mymodule.MyReporterClass. output-format=text # Tells whether to display a full report or only the messages. reports=no # Activate the evaluation score. score=yes [REFACTORING] # Maximum number of nested blocks for function / method body max-nested-blocks=5 # Complete name of functions that never returns. When checking for # inconsistent-return-statements if a never returning function is called then # it will be considered as an explicit return statement and no message will be # printed. never-returning-functions=sys.exit [LOGGING] # Logging modules to check that the string format arguments are in logging # function parameter format. logging-modules=logging [SPELLING] # Limits count of emitted suggestions for spelling mistakes. max-spelling-suggestions=4 # Spelling dictionary name. Available dictionaries: none. To make it working # install python-enchant package.. spelling-dict= # List of comma separated words that should not be checked. spelling-ignore-words= # A path to a file that contains private dictionary; one word per line. spelling-private-dict-file= # Tells whether to store unknown words to indicated private dictionary in # --spelling-private-dict-file option instead of raising a message. spelling-store-unknown-words=no [MISCELLANEOUS] # List of note tags to take in consideration, separated by a comma. notes=FIXME, XXX, TODO [TYPECHECK] # List of decorators that produce context managers, such as # contextlib.contextmanager. Add to this list to register other decorators that # produce valid context managers. contextmanager-decorators=contextlib.contextmanager # List of members which are set dynamically and missed by pylint inference # system, and so shouldn't trigger E1101 when accessed. Python regular # expressions are accepted. generated-members= # Tells whether missing members accessed in mixin class should be ignored. A # mixin class is detected if its name ends with "mixin" (case insensitive). ignore-mixin-members=yes # Tells whether to warn about missing members when the owner of the attribute # is inferred to be None. ignore-none=yes # This flag controls whether pylint should warn about no-member and similar # checks whenever an opaque object is returned when inferring. The inference # can return multiple potential results while evaluating a Python object, but # some branches might not be evaluated, which results in partial inference. In # that case, it might be useful to still emit no-member and other checks for # the rest of the inferred objects. ignore-on-opaque-inference=yes # List of class names for which member attributes should not be checked (useful # for classes with dynamically set attributes). This supports the use of # qualified names. ignored-classes=optparse.Values,thread._local,_thread._local # List of module names for which member attributes should not be checked # (useful for modules/projects where namespaces are manipulated during runtime # and thus existing member attributes cannot be deduced by static analysis. It # supports qualified module names, as well as Unix pattern matching. ignored-modules= # Show a hint with possible names when a member name was not found. The aspect # of finding the hint is based on edit distance. missing-member-hint=yes # The minimum edit distance a name should have in order to be considered a # similar match for a missing member name. missing-member-hint-distance=1 # The total number of similar names that should be taken in consideration when # showing a hint for a missing member. missing-member-max-choices=1 [VARIABLES] # List of additional names supposed to be defined in builtins. Remember that # you should avoid to define new builtins when possible. additional-builtins= # Tells whether unused global variables should be treated as a violation. allow-global-unused-variables=yes # List of strings which can identify a callback function by name. A callback # name must start or end with one of those strings. callbacks=cb_, _cb # A regular expression matching the name of dummy variables (i.e. expected to # not be used). dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ # Argument names that match this expression will be ignored. Default to name # with leading underscore. ignored-argument-names=_.*|^ignored_|^unused_ # Tells whether we should check for unused import in __init__ files. init-import=no # List of qualified module names which can have objects that can redefine # builtins. redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io [FORMAT] # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. expected-line-ending-format= # Regexp for a line that is allowed to be longer than the limit. ignore-long-lines=^\s*(# )??$ # Number of spaces of indent required inside a hanging or continued line. indent-after-paren=4 # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 # tab). indent-string=' ' # Maximum number of characters on a single line. max-line-length=100 # Maximum number of lines in a module. max-module-lines=1000 # List of optional constructs for which whitespace checking is disabled. `dict- # separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. # `trailing-comma` allows a space between comma and closing bracket: (a, ). # `empty-line` allows space-only lines. no-space-check=trailing-comma, dict-separator # Allow the body of a class to be on the same line as the declaration if body # contains single statement. single-line-class-stmt=no # Allow the body of an if to be on the same line as the test if there is no # else. single-line-if-stmt=no [SIMILARITIES] # Ignore comments when computing similarities. ignore-comments=yes # Ignore docstrings when computing similarities. ignore-docstrings=yes # Ignore imports when computing similarities. ignore-imports=no # Minimum lines number of a similarity. min-similarity-lines=4 [BASIC] # Naming style matching correct argument names. argument-naming-style=snake_case # Regular expression matching correct argument names. Overrides argument- # naming-style. #argument-rgx= # Naming style matching correct attribute names. attr-naming-style=snake_case # Regular expression matching correct attribute names. Overrides attr-naming- # style. #attr-rgx= # Bad variable names which should always be refused, separated by a comma. bad-names=foo, bar, baz, toto, tutu, tata # Naming style matching correct class attribute names. class-attribute-naming-style=any # Regular expression matching correct class attribute names. Overrides class- # attribute-naming-style. #class-attribute-rgx= # Naming style matching correct class names. class-naming-style=PascalCase # Regular expression matching correct class names. Overrides class-naming- # style. #class-rgx= # Naming style matching correct constant names. const-naming-style=UPPER_CASE # Regular expression matching correct constant names. Overrides const-naming- # style. #const-rgx= # Minimum line length for functions/classes that require docstrings, shorter # ones are exempt. docstring-min-length=-1 # Naming style matching correct function names. function-naming-style=snake_case # Regular expression matching correct function names. Overrides function- # naming-style. #function-rgx= # Good variable names which should always be accepted, separated by a comma. good-names=i, j, k, ex, Run, _ # Include a hint for the correct naming format with invalid-name. include-naming-hint=no # Naming style matching correct inline iteration names. inlinevar-naming-style=any # Regular expression matching correct inline iteration names. Overrides # inlinevar-naming-style. #inlinevar-rgx= # Naming style matching correct method names. method-naming-style=snake_case # Regular expression matching correct method names. Overrides method-naming- # style. #method-rgx= # Naming style matching correct module names. module-naming-style=snake_case # Regular expression matching correct module names. Overrides module-naming- # style. #module-rgx= # Colon-delimited sets of names that determine each other's naming style when # the name regexes allow several styles. name-group= # Regular expression which should only match function or class names that do # not require a docstring. no-docstring-rgx=^_ # List of decorators that produce properties, such as abc.abstractproperty. Add # to this list to register other decorators that produce valid properties. property-classes=abc.abstractproperty # Naming style matching correct variable names. variable-naming-style=snake_case # Regular expression matching correct variable names. Overrides variable- # naming-style. #variable-rgx= [IMPORTS] # Allow wildcard imports from modules that define __all__. allow-wildcard-with-all=no # Analyse import fallback blocks. This can be used to support both Python 2 and # 3 compatible code, which means that the block might have code that exists # only in one or another interpreter, leading to false positives when analysed. analyse-fallback-blocks=no # Deprecated modules which should not be used, separated by a comma. deprecated-modules=optparse,tkinter.tix # Create a graph of external dependencies in the given file (report RP0402 must # not be disabled). ext-import-graph= # Create a graph of every (i.e. internal and external) dependencies in the # given file (report RP0402 must not be disabled). import-graph= # Create a graph of internal dependencies in the given file (report RP0402 must # not be disabled). int-import-graph= # Force import order to recognize a module as part of the standard # compatibility libraries. known-standard-library= # Force import order to recognize a module as part of a third party library. known-third-party=enchant [CLASSES] # List of method names used to declare (i.e. assign) instance attributes. defining-attr-methods=__init__, __new__, setUp # List of member names, which should be excluded from the protected access # warning. exclude-protected=_asdict, _fields, _replace, _source, _make # List of valid names for the first argument in a class method. valid-classmethod-first-arg=cls # List of valid names for the first argument in a metaclass class method. valid-metaclass-classmethod-first-arg=cls [DESIGN] # Maximum number of arguments for function / method. max-args=5 # Maximum number of attributes for a class (see R0902). max-attributes=15 # Maximum number of boolean expressions in an if statement. max-bool-expr=5 # Maximum number of branch for function / method body. max-branches=12 # Maximum number of locals for function / method body. max-locals=15 # Maximum number of parents for a class (see R0901). max-parents=15 # Maximum number of public methods for a class (see R0904). max-public-methods=20 # Maximum number of return / yield for function / method body. max-returns=6 # Maximum number of statements in function / method body. max-statements=50 # Minimum number of public methods for a class (see R0903). min-public-methods=2 [EXCEPTIONS] # Exceptions that will emit a warning when being caught. Defaults to # "Exception". overgeneral-exceptions=Exception clarkperkins-click-shell-7a94049/.travis.yml000066400000000000000000000040171406573761400210050ustar00rootroot00000000000000language: python os: linux dist: bionic python: - "3.9" - "3.8" - "3.7" - "3.6" - "2.7" env: - CLICK_VERSION="8.0" - CLICK_VERSION="7.0" # click 8 doesn't support python2 jobs: exclude: - python: "2.7" env: CLICK_VERSION="8.0" cache: pip git: depth: false branches: only: - master - /^[0-9]+\.x$/ - /^[0-9]+\.[0-9]+$/ addons: sonarcloud: organization: clarkperkins token: secure: "thxDw6g+PgwiWrCQ4pgStlU3wbT+Bn06kEHd3DMo1ck5pL+nj9EVwihJp6ToJ7LMV74HjB4Y0A5DREHzS1Uoq8VPWzUXyAAcIXzWxX/GFSDDTJeLqlIE4Z3JBhpMc0bmAkXh6/9vGCQHsNTIi5SpPaw8fs+Fd7jUOAnHsLzTwCU/1G45BHwz/aB7uxhA1XdB4rbGWKBtbxLppH9B7tH2lH1QXriB34BnzoOrcL8xbX231ss3cIINcDq+d13+WWUtR5NynT0g0lUYPXp52202O0Q4xSqpEQ/HCDfcjrBHsn1qguijjbv8pEaa4zpW87nw06VbFVfbY33j4v0AUr57b/K/QBcpI4rRnFk/PAcmkbIDi1luJ0UnhYnhdlFbltbe0qfEO2ZuBc3MGzBpf7lH2UbUfsvNx3AC0/GFaZbVsjluNh+1AZO5vcgGeMPVnS0751/OYhMByp0PpFUlkIQg2vgDAfaF4i/y1h1HF3p1Jvrx7U9BD45ep412LMEeFLGKZ2fqO70Z+xaiIGwyKJjhIMaLDxrSVe4+IshnK4iBltsl4P5vKv0a4REuQed/hhU2YaVX8csz+H4WGq+9+IuN2O3E4shmjzZYAhJj2oYcjv0MXSNpvRBZb0+jr6C1HDEjycPmMcWEj2ByjKYz8HWoDiFVd75ej6WTBUCNt9RyGAg=" install: - ./install.sh script: - ./build.sh deploy: - provider: pypi user: "__token__" password: secure: "rIydgOGZ8IAxTqFLPmrcKQsJSmbSryqyCdIBvvPVsgs5jqUKLR/5XmS8KqX2gZFr5CaMrP85P7olrwt4aQPBCbLn4t3dT+/a1RaScr/fG9Ee5O+dj70ZYTrP02sNupOdEnzgV1S6giHgP/DAfu4UrA6fH/GgtWyyk8l5oV0kajGAceufmuA2sDwjcq4sxZaiV/KY6eFWlwnpYzeVvImXYrHU5mUAxtQvC8oKgk1FKrABCkdfRcXsW7yNmB5tmduSCaMyK2PutN4eBKqbSLWPTORomtt0uAOaVHaIS4p52z15Ug6i9q0FjJwXmxN45wUmS6zElDPYjbJi2tvS6B8gKlrOMbijCe82dDA5LX2NX161mbxeJS24Qvgo+GUhIkQxDFlM8gAuh6Mf19UTvgnPxkw71ubRT7W/43uu5WyZ8IHptg2lw+ss4js7aajHri2h7zS2DIFrTg7LweKHeosiceH+JGoB17KlxmRhwQvAEtW22W3l6oUycrvpSZ0/gy6NyQzgzn4NvaWEUHVIC80AT9/Oq+5TEr9Pr9kDSCeBwgRWmCJ9YIJVILMM69YCBtqEgf6fhTXRQzGv7vaj1yPIKqKuIQh2fUGWjFJN9vIN3mfWmwqAamg2PTZrK1GTDfAA6JDYIjyZeE5GNnjpd66sKEefsGwKfrrgxhFTF6mksmU=" distributions: sdist bdist_wheel on: tags: true repo: clarkperkins/click-shell python: '3.9' clarkperkins-click-shell-7a94049/CHANGELOG.rst000066400000000000000000000016521406573761400207170ustar00rootroot00000000000000Version 2.0 ----------- Released 2020-02-17 - Drop support for Python 2.6, 3.3, and 3.4 - Add support for Python 3.6, 3.7, and 3.8 - Add support for Click 7 - Added an ``on_finished`` callback method that will get called when the shell exits. `#16 `_ - Added support for a changeable prompt. `#1 `_ `#18 `_ - Handle Python installs where ``readline.__doc__`` is None. `#7 `_ `#11 `_ Version 1.0 ----------- Released 2016-11-28 - Support ``pyreadline`` for Windows. `#5 `_ - Fixed a bug where the command name was passed along to the shell. `#4 `_ clarkperkins-click-shell-7a94049/LICENSE000066400000000000000000000027131406573761400177020ustar00rootroot00000000000000Copyright (c) 2015, Clark Perkins All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of click-shell nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. clarkperkins-click-shell-7a94049/Pipfile000066400000000000000000000003551406573761400202100ustar00rootroot00000000000000[[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [packages] click-shell = {editable = true,path = "."} [dev-packages] mypy = "*" pycodestyle = "*" pylint = "*" pytest = "*" pytest-click = "*" pytest-cov = "*" clarkperkins-click-shell-7a94049/Pipfile.lock000066400000000000000000000403131406573761400211350ustar00rootroot00000000000000{ "_meta": { "hash": { "sha256": "0536f54d891cc05878ff66ece420f6d1dcffcb3a01180b18cad1bc58d200d628" }, "pipfile-spec": 6, "requires": {}, "sources": [ { "name": "pypi", "url": "https://pypi.org/simple", "verify_ssl": true } ] }, "default": { "click": { "hashes": [ "sha256:8c04c11192119b1ef78ea049e0a6f0463e4c48ef00a30160c704337586f3ad7a", "sha256:fba402a4a47334742d782209a7c79bc448911afe1149d07bdabdf480b3e2f4b6" ], "markers": "python_version >= '3.6'", "version": "==8.0.1" }, "click-shell": { "editable": true, "path": "." } }, "develop": { "astroid": { "hashes": [ "sha256:4db03ab5fc3340cf619dbc25e42c2cc3755154ce6009469766d7143d1fc2ee4e", "sha256:8a398dfce302c13f14bab13e2b14fe385d32b73f4e4853b9bdfb64598baa1975" ], "markers": "python_version ~= '3.6'", "version": "==2.5.6" }, "attrs": { "hashes": [ "sha256:149e90d6d8ac20db7a955ad60cf0e6881a3f20d37096140088356da6c716b0b1", "sha256:ef6aaac3ca6cd92904cdd0d83f629a15f18053ec84e6432106f7a4d04ae4f5fb" ], "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4'", "version": "==21.2.0" }, "click": { "hashes": [ "sha256:8c04c11192119b1ef78ea049e0a6f0463e4c48ef00a30160c704337586f3ad7a", "sha256:fba402a4a47334742d782209a7c79bc448911afe1149d07bdabdf480b3e2f4b6" ], "markers": "python_version >= '3.6'", "version": "==8.0.1" }, "coverage": { "hashes": [ "sha256:004d1880bed2d97151facef49f08e255a20ceb6f9432df75f4eef018fdd5a78c", "sha256:01d84219b5cdbfc8122223b39a954820929497a1cb1422824bb86b07b74594b6", "sha256:040af6c32813fa3eae5305d53f18875bedd079960822ef8ec067a66dd8afcd45", "sha256:06191eb60f8d8a5bc046f3799f8a07a2d7aefb9504b0209aff0b47298333302a", "sha256:13034c4409db851670bc9acd836243aeee299949bd5673e11844befcb0149f03", "sha256:13c4ee887eca0f4c5a247b75398d4114c37882658300e153113dafb1d76de529", "sha256:184a47bbe0aa6400ed2d41d8e9ed868b8205046518c52464fde713ea06e3a74a", "sha256:18ba8bbede96a2c3dde7b868de9dcbd55670690af0988713f0603f037848418a", "sha256:1aa846f56c3d49205c952d8318e76ccc2ae23303351d9270ab220004c580cfe2", "sha256:217658ec7187497e3f3ebd901afdca1af062b42cfe3e0dafea4cced3983739f6", "sha256:24d4a7de75446be83244eabbff746d66b9240ae020ced65d060815fac3423759", "sha256:2910f4d36a6a9b4214bb7038d537f015346f413a975d57ca6b43bf23d6563b53", "sha256:2949cad1c5208b8298d5686d5a85b66aae46d73eec2c3e08c817dd3513e5848a", "sha256:2a3859cb82dcbda1cfd3e6f71c27081d18aa251d20a17d87d26d4cd216fb0af4", "sha256:2cafbbb3af0733db200c9b5f798d18953b1a304d3f86a938367de1567f4b5bff", "sha256:2e0d881ad471768bf6e6c2bf905d183543f10098e3b3640fc029509530091502", "sha256:30c77c1dc9f253283e34c27935fded5015f7d1abe83bc7821680ac444eaf7793", "sha256:3487286bc29a5aa4b93a072e9592f22254291ce96a9fbc5251f566b6b7343cdb", "sha256:372da284cfd642d8e08ef606917846fa2ee350f64994bebfbd3afb0040436905", "sha256:41179b8a845742d1eb60449bdb2992196e211341818565abded11cfa90efb821", "sha256:44d654437b8ddd9eee7d1eaee28b7219bec228520ff809af170488fd2fed3e2b", "sha256:4a7697d8cb0f27399b0e393c0b90f0f1e40c82023ea4d45d22bce7032a5d7b81", "sha256:51cb9476a3987c8967ebab3f0fe144819781fca264f57f89760037a2ea191cb0", "sha256:52596d3d0e8bdf3af43db3e9ba8dcdaac724ba7b5ca3f6358529d56f7a166f8b", "sha256:53194af30d5bad77fcba80e23a1441c71abfb3e01192034f8246e0d8f99528f3", "sha256:5fec2d43a2cc6965edc0bb9e83e1e4b557f76f843a77a2496cbe719583ce8184", "sha256:6c90e11318f0d3c436a42409f2749ee1a115cd8b067d7f14c148f1ce5574d701", "sha256:74d881fc777ebb11c63736622b60cb9e4aee5cace591ce274fb69e582a12a61a", "sha256:7501140f755b725495941b43347ba8a2777407fc7f250d4f5a7d2a1050ba8e82", "sha256:796c9c3c79747146ebd278dbe1e5c5c05dd6b10cc3bcb8389dfdf844f3ead638", "sha256:869a64f53488f40fa5b5b9dcb9e9b2962a66a87dab37790f3fcfb5144b996ef5", "sha256:8963a499849a1fc54b35b1c9f162f4108017b2e6db2c46c1bed93a72262ed083", "sha256:8d0a0725ad7c1a0bcd8d1b437e191107d457e2ec1084b9f190630a4fb1af78e6", "sha256:900fbf7759501bc7807fd6638c947d7a831fc9fdf742dc10f02956ff7220fa90", "sha256:92b017ce34b68a7d67bd6d117e6d443a9bf63a2ecf8567bb3d8c6c7bc5014465", "sha256:970284a88b99673ccb2e4e334cfb38a10aab7cd44f7457564d11898a74b62d0a", "sha256:972c85d205b51e30e59525694670de6a8a89691186012535f9d7dbaa230e42c3", "sha256:9a1ef3b66e38ef8618ce5fdc7bea3d9f45f3624e2a66295eea5e57966c85909e", "sha256:af0e781009aaf59e25c5a678122391cb0f345ac0ec272c7961dc5455e1c40066", "sha256:b6d534e4b2ab35c9f93f46229363e17f63c53ad01330df9f2d6bd1187e5eaacf", "sha256:b7895207b4c843c76a25ab8c1e866261bcfe27bfaa20c192de5190121770672b", "sha256:c0891a6a97b09c1f3e073a890514d5012eb256845c451bd48f7968ef939bf4ae", "sha256:c2723d347ab06e7ddad1a58b2a821218239249a9e4365eaff6649d31180c1669", "sha256:d1f8bf7b90ba55699b3a5e44930e93ff0189aa27186e96071fac7dd0d06a1873", "sha256:d1f9ce122f83b2305592c11d64f181b87153fc2c2bbd3bb4a3dde8303cfb1a6b", "sha256:d314ed732c25d29775e84a960c3c60808b682c08d86602ec2c3008e1202e3bb6", "sha256:d636598c8305e1f90b439dbf4f66437de4a5e3c31fdf47ad29542478c8508bbb", "sha256:deee1077aae10d8fa88cb02c845cfba9b62c55e1183f52f6ae6a2df6a2187160", "sha256:ebe78fe9a0e874362175b02371bdfbee64d8edc42a044253ddf4ee7d3c15212c", "sha256:f030f8873312a16414c0d8e1a1ddff2d3235655a2174e3648b4fa66b3f2f1079", "sha256:f0b278ce10936db1a37e6954e15a3730bea96a0997c26d7fee88e6c396c2086d", "sha256:f11642dddbb0253cc8853254301b51390ba0081750a8ac03f20ea8103f0c56b6" ], "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4' and python_version < '4'", "version": "==5.5" }, "iniconfig": { "hashes": [ "sha256:011e24c64b7f47f6ebd835bb12a743f2fbe9a26d4cecaa7f53bc4f35ee9da8b3", "sha256:bc3af051d7d14b2ee5ef9969666def0cd1a000e121eaea580d4a313df4b37f32" ], "version": "==1.1.1" }, "isort": { "hashes": [ "sha256:83510593e07e433b77bd5bff0f6f607dbafa06d1a89022616f02d8b699cfcd56", "sha256:8e2c107091cfec7286bc0f68a547d0ba4c094d460b732075b6fba674f1035c0c" ], "markers": "python_full_version >= '3.6.1' and python_version < '4'", "version": "==5.9.1" }, "lazy-object-proxy": { "hashes": [ "sha256:17e0967ba374fc24141738c69736da90e94419338fd4c7c7bef01ee26b339653", "sha256:1fee665d2638491f4d6e55bd483e15ef21f6c8c2095f235fef72601021e64f61", "sha256:22ddd618cefe54305df49e4c069fa65715be4ad0e78e8d252a33debf00f6ede2", "sha256:24a5045889cc2729033b3e604d496c2b6f588c754f7a62027ad4437a7ecc4837", "sha256:410283732af311b51b837894fa2f24f2c0039aa7f220135192b38fcc42bd43d3", "sha256:4732c765372bd78a2d6b2150a6e99d00a78ec963375f236979c0626b97ed8e43", "sha256:489000d368377571c6f982fba6497f2aa13c6d1facc40660963da62f5c379726", "sha256:4f60460e9f1eb632584c9685bccea152f4ac2130e299784dbaf9fae9f49891b3", "sha256:5743a5ab42ae40caa8421b320ebf3a998f89c85cdc8376d6b2e00bd12bd1b587", "sha256:85fb7608121fd5621cc4377a8961d0b32ccf84a7285b4f1d21988b2eae2868e8", "sha256:9698110e36e2df951c7c36b6729e96429c9c32b3331989ef19976592c5f3c77a", "sha256:9d397bf41caad3f489e10774667310d73cb9c4258e9aed94b9ec734b34b495fd", "sha256:b579f8acbf2bdd9ea200b1d5dea36abd93cabf56cf626ab9c744a432e15c815f", "sha256:b865b01a2e7f96db0c5d12cfea590f98d8c5ba64ad222300d93ce6ff9138bcad", "sha256:bf34e368e8dd976423396555078def5cfc3039ebc6fc06d1ae2c5a65eebbcde4", "sha256:c6938967f8528b3668622a9ed3b31d145fab161a32f5891ea7b84f6b790be05b", "sha256:d1c2676e3d840852a2de7c7d5d76407c772927addff8d742b9808fe0afccebdf", "sha256:d7124f52f3bd259f510651450e18e0fd081ed82f3c08541dffc7b94b883aa981", "sha256:d900d949b707778696fdf01036f58c9876a0d8bfe116e8d220cfd4b15f14e741", "sha256:ebfd274dcd5133e0afae738e6d9da4323c3eb021b3e13052d8cbd0e457b1256e", "sha256:ed361bb83436f117f9917d282a456f9e5009ea12fd6de8742d1a4752c3017e93", "sha256:f5144c75445ae3ca2057faac03fda5a902eff196702b0a24daf1d6ce0650514b" ], "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4, 3.5'", "version": "==1.6.0" }, "mccabe": { "hashes": [ "sha256:ab8a6258860da4b6677da4bd2fe5dc2c659cff31b3ee4f7f5d64e79735b80d42", "sha256:dd8d182285a0fe56bace7f45b5e7d1a6ebcbf524e8f3bd87eb0f125271b8831f" ], "version": "==0.6.1" }, "mypy": { "hashes": [ "sha256:088cd9c7904b4ad80bec811053272986611b84221835e079be5bcad029e79dd9", "sha256:0aadfb2d3935988ec3815952e44058a3100499f5be5b28c34ac9d79f002a4a9a", "sha256:119bed3832d961f3a880787bf621634ba042cb8dc850a7429f643508eeac97b9", "sha256:1a85e280d4d217150ce8cb1a6dddffd14e753a4e0c3cf90baabb32cefa41b59e", "sha256:3c4b8ca36877fc75339253721f69603a9c7fdb5d4d5a95a1a1b899d8b86a4de2", "sha256:3e382b29f8e0ccf19a2df2b29a167591245df90c0b5a2542249873b5c1d78212", "sha256:42c266ced41b65ed40a282c575705325fa7991af370036d3f134518336636f5b", "sha256:53fd2eb27a8ee2892614370896956af2ff61254c275aaee4c230ae771cadd885", "sha256:704098302473cb31a218f1775a873b376b30b4c18229421e9e9dc8916fd16150", "sha256:7df1ead20c81371ccd6091fa3e2878559b5c4d4caadaf1a484cf88d93ca06703", "sha256:866c41f28cee548475f146aa4d39a51cf3b6a84246969f3759cb3e9c742fc072", "sha256:a155d80ea6cee511a3694b108c4494a39f42de11ee4e61e72bc424c490e46457", "sha256:adaeee09bfde366d2c13fe6093a7df5df83c9a2ba98638c7d76b010694db760e", "sha256:b6fb13123aeef4a3abbcfd7e71773ff3ff1526a7d3dc538f3929a49b42be03f0", "sha256:b94e4b785e304a04ea0828759172a15add27088520dc7e49ceade7834275bedb", "sha256:c0df2d30ed496a08de5daed2a9ea807d07c21ae0ab23acf541ab88c24b26ab97", "sha256:c6c2602dffb74867498f86e6129fd52a2770c48b7cd3ece77ada4fa38f94eba8", "sha256:ceb6e0a6e27fb364fb3853389607cf7eb3a126ad335790fa1e14ed02fba50811", "sha256:d9dd839eb0dc1bbe866a288ba3c1afc33a202015d2ad83b31e875b5905a079b6", "sha256:e4dab234478e3bd3ce83bac4193b2ecd9cf94e720ddd95ce69840273bf44f6de", "sha256:ec4e0cd079db280b6bdabdc807047ff3e199f334050db5cbb91ba3e959a67504", "sha256:ecd2c3fe726758037234c93df7e98deb257fd15c24c9180dacf1ef829da5f921", "sha256:ef565033fa5a958e62796867b1df10c40263ea9ded87164d67572834e57a174d" ], "index": "pypi", "version": "==0.910" }, "mypy-extensions": { "hashes": [ "sha256:090fedd75945a69ae91ce1303b5824f428daf5a028d2f6ab8a299250a846f15d", "sha256:2d82818f5bb3e369420cb3c4060a7970edba416647068eb4c5343488a6c604a8" ], "version": "==0.4.3" }, "packaging": { "hashes": [ "sha256:5b327ac1320dc863dca72f4514ecc086f31186744b84a230374cc1fd776feae5", "sha256:67714da7f7bc052e064859c05c595155bd1ee9f69f76557e21f051443c20947a" ], "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==20.9" }, "pluggy": { "hashes": [ "sha256:15b2acde666561e1298d71b523007ed7364de07029219b604cf808bfa1c765b0", "sha256:966c145cd83c96502c3c3868f50408687b38434af77734af1e9ca461a4081d2d" ], "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==0.13.1" }, "py": { "hashes": [ "sha256:21b81bda15b66ef5e1a777a21c4dcd9c20ad3efd0b3f817e7a809035269e1bd3", "sha256:3b80836aa6d1feeaa108e046da6423ab8f6ceda6468545ae8d02d9d58d18818a" ], "markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3'", "version": "==1.10.0" }, "pycodestyle": { "hashes": [ "sha256:514f76d918fcc0b55c6680472f0a37970994e07bbb80725808c17089be302068", "sha256:c389c1d06bf7904078ca03399a4816f974a1d590090fecea0c63ec26ebaf1cef" ], "index": "pypi", "version": "==2.7.0" }, "pylint": { "hashes": [ "sha256:0a049c5d47b629d9070c3932d13bff482b12119b6a241a93bc460b0be16953c8", "sha256:792b38ff30903884e4a9eab814ee3523731abd3c463f3ba48d7b627e87013484" ], "index": "pypi", "version": "==2.8.3" }, "pyparsing": { "hashes": [ "sha256:c203ec8783bf771a155b207279b9bccb8dea02d8f0c9e5f8ead507bc3246ecc1", "sha256:ef9d7589ef3c200abe66653d3f1ab1033c3c419ae9b9bdb1240a85b024efc88b" ], "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2'", "version": "==2.4.7" }, "pytest": { "hashes": [ "sha256:50bcad0a0b9c5a72c8e4e7c9855a3ad496ca6a881a3641b4260605450772c54b", "sha256:91ef2131a9bd6be8f76f1f08eac5c5317221d6ad1e143ae03894b862e8976890" ], "index": "pypi", "version": "==6.2.4" }, "pytest-click": { "hashes": [ "sha256:ac298e15a31d8892d9d063c3be82bb9877aaa11a4944e05e541ecc753258e474", "sha256:b40b8435adde7a0d931352036a3882b13cd424fce2ffd7be6c87665050259be5" ], "index": "pypi", "version": "==1.0.2" }, "pytest-cov": { "hashes": [ "sha256:261bb9e47e65bd099c89c3edf92972865210c36813f80ede5277dceb77a4a62a", "sha256:261ceeb8c227b726249b376b8526b600f38667ee314f910353fa318caa01f4d7" ], "index": "pypi", "version": "==2.12.1" }, "toml": { "hashes": [ "sha256:806143ae5bfb6a3c6e736a764057db0e6a0e05e338b5630894a5f779cabb4f9b", "sha256:b3bda1d108d5dd99f4a20d24d9c348e91c4db7ab1b749200bded2f839ccbe68f" ], "markers": "python_version >= '2.6' and python_version not in '3.0, 3.1, 3.2'", "version": "==0.10.2" }, "typing-extensions": { "hashes": [ "sha256:0ac0f89795dd19de6b97debb0c6af1c70987fd80a2d62d1958f7e56fcc31b497", "sha256:50b6f157849174217d0656f99dc82fe932884fb250826c18350e159ec6cdf342", "sha256:779383f6086d90c99ae41cf0ff39aac8a7937a9283ce0a414e5dd782f4c94a84" ], "version": "==3.10.0.0" }, "wrapt": { "hashes": [ "sha256:b62ffa81fb85f4332a4f609cab4ac40709470da05643a082ec1eb88e6d9b97d7" ], "version": "==1.12.1" } } } clarkperkins-click-shell-7a94049/README.rst000066400000000000000000000034721406573761400203670ustar00rootroot00000000000000click-shell =========== |TravisCI| |DocsStatus| click-shell is an extension to `click`_ that easily turns your click app into a shell utility. It is built on top of the built in python `cmd`_ module, with modifications to make it work with click. Features -------- * Adds a "shell" mode **with command completion** to any click app * Just a one line change for most click apps Usage ----- Simply replace ``@click.group`` with ``@click_shell.shell`` on the root level command: .. code-block:: python from click_shell import shell # @click.group() # no longer @shell(prompt='my-app > ', intro='Starting my app...') def my_app(): pass @my_app.command() def testcommand(): print('testcommand is running') # more commands if __name__ == '__main__': my_app() When run, you should expect an output like so: .. code-block:: bash $ python my_app.py Starting my app... my-app > testcommand testcommand is running my-app > .. note:: It should be noted that this decorator **only** alters functionality if no arguments are passed on the command line. If you try to run a command directly (like ``python my_app.py the_command`` in the above example), your app will function identically to how it did before. For more advanced usage, check out our docs at https://click-shell.readthedocs.io/ .. _click: http://click.pocoo.org/ .. _cmd: https://docs.python.org/2/library/cmd.html .. |TravisCI| image:: https://travis-ci.com/clarkperkins/click-shell.svg?branch=master :target: https://travis-ci.com/clarkperkins/click-shell :alt: Build status .. |DocsStatus| image:: https://readthedocs.org/projects/click-shell/badge/?version=latest :target: https://click-shell.readthedocs.io/en/latest/?badge=latest :alt: Documentation Status clarkperkins-click-shell-7a94049/build.sh000077500000000000000000000014051406573761400203300ustar00rootroot00000000000000#!/bin/bash set -e mkdir -p reports # Code linting echo "Running pycodestyle..." pycodestyle click_shell echo "Running pylint..." pylint click_shell --reports=n --exit-zero --msg-template="{path}:{line}: [{msg_id}({symbol}), {obj}] {msg}" > reports/pylint.txt # Type checking # mypy doesn't work at all on python2, and there's some other issues with pipenv packages on python3 < 3.8 if [ "$TRAVIS_PYTHON_VERSION" == "3.9" ]; then echo "Running mypy..." mypy click_shell fi # Unit tests pytest -vv --cov=click_shell --cov-report=xml if [ "$TRAVIS_PYTHON_VERSION" == "3.9" ] && [ "$CLICK_VERSION" == "8.0" ] && [ "$TRAVIS_TAG" == "" ]; then echo "Python 3.9 detected, running sonar-scanner" sonar-scanner -Dsonar.projectVersion=$(python setup.py --version) fi clarkperkins-click-shell-7a94049/click_shell/000077500000000000000000000000001406573761400211465ustar00rootroot00000000000000clarkperkins-click-shell-7a94049/click_shell/__init__.py000066400000000000000000000004231406573761400232560ustar00rootroot00000000000000""" click-shell An extension to click that easily turns your click app into a shell utility """ from .core import make_click_shell, Shell from .decorators import shell __all__ = [ 'make_click_shell', 'shell', 'Shell', '__version__', ] __version__ = "2.1" clarkperkins-click-shell-7a94049/click_shell/_cmd.py000066400000000000000000000133061406573761400224250ustar00rootroot00000000000000""" click_shell._cmd This module overrides the builtin python cmd module """ import inspect import os from cmd import Cmd import click from click_shell._compat import readline, get_input class ClickCmd(Cmd, object): """ A simple wrapper around the builtin python cmd module that: 1) makes completion work on OSX 2) uses a history file 3) uses click.echo instead of std*.write() 4) turns Cmd into a new-style python object :) """ # Allow dashes identchars = Cmd.identchars + '-' nohelp = "No help on %s" nocommand = "Command not found: %s" def __init__(self, ctx=None, on_finished=None, hist_file=None, *args, **kwargs): # Never allow super() to default to sys.stdout for stdout. # Instead pass along a wrapper that delegates to click.echo(). self._stdout = kwargs.get('stdout') super(ClickCmd, self).__init__(*args, **kwargs) self.old_completer = None self.old_delims = None # We need to save the context!! self.ctx = ctx self.on_finished = on_finished # Set the history file hist_file = hist_file or os.path.join(os.path.expanduser('~'), '.click-history') self.hist_file = os.path.abspath(hist_file) # Make the parent directory if not os.path.isdir(os.path.dirname(self.hist_file)): os.makedirs(os.path.dirname(self.hist_file)) def preloop(self): # read our history if readline: try: readline.read_history_file(self.hist_file) except IOError: pass def postloop(self): # Write our history if readline: readline.set_history_length(1000) try: readline.write_history_file(self.hist_file) except IOError: pass # Finisher callback on the context if self.on_finished: self.on_finished(self.ctx) # We need to override this to fix readline def cmdloop(self, intro=None): # pylint: disable=too-many-branches self.preloop() if self.completekey and readline: self.old_completer = readline.get_completer() self.old_delims = readline.get_completer_delims() readline.set_completer(self.complete) readline.set_completer_delims(' \n\t') to_parse = self.completekey + ': complete' if readline.__doc__ and 'libedit' in readline.__doc__: # Special case for mac OSX to_parse = 'bind ^I rl_complete' readline.parse_and_bind(to_parse) try: if intro is not None: self.intro = intro if self.intro: click.echo(self.intro, file=self._stdout) stop = None while not stop: if self.cmdqueue: line = self.cmdqueue.pop(0) else: try: line = get_input(self.get_prompt()) except EOFError: # We just want to quit here instead of changing the arg to EOF click.echo(file=self._stdout) break except KeyboardInterrupt: # We don't want to exit the shell on a keyboard interrupt click.echo(file=self._stdout) click.echo('KeyboardInterrupt', file=self._stdout) continue line = self.precmd(line) stop = self.onecmd(line) stop = self.postcmd(stop, line) finally: self.postloop() if self.completekey and readline: readline.set_completer(self.old_completer) readline.set_completer_delims(self.old_delims) def get_prompt(self): if callable(self.prompt): kwargs = {} if hasattr(inspect, 'signature'): sig = inspect.signature(self.prompt) if 'ctx' in sig.parameters: kwargs['ctx'] = self.ctx return self.prompt(**kwargs) else: return self.prompt def emptyline(self): # we don't want to repeat the last command if nothing was typed return False def default(self, line): click.echo(self.nocommand % line, file=self._stdout) def get_names(self): # Do dir(self) instead of dir(self.__class__) return dir(self) def do_help(self, arg): if not arg: super(ClickCmd, self).do_help(arg) return # Override to give better error message try: func = getattr(self, 'help_' + arg) except AttributeError: try: do_fun = getattr(self, 'do_' + arg, None) if do_fun is None: click.echo(self.nocommand % arg, file=self._stdout) return doc = do_fun.__doc__ if doc: click.echo(doc, file=self._stdout) return except AttributeError: pass click.echo(self.nohelp % arg, file=self._stdout) return func() def do_quit(self, arg): # pylint: disable=unused-argument,no-self-use return True def do_exit(self, arg): # pylint: disable=unused-argument,no-self-use return True def print_topics(self, header, cmds, cmdlen, maxcol): if cmds: click.echo(header, file=self._stdout) if self.ruler: click.echo(str(self.ruler * len(header)), file=self._stdout) self.columnize(cmds, maxcol - 1) click.echo(file=self._stdout) clarkperkins-click-shell-7a94049/click_shell/_compat.py000066400000000000000000000035241406573761400231460ustar00rootroot00000000000000""" click_shell._compat Compatibility things for python 2.6 """ # pylint: disable=unused-import, wrong-import-position import sys import types PY2 = sys.version_info[0] == 2 try: import readline except ImportError: try: import pyreadline as readline except ImportError: readline = None try: from click._compat import raw_input as get_input except ImportError: # If click._compat does not provide raw_input, it means we're # dealing with click >= 8, which means we're under Python 3, # so we can just use the standard input function. get_input = input def get_method_type(func, obj): if PY2: return types.MethodType(func, obj, type(obj)) else: return types.MethodType(func, obj) try: from click._bashcomplete import get_choices except ImportError: import click try: from click._bashcomplete import resolve_ctx except ImportError: from click.shell_completion import _resolve_context def resolve_ctx(cli, prog_name, args): return _resolve_context(cli, {}, prog_name, args) def get_choices(cli, prog_name, args, incomplete): """ This is identical to click._bashcomplete:get_choices in click 6.4+ """ ctx = resolve_ctx(cli, prog_name, args) if ctx is None: return choices = [] if incomplete and not incomplete[:1].isalnum(): for param in ctx.command.params: if not isinstance(param, click.Option): continue choices.extend(param.opts) choices.extend(param.secondary_opts) elif isinstance(ctx.command, click.MultiCommand): choices.extend(ctx.command.list_commands(ctx)) for item in choices: if item.startswith(incomplete): yield item clarkperkins-click-shell-7a94049/click_shell/core.py000066400000000000000000000124101406573761400224460ustar00rootroot00000000000000""" click_shell.core Core functionality for click-shell """ import logging import shlex import traceback from functools import update_wrapper from logging import NullHandler import click from ._cmd import ClickCmd from ._compat import get_method_type, get_choices logger = logging.getLogger(__name__) logger.addHandler(NullHandler()) def get_invoke(command): """ Get the Cmd main method from the click command :param command: The click Command object :return: the do_* method for Cmd :rtype: function """ assert isinstance(command, click.Command) def invoke_(self, arg): # pylint: disable=unused-argument try: command.main(args=shlex.split(arg), prog_name=command.name, standalone_mode=False, parent=self.ctx) except click.ClickException as e: # Show the error message e.show() except click.Abort: # We got an EOF or Keyboard interrupt. Just silence it pass except SystemExit: # Catch this an return the code instead. All of click's help commands do a sys.exit(), # and that's not ideal when running in a shell. pass except Exception as e: traceback.print_exception(type(e), e, None) logger.warning(traceback.format_exc()) # Always return False so the shell doesn't exit return False invoke_ = update_wrapper(invoke_, command.callback) invoke_.__name__ = 'do_%s' % command.name return invoke_ def get_help(command): """ Get the Cmd help function from the click command :param command: The click Command object :return: the help_* method for Cmd :rtype: function """ assert isinstance(command, click.Command) def help_(self): # pylint: disable=unused-argument extra = {} for key, value in command.context_settings.items(): if key not in extra: extra[key] = value # Print click's help message with click.Context(command, info_name=command.name, parent=self.ctx, **extra) as ctx: click.echo(ctx.get_help(), color=ctx.color) help_.__name__ = 'help_%s' % command.name return help_ def get_complete(command): """ Get the Cmd complete function for the click command :param command: The click Command object :return: the complete_* method for Cmd :rtype: function """ assert isinstance(command, click.Command) def complete_(self, text, line, begidx, endidx): # pylint: disable=unused-argument # Parse the args args = shlex.split(line[:begidx]) # Strip of the first item which is the name of the command args = args[1:] # Then pass them on to the get_choices method that click uses for completion return [choice[0] if isinstance(choice, tuple) else choice for choice in get_choices(command, command.name, args, text)] complete_.__name__ = 'complete_%s' % command.name return complete_ class ClickShell(ClickCmd): def add_command(self, cmd, name): # Use the MethodType to add these as bound methods to our current instance setattr(self, 'do_%s' % name, get_method_type(get_invoke(cmd), self)) setattr(self, 'help_%s' % name, get_method_type(get_help(cmd), self)) setattr(self, 'complete_%s' % name, get_method_type(get_complete(cmd), self)) def make_click_shell(ctx, prompt=None, intro=None, hist_file=None): assert isinstance(ctx, click.Context) assert isinstance(ctx.command, click.MultiCommand) # Set this to None so that it doesn't get printed out in usage messages ctx.info_name = None # Create our shell object shell = ClickShell(ctx=ctx, hist_file=hist_file) if prompt is not None: shell.prompt = prompt if intro is not None: shell.intro = intro # Add all the commands for name in ctx.command.list_commands(ctx): command = ctx.command.get_command(ctx, name) shell.add_command(command, name) return shell class Shell(click.Group): def __init__(self, prompt=None, intro=None, hist_file=None, on_finished=None, **attrs): attrs['invoke_without_command'] = True super(Shell, self).__init__(**attrs) # Make our shell self.shell = ClickShell(hist_file=hist_file, on_finished=on_finished) if prompt: self.shell.prompt = prompt self.shell.intro = intro def add_command(self, cmd, name=None): super(Shell, self).add_command(cmd, name) # Grab the proper name name = name or cmd.name # Add the command to the shell self.shell.add_command(cmd, name) def invoke(self, ctx): # Call super() first. This ensures that we call the method body of our instance first, # in case it's something other than `pass` ret = super(Shell, self).invoke(ctx) if not ctx.protected_args and not ctx.invoked_subcommand: # Set this to None so that it doesn't get printed out in usage messages ctx.info_name = None # Set the context on the shell self.shell.ctx = ctx # Start up the shell return self.shell.cmdloop() return ret clarkperkins-click-shell-7a94049/click_shell/decorators.py000066400000000000000000000006661406573761400236750ustar00rootroot00000000000000""" click_shell.decorators Decorators to make using click_shell simpler and more similar to click. """ import click from .core import Shell def shell(name=None, **attrs): """Creates a new :class:`Shell` with a function as callback. This works otherwise the same as :func:`command` just that the `cls` parameter is set to :class:`Shell`. """ attrs.setdefault('cls', Shell) return click.command(name, **attrs) clarkperkins-click-shell-7a94049/docs/000077500000000000000000000000001406573761400176225ustar00rootroot00000000000000clarkperkins-click-shell-7a94049/docs/Makefile000066400000000000000000000164051406573761400212700ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(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/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " applehelp to make an Apple Help Book" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" @echo " coverage to run coverage check of the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/click-shell.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/click-shell.qhc" applehelp: $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp @echo @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." @echo "N.B. You won't be able to view it unless you put it in" \ "~/Library/Documentation/Help or install it in your application" \ "bundle." devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/click-shell" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/click-shell" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." coverage: $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage @echo "Testing of coverage in the sources finished, look at the " \ "results in $(BUILDDIR)/coverage/python.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." clarkperkins-click-shell-7a94049/docs/changelog.rst000066400000000000000000000002001406573761400222730ustar00rootroot00000000000000Changelog ========= The changelog is located in GitHub: https://github.com/clarkperkins/click-shell/blob/master/CHANGELOG.rst clarkperkins-click-shell-7a94049/docs/conf.py000066400000000000000000000276571406573761400211420ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # click-shell documentation build configuration file, created by # sphinx-quickstart on Sun Dec 13 02:02:08 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import io import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def read(rel_path): with io.open(os.path.join(BASE_DIR, rel_path), 'r') as fp: return fp.read() def get_version(rel_path): for line in read(rel_path).splitlines(): if line.startswith('__version__'): # __version__ = "0.9" delim = '"' if '"' in line else "'" return line.split(delim)[1] else: raise RuntimeError("Unable to find version string.") # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.mathjax', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'click-shell' copyright = u'2015, Clark Perkins' author = u'Clark Perkins' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The full version, including alpha/beta/rc tags. release = get_version('click_shell/__init__.py') # The short X.Y version. version = release.split('.')[0] # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' # html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value # html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. # html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'click-shelldoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # 'preamble': '', # Latex figure (float) alignment # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'click-shell.tex', u'click-shell Documentation', u'Clark Perkins', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'click-shell', u'click-shell Documentation', [author], 1) ] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'click-shell', u'click-shell Documentation', author, 'click-shell', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. # texinfo_no_detailmenu = False # -- Options for Epub output ---------------------------------------------- # Bibliographic Dublin Core info. epub_title = project epub_author = author epub_publisher = author epub_copyright = copyright # The basename for the epub file. It defaults to the project name. # epub_basename = project # The HTML theme for the epub output. Since the default themes are not optimized # for small screen space, using the same theme for HTML and epub output is # usually not wise. This defaults to 'epub', a theme designed to save visual # space. # epub_theme = 'epub' # The language of the text. It defaults to the language option # or 'en' if the language is not set. # epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. # epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. # epub_identifier = '' # A unique identification for the text. # epub_uid = '' # A tuple containing the cover image and cover page html template filenames. # epub_cover = () # A sequence of (type, uri, title) tuples for the guide element of content.opf. # epub_guide = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. # epub_pre_files = [] # HTML files shat should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. # epub_post_files = [] # A list of files that should not be packed into the epub file. epub_exclude_files = ['search.html'] # The depth of the table of contents in toc.ncx. # epub_tocdepth = 3 # Allow duplicate toc entries. # epub_tocdup = True # Choose between 'default' and 'includehidden'. # epub_tocscope = 'default' # Fix unsupported image types using the Pillow. # epub_fix_images = False # Scale large images. # epub_max_image_width = 0 # How to display URL addresses: 'footnote', 'no', or 'inline'. # epub_show_urls = 'inline' # If false, no index is generated. # epub_use_index = True # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'https://docs.python.org/': None} clarkperkins-click-shell-7a94049/docs/index.rst000066400000000000000000000015511406573761400214650ustar00rootroot00000000000000Welcome to click-shell's documentation! ======================================= click-shell is an extension to `click`_ that easily turns your click app into a shell utility. It is built on top of the built in python `cmd`_ module, with modifications to make it work with click. click-shell is compatible with python versions 2.7, 3.5, 3.6, 3.7, and 3.8. Features -------- * Adds a "shell" mode **with command completion** to any click app * Just a one line change for most click apps .. note:: It should be noted that click-shell **only** alters functionality if no arguments are passed on the command line. Previously if no arguments were passed, the help was displayed. .. toctree:: :maxdepth: 2 install usage changelog troubleshooting .. _click: https://click.palletsprojects.com/ .. _cmd: https://docs.python.org/3/library/cmd.html clarkperkins-click-shell-7a94049/docs/install.rst000066400000000000000000000004561406573761400220270ustar00rootroot00000000000000Installation ============ The easiest way to install is with pip: .. code-block:: bash pip install click-shell If you'd rather, you can clone the github repo and install manually: .. code-block:: bash git clone https://github.com/clarkperkins/click-shell.git python setup.py install clarkperkins-click-shell-7a94049/docs/troubleshooting.rst000066400000000000000000000006471406573761400236120ustar00rootroot00000000000000Troubleshooting =============== Autocomplete ------------ If autocomplete isn't working after installation, you may be missing the ``readline`` module. Try one of the following depending on your platform: For macOS / linux (the ``readline`` extra): .. code-block:: bash pip install click-shell[readline] For Windows / cygwin (the ``windows`` extra): .. code-block:: bash pip install click-shell[windows] clarkperkins-click-shell-7a94049/docs/usage.rst000066400000000000000000000050571406573761400214670ustar00rootroot00000000000000Usage ===== There are 2 main ways to utilize click-shell: the decorator and the factory method. Decorator --------- The easiest way to get going with click-shell is with the click style decorator. ``@click_shell.shell`` is meant to replace click's ``@click.group`` decorator for the root level of your app. In fact, the object generated by ``@click_shell.shell`` is a ``click_shell.core.Shell`` object, which is a subclass of ``click.core.Group``. .. code-block:: python from click_shell import shell # @click.group() # no longer @shell(prompt='my-app > ', intro='Starting my app...') def my_app(): pass @my_app.command() def testcommand(): print('testcommand is running') # more commands if __name__ == '__main__': my_app() When run with the above arguments, you should expect an output like so: .. code-block:: bash $ python my_app.py Starting my app... my-app > testcommand testcommand is running my-app > ``@shell`` takes 4 arguments: - ``prompt`` - this will get printed as the beginning of each line in the shell. This can take a callable that will be called each time a prompt is printed. On Python 3 ONLY, if the callable takes an argument named ``ctx``, the click context will be passed in as that argument. Defaults to ``'(Cmd) '`` - ``intro`` - this will get printed once when the shell first starts Defaults to ``None``, meaning nothing gets printed - ``hist_file`` - this is the location of the history file used by the shell. Defaults to ``'~/.click-history'`` - ``on_finished`` - a callable that will be called when the shell exits. You can use it to clean up any resources that may need cleaning up. ``@shell`` also takes arbitrary keyword arguments, and they are passed on directly to the constructor for the `click_shell.Shell`` class. Factory Method -------------- If you'd rather not use decorators (or can't for some reason), you can manually create a shell object and start it up: .. code-block:: python import click from click_shell import make_click_shell @click.group() @click.pass_context def my_app(ctx): pass # Somewhere else in your code (as long as you have access to the root level Context object) shell = make_click_shell(ctx, prompt='my-app > ', intro='Starting my app...') shell.cmdloop() The first argument passed to ``make_click_shell`` must be the root level context object for your click application. The other 3 args (prompt, intro, hist_file) are the same as described above under the Decorator section. clarkperkins-click-shell-7a94049/install.sh000077500000000000000000000005571406573761400207060ustar00rootroot00000000000000#!/bin/bash if [ "$TRAVIS_PYTHON_VERSION" == "2.7" ]; then echo "Python 2 detected, installing dependencies with pip" pip install -r requirements-python2.txt else echo "Installing dependencies with pipenv" pip install pipenv --upgrade pipenv install --deploy --dev fi # install the correct version of click for testing pip install "click~=$CLICK_VERSION" clarkperkins-click-shell-7a94049/pyproject.toml000066400000000000000000000001441406573761400216050ustar00rootroot00000000000000[build-system] requires = ["setuptools", "wheel"] build-backend = "setuptools.build_meta:__legacy__"clarkperkins-click-shell-7a94049/readthedocs.yaml000066400000000000000000000010251406573761400220410ustar00rootroot00000000000000# readthedocs.yaml # Read the Docs configuration file # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details # Required version: 2 # Build documentation in the docs/ directory with Sphinx sphinx: builder: html configuration: docs/conf.py # Build documentation with MkDocs #mkdocs: # configuration: mkdocs.yml # Optionally build your docs in additional formats such as PDF and ePub formats: all # Optionally set the version of Python and requirements required to build your docs python: version: 3.5 clarkperkins-click-shell-7a94049/requirements-python2.txt000066400000000000000000000000731406573761400235570ustar00rootroot00000000000000-e . pycodestyle pylint pytest pytest-click<1.0 pytest-cov clarkperkins-click-shell-7a94049/setup.cfg000066400000000000000000000015521406573761400205160ustar00rootroot00000000000000[bdist_wheel] universal=1 [pycodestyle] max_line_length = 100 [mypy] ignore_missing_imports = True [mypy-click_shell._compat] ignore_errors = True [tool:pytest] testpaths = tests # Coverage settings [coverage:run] branch = True [coverage:report] # Regexes for lines to exclude from consideration exclude_lines = # Have to re-enable the standard pragma pragma: no cover # Don't complain about missing debug-only code: def __repr__ if self\.debug # Don't complain if tests don't hit defensive assertion code: raise AssertionError raise NotImplementedError # Don't complain if non-runnable code isn't run: if 0: if __name__ == .__main__.: ignore_errors = True omit = */site-packages/* */python*/* [coverage:html] directory = reports/html title = click-shell coverage [coverage:xml] output = reports/coverage.xml clarkperkins-click-shell-7a94049/setup.py000066400000000000000000000037571406573761400204200ustar00rootroot00000000000000import io import os from setuptools import setup, find_packages def read(rel_path): here = os.path.abspath(os.path.dirname(__file__)) with io.open(os.path.join(here, rel_path), 'r') as fp: return fp.read() def get_version(rel_path): for line in read(rel_path).splitlines(): if line.startswith('__version__'): # __version__ = "0.9" delim = '"' if '"' in line else "'" return line.split(delim)[1] else: raise RuntimeError("Unable to find version string.") SHORT_DESCRIPTION = "An extension to click that easily turns your click app into a shell utility" # Use the README.md as the long description LONG_DESCRIPTION = read('README.rst') requirements = [ 'click>=6.0', ] setup( name='click-shell', version=get_version('click_shell/__init__.py'), url="https://github.com/clarkperkins/click-shell", author="Clark Perkins", author_email="r.clark.perkins@gmail.com", description=SHORT_DESCRIPTION, long_description=LONG_DESCRIPTION, license='BSD', include_package_data=True, packages=find_packages(), zip_safe=False, install_requires=requirements, dependency_links=[], extras_require={ 'readline': ['gnureadline'], 'windows': ['pyreadline'], }, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Topic :: Software Development :: User Interfaces', 'Topic :: System :: Shells', 'Topic :: Utilities', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', ] ) clarkperkins-click-shell-7a94049/sonar-project.properties000066400000000000000000000007671406573761400236100ustar00rootroot00000000000000sonar.projectKey=clarkperkins_click-shell # this is the name and version displayed in the SonarCloud UI. sonar.projectName=click-shell # Path is relative to the sonar-project.properties file. Replace "\" by "/" on Windows. # This property is optional if sonar.modules is set. sonar.sources=click_shell sonar.python.pylint.reportPath=reports/pylint.txt sonar.python.coverage.reportPaths=reports/coverage.xml # Encoding of the source code. Default is default system encoding sonar.sourceEncoding=UTF-8 clarkperkins-click-shell-7a94049/tests/000077500000000000000000000000001406573761400200345ustar00rootroot00000000000000clarkperkins-click-shell-7a94049/tests/test_cmd.py000066400000000000000000000132271406573761400222150ustar00rootroot00000000000000import os import sys from cmd import Cmd import click from click_shell._cmd import ClickCmd from click_shell._compat import PY2 if PY2: from StringIO import StringIO else: from io import StringIO class BadStringIO(StringIO, object): def __init__(self, *args, **kwargs): super(BadStringIO, self).__init__(*args, **kwargs) self.first = True def read(self, *args, **kwargs): if self.first: self.first = False raise KeyboardInterrupt() return super(BadStringIO, self).read(*args, **kwargs) def readline(self, *args, **kwargs): if self.first: self.first = False raise KeyboardInterrupt() return super(BadStringIO, self).readline(*args, **kwargs) def test_create(): cmd = ClickCmd() # Make sure it's a Cmd assert isinstance(cmd, Cmd) # Make sure it's a new-style class assert isinstance(cmd, object) # Make sure we have our exit functions assert hasattr(cmd, 'do_quit') assert hasattr(cmd, 'do_exit') def test_intro_default(cli_runner): with cli_runner.isolation() as outstreams: cmd = ClickCmd(hist_file='.history') cmd.cmdloop() output = outstreams[0].getvalue() \ .decode(cli_runner.charset, 'replace').replace('\r\n', '\n') assert output == '(Cmd) \n' os.remove('.history') def test_intro_custom(cli_runner): for test_in in ('foo', 'bar', 'blah\n version 2'): with cli_runner.isolation() as outstreams: cmd = ClickCmd(hist_file='.history') cmd.cmdloop(test_in) output = outstreams[0].getvalue() \ .decode(cli_runner.charset, 'replace').replace('\r\n', '\n') assert output == '{0}\n(Cmd) \n'.format(test_in) os.remove('.history') def test_prompt(cli_runner): with cli_runner.isolation() as outstreams: cmd = ClickCmd(hist_file='.history') cmd.prompt = 'foobar > ' cmd.cmdloop() output = outstreams[0].getvalue() \ .decode(cli_runner.charset, 'replace').replace('\r\n', '\n') assert output == 'foobar > \n' os.remove('.history') def test_bad_input(cli_runner): with cli_runner.isolation(input='foobar\n') as outstreams: cmd = ClickCmd(hist_file='.history') cmd.cmdloop() output = outstreams[0].getvalue() \ .decode(cli_runner.charset, 'replace').replace('\r\n', '\n') assert output == '{0}{1}\n{0}\n'.format(ClickCmd.prompt, ClickCmd.nocommand % 'foobar') os.remove('.history') def test_empty_input(cli_runner): with cli_runner.isolation(input='\n') as outstreams: cmd = ClickCmd(hist_file='.history') cmd.cmdloop() output = outstreams[0].getvalue() \ .decode(cli_runner.charset, 'replace').replace('\r\n', '\n') assert output == '{0}{0}\n'.format(ClickCmd.prompt) os.remove('.history') def test_quit(cli_runner): with cli_runner.isolation(input='quit\n') as outstreams: cmd = ClickCmd(hist_file='.history') cmd.cmdloop() output = outstreams[0].getvalue() \ .decode(cli_runner.charset, 'replace').replace('\r\n', '\n') assert output == ClickCmd.prompt os.remove('.history') def test_exit(cli_runner): with cli_runner.isolation(input='exit\n') as outstreams: cmd = ClickCmd(hist_file='.history') cmd.cmdloop() output = outstreams[0].getvalue() \ .decode(cli_runner.charset, 'replace').replace('\r\n', '\n') assert output == ClickCmd.prompt os.remove('.history') def test_on_finished(cli_runner): with cli_runner.isolation() as outstreams: def finisher(c): click.echo(c + '#finished') cmd = ClickCmd(ctx='dummy-ctx', hist_file='.history', on_finished=finisher) cmd.cmdloop() output = outstreams[0].getvalue() \ .decode(cli_runner.charset, 'replace').replace('\r\n', '\n') assert output == ClickCmd.prompt + '\ndummy-ctx#finished\n' os.remove('.history') def test_help(cli_runner): with cli_runner.isolation(input='help\n') as outstreams: cmd = ClickCmd(hist_file='.history') cmd.cmdloop() output = outstreams[0].getvalue() \ .decode(cli_runner.charset, 'replace').replace('\r\n', '\n') assert output == '{0}\n' \ 'Undocumented commands:\n' \ '======================\n' \ 'exit help quit\n' \ '\n' \ '{0}\n'.format(ClickCmd.prompt) os.remove('.history') def test_keyboard_interrupt(): stdin = BadStringIO() stdout = StringIO() old_in = sys.stdin old_out = sys.stdout try: sys.stdin = stdin sys.stdout = stdout cmd = ClickCmd(hist_file='.history') cmd.cmdloop() finally: sys.stdin = old_in sys.stdout = old_out assert stdout.getvalue() == '{0}\nKeyboardInterrupt\n{0}\n'.format(ClickCmd.prompt) os.remove('.history') def test_changable_prompt(cli_runner): with cli_runner.isolation(input='\n\n\n') as outstreams: cmd = ClickCmd(hist_file='.history') class Prompt(object): def __init__(self): self.num = 0 def __call__(self): self.num += 1 return "prompt #{} > ".format(self.num) cmd.prompt = Prompt() cmd.cmdloop() output = outstreams[0].getvalue() \ .decode(cli_runner.charset, 'replace').replace('\r\n', '\n') assert output == 'prompt #1 > prompt #2 > prompt #3 > prompt #4 > \n' os.remove('.history') clarkperkins-click-shell-7a94049/tests/test_core.py000066400000000000000000000050041406573761400223740ustar00rootroot00000000000000 from datetime import datetime import click import pytest from click_shell._cmd import ClickCmd from click_shell.core import Shell, make_click_shell, get_invoke class TestShell(object): def test_create(self): shell = Shell() assert isinstance(shell, click.MultiCommand) def test_invoke_no_args(self): shell = Shell() ctx = shell.make_context('click-shell-test', args=[]) with pytest.raises(IOError): shell.invoke(ctx) def test_invoke_with_args(self): shell = Shell() # Create a 'foo' command @shell.command() def foo(): click.echo('bar') return 0 ctx = shell.make_context('click-shell-test', args=['foo']) retcode = shell.invoke(ctx) assert retcode == 0 class TestFactory(object): def test_fail_on_bad_command(self): command = click.Command('test-command') ctx = click.Context(command) with pytest.raises(AssertionError): make_click_shell(ctx) def test_with_group(self): command = click.Group() ctx = click.Context(command) shell = make_click_shell(ctx) assert isinstance(shell, ClickCmd) def test_get_invoke_command(self): time_str = str(datetime.now()) @click.command() def test_command(): click.echo(time_str) return time_str fun = get_invoke(test_command) assert callable(fun) ret = fun(None, '') # Make sure it returned the correct thing assert ret is False def test_get_invoke_group(self): time_str = str(datetime.now()) @click.group(invoke_without_command=True) def main_level(): pass @main_level.group() def test_group(): pass @test_group.command() def foo(): click.echo(time_str) return time_str @test_group.command() def bar(): click.echo('foo') return 'foo' fun = get_invoke(test_group) assert callable(fun) # This should be the help function ret = fun(None, '') assert ret is False # Also help ret = fun(None, '--help') assert ret is False # non-existant ret = fun(None, 'foobar') assert ret is False ret = fun(None, 'foo') assert ret is False ret = fun(None, 'bar') assert ret is False def test_get_help(self): pass clarkperkins-click-shell-7a94049/tests/test_shell.py000066400000000000000000000020261406573761400225540ustar00rootroot00000000000000import click import click_shell # Test shell decorator def test_shell_decorator(cli_runner): @click_shell.shell(prompt='app# ') def app(): pass result = cli_runner.invoke(app) assert result.output == 'app# \n' # Test with one command def test_command_decorator(cli_runner): @click_shell.shell(prompt='app$ ') def app_one_command(): pass @app_one_command.command() def printer(): click.echo('printed') result = cli_runner.invoke(app_one_command, input='printer\n') # Verify the context key dictionary 'param' is printed assert result.output == 'app$ printed\napp$ \n' # Test with finisher def test_on_finished(cli_runner): def finisher(ctx): click.echo(ctx.obj['param']) @click_shell.shell(prompt='app> ', on_finished=finisher) def app_with_finisher(): pass result = cli_runner.invoke(app_with_finisher, obj={'param': 'value'}) # Verify the context key dictionary 'param' is printed assert result.output == 'app> \nvalue\n'