Repository navigation
Expand file tree
/
Copy pathbuild.py.html
More file actions
675 lines (571 loc) · 22.3 KB
/
Copy pathbuild.py.html
File metadata and controls
675 lines (571 loc) · 22.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Docutils 0.11: http://docutils.sourceforge.net/" />
<title>Build Script</title>
<style type="text/css">
/*
:Author: David Goodger (goodger@python.org)
:Id: $Id: html4css1.css 7614 2013-02-21 15:55:51Z milde $
:Copyright: This stylesheet has been placed in the public domain.
Default cascading style sheet for the HTML output of Docutils.
See http://docutils.sf.net/docs/howto/html-stylesheets.html for how to
customize this style sheet.
*/
/* used to remove borders from tables and images */
.borderless, table.borderless td, table.borderless th {
border: 0 }
table.borderless td, table.borderless th {
/* Override padding for "table.docutils td" with "! important".
The right padding separates the table cells. */
padding: 0 0.5em 0 0 ! important }
.first {
/* Override more specific margin styles with "! important". */
margin-top: 0 ! important }
.last, .with-subtitle {
margin-bottom: 0 ! important }
.hidden {
display: none }
a.toc-backref {
text-decoration: none ;
color: black }
blockquote.epigraph {
margin: 2em 5em ; }
dl.docutils dd {
margin-bottom: 0.5em }
object[type="image/svg+xml"], object[type="application/x-shockwave-flash"] {
overflow: hidden;
}
/* Uncomment (and remove this text!) to get bold-faced definition list terms
dl.docutils dt {
font-weight: bold }
*/
div.abstract {
margin: 2em 5em }
div.abstract p.topic-title {
font-weight: bold ;
text-align: center }
div.admonition, div.attention, div.caution, div.danger, div.error,
div.hint, div.important, div.note, div.tip, div.warning {
margin: 2em ;
border: medium outset ;
padding: 1em }
div.admonition p.admonition-title, div.hint p.admonition-title,
div.important p.admonition-title, div.note p.admonition-title,
div.tip p.admonition-title {
font-weight: bold ;
font-family: sans-serif }
div.attention p.admonition-title, div.caution p.admonition-title,
div.danger p.admonition-title, div.error p.admonition-title,
div.warning p.admonition-title, .code .error {
color: red ;
font-weight: bold ;
font-family: sans-serif }
/* Uncomment (and remove this text!) to get reduced vertical space in
compound paragraphs.
div.compound .compound-first, div.compound .compound-middle {
margin-bottom: 0.5em }
div.compound .compound-last, div.compound .compound-middle {
margin-top: 0.5em }
*/
div.dedication {
margin: 2em 5em ;
text-align: center ;
font-style: italic }
div.dedication p.topic-title {
font-weight: bold ;
font-style: normal }
div.figure {
margin-left: 2em ;
margin-right: 2em }
div.footer, div.header {
clear: both;
font-size: smaller }
div.line-block {
display: block ;
margin-top: 1em ;
margin-bottom: 1em }
div.line-block div.line-block {
margin-top: 0 ;
margin-bottom: 0 ;
margin-left: 1.5em }
div.sidebar {
margin: 0 0 0.5em 1em ;
border: medium outset ;
padding: 1em ;
background-color: #ffffee ;
width: 40% ;
float: right ;
clear: right }
div.sidebar p.rubric {
font-family: sans-serif ;
font-size: medium }
div.system-messages {
margin: 5em }
div.system-messages h1 {
color: red }
div.system-message {
border: medium outset ;
padding: 1em }
div.system-message p.system-message-title {
color: red ;
font-weight: bold }
div.topic {
margin: 2em }
h1.section-subtitle, h2.section-subtitle, h3.section-subtitle,
h4.section-subtitle, h5.section-subtitle, h6.section-subtitle {
margin-top: 0.4em }
h1.title {
text-align: center }
h2.subtitle {
text-align: center }
hr.docutils {
width: 75% }
img.align-left, .figure.align-left, object.align-left {
clear: left ;
float: left ;
margin-right: 1em }
img.align-right, .figure.align-right, object.align-right {
clear: right ;
float: right ;
margin-left: 1em }
img.align-center, .figure.align-center, object.align-center {
display: block;
margin-left: auto;
margin-right: auto;
}
.align-left {
text-align: left }
.align-center {
clear: both ;
text-align: center }
.align-right {
text-align: right }
/* reset inner alignment in figures */
div.align-right {
text-align: inherit }
/* div.align-center * { */
/* text-align: left } */
ol.simple, ul.simple {
margin-bottom: 1em }
ol.arabic {
list-style: decimal }
ol.loweralpha {
list-style: lower-alpha }
ol.upperalpha {
list-style: upper-alpha }
ol.lowerroman {
list-style: lower-roman }
ol.upperroman {
list-style: upper-roman }
p.attribution {
text-align: right ;
margin-left: 50% }
p.caption {
font-style: italic }
p.credits {
font-style: italic ;
font-size: smaller }
p.label {
white-space: nowrap }
p.rubric {
font-weight: bold ;
font-size: larger ;
color: maroon ;
text-align: center }
p.sidebar-title {
font-family: sans-serif ;
font-weight: bold ;
font-size: larger }
p.sidebar-subtitle {
font-family: sans-serif ;
font-weight: bold }
p.topic-title {
font-weight: bold }
pre.address {
margin-bottom: 0 ;
margin-top: 0 ;
font: inherit }
pre.literal-block, pre.doctest-block, pre.math, pre.code {
margin-left: 2em ;
margin-right: 2em }
pre.code .ln { color: grey; } /* line numbers */
pre.code, code { background-color: #eeeeee }
pre.code .comment, code .comment { color: #5C6576 }
pre.code .keyword, code .keyword { color: #3B0D06; font-weight: bold }
pre.code .literal.string, code .literal.string { color: #0C5404 }
pre.code .name.builtin, code .name.builtin { color: #352B84 }
pre.code .deleted, code .deleted { background-color: #DEB0A1}
pre.code .inserted, code .inserted { background-color: #A3D289}
span.classifier {
font-family: sans-serif ;
font-style: oblique }
span.classifier-delimiter {
font-family: sans-serif ;
font-weight: bold }
span.interpreted {
font-family: sans-serif }
span.option {
white-space: nowrap }
span.pre {
white-space: pre }
span.problematic {
color: red }
span.section-subtitle {
/* font-size relative to parent (h1..h6 element) */
font-size: 80% }
table.citation {
border-left: solid 1px gray;
margin-left: 1px }
table.docinfo {
margin: 2em 4em }
table.docutils {
margin-top: 0.5em ;
margin-bottom: 0.5em }
table.footnote {
border-left: solid 1px black;
margin-left: 1px }
table.docutils td, table.docutils th,
table.docinfo td, table.docinfo th {
padding-left: 0.5em ;
padding-right: 0.5em ;
vertical-align: top }
table.docutils th.field-name, table.docinfo th.docinfo-name {
font-weight: bold ;
text-align: left ;
white-space: nowrap ;
padding-left: 0 }
/* "booktabs" style (no vertical lines) */
table.docutils.booktabs {
border: 0px;
border-top: 2px solid;
border-bottom: 2px solid;
border-collapse: collapse;
}
table.docutils.booktabs * {
border: 0px;
}
table.docutils.booktabs th {
border-bottom: thin solid;
text-align: left;
}
h1 tt.docutils, h2 tt.docutils, h3 tt.docutils,
h4 tt.docutils, h5 tt.docutils, h6 tt.docutils {
font-size: 100% }
ul.auto-toc {
list-style-type: none }
</style>
<style type="text/css">
/* example stylesheet for Docutils */
/* :Author: Günter Milde */
/* :Copyright: © 2012 G. Milde */
/* :License: This stylesheet is placed in the public domain. */
/* Syntax highlight rules for HTML documents generated with Docutils */
/* using the ``--syntax-highlight=long`` option (new in v. 0.9). */
/* This stylesheet implements Pygment's "default" style with less rules than */
/* pygments-default using class hierarchies. */
/* Use it as example for "handcrafted" styles with only few rules. */
.code { background: #f8f8f8; }
.code .comment { color: #008800; font-style: italic }
.code .error { border: 1px solid #FF0000 }
.code .generic.deleted { color: #A00000 }
.code .generic.emph { font-style: italic }
.code .generic.error { color: #FF0000 }
.code .generic.heading { color: #000080; font-weight: bold }
.code .generic.inserted { color: #00A000 }
.code .generic.output { color: #808080 }
.code .generic.prompt { color: #000080; font-weight: bold }
.code .generic.strong { font-weight: bold }
.code .generic.subheading { color: #800080; font-weight: bold }
.code .generic.traceback { color: #0040D0 }
.code .keyword { color: #AA22FF; font-weight: bold }
.code .keyword.pseudo { font-weight: normal }
.code .literal.number { color: #666666 }
.code .literal.string { color: #BB4444 }
.code .literal.string.doc { color: #BB4444; font-style: italic }
.code .literal.string.escape { color: #BB6622; font-weight: bold }
.code .literal.string.interpol { color: #BB6688; font-weight: bold }
.code .literal.string.other { color: #008000 }
.code .literal.string.regex { color: #BB6688 }
.code .literal.string.symbol { color: #B8860B }
.code .name.attribute { color: #BB4444 }
.code .name.builtin { color: #AA22FF }
.code .name.class { color: #0000FF }
.code .name.constant { color: #880000 }
.code .name.decorator { color: #AA22FF }
.code .name.entity { color: #999999; font-weight: bold }
.code .name.exception { color: #D2413A; font-weight: bold }
.code .name.function { color: #00A000 }
.code .name.label { color: #A0A000 }
.code .name.namespace { color: #0000FF; font-weight: bold }
.code .name.tag { color: #008000; font-weight: bold }
.code .name.variable { color: #B8860B }
.code .operator { color: #666666 }
.code .operator.word { color: #AA22FF; font-weight: bold }
</style>
<style type="text/css">
/* Page layout tweaks */
div.document { width: 6in; }
</style>
</head>
<body>
<div class="document" id="build-script">
<h1 class="title">Build Script</h1>
<!-- #!/usr/bin/env python3.3 -->
<div class="contents topic" id="contents">
<p class="topic-title first">Contents</p>
<ul class="auto-toc simple">
<li><a class="reference internal" href="#design" id="id1">1 Design</a></li>
<li><a class="reference internal" href="#module-overheads" id="id2">2 Module Overheads</a></li>
<li><a class="reference internal" href="#some-logging-setup" id="id3">3 Some Logging Setup</a></li>
<li><a class="reference internal" href="#the-core-functions" id="id4">4 The Core Functions</a></li>
<li><a class="reference internal" href="#the-builders" id="id5">5 The Builders</a></li>
<li><a class="reference internal" href="#file-name-transformations" id="id6">6 File Name Transformations</a></li>
<li><a class="reference internal" href="#main-script" id="id7">7 Main Script</a></li>
</ul>
</div>
<div class="section" id="design">
<h1><a class="toc-backref" href="#id1">1 Design</a></h1>
<p>This is a tool somewhat like ant or scons which will track dependencies
among files and rebuild dependent files when the sources have
changed.</p>
<p>We have to model two kinds of dependencies.</p>
<ul class="simple">
<li>A generic <tt class="docutils literal">*.txt</tt> on <tt class="docutils literal">*.py</tt>, as well as <tt class="docutils literal">*.html</tt> on <tt class="docutils literal">*.txt</tt>.</li>
<li>A specific index.rst on <tt class="docutils literal"><span class="pre">[*.py]</span></tt>.</li>
</ul>
<p>The distinction here is that a generic rule is a template
that applies to a number of files in a kind of 1-1 relationship.</p>
<p>The specific rule is a slightly more general 1-m target-source relationship.</p>
<p>We'll define a function to build if necessary. This will be a higher-order
function which requires a builder which can rebuild the target if
any of the sources have been changed.</p>
<p>We'll define a number of builders for the various tools we need to automate.</p>
</div>
<div class="section" id="module-overheads">
<h1><a class="toc-backref" href="#id2">2 Module Overheads</a></h1>
<p>Module Docstring</p>
<pre class="literal-block">
"""Build all the code sample files into slightly more readable HTML pages.
1. Run pylit to build the RST *.txt files from the code in *.py files.
2. Create the index.rst page as an additional file.
3. Run rst2html.py to build the *.html versions of the *.txt files.
Requires pylit and docutils.
"""
</pre>
<p>Our includes</p>
<pre class="literal-block">
import os
import glob
import subprocess
import datetime
import sys
import logging
from functools import partial
</pre>
</div>
<div class="section" id="some-logging-setup">
<h1><a class="toc-backref" href="#id3">3 Some Logging Setup</a></h1>
<p>We'll define a decorator to create function-specific loggers.
This will provide an extra keyword argument with a named logger.
It slightly simplifies the function because we don't have
to create the logger, we can just assume it will be provided
as an argument.</p>
<pre class="literal-block">
from functools import wraps
def logged(some_function):
@wraps(some_function)
def decorated(*args, **kw):
logger= logging.getLogger(some_function.__name__)
return some_function(*args, logger=logger, **kw)
return decorated
</pre>
<p>When we put the <tt class="docutils literal">@logged</tt> decorator on a function, then
a <tt class="docutils literal">logger=</tt> keyword parameter is set with a
properly named named logger.</p>
<p>Here's the logging setup done as context management.
We'll initialized logging and shutdown logging, also.</p>
<pre class="literal-block">
class Logging_Config:
def __enter__( self, filename="logging.config" ):
logging.basicConfig( stream=sys.stderr, level=logging.INFO )
def __exit__( self, *exc ):
logging.shutdown()
</pre>
</div>
<div class="section" id="the-core-functions">
<h1><a class="toc-backref" href="#id4">4 The Core Functions</a></h1>
<p>The core feature is a <tt class="docutils literal">build_if_needed()</tt> function. This will
check the modification times of the named files. This function
has a simple body:</p>
<ul class="simple">
<li>If the target is newer than the source, do nothing.</li>
<li>If the target is older than the source, apply the builder function.</li>
</ul>
<p>In order to determine if we should build, we need to compare
the modification times of the target and all of the sources.</p>
<pre class="literal-block">
@logged
def target_ok( target_file, *source_list, logger=logging ):
"""Was the target file created after all the source files?
If so, this is OK.
If there's no target, or the target is out-of-date,
it's not OK.
"""
try:
mtime_target= datetime.datetime.fromtimestamp(
os.path.getmtime( target_file ) )
except Exception:
logger.debug( "File {0} not found".format(target_file) )
return False
logger.debug( "Compare {0} {1} >ALL {2}".format(
target_file, mtime_target,
source_list ) )
# If a source doesn't exist, we have bigger problems.
times = (datetime.datetime.fromtimestamp(
os.path.getmtime( source ) ) for source in source_list)
return all(mtime_target > mtime_source for mtime_source in times)
</pre>
<p>The <tt class="docutils literal">build_if_needed()</tt> function requires a builder, a target and
one or more sources. It will apply the <tt class="docutils literal">target_ok()</tt> function
to the target and source files. If necessary, it will apply
the builder.</p>
<pre class="literal-block">
@logged
def build_if_needed( builder, target_file, *source, logger=logging ):
logger.info( "Checking {0}".format(target_file) )
if target_ok( target_file, *source ):
return "ok({0},...)".format(target_file)
builder( target_file, *source )
return "{0}({1},...)".format(builder.__class__.__name__,target_file)
</pre>
<p>We could approach this a different way. We could have
had the build_if_needed() return one of two things:</p>
<ul class="simple">
<li>builder(target,*source) for evaluation later.</li>
<li>ok(target,*source) which is a stub builder that doesn't do anything.</li>
</ul>
<p>The idea would be that the output from the above would be
a script that clearly shows what needs to be done.</p>
</div>
<div class="section" id="the-builders">
<h1><a class="toc-backref" href="#id5">5 The Builders</a></h1>
<p>Each builder is a function which takes the target filename
and a list of source filenames. It's job is to create the target
from the sources.</p>
<p>Since we rely on the <tt class="docutils literal">subprocess.check_call()</tt> function, each
builder is properly a composition of the <tt class="docutils literal">check_call()</tt> and
another function that builds the command which is called.</p>
<p>We'll have several ways to implement the functional composition:
via subclass definition, decorators, or a higher-order function
that combines the two other functions.</p>
<p>We'll opt for a generic higher-order function and create a partial
when we bind in the function that builds the arguments.</p>
<pre class="literal-block">
@logged
def subprocess_builder( make_command, target_file, *source_list, logger=logging ):
command= make_command( target_file, *source_list )
logger.debug( "Command {0}".format(command) )
subprocess.check_call( command )
</pre>
<p>The PyLit subprocess_builder creates a command to run PyLit.</p>
<pre class="literal-block">
def command_pylit( output, *input ):
return ["python3", "-m", "pylit", input[0]]
pylit= partial( subprocess_builder, command_pylit )
</pre>
<p>The rst2html subprocess_builder creates a command to run rst2html.
It includes two common arguments required to make acceptable-looking
content.</p>
<pre class="literal-block">
def command_rst2html( output, *input ):
return ["rst2html.py", "--syntax-highlight=long", "--input-encoding=utf-8", input[0], output]
rst2html= partial( subprocess_builder, command_rst2html )
</pre>
<p>A builder to create an index page. This will apply three internal functions
to create a header, create the body, and create a footer.</p>
<pre class="literal-block">
header= lambda : """
#############################################
Function Python Programming Bonus Code
#############################################
© 2014, Steven F. Lott
.. raw:: html
<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/">
<img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png" /></a>
<br />This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/">Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License</a>.
Some Bonus Material.
"""
footer = lambda : "Updated {0}".format(datetime.datetime.now())
def body( source_list ):
return "\n".join(
"- `{0} <{0}>`_".format(ext_to( name, ".html" ))
for name in source_list)
def make_index( target_file, *source_list ):
with open(target_file,"w") as target:
print( header(), file=target )
print( file=target )
print( body(source_list), file=target )
print( file=target )
print( footer(), file=target )
</pre>
</div>
<div class="section" id="file-name-transformations">
<h1><a class="toc-backref" href="#id6">6 File Name Transformations</a></h1>
<p>When we think about a generic rule, we're usually talking about
simple rewrite from a filename to a filename with a different
extension. We have two filename extension rewriters.</p>
<p>The <tt class="docutils literal">ext_to()</tt> function changes the extension on a filename.</p>
<pre class="literal-block">
def ext_to( filename, new_ext ):
"""Switch .ext"""
name, ext = os.path.splitext( filename )
return name + new_ext
</pre>
<p>The <tt class="docutils literal">ext_add()</tt> function appends an additional extension to
a filename.</p>
<pre class="literal-block">
def ext_add( filename, add_ext ):
"""Add .ext"""
return filename + add_ext
</pre>
<p>We can these functions to transform names so that a generic
rule can apply to many similarly-named files.</p>
</div>
<div class="section" id="main-script">
<h1><a class="toc-backref" href="#id7">7 Main Script</a></h1>
<p>Here's the top-level definition of the dependencies.
There are three sets of rules.</p>
<ul class="simple">
<li><tt class="docutils literal">.txt</tt> based on <tt class="docutils literal">.py</tt> files for files in <tt class="docutils literal">\.py</tt>.</li>
<li><tt class="docutils literal">index.txt</tt> based on <tt class="docutils literal">.txt</tt> files built from names in <tt class="docutils literal">*.py</tt>.</li>
<li><tt class="docutils literal">*.html</tt> based on <tt class="docutils literal">.txt</tt> files for files in <tt class="docutils literal">*.txt</tt></li>
</ul>
<p>We've stated the rules two ways below. One has a list of
dependency function values. The other as a <strong>for</strong> loop.
Both versions seem reasonably clear.</p>
<pre class="literal-block">
def make_files():
files_py = glob.glob( "*.py" )
[build_if_needed( pylit, ext_add(f,'.txt'), f )
for f in files_py]
build_if_needed( make_index, "index.txt",
*[ext_add(f,'.txt') for f in files_py] )
files_txt = glob.glob( "*.txt" )
for f in files_txt:
build_if_needed( rst2html, ext_to(f,'.html'), f )
</pre>
<p>The Main script that does all the work.
We create a logging context. We apply the build-if-needed rules.</p>
<pre class="literal-block">
if __name__ == "__main__":
with Logging_Config():
os.chdir("Bonus")
make_files()
</pre>
</div>
</div>
</body>
</html>