Merge branch 'main' into fix-cli-runner-prompt-eof-handling
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Rowlando13 · committed by GitHub · parents 93c6966, 36deba8 · Browse files · 65 files·+4464 added−2484 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
65 files+4464 added−2484 removed
- tests:+1921 added−150 removed
- other:+2543 added−2334 removed
Provenance
- Commit
e11a1ef- Tree
ccecb38- Author
Rowlando13 <67291205+Rowlando13@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
93c6966- Parent 2
36deba8
65 files changed+4464 added−2484 removed
modified:.github/workflows/pre-commit.yaml+1 added-1 removed
6 unmodified lines7891011111213141510 unmodified lines6 unmodified lines main: runs-on: ubuntu-latest steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - uses: astral-sh/setup-uv@6b9c6063abd6010835644d4c2e1bef4cf5cd0fca # v6.0.1 - uses: astral-sh/setup-uv@f0ec1fc3b38f5e7cd731bb6ce540c5af426746bb # v6.1.0 with: enable-cache: true prune-cache: false - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.010 unmodified linesmodified:.github/workflows/publish.yaml+4 added-22 removed
3 unmodified lines45678989121011121314151617182122231920212728293031323334353622382324252627282945464748303132335234353637387 unmodified lines3 unmodified lines tags: ['*']jobs: build: runs-on: ubuntu-latest outputs: hash: ${{ steps.hash.outputs.hash }} steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - uses: astral-sh/setup-uv@6b9c6063abd6010835644d4c2e1bef4cf5cd0fca # v6.0.1 - uses: astral-sh/setup-uv@f0ec1fc3b38f5e7cd731bb6ce540c5af426746bb # v6.1.0 with: enable-cache: true prune-cache: false - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 with: python-version-file: pyproject.toml - run: echo "SOURCE_DATE_EPOCH=$(git log -1 --pretty=%ct)" >> $GITHUB_ENV - run: uv build - name: generate hash id: hash run: cd dist && echo "hash=$(sha256sum * | base64 -w0)" >> $GITHUB_OUTPUT - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: path: ./dist provenance: needs: [build] permissions: actions: read id-token: write contents: write # Can't pin with hash due to how this workflow works. uses: slsa-framework/slsa-github-generator/.github/workflows/generator_generic_slsa3.yml@v2.1.0 with: base64-subjects: ${{ needs.build.outputs.hash }} create-release: needs: [provenance] needs: [build] runs-on: ubuntu-latest permissions: contents: write steps: - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 - name: create release run: > gh release create --draft --repo ${{ github.repository }} ${{ github.ref_name }} *.intoto.jsonl/* artifact/* run: gh release create --draft --repo ${{ github.repository }} ${{ github.ref_name }} artifact/* env: GH_TOKEN: ${{ github.token }} publish-pypi: needs: [provenance] needs: [build] environment: name: publish url: https://pypi.org/project/click/${{ github.ref_name }} runs-on: ubuntu-latest7 unmodified linesmodified:.github/workflows/tests.yaml+2 added-2 removed
20 unmodified lines212223242525262728293 unmodified lines333435363737383940418 unmodified lines20 unmodified lines - {python: '3.10'} - {name: PyPy, python: 'pypy-3.11', tox: pypy3.11} steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - uses: astral-sh/setup-uv@6b9c6063abd6010835644d4c2e1bef4cf5cd0fca # v6.0.1 - uses: astral-sh/setup-uv@f0ec1fc3b38f5e7cd731bb6ce540c5af426746bb # v6.1.0 with: enable-cache: true prune-cache: false - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.03 unmodified lines typing: runs-on: ubuntu-latest steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - uses: astral-sh/setup-uv@6b9c6063abd6010835644d4c2e1bef4cf5cd0fca # v6.0.1 - uses: astral-sh/setup-uv@f0ec1fc3b38f5e7cd731bb6ce540c5af426746bb # v6.1.0 with: enable-cache: true prune-cache: false - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.08 unmodified linesdeleted:artwork/logo.svg-75 removed
1-<?xml version="1.0" encoding="UTF-8" standalone="no"?>2-<!-- Created with Inkscape (http://www.inkscape.org/) -->3-4-<svg5- xmlns:dc="http://purl.org/dc/elements/1.1/"6- xmlns:cc="http://creativecommons.org/ns#"7- xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"8- xmlns:svg="http://www.w3.org/2000/svg"9- xmlns="http://www.w3.org/2000/svg"10- xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"11- xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"12- width="237.36929"13- height="110.7928"14- id="svg4837"15- version="1.1"16- inkscape:version="0.48.2 r9819"17- sodipodi:docname="New document 8">18- <defs19- id="defs4839" />20- <sodipodi:namedview21- id="base"22- pagecolor="#ffffff"23- bordercolor="#666666"24- borderopacity="1.0"25- inkscape:pageopacity="0.0"26- inkscape:pageshadow="2"27- inkscape:zoom="0.98994949"28- inkscape:cx="259.76814"29- inkscape:cy="40.769955"30- inkscape:document-units="px"31- inkscape:current-layer="layer1"32- showgrid="false"33- fit-margin-top="10"34- fit-margin-left="10"35- fit-margin-right="10"36- fit-margin-bottom="10"37- inkscape:window-width="1676"38- inkscape:window-height="1006"39- inkscape:window-x="4"40- inkscape:window-y="0"41- inkscape:window-maximized="1" />42- <metadata43- id="metadata4842">44- <rdf:RDF>45- <cc:Work46- rdf:about="">47- <dc:format>image/svg+xml</dc:format>48- <dc:type49- rdf:resource="http://purl.org/dc/dcmitype/StillImage" />50- <dc:title></dc:title>51- </cc:Work>52- </rdf:RDF>53- </metadata>54- <g55- inkscape:label="Layer 1"56- inkscape:groupmode="layer"57- id="layer1"58- transform="translate(-255.43458,-207.38101)">59- <path60- style="fill:#000000"61- d="m 466.33424,306.48462 0,-1.6892 3.16724,0 3.16723,0 0,1.6892 0,1.68919 -3.16723,0 -3.16724,0 0,-1.68919 z m -3.37839,-5.06759 0,-3.37839 1.47804,0 1.47805,0 0,3.37839 0,3.37839 -1.47805,0 -1.47804,0 0,-3.37839 z m 10.13516,0 0,-3.37839 1.47804,0 1.47805,0 0,3.37839 0,3.37839 -1.47805,0 -1.47804,0 0,-3.37839 z m -30.82778,-28.92744 0,-28.92744 1.68919,0 c 1.68919,0 1.68919,0 1.68919,1.68919 0,1.6892 0,1.6892 1.6892,1.6892 1.68919,0 1.68919,0 1.68919,1.68919 0,1.6892 0,1.6892 1.6892,1.6892 1.68919,0 1.68919,0 1.68919,1.68919 0,1.6892 0,1.6892 -1.68919,1.6892 -1.6892,0 -1.6892,0 -1.6892,-1.6892 0,-1.68919 0,-1.68919 -1.68919,-1.68919 l -1.6892,0 0,23.85986 0,23.85985 1.6892,0 c 1.68919,0 1.68919,0 1.68919,1.6892 l 0,1.68919 -3.37839,0 -3.37838,0 0,-28.92744 z m 7.00029,25.22951 c -0.13394,-0.13393 -0.24352,-0.87696 -0.24352,-1.65118 0,-1.36423 0.0529,-1.40766 1.71469,-1.40766 l 1.71468,0 -0.13106,1.58362 c -0.12024,1.45279 -0.24178,1.5892 -1.47117,1.65118 -0.73706,0.0372 -1.44968,-0.042 -1.58362,-0.17596 z m 10.14204,-0.0392 c -0.13814,-0.22352 -0.20454,-1.7545 -0.14756,-3.40219 l 0.10361,-2.99581 1.60373,0 1.60374,0 -0.12334,3.27282 -0.12334,3.27281 -1.33284,0.12938 c -0.73305,0.0712 -1.44586,-0.0535 -1.584,-0.27702 z m 10.30707,-3.03247 0,-3.36553 1.47803,0 1.47805,0 0,3.30997 0,3.30996 -1.47805,0.0556 -1.47803,0.0556 0,-3.36553 z m -17.03271,-0.26872 c -0.15484,-0.15483 -0.28153,-0.91497 -0.28153,-1.68919 0,-1.36073 0.0563,-1.40766 1.68919,-1.40766 1.6892,0 1.6892,0 1.6892,1.6892 0,1.63289 -0.0469,1.68919 -1.40766,1.68919 -0.77422,0 -1.53436,-0.12669 -1.6892,-0.28154 z m 3.09686,-4.99719 c 0,-1.44286 0.0402,-1.47804 1.68919,-1.47804 1.64898,0 1.68919,0.0352 1.68919,1.47804 0,1.44285 -0.0402,1.47805 -1.68919,1.47805 -1.64898,0 -1.68919,-0.0352 -1.68919,-1.47805 z m 10.55746,-1.68919 0,-3.16724 6.75677,0 6.75678,0 0,-1.68919 c 0,-1.64898 0.0351,-1.6892 1.47804,-1.6892 l 1.47804,0 0,3.15652 0,3.15651 -6.6512,0.1163 -6.65119,0.1163 -0.13108,1.58361 c -0.12394,1.49763 -0.20994,1.58363 -1.58361,1.58363 l -1.45255,0 0,-3.16724 z m 10.13516,-8.44597 c 0,-1.40766 0.0704,-1.47804 1.47804,-1.47804 1.40766,0 1.47805,0.0704 1.47805,1.47804 0,1.40766 -0.0704,1.47804 -1.47805,1.47804 -1.40766,0 -1.47804,-0.0704 -1.47804,-1.47804 z m -3.37839,-3.37839 c 0,-1.40766 0.0704,-1.47804 1.47804,-1.47804 1.40767,0 1.47805,0.0704 1.47805,1.47804 0,1.40767 -0.0704,1.47805 -1.47805,1.47805 -1.40765,0 -1.47804,-0.0704 -1.47804,-1.47805 z m -3.37838,-3.37839 c 0,-1.40765 0.0704,-1.47804 1.47803,-1.47804 1.40767,0 1.47805,0.0704 1.47805,1.47804 0,1.40767 -0.0704,1.47805 -1.47805,1.47805 -1.40765,0 -1.47803,-0.0704 -1.47803,-1.47805 z m -3.37839,-3.48871 c 0,-1.52897 0.0553,-1.58931 1.47804,-1.61346 1.43567,-0.0244 1.47804,0.0211 1.47804,1.58838 0,1.56241 -0.0467,1.61345 -1.47804,1.61345 -1.42721,0 -1.47804,-0.0546 -1.47804,-1.58837 z m -3.37839,-3.47921 c 0,-1.64897 0.0351,-1.68919 1.47804,-1.68919 1.44285,0 1.47805,0.0402 1.47805,1.68919 0,1.64898 -0.0352,1.6892 -1.47805,1.6892 -1.44285,0 -1.47804,-0.0403 -1.47804,-1.6892 z m -3.45076,-3.37839 c 0.15328,-1.60738 0.23052,-1.68919 1.59478,-1.68919 1.3911,0 1.43368,0.0502 1.43368,1.68919 0,1.67253 -0.0157,1.6892 -1.59478,1.6892 l -1.59477,0 0.16109,-1.6892 z m -3.30601,-3.37838 c 0,-1.64898 0.0351,-1.6892 1.47804,-1.6892 1.44285,0 1.47804,0.0402 1.47804,1.6892 0,1.64897 -0.0352,1.68919 -1.47804,1.68919 -1.44286,0 -1.47804,-0.0402 -1.47804,-1.68919 z m -3.72061,-3.27282 c 0.12395,-1.49762 0.21706,-1.59073 1.71468,-1.71468 l 1.58363,-0.13107 0,1.71469 0,1.71468 -1.71469,0 -1.71468,0 0.13106,-1.58362 z"62- id="path4856"63- inkscape:connector-curvature="0" />64- <path65- style="fill:#000000"66- d="m 271.34527,247.46047 c 0,-1.32826 -0.94153,-2.12734 -3.05297,-2.59109 -4.04056,-0.88746 -3.19986,-3.08429 1.01754,-2.65894 9.32239,0.94022 10.81407,-3.50307 2.60795,-7.76831 -2.71012,-1.40862 -5.36388,-3.27897 -5.89726,-4.15634 -1.47604,-2.42802 -0.0246,-6.42458 2.80076,-7.7119 1.48697,-0.67751 2.52398,-1.98054 2.52398,-3.17144 0,-1.13017 0.66136,-2.02144 1.5,-2.02144 0.825,0 1.5,0.85122 1.5,1.89159 0,1.19765 0.94321,2.12832 2.57104,2.53688 3.91591,0.98283 2.39946,3.10499 -1.95093,2.73019 -6.99788,-0.60291 -8.93527,3.8291 -2.87011,6.5657 9.0905,4.10163 11.015,9.73021 4.5,13.16112 -1.2375,0.65169 -2.25,2.06905 -2.25,3.1497 0,1.08065 -0.675,1.96482 -1.5,1.96482 -0.825,0 -1.5,-0.86425 -1.5,-1.92054 z m 38.357,-3.07104 c -4.57947,-1.84804 -6.77791,-8.48491 -4.32736,-13.06381 2.11183,-3.94599 10.30093,-6.28597 13.9414,-3.98367 2.2687,1.43477 0.36183,2.48777 -3.94232,2.177 -6.96682,-0.50302 -10.61631,6.27447 -5.91184,10.97894 1.71218,1.71218 2.95483,2.02243 6.5,1.62284 3.13626,-0.35351 4.38312,-0.13272 4.38312,0.77613 0,2.4062 -6.21813,3.27822 -10.643,1.49257 z m 21.1997,-1.23093 c -1.16379,-1.66155 -1.5567,-4.81653 -1.5567,-12.5 l 0,-10.27749 -2.5,0 c -1.55556,0 -2.5,-0.56667 -2.5,-1.5 0,-1.08333 1.11111,-1.5 4,-1.5 l 4,0 0.0153,11.25 c 0.008,6.1875 0.41056,11.87411 0.89363,12.63691 0.54214,0.85607 1.88505,1.19446 3.50856,0.88411 2.94677,-0.56331 4.58181,0.98192 2.46061,2.32547 -2.5829,1.63598 -6.70984,0.98184 -8.32141,-1.319 z m 20.4433,0.22251 c -1.55556,-1.55556 -2,-3.33333 -2,-8 0,-5.73333 -0.11111,-6 -2.5,-6 -1.55556,0 -2.5,-0.56667 -2.5,-1.5 0,-1.08333 1.11111,-1.5 4,-1.5 l 4,0 0.0153,6.75 c 0.0183,8.04891 0.82623,9.70461 4.40219,9.02102 2.94677,-0.56331 4.58181,0.98192 2.46061,2.32547 -2.3358,1.47948 -5.78176,0.99986 -7.87811,-1.09649 z m 18.357,1.00842 c -4.57947,-1.84804 -6.77791,-8.48491 -4.32736,-13.06381 2.11183,-3.94599 10.30093,-6.28597 13.9414,-3.98367 2.2687,1.43477 0.36183,2.48777 -3.94232,2.177 -6.96682,-0.50302 -10.61631,6.27447 -5.91184,10.97894 1.71218,1.71218 2.95483,2.02243 6.5,1.62284 3.13626,-0.35351 4.38312,-0.13272 4.38312,0.77613 0,2.4062 -6.21813,3.27822 -10.643,1.49257 z m 15.86478,-12.67646 c 0.20032,-9.84119 0.6282,-13.78431 1.52822,-14.08333 0.9358,-0.31091 1.25628,1.80502 1.275,8.41804 l 0.025,8.83333 4.01111,-4.25 c 2.32594,-2.46446 4.92367,-4.25 6.18321,-4.25 1.8968,0 1.6121,0.57059 -2.24643,4.50214 l -4.41851,4.50213 4.92271,4.99787 c 3.84161,3.90023 4.49929,4.99786 2.99467,4.99786 -1.06044,0 -4.08102,-2.12058 -6.71241,-4.71241 l -4.78435,-4.71241 0,4.71241 c 0,3.56082 -0.37346,4.71241 -1.52822,4.71241 -1.30999,0 -1.48849,-1.95179 -1.25,-13.66804 z m -37.85759,-9.82527 c -0.34636,-0.90262 -0.15025,-2.12063 0.43581,-2.70669 1.52361,-1.52361 4.41041,-0.13109 4.01242,1.93549 -0.4433,2.30188 -3.64766,2.85743 -4.44823,0.7712 z"67- id="path4887"68- inkscape:connector-curvature="0" />69- <path70- style="fill:#000000;fill-opacity:1;stroke:none"71- d="m 411.32164,243.39982 c 7.38153,0.15924 14.76525,0.0821 22.14736,0.0136 -3.6814,3.83663 -9.42739,1.45689 -14.06576,2.07921 -3.69684,-0.007 -7.3939,0.0151 -11.09,0.0923 1.0029,-0.72825 2.00505,-1.45754 3.0084,-2.18514 z"72- id="path4889"73- inkscape:connector-curvature="0" />74- </g>75-</svg>deleted:docs/_static/click-icon.pngbinary
A binary file, deleted.
added:docs/_static/click-icon.svg+11 added
1+<?xml version="1.0" encoding="UTF-8" standalone="no"?>2+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">3+<svg width="100%" height="100%" viewBox="0 0 500 500" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">4+ <rect id="Icon" x="0" y="0" width="500" height="500" style="fill:none;"/>5+ <g>6+ <path d="M448.569,446.761l-66.389,49.07c-3.528,2.565 -8.018,4.169 -12.508,4.169l-136.626,-0c-19.243,-0 -28.223,-23.733 -14.112,-36.562l54.843,-49.07c3.849,-3.528 8.66,-5.452 14.112,-5.452l147.851,-0c20.526,-0 28.865,25.657 12.829,37.845Z" style="fill:#5c549e;fill-rule:nonzero;"/>7+ <path d="M192.956,406.03l-91.404,84.028c-6.415,6.414 -15.074,9.942 -23.734,9.942c-8.659,-0 -17.318,-3.528 -23.733,-9.942c-13.47,-13.47 -13.47,-34.317 0,-47.467l32.713,-36.561l106.158,-0Z" style="fill:#5c549e;fill-rule:nonzero;"/>8+ <path d="M328.299,216.485l-113.855,-102.309l-109.685,-0l124.118,135.343l-124.118,135.343l108.723,-0.321l114.817,-101.988c8.66,-9.301 13.15,-21.167 12.829,-33.355c0.321,-11.225 -4.169,-23.412 -12.829,-32.713Z" style="fill:#5c549e;fill-rule:nonzero;"/>9+ <path d="M191.994,93.97l-91.405,-84.028c-6.414,-6.414 -15.073,-9.942 -23.733,-9.942c-8.659,0 -17.319,3.528 -23.733,9.942c-13.47,13.47 -13.47,34.317 0,47.467l33.034,36.561l105.837,0Z" style="fill:#5c549e;fill-rule:nonzero;"/>10+ </g>11+</svg>deleted:docs/_static/click-logo-sidebar.pngbinary
A binary file, deleted.
deleted:docs/_static/click-logo.pngbinary
A binary file, deleted.
added:docs/_static/click-logo.svg+18 added
1+<?xml version="1.0" encoding="UTF-8" standalone="no"?>2+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">3+<svg width="100%" height="100%" viewBox="0 0 500 500" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">4+ <rect id="Logo" x="0" y="0" width="500" height="500" style="fill:none;"/>5+ <g>6+ <path id="Box" d="M500,50l0,400c0,27.596 -22.404,50 -50,50l-400,0c-27.596,0 -50,-22.404 -50,-50l0,-400c0,-27.596 22.404,-50 50,-50l400,0c27.596,0 50,22.404 50,50Z" style="fill:url(#_Linear1);"/>7+ <path id="Shadow" d="M500,432.911l0,17.089c0,27.596 -22.404,50 -50,50l-211.576,0l-105.636,-105.637c3.812,3.641 8.857,5.637 13.903,5.637c5.196,0 10.391,-2.117 14.24,-5.965l54.843,-50.417l-40.218,-0l-12.701,-12.701l65.234,-0.192l68.891,-61.193c5.195,-5.581 7.889,-12.701 7.697,-20.013c0.192,-6.735 -2.502,-14.048 -7.697,-19.628l203.02,203.02Zm-284.804,-276.529l12.124,12.123l-63.503,0l-12.123,-12.123l63.502,0Zm153.945,211.674c9.622,-7.312 4.619,-22.706 -7.697,-22.706l-88.711,-0c-3.271,-0 -6.157,1.154 -8.467,3.271l-32.905,29.442c-8.467,7.697 -3.079,21.937 8.467,21.937l81.975,0c2.694,0 5.388,-0.962 7.505,-2.502l39.833,-29.442Z" style="fill:#493e5e;"/>8+ <g id="Icon">9+ <path d="M369.141,368.056l-39.833,29.442c-2.117,1.54 -4.811,2.502 -7.505,2.502l-81.975,0c-11.546,0 -16.934,-14.24 -8.467,-21.937l32.905,-29.442c2.31,-2.117 5.196,-3.271 8.467,-3.271l88.711,-0c12.316,-0 17.319,15.394 7.697,22.706Z" style="fill:#fff;fill-rule:nonzero;"/>10+ <path d="M215.774,343.618l-54.843,50.417c-3.849,3.848 -9.044,5.965 -14.24,5.965c-5.196,0 -10.391,-2.117 -14.24,-5.965c-8.082,-8.082 -8.082,-20.59 0,-28.48l19.628,-21.937l63.695,-0Z" style="fill:#fff;fill-rule:nonzero;"/>11+ <path d="M296.98,229.891l-68.313,-61.386l-65.812,0l74.471,81.206l-74.471,81.206l65.234,-0.192l68.891,-61.193c5.195,-5.581 7.889,-12.701 7.697,-20.013c0.192,-6.735 -2.502,-14.048 -7.697,-19.628Z" style="fill:#fff;fill-rule:nonzero;"/>12+ <path d="M215.196,156.382l-54.842,-50.417c-3.849,-3.848 -9.045,-5.965 -14.24,-5.965c-5.196,0 -10.392,2.117 -14.24,5.965c-8.082,8.082 -8.082,20.59 -0,28.48l19.82,21.937l63.502,0Z" style="fill:#fff;fill-rule:nonzero;"/>13+ </g>14+ </g>15+ <defs>16+ <linearGradient id="_Linear1" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(3.06162e-14,500,-500,3.06162e-14,267.59,0)"><stop offset="0" style="stop-color:#d8a9ca;stop-opacity:1"/><stop offset="1" style="stop-color:#53519b;stop-opacity:1"/></linearGradient>17+ </defs>18+</svg>added:docs/_static/click-name.svg+24 added
1+<?xml version="1.0" encoding="UTF-8" standalone="no"?>2+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">3+<svg width="100%" height="100%" viewBox="0 0 679 300" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">4+ <g>5+ <path id="Name" d="M410.6,166.725l19.35,0c0,13.6 -3.4,24.05 -10.2,31.35c-6.8,7.3 -16.4,10.95 -28.8,10.95c-27.3,0 -40.95,-16.05 -40.95,-48.15l0,-9c0,-25.3 7,-41.15 21,-47.55c5.5,-2.6 12.15,-3.9 19.95,-3.9c11.4,0 20.675,3.125 27.825,9.375c7.15,6.25 10.725,15.275 10.725,27.075l-19.5,0c-1.1,-5.9 -3.05,-10.35 -5.85,-13.35c-2.8,-3 -7.2,-4.5 -13.2,-4.5c-7,0 -12.2,2.2 -15.6,6.6c-2.4,3.1 -3.8,8.4 -4.2,15.9c-0.2,2.4 -0.3,5.65 -0.3,9.75l0,9.3c0,11.5 1.6,19.35 4.8,23.55c3.3,4.2 8.425,6.3 15.375,6.3c6.95,0 11.75,-1.925 14.4,-5.775c2.65,-3.85 4.375,-9.825 5.175,-17.925Z" style="fill-rule:nonzero;"/>6+ <path d="M464.9,208.125l-19.5,0.15l0,-112.95l19.5,0l0,112.8Z" style="fill-rule:nonzero;"/>7+ <path d="M495.8,89.775c4.7,0 7.75,0.725 9.15,2.175c1.4,1.45 2.1,4.5 2.1,9.15c0,4.65 -0.725,7.7 -2.175,9.15c-1.45,1.45 -4.5,2.175 -9.15,2.175c-4.65,0 -7.7,-0.75 -9.15,-2.25c-1.45,-1.5 -2.175,-4.55 -2.175,-9.15c0,-4.6 0.725,-7.625 2.175,-9.075c1.45,-1.45 4.525,-2.175 9.225,-2.175Zm9.6,118.35l-19.5,0l0,-82.5l19.5,0l0,82.5Z" style="fill-rule:nonzero;"/>8+ <path d="M570.95,176.775l17.7,-0.15c-0.1,0.8 -0.2,2.25 -0.3,4.35c-0.1,2.1 -0.175,3.525 -0.225,4.275c-0.05,0.75 -0.175,1.925 -0.375,3.525c-0.2,1.6 -0.425,2.775 -0.675,3.525c-0.25,0.75 -0.575,1.725 -0.975,2.925c-1.8,5.2 -6.7,9.3 -14.7,12.3c-5.1,1.8 -10.425,2.7 -15.975,2.7c-5.55,-0 -10.575,-0.9 -15.075,-2.7c-4.5,-1.8 -8.05,-4.1 -10.65,-6.9c-5.9,-6.2 -8.85,-17.825 -8.85,-34.875c0,-17.05 2.95,-28.675 8.85,-34.875c2.6,-2.8 6.15,-5.1 10.65,-6.9c4.5,-1.8 9.5,-2.7 15,-2.7c10.8,0 19,2.7 24.6,8.1c5.6,5.4 8.4,12.9 8.4,22.5l-17.7,0c0,-4.4 -1.1,-7.675 -3.3,-9.825c-2.2,-2.15 -6.275,-3.225 -12.225,-3.225c-5.95,-0 -9.9,1.85 -11.85,5.55c-1.95,3.7 -2.925,9.25 -2.925,16.65l0,7.8c0,11.9 2.3,19.2 6.9,21.9c2.1,1.3 4.85,1.95 8.25,1.95c3.4,-0 6.175,-0.325 8.325,-0.975c2.15,-0.65 3.7,-1.775 4.65,-3.375c0.95,-1.6 1.575,-3.175 1.875,-4.725c0.3,-1.55 0.5,-3.825 0.6,-6.825Z" style="fill-rule:nonzero;"/>9+ <path d="M678.65,208.125l-23.4,0l-22.5,-30.3l-8.55,12.15l0,18.15l-19.5,0l0,-112.8l19.5,0l0,71.25l27.3,-40.65l22.05,0l-28.05,38.4l33.15,43.8Z" style="fill-rule:nonzero;"/>10+ <g id="Logo">11+ <path id="Box" d="M300,30l0,240c0,16.557 -13.443,30 -30,30l-240,-0c-16.557,-0 -30,-13.443 -30,-30l0,-240c0,-16.557 13.443,-30 30,-30l240,0c16.557,0 30,13.443 30,30Z" style="fill:url(#_Linear1);"/>12+ <path id="Shadow" d="M300,259.747l0,10.253c0,16.557 -13.443,30 -30,30l-126.946,-0l-63.381,-63.382c2.287,2.184 5.314,3.382 8.342,3.382c3.117,0 6.234,-1.27 8.544,-3.579l32.905,-30.25l-24.131,-0l-7.62,-7.621l39.141,-0.115l41.334,-36.716c3.117,-3.348 4.734,-7.62 4.618,-12.008c0.116,-4.041 -1.501,-8.428 -4.618,-11.776l121.812,121.812Zm-170.882,-165.918l7.274,7.274l-38.102,0l-7.273,-7.274l38.101,0Zm92.367,127.005c5.773,-4.388 2.771,-13.624 -4.619,-13.624l-53.226,-0c-1.963,-0 -3.695,0.693 -5.08,1.963l-19.744,17.665c-5.08,4.618 -1.847,13.162 5.081,13.162l49.185,0c1.616,0 3.233,-0.577 4.503,-1.501l23.9,-17.665Z" style="fill:#493e5e;"/>13+ <g id="Icon">14+ <path d="M221.485,220.834l-23.9,17.665c-1.27,0.924 -2.887,1.501 -4.503,1.501l-49.185,0c-6.928,0 -10.161,-8.544 -5.081,-13.162l19.744,-17.665c1.385,-1.27 3.117,-1.963 5.08,-1.963l53.226,-0c7.39,-0 10.392,9.236 4.619,13.624Z" style="fill:#fff;fill-rule:nonzero;"/>15+ <path d="M129.464,206.171l-32.905,30.25c-2.31,2.309 -5.427,3.579 -8.544,3.579c-3.118,0 -6.235,-1.27 -8.544,-3.579c-4.85,-4.849 -4.85,-12.354 -0,-17.088l11.776,-13.162l38.217,-0Z" style="fill:#fff;fill-rule:nonzero;"/>16+ <path d="M178.188,137.935l-40.988,-36.832l-39.487,0l44.683,48.724l-44.683,48.723l39.141,-0.115l41.334,-36.716c3.117,-3.348 4.734,-7.62 4.618,-12.008c0.116,-4.041 -1.501,-8.428 -4.618,-11.776Z" style="fill:#fff;fill-rule:nonzero;"/>17+ <path d="M129.118,93.829l-32.906,-30.25c-2.309,-2.309 -5.426,-3.579 -8.544,-3.579c-3.117,0 -6.235,1.27 -8.544,3.579c-4.849,4.849 -4.849,12.354 0,17.088l11.893,13.162l38.101,0Z" style="fill:#fff;fill-rule:nonzero;"/>18+ </g>19+ </g>20+ </g>21+ <defs>22+ <linearGradient id="_Linear1" x1="0" y1="0" x2="1" y2="0" gradientUnits="userSpaceOnUse" gradientTransform="matrix(1.83697e-14,300,-300,1.83697e-14,160.554,0)"><stop offset="0" style="stop-color:#d8a9ca;stop-opacity:1"/><stop offset="1" style="stop-color:#53519b;stop-opacity:1"/></linearGradient>23+ </defs>24+</svg>modified:docs/conf.py+2 added-2 removed
49 unmodified lines50 "**": ["localtoc.html", "relations.html", "searchbox.html", "ethicalads.html"],51 }52 singlehtml_sidebars = {"index": ["project.html", "localtoc.html", "ethicalads.html"]}53 html_static_path = ["_static"]54-html_favicon = "_static/click-icon.png"55-html_logo = "_static/click-logo-sidebar.png"54+html_favicon = "_static/click-icon.svg"55+html_logo = "_static/click-logo.svg"56 html_title = f"Click Documentation ({version})"57 html_show_sourcelink = Falseadded:docs/contrib.md+45 added
1+(contrib)=2+3+# click-contrib4+5+As the user number of Click grows, more and more major feature requests are6+made. To users, it may seem reasonable to include those features with Click;7+however, many of them are experimental or aren't practical to support8+generically. Maintainers have to choose what is reasonable to maintain in Click9+core.10+11+The [click-contrib](https://github.com/click-contrib/) GitHub organization exists as a place to collect third-party12+packages that extend Click's features. It is also meant to ease the effort of13+searching for such extensions.14+15+Please note that the quality and stability of those packages may be different16+from Click itself. While published under a common organization, they are still17+separate from Click and the Pallets maintainers.18+19+## Third-party projects20+21+Other projects that extend Click's features are available outside the22+[click-contrib](https://github.com/click-contrib/) organization.23+24+Some of the most popular and actively maintained are listed below:25+26+| Project | Description | Popularity | Activity |27+|---------------------------------------------------------|--------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------|28+| [Typer](https://github.com/fastapi/typer) | Use Python type hints to create CLI apps. |  |  |29+| [rich-click](https://github.com/ewels/rich-click) | Format help output with Rich. |  |  |30+| [click-app](https://github.com/simonw/click-app) | Cookiecutter template for creating new CLIs. |  |  |31+| [Cloup](https://github.com/janluke/cloup) | Adds option groups, constraints, command aliases, help themes, suggestions and more. |  |  |32+| [Click Extra](https://github.com/kdeldycke/click-extra) | Cloup + colorful `--help`, `--config`, `--show-params`, `--verbosity` options, etc. |  |  |33+34+```{note}35+To make it into the list above, a project:36+37+- must be actively maintained (at least one commit in the last year)38+- must have a reasonable number of stars (at least 20)39+40+If you have a project that meets these criteria, please open a pull request41+to add it to the list.42+43+If a project is no longer maintained or does not meet the criteria above,44+please open a pull request to remove it from the list.45+```deleted:docs/contrib.rst-58 removed
1-.. _contrib:2-3-=============4-click-contrib5-=============6-7-As the number of users of Click grows, more and more major feature requests are8-made. To users it may seem reasonable to include those features with Click;9-however, many of them are experimental or aren't practical to support10-generically. Maintainers have to choose what is reasonable to maintain in Click11-core.12-13-The click-contrib_ GitHub organization exists as a place to collect third-party14-packages that extend Click's features. It is also meant to ease the effort of15-searching for such extensions.16-17-Please note that the quality and stability of those packages may be different18-than Click itself. While published under a common organization, they are still19-separate from Click and the Pallets maintainers.20-21-22-Third-party projects23---------------------24-25-Other projects that extend Click's features are available outside of the26-click-contrib_ organization.27-28-Some of the most popular and actively maintained are listed below:29-30-========================================================== =========================================================================================== ================================================================================================= ======================================================================================================31-Project Description Popularity Activity32-========================================================== =========================================================================================== ================================================================================================= ======================================================================================================33-`Typer <https://github.com/fastapi/typer>`_ Use Python type hints to create CLI apps. .. image:: https://img.shields.io/github/stars/fastapi/typer?label=%20&style=flat-square .. image:: https://img.shields.io/github/last-commit/fastapi/typer?label=%20&style=flat-square34- :alt: GitHub stars :alt: Last commit35-`rich-click <https://github.com/ewels/rich-click>`_ Format help outputwith Rich. .. image:: https://img.shields.io/github/stars/ewels/rich-click?label=%20&style=flat-square .. image:: https://img.shields.io/github/last-commit/ewels/rich-click?label=%20&style=flat-square36- :alt: GitHub stars :alt: Last commit37-`click-app <https://github.com/simonw/click-app>`_ Cookiecutter template for creating new CLIs. .. image:: https://img.shields.io/github/stars/simonw/click-app?label=%20&style=flat-square .. image:: https://img.shields.io/github/last-commit/simonw/click-app?label=%20&style=flat-square38- :alt: GitHub stars :alt: Last commit39-`Cloup <https://github.com/janluke/cloup>`_ Adds option groups, constraints, command aliases, help themes, suggestions and more. .. image:: https://img.shields.io/github/stars/janluke/cloup?label=%20&style=flat-square .. image:: https://img.shields.io/github/last-commit/janluke/cloup?label=%20&style=flat-square40- :alt: GitHub stars :alt: Last commit41-`Click Extra <https://github.com/kdeldycke/click-extra>`_ Cloup + colorful ``--help``, ``--config``, ``--show-params``, ``--verbosity`` options, etc. .. image:: https://img.shields.io/github/stars/kdeldycke/click-extra?label=%20&style=flat-square .. image:: https://img.shields.io/github/last-commit/kdeldycke/click-extra?label=%20&style=flat-square42- :alt: GitHub stars :alt: Last commit43-========================================================== =========================================================================================== ================================================================================================= ======================================================================================================44-45-.. note::46-47- To make it into the list above, a project:48-49- - must be actively maintained (at least one commit in the last year)50- - must have a reasonable number of stars (at least 20)51-52- If you have a project that meets these criteria, please open a pull request53- to add it to the list.54-55- If a project is no longer maintained or does not meet the criteria above,56- please open a pull request to remove it from the list.57-58-.. _click-contrib: https://github.com/click-contrib/added:docs/documentation.md+277 added
1+# Help Pages2+3+```{currentmodule} click4+```5+6+Click makes it very easy to document your command line tools. For most things Click automatically generates help pages for you. By design the text is customizable, but the layout is not.7+8+## Help Texts9+10+Commands and options accept help arguments. For commands, the docstring of the function is automatically used if provided.11+12+Simple example:13+14+```{eval-rst}15+.. click:example::16+17+ @click.command()18+ @click.argument('name')19+ @click.option('--count', default=1, help='number of greetings')20+ def hello(name: str, count: int):21+ """This script prints hello and a name one or more times."""22+ for x in range(count):23+ if name:24+ click.echo(f"Hello {name}!")25+ else:26+ click.echo("Hello!")27+28+.. click:run::29+ invoke(hello, args=['--help'])30+```31+32+## Command Short Help33+34+For subcommands, a short help snippet is generated. By default, it's the first sentence of the docstring. If too long, then it will ellipsize what cannot be fit on a single line with `...`. The short help snippet can also be overridden with `short_help`:35+36+```{eval-rst}37+.. click:example::38+39+ import click40+41+ @click.group()42+ def cli():43+ """A simple command line tool."""44+45+ @cli.command('init', short_help='init the repo')46+ def init():47+ """Initializes the repository."""48+49+.. click:run::50+ invoke(cli, args=['--help'])51+```52+53+## Command Epilog Help54+55+The help epilog is printed at the end of the help and is useful for showing example command usages or referencing additional help resources.56+57+```{eval-rst}58+.. click:example::59+60+ import click61+62+ @click.command(63+ epilog='See https://example.com for more details',64+ )65+ def init():66+ """Initializes the repository."""67+68+.. click:run::69+ invoke(init, args=['--help'])70+```71+72+(documenting-arguments)=73+74+## Documenting Arguments75+76+{class}`click.argument` does not take a `help` parameter. This follows the Unix Command Line Tools convention of using arguments only for necessary things and documenting them in the command help text77+by name. This should then be done via the docstring.78+79+A brief example:80+81+```{eval-rst}82+.. click:example::83+84+ @click.command()85+ @click.argument('filename')86+ def touch(filename):87+ """Print FILENAME."""88+ click.echo(filename)89+90+.. click:run::91+ invoke(touch, args=['--help'])92+```93+94+Or more explicitly:95+96+```{eval-rst}97+.. click:example::98+99+ @click.command()100+ @click.argument('filename')101+ def touch(filename):102+ """Print FILENAME.103+104+ FILENAME is the name of the file to check.105+ """106+ click.echo(filename)107+108+.. click:run::109+ invoke(touch, args=['--help'])110+```111+112+## Showing Defaults113+114+To control the appearance of defaults pass `show_default`.115+116+```{eval-rst}117+.. click:example::118+119+ @click.command()120+ @click.option('--n', default=1, show_default=False, help='number of dots')121+ def dots(n):122+ click.echo('.' * n)123+124+.. click:run::125+ invoke(dots, args=['--help'])126+```127+128+For single option boolean flags, the default remains hidden if the default value is False, even if show default is set to true.129+130+```{eval-rst}131+.. click:example::132+133+ @click.command()134+ @click.option('--n', default=1, show_default=True)135+ @click.option("--gr", is_flag=True, show_default=True, default=False, help="Greet the world.")136+ @click.option("--br", is_flag=True, show_default=True, default=True, help="Add a thematic break")137+ def dots(n, gr, br):138+ if gr:139+ click.echo('Hello world!')140+ click.echo('.' * n)141+ if br:142+ click.echo('-' * n)143+144+.. click:run::145+ invoke(dots, args=['--help'])146+```147+148+## Click's Wrapping Behavior149+150+Click's default wrapping ignores single new lines and rewraps the text based on the width of the terminal to a maximum of 80 characters by default, but this can be modified with {attr}`~Context.max_content_width`. In the example notice how the second grouping of three lines is rewrapped into a single paragraph.151+152+```{eval-rst}153+.. click:example::154+155+ import click156+157+ @click.command()158+ def cli():159+ """160+ This is a very long paragraph and as you161+ can see wrapped very early in the source text162+ but will be rewrapped to the terminal width in163+ the final output.164+165+ This is166+ a paragraph167+ that is compacted.168+ """169+170+.. click:run::171+ invoke(cli, args=['--help'])172+```173+174+## Escaping Click's Wrapping175+176+Sometimes Click's wrapping can be a problem, such as when showing code examples where new lines are significant. This behavior can be escaped on a per-paragraph basis by adding a line with only `\b` . The `\b` is removed from the rendered help text.177+178+Example:179+180+```{eval-rst}181+.. click:example::182+183+ import click184+185+ @click.command()186+ def cli():187+ """First paragraph.188+189+ \b190+ This is191+ a paragraph192+ without rewrapping.193+194+ And this is a paragraph195+ that will be rewrapped again.196+ """197+198+.. click:run::199+ invoke(cli, args=['--help'])200+```201+202+To change the rendering maximum width, pass `max_content_width` when calling the command.203+204+```bash205+cli(max_content_width=120)206+```207+208+## Truncating Help Texts209+210+Click gets {class}`Command` help text from the docstring. If you do not want to include part of the docstring, add the `\f` escape marker to have Click truncate the help text after the marker.211+212+Example:213+214+```{eval-rst}215+.. click:example::216+217+ import click218+219+ @click.command()220+ def cli():221+ """First paragraph.222+ \f223+224+ Words to not be included.225+ """226+227+.. click:run::228+ invoke(cli, args=['--help'])229+```230+231+(doc-meta-variables)=232+233+## Placeholder / Meta Variable234+235+The default placeholder variable ([meta variable](https://en.wikipedia.org/wiki/Metasyntactic_variable#IETF_Requests_for_Comments)) in the help pages is the parameter name in uppercase with underscores. This can be changed for Commands and Parameters with the `options_metavar` and `metavar` kwargs.236+237+```{eval-rst}238+.. click:example::239+240+ # This controls entry on the usage line.241+ @click.command(options_metavar='[[options]]')242+ @click.option('--count', default=1, help='number of greetings',243+ metavar='<int>')244+ @click.argument('name', metavar='<name>')245+ def hello(name: str, count: int) -> None:246+ """This script prints 'hello <name>' a total of <count> times."""247+ for x in range(count):248+ click.echo(f"Hello {name}!")249+250+# Example usage:251+252+.. click:run::253+ invoke(hello, args=['--help'])254+255+```256+257+## Help Parameter Customization258+259+Help parameters are automatically added by Click for any command. The default is `--help` but can be overridden by the context setting {attr}`~Context.help_option_names`. Click also performs automatic conflict resolution on the default help parameter, so if a command itself implements a parameter named `help` then the default help will not be run.260+261+This example changes the default parameters to `-h` and `--help`262+instead of just `--help`:263+264+```{eval-rst}265+.. click:example::266+267+ import click268+269+ CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])270+271+ @click.command(context_settings=CONTEXT_SETTINGS)272+ def cli():273+ pass274+275+.. click:run::276+ invoke(cli, ['-h'])277+```deleted:docs/documentation.rst-267 removed
1-Help Pages2-===================3-4-.. currentmodule:: click5-6-Click makes it very easy to document your command line tools. For most things Click automatically generates help pages for you. By design the text is customizable, but the layout is not.7-8-Help Texts9---------------10-11-Commands and options accept help arguments. For commands, the docstring of the function is automatically used if provided.12-13-Simple example:14-15-.. click:example::16-17- @click.command()18- @click.argument('name')19- @click.option('--count', default=1, help='number of greetings')20- def hello(name: str, count: int):21- """This script prints hello and a name one or more times."""22- for x in range(count):23- if name:24- click.echo(f"Hello {name}!")25- else:26- click.echo("Hello!")27-28-.. click:run::29-30- invoke(hello, args=['--help'])31-32-33-Command Short Help34-------------------35-36-For subcommands, a short help snippet is generated. By default, it's the first sentence of the docstring. If too long, then it will ellipsize what cannot be fit on a single line with ``...``. The short help snippet can also be overridden with ``short_help``:37-38-.. click:example::39-40- @click.group()41- def cli():42- """A simple command line tool."""43-44- @cli.command('init', short_help='init the repo')45- def init():46- """Initializes the repository."""47-48-49-.. click:run::50-51- invoke(cli, args=['--help'])52-53-Command Epilog Help54--------------------55-56-The help epilog is printed at the end of the help and is useful for showing example command usages or referencing additional help resources.57-58-.. click:example::59-60- @click.command(61- epilog='See https://example.com for more details',62- )63- def init():64- """Initializes the repository."""65-66-67-.. click:run::68-69- invoke(init, args=['--help'])70-71-.. _documenting-arguments:72-73-Documenting Arguments74-----------------------75-76-:class:`click.argument` does not take a ``help`` parameter. This follows the Unix Command Line Tools convention of using arguments only for necessary things and documenting them in the command help text77-by name. This should then be done via the docstring.78-79-A brief example:80-81-.. click:example::82-83- @click.command()84- @click.argument('filename')85- def touch(filename):86- """Print FILENAME."""87- click.echo(filename)88-89-90-.. click:run::91-92- invoke(touch, args=['--help'])93-94-Or more explicitly:95-96-.. click:example::97-98- @click.command()99- @click.argument('filename')100- def touch(filename):101- """Print FILENAME.102-103- FILENAME is the name of the file to check.104- """105- click.echo(filename)106-107-.. click:run::108-109- invoke(touch, args=['--help'])110-111-112-Showing Defaults113----------------------------114-To control the appearance of defaults pass ``show_default``.115-116-.. click:example::117-118- @click.command()119- @click.option('--n', default=1, show_default=False, help='number of dots')120- def dots(n):121- click.echo('.' * n)122-123-.. click:run::124-125- invoke(dots, args=['--help'])126-127-For single option boolean flags, the default remains hidden if the default value is False even if show default is true.128-129-.. click:example::130-131- @click.command()132- @click.option('--n', default=1, show_default=True)133- @click.option("--gr", is_flag=True, show_default=True, default=False, help="Greet the world.")134- @click.option("--br", is_flag=True, show_default=True, default=True, help="Add a thematic break")135- def dots(n, gr, br):136- if gr:137- click.echo('Hello world!')138- click.echo('.' * n)139- if br:140- click.echo('-' * n)141-142-.. click:run::143-144- invoke(dots, args=['--help'])145-146-147-Click's Wrapping Behavior148-----------------------------149-Click's default wrapping ignores single new lines and rewraps the text based on the width of the terminal, to a maximum of 80 characters. In the example notice how the second grouping of three lines is rewrapped into a single paragraph.150-151-.. click:example::152-153- @click.command()154- def cli():155- """156- This is a very long paragraph and as you157- can see wrapped very early in the source text158- but will be rewrapped to the terminal width in159- the final output.160-161- This is162- a paragraph163- that is compacted.164- """165-166-.. click:run::167-168- invoke(cli, args=['--help'])169-170-Escaping Click's Wrapping171----------------------------172-Sometimes Click's wrapping can be a problem, such as when showing code examples where newlines are significant. This behavior can be escaped on a per-paragraph basis by adding a line with only ``\b`` . The ``\b`` is removed from the rendered help text.173-174-Example:175-176-.. click:example::177-178- @click.command()179- def cli():180- """First paragraph.181-182- \b183- This is184- a paragraph185- without rewrapping.186-187- And this is a paragraph188- that will be rewrapped again.189- """190-191-192-.. click:run::193-194- invoke(cli, args=['--help'])195-196-To change the rendering maximum width, pass ``max_content_width`` when calling the command.197-198-.. code-block:: python199-200- cli(max_content_width=120)201-202-.. _doc-meta-variables:203-204-Truncating Help Texts205----------------------206-207-Click gets :class:`Command` help text from the docstring. If you do not want to include part of the docstring, add the ``\f`` escape marker to have Click truncate the help text after the marker.208-209-Example:210-211-.. click:example::212-213- @click.command()214- def cli():215- """First paragraph.216- \f217-218- Words to not be included.219- """220-221-.. click:run::222-223- invoke(cli, args=['--help'])224-225-226-Placeholder / Meta Variable227------------------------------228-229-The default placeholder variable (`meta variable <https://en.wikipedia.org/wiki/Metasyntactic_variable#IETF_Requests_for_Comments>`_) in the help pages is the parameter name in uppercase with underscores. This can be changed for Commands and Parameters with the ``options_metavar`` and ``metavar`` kwargs.230-231-.. click:example::232-233- # This controls entry on the usage line.234- @click.command(options_metavar='[[options]]')235- @click.option('--count', default=1, help='number of greetings',236- metavar='<int>')237- @click.argument('name', metavar='<name>')238- def hello(name: str, count: int) -> None:239- """This script prints 'hello <name>' a total of <count> times."""240- for x in range(count):241- click.echo(f"Hello {name}!")242-243-Example:244-245-.. click:run::246-247- invoke(hello, args=['--help'])248-249-Help Parameter Customization250-----------------------------251-Help parameters are automatically added by Click for any command. The default is ``--help`` but can be override by the context setting :attr:`~Context.help_option_names`. Click also performs automatic conflict resolution on the default help parameter so if a command itself implements a parameter named ``help`` then the default help will not be run.252-253-This example changes the default parameters to ``-h`` and ``--help``254-instead of just ``--help``:255-256-.. click:example::257-258- CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])259-260- @click.command(context_settings=CONTEXT_SETTINGS)261- def cli():262- pass263-264-265-.. click:run::266-267- invoke(cli, ['-h'])modified:docs/entry-points.rst+2 added-2 removed
1 Packaging Entry Points2 ======================3 4 It's recommended to write command line utilities as installable packages with5-entry points instead telling users to run ``python hello.py``.5+entry points instead of telling users to run ``python hello.py``.6 7 A distribution package is a ``.whl`` file you install with pip or another Python8 installer. You use a ``pyproject.toml`` file to describe the project and how it9 is built into a package. You might upload this package to PyPI, or distribute it44 unmodified lines54 "click>=8.1",55 ]56 57 [project.scripts]58- hello = "hello:cli"58+ hello = "hello.hello:cli"59 60 [build-system]61 requires = ["flit_core<4"]62 build-backend = "flit_core.buildapi"25 unmodified linesmodified:docs/index.rst+9 added-10 removed
1 unmodified line2 3 Welcome to Click4 ================5 6-.. image:: _static/click-logo.png6+.. image:: _static/click-name.svg7 :align: center8- :scale: 50%9- :target: https://palletsprojects.com/p/click/8+ :height: 200px9 10 Click is a Python package for creating beautiful command line interfaces11 in a composable way with as little code as necessary. It's the "Command12 Line Interface Creation Kit". It's highly configurable but comes with43 unmodified lines56 57 pip install click58 59 Documentation61--------------60+==============61 62 .. toctree::63 :maxdepth: 264 65 faqs66 67 Tutorials69-^^^^^^^^^^^^^68+------------69 .. toctree::70 :maxdepth: 171 72 quickstart73 virtualenv74 75 How to Guides77-^^^^^^^^^^^^^76+---------------77 .. toctree::78 :maxdepth: 179 80 entry-points81 setuptools82 support-multiple-versions83 84 Conceptual Guides86-^^^^^^^^^^^^^^^^^^^85+-------------------86 .. toctree::87 :maxdepth: 188 89 why90 click-concepts91 92 General Reference94-^^^^^^^^^^^^^^^^^^^93+--------------------94 95 .. toctree::96 :maxdepth: 197 17 unmodified lines115 unicode-support116 wincmd117 118 API Reference120-^^^^^^^^^^^^^^^119+-------------------120 121 .. toctree::122 :maxdepth: 2123 124 api125 126 About Project128--------------------127+===============128 129 * This documentation is structured according to `Diataxis <https://diataxis.fr/>`_130 131 * `Version Policy <https://palletsprojects.com/versions>`_11 unmodified linesdeleted:docs/make.bat-36 removed
1-@ECHO OFF2-3-pushd %~dp04-5-REM Command file for Sphinx documentation6-7-if "%SPHINXBUILD%" == "" (8- set SPHINXBUILD=sphinx-build9-)10-set SOURCEDIR=.11-set BUILDDIR=_build12-set SPHINXPROJ=Jinja13-14-if "%1" == "" goto help15-16-%SPHINXBUILD% >NUL 2>NUL17-if errorlevel 9009 (18- echo.19- echo.The 'sphinx-build' command was not found. Make sure you have Sphinx20- echo.installed, then set the SPHINXBUILD environment variable to point21- echo.to the full path of the 'sphinx-build' executable. Alternatively you22- echo.may add the Sphinx directory to PATH.23- echo.24- echo.If you don't have Sphinx installed, grab it from25- echo.http://sphinx-doc.org/26- exit /b 127-)28-29-%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%30-goto end31-32-:help33-%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%34-35-:end36-popddeleted:docs/Makefile-20 removed
1-# Minimal makefile for Sphinx documentation2-#3-4-# You can set these variables from the command line.5-SPHINXOPTS =6-SPHINXBUILD = sphinx-build7-SPHINXPROJ = Jinja8-SOURCEDIR = .9-BUILDDIR = _build10-11-# Put it first so that "make" without argument is like "make help".12-help:13- @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)14-15-.PHONY: help Makefile16-17-# Catch-all target: route all unknown targets to Sphinx using the new18-# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).19-%: Makefile20- @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)modified:docs/options.md+53 added-7 removed
150 unmodified lines151 (tuple-type)=152 153 ## Multi Value Options as Tuples154 155-:::{versionadded} 4.0156-:::155+```{versionadded} 4.0156+```157 158 As you can see that by using `nargs` set to a specific number each item in159 the resulting tuple is of the same type. This might not be what you want.160 Commonly you might want to use different types for different indexes in127 unmodified lines288 def log(debug):289 click.echo(f"debug={debug}")290 ```291 292-:::{versionchanged} 6.0293-:::292+```{versionchanged} 6.0293+```294 295 If you want to define an alias for the second option only, then you will need to use leading whitespace to disambiguate the format string.296 297 ```{eval-rst}15 unmodified lines313 ```314 315 ## Flag Value316 317-To have an flag pass a value to the underlying function set `flag_value`. This automatically sets `is_flag=True`. To set a default flag, set `default=True`. Setting flag values can be used to create patterns like this:317+To have an flag pass a value to the underlying function set `flag_value`. This automatically sets `is_flag=True`. To mark the flag as default, set `default=True`. Setting flag values can be used to create patterns like this:318 319 ```{eval-rst}320 .. click:example::321 12 unmodified lines334 invoke(info, args=['--lower'])335 invoke(info)336 ```337 338+````{note}339+The `default` value is given to the underlying function as-is. So if you set `default=None`, the value passed to the function is the `None` Python value. Same for any other type.340+341+But there is a special case for flags. If a flag has a `flag_value`, then setting `default=True` is interpreted as *the flag should be activated by default*. So instead of the underlying function receiving the `True` Python value, it will receive the `flag_value`.342+343+Which means, in example above, this option:344+345+```python346+@click.option('--upper', 'transformation', flag_value='upper', default=True)347+```348+349+is equivalent to:350+351+```python352+@click.option('--upper', 'transformation', flag_value='upper', default='upper')353+```354+355+Because the two are equivalent, it is recommended to always use the second form, and set `default` to the actual value you want to pass. And not use the special `True` case. This makes the code more explicit and predictable.356+````357+358 ## Values from Environment Variables359 360 To pass in a value in from a specific environment variable use `envvar`.361 25 unmodified lines387 invoke(greet, env={'ALT_USERNAME': 'Bill', 'USERNAME': 'john'})388 389 ```390 391+Variable names are:392+ - [Case-insensitive on Windows but not on other platforms](https://github.com/python/cpython/blob/aa9eb5f757ceff461e6e996f12c89e5d9b583b01/Lib/os.py#L777-L789).393+ - Not stripped of whitespaces and should match the exact name provided to the `envvar` argument.394+395+For flag options, there is two concepts to consider: the activation of the flag driven by the environment variable, and the value of the flag if it is activated.396+397+The environment variable need to be interpreted, because values read from them are always strings. We need to transform these strings into boolean values that will determine if the flag is activated or not.398+399+Here are the rules used to parse environment variable values for flag options:400+ - `true`, `1`, `yes`, `on`, `t`, `y` are interpreted as activating the flag401+ - `false`, `0`, `no`, `off`, `f`, `n` are interpreted as deactivating the flag402+ - The presence of the environment variable without value is interpreted as deactivating the flag403+ - Empty strings are interpreted as deactivating the flag404+ - Values are case-insensitive, so the `True`, `TRUE`, `tRuE` strings are all activating the flag405+ - Values are stripped of leading and trailing whitespaces before being interpreted, so the `" True "` string is transformed to `"true"` and so activates the flag406+ - If the flag option has a `flag_value` argument, passing that value in the environment variable will activate the flag, in addition to all the cases described above407+ - Any other value is interpreted as deactivating the flag408+409+```{caution}410+For boolean flags with a pair of values, the only recognized environment variable is the one provided to the `envvar` argument.411+412+So an option defined as `--flag\--no-flag`, with a `envvar="FLAG"` parameter, there is no magical `NO_FLAG=<anything>` variable that is recognized. Only the `FLAG=<anything>` environment variable is recognized.413+```414+415+Once the status of the flag has been determine to be activated or not, the `flag_value` is used as the value of the flag if it is activated. If the flag is not activated, the value of the flag is set to `None` by default.416+417 ## Multiple Options from Environment Values418 419 As options can accept multiple values, pulling in such values from420 environment variables (which are strings) is a bit more complex. The way56 unmodified lines477 providing only the option's flag without a value will either show a478 prompt or use its `flag_value`.479 480 Setting `is_flag=False, flag_value=value` tells Click that the option435-can still be passed a value, but only if the flag is given the436-`flag_value`.481+can still be passed a value, but if only the flag is given, the482+value will be `flag_value`.483 484 ```{eval-rst}485 .. click:example::486 11 unmodified linesadded:docs/parameters.md+55 added
1+(parameters)=2+3+# Parameters4+5+```{currentmodule} click6+```7+8+Click supports only two principle types of parameters for scripts (by design): options and arguments.9+10+## Options11+12+- Are optional.13+- Recommended to use for everything except subcommands, urls, or files.14+- Can take a fixed number of arguments. The default is 1. They may be specified multiple times using {ref}`multiple-options`.15+- Are fully documented by the help page.16+- Have automatic prompting for missing input.17+- Can act as flags (boolean or otherwise).18+- Can be pulled from environment variables.19+20+## Arguments21+22+- Are optional with in reason, but not entirely so.23+- Recommended to use for subcommands, urls, or files.24+- Can take an arbitrary number of arguments.25+- Are not fully documented by the help page since they may be too specific to be automatically documented. For more see {ref}`documenting-arguments`.26+- Can be pulled from environment variables but only explicitly named ones. For more see {ref}`environment-variables`.27+28+On each principle type you can specify {ref}`parameter-types`. Specifying these types helps Click add details to your help pages and help with the handling of those types.29+30+(parameter-names)=31+32+## Parameter Names33+34+Parameters (options and arguments) have a name that will be used as35+the Python argument name when calling the decorated function with36+values.37+38+In the example, the argument's name is `filename`. The name must match the python arg name. To provide a different name for use in help text, see {ref}`doc-meta-variables`.39+The option's names are `-t` and `--times`. More names are available for options and are covered in {ref}`options`.40+41+```{eval-rst}42+.. click:example::43+44+ @click.command()45+ @click.argument('filename')46+ @click.option('-t', '--times', type=int)47+ def multi_echo(filename, times):48+ """Print value filename multiple times."""49+ for x in range(times):50+ click.echo(filename)51+52+.. click:run::53+54+ invoke(multi_echo, ['--times=3', 'index.txt'], prog_name='multi_echo')55+```deleted:docs/parameters.rst-58 removed
1-.. _parameters:2-3-Parameters4-==========5-6-.. currentmodule:: click7-8-Click supports only two principle types of parameters for scripts (by design): options and arguments.9-10-Options11-----------------12-13-* Are optional.14-* Recommended to use for everything except subcommands, urls, or files.15-* Can take a fixed number of arguments. The default is 1. They may be specified multiple times using :ref:`multiple-options`.16-* Are fully documented by the help page.17-* Have automatic prompting for missing input.18-* Can act as flags (boolean or otherwise).19-* Can be pulled from environment variables.20-21-Arguments22-----------------23-24-* Are optional with in reason, but not entirely so.25-* Recommended to use for subcommands, urls, or files.26-* Can take an arbitrary number of arguments.27-* Are not fully documented by the help page since they may be too specific to be automatically documented. For more see :ref:`documenting-arguments`.28-* Can be pulled from environment variables but only explicitly named ones. For more see :ref:`environment-variables`.29-30-On each principle type you can specify :ref:`parameter-types`. Specifying these types helps Click add details to your help pages and help with the handling of those types.31-32-.. _parameter_names:33-34-Parameter Names35----------------36-37-Parameters (options and arguments) have a name that will be used as38-the Python argument name when calling the decorated function with39-values.40-41-.. click:example::42-43- @click.command()44- @click.argument('filename')45- @click.option('-t', '--times', type=int)46- def multi_echo(filename, times):47- """Print value filename multiple times."""48- for x in range(times):49- click.echo(filename)50-51-In the above example the argument's name is ``filename``. The name must match the python arg name. To provide a different name for use in help text, see :ref:`doc-meta-variables`.52-The option's names are ``-t`` and ``--times``. More names are available for options and are covered in :ref:`options`.53-54-And what it looks like when run:55-56-.. click:run::57-58- invoke(multi_echo, ['--times=3', 'index.txt'], prog_name='multi_echo')added:docs/prompts.md+168 added
1+# User Input Prompts2+3+```{currentmodule} click4+```5+6+Click supports prompts in two different places. The first is automated prompts when the parameter handling happens, and7+the second is to ask for prompts at a later point independently.8+9+This can be accomplished with the {func}`prompt` function, which asks for valid input according to a type, or the10+{func}`confirm` function, which asks for confirmation (yes/no).11+12+```{contents}13+---14+depth: 215+local: true16+---17+```18+19+(option-prompting)=20+21+## Option Prompts22+23+Option prompts are integrated into the option interface. Internally, it automatically calls either {func}`prompt` or24+{func}`confirm` as necessary.25+26+In some cases, you want parameters that can be provided from the command line, but if not provided, ask for user input27+instead. This can be implemented with Click by defining a prompt string.28+29+Example:30+31+```{eval-rst}32+.. click:example::33+34+ @click.command()35+ @click.option('--name', prompt=True)36+ def hello(name):37+ click.echo(f"Hello {name}!")38+39+And what it looks like:40+41+.. click:run::42+43+ invoke(hello, args=['--name=John'])44+ invoke(hello, input=['John'])45+```46+47+If you are not happy with the default prompt string, you can ask for48+a different one:49+50+```{eval-rst}51+.. click:example::52+53+ @click.command()54+ @click.option('--name', prompt='Your name please')55+ def hello(name):56+ click.echo(f"Hello {name}!")57+58+What it looks like:59+60+.. click:run::61+62+ invoke(hello, input=['John'])63+```64+65+It is advised that prompt not be used in conjunction with the multiple flag set to True. Instead, prompt in the function66+interactively.67+68+By default, the user will be prompted for an input if one was not passed through the command line. To turn this behavior69+off, see {ref}`optional-value`.70+71+## Input Prompts72+73+To manually ask for user input, you can use the {func}`prompt` function. By default, it accepts any Unicode string, but74+you can ask for any other type. For instance, you can ask for a valid integer:75+76+```python77+value = click.prompt('Please enter a valid integer', type=int)78+```79+80+Additionally, the type will be determined automatically if a default value is provided. For instance, the following will81+only accept floats:82+83+```python84+value = click.prompt('Please enter a number', default=42.0)85+```86+87+## Optional Prompts88+89+If the option has `prompt` enabled, then setting `prompt_required=False` tells Click to only show the prompt if the90+option's flag is given, instead of if the option is not provided at all.91+92+```{eval-rst}93+.. click:example::94+95+ @click.command()96+ @click.option('--name', prompt=True, prompt_required=False, default="Default")97+ def hello(name):98+ click.echo(f"Hello {name}!")99+100+.. click:run::101+102+ invoke(hello)103+ invoke(hello, args=["--name", "Value"])104+ invoke(hello, args=["--name"], input="Prompt")105+```106+107+If `required=True`, then the option will still prompt if it is not given, but it will also prompt if only the flag is108+given.109+110+## Confirmation Prompts111+112+To ask if a user wants to continue with an action, the {func}`confirm` function comes in handy. By default, it returns113+the result of the prompt as a boolean value:114+115+```python116+if click.confirm('Do you want to continue?'):117+ click.echo('Well done!')118+```119+120+There is also the option to make the function automatically abort the execution of the program if it does not return121+`True`:122+123+```python124+click.confirm('Do you want to continue?', abort=True)125+```126+127+## Dynamic Defaults for Prompts128+129+The `auto_envvar_prefix` and `default_map` options for the context allow the program to read option values from the130+environment or a configuration file. However, this overrides the prompting mechanism, so that the user does not get the131+option to change the value interactively.132+133+If you want to let the user configure the default value, but still be prompted if the option isn't specified on the134+command line, you can do so by supplying a callable as the default value. For example, to get a default from the135+environment:136+137+```python138+import os139+140+@click.command()141+@click.option(142+ "--username", prompt=True,143+ default=lambda: os.environ.get("USER", "")144+)145+def hello(username):146+ click.echo(f"Hello, {username}!")147+```148+149+To describe what the default value will be, set it in ``show_default``.150+151+```{eval-rst}152+.. click:example::153+154+ import os155+156+ @click.command()157+ @click.option(158+ "--username", prompt=True,159+ default=lambda: os.environ.get("USER", ""),160+ show_default="current user"161+ )162+ def hello(username):163+ click.echo(f"Hello, {username}!")164+165+.. click:run::166+167+ invoke(hello, args=["--help"])168+```deleted:docs/prompts.rst-162 removed
1-User Input Prompts2-==================3-4-.. currentmodule:: click5-6-Click supports prompts in two different places. The first is automated7-prompts when the parameter handling happens, and the second is to ask for8-prompts at a later point independently.9-10-This can be accomplished with the :func:`prompt` function, which asks for11-valid input according to a type, or the :func:`confirm` function, which asks12-for confirmation (yes/no).13-14-.. contents::15- :depth: 216- :local:17-18-.. _option-prompting:19-20-Option Prompts21---------------22-23-Option prompts are integrated into the option interface. Internally, it24-automatically calls either :func:`prompt` or :func:`confirm` as necessary.25-26-In some cases, you want parameters that can be provided from the command line,27-but if not provided, ask for user input instead. This can be implemented with28-Click by defining a prompt string.29-30-Example:31-32-.. click:example::33-34- @click.command()35- @click.option('--name', prompt=True)36- def hello(name):37- click.echo(f"Hello {name}!")38-39-And what it looks like:40-41-.. click:run::42-43- invoke(hello, args=['--name=John'])44- invoke(hello, input=['John'])45-46-If you are not happy with the default prompt string, you can ask for47-a different one:48-49-.. click:example::50-51- @click.command()52- @click.option('--name', prompt='Your name please')53- def hello(name):54- click.echo(f"Hello {name}!")55-56-What it looks like:57-58-.. click:run::59-60- invoke(hello, input=['John'])61-62-It is advised that prompt not be used in conjunction with the multiple63-flag set to True. Instead, prompt in the function interactively.64-65-By default, the user will be prompted for an input if one was not passed66-through the command line. To turn this behavior off, see67-:ref:`optional-value`.68-69-Input Prompts70--------------71-72-To manually ask for user input, you can use the :func:`prompt` function.73-By default, it accepts any Unicode string, but you can ask for any other74-type. For instance, you can ask for a valid integer::75-76- value = click.prompt('Please enter a valid integer', type=int)77-78-Additionally, the type will be determined automatically if a default value is79-provided. For instance, the following will only accept floats::80-81- value = click.prompt('Please enter a number', default=42.0)82-83-Optional Prompts84-------------------85-If the option has ``prompt`` enabled, then setting86-``prompt_required=False`` tells Click to only show the prompt if the87-option's flag is given, instead of if the option is not provided at all.88-89-.. click:example::90-91- @click.command()92- @click.option('--name', prompt=True, prompt_required=False, default="Default")93- def hello(name):94- click.echo(f"Hello {name}!")95-96-.. click:run::97-98- invoke(hello)99- invoke(hello, args=["--name", "Value"])100- invoke(hello, args=["--name"], input="Prompt")101-102-If ``required=True``, then the option will still prompt if it is not103-given, but it will also prompt if only the flag is given.104-105-Confirmation Prompts106---------------------107-108-To ask if a user wants to continue with an action, the :func:`confirm`109-function comes in handy. By default, it returns the result of the prompt110-as a boolean value::111-112- if click.confirm('Do you want to continue?'):113- click.echo('Well done!')114-115-There is also the option to make the function automatically abort the116-execution of the program if it does not return ``True``::117-118- click.confirm('Do you want to continue?', abort=True)119-120-Dynamic Defaults for Prompts121-----------------------------122-123-The ``auto_envvar_prefix`` and ``default_map`` options for the context124-allow the program to read option values from the environment or a125-configuration file. However, this overrides the prompting mechanism, so126-that the user does not get the option to change the value interactively.127-128-If you want to let the user configure the default value, but still be129-prompted if the option isn't specified on the command line, you can do so130-by supplying a callable as the default value. For example, to get a default131-from the environment:132-133-.. code-block:: python134-135- import os136-137- @click.command()138- @click.option(139- "--username", prompt=True,140- default=lambda: os.environ.get("USER", "")141- )142- def hello(username):143- click.echo(f"Hello, {username}!")144-145-To describe what the default value will be, set it in ``show_default``.146-147-.. click:example::148-149- import os150-151- @click.command()152- @click.option(153- "--username", prompt=True,154- default=lambda: os.environ.get("USER", ""),155- show_default="current user"156- )157- def hello(username):158- click.echo(f"Hello, {username}!")159-160-.. click:run::161-162- invoke(hello, args=["--help"])added:docs/quickstart.md+196 added
1+# Quickstart2+3+```{currentmodule} click4+```5+6+## Install7+8+Install from PyPI:9+10+```console11+pip install click12+```13+14+Installing into a virtual environment is highly recommended. We suggest {ref}`virtualenv-heading`.15+16+## Examples17+18+Some standalone examples of Click applications are packaged with Click. They are available in the19+[examples folder](https://github.com/pallets/click/tree/main/examples) of the repo.20+21+- [inout](https://github.com/pallets/click/tree/main/examples/inout) : A very simple example of an application that can22+ read from files and write to files and also accept input from stdin or write to stdout.23+- [validation](https://github.com/pallets/click/tree/main/examples/validation) : A simple example of an application that24+ performs custom validation of parameters in different ways.25+- [naval](https://github.com/pallets/click/tree/main/examples/naval) : Port of the [docopt](http://docopt.org/) naval26+ example.27+- [colors](https://github.com/pallets/click/tree/main/examples/colors) : A simple example that colorizes text. Uses28+ colorama on Windows.29+- [aliases](https://github.com/pallets/click/tree/main/examples/aliases) : An advanced example that implements30+ {ref}`aliases`.31+- [imagepipe](https://github.com/pallets/click/tree/main/examples/imagepipe) : A complex example that implements some32+ {ref}`command-pipelines` . It chains together image processing instructions. Requires pillow.33+- [repo](https://github.com/pallets/click/tree/main/examples/repo) : An advanced example that implements a34+ Git-/Mercurial-like command line interface.35+- [complex](https://github.com/pallets/click/tree/main/examples/complex) : A very advanced example that implements36+ loading subcommands dynamically from a plugin folder.37+- [termui](https://github.com/pallets/click/tree/main/examples/termui) : A simple example that showcases terminal UI38+ helpers provided by click.39+40+## Basic Concepts - Creating a Command41+42+Click is based on declaring commands through decorators. Internally, there is a non-decorator interface for advanced use43+cases, but it's discouraged for high-level usage.44+45+A function becomes a Click command line tool by decorating it through {func}`command`. At its simplest, just46+decorating a function with this decorator will make it into a callable script:47+48+49+```{eval-rst}50+.. click:example::51+ import click52+53+ @click.command()54+ def hello():55+ click.echo('Hello World!')56+57+What's happening is that the decorator converts the function into a :class:`Command` which then can be invoked:58+59+.. click:example::60+ if __name__ == '__main__':61+ hello()62+63+And what it looks like:64+65+.. click:run::66+ invoke(hello, args=[], prog_name='python hello.py')67+68+And the corresponding help page:69+70+.. click:run::71+ invoke(hello, args=['--help'], prog_name='python hello.py')72+```73+74+## Echoing75+76+Why does this example use {func}`echo` instead of the regular {func}`print` function? The answer to this question is77+that Click attempts to support different environments consistently and to be very robust even when the environment is78+misconfigured. Click wants to be functional at least on a basic level even if everything is completely broken.79+80+What this means is that the {func}`echo` function applies some error correction in case the terminal is misconfigured81+instead of dying with a {exc}`UnicodeError`.82+83+The echo function also supports color and other styles in output. It will automatically remove styles if the output84+stream is a file. On Windows, colorama is automatically installed and used. See {ref}`ansi-colors`.85+86+If you don't need this, you can also use the `print()` construct / function.87+88+## Nesting Commands89+90+Commands can be attached to other commands of type {class}`Group`. This allows arbitrary nesting of scripts. As an91+example here is a script that implements two commands for managing databases:92+93+```{eval-rst}94+.. click:example::95+ @click.group()96+ def cli():97+ pass98+99+ @click.command()100+ def initdb():101+ click.echo('Initialized the database')102+103+ @click.command()104+ def dropdb():105+ click.echo('Dropped the database')106+107+ cli.add_command(initdb)108+ cli.add_command(dropdb)109+```110+111+As you can see, the {func}`group` decorator works like the {func}`command` decorator, but creates a {class}`Group`112+object instead which can be given multiple subcommands that can be attached with {meth}`Group.add_command`.113+114+For simple scripts, it's also possible to automatically attach and create a command by using the {meth}`Group.command`115+decorator instead. The above script can instead be written like this:116+117+```{eval-rst}118+.. click:example::119+ @click.group()120+ def cli():121+ pass122+123+ @cli.command()124+ def initdb():125+ click.echo('Initialized the database')126+127+ @cli.command()128+ def dropdb():129+ click.echo('Dropped the database')130+131+You would then invoke the :class:`Group` in your entry points or other invocations:132+133+.. click:example::134+ if __name__ == '__main__':135+ cli()136+```137+138+## Registering Commands Later139+140+Instead of using the `@group.command()` decorator, commands can be decorated with the plain `@command()` decorator141+and registered with a group later with `group.add_command()`. This could be used to split commands into multiple Python142+modules.143+144+```{code-block} python145+ @click.command()146+ def greet():147+ click.echo("Hello, World!")148+```149+150+```{code-block} python151+ @click.group()152+ def group():153+ pass154+155+ group.add_command(greet)156+```157+158+## Adding Parameters159+160+To add parameters, use the {func}`option` and {func}`argument` decorators:161+162+```{eval-rst}163+.. click:example::164+ @click.command()165+ @click.option('--count', default=1, help='number of greetings')166+ @click.argument('name')167+ def hello(count, name):168+ for x in range(count):169+ click.echo(f"Hello {name}!")170+171+What it looks like:172+173+.. click:run::174+ invoke(hello, args=['--help'], prog_name='python hello.py')175+```176+177+## Switching to Entry Points178+179+In the code you wrote so far there is a block at the end of the file which looks like this:180+`if __name__ == '__main__':`. This is traditionally how a standalone Python file looks like. With Click you can continue181+doing that, but a better way is to package your app with an entry point.182+183+There are two main (and many more) reasons for this:184+185+The first one is that installers automatically generate executable wrappers for Windows so your command line utilities186+work on Windows too.187+188+The second reason is that entry point scripts work with virtualenv on Unix without the virtualenv having to be189+activated. This is a very useful concept which allows you to bundle your scripts with all requirements into a190+virtualenv.191+192+Click is perfectly equipped to work with that and in fact the rest of the documentation will assume that you are writing193+applications as distributed packages.194+195+Look at the {doc}`entry-points` chapter before reading the rest as the examples assume that you will be using entry196+points.deleted:docs/quickstart.rst-206 removed
1-Quickstart2-==========3-4-.. currentmodule:: click5-6-Install7-----------------------8-Install from PyPI::9-10- pip install click11-12-Installing into a virtual environment is highly recommended. We suggest :ref:`virtualenv-heading`.13-14-Examples15------------------------16-17-Some standalone examples of Click applications are packaged with Click. They are available in the `examples folder <https://github.com/pallets/click/tree/main/examples>`_ of the repo.18-19-* `inout <https://github.com/pallets/click/tree/main/examples/inout>`_ : A very simple example of an application that can read from files and write to files and also accept input from stdin or write to stdout.20-* `validation <https://github.com/pallets/click/tree/main/examples/validation>`_ : A simple example of an application that performs custom validation of parameters in different ways.21-* `naval <https://github.com/pallets/click/tree/main/examples/naval>`_ : Port of the `docopt <http://docopt.org/>`_ naval example.22-* `colors <https://github.com/pallets/click/tree/main/examples/colors>`_ : A simple example that colorizes text. Uses colorama on Windows.23-* `aliases <https://github.com/pallets/click/tree/main/examples/aliases>`_ : An advanced example that implements :ref:`aliases`.24-* `imagepipe <https://github.com/pallets/click/tree/main/examples/imagepipe>`_ : A complex example that implements some :ref:`command-pipelines` . It chains together image processing instructions. Requires pillow.25-* `repo <https://github.com/pallets/click/tree/main/examples/repo>`_ : An advanced example that implements a Git-/Mercurial-like command line interface.26-* `complex <https://github.com/pallets/click/tree/main/examples/complex>`_ : A very advanced example that implements loading subcommands dynamically from a plugin folder.27-* `termui <https://github.com/pallets/click/tree/main/examples/termui>`_ : A simple example that showcases terminal UI helpers provided by click.28-29-Basic Concepts - Creating a Command30------------------------------------31-32-Click is based on declaring commands through decorators. Internally, there33-is a non-decorator interface for advanced use cases, but it's discouraged34-for high-level usage.35-36-A function becomes a Click command line tool by decorating it through37-:func:`click.command`. At its simplest, just decorating a function38-with this decorator will make it into a callable script:39-40-.. click:example::41-42- import click43-44- @click.command()45- def hello():46- click.echo('Hello World!')47-48-What's happening is that the decorator converts the function into a49-:class:`Command` which then can be invoked::50-51- if __name__ == '__main__':52- hello()53-54-And what it looks like:55-56-.. click:run::57-58- invoke(hello, args=[], prog_name='python hello.py')59-60-And the corresponding help page:61-62-.. click:run::63-64- invoke(hello, args=['--help'], prog_name='python hello.py')65-66-Echoing67--------68-69-Why does this example use :func:`echo` instead of the regular70-:func:`print` function? The answer to this question is that Click71-attempts to support different environments consistently and to be very72-robust even when the environment is misconfigured. Click wants to be73-functional at least on a basic level even if everything is completely74-broken.75-76-What this means is that the :func:`echo` function applies some error77-correction in case the terminal is misconfigured instead of dying with a78-:exc:`UnicodeError`.79-80-The echo function also supports color and other styles in output. It81-will automatically remove styles if the output stream is a file. On82-Windows, colorama is automatically installed and used. See83-:ref:`ansi-colors`.84-85-If you don't need this, you can also use the `print()` construct /86-function.87-88-Nesting Commands89-----------------90-91-Commands can be attached to other commands of type :class:`Group`. This92-allows arbitrary nesting of scripts. As an example here is a script that93-implements two commands for managing databases:94-95-.. click:example::96-97- @click.group()98- def cli():99- pass100-101- @click.command()102- def initdb():103- click.echo('Initialized the database')104-105- @click.command()106- def dropdb():107- click.echo('Dropped the database')108-109- cli.add_command(initdb)110- cli.add_command(dropdb)111-112-As you can see, the :func:`group` decorator works like the :func:`command`113-decorator, but creates a :class:`Group` object instead which can be given114-multiple subcommands that can be attached with :meth:`Group.add_command`.115-116-For simple scripts, it's also possible to automatically attach and create a117-command by using the :meth:`Group.command` decorator instead. The above118-script can instead be written like this:119-120-.. click:example::121-122- @click.group()123- def cli():124- pass125-126- @cli.command()127- def initdb():128- click.echo('Initialized the database')129-130- @cli.command()131- def dropdb():132- click.echo('Dropped the database')133-134-You would then invoke the :class:`Group` in your entry points or other invocations::135-136- if __name__ == '__main__':137- cli()138-139-140-Registering Commands Later141---------------------------142-143-Instead of using the ``@group.command()`` decorator, commands can be144-decorated with the plain ``@click.command()`` decorator and registered145-with a group later with ``group.add_command()``. This could be used to146-split commands into multiple Python modules.147-148-.. code-block:: python149-150- @click.command()151- def greet():152- click.echo("Hello, World!")153-154-.. code-block:: python155-156- @click.group()157- def group():158- pass159-160- group.add_command(greet)161-162-163-Adding Parameters164------------------165-166-To add parameters, use the :func:`option` and :func:`argument` decorators:167-168-.. click:example::169-170- @click.command()171- @click.option('--count', default=1, help='number of greetings')172- @click.argument('name')173- def hello(count, name):174- for x in range(count):175- click.echo(f"Hello {name}!")176-177-What it looks like:178-179-.. click:run::180-181- invoke(hello, args=['--help'], prog_name='python hello.py')182-183-Switching to Entry Points184--------------------------185-186-In the code you wrote so far there is a block at the end of the file which187-looks like this: ``if __name__ == '__main__':``. This is traditionally188-how a standalone Python file looks like. With Click you can continue189-doing that, but a better way is to package your app with an entry point.190-191-There are two main (and many more) reasons for this:192-193-The first one is that installers automatically generate executable194-wrappers for Windows so your command line utilities work on Windows too.195-196-The second reason is that entry point scripts work with virtualenv on Unix197-without the virtualenv having to be activated. This is a very useful198-concept which allows you to bundle your scripts with all requirements into199-a virtualenv.200-201-Click is perfectly equipped to work with that and in fact the rest of the202-documentation will assume that you are writing applications as distributed203-packages.204-205-Look at the :doc:`entry-points` chapter before reading the rest as the examples206-assume that you will be using entry points.added:docs/setuptools.md+7 added
1+---2+orphan: true3+---4+5+# Setuptools Integration6+7+Moved to {doc}`entry-points`.deleted:docs/setuptools.rst-6 removed
1-:orphan:2-3-Setuptools Integration4-======================5-6-Moved to :doc:`entry-points`.added:docs/shell-completion.md+249 added
1+(shell-completion)=2+3+# Shell Completion4+5+```{currentmodule} click.shell_completion6+```7+8+Click provides tab completion support for Bash (version 4.4 and up), Zsh, and Fish. It is possible to add support for9+other shells too, and suggestions can be customized at multiple levels.10+11+Shell completion suggests command names, option names, and values for choice, file, and path parameter types. Options12+are only listed if at least a dash has been entered. Hidden commands and options are not shown.13+14+```console15+$ repo <TAB><TAB>16+clone commit copy delete setuser17+$ repo clone -<TAB><TAB>18+--deep --help --rev --shallow -r19+```20+21+## Enabling Completion22+23+Completion is only available if a script is installed and invoked through an entry point, not through the `python`24+command. See {doc}`entry-points`. Once the executable is installed, calling it with a special environment variable will25+put Click in completion mode.26+27+To enable shell completion, the user needs to register a special function with their shell. The exact script varies28+depending on the shell you are using. Click will output it when called with `_{FOO_BAR}_COMPLETE` set to29+`{shell}_source`. `{FOO_BAR}` is the executable name in uppercase with dashes replaced by underscores. It is30+conventional but not strictly required for environment variable names to be in upper case. This convention helps31+distinguish environment variables from regular shell variables and commands, making scripts and configuration files more32+readable and easier to maintain. The built-in shells are `bash`, `zsh`, and `fish`.33+34+Provide your users with the following instructions customized to your program name. This uses `foo-bar` as an example.35+36+```{eval-rst}37+.. tabs::38+39+ .. group-tab:: Bash40+41+ Add this to ``~/.bashrc``:42+43+ .. code-block:: bash44+45+ eval "$(_FOO_BAR_COMPLETE=bash_source foo-bar)"46+47+ .. group-tab:: Zsh48+49+ Add this to ``~/.zshrc``:50+51+ .. code-block:: zsh52+53+ eval "$(_FOO_BAR_COMPLETE=zsh_source foo-bar)"54+55+ .. group-tab:: Fish56+57+ Add this to ``~/.config/fish/completions/foo-bar.fish``:58+59+ .. code-block:: fish60+61+ _FOO_BAR_COMPLETE=fish_source foo-bar | source62+63+ This is the same file used for the activation script method64+ below. For Fish it's probably always easier to use that method.65+```66+67+Using `eval` means that the command is invoked and evaluated every time a shell is started, which can delay shell68+responsiveness. To speed it up, write the generated script to a file, then source that. You can generate the files ahead69+of time and distribute them with your program to save your users a step.70+71+```{eval-rst}72+.. tabs::73+74+ .. group-tab:: Bash75+76+ Save the script somewhere.77+78+ .. code-block:: bash79+80+ _FOO_BAR_COMPLETE=bash_source foo-bar > ~/.foo-bar-complete.bash81+82+ Source the file in ``~/.bashrc``.83+84+ .. code-block:: bash85+86+ . ~/.foo-bar-complete.bash87+88+ .. group-tab:: Zsh89+90+ Save the script somewhere.91+92+ .. code-block:: bash93+94+ _FOO_BAR_COMPLETE=zsh_source foo-bar > ~/.foo-bar-complete.zsh95+96+ Source the file in ``~/.zshrc``.97+98+ .. code-block:: bash99+100+ . ~/.foo-bar-complete.zsh101+102+ .. group-tab:: Fish103+104+ Save the script to ``~/.config/fish/completions/foo-bar.fish``:105+106+ .. code-block:: fish107+108+ _FOO_BAR_COMPLETE=fish_source foo-bar > ~/.config/fish/completions/foo-bar.fish109+```110+111+After modifying the shell config, you need to start a new shell in order for the changes to be loaded.112+113+## Custom Type Completion114+115+When creating a custom {class}`~click.ParamType`, override its {meth}`~click.ParamType.shell_complete` method to provide116+shell completion for parameters with the type. The method must return a list of {class}`~CompletionItem` objects.117+Besides the value, these objects hold metadata that shell support might use. The built-in implementations use `type` to118+indicate special handling for paths, and `help` for shells that support showing a help string next to a suggestion.119+120+In this example, the type will suggest environment variables that start with the incomplete value.121+122+```python123+class EnvVarType(ParamType):124+ name = "envvar"125+126+ def shell_complete(self, ctx, param, incomplete):127+ return [128+ CompletionItem(name)129+ for name in os.environ if name.startswith(incomplete)130+ ]131+132+@click.command()133+@click.option("--ev", type=EnvVarType())134+def cli(ev):135+ click.echo(os.environ[ev])136+```137+138+## Overriding Value Completion139+140+Value completions for a parameter can be customized without a custom type by providing a `shell_complete` function. The141+function is used instead of any completion provided by the type. It is passed 3 positional arguments:142+143+- `ctx` - The current command context.144+- `param` - The current parameter requesting completion.145+- `incomplete` - The partial word that is being completed. May be an empty string if no characters have been entered146+ yet.147+148+It must return a list of {class}`CompletionItem` objects, or as a shortcut it can return a list of strings.149+150+In this example, the command will suggest environment variables that start with the incomplete value.151+152+```python153+def complete_env_vars(ctx, param, incomplete):154+ return [k for k in os.environ if k.startswith(incomplete)]155+156+@click.command()157+@click.argument("name", shell_complete=complete_env_vars)158+def cli(name):159+ click.echo(f"Name: {name}")160+ click.echo(f"Value: {os.environ[name]}")161+```162+163+## Adding Support for a Shell164+165+Support can be added for shells that do not come built in. Be sure to check PyPI to see if there's already a package166+that adds support for your shell. This topic is very technical, you'll want to look at Click's source to study the167+built-in implementations.168+169+Shell support is provided by subclasses of {class}`ShellComplete` registered with {func}`add_completion_class`. When170+Click is invoked in completion mode, it calls {meth}`~ShellComplete.source` to output the completion script, or171+{meth}`~ShellComplete.complete` to output completions. The base class provides default implementations that require172+implementing some smaller parts.173+174+First, you'll need to figure out how your shell's completion system works and write a script to integrate it with Click.175+It must invoke your program with the environment variable `_{FOO_BAR}_COMPLETE` set to `{shell}_complete` and pass the176+complete args and incomplete value. How it passes those values, and the format of the completion response from Click is177+up to you.178+179+In your subclass, set {attr}`ShellComplete.source_template` to the completion script. The default implementation will180+perform `%` formatting with the following variables:181+182+- `complete_func` - A safe name for the completion function defined in the script.183+- `complete_var` - The environment variable name for passing the `{shell}_complete` instruction.184+- `foo_bar` - The name of the executable being completed.185+186+The example code is for a made up shell "My Shell" or "mysh" for short.187+188+```python189+from click.shell_completion import add_completion_class190+from click.shell_completion import ShellComplete191+192+_mysh_source = """\193+%(complete_func)s {194+ response=$(%(complete_var)s=mysh_complete %(foo_bar)s)195+ # parse response and set completions somehow196+}197+call-on-complete %(foo_bar)s %(complete_func)s198+"""199+200+@add_completion_class201+class MyshComplete(ShellComplete):202+ name = "mysh"203+ source_template = _mysh_source204+```205+206+Next, implement {meth}`~ShellComplete.get_completion_args`. This must get, parse, and return the complete args and207+incomplete value from the completion script. For example, for the Bash implementation the `COMP_WORDS` env var contains208+the command line args as a string, and the `COMP_CWORD` env var contains the index of the incomplete arg. The method209+must return a `(args, incomplete)` tuple.210+211+```python212+import os213+from click.parser import split_arg_string214+215+class MyshComplete(ShellComplete):216+ ...217+218+ def get_completion_args(self):219+ args = split_arg_string(os.environ["COMP_WORDS"])220+221+ if os.environ["COMP_PARTIAL"] == "1":222+ incomplete = args.pop()223+ return args, incomplete224+225+ return args, ""226+```227+228+Finally, implement {meth}`~ShellComplete.format_completion`. This is called to format each {class}`CompletionItem` into a string. For example, the Bash implementation returns `f"{item.type},{item.value}` (it doesn't support help strings), and the Zsh implementation returns each part separated by a newline, replacing empty help with a `_` placeholder. This format is entirely up to what you parse with your completion script.229+230+The `type` value is usually `plain`, but it can be another value that the completion script can switch on. For example,231+`file` or `dir` can tell the shell to handle path completion, since the shell is better at that than Click.232+233+```python234+class MyshComplete(ShellComplete):235+ ...236+237+ def format_completion(self, item):238+ return f"{item.type}\t{item.value}"239+```240+241+With those three things implemented, the new shell support is ready. In case those weren't sufficient, there are more242+parts that can be overridden, but that probably isn't necessary.243+244+The activation instructions will again depend on how your shell works. Use the following to generate the completion245+script, then load it into the shell somehow.246+247+```console248+_FOO_BAR_COMPLETE=mysh_source foo-bar249+```deleted:docs/shell-completion.rst-291 removed
1-.. currentmodule:: click.shell_completion2-3-Shell Completion4-================5-6-Click provides tab completion support for Bash (version 4.4 and up),7-Zsh, and Fish. It is possible to add support for other shells too, and8-suggestions can be customized at multiple levels.9-10-Shell completion suggests command names, option names, and values for11-choice, file, and path parameter types. Options are only listed if at12-least a dash has been entered. Hidden commands and options are not13-shown.14-15-.. code-block:: text16-17- $ repo <TAB><TAB>18- clone commit copy delete setuser19- $ repo clone -<TAB><TAB>20- --deep --help --rev --shallow -r21-22-23-Enabling Completion24--------------------25-26-Completion is only available if a script is installed and invoked27-through an entry point, not through the ``python`` command. See28-:doc:`entry-points`. Once the executable is installed, calling it with29-a special environment variable will put Click in completion mode.30-31-To enable shell completion, the user needs to register a special32-function with their shell. The exact script varies depending on the33-shell you are using. Click will output it when called with34-``_{FOO_BAR}_COMPLETE`` set to ``{shell}_source``. ``{FOO_BAR}`` is35-the executable name in uppercase with dashes replaced by underscores.36-It is conventional but not strictly required for environment variable37-names to be in upper case. This convention helps distinguish environment38-variables from regular shell variables and commands, making scripts39-and configuration files more readable and easier to maintain. The40-built-in shells are ``bash``, ``zsh``, and ``fish``.41-42-Provide your users with the following instructions customized to your43-program name. This uses ``foo-bar`` as an example.44-45-.. tabs::46-47- .. group-tab:: Bash48-49- Add this to ``~/.bashrc``:50-51- .. code-block:: bash52-53- eval "$(_FOO_BAR_COMPLETE=bash_source foo-bar)"54-55- .. group-tab:: Zsh56-57- Add this to ``~/.zshrc``:58-59- .. code-block:: zsh60-61- eval "$(_FOO_BAR_COMPLETE=zsh_source foo-bar)"62-63- .. group-tab:: Fish64-65- Add this to ``~/.config/fish/completions/foo-bar.fish``:66-67- .. code-block:: fish68-69- _FOO_BAR_COMPLETE=fish_source foo-bar | source70-71- This is the same file used for the activation script method72- below. For Fish it's probably always easier to use that method.73-74-Using ``eval`` means that the command is invoked and evaluated every75-time a shell is started, which can delay shell responsiveness. To speed76-it up, write the generated script to a file, then source that. You can77-generate the files ahead of time and distribute them with your program78-to save your users a step.79-80-.. tabs::81-82- .. group-tab:: Bash83-84- Save the script somewhere.85-86- .. code-block:: bash87-88- _FOO_BAR_COMPLETE=bash_source foo-bar > ~/.foo-bar-complete.bash89-90- Source the file in ``~/.bashrc``.91-92- .. code-block:: bash93-94- . ~/.foo-bar-complete.bash95-96- .. group-tab:: Zsh97-98- Save the script somewhere.99-100- .. code-block:: bash101-102- _FOO_BAR_COMPLETE=zsh_source foo-bar > ~/.foo-bar-complete.zsh103-104- Source the file in ``~/.zshrc``.105-106- .. code-block:: bash107-108- . ~/.foo-bar-complete.zsh109-110- .. group-tab:: Fish111-112- Save the script to ``~/.config/fish/completions/foo-bar.fish``:113-114- .. code-block:: fish115-116- _FOO_BAR_COMPLETE=fish_source foo-bar > ~/.config/fish/completions/foo-bar.fish117-118-After modifying the shell config, you need to start a new shell in order119-for the changes to be loaded.120-121-122-Custom Type Completion123-----------------------124-125-When creating a custom :class:`~click.ParamType`, override its126-:meth:`~click.ParamType.shell_complete` method to provide shell127-completion for parameters with the type. The method must return a list128-of :class:`~CompletionItem` objects. Besides the value, these objects129-hold metadata that shell support might use. The built-in implementations130-use ``type`` to indicate special handling for paths, and ``help`` for131-shells that support showing a help string next to a suggestion.132-133-In this example, the type will suggest environment variables that start134-with the incomplete value.135-136-.. code-block:: python137-138- class EnvVarType(ParamType):139- name = "envvar"140-141- def shell_complete(self, ctx, param, incomplete):142- return [143- CompletionItem(name)144- for name in os.environ if name.startswith(incomplete)145- ]146-147- @click.command()148- @click.option("--ev", type=EnvVarType())149- def cli(ev):150- click.echo(os.environ[ev])151-152-153-Overriding Value Completion154----------------------------155-156-Value completions for a parameter can be customized without a custom157-type by providing a ``shell_complete`` function. The function is used158-instead of any completion provided by the type. It is passed 3 keyword159-arguments:160-161-- ``ctx`` - The current command context.162-- ``param`` - The current parameter requesting completion.163-- ``incomplete`` - The partial word that is being completed. May164- be an empty string if no characters have been entered yet.165-166-It must return a list of :class:`CompletionItem` objects, or as a167-shortcut it can return a list of strings.168-169-In this example, the command will suggest environment variables that170-start with the incomplete value.171-172-.. code-block:: python173-174- def complete_env_vars(ctx, param, incomplete):175- return [k for k in os.environ if k.startswith(incomplete)]176-177- @click.command()178- @click.argument("name", shell_complete=complete_env_vars)179- def cli(name):180- click.echo(f"Name: {name}")181- click.echo(f"Value: {os.environ[name]}")182-183-184-Adding Support for a Shell185---------------------------186-187-Support can be added for shells that do not come built in. Be sure to188-check PyPI to see if there's already a package that adds support for189-your shell. This topic is very technical, you'll want to look at Click's190-source to study the built-in implementations.191-192-Shell support is provided by subclasses of :class:`ShellComplete`193-registered with :func:`add_completion_class`. When Click is invoked in194-completion mode, it calls :meth:`~ShellComplete.source` to output the195-completion script, or :meth:`~ShellComplete.complete` to output196-completions. The base class provides default implementations that197-require implementing some smaller parts.198-199-First, you'll need to figure out how your shell's completion system200-works and write a script to integrate it with Click. It must invoke your201-program with the environment variable ``_{FOO_BAR}_COMPLETE`` set to202-``{shell}_complete`` and pass the complete args and incomplete value.203-How it passes those values, and the format of the completion response204-from Click is up to you.205-206-In your subclass, set :attr:`~ShellComplete.source_template` to the207-completion script. The default implementation will perform ``%``208-formatting with the following variables:209-210-- ``complete_func`` - A safe name for the completion function defined211- in the script.212-- ``complete_var`` - The environment variable name for passing the213- ``{shell}_complete`` instruction.214-- ``foo_bar`` - The name of the executable being completed.215-216-The example code is for a made up shell "My Shell" or "mysh" for short.217-218-.. code-block:: python219-220- from click.shell_completion import add_completion_class221- from click.shell_completion import ShellComplete222-223- _mysh_source = """\224- %(complete_func)s {225- response=$(%(complete_var)s=mysh_complete %(foo_bar)s)226- # parse response and set completions somehow227- }228- call-on-complete %(foo_bar)s %(complete_func)s229- """230-231- @add_completion_class232- class MyshComplete(ShellComplete):233- name = "mysh"234- source_template = _mysh_source235-236-Next, implement :meth:`~ShellComplete.get_completion_args`. This must237-get, parse, and return the complete args and incomplete value from the238-completion script. For example, for the Bash implementation the239-``COMP_WORDS`` env var contains the command line args as a string, and240-the ``COMP_CWORD`` env var contains the index of the incomplete arg. The241-method must return a ``(args, incomplete)`` tuple.242-243-.. code-block:: python244-245- import os246- from click.parser import split_arg_string247-248- class MyshComplete(ShellComplete):249- ...250-251- def get_completion_args(self):252- args = split_arg_string(os.environ["COMP_WORDS"])253-254- if os.environ["COMP_PARTIAL"] == "1":255- incomplete = args.pop()256- return args, incomplete257-258- return args, ""259-260-Finally, implement :meth:`~ShellComplete.format_completion`. This is261-called to format each :class:`CompletionItem` into a string. For262-example, the Bash implementation returns ``f"{item.type},{item.value}``263-(it doesn't support help strings), and the Zsh implementation returns264-each part separated by a newline, replacing empty help with a ``_``265-placeholder. This format is entirely up to what you parse with your266-completion script.267-268-The ``type`` value is usually ``plain``, but it can be another value269-that the completion script can switch on. For example, ``file`` or270-``dir`` can tell the shell to handle path completion, since the shell is271-better at that than Click.272-273-.. code-block:: python274-275- class MyshComplete(ShellComplete):276- ...277-278- def format_completion(self, item):279- return f"{item.type}\t{item.value}"280-281-With those three things implemented, the new shell support is ready. In282-case those weren't sufficient, there are more parts that can be283-overridden, but that probably isn't necessary.284-285-The activation instructions will again depend on how your shell works.286-Use the following to generate the completion script, then load it into287-the shell somehow.288-289-.. code-block:: text290-291- _FOO_BAR_COMPLETE=mysh_source foo-baradded:docs/unicode-support.md+100 added
1+# Unicode Support2+3+```{currentmodule} click4+```5+6+Click has to take extra care to support Unicode text in different environments.7+8+- The command line in Unix is traditionally bytes, not Unicode. While there are encoding hints, there are some9+ situations where this can break. The most common one is SSH connections to machines with different locales.10+11+ Misconfigured environments can cause a wide range of Unicode problems due to the lack of support for roundtripping12+ surrogate escapes. This will not be fixed in Click itself!13+14+- Standard input and output is opened in text mode by default. Click has to reopen the stream in binary mode in certain15+ situations. Because there is no standard way to do this, it might not always work. Primarily this can become a problem16+ when testing command-line applications.17+18+ This is not supported:19+20+ ```python21+ sys.stdin = io.StringIO('Input here')22+ sys.stdout = io.StringIO()23+ ```24+25+ Instead you need to do this:26+27+ ```python28+ input = 'Input here'29+ in_stream = io.BytesIO(input.encode('utf-8'))30+ sys.stdin = io.TextIOWrapper(in_stream, encoding='utf-8')31+ out_stream = io.BytesIO()32+ sys.stdout = io.TextIOWrapper(out_stream, encoding='utf-8')33+ ```34+35+ Remember in that case, you need to use `out_stream.getvalue()` and not `sys.stdout.getvalue()` if you want to access36+ the buffer contents as the wrapper will not forward that method.37+38+- `sys.stdin`, `sys.stdout` and `sys.stderr` are by default text-based. When Click needs a binary stream, it attempts to39+ discover the underlying binary stream.40+41+- `sys.argv` is always text. This means that the native type for input values to the types in Click is Unicode, not42+ bytes.43+44+ This causes problems if the terminal is incorrectly set and Python does not figure out the encoding. In that case, the45+ Unicode string will contain error bytes encoded as surrogate escapes.46+47+- When dealing with files, Click will always use the Unicode file system API by using the operating system's reported or48+ guessed filesystem encoding. Surrogates are supported for filenames, so it should be possible to open files through49+ the {func}`File` type even if the environment is misconfigured.50+51+## Surrogate Handling52+53+Click does all the Unicode handling in the standard library and is subject to its behavior. Unicode requires extra care.54+The reason for this is that the encoding detection is done in the interpreter, and on Linux and certain other operating55+systems, its encoding handling is problematic.56+57+The biggest source of frustration is that Click scripts invoked by init systems, deployment tools, or cron jobs will58+refuse to work unless a Unicode locale is exported.59+60+If Click encounters such an environment it will prevent further execution to force you to set a locale. This is done61+because Click cannot know about the state of the system once it's invoked and restore the values before Python's Unicode62+handling kicked in.63+64+If you see something like this error:65+66+```console67+Traceback (most recent call last):68+ ...69+RuntimeError: Click will abort further execution because Python was70+ configured to use ASCII as encoding for the environment. Consult71+ https://click.palletsprojects.com/unicode-support/ for mitigation72+ steps.73+```74+75+You are dealing with an environment where Python thinks you are restricted to ASCII data. The solution to these problems76+is different depending on which locale your computer is running in.77+78+For instance, if you have a German Linux machine, you can fix the problem by exporting the locale to `de_DE.utf-8`:79+80+```console81+export LC_ALL=de_DE.utf-882+export LANG=de_DE.utf-883+```84+85+If you are on a US machine, `en_US.utf-8` is the encoding of choice. On some newer Linux systems, you could also try86+`C.UTF-8` as the locale:87+88+```console89+export LC_ALL=C.UTF-890+export LANG=C.UTF-891+```92+93+On some systems it was reported that `UTF-8` has to be written as `UTF8` and vice versa. To see which locales are94+supported you can invoke `locale -a`.95+96+You need to export the values before you invoke your Python script.97+98+In Python 3.7 and later you will no longer get a `RuntimeError` in many cases thanks to {pep}`538` and {pep}`540`, which99+changed the default assumption in unconfigured environments. This doesn't change the general issue that your locale may100+be misconfigured.deleted:docs/unicode-support.rst-112 removed
1-Unicode Support2-===============3-4-.. currentmodule:: click5-6-Click has to take extra care to support Unicode text in different7-environments.8-9-* The command line in Unix is traditionally bytes, not Unicode. While10- there are encoding hints, there are some situations where this can11- break. The most common one is SSH connections to machines with12- different locales.13-14- Misconfigured environments can cause a wide range of Unicode15- problems due to the lack of support for roundtripping surrogate16- escapes. This will not be fixed in Click itself!17-18-* Standard input and output is opened in text mode by default. Click19- has to reopen the stream in binary mode in certain situations.20- Because there is no standard way to do this, it might not always21- work. Primarily this can become a problem when testing command-line22- applications.23-24- This is not supported::25-26- sys.stdin = io.StringIO('Input here')27- sys.stdout = io.StringIO()28-29- Instead you need to do this::30-31- input = 'Input here'32- in_stream = io.BytesIO(input.encode('utf-8'))33- sys.stdin = io.TextIOWrapper(in_stream, encoding='utf-8')34- out_stream = io.BytesIO()35- sys.stdout = io.TextIOWrapper(out_stream, encoding='utf-8')36-37- Remember in that case, you need to use ``out_stream.getvalue()``38- and not ``sys.stdout.getvalue()`` if you want to access the buffer39- contents as the wrapper will not forward that method.40-41-* ``sys.stdin``, ``sys.stdout`` and ``sys.stderr`` are by default42- text-based. When Click needs a binary stream, it attempts to43- discover the underlying binary stream.44-45-* ``sys.argv`` is always text. This means that the native type for46- input values to the types in Click is Unicode, not bytes.47-48- This causes problems if the terminal is incorrectly set and Python49- does not figure out the encoding. In that case, the Unicode string50- will contain error bytes encoded as surrogate escapes.51-52-* When dealing with files, Click will always use the Unicode file53- system API by using the operating system's reported or guessed54- filesystem encoding. Surrogates are supported for filenames, so it55- should be possible to open files through the :class:`File` type even56- if the environment is misconfigured.57-58-59-Surrogate Handling60-------------------61-62-Click does all the Unicode handling in the standard library and is63-subject to its behavior. Unicode requires extra care. The reason for64-this is that the encoding detection is done in the interpreter, and on65-Linux and certain other operating systems, its encoding handling is66-problematic.67-68-The biggest source of frustration is that Click scripts invoked by init69-systems, deployment tools, or cron jobs will refuse to work unless a70-Unicode locale is exported.71-72-If Click encounters such an environment it will prevent further73-execution to force you to set a locale. This is done because Click74-cannot know about the state of the system once it's invoked and restore75-the values before Python's Unicode handling kicked in.76-77-If you see something like this error::78-79- Traceback (most recent call last):80- ...81- RuntimeError: Click will abort further execution because Python was82- configured to use ASCII as encoding for the environment. Consult83- https://click.palletsprojects.com/unicode-support/ for mitigation84- steps.85-86-You are dealing with an environment where Python thinks you are87-restricted to ASCII data. The solution to these problems is different88-depending on which locale your computer is running in.89-90-For instance, if you have a German Linux machine, you can fix the91-problem by exporting the locale to ``de_DE.utf-8``::92-93- export LC_ALL=de_DE.utf-894- export LANG=de_DE.utf-895-96-If you are on a US machine, ``en_US.utf-8`` is the encoding of choice.97-On some newer Linux systems, you could also try ``C.UTF-8`` as the98-locale::99-100- export LC_ALL=C.UTF-8101- export LANG=C.UTF-8102-103-On some systems it was reported that ``UTF-8`` has to be written as104-``UTF8`` and vice versa. To see which locales are supported you can105-invoke ``locale -a``.106-107-You need to export the values before you invoke your Python script.108-109-In Python 3.7 and later you will no longer get a ``RuntimeError`` in110-many cases thanks to :pep:`538` and :pep:`540`, which changed the111-default assumption in unconfigured environments. This doesn't change the112-general issue that your locale may be misconfigured.added:docs/utils.md+392 added
1+# Utilities2+3+```{currentmodule} click4+```5+6+Besides the functionality that Click provides to interface with argument parsing and handling, it also provides a bunch7+of addon functionality that is useful for writing command line utilities.8+9+## Printing to Stdout10+11+The most obvious helper is the {func}`echo` function, which in many ways works like the Python `print` statement or12+function. The main difference is that it works the same in many different terminal environments.13+14+Example:15+16+```python17+import click18+19+click.echo('Hello World!')20+```21+22+It can output both text and binary data. It will emit a trailing newline by default, which needs to be suppressed by23+passing `nl=False`:24+25+```python26+click.echo(b'\xe2\x98\x83', nl=False)27+```28+29+Last but not least {func}`echo` uses click's intelligent internal output streams to stdout and stderr which support30+unicode output on the Windows console. This means for as long as you are using `click.echo` you can output unicode31+characters (there are some limitations on the default font with regards to which characters can be displayed).32+33+```{versionadded} 6.034+```35+36+Click emulates output streams on Windows to support unicode to the Windows console through separate APIs. For more37+information see {doc}`wincmd`.38+39+```{versionadded} 3.040+```41+42+You can also easily print to standard error by passing `err=True`:43+44+```python45+click.echo('Hello World!', err=True)46+```47+48+(ansi-colors)=49+50+## ANSI Colors51+52+```{versionadded} 2.053+```54+55+The {func}`echo` function supports ANSI colors and styles. On Windows this uses [colorama](https://pypi.org/project/colorama/).56+57+Primarily this means that:58+59+- Click's {func}`echo` function will automatically strip ANSI color codes if the stream is not connected to a terminal.60+- the {func}`echo` function will transparently connect to the terminal on Windows and translate ANSI codes to terminal61+ API calls. This means that colors will work on Windows the same way they do on other operating systems.62+63+On Windows, Click uses colorama without calling `colorama.init()`. You can still call that in your code, but it's not64+required for Click.65+66+For styling a string, the {func}`style` function can be used:67+68+```python69+import click70+71+click.echo(click.style('Hello World!', fg='green'))72+click.echo(click.style('Some more text', bg='blue', fg='white'))73+click.echo(click.style('ATTENTION', blink=True, bold=True))74+```75+76+The combination of {func}`echo` and {func}`style` is also available in a single function called {func}`secho`:77+78+```python79+click.secho('Hello World!', fg='green')80+click.secho('Some more text', bg='blue', fg='white')81+click.secho('ATTENTION', blink=True, bold=True)82+```83+84+## Pager Support85+86+In some situations, you might want to show long texts on the terminal and let a user scroll through it. This can be87+achieved by using the {func}`echo_via_pager` function which works similarly to the {func}`echo` function, but always88+writes to stdout and, if possible, through a pager.89+90+Example:91+92+```{eval-rst}93+.. click:example::94+ @click.command()95+ def less():96+ click.echo_via_pager("\n".join(f"Line {idx}" for idx in range(200)))97+```98+99+If you want to use the pager for a lot of text, especially if generating everything in advance would take a lot of time,100+you can pass a generator (or generator function) instead of a string:101+102+```{eval-rst}103+.. click:example::104+ def _generate_output():105+ for idx in range(50000):106+ yield f"Line {idx}\n"107+108+ @click.command()109+ def less():110+ click.echo_via_pager(_generate_output())111+```112+113+## Screen Clearing114+115+```{versionadded} 2.0116+```117+118+To clear the terminal screen, you can use the {func}`clear` function that is provided starting with Click 2.0. It does119+what the name suggests: it clears the entire visible screen in a platform-agnostic way:120+121+```python122+import click123+click.clear()124+```125+126+## Getting Characters from Terminal127+128+```{versionadded} 2.0129+```130+131+Normally, when reading input from the terminal, you would read from standard input. However, this is buffered input and132+will not show up until the line has been terminated. In certain circumstances, you might not want to do that and instead133+read individual characters as they are being written.134+135+For this, Click provides the {func}`getchar` function which reads a single character from the terminal buffer and136+returns it as a Unicode character.137+138+Note that this function will always read from the terminal, even if stdin is instead a pipe.139+140+Example:141+142+```python143+import click144+145+click.echo('Continue? [yn] ', nl=False)146+c = click.getchar()147+click.echo()148+if c == 'y':149+ click.echo('We will go on')150+elif c == 'n':151+ click.echo('Abort!')152+else:153+ click.echo('Invalid input :(')154+```155+156+Note that this reads raw input, which means that things like arrow keys will show up in the platform's native escape157+format. The only characters translated are `^C` and `^D` which are converted into keyboard interrupts and end of file158+exceptions respectively. This is done because otherwise, it's too easy to forget about that and to create scripts that159+cannot be properly exited.160+161+## Waiting for Key Press162+163+```{versionadded} 2.0164+```165+166+Sometimes, it's useful to pause until the user presses any key on the keyboard. This is especially useful on Windows167+where `cmd.exe` will close the window at the end of the command execution by default, instead of waiting.168+169+In click, this can be accomplished with the {func}`pause` function. This function will print a quick message to the170+terminal (which can be customized) and wait for the user to press a key. In addition to that, it will also become a NOP171+(no operation instruction) if the script is not run interactively.172+173+Example:174+175+```python176+import click177+click.pause()178+```179+180+## Launching Editors181+182+```{versionadded} 2.0183+```184+185+Click supports launching editors automatically through {func}`edit`. This is very useful for asking users for multi-line186+input. It will automatically open the user's defined editor or fall back to a sensible default. If the user closes the187+editor without saving, the return value will be `None`, otherwise the entered text.188+189+Example usage:190+191+```python192+import click193+194+def get_commit_message():195+ MARKER = '# Everything below is ignored\n'196+ message = click.edit('\n\n' + MARKER)197+ if message is not None:198+ return message.split(MARKER, 1)[0].rstrip('\n')199+```200+201+Alternatively, the function can also be used to launch editors for files by a specific filename. In this case, the202+return value is always `None`.203+204+Example usage:205+206+```python207+import click208+click.edit(filename='/etc/passwd')209+```210+211+## Launching Applications212+213+```{versionadded} 2.0214+```215+216+Click supports launching applications through {func}`launch`. This can be used to open the default application217+associated with a URL or filetype. This can be used to launch web browsers or picture viewers, for instance. In addition218+to this, it can also launch the file manager and automatically select the provided file.219+220+Example usage:221+222+```python223+click.launch("https://click.palletsprojects.com/")224+click.launch("/my/downloaded/file.txt", locate=True)225+```226+227+## Printing Filenames228+229+Because filenames might not be Unicode, formatting them can be a bit tricky.230+231+The way this works with click is through the {func}`format_filename` function. It does a best-effort conversion of the232+filename to Unicode and will never fail. This makes it possible to use these filenames in the context of a full Unicode233+string.234+235+Example:236+237+```python238+click.echo(f"Path: {click.format_filename(b'foo.txt')}")239+```240+241+## Standard Streams242+243+For command line utilities, it's very important to get access to input and output streams reliably. Python generally244+provides access to these streams through `sys.stdout` and friends, but unfortunately, there are API differences between245+2.x and 3.x, especially with regards to how these streams respond to Unicode and binary data.246+247+Because of this, click provides the {func}`get_binary_stream` and {func}`get_text_stream` functions, which produce248+consistent results with different Python versions and for a wide variety of terminal configurations.249+250+The end result is that these functions will always return a functional stream object (except in very odd cases; see251+{doc}`/unicode-support`).252+253+Example:254+255+```python256+import click257+258+stdin_text = click.get_text_stream('stdin')259+stdout_binary = click.get_binary_stream('stdout')260+```261+262+```{versionadded} 6.0263+```264+265+Click now emulates output streams on Windows to support unicode to the Windows console through separate APIs. For more266+information see {doc}`wincmd`.267+268+## Intelligent File Opening269+270+```{versionadded} 3.0271+```272+273+Starting with Click 3.0 the logic for opening files from the {func}`File` type is exposed through the {func}`open_file`274+function. It can intelligently open stdin/stdout as well as any other file.275+276+Example:277+278+```python279+import click280+281+stdout = click.open_file('-', 'w')282+test_file = click.open_file('test.txt', 'w')283+```284+285+If stdin or stdout are returned, the return value is wrapped in a special file where the context manager will prevent286+the closing of the file. This makes the handling of standard streams transparent and you can always use it like this:287+288+```python289+with click.open_file(filename, 'w') as f:290+ f.write('Hello World!\n')291+```292+293+## Finding Application Folders294+295+```{versionadded} 2.0296+```297+298+Very often, you want to open a configuration file that belongs to your application. However, different operating systems299+store these configuration files in different locations depending on their standards. Click provides a300+{func}`get_app_dir` function which returns the most appropriate location for per-user config files for your application301+depending on the OS.302+303+Example usage:304+305+```python306+import os307+import click308+import ConfigParser309+310+APP_NAME = 'My Application'311+def read_config():312+cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini')313+parser = ConfigParser.RawConfigParser()314+parser.read([cfg])315+rv = {}316+for section in parser.sections():317+ for key, value in parser.items(section):318+ rv[f"{section}.{key}"] = value319+return rv320+```321+322+## Showing Progress Bars323+324+Sometimes, you have command line scripts that need to process a lot of data, but you want to quickly show the user some325+progress about how long that will take. Click supports simple progress bar rendering for that through the326+{func}`progressbar` function.327+328+```{note} If you find that you have requirements beyond what Click's progress bar supports, try using [tqdm](https://tqdm.github.io/).329+```330+331+The basic usage is very simple: the idea is that you have an iterable that you want to operate on. For each item in the332+iterable it might take some time to do processing. So say you have a loop like this:333+334+```python335+for user in all_the_users_to_process:336+ modify_the_user(user)337+```338+339+To hook this up with an automatically updating progress bar, all you need to do is to change the code to this:340+341+```python342+import click343+344+with click.progressbar(all_the_users_to_process) as bar:345+ for user in bar:346+ modify_the_user(user)347+```348+349+Click will then automatically print a progress bar to the terminal and calculate the remaining time for you. The350+calculation of remaining time requires that the iterable has a length. If it does not have a length but you know the351+length, you can explicitly provide it:352+353+```python354+with click.progressbar(all_the_users_to_process,355+ length=number_of_users) as bar:356+ for user in bar:357+ modify_the_user(user)358+```359+360+Note that {func}`progressbar` updates the bar *after* each iteration of the loop. So code like this will render361+correctly:362+363+```python364+import time365+366+with click.progressbar([1, 2, 3]) as bar:367+ for x in bar:368+ print(f"sleep({x})...")369+ time.sleep(x)370+```371+372+Another useful feature is to associate a label with the progress bar which will be shown preceding the progress bar:373+374+```python375+with click.progressbar(all_the_users_to_process,376+ label='Modifying user accounts',377+ length=number_of_users) as bar:378+ for user in bar:379+ modify_the_user(user)380+```381+382+Sometimes, one may need to iterate over an external iterator, and advance the progress bar irregularly. To do so, you383+need to specify the length (and no iterable), and use the update method on the context return value instead of iterating384+directly over it:385+386+```python387+with click.progressbar(length=total_size,388+ label='Unzipping archive') as bar:389+ for archive in zip_file:390+ archive.extract()391+ bar.update(archive.size)392+```deleted:docs/utils.rst-408 removed
1-Utilities2-=========3-4-.. currentmodule:: click5-6-Besides the functionality that Click provides to interface with argument7-parsing and handling, it also provides a bunch of addon functionality that8-is useful for writing command line utilities.9-10-11-Printing to Stdout12-------------------13-14-The most obvious helper is the :func:`echo` function, which in many ways15-works like the Python ``print`` statement or function. The main difference is16-that it works the same in many different terminal environments.17-18-Example::19-20- import click21-22- click.echo('Hello World!')23-24-It can output both text and binary data. It will emit a trailing newline25-by default, which needs to be suppressed by passing ``nl=False``::26-27- click.echo(b'\xe2\x98\x83', nl=False)28-29-Last but not least :func:`echo` uses click's intelligent internal output30-streams to stdout and stderr which support unicode output on the Windows31-console. This means for as long as you are using `click.echo` you can32-output unicode characters (there are some limitations on the default font33-with regards to which characters can be displayed).34-35-.. versionadded:: 6.036-37-Click emulates output streams on Windows to support unicode to the38-Windows console through separate APIs. For more information see39-:doc:`wincmd`.40-41-.. versionadded:: 3.042-43-You can also easily print to standard error by passing ``err=True``::44-45- click.echo('Hello World!', err=True)46-47-48-.. _ansi-colors:49-50-ANSI Colors51------------52-53-.. versionadded:: 2.054-55-The :func:`echo` function supports ANSI colors and styles. On Windows56-this uses `colorama`_.57-58-Primarily this means that:59-60-- Click's :func:`echo` function will automatically strip ANSI color codes61- if the stream is not connected to a terminal.62-- the :func:`echo` function will transparently connect to the terminal on63- Windows and translate ANSI codes to terminal API calls. This means64- that colors will work on Windows the same way they do on other65- operating systems.66-67-On Windows, Click uses colorama without calling ``colorama.init()``. You68-can still call that in your code, but it's not required for Click.69-70-For styling a string, the :func:`style` function can be used::71-72- import click73-74- click.echo(click.style('Hello World!', fg='green'))75- click.echo(click.style('Some more text', bg='blue', fg='white'))76- click.echo(click.style('ATTENTION', blink=True, bold=True))77-78-The combination of :func:`echo` and :func:`style` is also available in79-a single function called :func:`secho`::80-81- click.secho('Hello World!', fg='green')82- click.secho('Some more text', bg='blue', fg='white')83- click.secho('ATTENTION', blink=True, bold=True)84-85-86-.. _colorama: https://pypi.org/project/colorama/87-88-Pager Support89--------------90-91-In some situations, you might want to show long texts on the terminal and92-let a user scroll through it. This can be achieved by using the93-:func:`echo_via_pager` function which works similarly to the :func:`echo`94-function, but always writes to stdout and, if possible, through a pager.95-96-Example:97-98-.. click:example::99-100- @click.command()101- def less():102- click.echo_via_pager("\n".join(f"Line {idx}" for idx in range(200)))103-104-If you want to use the pager for a lot of text, especially if generating everything in advance would take a lot of time, you can pass a generator (or generator function) instead of a string:105-106-.. click:example::107- def _generate_output():108- for idx in range(50000):109- yield f"Line {idx}\n"110-111- @click.command()112- def less():113- click.echo_via_pager(_generate_output())114-115-116-Screen Clearing117----------------118-119-.. versionadded:: 2.0120-121-To clear the terminal screen, you can use the :func:`clear` function that122-is provided starting with Click 2.0. It does what the name suggests: it123-clears the entire visible screen in a platform-agnostic way:124-125-::126-127- import click128- click.clear()129-130-131-Getting Characters from Terminal132---------------------------------133-134-.. versionadded:: 2.0135-136-Normally, when reading input from the terminal, you would read from137-standard input. However, this is buffered input and will not show up until138-the line has been terminated. In certain circumstances, you might not want139-to do that and instead read individual characters as they are being written.140-141-For this, Click provides the :func:`getchar` function which reads a single142-character from the terminal buffer and returns it as a Unicode character.143-144-Note that this function will always read from the terminal, even if stdin145-is instead a pipe.146-147-Example::148-149- import click150-151- click.echo('Continue? [yn] ', nl=False)152- c = click.getchar()153- click.echo()154- if c == 'y':155- click.echo('We will go on')156- elif c == 'n':157- click.echo('Abort!')158- else:159- click.echo('Invalid input :(')160-161-Note that this reads raw input, which means that things like arrow keys162-will show up in the platform's native escape format. The only characters163-translated are ``^C`` and ``^D`` which are converted into keyboard164-interrupts and end of file exceptions respectively. This is done because165-otherwise, it's too easy to forget about that and to create scripts that166-cannot be properly exited.167-168-169-Waiting for Key Press170----------------------171-172-.. versionadded:: 2.0173-174-Sometimes, it's useful to pause until the user presses any key on the175-keyboard. This is especially useful on Windows where ``cmd.exe`` will176-close the window at the end of the command execution by default, instead177-of waiting.178-179-In click, this can be accomplished with the :func:`pause` function. This180-function will print a quick message to the terminal (which can be181-customized) and wait for the user to press a key. In addition to that,182-it will also become a NOP (no operation instruction) if the script is not183-run interactively.184-185-Example::186-187- import click188- click.pause()189-190-191-Launching Editors192------------------193-194-.. versionadded:: 2.0195-196-Click supports launching editors automatically through :func:`edit`. This197-is very useful for asking users for multi-line input. It will198-automatically open the user's defined editor or fall back to a sensible199-default. If the user closes the editor without saving, the return value200-will be ``None``, otherwise the entered text.201-202-Example usage::203-204- import click205-206- def get_commit_message():207- MARKER = '# Everything below is ignored\n'208- message = click.edit('\n\n' + MARKER)209- if message is not None:210- return message.split(MARKER, 1)[0].rstrip('\n')211-212-Alternatively, the function can also be used to launch editors for files by213-a specific filename. In this case, the return value is always `None`.214-215-Example usage::216-217- import click218- click.edit(filename='/etc/passwd')219-220-221-Launching Applications222-----------------------223-224-.. versionadded:: 2.0225-226-Click supports launching applications through :func:`launch`. This can be227-used to open the default application associated with a URL or filetype.228-This can be used to launch web browsers or picture viewers, for instance.229-In addition to this, it can also launch the file manager and automatically230-select the provided file.231-232-Example usage::233-234- click.launch("https://click.palletsprojects.com/")235- click.launch("/my/downloaded/file.txt", locate=True)236-237-238-Printing Filenames239-------------------240-241-Because filenames might not be Unicode, formatting them can be a bit242-tricky.243-244-The way this works with click is through the :func:`format_filename`245-function. It does a best-effort conversion of the filename to Unicode and246-will never fail. This makes it possible to use these filenames in the247-context of a full Unicode string.248-249-Example::250-251- click.echo(f"Path: {click.format_filename(b'foo.txt')}")252-253-254-Standard Streams255-----------------256-257-For command line utilities, it's very important to get access to input and258-output streams reliably. Python generally provides access to these259-streams through ``sys.stdout`` and friends, but unfortunately, there are260-API differences between 2.x and 3.x, especially with regards to how these261-streams respond to Unicode and binary data.262-263-Because of this, click provides the :func:`get_binary_stream` and264-:func:`get_text_stream` functions, which produce consistent results with265-different Python versions and for a wide variety of terminal configurations.266-267-The end result is that these functions will always return a functional268-stream object (except in very odd cases; see :doc:`/unicode-support`).269-270-Example::271-272- import click273-274- stdin_text = click.get_text_stream('stdin')275- stdout_binary = click.get_binary_stream('stdout')276-277-.. versionadded:: 6.0278-279-Click now emulates output streams on Windows to support unicode to the280-Windows console through separate APIs. For more information see281-:doc:`wincmd`.282-283-284-Intelligent File Opening285-------------------------286-287-.. versionadded:: 3.0288-289-Starting with Click 3.0 the logic for opening files from the :class:`File`290-type is exposed through the :func:`open_file` function. It can291-intelligently open stdin/stdout as well as any other file.292-293-Example::294-295- import click296-297- stdout = click.open_file('-', 'w')298- test_file = click.open_file('test.txt', 'w')299-300-If stdin or stdout are returned, the return value is wrapped in a special301-file where the context manager will prevent the closing of the file. This302-makes the handling of standard streams transparent and you can always use303-it like this::304-305- with click.open_file(filename, 'w') as f:306- f.write('Hello World!\n')307-308-309-Finding Application Folders310----------------------------311-312-.. versionadded:: 2.0313-314-Very often, you want to open a configuration file that belongs to your315-application. However, different operating systems store these configuration316-files in different locations depending on their standards. Click provides317-a :func:`get_app_dir` function which returns the most appropriate location318-for per-user config files for your application depending on the OS.319-320-Example usage::321-322- import os323- import click324- import ConfigParser325-326- APP_NAME = 'My Application'327-328- def read_config():329- cfg = os.path.join(click.get_app_dir(APP_NAME), 'config.ini')330- parser = ConfigParser.RawConfigParser()331- parser.read([cfg])332- rv = {}333- for section in parser.sections():334- for key, value in parser.items(section):335- rv[f"{section}.{key}"] = value336- return rv337-338-339-Showing Progress Bars340----------------------341-342-Sometimes, you have command line scripts that need to process a lot of data,343-but you want to quickly show the user some progress about how long that344-will take. Click supports simple progress bar rendering for that through345-the :func:`progressbar` function.346-347-.. note::348-349- If you find that you have requirements beyond what Click's progress350- bar supports, try using `tqdm`_.351-352- .. _tqdm: https://tqdm.github.io/353-354-The basic usage is very simple: the idea is that you have an iterable that355-you want to operate on. For each item in the iterable it might take some356-time to do processing. So say you have a loop like this::357-358- for user in all_the_users_to_process:359- modify_the_user(user)360-361-To hook this up with an automatically updating progress bar, all you need362-to do is to change the code to this::363-364- import click365-366- with click.progressbar(all_the_users_to_process) as bar:367- for user in bar:368- modify_the_user(user)369-370-Click will then automatically print a progress bar to the terminal and371-calculate the remaining time for you. The calculation of remaining time372-requires that the iterable has a length. If it does not have a length373-but you know the length, you can explicitly provide it::374-375- with click.progressbar(all_the_users_to_process,376- length=number_of_users) as bar:377- for user in bar:378- modify_the_user(user)379-380-Note that :func:`progressbar` updates the bar *after* each iteration of the381-loop. So code like this will render correctly::382-383- import time384-385- with click.progressbar([1, 2, 3]) as bar:386- for x in bar:387- print(f"sleep({x})...")388- time.sleep(x)389-390-Another useful feature is to associate a label with the progress bar which391-will be shown preceding the progress bar::392-393- with click.progressbar(all_the_users_to_process,394- label='Modifying user accounts',395- length=number_of_users) as bar:396- for user in bar:397- modify_the_user(user)398-399-Sometimes, one may need to iterate over an external iterator, and advance the400-progress bar irregularly. To do so, you need to specify the length (and no401-iterable), and use the update method on the context return value instead of402-iterating directly over it::403-404- with click.progressbar(length=total_size,405- label='Unzipping archive') as bar:406- for archive in zip_file:407- archive.extract()408- bar.update(archive.size)added:docs/virtualenv.md+58 added
1+(virtualenv-heading)=2+3+# Virtualenv4+5+## Why Use Virtualenv?6+7+You should use [Virtualenv](https://virtualenv.pypa.io/en/latest/) because:8+9+- It allows you to install multiple versions of the same dependency.10+- If you have an operating system version of Python, it prevents you from changing its dependencies and potentially11+ messing up your os.12+13+## How to Use Virtualenv14+15+Create your project folder, then a virtualenv within it:16+17+```console18+$ mkdir myproject19+$ cd myproject20+$ python3 -m venv .venv21+```22+23+Now, whenever you want to work on a project, you only have to activate the corresponding environment.24+25+26+```{eval-rst}27+.. tabs::28+29+ .. group-tab:: OSX/Linux30+31+ .. code-block:: text32+33+ $ . .venv/bin/activate34+ (venv) $35+36+ .. group-tab:: Windows37+38+ .. code-block:: text39+40+ > .venv\scripts\activate41+ (venv) >42+```43+44+You are now using your virtualenv (notice how the prompt of your shell has changed to show the active environment).45+46+To install packages in the virtual environment:47+48+```console49+$ pip install click50+```51+52+And if you want to stop using the virtualenv, use the following command:53+54+```console55+$ deactivate56+```57+58+After doing this, the prompt of your shell should be as familiar as before.deleted:docs/virtualenv.rst-54 removed
1-.. _virtualenv-heading:2-3-Virtualenv4-=========================5-6-Why Use Virtualenv?7--------------------------8-9-You should use `Virtualenv <https://virtualenv.pypa.io/en/latest/>`_ because:10-11-* It allows you to install multiple versions of the same dependency.12-13-* If you have an operating system version of Python, it prevents you from changing its dependencies and potentially messing up your os.14-15-How to Use Virtualenv16------------------------------17-18-Create your project folder, then a virtualenv within it::19-20- $ mkdir myproject21- $ cd myproject22- $ python3 -m venv .venv23-24-Now, whenever you want to work on a project, you only have to activate the25-corresponding environment.26-27-.. tabs::28-29- .. group-tab:: OSX/Linux30-31- .. code-block:: text32-33- $ . .venv/bin/activate34- (venv) $35-36- .. group-tab:: Windows37-38- .. code-block:: text39-40- > .venv\scripts\activate41- (venv) >42-43-44-You are now using your virtualenv (notice how the prompt of your shell has changed to show the active environment).45-46-To install packages in the virtual environment::47-48- $ pip install click49-50-And if you want to stop using the virtualenv, use the following command::51-52- $ deactivate53-54-After doing this, the prompt of your shell should be as familiar as before.added:docs/why.md+106 added
1+# Why Click?2+3+There are so many libraries out there for writing command line utilities; why does Click exist?4+5+This question is easy to answer: because there is not a single command line utility for Python out there which ticks the6+following boxes:7+8+- Is lazily composable without restrictions.9+- Supports implementation of Unix/POSIX command line conventions.10+- Supports loading values from environment variables out of the box.11+- Support for prompting of custom values.12+- Is fully nestable and composable.13+- Supports file handling out of the box.14+- Comes with useful common helpers (getting terminal dimensions, ANSI colors, fetching direct keyboard input, screen15+ clearing, finding config paths, launching apps and editors, etc.).16+17+There are many alternatives to Click; the obvious ones are `optparse` and `argparse` from the standard library. Have a18+look to see if something else resonates with you.19+20+Click actually implements its own parsing of arguments and does not use `optparse` or `argparse` following the21+`optparse` parsing behavior. The reason it's not based on `argparse` is that `argparse` does not allow proper nesting of22+commands by design and has some deficiencies when it comes to POSIX compliant argument handling.23+24+Click is designed to be fun and customizable but not overly flexible. For instance, the customizability of help pages is25+constrained. This constraint is intentional because Click promises multiple Click instances will continue to function as26+intended when strung together.27+28+Too much customizability would break this promise.29+30+Click was written to support the [Flask](https://palletsprojects.com/p/flask/) microframework ecosystem because no tool31+could provide it with the functionality it needed.32+33+To get an understanding of what Click is all about, I strongly recommend looking at the {ref}`complex-guide` chapter.34+35+## Why not Argparse?36+37+Click is internally based on `optparse` instead of `argparse`. This is an implementation detail that a user does not38+have to be concerned with. Click is not based on `argparse` because it has some behaviors that make handling arbitrary39+command line interfaces hard:40+41+- `argparse` has built-in behavior to guess if something is an argument or an option. This becomes a problem when42+ dealing with incomplete command lines; the behaviour becomes unpredictable without full knowledge of a command line.43+ This goes against Click's ambitions of dispatching to subparsers.44+- `argparse` does not support disabling interspersed arguments. Without this feature, it's not possible to safely45+ implement Click's nested parsing.46+47+## Why not Docopt etc.?48+49+Docopt, and many tools like it, are cool in how they work, but very few of these tools deal with nesting of commands and50+composability in a way like Click. To the best of the developer's knowledge, Click is the first Python library that aims51+to create a level of composability of applications that goes beyond what the system itself supports.52+53+Docopt, for instance, acts by parsing your help pages and then parsing according to those rules. The side effect of this54+is that docopt is quite rigid in how it handles the command line interface. The upside of docopt is that it gives you55+strong control over your help page; the downside is that due to this it cannot rewrap your output for the current56+terminal width, and it makes translations hard. On top of that, docopt is restricted to basic parsing. It does not57+handle argument dispatching and callback invocation or types. This means there is a lot of code that needs to be written58+in addition to the basic help page to handle the parsing results.59+60+Most of all, however, it makes composability hard. While docopt does support dispatching to subcommands, it, for61+instance, does not directly support any kind of automatic subcommand enumeration based on what's available or it does62+not enforce subcommands to work in a consistent way.63+64+This is fine, but it's different from how Click wants to work. Click aims to support fully composable command line user65+interfaces by doing the following:66+67+- Click does not just parse, it also dispatches to the appropriate code.68+- Click has a strong concept of an invocation context that allows subcommands to respond to data from the parent69+ command.70+- Click has strong information available for all parameters and commands, so it can generate unified help pages for the71+ full CLI and assist the user in converting the input data as necessary.72+- Click has a strong understanding of what types are, and it can give the user consistent error messages if something73+ goes wrong. A subcommand written by a different developer will not suddenly die with a different error message because74+ it's manually handled.75+- Click has enough meta information available for its whole program to evolve over time and improve the user experience76+ without forcing developers to adjust their programs. For instance, if Click decides to change how help pages are77+ formatted, all Click programs will automatically benefit from this.78+79+The aim of Click is to make composable systems. Whereas, the aim of docopt is to build the most beautiful and80+hand-crafted command line interfaces. These two goals conflict with one another in subtle ways. Click actively prevents81+people from implementing certain patterns in order to achieve unified command line interfaces. For instance, as a82+developer, you are given very little choice in formatting your help pages.83+84+## Why Hardcoded Behaviors?85+86+The other question is why Click goes away from optparse and hardcodes certain behaviors instead of staying configurable.87+There are multiple reasons for this. The biggest one is that too much configurability makes it hard to achieve a88+consistent command line experience.89+90+The best example for this is optparse's `callback` functionality for accepting an arbitrary number of arguments. Due to91+syntactical ambiguities on the command line, there is no way to implement fully variadic arguments. There are always92+tradeoffs that need to be made and in case of `argparse` these tradeoffs have been critical enough, that a system like93+Click cannot even be implemented on top of it.94+95+In this particular case, Click attempts to stay with a handful of accepted paradigms for building command line96+interfaces that can be well documented and tested.97+98+## Why No Auto Correction?99+100+The question came up why Click does not auto correct parameters given that even optparse and `argparse` support101+automatic expansion of long arguments. The reason for this is that it's a liability for backwards compatibility. If102+people start relying on automatically modified parameters and someone adds a new parameter in the future, the script103+might stop working. These kinds of problems are hard to find, so Click does not attempt to be magical about this.104+105+This sort of behavior however can be implemented on a higher level to support things such as explicit aliases. For more106+information see {ref}`aliases`.deleted:docs/why.rst-146 removed
1-Why Click?2-==========3-4-There are so many libraries out there for writing command line utilities;5-why does Click exist?6-7-This question is easy to answer: because there is not a single command8-line utility for Python out there which ticks the following boxes:9-10-* Is lazily composable without restrictions.11-* Supports implementation of Unix/POSIX command line conventions.12-* Supports loading values from environment variables out of the box.13-* Support for prompting of custom values.14-* Is fully nestable and composable.15-* Supports file handling out of the box.16-* Comes with useful common helpers (getting terminal dimensions,17- ANSI colors, fetching direct keyboard input, screen clearing,18- finding config paths, launching apps and editors, etc.).19-20-There are many alternatives to Click; the obvious ones are ``optparse``21-and ``argparse`` from the standard library. Have a look to see if something22-else resonates with you.23-24-Click actually implements its own parsing of arguments and does not use25-``optparse`` or ``argparse`` following the ``optparse`` parsing behavior.26-The reason it's not based on ``argparse`` is that ``argparse`` does not27-allow proper nesting of commands by design and has some deficiencies when28-it comes to POSIX compliant argument handling.29-30-Click is designed to be fun and customizable but not overly flexible.31-For instance, the customizability of help pages is constrained. This32-constraint is intentional because Click promises multiple Click instances33-will continue to function as intended when strung together.34-35-Too much customizability would break this promise.36-37-Click was written to support the `Flask <https://palletsprojects.com/p/flask/>`_38-microframework ecosystem because no tool could provide it with the39-functionality it needed.40-41-To get an understanding of what Click is all about, I strongly recommend42-looking at the :ref:`complex-guide` chapter.43-44-Why not Argparse?45------------------46-47-Click is internally based on ``optparse`` instead of ``argparse``. This48-is an implementation detail that a user does not have to be concerned49-with. Click is not based on ``argparse`` because it has some behaviors that50-make handling arbitrary command line interfaces hard:51-52-* ``argparse`` has built-in behavior to guess if something is an53- argument or an option. This becomes a problem when dealing with54- incomplete command lines; the behaviour becomes unpredictable55- without full knowledge of a command line. This goes against Click's56- ambitions of dispatching to subparsers.57-* ``argparse`` does not support disabling interspersed arguments. Without58- this feature, it's not possible to safely implement Click's nested59- parsing.60-61-Why not Docopt etc.?62---------------------63-64-Docopt, and many tools like it, are cool in how they work, but very few of65-these tools deal with nesting of commands and composability in a way like66-Click. To the best of the developer's knowledge, Click is the first67-Python library that aims to create a level of composability of applications68-that goes beyond what the system itself supports.69-70-Docopt, for instance, acts by parsing your help pages and then parsing71-according to those rules. The side effect of this is that docopt is quite72-rigid in how it handles the command line interface. The upside of docopt73-is that it gives you strong control over your help page; the downside is74-that due to this it cannot rewrap your output for the current terminal75-width, and it makes translations hard. On top of that, docopt is restricted76-to basic parsing. It does not handle argument dispatching and callback77-invocation or types. This means there is a lot of code that needs to be78-written in addition to the basic help page to handle the parsing results.79-80-Most of all, however, it makes composability hard. While docopt does81-support dispatching to subcommands, it, for instance, does not directly82-support any kind of automatic subcommand enumeration based on what's83-available or it does not enforce subcommands to work in a consistent way.84-85-This is fine, but it's different from how Click wants to work. Click aims86-to support fully composable command line user interfaces by doing the87-following:88-89-- Click does not just parse, it also dispatches to the appropriate code.90-- Click has a strong concept of an invocation context that allows91- subcommands to respond to data from the parent command.92-- Click has strong information available for all parameters and commands,93- so it can generate unified help pages for the full CLI and94- assist the user in converting the input data as necessary.95-- Click has a strong understanding of what types are, and it can give the user96- consistent error messages if something goes wrong. A subcommand97- written by a different developer will not suddenly die with a98- different error message because it's manually handled.99-- Click has enough meta information available for its whole program100- to evolve over time and improve the user experience without101- forcing developers to adjust their programs. For instance, if Click102- decides to change how help pages are formatted, all Click programs103- will automatically benefit from this.104-105-The aim of Click is to make composable systems. Whereas, the aim of docopt106-is to build the most beautiful and hand-crafted command line interfaces.107-These two goals conflict with one another in subtle ways. Click108-actively prevents people from implementing certain patterns in order to109-achieve unified command line interfaces. For instance, as a developer, you110-are given very little choice in formatting your help pages.111-112-113-Why Hardcoded Behaviors?114-------------------------115-116-The other question is why Click goes away from optparse and hardcodes117-certain behaviors instead of staying configurable. There are multiple118-reasons for this. The biggest one is that too much configurability makes119-it hard to achieve a consistent command line experience.120-121-The best example for this is optparse's ``callback`` functionality for122-accepting an arbitrary number of arguments. Due to syntactical ambiguities123-on the command line, there is no way to implement fully variadic arguments.124-There are always tradeoffs that need to be made and in case of125-``argparse`` these tradeoffs have been critical enough, that a system like126-Click cannot even be implemented on top of it.127-128-In this particular case, Click attempts to stay with a handful of accepted129-paradigms for building command line interfaces that can be well documented130-and tested.131-132-133-Why No Auto Correction?134------------------------135-136-The question came up why Click does not auto correct parameters given that137-even optparse and ``argparse`` support automatic expansion of long arguments.138-The reason for this is that it's a liability for backwards compatibility.139-If people start relying on automatically modified parameters and someone140-adds a new parameter in the future, the script might stop working. These141-kinds of problems are hard to find, so Click does not attempt to be magical142-about this.143-144-This sort of behavior however can be implemented on a higher level to145-support things such as explicit aliases. For more information see146-:ref:`aliases`.added:docs/wincmd.md+47 added
1+# Windows Console Notes2+3+```{versionadded} 6.04+```5+6+Click emulates output streams on Windows to support unicode to the Windows console through separate APIs and we perform7+different decoding of parameters.8+9+Here is a brief overview of how this works and what it means to you.10+11+## Unicode Arguments12+13+Click internally is generally based on the concept that any argument can come in as either byte string or unicode string14+and conversion is performed to the type expected value as late as possible. This has some advantages as it allows us to15+accept the data in the most appropriate form for the operating system and Python version.16+17+This caused some problems on Windows where initially the wrong encoding was used and garbage ended up in your input18+data. We not only fixed the encoding part, but we also now extract unicode parameters from `sys.argv`.19+20+There is also another limitation with this: if `sys.argv` was modified prior to invoking a click handler, we have to21+fall back to the regular byte input in which case not all unicode values are available but only a subset of the codepage22+used for parameters.23+24+## Unicode Output and Input25+26+Unicode output and input on Windows is implemented through the concept of a dispatching text stream. What this means is27+that when click first needs a text output (or input) stream on windows it goes through a few checks to figure out of a28+windows console is connected or not. If no Windows console is present then the text output stream is returned as such29+and the encoding for that stream is set to `utf-8` like on all platforms.30+31+However if a console is connected the stream will instead be emulated and use the cmd.exe unicode APIs to output text32+information. In this case the stream will also use `utf-16-le` as internal encoding. However there is some hackery going33+on that the underlying raw IO buffer is still bypassing the unicode APIs and byte output through an indirection is still34+possible.35+36+- This unicode support is limited to `click.echo`, `click.prompt` as well as `click.get_text_stream`.37+- Depending on if unicode values or byte strings are passed the control flow goes completely different places internally38+ which can have some odd artifacts if data partially ends up being buffered. Click attempts to protect against that by39+ manually always flushing but if you are mixing and matching different string types to `stdout` or `stderr` you will40+ need to manually flush.41+- The raw output stream is set to binary mode, which is a global operation on Windows, so `print` calls will be42+ affected. Prefer `click.echo` over `print`.43+- On Windows 7 and below, there is a limitation where at most 64k characters can be written in one call in binary mode.44+ In this situation, `sys.stdout` and `sys.stderr` are replaced with wrappers that work around the limitation.45+46+Another important thing to note is that the Windows console's default fonts do not support a lot of characters which47+means that you are mostly limited to international letters but no emojis or special characters.deleted:docs/wincmd.rst-64 removed
1-Windows Console Notes2-=====================3-4-.. versionadded:: 6.05-6-Click emulates output streams on Windows to support unicode to the7-Windows console through separate APIs and we perform different decoding of8-parameters.9-10-Here is a brief overview of how this works and what it means to you.11-12-Unicode Arguments13------------------14-15-Click internally is generally based on the concept that any argument can16-come in as either byte string or unicode string and conversion is17-performed to the type expected value as late as possible. This has some18-advantages as it allows us to accept the data in the most appropriate form19-for the operating system and Python version.20-21-This caused some problems on Windows where initially the wrong encoding22-was used and garbage ended up in your input data. We not only fixed the23-encoding part, but we also now extract unicode parameters from `sys.argv`.24-25-There is also another limitation with this: if `sys.argv` was modified26-prior to invoking a click handler, we have to fall back to the regular27-byte input in which case not all unicode values are available but only a28-subset of the codepage used for parameters.29-30-Unicode Output and Input31-------------------------32-33-Unicode output and input on Windows is implemented through the concept of34-a dispatching text stream. What this means is that when click first needs35-a text output (or input) stream on windows it goes through a few checks to36-figure out of a windows console is connected or not. If no Windows37-console is present then the text output stream is returned as such and the38-encoding for that stream is set to ``utf-8`` like on all platforms.39-40-However if a console is connected the stream will instead be emulated and41-use the cmd.exe unicode APIs to output text information. In this case the42-stream will also use ``utf-16-le`` as internal encoding. However there is43-some hackery going on that the underlying raw IO buffer is still bypassing44-the unicode APIs and byte output through an indirection is still possible.45-46-* This unicode support is limited to ``click.echo``, ``click.prompt`` as47- well as ``click.get_text_stream``.48-* Depending on if unicode values or byte strings are passed the control49- flow goes completely different places internally which can have some50- odd artifacts if data partially ends up being buffered. Click51- attempts to protect against that by manually always flushing but if52- you are mixing and matching different string types to ``stdout`` or53- ``stderr`` you will need to manually flush.54-* The raw output stream is set to binary mode, which is a global55- operation on Windows, so ``print`` calls will be affected. Prefer56- ``click.echo`` over ``print``.57-* On Windows 7 and below, there is a limitation where at most 64k58- characters can be written in one call in binary mode. In this59- situation, ``sys.stdout`` and ``sys.stderr`` are replaced with60- wrappers that work around the limitation.61-62-Another important thing to note is that the Windows console's default63-fonts do not support a lot of characters which means that you are mostly64-limited to international letters but no emojis or special characters.modified:src/click/_termui_impl.py+14 added-6 removed
15 unmodified lines16 import typing as t17 from gettext import gettext as _18 from io import StringIO19 from pathlib import Path20-from shutil import which20 from types import TracebackType21 22 from ._compat import _default_text_stdout23 from ._compat import CYGWIN209 unmodified lines233 }234 ).rstrip()235 236 def render_progress(self) -> None:238- import shutil239-237 if self.hidden:238 return239 240 if not self._is_atty:5 unmodified lines246 247 buf = []248 # Update width in case the terminal has been resized249 if self.autowidth:250+ import shutil251+252 old_width = self.width253 self.width = 0254 clutter_length = term_len(self.format_progress_line())255 new_width = max(0, shutil.get_terminal_size().columns - clutter_length)163 unmodified lines419 """420 # Split the command into the invoked CLI and its parameters.421 if not cmd_parts:422 return False423+424+ import shutil425+426 cmd = cmd_parts[0]427 cmd_params = cmd_parts[1:]428 427- cmd_filepath = which(cmd)429+ cmd_filepath = shutil.which(cmd)430 if not cmd_filepath:431 return False432 # Resolves symlinks and produces a normalized absolute path string.433 cmd_path = Path(cmd_filepath).resolve()77 unmodified lines511 """512 # Split the command into the invoked CLI and its parameters.513 if not cmd_parts:514 return False515+516+ import shutil517+518 cmd = cmd_parts[0]519 515- cmd_filepath = which(cmd)520+ cmd_filepath = shutil.which(cmd)521 if not cmd_filepath:522 return False523 # Resolves symlinks and produces a normalized absolute path string.524 cmd_path = Path(cmd_filepath).resolve()52 unmodified lines577 if rv:578 return rv579 if WIN:580 return "notepad"581+582+ from shutil import which583+584 for editor in "sensible-editor", "vim", "nano":585 if which(editor) is not None:586 return editor587 return "vi"35 unmodified lines623 def edit(self, text: str | bytes | bytearray | None) -> str | bytes | None:624 import tempfile625 626 if text is None:619- data = b""627+ data: bytes | bytearray = b""628 elif isinstance(text, (bytes, bytearray)):629 data = text630 else:631 if text and not text.endswith("\n"):216 unmodified linesadded:src/click/_utils.py+36 added
1+from __future__ import annotations2+3+import enum4+import typing as t5+6+7+class Sentinel(enum.Enum):8+ """Enum used to define sentinel values.9+10+ .. seealso::11+12+ `PEP 661 - Sentinel Values <https://peps.python.org/pep-0661/>`_.13+ """14+15+ UNSET = object()16+ FLAG_NEEDS_VALUE = object()17+18+ def __repr__(self) -> str:19+ return f"{self.__class__.__name__}.{self.name}"20+21+22+UNSET = Sentinel.UNSET23+"""Sentinel used to indicate that a value is not set."""24+25+FLAG_NEEDS_VALUE = Sentinel.FLAG_NEEDS_VALUE26+"""Sentinel used to indicate an option was passed as a flag without a27+value but is not a flag option.28+29+``Option.consume_value`` uses this to prompt or use the ``flag_value``.30+"""31+32+T_UNSET = t.Literal[UNSET] # type: ignore[valid-type]33+"""Type hint for the :data:`UNSET` sentinel value."""34+35+T_FLAG_NEEDS_VALUE = t.Literal[FLAG_NEEDS_VALUE] # type: ignore[valid-type]36+"""Type hint for the :data:`FLAG_NEEDS_VALUE` sentinel value."""modified:src/click/core.py+381 added-169 removed
17 unmodified lines18 from itertools import repeat19 from types import TracebackType20 21 from . import types22+from ._utils import FLAG_NEEDS_VALUE23+from ._utils import UNSET24 from .exceptions import Abort25 from .exceptions import BadParameter26 from .exceptions import ClickException27 from .exceptions import Exit3 unmodified lines31 from .formatting import HelpFormatter32 from .formatting import join_options33 from .globals import pop_context34 from .globals import push_context33-from .parser import _flag_needs_value35 from .parser import _OptionParser36 from .parser import _split_opt37 from .termui import confirm38 from .termui import prompt443 unmodified lines482 self,483 exc_type: type[BaseException] | None,484 exc_value: BaseException | None,485 tb: TracebackType | None,485- ) -> None:486+ ) -> bool | None:487 self._depth -= 1488+ exit_result: bool | None = None489 if self._depth == 0:488- self.close()490+ exit_result = self._close_with_exception_info(exc_type, exc_value, tb)491 pop_context()492 493+ return exit_result494+495 @contextmanager496 def scope(self, cleanup: bool = True) -> cabc.Iterator[Context]:497 """This helper method can be used with the context object to promote498 it to the current thread local (see :func:`get_current_context`).118 unmodified lines617 """Invoke all close callbacks registered with618 :meth:`call_on_close`, and exit all context managers entered619 with :meth:`with_resource`.620 """617- self._exit_stack.close()621+ self._close_with_exception_info(None, None, None)622+623+ def _close_with_exception_info(624+ self,625+ exc_type: type[BaseException] | None,626+ exc_value: BaseException | None,627+ tb: TracebackType | None,628+ ) -> bool | None:629+ """Unwind the exit stack by calling its :meth:`__exit__` providing the exception630+ information to allow for exception handling by the various resources registered631+ using :meth;`with_resource`632+633+ :return: Whatever ``exit_stack.__exit__()`` returns.634+ """635+ exit_result = self._exit_stack.__exit__(exc_type, exc_value, tb)636 # In case the context is reused, create a new exit stack.637 self._exit_stack = ExitStack()638 639+ return exit_result640+641 @property642 def command_path(self) -> str:643 """The computed command path. This is used for the ``usage``644 information on the help page. It's automatically created by60 unmodified lines705 .. versionchanged:: 8.0706 Added the ``call`` parameter.707 """708 if self.default_map is not None:689- value = self.default_map.get(name)709+ value = self.default_map.get(name, UNSET)710 711 if call and callable(value):712 return value()713 714 return value715 696- return None716+ return UNSET717 718 def fail(self, message: str) -> t.NoReturn:719 """Aborts the execution of the program with a specific error720 message.492 unmodified lines1213 parser = self.make_parser(ctx)1214 opts, args, param_order = parser.parse_args(args=args)1215 1216 for param in iter_params_for_processing(param_order, self.get_params(ctx)):1197- value, args = param.handle_parse_result(ctx, opts, args)1217+ _, args = param.handle_parse_result(ctx, opts, args)1218 1219 if args and not ctx.allow_extra_args and not ctx.resilient_parsing:1220 ctx.fail(1221 ngettext(812 unmodified lines2034 otherwise it's skipped.2035 :param is_eager: eager values are processed before non eager ones. This2036 should not be set for arguments or it will inverse the2037 order of processing.2018- :param envvar: a string or list of strings that are environment variables2019- that should be checked.2038+ :param envvar: environment variable(s) that are used to provide a default value for2039+ this parameter. This can be a string or a sequence of strings. If a sequence is2040+ given, only the first non-empty environment variable is used for the parameter.2041 :param shell_complete: A function that returns custom shell2042 completions. Used instead of the param's type completion if2043 given. Takes ``ctx, param, incomplete`` and must return a list2044 of :class:`~click.shell_completion.CompletionItem` or a list of53 unmodified lines2098 self,2099 param_decls: cabc.Sequence[str] | None = None,2100 type: types.ParamType | t.Any | None = None,2101 required: bool = False,2102+ # XXX The default historically embed two concepts:2103+ # - the declaration of a Parameter object carrying the default (handy to2104+ # arbitrage the default value of coupled Parameters sharing the same2105+ # self.name, like flag options),2106+ # - and the actual value of the default.2107+ # It is confusing and is the source of many issues discussed in:2108+ # https://github.com/pallets/click/pull/30302109+ # In the future, we might think of splitting it in two, not unlike2110+ # Option.is_flag and Option.flag_value: we could have something like2111+ # Parameter.is_default and Parameter.default_value.2081- default: t.Any | t.Callable[[], t.Any] | None = None,2112+ default: t.Any | t.Callable[[], t.Any] | None = UNSET,2113 callback: t.Callable[[Context, Parameter, t.Any], t.Any] | None = None,2114 nargs: int | None = None,2115 multiple: bool = False,2116 metavar: str | None = None,40 unmodified lines2157 f"'nargs' must be {self.type.arity} (or None) for"2158 f" type {self.type!r}, but it was {nargs}."2159 )2160 2130- # Skip no default or callable default.2131- check_default = default if not callable(default) else None2132-2133- if check_default is not None:2134- if multiple:2135- try:2136- # Only check the first value against nargs.2137- check_default = next(_check_iter(check_default), None)2138- except TypeError:2139- raise ValueError(2140- "'default' must be a list when 'multiple' is true."2141- ) from None2142-2143- # Can be None for multiple with empty default.2144- if nargs != 1 and check_default is not None:2145- try:2146- _check_iter(check_default)2147- except TypeError:2148- if multiple:2149- message = (2150- "'default' must be a list of lists when 'multiple' is"2151- " true and 'nargs' != 1."2152- )2153- else:2154- message = "'default' must be a list when 'nargs' != 1."2155-2156- raise ValueError(message) from None2157-2158- if nargs > 1 and len(check_default) != nargs:2159- subject = "item length" if multiple else "length"2160- raise ValueError(2161- f"'default' {subject} must match nargs={nargs}."2162- )2163-2161 if required and deprecated:2162 raise ValueError(2163 f"The {self.param_type_name} '{self.human_readable_name}' "2164 "is deprecated and still required. A deprecated "6 unmodified lines2171 2172 Use :meth:`click.Context.to_info_dict` to traverse the entire2173 CLI structure.2174 2175+ .. versionchanged:: 8.3.02176+ Returns ``None`` for the :attr:`default` if it was not set.2177+2178 .. versionadded:: 8.02179 """2180 return {2181 "name": self.name,3 unmodified lines2185 "type": self.type.to_info_dict(),2186 "required": self.required,2187 "nargs": self.nargs,2188 "multiple": self.multiple,2189- "default": self.default,2189+ # We explicitly hide the :attr:`UNSET` value to the user, as we choose to2190+ # make it an implementation detail. And because ``to_info_dict`` has been2191+ # designed for documentation purposes, we return ``None`` instead.2192+ "default": self.default if self.default is not UNSET else None,2193 "envvar": self.envvar,2194 }2195 2196 def __repr__(self) -> str:59 unmodified lines2256 Added the ``call`` parameter.2257 """2258 value = ctx.lookup_default(self.name, call=False) # type: ignore2259 2257- if value is None:2260+ if value is UNSET:2261 value = self.default2262 2263 if call and callable(value):2264 value = value()5 unmodified lines2270 2271 def consume_value(2272 self, ctx: Context, opts: cabc.Mapping[str, t.Any]2273 ) -> tuple[t.Any, ParameterSource]:2271- value = opts.get(self.name) # type: ignore2272- source = ParameterSource.COMMANDLINE2274+ """Returns the parameter value produced by the parser.2275 2274- if value is None:2275- value = self.value_from_envvar(ctx)2276- source = ParameterSource.ENVIRONMENT2276+ If the parser did not produce a value from user input, the value is either2277+ sourced from the environment variable, the default map, or the parameter's2278+ default value. In that order of precedence.2279 2278- if value is None:2279- value = ctx.lookup_default(self.name) # type: ignore2280- source = ParameterSource.DEFAULT_MAP2280+ If no value is found, an internal sentinel value is returned.2281 2282- if value is None:2283- value = self.get_default(ctx)2284- source = ParameterSource.DEFAULT2282+ :meta private:2283+ """2284+ # Collect from the parse the value passed by the user to the CLI.2285+ value = opts.get(self.name, UNSET) # type: ignore2286+ # If the value is set, it means it was sourced from the command line by the2287+ # parser, otherwise it left unset by default.2288+ source = (2289+ ParameterSource.COMMANDLINE2290+ if value is not UNSET2291+ else ParameterSource.DEFAULT2292+ )2293 2294+ if value is UNSET:2295+ envvar_value = self.value_from_envvar(ctx)2296+ if envvar_value is not None:2297+ value = envvar_value2298+ source = ParameterSource.ENVIRONMENT2299+2300+ if value is UNSET:2301+ default_map_value = ctx.lookup_default(self.name) # type: ignore2302+ if default_map_value is not UNSET:2303+ value = default_map_value2304+ source = ParameterSource.DEFAULT_MAP2305+2306+ if value is UNSET:2307+ default_value = self.get_default(ctx)2308+ if default_value is not UNSET:2309+ value = default_value2310+ source = ParameterSource.DEFAULT2311+2312 return value, source2313 2314 def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any:2289- """Convert and validate a value against the option's2315+ """Convert and validate a value against the parameter's2316 :attr:`type`, :attr:`multiple`, and :attr:`nargs`.2317 """2292- if value is None:2293- return () if self.multiple or self.nargs == -1 else None2318+ if value in (None, UNSET):2319+ if self.multiple or self.nargs == -1:2320+ return ()2321+ else:2322+ return value2323 2324 def check_iter(value: t.Any) -> cabc.Iterator[t.Any]:2325 try:2326 return _check_iter(value)4 unmodified lines2331 raise BadParameter(2332 _("Value must be an iterable."), ctx=ctx, param=self2333 ) from None2334 2335+ # Define the conversion function based on nargs and type.2336+2337 if self.nargs == 1 or self.type.is_composite:2338 2339 def convert(value: t.Any) -> t.Any:2340 return self.type(value, param=self, ctx=ctx)26 unmodified lines2367 2368 return convert(value)2369 2370 def value_is_missing(self, value: t.Any) -> bool:2371+ """A value is considered missing if:2372+2373+ - it is :attr:`UNSET`,2374+ - or if it is an empty sequence while the parameter is suppose to have2375+ non-single value (i.e. :attr:`nargs` is not ``1`` or :attr:`multiple` is2376+ set).2377+2378+ :meta private:2379+ """2340- if value is None:2380+ if value is UNSET:2381 return True2382 2383 if (self.nargs != 1 or self.multiple) and value == ():2384 return True2385 2386 return False2387 2388 def process_value(self, ctx: Context, value: t.Any) -> t.Any:2389+ """Process the value of this parameter:2390+2391+ 1. Type cast the value using :meth:`type_cast_value`.2392+ 2. Check if the value is missing (see: :meth:`value_is_missing`), and raise2393+ :exc:`MissingParameter` if it is required.2394+ 3. If a :attr:`callback` is set, call it to have the value replaced by the2395+ result of the callback. If the value was not set, the callback receive2396+ ``None``. This keep the legacy behavior as it was before the introduction of2397+ the :attr:`UNSET` sentinel.2398+2399+ :meta private:2400+ """2401 value = self.type_cast_value(ctx, value)2402 2403 if self.required and self.value_is_missing(value):2404 raise MissingParameter(ctx=ctx, param=self)2405 2406 if self.callback is not None:2407+ # Legacy case: UNSET is not exposed directly to the callback, but converted2408+ # to None.2409+ if value is UNSET:2410+ value = None2411 value = self.callback(ctx, self, value)2412 2413 return value2414 2415 def resolve_envvar_value(self, ctx: Context) -> str | None:2360- if self.envvar is None:2416+ """Returns the value found in the environment variable(s) attached to this2417+ parameter.2418+2419+ Environment variables values are `always returned as strings2420+ <https://docs.python.org/3/library/os.html#os.environ>`_.2421+2422+ This method returns ``None`` if:2423+2424+ - the :attr:`envvar` property is not set on the :class:`Parameter`,2425+ - the environment variable is not found in the environment,2426+ - the variable is found in the environment but its value is empty (i.e. the2427+ environment variable is present but has an empty string).2428+2429+ If :attr:`envvar` is setup with multiple environment variables,2430+ then only the first non-empty value is returned.2431+2432+ .. caution::2433+2434+ The raw value extracted from the environment is not normalized and is2435+ returned as-is. Any normalization or reconciliation is performed later by2436+ the :class:`Parameter`'s :attr:`type`.2437+2438+ :meta private:2439+ """2440+ if not self.envvar:2441 return None2442 2443 if isinstance(self.envvar, str):2444 rv = os.environ.get(self.envvar)3 unmodified lines2448 else:2449 for envvar in self.envvar:2450 rv = os.environ.get(envvar)2451 2452+ # Return the first non-empty value of the list of environment variables.2453 if rv:2454 return rv2455+ # Else, absence of value is interpreted as an environment variable that2456+ # is not set, so proceed to the next one.2457 2458 return None2459 2377- def value_from_envvar(self, ctx: Context) -> t.Any | None:2378- rv: t.Any | None = self.resolve_envvar_value(ctx)2460+ def value_from_envvar(self, ctx: Context) -> str | cabc.Sequence[str] | None:2461+ """Process the raw environment variable string for this parameter.2462 2463+ Returns the string as-is or splits it into a sequence of strings if the2464+ parameter is expecting multiple values (i.e. its :attr:`nargs` property is set2465+ to a value other than ``1``).2466+2467+ :meta private:2468+ """2469+ rv = self.resolve_envvar_value(ctx)2470+2471 if rv is not None and self.nargs != 1:2381- rv = self.type.split_envvar_value(rv)2472+ return self.type.split_envvar_value(rv)2473 2474 return rv2475 2476 def handle_parse_result(2477 self, ctx: Context, opts: cabc.Mapping[str, t.Any], args: list[str]2478 ) -> tuple[t.Any, list[str]]:2479+ """Process the value produced by the parser from user input.2480+2481+ Always process the value through the Parameter's :attr:`type`, wherever it2482+ comes from.2483+2484+ If the parameter is deprecated, this method warn the user about it. But only if2485+ the value has been explicitly set by the user (and as such, is not coming from2486+ a default).2487+2488+ :meta private:2489+ """2490 with augment_usage_errors(ctx, param=self):2491 value, source = self.consume_value(ctx, opts)2492 2493+ ctx.set_parameter_source(self.name, source) # type: ignore2494+2495+ # Display a deprecation warning if necessary.2496 if (2497 self.deprecated2393- and value is not None2394- and source2395- not in (2396- ParameterSource.DEFAULT,2397- ParameterSource.DEFAULT_MAP,2398- )2498+ and value is not UNSET2499+ and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP)2500 ):2501 extra_message = (2502 f" {self.deprecated}" if isinstance(self.deprecated, str) else ""2503 )6 unmodified lines2510 extra_message=extra_message,2511 )2512 echo(style(message, fg="red"), err=True)2513 2413- ctx.set_parameter_source(self.name, source) # type: ignore2414-2514+ # Process the value through the parameter's type.2515 try:2516 value = self.process_value(ctx, value)2517 except Exception:2518 if not ctx.resilient_parsing:2519 raise2520+ # In resilient parsing mode, we do not want to fail the command if the2521+ # value is incompatible with the parameter type, so we reset the value2522+ # to UNSET, which will be interpreted as a missing value.2523+ value = UNSET2524 2421- value = None2525+ # Add parameter's value to the context.2526+ if (2527+ self.expose_value2528+ # We skip adding the value if it was previously set by another parameter2529+ # targeting the same variable name. This prevents parameters competing for2530+ # the same name to override each other.2531+ and self.name not in ctx.params2532+ ):2533+ # Click is logically enforcing that the name is None if the parameter is2534+ # not to be exposed. We still assert it here to please the type checker.2535+ assert self.name is not None, (2536+ f"{self!r} parameter's name should not be None when exposing value."2537+ )2538+ # Normalize UNSET values to None, as we're about to pass them to the2539+ # command function and move them to the pure-Python realm of user-written2540+ # code.2541+ ctx.params[self.name] = value if value is not UNSET else None2542 2423- if self.expose_value:2424- ctx.params[self.name] = value # type: ignore2425-2543 return value, args2544 2545 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:2546 pass108 unmodified lines2655 confirmation_prompt: bool | str = False,2656 prompt_required: bool = True,2657 hide_input: bool = False,2658 is_flag: bool | None = None,2542- flag_value: t.Any | None = None,2659+ flag_value: t.Any = UNSET,2660 multiple: bool = False,2661 count: bool = False,2662 allow_from_autoenv: bool = True,2663 type: types.ParamType | t.Any | None = None,6 unmodified lines2670 ) -> None:2671 if help:2672 help = inspect.cleandoc(help)2673 2557- default_is_missing = "default" not in attrs2674 super().__init__(2675 param_decls, type=type, multiple=multiple, deprecated=deprecated, **attrs2676 )2677 20 unmodified lines2698 self.prompt_required = prompt_required2699 self.hide_input = hide_input2700 self.hidden = hidden2701 2586- # If prompt is enabled but not required, then the option can be2587- # used as a flag to indicate using prompt or flag_value.2702+ # The _flag_needs_value property tells the parser that this option is a flag2703+ # that cannot be used standalone and needs a value. With this information, the2704+ # parser can determine whether to consider the next user-provided argument in2705+ # the CLI as a value for this flag or as a new option.2706+ # If prompt is enabled but not required, then it opens the possibility for the2707+ # option to gets its value from the user.2708 self._flag_needs_value = self.prompt is not None and not self.prompt_required2709 2710+ # Auto-detect if this is a flag or not.2711 if is_flag is None:2591- if flag_value is not None:2592- # Implicitly a flag because flag_value was set.2712+ # Implicitly a flag because flag_value was set.2713+ if flag_value is not UNSET:2714 is_flag = True2715+ # Not a flag, but when used as a flag it shows a prompt.2716 elif self._flag_needs_value:2595- # Not a flag, but when used as a flag it shows a prompt.2717 is_flag = False2597- else:2598- # Implicitly a flag because flag options were given.2599- is_flag = bool(self.secondary_opts)2718+ # Implicitly a flag because secondary options names were given.2719+ elif self.secondary_opts:2720+ is_flag = True2721+ # The option is explicitly not a flag. But we do not know yet if it needs a2722+ # value or not. So we look at the default value to determine it.2723 elif is_flag is False and not self._flag_needs_value:2601- # Not a flag, and prompt is not enabled, can be used as a2602- # flag if flag_value is set.2603- self._flag_needs_value = flag_value is not None2724+ self._flag_needs_value = self.default is UNSET2725 2605- self.default: t.Any | t.Callable[[], t.Any]2726+ if is_flag:2727+ # Set missing default for flags if not explicitly required or prompted.2728+ if self.default is UNSET and not self.required and not self.prompt:2729+ if multiple:2730+ self.default = ()2731 2607- if is_flag and default_is_missing and not self.required:2608- if multiple:2609- self.default = ()2610- else:2611- self.default = False2732+ # Auto-detect the type of the flag based on the flag_value.2733+ if type is None:2734+ # A flag without a flag_value is a boolean flag.2735+ if flag_value is UNSET:2736+ self.type = types.BoolParamType()2737+ # If the flag value is a boolean, use BoolParamType.2738+ elif isinstance(flag_value, bool):2739+ self.type = types.BoolParamType()2740+ # Otherwise, guess the type from the flag value.2741+ else:2742+ self.type = types.convert_type(None, flag_value)2743 2613- if is_flag and flag_value is None:2614- flag_value = not self.default2744+ self.is_flag: bool = bool(is_flag)2745+ self.is_bool_flag: bool = bool(2746+ is_flag and isinstance(self.type, types.BoolParamType)2747+ )2748+ self.flag_value: t.Any = flag_value2749 2616- self.type: types.ParamType2617- if is_flag and type is None:2618- # Re-guess the type from the flag value instead of the2619- # default.2620- self.type = types.convert_type(None, flag_value)2750+ # Set boolean flag default to False if unset and not required.2751+ if self.is_bool_flag:2752+ if self.default is UNSET and not self.required:2753+ self.default = False2754 2622- self.is_flag: bool = is_flag2623- self.is_bool_flag: bool = is_flag and isinstance(self.type, types.BoolParamType)2624- self.flag_value: t.Any = flag_value2755+ # Support the special case of aligning the default value with the flag_value2756+ # for flags whose default is explicitly set to True. Note that as long as we2757+ # have this condition, there is no way a flag can have a default set to True,2758+ # and a flag_value set to something else. Refs:2759+ # https://github.com/pallets/click/issues/3024#issuecomment-31461994612760+ # https://github.com/pallets/click/pull/3030/commits/06847da2761+ if self.default is True and self.flag_value is not UNSET:2762+ self.default = self.flag_value2763 2764+ # Set the default flag_value if it is not set.2765+ if self.flag_value is UNSET:2766+ if self.is_flag:2767+ self.flag_value = True2768+ else:2769+ self.flag_value = None2770+2626- # Counting2771+ # Counting.2772 self.count = count2773 if count:2774 if type is None:2775 self.type = types.IntRange(min=0)2631- if default_is_missing:2776+ if self.default is UNSET:2777 self.default = 02778 2779 self.allow_from_autoenv = allow_from_autoenv2780 self.help = help7 unmodified lines2788 2789 if self.nargs == -1:2790 raise TypeError("nargs=-1 is not supported for options.")2791 2647- if self.prompt and self.is_flag and not self.is_bool_flag:2648- raise TypeError("'prompt' is not valid for non-boolean flag.")2649-2792 if not self.is_bool_flag and self.secondary_opts:2793 raise TypeError("Secondary flag is not valid for non-boolean flag.")2794 2795 if self.is_bool_flag and self.hide_input and self.prompt is not None:8 unmodified lines2804 if self.is_flag:2805 raise TypeError("'count' is not valid with 'is_flag'.")2806 2807 def to_info_dict(self) -> dict[str, t.Any]:2808+ """2809+ .. versionchanged:: 8.3.02810+ Returns ``None`` for the :attr:`flag_value` if it was not set.2811+ """2812 info_dict = super().to_info_dict()2813 info_dict.update(2814 help=self.help,2815 prompt=self.prompt,2816 is_flag=self.is_flag,2671- flag_value=self.flag_value,2817+ # We explicitly hide the :attr:`UNSET` value to the user, as we choose to2818+ # make it an implementation detail. And because ``to_info_dict`` has been2819+ # designed for documentation purposes, we return ``None`` instead.2820+ flag_value=self.flag_value if self.flag_value is not UNSET else None,2821 count=self.count,2822 hidden=self.hidden,2823 )2824 return info_dict2825 2826 def get_error_hint(self, ctx: Context) -> str:2827 result = super().get_error_hint(ctx)2679- if self.show_envvar:2828+ if self.show_envvar and self.envvar is not None:2829 result += f" (env var: '{self.envvar}')"2830 return result2831 2832 def _parse_decls(176 unmodified lines3009 show_default = self.show_default3010 elif ctx.show_default is not None:3011 show_default = ctx.show_default3012 2864- if show_default_is_str or (show_default and (default_value is not None)):3013+ if show_default_is_str or (3014+ show_default and (default_value not in (None, UNSET))3015+ ):3016 if show_default_is_str:3017 default_string = f"({self.show_default})"3018 elif isinstance(default_value, (list, tuple)):3019 default_string = ", ".join(str(d) for d in default_value)3020+ elif isinstance(default_value, enum.Enum):3021+ default_string = default_value.name3022 elif inspect.isfunction(default_value):3023 default_string = _("(dynamic)")3024 elif self.is_bool_flag and self.secondary_opts:3025 # For boolean flags that have distinct True/False opts,25 unmodified lines3051 extra["required"] = "required"3052 3053 return extra3054 2902- @t.overload2903- def get_default(2904- self, ctx: Context, call: t.Literal[True] = True2905- ) -> t.Any | None: ...2906-2907- @t.overload2908- def get_default(2909- self, ctx: Context, call: bool = ...2910- ) -> t.Any | t.Callable[[], t.Any] | None: ...2911-2912- def get_default(2913- self, ctx: Context, call: bool = True2914- ) -> t.Any | t.Callable[[], t.Any] | None:2915- # If we're a non boolean flag our default is more complex because2916- # we need to look at all flags in the same group to figure out2917- # if we're the default one in which case we return the flag2918- # value as default.2919- if self.is_flag and not self.is_bool_flag:2920- for param in ctx.command.params:2921- if param.name == self.name and param.default:2922- return t.cast(Option, param).flag_value2923-2924- return None2925-2926- return super().get_default(ctx, call=call)2927-3055 def prompt_for_value(self, ctx: Context) -> t.Any:3056 """This is an alternative flow that can be activated in the full3057 value processing if a value does not exist. It will prompt the3058 user until a valid value exists and then returns the processed3059 value as result.3060 """3061 assert self.prompt is not None3062 2936- # Calculate the default before prompting anything to be stable.3063+ # Calculate the default before prompting anything to lock in the value before3064+ # attempting any user interaction.3065 default = self.get_default(ctx)3066 2939- # If this is a prompt for a flag we need to handle this2940- # differently.3067+ # A boolean flag can use a simplified [y/n] confirmation prompt.3068 if self.is_bool_flag:3069+ # If we have no boolean default, we force the user to explicitly provide3070+ # one.3071+ if default in (UNSET, None):3072+ default = None3073+ # Nothing prevent you to declare an option that is simultaneously:3074+ # 1) auto-detected as a boolean flag,3075+ # 2) allowed to prompt, and3076+ # 3) still declare a non-boolean default.3077+ # This forced casting into a boolean is necessary to align any non-boolean3078+ # default to the prompt, which is going to be a [y/n]-style confirmation3079+ # because the option is still a boolean flag. That way, instead of [y/n],3080+ # we get [Y/n] or [y/N] depending on the truthy value of the default.3081+ # Refs: https://github.com/pallets/click/pull/3030#discussion_r22891802493082+ else:3083+ default = bool(default)3084 return confirm(self.prompt, default)3085 3086 # If show_default is set to True/False, provide this to `prompt` as well. For3087 # non-bool values of `show_default`, we use `prompt`'s default behavior2 unmodified lines3090 prompt_kwargs["show_default"] = self.show_default3091 3092 return prompt(3093 self.prompt,2952- default=default,3094+ # Use ``None`` to inform the prompt() function to reiterate until a valid3095+ # value is provided by the user if we have no default.3096+ default=None if default is UNSET else default,3097 type=self.type,3098 hide_input=self.hide_input,3099 show_choices=self.show_choices,3100 confirmation_prompt=self.confirmation_prompt,1 unmodified line3102 **prompt_kwargs,3103 )3104 3105 def resolve_envvar_value(self, ctx: Context) -> str | None:3106+ """:class:`Option` resolves its environment variable the same way as3107+ :func:`Parameter.resolve_envvar_value`, but it also supports3108+ :attr:`Context.auto_envvar_prefix`. If we could not find an environment from3109+ the :attr:`envvar` property, we fallback on :attr:`Context.auto_envvar_prefix`3110+ to build dynamiccaly the environment variable name using the3111+ :python:`{ctx.auto_envvar_prefix}_{self.name.upper()}` template.3112+3113+ :meta private:3114+ """3115 rv = super().resolve_envvar_value(ctx)3116 3117 if rv is not None:2965- if self.is_flag and self.flag_value:2966- return str(self.flag_value)3118 return rv3119 3120 if (3121 self.allow_from_autoenv7 unmodified lines3129 return rv3130 3131 return None3132 2982- def value_from_envvar(self, ctx: Context) -> t.Any | None:2983- rv: t.Any | None = self.resolve_envvar_value(ctx)3133+ def value_from_envvar(self, ctx: Context) -> t.Any:3134+ """For :class:`Option`, this method processes the raw environment variable3135+ string the same way as :func:`Parameter.value_from_envvar` does.3136 3137+ But in the case of non-boolean flags, the value is analyzed to determine if the3138+ flag is activated or not, and returns a boolean of its activation, or the3139+ :attr:`flag_value` if the latter is set.3140+3141+ This method also takes care of repeated options (i.e. options with3142+ :attr:`multiple` set to ``True``).3143+3144+ :meta private:3145+ """3146+ rv = self.resolve_envvar_value(ctx)3147+3148+ # Absent environment variable or an empty string is interpreted as unset.3149 if rv is None:3150 return None3151 2988- value_depth = (self.nargs != 1) + bool(self.multiple)3152+ # Non-boolean flags are more liberal in what they accept. But a flag being a3153+ # flag, its envvar value still needs to be analyzed to determine if the flag is3154+ # activated or not.3155+ if self.is_flag and not self.is_bool_flag:3156+ # If the flag_value is set and match the envvar value, return it3157+ # directly.3158+ if self.flag_value is not UNSET and rv == self.flag_value:3159+ return self.flag_value3160+ # Analyze the envvar value as a boolean to know if the flag is3161+ # activated or not.3162+ return types.BoolParamType.str_to_bool(rv)3163 3164+ # Split the envvar value if it is allowed to be repeated.3165+ value_depth = (self.nargs != 1) + bool(self.multiple)3166 if value_depth > 0:2991- rv = self.type.split_envvar_value(rv)2992-3167+ multi_rv = self.type.split_envvar_value(rv)3168 if self.multiple and self.nargs != 1:2994- rv = batch(rv, self.nargs)3169+ multi_rv = batch(multi_rv, self.nargs) # type: ignore[assignment]3170 3171+ return multi_rv3172+3173 return rv3174 3175 def consume_value(3176 self, ctx: Context, opts: cabc.Mapping[str, Parameter]3177 ) -> tuple[t.Any, ParameterSource]:3178+ """For :class:`Option`, the value can be collected from an interactive prompt3179+ if the option is a flag that needs a value (and the :attr:`prompt` property is3180+ set).3181+3182+ Additionally, this method handles flag option that are activated without a3183+ value, in which case the :attr:`flag_value` is returned.3184+3185+ :meta private:3186+ """3187 value, source = super().consume_value(ctx, opts)3188 3003- # The parser will emit a sentinel value if the option can be3004- # given as a flag without a value. This is different from None3005- # to distinguish from the flag not being given at all.3006- if value is _flag_needs_value:3189+ # The parser will emit a sentinel value if the option is allowed to as a flag3190+ # without a value.3191+ if value is FLAG_NEEDS_VALUE:3192+ # If the option allows for a prompt, we start an interaction with the user.3193 if self.prompt is not None and not ctx.resilient_parsing:3194 value = self.prompt_for_value(ctx)3195 source = ParameterSource.PROMPT3196+ # Else the flag takes its flag_value as value.3197 else:3198 value = self.flag_value3199 source = ParameterSource.COMMANDLINE3200 3201+ # A flag which is activated always returns the flag value, unless the value3202+ # comes from the explicitly sets default.3203 elif (3204+ self.is_flag3205+ and value is True3206+ and not self.is_bool_flag3207+ and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP)3208+ ):3209+ value = self.flag_value3210+3211+ # Re-interpret a multiple option which has been sent as-is by the parser.3212+ # Here we replace each occurrence of value-less flags (marked by the3213+ # FLAG_NEEDS_VALUE sentinel) with the flag_value.3214+ elif (3215 self.multiple3016- and value is not None3017- and any(v is _flag_needs_value for v in value)3216+ and value is not UNSET3217+ and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP)3218+ and any(v is FLAG_NEEDS_VALUE for v in value)3219 ):3019- value = [self.flag_value if v is _flag_needs_value else v for v in value]3220+ value = [self.flag_value if v is FLAG_NEEDS_VALUE else v for v in value]3221 source = ParameterSource.COMMANDLINE3222 3022- # The value wasn't set, or used the param's default, prompt if3023- # prompting is enabled.3223+ # The value wasn't set, or used the param's default, prompt for one to the user3224+ # if prompting is enabled.3225 elif (3025- source in {None, ParameterSource.DEFAULT}3226+ (3227+ value is UNSET3228+ or source in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP)3229+ )3230 and self.prompt is not None3231 and (self.required or self.prompt_required)3232 and not ctx.resilient_parsing3233 ):1 unmodified line3235 source = ParameterSource.PROMPT3236 3237 return value, source3238 3239+ def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any:3240+ if self.is_flag and not self.required:3241+ if value is UNSET:3242+ if self.is_bool_flag:3243+ # If the flag is a boolean flag, we return False if it is not set.3244+ value = False3245+ return super().type_cast_value(ctx, value)3246 3247+3248 class Argument(Parameter):3249 """Arguments are positional parameters to a command. They generally3250 provide fewer features than options but can have infinite ``nargs``3251 and are required by default.8 unmodified lines3260 param_decls: cabc.Sequence[str],3261 required: bool | None = None,3262 **attrs: t.Any,3263 ) -> None:3264+ # Auto-detect the requirement status of the argument if not explicitly set.3265 if required is None:3053- if attrs.get("default") is not None:3054- required = False3055- else:3266+ # The argument gets automatically required if it has no explicit default3267+ # value set and is setup to match at least one value.3268+ if attrs.get("default", UNSET) is UNSET:3269 required = attrs.get("nargs", 1) > 03270+ # If the argument has a default value, it is not required.3271+ else:3272+ required = False3273 3274 if "multiple" in attrs:3275 raise TypeError("__init__() got an unexpected keyword argument 'multiple'.")3276 3277 super().__init__(param_decls, required=required, **attrs)3278 3063- if __debug__:3064- if self.default is not None and self.nargs == -1:3065- raise TypeError("'default' is not supported for nargs=-1.")3066-3279 @property3280 def human_readable_name(self) -> str:3281 if self.metavar is not None:3282 return self.metavar65 unmodified linesmodified:src/click/exceptions.py+3 added-3 removed
113 unmodified lines114 self,115 message: str,116 ctx: Context | None = None,117 param: Parameter | None = None,118- param_hint: str | None = None,118+ param_hint: cabc.Sequence[str] | str | None = None,119 ) -> None:120 super().__init__(message, ctx)121 self.param = param122 self.param_hint = param_hint27 unmodified lines150 self,151 message: str | None = None,152 ctx: Context | None = None,153 param: Parameter | None = None,154- param_hint: str | None = None,154+ param_hint: cabc.Sequence[str] | str | None = None,155 param_type: str | None = None,156 ) -> None:157 super().__init__(message or "", ctx, param, param_hint)158 self.param_type = param_type159 160 def format_message(self) -> str:161 if self.param_hint is not None:162- param_hint: str | None = self.param_hint162+ param_hint: cabc.Sequence[str] | str | None = self.param_hint163 elif self.param is not None:164 param_hint = self.param.get_error_hint(self.ctx) # type: ignore165 else:166 param_hint = None142 unmodified linesmodified:src/click/formatting.py+2 added-2 removed
117 unmodified lines118 indent_increment: int = 2,119 width: int | None = None,120 max_width: int | None = None,121 ) -> None:122- import shutil123-122 self.indent_increment = indent_increment123 if max_width is None:124 max_width = 80125 if width is None:126+ import shutil127+128 width = FORCED_WIDTH129 if width is None:130 width = max(min(shutil.get_terminal_size().columns, max_width) - 2, 50)131 self.width = width170 unmodified linesmodified:src/click/parser.py+24 added-24 removed
28 unmodified lines29 from collections import deque30 from gettext import gettext as _31 from gettext import ngettext32 33+from ._utils import FLAG_NEEDS_VALUE34+from ._utils import UNSET35 from .exceptions import BadArgumentUsage36 from .exceptions import BadOptionUsage37 from .exceptions import NoSuchOption38 from .exceptions import UsageError39 40 if t.TYPE_CHECKING:41+ from ._utils import T_FLAG_NEEDS_VALUE42+ from ._utils import T_UNSET43 from .core import Argument as CoreArgument44 from .core import Context45 from .core import Option as CoreOption46 from .core import Parameter as CoreParameter47 48 V = t.TypeVar("V")49 46-# Sentinel value that indicates an option was passed as a flag without a47-# value but is not a flag option. Option.consume_value uses this to48-# prompt or use the flag_value.49-_flag_needs_value = object()50 51-51 def _unpack_args(52 args: cabc.Sequence[str], nargs_spec: cabc.Sequence[int]53 ) -> tuple[cabc.Sequence[str | cabc.Sequence[str | None] | None], list[str]]:54 """Given an iterable of arguments and an iterable of nargs specifications,2 unmodified lines57 58 The nargs specification is the number of arguments that should be consumed59 or `-1` to indicate that this position should eat up all the remainders.60 62- Missing items are filled with `None`.61+ Missing items are filled with ``UNSET``.62 """63 args = deque(args)64 nargs_spec = deque(nargs_spec)66- rv: list[str | tuple[str | None, ...] | None] = []65+ rv: list[str | tuple[str | T_UNSET, ...] | T_UNSET] = []66 spos: int | None = None67 69- def _fetch(c: deque[V]) -> V | None:68+ def _fetch(c: deque[V]) -> V | T_UNSET:69 try:70 if spos is None:71 return c.popleft()72 else:73 return c.pop()74 except IndexError:76- return None75+ return UNSET76 77 while nargs_spec:78 nargs = _fetch(nargs_spec)79 80 if nargs is None:81 continue82 83 if nargs == 1:85- rv.append(_fetch(args))84+ rv.append(_fetch(args)) # type: ignore[arg-type]85 elif nargs > 1:86 x = [_fetch(args) for _ in range(nargs)]87 88 # If we're reversed, we're pulling in the arguments in reverse,6 unmodified lines95 if spos is not None:96 raise TypeError("Cannot have two nargs < 0")97 98 spos = len(rv)100- rv.append(None)99+ rv.append(UNSET)100 101 # spos is the position of the wildcard (star). If it's not `None`,102 # we fill it with the remainder.103 if spos is not None:81 unmodified lines185 self.obj = obj186 187 def process(188 self,190- value: str | cabc.Sequence[str | None] | None,189+ value: str | cabc.Sequence[str | None] | None | T_UNSET,190 state: _ParsingState,191 ) -> None:192 if self.nargs > 1:194- assert value is not None195- holes = sum(1 for x in value if x is None)193+ assert isinstance(value, cabc.Sequence)194+ holes = sum(1 for x in value if x is UNSET)195 if holes == len(value):197- value = None196+ value = UNSET197 elif holes != 0:198 raise BadArgumentUsage(199 _("Argument {name!r} takes {nargs} values.").format(200 name=self.dest, nargs=self.nargs201 )202 )203 205- if self.nargs == -1 and self.obj.envvar is not None and value == ():206- # Replace empty tuple with None so that a value from the207- # environment may be tried.208- value = None204+ # We failed to collect any argument value so we consider the argument as unset.205+ if value == ():206+ value = UNSET207 208 state.opts[self.dest] = value # type: ignore209 state.order.append(self.obj)210 170 unmodified lines381 opt, _("Option {name!r} does not take a value.").format(name=opt)382 )383 384 else:387- value = None385+ value = UNSET386 387 option.process(value, state)388 389 def _match_short_opt(self, arg: str, state: _ParsingState) -> None:21 unmodified lines411 412 value = self._get_value_from_state(opt, option, state)413 414 else:417- value = None415+ value = UNSET416 417 option.process(value, state)418 419 if stop:7 unmodified lines427 state.largs.append(f"{prefix}{''.join(unknown_options)}")428 429 def _get_value_from_state(430 self, option_name: str, option: _Option, state: _ParsingState433- ) -> t.Any:431+ ) -> str | cabc.Sequence[str] | T_FLAG_NEEDS_VALUE:432 nargs = option.nargs433 434+ value: str | cabc.Sequence[str] | T_FLAG_NEEDS_VALUE435+436 if len(state.rargs) < nargs:437 if option.obj._flag_needs_value:438 # Option allows omitting the value.439- value = _flag_needs_value439+ value = FLAG_NEEDS_VALUE440 else:441 raise BadOptionUsage(442 option_name,443 ngettext(12 unmodified lines456 and len(next_rarg) > 1457 ):458 # The next arg looks like the start of an option, don't459 # use it as the value if omitting the value is allowed.460- value = _flag_needs_value460+ value = FLAG_NEEDS_VALUE461 else:462 value = state.rargs.pop(0)463 else:464 value = tuple(state.rargs[:nargs])68 unmodified linesmodified:src/click/shell_completion.py+24 added-1 removed
122 unmodified lines123 124 %(complete_func)s_setup;125 """126 127+# See ZshComplete.format_completion below, and issue #2703, before128+# changing this script.129+#130+# (TL;DR: _describe is picky about the format, but this Zsh script snippet131+# is already widely deployed. So freeze this script, and use clever-ish132+# handling of colons in ZshComplet.format_completion.)133 _SOURCE_ZSH = """\134 #compdef %(prog_name)s135 136 %(complete_func)s() {241 unmodified lines378 379 return args, incomplete380 381 def format_completion(self, item: CompletionItem) -> str:376- return f"{item.type}\n{item.value}\n{item.help if item.help else '_'}"382+ help_ = item.help or "_"383+ # The zsh completion script uses `_describe` on items with help384+ # texts (which splits the item help from the item value at the385+ # first unescaped colon) and `compadd` on items without help386+ # text (which uses the item value as-is and does not support387+ # colon escaping). So escape colons in the item value if and388+ # only if the item help is not the sentinel "_" value, as used389+ # by the completion script.390+ #391+ # (The zsh completion script is potentially widely deployed, and392+ # thus harder to fix than this method.)393+ #394+ # See issue #1812 and issue #2703 for further context.395+ value = item.value.replace(":", r"\:") if help_ != "_" else item.value396+ return f"{item.type}\n{value}\n{help_}"397 398 399 class FishComplete(ShellComplete):400 """Shell completion for Fish."""3 unmodified lines404 405 def get_completion_args(self) -> tuple[list[str], str]:406 cwords = split_arg_string(os.environ["COMP_WORDS"])407 incomplete = os.environ["COMP_CWORD"]408+ if incomplete:409+ incomplete = split_arg_string(incomplete)[0]410 args = cwords[1:]411 412 # Fish stores the partial word in both COMP_WORDS and413 # COMP_CWORD, remove it from complete args.139 unmodified lines553 break554 555 if _start_of_option(ctx, arg):556 last_option = arg557+ break558 559 return last_option is not None and last_option in param.opts560 561 106 unmodified linesmodified:src/click/testing.py+14 added-1 removed
3 unmodified lines4 import contextlib5 import io6 import os7 import shlex8-import shutil8 import sys9 import tempfile10 import typing as t11 from types import TracebackType85 unmodified lines97 self.output: io.BytesIO = io.BytesIO()98 self.stdout: io.BytesIO = BytesIOCopy(copy_to=self.output)99 self.stderr: io.BytesIO = BytesIOCopy(copy_to=self.output)100 101+ def __del__(self) -> None:102+ """103+ Guarantee that embedded file-like objects are closed in a104+ predictable order, protecting against races between105+ self.output being closed and other streams being flushed on close106 107+ .. versionadded:: 8.2.2108+ """109+ self.stderr.close()110+ self.stdout.close()111+ self.output.close()112+113+114 class _NamedTextIOWrapper(io.TextIOWrapper):115 def __init__(116 self, buffer: t.BinaryIO, name: str, mode: str, **kwargs: t.Any117 ) -> None:450 unmodified lines568 finally:569 os.chdir(cwd)570 571 if temp_dir is None:572+ import shutil573+574 try:575 shutil.rmtree(dt)576 except OSError:577 passmodified:src/click/types.py+57 added-13 removed
659 unmodified lines660 661 class BoolParamType(ParamType):662 name = "boolean"663 664- def convert(665- self, value: t.Any, param: Parameter | None, ctx: Context | None666- ) -> t.Any:667- if value in {False, True}:668- return bool(value)664+ bool_states: dict[str, bool] = {665+ "1": True,666+ "0": False,667+ "yes": True,668+ "no": False,669+ "true": True,670+ "false": False,671+ "on": True,672+ "off": False,673+ "t": True,674+ "f": False,675+ "y": True,676+ "n": False,677+ # Absence of value is considered False.678+ "": False,679+ }680+ """A mapping of string values to boolean states.681 670- norm = value.strip().lower()682+ Mapping is inspired by :py:attr:`configparser.ConfigParser.BOOLEAN_STATES`683+ and extends it.684 672- if norm in {"1", "true", "t", "yes", "y", "on"}:673- return True685+ .. caution::686+ String values are lower-cased, as the ``str_to_bool`` comparison function687+ below is case-insensitive.688 675- if norm in {"0", "false", "f", "no", "n", "off"}:676- return False689+ .. warning::690+ The mapping is not exhaustive, and does not cover all possible boolean strings691+ representations. It will remains as it is to avoid endless bikeshedding.692 678- self.fail(679- _("{value!r} is not a valid boolean.").format(value=value), param, ctx680- )693+ Future work my be considered to make this mapping user-configurable from public694+ API.695+ """696 697+ @staticmethod698+ def str_to_bool(value: str | bool) -> bool | None:699+ """Convert a string to a boolean value.700+701+ If the value is already a boolean, it is returned as-is. If the value is a702+ string, it is stripped of whitespaces and lower-cased, then checked against703+ the known boolean states pre-defined in the `BoolParamType.bool_states` mapping704+ above.705+706+ Returns `None` if the value does not match any known boolean state.707+ """708+ if isinstance(value, bool):709+ return value710+ return BoolParamType.bool_states.get(value.strip().lower())711+712+ def convert(713+ self, value: t.Any, param: Parameter | None, ctx: Context | None714+ ) -> bool:715+ normalized = self.str_to_bool(value)716+ if normalized is None:717+ self.fail(718+ _(719+ "{value!r} is not a valid boolean. Recognized values: {states}"720+ ).format(value=value, states=", ".join(sorted(self.bool_states))),721+ param,722+ ctx,723+ )724+ return normalized725+726 def __repr__(self) -> str:727 return "BOOL"728 729 480 unmodified linesmodified:src/click/utils.py+1 added-1 removed
275 unmodified lines276 return277 278 # Convert non bytes/text into the native string type.279 if message is not None and not isinstance(message, (str, bytes, bytearray)):280- out: str | bytes | None = str(message)280+ out: str | bytes | bytearray | None = str(message)281 else:282 out = message283 284 if nl:343 unmodified linesmodified:tests/test_arguments.py+150 added-43 removed
2 unmodified lines3 4 import pytest5 6 import click7+from click._utils import UNSET8 9 10 def test_nargs_star(runner):11 @click.command()7 unmodified lines19 assert not result.exception20 assert result.output.splitlines() == ["src=foo.txt|bar.txt", "dst=dir"]21 22 22-def test_argument_unbounded_nargs_cant_have_default(runner):23- with pytest.raises(TypeError, match="nargs=-1"):24-25- @click.command()26- @click.argument("src", nargs=-1, default=["42"])27- def copy(src):28- pass29-30-23 def test_nargs_tup(runner):24 @click.command()25 @click.argument("name", nargs=1)26 @click.argument("point", nargs=2, type=click.INT)27 unmodified lines54 assert result.exception is None55 assert result.output.splitlines() == ["name=peter id=1"]56 57 58+def test_nargs_mismatch_with_tuple_type():59+ with pytest.raises(ValueError, match="nargs.*must be 2.*but it was 3"):60+61+ @click.command()62+ @click.argument("test", type=(str, int), nargs=3)63+ def cli(_):64+ pass65+66+67 def test_nargs_err(runner):68 @click.command()69 @click.argument("x")70 def copy(x):94 unmodified lines165 166 result = runner.invoke(inout, [])167 assert not result.exception168 assert result.output == "Foo bar baz\n"169+ assert result.stdout == "Foo bar baz\n"170+ assert not result.stderr171 172 173 @pytest.mark.parametrize(174 ("nargs", "value", "expect"),25 unmodified lines200 else:201 assert result.return_value == expect202 203 201-def test_envvar_flag_value(runner):202- @click.command()203- # is_flag is implicitly true204- @click.option("--upper", flag_value="upper", envvar="UPPER")205- def cmd(upper):206- click.echo(upper)207- return upper208-209- # For whatever value of the `env` variable, if it exists, the flag should be `upper`210- result = runner.invoke(cmd, env={"UPPER": "whatever"})211- assert result.output.strip() == "upper"212-213-204 def test_nargs_envvar_only_if_values_empty(runner):205 @click.command()206 @click.argument("arg", envvar="X", nargs=-1)207 def cli(arg):36 unmodified lines244 assert result.exit_code == 2245 assert "Missing argument 'ARG'." in result.output246 247 258-def test_missing_argument_string_cast():248+@pytest.mark.parametrize(249+ ("value", "expect_missing", "processed_value"),250+ [251+ # Unspecified type of the argument fallback to string, so everything is252+ # processed the click.STRING type.253+ ("", False, ""),254+ (" ", False, " "),255+ ("foo", False, "foo"),256+ ("12", False, "12"),257+ (12, False, "12"),258+ (12.1, False, "12.1"),259+ (list(), False, "[]"),260+ (tuple(), False, "()"),261+ (set(), False, "set()"),262+ (frozenset(), False, "frozenset()"),263+ (dict(), False, "{}"),264+ # None is a value that is allowed to be processed by a required argument265+ # because at this stage, the process_value method happens after the default is266+ # applied.267+ (None, False, None),268+ # An UNSET required argument will raise MissingParameter.269+ (UNSET, True, None),270+ ],271+)272+def test_required_argument(value, expect_missing, processed_value):273+ """Test how a required argument is processing the provided values."""274 ctx = click.Context(click.Command(""))275+ argument = click.Argument(["a"], required=True)276 277+ if expect_missing:261- with pytest.raises(click.MissingParameter) as excinfo:262- click.Argument(["a"], required=True).process_value(ctx, None)278+ with pytest.raises(click.MissingParameter) as excinfo:279+ argument.process_value(ctx, value)280+ assert str(excinfo.value) == "Missing parameter: a"281 264- assert str(excinfo.value) == "Missing parameter: a"282+ else:283+ value = argument.process_value(ctx, value)284+ assert value == processed_value285 286 287 def test_implicit_non_required(runner):288 @click.command()85 unmodified lines374 result = runner.invoke(cmd, ["a", "b", "c", "d", "e", "f"])375 assert result.output.splitlines() == ["('a', 'b', 'c')", "d", "('e', 'f')"]376 377 358-def test_defaults_for_nargs(runner):378+@pytest.mark.parametrize(379+ ("argument_params", "args", "expected"),380+ [381+ # Any iterable with the same number of arguments as nargs is valid.382+ [{"nargs": 2, "default": (1, 2)}, [], (1, 2)],383+ [{"nargs": 2, "default": (1.1, 2.2)}, [], (1, 2)],384+ [{"nargs": 2, "default": ("1", "2")}, [], (1, 2)],385+ [{"nargs": 2, "default": (None, None)}, [], (None, None)],386+ [{"nargs": 2, "default": [1, 2]}, [], (1, 2)],387+ [{"nargs": 2, "default": {1, 2}}, [], (1, 2)],388+ [{"nargs": 2, "default": frozenset([1, 2])}, [], (1, 2)],389+ [{"nargs": 2, "default": {1: "a", 2: "b"}}, [], (1, 2)],390+ # Empty iterable is valid if default is None.391+ [{"nargs": 2, "default": None}, [], None],392+ # Arguments overrides the default.393+ [{"nargs": 2, "default": (1, 2)}, ["3", "4"], (3, 4)],394+ # Unbounded arguments are allowed to have a default.395+ # See: https://github.com/pallets/click/issues/2164396+ [{"nargs": -1, "default": [42]}, [], (42,)],397+ [{"nargs": -1, "default": None}, [], ()],398+ [{"nargs": -1, "default": {1, 2, 3, 4, 5}}, [], (1, 2, 3, 4, 5)],399+ ],400+)401+def test_good_defaults_for_nargs(runner, argument_params, args, expected):402 @click.command()360- @click.argument("a", nargs=2, type=int, default=(1, 2))403+ @click.argument("a", type=int, **argument_params)404 def cmd(a):362- x, y = a363- click.echo(x + y)405+ click.echo(repr(a), nl=False)406 365- result = runner.invoke(cmd, [])366- assert result.output.strip() == "3"407+ result = runner.invoke(cmd, args)408+ assert result.output == repr(expected)409 368- result = runner.invoke(cmd, ["3", "4"])369- assert result.output.strip() == "7"410 371- result = runner.invoke(cmd, ["3"])372- assert result.exception is not None373- assert "Argument 'a' takes 2 values." in result.output411+@pytest.mark.parametrize(412+ ("default", "message"),413+ [414+ # Non-iterables defaults.415+ ["Yo", "Error: Invalid value for '[A]...': Value must be an iterable."],416+ ["", "Error: Invalid value for '[A]...': Value must be an iterable."],417+ [True, "Error: Invalid value for '[A]...': Value must be an iterable."],418+ [False, "Error: Invalid value for '[A]...': Value must be an iterable."],419+ [12, "Error: Invalid value for '[A]...': Value must be an iterable."],420+ [7.9, "Error: Invalid value for '[A]...': Value must be an iterable."],421+ # Generator default.422+ [(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given."],423+ # Unset default.424+ [UNSET, "Error: Missing argument 'A...'."],425+ # Tuples defaults with wrong length.426+ [427+ tuple(),428+ "Error: Invalid value for '[A]...': Takes 2 values but 0 were given.",429+ ],430+ [(1,), "Error: Invalid value for '[A]...': Takes 2 values but 1 was given."],431+ [432+ (1, 2, 3),433+ "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",434+ ],435+ # Lists defaults with wrong length.436+ [list(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given."],437+ [[1], "Error: Invalid value for '[A]...': Takes 2 values but 1 was given."],438+ [439+ [1, 2, 3],440+ "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",441+ ],442+ # Sets defaults with wrong length.443+ [set(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given."],444+ [445+ set([1]),446+ "Error: Invalid value for '[A]...': Takes 2 values but 1 was given.",447+ ],448+ [449+ set([1, 2, 3]),450+ "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",451+ ],452+ # Frozensets defaults with wrong length.453+ [454+ frozenset(),455+ "Error: Invalid value for '[A]...': Takes 2 values but 0 were given.",456+ ],457+ [458+ frozenset([1]),459+ "Error: Invalid value for '[A]...': Takes 2 values but 1 was given.",460+ ],461+ [462+ frozenset([1, 2, 3]),463+ "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",464+ ],465+ # Dictionaries defaults with wrong length.466+ [dict(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given."],467+ [468+ {1: "a"},469+ "Error: Invalid value for '[A]...': Takes 2 values but 1 was given.",470+ ],471+ [472+ {1: "a", 2: "b", 3: "c"},473+ "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",474+ ],475+ ],476+)477+def test_bad_defaults_for_nargs(runner, default, message):478+ """Some defaults are not valid when nargs is set."""479 480+ @click.command()481+ @click.argument("a", nargs=2, type=int, default=default)482+ def cmd(a):483+ click.echo(repr(a))484 485+ result = runner.invoke(cmd, [])486+ assert message in result.stderr487+488+489 def test_multiple_param_decls_not_allowed(runner):490 with pytest.raises(TypeError):491 492 @click.command()6 unmodified lines499 with pytest.raises(TypeError, match="multiple"):500 click.Argument(["a"], multiple=True)501 502 390-@pytest.mark.parametrize("value", [(), ("a",), ("a", "b", "c")])391-def test_nargs_bad_default(runner, value):392- with pytest.raises(ValueError, match="nargs=2"):393- click.Argument(["a"], nargs=2, default=value)394-395-503 def test_subcommand_help(runner):504 @click.group()505 @click.argument("name")506 @click.argument("val")75 unmodified linesmodified:tests/test_basic.py+95 added-14 removed
5 unmodified lines6 7 import pytest8 9 import click10+from click._utils import UNSET11 12 13 def test_basic_functionality(runner):14 @click.command()190 unmodified lines205 else:206 assert result.exception is None207 208 208-@pytest.mark.parametrize("default", [True, False])209 @pytest.mark.parametrize(210- ("args", "expect"), [(["--on"], True), (["--off"], False), ([], None)]210+ ("args", "default", "expect"),211+ [212+ (["--on"], True, True),213+ (["--on"], False, True),214+ (["--on"], None, True),215+ (["--on"], UNSET, True),216+ (["--off"], True, False),217+ (["--off"], False, False),218+ (["--off"], None, False),219+ (["--off"], UNSET, False),220+ ([], True, True),221+ ([], False, False),222+ ([], None, None),223+ ([], UNSET, False),224+ ],225 )212-def test_boolean_switch(runner, default, args, expect):226+def test_boolean_switch(runner, args, default, expect):227 @click.command()228 @click.option("--on/--off", default=default)229 def cli(on):230 return on231 218- if expect is None:219- expect = default220-232 result = runner.invoke(cli, args, standalone_mode=False)233 assert result.return_value is expect234 235 225-@pytest.mark.parametrize("default", [True, False])226-@pytest.mark.parametrize(("args", "expect"), [(["--f"], True), ([], False)])236+@pytest.mark.parametrize(237+ ("default", "args", "expect"),238+ (239+ (True, ["--f"], True),240+ (True, [], True),241+ (False, ["--f"], True),242+ (False, [], False),243+ # Boolean flags have a 3-states logic.244+ # See: https://github.com/pallets/click/issues/3024#issue-3285556668245+ (None, ["--f"], True),246+ (None, [], None),247+ ),248+)249 def test_boolean_flag(runner, default, args, expect):250 @click.command()251 @click.option("--f", is_flag=True, default=default)252 def cli(f):253 return f254 233- if default:234- expect = not expect235-255 result = runner.invoke(cli, args, standalone_mode=False)256 assert result.return_value is expect257 258 16 unmodified lines275 result = runner.invoke(cli, ["--flag", value.title()])276 assert result.output == expect277 278 279+@pytest.mark.parametrize(280+ ("default", "args", "expected"),281+ # These test cases are similar to the ones in282+ # tests/test_options.py::test_default_dual_option_callback, so keep them in sync.283+ (284+ # Each option is returning its own flag_value, whatever the default is.285+ (True, ["--upper"], "upper"),286+ (True, ["--lower"], "lower"),287+ (False, ["--upper"], "upper"),288+ (False, ["--lower"], "lower"),289+ (None, ["--upper"], "upper"),290+ (None, ["--lower"], "lower"),291+ (UNSET, ["--upper"], "upper"),292+ (UNSET, ["--lower"], "lower"),293+ # Check that the last option wins when both are specified.294+ (True, ["--upper", "--lower"], "lower"),295+ (True, ["--lower", "--upper"], "upper"),296+ # Check that the default is returned as-is when no option is specified.297+ ("upper", [], "upper"),298+ ("lower", [], "lower"),299+ ("uPPer", [], "uPPer"),300+ ("lOwEr", [], "lOwEr"),301+ (" ᕕ( ᐛ )ᕗ ", [], " ᕕ( ᐛ )ᕗ "),302+ (None, [], None),303+ # Default is normalized to None if it is UNSET.304+ (UNSET, [], None),305+ # Special case: if default=True and flag_value is set, the value returned is the306+ # flag_value, not the True Python value itself.307+ (True, [], "upper"),308+ # Non-string defaults are process as strings by the default Parameter's type.309+ (False, [], "False"),310+ (42, [], "42"),311+ (12.3, [], "12.3"),312+ ),313+)314+def test_flag_value_dual_options(runner, default, args, expected):315+ """Check how default is processed when options compete for the same variable name.316+317+ Covers the regression reported in318+ https://github.com/pallets/click/issues/3024#issuecomment-3146199461319+ """320+321+ @click.command()322+ @click.option("--upper", "case", flag_value="upper", default=default)323+ @click.option("--lower", "case", flag_value="lower")324+ def cli(case):325+ click.echo(repr(case), nl=False)326+327+ result = runner.invoke(cli, args)328+ assert result.output == repr(expected)329+330+331 def test_file_option(runner):332 @click.command()333 @click.option("--file", type=click.File("w"))334 def input(file):206 unmodified lines541 "method", type=click.Choice(["not-none", None], case_sensitive=False)542 )543 def cli(method: str | None):544 assert isinstance(method, str) or method is None474- click.echo(method)545+ click.echo(repr(method), nl=False)546 547 result = runner.invoke(cli, ["not-none"])548 assert not result.exception478- assert result.output == "not-none\n"549+ assert result.output == repr("not-none")550 480- # None is not yet supported.551 result = runner.invoke(cli, ["none"])552+ assert not result.exception553+ assert result.output == repr(None)554+555+ result = runner.invoke(cli, [])556 assert result.exception557+ assert (558+ "Error: Missing argument '{not-none|none}'. "559+ "Choose from:\n\tnot-none,\n\tnone\n" in result.stderr560+ )561 562+ result = runner.invoke(cli, ["--help"])563+ assert result.output.startswith("Usage: cli [OPTIONS] {not-none|none}\n")564 565+566 def test_datetime_option_default(runner):567 @click.command()568 @click.option("--start_date", type=click.DateTime())569 def cli(start_date):166 unmodified linesmodified:tests/test_context.py+127 added
1 import logging2+from contextlib import AbstractContextManager3 from contextlib import contextmanager4+from types import TracebackType5 6 import pytest7 8 import click415 unmodified lines424 425 assert rv == [0]426 427 428+def test_with_resource_exception() -> None:429+ class TestContext(AbstractContextManager[list[int]]):430+ _handle_exception: bool431+ _base_val: int432+ val: list[int]433+434+ def __init__(self, base_val: int = 1, *, handle_exception: bool = True) -> None:435+ self._handle_exception = handle_exception436+ self._base_val = base_val437+438+ def __enter__(self) -> list[int]:439+ self.val = [self._base_val]440+ return self.val441+442+ def __exit__(443+ self,444+ exc_type: type[BaseException] | None,445+ exc_value: BaseException | None,446+ traceback: TracebackType | None,447+ ) -> bool | None:448+ if not exc_type:449+ self.val[0] = self._base_val - 1450+ return None451+452+ self.val[0] = self._base_val + 1453+ return self._handle_exception454+455+ class TestException(Exception):456+ pass457+458+ ctx = click.Context(click.Command("test"))459+460+ base_val = 1461+462+ with ctx.scope():463+ rv = ctx.with_resource(TestContext(base_val=base_val))464+ assert rv[0] == base_val465+466+ assert rv == [base_val - 1]467+468+ with ctx.scope():469+ rv = ctx.with_resource(TestContext(base_val=base_val))470+ raise TestException()471+472+ assert rv == [base_val + 1]473+474+ with pytest.raises(TestException):475+ with ctx.scope():476+ rv = ctx.with_resource(477+ TestContext(base_val=base_val, handle_exception=False)478+ )479+ raise TestException()480+481+482+def test_with_resource_nested_exception() -> None:483+ class TestContext(AbstractContextManager[list[int]]):484+ _handle_exception: bool485+ _base_val: int486+ val: list[int]487+488+ def __init__(self, base_val: int = 1, *, handle_exception: bool = True) -> None:489+ self._handle_exception = handle_exception490+ self._base_val = base_val491+492+ def __enter__(self) -> list[int]:493+ self.val = [self._base_val]494+ return self.val495+496+ def __exit__(497+ self,498+ exc_type: type[BaseException] | None,499+ exc_value: BaseException | None,500+ traceback: TracebackType | None,501+ ) -> bool | None:502+ if not exc_type:503+ self.val[0] = self._base_val - 1504+ return None505+506+ self.val[0] = self._base_val + 1507+ return self._handle_exception508+509+ class TestException(Exception):510+ pass511+512+ ctx = click.Context(click.Command("test"))513+ base_val = 1514+ base_val_nested = 11515+516+ with ctx.scope():517+ rv = ctx.with_resource(TestContext(base_val=base_val))518+ rv_nested = ctx.with_resource(TestContext(base_val=base_val_nested))519+ assert rv[0] == base_val520+ assert rv_nested[0] == base_val_nested521+522+ assert rv == [base_val - 1]523+ assert rv_nested == [base_val_nested - 1]524+525+ with ctx.scope():526+ rv = ctx.with_resource(TestContext(base_val=base_val))527+ rv_nested = ctx.with_resource(TestContext(base_val=base_val_nested))528+ raise TestException()529+530+ # If one of the context "eats" the exceptions they will not be forwarded to other531+ # parts. This is due to how ExitStack unwinding works532+ assert rv_nested == [base_val_nested + 1]533+ assert rv == [base_val - 1]534+535+ with ctx.scope():536+ rv = ctx.with_resource(TestContext(base_val=base_val))537+ rv_nested = ctx.with_resource(538+ TestContext(base_val=base_val_nested, handle_exception=False)539+ )540+ raise TestException()541+542+ assert rv_nested == [base_val_nested + 1]543+ assert rv == [base_val + 1]544+545+ with pytest.raises(TestException):546+ rv = ctx.with_resource(TestContext(base_val=base_val, handle_exception=False))547+ rv_nested = ctx.with_resource(548+ TestContext(base_val=base_val_nested, handle_exception=False)549+ )550+ raise TestException()551+552+553 def test_make_pass_decorator_args(runner):554 """555 Test to check that make_pass_decorator doesn't consume arguments based on556 invocation order.116 unmodified linesmodified:tests/test_imports.py+15 added-15 removed
25 unmodified lines26 """27 28 ALLOWED_IMPORTS = {29 "__future__",30- "weakref",31- "os",32- "struct",30+ "codecs",31 "collections",32 "collections.abc",35- "sys",33+ "configparser",34 "contextlib",35+ "datetime",36+ "enum",37+ "errno",38+ "fcntl",39 "functools",38- "stat",39- "re",40- "codecs",40+ "gettext",41 "inspect",42- "itertools",42 "io",43+ "itertools",44+ "os",45+ "re",46+ "stat",47+ "struct",48+ "sys",49 "threading",45- "errno",46- "fcntl",47- "datetime",48- "enum",49- "typing",50 "types",51- "gettext",52- "shutil",51+ "typing",52+ "weakref",53 }54 55 if WIN:56 ALLOWED_IMPORTS.update(["ctypes", "ctypes.wintypes", "msvcrt", "time"])14 unmodified linesmodified:tests/test_options.py+1174 added-74 removed
1+import enum2 import os3 import re4+import sys5+import tempfile6+from contextlib import nullcontext7+from typing import Literal8 9+if sys.version_info < (3, 11):10+ enum.StrEnum = enum.Enum # type: ignore[assignment]11+12 import pytest13 14 import click15 from click import Option16+from click import UNPROCESSED17+from click._utils import UNSET18 19 20 def test_prefixes(runner):21 @click.command()67 unmodified lines89 click.Option(["--a"], prompt=True, deprecated=True)90 91 92 def test_invalid_nargs(runner):83- with pytest.raises(TypeError, match="nargs=-1"):93+ with pytest.raises(TypeError, match="nargs=-1 is not supported for options."):94 95 @click.command()96 @click.option("--foo", nargs=-1)97 def cli(foo):76 unmodified lines174 assert "Error: Missing option '-m' / '--message'." in result.output175 176 177 @pytest.mark.parametrize(168- ("multiple", "nargs", "default"),178+ ("multiple", "nargs", "default", "expected"),179 [170- (True, 1, []),171- (True, 1, [1]),172- # (False, -1, []),173- # (False, -1, [1]),174- (False, 2, [1, 2]),175- # (True, -1, [[]]),176- # (True, -1, []),177- # (True, -1, [[1]]),178- (True, 2, []),179- (True, 2, [[1, 2]]),180+ # If multiple values are allowed, defaults should be iterable.181+ (True, 1, [], ()),182+ (True, 1, (), ()),183+ (True, 1, tuple(), ()),184+ (True, 1, set(), ()),185+ (True, 1, frozenset(), ()),186+ (True, 1, {}, ()),187+ # Special values.188+ (True, 1, None, ()),189+ (True, 1, UNSET, ()),190+ # Number of values are kept as-is in the default.191+ (True, 1, [1], (1,)),192+ (True, 1, [1, 2], (1, 2)),193+ (True, 1, [1, 2, 3], (1, 2, 3)),194+ (True, 1, [1.1, 2.2], (1.1, 2.2)),195+ (True, 1, ["1", "2"], ("1", "2")),196+ (True, 1, [None, None], (None, None)),197+ # Contrary to list or tuples, native Python types not supported by Click are198+ # not recognized and are converted to the default format: tuple of strings.199+ # Refs: https://github.com/pallets/click/issues/3036200+ (True, 1, {1, 2}, ("1", "2")),201+ (True, 1, frozenset([1, 2]), ("1", "2")),202+ (True, 1, {1: "a", 2: "b"}, ("1", "2")),203+ # Multiple values with nargs > 1.204+ (True, 2, [], ()),205+ (True, 2, (), ()),206+ (True, 2, tuple(), ()),207+ (True, 2, set(), ()),208+ (True, 2, frozenset(), ()),209+ (True, 2, {}, ()),210+ (True, 2, None, ()),211+ (True, 2, UNSET, ()),212+ (True, 2, [[1, 2]], ((1, 2),)),213+ (True, 2, [[1, 2], [3, 4]], ((1, 2), (3, 4))),214+ (True, 2, [[1, 2], [3, 4], [5, 6]], ((1, 2), (3, 4), (5, 6))),215+ (True, 2, [[1.1, 2.2], [3.3, 4.4]], ((1.1, 2.2), (3.3, 4.4))),216+ (True, 2, [["1", "2"], ["3", "4"]], (("1", "2"), ("3", "4"))),217+ (True, 2, [[None, None], [None, None]], ((None, None), (None, None))),218+ (True, 2, [[1, 2.2], ["3", None]], ((1, 2.2), (3, None))),219+ (True, 2, [[1, 2.2], None], ((1, 2.2), None)),220+ # Default of the right length works for non-multiples.221+ (False, 2, [1, 2], (1, 2)),222 ],223 )182-def test_init_good_default_list(runner, multiple, nargs, default):183- click.Option(["-a"], multiple=multiple, nargs=nargs, default=default)224+def test_good_defaults_for_multiple(runner, multiple, nargs, default, expected):225+ @click.command()226+ @click.option("-a", multiple=multiple, nargs=nargs, default=default)227+ def cmd(a):228+ click.echo(repr(a), nl=False)229 230+ result = runner.invoke(cmd)231+ assert result.output == repr(expected)232 233+234 @pytest.mark.parametrize(187- ("multiple", "nargs", "default"),235+ ("multiple", "nargs", "default", "exception", "message"),236 [189- (True, 1, 1),190- # (False, -1, 1),191- (False, 2, [1]),192- (True, 2, [[1]]),237+ # Non-iterables defaults.238+ (239+ True,240+ 1,241+ "Yo",242+ None,243+ "Error: Invalid value for '-a': Value must be an iterable.",244+ ),245+ (246+ True,247+ 1,248+ "",249+ None,250+ "Error: Invalid value for '-a': Value must be an iterable.",251+ ),252+ (253+ True,254+ 1,255+ True,256+ None,257+ "Error: Invalid value for '-a': Value must be an iterable.",258+ ),259+ (260+ True,261+ 1,262+ False,263+ None,264+ "Error: Invalid value for '-a': Value must be an iterable.",265+ ),266+ (267+ True,268+ 1,269+ 12,270+ None,271+ "Error: Invalid value for '-a': Value must be an iterable.",272+ ),273+ (274+ True,275+ 1,276+ 7.9,277+ None,278+ "Error: Invalid value for '-a': Value must be an iterable.",279+ ),280+ #281+ (282+ False,283+ 2,284+ 42,285+ None,286+ "Error: Invalid value for '-a': Value must be an iterable.",287+ ),288+ (289+ True,290+ 2,291+ ["test string which is not a list in the list"],292+ None,293+ "Error: Invalid value for '-a': Value must be an iterable.",294+ ),295+ # Multiple options, each with 2 args, but with wrong length.296+ (297+ True,298+ 2,299+ (1,),300+ None,301+ "Error: Invalid value for '-a': Value must be an iterable.",302+ ),303+ (304+ True,305+ 2,306+ (1, 2, 3),307+ None,308+ "Error: Invalid value for '-a': Value must be an iterable.",309+ ),310+ (311+ True,312+ 2,313+ [tuple()],314+ ValueError,315+ r"'nargs' must be 0 \(or None\) for type <click\.types\.Tuple object at "316+ r"0x[0-9A-Fa-f]+>, but it was 2\.",317+ ),318+ (319+ True,320+ 2,321+ [(1,)],322+ ValueError,323+ r"'nargs' must be 1 \(or None\) for type <click\.types\.Tuple object at "324+ r"0x[0-9A-Fa-f]+>, but it was 2\.",325+ ),326+ (327+ True,328+ 2,329+ [(1, 2, 3)],330+ ValueError,331+ r"'nargs' must be 3 \(or None\) for type <click\.types\.Tuple object at "332+ r"0x[0-9A-Fa-f]+>, but it was 2\.",333+ ),334+ # A mix of valid and invalid defaults.335+ (336+ True,337+ 2,338+ [[1, 2.2], []],339+ None,340+ "Error: Invalid value for '-a': 2 values are required, but 0 were given.",341+ ),342+ # Default values that are iterable but not of the right length.343+ (344+ False,345+ 2,346+ [1],347+ None,348+ "Error: Invalid value for '-a': Takes 2 values but 1 was given.",349+ ),350+ (351+ True,352+ 2,353+ [[1]],354+ ValueError,355+ r"'nargs' must be 1 \(or None\) for type <click\.types\.Tuple object at "356+ r"0x[0-9A-Fa-f]+>, but it was 2\.",357+ ),358 ],359 )195-def test_init_bad_default_list(runner, multiple, nargs, default):196- type = (str, str) if nargs == 2 else None360+def test_bad_defaults_for_multiple(361+ runner, multiple, nargs, default, exception, message362+):363+ if exception:364+ assert issubclass(exception, Exception)365+ else:366+ assert exception is None367 198- with pytest.raises(ValueError, match="default"):199- click.Option(["-a"], type=type, multiple=multiple, nargs=nargs, default=default)368+ with (369+ pytest.raises(exception, match=re.compile(message))370+ if exception371+ else nullcontext()372+ ):373 374+ @click.command()375+ @click.option("-a", multiple=multiple, nargs=nargs, default=default)376+ def cmd(a):377+ click.echo(repr(a))378 379+ result = runner.invoke(cmd)380+ assert message in result.stderr381+382+383 @pytest.mark.parametrize("env_key", ["MYPATH", "AUTO_MYPATH"])384 def test_empty_envvar(runner, env_key):385 @click.command()386 @click.option("--mypath", type=click.Path(exists=True), envvar="MYPATH")40 unmodified lines427 assert not result.exception428 assert result.output == "foo|bar\n"429 430 250-def test_trailing_blanks_boolean_envvar(runner):431+@pytest.mark.parametrize(432+ ("envvar_name", "envvar_value", "expected"),433+ (434+ # Lower-cased variations of value.435+ ("SHOUT", "true", True),436+ ("SHOUT", "false", False),437+ # Title-cased variations of value.438+ ("SHOUT", "True", True),439+ ("SHOUT", "False", False),440+ # Upper-cased variations of value.441+ ("SHOUT", "TRUE", True),442+ ("SHOUT", "FALSE", False),443+ # Random-cased variations of value.444+ ("SHOUT", "TruE", True),445+ ("SHOUT", "truE", True),446+ ("SHOUT", "FaLsE", False),447+ ("SHOUT", "falsE", False),448+ # Extra spaces around the value.449+ ("SHOUT", "true ", True),450+ ("SHOUT", " true ", True),451+ ("SHOUT", " true", True),452+ ("SHOUT", "false ", False),453+ ("SHOUT", " false ", False),454+ ("SHOUT", " false", False),455+ # Integer variations.456+ ("SHOUT", "1", True),457+ ("SHOUT", "0", False),458+ # Alternative states.459+ ("SHOUT", "t", True),460+ ("SHOUT", "T", True),461+ ("SHOUT", " T ", True),462+ ("SHOUT", "f", False),463+ ("SHOUT", "y", True),464+ ("SHOUT", "n", False),465+ ("SHOUT", "yes", True),466+ ("SHOUT", "no", False),467+ ("SHOUT", "on", True),468+ ("SHOUT", "off", False),469+ # Blank value variations.470+ ("SHOUT", None, False),471+ ("SHOUT", "", False),472+ ("SHOUT", " ", False),473+ ("SHOUT", " ", False),474+ # Variable names are not stripped of spaces and so don't match the475+ # flag, which then naturraly takes its default value.476+ ("SHOUT ", "True", False),477+ ("SHOUT ", "False", False),478+ (" SHOUT ", "True", False),479+ (" SHOUT ", "False", False),480+ (" SHOUT", "True", False),481+ (" SHOUT", "False", False),482+ ("SH OUT", "True", False),483+ ("SH OUT", "False", False),484+ # Same for random and reverse environment variable names: they are not485+ # recognized by the option.486+ ("RANDOM", "True", False),487+ ("NO_SHOUT", "True", False),488+ ("NO_SHOUT", "False", False),489+ ("NOSHOUT", "True", False),490+ ("NOSHOUT", "False", False),491+ ),492+)493+def test_boolean_flag_envvar(runner, envvar_name, envvar_value, expected):494+ assert isinstance(envvar_name, str)495+ assert isinstance(envvar_value, str) or envvar_value is None496+497 @click.command()498 @click.option("--shout/--no-shout", envvar="SHOUT")499 def cli(shout):254- click.echo(f"shout: {shout!r}")500+ click.echo(repr(shout), nl=False)501 256- result = runner.invoke(cli, [], env={"SHOUT": " true "})502+ result = runner.invoke(cli, [], env={envvar_name: envvar_value})503 assert result.exit_code == 0258- assert result.output == "shout: True\n"504+ assert result.output == repr(expected)505 506 507+@pytest.mark.parametrize(508+ "value",509+ (510+ # Extra spaces inside the value.511+ "tr ue",512+ "fa lse",513+ # Numbers.514+ "10",515+ "01",516+ "00",517+ "11",518+ "0.0",519+ "1.1",520+ # Random strings.521+ "randomstring",522+ "None",523+ "'None'",524+ "A B",525+ " 1 2 ",526+ "9.3",527+ "a;n",528+ "x:y",529+ "i/o",530+ ),531+)532+def test_boolean_envvar_bad_values(runner, value):533+ @click.command()534+ @click.option("--shout/--no-shout", envvar="SHOUT")535+ def cli(shout):536+ click.echo(shout)537+538+ result = runner.invoke(cli, [], env={"SHOUT": value})539+ assert result.exit_code == 2540+ assert (541+ f"Invalid value for '--shout': {value!r} is not a valid boolean."542+ in result.output543+ )544+545+546 def test_multiple_default_help(runner):547 @click.command()548 @click.option("--arg1", multiple=True, default=("foo", "bar"), show_default=True)549 @click.option("--arg2", multiple=True, default=(1, 2), type=int, show_default=True)278 unmodified lines828 result = runner.invoke(cmd, ["-whatever=23"])829 assert result.output == "23\n"830 831 547-def test_missing_option_string_cast():832+@pytest.mark.parametrize(833+ ("value", "expect_missing", "processed_value"),834+ [835+ (UNSET, True, None),836+ (None, False, None),837+ # Default type of the argument is str, so everything is processed as strings.838+ ("", False, ""),839+ (" ", False, " "),840+ ("foo", False, "foo"),841+ ("12", False, "12"),842+ (12, False, "12"),843+ (12.1, False, "12.1"),844+ (list(), False, "[]"),845+ (tuple(), False, "()"),846+ (set(), False, "set()"),847+ (frozenset(), False, "frozenset()"),848+ (dict(), False, "{}"),849+ ],850+)851+def test_required_option(value, expect_missing, processed_value):852 ctx = click.Context(click.Command(""))853+ argument = click.Option(["-a"], required=True)854 855+ if expect_missing:550- with pytest.raises(click.MissingParameter) as excinfo:551- click.Option(["-a"], required=True).process_value(ctx, None)856+ with pytest.raises(click.MissingParameter) as excinfo:857+ argument.process_value(ctx, value)858+ assert str(excinfo.value) == "Missing parameter: a"859 553- assert str(excinfo.value) == "Missing parameter: a"860+ else:861+ value = argument.process_value(ctx, value)862+ assert value == processed_value863 864 865 def test_missing_required_flag(runner):866 cli = click.Command(33 unmodified lines900 result = runner.invoke(cli)901 assert result.exit_code == 2902 assert "Error: Missing option '--foo' (env var: 'bar')." in result.output903 904+ cli = click.Command(905+ "cli", params=[click.Option(["--foo"], show_envvar=True, required=True)]906+ )907+ result = runner.invoke(cli)908+ assert result.exit_code == 2909+ assert "Error: Missing option '--foo'." in result.output910 911+912 def test_case_insensitive_choice(runner):913 @click.command()914 @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))915 def cmd(foo):407 unmodified lines1323 assert param.type is click.INT1324 1325 1326 @pytest.mark.parametrize(1011- ("opts", "pass_flag", "expected"),1327+ ("opt_params", "args", "expected"),1328 [1013- pytest.param({"type": bool}, False, "False"),1014- pytest.param({"type": bool}, True, "True"),1015- pytest.param({"type": bool, "default": True}, False, "True"),1016- pytest.param({"type": bool, "default": True}, True, "False"),1017- pytest.param({"type": click.BOOL}, False, "False"),1018- pytest.param({"type": click.BOOL}, True, "True"),1019- pytest.param({"type": click.BOOL, "default": True}, False, "True"),1020- pytest.param({"type": click.BOOL, "default": True}, True, "False"),1021- pytest.param({"type": str}, False, ""),1022- pytest.param({"type": str}, True, "True"),1329+ # The type passed to the option is responsible to converting the value, whether1330+ # we pass the option flag or not.1331+ ({"type": bool}, [], False),1332+ ({"type": bool}, ["--foo"], True),1333+ ({"type": click.BOOL}, [], False),1334+ ({"type": click.BOOL}, ["--foo"], True),1335+ ({"type": str}, [], None),1336+ ({"type": str}, ["--foo"], "True"),1337+ # Default value is given as-is to the --foo option when it is not passed,1338+ # whatever the type. Now if --foo is passed, the value is always True, whatever1339+ # the type. In both case the type of the option is responsible for the1340+ # conversion of the value.1341+ ({"type": bool, "default": True}, [], True),1342+ ({"type": bool, "default": True}, ["--foo"], True),1343+ ({"type": bool, "default": False}, [], False),1344+ ({"type": bool, "default": False}, ["--foo"], True),1345+ # ({"type": bool, "default": "foo"}, [], "foo"),1346+ ({"type": bool, "default": "foo"}, ["--foo"], True),1347+ ({"type": bool, "default": None}, [], None),1348+ ({"type": bool, "default": None}, ["--foo"], True),1349+ ({"type": click.BOOL, "default": True}, [], True),1350+ ({"type": click.BOOL, "default": True}, ["--foo"], True),1351+ ({"type": click.BOOL, "default": False}, [], False),1352+ ({"type": click.BOOL, "default": False}, ["--foo"], True),1353+ # ({"type": click.BOOL, "default": "foo"}, [], "foo"),1354+ ({"type": click.BOOL, "default": "foo"}, ["--foo"], True),1355+ ({"type": click.BOOL, "default": None}, [], None),1356+ ({"type": click.BOOL, "default": None}, ["--foo"], True),1357+ ({"type": str, "default": True}, [], "True"),1358+ ({"type": str, "default": True}, ["--foo"], "True"),1359+ ({"type": str, "default": False}, [], "False"),1360+ ({"type": str, "default": False}, ["--foo"], "True"),1361+ ({"type": str, "default": "foo"}, [], "foo"),1362+ ({"type": str, "default": "foo"}, ["--foo"], "True"),1363+ ({"type": str, "default": None}, [], None),1364+ ({"type": str, "default": None}, ["--foo"], "True"),1365+ # Flag value is given as-is to the --foo option when it is passed, then1366+ # converted by the option type.1367+ ({"type": bool, "flag_value": True}, [], False),1368+ ({"type": bool, "flag_value": True}, ["--foo"], True),1369+ ({"type": bool, "flag_value": False}, [], False),1370+ ({"type": bool, "flag_value": False}, ["--foo"], False),1371+ ({"type": bool, "flag_value": None}, [], False),1372+ ({"type": bool, "flag_value": None}, ["--foo"], None),1373+ ({"type": click.BOOL, "flag_value": True}, [], False),1374+ ({"type": click.BOOL, "flag_value": True}, ["--foo"], True),1375+ ({"type": click.BOOL, "flag_value": False}, [], False),1376+ ({"type": click.BOOL, "flag_value": False}, ["--foo"], False),1377+ ({"type": click.BOOL, "flag_value": None}, [], False),1378+ ({"type": click.BOOL, "flag_value": None}, ["--foo"], None),1379+ ({"type": str, "flag_value": True}, [], None),1380+ ({"type": str, "flag_value": True}, ["--foo"], "True"),1381+ ({"type": str, "flag_value": False}, [], None),1382+ ({"type": str, "flag_value": False}, ["--foo"], "False"),1383+ ({"type": str, "flag_value": "foo"}, [], None),1384+ ({"type": str, "flag_value": "foo"}, ["--foo"], "foo"),1385+ ({"type": str, "flag_value": None}, [], None),1386+ ({"type": str, "flag_value": None}, ["--foo"], None),1387+ # Not passing --foo returns the default value as-is, in its Python type, then1388+ # converted by the option type.1389+ ({"type": bool, "default": True, "flag_value": True}, [], True),1390+ ({"type": bool, "default": True, "flag_value": False}, [], False),1391+ ({"type": bool, "default": False, "flag_value": True}, [], False),1392+ ({"type": bool, "default": False, "flag_value": False}, [], False),1393+ ({"type": bool, "default": None, "flag_value": True}, [], None),1394+ ({"type": bool, "default": None, "flag_value": False}, [], None),1395+ ({"type": str, "default": True, "flag_value": True}, [], "True"),1396+ ({"type": str, "default": True, "flag_value": False}, [], "False"),1397+ ({"type": str, "default": False, "flag_value": True}, [], "False"),1398+ ({"type": str, "default": False, "flag_value": False}, [], "False"),1399+ ({"type": str, "default": "foo", "flag_value": True}, [], "foo"),1400+ ({"type": str, "default": "foo", "flag_value": False}, [], "foo"),1401+ ({"type": str, "default": "foo", "flag_value": "bar"}, [], "foo"),1402+ ({"type": str, "default": "foo", "flag_value": None}, [], "foo"),1403+ ({"type": str, "default": None, "flag_value": True}, [], None),1404+ ({"type": str, "default": None, "flag_value": False}, [], None),1405+ # Passing --foo returns the flag_value that was explicitly set by the user,1406+ # with its Python type, but still converted by the option type.1407+ ({"type": bool, "default": True, "flag_value": True}, ["--foo"], True),1408+ ({"type": bool, "default": True, "flag_value": False}, ["--foo"], False),1409+ ({"type": bool, "default": False, "flag_value": True}, ["--foo"], True),1410+ ({"type": bool, "default": False, "flag_value": False}, ["--foo"], False),1411+ ({"type": bool, "default": None, "flag_value": True}, ["--foo"], True),1412+ ({"type": bool, "default": None, "flag_value": False}, ["--foo"], False),1413+ ({"type": str, "default": True, "flag_value": True}, ["--foo"], "True"),1414+ ({"type": str, "default": True, "flag_value": False}, ["--foo"], "False"),1415+ ({"type": str, "default": False, "flag_value": True}, ["--foo"], "True"),1416+ ({"type": str, "default": False, "flag_value": False}, ["--foo"], "False"),1417+ ({"type": str, "default": "foo", "flag_value": True}, ["--foo"], "True"),1418+ ({"type": str, "default": "foo", "flag_value": False}, ["--foo"], "False"),1419+ ({"type": str, "default": "foo", "flag_value": "bar"}, ["--foo"], "bar"),1420+ ({"type": str, "default": "foo", "flag_value": None}, ["--foo"], None),1421+ ({"type": str, "default": None, "flag_value": True}, ["--foo"], "True"),1422+ ({"type": str, "default": None, "flag_value": False}, ["--foo"], "False"),1423 ],1424 )1025-def test_flag_value_is_correctly_set(runner, opts, pass_flag, expected):1425+def test_flag_value_and_default(runner, opt_params, args, expected):1426 @click.command()1427+ @click.option("--foo", is_flag=True, **opt_params)1428+ def cmd(foo):1429+ click.echo(repr(foo), nl=False)1430+1431+ result = runner.invoke(cmd, args)1432+ assert result.output == repr(expected)1433+1434+1435+@pytest.mark.parametrize(1436+ ("args", "opts"),1437+ [1438+ ([], {"type": bool, "default": "foo"}),1439+ ([], {"type": click.BOOL, "default": "foo"}),1440+ (["--foo"], {"type": bool, "flag_value": "foo"}),1441+ (["--foo"], {"type": click.BOOL, "flag_value": "foo"}),1442+ ],1443+)1444+def test_invalid_flag_definition(runner, args, opts):1445+ @click.command()1446 @click.option("--foo", is_flag=True, **opts)1447 def cmd(foo):1448 click.echo(foo)1449 1031- result = runner.invoke(cmd, ["--foo"] if pass_flag else [])1032- assert result.output == f"{expected}\n"1450+ result = runner.invoke(cmd, args)1451+ assert (1452+ "Error: Invalid value for '--foo': 'foo' is not a valid boolean"1453+ in result.output1454+ )1455 1456 1457 @pytest.mark.parametrize(1036- ("option", "expected"),1458+ ("default", "args", "expected"),1459+ # These test cases are similar to the ones in1460+ # tests/test_basic.py::test_flag_value_dual_options, so keep them in sync.1461+ (1462+ # Each option is returning its own flag_value, whatever the default is.1463+ (True, ["--js"], "js"),1464+ (True, ["--xml"], "xml"),1465+ (False, ["--js"], "js"),1466+ (False, ["--xml"], "xml"),1467+ (None, ["--js"], "js"),1468+ (None, ["--xml"], "xml"),1469+ (UNSET, ["--js"], "js"),1470+ (UNSET, ["--xml"], "xml"),1471+ # Check that the last option wins when both are specified.1472+ (True, ["--js", "--xml"], "xml"),1473+ (True, ["--xml", "--js"], "js"),1474+ # Check that the default is returned as-is when no option is specified.1475+ ("js", [], "js"),1476+ ("xml", [], "xml"),1477+ ("jS", [], "jS"),1478+ ("xMl", [], "xMl"),1479+ (" ᕕ( ᐛ )ᕗ ", [], " ᕕ( ᐛ )ᕗ "),1480+ (None, [], None),1481+ # Special case: UNSET is not provided as-is to the callback, but normalized to1482+ # None.1483+ (UNSET, [], None),1484+ # Special case: if default=True and flag_value is set, the value returned is the1485+ # flag_value, not the True Python value itself.1486+ (True, [], "js"),1487+ # Non-string defaults are process as strings by the default Parameter's type.1488+ (False, [], "False"),1489+ (42, [], "42"),1490+ (12.3, [], "12.3"),1491+ ),1492+)1493+def test_default_dual_option_callback(runner, default, args, expected):1494+ """Check how default is processed by the callback when options compete for the same1495+ variable name.1496+1497+ Reproduction of the issue reported in1498+ https://github.com/pallets/click/pull/3030#discussion_r22715718191499+ """1500+1501+ def _my_func(ctx, param, value):1502+ # Print the value received by the callback as-is, so we can check for it.1503+ return f"Callback value: {value!r}"1504+1505+ @click.command()1506+ @click.option("--js", "fmt", flag_value="js", callback=_my_func, default=default)1507+ @click.option("--xml", "fmt", flag_value="xml", callback=_my_func)1508+ def main(fmt):1509+ click.secho(fmt, nl=False)1510+1511+ result = runner.invoke(main, args)1512+ assert result.output == f"Callback value: {expected!r}"1513+ assert result.exit_code == 01514+1515+1516+@pytest.mark.parametrize(1517+ ("flag_value", "envvar_value", "expected"),1518 [1038- # Not boolean flags1039- pytest.param(Option(["-a"], type=int), False, id="int option"),1040- pytest.param(Option(["-a"], type=bool), False, id="bool non-flag [None]"),1041- pytest.param(Option(["-a"], default=True), False, id="bool non-flag [True]"),1042- pytest.param(Option(["-a"], default=False), False, id="bool non-flag [False]"),1043- pytest.param(Option(["-a"], flag_value=1), False, id="non-bool flag_value"),1044- # Boolean flags1045- pytest.param(Option(["-a"], is_flag=True), True, id="is_flag=True"),1046- pytest.param(Option(["-a/-A"]), True, id="secondary option [implicit flag]"),1047- pytest.param(Option(["-a"], flag_value=True), True, id="bool flag_value"),1519+ # The envvar match exactly the flag value and is case-sensitive.1520+ ("bar", "bar", "bar"),1521+ ("BAR", "BAR", "BAR"),1522+ (" bar ", " bar ", " bar "),1523+ ("42", "42", "42"),1524+ ("None", "None", "None"),1525+ ("True", "True", "True"),1526+ ("False", "False", "False"),1527+ ("true", "true", "true"),1528+ ("false", "false", "false"),1529+ ("A B", "A B", "A B"),1530+ (" 1 2 ", " 1 2 ", " 1 2 "),1531+ ("9.3", "9.3", "9.3"),1532+ ("a;n", "a;n", "a;n"),1533+ ("x:y", "x:y", "x:y"),1534+ ("i/o", "i/o", "i/o"),1535+ # Empty or absent envvar is consider unset, so the flag default value is1536+ # returned, which is None in this case.1537+ ("bar", "", None),1538+ ("bar", None, None),1539+ ("BAR", "", None),1540+ ("BAR", None, None),1541+ (" bar ", "", None),1542+ (" bar ", None, None),1543+ (42, "", None),1544+ (42, None, None),1545+ ("42", "", None),1546+ ("42", None, None),1547+ (None, "", None),1548+ (None, None, None),1549+ ("None", "", None),1550+ ("None", None, None),1551+ (True, "", None),1552+ (True, None, None),1553+ ("True", "", None),1554+ ("True", None, None),1555+ ("true", "", None),1556+ ("true", None, None),1557+ (False, "", None),1558+ (False, None, None),1559+ ("False", "", None),1560+ ("False", None, None),1561+ ("false", "", None),1562+ ("false", None, None),1563+ # Activate the flag with a value recognized as True by the envvar, which1564+ # returns the flag_value.1565+ ("bar", "True", "bar"),1566+ ("bar", "true", "bar"),1567+ ("bar", "trUe", "bar"),1568+ ("bar", " TRUE ", "bar"),1569+ ("bar", "1", "bar"),1570+ ("bar", "yes", "bar"),1571+ ("bar", "on", "bar"),1572+ ("bar", "t", "bar"),1573+ ("bar", "y", "bar"),1574+ # Deactivating the flag with a value recognized as False by the envvar, which1575+ # explicitly return the 'False' as the option is explicitly declared as a1576+ # string.1577+ ("bar", "False", "False"),1578+ ("bar", "false", "False"),1579+ ("bar", "faLse", "False"),1580+ ("bar", " FALSE ", "False"),1581+ ("bar", "0", "False"),1582+ ("bar", "no", "False"),1583+ ("bar", "off", "False"),1584+ ("bar", "f", "False"),1585+ ("bar", "n", "False"),1586+ # Any other value than the flag_value, or a recogned True or False value, fails1587+ # to explicitly activate or deactivate the flag. So the flag default value is1588+ # returned, which is None in this case.1589+ ("bar", " bar ", None),1590+ ("bar", "BAR", None),1591+ ("bar", "random", None),1592+ ("bar", "bar random", None),1593+ ("bar", "random bar", None),1594+ ("BAR", "bar", None),1595+ (" bar ", "bar", None),1596+ (" bar ", "BAR", None),1597+ (42, "42", None),1598+ (42, "foo", None),1599+ (None, "foo", None),1600+ ("None", "foo", None),1601 ],1602 )1050-def test_is_bool_flag_is_correctly_set(option, expected):1051- assert option.is_bool_flag is expected1603+def test_envvar_string_flag_value(runner, flag_value, envvar_value, expected):1604+ """Ensure that flag_value is recognized by the envvar."""1605 1606+ @click.command()1607+ @click.option("--upper", type=str, flag_value=flag_value, envvar="UPPER")1608+ def cmd(upper):1609+ click.echo(repr(upper), nl=False)1610 1611+ result = runner.invoke(cmd, env={"UPPER": envvar_value})1612+ assert result.exit_code == 01613+ assert result.output == repr(expected)1614+1615+1616 @pytest.mark.parametrize(1617+ ("opt_decls", "opt_params", "expect_is_flag", "expect_is_bool_flag"),1618+ [1619+ # Not boolean flags.1620+ ("-a", {"type": int}, False, False),1621+ ("-a", {"type": bool}, False, False),1622+ ("-a", {"default": True}, False, False),1623+ ("-a", {"default": False}, False, False),1624+ ("-a", {"flag_value": 1}, True, False),1625+ # Boolean flags.1626+ ("-a", {"is_flag": True}, True, True),1627+ ("-a/-A", {}, True, True),1628+ ("-a", {"flag_value": True}, True, True),1629+ # Non-flag with flag_value.1630+ ("-a", {"is_flag": False, "flag_value": 1}, False, False),1631+ ],1632+)1633+def test_flag_auto_detection(1634+ opt_decls, opt_params, expect_is_flag, expect_is_bool_flag1635+):1636+ option = Option([opt_decls], **opt_params)1637+ assert option.is_flag is expect_is_flag1638+ assert option.is_bool_flag is expect_is_bool_flag1639+1640+1641+@pytest.mark.parametrize(1642 ("kwargs", "message"),1643 [1644 ({"count": True, "multiple": True}, "'count' is not valid with 'multiple'."),1645 ({"count": True, "is_flag": True}, "'count' is not valid with 'is_flag'."),19 unmodified lines1665 result = runner.invoke(cmd)1666 assert result.exit_code == 01667 1668 1669+class HashType(enum.Enum):1670+ MD5 = "MD5"1671+ SHA1 = "SHA1"1672+ SHA256 = "SHA-256"1673+1674+1675+class Number(enum.IntEnum):1676+ ONE = enum.auto()1677+ TWO = enum.auto()1678+1679+1680+class Letter(enum.StrEnum):1681+ NAME_1 = "Value-1"1682+ NAME_2 = "Value_2"1683+ NAME_3 = "42_value"1684+1685+1686+class Color(enum.Flag):1687+ RED = enum.auto()1688+ GREEN = enum.auto()1689+ BLUE = enum.auto()1690+1691+1692+class ColorInt(enum.IntFlag):1693+ RED = enum.auto()1694+ GREEN = enum.auto()1695+ BLUE = enum.auto()1696+1697+1698 @pytest.mark.parametrize(1083- ("choices", "metavars"),1699+ ("choices", "metavar"),1700 [1085- pytest.param(["foo", "bar"], "[TEXT]", id="text choices"),1086- pytest.param([1, 2], "[INTEGER]", id="int choices"),1087- pytest.param([1.0, 2.0], "[FLOAT]", id="float choices"),1088- pytest.param([True, False], "[BOOLEAN]", id="bool choices"),1089- pytest.param(["foo", 1], "[TEXT|INTEGER]", id="text/int choices"),1701+ (["foo", "bar"], "[TEXT]"),1702+ ([1, 2], "[INTEGER]"),1703+ ([1.0, 2.0], "[FLOAT]"),1704+ ([True, False], "[BOOLEAN]"),1705+ (["foo", 1], "[TEXT|INTEGER]"),1706+ (HashType, "[HASHTYPE]"),1707+ (Number, "[NUMBER]"),1708+ (Letter, "[LETTER]"),1709+ (Color, "[COLOR]"),1710+ (ColorInt, "[COLORINT]"),1711 ],1712 )1092-def test_usage_show_choices(runner, choices, metavars):1093- """When show_choices=False is set, the --help output1094- should print choice metavars instead of values.1713+def test_choice_usage_rendering(runner, choices, metavar):1714+ """BY default ``--help`` prints choice's values in the usage message.1715+1716+ But ``show_choices=False`` makes ``--help`` prints choice's METAVAR instead of1717+ values.1718+1719+ Also check that usage error message always suggests the actual values.1720 """1721 1722 @click.command()1723 @click.option("-g", type=click.Choice(choices))1724 def cli_with_choices(g):1725 pass1726 1727 @click.command()1103- @click.option(1104- "-g",1105- type=click.Choice(choices),1106- show_choices=False,1107- )1728+ @click.option("-g", type=click.Choice(choices), show_choices=False)1729 def cli_without_choices(g):1730 pass1731 1732+ display_values = tuple(1733+ i.name if isinstance(i, enum.Enum) else str(i) for i in choices1734+ )1735+1736+ # Check that the choices values are rendered as-is in the usage message.1737 result = runner.invoke(cli_with_choices, ["--help"])1112- assert f"[{'|'.join([str(i) for i in choices])}]" in result.output1738+ assert f"[{'|'.join(display_values)}]" in result.stdout1739+ assert not result.stderr1740+ assert result.exit_code == 01741 1742+ # Check that the metavar is rendered instead of the choices values themselves.1743 result = runner.invoke(cli_without_choices, ["--help"])1115- assert metavars in result.output1744+ assert metavar in result.stdout1745+ assert not result.stderr1746+ assert result.exit_code == 01747 1748+ # Check the usage error message suggests the actual accepted values.1749+ for cli in (cli_with_choices, cli_without_choices):1750+ result = runner.invoke(cli, ["-g", "random"])1751+ assert (1752+ "\n\nError: Invalid value for '-g': 'random' is not one of "1753+ f"{', '.join(map(repr, display_values))}.\n" in result.stderr1754+ )1755+ assert not result.stdout1756+ assert result.exit_code == 21757 1758+1759 @pytest.mark.parametrize(1760+ ("choices", "default", "default_string"),1761+ [1762+ (["foo", "bar"], "bar", "bar"),1763+ # The default value is not enforced to be in the choices.1764+ (["foo", "bar"], "random", "random"),1765+ # None cannot be a default value as-is: it left the default value as unset.1766+ (["foo", "bar"], None, None),1767+ ([0, 1], 0, "0"),1768+ # Values are not coerced to the type of the choice, even if equivalent.1769+ ([0, 1], 0.0, "0.0"),1770+ ([1, 2], 2, "2"),1771+ ([1.0, 2.0], 2, "2"),1772+ ([1.0, 2.0], 2.0, "2.0"),1773+ ([True, False], True, "True"),1774+ ([True, False], False, "False"),1775+ (["foo", 1], "foo", "foo"),1776+ (["foo", 1], 1, "1"),1777+ # Enum choices are rendered as their names, not values.1778+ # See: https://github.com/pallets/click/issues/29111779+ (HashType, HashType.SHA1, "SHA1"),1780+ # Enum choices allow defaults strings that are their names.1781+ (HashType, HashType.SHA256, "SHA256"),1782+ (HashType, "SHA256", "SHA256"),1783+ (Number, Number.TWO, "TWO"),1784+ (Number, "TWO", "TWO"),1785+ (Letter, Letter.NAME_1, "NAME_1"),1786+ (Letter, Letter.NAME_2, "NAME_2"),1787+ (Letter, Letter.NAME_3, "NAME_3"),1788+ (Letter, "NAME_1", "NAME_1"),1789+ (Letter, "NAME_2", "NAME_2"),1790+ (Letter, "NAME_3", "NAME_3"),1791+ (Color, Color.GREEN, "GREEN"),1792+ (Color, "GREEN", "GREEN"),1793+ (ColorInt, ColorInt.GREEN, "GREEN"),1794+ (ColorInt, "GREEN", "GREEN"),1795+ ],1796+)1797+def test_choice_default_rendering(runner, choices, default, default_string):1798+ @click.command()1799+ @click.option("-g", type=click.Choice(choices), default=default, show_default=True)1800+ def cli_with_choices(g):1801+ pass1802+1803+ # Check that the default value is kept normalized to the type of the choice.1804+ assert cli_with_choices.params[0].default == default1805+1806+ result = runner.invoke(cli_with_choices, ["--help"])1807+ extra_usage = f"[default: {default_string}]"1808+ if default_string is None:1809+ assert extra_usage not in result.output1810+ else:1811+ assert extra_usage in result.output1812+1813+1814+@pytest.mark.parametrize(1815 "opts_one,opts_two",1816 [1817 # No duplicate shortnames1818 (15 unmodified lines1834 pass1835 1836 with pytest.warns(UserWarning):1837 runner.invoke(cli, [])1838+1839+1840+OBJECT_SENTINEL = object()1841+"""An object-based sentinel value."""1842+1843+1844+class EnumSentinel(enum.Enum):1845+ FALSY_SENTINEL = object()1846+1847+ def __bool__(self) -> Literal[False]:1848+ """Force the sentinel to be falsy to make sure it is not caught by Click1849+ internal implementation.1850+1851+ Falsy sentinels have been discussed in:1852+ https://github.com/pallets/click/pull/3030#pullrequestreview-31066047951853+ https://github.com/pallets/click/pull/3030#pullrequestreview-31084715521854+ """1855+ return False1856+1857+1858+# Any kind of sentinel value is recognized by Click as a valid flag value.1859+@pytest.mark.parametrize("sentinel", (OBJECT_SENTINEL, EnumSentinel.FALSY_SENTINEL))1860+@pytest.mark.parametrize(1861+ ("args", "expected"),1862+ (1863+ # Option default to None.1864+ ([], None),1865+ # Config has no default value, and no flag value, so it requires an argument.1866+ (1867+ ["--config"],1868+ re.compile(re.escape("Error: Option '--config' requires an argument.\n")),1869+ ),1870+ (1871+ ["--no-config", "--config"],1872+ re.compile(re.escape("Error: Option '--config' requires an argument.\n")),1873+ ),1874+ # Passing --no-config defaults to the sentinel value because of the flag_value,1875+ # and then the custom type receives that sentinel and returns a message.1876+ (["--no-config"], "No configuration file provided."),1877+ # Passing --config with an argument returns the file path.1878+ (["--config", "foo.conf"], "foo.conf"),1879+ # An argument is not allowed for --no-config, so it raises an error.1880+ (1881+ ["--no-config", "foo.conf"],1882+ re.compile(1883+ r"Usage: main \[OPTIONS\]\n"1884+ r"Try 'main --help' for help.\n"1885+ r"\n"1886+ r"Error: Got unexpected extra argument (.+)\n"1887+ ),1888+ ),1889+ # Passing --config with an argument that does not exist raises an error.1890+ (1891+ ["--config", "random-file.conf"],1892+ re.compile(1893+ r"Usage: main \[OPTIONS\]\n"1894+ r"Try 'main --help' for help.\n"1895+ r"\n"1896+ r"Error: Invalid value for '-c' / '--config': "1897+ r"File 'random-file.conf' does not exist.\n"1898+ ),1899+ ),1900+ (1901+ ["--config", "--no-config"],1902+ re.compile(1903+ r"Usage: main \[OPTIONS\]\n"1904+ r"Try 'main --help' for help.\n"1905+ r"\n"1906+ r"Error: Invalid value for '-c' / '--config': "1907+ r"File '--no-config' does not exist.\n"1908+ ),1909+ ),1910+ (1911+ ["--config", "--no-config", "foo.conf"],1912+ re.compile(1913+ r"Usage: main \[OPTIONS\]\n"1914+ r"Try 'main --help' for help.\n"1915+ r"\n"1916+ r"Error: Invalid value for '-c' / '--config': "1917+ r"File '--no-config' does not exist.\n"1918+ ),1919+ ),1920+ # --config is passed last and overrides the --no-config option.1921+ (["--no-config", "--config", "foo.conf"], "foo.conf"),1922+ ),1923+)1924+def test_dual_options_custom_type_sentinel_flag_value(runner, sentinel, args, expected):1925+ """Check that an object-based sentinel, used as a flag value, is returned as-is1926+ to a custom type that is shared by two options, competing for the same variable1927+ name.1928+1929+ A reproduction of1930+ https://github.com/pallets/click/issues/3024#issuecomment-31465113561931+ """1932+1933+ class ConfigParamType(click.ParamType):1934+ """A custom type that accepts a file path or a sentinel value."""1935+1936+ def convert(self, value, param, ctx):1937+ if value is sentinel:1938+ return "No configuration file provided."1939+ else:1940+ return click.Path(exists=True, dir_okay=False).convert(1941+ value, param, ctx1942+ )1943+1944+ @click.command()1945+ @click.option("-c", "--config", type=ConfigParamType())1946+ @click.option("--no-config", "config", flag_value=sentinel, type=ConfigParamType())1947+ def main(config):1948+ click.echo(repr(config), nl=False)1949+1950+ with tempfile.NamedTemporaryFile(mode="w") as named_tempfile:1951+ if "foo.conf" in args:1952+ named_tempfile.write("Blah blah")1953+ named_tempfile.flush()1954+ args = [named_tempfile.name if a == "foo.conf" else a for a in args]1955+1956+ result = runner.invoke(main, args)1957+1958+ if isinstance(expected, re.Pattern):1959+ assert re.match(expected, result.output)1960+ else:1961+ assert result.output == repr(1962+ named_tempfile.name if expected == "foo.conf" else expected1963+ )1964+1965+1966+class EngineType(enum.Enum):1967+ OSS = enum.auto()1968+ PRO = enum.auto()1969+ MAX = enum.auto()1970+1971+1972+class Class1:1973+ pass1974+1975+1976+class Class2:1977+ pass1978+1979+1980+@pytest.mark.parametrize(1981+ ("opt_params", "args", "expected"),1982+ [1983+ # Check that the flag value is returned as-is when the option is passed, and1984+ # not normalized to a boolean, even if it is explicitly declared as a flag.1985+ ({"type": EngineType, "flag_value": None}, ["--pro"], None),1986+ (1987+ {"type": EngineType, "is_flag": True, "flag_value": None},1988+ ["--pro"],1989+ None,1990+ ),1991+ ({"type": EngineType, "flag_value": EngineType.OSS}, ["--pro"], EngineType.OSS),1992+ (1993+ {"type": EngineType, "is_flag": True, "flag_value": EngineType.OSS},1994+ ["--pro"],1995+ EngineType.OSS,1996+ ),1997+ (1998+ {"type": EngineType, "is_flag": True, "default": EngineType.OSS},1999+ ["--pro"],2000+ EngineType.OSS,2001+ ),2002+ # The default value is returned as-is when the option is not passed, whatever2003+ # the flag value.2004+ ({"type": EngineType, "flag_value": None}, [], None),2005+ ({"type": EngineType, "is_flag": True, "flag_value": None}, [], None),2006+ ({"type": EngineType, "flag_value": EngineType.OSS}, [], None),2007+ (2008+ {"type": EngineType, "is_flag": True, "flag_value": EngineType.OSS},2009+ [],2010+ None,2011+ ),2012+ (2013+ {"type": EngineType, "is_flag": True, "default": EngineType.OSS},2014+ [],2015+ EngineType.OSS,2016+ ),2017+ # The option has not enough parameters to be detected as flag-like, so it2018+ # requires an argument.2019+ (2020+ {"type": EngineType, "default": EngineType.OSS},2021+ ["--pro"],2022+ re.compile(re.escape("Error: Option '--pro' requires an argument.\n")),2023+ ),2024+ ({"type": EngineType, "default": EngineType.OSS}, [], EngineType.OSS),2025+ # If a flag value is set, it is returned instead of the default value.2026+ (2027+ {"type": EngineType, "flag_value": EngineType.OSS, "default": True},2028+ ["--pro"],2029+ EngineType.OSS,2030+ ),2031+ (2032+ {"type": EngineType, "flag_value": EngineType.OSS, "default": True},2033+ [],2034+ EngineType.OSS,2035+ ),2036+ # Type is not specified and default to string, so the default value is2037+ # returned as a string, even if it is a boolean. Also, defaults to the2038+ # flag_value instead of the default value to support legacy behavior.2039+ ({"flag_value": "1", "default": True}, [], "1"),2040+ ({"flag_value": "1", "default": 42}, [], "42"),2041+ ({"flag_value": EngineType.OSS, "default": True}, [], "EngineType.OSS"),2042+ ({"flag_value": EngineType.OSS, "default": 42}, [], "42"),2043+ # See: the result is the same if we force the type to be str.2044+ ({"type": str, "flag_value": 1, "default": True}, [], "1"),2045+ ({"type": str, "flag_value": 1, "default": 42}, [], "42"),2046+ ({"type": str, "flag_value": "1", "default": True}, [], "1"),2047+ ({"type": str, "flag_value": "1", "default": 42}, [], "42"),2048+ (2049+ {"type": str, "flag_value": EngineType.OSS, "default": True},2050+ [],2051+ "EngineType.OSS",2052+ ),2053+ ({"type": str, "flag_value": EngineType.OSS, "default": 42}, [], "42"),2054+ # But having the flag value set to integer is automaticcally recognized by2055+ # Click.2056+ ({"flag_value": 1, "default": True}, [], 1),2057+ ({"flag_value": 1, "default": 42}, [], 42),2058+ ({"type": int, "flag_value": 1, "default": True}, [], 1),2059+ ({"type": int, "flag_value": 1, "default": 42}, [], 42),2060+ ({"type": int, "flag_value": "1", "default": True}, [], 1),2061+ ({"type": int, "flag_value": "1", "default": 42}, [], 42),2062+ ],2063+)2064+def test_custom_type_flag_value_standalone_option(runner, opt_params, args, expected):2065+ """Test how the type and flag_value influence the returned value.2066+2067+ Cover cases reported in:2068+ https://github.com/pallets/click/issues/3024#issuecomment-31464807142069+ https://github.com/pallets/click/issues/2012#issuecomment-8924370602070+ """2071+2072+ @click.command()2073+ @click.option("--pro", **opt_params)2074+ def scan(pro):2075+ click.echo(repr(pro), nl=False)2076+2077+ result = runner.invoke(scan, args)2078+ if isinstance(expected, re.Pattern):2079+ assert re.match(expected, result.output)2080+ else:2081+ assert result.output == repr(expected)2082+2083+2084+@pytest.mark.parametrize(2085+ ("opt1_params", "opt2_params", "args", "expected"),2086+ [2087+ # Dual options sharing the same variable name, are not competitive, and the2088+ # flag value is returned as-is. Especially when the type is force to be2089+ # unprocessed.2090+ (2091+ {"flag_value": EngineType.OSS, "type": UNPROCESSED},2092+ {"flag_value": EngineType.PRO, "type": UNPROCESSED},2093+ [],2094+ None,2095+ ),2096+ (2097+ {"flag_value": EngineType.OSS, "type": UNPROCESSED},2098+ {"flag_value": EngineType.PRO, "type": UNPROCESSED},2099+ ["--opt1"],2100+ EngineType.OSS,2101+ ),2102+ (2103+ {"flag_value": EngineType.OSS, "type": UNPROCESSED},2104+ {"flag_value": EngineType.PRO, "type": UNPROCESSED},2105+ ["--opt2"],2106+ EngineType.PRO,2107+ ),2108+ # Check that passing exotic flag values like classes is supported, but are2109+ # rendered to strings when the type is not specified.2110+ (2111+ {"flag_value": Class1, "default": True},2112+ {"flag_value": Class2},2113+ [],2114+ re.compile(r"'<test_options.Class1 object at 0x[0-9A-Fa-f]+>'"),2115+ ),2116+ (2117+ {"flag_value": Class1, "default": True},2118+ {"flag_value": Class2},2119+ ["--opt1"],2120+ "<class 'test_options.Class1'>",2121+ ),2122+ (2123+ {"flag_value": Class1, "default": True},2124+ {"flag_value": Class2},2125+ ["--opt2"],2126+ "<class 'test_options.Class2'>",2127+ ),2128+ # Even the default is processed as a string.2129+ ({"flag_value": Class1, "default": "True"}, {"flag_value": Class2}, [], "True"),2130+ ({"flag_value": Class1, "default": None}, {"flag_value": Class2}, [], None),2131+ # To get the classes as-is, we need to specify the type as UNPROCESSED.2132+ (2133+ {"flag_value": Class1, "type": UNPROCESSED, "default": True},2134+ {"flag_value": Class2, "type": UNPROCESSED},2135+ [],2136+ re.compile(r"<test_options.Class1 object at 0x[0-9A-Fa-f]+>"),2137+ ),2138+ (2139+ {"flag_value": Class1, "type": UNPROCESSED, "default": True},2140+ {"flag_value": Class2, "type": UNPROCESSED},2141+ ["--opt1"],2142+ Class1,2143+ ),2144+ (2145+ {"flag_value": Class1, "type": UNPROCESSED, "default": True},2146+ {"flag_value": Class2, "type": UNPROCESSED},2147+ ["--opt2"],2148+ Class2,2149+ ),2150+ # Setting the default to a class, an instance of the class is returned instead2151+ # of the class itself, because the default is allowed to be callable (and2152+ # consummd). And this happens whatever the type is.2153+ (2154+ {"flag_value": Class1, "default": Class1},2155+ {"flag_value": Class2},2156+ [],2157+ re.compile(r"'<test_options.Class1 object at 0x[0-9A-Fa-f]+>'"),2158+ ),2159+ (2160+ {"flag_value": Class1, "default": Class2},2161+ {"flag_value": Class2},2162+ [],2163+ re.compile(r"'<test_options.Class2 object at 0x[0-9A-Fa-f]+>'"),2164+ ),2165+ (2166+ {"flag_value": Class1, "type": UNPROCESSED, "default": Class1},2167+ {"flag_value": Class2, "type": UNPROCESSED},2168+ [],2169+ re.compile(r"<test_options.Class1 object at 0x[0-9A-Fa-f]+>"),2170+ ),2171+ (2172+ {"flag_value": Class1, "type": UNPROCESSED, "default": Class2},2173+ {"flag_value": Class2, "type": UNPROCESSED},2174+ [],2175+ re.compile(r"<test_options.Class2 object at 0x[0-9A-Fa-f]+>"),2176+ ),2177+ # Having the flag value set to integer is automaticcally recognized by Click.2178+ (2179+ {"flag_value": 1, "default": True},2180+ {"flag_value": "1"},2181+ [],2182+ 1,2183+ ),2184+ (2185+ {"flag_value": 1, "type": int, "default": True},2186+ {"flag_value": "1", "type": int},2187+ [],2188+ 1,2189+ ),2190+ ],2191+)2192+def test_custom_type_flag_value_dual_options(2193+ runner, opt1_params, opt2_params, args, expected2194+):2195+ """Test how flag values are processed with dual options competing for the same2196+ variable name.2197+2198+ Reproduce issues reported in:2199+ https://github.com/pallets/click/issues/3024#issuecomment-31465085362200+ https://github.com/pallets/click/issues/2012#issue-9464710492201+ https://github.com/pallets/click/issues/2012#issuecomment-8924370602202+ """2203+2204+ @click.command()2205+ @click.option("--opt1", "dual_option", **opt1_params)2206+ @click.option("--opt2", "dual_option", **opt2_params)2207+ def cli(dual_option):2208+ click.echo(repr(dual_option), nl=False)2209+2210+ result = runner.invoke(cli, args)2211+ if isinstance(expected, re.Pattern):2212+ assert re.match(expected, result.output)2213+ else:2214+ assert result.output == repr(expected)2215+2216+2217+def test_custom_type_frozenset_flag_value(runner):2218+ """Check that frozenset is correctly handled as a type, a flag value and a default.2219+2220+ Reproduces https://github.com/pallets/click/issues/26102221+ """2222+2223+ @click.command()2224+ @click.option(2225+ "--without-scm-ignore-files",2226+ "scm_ignore_files",2227+ is_flag=True,2228+ type=frozenset,2229+ flag_value=frozenset(),2230+ default=frozenset(["git"]),2231+ )2232+ def rcli(scm_ignore_files):2233+ click.echo(repr(scm_ignore_files), nl=False)2234+2235+ result = runner.invoke(rcli)2236+ assert result.stdout == "frozenset({'git'})"2237+ assert result.exit_code == 02238+2239+ result = runner.invoke(rcli, ["--without-scm-ignore-files"])2240+ assert result.stdout == "frozenset()"2241+ assert result.exit_code == 0modified:tests/test_shell_completion.py+89 added
1+import textwrap2 import warnings3+from collections.abc import Mapping4 5 import pytest6 7 import click.shell_completion211 unmodified lines219 # flag option doesn't take value, use choice argument220 assert _get_words(cli, ["--on"], "a") == ["a1", "a2"]221 222 223+def test_flag_option_with_nargs_option():224+ cli = Command(225+ "cli",226+ add_help_option=False,227+ params=[228+ Argument(["a"], type=Choice(["a1", "a2", "b"])),229+ Option(["--flag"], is_flag=True),230+ Option(["-c"], type=Choice(["p", "q"]), nargs=2),231+ ],232+ )233+ assert _get_words(cli, ["a1", "--flag", "-c"], "") == ["p", "q"]234+235+236 def test_option_custom():237 def custom(ctx, param, incomplete):238 return [incomplete.upper()]239 118 unmodified lines358 ("zsh", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain\na\n_\nplain\nb\nbee\n"),359 ("zsh", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain\nb\nbee\n"),360 ("fish", {"COMP_WORDS": "", "COMP_CWORD": ""}, "plain,a\nplain,b\tbee\n"),361 ("fish", {"COMP_WORDS": "a b", "COMP_CWORD": "b"}, "plain,b\tbee\n"),362+ ("fish", {"COMP_WORDS": 'a "b', "COMP_CWORD": '"b'}, "plain,b\tbee\n"),363 ],364 )365 @pytest.mark.usefixtures("_patch_for_completion")366 def test_full_complete(runner, shell, env, expect):2 unmodified lines369 result = runner.invoke(cli, env=env)370 assert result.output == expect371 372 373+@pytest.mark.parametrize(374+ ("env", "expect"),375+ [376+ (377+ {"COMP_WORDS": "", "COMP_CWORD": "0"},378+ textwrap.dedent(379+ """\380+ plain381+ a382+ _383+ plain384+ b385+ bee386+ plain387+ c\\:d388+ cee:dee389+ plain390+ c:e391+ _392+ """393+ ),394+ ),395+ (396+ {"COMP_WORDS": "a c", "COMP_CWORD": "1"},397+ textwrap.dedent(398+ """\399+ plain400+ c\\:d401+ cee:dee402+ plain403+ c:e404+ _405+ """406+ ),407+ ),408+ (409+ {"COMP_WORDS": "a c:", "COMP_CWORD": "1"},410+ textwrap.dedent(411+ """\412+ plain413+ c\\:d414+ cee:dee415+ plain416+ c:e417+ _418+ """419+ ),420+ ),421+ ],422+)423 @pytest.mark.usefixtures("_patch_for_completion")424+def test_zsh_full_complete_with_colons(425+ runner, env: Mapping[str, str], expect: str426+) -> None:427+ cli = Group(428+ "cli",429+ commands=[430+ Command("a"),431+ Command("b", help="bee"),432+ Command("c:d", help="cee:dee"),433+ Command("c:e"),434+ ],435+ )436+ result = runner.invoke(437+ cli,438+ env={439+ **env,440+ "_CLI_COMPLETE": "zsh_complete",441+ },442+ )443+ assert result.output == expect444+445+446+@pytest.mark.usefixtures("_patch_for_completion")447 def test_context_settings(runner):448 def complete(ctx, param, incomplete):449 return ctx.obj["choices"]450 111 unmodified linesmodified:tests/test_termui.py+218 added
4 unmodified lines5 import pytest6 7 import click._termui_impl8 from click._compat import WIN9+from click.exceptions import BadParameter10+from click.exceptions import MissingParameter11 12 13 class FakeClock:14 def __init__(self):471 unmodified lines486 # Confirm that the default value is not included in the output when `show_default`487 # is False488 result = runner.invoke(cmd, input="my-input", standalone_mode=False)489 assert "my-default-value" not in result.output490+491+492+REPEAT = object()493+"""Sentinel value to indicate that the prompt is expected to be repeated.494+495+I.e. the value provided by the user is not satisfactory and need to be re-prompted.496+"""497+498+INVALID = object()499+"""Sentinel value to indicate that the prompt is expected to be invalid.500+501+On invalid input, Click will output an error message and re-prompt the user.502+"""503+504+BOOLEAN_FLAG_PROMPT_CASES = [505+ ###506+ ### Test cases with prompt=True explicitly enabled for the flag.507+ ###508+ # Prompt is allowed and the flag has no default, so it prompts.509+ ({"prompt": True}, [], "[y/N]", "y", True),510+ ({"prompt": True}, [], "[y/N]", "n", False),511+ # Empty input default to False.512+ ({"prompt": True}, [], "[y/N]", "", False),513+ # Changing the default to True, makes the prompt change to [Y/n].514+ ({"prompt": True, "default": True}, [], "[Y/n]", "", True),515+ ({"prompt": True, "default": True}, [], "[Y/n]", "y", True),516+ ({"prompt": True, "default": True}, [], "[Y/n]", "n", False),517+ # False is the default's default, so it prompts with [y/N].518+ ({"prompt": True, "default": False}, [], "[y/N]", "", False),519+ ({"prompt": True, "default": False}, [], "[y/N]", "y", True),520+ ({"prompt": True, "default": False}, [], "[y/N]", "n", False),521+ # Defaulting to None, prompts with [y/n], which makes the user explicitly choose522+ # between True or False.523+ ({"prompt": True, "default": None}, [], "[y/n]", "y", True),524+ ({"prompt": True, "default": None}, [], "[y/n]", "n", False),525+ # Random string default is treated as a truthy value, so it prompts with [Y/n].526+ ({"prompt": True, "default": "foo"}, [], "[Y/n]", "", True),527+ ({"prompt": True, "default": "foo"}, [], "[Y/n]", "y", True),528+ ({"prompt": True, "default": "foo"}, [], "[Y/n]", "n", False),529+ ###530+ ### Test cases with required=True explicitly enabled for the flag.531+ ###532+ # A required flag just raises an error unless a default is set.533+ ({"required": True}, [], None, None, MissingParameter),534+ ({"required": True, "default": True}, [], None, None, True),535+ ({"required": True, "default": False}, [], None, None, False),536+ ({"required": True, "default": None}, [], None, None, None),537+ ({"required": True, "default": "on"}, [], None, None, True),538+ ({"required": True, "default": "off"}, [], None, None, False),539+ ({"required": True, "default": "foo"}, [], None, None, BadParameter),540+ ###541+ ### Explicitly passing the flag to the CLI bypass any prompt, whatever the542+ ### configuration of the flag.543+ ###544+ # Flag allowing a prompt.545+ ({"prompt": True}, ["--flag"], None, None, True),546+ ({"prompt": True}, ["--no-flag"], None, None, False),547+ ({"prompt": True, "default": None}, ["--flag"], None, None, True),548+ ({"prompt": True, "default": None}, ["--no-flag"], None, None, False),549+ ({"prompt": True, "default": True}, ["--flag"], None, None, True),550+ ({"prompt": True, "default": True}, ["--no-flag"], None, None, False),551+ ({"prompt": True, "default": False}, ["--flag"], None, None, True),552+ ({"prompt": True, "default": False}, ["--no-flag"], None, None, False),553+ ({"prompt": True, "default": "foo"}, ["--flag"], None, None, True),554+ ({"prompt": True, "default": "foo"}, ["--no-flag"], None, None, False),555+ # Required flag.556+ ({"required": True}, ["--flag"], None, None, True),557+ ({"required": True}, ["--no-flag"], None, None, False),558+ ({"required": True, "default": None}, ["--flag"], None, None, True),559+ ({"required": True, "default": None}, ["--no-flag"], None, None, False),560+ ({"required": True, "default": True}, ["--flag"], None, None, True),561+ ({"required": True, "default": True}, ["--no-flag"], None, None, False),562+ ({"required": True, "default": False}, ["--flag"], None, None, True),563+ ({"required": True, "default": False}, ["--no-flag"], None, None, False),564+ ({"required": True, "default": "foo"}, ["--flag"], None, None, True),565+ ({"required": True, "default": "foo"}, ["--no-flag"], None, None, False),566+]567+568+FLAG_VALUE_PROMPT_CASES = [569+ ###570+ ### Test cases with prompt=True explicitly enabled for the flag.571+ ###572+ # Prompt is allowed and the flag has no default, so it prompts.573+ # But the flag_value is not set, so it defaults to a string.574+ ({"prompt": True}, [], "", "", REPEAT),575+ ({"prompt": True}, [], "", "y", "y"),576+ ({"prompt": True}, [], "", "n", "n"),577+ ({"prompt": True}, [], "", "foo", "foo"),578+ # This time we provide a boolean flag_value, which makes the flag behave like a579+ # boolean flag, and use the appropriate variation of [y/n].580+ ({"prompt": True, "flag_value": True}, [], "[y/N]", "", False),581+ ({"prompt": True, "flag_value": True}, [], "[y/N]", "y", True),582+ ({"prompt": True, "flag_value": True}, [], "[y/N]", "n", False),583+ ({"prompt": True, "flag_value": False}, [], "[y/N]", "", False),584+ ({"prompt": True, "flag_value": False}, [], "[y/N]", "y", True),585+ ({"prompt": True, "flag_value": False}, [], "[y/N]", "n", False),586+ # Other flag values changes the auto-detection of the flag type.587+ ({"prompt": True, "flag_value": None}, [], "", "", REPEAT),588+ ({"prompt": True, "flag_value": None}, [], "", "y", "y"),589+ ({"prompt": True, "flag_value": None}, [], "", "n", "n"),590+ ({"prompt": True, "flag_value": "foo"}, [], "", "", REPEAT),591+ ({"prompt": True, "flag_value": "foo"}, [], "", "y", "y"),592+ ({"prompt": True, "flag_value": "foo"}, [], "", "n", "n"),593+ ###594+ ### Test cases with a flag_value and a default.595+ ###596+ # default=True597+ ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "", True),598+ ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "y", True),599+ ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "n", False),600+ ({"prompt": True, "default": True, "flag_value": False}, [], "[y/N]", "", False),601+ ({"prompt": True, "default": True, "flag_value": False}, [], "[y/N]", "y", True),602+ ({"prompt": True, "default": True, "flag_value": False}, [], "[y/N]", "n", False),603+ # default=False604+ ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "", False),605+ ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "y", True),606+ ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "n", False),607+ ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "", False),608+ ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "y", True),609+ ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "n", False),610+ # default=None611+ (612+ {"prompt": True, "default": None, "flag_value": True},613+ [],614+ "[y/n]",615+ "",616+ INVALID,617+ ),618+ ({"prompt": True, "default": None, "flag_value": True}, [], "[y/n]", "y", True),619+ ({"prompt": True, "default": None, "flag_value": True}, [], "[y/n]", "n", False),620+ (621+ {"prompt": True, "default": None, "flag_value": False},622+ [],623+ "[y/n]",624+ "",625+ INVALID,626+ ),627+ ({"prompt": True, "default": None, "flag_value": False}, [], "[y/n]", "y", True),628+ ({"prompt": True, "default": None, "flag_value": False}, [], "[y/n]", "n", False),629+ # If the flag_value is None, the flag behave like a string flag, whatever the630+ # default is.631+ ({"prompt": True, "default": True, "flag_value": None}, [], "", "", REPEAT),632+ ({"prompt": True, "default": True, "flag_value": None}, [], "", "y", "y"),633+ ({"prompt": True, "default": True, "flag_value": None}, [], "", "n", "n"),634+ (635+ {"prompt": True, "default": False, "flag_value": None},636+ [],637+ "[False]",638+ "",639+ "False",640+ ),641+ ({"prompt": True, "default": False, "flag_value": None}, [], "[False]", "y", "y"),642+ ({"prompt": True, "default": False, "flag_value": None}, [], "[False]", "n", "n"),643+ ({"prompt": True, "default": None, "flag_value": None}, [], "", "", REPEAT),644+ ({"prompt": True, "default": None, "flag_value": None}, [], "", "y", "y"),645+ ({"prompt": True, "default": None, "flag_value": None}, [], "", "n", "n"),646+]647+648+649+@pytest.mark.parametrize(650+ ("opt_decls", "opt_params", "args", "prompt", "input", "expected"),651+ # Boolean flag prompt cases.652+ [("--flag/--no-flag", *case_params) for case_params in BOOLEAN_FLAG_PROMPT_CASES]653+ # Non-boolean flag prompt cases.654+ + [("--flag", *case_params) for case_params in FLAG_VALUE_PROMPT_CASES],655+)656+def test_flag_value_prompt(657+ runner, opt_decls, opt_params, args, prompt, input, expected658+):659+ """Check how flag value are prompted and handled by all combinations of660+ ``prompt``, ``default``, and ``flag_value`` parameters.661+662+ Covers concerns raised in issue https://github.com/pallets/click/issues/1992.663+ """664+665+ @click.command()666+ @click.option(opt_decls, **opt_params)667+ def cli(flag):668+ click.echo(repr(flag))669+670+ invoke_options = {"standalone_mode": False}671+ if input is not None:672+ assert isinstance(input, str)673+ invoke_options["input"] = f"{input}\n"674+675+ result = runner.invoke(cli, args, **invoke_options)676+677+ if expected in (MissingParameter, BadParameter):678+ assert isinstance(result.exception, expected)679+ assert not result.output680+ assert result.exit_code == 1681+682+ else:683+ expected_output = ""684+ if prompt is not None:685+ # Build the expected prompt.686+ assert isinstance(prompt, str)687+ expected_prompt = f"Flag {prompt}: " if prompt else "Flag: "688+689+ # Add the user input to the expected output.690+ assert isinstance(input, str)691+ expected_output += f"{expected_prompt}{input}\n"692+693+ if expected is INVALID:694+ expected_output += "Error: invalid input\n"695+696+ # The prompt is expected to be repeated.697+ if expected in (REPEAT, INVALID):698+ expected_output += expected_prompt699+700+ if expected not in (REPEAT, INVALID):701+ expected_output += f"{expected!r}\n"702+703+ assert result.output == expected_output704+ assert not result.stderr705+ assert result.exit_code == 0 if expected not in (REPEAT, INVALID) else 1modified:tests/test_testing.py+2 added-4 removed
446 unmodified lines447 runner = CliRunner()448 449 with runner.isolation() as (_, err, _):450 click.echo("\udce2", err=True, nl=False)451+ assert err.getvalue() == b"\\udce2"452 452- assert err.getvalue() == b"\\udce2"453 454-454 def test_isolation_flushes_unflushed_stderr():455 """An un-flushed write to stderr, as with `print(..., file=sys.stderr)`, will end up456 flushed by the runner at end of invocation.457 """458 runner = CliRunner()459 460 with runner.isolation() as (_, err, _):461 click.echo("\udce2", err=True, nl=False)462+ assert err.getvalue() == b"\\udce2"463 464- assert err.getvalue() == b"\\udce2"465-464 @click.command()465 def cli():466 # set end="", flush=False so that it's totally clear that we won't get any467 # auto-flush behaviors4 unmodified linesmodified:tests/test_utils.py+51 added
3 unmodified lines4 import subprocess5 import sys6 from collections import namedtuple7 from contextlib import nullcontext8+from decimal import Decimal9+from fractions import Fraction10 from functools import partial11 from io import StringIO12 from pathlib import Path13 from tempfile import tempdir3 unmodified lines17 18 import click._termui_impl19 import click.utils20 from click._compat import WIN21+from click._utils import UNSET22 23 24+def test_unset_sentinel():25+ value = UNSET26+27+ assert value28+ assert value is UNSET29+ assert value == UNSET30+ assert repr(value) == "Sentinel.UNSET"31+ assert str(value) == "Sentinel.UNSET"32+ assert bool(value) is True33+34+ # Try all native Python values that can be falsy or truthy.35+ # See: https://docs.python.org/3/library/stdtypes.html#truth-value-testing36+ real_values = (37+ None,38+ True,39+ False,40+ 0,41+ 1,42+ 0.0,43+ 1.0,44+ 0j,45+ 1j,46+ Decimal(0),47+ Decimal(1),48+ Fraction(0, 1),49+ Fraction(1, 1),50+ "",51+ "a",52+ "UNSET",53+ "Sentinel.UNSET",54+ [1],55+ (1),56+ {1: "a"},57+ set(),58+ set([1]),59+ frozenset(),60+ frozenset([1]),61+ range(0),62+ range(1),63+ )64+65+ for real_value in real_values:66+ assert value != real_value67+ assert value is not real_value68+69+ assert value not in real_values70+71+72 def test_echo(runner):73 with runner.isolation() as outstreams:74 click.echo("\N{SNOWMAN}")75 click.echo(b"\x44\x44")647 unmodified linesmodified:.pre-commit-config.yaml+2 added-2 removed
1 repos:2 - repo: https://github.com/astral-sh/ruff-pre-commit3- rev: 24e02b24b8ab2b7c76225602d13fa60e12d114e6 # frozen: v0.11.93+ rev: 9aeda5d1f4bbd212c557da1ea78eca9e8c829e19 # frozen: v0.11.134 hooks:5 - id: ruff6 - id: ruff-format7 - repo: https://github.com/astral-sh/uv-pre-commit8- rev: 14ac15b122e538e407d036ff45e3895b7cf4a2bf # frozen: 0.7.38+ rev: a621b109bab2e7e832d98c88fd3e83399f4e6657 # frozen: 0.7.129 hooks:10 - id: uv-lock11 - repo: https://github.com/pre-commit/pre-commit-hooks12 rev: cef0300fd0fc4d2a87a85fa2093c6b283ea36f4b # frozen: v5.0.06 unmodified linesmodified:.readthedocs.yaml+12 added-5 removed
1 version: 22+# Do not specify sphinx key here to be in full control of build steps.3+# https://docs.readthedocs.com/platform/stable/build-customization.html#extend-or-override-the-build-process4+5 build:6 os: ubuntu-24.047 tools:8 python: '3.13'6- commands:7- - asdf plugin add uv8- - asdf install uv latest9- - asdf global uv latest10- - uv run --group docs sphinx-build -W -b dirhtml docs $READTHEDOCS_OUTPUT/html9+ jobs:10+ install:11+ - echo "Installing dependencies"12+ - asdf plugin add uv13+ - asdf install uv latest14+ - asdf global uv latest15+ build:16+ html:17+ - uv run --group docs sphinx-build -W -b dirhtml docs $READTHEDOCS_OUTPUT/htmlmodified:CHANGES.rst+42 added-1 removed
1 .. currentmodule:: click2 3+Version 8.3.x4+--------------5+6+Unreleased7+8+- **Improved flag option handling**: Reworked the relationship between ``flag_value``9+ and ``default`` parameters for better consistency:10+11+ * The ``default`` parameter value is now preserved as-is and passed directly12+ to CLI functions (no more unexpected transformations)13+ * Exception: flag options with ``default=True`` maintain backward compatibility14+ by defaulting to their ``flag_value``15+ * The ``default`` parameter can now be any type (``bool``, ``None``, etc.)16+ * Fixes inconsistencies reported in: :issue:`1992` :issue:`2514` :issue:`2610`17+ :issue:`3024` :pr:`3030`18+- Allow ``default`` to be set on ``Argument`` for ``nargs = -1``. :issue:`2164`19+ :pr:`3030`20+- Show correct auto complete value for ``nargs`` option in combination with flag21+ option :issue:`2813`22+- Show correct auto complete value for nargs option in combination with flag option :issue:`2813`23+- Fix handling of quoted and escaped parameters in Fish autocompletion. :issue:`2995` :pr:`3013`24+- Lazily import ``shutil``. :pr:`3023`25+- Properly forward exception information to resources registered with26+ ``click.core.Context.with_resource()``. :issue:`2447` :pr:`3058`27+- Fix regression related to EOF handling in CliRunner. :issue:`2939`:pr:`2940`28+29 Version 8.2.230 -------------31 6-- Fix regression related to EOF handling in CliRunner. :issue:`2939`32+Released 2025-07-3133 34+- Fix reconciliation of ``default``, ``flag_value`` and ``type`` parameters for35+ flag options, as well as parsing and normalization of environment variables.36+ :issue:`2952` :pr:`2956`37+- Fix typing issue in ``BadParameter`` and ``MissingParameter`` exceptions for the38+ parameter ``param_hint`` that did not allow for a sequence of string where the39+ underlying function ``_join_param_hints`` allows for it. :issue:`2777` :pr:`2990`40+- Use the value of ``Enum`` choices to render their default value in help41+ screen. Refs :issue:`2911` :pr:`3004`42+- Fix completion for the Z shell (``zsh``) for completion items containing43+ colons. :issue:`2703` :pr:`2846`44+- Don't include envvar in error hint when not configured. :issue:`2971` :pr:`2972`45+- Fix a rare race in ``click.testing.StreamMixer``'s finalization that manifested46+ as a ``ValueError`` on close in a multi-threaded test session.47+ :issue:`2993` :pr:`2991`48+49 Version 8.2.150 -------------51 52 Released 2025-05-201241 unmodified linesmodified:pyproject.toml+1 added-6 removed
1 [project]2 name = "click"3-version = "8.2.1"3+version = "8.2.2"4 description = "Composable command line interface toolkit"5 readme = "README.md"6 license = "BSD-3-Clause"7 license-files = ["LICENSE.txt"]131 unmodified lines139 [tool.ruff.lint.isort]140 force-single-line = true141 order-by-type = false142 143-[tool.gha-update]144-tag-only = [145- "slsa-framework/slsa-github-generator",146-]147-143 [tool.tox]144 env_list = [145 "py3.13", "py3.12", "py3.11", "py3.10",146 "pypy3.11",62 unmodified linesmodified:README.md+3 added-1 removed
1-# $ click_1+<div align="center"><img src="https://raw.githubusercontent.com/pallets/click/refs/heads/stable/docs/_static/click-name.svg" alt="" height="150"></div>2 3+# Click4+5 Click is a Python package for creating beautiful command line interfaces6 in a composable way with as little code as necessary. It's the "Command7 Line Interface Creation Kit". It's highly configurable but comes with8 sensible defaults out of the box.54 unmodified linesmodified:uv.lock+101 added-90 removed
40 unmodified lines41 ]42 43 [[package]]44 name = "cachetools"45-version = "5.5.2"45+version = "6.0.0"46 source = { registry = "https://pypi.org/simple" }47-sdist = { url = "https://files.pythonhosted.org/packages/6c/81/3747dad6b14fa2cf53fcf10548cf5aea6913e96fab41a3c198676f8948a5/cachetools-5.5.2.tar.gz", hash = "sha256:1a661caa9175d26759571b2e19580f9d6393969e5dfca11fdb1f947a23e640d4", size = 28380, upload-time = "2025-02-20T21:01:19.524Z" }47+sdist = { url = "https://files.pythonhosted.org/packages/c0/b0/f539a1ddff36644c28a61490056e5bae43bd7386d9f9c69beae2d7e7d6d1/cachetools-6.0.0.tar.gz", hash = "sha256:f225782b84438f828328fc2ad74346522f27e5b1440f4e9fd18b20ebfd1aa2cf", size = 30160, upload-time = "2025-05-23T20:01:13.076Z" }48 wheels = [49- { url = "https://files.pythonhosted.org/packages/72/76/20fa66124dbe6be5cafeb312ece67de6b61dd91a0247d1ea13db4ebb33c2/cachetools-5.5.2-py3-none-any.whl", hash = "sha256:d26a22bcc62eb95c3beabd9f1ee5e820d3d2704fe2967cbe350e20c8ffcd3f0a", size = 10080, upload-time = "2025-02-20T21:01:16.647Z" },49+ { url = "https://files.pythonhosted.org/packages/6a/c3/8bb087c903c95a570015ce84e0c23ae1d79f528c349cbc141b5c4e250293/cachetools-6.0.0-py3-none-any.whl", hash = "sha256:82e73ba88f7b30228b5507dce1a1f878498fc669d972aef2dde4f3a3c24f103e", size = 10964, upload-time = "2025-05-23T20:01:11.323Z" },50 ]51 52 [[package]]53 name = "certifi"84 unmodified lines138 ]139 140 [[package]]141 name = "click"142-version = "8.2.1"142+version = "8.2.2"143 source = { editable = "." }144 dependencies = [145 { name = "colorama", marker = "sys_platform == 'win32'" },146 ]159 unmodified lines306 ]307 308 [[package]]309 name = "identify"310-version = "2.6.10"310+version = "2.6.12"311 source = { registry = "https://pypi.org/simple" }312-sdist = { url = "https://files.pythonhosted.org/packages/0c/83/b6ea0334e2e7327084a46aaaf71f2146fc061a192d6518c0d020120cd0aa/identify-2.6.10.tar.gz", hash = "sha256:45e92fd704f3da71cc3880036633f48b4b7265fd4de2b57627cb157216eb7eb8", size = 99201, upload-time = "2025-04-19T15:10:38.32Z" }312+sdist = { url = "https://files.pythonhosted.org/packages/a2/88/d193a27416618628a5eea64e3223acd800b40749a96ffb322a9b55a49ed1/identify-2.6.12.tar.gz", hash = "sha256:d8de45749f1efb108badef65ee8386f0f7bb19a7f26185f74de6367bffbaf0e6", size = 99254, upload-time = "2025-05-23T20:37:53.3Z" }313 wheels = [314- { url = "https://files.pythonhosted.org/packages/2b/d3/85feeba1d097b81a44bcffa6a0beab7b4dfffe78e82fc54978d3ac380736/identify-2.6.10-py2.py3-none-any.whl", hash = "sha256:5f34248f54136beed1a7ba6a6b5c4b6cf21ff495aac7c359e1ef831ae3b8ab25", size = 99101, upload-time = "2025-04-19T15:10:36.701Z" },314+ { url = "https://files.pythonhosted.org/packages/7a/cd/18f8da995b658420625f7ef13f037be53ae04ec5ad33f9b718240dcfd48c/identify-2.6.12-py2.py3-none-any.whl", hash = "sha256:ad9672d5a72e0d2ff7c5c8809b62dfa60458626352fb0eb7b55e69bdc45334a2", size = 99145, upload-time = "2025-05-23T20:37:51.495Z" },315 ]316 317 [[package]]318 name = "idna"126 unmodified lines445 ]446 447 [[package]]448 name = "mypy"449-version = "1.15.0"449+version = "1.16.0"450 source = { registry = "https://pypi.org/simple" }451 dependencies = [452 { name = "mypy-extensions" },453+ { name = "pathspec" },454 { name = "tomli", marker = "python_full_version < '3.11'" },455 { name = "typing-extensions" },456 ]456-sdist = { url = "https://files.pythonhosted.org/packages/ce/43/d5e49a86afa64bd3839ea0d5b9c7103487007d728e1293f52525d6d5486a/mypy-1.15.0.tar.gz", hash = "sha256:404534629d51d3efea5c800ee7c42b72a6554d6c400e6a79eafe15d11341fd43", size = 3239717, upload-time = "2025-02-05T03:50:34.655Z" }457+sdist = { url = "https://files.pythonhosted.org/packages/d4/38/13c2f1abae94d5ea0354e146b95a1be9b2137a0d506728e0da037c4276f6/mypy-1.16.0.tar.gz", hash = "sha256:84b94283f817e2aa6350a14b4a8fb2a35a53c286f97c9d30f53b63620e7af8ab", size = 3323139, upload-time = "2025-05-29T13:46:12.532Z" }458 wheels = [458- { url = "https://files.pythonhosted.org/packages/68/f8/65a7ce8d0e09b6329ad0c8d40330d100ea343bd4dd04c4f8ae26462d0a17/mypy-1.15.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:979e4e1a006511dacf628e36fadfecbcc0160a8af6ca7dad2f5025529e082c13", size = 10738433, upload-time = "2025-02-05T03:49:29.145Z" },459- { url = "https://files.pythonhosted.org/packages/b4/95/9c0ecb8eacfe048583706249439ff52105b3f552ea9c4024166c03224270/mypy-1.15.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:c4bb0e1bd29f7d34efcccd71cf733580191e9a264a2202b0239da95984c5b559", size = 9861472, upload-time = "2025-02-05T03:49:16.986Z" },460- { url = "https://files.pythonhosted.org/packages/84/09/9ec95e982e282e20c0d5407bc65031dfd0f0f8ecc66b69538296e06fcbee/mypy-1.15.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:be68172e9fd9ad8fb876c6389f16d1c1b5f100ffa779f77b1fb2176fcc9ab95b", size = 11611424, upload-time = "2025-02-05T03:49:46.908Z" },461- { url = "https://files.pythonhosted.org/packages/78/13/f7d14e55865036a1e6a0a69580c240f43bc1f37407fe9235c0d4ef25ffb0/mypy-1.15.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c7be1e46525adfa0d97681432ee9fcd61a3964c2446795714699a998d193f1a3", size = 12365450, upload-time = "2025-02-05T03:50:05.89Z" },462- { url = "https://files.pythonhosted.org/packages/48/e1/301a73852d40c241e915ac6d7bcd7fedd47d519246db2d7b86b9d7e7a0cb/mypy-1.15.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:2e2c2e6d3593f6451b18588848e66260ff62ccca522dd231cd4dd59b0160668b", size = 12551765, upload-time = "2025-02-05T03:49:33.56Z" },463- { url = "https://files.pythonhosted.org/packages/77/ba/c37bc323ae5fe7f3f15a28e06ab012cd0b7552886118943e90b15af31195/mypy-1.15.0-cp310-cp310-win_amd64.whl", hash = "sha256:6983aae8b2f653e098edb77f893f7b6aca69f6cffb19b2cc7443f23cce5f4828", size = 9274701, upload-time = "2025-02-05T03:49:38.981Z" },464- { url = "https://files.pythonhosted.org/packages/03/bc/f6339726c627bd7ca1ce0fa56c9ae2d0144604a319e0e339bdadafbbb599/mypy-1.15.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:2922d42e16d6de288022e5ca321cd0618b238cfc5570e0263e5ba0a77dbef56f", size = 10662338, upload-time = "2025-02-05T03:50:17.287Z" },465- { url = "https://files.pythonhosted.org/packages/e2/90/8dcf506ca1a09b0d17555cc00cd69aee402c203911410136cd716559efe7/mypy-1.15.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:2ee2d57e01a7c35de00f4634ba1bbf015185b219e4dc5909e281016df43f5ee5", size = 9787540, upload-time = "2025-02-05T03:49:51.21Z" },466- { url = "https://files.pythonhosted.org/packages/05/05/a10f9479681e5da09ef2f9426f650d7b550d4bafbef683b69aad1ba87457/mypy-1.15.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:973500e0774b85d9689715feeffcc980193086551110fd678ebe1f4342fb7c5e", size = 11538051, upload-time = "2025-02-05T03:50:20.885Z" },467- { url = "https://files.pythonhosted.org/packages/e9/9a/1f7d18b30edd57441a6411fcbc0c6869448d1a4bacbaee60656ac0fc29c8/mypy-1.15.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5a95fb17c13e29d2d5195869262f8125dfdb5c134dc8d9a9d0aecf7525b10c2c", size = 12286751, upload-time = "2025-02-05T03:49:42.408Z" },468- { url = "https://files.pythonhosted.org/packages/72/af/19ff499b6f1dafcaf56f9881f7a965ac2f474f69f6f618b5175b044299f5/mypy-1.15.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:1905f494bfd7d85a23a88c5d97840888a7bd516545fc5aaedff0267e0bb54e2f", size = 12421783, upload-time = "2025-02-05T03:49:07.707Z" },469- { url = "https://files.pythonhosted.org/packages/96/39/11b57431a1f686c1aed54bf794870efe0f6aeca11aca281a0bd87a5ad42c/mypy-1.15.0-cp311-cp311-win_amd64.whl", hash = "sha256:c9817fa23833ff189db061e6d2eff49b2f3b6ed9856b4a0a73046e41932d744f", size = 9265618, upload-time = "2025-02-05T03:49:54.581Z" },470- { url = "https://files.pythonhosted.org/packages/98/3a/03c74331c5eb8bd025734e04c9840532226775c47a2c39b56a0c8d4f128d/mypy-1.15.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:aea39e0583d05124836ea645f412e88a5c7d0fd77a6d694b60d9b6b2d9f184fd", size = 10793981, upload-time = "2025-02-05T03:50:28.25Z" },471- { url = "https://files.pythonhosted.org/packages/f0/1a/41759b18f2cfd568848a37c89030aeb03534411eef981df621d8fad08a1d/mypy-1.15.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:2f2147ab812b75e5b5499b01ade1f4a81489a147c01585cda36019102538615f", size = 9749175, upload-time = "2025-02-05T03:50:13.411Z" },472- { url = "https://files.pythonhosted.org/packages/12/7e/873481abf1ef112c582db832740f4c11b2bfa510e829d6da29b0ab8c3f9c/mypy-1.15.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ce436f4c6d218a070048ed6a44c0bbb10cd2cc5e272b29e7845f6a2f57ee4464", size = 11455675, upload-time = "2025-02-05T03:50:31.421Z" },473- { url = "https://files.pythonhosted.org/packages/b3/d0/92ae4cde706923a2d3f2d6c39629134063ff64b9dedca9c1388363da072d/mypy-1.15.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8023ff13985661b50a5928fc7a5ca15f3d1affb41e5f0a9952cb68ef090b31ee", size = 12410020, upload-time = "2025-02-05T03:48:48.705Z" },474- { url = "https://files.pythonhosted.org/packages/46/8b/df49974b337cce35f828ba6fda228152d6db45fed4c86ba56ffe442434fd/mypy-1.15.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:1124a18bc11a6a62887e3e137f37f53fbae476dc36c185d549d4f837a2a6a14e", size = 12498582, upload-time = "2025-02-05T03:49:03.628Z" },475- { url = "https://files.pythonhosted.org/packages/13/50/da5203fcf6c53044a0b699939f31075c45ae8a4cadf538a9069b165c1050/mypy-1.15.0-cp312-cp312-win_amd64.whl", hash = "sha256:171a9ca9a40cd1843abeca0e405bc1940cd9b305eaeea2dda769ba096932bb22", size = 9366614, upload-time = "2025-02-05T03:50:00.313Z" },476- { url = "https://files.pythonhosted.org/packages/6a/9b/fd2e05d6ffff24d912f150b87db9e364fa8282045c875654ce7e32fffa66/mypy-1.15.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:93faf3fdb04768d44bf28693293f3904bbb555d076b781ad2530214ee53e3445", size = 10788592, upload-time = "2025-02-05T03:48:55.789Z" },477- { url = "https://files.pythonhosted.org/packages/74/37/b246d711c28a03ead1fd906bbc7106659aed7c089d55fe40dd58db812628/mypy-1.15.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:811aeccadfb730024c5d3e326b2fbe9249bb7413553f15499a4050f7c30e801d", size = 9753611, upload-time = "2025-02-05T03:48:44.581Z" },478- { url = "https://files.pythonhosted.org/packages/a6/ac/395808a92e10cfdac8003c3de9a2ab6dc7cde6c0d2a4df3df1b815ffd067/mypy-1.15.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:98b7b9b9aedb65fe628c62a6dc57f6d5088ef2dfca37903a7d9ee374d03acca5", size = 11438443, upload-time = "2025-02-05T03:49:25.514Z" },479- { url = "https://files.pythonhosted.org/packages/d2/8b/801aa06445d2de3895f59e476f38f3f8d610ef5d6908245f07d002676cbf/mypy-1.15.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c43a7682e24b4f576d93072216bf56eeff70d9140241f9edec0c104d0c515036", size = 12402541, upload-time = "2025-02-05T03:49:57.623Z" },480- { url = "https://files.pythonhosted.org/packages/c7/67/5a4268782eb77344cc613a4cf23540928e41f018a9a1ec4c6882baf20ab8/mypy-1.15.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:baefc32840a9f00babd83251560e0ae1573e2f9d1b067719479bfb0e987c6357", size = 12494348, upload-time = "2025-02-05T03:48:52.361Z" },481- { url = "https://files.pythonhosted.org/packages/83/3e/57bb447f7bbbfaabf1712d96f9df142624a386d98fb026a761532526057e/mypy-1.15.0-cp313-cp313-win_amd64.whl", hash = "sha256:b9378e2c00146c44793c98b8d5a61039a048e31f429fb0eb546d93f4b000bedf", size = 9373648, upload-time = "2025-02-05T03:49:11.395Z" },482- { url = "https://files.pythonhosted.org/packages/09/4e/a7d65c7322c510de2c409ff3828b03354a7c43f5a8ed458a7a131b41c7b9/mypy-1.15.0-py3-none-any.whl", hash = "sha256:5469affef548bd1895d86d3bf10ce2b44e33d86923c29e4d675b3e323437ea3e", size = 2221777, upload-time = "2025-02-05T03:50:08.348Z" },459+ { url = "https://files.pythonhosted.org/packages/64/5e/a0485f0608a3d67029d3d73cec209278b025e3493a3acfda3ef3a88540fd/mypy-1.16.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:7909541fef256527e5ee9c0a7e2aeed78b6cda72ba44298d1334fe7881b05c5c", size = 10967416, upload-time = "2025-05-29T13:34:17.783Z" },460+ { url = "https://files.pythonhosted.org/packages/4b/53/5837c221f74c0d53a4bfc3003296f8179c3a2a7f336d7de7bbafbe96b688/mypy-1.16.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:e71d6f0090c2256c713ed3d52711d01859c82608b5d68d4fa01a3fe30df95571", size = 10087654, upload-time = "2025-05-29T13:32:37.878Z" },461+ { url = "https://files.pythonhosted.org/packages/29/59/5fd2400352c3093bed4c09017fe671d26bc5bb7e6ef2d4bf85f2a2488104/mypy-1.16.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:936ccfdd749af4766be824268bfe22d1db9eb2f34a3ea1d00ffbe5b5265f5491", size = 11875192, upload-time = "2025-05-29T13:34:54.281Z" },462+ { url = "https://files.pythonhosted.org/packages/ad/3e/4bfec74663a64c2012f3e278dbc29ffe82b121bc551758590d1b6449ec0c/mypy-1.16.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4086883a73166631307fdd330c4a9080ce24913d4f4c5ec596c601b3a4bdd777", size = 12612939, upload-time = "2025-05-29T13:33:14.766Z" },463+ { url = "https://files.pythonhosted.org/packages/88/1f/fecbe3dcba4bf2ca34c26ca016383a9676711907f8db4da8354925cbb08f/mypy-1.16.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:feec38097f71797da0231997e0de3a58108c51845399669ebc532c815f93866b", size = 12874719, upload-time = "2025-05-29T13:21:52.09Z" },464+ { url = "https://files.pythonhosted.org/packages/f3/51/c2d280601cd816c43dfa512a759270d5a5ef638d7ac9bea9134c8305a12f/mypy-1.16.0-cp310-cp310-win_amd64.whl", hash = "sha256:09a8da6a0ee9a9770b8ff61b39c0bb07971cda90e7297f4213741b48a0cc8d93", size = 9487053, upload-time = "2025-05-29T13:33:29.797Z" },465+ { url = "https://files.pythonhosted.org/packages/24/c4/ff2f79db7075c274fe85b5fff8797d29c6b61b8854c39e3b7feb556aa377/mypy-1.16.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:9f826aaa7ff8443bac6a494cf743f591488ea940dd360e7dd330e30dd772a5ab", size = 10884498, upload-time = "2025-05-29T13:18:54.066Z" },466+ { url = "https://files.pythonhosted.org/packages/02/07/12198e83006235f10f6a7808917376b5d6240a2fd5dce740fe5d2ebf3247/mypy-1.16.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:82d056e6faa508501af333a6af192c700b33e15865bda49611e3d7d8358ebea2", size = 10011755, upload-time = "2025-05-29T13:34:00.851Z" },467+ { url = "https://files.pythonhosted.org/packages/f1/9b/5fd5801a72b5d6fb6ec0105ea1d0e01ab2d4971893076e558d4b6d6b5f80/mypy-1.16.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:089bedc02307c2548eb51f426e085546db1fa7dd87fbb7c9fa561575cf6eb1ff", size = 11800138, upload-time = "2025-05-29T13:32:55.082Z" },468+ { url = "https://files.pythonhosted.org/packages/2e/81/a117441ea5dfc3746431e51d78a4aca569c677aa225bca2cc05a7c239b61/mypy-1.16.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6a2322896003ba66bbd1318c10d3afdfe24e78ef12ea10e2acd985e9d684a666", size = 12533156, upload-time = "2025-05-29T13:19:12.963Z" },469+ { url = "https://files.pythonhosted.org/packages/3f/38/88ec57c6c86014d3f06251e00f397b5a7daa6888884d0abf187e4f5f587f/mypy-1.16.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:021a68568082c5b36e977d54e8f1de978baf401a33884ffcea09bd8e88a98f4c", size = 12742426, upload-time = "2025-05-29T13:20:22.72Z" },470+ { url = "https://files.pythonhosted.org/packages/bd/53/7e9d528433d56e6f6f77ccf24af6ce570986c2d98a5839e4c2009ef47283/mypy-1.16.0-cp311-cp311-win_amd64.whl", hash = "sha256:54066fed302d83bf5128632d05b4ec68412e1f03ef2c300434057d66866cea4b", size = 9478319, upload-time = "2025-05-29T13:21:17.582Z" },471+ { url = "https://files.pythonhosted.org/packages/70/cf/158e5055e60ca2be23aec54a3010f89dcffd788732634b344fc9cb1e85a0/mypy-1.16.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c5436d11e89a3ad16ce8afe752f0f373ae9620841c50883dc96f8b8805620b13", size = 11062927, upload-time = "2025-05-29T13:35:52.328Z" },472+ { url = "https://files.pythonhosted.org/packages/94/34/cfff7a56be1609f5d10ef386342ce3494158e4d506516890142007e6472c/mypy-1.16.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f2622af30bf01d8fc36466231bdd203d120d7a599a6d88fb22bdcb9dbff84090", size = 10083082, upload-time = "2025-05-29T13:35:33.378Z" },473+ { url = "https://files.pythonhosted.org/packages/b3/7f/7242062ec6288c33d8ad89574df87c3903d394870e5e6ba1699317a65075/mypy-1.16.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d045d33c284e10a038f5e29faca055b90eee87da3fc63b8889085744ebabb5a1", size = 11828306, upload-time = "2025-05-29T13:21:02.164Z" },474+ { url = "https://files.pythonhosted.org/packages/6f/5f/b392f7b4f659f5b619ce5994c5c43caab3d80df2296ae54fa888b3d17f5a/mypy-1.16.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b4968f14f44c62e2ec4a038c8797a87315be8df7740dc3ee8d3bfe1c6bf5dba8", size = 12702764, upload-time = "2025-05-29T13:20:42.826Z" },475+ { url = "https://files.pythonhosted.org/packages/9b/c0/7646ef3a00fa39ac9bc0938626d9ff29d19d733011be929cfea59d82d136/mypy-1.16.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:eb14a4a871bb8efb1e4a50360d4e3c8d6c601e7a31028a2c79f9bb659b63d730", size = 12896233, upload-time = "2025-05-29T13:18:37.446Z" },476+ { url = "https://files.pythonhosted.org/packages/6d/38/52f4b808b3fef7f0ef840ee8ff6ce5b5d77381e65425758d515cdd4f5bb5/mypy-1.16.0-cp312-cp312-win_amd64.whl", hash = "sha256:bd4e1ebe126152a7bbaa4daedd781c90c8f9643c79b9748caa270ad542f12bec", size = 9565547, upload-time = "2025-05-29T13:20:02.836Z" },477+ { url = "https://files.pythonhosted.org/packages/97/9c/ca03bdbefbaa03b264b9318a98950a9c683e06472226b55472f96ebbc53d/mypy-1.16.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:a9e056237c89f1587a3be1a3a70a06a698d25e2479b9a2f57325ddaaffc3567b", size = 11059753, upload-time = "2025-05-29T13:18:18.167Z" },478+ { url = "https://files.pythonhosted.org/packages/36/92/79a969b8302cfe316027c88f7dc6fee70129490a370b3f6eb11d777749d0/mypy-1.16.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:0b07e107affb9ee6ce1f342c07f51552d126c32cd62955f59a7db94a51ad12c0", size = 10073338, upload-time = "2025-05-29T13:19:48.079Z" },479+ { url = "https://files.pythonhosted.org/packages/14/9b/a943f09319167da0552d5cd722104096a9c99270719b1afeea60d11610aa/mypy-1.16.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c6fb60cbd85dc65d4d63d37cb5c86f4e3a301ec605f606ae3a9173e5cf34997b", size = 11827764, upload-time = "2025-05-29T13:46:04.47Z" },480+ { url = "https://files.pythonhosted.org/packages/ec/64/ff75e71c65a0cb6ee737287c7913ea155845a556c64144c65b811afdb9c7/mypy-1.16.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a7e32297a437cc915599e0578fa6bc68ae6a8dc059c9e009c628e1c47f91495d", size = 12701356, upload-time = "2025-05-29T13:35:13.553Z" },481+ { url = "https://files.pythonhosted.org/packages/0a/ad/0e93c18987a1182c350f7a5fab70550852f9fabe30ecb63bfbe51b602074/mypy-1.16.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:afe420c9380ccec31e744e8baff0d406c846683681025db3531b32db56962d52", size = 12900745, upload-time = "2025-05-29T13:17:24.409Z" },482+ { url = "https://files.pythonhosted.org/packages/28/5d/036c278d7a013e97e33f08c047fe5583ab4f1fc47c9a49f985f1cdd2a2d7/mypy-1.16.0-cp313-cp313-win_amd64.whl", hash = "sha256:55f9076c6ce55dd3f8cd0c6fff26a008ca8e5131b89d5ba6d86bd3f47e736eeb", size = 9572200, upload-time = "2025-05-29T13:33:44.92Z" },483+ { url = "https://files.pythonhosted.org/packages/99/a3/6ed10530dec8e0fdc890d81361260c9ef1f5e5c217ad8c9b21ecb2b8366b/mypy-1.16.0-py3-none-any.whl", hash = "sha256:29e1499864a3888bca5c1542f2d7232c6e586295183320caa95758fc84034031", size = 2265773, upload-time = "2025-05-29T13:35:18.762Z" },484 ]485 486 [[package]]487 name = "mypy-extensions"55 unmodified lines543 { url = "https://files.pythonhosted.org/packages/ff/7d/a4aa06e452e031559dcfb066e035d2615ebfa6148e93514d7c36030004c1/pallets_sphinx_themes-2.3.0-py3-none-any.whl", hash = "sha256:7ed13de3743c462c2804e2aa63d96cc9ffa82cb76d0251cea03de9bcd9f8dbec", size = 24745, upload-time = "2024-10-24T18:52:37.265Z" },544 ]545 546 [[package]]547+name = "pathspec"548+version = "0.12.1"549+source = { registry = "https://pypi.org/simple" }550+sdist = { url = "https://files.pythonhosted.org/packages/ca/bc/f35b8446f4531a7cb215605d100cd88b7ac6f44ab3fc94870c120ab3adbf/pathspec-0.12.1.tar.gz", hash = "sha256:a482d51503a1ab33b1c67a6c3813a26953dbdc71c31dacaef9a838c4e29f5712", size = 51043, upload-time = "2023-12-10T22:30:45Z" }551+wheels = [552+ { url = "https://files.pythonhosted.org/packages/cc/20/ff623b09d963f88bfde16306a54e12ee5ea43e9b597108672ff3a408aad6/pathspec-0.12.1-py3-none-any.whl", hash = "sha256:a0d503e138a4c123b27490a4f7beda6a01c6f288df0e4a8b79c7eb0dc7b4cc08", size = 31191, upload-time = "2023-12-10T22:30:43.14Z" },553+]554+555+[[package]]556 name = "platformdirs"557 version = "4.3.8"558 source = { registry = "https://pypi.org/simple" }559 sdist = { url = "https://files.pythonhosted.org/packages/fe/8b/3c73abc9c759ecd3f1f7ceff6685840859e8070c4d947c93fae71f6a0bf2/platformdirs-4.3.8.tar.gz", hash = "sha256:3d512d96e16bcb959a814c9f348431070822a6496326a4be0911c40b5a74c2bc", size = 21362, upload-time = "2025-05-07T22:47:42.121Z" }62 unmodified lines622 ]623 624 [[package]]625 name = "pyright"616-version = "1.1.400"626+version = "1.1.401"627 source = { registry = "https://pypi.org/simple" }628 dependencies = [629 { name = "nodeenv" },630 { name = "typing-extensions" },631 ]622-sdist = { url = "https://files.pythonhosted.org/packages/6c/cb/c306618a02d0ee8aed5fb8d0fe0ecfed0dbf075f71468f03a30b5f4e1fe0/pyright-1.1.400.tar.gz", hash = "sha256:b8a3ba40481aa47ba08ffb3228e821d22f7d391f83609211335858bf05686bdb", size = 3846546, upload-time = "2025-04-24T12:55:18.907Z" }632+sdist = { url = "https://files.pythonhosted.org/packages/79/9a/7ab2b333b921b2d6bfcffe05a0e0a0bbeff884bd6fb5ed50cd68e2898e53/pyright-1.1.401.tar.gz", hash = "sha256:788a82b6611fa5e34a326a921d86d898768cddf59edde8e93e56087d277cc6f1", size = 3894193, upload-time = "2025-05-21T10:44:52.03Z" }633 wheels = [624- { url = "https://files.pythonhosted.org/packages/c8/a5/5d285e4932cf149c90e3c425610c5efaea005475d5f96f1bfdb452956c62/pyright-1.1.400-py3-none-any.whl", hash = "sha256:c80d04f98b5a4358ad3a35e241dbf2a408eee33a40779df365644f8054d2517e", size = 5563460, upload-time = "2025-04-24T12:55:17.002Z" },634+ { url = "https://files.pythonhosted.org/packages/0d/e6/1f908fce68b0401d41580e0f9acc4c3d1b248adcff00dfaad75cd21a1370/pyright-1.1.401-py3-none-any.whl", hash = "sha256:6fde30492ba5b0d7667c16ecaf6c699fab8d7a1263f6a18549e0b00bf7724c06", size = 5629193, upload-time = "2025-05-21T10:44:50.129Z" },635 ]636 637 [[package]]638 name = "pytest"629-version = "8.3.5"639+version = "8.4.0"640 source = { registry = "https://pypi.org/simple" }641 dependencies = [642 { name = "colorama", marker = "sys_platform == 'win32'" },643 { name = "exceptiongroup", marker = "python_full_version < '3.11'" },644 { name = "iniconfig" },645 { name = "packaging" },646 { name = "pluggy" },647+ { name = "pygments" },648 { name = "tomli", marker = "python_full_version < '3.11'" },649 ]639-sdist = { url = "https://files.pythonhosted.org/packages/ae/3c/c9d525a414d506893f0cd8a8d0de7706446213181570cdbd766691164e40/pytest-8.3.5.tar.gz", hash = "sha256:f4efe70cc14e511565ac476b57c279e12a855b11f48f212af1080ef2263d3845", size = 1450891, upload-time = "2025-03-02T12:54:54.503Z" }650+sdist = { url = "https://files.pythonhosted.org/packages/fb/aa/405082ce2749be5398045152251ac69c0f3578c7077efc53431303af97ce/pytest-8.4.0.tar.gz", hash = "sha256:14d920b48472ea0dbf68e45b96cd1ffda4705f33307dcc86c676c1b5104838a6", size = 1515232, upload-time = "2025-06-02T17:36:30.03Z" }651 wheels = [641- { url = "https://files.pythonhosted.org/packages/30/3d/64ad57c803f1fa1e963a7946b6e0fea4a70df53c1a7fed304586539c2bac/pytest-8.3.5-py3-none-any.whl", hash = "sha256:c69214aa47deac29fad6c2a4f590b9c4a9fdb16a403176fe154b79c0b4d4d820", size = 343634, upload-time = "2025-03-02T12:54:52.069Z" },652+ { url = "https://files.pythonhosted.org/packages/2f/de/afa024cbe022b1b318a3d224125aa24939e99b4ff6f22e0ba639a2eaee47/pytest-8.4.0-py3-none-any.whl", hash = "sha256:f40f825768ad76c0977cbacdf1fd37c6f7a468e460ea6a0636078f8972d4517e", size = 363797, upload-time = "2025-06-02T17:36:27.859Z" },653 ]654 655 [[package]]656 name = "pyyaml"64 unmodified lines721 ]722 723 [[package]]724 name = "ruff"714-version = "0.11.10"725+version = "0.11.13"726 source = { registry = "https://pypi.org/simple" }716-sdist = { url = "https://files.pythonhosted.org/packages/e8/4c/4a3c5a97faaae6b428b336dcca81d03ad04779f8072c267ad2bd860126bf/ruff-0.11.10.tar.gz", hash = "sha256:d522fb204b4959909ecac47da02830daec102eeb100fb50ea9554818d47a5fa6", size = 4165632, upload-time = "2025-05-15T14:08:56.76Z" }727+sdist = { url = "https://files.pythonhosted.org/packages/ed/da/9c6f995903b4d9474b39da91d2d626659af3ff1eeb43e9ae7c119349dba6/ruff-0.11.13.tar.gz", hash = "sha256:26fa247dc68d1d4e72c179e08889a25ac0c7ba4d78aecfc835d49cbfd60bf514", size = 4282054, upload-time = "2025-06-05T21:00:15.721Z" }728 wheels = [718- { url = "https://files.pythonhosted.org/packages/2f/9f/596c628f8824a2ce4cd12b0f0b4c0629a62dfffc5d0f742c19a1d71be108/ruff-0.11.10-py3-none-linux_armv6l.whl", hash = "sha256:859a7bfa7bc8888abbea31ef8a2b411714e6a80f0d173c2a82f9041ed6b50f58", size = 10316243, upload-time = "2025-05-15T14:08:12.884Z" },719- { url = "https://files.pythonhosted.org/packages/3c/38/c1e0b77ab58b426f8c332c1d1d3432d9fc9a9ea622806e208220cb133c9e/ruff-0.11.10-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:968220a57e09ea5e4fd48ed1c646419961a0570727c7e069842edd018ee8afed", size = 11083636, upload-time = "2025-05-15T14:08:16.551Z" },720- { url = "https://files.pythonhosted.org/packages/23/41/b75e15961d6047d7fe1b13886e56e8413be8467a4e1be0a07f3b303cd65a/ruff-0.11.10-py3-none-macosx_11_0_arm64.whl", hash = "sha256:1067245bad978e7aa7b22f67113ecc6eb241dca0d9b696144256c3a879663bca", size = 10441624, upload-time = "2025-05-15T14:08:19.032Z" },721- { url = "https://files.pythonhosted.org/packages/b6/2c/e396b6703f131406db1811ea3d746f29d91b41bbd43ad572fea30da1435d/ruff-0.11.10-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f4854fd09c7aed5b1590e996a81aeff0c9ff51378b084eb5a0b9cd9518e6cff2", size = 10624358, upload-time = "2025-05-15T14:08:21.542Z" },722- { url = "https://files.pythonhosted.org/packages/bd/8c/ee6cca8bdaf0f9a3704796022851a33cd37d1340bceaf4f6e991eb164e2e/ruff-0.11.10-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:8b4564e9f99168c0f9195a0fd5fa5928004b33b377137f978055e40008a082c5", size = 10176850, upload-time = "2025-05-15T14:08:23.682Z" },723- { url = "https://files.pythonhosted.org/packages/e9/ce/4e27e131a434321b3b7c66512c3ee7505b446eb1c8a80777c023f7e876e6/ruff-0.11.10-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:5b6a9cc5b62c03cc1fea0044ed8576379dbaf751d5503d718c973d5418483641", size = 11759787, upload-time = "2025-05-15T14:08:25.733Z" },724- { url = "https://files.pythonhosted.org/packages/58/de/1e2e77fc72adc7cf5b5123fd04a59ed329651d3eab9825674a9e640b100b/ruff-0.11.10-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:607ecbb6f03e44c9e0a93aedacb17b4eb4f3563d00e8b474298a201622677947", size = 12430479, upload-time = "2025-05-15T14:08:28.013Z" },725- { url = "https://files.pythonhosted.org/packages/07/ed/af0f2340f33b70d50121628ef175523cc4c37619e98d98748c85764c8d88/ruff-0.11.10-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7b3a522fa389402cd2137df9ddefe848f727250535c70dafa840badffb56b7a4", size = 11919760, upload-time = "2025-05-15T14:08:30.956Z" },726- { url = "https://files.pythonhosted.org/packages/24/09/d7b3d3226d535cb89234390f418d10e00a157b6c4a06dfbe723e9322cb7d/ruff-0.11.10-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:2f071b0deed7e9245d5820dac235cbdd4ef99d7b12ff04c330a241ad3534319f", size = 14041747, upload-time = "2025-05-15T14:08:33.297Z" },727- { url = "https://files.pythonhosted.org/packages/62/b3/a63b4e91850e3f47f78795e6630ee9266cb6963de8f0191600289c2bb8f4/ruff-0.11.10-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4a60e3a0a617eafba1f2e4186d827759d65348fa53708ca547e384db28406a0b", size = 11550657, upload-time = "2025-05-15T14:08:35.639Z" },728- { url = "https://files.pythonhosted.org/packages/46/63/a4f95c241d79402ccdbdb1d823d156c89fbb36ebfc4289dce092e6c0aa8f/ruff-0.11.10-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:da8ec977eaa4b7bf75470fb575bea2cb41a0e07c7ea9d5a0a97d13dbca697bf2", size = 10489671, upload-time = "2025-05-15T14:08:38.437Z" },729- { url = "https://files.pythonhosted.org/packages/6a/9b/c2238bfebf1e473495659c523d50b1685258b6345d5ab0b418ca3f010cd7/ruff-0.11.10-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:ddf8967e08227d1bd95cc0851ef80d2ad9c7c0c5aab1eba31db49cf0a7b99523", size = 10160135, upload-time = "2025-05-15T14:08:41.247Z" },730- { url = "https://files.pythonhosted.org/packages/ba/ef/ba7251dd15206688dbfba7d413c0312e94df3b31b08f5d695580b755a899/ruff-0.11.10-py3-none-musllinux_1_2_i686.whl", hash = "sha256:5a94acf798a82db188f6f36575d80609072b032105d114b0f98661e1679c9125", size = 11170179, upload-time = "2025-05-15T14:08:43.762Z" },731- { url = "https://files.pythonhosted.org/packages/73/9f/5c336717293203ba275dbfa2ea16e49b29a9fd9a0ea8b6febfc17e133577/ruff-0.11.10-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:3afead355f1d16d95630df28d4ba17fb2cb9c8dfac8d21ced14984121f639bad", size = 11626021, upload-time = "2025-05-15T14:08:46.451Z" },732- { url = "https://files.pythonhosted.org/packages/d9/2b/162fa86d2639076667c9aa59196c020dc6d7023ac8f342416c2f5ec4bda0/ruff-0.11.10-py3-none-win32.whl", hash = "sha256:dc061a98d32a97211af7e7f3fa1d4ca2fcf919fb96c28f39551f35fc55bdbc19", size = 10494958, upload-time = "2025-05-15T14:08:49.601Z" },733- { url = "https://files.pythonhosted.org/packages/24/f3/66643d8f32f50a4b0d09a4832b7d919145ee2b944d43e604fbd7c144d175/ruff-0.11.10-py3-none-win_amd64.whl", hash = "sha256:5cc725fbb4d25b0f185cb42df07ab6b76c4489b4bfb740a175f3a59c70e8a224", size = 11650285, upload-time = "2025-05-15T14:08:52.392Z" },734- { url = "https://files.pythonhosted.org/packages/95/3a/2e8704d19f376c799748ff9cb041225c1d59f3e7711bc5596c8cfdc24925/ruff-0.11.10-py3-none-win_arm64.whl", hash = "sha256:ef69637b35fb8b210743926778d0e45e1bffa850a7c61e428c6b971549b5f5d1", size = 10765278, upload-time = "2025-05-15T14:08:54.56Z" },729+ { url = "https://files.pythonhosted.org/packages/7d/ce/a11d381192966e0b4290842cc8d4fac7dc9214ddf627c11c1afff87da29b/ruff-0.11.13-py3-none-linux_armv6l.whl", hash = "sha256:4bdfbf1240533f40042ec00c9e09a3aade6f8c10b6414cf11b519488d2635d46", size = 10292516, upload-time = "2025-06-05T20:59:32.944Z" },730+ { url = "https://files.pythonhosted.org/packages/78/db/87c3b59b0d4e753e40b6a3b4a2642dfd1dcaefbff121ddc64d6c8b47ba00/ruff-0.11.13-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:aef9c9ed1b5ca28bb15c7eac83b8670cf3b20b478195bd49c8d756ba0a36cf48", size = 11106083, upload-time = "2025-06-05T20:59:37.03Z" },731+ { url = "https://files.pythonhosted.org/packages/77/79/d8cec175856ff810a19825d09ce700265f905c643c69f45d2b737e4a470a/ruff-0.11.13-py3-none-macosx_11_0_arm64.whl", hash = "sha256:53b15a9dfdce029c842e9a5aebc3855e9ab7771395979ff85b7c1dedb53ddc2b", size = 10436024, upload-time = "2025-06-05T20:59:39.741Z" },732+ { url = "https://files.pythonhosted.org/packages/8b/5b/f6d94f2980fa1ee854b41568368a2e1252681b9238ab2895e133d303538f/ruff-0.11.13-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ab153241400789138d13f362c43f7edecc0edfffce2afa6a68434000ecd8f69a", size = 10646324, upload-time = "2025-06-05T20:59:42.185Z" },733+ { url = "https://files.pythonhosted.org/packages/6c/9c/b4c2acf24ea4426016d511dfdc787f4ce1ceb835f3c5fbdbcb32b1c63bda/ruff-0.11.13-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:6c51f93029d54a910d3d24f7dd0bb909e31b6cd989a5e4ac513f4eb41629f0dc", size = 10174416, upload-time = "2025-06-05T20:59:44.319Z" },734+ { url = "https://files.pythonhosted.org/packages/f3/10/e2e62f77c65ede8cd032c2ca39c41f48feabedb6e282bfd6073d81bb671d/ruff-0.11.13-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1808b3ed53e1a777c2ef733aca9051dc9bf7c99b26ece15cb59a0320fbdbd629", size = 11724197, upload-time = "2025-06-05T20:59:46.935Z" },735+ { url = "https://files.pythonhosted.org/packages/bb/f0/466fe8469b85c561e081d798c45f8a1d21e0b4a5ef795a1d7f1a9a9ec182/ruff-0.11.13-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:d28ce58b5ecf0f43c1b71edffabe6ed7f245d5336b17805803312ec9bc665933", size = 12511615, upload-time = "2025-06-05T20:59:49.534Z" },736+ { url = "https://files.pythonhosted.org/packages/17/0e/cefe778b46dbd0cbcb03a839946c8f80a06f7968eb298aa4d1a4293f3448/ruff-0.11.13-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:55e4bc3a77842da33c16d55b32c6cac1ec5fb0fbec9c8c513bdce76c4f922165", size = 12117080, upload-time = "2025-06-05T20:59:51.654Z" },737+ { url = "https://files.pythonhosted.org/packages/5d/2c/caaeda564cbe103bed145ea557cb86795b18651b0f6b3ff6a10e84e5a33f/ruff-0.11.13-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:633bf2c6f35678c56ec73189ba6fa19ff1c5e4807a78bf60ef487b9dd272cc71", size = 11326315, upload-time = "2025-06-05T20:59:54.469Z" },738+ { url = "https://files.pythonhosted.org/packages/75/f0/782e7d681d660eda8c536962920c41309e6dd4ebcea9a2714ed5127d44bd/ruff-0.11.13-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4ffbc82d70424b275b089166310448051afdc6e914fdab90e08df66c43bb5ca9", size = 11555640, upload-time = "2025-06-05T20:59:56.986Z" },739+ { url = "https://files.pythonhosted.org/packages/5d/d4/3d580c616316c7f07fb3c99dbecfe01fbaea7b6fd9a82b801e72e5de742a/ruff-0.11.13-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:4a9ddd3ec62a9a89578c85842b836e4ac832d4a2e0bfaad3b02243f930ceafcc", size = 10507364, upload-time = "2025-06-05T20:59:59.154Z" },740+ { url = "https://files.pythonhosted.org/packages/5a/dc/195e6f17d7b3ea6b12dc4f3e9de575db7983db187c378d44606e5d503319/ruff-0.11.13-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:d237a496e0778d719efb05058c64d28b757c77824e04ffe8796c7436e26712b7", size = 10141462, upload-time = "2025-06-05T21:00:01.481Z" },741+ { url = "https://files.pythonhosted.org/packages/f4/8e/39a094af6967faa57ecdeacb91bedfb232474ff8c3d20f16a5514e6b3534/ruff-0.11.13-py3-none-musllinux_1_2_i686.whl", hash = "sha256:26816a218ca6ef02142343fd24c70f7cd8c5aa6c203bca284407adf675984432", size = 11121028, upload-time = "2025-06-05T21:00:04.06Z" },742+ { url = "https://files.pythonhosted.org/packages/5a/c0/b0b508193b0e8a1654ec683ebab18d309861f8bd64e3a2f9648b80d392cb/ruff-0.11.13-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:51c3f95abd9331dc5b87c47ac7f376db5616041173826dfd556cfe3d4977f492", size = 11602992, upload-time = "2025-06-05T21:00:06.249Z" },743+ { url = "https://files.pythonhosted.org/packages/7c/91/263e33ab93ab09ca06ce4f8f8547a858cc198072f873ebc9be7466790bae/ruff-0.11.13-py3-none-win32.whl", hash = "sha256:96c27935418e4e8e77a26bb05962817f28b8ef3843a6c6cc49d8783b5507f250", size = 10474944, upload-time = "2025-06-05T21:00:08.459Z" },744+ { url = "https://files.pythonhosted.org/packages/46/f4/7c27734ac2073aae8efb0119cae6931b6fb48017adf048fdf85c19337afc/ruff-0.11.13-py3-none-win_amd64.whl", hash = "sha256:29c3189895a8a6a657b7af4e97d330c8a3afd2c9c8f46c81e2fc5a31866517e3", size = 11548669, upload-time = "2025-06-05T21:00:11.147Z" },745+ { url = "https://files.pythonhosted.org/packages/ec/bf/b273dd11673fed8a6bd46032c0ea2a04b2ac9bfa9c628756a5856ba113b0/ruff-0.11.13-py3-none-win_arm64.whl", hash = "sha256:b4385285e9179d608ff1d2fb9922062663c658605819a6876d8beef0c30b7f3b", size = 10683928, upload-time = "2025-06-05T21:00:13.758Z" },746 ]747 748 [[package]]749 name = "sniffio"190 unmodified lines940 ]941 942 [[package]]943 name = "starlette"933-version = "0.46.2"944+version = "0.47.0"945 source = { registry = "https://pypi.org/simple" }946 dependencies = [947 { name = "anyio" },948 ]938-sdist = { url = "https://files.pythonhosted.org/packages/ce/20/08dfcd9c983f6a6f4a1000d934b9e6d626cff8d2eeb77a89a68eef20a2b7/starlette-0.46.2.tar.gz", hash = "sha256:7f7361f34eed179294600af672f565727419830b54b7b084efe44bb82d2fccd5", size = 2580846, upload-time = "2025-04-13T13:56:17.942Z" }949+sdist = { url = "https://files.pythonhosted.org/packages/8b/d0/0332bd8a25779a0e2082b0e179805ad39afad642938b371ae0882e7f880d/starlette-0.47.0.tar.gz", hash = "sha256:1f64887e94a447fed5f23309fb6890ef23349b7e478faa7b24a851cd4eb844af", size = 2582856, upload-time = "2025-05-29T15:45:27.628Z" }950 wheels = [940- { url = "https://files.pythonhosted.org/packages/8b/0c/9d30a4ebeb6db2b25a841afbb80f6ef9a854fc3b41be131d249a977b4959/starlette-0.46.2-py3-none-any.whl", hash = "sha256:595633ce89f8ffa71a015caed34a5b2dc1c0cdb3f0f1fbd1e69339cf2abeec35", size = 72037, upload-time = "2025-04-13T13:56:16.21Z" },951+ { url = "https://files.pythonhosted.org/packages/e3/81/c60b35fe9674f63b38a8feafc414fca0da378a9dbd5fa1e0b8d23fcc7a9b/starlette-0.47.0-py3-none-any.whl", hash = "sha256:9d052d4933683af40ffd47c7465433570b4949dc937e20ad1d73b34e72f10c37", size = 72796, upload-time = "2025-05-29T15:45:26.305Z" },952 ]953 954 [[package]]955 name = "tomli"57 unmodified lines1013 ]1014 1015 [[package]]1016 name = "tox-uv"1006-version = "1.25.0"1017+version = "1.26.0"1018 source = { registry = "https://pypi.org/simple" }1019 dependencies = [1020 { name = "packaging" },1021 { name = "tox" },1022 { name = "uv" },1023 ]1013-sdist = { url = "https://files.pythonhosted.org/packages/5d/3a/3e445f25978a716ba6674f33f687d9336d0312086a277a778a5e9e9220d7/tox_uv-1.25.0.tar.gz", hash = "sha256:59ee5e694c41fef7bbcf058f22a5f9b6a8509698def2ea60c08554f4e36b9fcc", size = 21114, upload-time = "2025-02-21T16:37:51.796Z" }1024+sdist = { url = "https://files.pythonhosted.org/packages/7e/da/37790b4a176f05b0ec7a699f54979078fc726f743640aa5c10c551c27edb/tox_uv-1.26.0.tar.gz", hash = "sha256:5045880c467eed58a98f7eaa7fe286b7ef688e2c56f2123d53e275011495c381", size = 21523, upload-time = "2025-05-27T14:51:42.702Z" }1025 wheels = [1015- { url = "https://files.pythonhosted.org/packages/3c/a7/f5c29e0e6faaccefcab607f672b176927144e9412c8183d21301ea2a6f6c/tox_uv-1.25.0-py3-none-any.whl", hash = "sha256:50cfe7795dcd49b2160d7d65b5ece8717f38cfedc242c852a40ec0a71e159bf7", size = 16431, upload-time = "2025-02-21T16:37:49.657Z" },1026+ { url = "https://files.pythonhosted.org/packages/46/b8/04c5cb83da072a3f96d357d68a551f5e97e162573c2011a09437df995811/tox_uv-1.26.0-py3-none-any.whl", hash = "sha256:894b2e7274fd6131c3bd1012813edc858753cad67727050c21cd973a08e691c8", size = 16562, upload-time = "2025-05-27T14:51:40.803Z" },1027 ]1028 1029 [[package]]1030 name = "typing-extensions"1020-version = "4.13.2"1031+version = "4.14.0"1032 source = { registry = "https://pypi.org/simple" }1022-sdist = { url = "https://files.pythonhosted.org/packages/f6/37/23083fcd6e35492953e8d2aaaa68b860eb422b34627b13f2ce3eb6106061/typing_extensions-4.13.2.tar.gz", hash = "sha256:e6c81219bd689f51865d9e372991c540bda33a0379d5573cddb9a3a23f7caaef", size = 106967, upload-time = "2025-04-10T14:19:05.416Z" }1033+sdist = { url = "https://files.pythonhosted.org/packages/d1/bc/51647cd02527e87d05cb083ccc402f93e441606ff1f01739a62c8ad09ba5/typing_extensions-4.14.0.tar.gz", hash = "sha256:8676b788e32f02ab42d9e7c61324048ae4c6d844a399eebace3d4979d75ceef4", size = 107423, upload-time = "2025-06-02T14:52:11.399Z" }1034 wheels = [1024- { url = "https://files.pythonhosted.org/packages/8b/54/b1ae86c0973cc6f0210b53d508ca3641fb6d0c56823f288d108bc7ab3cc8/typing_extensions-4.13.2-py3-none-any.whl", hash = "sha256:a439e7c04b49fec3e5d3e2beaa21755cadbbdc391694e28ccdd36ca4a1408f8c", size = 45806, upload-time = "2025-04-10T14:19:03.967Z" },1035+ { url = "https://files.pythonhosted.org/packages/69/e0/552843e0d356fbb5256d21449fa957fa4eff3bbc135a74a691ee70c7c5da/typing_extensions-4.14.0-py3-none-any.whl", hash = "sha256:a1514509136dd0b477638fc68d6a91497af5076466ad0fa6c338e44e359944af", size = 43839, upload-time = "2025-06-02T14:52:10.026Z" },1036 ]1037 1038 [[package]]1039 name = "urllib3"5 unmodified lines1045 ]1046 1047 [[package]]1048 name = "uv"1038-version = "0.7.3"1049+version = "0.7.12"1050 source = { registry = "https://pypi.org/simple" }1040-sdist = { url = "https://files.pythonhosted.org/packages/77/9e/4ea6d224f868badecd48b8fed17f83adb0ff62f75bc21785d91dee75c744/uv-0.7.3.tar.gz", hash = "sha256:863ceb63aefc7c2db9918313a1cb3c8bf3fc3d59b656b617db9e4abad90373f3", size = 3242256, upload-time = "2025-05-07T20:01:59.783Z" }1051+sdist = { url = "https://files.pythonhosted.org/packages/67/35/360a4aa325254b7f11d0898d30588861428659011b34f1e19c40fdd15db6/uv-0.7.12.tar.gz", hash = "sha256:4aa152e6a70d5662ca66a918f697bf8fb710f391068aa7d04e032af2edebb095", size = 3298683, upload-time = "2025-06-06T20:39:04.308Z" }1052 wheels = [1042- { url = "https://files.pythonhosted.org/packages/e4/8b/09a9d9da09d90ec6829dc4b3e9b7ff99222b7f05bc5d292bc30b04b92209/uv-0.7.3-py3-none-linux_armv6l.whl", hash = "sha256:f37c8a6b172776fb5305afe0699907aff44a778669de7a8fbe5a9c09c1a88a97", size = 16673361, upload-time = "2025-05-07T20:01:04.641Z" },1043- { url = "https://files.pythonhosted.org/packages/ba/de/794ea8c9729784c7626f05a98fe91b8367587f57f023cb95adcd8f8a9215/uv-0.7.3-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:3e6e1fd5755d4ef4c6e1ce55bd2c6d9dec278a8bef5752703d702ce03704fe29", size = 16755964, upload-time = "2025-05-07T20:01:09.43Z" },1044- { url = "https://files.pythonhosted.org/packages/df/1b/50922bfbe1631d022e0c6434ade17158b9b4e0bb7fccc77c928e32dd9021/uv-0.7.3-py3-none-macosx_11_0_arm64.whl", hash = "sha256:db8a5d5995b160158405379deadf0ffccf849a5e7ce048900b73517daf109e2c", size = 15577471, upload-time = "2025-05-07T20:01:12.235Z" },1045- { url = "https://files.pythonhosted.org/packages/69/39/cba47262d9547695657885391b34e8732cb0c34b5b876b811851cd320f3a/uv-0.7.3-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.musllinux_1_1_aarch64.whl", hash = "sha256:d246243f348796730e8ea9736ddd48702d4448d98af5e61693063ed616e30378", size = 16027456, upload-time = "2025-05-07T20:01:14.653Z" },1046- { url = "https://files.pythonhosted.org/packages/e6/33/1acf89318fb987a6eb9989a6991b76b6c930b6a724ce5f1ed848519d6a5f/uv-0.7.3-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:acef117a0c52299e60c6f7a3e60849050cd233704c561f688fac1100d113da2e", size = 16390903, upload-time = "2025-05-07T20:01:17.018Z" },1047- { url = "https://files.pythonhosted.org/packages/ad/66/2fe8ec6e5390de4cfc6db312464b4f28e5b3d98d576adc42731c0aeb5073/uv-0.7.3-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:90990e4c289feee24164c8e463fc0ebc9a336960119cd256acca7c1439f0f536", size = 17167937, upload-time = "2025-05-07T20:01:19.567Z" },1048- { url = "https://files.pythonhosted.org/packages/a5/8a/dc46e79f5fd068cb841a716a96f0344af62cf2deb2e78f57e0e147de26ac/uv-0.7.3-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:4809e5f7f5b2d6423d6573fda5655389c955ca649499fe9750b61af95daf9b7d", size = 18077868, upload-time = "2025-05-07T20:01:22.447Z" },1049- { url = "https://files.pythonhosted.org/packages/da/af/f7165a205ce8bb5e00f197d86a6fce4b4a317db0e471a31db9137ca1cc2d/uv-0.7.3-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:acff7fba5ff40dcb5a42de496db92a3965edac7a3d687d9b013ba6e0336995df", size = 17793072, upload-time = "2025-05-07T20:01:25.942Z" },1050- { url = "https://files.pythonhosted.org/packages/27/5e/2e9172ec3fa8acfa69642900d6eee8e5021f6c14d135edef524c674b4cfb/uv-0.7.3-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:fbb2d322d453e498e1431c51421cee597962ecd3f93fcef853b258e9c7e7636c", size = 22181943, upload-time = "2025-05-07T20:01:28.576Z" },1051- { url = "https://files.pythonhosted.org/packages/f1/b1/8af4ea6d09d05b9edead5e701dd91e04d55971483a7a644bab7a979bb46b/uv-0.7.3-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b1414a026c153ae0731daed0812b17bf77d34eafedaeb3a5c72e08181aea116b", size = 17400777, upload-time = "2025-05-07T20:01:32.27Z" },1052- { url = "https://files.pythonhosted.org/packages/09/ae/ccd123274ae59707e84fc5542776f89887818bad915167fbaeda65ebf52a/uv-0.7.3-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:c976fce3d1068a1d007f50127cc7873d67643c1a60439564970f092d9be41877", size = 16306132, upload-time = "2025-05-07T20:01:36.572Z" },1053- { url = "https://files.pythonhosted.org/packages/01/5c/99ef96ca53c74552b616bd341cd5d298bc8a603151343c409efeaf1552a0/uv-0.7.3-py3-none-musllinux_1_1_armv7l.whl", hash = "sha256:cc27207c35c959d2e0e873e86a80a2470a77b7a34a4512a831e8d4f7c87f4404", size = 16376728, upload-time = "2025-05-07T20:01:39.357Z" },1054- { url = "https://files.pythonhosted.org/packages/74/91/07f7e68f08e617d27ae9908a4e8deb756368b942319634956ed92d7cf35c/uv-0.7.3-py3-none-musllinux_1_1_i686.whl", hash = "sha256:5eb4872888a9fb10b62cc00be8e84822d63d3e622a5f340248e53ecf321dba96", size = 16707670, upload-time = "2025-05-07T20:01:46.816Z" },1055- { url = "https://files.pythonhosted.org/packages/a9/73/385a5a55fccfebac84a88b629992e301c080640691f2e27a3e3ccee8315e/uv-0.7.3-py3-none-musllinux_1_1_x86_64.whl", hash = "sha256:0646e463365e7277f22200ce2d43b7a44e5a3192320500b4983b4fe34d69a5fb", size = 17514613, upload-time = "2025-05-07T20:01:49.245Z" },1056- { url = "https://files.pythonhosted.org/packages/6a/97/1138bb26038805a14d930c7261faf363a5256757390b4be0aaf6e33a41c0/uv-0.7.3-py3-none-win32.whl", hash = "sha256:44e2f3fcbd1ab519bdb68986449b2e3103d2261be95f985cadcf7ec7c510b595", size = 16897117, upload-time = "2025-05-07T20:01:51.728Z" },1057- { url = "https://files.pythonhosted.org/packages/64/1b/c9f0ad7c75bf0a04c52c7e766593f5e79b1ac7d97fa1cb34c6ce0cfe3746/uv-0.7.3-py3-none-win_amd64.whl", hash = "sha256:0a446d4e5b10ce8a793156a276727bb7affa96a85e80dc5ad34e0c2de7e71cc8", size = 18323992, upload-time = "2025-05-07T20:01:54.495Z" },1058- { url = "https://files.pythonhosted.org/packages/47/1b/7ca1b8ec4bcf1c807f61e6ced7ca704791843cf1297db5edb54db07bd1db/uv-0.7.3-py3-none-win_arm64.whl", hash = "sha256:cb2547fd1466698e9b4f11de5eef7055b8cbcc3c693d79f6d747e3f8e6be2ab7", size = 17017988, upload-time = "2025-05-07T20:01:57.283Z" },1053+ { url = "https://files.pythonhosted.org/packages/f8/64/ee9f1b27f006c49a6765e9655ab93e7c8cbd6f0bf8b731f30f608b0be9fd/uv-0.7.12-py3-none-linux_armv6l.whl", hash = "sha256:81824caf5756ffee54b4c937d92d7c8c224c416270c90a83b9b4a973f6e4e559", size = 17024991, upload-time = "2025-06-06T20:38:17.053Z" },1054+ { url = "https://files.pythonhosted.org/packages/43/aa/f42707faa13a9c1b4f662456b2dca4bde169eb921f135319d8856c6e5e8e/uv-0.7.12-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:02e67c5f9d141fb25976cddb28abceaf715412ed83070cb9b87c5c488c8451af", size = 17097383, upload-time = "2025-06-06T20:38:21.174Z" },1055+ { url = "https://files.pythonhosted.org/packages/b9/a9/0f27e16e161f98240a328b5201b8abf178b751fde4fc56c54c1321812cd5/uv-0.7.12-py3-none-macosx_11_0_arm64.whl", hash = "sha256:e70a4393fd6a09b056e1ac500fe2b796d26c30783194868c6801ea08c3bbf863", size = 15812649, upload-time = "2025-06-06T20:38:23.51Z" },1056+ { url = "https://files.pythonhosted.org/packages/0b/eb/605d8f1d08606024209d0e31c3799c696199a887260ee1db52663e4da2e8/uv-0.7.12-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.musllinux_1_1_aarch64.whl", hash = "sha256:bb47326b9c4802db28e11f1aab174d5c9c0a8b26ed0a83094d3882dd8f5049ad", size = 16344497, upload-time = "2025-06-06T20:38:25.899Z" },1057+ { url = "https://files.pythonhosted.org/packages/b7/86/3503eb869fa17d607cc296a6514db52ec73c2ec85ad608952a207fd2e8ff/uv-0.7.12-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:14214a51e0ae0f0e8dbcac35a29722c45dbf40d0fd37309897642f7989af6caf", size = 16773525, upload-time = "2025-06-06T20:38:28.619Z" },1058+ { url = "https://files.pythonhosted.org/packages/9b/d6/868fb3f0b9f2a0d2f14cb8079171b862adbd782e47e0469dad3d3d71c938/uv-0.7.12-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:0fa630d865111c26f26c5e6f4547a73b13284f098471a4ca982d7b0caf0e658b", size = 17551173, upload-time = "2025-06-06T20:38:31.166Z" },1059+ { url = "https://files.pythonhosted.org/packages/d4/a8/b5be1c67c7894caf178e850903ac25f465e3508a6eada2ae735b187dc39d/uv-0.7.12-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:1557a154d2c36030ff0b707f3c2bfafd977e54fcd4d628dd0fa8a265449e9f13", size = 18359491, upload-time = "2025-06-06T20:38:33.569Z" },1060+ { url = "https://files.pythonhosted.org/packages/95/23/f62bab13f67ed785f7ad01546c499809d1db71b03f94950380f0bc407625/uv-0.7.12-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7e0ba7767b21d58d65703c3cd43814ccfe06d7664ac42b3589d5f2b72486b903", size = 18098855, upload-time = "2025-06-06T20:38:36.029Z" },1061+ { url = "https://files.pythonhosted.org/packages/a6/4a/db21a5d3839771799af2df366cc5ed0933ebe9fc9e920f212e33dc00136e/uv-0.7.12-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e0672dc5dc1b0ae7191d11ecae8bb794c7e860936b66c2bc3855bd0dee17fca1", size = 18206282, upload-time = "2025-06-06T20:38:38.582Z" },1062+ { url = "https://files.pythonhosted.org/packages/bc/ae/fcfd916cbc109c5626dc25b208395b47ba12b27af82f3bb8e247b4e95692/uv-0.7.12-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e34b4ad4288828210c2e075934009903514ca97bd603aced7d0755040b4d0489", size = 17777690, upload-time = "2025-06-06T20:38:41.021Z" },1063+ { url = "https://files.pythonhosted.org/packages/92/78/608163b35ffaf1054cd10197646b6336e7be7b6a51dfef6d98a91600c6be/uv-0.7.12-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:8a7ed9e94ec409bfc7181ee274d1b0ed6292698a20df0ae035ce422224863af5", size = 16599406, upload-time = "2025-06-06T20:38:43.72Z" },1064+ { url = "https://files.pythonhosted.org/packages/d4/d6/6fe3b16390472a9d31dd1e0e7e3759b884d71e8a0dff1baf4a753b4adaaa/uv-0.7.12-py3-none-musllinux_1_1_armv7l.whl", hash = "sha256:85e8d3dea95016a45ed8c48343f98734d1b5c4be7bba26257d4c8873059646fa", size = 16714823, upload-time = "2025-06-06T20:38:45.949Z" },1065+ { url = "https://files.pythonhosted.org/packages/b3/a5/b0432a25eaa23e9f909649321784b8e4be4579e9957eb5d369aa30c79164/uv-0.7.12-py3-none-musllinux_1_1_i686.whl", hash = "sha256:01310c45d55f6e7580124c9b1f7e3586b9609c4f8e5a78558a75951b03541bb2", size = 17086446, upload-time = "2025-06-06T20:38:48.648Z" },1066+ { url = "https://files.pythonhosted.org/packages/da/d8/673591f34f897aa4216144a513e60c2004399155c47e7b550612960359c6/uv-0.7.12-py3-none-musllinux_1_1_x86_64.whl", hash = "sha256:4c697ef9d9f6b6f42df5a661efa8a745c0e4c330039d45b549b2ca7e7b66f8a5", size = 17903789, upload-time = "2025-06-06T20:38:51.864Z" },1067+ { url = "https://files.pythonhosted.org/packages/15/09/e476187c0a1da78b9c2021f3c3ab31ed2469a70d222bde5dc892236b3c4f/uv-0.7.12-py3-none-win32.whl", hash = "sha256:6008abf92c8d37060944377d89bf9f514aa18370391d9d63dc7d449dac94aca1", size = 17344011, upload-time = "2025-06-06T20:38:54.276Z" },1068+ { url = "https://files.pythonhosted.org/packages/08/9e/c52c7f50280e57110ca79b6805877f50514d9a777d31a683a4eb1de52312/uv-0.7.12-py3-none-win_amd64.whl", hash = "sha256:bb57bd26becd86194788f832af373b6ba431314fa0f6f7e904c90cac1818a7dc", size = 18803328, upload-time = "2025-06-06T20:38:59.368Z" },1069+ { url = "https://files.pythonhosted.org/packages/8e/35/4800ff7bc1663d9f967eabc8440074f906c8a98ea28d1aae66d2d19b7ae9/uv-0.7.12-py3-none-win_arm64.whl", hash = "sha256:8aba24e12ded2f2974a2f213e55daabf78002613d3772c1396fc924c6682cd27", size = 17450522, upload-time = "2025-06-06T20:39:01.963Z" },1070 ]1071 1072 [[package]]1073 name = "uvicorn"1063-version = "0.34.2"1074+version = "0.34.3"1075 source = { registry = "https://pypi.org/simple" }1076 dependencies = [1077 { name = "click" },1078 { name = "h11" },1079 { name = "typing-extensions", marker = "python_full_version < '3.11'" },1080 ]1070-sdist = { url = "https://files.pythonhosted.org/packages/a6/ae/9bbb19b9e1c450cf9ecaef06463e40234d98d95bf572fab11b4f19ae5ded/uvicorn-0.34.2.tar.gz", hash = "sha256:0e929828f6186353a80b58ea719861d2629d766293b6d19baf086ba31d4f3328", size = 76815, upload-time = "2025-04-19T06:02:50.101Z" }1081+sdist = { url = "https://files.pythonhosted.org/packages/de/ad/713be230bcda622eaa35c28f0d328c3675c371238470abdea52417f17a8e/uvicorn-0.34.3.tar.gz", hash = "sha256:35919a9a979d7a59334b6b10e05d77c1d0d574c50e0fc98b8b1a0f165708b55a", size = 76631, upload-time = "2025-06-01T07:48:17.531Z" }1082 wheels = [1072- { url = "https://files.pythonhosted.org/packages/b1/4b/4cef6ce21a2aaca9d852a6e84ef4f135d99fcd74fa75105e2fc0c8308acd/uvicorn-0.34.2-py3-none-any.whl", hash = "sha256:deb49af569084536d269fe0a6d67e3754f104cf03aba7c11c40f01aadf33c403", size = 62483, upload-time = "2025-04-19T06:02:48.42Z" },1083+ { url = "https://files.pythonhosted.org/packages/6d/0d/8adfeaa62945f90d19ddc461c55f4a50c258af7662d34b6a3d5d1f8646f6/uvicorn-0.34.3-py3-none-any.whl", hash = "sha256:16246631db62bdfbf069b0645177d6e8a77ba950cfedbfd093acef9444e4d885", size = 62431, upload-time = "2025-06-01T07:48:15.664Z" },1084 ]1085 1086 [[package]]1087 name = "virtualenv"135 unmodified lines