Command line tool to duplicate/modify version number strings across source code and distribution files according to syntax context.

⌈⌋ branch:  version numbers get/write


Check-in [789c1a3df8]

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Moved data/regex into cfg{}
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1:789c1a3df8a840e7cc5738713ec4e44f11e21d37
User & Date: mario 2014-02-08 23:24:55
Context
2014-02-09
00:35
Allow reading Version: from .deb archive check-in: 6b2d027406 user: mario tags: trunk
2014-02-08
23:24
Moved data/regex into cfg{} check-in: 789c1a3df8 user: mario tags: trunk
03:57
Add wordpress and document 'any' type. check-in: d56b82dd48 user: mario tags: trunk
Changes

Changes to version.php.

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
..
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
...
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
...
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
...
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
...
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
...
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
...
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
#!/usr/bin/php
<?php
/**
 * type: cli
 * title: Version Get/Write
 * description: Commandline tool to read and update source code version numbers
 * version: 3.2.2
 * category: tools
 * 
 *
 * This tool reads various formats of "Version: x.y*" from and to source code
 * or distribution files. It's useful for keeping them synced or prepared without
 * further packaging tool scripting.
 *
 * It's indifferent to versioning schemes, understands various source and target
 * syntax variations:
 *
 *   PHP plugins   # version: 1.2.3       RPM/EPM spec    %version 7.1
 *   PHP docblock  * @version: 0.0        Debian control  Version: 2.0-3
 *   Python src    version = 
 *   Script vars   $version = "1.0";      JSON    { "version": "0.2.2" }
 *
 * Multiple commands are supported and can be chained often quite readibly to
 * move version numbers across files:
 *
 *   version  get file.php
 *
................................................................................
 *
 *    VERSION=$(version get orig.c ++)
 *    version write $VERSION dest.cpp
 *
 * There's no commandline option for custom regexen, to eschew code duplication
 * in said shell scripts.
 *
 *@version 3.2.1-0
 */               


 




#-- regular expressions


$rx_ver        = "(  (?<epoch>\d+:)? (?<major>\d+) \.(?<minor>\d+) (?:\.(?<patch>\d+))? (?<suffix>[\d\w-+.~_]*)  )";

$rx_ws  =  $s  = "[^\S\R]";    // whitespace without linebreaks



$rx_end        = " $s* $";   // default regex end match (everything after the $rx_ver match)



$rx_format = array(
     // Debian package description
    "debian"   =>       "^ Version: $s+ ",
     // RPM package description
    "rpmspec"  =>       "^ % version $s+",
     // Generic meta data comment block
    "plugin"   =>       "^ $s* (?:\*|\#|\/\/) $s* (?i) version: $s* ",

     // Documentation
    "docblock" =>       "^ $s* [*] $s? @version $s+",
     // Constant declarations
    "const"    => array("^ $s* const $s+ \w*VERSION $s+ = $s+ [\'\"]",  $rx_ver,   "[\'\"]; $rx_end"),

     // PHP constant declarations
    "define"   => array("^ $s* define \( [\'\"] \w*VERSION [\'\"], $s* [\'\"]",  $rx_ver,  "[\'\"]\); $rx_end"),

     // Scripting language variable or property assignments
    "var"      => array("^ $s* (?:var|public|private|protected|static|global)? $s* \$\w*version $s* = $s* [\'\"]",  $rx_ver,  "[\'\"]; $rx_end"),

     // Wordpress plugin meta data
    "wordpress"=>       "^ $s* Version: $s* ",
     // Config.ini files
    "ini"      => array("^ $s* version $s* = $s* [\'\"]?",  $rx_ver,  "[\'\"]? $rx_end"),

     // Python module versions
    "python"   => array("^ $s* __version__ $s* = $s* [\'\"]",  $rx_ver,  "[\'\"] $rx_end"),

     // JSON dict as used by PHP composer
    "composer" => array("[{,] $s* \"version\" $s* : $s* \" ",  $rx_ver,  " \"  $s* [,}] "),

     // Single XML tag
    "xmltag"   => array("<version>$s*", $rx_ver, "$s*<\/version>"),
     // Would match ANYTHING in a text file that looks like a version number.
    "_raw_"    => array("", $rx_ver, "")
);


