wip revive and split off doc generatin toolchain
[plcapi.git] / pakefile.php
1 <?php
2 /**
3  * Makefile for phpxmlrpc library.
4  * To be used with the Pake tool: https://github.com/indeyets/pake/wiki
5  *
6  * @copyright (c) 2015-2021 G. Giunta
7  *
8  * @todo !important allow user to specify location of docbook xslt instead of the one installed via composer
9  */
10
11 namespace PhpXmlRpc {
12
13 class Builder
14 {
15     protected static $buildDir = 'build';
16     protected static $libVersion;
17     protected static $tools = array(
18         'asciidoctor' => 'asciidoctor',
19         'fop' => 'fop',
20         'php' => 'php',
21         'zip' => 'zip',
22     );
23     protected static $options = array(
24         'repo' => 'https://github.com/gggeek/phpxmlrpc',
25         'branch' => 'master'
26     );
27
28     public static function libVersion()
29     {
30         if (self::$libVersion == null)
31             throw new \Exception('Missing library version argument');
32         return self::$libVersion;
33     }
34
35     public static function buildDir()
36     {
37         return self::$buildDir;
38     }
39
40     public static function workspaceDir()
41     {
42         return self::buildDir().'/workspace';
43     }
44
45     public static function toolsDir()
46     {
47         return self::buildDir().'/tools';
48     }
49
50     /// most likely things will break if this one is moved outside of BuildDir
51     public static function distDir()
52     {
53         return self::buildDir().'/xmlrpc-'.self::libVersion();
54     }
55
56     /// these will be generated in BuildDir
57     public static function distFiles()
58     {
59         return array(
60             'xmlrpc-'.self::libVersion().'.tar.gz',
61             'xmlrpc-'.self::libVersion().'.zip',
62         );
63     }
64
65     public static function getOpts($args=array(), $cliOpts=array())
66     {
67         if (count($args) > 0)
68         //    throw new \Exception('Missing library version argument');
69             self::$libVersion = $args[0];
70
71         foreach (self::$tools as $name => $binary) {
72             if (isset($cliOpts[$name])) {
73                 self::$tools[$name] = $cliOpts[$name];
74             }
75         }
76
77         foreach (self::$options as $name => $value) {
78             if (isset($cliOpts[$name])) {
79                 self::$options[$name] = $cliOpts[$name];
80             }
81         }
82
83         //pake_echo('---'.self::$libVersion.'---');
84     }
85
86     /**
87      * @param string $name
88      * @return string
89      */
90     public static function tool($name)
91     {
92         return self::$tools[$name];
93     }
94
95     /**
96      * @param string $name
97      * @return string
98      */
99     public static function option($name)
100     {
101         return self::$options[$name];
102     }
103
104     /**
105      * @param string $inFile
106      * @param string $xssFile
107      * @param string $outFileOrDir
108      * @throws \Exception
109      */
110     public static function applyXslt($inFile, $xssFile, $outFileOrDir)
111     {
112         if (!file_exists($inFile)) {
113             throw new \Exception("File $inFile cannot be found");
114         }
115         if (!file_exists($xssFile)) {
116             throw new \Exception("File $xssFile cannot be found");
117         }
118
119         // Load the XML source
120         $xml = new \DOMDocument();
121         $xml->load($inFile);
122         $xsl = new \DOMDocument();
123         $xsl->load($xssFile);
124
125         // Configure the transformer
126         $processor = new \XSLTProcessor();
127         if (version_compare(PHP_VERSION, '5.4', "<")) {
128             if (defined('XSL_SECPREF_WRITE_FILE')) {
129                 ini_set("xsl.security_prefs", XSL_SECPREF_CREATE_DIRECTORY | XSL_SECPREF_WRITE_FILE);
130             }
131         } else {
132             // the php online docs only mention setSecurityPrefs, but somehow some installs have setSecurityPreferences...
133             if (method_exists('XSLTProcessor', 'setSecurityPrefs')) {
134                 $processor->setSecurityPrefs(XSL_SECPREF_CREATE_DIRECTORY | XSL_SECPREF_WRITE_FILE);
135             } else {
136                 $processor->setSecurityPreferences(XSL_SECPREF_CREATE_DIRECTORY | XSL_SECPREF_WRITE_FILE);
137             }
138         }
139         $processor->importStyleSheet($xsl); // attach the xsl rules
140
141         if (is_dir($outFileOrDir)) {
142             if (!$processor->setParameter('', 'base.dir', realpath($outFileOrDir))) {
143                 echo "setting param base.dir KO\n";
144             }
145         }
146
147         $out = $processor->transformToXML($xml);
148
149         if (!is_dir($outFileOrDir)) {
150             file_put_contents($outFileOrDir, $out);
151         }
152     }
153
154     public static function highlightPhpInHtml($content)
155     {
156         $startTag = '<pre class="programlisting">';
157         $endTag = '</pre>';
158
159         //$content = file_get_contents($inFile);
160         $last = 0;
161         $out = '';
162         while (($start = strpos($content, $startTag, $last)) !== false) {
163             $end = strpos($content, $endTag, $start);
164             $code = substr($content, $start + strlen($startTag), $end - $start - strlen($startTag));
165             if ($code[strlen($code) - 1] == "\n") {
166                 $code = substr($code, 0, -1);
167             }
168
169             $code = str_replace(array('&gt;', '&lt;'), array('>', '<'), $code);
170             $code = highlight_string('<?php ' . $code, true);
171             $code = str_replace('<span style="color: #0000BB">&lt;?php&nbsp;<br />', '<span style="color: #0000BB">', $code);
172
173             $out = $out . substr($content, $last, $start + strlen($startTag) - $last) . $code . $endTag;
174             $last = $end + strlen($endTag);
175         }
176         $out .= substr($content, $last, strlen($content));
177
178         return $out;
179     }
180 }
181
182 }
183
184 namespace {
185
186 use PhpXmlRpc\Builder;
187
188 function run_default($task=null, $args=array(), $cliOpts=array())
189 {
190     echo "Syntax: pake {\$pake-options} \$task \$lib-version [\$git-tag] {\$task-options}\n";
191     echo "\n";
192     echo "  Run 'pake help' to list all pake options\n";
193     echo "  Run 'pake -T' to list available tasks\n";
194     echo "  Run 'pake -P' to list all available tasks (including hidden ones) and their dependencies\n";
195     echo "\n";
196     echo "  Task options:\n";
197     echo "      --repo=REPO      URL of the source repository to clone. Defaults to the github repo.\n";
198     echo "      --branch=BRANCH  The git branch to build from.\n";
199     echo "      --asciidoctor=ASCIIDOCTOR Location of the asciidoctor command-line tool\n";
200     echo "      --fop=FOP        Location of the apache fop command-line tool\n";
201     echo "      --php=PHP        Location of the php command-line interpreter\n";
202     echo "      --zip=ZIP        Location of the zip tool\n";
203 }
204
205 function run_getopts($task=null, $args=array(), $cliOpts=array())
206 {
207     Builder::getOpts($args, $cliOpts);
208 }
209
210 /**
211  * Downloads source code in the build workspace directory, optionally checking out the given branch/tag
212  */
213 function run_init($task=null, $args=array(), $cliOpts=array())
214 {
215     // download the current version into the workspace
216     $targetDir = Builder::workspaceDir();
217
218     // check if workspace exists and is not already set to the correct repo
219     if (is_dir($targetDir) && pakeGit::isRepository($targetDir)) {
220         $repo = new pakeGit($targetDir);
221         $remotes = $repo->remotes();
222         if (trim($remotes['origin']['fetch']) != Builder::option('repo')) {
223             throw new Exception("Directory '$targetDir' exists and is not linked to correct git repo");
224         }
225
226         /// @todo should we not just fetch instead?
227         $repo->pull();
228     } else {
229         pake_mkdirs(dirname($targetDir));
230         $repo = pakeGit::clone_repository(Builder::option('repo'), Builder::workspaceDir());
231     }
232
233     $repo->checkout(Builder::option('branch'));
234 }
235
236 /**
237  * Runs all the build steps.
238  *
239  * (does nothing by itself, as all the steps are managed via task dependencies)
240  */
241 function run_build($task=null, $args=array(), $cliOpts=array())
242 {
243 }
244
245 function run_clean_doc()
246 {
247     pake_remove_dir(Builder::workspaceDir().'/doc/api');
248     $finder = pakeFinder::type('file')->name('*.html');
249     pake_remove($finder, Builder::workspaceDir().'/doc/manual');
250     $finder = pakeFinder::type('file')->name('*.xml');
251     pake_remove($finder, Builder::workspaceDir().'/doc/manual');
252 }
253
254 /**
255  * Generates documentation in all formats
256  */
257 function run_doc($task=null, $args=array(), $cliOpts=array())
258 {
259     $docDir = Builder::workspaceDir().'/doc';
260
261     // API docs
262
263     /// @todo sami is anbandonware, whereas phpdocumentor is not. switch back to phpdocumentor
264
265     // from phpdoc comments using phpdocumentor
266     //$cmd = Builder::tool('php');
267     //pake_sh("$cmd " . Builder::toolsDir(). "/vendor/bin/phpdoc run -d ".Builder::workspaceDir().'/src'." -t ".Builder::workspaceDir().'/doc/api --title PHP-XMLRPC');
268
269     // from phpdoc comments using Sami
270     $samiConfig = <<<EOT
271 <?php
272     \$iterator = Symfony\Component\Finder\Finder::create()
273       ->files()
274       ->exclude('debugger')
275       ->exclude('demo')
276       ->exclude('doc')
277       ->exclude('tests')
278       ->in('./build/workspace');
279     return new Sami\Sami(\$iterator, array(
280         'title' => 'PHP-XMLRPC',
281         'build_dir' => 'build/workspace/doc/api',
282         'cache_dir' => 'build/cache',
283     ));
284 EOT;
285     file_put_contents('build/sami_config.php', $samiConfig);
286     $cmd = Builder::tool('php');
287     pake_sh("$cmd " . Builder::toolsDir(). "/vendor/bin/sami.php update -vvv build/sami_config.php");
288
289     // User Manual
290
291     // html (single file) from asciidoc
292     $cmd = Builder::tool('asciidoctor');
293     pake_sh("$cmd -d book $docDir/manual/phpxmlrpc_manual.adoc");
294
295     // then docbook from asciidoc
296     /// @todo create phpxmlrpc_manual.xml with the good version number
297     /// @todo create phpxmlrpc_manual.xml with the date set to the one of last commit (or today?)
298     pake_sh("$cmd -d book -b docbook $docDir/manual/phpxmlrpc_manual.adoc");
299
300     # Other tools for docbook...
301     #
302     # jade cmd yet to be rebuilt, starting from xml file and putting output in ./out dir, e.g.
303     #   jade -t xml -d custom.dsl xmlrpc_php.xml
304     #
305     # convertdoc command for xmlmind xxe editor
306     #   convertdoc docb.toHTML xmlrpc_php.xml -u out
307     #
308     # saxon + xerces xml parser + saxon extensions + xslthl: adds a little syntax highligting
309     # (bold and italics only, no color) for php source examples...
310     #   java \
311     #   -classpath c:\programmi\saxon\saxon.jar\;c:\programmi\saxon\xslthl.jar\;c:\programmi\xerces\xercesImpl.jar\;C:\htdocs\xmlrpc_cvs\docbook-xsl\extensions\saxon65.jar \
312     #   -Djavax.xml.parsers.DocumentBuilderFactory=org.apache.xerces.jaxp.DocumentBuilderFactoryImpl \
313     #   -Djavax.xml.parsers.SAXParserFactory=org.apache.xerces.jaxp.SAXParserFactoryImpl \
314     #   -Dxslthl.config=file:///c:/htdocs/xmlrpc_cvs/docbook-xsl/highlighting/xslthl-config.xml \
315     #   com.icl.saxon.StyleSheet -o xmlrpc_php.fo.xml xmlrpc_php.xml custom.fo.xsl use.extensions=1
316
317     // HTML (multiple files) from docbook - discontinued, as we use the nicer-looking html gotten from asciidoc
318     /*Builder::applyXslt($docDir.'/manual/phpxmlrpc_manual.xml', $docDir.'/build/custom.xsl', $docDir.'/manual');
319     // post process html files to highlight php code samples
320     foreach(pakeFinder::type('file')->name('*.html')->in($docDir.'/manual') as $file)
321     {
322         file_put_contents($file, Builder::highlightPhpInHtml(file_get_contents($file)));
323     }*/
324
325     // PDF file from docbook
326
327     // convert to fo and then to pdf using apache fop
328     Builder::applyXslt($docDir.'/manual/phpxmlrpc_manual.xml', $docDir.'/build/custom.fo.xsl', $docDir.'/manual/phpxmlrpc_manual.fo.xml');
329     $cmd = Builder::tool('fop');
330     pake_sh("$cmd $docDir/manual/phpxmlrpc_manual.fo.xml $docDir/manual/phpxmlrpc_manual.pdf");
331
332     // cleanup
333     unlink($docDir.'/manual/phpxmlrpc_manual.xml');
334     unlink($docDir.'/manual/phpxmlrpc_manual.fo.xml');
335 }
336
337 function run_clean_dist()
338 {
339     pake_remove_dir(Builder::distDir());
340     $finder = pakeFinder::type('file')->name(Builder::distFiles());
341     pake_remove($finder, Builder::buildDir());
342 }
343
344 /**
345  * Creates the tarballs for a release
346  */
347 function run_dist($task=null, $args=array(), $cliOpts=array())
348 {
349     // copy workspace dir into dist dir, without git
350     pake_mkdirs(Builder::distDir());
351     $finder = pakeFinder::type('any')->ignore_version_control();
352     pake_mirror($finder, realpath(Builder::workspaceDir()), realpath(Builder::distDir()));
353
354     // remove unwanted files from dist dir
355
356     // also: do we still need to run dos2unix?
357
358     // create tarballs
359     $cwd = getcwd();
360     chdir(dirname(Builder::distDir()));
361     foreach(Builder::distFiles() as $distFile) {
362         // php can not really create good zip files via phar: they are not compressed!
363         if (substr($distFile, -4) == '.zip') {
364             $cmd = Builder::tool('zip');
365             $extra = '-9 -r';
366             pake_sh("$cmd $distFile $extra ".basename(Builder::distDir()));
367         }
368         else {
369             $finder = pakeFinder::type('any')->pattern(basename(Builder::distDir()).'/**');
370             // see https://bugs.php.net/bug.php?id=58852
371             $pharFile = str_replace(Builder::libVersion(), '_LIBVERSION_', $distFile);
372             pakeArchive::createArchive($finder, '.', $pharFile);
373             rename($pharFile, $distFile);
374         }
375     }
376     chdir($cwd);
377 }
378
379 function run_clean_workspace($task=null, $args=array(), $cliOpts=array())
380 {
381     pake_remove_dir(Builder::workspaceDir());
382 }
383
384 /**
385  * Cleans up the whole build directory
386  * @todo 'make clean' usually just removes the results of the build, distclean removes all but sources
387  */
388 function run_clean($task=null, $args=array(), $cliOpts=array())
389 {
390     pake_remove_dir(Builder::buildDir());
391 }
392
393 // helper task: display help text
394 pake_task( 'default' );
395 // internal task: parse cli options
396 pake_task('getopts');
397 pake_task('init', 'getopts');
398 pake_task('doc', 'getopts', 'init', 'clean-doc');
399 pake_task('build', 'getopts', 'init', 'doc');
400 pake_task('dist', 'getopts', 'init', 'build', 'clean-dist');
401 pake_task('clean-doc', 'getopts');
402 pake_task('clean-dist', 'getopts');
403 pake_task('clean-workspace', 'getopts');
404 pake_task('clean', 'getopts');
405
406 }