Skip to content
Myr

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

30 files+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/) -->34<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
added:docs/_templates/sidebarlogo.html+3 added
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 */89{% set page_width = '940px' %}10{% set sidebar_width = '220px' %}11 12@import url("basic.css");1314@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 19body {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}2728div.document {29 width: {{ page_width }};30 margin: 30px auto 0 auto;31}3233div.documentwrapper {34 float: left;35 width: 100%;36}3738div.bodywrapper {39 margin: 0 0 0 {{ sidebar_width }};40}4142div.sphinxsidebar {43 width: {{ sidebar_width }};44}4546div.sphinxsidebar h3,47div.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}5354hr {55 border: 1px solid #B1B4B6;56}57 58div.body {59 background-color: #ffffff;60 color: #3E4349;61 padding: 0 30px 0 30px;62}6364img.floatingflask {65 padding: 0 0 10px 10px;66 float: right;67}68 69div.footer {70 width: {{ page_width }};71 margin: 20px auto 30px auto;72 font-size: 14px;73 color: #888;74 text-align: right;75}7677div.footer a {78 color: #888;79}8081div.related {82 display: none;83}84 85div.sphinxsidebar a {86 color: #444;87 text-decoration: none;88 border-bottom: 1px dotted #999;89}9091div.sphinxsidebar a:hover {92 border-bottom: 1px solid #999;93}94 95div.sphinxsidebar {96 font-size: 14px;97 line-height: 1.5;98}99100div.sphinxsidebarwrapper {101 padding: 18px 10px;102}103104div.sphinxsidebarwrapper p.logo {105 padding: 0 0 20px 0;106 margin: 0;107 text-align: left;108}109 110div.sphinxsidebar h3,111div.sphinxsidebar h4 {112 color: #444;113 font-size: 18px;114 font-weight: normal;115 margin: 0 0 5px 0;116 padding: 0;117}118119div.sphinxsidebar h4 {120 font-size: 15px;121}122 123div.sphinxsidebar h3 a {124 color: #444;125}126127div.sphinxsidebar p.logo a,128div.sphinxsidebar h3 a,129div.sphinxsidebar p.logo a:hover,130div.sphinxsidebar h3 a:hover {131 border: none;132}133 134div.sphinxsidebar p {135 color: #555;136 margin: 10px 0;137}138139div.sphinxsidebar ul {140 margin: 10px 0;141 padding: 0;142 color: #000;143}144 145div.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}150151div.sphinxsidebar #searchbox input[type="text"] {152 width: 120px;153}154 155/* -- body styles ----------------------------------------------------------- */156 157a {158 color: #5D2CD1;159 text-decoration: underline;160}161 162a:hover {163 color: #7546E3;164 text-decoration: underline;165}166 167div.body h1,168div.body h2,169div.body h3,170div.body h4,171div.body h5,172div.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}178179div.indexwrapper h1 {180 text-indent: -999999px;181 background: url(click.png) no-repeat center center;182 height: 200px;183}184 185div.body h1 { margin-top: 0; padding-top: 0; font-size: 240%; }186div.body h2 { font-size: 180%; }187div.body h3 { font-size: 150%; }188div.body h4 { font-size: 130%; }189div.body h5 { font-size: 100%; }190div.body h6 { font-size: 100%; }191 192a.headerlink {193 color: #ddd;194 padding: 0 4px;195 text-decoration: none;196}197 198a.headerlink:hover {199 color: #444;200 background: #eaeaea;201}202 203div.body p, div.body dd, div.body li {204 line-height: 1.4em;205}206207div.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}214215div.admonition tt.xref, div.admonition a tt {216 border-bottom: 1px solid #fafafa;217}218219dd div.admonition {220 margin-left: -60px;221 padding-left: 60px;222}223224div.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}232233div.admonition p.last {234 margin-bottom: 0;235}236237div.highlight {238 background-color: white;239}240241dt:target, .highlight {242 background: #FAF3E8;243}244245div.note {246 background-color: #eee;247 border: 1px solid #ccc;248}249 250div.seealso {251 background-color: #ffc;252 border: 1px solid #ff6;253}254 255div.topic {256 background-color: #eee;257}258 259p.admonition-title {260 display: inline;261}262 263p.admonition-title:after {264 content: ":";265}266267pre, tt {268 font-family: 'Ubuntu Mono', 'Consolas', 'Menlo', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono';269 font-size: 15px;270}271272img.screenshot {273}274275tt.descname, tt.descclassname {276 font-size: 0.95em;277}278279tt.descname {280 padding-right: 0.08em;281}282283img.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}288289table.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}295296table.docutils td, table.docutils th {297 border: 1px solid #888;298 padding: 0.25em 0.7em;299}300301table.field-list, table.footnote {302 border: none;303 -moz-box-shadow: none;304 -webkit-box-shadow: none;305 box-shadow: none;306}307308table.footnote {309 margin: 15px 0;310 width: 100%;311 border: 1px solid #eee;312 background: #fdfdfd;313 font-size: 0.9em;314}315316table.footnote + table.footnote {317 margin-top: -15px;318 border-top: none;319}320321table.field-list th {322 padding: 0 0.8em 0 0;323}324325table.field-list td {326 padding: 0;327}328329table.footnote td.label {330 width: 0px;331 padding: 0.3em 0 0.3em 0.5em;332}333334table.footnote td {335 padding: 0.3em 0.5em;336}337338dl {339 margin: 0;340 padding: 0;341}342343dl dd {344 margin-left: 30px;345}346347blockquote {348 margin: 0 0 0 30px;349 padding: 0;350}351352ul, ol {353 margin: 10px 0 10px 30px;354 padding: 0;355}356 357pre {358 padding: 7px 0 7px 30px;359 margin: 15px 0;360 line-height: 1.3em;361}362 363tt {364 background-color: #ecf0f3;365 color: #222;366 /* padding: 1px 2px; */367}368369tt.xref, a tt {370 background-color: #FBFBFB;371 border-bottom: 1px solid white;372}373374a.reference {375 text-decoration: none;376 border-bottom: 1px dotted #5D2CD1;377}378379a.reference:hover {380 border-bottom: 1px solid #7546E3;381}382383a.footnote-reference {384 text-decoration: none;385 font-size: 0.7em;386 vertical-align: top;387 border-bottom: 1px dotted #5D2CD1;388}389390a.footnote-reference:hover {391 border-bottom: 1px solid #7546E3;392}393394a:hover tt {395 background: #EEE;396}
added:docs/_themes/click/layout.html+20 added
added:docs/_themes/click/relations.html+19 added
added:docs/_themes/click/theme.conf+4 added
1[theme]2inherit = basic3stylesheet = click.css4pygments_style = tango
added:docs/_themes/LICENSE+37 added
1Copyright (c) 2014 by Armin Ronacher.23Some rights reserved.45Redistribution and use in source and binary forms of the theme, with or6without modification, are permitted provided that the following conditions7are met:89* Redistributions of source code must retain the above copyright10 notice, this list of conditions and the following disclaimer.1112* 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.1617* The names of the contributors may not be used to endorse or18 promote products derived from this software without specific19 prior written permission.2021We kindly ask you to only use these themes in an unmodified manner just22for Click and Click-related products, not for unrelated projects. If you23like the visual style and want to use it for your own projects, please24consider making some larger changes to the themes (such as changing25font faces, sizes, colors or margins).2627THIS THEME IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"28AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE29IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE30ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE31LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR32CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF33SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS34INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN35CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)36ARISING IN ANY WAY OUT OF THE USE OF THIS THEME, EVEN IF ADVISED OF THE37POSSIBILITY OF SUCH DAMAGE.
added:docs/_themes/README+31 added
1Flask Sphinx Styles2===================34This repository contains sphinx styles for Flask and Flask related5projects. To use this style in your Sphinx documentation, follow6this guide:781. put this folder as _themes into your docs folder. Alternatively9 you can also use git submodules to check out the contents there.102. add this to your conf.py:1112 sys.path.append(os.path.abspath('_themes'))13 html_theme_path = ['_themes']14 html_theme = 'flask'1516The following themes exist:1718- '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.2223The following options exist for the flask_small theme:2425 [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" badge
added:docs/api.rst+85 added
1API2===34.. module:: click56This part of the documentation shows the full API reference of all public7classes and functions.89Decorators10----------1112.. autofunction:: command1314.. autofunction:: group1516.. autofunction:: argument1718.. autofunction:: option1920.. autofunction:: password_option2122.. autofunction:: confirmation_option2324.. autofunction:: version_option2526.. autofunction:: help_option2728Helper Functions29----------------3031.. autofunction:: prompt3233.. autofunction:: confirm3435.. autofunction:: get_terminal_size3637Commands38--------3940.. autoclass:: Command41 :members:4243.. autoclass:: MultiCommand44 :members:4546.. autoclass:: Group47 :members:4849Parameters50----------5152.. autoclass:: Parameter53 :members:5455.. autoclass:: Option5657.. autoclass:: Argument5859Context60-------6162.. autoclass:: Context63 :members:6465Types66-----6768.. autodata:: STRING6970.. autodata:: INT7172.. autodata:: FLOAT7374.. autodata:: BOOL7576.. autoclass:: File7778.. autoclass:: ParamType7980Exceptions81----------8283.. autoexception:: Abort8485.. autoexception:: UsageError
added:docs/arguments.rst+114 added
1Arguments2=========34.. currentmodule:: click56Arguments work similar to options but are positional. They also only7support subset of the features of options due to their syntactical nature.8Click also will not attempt to document arguments for you and wants you to9document them manually to avoid ugly looking help pages.1011Basic Arguments12---------------1314The most basic option is a simple string arguments of one value. If no15type is provided the type of the default value is used. If no default16value is provided the type is assumed to be :data:`STRING`.1718Example::1920 @click.command()21 @click.argument('filename')22 def touch(filename):23 print(filename)2425And what it looks like::2627 $ python touch.py foo.txt28 foo.txt2930Variadic Arguments31------------------3233The second most common version is variadic arguments where a specific (or34unlimited) number of arguments is accepted. This can be controlled with35the ``nargs`` parameter. If it's set to ``-1`` then an unlimited number36of arguments is accepted.3738The value is then passed as tuple. Note that only one argument really can39be set to ``nargs=-1`` and right now only the last.4041Example::4243 @click.command()44 @click.argument('files', nargs=-1)45 def touch(files):46 for file in files:47 print(file)4849And what it looks like::5051 $ python touch.py foo.txt bar.txt52 foo.txt53 bar.txt5455File Arguments56--------------5758Since all the examples have already worked with file names it makes sense59to explain how to deal with files properly. Command line tools are more60fun if they work with files the unix way which is to accept ``-`` as61special file that refers to stdin/stdout.6263Click supports this through the :class:`click.File` type which64intelligently handles files for you. It also deals with unicode and bytes65correctly for all versions of Python so your script stays very portable.6667Example::6869 @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)7879And what it does::8081 $ python inout.py - hello.txt82 hello83 ^D84 $ python inout.py hello.txt -85 hello8687Environment Variables88---------------------8990Like options, arguments can also get values from an environment variable.91Unlike options however this is only supported for explicitly named92environment variables.9394Example usage::9596 @click.command()97 @click.argument('--src', envvar='SOURCE', type=click.File('r'))98 def echo(src):99 print(src.read())100101 if __name__ == '__main__':102 echo()103104And from the command line::105106 $ export SRC=hello.txt107 $ python echo.py108 Hello!109110In that case it can also be a list of different environment variables111where the first one is picked.112113Generally this feature is not recommended because it can cause a lot of114confusion to the user.
added:docs/commands.rst+170 added
1Commands and Groups2===================34.. currentmodule:: click56The most important feature of click is the concept of arbitrarily nesting7command line utilities. This is implemented through the :class:`Command`8and :class:`Group` (actually :class:`MultiCommand`).910Callback Invocation11-------------------1213For a regular command the callback is executed whenever the command runs.14So if the script is the only command it will always fire (unless a15parameter callback prevents it. This for instance happens if someone16passes ``--help`` to the script).1718For groups and multi commands the situation looks different. In that case19the callback fires whenever a subcommand fires (unless this behavior is20changed). What this means in practice is that an outer command runs21when an inner command runs::2223 import click2425 @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'))2930 @cli.command()31 def sync():32 print('Synching')3334 if __name__ == '__main__':35 cli()3637Here is what this looks like::3839 $ python tool.py40 Usage: tool.py [OPTIONS] COMMAND [ARGS]...4142 Commands:43 sync 4445 Options:46 --debug / --no-debug 47 --help Show this message and exit.48 49 $ python tool.py --debug sync50 Debug mode is on51 Synching 5253Nested Handling and Contexts54----------------------------5556As you can see from the earlier example the basic command group accepts a57debug argument which is passed to its callback, but not to the sync58command itself. The sync command only accepts its own arguments.5960This allows tools to act completely independent of each other. But how61does on command talk to a nested on? The answer to this is the62:class:`Context`.6364Each time a command invokes a new context is created and linked with the65parent context. Normally you can't see these contexts, but they are66there. Contexts are passed to parameter callbacks together with the67value automatically. Commands can also ask for the context to be passed68by passing ``pass_context=True`` to the :func:`command` or :func:`group`69decorator. In that case the context is passed as first argument.7071The context can also carry a program specified object that can be72used for the program's purposes. What this means is that you can build a73script like this::7475 import click7677 @click.group(pass_context=True)78 @click.option('--debug/--no-debug', default=False)79 def cli(ctx, debug):80 ctx.obj['DEBUG'] = debug8182 @cli.command(pass_context=True)83 def sync(ctx):84 print('Debug is %s' % (ctx.obj['DEBUG'] and 'on' or 'off'))8586 if __name__ == '__main__':87 cli(obj={})8889If the object is provided each context will pass the object onwards to90it's children, but at any level a context's object can be overridden. To91reach to a parent ``context.parent`` can be used.9293In addition to that instead of passing an object down nothing stops the94application from modifying global state. For instance you could just flip95a global ``DEBUG`` variable and be done with it.9697Group Invocation Without Command98--------------------------------99100By default a group or multi command is not invoked unless a subcommand is101passed. In fact, not providing a command automatically passes ``--help``102by default. This behavior can be changed by passing103``invoke_without_command=True`` to a group. In that case the callback is104always invoked instead of showing the help page. The context object also105includes information about if the invocation would go to a subcommand or106not.107108Example::109110 import click111112 @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)118119 @cli.command()120 def sync():121 print('The subcommand')122123 if __name__ == '__main__':124 cli()125126And how it works in practice::127128 $ python tool.py 129 I was invoked without subcommand130 $ python tool.py sync131 I am about to invoke sync132 The subcommand133134Custom Multi Commands135---------------------136137In addition to using :func:`click.group` you can also build your own138custom multi commands. This is useful when you want to support commands139being loaded lazily from plugins.140141A custom multi command just needs to implement a list and load method::142143 import click144 import os145146 plugin_folder = os.path.join(os.path.dirname(__file__), 'commands')147148 class MyCLI(click.MultiCommand):149150 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 rv157158 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']165166 cli = MyCLI(help='This tool\'s subcommands are loaded from a '167 'plugin folder dynamically.')168169 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.1314import sys, os1516# 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.19sys.path.append(os.path.abspath('_themes'))20sys.path.append(os.path.abspath('..'))2122# -- General configuration -----------------------------------------------------2324# If your documentation needs a minimal Sphinx version, state it here.25#needs_sphinx = '1.0'2627# Add any Sphinx extension module names here, as strings. They can be extensions28# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.29extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx']3031# Add any paths that contain templates here, relative to this directory.32templates_path = ['_templates']3334# The suffix of source filenames.35source_suffix = '.rst'3637# The encoding of source files.38#source_encoding = 'utf-8-sig'3940# The master toctree document.41master_doc = 'index'4243# General information about the project.44project = u'click'45copyright = u'2014, Armin Ronacher'4647# 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.52version = '1.0'53# The full version, including alpha/beta/rc tags.54release = '1.0'5556# The language for content autogenerated by Sphinx. Refer to documentation57# for a list of supported languages.58#language = None5960# 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'6566# List of patterns, relative to source directory, that match files and67# directories to ignore when looking for source files.68exclude_patterns = ['_build']6970# The reST default role (used for this markup: `text`) to use for all documents.71#default_role = None7273# If true, '()' will be appended to :func: etc. cross-reference text.74#add_function_parentheses = True7576# If true, the current module name will be prepended to all description77# unit titles (such as .. function::).78#add_module_names = True7980# If true, sectionauthor and moduleauthor directives will be shown in the81# output. They are ignored by default.82#show_authors = False8384# A list of ignored prefixes for module index sorting.85#modindex_common_prefix = []868788# -- Options for HTML output ---------------------------------------------------8990# The theme to use for HTML and HTML Help pages. Major themes that come with91# Sphinx are currently 'default' and 'sphinxdoc'.92html_theme = 'click'9394# 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.97html_theme_options = {98}99100# Add any paths that contain custom themes here, relative to this directory.101html_theme_path = ['_themes']102103# The name for this set of Sphinx documents. If None, it defaults to104# "<project> v<release> documentation".105html_title = 'click'106107# A shorter title for the navigation bar. Default is the same as html_title.108#html_short_title = None109110# The name of an image file (relative to this directory) to place at the top111# of the sidebar.112#html_logo = None113114# 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 = None118119# 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".122html_static_path = ['_static']123124# 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'127128# If true, SmartyPants will be used to convert quotes and dashes to129# typographically correct entities.130#html_use_smartypants = True131132# Custom sidebar templates, maps document names to template names.133html_sidebars = {134 'index': ['sidebarintro.html', 'sourcelink.html', 'searchbox.html'],135 '**': ['sidebarlogo.html', 'localtoc.html', 'relations.html',136 'sourcelink.html', 'searchbox.html']137}138139# Additional templates that should be rendered to pages, maps page names to140# template names.141#html_additional_pages = {}142143# If false, no module index is generated.144#html_domain_indices = True145146# If false, no index is generated.147#html_use_index = True148149# If true, the index is split into individual pages for each letter.150#html_split_index = False151152# If true, links to the reST sources are added to the pages.153#html_show_sourcelink = True154155# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.156#html_show_sphinx = True157158# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.159#html_show_copyright = True160161# 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 = ''165166# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").167#html_file_suffix = ''168169# Output file base name for HTML help builder.170htmlhelp_basename = 'clickdoc'171172173# -- Options for LaTeX output --------------------------------------------------174175# The paper size ('letter' or 'a4').176#latex_paper_size = 'letter'177178# The font size ('10pt', '11pt' or '12pt').179#latex_font_size = '10pt'180181# Grouping the document tree into LaTeX files. List of tuples182# (source start file, target name, title, author, documentclass [howto/manual]).183latex_documents = [184 ('index', 'click.tex', u'click documentation',185 u'Armin Ronacher', 'manual'),186]187188# The name of an image file (relative to this directory) to place at the top of189# the title page.190#latex_logo = None191192# For "manual" documents, if this is true, then toplevel headings are parts,193# not chapters.194#latex_use_parts = False195196# Additional stuff for the LaTeX preamble.197#latex_preamble = ''198199# Documents to append as an appendix to all manuals.200#latex_appendices = []201202# If false, no module index is generated.203#latex_domain_indices = True204205206# -- Options for manual page output --------------------------------------------207208# One entry per manual page. List of tuples209# (source start file, name, description, authors, manual section).210man_pages = [211 ('index', 'click', u'click documentation',212 [u'Armin Ronacher'], 1)213]214215intersphinx_mapping = {216 'http://docs.python.org/dev': None217}
added:docs/documentation.rst+98 added
1Documenting Scripts2===================34Click makes it very easy to document your command line tools. First of5all it automatically generates help pages for you. While these are6currently not customizable in layout, all the texts can be changed.78Help Texts9----------1011Commands and options accept help arguments. In case of commands the doc12string of the function is automatically used if provided.1314Simple example::1516 @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)2324And what it looks like::2526 $ python hello.py --help27 Usage: hello.py [OPTIONS] NAME2829 This script prints hello NAME COUNT times.3031 Options:32 --count=COUNT number of greetings33 --help Show this message and exit.3435Arguments cannot be documented this way. This is to follow general36convention of Unix tools to use arguments only for the most necessary37things and to document them in the introduction text by referring to them38by name.3940Meta Vars41---------4243Options and parameters accept a ``metavar`` argument that can change the44meta variable in the help page. The default version is the parameter name45in uppercase with underscores and sometimes annotated differently if46optional. This can be customized at all levels::4748 @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)5657Example::5859 Usage: hello.py <options> <name>6061 This script prints hello <name> <int> times.6263 Options:64 --count=<int> number of greetings65 --help Show this message and exit.66 6768Command Short Help69------------------7071For 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 too73long. This can also be overridden::7475 @click.group()76 def cli():77 """A simple command line tool."""7879 @cli.command('init', short_help='init the repo')80 def init():81 """Initializes the repository."""8283 @cli.command('delete', short_help='delete the repo')84 def delete():85 """Deletes the repository."""8687And what it looks like::8889 Usage: repo.py [OPTIONS] COMMAND [ARGS]...9091 A simple command line tool.9293 Commands:94 delete delete the repo95 init init the repo9697 Options:98 --help Show this message and exit.
added:docs/index.rst+65 added
1click2=====34click is a Python package for creating beautiful command line interfaces5in a composable way with as little amount of code as necessary. It's the6"Command Line Interface Creation Kit". It's highly configurable but comes7with good defaults out of the box.89It aims at making writing command line tools fun and quick without causing10user frustration at not being able to implement an intended CLI API.1112Click in three points:1314- arbitrary nesting of commands15- automatic help page generation16- supports lazy loading of subcommands at runtime1718What does it look like? A simple example can be this::1920 import click2122 @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)2930 if __name__ == '__main__':31 hello()3233You can get the library directly from PyPI::3435 pip install click3637Documentation Contents38----------------------3940This part of the documentation guides you through all the usage patterns41of the library.4243.. toctree::44 :maxdepth: 24546 why47 quickstart48 parameters49 options50 arguments51 commands52 prompts53 documentation54 setuptools5556API Reference57-------------5859If you are looking for information on a specific function, class or60method, this part of the documentation is for you.6162.. toctree::63 :maxdepth: 26465 api
added:docs/make.bat+155 added
1@ECHO OFF23REM Command file for Sphinx documentation45if "%SPHINXBUILD%" == "" (6 set SPHINXBUILD=sphinx-build7)8set BUILDDIR=_build9set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .10if NOT "%PAPER%" == "" (11 set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%12)1314if "%1" == "" goto help1516if "%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)3637if "%1" == "clean" (38 for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i39 del /q /s %BUILDDIR%\*40 goto end41)4243if "%1" == "html" (44 %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html45 echo.46 echo.Build finished. The HTML pages are in %BUILDDIR%/html.47 goto end48)4950if "%1" == "dirhtml" (51 %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml52 echo.53 echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.54 goto end55)5657if "%1" == "singlehtml" (58 %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml59 echo.60 echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.61 goto end62)6364if "%1" == "pickle" (65 %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle66 echo.67 echo.Build finished; now you can process the pickle files.68 goto end69)7071if "%1" == "json" (72 %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json73 echo.74 echo.Build finished; now you can process the JSON files.75 goto end76)7778if "%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)8586if "%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)9697if "%1" == "devhelp" (98 %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp99 echo.100 echo.Build finished.101 goto end102)103104if "%1" == "epub" (105 %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub106 echo.107 echo.Build finished. The epub file is in %BUILDDIR%/epub.108 goto end109)110111if "%1" == "latex" (112 %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex113 echo.114 echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.115 goto end116)117118if "%1" == "text" (119 %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text120 echo.121 echo.Build finished. The text files are in %BUILDDIR%/text.122 goto end123)124125if "%1" == "man" (126 %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man127 echo.128 echo.Build finished. The manual pages are in %BUILDDIR%/man.129 goto end130)131132if "%1" == "changes" (133 %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes134 echo.135 echo.The overview file is in %BUILDDIR%/changes.136 goto end137)138139if "%1" == "linkcheck" (140 %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck141 echo.142 echo.Link check complete; look for any errors in the above output ^143or in %BUILDDIR%/linkcheck/output.txt.144 goto end145)146147if "%1" == "doctest" (148 %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest149 echo.150 echo.Testing of doctests in the sources finished, look at the ^151results in %BUILDDIR%/doctest/output.txt.152 goto end153)154155:end
added:docs/Makefile+130 added
1# Makefile for Sphinx documentation2#34# You can set these variables from the command line.5SPHINXOPTS =6SPHINXBUILD = sphinx-build7PAPER =8BUILDDIR = _build910# Internal variables.11PAPEROPT_a4 = -D latex_paper_size=a412PAPEROPT_letter = -D latex_paper_size=letter13ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .1415.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest1617help: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)"3536clean:37 -rm -rf $(BUILDDIR)/*3839html:40 $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html41 @echo42 @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."4344dirhtml:45 $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml46 @echo47 @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."4849singlehtml:50 $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml51 @echo52 @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."5354pickle:55 $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle56 @echo57 @echo "Build finished; now you can process the pickle files."5859json:60 $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json61 @echo62 @echo "Build finished; now you can process the JSON files."6364htmlhelp: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."6970qthelp: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"7879devhelp: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"8788epub:89 $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub90 @echo91 @echo "Build finished. The epub file is in $(BUILDDIR)/epub."9293latex: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."99100latexpdf: 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."105106text:107 $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text108 @echo109 @echo "Build finished. The text files are in $(BUILDDIR)/text."110111man:112 $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man113 @echo114 @echo "Build finished. The manual pages are in $(BUILDDIR)/man."115116changes:117 $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes118 @echo119 @echo "The overview file is in $(BUILDDIR)/changes."120121linkcheck: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."126127doctest: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
1Options2=======34.. currentmodule:: click56Adding options to commands can be accomplished by the :func:`option`7decorator. Since options can come in various different versions there8have a ton of parameters to configure their behavior.910Basic Value Options11-------------------1213The most basic option is a value option. These options accept one14argument which is a value. If no type is provided the type of the default15value is used. If no default value is provided the type is assumed to be16:data:`STRING`.1718Example::1920 @click.command()21 @click.option('--n', default=1)22 def dots(n):23 print('.' * n)2425And on the command line::2627 $ python dots.py --n=228 ..2930In this case the option is of type :data:`INT` because the default value31is an integer.3233The name of the parameter is the longest3435Multi Value Options36-------------------3738Sometimes you have options that take more than one argument. For options39only a fixed number of arguments is supported. This can be configured by40the ``nargs`` parameter. The values are then stored as tuple:4142Example::434445 @click.command()46 @click.option('--pos', nargs=2, type=float)47 def findme(pos):48 print('%s / %s' % pos)4950And on the command line::5152 $ python findme.py --pos 2.0 3.053 2.0 / 3.05455Boolean Flags56-------------5758Boolean flags are options that can be enabled or disabled. This can be59accomplished by defining two flags in one go separated by a slash (``/``)60for enabling or disabling the option. Click always wants you to provide61an enable and disable flag so that you can change the default later.6263Example::6465 import os6667 @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)7475And on the command line::7677 $ python info.py --shout78 DARWIN!!!!11179 $ python info.py --no-shout80 Darwin8182If you really don't want an off-switch you can just define one and83manually inform click that something is a flag::8485 import os8687 @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)9495And on the command line::9697 $ python info.py --shout98 DARWIN!!!!11199100Feature Switches101----------------102103In addition to boolean flag there are also feature switches. These are104implemented by setting multiple options to the same parameter name and by105defining a flag value. To select a default the default flag can be set to106`True` on the one that should be the default.107108Example::109110 import os111112 @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)())118119And on the command line::120121 $ python info.py --upper122 DARWIN123 $ python info.py --lower124 darwin125 $ python info.py126 DARWIN127128.. _option-prompting:129130Prompting131---------132133Sometimes you want parameters that can either be provided from the command134line or if not, you want to ask for user input. This can be implemented135with click by defining a prompt string:136137Example::138139 import os140141 @click.command()142 @click.option('--name', prompt=True)143 def hello(name):144 print('Hello %s!' % name)145146And what it looks like::147148 $ python hello.py --name=John149 Hello John!150 $ python hello.py151 Name: John152 Hello John!153154If you are not happy with the default prompt string you can ask for155a different one::156157 import os158159 @click.command()160 @click.option('--name', prompt='Your name please')161 def hello(name):162 print('Hello %s!' % name)163164What it looks like::165166 $ python hello.py167 Your name please: John168 Hello John!169170Password Prompts171----------------172173Click also supports hidden prompts and asking for confirmation. This is174useful for password input::175176 @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'))181182What it looks like::183184 $ python encrypt.py185 Password:186 Repeat for confirmation:187 Encrypting password to frpher188189Because this combination of parameters is quite common this can also be190replaced with the :func:`password_option` decorator::191192 @click.command()193 @click.password_option()194 def encrypt(password):195 print('Encrypting password to %s' % password.encode('rot13'))196197Callbacks and Eager Options198---------------------------199200Sometimes you want a parameter to completely change the execution flow.201This for instance is the case when you want to have a ``--version``202parameter that prints out the version and then exists the application.203204In such cases you need two concepts: eager parameters and a callback. An205eager parameter is a parameter that is handled before others and a206callback is what executes after the parameter is handled. The eagerness207is necessary so that an earlier required parameter does not produce an208error message. For isntance if ``--version`` was not eager and a209parameter ``--foo`` was required and defined before, you would need to210specify it for ``--version`` to work.211212A callback is a function that is invoked with two parameters: the current213:class:`Context` and the value. The context provides some useful features214such as quitting the application and gives access to other already215processed parameters.216217Here an example for a ``--version`` flag::218219 def print_version(ctx, value):220 if not value:221 return222 print('Version 1.0')223 ctx.exit()224225 @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!')230231The `expose_value` parameter prevents the now pretty pointless ``version``232parameter to be passed to the callback. If that was not specified a233boolean would be passed to the `hello` script.234235What it looks like::236237 $ python hello.py 238 Hello World!239 $ python hello.py --version240 Version 1.0241242Yes Parameters243--------------244245For dangerous operations it's very useful to be able to ask a user for246confirmation. This can be done by adding a boolean ``--yes`` flag and247asking for confirmation if the user did not provide it and to fail in a248callback::249250 def abort_if_false(ctx, value):251 if not value:252 ctx.abort()253254 @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!')260261And what it looks like on the command line::262263 $ python dropdb.py264 Are you sure you want to drop the db? [yN]: n 265 Aborted!266 $ python dropdb.py --yes267 Dropped all tables!268269Because this combination of parameters is quite common this can also be270replaced with the :func:`confirmation_option` decorator::271272 @click.command()273 @click.confirmation_option('Are you sure you want to drop the db?')274 def dropdb():275 print('Dropped all tables!')276277Values from Environment Variables278---------------------------------279280A very useful feature of click is the ability to accept parameters from281environment variables in addition to regular parameters. This allows282tools to be much easier automated. For instance you might want to pass283the config file as ``--config`` parameter but also support exporting a284``TOOL_CONFIG=hello.cfg`` key / value pair for a nicer development285experience.286287This is supported by click in two ways. One is to automatically build288environment variables which is supported for options only. To enable this289feature the ``auto_envvar_prefix`` parameter needs to be passed to the290script that is invoked. Each command and parameter is then added as291underscore separated variable in uppercase. So if you have a subcommand292called ``foo`` taking an option called ``bar`` and the prefix is293``MY_TOOL`` then the variable is ``MY_TOOL_FOO_BAR``.294295Example usage::296297 @click.command()298 @click.option('--username')299 def greet(username):300 print('Hello %s!' % username)301302 if __name__ == '__main__':303 greet(auto_envvar_prefix='GREETER')304305And from the command line::306307 $ export GREETER_USERNAME=john308 $ python greet.py309 Hello john!310311The second option is to manually pull values in from specific environment312variables by defining the name of the environment variable on the option.313314Example usage::315316 @click.command()317 @click.option('--username', envvar='USERNAME')318 def greet(username):319 print('Hello %s!' % username)320321 if __name__ == '__main__':322 greet()323324And from the command line::325326 $ export USERNAME=john327 $ python greet.py328 Hello john!329330In that case it can also be a list of different environment variables331where the first one is picked.
added:docs/parameters.rst+108 added
1Parameters2==========34.. currentmodule:: click56Click supports two types of parameters for scripts: options and arguments.7There is generally some confusion among authors of command line scripts8when to use which so here is a quick overview of the differences. As the9name indicates an option is optional. While arguments can be optional10within reason they are much more restricted in how they can be optional.1112To help you pick when to use what the recommendation is to use arguments13exclusively for things like going to subcommands or input filenames /14URLs and have everything else be an option instead.1516Differences17-----------1819Arguments can do less than options. The following features are only20available for options:2122* 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)2829On the other hand arguments unlike options can accept an arbitrary number30of arguments. Options can strictly ever only accept a fixed number of31arguments (defaults to 1).3233Parameter Types34---------------3536Parameters can be of different types. Types can be implemented with37different behavior and some are supported out of the box:3839``str`` / :data:`click.STRING`:40 The default parameter type which indicates unicode strings.4142``int`` / :data:`click.INT`:43 A parameter that only accepts integers.4445``float`` / :data:`click.FLOAT`:46 A parameter that only accepts floating point values.4748``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`.5354:class:`click.File`:55 A parameter that is an opened file. It can be opened for reading or56 writing.5758Custom parameter types can be implemented by subclassing59:class:`click.ParamType`. For simple cases passing a python function that60failes with a `ValueError` is also supported though discouraged.6162Parameter Names63---------------6465Parameters (both options and arguments) accept a number of positional66arguments which are the parameter declarations. Each string string with a67single dash is added as short argument, each string starting with a double68dash as long one. If a string is added without any dashes it's the69internal parameter name which is also used as variable name.7071If a parameter does not have a name without dashes added one is generated72automatically by taking the longest argument and converting all dashes to73underscores. So for an option with ``('-f', '--foo-bar')`` the parameter74name is `foo_bar`. For an option with ``('-x',)`` the parameter is `x`.75For an option with ``('-f', '--filename', 'dest')`` the parameter is76called `dest`.7778Implementing Custom Types79-------------------------8081To implement a custom type you need to subclass the :class:`ParamType`82class. Types can be invoked with or without context and parameter object83which is why they need to be able to deal with this.8485The following code implements an integer type that accepts hex, octal86numbers in addition to normal integers and converts them into regular87integers::8889 import click9091 class BasedIntParamType(click.ParamType):92 name = 'integer'9394 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)103104 BASED_INT = BasedIntParamType()105106As you can see a subclass needs to implement the :meth:`ParamType.convert`107method and optionally provide the :attr:`ParamType.name` attribute. The108latter can be used for documentation purposes.
added:docs/prompts.rst+47 added
1User Input Prompts2==================34.. currentmodule:: click56Click supports prompts in two different places. One is automated prompts7when the parameter handling happens. The second option is to ask for8prompts at a later point independently.910This can be accomplished with the :func:`prompt` function which asks for11valid input according to a type or the :func:`confirm` function which asks12for confirmation (yes / no).1314Option Prompts15--------------1617Option prompts are integrated into the option interface. See18:ref:`option-prompting` for more information. Internally it19automatically calls into :func:`prompt` or :func:`confirm` as necessary.2021Input Prompts22-------------2324To manually ask for user input you can use the :func:`prompt` function.25By default it accepts any unicode string but you can ask for any other26type. For instance you can ask for a valid integer::2728 value = click.prompt('Please enter a valid integer', type=int)2930The type is also automatically detected if a default is provided. The31following for instance will only accept floats::3233 value = click.prompt('Please enter a number', default=42.0)3435Confirmation Prompts36--------------------3738To ask a user if he wants to continue with an action the :func:`confirm`39function comes in handy. By default it returns the result of the prompt40as boolean value::4142 if click.confirm('Do you want to continue?'):43 print('Well done!')4445There is also the option to make it automatically abort the execution::4647 click.confirm('Do you want to continue?', abort=True)
added:docs/quickstart.rst+110 added
1Quickstart2==========34.. currentmodule:: click56You can get the library directly from PyPI::78 pip install click910Basic Concepts11--------------1213Click is based on declaring commands through decorators. Internally there14is a non-decorator interface for advanced use cases but it's discouraged15for high-level usage.1617A function becomes a click command line tool by decorating it through18:func:`click.command`. In the most simple version just decorating a19function with this decorator will make it into a callable script::2021 import click2223 @click.command()24 def hello():25 print('Hello World!')2627What's happening is that the decorator converts the function into a28:class:`Command` which then can be invoked::2930 if __name__ == '__main__':31 hello()3233Nesting Commands34----------------3536Commands can be attached to other commands of type :class:`Group`. This37allows arbitrary nesting of scripts. As an example here is a script that38implements two commands for managing databases::3940 import click4142 @click.group()43 def cli():44 pass4546 @click.command()47 def initdb():48 print('Initialized the database')4950 @click.command()51 def dropdb():52 print('Initialized the database')5354 cli.add_command(initdb)55 cli.add_command(dropdb)5657 if __name__ == '__main__':58 cli()5960As you can see the :func:`group` decorator works like the :func:`command`61decorator but creates a :class:`Group` object instead which can be given62multiple subcommands that can be attached with63:meth:`Group.add_command`.6465For simple scripts it's also possible to automatically attach and create a66command by using the :meth:`Group.command` decorator instead. The above67script can be written like this then::6869 import click7071 @click.group()72 def cli():73 pass7475 @cli.command()76 def initdb():77 print('Initialized the database')7879 @cli.command()80 def dropdb():81 print('Initialized the database')8283 if __name__ == '__main__':84 cli()8586Adding Parameters87-----------------8889To add parameters the :func:`option` and :func:`argument` decorators::9091 import click9293 @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)99100 if __name__ == '__main__':101 hello()102103What it looks like::104105 $ python hello.py106 Usage: hello.py [OPTIONS] NAME107108 Options:109 --count=COUNT number of greetings110 --help Show this message and exit.
added:docs/setuptools.rst+76 added
1Usage with Setuptools2=====================34When writing command line utilities it's recommended to write them as5modules that are distributed with setuptools instead of using UNIX6shebangs. There are a bunch of reasons for this.78The first one is that setuptools automatically generates executable9wrapeprs for Windows so your command line utilies work on Windows too.1011The second reason is that setuptools scripts work with virtualenv on UNIX12without the virtualenv having to be activated. This is a very useful13concept which allows you to bundle your scripts with all requirements into14a virtualenv.1516Introduction17------------1819All you need to do to bundle your scripts with setuptools is your script20in a python package and a ``setup.py`` file.2122Imagine this layout::2324 yourpackage/25 cli.py26 setup.py2728Contents of ``cli.py``::2930 import click3132 @click.command()33 def cli():34 """Example script."""35 print('Hello World!')3637Contents of ``setup.py``::3839 from setuptools import setup, find_packages4041 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 )5455The magic is in the ``entry_points`` parameter. Below ``console_scripts``56each line identifies one console script. The first part before the equals57sign (``=``) is the name of the script that should be generate, the second58part is the import path followed by a colon (``:``) with the click59command.6061That's it.6263Testing The Script64------------------6566To test the script you can make a new virtualenv and then install your67package::6869 $ virtualenv venv70 $ . venv/bin/activate71 $ pip install --editable .7273Afterwards your command should be available::7475 $ yourscript76 Hello World!
added:docs/why.rst+43 added
1Why Click?2==========34There are so many libraries out there for writing command line utilities,5why does click exist?67This question is easy to answer: beacuse there is not a single command8line utility for Python out there which ticks the following boxes:910* 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 box1718There are many alternatives to click and you can have a look at them if19you enjoy them better. The obvious ones are ``optparse`` and ``argparse``20from the standard library.2122click is actually implemented as a wrapper around ``optparse`` and does23not implement any parsing itself. The reason it's not based on24``argparse`` is that ``argparse``\'s design does not allow proper nesting25of commands by design and has some deficiencies when it comes to POSIX26compliant argument handling.2728In case ``optparse`` ever gets deprecated and removed from Python,29``click`` will ship a version of it.3031Click is designed to be fun to work with and at the same time not stand in32your way. It's not overly flexible at the same time either. Currently33for instance it does not allow you to customize the help pages too much.34This is intentional because click is desigend to allow you to nest command35line utilities. The idae is that you can have a system that works36together with another system by tacking two click instances together and37they will continue working as they should.3839Too much customizability would break this promise.4041Click was written to support the `Flask <http://flask.pocoo.org/>`_42microframework ecosystem because no tool could provide it with the43functionality it needed.
added:examples/repo/repo.py+51 added
1import click234@click.group()5@click.option('--repo-home', envvar='REPO_HOME')6def 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)111213@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.')18def clone(src, dest, shallow):19 """Clones a repository.2021 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)282930@cli.command()31@click.confirmation_option()32def delete():33 """Deletes a repository.3435 This will throw away the current repository.36 """37 print('Deleted')383940@cli.command()41@click.option('--username', prompt=True, required=True)42@click.option('--email', prompt='E-Mail', required=True)43@click.password_option()44def setuser(username, email, password):45 """Sets the user credentials.4647 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
1from setuptools import setup23setup(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-ignore5dist6build7docs/_build
added:click.py+1533 added
1# -*- coding: utf-8 -*-2"""3 click4 ~~~~~56 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.910 In case optparse ever goes away from the stdlib it will be shipped by11 this module.1213 :copyright: (c) 2014 by Armin Ronacher.14 :license: BSD, see LICENSE for more details.15"""16import os17import sys18import codecs19import inspect20import getpass21import optparse22import textwrap23import fcntl24import termios25import struct26from itertools import chain272829PY2 = sys.version_info[0] == 230if PY2:31 text_type = unicode32 bytes = str3334 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, False50else:51 text_type = str52 raw_input = input5354 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, False707172def 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 cr8283 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])979899class TextWrapper(textwrap.TextWrapper):100101 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, ''108109 def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width):110 space_left = max(width - cur_len, 1)111112 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())118119 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))131132 rv = []133 for text in p:134 rv.append(self.fill(text))135 return '\n\n'.join(rv)136137138def _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 f147148149def 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()158159160class 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.164165 The context is useful as it can pass internal objects around and can166 control special execution features such as reading data from167 environment variables.168169 A context can be used as context manager in which case it will call170 :meth:`close` on teardown.171172 :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 """186187 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 = obj210211 # 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_prefix223224 self._parser = command._make_parser(self)225 self._close_callbacks = []226227 def __enter__(self):228 return self229230 def __exit__(self, exc_type, exc_value, tb):231 self.close()232233 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.239240 :param f: the function to execute on teardown.241 """242 self._close_callbacks.append(f)243 return f244245 def close(self):246 """Invokes all close callbacks."""247 for cb in self._close_callbacks:248 cb()249 self._close_callbacks = []250251 @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()263264 def find_root(self):265 """Finds the outermost context."""266 node = self267 while node.parent is not None:268 node = node.parent269 return node270271 def fail(self, message):272 """Aborts the execution of the program with a specific error273 message.274275 :param message: the error message to fail with.276 """277 raise UsageError(message, self)278279 def abort(self):280 """Aborts the script."""281 raise Abort()282283 def exit(self, code=0):284 """Exits the application with a given exit code."""285 sys.exit(code)286287 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()292293 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()298299300class UsageError(Exception):301 """An internal exception that signals a usage error. This typically302 aborts any further handling.303 """304305 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 = ctx312313314class Abort(Exception):315 """An internal signalling exception that signals click to abort."""316317318class _SimplifiedFormatter(optparse.IndentedHelpFormatter):319320 def __init__(self):321 optparse.IndentedHelpFormatter.__init__(self,322 width=min(get_terminal_size()[0], 80) - 2)323 self.default_tag = ''324325 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))333334 def _format_text(self, text):335 text_width = self.width - self.current_indent336 indent = ' ' * self.current_indent337338 return TextWrapper(text_width,339 initial_indent=indent,340 subsequent_indent=indent,341 replace_whitespace=False).fill_paragraphs(text)342343 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 rv350351 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 rv357358359class _SimplifiedOptionParser(optparse.OptionParser):360361 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 = ctx369370 def expand_prog_name(self, s):371 return s372373 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 rv379380 def error(self, msg):381 raise UsageError(msg, self.__ctx)382383384class 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.388389 :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 = False405406 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)434435 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 param446447 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 parser452453 def _format_extra_help(self, ctx):454 pass455456 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.460461 :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__474475 for param in ctx.command.iter_params_for_processing():476 value, args = param.handle_parse_result(ctx, opts, args)477478 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)))481482 ctx.args = args483484 return ctx485486 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)494495 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.500501 This method is also available by directly calling the instance of502 a :class:`Command`.503504 :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)534535 def __call__(self, *args, **kwargs):536 """Alias for :meth:`main`."""537 return self.main(*args, **kwargs)538539540class 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`.544545 :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 = True558559 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_metavar568569 def _make_parser(self, ctx):570 parser = Command._make_parser(self, ctx)571 parser.usage += ' ' + self.subcommand_metavar572 parser.disable_interspersed_args()573 return parser574575 def _format_extra_help(self, ctx):576 commands = self.list_commands()577 if not commands:578 return579580 longest = len(sorted(commands, key=len)[-1])581582 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))587588 return 'Commands:\n%s' % '\n'.join(subcommand_info)589590 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)596597 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]603604 cmd = self.get_command(ctx, cmd_name)605 if cmd is None:606 ctx.fail('No such command "%s"' % cmd_name)607608 # 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)612613 with cmd.make_context(cmd_name, ctx.args[1:], parent=ctx) as cmd_ctx:614 return cmd.invoke(cmd_ctx)615616 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()621622 def list_commands(self):623 """Returns a list of subcommand names in the order they should624 appear.625 """626 return []627628629class Group(MultiCommand):630 """A group allows a command to have subcommands attached. This is the631 most common way to implement nesting in click.632633 :param commands: a dictionary of commands.634 """635636 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 {}640641 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] = cmd649650 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 decorator661662 def get_command(self, ctx, cmd_name):663 return self.commands.get(cmd_name)664665 def list_commands(self):666 return sorted(self.commands)667668669class ParamType(object):670 """Helper for converting values through types. The following is671 necessary for a valid type:672673 * 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 """682683 #: the descriptive name of this type684 name = None685686 def __call__(self, value, param=None, ctx=None):687 if value is not None:688 return self.convert(value, param, ctx)689690 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 value695696 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)703704705class FuncParamType(ParamType):706707 def __init__(self, func):708 self.name = func.__name__709 self.func = func710711 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)720721722class StringParamType(ParamType):723 name = 'string'724725 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 value737738 def __repr__(self):739 return 'STRING'740741742class IntParamType(ParamType):743 name = 'integer'744745 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)750751 def __repr__(self):752 return 'INT'753754755class BoolParamType(ParamType):756 name = 'boolean'757758 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)767768 def __repr__(self):769 return 'BOOL'770771772class FloatParamType(ParamType):773 name = 'float'774775 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)781782 def __repr__(self):783 return 'FLOAT'784785786class 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).790791 Files can be opened for reading or writing. The special value ``-``792 indicates stdin or stdout depending on the mode.793794 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'799800 def __init__(self, mode='r', encoding=None, errors='strict'):801 self.mode = mode802 self.encoding = encoding803 self.errors = errors804805 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)825826827def 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)852853854class 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.859860 Some settings are supported by both options and arguments.861862 :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'889890 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 = envvar906907 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 metavar914915 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.default921922 def _add_to_parser(self, parser, ctx):923 raise NotImplementedError()924925 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 value935936 def full_process_value(self, ctx, value):937 value = self.process_value(ctx, value)938939 if value is None:940 value = self.get_default(ctx)941942 if value is None and self.required:943 ctx.fail(self.get_missing_message(ctx))944945 return value946947 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 )952953 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)963964 def consume_value(self, ctx, opts, args):965 return None, args966967 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, args975976977class Option(Parameter):978 """Options are usually optionaly values on the command line and979 have some extra features that arguments don't have.980981 All other parameters are passed onwards to the parameter constructor.982983 :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'10041005 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_input10171018 if is_flag is None:1019 if flag_value is not None:1020 is_flag = True1021 else:1022 is_flag = bool(self.secondary_opts)10231024 if is_flag and self.default is None:1025 self.default = False1026 if show_default is None:1027 show_default = False10281029 if flag_value is None:1030 flag_value = not self.default10311032 self.show_default = show_default1033 self.is_flag = is_flag1034 self.flag_value = flag_value10351036 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 = False10421043 self.allow_from_autoenv = allow_from_autoenv10441045 # 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.')10551056 def _parse_decls(self, decls):1057 opts = []1058 secondary_opts = []1059 name = None1060 possible_names = []10611062 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)10761077 if name is None and possible_names:1078 possible_names.sort(key=len)1079 name = possible_names[-1]10801081 if name is None:1082 raise TypeError('Could not determine name for option')10831084 return name.replace('-', '_'), opts, secondary_opts10851086 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))10971098 kwargs = {1099 'help': help,1100 'dest': self.name,1101 'nargs': self.nargs,1102 'metavar': self.make_metavar(),1103 }11041105 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)11251126 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)11371138 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)11461147 # 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)11511152 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))11561157 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)11641165 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)11691170 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, args117511761177class Argument(Parameter):1178 param_type_name = 'argument'11791180 def __init__(self, param_decls, required=True, **attrs):1181 Parameter.__init__(self, param_decls, required=required, **attrs)11821183 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 var11921193 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], []12041205 def _add_to_parser(self, parser, ctx):1206 parser.usage += ' ' + self.make_metavar()12071208 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, args123012311232def _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)124812491250def 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.12541255 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.12581259 All keyword arguments are forwarded to the underlying command class.12601261 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 decorator126812691270def 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 decorator127812791280def _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)128712881289def 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 decorator130013011302def 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 decorator131313141315def confirmation_option(*param_decls, **attrs):1316 """Shortcut for confirmation prompts that can be ignored by bypassed1317 ``--yes`` as parameter.13181319 This is equivalent to decorating a function with :func:`option` with1320 the following parameters::13211322 def callback(ctx, value):1323 if not value:1324 ctx.abort()13251326 @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 decorator134213431344def password_option(*param_decls, **attrs):1345 """Shortcut for password prompts.13461347 This is equivalent to decorating a function with :func:`option` with1348 the following parameters::13491350 @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 decorator136213631364def 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.13681369 :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')13781379 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()13901391 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 decorator139813991400def 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.14041405 Like :func:`version_option` this is implemented as eager option that1406 prints in the callback and exits.14071408 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 decorator142214231424def confirm(text, default=False, abort=False):1425 """Prompts for confirmation (yes/no question).14261427 If the user aborts the input by sending a interrupt signal this1428 function will catch it and raise a :exc:`Abort` exception.14291430 :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 rv145414551456def 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.14611462 If the user aborts the input by sending a interrupt signal this1463 function will catch it and raise a :exc:`Abort` exception.14641465 :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 = None14771478 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()14841485 if value_proc is None:1486 value_proc = convert_type(type, default)14871488 prompt = text1489 if default is not None:1490 prompt = '%s [%s]' % (prompt, default)1491 prompt += ': '14921493 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')151715181519#: A unicode string parameter type which is the implicit default. This1520#: can also be selected by using ``str`` as type.1521STRING = StringParamType()15221523#: An integer parameter. This can also be selected by using ``int`` as1524#: type.1525INT = IntParamType()15261527#: A floating point value parameter. This can also be selected by using1528#: ``float`` as type.1529FLOAT = FloatParamType()15301531#: A boolean parameter. This is the default for boolean flags. This can1532#: also be selected by using ``bool`` as a type.1533BOOL = BoolParamType()
added:setup.py+18 added
1from setuptools import setup234setup(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)