// Map file extensions to regex format names
$ext_to_rxformat = array(
    "php" => array("plugin", "docblock", "define", "const", "var", "wordpress"),
    "control" => array("debian"),
    "py" => array("python", "plugin", "ini"),
    "cpp" => array("plugin", "const"),
    "c" => array("plugin", "ini"),
    "json" => array("composer"),
    "sh" => array("plugin", "ini"),
    "xml" => array("xmltag"),
    "spec" => array("rpmspec"),
    "list" => array("rpmspec"),
   #"txt" => array("_raw_"),  // e.g. distutils2 version.txt
    "any" => array_keys(array_diff_key($rx_format, array("_raw_"=>FALSE))),

);


// Binary file format handlers (see action:: class)
$bin_handlers = array(
    "phar" => "bin_phar",
);


// Command aliases
$action_aliases = aliases_flip(array(
    "write" => array("save", "write", "update"),
    "get" => array("get", "from"),
    "read" => array("read", "fetch"),
    "show" => array("show", "echo", "print"),
    "increment" => array("++", "add", "inc", "incr", "increment"),
    "bump" => array("bump", "suffix", "release",),
    "format" => array("fmt", "format", "and", "then", "set"),
    "last" => array("last"),








    "help" => array("help"),
    "dry" => array("dry", "nowrite", "dryrun"),

));






#-- most commands require a pair of $action + $file to be run
$version = "";
class command {
    var $action = "";
    var $file = "";
    var $ext = "";
    var $format = "";
    var $count = 1;
................................................................................
    var $version;
}
$cmd = new command();
$last = new command();





#-- init argv
$argv = array_slice($_SERVER["argv"], 1);

// no args = help
if (empty($argv)) {
    action::help();
}

// just one filename arg = default action to 'get'
elseif (count($argv) == 1) {
    $cmd->action = "get";  //@todo: get_ or set_ from argv[0] basename?
}



#-- go over args list


