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 [a26eca426c]

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

Overview
Comment:Make quotes optional for 'ini', add '.list' extension, move is_valid_ver into rx::, allow optional dashes on --last command, more comments.
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1:a26eca426c463afb3ed38e8b2a6a3b7c79b68571
User & Date: mario 2014-02-08 03:57:30
Context
2014-02-08
03:57
Add wordpress and document 'any' type. check-in: d56b82dd48 user: mario tags: trunk
03:57
Make quotes optional for 'ini', add '.list' extension, move is_valid_ver into rx::, allow optional dashes on --last command, more comments. check-in: a26eca426c user: mario tags: trunk
01:42
Updated format list to tbl in manpage check-in: 7a72fe8b4c 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
..
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
..
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
...
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
...
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
...
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
...
303
304
305
306
307
308
309

310
311
312
313
314
315
316
...
348
349
350
351
352
353
354

355
356
357
358
359
360
361
...
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
...
521
522
523
524
525
526
527
















528
529
530
531
532
533
534
...
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
#!/usr/bin/php
<?php
/**
 * type: cli
 * title: Version Get/Write
 * description: Commandline tool to read and update source code version numbers
 * version: 3.2.1-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 following source and target
 * text 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
................................................................................
 *
 *   version  read:php file.php  bump  write:spec package.spec
 *
 *   version  1.2.3-dev  write  source.php
 *
 *   version  get  phar://project.phar/.phar/stub.php   write project.phar
 *
 *
 * Everything that's not a valid filename is presumed to be an action command,
 * and can also be prefixed with a - single or -- double dash, as in --get.
 * The order of filenames and actions is often irrelevant.
 *
 *   --get    Loads and shows version from file.
 *   --read   Just loads version, does not display it.
 *   --show   Just prints out current or increased/bumped version number.
................................................................................
 *   --bump   Add/count up packaging/suffix (first num after dash 0.0.0-x)
 *            You can also bump in bigger spans using --bump::2 or --incr::3
 *
 *   --format:ini     Explicit file format
 *   --format:php:2   Also specify how many occurences to replace.
 *
 * You can add the :format:count extras to any command actually, so `-fmt:py:2`
 * and is used in `-write:py:2` implicitly
 * More aliases exist for actions, for example ++ for -increment.
 * For format types you can specify both file extension and internal rx format
 * monikers (ini, var, docblock, ..., `_raw_` for any versiony-looking string).
 *
 * Often you may wish to split up invocations from the shell, as in:
 *
 *    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"   =>       "^ Version: $s+ ",

    "rpmspec"  =>       "^ % version $s+",

    "plugin"   =>       "^ $s* (?:\*|\#|\/\/) $s* (?i) version: $s* ",   // generic meta data comment block

    "docblock" =>       "^ $s* [*] $s? @version $s+",

    "const"    => array("^ $s* const $s+ \w*VERSION $s+ = $s+ [\'\"]",  $rx_ver,   "[\'\"]; $rx_end"),

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

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

    "wordpress"=>       "^ $s* Version: $s* ",

    "ini"      => array("^ $s* version $s* = $s* [\'\"]",  $rx_ver,  "[\'\"] $rx_end"),

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

    "composer" => array("$s* \"version\" $s* : $s* \" ",  $rx_ver,  " \"  $s* [,}] "),

    "xmltag"   => array("<version>$s*", $rx_ver, "$s*<\/version>"),
    "_raw_"    => array("", $rx_ver, "")  // would match anything in a text file that looks like a version number

);

#-- config

$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"),

   #"txt" => array("_raw_"),  // e.g. distutils2 version.txt
    "any" => array_keys(array_diff_key($rx_format, array("_raw_"=>FALSE))),
);

$bin_handlers = array(
    "phar" => "bin_phar",
);

$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",),
................................................................................

    // STDIN
    elseif ($arg == "-") {
        $cmd->file = "php://stdin";
    }

    // Reuse previous filename and options (but retain current action)
    elseif ($arg == "last") {
        $last->action = $cmd->action;
        $cmd = $last;
        #continue;   // oh no, such a great opportunity missed for using `goto`
    }
    
    // Input version number
    elseif (preg_match("/^$rx_ver$/x", $arg)) {
        if (!is_valid_ver($arg)) { error("Invalid version string supplied '$arg'", 33 /*EDOM*/); }
        $cmd->version = $arg;
    }

    // Action/command name
    else {
    
        // extra flags
................................................................................
            print $version;
            break;

        // Read and print from file
        case "get":
            if ($cmd->file) {
                action::read($cmd);
                if (!is_valid_ver($cmd->version)) {
                    // return 0.0-0error on failure
                    fwrite(STDOUT, "0.0-0error");
                    error("No version number found in file '$this->file'", 61/*ENODATA*/);
                    // (while --read should not not)
                }
                print $cmd->version;
                $last=$cmd and $cmd=new command();
................................................................................
                $last=$cmd and $cmd=new command();
            }
            break;

        // Update current $version string into target source code
        case "write":
            if ($cmd->file) {
                if (!is_valid_ver($version)) {
                    // fail
                    error("No valid version number to write. Aborting.", 33 /*EDOM*/);
                }
                action::write($cmd);
                $last=$cmd and $cmd=new command();
            }
            break;
................................................................................
            }
        }
        
        //ooops
        
    }



    /**
     * Read file, and preg_match() for version number.
     *
     */
    function write($cmd) {

................................................................................
        if (isset($cmd->dry)) {
            die("$src");
        }
        else {
            file_put_contents($cmd->file, $src);
        }
    }



    /**
     * Increment patch 0.0.x or minor version number 0.y
     *
     */
    function increment($cmd) {
................................................................................

    #-- binary handlers


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


        $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;
            }
        }
    }

    
    // .phar files
    function bin_phar($cmd) {

        // open and get old meta block
        $p = new Phar($cmd->file);
        $m = $p->getMetadata();
................................................................................
        
            // wrap
            $prefixes[$i] = "/ (?<begin>$begin) (?<version>$ver) (?<end>$end) /mx";
        }
        
        return array_unique($prefixes);
    }

















}





