chiark / gitweb /
commitid.scad.pl: Wip do_git_best
[reprap-play.git] / commitid.scad.pl
1 #!/usr/bin/perl -w
2 use strict;
3
4 $SIG{__WARN__} = sub { die @_; };
5
6 #  xxx much of the comment below is TODO
7 #
8 # Usage:
9 #
10 #   .../commitid.scad.pl [OPTION...] [STRING...] >commitid.scad.new \
11 #     && mv -f commitid.scad.new commitid.scad
12 #
13 # Options:
14 #
15 #   --git    generate git commit indications, as shown below
16 #            (this is the default if no strings are requested with -t)
17 #
18 #   --git=object
19 #            generate git commit indication based on commit object only
20 #            (ie avoid counting commits)
21 #
22 #   -i       do not generate `+' if git-untracked files are present
23 #
24 #   [-t[FORM]] TEXT
25 #            generate a form FORM containing TEXT
26 #            TEXT can contain newlines (final newline usually undesirable)
27 #            if FORM not specified, generates Arg0 Arg1 Arg2 in sequence
28 #            character set is SPC 0-9 a-f + *
29 #
30 # We generate a physical indication of which commit was used.
31 #
32 # We provide for scaling factors with dynamic variables:
33 #    $Commitid_pixelsz        if not set, we use 0.8 } multiplied
34 #    $Commitid_scale          if not set, we use 1.0 }  together
35 #    $Commitid_depth          if not set, we use xy pixel size from above / 2
36 #    $Commitid_depth_scale    if not set, we use 1.0 (multiplies depth above)
37 #
38 # For each form we have
39 #
40 #    module Commitid_Form_2D() { ... }
41 #    module Commitid_Form() { ... }
42 #    function Commitid_Form_sz()     => [ x, y ]
43 #
44 #  These have their origin in the bottom left corner.  The 3D model
45 #  is a positive, has its origin halfway through, and is twice the
46 #  depth in height, so it can be added or subtracted.
47 #
48 # And we provide
49 #
50 #   function Commitid_pixelsz()    // $Commitid_pixelsz * $Commitid_scale
51 #   function Commitid_depth()      // see above
52 #
53 # We can generate these forms:
54 #
55 #  In each case:
56 #    if tree is dirty, * is suffixed or prefixed to count or commitid
57 #    if tree has untracked files, + is added
58 #    (where it is added depends on the Form; in any case it does not
59 #    change the size, but steals space from digits)
60 #
61 #   Small2 Small3 ... Small10:
62 #       git rev-list --first-parent --count HEAD
63 #       typically 3-4 characters but we allow for up to 6
64 #       padded with zeroes; if too long we reduce mod 10^n
65 #       eg if the count is 123456
66 #            Small5    3456*
67 #            Small8    __123456    (where _ are spaces)
68 #
69 #   Small2S Small4S ... Small10S:
70 #   Small3T Small9T:
71 #       same but split into two lines (S) or three lines (T) eg
72 #            Small4S  45     Small6T   _3
73 #                     6*               45
74 #                                      6*
75 #
76 #   Git2 Git3 ... Git10:
77 #   Git4S Git6S ... Git10S:
78 #   Git6T Git9T:
79 #       git-rev-parse HEAD   (prefix of requested length)
80 #       eg if the commitid is abcdef0123...
81 #            Git5    abcd*
82
83 #   Full4 Full6 ... Full20:
84 #       git-rev-list --first-parent --count HEAD
85 #       git-rev-parse HEAD
86 #       (all on two lines)
87 #       eg
88 #            Full6    abcdef       Full8     abcdef01
89 #                     23456*                 _123456*
90 #
91 #   Full6T Full9T ... Full30T
92 #       as Full but commit is split over two lines
93 #       for a 3-line message; eg
94 #             Full9T    abc
95 #                       de*
96 #                       456
97 #
98 #   FontDemo
99 #
100 #   Arg0, Arg1, ...
101 #       Strings passed on command line
102
103 sub p { print @_ or die $!; }
104
105 p <<'END';
106 // *** AUTOGENERATED - DO NOT EDIT *** //
107 function Commitid_pixelsz() =
108   ($Commitid_pixelsz       ? $Commitid_pixelsz       : 0.8) *
109   ($Commitid_scale         ? $Commitid_scale         : 1.0);
110 function Commitid_depth() =
111   ($Commitid_depth         ? $Commitid_depth         : Commitid_pixelsz()/2) *
112   ($Commitid_depth_scale   ? $Commitid_depth_scale   : 1.0);
113 function Commitid__scale() =
114   Commitid_pixelsz() / 0.2;
115 END
116
117 sub chrmodname ($) {
118     my ($chr) = @_;
119     my $chrx = sprintf '%#x', ord $chr;
120     return "Commitid__chr_$chrx";
121 }
122
123 our $gtm_demo_i = -1;
124 our $gtm_demo_j;
125 our @gtm_demo_o;
126
127 sub gentextmodule_demo_start_batch () {
128     $gtm_demo_j = 0;
129     $gtm_demo_i++;
130 }
131
132 sub gentextmodule ($@) {
133     my ($form, @lines) = @_;
134     my $modb = "Commitid_$form";
135     p "module ${modb}_2D(){\n";
136     p " // |$_|\n" foreach @lines;
137     p " scale(Commitid__scale()){\n";
138     my $y = @lines;
139     my $cols = 1;
140     foreach my $line (@lines) {
141         $y--;
142         my $x = 0;
143         foreach my $chr (split //, $line) {
144             p sprintf "  translate([%d * 0.8, %d * 1.2]) %s();\n",
145                 $x, $y, chrmodname $chr
146                 if $chr =~ m/\S/;
147             $x++;
148         }
149         $cols = $x if $x > $cols;
150     }
151     p " }\n";
152     p "}\n";
153     p "module ${modb}(){\n";
154     p " d=Commitid_depth();\n";
155     p " translate([0,0,-d]) linear_extrude(height=d*2) ${modb}_2D();\n";
156     p "}\n";
157
158     p sprintf "function %s_sz() = Commitid__scale() * 0.1 * [ %d, %d ];\n",
159         $modb, 2 * ($cols * 4 - 1), 2 * (@lines * 6 - 1);
160
161     push @gtm_demo_o, <<END;
162  translate([$gtm_demo_i * st[0], $gtm_demo_j * st[1]]) {
163   difference(){
164    color("blue") translate([-e,-e]) square(${modb}_sz() + 2*[e,e]);
165    square(${modb}_sz());
166   }
167   ${modb}_2D();
168 }
169 END
170     $gtm_demo_j++;
171 }
172
173 our @demo;
174
175 sub parsefont () {
176     my %cellmap;
177     for (;;) {
178         $_ = <DATA> // die;
179         last if %cellmap && !m/\S/;
180         next unless m/\S/;
181         chomp;
182         s{^(.) }{};
183         $cellmap{$1} = $_;
184     }
185     my %chrpolys;
186     while (<DATA>) {
187         next unless m/\S/;
188         chomp;
189         my @chrs = split / /, $_;
190         <DATA> !~ m/\S/ or die;
191         foreach my $row (reverse 0..4) {
192             $_ = <DATA>;
193             chomp;
194             s{^}{ };
195             $_ .= ' ' x 8;
196             m{\S/\S} and die;
197             s{/(?=\s)}{L}g;
198             s{/(?=\S)}{r}g;
199             s{\\(?=\s)}{l}g;
200             s{\\(?=\S)}{R}g;
201             p "// $_\n";
202             foreach my $chr (@chrs) {
203                 s{^ }{} or die "$chr $_ ?";
204                 foreach my $col (0..2) {
205                     my @verts;
206                     if (s{^ }{}) {
207                     } elsif (s{^\S}{}) {
208                         my $f = $cellmap{$&};
209                         die unless $f;
210                         $f =~ s/\b\d/ sprintf '%05d', $col*2000 + $&*1025 /ge;
211                         $f =~ s/\d\b/ sprintf '%05d', $row*2000 + $&*1025 /ge;
212                         push @{ $chrpolys{$chr} }, [ split / /, $f ];
213                     } else {
214                         die "$_ ?";
215                     }
216                 }
217             }
218             die "$_ ?" if m{\S};
219         }    
220     }
221
222     my $demo = '';
223     my $democols = 6;
224     foreach my $chr (sort keys %chrpolys) {
225         my $mod = chrmodname $chr;
226         p "module $mod () {\n";
227         foreach my $poly (@{ $chrpolys{$chr} }) {
228             p " polygon([";
229             my $delim = "";
230             foreach my $pt (@$poly) {
231                 p $delim;
232                 $pt =~ s{\d{5}}{$&,};
233                 $pt =~ s{\b\d}{$&.}g;
234                 p "[$pt]";
235                 $delim = ',';
236             }
237             p "]);\n";
238         }
239         p "}\n";
240         $demo .= $chr;
241     }
242     @demo = reverse $demo =~ m{.{1,$democols}}go;
243 }
244
245 parsefont();
246
247 our $do_git; # contains may chars 'c' (count) and/or 'o' (object)
248 our $do_git_untracked = 1;
249 our $argcounter;
250
251 our @forms;
252
253 sub rjustt ($$;$) { # right justify and truncate (ie, pad and truncate at left)
254                     # always includes prefix
255     my ($sz, $whole, $prefix) = @_;
256     $prefix //= '';
257     my $lw = length $whole;
258     my $spare = $sz - $lw - (length $prefix);
259     return
260         ($spare > 0 ? (' ' x $spare) : '').
261         $prefix.
262         substr($whole, ($spare < 0 ? -$spare : 0));
263 }
264
265 sub ljustt ($$;$) {
266     my ($sz, $whole, $suffix) = @_;
267     $suffix //= '';
268     $sz -= length $suffix;
269     return sprintf "%-${sz}.${sz}s%s", $whole, $suffix;
270 }
271
272 sub genform ($@) {
273     my ($form, @lines) = @_;
274     gentextmodule($form, @lines);
275     my $f = {
276         Form => $form,
277         Chars => (length join '', @lines),
278         Lines => (scalar @lines),
279         Ambiguous => ($form =~ m/Full/ && !grep { m/\W/ } @lines),
280     };
281     push @forms, $f;
282 }
283
284 sub genform_q ($$$) {
285     my ($form, $s, $lines) = @_;
286     $gtm_demo_j++;
287     my $l = length $s;
288     return if $l % $lines;
289     my $e = $l/$lines;
290     return if $e < 2;
291     $gtm_demo_j--;
292     genform($form, $s =~ m/.{$e}/g);
293 }
294
295 sub genform_plusq ($$) {
296     my ($form, $s) = @_;
297     genform($form, $s);
298     genform_q("${form}S", $s, 2);
299     genform_q("${form}T", $s, 3);
300 }
301
302 our @gcmd;
303
304 sub gitrun_start () {
305     open F, "-|", @gcmd or die "$gcmd[0]: start: $!";
306 }
307
308 sub gitrun_done (;$) {
309     my ($errok) = @_;
310     $?=0; $!=0;
311     return if close F;
312     return if $errok;
313     die $! if $!;
314     die "@gcmd failed ($?)\n";
315 }
316
317 sub gitoutput (@) {
318     (@gcmd) = (qw(git), @_);
319     gitrun_start;
320     $_ = <F>;
321     gitrun_done;
322     defined or die "@gcmd produced no output";
323     chomp or die "@gcmd produced no final newline";
324     $_;
325 }
326
327 sub do_git () {
328     return unless $do_git;
329
330     @gcmd = qw(git status --porcelain);
331     push @gcmd, qw(--untracked=no) unless $do_git_untracked;
332
333     my $git_dirty = '';
334     gitrun_start;
335     while (<F>) {
336         if (m/^\?\?/ && $do_git_untracked) {
337             $git_dirty = '+';
338             next;
339         }
340         $git_dirty = '*';
341         last;
342     }
343     gitrun_done($git_dirty eq '*');
344
345     my $git_count;
346     my $git_object;
347
348     if ($do_git =~ m/c/) {
349         $git_count = gitoutput qw(rev-list --first-parent --count HEAD);
350     }
351     if ($do_git =~ m/o/) {
352         $git_object = gitoutput qw(rev-parse HEAD);
353     }
354
355     foreach my $sz (2..10) {
356         gentextmodule_demo_start_batch();
357
358         genform_plusq("Small$sz", rjustt($sz, $git_count, $git_dirty))
359             if defined $git_count;
360
361         genform_plusq("Git$sz", ljustt($sz, $git_object, $git_dirty))
362             if defined $git_object;
363
364         if (defined $git_count && defined $git_object) {
365             genform("Full".($sz*2),
366                     ljustt($sz, $git_object),
367                     rjustt($sz, $git_count, $git_dirty));
368
369             my $e = $sz;
370             genform("Full".($e*3)."T",
371                     ljustt($e*2, $git_object, $git_dirty)
372                     =~ m/.{$e}/g,
373                     rjustt($e, $git_count));
374         }
375     }
376 }
377
378 sub do_some_best ($$) {
379     my ($modname, $formre) = @_;
380     p "module Commitid_$modname(max_sz) {\n";
381     foreach my $f (
382         sort {
383             $b->{Chars} <=> $a->{Chars} or
384             $a->{Lines} <=> $b->{Chars}
385         }
386         grep {
387             $_->{Form} =~ m/$formre/ &&
388             !$_->{Ambiguous}
389         }
390         @forms
391     ) {
392         p "// $f->{Form}\n";
393     }
394     p "}\n";
395 }
396
397 sub do_git_best () {
398     return unless $do_git;
399
400     # Auto-computer for `best fit'
401     #
402     # We have two best fit approaches: with count, and git-object-id-only
403     #
404     # For `with count', we only ever include the git object id if the
405     # result would be unambigous.  That means that at least one space
406     # or punctuation was generated.
407     #
408     # We sort the options by firstly number of characters
409     # (decreasing), and then by number of lines (increasing) and
410     # try each one both ways round.
411
412     do_some_best('BestCount', 'Small|Full') if $do_git =~ m/c/;
413     do_some_best('BestObjid', 'Git|Full') if $do_git =~ m/o/;
414 }
415
416 while (@ARGV) {
417     $_ = shift;
418     if (m/^--(no)?-git$/) {
419         $do_git = $1 ? '' : 'co';
420     } elsif (m/^---git=object$/) {
421         $do_git = 'o';
422     } elsif (m/^-i$/) {
423         $do_git_untracked = 0;
424     } elsif (m/^-t(.*)$/) {
425         my $form = $1;
426         die "bad usage: -t needs string argument\n";
427         $_ = shift;
428         gentextmodule($form, split /\n/, $_);
429         $argcounter //= 0;
430     } elsif (m/^[^-]/) {
431         gentextmodule("Arg$argcounter", $_);
432         $argcounter++;
433     } else {
434         die "bad usage: unknown option \`$_'\n";
435     }
436 }
437
438 $do_git //= defined($argcounter) ? '' : 'co';
439
440 gentextmodule_demo_start_batch();
441 gentextmodule('FontDemo', @demo);
442
443 do_git();
444 do_git_best();
445
446 p "module Commitid_2DDemo(){\n";
447 p " st = Commitid__scale() * [ 10, 5 ];\n";
448 p " e  = Commitid_pixelsz();\n";
449 p $_ foreach @gtm_demo_o;
450 p "}\n";
451
452 flush STDOUT or die $!;
453 close STDOUT or die $!;
454
455 __DATA__
456
457 # 00 20 22 02
458 l 00 20 02
459 r 00 20 22
460 L 00 22 02
461 R 20 22 02
462 > 00 20 22 02 11
463 < 00 20 11 22 02
464
465 0 1 2 3 4 5 6 7 8 9
466
467 /#\  r  /#\ ##\ # # ### //  ### /#\ /#\
468 # # /#    #   # # # #   #     # # # # #
469 # #  #  /#/ ##< \## ##\ ##\  // >#< \##
470 # #  #  #     #   #   # # #  #  # #   #
471 \#/ /#\ ### ##/   # ##/ \#/  #  \#/ ##/
472
473 a b c d e f
474
475     #         #     /##
476     #   /##   # /#\ #
477 /## ##\ #   /## #r# ###
478 # # # # #   # # #/  #
479 \## ##/ \## \## \#/ #
480
481 + *
482
483     # #
484  #  \#/
485 ### ###
486  #  /#\
487     # #