foreach ($argv as $arg) {


    #-- categorize current argument
    
    // It's a filename
    if (file_exists($arg)) {
        $cmd->file = $arg;
        $cmd->ext = basename(trim(substr($arg, strrpos($arg, ".")), "."));   // extension or basename (e.g. for DEBIAN/control file)
    }

................................................................................
    // Reuse previous filename and options (but retain current action)
    elseif (ltrim($arg, "-") == "last") {
        $last->action = $cmd->action;
        $cmd = $last;
    }
    
    // Input version number
    elseif (preg_match("/^$rx_ver$/x", $arg)) {
        if (!rx::is_valid_ver($arg)) { error("Invalid version string supplied '$arg'", 33 /*EDOM*/); }
        $cmd->version = $arg;
    }

    // Action/command name
    else {
    
        // extra flags
        if (strpos($arg, ":")) {
            list($arg, $cmd->format, $cmd->count) = explode(":", "$arg:1");
        }
        
        // normalize
        $cmd->action = $action_aliases[ltrim($arg, "-")]
        or error("Unknown action command or non-existant file '$arg'\n", 2 /*ENOENT*/);
    }



    #-- Processing/behaviour
    switch ($cmd->action) {
................................................................................

    #-- binary handlers


    
    // read "version" meta field via binary helpers
    function bin_read($cmd) {
        global $bin_handlers;
        if (isset($bin_handlers[$cmd->ext])) {
            $cmd->version = "";  // unset ->version so it becomes a read action
            return self::bin_write($cmd);
        }
    }

    
    // write "version" meta field to binary
    function bin_write($cmd) {
        global $bin_handlers;
        if (isset($bin_handlers[$cmd->ext])) {
            $h = $bin_handlers[$cmd->ext];
            if (method_exists("action", $h)) {
                call_user_func(array("action",$h), $cmd);
                return TRUE;
            }
        }
    }

................................................................................

/**
 * Regex lookup and preparation
 * *
 */ 
class rx {


    // turn list of formats or ext specifiers into regex list
    function get($cmd) {
        return rx::combine( rx::formats($cmd) );
    }


    /**
     * Return ordered list of regular expression to try.
     * A specific ->type overrides the ->ext defaults.
     *
     */
    function formats($cmd) {

        global $rx_format;    # list of regex
        global $ext_to_rxformat;  # indirect reference
        
        // request a specific rx_format or file extension
        if ($cmd->format) {
            $search = explode(",", $cmd->format);
        }
        // base on file extensions
        elseif ($cmd->ext) {
            $search = array($cmd->ext);
................................................................................
        else {
            $search = array("any");
        }
        
        // unpack remaining file extensions into rx_format names
        $rx = array();
        foreach ($search as $s) {
            if (isset($rx_format[$s])) {
                $rx[] = $rx_format[$s];
            }
            elseif (isset($ext_to_rxformat[$s])) {
                foreach ($ext_to_rxformat[$s] as $s2) {
                    $rx[] = $rx_format[$s2];
                }
            }
            else {
                error("Unkown file extension or rx_format '$s' name", 65 /*ENOPKG*/);
            }
        }
        return $rx;
    }

    
    /**
     * Combine a list of regex parts with $rx_ver, $rx_end
     *
     *   / ($BEGIN)  ($rx_ver)  ($END | $rx_end) /mx
     *
     * Return list, to be readily used in preg_match or _replace.
     *
     */
    function combine($prefixes) {
        global $rx_ver, $rx_end, $rx_ws;

        // patch together
        foreach ($prefixes as $i=>$parts) {

            // parts
            list($begin, $ver, $end) = is_array($parts)
                ? $parts
                : array($parts, $rx_ver, $rx_end);
        
            // wrap



            $prefixes[$i] = "/ (?<begin>$begin) (?<version>$ver) (?<end>$end) /mx";

        }
        
        return array_unique($prefixes);
    }



................................................................................
     * Version string conformance testing.
     *
     *  Applies $rx_ver obviously,
     *  but also checks for `0.0-0error` specials (which --get may have returned on previous runs).
     *
     */
    function is_valid_ver($version) {
        global $rx_ver;
        return preg_match("/^($rx_ver)$/x", $version)
           and !preg_match("/^0\.0([0.-]*|[12]?error)+$/", $version);
    }


}





/**
 * Unpack aliases into flat list.
 *   asvalue => [newkey1, newkey2, newkey3]
 *
 */
function aliases_flip($from) {
    $r = array();
    foreach ($from as $key=>$values) {
        $r[$key] = $key;
        foreach ($values as $v) {
            $r[$v] = $key;
        }
    }
    return $r;
}



/**
 * Abort.
 *
 *
 */






|











|
|







 







|



|
>
>
>
>
|
>
>
|
>
|
>
>
>
|
>
>
>
|
|
|
|
|
|
<
>
|
|
|
<
>
|
<
>
|
<
>
|
|
|
<
>
|
<
>
|
<
>
|
|
|
|
|

>
|
|
|
|
|
|
|
|
|
|
|
|
|
<
>
|
>
>
|
|
|
|
>
>
|
|
<
<
<
<
<
<
<
<
>
>
>
>
>
>
>
>
|
<
>
|

>


>
>
|







 







>
>
|

>




>







|
>
>



|







 







|













|







 







<
|








<
|
|







 







>
|



>








<
<
<







 







|
|

|
|
|








>










<







|


>
>
>
|
>







 







<
|






<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







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
..
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
...
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
...
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
...
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
...
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
...
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
...
581
582
583
584
585
586
587

588
589
590
591
592
593
594




















595
596
597
598
599
600
601
#!/usr/bin/php
<?php
/**
 * type: cli
 * title: Version Get/Write
 * description: Commandline tool to read and update source code version numbers
 * version: 3.2.2-0
 * category: tools
 * 
 *
 * This tool reads various formats of "Version: x.y*" from and to source code
 * or distribution files. It's useful for keeping them synced or prepared without
 * further packaging tool scripting.
 *
 * It's indifferent to versioning schemes, understands various source and target
 * syntax variations:
 *
 *   PHP plugins   # version: 1.2.3       RPM/EPM spec    %version 7.1
 *   PHP docblock  * @version: 0.41       Debian control  Version: 2.0-3
 *   Python/INI    version = 5.3          Constants   const VERSION = '2.0'
 *   Script vars   $version = "1.0";      JSON    { "version": "0.2.2" }
 *
 * Multiple commands are supported and can be chained often quite readibly to
 * move version numbers across files:
 *
 *   version  get file.php
 *
................................................................................
 *
 *    VERSION=$(version get orig.c ++)
 *    version write $VERSION dest.cpp
 *
 * There's no commandline option for custom regexen, to eschew code duplication
 * in said shell scripts.
 *
 *@version 3.2.2-0
 */               



// Tool-specific data
class cfg {

 
    #-- Regular expressions
    
    // Generic version matching with (?&ver)
    static $rx_ver = "(  (?<epoch>\d+:)? (?<major>\d+) \.(?<minor>\d+) (?:\.(?<patch>\d+))? (?<suffix>[\d\w-+.~_]*)  )";

    // Whitespace without linebreaks,
    // will be applied in place of `\s` in the following rx_format list
    static $rx_ws  = "[^\S\R]";

    // Default regex end match (?&end)
    static $rx_end = " \s* $";

    // Filetype/language-specific context matching
    static $rx_format = array(
         // Debian package description
        "debian"   =>       "^ Version: \s+ ",
         // RPM package description
        "rpmspec"  =>       "^ % version \s+",
         // Generic meta data comment block

        "plugin"   =>       "^ \s* (?:\*|\#|\/\/) \s* (?i) version: \s* ",
         // Documentation
        "docblock" =>       "^ \s* [*] \s? @version \s+",
         // Constant declarations

        "const"    => array("^ \s* const \s+ \w*VERSION \s+ = \s+ [\'\"]",  '(?&ver)',   "[\'\"]; (?&end)"),
         // PHP constant declarations

        "define"   => array("^ \s* define \( [\'\"] \w*VERSION [\'\"], \s* [\'\"]",  '(?&ver)',  "[\'\"]\); (?&end)"),
         // Scripting language variable or property assignments

        "var"      => array("^ \s* (?:var|public|private|protected|static|global)? \s* \$\w*version \s* = \s* [\'\"]",  '(?&ver)',  "[\'\"]; (?&end)"),
         // Wordpress plugin meta data
        "wordpress"=>       "^ \s* Version: \s* ",
         // Config.ini files

        "ini"      => array("^ \s* version \s* = \s* [\'\"]?",  '(?&ver)',  "[\'\"]? (?&end)"),
         // Python module versions

        "python"   => array("^ \s* __version__ \s* = \s* [\'\"]",  '(?&ver)',  "[\'\"] (?&end)"),
         // JSON dict as used by PHP composer

        "composer" => array("[{,] \s* \"version\" \s* : \s* \" ",  '(?&ver)',  " \"  \s* [,}] "),
         // Single XML tag
        "xmltag"   => array("<version>\s*", '(?&ver)', "\s*<\/version>"),
         // Would match ANYTHING in a text file that looks like a version number.
        "_raw_"    => array("", '(?&ver)', "")
    );


    // Map file extensions to regex format names
    static $ext_to_rxformat = array(
        "php" => array("plugin", "docblock", "define", "const", "var", "wordpress"),
        "control" => array("debian"),
        "py" => array("python", "plugin", "ini"),
        "cpp" => array("plugin", "const"),
        "c" => array("plugin", "ini"),
        "json" => array("composer"),
        "sh" => array("plugin", "ini"),
        "xml" => array("xmltag"),
        "spec" => array("rpmspec"),
        "list" => array("rpmspec"),
       #"txt" => array("_raw_"),  // e.g. distutils2 version.txt

        "any" => array("debian","rpmspec","plugin","docblock","const","define","var","wordpress","ini","python","composer","xmltag"),
    );


    // Binary file format handlers (see action:: class)
    static $bin_handlers = array(
        "phar" => "bin_phar",
    );


    // Command line aliases
    static $action_aliases = array (








        "write" => "write",  "save" => "write",  "update" => "write",
        "get" => "get",  "from" => "get",
        "read" => "read",  "fetch" => "read",
        "show" => "show",  "echo" => "show",  "print" => "show",
        "increment" => "increment",  "++" => "increment",  "add" => "increment",  "inc" => "increment",  "incr" => "increment",
        "bump" => "bump",  "suffix" => "bump",  "release" => "bump",
        "format" => "format",  "fmt" => "format",   "and" => "format",  "then" => "format",  "set" => "format",
        "last" => "last",  "lastfn" => "last",
       #"help" => "help",

        "dry" => "dry",  "nowrite" => "dry",  "dryrun" => "dry",
    );

}//cfg




#-- Most commands require a pair of $action + $file to be run
$version = "";
class command {
    var $action = "";
    var $file = "";
    var $ext = "";
    var $format = "";
    var $count = 1;
................................................................................
    var $version;
}
$cmd = new command();
$last = new command();





#-- Init argument list
$argv = array_slice($_SERVER["argv"], 1);

// no args = help
if (empty($argv)) {
    action::help();
}

// just one filename arg = default action to 'get'
elseif (count($argv) == 1) {
    $cmd->action = "get";  //@todo: get_ or set_ from argv[0] basename?
}





#-- Iterate over argument list
foreach ($argv as $arg) {


    #-- Categorize current argument
    
    // It's a filename
    if (file_exists($arg)) {
        $cmd->file = $arg;
        $cmd->ext = basename(trim(substr($arg, strrpos($arg, ".")), "."));   // extension or basename (e.g. for DEBIAN/control file)
    }

................................................................................
    // Reuse previous filename and options (but retain current action)
    elseif (ltrim($arg, "-") == "last") {
        $last->action = $cmd->action;
        $cmd = $last;
    }
    
    // Input version number
    elseif (preg_match("/^".cfg::$rx_ver."$/x", $arg)) {
        if (!rx::is_valid_ver($arg)) { error("Invalid version string supplied '$arg'", 33 /*EDOM*/); }
        $cmd->version = $arg;
    }

    // Action/command name
    else {
    
        // extra flags
        if (strpos($arg, ":")) {
            list($arg, $cmd->format, $cmd->count) = explode(":", "$arg:1");
        }
        
        // normalize
        $cmd->action = cfg::$action_aliases[ltrim($arg, "-")]
        or error("Unknown action command or non-existant file '$arg'\n", 2 /*ENOENT*/);
    }



    #-- Processing/behaviour
    switch ($cmd->action) {
................................................................................

    #-- binary handlers


    
    // read "version" meta field via binary helpers
    function bin_read($cmd) {

        if (isset(cfg::$bin_handlers[$cmd->ext])) {
            $cmd->version = "";  // unset ->version so it becomes a read action
            return self::bin_write($cmd);
        }
    }

    
    // write "version" meta field to binary
    function bin_write($cmd) {

        if (isset(cfg::$bin_handlers[$cmd->ext])) {
            $h = cfg::$bin_handlers[$cmd->ext];
            if (method_exists("action", $h)) {
                call_user_func(array("action",$h), $cmd);
                return TRUE;
            }
        }
    }

................................................................................

/**
 * Regex lookup and preparation
 * *
 */ 
class rx {


    // Turn list of formats or ext specifiers into regex list
    function get($cmd) {
        return rx::combine( rx::formats($cmd) );
    }


    /**
     * Return ordered list of regular expression to try.
     * A specific ->type overrides the ->ext defaults.
     *
     */
    function formats($cmd) {




        // request a specific rx_format or file extension
        if ($cmd->format) {
            $search = explode(",", $cmd->format);
        }
        // base on file extensions
        elseif ($cmd->ext) {
            $search = array($cmd->ext);
................................................................................
        else {
            $search = array("any");
        }
        
        // unpack remaining file extensions into rx_format names
        $rx = array();
        foreach ($search as $s) {
            if (isset(cfg::$rx_format[$s])) {
                $rx[] = cfg::$rx_format[$s];
            }
            elseif (isset(cfg::$ext_to_rxformat[$s])) {
                foreach (cfg::$ext_to_rxformat[$s] as $s2) {
                    $rx[] = cfg::$rx_format[$s2];
                }
            }
            else {
                error("Unkown file extension or rx_format '$s' name", 65 /*ENOPKG*/);
            }
        }
        return $rx;
    }

    
    /**
     * Combine a list of regex parts with $rx_ver, $rx_end
     *
     *   / ($BEGIN)  ($rx_ver)  ($END | $rx_end) /mx
     *
     * Return list, to be readily used in preg_match or _replace.
     *
     */
    function combine($prefixes) {


        // patch together
        foreach ($prefixes as $i=>$parts) {

            // parts
            list($begin, $ver, $end) = is_array($parts)
                ? $parts
                : array($parts, cfg::$rx_ver, cfg::$rx_end);
        
            // wrap
            $prefixes[$i] = str_replace(
                array(      "\\s",     "(?&ver)",    "(?&end)"),
                array(cfg::$rx_ws, cfg::$rx_ver, cfg::$rx_end),
                "/ (?<begin>$begin) (?<version>$ver) (?<end>$end) /mx"
            );
        }
        
        return array_unique($prefixes);
    }



................................................................................
     * Version string conformance testing.
     *
     *  Applies $rx_ver obviously,
     *  but also checks for `0.0-0error` specials (which --get may have returned on previous runs).
     *
     */
    function is_valid_ver($version) {

        return preg_match("/^(".cfg::$rx_ver.")$/x", $version)
           and !preg_match("/^0\.0([0.-]*|[12]?error)+$/", $version);
    }


}























/**
 * Abort.
 *
 *
 */