xenogenesi::blog
memento
3d adt android apache2 app apt aria2 build bullet cflags chromium codeigniter debian demoscene dependencies dpkg driver emulator freeglut gcc gfx git glut htaccess javascript json kernel linux make metalink minimal mysql opengl php python raspbian realtime rpi specs template toolchain update-alternatives video wifi wordpress

Phing’s AdhocTaskdefTask adjusting relative paths

I’m using phing to automate a deploy of a php web application to production, phing is a really powerful tool (and easy to use), AdhocTaskdefTask allow to implement custom tags with input and output parameters, for example, I needed to adjust some relative path in production, there’s a simple adhoc task to get the new paths:

<!--
    Usage:
    <relative-path from="${from}" to="${to}"
        output="project_property" />
-->
<adhoc-task name="relative-path"><![CDATA[
    class RelativePath extends Task {
        private $from;
        private $to;
        private $output;

        function setFrom($from) {
            $this->from = $from;
        }

        function setTo($to) {
            $this->to = $to;
        }

        function setOutput($output=null) {
            $this->output = $output;
        }

        function main() {
            $relpath = $this->find_relative_path($this->from, $this->to);
            $this->log("relpath = " . $relpath);
            if ($this->output != null) {
                $this->project->setProperty($this->output, $relpath);
            }
        }

        /**
         * credits: https://gist.github.com/ohaal/2936041
         * Find the relative file system path between two file system paths
         *
         * @param  string  $frompath  Path to start from
         * @param  string  $topath    Path we want to end up in
         *
         * @return string             Path leading from $frompath to $topath
         */
        function find_relative_path ( $frompath, $topath ) {
            $from = explode( DIRECTORY_SEPARATOR, $frompath ); // Folders/File
            $to = explode( DIRECTORY_SEPARATOR, $topath ); // Folders/File
            $relpath = '';

            $i = 0;
            // Find how far the path is the same
            while ( isset($from[$i]) && isset($to[$i]) ) {
                if ( $from[$i] != $to[$i] ) break;
                $i++;
            }
            $j = count( $from ) - 1;
            // Add '..' until the path is the same
            while ( $i <= $j ) {
                if ( !empty($from[$j]) ) $relpath .= '..'.DIRECTORY_SEPARATOR;
                $j--;
            }
            // Go to folder from where it starts differing
            while ( isset($to[$i]) ) {
                if ( !empty($to[$i]) ) $relpath .= $to[$i].DIRECTORY_SEPARATOR;
                $i++;
            }

            // Strip last separator
            return substr($relpath, 0, -1);
        }
    }
]]></adhoc-task>