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