................................................................................
    fwrite(STDERR, basename($_SERVER['argv'][0]) . ": " . $msg . "\n");
    if ($errno > 0) {
        exit($errno   );
    }
}




/**
 * 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);
}

?>






|







|
|







 







<







 







|


|










|








>

>

>
|
>

>

>

>

>

>
|
>

>
|
>

|
>


<
>










>



>



>







 







|


<




|







 







|







 







|







 







>







 







>







 







>
>
|
|
|
>
>












>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
..
33
34
35
36
37
38
39

40
41
42
43
44
45
46
..
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
...
184
185
186
187
188
189
190
191
192
193

194
195
196
197
198
199
200
201
202
203
204
205
...
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
...
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
...
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
...
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
...
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
...
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
...
596
597
598
599
600
601
602















603
#!/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
................................................................................
 *
 *   version  read:php file.php  bump  write:spec package.spec
 *
 *   version  1.2.3-dev  write  source.php
 *
 *   version  get  phar://project.phar/.phar/stub.php   write project.phar
 *

 * Everything that's not a valid filename is presumed to be an action command,
 * and can also be prefixed with a - single or -- double dash, as in --get.
 * The order of filenames and actions is often irrelevant.
 *
 *   --get    Loads and shows version from file.
 *   --read   Just loads version, does not display it.
 *   --show   Just prints out current or increased/bumped version number.
................................................................................
 *   --bump   Add/count up packaging/suffix (first num after dash 0.0.0-x)
 *            You can also bump in bigger spans using --bump::2 or --incr::3
 *
 *   --format:ini     Explicit file format
 *   --format:php:2   Also specify how many occurences to replace.
 *
 * You can add the :format:count extras to any command actually, so `-fmt:py:2`
 * is used in `-write:py:2` implicitly.
 * More aliases exist for actions, for example ++ for -increment.
 * For format types you can specify both file extension and internal rx format
 * monikers (ini, var, const, ... or `_raw_` for any versiony-looking string).
 *
 * Often you may wish to split up invocations from the shell, as in:
 *
 *    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",),
................................................................................

    // STDIN
    elseif ($arg == "-") {
        $cmd->file = "php://stdin";
    }

    // 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
................................................................................
            print $version;
            break;

        // Read and print from file
        case "get":
            if ($cmd->file) {
                action::read($cmd);
                if (!rx::is_valid_ver($cmd->version)) {
                    // return 0.0-0error on failure
                    fwrite(STDOUT, "0.0-0error");
                    error("No version number found in file '$this->file'", 61/*ENODATA*/);
                    // (while --read should not not)
                }
                print $cmd->version;
                $last=$cmd and $cmd=new command();
................................................................................
                $last=$cmd and $cmd=new command();
            }
            break;

        // Update current $version string into target source code
        case "write":
            if ($cmd->file) {
                if (!rx::is_valid_ver($version)) {
                    // fail
                    error("No valid version number to write. Aborting.", 33 /*EDOM*/);
                }
                action::write($cmd);
                $last=$cmd and $cmd=new command();
            }
            break;
................................................................................
            }
        }
        
        //ooops
        
    }



    /**
     * Read file, and preg_match() for version number.
     *
     */
    function write($cmd) {

................................................................................
        if (isset($cmd->dry)) {
            die("$src");
        }
        else {
            file_put_contents($cmd->file, $src);
        }
    }



    /**
     * Increment patch 0.0.x or minor version number 0.y
     *
     */
    function increment($cmd) {
................................................................................

    #-- 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;
            }
        }
    }

    
    // .phar files
    function bin_phar($cmd) {

        // open and get old meta block
        $p = new Phar($cmd->file);
        $m = $p->getMetadata();
................................................................................
        
            // 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);
    }


}





................................................................................
    fwrite(STDERR, basename($_SERVER['argv'][0]) . ": " . $msg . "\n");
    if ($errno > 0) {
        exit($errno   );
    }
}

















?>