Initial commit
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · the first commit · Browse files · 30 files·+3971 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
30 files+3971 added−0 removed
- other:+3971 added−0 removed
Provenance
- Commit
4101de3- Tree
67db98f- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>
30 files changed+3971 added−0 removed
added:artwork/logo.svg+75 added
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>added:docs/_static/click-small.pngbinary
A binary file, added.
added:docs/_static/click.pngbinary
A binary file, added.
added:docs/_templates/sidebarintro.html+13 added
12345678910111213<h3>About</h3><p> Click is a Python package for creating beautiful command line interfaces in a composable way with as little amount of code as necessary. It’s the “Command Line Interface Creation Kit”.</p><h3>Useful Links</h3><ul> <li><a href="http://click.pocoo.org/">The Click Website</a></li> <li><a href="http://pypi.python.org/pypi/click">click @ PyPI</a></li> <li><a href="http://github.com/mitsuhiko/click">click @ github</a></li> <li><a href="http://github.com/mitsuhiko/click/issues">Issue Tracker</a></li></ul>added:docs/_templates/sidebarlogo.html+3 added
123<p class="logo"><a href="{{ pathto(master_doc) }}"> <img class="logo" src="{{ pathto('_static/click-small.png', 1) }}" alt="Logo"></a></p>added:docs/_themes/click/static/click.css_t+396 added
1+/*2+ * click.css_t3+ * ~~~~~~~~~~~4+ *5+ * :copyright: Copyright 2014 by Armin Ronacher.6+ * :license: Flask Design License, see LICENSE for details.7+ */8+9+{% set page_width = '940px' %}10+{% set sidebar_width = '220px' %}11+ 12+@import url("basic.css");13+14+@import url(http://fonts.googleapis.com/css?family=Ubuntu+Mono:400,400italic,700,700italic);15+@import url(http://fonts.googleapis.com/css?family=Open+Sans:300,400);16+ 17+/* -- page layout ----------------------------------------------------------- */18+ 19+body {20+ font-family: 'Ubuntu Mono', 'Consolas', 'Menlo', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono';21+ font-size: 15px;22+ background-color: white;23+ color: #000;24+ margin: 0;25+ padding: 0;26+}27+28+div.document {29+ width: {{ page_width }};30+ margin: 30px auto 0 auto;31+}32+33+div.documentwrapper {34+ float: left;35+ width: 100%;36+}37+38+div.bodywrapper {39+ margin: 0 0 0 {{ sidebar_width }};40+}41+42+div.sphinxsidebar {43+ width: {{ sidebar_width }};44+}45+46+div.sphinxsidebar h3,47+div.sphinxsidebar h4 {48+ font-family: 'Open Sans', 'Helvetica', 'Arial', sans-serif;49+ font-weight: 300;50+ margin: 20px 0px 10px 0px;51+ padding: 0;52+}53+54+hr {55+ border: 1px solid #B1B4B6;56+}57+ 58+div.body {59+ background-color: #ffffff;60+ color: #3E4349;61+ padding: 0 30px 0 30px;62+}63+64+img.floatingflask {65+ padding: 0 0 10px 10px;66+ float: right;67+}68+ 69+div.footer {70+ width: {{ page_width }};71+ margin: 20px auto 30px auto;72+ font-size: 14px;73+ color: #888;74+ text-align: right;75+}76+77+div.footer a {78+ color: #888;79+}80+81+div.related {82+ display: none;83+}84+ 85+div.sphinxsidebar a {86+ color: #444;87+ text-decoration: none;88+ border-bottom: 1px dotted #999;89+}90+91+div.sphinxsidebar a:hover {92+ border-bottom: 1px solid #999;93+}94+ 95+div.sphinxsidebar {96+ font-size: 14px;97+ line-height: 1.5;98+}99+100+div.sphinxsidebarwrapper {101+ padding: 18px 10px;102+}103+104+div.sphinxsidebarwrapper p.logo {105+ padding: 0 0 20px 0;106+ margin: 0;107+ text-align: left;108+}109+ 110+div.sphinxsidebar h3,111+div.sphinxsidebar h4 {112+ color: #444;113+ font-size: 18px;114+ font-weight: normal;115+ margin: 0 0 5px 0;116+ padding: 0;117+}118+119+div.sphinxsidebar h4 {120+ font-size: 15px;121+}122+ 123+div.sphinxsidebar h3 a {124+ color: #444;125+}126+127+div.sphinxsidebar p.logo a,128+div.sphinxsidebar h3 a,129+div.sphinxsidebar p.logo a:hover,130+div.sphinxsidebar h3 a:hover {131+ border: none;132+}133+ 134+div.sphinxsidebar p {135+ color: #555;136+ margin: 10px 0;137+}138+139+div.sphinxsidebar ul {140+ margin: 10px 0;141+ padding: 0;142+ color: #000;143+}144+ 145+div.sphinxsidebar input {146+ border: 1px solid #ccc;147+ font-family: 'Ubuntu Mono', 'Consolas', 'Menlo', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono';148+ font-size: 13px;149+}150+151+div.sphinxsidebar #searchbox input[type="text"] {152+ width: 120px;153+}154+ 155+/* -- body styles ----------------------------------------------------------- */156+ 157+a {158+ color: #5D2CD1;159+ text-decoration: underline;160+}161+ 162+a:hover {163+ color: #7546E3;164+ text-decoration: underline;165+}166+ 167+div.body h1,168+div.body h2,169+div.body h3,170+div.body h4,171+div.body h5,172+div.body h6 {173+ font-family: 'Open Sans', 'Helvetica', 'Arial', sans-serif;174+ font-weight: 400;175+ margin: 30px 0px 10px 0px;176+ padding: 0;177+}178+179+div.indexwrapper h1 {180+ text-indent: -999999px;181+ background: url(click.png) no-repeat center center;182+ height: 200px;183+}184+ 185+div.body h1 { margin-top: 0; padding-top: 0; font-size: 240%; }186+div.body h2 { font-size: 180%; }187+div.body h3 { font-size: 150%; }188+div.body h4 { font-size: 130%; }189+div.body h5 { font-size: 100%; }190+div.body h6 { font-size: 100%; }191+ 192+a.headerlink {193+ color: #ddd;194+ padding: 0 4px;195+ text-decoration: none;196+}197+ 198+a.headerlink:hover {199+ color: #444;200+ background: #eaeaea;201+}202+ 203+div.body p, div.body dd, div.body li {204+ line-height: 1.4em;205+}206+207+div.admonition {208+ background: #fafafa;209+ margin: 20px -30px;210+ padding: 10px 30px;211+ border-top: 1px solid #ccc;212+ border-bottom: 1px solid #ccc;213+}214+215+div.admonition tt.xref, div.admonition a tt {216+ border-bottom: 1px solid #fafafa;217+}218+219+dd div.admonition {220+ margin-left: -60px;221+ padding-left: 60px;222+}223+224+div.admonition p.admonition-title {225+ font-family: 'Open Sans', 'Helvetica', 'Arial', sans-serif;226+ font-weight: 400;227+ font-size: 24px;228+ margin: 0 0 10px 0;229+ padding: 0;230+ line-height: 1;231+}232+233+div.admonition p.last {234+ margin-bottom: 0;235+}236+237+div.highlight {238+ background-color: white;239+}240+241+dt:target, .highlight {242+ background: #FAF3E8;243+}244+245+div.note {246+ background-color: #eee;247+ border: 1px solid #ccc;248+}249+ 250+div.seealso {251+ background-color: #ffc;252+ border: 1px solid #ff6;253+}254+ 255+div.topic {256+ background-color: #eee;257+}258+ 259+p.admonition-title {260+ display: inline;261+}262+ 263+p.admonition-title:after {264+ content: ":";265+}266+267+pre, tt {268+ font-family: 'Ubuntu Mono', 'Consolas', 'Menlo', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono';269+ font-size: 15px;270+}271+272+img.screenshot {273+}274+275+tt.descname, tt.descclassname {276+ font-size: 0.95em;277+}278+279+tt.descname {280+ padding-right: 0.08em;281+}282+283+img.screenshot {284+ -moz-box-shadow: 2px 2px 4px #eee;285+ -webkit-box-shadow: 2px 2px 4px #eee;286+ box-shadow: 2px 2px 4px #eee;287+}288+289+table.docutils {290+ border: 1px solid #888;291+ -moz-box-shadow: 2px 2px 4px #eee;292+ -webkit-box-shadow: 2px 2px 4px #eee;293+ box-shadow: 2px 2px 4px #eee;294+}295+296+table.docutils td, table.docutils th {297+ border: 1px solid #888;298+ padding: 0.25em 0.7em;299+}300+301+table.field-list, table.footnote {302+ border: none;303+ -moz-box-shadow: none;304+ -webkit-box-shadow: none;305+ box-shadow: none;306+}307+308+table.footnote {309+ margin: 15px 0;310+ width: 100%;311+ border: 1px solid #eee;312+ background: #fdfdfd;313+ font-size: 0.9em;314+}315+316+table.footnote + table.footnote {317+ margin-top: -15px;318+ border-top: none;319+}320+321+table.field-list th {322+ padding: 0 0.8em 0 0;323+}324+325+table.field-list td {326+ padding: 0;327+}328+329+table.footnote td.label {330+ width: 0px;331+ padding: 0.3em 0 0.3em 0.5em;332+}333+334+table.footnote td {335+ padding: 0.3em 0.5em;336+}337+338+dl {339+ margin: 0;340+ padding: 0;341+}342+343+dl dd {344+ margin-left: 30px;345+}346+347+blockquote {348+ margin: 0 0 0 30px;349+ padding: 0;350+}351+352+ul, ol {353+ margin: 10px 0 10px 30px;354+ padding: 0;355+}356+ 357+pre {358+ padding: 7px 0 7px 30px;359+ margin: 15px 0;360+ line-height: 1.3em;361+}362+ 363+tt {364+ background-color: #ecf0f3;365+ color: #222;366+ /* padding: 1px 2px; */367+}368+369+tt.xref, a tt {370+ background-color: #FBFBFB;371+ border-bottom: 1px solid white;372+}373+374+a.reference {375+ text-decoration: none;376+ border-bottom: 1px dotted #5D2CD1;377+}378+379+a.reference:hover {380+ border-bottom: 1px solid #7546E3;381+}382+383+a.footnote-reference {384+ text-decoration: none;385+ font-size: 0.7em;386+ vertical-align: top;387+ border-bottom: 1px dotted #5D2CD1;388+}389+390+a.footnote-reference:hover {391+ border-bottom: 1px solid #7546E3;392+}393+394+a:hover tt {395+ background: #EEE;396+}added:docs/_themes/click/layout.html+20 added
1234567891011121314151617181920{%- extends "basic/layout.html" %}{%- block extrahead %} {{ super() }}{% endblock %}{%- block relbar2 %}{% endblock %}{% block header %} {{ super() }} {% if pagename == 'index' %} <div class=indexwrapper> {% endif %}{% endblock %}{%- block footer %} <div class="footer"> © Copyright {{ copyright }}. Created using <a href="http://sphinx.pocoo.org/">Sphinx</a>. </div> {% if pagename == 'index' %} </div> {% endif %}{%- endblock %}added:docs/_themes/click/relations.html+19 added
12345678910111213141516171819<h3>Related Topics</h3><ul> <li><a href="{{ pathto(master_doc) }}">Documentation overview</a><ul> {%- for parent in parents %} <li><a href="{{ parent.link|e }}">{{ parent.title }}</a><ul> {%- endfor %} {%- if prev %} <li>Previous: <a href="{{ prev.link|e }}" title="{{ _('previous chapter') }}">{{ prev.title }}</a></li> {%- endif %} {%- if next %} <li>Next: <a href="{{ next.link|e }}" title="{{ _('next chapter') }}">{{ next.title }}</a></li> {%- endif %} {%- for parent in parents %} </ul></li> {%- endfor %} </ul></li></ul>added:docs/_themes/click/theme.conf+4 added
1+[theme]2+inherit = basic3+stylesheet = click.css4+pygments_style = tangoadded:docs/_themes/LICENSE+37 added
1+Copyright (c) 2014 by Armin Ronacher.2+3+Some rights reserved.4+5+Redistribution and use in source and binary forms of the theme, with or6+without modification, are permitted provided that the following conditions7+are met:8+9+* Redistributions of source code must retain the above copyright10+ notice, this list of conditions and the following disclaimer.11+12+* Redistributions in binary form must reproduce the above13+ copyright notice, this list of conditions and the following14+ disclaimer in the documentation and/or other materials provided15+ with the distribution.16+17+* The names of the contributors may not be used to endorse or18+ promote products derived from this software without specific19+ prior written permission.20+21+We kindly ask you to only use these themes in an unmodified manner just22+for Click and Click-related products, not for unrelated projects. If you23+like the visual style and want to use it for your own projects, please24+consider making some larger changes to the themes (such as changing25+font faces, sizes, colors or margins).26+27+THIS THEME IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"28+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE29+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE30+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE31+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR32+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF33+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS34+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN35+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)36+ARISING IN ANY WAY OUT OF THE USE OF THIS THEME, EVEN IF ADVISED OF THE37+POSSIBILITY OF SUCH DAMAGE.added:docs/_themes/README+31 added
1+Flask Sphinx Styles2+===================3+4+This repository contains sphinx styles for Flask and Flask related5+projects. To use this style in your Sphinx documentation, follow6+this guide:7+8+1. put this folder as _themes into your docs folder. Alternatively9+ you can also use git submodules to check out the contents there.10+2. add this to your conf.py:11+12+ sys.path.append(os.path.abspath('_themes'))13+ html_theme_path = ['_themes']14+ html_theme = 'flask'15+16+The following themes exist:17+18+- 'flask' - the standard flask documentation theme for large19+ projects20+- 'flask_small' - small one-page theme. Intended to be used by21+ very small addon libraries for flask.22+23+The following options exist for the flask_small theme:24+25+ [options]26+ index_logo = '' filename of a picture in _static27+ to be used as replacement for the28+ h1 in the index.rst file.29+ index_logo_height = 120px height of the index logo30+ github_fork = '' repository name on github for the31+ "fork me" badgeadded:docs/api.rst+85 added
1+API2+===3+4+.. module:: click5+6+This part of the documentation shows the full API reference of all public7+classes and functions.8+9+Decorators10+----------11+12+.. autofunction:: command13+14+.. autofunction:: group15+16+.. autofunction:: argument17+18+.. autofunction:: option19+20+.. autofunction:: password_option21+22+.. autofunction:: confirmation_option23+24+.. autofunction:: version_option25+26+.. autofunction:: help_option27+28+Helper Functions29+----------------30+31+.. autofunction:: prompt32+33+.. autofunction:: confirm34+35+.. autofunction:: get_terminal_size36+37+Commands38+--------39+40+.. autoclass:: Command41+ :members:42+43+.. autoclass:: MultiCommand44+ :members:45+46+.. autoclass:: Group47+ :members:48+49+Parameters50+----------51+52+.. autoclass:: Parameter53+ :members:54+55+.. autoclass:: Option56+57+.. autoclass:: Argument58+59+Context60+-------61+62+.. autoclass:: Context63+ :members:64+65+Types66+-----67+68+.. autodata:: STRING69+70+.. autodata:: INT71+72+.. autodata:: FLOAT73+74+.. autodata:: BOOL75+76+.. autoclass:: File77+78+.. autoclass:: ParamType79+80+Exceptions81+----------82+83+.. autoexception:: Abort84+85+.. autoexception:: UsageErroradded:docs/arguments.rst+114 added
1+Arguments2+=========3+4+.. currentmodule:: click5+6+Arguments work similar to options but are positional. They also only7+support subset of the features of options due to their syntactical nature.8+Click also will not attempt to document arguments for you and wants you to9+document them manually to avoid ugly looking help pages.10+11+Basic Arguments12+---------------13+14+The most basic option is a simple string arguments of one value. If no15+type is provided the type of the default value is used. If no default16+value is provided the type is assumed to be :data:`STRING`.17+18+Example::19+20+ @click.command()21+ @click.argument('filename')22+ def touch(filename):23+ print(filename)24+25+And what it looks like::26+27+ $ python touch.py foo.txt28+ foo.txt29+30+Variadic Arguments31+------------------32+33+The second most common version is variadic arguments where a specific (or34+unlimited) number of arguments is accepted. This can be controlled with35+the ``nargs`` parameter. If it's set to ``-1`` then an unlimited number36+of arguments is accepted.37+38+The value is then passed as tuple. Note that only one argument really can39+be set to ``nargs=-1`` and right now only the last.40+41+Example::42+43+ @click.command()44+ @click.argument('files', nargs=-1)45+ def touch(files):46+ for file in files:47+ print(file)48+49+And what it looks like::50+51+ $ python touch.py foo.txt bar.txt52+ foo.txt53+ bar.txt54+55+File Arguments56+--------------57+58+Since all the examples have already worked with file names it makes sense59+to explain how to deal with files properly. Command line tools are more60+fun if they work with files the unix way which is to accept ``-`` as61+special file that refers to stdin/stdout.62+63+Click supports this through the :class:`click.File` type which64+intelligently handles files for you. It also deals with unicode and bytes65+correctly for all versions of Python so your script stays very portable.66+67+Example::68+69+ @click.command()70+ @click.argument('input', type=click.File('rb'))71+ @click.argument('output', type=click.File('wb'))72+ def inout(input, output):73+ while True:74+ chunk = input.read(1024)75+ if not chunk:76+ break77+ output.write(chunk)78+79+And what it does::80+81+ $ python inout.py - hello.txt82+ hello83+ ^D84+ $ python inout.py hello.txt -85+ hello86+87+Environment Variables88+---------------------89+90+Like options, arguments can also get values from an environment variable.91+Unlike options however this is only supported for explicitly named92+environment variables.93+94+Example usage::95+96+ @click.command()97+ @click.argument('--src', envvar='SOURCE', type=click.File('r'))98+ def echo(src):99+ print(src.read())100+101+ if __name__ == '__main__':102+ echo()103+104+And from the command line::105+106+ $ export SRC=hello.txt107+ $ python echo.py108+ Hello!109+110+In that case it can also be a list of different environment variables111+where the first one is picked.112+113+Generally this feature is not recommended because it can cause a lot of114+confusion to the user.added:docs/commands.rst+170 added
1+Commands and Groups2+===================3+4+.. currentmodule:: click5+6+The most important feature of click is the concept of arbitrarily nesting7+command line utilities. This is implemented through the :class:`Command`8+and :class:`Group` (actually :class:`MultiCommand`).9+10+Callback Invocation11+-------------------12+13+For a regular command the callback is executed whenever the command runs.14+So if the script is the only command it will always fire (unless a15+parameter callback prevents it. This for instance happens if someone16+passes ``--help`` to the script).17+18+For groups and multi commands the situation looks different. In that case19+the callback fires whenever a subcommand fires (unless this behavior is20+changed). What this means in practice is that an outer command runs21+when an inner command runs::22+23+ import click24+25+ @click.group()26+ @click.option('--debug/--no-debug', default=False)27+ def cli(debug):28+ print('Debug mode is %s' % ('on' if debug else 'off'))29+30+ @cli.command()31+ def sync():32+ print('Synching')33+34+ if __name__ == '__main__':35+ cli()36+37+Here is what this looks like::38+39+ $ python tool.py40+ Usage: tool.py [OPTIONS] COMMAND [ARGS]...41+42+ Commands:43+ sync 44+45+ Options:46+ --debug / --no-debug 47+ --help Show this message and exit.48+ 49+ $ python tool.py --debug sync50+ Debug mode is on51+ Synching 52+53+Nested Handling and Contexts54+----------------------------55+56+As you can see from the earlier example the basic command group accepts a57+debug argument which is passed to its callback, but not to the sync58+command itself. The sync command only accepts its own arguments.59+60+This allows tools to act completely independent of each other. But how61+does on command talk to a nested on? The answer to this is the62+:class:`Context`.63+64+Each time a command invokes a new context is created and linked with the65+parent context. Normally you can't see these contexts, but they are66+there. Contexts are passed to parameter callbacks together with the67+value automatically. Commands can also ask for the context to be passed68+by passing ``pass_context=True`` to the :func:`command` or :func:`group`69+decorator. In that case the context is passed as first argument.70+71+The context can also carry a program specified object that can be72+used for the program's purposes. What this means is that you can build a73+script like this::74+75+ import click76+77+ @click.group(pass_context=True)78+ @click.option('--debug/--no-debug', default=False)79+ def cli(ctx, debug):80+ ctx.obj['DEBUG'] = debug81+82+ @cli.command(pass_context=True)83+ def sync(ctx):84+ print('Debug is %s' % (ctx.obj['DEBUG'] and 'on' or 'off'))85+86+ if __name__ == '__main__':87+ cli(obj={})88+89+If the object is provided each context will pass the object onwards to90+it's children, but at any level a context's object can be overridden. To91+reach to a parent ``context.parent`` can be used.92+93+In addition to that instead of passing an object down nothing stops the94+application from modifying global state. For instance you could just flip95+a global ``DEBUG`` variable and be done with it.96+97+Group Invocation Without Command98+--------------------------------99+100+By default a group or multi command is not invoked unless a subcommand is101+passed. In fact, not providing a command automatically passes ``--help``102+by default. This behavior can be changed by passing103+``invoke_without_command=True`` to a group. In that case the callback is104+always invoked instead of showing the help page. The context object also105+includes information about if the invocation would go to a subcommand or106+not.107+108+Example::109+110+ import click111+112+ @click.group(pass_context=True, invoke_without_command=True)113+ def cli(ctx):114+ if ctx.invoked_subcommand is None:115+ print('I was invoked without subcommand')116+ else:117+ print('I am about to invoke %s' % ctx.invoked_subcommand)118+119+ @cli.command()120+ def sync():121+ print('The subcommand')122+123+ if __name__ == '__main__':124+ cli()125+126+And how it works in practice::127+128+ $ python tool.py 129+ I was invoked without subcommand130+ $ python tool.py sync131+ I am about to invoke sync132+ The subcommand133+134+Custom Multi Commands135+---------------------136+137+In addition to using :func:`click.group` you can also build your own138+custom multi commands. This is useful when you want to support commands139+being loaded lazily from plugins.140+141+A custom multi command just needs to implement a list and load method::142+143+ import click144+ import os145+146+ plugin_folder = os.path.join(os.path.dirname(__file__), 'commands')147+148+ class MyCLI(click.MultiCommand):149+150+ def list_commands(self):151+ rv = []152+ for filename in os.listdir(plugin_folder):153+ if filename.endswith('.py'):154+ rv.append(filename[:-3])155+ rv.sort()156+ return rv157+158+ def get_command(self, name):159+ ns = {}160+ fn = os.path.join(plugin_folder, name + '.py')161+ with open(fn) as f:162+ code = compile(f.read(), fn, 'exec')163+ eval(code, ns, ns)164+ return ns['cli']165+166+ cli = MyCLI(help='This tool\'s subcommands are loaded from a '167+ 'plugin folder dynamically.')168+169+ if __name__ == '__main__':170+ cli()added:docs/conf.py+217 added
1+# -*- coding: utf-8 -*-2+#3+# click documentation build configuration file, created by4+# sphinx-quickstart on Mon Apr 26 19:53:01 2010.5+#6+# This file is execfile()d with the current directory set to its containing dir.7+#8+# Note that not all possible configuration values are present in this9+# autogenerated file.10+#11+# All configuration values have a default; values that are commented out12+# serve to show the default.13+14+import sys, os15+16+# If extensions (or modules to document with autodoc) are in another directory,17+# add these directories to sys.path here. If the directory is relative to the18+# documentation root, use os.path.abspath to make it absolute, like shown here.19+sys.path.append(os.path.abspath('_themes'))20+sys.path.append(os.path.abspath('..'))21+22+# -- General configuration -----------------------------------------------------23+24+# If your documentation needs a minimal Sphinx version, state it here.25+#needs_sphinx = '1.0'26+27+# Add any Sphinx extension module names here, as strings. They can be extensions28+# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.29+extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx']30+31+# Add any paths that contain templates here, relative to this directory.32+templates_path = ['_templates']33+34+# The suffix of source filenames.35+source_suffix = '.rst'36+37+# The encoding of source files.38+#source_encoding = 'utf-8-sig'39+40+# The master toctree document.41+master_doc = 'index'42+43+# General information about the project.44+project = u'click'45+copyright = u'2014, Armin Ronacher'46+47+# The version info for the project you're documenting, acts as replacement for48+# |version| and |release|, also used in various other places throughout the49+# built documents.50+#51+# The short X.Y version.52+version = '1.0'53+# The full version, including alpha/beta/rc tags.54+release = '1.0'55+56+# The language for content autogenerated by Sphinx. Refer to documentation57+# for a list of supported languages.58+#language = None59+60+# There are two options for replacing |today|: either, you set today to some61+# non-false value, then it is used:62+#today = ''63+# Else, today_fmt is used as the format for a strftime call.64+#today_fmt = '%B %d, %Y'65+66+# List of patterns, relative to source directory, that match files and67+# directories to ignore when looking for source files.68+exclude_patterns = ['_build']69+70+# The reST default role (used for this markup: `text`) to use for all documents.71+#default_role = None72+73+# If true, '()' will be appended to :func: etc. cross-reference text.74+#add_function_parentheses = True75+76+# If true, the current module name will be prepended to all description77+# unit titles (such as .. function::).78+#add_module_names = True79+80+# If true, sectionauthor and moduleauthor directives will be shown in the81+# output. They are ignored by default.82+#show_authors = False83+84+# A list of ignored prefixes for module index sorting.85+#modindex_common_prefix = []86+87+88+# -- Options for HTML output ---------------------------------------------------89+90+# The theme to use for HTML and HTML Help pages. Major themes that come with91+# Sphinx are currently 'default' and 'sphinxdoc'.92+html_theme = 'click'93+94+# Theme options are theme-specific and customize the look and feel of a theme95+# further. For a list of options available for each theme, see the96+# documentation.97+html_theme_options = {98+}99+100+# Add any paths that contain custom themes here, relative to this directory.101+html_theme_path = ['_themes']102+103+# The name for this set of Sphinx documents. If None, it defaults to104+# "<project> v<release> documentation".105+html_title = 'click'106+107+# A shorter title for the navigation bar. Default is the same as html_title.108+#html_short_title = None109+110+# The name of an image file (relative to this directory) to place at the top111+# of the sidebar.112+#html_logo = None113+114+# The name of an image file (within the static path) to use as favicon of the115+# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32116+# pixels large.117+#html_favicon = None118+119+# Add any paths that contain custom static files (such as style sheets) here,120+# relative to this directory. They are copied after the builtin static files,121+# so a file named "default.css" will overwrite the builtin "default.css".122+html_static_path = ['_static']123+124+# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,125+# using the given strftime format.126+#html_last_updated_fmt = '%b %d, %Y'127+128+# If true, SmartyPants will be used to convert quotes and dashes to129+# typographically correct entities.130+#html_use_smartypants = True131+132+# Custom sidebar templates, maps document names to template names.133+html_sidebars = {134+ 'index': ['sidebarintro.html', 'sourcelink.html', 'searchbox.html'],135+ '**': ['sidebarlogo.html', 'localtoc.html', 'relations.html',136+ 'sourcelink.html', 'searchbox.html']137+}138+139+# Additional templates that should be rendered to pages, maps page names to140+# template names.141+#html_additional_pages = {}142+143+# If false, no module index is generated.144+#html_domain_indices = True145+146+# If false, no index is generated.147+#html_use_index = True148+149+# If true, the index is split into individual pages for each letter.150+#html_split_index = False151+152+# If true, links to the reST sources are added to the pages.153+#html_show_sourcelink = True154+155+# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.156+#html_show_sphinx = True157+158+# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.159+#html_show_copyright = True160+161+# If true, an OpenSearch description file will be output, and all pages will162+# contain a <link> tag referring to it. The value of this option must be the163+# base URL from which the finished HTML is served.164+#html_use_opensearch = ''165+166+# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").167+#html_file_suffix = ''168+169+# Output file base name for HTML help builder.170+htmlhelp_basename = 'clickdoc'171+172+173+# -- Options for LaTeX output --------------------------------------------------174+175+# The paper size ('letter' or 'a4').176+#latex_paper_size = 'letter'177+178+# The font size ('10pt', '11pt' or '12pt').179+#latex_font_size = '10pt'180+181+# Grouping the document tree into LaTeX files. List of tuples182+# (source start file, target name, title, author, documentclass [howto/manual]).183+latex_documents = [184+ ('index', 'click.tex', u'click documentation',185+ u'Armin Ronacher', 'manual'),186+]187+188+# The name of an image file (relative to this directory) to place at the top of189+# the title page.190+#latex_logo = None191+192+# For "manual" documents, if this is true, then toplevel headings are parts,193+# not chapters.194+#latex_use_parts = False195+196+# Additional stuff for the LaTeX preamble.197+#latex_preamble = ''198+199+# Documents to append as an appendix to all manuals.200+#latex_appendices = []201+202+# If false, no module index is generated.203+#latex_domain_indices = True204+205+206+# -- Options for manual page output --------------------------------------------207+208+# One entry per manual page. List of tuples209+# (source start file, name, description, authors, manual section).210+man_pages = [211+ ('index', 'click', u'click documentation',212+ [u'Armin Ronacher'], 1)213+]214+215+intersphinx_mapping = {216+ 'http://docs.python.org/dev': None217+}added:docs/documentation.rst+98 added
1+Documenting Scripts2+===================3+4+Click makes it very easy to document your command line tools. First of5+all it automatically generates help pages for you. While these are6+currently not customizable in layout, all the texts can be changed.7+8+Help Texts9+----------10+11+Commands and options accept help arguments. In case of commands the doc12+string of the function is automatically used if provided.13+14+Simple example::15+16+ @click.command()17+ @click.option('--count', default=1, help='number of greetings')18+ @click.argument('name')19+ def hello(count, name):20+ """This script prints hello NAME COUNT times."""21+ for x in range(count):22+ print('Hello %s!' % name)23+24+And what it looks like::25+26+ $ python hello.py --help27+ Usage: hello.py [OPTIONS] NAME28+29+ This script prints hello NAME COUNT times.30+31+ Options:32+ --count=COUNT number of greetings33+ --help Show this message and exit.34+35+Arguments cannot be documented this way. This is to follow general36+convention of Unix tools to use arguments only for the most necessary37+things and to document them in the introduction text by referring to them38+by name.39+40+Meta Vars41+---------42+43+Options and parameters accept a ``metavar`` argument that can change the44+meta variable in the help page. The default version is the parameter name45+in uppercase with underscores and sometimes annotated differently if46+optional. This can be customized at all levels::47+48+ @click.command(options_metavar='<options>')49+ @click.option('--count', default=1, help='number of greetings',50+ metavar='<int>')51+ @click.argument('name', metavar='<name>')52+ def hello(count, name):53+ """This script prints hello <name> <int> times."""54+ for x in range(count):55+ print('Hello %s!' % name)56+57+Example::58+59+ Usage: hello.py <options> <name>60+61+ This script prints hello <name> <int> times.62+63+ Options:64+ --count=<int> number of greetings65+ --help Show this message and exit.66+ 67+68+Command Short Help69+------------------70+71+For commands a short help is generated. By default it's the first part72+(until the first dot) of the help message of the command unless it's too73+long. This can also be overridden::74+75+ @click.group()76+ def cli():77+ """A simple command line tool."""78+79+ @cli.command('init', short_help='init the repo')80+ def init():81+ """Initializes the repository."""82+83+ @cli.command('delete', short_help='delete the repo')84+ def delete():85+ """Deletes the repository."""86+87+And what it looks like::88+89+ Usage: repo.py [OPTIONS] COMMAND [ARGS]...90+91+ A simple command line tool.92+93+ Commands:94+ delete delete the repo95+ init init the repo96+97+ Options:98+ --help Show this message and exit.added:docs/index.rst+65 added
1+click2+=====3+4+click is a Python package for creating beautiful command line interfaces5+in a composable way with as little amount of code as necessary. It's the6+"Command Line Interface Creation Kit". It's highly configurable but comes7+with good defaults out of the box.8+9+It aims at making writing command line tools fun and quick without causing10+user frustration at not being able to implement an intended CLI API.11+12+Click in three points:13+14+- arbitrary nesting of commands15+- automatic help page generation16+- supports lazy loading of subcommands at runtime17+18+What does it look like? A simple example can be this::19+20+ import click21+22+ @click.command()23+ @click.option('--count', default=1, help='number of greetings')24+ @click.option('--name', prompt='Your name',25+ help='the person to greet', required=True)26+ def hello(count, name):27+ for x in range(count):28+ print('Hello %s!' % name)29+30+ if __name__ == '__main__':31+ hello()32+33+You can get the library directly from PyPI::34+35+ pip install click36+37+Documentation Contents38+----------------------39+40+This part of the documentation guides you through all the usage patterns41+of the library.42+43+.. toctree::44+ :maxdepth: 245+46+ why47+ quickstart48+ parameters49+ options50+ arguments51+ commands52+ prompts53+ documentation54+ setuptools55+56+API Reference57+-------------58+59+If you are looking for information on a specific function, class or60+method, this part of the documentation is for you.61+62+.. toctree::63+ :maxdepth: 264+65+ apiadded:docs/make.bat+155 added
1+@ECHO OFF2+3+REM Command file for Sphinx documentation4+5+if "%SPHINXBUILD%" == "" (6+ set SPHINXBUILD=sphinx-build7+)8+set BUILDDIR=_build9+set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .10+if NOT "%PAPER%" == "" (11+ set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%12+)13+14+if "%1" == "" goto help15+16+if "%1" == "help" (17+ :help18+ echo.Please use `make ^<target^>` where ^<target^> is one of19+ echo. html to make standalone HTML files20+ echo. dirhtml to make HTML files named index.html in directories21+ echo. singlehtml to make a single large HTML file22+ echo. pickle to make pickle files23+ echo. json to make JSON files24+ echo. htmlhelp to make HTML files and a HTML help project25+ echo. qthelp to make HTML files and a qthelp project26+ echo. devhelp to make HTML files and a Devhelp project27+ echo. epub to make an epub28+ echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter29+ echo. text to make text files30+ echo. man to make manual pages31+ echo. changes to make an overview over all changed/added/deprecated items32+ echo. linkcheck to check all external links for integrity33+ echo. doctest to run all doctests embedded in the documentation if enabled34+ goto end35+)36+37+if "%1" == "clean" (38+ for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i39+ del /q /s %BUILDDIR%\*40+ goto end41+)42+43+if "%1" == "html" (44+ %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html45+ echo.46+ echo.Build finished. The HTML pages are in %BUILDDIR%/html.47+ goto end48+)49+50+if "%1" == "dirhtml" (51+ %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml52+ echo.53+ echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.54+ goto end55+)56+57+if "%1" == "singlehtml" (58+ %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml59+ echo.60+ echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.61+ goto end62+)63+64+if "%1" == "pickle" (65+ %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle66+ echo.67+ echo.Build finished; now you can process the pickle files.68+ goto end69+)70+71+if "%1" == "json" (72+ %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json73+ echo.74+ echo.Build finished; now you can process the JSON files.75+ goto end76+)77+78+if "%1" == "htmlhelp" (79+ %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp80+ echo.81+ echo.Build finished; now you can run HTML Help Workshop with the ^82+.hhp project file in %BUILDDIR%/htmlhelp.83+ goto end84+)85+86+if "%1" == "qthelp" (87+ %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp88+ echo.89+ echo.Build finished; now you can run "qcollectiongenerator" with the ^90+.qhcp project file in %BUILDDIR%/qthelp, like this:91+ echo.^> qcollectiongenerator %BUILDDIR%\qthelp\Classy.qhcp92+ echo.To view the help file:93+ echo.^> assistant -collectionFile %BUILDDIR%\qthelp\Classy.ghc94+ goto end95+)96+97+if "%1" == "devhelp" (98+ %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp99+ echo.100+ echo.Build finished.101+ goto end102+)103+104+if "%1" == "epub" (105+ %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub106+ echo.107+ echo.Build finished. The epub file is in %BUILDDIR%/epub.108+ goto end109+)110+111+if "%1" == "latex" (112+ %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex113+ echo.114+ echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.115+ goto end116+)117+118+if "%1" == "text" (119+ %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text120+ echo.121+ echo.Build finished. The text files are in %BUILDDIR%/text.122+ goto end123+)124+125+if "%1" == "man" (126+ %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man127+ echo.128+ echo.Build finished. The manual pages are in %BUILDDIR%/man.129+ goto end130+)131+132+if "%1" == "changes" (133+ %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes134+ echo.135+ echo.The overview file is in %BUILDDIR%/changes.136+ goto end137+)138+139+if "%1" == "linkcheck" (140+ %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck141+ echo.142+ echo.Link check complete; look for any errors in the above output ^143+or in %BUILDDIR%/linkcheck/output.txt.144+ goto end145+)146+147+if "%1" == "doctest" (148+ %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest149+ echo.150+ echo.Testing of doctests in the sources finished, look at the ^151+results in %BUILDDIR%/doctest/output.txt.152+ goto end153+)154+155+:endadded:docs/Makefile+130 added
1+# Makefile for Sphinx documentation2+#3+4+# You can set these variables from the command line.5+SPHINXOPTS =6+SPHINXBUILD = sphinx-build7+PAPER =8+BUILDDIR = _build9+10+# Internal variables.11+PAPEROPT_a4 = -D latex_paper_size=a412+PAPEROPT_letter = -D latex_paper_size=letter13+ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .14+15+.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest16+17+help:18+ @echo "Please use \`make <target>' where <target> is one of"19+ @echo " html to make standalone HTML files"20+ @echo " dirhtml to make HTML files named index.html in directories"21+ @echo " singlehtml to make a single large HTML file"22+ @echo " pickle to make pickle files"23+ @echo " json to make JSON files"24+ @echo " htmlhelp to make HTML files and a HTML help project"25+ @echo " qthelp to make HTML files and a qthelp project"26+ @echo " devhelp to make HTML files and a Devhelp project"27+ @echo " epub to make an epub"28+ @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"29+ @echo " latexpdf to make LaTeX files and run them through pdflatex"30+ @echo " text to make text files"31+ @echo " man to make manual pages"32+ @echo " changes to make an overview of all changed/added/deprecated items"33+ @echo " linkcheck to check all external links for integrity"34+ @echo " doctest to run all doctests embedded in the documentation (if enabled)"35+36+clean:37+ -rm -rf $(BUILDDIR)/*38+39+html:40+ $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html41+ @echo42+ @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."43+44+dirhtml:45+ $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml46+ @echo47+ @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."48+49+singlehtml:50+ $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml51+ @echo52+ @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."53+54+pickle:55+ $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle56+ @echo57+ @echo "Build finished; now you can process the pickle files."58+59+json:60+ $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json61+ @echo62+ @echo "Build finished; now you can process the JSON files."63+64+htmlhelp:65+ $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp66+ @echo67+ @echo "Build finished; now you can run HTML Help Workshop with the" \68+ ".hhp project file in $(BUILDDIR)/htmlhelp."69+70+qthelp:71+ $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp72+ @echo73+ @echo "Build finished; now you can run "qcollectiongenerator" with the" \74+ ".qhcp project file in $(BUILDDIR)/qthelp, like this:"75+ @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Classy.qhcp"76+ @echo "To view the help file:"77+ @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Classy.qhc"78+79+devhelp:80+ $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp81+ @echo82+ @echo "Build finished."83+ @echo "To view the help file:"84+ @echo "# mkdir -p $$HOME/.local/share/devhelp/Classy"85+ @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Classy"86+ @echo "# devhelp"87+88+epub:89+ $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub90+ @echo91+ @echo "Build finished. The epub file is in $(BUILDDIR)/epub."92+93+latex:94+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex95+ @echo96+ @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."97+ @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \98+ "run these through (pdf)latex."99+100+latexpdf: latex101+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex102+ @echo "Running LaTeX files through pdflatex..."103+ make -C $(BUILDDIR)/latex all-pdf104+ @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."105+106+text:107+ $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text108+ @echo109+ @echo "Build finished. The text files are in $(BUILDDIR)/text."110+111+man:112+ $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man113+ @echo114+ @echo "Build finished. The manual pages are in $(BUILDDIR)/man."115+116+changes:117+ $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes118+ @echo119+ @echo "The overview file is in $(BUILDDIR)/changes."120+121+linkcheck:122+ $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck123+ @echo124+ @echo "Link check complete; look for any errors in the above output " \125+ "or in $(BUILDDIR)/linkcheck/output.txt."126+127+doctest:128+ $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest129+ @echo "Testing of doctests in the sources finished, look at the " \130+ "results in $(BUILDDIR)/doctest/output.txt."added:docs/options.rst+331 added
1+Options2+=======3+4+.. currentmodule:: click5+6+Adding options to commands can be accomplished by the :func:`option`7+decorator. Since options can come in various different versions there8+have a ton of parameters to configure their behavior.9+10+Basic Value Options11+-------------------12+13+The most basic option is a value option. These options accept one14+argument which is a value. If no type is provided the type of the default15+value is used. If no default value is provided the type is assumed to be16+:data:`STRING`.17+18+Example::19+20+ @click.command()21+ @click.option('--n', default=1)22+ def dots(n):23+ print('.' * n)24+25+And on the command line::26+27+ $ python dots.py --n=228+ ..29+30+In this case the option is of type :data:`INT` because the default value31+is an integer.32+33+The name of the parameter is the longest34+35+Multi Value Options36+-------------------37+38+Sometimes you have options that take more than one argument. For options39+only a fixed number of arguments is supported. This can be configured by40+the ``nargs`` parameter. The values are then stored as tuple:41+42+Example::43+44+45+ @click.command()46+ @click.option('--pos', nargs=2, type=float)47+ def findme(pos):48+ print('%s / %s' % pos)49+50+And on the command line::51+52+ $ python findme.py --pos 2.0 3.053+ 2.0 / 3.054+55+Boolean Flags56+-------------57+58+Boolean flags are options that can be enabled or disabled. This can be59+accomplished by defining two flags in one go separated by a slash (``/``)60+for enabling or disabling the option. Click always wants you to provide61+an enable and disable flag so that you can change the default later.62+63+Example::64+65+ import os66+67+ @click.command()68+ @click.option('--shout/--no-shout', default=False)69+ def info(shout):70+ rv = os.uname()[0]71+ if shout:72+ rv = rv.upper() + '!!!!111'73+ print(rv)74+75+And on the command line::76+77+ $ python info.py --shout78+ DARWIN!!!!11179+ $ python info.py --no-shout80+ Darwin81+82+If you really don't want an off-switch you can just define one and83+manually inform click that something is a flag::84+85+ import os86+87+ @click.command()88+ @click.option('--shout', is_flag=True)89+ def info(shout):90+ rv = os.uname()[0]91+ if shout:92+ rv = rv.upper() + '!!!!111'93+ print(rv)94+95+And on the command line::96+97+ $ python info.py --shout98+ DARWIN!!!!11199+100+Feature Switches101+----------------102+103+In addition to boolean flag there are also feature switches. These are104+implemented by setting multiple options to the same parameter name and by105+defining a flag value. To select a default the default flag can be set to106+`True` on the one that should be the default.107+108+Example::109+110+ import os111+112+ @click.command()113+ @click.option('--upper', 'transformation', flag_value='upper',114+ default=True)115+ @click.option('--lower', 'transformation', flag_value='lower')116+ def info(transformation):117+ print(getattr(os.uname()[0], transformation)())118+119+And on the command line::120+121+ $ python info.py --upper122+ DARWIN123+ $ python info.py --lower124+ darwin125+ $ python info.py126+ DARWIN127+128+.. _option-prompting:129+130+Prompting131+---------132+133+Sometimes you want parameters that can either be provided from the command134+line or if not, you want to ask for user input. This can be implemented135+with click by defining a prompt string:136+137+Example::138+139+ import os140+141+ @click.command()142+ @click.option('--name', prompt=True)143+ def hello(name):144+ print('Hello %s!' % name)145+146+And what it looks like::147+148+ $ python hello.py --name=John149+ Hello John!150+ $ python hello.py151+ Name: John152+ Hello John!153+154+If you are not happy with the default prompt string you can ask for155+a different one::156+157+ import os158+159+ @click.command()160+ @click.option('--name', prompt='Your name please')161+ def hello(name):162+ print('Hello %s!' % name)163+164+What it looks like::165+166+ $ python hello.py167+ Your name please: John168+ Hello John!169+170+Password Prompts171+----------------172+173+Click also supports hidden prompts and asking for confirmation. This is174+useful for password input::175+176+ @click.command()177+ @click.option('--password', prompt=True, hide_input=True,178+ confirmation_prompt=True)179+ def encrypt(password):180+ print('Encrypting password to %s' % password.encode('rot13'))181+182+What it looks like::183+184+ $ python encrypt.py185+ Password:186+ Repeat for confirmation:187+ Encrypting password to frpher188+189+Because this combination of parameters is quite common this can also be190+replaced with the :func:`password_option` decorator::191+192+ @click.command()193+ @click.password_option()194+ def encrypt(password):195+ print('Encrypting password to %s' % password.encode('rot13'))196+197+Callbacks and Eager Options198+---------------------------199+200+Sometimes you want a parameter to completely change the execution flow.201+This for instance is the case when you want to have a ``--version``202+parameter that prints out the version and then exists the application.203+204+In such cases you need two concepts: eager parameters and a callback. An205+eager parameter is a parameter that is handled before others and a206+callback is what executes after the parameter is handled. The eagerness207+is necessary so that an earlier required parameter does not produce an208+error message. For isntance if ``--version`` was not eager and a209+parameter ``--foo`` was required and defined before, you would need to210+specify it for ``--version`` to work.211+212+A callback is a function that is invoked with two parameters: the current213+:class:`Context` and the value. The context provides some useful features214+such as quitting the application and gives access to other already215+processed parameters.216+217+Here an example for a ``--version`` flag::218+219+ def print_version(ctx, value):220+ if not value:221+ return222+ print('Version 1.0')223+ ctx.exit()224+225+ @click.command()226+ @click.option('--version', is_flag=True, callback=print_version,227+ expose_value=False, is_eager=True)228+ def hello():229+ print('Hello World!')230+231+The `expose_value` parameter prevents the now pretty pointless ``version``232+parameter to be passed to the callback. If that was not specified a233+boolean would be passed to the `hello` script.234+235+What it looks like::236+237+ $ python hello.py 238+ Hello World!239+ $ python hello.py --version240+ Version 1.0241+242+Yes Parameters243+--------------244+245+For dangerous operations it's very useful to be able to ask a user for246+confirmation. This can be done by adding a boolean ``--yes`` flag and247+asking for confirmation if the user did not provide it and to fail in a248+callback::249+250+ def abort_if_false(ctx, value):251+ if not value:252+ ctx.abort()253+254+ @click.command()255+ @click.option('--yes', is_flag=True, callback=abort_if_false,256+ expose_value=False,257+ prompt='Are you sure you want to drop the db?')258+ def dropdb():259+ print('Dropped all tables!')260+261+And what it looks like on the command line::262+263+ $ python dropdb.py264+ Are you sure you want to drop the db? [yN]: n 265+ Aborted!266+ $ python dropdb.py --yes267+ Dropped all tables!268+269+Because this combination of parameters is quite common this can also be270+replaced with the :func:`confirmation_option` decorator::271+272+ @click.command()273+ @click.confirmation_option('Are you sure you want to drop the db?')274+ def dropdb():275+ print('Dropped all tables!')276+277+Values from Environment Variables278+---------------------------------279+280+A very useful feature of click is the ability to accept parameters from281+environment variables in addition to regular parameters. This allows282+tools to be much easier automated. For instance you might want to pass283+the config file as ``--config`` parameter but also support exporting a284+``TOOL_CONFIG=hello.cfg`` key / value pair for a nicer development285+experience.286+287+This is supported by click in two ways. One is to automatically build288+environment variables which is supported for options only. To enable this289+feature the ``auto_envvar_prefix`` parameter needs to be passed to the290+script that is invoked. Each command and parameter is then added as291+underscore separated variable in uppercase. So if you have a subcommand292+called ``foo`` taking an option called ``bar`` and the prefix is293+``MY_TOOL`` then the variable is ``MY_TOOL_FOO_BAR``.294+295+Example usage::296+297+ @click.command()298+ @click.option('--username')299+ def greet(username):300+ print('Hello %s!' % username)301+302+ if __name__ == '__main__':303+ greet(auto_envvar_prefix='GREETER')304+305+And from the command line::306+307+ $ export GREETER_USERNAME=john308+ $ python greet.py309+ Hello john!310+311+The second option is to manually pull values in from specific environment312+variables by defining the name of the environment variable on the option.313+314+Example usage::315+316+ @click.command()317+ @click.option('--username', envvar='USERNAME')318+ def greet(username):319+ print('Hello %s!' % username)320+321+ if __name__ == '__main__':322+ greet()323+324+And from the command line::325+326+ $ export USERNAME=john327+ $ python greet.py328+ Hello john!329+330+In that case it can also be a list of different environment variables331+where the first one is picked.added:docs/parameters.rst+108 added
1+Parameters2+==========3+4+.. currentmodule:: click5+6+Click supports two types of parameters for scripts: options and arguments.7+There is generally some confusion among authors of command line scripts8+when to use which so here is a quick overview of the differences. As the9+name indicates an option is optional. While arguments can be optional10+within reason they are much more restricted in how they can be optional.11+12+To help you pick when to use what the recommendation is to use arguments13+exclusively for things like going to subcommands or input filenames /14+URLs and have everything else be an option instead.15+16+Differences17+-----------18+19+Arguments can do less than options. The following features are only20+available for options:21+22+* automatic prompting for missing input23+* act as flags (boolean or otherwise)24+* option values can be pulled from environment variables, arguments can not25+* options are fully documented in the help page, arguments are not26+ (this is intentional as arguments might be too specific to be27+ automatically documented)28+29+On the other hand arguments unlike options can accept an arbitrary number30+of arguments. Options can strictly ever only accept a fixed number of31+arguments (defaults to 1).32+33+Parameter Types34+---------------35+36+Parameters can be of different types. Types can be implemented with37+different behavior and some are supported out of the box:38+39+``str`` / :data:`click.STRING`:40+ The default parameter type which indicates unicode strings.41+42+``int`` / :data:`click.INT`:43+ A parameter that only accepts integers.44+45+``float`` / :data:`click.FLOAT`:46+ A parameter that only accepts floating point values.47+48+``bool`` / :data:`click.BOOL`:49+ A parameter that accepts boolean values. This is automatically used50+ for boolean flags. If used with string values ``1``, ``yes``, ``y``51+ and ``true`` convert to `True` and ``0``, ``no``, ``n`` and ``false``52+ convert to `False`.53+54+:class:`click.File`:55+ A parameter that is an opened file. It can be opened for reading or56+ writing.57+58+Custom parameter types can be implemented by subclassing59+:class:`click.ParamType`. For simple cases passing a python function that60+failes with a `ValueError` is also supported though discouraged.61+62+Parameter Names63+---------------64+65+Parameters (both options and arguments) accept a number of positional66+arguments which are the parameter declarations. Each string string with a67+single dash is added as short argument, each string starting with a double68+dash as long one. If a string is added without any dashes it's the69+internal parameter name which is also used as variable name.70+71+If a parameter does not have a name without dashes added one is generated72+automatically by taking the longest argument and converting all dashes to73+underscores. So for an option with ``('-f', '--foo-bar')`` the parameter74+name is `foo_bar`. For an option with ``('-x',)`` the parameter is `x`.75+For an option with ``('-f', '--filename', 'dest')`` the parameter is76+called `dest`.77+78+Implementing Custom Types79+-------------------------80+81+To implement a custom type you need to subclass the :class:`ParamType`82+class. Types can be invoked with or without context and parameter object83+which is why they need to be able to deal with this.84+85+The following code implements an integer type that accepts hex, octal86+numbers in addition to normal integers and converts them into regular87+integers::88+89+ import click90+91+ class BasedIntParamType(click.ParamType):92+ name = 'integer'93+94+ def convert(self, value, param, ctx):95+ try:96+ if value[:2].lower() == '0x':97+ return int(value[2:], 16)98+ elif value[:1] == '0':99+ return int(value, 8)100+ return int(value, 10)101+ except ValueError:102+ self.fail('%s is not a valid integer' % value, param, ctx)103+104+ BASED_INT = BasedIntParamType()105+106+As you can see a subclass needs to implement the :meth:`ParamType.convert`107+method and optionally provide the :attr:`ParamType.name` attribute. The108+latter can be used for documentation purposes.added:docs/prompts.rst+47 added
1+User Input Prompts2+==================3+4+.. currentmodule:: click5+6+Click supports prompts in two different places. One is automated prompts7+when the parameter handling happens. The second option 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+Option Prompts15+--------------16+17+Option prompts are integrated into the option interface. See18+:ref:`option-prompting` for more information. Internally it19+automatically calls into :func:`prompt` or :func:`confirm` as necessary.20+21+Input Prompts22+-------------23+24+To manually ask for user input you can use the :func:`prompt` function.25+By default it accepts any unicode string but you can ask for any other26+type. For instance you can ask for a valid integer::27+28+ value = click.prompt('Please enter a valid integer', type=int)29+30+The type is also automatically detected if a default is provided. The31+following for instance will only accept floats::32+33+ value = click.prompt('Please enter a number', default=42.0)34+35+Confirmation Prompts36+--------------------37+38+To ask a user if he wants to continue with an action the :func:`confirm`39+function comes in handy. By default it returns the result of the prompt40+as boolean value::41+42+ if click.confirm('Do you want to continue?'):43+ print('Well done!')44+45+There is also the option to make it automatically abort the execution::46+47+ click.confirm('Do you want to continue?', abort=True)added:docs/quickstart.rst+110 added
1+Quickstart2+==========3+4+.. currentmodule:: click5+6+You can get the library directly from PyPI::7+8+ pip install click9+10+Basic Concepts11+--------------12+13+Click is based on declaring commands through decorators. Internally there14+is a non-decorator interface for advanced use cases but it's discouraged15+for high-level usage.16+17+A function becomes a click command line tool by decorating it through18+:func:`click.command`. In the most simple version just decorating a19+function with this decorator will make it into a callable script::20+21+ import click22+23+ @click.command()24+ def hello():25+ print('Hello World!')26+27+What's happening is that the decorator converts the function into a28+:class:`Command` which then can be invoked::29+30+ if __name__ == '__main__':31+ hello()32+33+Nesting Commands34+----------------35+36+Commands can be attached to other commands of type :class:`Group`. This37+allows arbitrary nesting of scripts. As an example here is a script that38+implements two commands for managing databases::39+40+ import click41+42+ @click.group()43+ def cli():44+ pass45+46+ @click.command()47+ def initdb():48+ print('Initialized the database')49+50+ @click.command()51+ def dropdb():52+ print('Initialized the database')53+54+ cli.add_command(initdb)55+ cli.add_command(dropdb)56+57+ if __name__ == '__main__':58+ cli()59+60+As you can see the :func:`group` decorator works like the :func:`command`61+decorator but creates a :class:`Group` object instead which can be given62+multiple subcommands that can be attached with63+:meth:`Group.add_command`.64+65+For simple scripts it's also possible to automatically attach and create a66+command by using the :meth:`Group.command` decorator instead. The above67+script can be written like this then::68+69+ import click70+71+ @click.group()72+ def cli():73+ pass74+75+ @cli.command()76+ def initdb():77+ print('Initialized the database')78+79+ @cli.command()80+ def dropdb():81+ print('Initialized the database')82+83+ if __name__ == '__main__':84+ cli()85+86+Adding Parameters87+-----------------88+89+To add parameters the :func:`option` and :func:`argument` decorators::90+91+ import click92+93+ @click.command()94+ @click.option('--count', default=1, help='number of greetings')95+ @click.argument('name')96+ def hello(count, name):97+ for x in range(count):98+ print('Hello %s!' % name)99+100+ if __name__ == '__main__':101+ hello()102+103+What it looks like::104+105+ $ python hello.py106+ Usage: hello.py [OPTIONS] NAME107+108+ Options:109+ --count=COUNT number of greetings110+ --help Show this message and exit.added:docs/setuptools.rst+76 added
1+Usage with Setuptools2+=====================3+4+When writing command line utilities it's recommended to write them as5+modules that are distributed with setuptools instead of using UNIX6+shebangs. There are a bunch of reasons for this.7+8+The first one is that setuptools automatically generates executable9+wrapeprs for Windows so your command line utilies work on Windows too.10+11+The second reason is that setuptools scripts work with virtualenv on UNIX12+without the virtualenv having to be activated. This is a very useful13+concept which allows you to bundle your scripts with all requirements into14+a virtualenv.15+16+Introduction17+------------18+19+All you need to do to bundle your scripts with setuptools is your script20+in a python package and a ``setup.py`` file.21+22+Imagine this layout::23+24+ yourpackage/25+ cli.py26+ setup.py27+28+Contents of ``cli.py``::29+30+ import click31+32+ @click.command()33+ def cli():34+ """Example script."""35+ print('Hello World!')36+37+Contents of ``setup.py``::38+39+ from setuptools import setup, find_packages40+41+ setup(42+ name='yourpackage',43+ version='0.1',44+ packages=find_packages(),45+ include_package_data=True,46+ install_requires=[47+ 'Click',48+ ],49+ entry_points='''50+ [console_scripts]51+ yourscript=yourpackage.cli:cli52+ ''',53+ )54+55+The magic is in the ``entry_points`` parameter. Below ``console_scripts``56+each line identifies one console script. The first part before the equals57+sign (``=``) is the name of the script that should be generate, the second58+part is the import path followed by a colon (``:``) with the click59+command.60+61+That's it.62+63+Testing The Script64+------------------65+66+To test the script you can make a new virtualenv and then install your67+package::68+69+ $ virtualenv venv70+ $ . venv/bin/activate71+ $ pip install --editable .72+73+Afterwards your command should be available::74+75+ $ yourscript76+ Hello World!added:docs/why.rst+43 added
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: beacuse there is not a single command8+line utility for Python out there which ticks the following boxes:9+10+* is lazily composable without restrictions11+* fully follows the UNIX command line conventions12+* supports loading values from environment variables out of the box13+* supports for prompting of custom values14+* is fully nestable and composable15+* works the same on Python 2 and 316+* supports file handling out of the box17+18+There are many alternatives to click and you can have a look at them if19+you enjoy them better. The obvious ones are ``optparse`` and ``argparse``20+from the standard library.21+22+click is actually implemented as a wrapper around ``optparse`` and does23+not implement any parsing itself. The reason it's not based on24+``argparse`` is that ``argparse``\'s design does not allow proper nesting25+of commands by design and has some deficiencies when it comes to POSIX26+compliant argument handling.27+28+In case ``optparse`` ever gets deprecated and removed from Python,29+``click`` will ship a version of it.30+31+Click is designed to be fun to work with and at the same time not stand in32+your way. It's not overly flexible at the same time either. Currently33+for instance it does not allow you to customize the help pages too much.34+This is intentional because click is desigend to allow you to nest command35+line utilities. The idae is that you can have a system that works36+together with another system by tacking two click instances together and37+they will continue working as they should.38+39+Too much customizability would break this promise.40+41+Click was written to support the `Flask <http://flask.pocoo.org/>`_42+microframework ecosystem because no tool could provide it with the43+functionality it needed.added:examples/repo/repo.py+51 added
1+import click2+3+4+@click.group()5+@click.option('--repo-home', envvar='REPO_HOME')6+def cli(repo_home):7+ """Repo is a command line tool that showcases how to build complex8+ command line interfaces with Click.9+ """10+ print('Repo home: %s' % repo_home)11+12+13+@cli.command()14+@click.argument('src')15+@click.argument('dest', required=False)16+@click.option('--shallow/--deep', default=False,17+ help='Makes a checkout shallow or deep. Deep by default.')18+def clone(src, dest, shallow):19+ """Clones a repository.20+21+ This will clone the repository at SRC into the folder DEST. If DEST22+ is not provided this will automatically use the last path component23+ of SRC and create that folder.24+ """25+ print('Source: %s' % src)26+ print('Destination: %s' % dest)27+ print('Shallow: %s' % shallow)28+29+30+@cli.command()31+@click.confirmation_option()32+def delete():33+ """Deletes a repository.34+35+ This will throw away the current repository.36+ """37+ print('Deleted')38+39+40+@cli.command()41+@click.option('--username', prompt=True, required=True)42+@click.option('--email', prompt='E-Mail', required=True)43+@click.password_option()44+def setuser(username, email, password):45+ """Sets the user credentials.46+47+ This will override the current user config.48+ """49+ print('Username: %s' % username)50+ print('E-Mail: %s' % email)51+ print('Password: %s' % ('*' * len(password)))added:examples/repo/setup.py+15 added
1+from setuptools import setup2+3+setup(4+ name='repo',5+ version='0.1',6+ py_modules=['repo'],7+ include_package_data=True,8+ install_requires=[9+ 'Click',10+ ],11+ entry_points='''12+ [console_scripts]13+ repo=repo:cli14+ ''',15+)added:.gitignore+7 added
1+.DS_Store2+*.pyc3+*.pyo4+*.egg-ignore5+dist6+build7+docs/_buildadded:click.py+1533 added
1+# -*- coding: utf-8 -*-2+"""3+ click4+ ~~~~~5+6+ click is a simple Python module that wraps the stdlib's optparse to make7+ writing command line scripts fun. Unlike other modules it's based around8+ a simple API that does not come with too much magic and is composable.9+10+ In case optparse ever goes away from the stdlib it will be shipped by11+ this module.12+13+ :copyright: (c) 2014 by Armin Ronacher.14+ :license: BSD, see LICENSE for more details.15+"""16+import os17+import sys18+import codecs19+import inspect20+import getpass21+import optparse22+import textwrap23+import fcntl24+import termios25+import struct26+from itertools import chain27+28+29+PY2 = sys.version_info[0] == 230+if PY2:31+ text_type = unicode32+ bytes = str33+34+ def open_stream(filename, mode='r', encoding=None, errors='strict'):35+ if filename != '-':36+ if encoding is not None:37+ return codecs.open(filename, mode, encoding, errors), True38+ return open(filename, mode), True39+ if 'w' in mode:40+ f = sys.stdout41+ if encoding is not None:42+ f = _wrap_stream_for_codec(f, encoding, errors)43+ else:44+ f = sys.stdin45+ if 'b' not in mode:46+ if encoding is None:47+ encoding = sys.stdin.encoding48+ f = _wrap_stream_for_codec(f, encoding, errors)49+ return f, False50+else:51+ text_type = str52+ raw_input = input53+54+ def open_stream(filename, mode='r', encoding=None, errors='strict'):55+ if filename != '-':56+ return open(filename, mode, encoding=encoding, errors=errors), True57+ if 'w' in mode:58+ f = sys.stdout59+ if encoding is not None or 'b' in mode:60+ f = f.buffer.raw61+ if encoding is not None:62+ f = _wrap_stream_for_codec(f, encoding, errors)63+ else:64+ f = sys.stdin65+ if 'b' in mode:66+ f = f.buffer.raw67+ if encoding is not None:68+ f = _wrap_stream_for_codec(f, encoding, errors)69+ return f, False70+71+72+def get_terminal_size():73+ """Returns the current size of the terminal as tuple in the form74+ ``(width, height)`` in columns and rows.75+ """76+ def ioctl_gwinsz(fd):77+ try:78+ cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))79+ except Exception:80+ return81+ return cr82+83+ cr = ioctl_gwinsz(0) or ioctl_gwinsz(1) or ioctl_gwinsz(2)84+ if not cr:85+ try:86+ fd = os.open(os.ctermid(), os.O_RDONLY)87+ try:88+ cr = ioctl_gwinsz(fd)89+ finally:90+ os.close(fd)91+ except Exception:92+ pass93+ if not cr:94+ cr = (os.environ.get('LINES', 25),95+ os.environ.get('COLUMNS', 80))96+ return int(cr[1]), int(cr[0])97+98+99+class TextWrapper(textwrap.TextWrapper):100+101+ def _cutdown(self, ucstr, space_left):102+ l = 0103+ for i in xrange(len(ucstr)):104+ l += len(ucstr[i])105+ if space_left < l:106+ return (ucstr[:i], ucstr[i:])107+ return ucstr, ''108+109+ def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):110+ space_left = max(width - cur_len, 1)111+112+ if self.break_long_words:113+ cut, res = self._cutdown(reversed_chunks[-1], space_left)114+ cur_line.append(cut)115+ reversed_chunks[-1] = res116+ elif not cur_line:117+ cur_line.append(reversed_chunks.pop())118+119+ def fill_paragraphs(self, text):120+ # Remove unnecessary newlines so that we can fill properly121+ p = []122+ buf = []123+ for line in text.splitlines():124+ if not line:125+ p.append(' '.join(buf))126+ buf = []127+ else:128+ buf.append(line)129+ if buf:130+ p.append(' '.join(buf))131+132+ rv = []133+ for text in p:134+ rv.append(self.fill(text))135+ return '\n\n'.join(rv)136+137+138+def _wrap_stream_for_codec(f, encoding=None, errors='strict'):139+ if encoding is None:140+ encoding = 'utf-8'141+ info = codecs.lookup(encoding)142+ f = codecs.StreamReaderWriter(f, info.streamreader,143+ info.streamwriter,144+ errors)145+ f.encoding = encoding146+ return f147+148+149+def echo(message=None, file=None):150+ if file is None:151+ file = sys.stdout152+ if message:153+ if PY2 and isinstance(message, text_type):154+ message = message.encode(file.encoding)155+ file.write(message)156+ file.write('\n')157+ file.flush()158+159+160+class Context(object):161+ """The context is a special internal object that holds state relevant162+ for the script execution at every single level. It's normally invisible163+ to commands unless they opt-in to getting access to it.164+165+ The context is useful as it can pass internal objects around and can166+ control special execution features such as reading data from167+ environment variables.168+169+ A context can be used as context manager in which case it will call170+ :meth:`close` on teardown.171+172+ :param command: the command class for this context.173+ :param parent: the parent context.174+ :param info_name: the info name for this invokation. Generally this175+ is the most descriptive name for the script or176+ command. For the toplevel script is is usually177+ the name of the script, for commands below it it's178+ the name of the script.179+ :param obj: an arbitrary object of user data.180+ :param auto_envvar_prefix: the prefix to use for automatic environment181+ variables. If this is `None` then reading182+ from environment variables is disabled. This183+ does not affect manually set environment184+ variables which are always read.185+ """186+187+ def __init__(self, command, parent=None, info_name=None, obj=None,188+ auto_envvar_prefix=None):189+ #: the parent context or `None` if none exists.190+ self.parent = parent191+ #: the :class:`Command` for this context.192+ self.command = command193+ #: the descriptive information name194+ self.info_name = info_name195+ #: the parsed parameters except if the value is hidden in which196+ #: case it's not remembered.197+ self.params = {}198+ #: the leftover arguments.199+ self.args = []200+ #: this flag indicates if a subcommand is going to be executed.201+ #: a group callback can use this information to figure out if it's202+ #: being executed directly or because the execution flow passes203+ #: onwards to a subcommand. By default it's `None` but it can be204+ #: the name of the subcommand to execute.205+ self.invoked_subcommand = None206+ if obj is None and parent is not None:207+ obj = parent.obj208+ #: the user object stored.209+ self.obj = obj210+211+ # If there is no envvar prefix yet, but the parent has one and212+ # the command on this level has a name, we can expand the envvar213+ # prefix automatically.214+ if auto_envvar_prefix is None:215+ if parent is not None \216+ and parent.auto_envvar_prefix is not None and \217+ self.info_name is not None:218+ auto_envvar_prefix = '%s_%s' % (parent.auto_envvar_prefix,219+ self.info_name.upper())220+ else:221+ self.auto_envvar_prefix = auto_envvar_prefix.upper()222+ self.auto_envvar_prefix = auto_envvar_prefix223+224+ self._parser = command._make_parser(self)225+ self._close_callbacks = []226+227+ def __enter__(self):228+ return self229+230+ def __exit__(self, exc_type, exc_value, tb):231+ self.close()232+233+ def call_on_close(self, f):234+ """This decorator remembers a function as callback that should be235+ executed when the context tears down. This is most useful to bind236+ resource handling to the script execution. For instance file objects237+ opened by the :class:`File` type will register their close callbacks238+ here.239+240+ :param f: the function to execute on teardown.241+ """242+ self._close_callbacks.append(f)243+ return f244+245+ def close(self):246+ """Invokes all close callbacks."""247+ for cb in self._close_callbacks:248+ cb()249+ self._close_callbacks = []250+251+ @property252+ def command_path(self):253+ """The computed command path. This is used for the ``usage``254+ information on the help page. It's automatically created by255+ combining the info names of the chain of contexts to the root.256+ """257+ rv = ''258+ if self.info_name is not None:259+ rv = self.info_name260+ if self.parent is not None:261+ rv = self.parent.command_path + ' ' + rv262+ return rv.lstrip()263+264+ def find_root(self):265+ """Finds the outermost context."""266+ node = self267+ while node.parent is not None:268+ node = node.parent269+ return node270+271+ def fail(self, message):272+ """Aborts the execution of the program with a specific error273+ message.274+275+ :param message: the error message to fail with.276+ """277+ raise UsageError(message, self)278+279+ def abort(self):280+ """Aborts the script."""281+ raise Abort()282+283+ def exit(self, code=0):284+ """Exits the application with a given exit code."""285+ sys.exit(code)286+287+ def format_usage(self):288+ """Helper method to get formatted usage string for the current289+ context and command.290+ """291+ return self._parser.get_usage()292+293+ def format_help(self):294+ """Helper method to get formatted help page for the current295+ context and command.296+ """297+ return self._parser.format_help().rstrip()298+299+300+class UsageError(Exception):301+ """An internal exception that signals a usage error. This typically302+ aborts any further handling.303+ """304+305+ def __init__(self, message, ctx=None):306+ if PY2:307+ Exception.__init__(self, message.encode('utf-8'))308+ else:309+ Exception.__init__(self, message)310+ self.message = message311+ self.ctx = ctx312+313+314+class Abort(Exception):315+ """An internal signalling exception that signals click to abort."""316+317+318+class _SimplifiedFormatter(optparse.IndentedHelpFormatter):319+320+ def __init__(self):321+ optparse.IndentedHelpFormatter.__init__(self,322+ width=min(get_terminal_size()[0], 80) - 2)323+ self.default_tag = ''324+325+ def format_usage(self, usage):326+ prefix = 'Usage: '327+ indent = len(prefix)328+ text_width = self.width - indent329+ return '%s%s\n' % (prefix, TextWrapper(330+ text_width, initial_indent='',331+ subsequent_indent=' ' * indent,332+ replace_whitespace=False).fill(usage))333+334+ def _format_text(self, text):335+ text_width = self.width - self.current_indent336+ indent = ' ' * self.current_indent337+338+ return TextWrapper(text_width,339+ initial_indent=indent,340+ subsequent_indent=indent,341+ replace_whitespace=False).fill_paragraphs(text)342+343+ def format_description(self, description):344+ if not description:345+ return ''346+ self.indent()347+ rv = self._format_text(description) + '\n'348+ self.dedent()349+ return rv350+351+ def format_option_strings(self, option):352+ rv = optparse.IndentedHelpFormatter.format_option_strings(self, option)353+ if hasattr(option, '_negative_version'):354+ rv += ' / ' + optparse.IndentedHelpFormatter.format_option_strings(355+ self, option._negative_version)356+ return rv357+358+359+class _SimplifiedOptionParser(optparse.OptionParser):360+361+ def __init__(self, ctx, **extra):362+ usage = ctx.command_path + ' ' + ctx.command.options_metavar363+ optparse.OptionParser.__init__(self, prog=ctx.command_path,364+ usage=usage,365+ add_help_option=False,366+ formatter=_SimplifiedFormatter(),367+ **extra)368+ self.__ctx = ctx369+370+ def expand_prog_name(self, s):371+ return s372+373+ def format_option_help(self, formatter):374+ rv = optparse.OptionParser.format_option_help(self, formatter)375+ extra_help = self.__ctx.command._format_extra_help(self.__ctx)376+ if extra_help:377+ rv = '%s\n\n%s' % (extra_help, rv)378+ return rv379+380+ def error(self, msg):381+ raise UsageError(msg, self.__ctx)382+383+384+class Command(object):385+ """Commands are the basic building block of command line interfaces in386+ click. A basic command handles command line parsing and might dispatch387+ more parsing to commands nested blow it.388+389+ :param name: the name of the command to use unless a group overrides it.390+ :param callback: the callback to invoke. This is optional.391+ :param params: the parameters to register with this command. This can392+ be either :class:`Option` or :class:`Argument` objects.393+ :param pass_context: if this is set to `True` then the callback will394+ be passed the context as first argument.395+ :param pass_params: if this is set to `True` then the callback will396+ be passed all non hidden parameters as keyword397+ arguments.398+ :param help: the help string to use for this command.399+ :param short_help: the short help to use for this command. This is400+ shown on the command listing of the parent command.401+ :param add_help_option: by default each command registers a ``--help``402+ option. This can be disabled by this parameter.403+ """404+ allow_extra_args = False405+406+ def __init__(self, name, callback=None, params=None, pass_context=False,407+ pass_params=True, help=None, short_help=None,408+ options_metavar='[OPTIONS]', add_help_option=True):409+ #: the name the command things it has. Upon registering a command410+ #: on a :class:`Group` the group will default the command name411+ #: with this information. You should instead use the412+ #: :class:`Context`\'s :attr:`~Context.info_name` attribute.413+ self.name = name414+ #: the callback to execute when the command fires. This might be415+ #: `None` in which case nothing happens.416+ self.callback = callback417+ #: the list of parameters for this command in the order they418+ #: should show up in the help page and execute. Eager parameters419+ #: will automatically be handled before non eager ones.420+ self.params = params or []421+ self.pass_context = pass_context422+ self.pass_params = pass_params423+ self.help = help424+ self.options_metavar = options_metavar425+ if short_help is None and help:426+ short_help = help.split('.')[0].strip()427+ if len(short_help) > 45:428+ short_help = None429+ elif short_help:430+ short_help = short_help[0].lower() + short_help[1:] + '.'431+ self.short_help = short_help432+ if add_help_option:433+ help_option()(self)434+435+ def iter_params_for_processing(self):436+ """This returns an iterator over all attached parameters in the437+ order of processing. This iterator returns all eager parameters438+ first, followed by all non-eager parameters.439+ """440+ for param in self.params:441+ if param.is_eager:442+ yield param443+ for param in self.params:444+ if not param.is_eager:445+ yield param446+447+ def _make_parser(self, ctx):448+ parser = _SimplifiedOptionParser(ctx, description=self.help)449+ for param in self.params:450+ param._add_to_parser(parser, ctx)451+ return parser452+453+ def _format_extra_help(self, ctx):454+ pass455+456+ def make_context(self, info_name, args, parent=None, **extra):457+ """This function when given an info name and arguments will kick458+ off the parsing and create a new :class:`Context`. It does not459+ invoke the actual command callback though.460+461+ :param info_name: the info name for this invokation. Generally this462+ is the most descriptive name for the script or463+ command. For the toplevel script is is usually464+ the name of the script, for commands below it it's465+ the name of the script.466+ :param args: the arguments to parse as list of strings.467+ :param parent: the parent context if available.468+ :param extra: extra keyword arguments forwarded to the context469+ constructor.470+ """471+ ctx = Context(self, info_name=info_name, parent=parent, **extra)472+ opts, args = ctx._parser.parse_args(args=args)473+ opts = opts.__dict__474+475+ for param in ctx.command.iter_params_for_processing():476+ value, args = param.handle_parse_result(ctx, opts, args)477+478+ if args and not self.allow_extra_args:479+ ctx.fail('Got unexpected extra argument%s (%s)'480+ % (len(args) != 1 and 's' or '', ' '.join(args)))481+482+ ctx.args = args483+484+ return ctx485+486+ def invoke(self, ctx):487+ """Given a context, this invokes the attached callback (if it exists)488+ in the right way.489+ """490+ func_args = self.pass_context and (ctx,) or ()491+ func_kwargs = self.pass_params and ctx.params or {}492+ if self.callback is not None:493+ self.callback(*func_args, **func_kwargs)494+495+ def main(self, args=None, prog_name=None, **extra):496+ """This is the way to invoke a script with all the bells and497+ whistles as command line application. This will always terminate498+ the application after calling. If this is not wanted, ``SystemExit``499+ needs to be caught.500+501+ This method is also available by directly calling the instance of502+ a :class:`Command`.503+504+ :param args: the arguments that should be used for parsing. If not505+ provided, ``sys.argv[1:]`` is used.506+ :param prog_name: the program name that should be used. By default507+ the progam name is constructed by taking the file508+ name from ``sys.argv[0]``.509+ :param extra: extra keyword arguments are forwarded to the context510+ constructor.511+ """512+ if args is None:513+ args = sys.argv[1:]514+ else:515+ args = list(args)516+ if prog_name is None:517+ prog_name = os.path.basename(sys.argv and sys.argv[0] or __file__)518+ try:519+ try:520+ with self.make_context(prog_name, args, **extra) as ctx:521+ self.invoke(ctx)522+ ctx.exit()523+ except (EOFError, KeyboardInterrupt):524+ echo(file=sys.stderr)525+ raise Abort()526+ except UsageError as e:527+ if e.ctx is not None:528+ echo(e.ctx.format_usage(), file=sys.stderr)529+ echo('Error: %s' % e.message, file=sys.stderr)530+ sys.exit(2)531+ except Abort:532+ echo('Aborted!', file=sys.stderr)533+ sys.exit(1)534+535+ def __call__(self, *args, **kwargs):536+ """Alias for :meth:`main`."""537+ return self.main(*args, **kwargs)538+539+540+class MultiCommand(Command):541+ """A multi command is the basic implementation of a command that542+ dispatches to subcommands. The most common version is the543+ :class:`Command`.544+545+ :param invoke_without_command: this controls how the multi command itself546+ is invoked. By default it's only invoked547+ if a subcommand is provided.548+ :param no_args_is_help: this controls what happens if no arguments are549+ provided. This option is enabled by default if550+ `invoke_without_command` is disabled or disabled551+ if it's enabled. If enabled this will add552+ ``--help`` as argument if no arguments are553+ passed.554+ :param subcommand_metavar: the string that is used in the documentation555+ to indicate the subcommand place.556+ """557+ allow_extra_args = True558+559+ def __init__(self, name=None, invoke_without_command=False,560+ no_args_is_help=None,561+ subcommand_metavar='COMMAND [ARGS]...', **attrs):562+ Command.__init__(self, name, **attrs)563+ if no_args_is_help is None:564+ no_args_is_help = not invoke_without_command565+ self.no_args_is_help = no_args_is_help566+ self.invoke_without_command = invoke_without_command567+ self.subcommand_metavar = subcommand_metavar568+569+ def _make_parser(self, ctx):570+ parser = Command._make_parser(self, ctx)571+ parser.usage += ' ' + self.subcommand_metavar572+ parser.disable_interspersed_args()573+ return parser574+575+ def _format_extra_help(self, ctx):576+ commands = self.list_commands()577+ if not commands:578+ return579+580+ longest = len(sorted(commands, key=len)[-1])581+582+ subcommand_info = []583+ for subcommand in self.list_commands():584+ cmd = self.get_command(ctx, subcommand)585+ help = cmd.short_help or ''586+ subcommand_info.append(' %-*s %s' % (longest, subcommand, help))587+588+ return 'Commands:\n%s' % '\n'.join(subcommand_info)589+590+ def make_context(self, info_name, args, parent=None, **extra):591+ # Multi-commands invoked without any arguments is a shortcut to592+ # invoking it with --help unless supresssed.593+ if not args and self.no_args_is_help:594+ args = ['--help']595+ return Command.make_context(self, info_name, args, parent, **extra)596+597+ def invoke(self, ctx):598+ if not ctx.args:599+ if self.invoke_without_command:600+ return Command.invoke(self, ctx)601+ ctx.fail('Missing command')602+ cmd_name = ctx.args[0]603+604+ cmd = self.get_command(ctx, cmd_name)605+ if cmd is None:606+ ctx.fail('No such command "%s"' % cmd_name)607+608+ # Whenever we dispatch to a subcommand we also invoke the regular609+ # callback. This is done so that parameters can be handled.610+ ctx.invoked_subcommand = cmd_name611+ Command.invoke(self, ctx)612+613+ with cmd.make_context(cmd_name, ctx.args[1:], parent=ctx) as cmd_ctx:614+ return cmd.invoke(cmd_ctx)615+616+ def get_command(self, ctx, cmd_name):617+ """Given a context and a command name, this returns a618+ :class:`Command` object if it exists or returns `None`.619+ """620+ raise NotImplementedError()621+622+ def list_commands(self):623+ """Returns a list of subcommand names in the order they should624+ appear.625+ """626+ return []627+628+629+class Group(MultiCommand):630+ """A group allows a command to have subcommands attached. This is the631+ most common way to implement nesting in click.632+633+ :param commands: a dictionary of commands.634+ """635+636+ def __init__(self, name=None, commands=None, **attrs):637+ MultiCommand.__init__(self, name, **attrs)638+ #: the registered subcommands by their exported names.639+ self.commands = commands or {}640+641+ def add_command(self, cmd, name=None):642+ """Registers another :class:`Command` with this group. If the name643+ is not provided, the name of the command is used.644+ """645+ name = name or cmd.name646+ if name is None:647+ raise TypeError('Command has no name.')648+ self.commands[name] = cmd649+650+ def command(self, *args, **kwargs):651+ """A shortcut decorator for declaring and attaching a command to652+ the group. This takes the same arguments as :func:`command` but653+ immediately registers the created command with this instance by654+ calling into :meth:`add_command`.655+ """656+ def decorator(f):657+ cmd = command(*args, **kwargs)(f)658+ self.add_command(cmd)659+ return cmd660+ return decorator661+662+ def get_command(self, ctx, cmd_name):663+ return self.commands.get(cmd_name)664+665+ def list_commands(self):666+ return sorted(self.commands)667+668+669+class ParamType(object):670+ """Helper for converting values through types. The following is671+ necessary for a valid type:672+673+ * it needs a name674+ * it needs to pass through None unchanged675+ * it needs to convert from a string676+ * it needs to convert its result type through unchanged677+ (eg: needs to be idempotent)678+ * it needs to be able to deal with param and context being none.679+ This can be the case when the object is used with prompt680+ inputs.681+ """682+683+ #: the descriptive name of this type684+ name = None685+686+ def __call__(self, value, param=None, ctx=None):687+ if value is not None:688+ return self.convert(value, param, ctx)689+690+ def convert(self, param, ctx, value):691+ """Converts the value. This is not invoked for values that are692+ `None` (the missing value).693+ """694+ return value695+696+ def fail(self, message, param=None, ctx=None):697+ """Helper method to fail with an invalid value message."""698+ if param is None:699+ message = 'Invalid value: %s' % message700+ else:701+ message = 'Invalid value for %s: %s' % (param.name, message)702+ raise UsageError(message, ctx=ctx)703+704+705+class FuncParamType(ParamType):706+707+ def __init__(self, func):708+ self.name = func.__name__709+ self.func = func710+711+ def convert(self, value, param, ctx):712+ try:713+ return self.func(value)714+ except ValueError:715+ try:716+ value = unicode(value)717+ except UnicodeError:718+ value = str(value).decode('utf-8', 'replace')719+ self.fail(value, param, ctx)720+721+722+class StringParamType(ParamType):723+ name = 'string'724+725+ def convert(self, value, param, ctx):726+ if isinstance(value, bytes):727+ try:728+ if sys.stdin.encoding is not None:729+ value = value.decode(sys.stdin.encoding)730+ except UnicodeError:731+ try:732+ value = value.decode(sys.getfilesystemencoding())733+ except UnicodeError:734+ value = value.decode('utf-8', 'replace')735+ return value736+ return value737+738+ def __repr__(self):739+ return 'STRING'740+741+742+class IntParamType(ParamType):743+ name = 'integer'744+745+ def convert(self, value, param, ctx):746+ try:747+ return int(value)748+ except ValueError:749+ self.fail('%s is not a valid integer' % value, param, ctx)750+751+ def __repr__(self):752+ return 'INT'753+754+755+class BoolParamType(ParamType):756+ name = 'boolean'757+758+ def convert(self, value, param, ctx):759+ if isinstance(value, bool):760+ return bool(value)761+ value = value.lower()762+ if value in ('true', '1', 'yes', 'y'):763+ return True764+ elif value in ('false', '0', 'no', 'n'):765+ return False766+ self.fail('%s is not a valid boolean' % value, param, ctx)767+768+ def __repr__(self):769+ return 'BOOL'770+771+772+class FloatParamType(ParamType):773+ name = 'float'774+775+ def convert(self, value, param, ctx):776+ try:777+ return float(value)778+ except ValueError:779+ self.fail('%s is not a valid floating point value' %780+ value, param, ctx)781+782+ def __repr__(self):783+ return 'FLOAT'784+785+786+class File(ParamType):787+ """Declares a parameter to be a file for reading or writing. The file788+ is automatically closed once the context tears down (after the command789+ finished working).790+791+ Files can be opened for reading or writing. The special value ``-``792+ indicates stdin or stdout depending on the mode.793+794+ By default the file is opened for reading text data but it can also be795+ opened in binary mode or for writing. The encoding parameter can be used796+ to force a specific encoding.797+ """798+ name = 'filename'799+800+ def __init__(self, mode='r', encoding=None, errors='strict'):801+ self.mode = mode802+ self.encoding = encoding803+ self.errors = errors804+805+ def convert(self, value, param, ctx):806+ try:807+ f, was_opened = open_stream(value, self.mode, self.encoding,808+ self.errors)809+ # If a context is provided we automatically close the file810+ # at the end of the context execution (or flush out). If a811+ # context does not exist it's the caller's responsibility to812+ # properly close the file. This for instance happens when the813+ # type is used with prompts.814+ if ctx is not None:815+ if was_opened:816+ ctx.call_on_close(f.close)817+ else:818+ ctx.call_on_close(f.flush)819+ return f820+ except (IOError, OSError) as e:821+ if isinstance(value, bytes):822+ value = value.decode(sys.getfilesystemencoding(), 'replace')823+ self.fail('Could not open file %s: %s' % (value, e),824+ param, ctx)825+826+827+def convert_type(ty, default=None):828+ """Converts a callable or python ty into the most appropriate param829+ ty.830+ """831+ if isinstance(ty, ParamType):832+ return ty833+ guessed_type = False834+ if ty is None and default is not None:835+ ty = type(default)836+ guessed_type = True837+ if ty is text_type or ty is str or ty is None:838+ return STRING839+ if ty is int:840+ return INT841+ # Booleans are only okay if not guessed. This is done because for842+ # flags the default value is actually a bit of a lie in that it843+ # indicates which of the flags is the one we want. See get_default()844+ # for more information.845+ if ty is bool and not guessed_type:846+ return BOOL847+ if ty is float:848+ return FLOAT849+ if guessed_type:850+ return STRING851+ return FuncParamType(ty)852+853+854+class Parameter(object):855+ """A parameter to a command comes in two versions: they are either856+ :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently857+ not supported by design as some of the internals for parsing are858+ intentionally not finalized.859+860+ Some settings are supported by both options and arguments.861+862+ :param param_decls: the parameter declarations for this option or863+ argument. This is a list of flags or argument864+ names.865+ :param type: the type that should be used. Either a :class:`ParamType`866+ or a python type. The latter is converted into the former867+ automatically if supported.868+ :param required: controls if this is optional or not.869+ :param default: the default value if omitted. This can also be a callable870+ in which case it's invoked when the default is needed871+ without any arguments.872+ :param help: the help string.873+ :param callback: a callback that should be executed after the parameter874+ was matched. This is called as ``fn(ctx, value)`` and875+ needs to return the value.876+ :param nargs: the number of arguments to match. If not ``1`` the return877+ value is a tuple instead of single value.878+ :param metavar: how the value is represented in the help page.879+ :param expose_value: if this is `True` then the value is passed onwards880+ to the command callback and stored on the context,881+ otherwise it's skipped.882+ :param is_eager: eager values are processed before non eager ones. This883+ should not be set for arguments or it will inverse the884+ order of processing.885+ :param envvar: a string or list of strings that are environment variables886+ that should be checked.887+ """888+ param_type_name = 'parameter'889+890+ def __init__(self, param_decls=None, type=None, required=False,891+ default=None, help=None, callback=None, nargs=1,892+ metavar=None, expose_value=True, is_eager=False,893+ envvar=None):894+ self.name, self.opts, self.secondary_opts = \895+ self._parse_decls(param_decls or ())896+ self.type = convert_type(type, default)897+ self.required = required898+ self.help = help899+ self.callback = callback900+ self.nargs = nargs901+ self.expose_value = expose_value902+ self.default = default903+ self.is_eager = is_eager904+ self.metavar = metavar905+ self.envvar = envvar906+907+ def make_metavar(self):908+ if self.metavar is not None:909+ return self.metavar910+ metavar = self.name.upper()911+ if self.nargs != 1:912+ metavar += '...'913+ return metavar914+915+ def get_default(self, ctx):916+ """Given a context variable this calculates the default value."""917+ # Otherwise go with the regular default.918+ if callable(self.default):919+ return self.default()920+ return self.default921+922+ def _add_to_parser(self, parser, ctx):923+ raise NotImplementedError()924+925+ def process_value(self, ctx, value):926+ """Given a value and context this runs the logic to convert the927+ value as necessary.928+ """929+ if self.type is not None:930+ if self.nargs != 1 and value is not None:931+ value = tuple(self.type(x, self, ctx) for x in value)932+ else:933+ value = self.type(value, self, ctx)934+ return value935+936+ def full_process_value(self, ctx, value):937+ value = self.process_value(ctx, value)938+939+ if value is None:940+ value = self.get_default(ctx)941+942+ if value is None and self.required:943+ ctx.fail(self.get_missing_message(ctx))944+945+ return value946+947+ def get_missing_message(self, ctx):948+ return 'Missing %s "%s".' % (949+ self.param_type_name,950+ ' / '.join(chain(self.opts, self.secondary_opts)),951+ )952+953+ def value_from_envvar(self, ctx):954+ if self.envvar is None:955+ return956+ if isinstance(self.envvar, (tuple, list)):957+ for envvar in self.envvar:958+ rv = os.environ.get(envvar)959+ if rv is not None:960+ return rv961+ else:962+ return os.environ.get(self.envvar)963+964+ def consume_value(self, ctx, opts, args):965+ return None, args966+967+ def handle_parse_result(self, ctx, opts, args):968+ value, args = self.consume_value(ctx, opts, args)969+ value = self.full_process_value(ctx, value)970+ if self.callback is not None:971+ value = self.callback(ctx, value)972+ if self.expose_value:973+ ctx.params[self.name] = value974+ return value, args975+976+977+class Option(Parameter):978+ """Options are usually optionaly values on the command line and979+ have some extra features that arguments don't have.980+981+ All other parameters are passed onwards to the parameter constructor.982+983+ :param show_default: controls if the default value should be shown on the984+ help page. The default is auto detection.985+ :param prompt: if set to `True` or a non empty string then the user will986+ be prompted for input if not set. If set to `True` the987+ prompt will be the option name capitalized.988+ :param confirmation_prompt: if set then the value will need to be confirmed989+ if it was prompted for.990+ :param hide_input: if this is `True` then the input on the prompt will be991+ hidden from the user. This is useful for password992+ input.993+ :param is_flag: forces this option to act as a flag. The default is994+ auto detection.995+ :param flag_value: which value should be used for this flag if it's996+ enabled. This is set to a boolean automatically if997+ the option string contains a slash to mark two options.998+ :param allow_from_autoenv: if this is enabled then the value of this999+ parameter will be pulled from an environment1000+ variable in case a prefix is defined on the1001+ context.1002+ """1003+ param_type_name = 'option'1004+1005+ def __init__(self, param_decls=None, show_default=None,1006+ prompt=False, confirmation_prompt=False,1007+ hide_input=False, is_flag=None, flag_value=None,1008+ allow_from_autoenv=True, type=None, **attrs):1009+ Parameter.__init__(self, param_decls, type=type, **attrs)1010+ if prompt is True:1011+ prompt = self.name.replace('_', ' ').capitalize()1012+ elif prompt is False:1013+ prompt = None1014+ self.prompt = prompt1015+ self.confirmation_prompt = confirmation_prompt1016+ self.hide_input = hide_input1017+1018+ if is_flag is None:1019+ if flag_value is not None:1020+ is_flag = True1021+ else:1022+ is_flag = bool(self.secondary_opts)1023+1024+ if is_flag and self.default is None:1025+ self.default = False1026+ if show_default is None:1027+ show_default = False1028+1029+ if flag_value is None:1030+ flag_value = not self.default1031+1032+ self.show_default = show_default1033+ self.is_flag = is_flag1034+ self.flag_value = flag_value1035+1036+ if self.is_flag and isinstance(self.flag_value, bool) \1037+ and type is None:1038+ self.type = BoolParamType()1039+ self.is_bool_flag = True1040+ else:1041+ self.is_bool_flag = False1042+1043+ self.allow_from_autoenv = allow_from_autoenv1044+1045+ # Sanity check for stuff we don't support1046+ if __debug__:1047+ if self.prompt and self.is_flag and not self.is_bool_flag:1048+ raise TypeError('Cannot prompt for flags that are not bools.')1049+ if not self.is_bool_flag and self.secondary_opts:1050+ raise TypeError('Got secondary option for non boolean flag.')1051+ if self.is_bool_flag and self.hide_input \1052+ and self.prompt is not None:1053+ raise TypeError('Hidden input does not work with boolean '1054+ 'flag prompts.')1055+1056+ def _parse_decls(self, decls):1057+ opts = []1058+ secondary_opts = []1059+ name = None1060+ possible_names = []1061+1062+ for decl in decls:1063+ if not decl.startswith('-'):1064+ if name is not None:1065+ raise TypeError('Name defined twice')1066+ name = decl1067+ else:1068+ if '/' in decl:1069+ first, second = decl.split('/', 1)1070+ possible_names.append(first.lstrip('-'))1071+ opts.append(first)1072+ secondary_opts.append(second)1073+ else:1074+ possible_names.append(decl.lstrip('-'))1075+ opts.append(decl)1076+1077+ if name is None and possible_names:1078+ possible_names.sort(key=len)1079+ name = possible_names[-1]1080+1081+ if name is None:1082+ raise TypeError('Could not determine name for option')1083+1084+ return name.replace('-', '_'), opts, secondary_opts1085+1086+ def _add_to_parser(self, parser, ctx):1087+ help = self.help1088+ extra = []1089+ if self.default is not None and self.show_default:1090+ extra.append('default: %s' % self.default)1091+ if self.required:1092+ extra.append('required')1093+ if self.nargs != 1:1094+ extra.append('%d arguments' % self.nargs)1095+ if extra:1096+ help = '%s[%s]' % (help and help + ' ' or '', '; '.join(extra))1097+1098+ kwargs = {1099+ 'help': help,1100+ 'dest': self.name,1101+ 'nargs': self.nargs,1102+ 'metavar': self.make_metavar(),1103+ }1104+1105+ if self.is_flag:1106+ kwargs.pop('nargs', None)1107+ if self.is_bool_flag and self.secondary_opts:1108+ pos_opt = optparse.Option(*self.opts, action='store_true',1109+ **kwargs)1110+ kwargs.pop('default', None)1111+ kwargs.pop('help', None)1112+ neg_opt = optparse.Option(*self.secondary_opts,1113+ action='store_false',1114+ help=optparse.SUPPRESS_HELP,1115+ **kwargs)1116+ pos_opt._negative_version = neg_opt1117+ parser.add_option(pos_opt)1118+ parser.add_option(neg_opt)1119+ else:1120+ parser.add_option(*self.opts, action='store_const',1121+ const=self.flag_value,1122+ **kwargs)1123+ else:1124+ parser.add_option(*self.opts, **kwargs)1125+1126+ def get_default(self, ctx):1127+ # If we're a non boolean flag out default is more complex because1128+ # we need to look at all flags in the same group to figure out1129+ # if we're the the default one in which case we return the flag1130+ # value as default.1131+ if self.is_flag and not self.is_bool_flag:1132+ for param in ctx.command.params:1133+ if param.name == self.name and param.default:1134+ return param.flag_value1135+ return None1136+ return Parameter.get_default(self, ctx)1137+1138+ def prompt_for_value(self, ctx):1139+ """This is an alternative flow that can be activated in the full1140+ value processing if a value does not exist. It will prompt the1141+ user until a valid value exists and then returns the processed1142+ value as result.1143+ """1144+ # Calculate the default before prompting anything to be stable.1145+ default = self.get_default(ctx)1146+1147+ # If this is a prompt for a flag we need to handle this1148+ # differently.1149+ if self.is_bool_flag:1150+ return confirm(self.prompt, default)1151+1152+ return prompt(self.prompt, default=default,1153+ hide_input=self.hide_input,1154+ confirmation_prompt=self.confirmation_prompt,1155+ value_proc=lambda x: self.process_value(ctx, x))1156+1157+ def value_from_envvar(self, ctx):1158+ rv = Parameter.value_from_envvar(self, ctx)1159+ if rv is not None:1160+ return rv1161+ if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None:1162+ envvar = '%s_%s' % (ctx.auto_envvar_prefix, self.name.upper())1163+ return os.environ.get(envvar)1164+1165+ def full_process_value(self, ctx, value):1166+ if value is None and self.prompt is not None:1167+ return self.prompt_for_value(ctx)1168+ return Parameter.full_process_value(self, ctx, value)1169+1170+ def consume_value(self, ctx, opts, args):1171+ value = opts.get(self.name)1172+ if value is None:1173+ value = self.value_from_envvar(ctx)1174+ return value, args1175+1176+1177+class Argument(Parameter):1178+ param_type_name = 'argument'1179+1180+ def __init__(self, param_decls, required=True, **attrs):1181+ Parameter.__init__(self, param_decls, required=required, **attrs)1182+1183+ def make_metavar(self):1184+ if self.metavar is not None:1185+ return self.metavar1186+ var = self.name.upper()1187+ if not self.required:1188+ var = '[%s]' % var1189+ if self.nargs != 1:1190+ var += '...'1191+ return var1192+1193+ def _parse_decls(self, decls):1194+ if not decls:1195+ raise TypeError('Could not determine name for argument')1196+ if len(decls) == 1:1197+ name = arg = decls[0]1198+ elif len(decls) == 2:1199+ name, arg = decls1200+ else:1201+ raise TypeError('Arguments take exactly one or two '1202+ 'parameter declarations, got %d' % len(decls))1203+ return name.replace('-', '_'), [arg], []1204+1205+ def _add_to_parser(self, parser, ctx):1206+ parser.usage += ' ' + self.make_metavar()1207+1208+ def consume_value(self, ctx, opts, args):1209+ found = True1210+ if self.nargs == 1:1211+ try:1212+ value = args.pop(0)1213+ except IndexError:1214+ found = False1215+ elif self.nargs < 0:1216+ value = tuple(args)1217+ found = not value1218+ args = []1219+ else:1220+ values = args[:self.nargs]1221+ values += [None] * (self.nargs - len(values))1222+ args = args[self.nargs:]1223+ value = tuple(values)1224+ found = not value1225+ if not found:1226+ value = self.value_from_envvar(ctx)1227+ if self.nargs != 1:1228+ value = (value,)1229+ return value, args1230+1231+1232+def _make_command(f, name, attrs, cls):1233+ if isinstance(f, Command):1234+ raise TypeError('Attempted to convert a callback into a '1235+ 'command twice.')1236+ try:1237+ params = f.__click_params__1238+ params.reverse()1239+ del f.__click_params__1240+ except AttributeError:1241+ params = []1242+ help = inspect.getdoc(f)1243+ if isinstance(help, bytes):1244+ help = help.decode('utf-8')1245+ attrs.setdefault('help', help)1246+ return cls(name=name or f.__name__.lower(),1247+ callback=f, params=params, **attrs)1248+1249+1250+def command(name=None, **attrs):1251+ """Creates a new :class:`Command` and uses the decorated function as1252+ callback. This will also automatically attach all decorated1253+ :func:`option`\s and :func:`argument`\s as paramters to the command.1254+1255+ The name of the command defaults to the name of the function. If you1256+ want to change that, you can pass the intended name as the first1257+ argument.1258+1259+ All keyword arguments are forwarded to the underlying command class.1260+1261+ Once decorated the function turns into a :class:`Command` instance1262+ that can be invoked as a command line utility or be attached to a1263+ command :class:`Group`.1264+ """1265+ def decorator(f):1266+ return _make_command(f, name, attrs, Command)1267+ return decorator1268+1269+1270+def group(name=None, **attrs):1271+ """Creates a new :class:`Group` with a function as callback. This1272+ works otherwise the same as :func:`command` just that the generated1273+ class is different.1274+ """1275+ def decorator(f):1276+ return _make_command(f, name, attrs, Group)1277+ return decorator1278+1279+1280+def _param_memo(f, param):1281+ if isinstance(f, Command):1282+ f.params.append(param)1283+ else:1284+ if not hasattr(f, '__click_params__'):1285+ f.__click_params__ = []1286+ f.__click_params__.append(param)1287+1288+1289+def argument(*param_decls, **attrs):1290+ """Attaches an option to the command. All positional arguments are1291+ passed as parameter declarations to :class:`Argment`, all keyword1292+ arguments are forwarded unchanged. This is equivalent to creating an1293+ :class:`Option` instance manually and attaching it to the1294+ :attr:`Command.params` list.1295+ """1296+ def decorator(f):1297+ _param_memo(f, Argument(param_decls, **attrs))1298+ return f1299+ return decorator1300+1301+1302+def option(*param_decls, **attrs):1303+ """Attaches an option to the command. All positional arguments are1304+ passed as parameter declarations to :class:`Option`, all keyword1305+ arguments are forwarded unchanged. This is equivalent to creating an1306+ :class:`Option` instance manually and attaching it to the1307+ :attr:`Command.params` list.1308+ """1309+ def decorator(f):1310+ _param_memo(f, Option(param_decls, **attrs))1311+ return f1312+ return decorator1313+1314+1315+def confirmation_option(*param_decls, **attrs):1316+ """Shortcut for confirmation prompts that can be ignored by bypassed1317+ ``--yes`` as parameter.1318+1319+ This is equivalent to decorating a function with :func:`option` with1320+ the following parameters::1321+1322+ def callback(ctx, value):1323+ if not value:1324+ ctx.abort()1325+1326+ @click.command()1327+ @click.option('--yes', is_flag=True, callback=callback,1328+ expose_value=False, prompt='Do you want to continue?')1329+ def dropdb():1330+ pass1331+ """1332+ def decorator(f):1333+ def callback(ctx, value):1334+ if not value:1335+ ctx.abort()1336+ attrs.setdefault('is_flag', True)1337+ attrs.setdefault('callback', callback)1338+ attrs.setdefault('expose_value', False)1339+ attrs.setdefault('prompt', 'Do you want to continue?')1340+ return option(*(param_decls or ('--yes',)), **attrs)(f)1341+ return decorator1342+1343+1344+def password_option(*param_decls, **attrs):1345+ """Shortcut for password prompts.1346+1347+ This is equivalent to decorating a function with :func:`option` with1348+ the following parameters::1349+1350+ @click.command()1351+ @click.option('--password', prompt=True, confirmation_prompt=True,1352+ hide_input=True)1353+ def changeadmin(password):1354+ pass1355+ """1356+ def decorator(f):1357+ attrs.setdefault('prompt', True)1358+ attrs.setdefault('confirmation_prompt', True)1359+ attrs.setdefault('hide_input', True)1360+ return option(*(param_decls or ('--password',)), **attrs)(f)1361+ return decorator1362+1363+1364+def version_option(version, *param_decls, **attrs):1365+ """Adds a ``--version`` option which immediately ends the program1366+ printing out the version number. This is implemented as an eager1367+ option that prints the version and exits the program in the callback.1368+1369+ :param version: the version number to show1370+ :param prog_name: the name of the program (defaults to autodetection)1371+ :param message: custom message to show instead of the default1372+ (``'%(prog)s, version %(version)s'``)1373+ :param others: everything else is forwarded to :func:`option`.1374+ """1375+ def decorator(f):1376+ prog_name = attrs.pop('prog_name', None)1377+ message = attrs.pop('message', '%(prog)s, version %(version)s')1378+1379+ def callback(ctx, value):1380+ if not value:1381+ return1382+ prog = prog_name1383+ if prog is None:1384+ prog = ctx.find_root().info_name1385+ echo(message % {1386+ 'prog': prog,1387+ 'version': version,1388+ })1389+ ctx.exit()1390+1391+ attrs.setdefault('is_flag', True)1392+ attrs.setdefault('expose_value', False)1393+ attrs.setdefault('is_eager', True)1394+ attrs.setdefault('help', 'Show the version and exit.')1395+ attrs['callback'] = callback1396+ return option(*(param_decls or ('--version',)), **attrs)(f)1397+ return decorator1398+1399+1400+def help_option(*param_decls, **attrs):1401+ """Adds a ``--help`` option which immediately ends the program1402+ printing out the help page. This is usually unnecessary to add as1403+ this is added by default to all commands unless supressed.1404+1405+ Like :func:`version_option` this is implemented as eager option that1406+ prints in the callback and exits.1407+1408+ All arguments are forwarded to :func:`option`.1409+ """1410+ def decorator(f):1411+ def callback(ctx, value):1412+ if value:1413+ echo(ctx.format_help())1414+ ctx.exit()1415+ attrs.setdefault('is_flag', True)1416+ attrs.setdefault('expose_value', False)1417+ attrs.setdefault('help', 'Show this message and exit.')1418+ attrs.setdefault('is_eager', True)1419+ attrs['callback'] = callback1420+ return option(*(param_decls or ('--help',)), **attrs)(f)1421+ return decorator1422+1423+1424+def confirm(text, default=False, abort=False):1425+ """Prompts for confirmation (yes/no question).1426+1427+ If the user aborts the input by sending a interrupt signal this1428+ function will catch it and raise a :exc:`Abort` exception.1429+1430+ :param text: the question to ask.1431+ :param default: the default for the prompt.1432+ :param abort: if this is set to `True` a negative answer aborts the1433+ exception by raising :exc:`Abort`.1434+ """1435+ prompt = '%s [%s]: ' % (text, default and 'Yn' or 'yN')1436+ while 1:1437+ try:1438+ value = raw_input(prompt).lower().strip()1439+ except (KeyboardInterrupt, EOFError):1440+ raise Abort()1441+ if value in ('y', 'yes'):1442+ rv = True1443+ elif value in ('n', 'no'):1444+ rv = False1445+ elif value == '':1446+ rv = default1447+ else:1448+ echo('Error: invalid input')1449+ continue1450+ break1451+ if abort and not rv:1452+ raise Abort()1453+ return rv1454+1455+1456+def prompt(text, default=None, hide_input=False,1457+ confirmation_prompt=False, type=None,1458+ value_proc=None):1459+ """Prompts a user for input. This is a convenience function that can1460+ be used to prompt a user for input later.1461+1462+ If the user aborts the input by sending a interrupt signal this1463+ function will catch it and raise a :exc:`Abort` exception.1464+1465+ :param text: the text to show for the prompt.1466+ :param default: the default value to use if no input happens. If this1467+ is not given it will prompt until it's aborted.1468+ :param hide_input: if this is set to true then the input value will1469+ be hidden.1470+ :param confirmation_prompt: asks for confirmation for the value.1471+ :param type: the type to use to check the value against.1472+ :param value_proc: if this parameter is provided it's a function that1473+ is invoked instead of the type conversion to1474+ convert a value.1475+ """1476+ result = None1477+1478+ def prompt_func(text):1479+ f = hide_input and getpass.getpass or raw_input1480+ try:1481+ return f(text)1482+ except (KeyboardInterrupt, EOFError):1483+ raise Abort()1484+1485+ if value_proc is None:1486+ value_proc = convert_type(type, default)1487+1488+ prompt = text1489+ if default is not None:1490+ prompt = '%s [%s]' % (prompt, default)1491+ prompt += ': '1492+1493+ while 1:1494+ while 1:1495+ value = prompt_func(prompt)1496+ if value:1497+ break1498+ # If a default is set and used, then the confirmation1499+ # prompt is always skipped because that's the only thing1500+ # that really makes sense.1501+ elif default is not None:1502+ return default1503+ try:1504+ result = value_proc(value)1505+ except UsageError as e:1506+ echo('Error: %s' % e.message)1507+ continue1508+ if not confirmation_prompt:1509+ return result1510+ while 1:1511+ value2 = prompt_func('Repeat for confirmation: ')1512+ if value2:1513+ break1514+ if value == value2:1515+ return result1516+ echo('Error: the two entered values do not match')1517+1518+1519+#: A unicode string parameter type which is the implicit default. This1520+#: can also be selected by using ``str`` as type.1521+STRING = StringParamType()1522+1523+#: An integer parameter. This can also be selected by using ``int`` as1524+#: type.1525+INT = IntParamType()1526+1527+#: A floating point value parameter. This can also be selected by using1528+#: ``float`` as type.1529+FLOAT = FloatParamType()1530+1531+#: A boolean parameter. This is the default for boolean flags. This can1532+#: also be selected by using ``bool`` as a type.1533+BOOL = BoolParamType()added:setup.py+18 added
1+from setuptools import setup2+3+4+setup(5+ name='click',6+ author='Armin Ronacher',7+ author_email='armin.ronacher@active-4.com',8+ version='0.1',9+ url='http://github.com/mitsuhiko/click',10+ py_modules=['click'],11+ description='A simple wrapper around optparse for '12+ 'powerful command line utilities.',13+ classifiers=[14+ 'License :: OSI Approved :: BSD License',15+ 'Programming Language :: Python',16+ 'Programming Language :: Python :: 3',17+ ],18+)