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