3 # commitid.scad.pl - a program for annotating solid models with commit info
4 # Copyright (C)2016 Ian Jackson. See below. There is NO WARRANTY.
10 # .../commitid.scad.pl [OPTION...] [STRING...] >commitid.scad.new \
11 # && mv -f commitid.scad.new commitid.scad
13 # Run without arguments, commitid.scad.pl will output an openscad file
14 # which contains 2D and 3D models of the current git commit count and
15 # commit object id (commit hash), useful for identifying printed
18 # See below for details. You probably want these two sections, as a
19 # quick starting point:
20 # General form of provided openscad modules
23 # We can also generate models of short mainly-numeric strings
24 # specified on the command line.
29 # --git Generate git commit indications, as shown below
30 # (this is the default if no strings are requested with -t).
31 # Ie, produce the `Autoscaling modules' and `Specific layouts'.
34 # Generate git commit indication based on commit object only
35 # (ie avoid counting commits). Ie, do not generate `Small'
36 # and `Full' layouts (and never select them for `Best').
38 # -i Do not generate `+' dirty indication if git-untracked files
39 # are present (ie, missing .gitignore entries). The `*'
40 # dirty tree indication (for modified files) cannot be disabled.
43 # Generate a layout LAYOUT containing TEXT. TEXT can
44 # contain newlines (a final newline usually undesirable, as
45 # it will generate a blank line). If LAYOUT is not specified,
46 # generates Arg0, Arg1, Arg2, etc., for successive such
47 # TEXTs. The permissible character set in is TEXT is:
54 # Dynamic variables for configuration
55 # -----------------------------------
57 # We honour the following variables to control various scaling factors:
60 # $Commitid_pixelsz 0.8 \ multiplied together
61 # $Commitid_scale 1.0 /
62 # $Commitid_depth pixelsz/2 \ multiplied together
63 # $Commitid_depth_scale 1.0 /
64 # $Commitid_max_best_scale 2.0 limits XY scaling in *Best*
66 # FYI the font is nominally 3x5 pixels, with 1-pixel inter-line and
67 # inter-character gaps. (It's not strictly speaking a 3x5 bitmap
68 # font, size it contains partial pixels and diagonals.)
71 # Non-`module'-specific functions
72 # -------------------------------
74 # We provide the following functions (which depend on the config
75 # variables, but not on anything else) and compute useful values:
77 # function Commitid_pixelsz() Actual size of each nominal pixel
78 # function Commitid_depth() Depth to use (the amount characters
79 # should be raised or sunken)
81 # General form of provided openscad modules
82 # -----------------------------------------
84 # module Commitid_MODULE_2D(...) A collection of polygons forming characters
85 # module Commitid_MODULE(...) The above, extruded up and down in Z
86 # function Commitid_MODULE_sz() A 2-vector giving the X,Y size
88 # Except for *Best* modules, the XY origin is in the bottom left
89 # corner without any margin. Likewise Commitid_MODULE_sz does not
92 # For 3D versions, the model is 2*depth deep and the XY plane bisects
93 # the model. This means it's convenient to either add or subtract from
94 # a workpiece whose face is in the XY plane.
100 # These modules take a specification of the available XY space, and
101 # select and generate a suitable specific identification layout:
103 # module Commitid_BestCount_2D(max_sz, margin=Commitid_pixelsz())
104 # module Commitid_BestCount (max_sz, margin=Commitid_pixelsz())
105 # module Commitid_BestObjid_2D(max_sz, margin=Commitid_pixelsz())
106 # module Commitid_BestObjid (max_sz, margin=Commitid_pixelsz())
108 # max_sz should be [x,y].
110 # BestCount includes (as much as it can of) the git commit count,
112 # git rev-list --first-parent --count HEAD
113 # (and it may include some of the git revision ID too).
115 # BestObjid includes as much as it can of the git commit object hash,
116 # and never includes any of the count.
118 # All of these will autoscale and autorotate the selected model, and
119 # will include an internal margin of the specified size (by default,
120 # one pixel around each edge). If no margin is needed, pass margin=0.
122 # There are no `function Commitid_Best*_sz'. If they existed they
123 # would simply return max_sz.
129 # In general the output, although it may be over multiple lines,
130 # is always in this order
131 # git commit object id (hash)
135 # Not all layouts have all these parts. The commit object id may
136 # sometimes be split over multiple lines, but the count will not be.
137 # If both commit id and commit count appear they will be separated
138 # by (at least) a newline, or a dirty indicator, or a space.
140 # The commit id is truncated to fit, from the right.
142 # The commit count is truncated from the _left_, leaving the least
143 # significant decimal digits.
145 # The dirty indicator can be
147 # * meaning the working tree contains differences from HEAD
149 # + meaning the working tree contains untracked files
150 # (ie files you have failed to `git add' and also failed
151 # to add to gitignore). (But see the -i option.)
157 # If you want to control the exact layout (and make space for it in
158 # your design), you can use these:
160 # module Commitid_LAYOUT_2D()
161 # module Commitid_LAYOUT()
162 # function Commitid_LAYOUT_sz()
164 # Here LAYOUT is one of the following (giving for example, `module
165 # Commitid_Full8_2D'). In the examples, we will assume that the tree
166 # is dirty, the commit count is 123456, and the commit object id
167 # starts abcdeffedbcaabcdef... In the examples `_' shows where a
168 # space would be printed.
170 # Small2 Small3 ... Small10
171 # A single line containing as much of the count will fit, eg:
174 # The objectid is included if more than one character of of it
175 # will fit without makign the output ambiguous:
178 # Small2S Small4S ... Small10S
180 # Same as Small but split into two lines (S)
181 # or three lines (T). Eg:
182 # Small4S *4 Small6T _*
185 # Git2 Git3 ... Git10
186 # Git4S Git6S ... Git10S
188 # Just the commit object hash, in one, two (S) or three (T)
192 # Full4 Full6 ... Full20:
193 # The commit object hash plus the commit count, on
194 # separate lines, eg:
195 # Full6 abcdef Full8 abcdeffe
198 # Full6T Full9T ... Full30T
199 # As Full but the commit object id is split over two lines
200 # producing a 3-line layout, eg:
201 # Full9T abc Full21T abcdeff
210 # A demonstration of the built-in 18-character font
214 # Strings passed on command line (without -t, or bare -t,
215 # rather than with -tLAYOUT).
219 # Generated by passing -tLAYOUT on the command line.
223 # COPYRIGHT, LICENCE AND LACK-OF-WARRANTY INFORMATION
224 # ===================================================
226 # This program is Free Software and a Free Cultural Work.
228 # You can redistribute it and/or modify it under the terms of the
229 # GNU General Public License as published by the Free Software
230 # Foundation, either version 3 of the License, or (at your option)
233 # This program is distributed in the hope that it will be useful,
234 # but WITHOUT ANY WARRANTY; without even the implied warranty of
235 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
236 # GNU General Public License for more details.
238 # You should have received a copy of the GNU General Public License
239 # along with this program. If not, see <http://www.gnu.org/licenses/>.
241 # Alternatively, at your option:
243 # This work is licensed under the Creative Commons
244 # Attribution-ShareAlike 4.0 International License.
246 # There is NO WARRANTY.
251 $SIG{__WARN__} = sub { die @_; };
253 sub p { print @_ or die $!; }
256 // *** AUTOGENERATED - DO NOT EDIT *** //
257 function Commitid_pixelsz() =
258 ($Commitid_pixelsz ? $Commitid_pixelsz : 0.8) *
259 ($Commitid_scale ? $Commitid_scale : 1.0);
260 function Commitid_depth() =
261 ($Commitid_depth ? $Commitid_depth : Commitid_pixelsz()/2) *
262 ($Commitid_depth_scale ? $Commitid_depth_scale : 1.0);
263 function Commitid__scale() =
264 Commitid_pixelsz() / 0.2;
269 my $chrx = sprintf '%#x', ord $chr;
270 return "Commitid__chr_$chrx";
273 our $gtm_demo_i = -1;
277 sub gentextmodule_demo_start_batch () {
282 sub gen3dmodule ($@) {
283 my ($modb,@argl) = (@_);
284 p "module ${modb}(".(join ', ', @argl)."){\n";
285 p " d=Commitid_depth();\n";
286 p " translate([0,0,-d]) linear_extrude(height=d*2)\n";
287 p " ${modb}_2D(".(join ',', map { m/=/ ? $` : $_ } @argl).");\n";
291 sub gentextmodule ($@) {
292 my ($form, @lines) = @_;
293 my $modb = "Commitid_$form";
294 p "module ${modb}_2D(){\n";
295 p " // |$_|\n" foreach @lines;
296 p " scale(Commitid__scale()){\n";
299 foreach my $line (@lines) {
302 foreach my $chr (split //, $line) {
303 p sprintf " translate([%d * 0.8, %d * 1.2]) %s();\n",
304 $x, $y, chrmodname $chr
308 $cols = $x if $x > $cols;
314 p sprintf "function %s_sz() = Commitid__scale() * 0.1 * [ %d, %d ];\n",
315 $modb, 2 * ($cols * 4 - 1), 2 * (@lines * 6 - 1);
317 push @gtm_demo_o, <<END;
318 translate([$gtm_demo_i * st[0], $gtm_demo_j * st[1]]) {
320 color("blue") translate([-e,-e]) square(${modb}_sz() + 2*[e,e]);
321 square(${modb}_sz());
335 last if %cellmap && !m/\S/;
345 my @chrs = split / /, $_;
346 <DATA> !~ m/\S/ or die;
347 foreach my $row (reverse 0..4) {
358 foreach my $chr (@chrs) {
359 s{^ }{} or die "$chr $_ ?";
360 foreach my $col (0..2) {
364 my $f = $cellmap{$&};
366 $f =~ s/\b\d/ sprintf '%05d', $col*2000 + $&*1025 /ge;
367 $f =~ s/\d\b/ sprintf '%05d', $row*2000 + $&*1025 /ge;
368 push @{ $chrpolys{$chr} }, [ split / /, $f ];
380 foreach my $chr (sort keys %chrpolys) {
381 my $mod = chrmodname $chr;
382 p "module $mod () {\n";
383 foreach my $poly (@{ $chrpolys{$chr} }) {
386 foreach my $pt (@$poly) {
388 $pt =~ s{\d{5}}{$&,};
389 $pt =~ s{\b\d}{$&.}g;
398 @demo = reverse $demo =~ m{.{1,$democols}}go;
403 our $do_git; # contains may chars 'c' (count) and/or 'o' (object)
404 our $do_git_untracked = 1;
409 sub rjustt ($$;$) { # right justify and truncate (ie, pad and truncate at left)
410 # always includes prefix
411 my ($sz, $whole, $prefix) = @_;
413 my $lw = length $whole;
414 my $spare = $sz - $lw - (length $prefix);
416 ($spare > 0 ? (' ' x $spare) : '').
418 substr($whole, ($spare < 0 ? -$spare : 0));
422 my ($sz, $whole, $suffix) = @_;
424 $sz -= length $suffix;
425 return sprintf "%-${sz}.${sz}s%s", $whole, $suffix;
429 my ($form, @lines) = @_;
430 gentextmodule($form, @lines);
433 Chars => (length join '', @lines),
434 Lines => (scalar @lines),
435 Ambiguous => ($form =~ m/Full/ && !grep { m/\W/ } @lines),
440 sub genform_q ($$$) {
441 my ($form, $s, $lines) = @_;
444 return if $l % $lines;
448 genform($form, $s =~ m/.{$e}/g);
451 sub genform_plusq ($$) {
454 genform_q("${form}S", $s, 2);
455 genform_q("${form}T", $s, 3);
460 sub gitrun_start () {
461 open F, "-|", @gcmd or die "$gcmd[0]: start: $!";
464 sub gitrun_done (;$) {
470 die "@gcmd failed ($?)\n";
474 (@gcmd) = (qw(git), @_);
478 defined or die "@gcmd produced no output";
479 chomp or die "@gcmd produced no final newline";
484 return unless $do_git;
486 @gcmd = qw(git status --porcelain);
487 push @gcmd, qw(--untracked=no) unless $do_git_untracked;
492 if (m/^\?\?/ && $do_git_untracked) {
499 gitrun_done($git_dirty eq '*');
504 if ($do_git =~ m/c/) {
505 $git_count = gitoutput qw(rev-list --first-parent --count HEAD);
507 if ($do_git =~ m/o/) {
508 $git_object = gitoutput qw(rev-parse HEAD);
510 print STDERR join ' ', map { $_ // '?' }
511 "-- commitid", $git_object, $git_dirty, $git_count, "--\n";
513 foreach my $sz (2..10) {
514 gentextmodule_demo_start_batch();
516 if (defined($git_count)) {
517 my $smallstr = rjustt($sz, $git_count, $git_dirty);
518 if (defined($git_object) && $sz >= length($git_count) + 3) {
519 $smallstr = $git_object;
520 $smallstr .= ($git_dirty || ' ');
521 $smallstr .= $git_count;
522 $smallstr = rjustt($sz, $smallstr);
524 genform_plusq("Small$sz", $smallstr);
527 genform_plusq("Git$sz", ljustt($sz, $git_object, $git_dirty))
528 if defined $git_object;
530 if (defined $git_count && defined $git_object) {
531 genform("Full".($sz*2),
532 ljustt($sz, $git_object),
533 rjustt($sz, $git_count, $git_dirty));
536 genform("Full".($e*3)."T",
537 ljustt($e*2, $git_object, $git_dirty)
539 rjustt($e, $git_count));
544 sub do_some_best ($$) {
545 my ($modname, $formre) = @_;
546 my $fullmodname = "Commitid_${modname}_2D";
547 my @argl = qw(max_sz margin=Commitid_pixelsz());
548 p "module $fullmodname(".(join ', ', @argl).") {\n";
549 my $mbs = '$Commitid_max_best_scale';
550 p " sc_max = $mbs ? $mbs : 2;\n";
551 p " sz = max_sz - 2*[margin,margin];\n";
555 $b->{Chars} <=> $a->{Chars} or
556 $a->{Lines} <=> $b->{Chars}
559 $_->{Form} =~ m/$formre/ &&
564 my $form = $f->{Form};
565 p " sz_$form = Commitid_${form}_sz();\n";
566 foreach my $rot (qw(0 1)) {
567 my $id = "${form}_r${rot}";
568 p " sc_$id = min(sc_max";
569 foreach my $xy (qw(0 1)) {
570 p ",sz[$xy]/sz_$form","[",(($xy xor $rot)+0),"]";
573 push @do, " if (sc_$id >= 1.0";
574 push @do, " && sc_$id >= sc_${form}_r1" if !$rot;
576 push @do, " translate([margin,margin]) scale(sc_$id)\n";
577 push @do, " rotate(90) translate([0,-sz_$form"."[1]])\n" if $rot;
578 push @do, " Commitid_${form}_2D();\n";
584 echo("$fullmodname could not fit anything in", max_sz);
590 gen3dmodule "Commitid_$modname", @argl;
594 return unless $do_git;
596 # Auto-computer for `best fit'
598 # We have two best fit approaches: with count, and git-object-id-only
600 # For `with count', we only ever include the git object id if the
601 # result would be unambigous. That means that at least one space
602 # or punctuation was generated.
604 # We sort the options by firstly number of characters
605 # (decreasing), and then by number of lines (increasing) and
606 # try each one both ways round.
608 do_some_best('BestCount', 'Small|Full') if $do_git =~ m/c/;
609 do_some_best('BestObjid', 'Git|Full') if $do_git =~ m/o/;
614 if (m/^--(no)?-git$/) {
615 $do_git = $1 ? '' : 'co';
616 } elsif (m/^---git=objid$/i) {
619 $do_git_untracked = 0;
620 } elsif (m/^-t(.*)$/) {
622 die "bad usage: -t needs string argument\n";
624 gentextmodule($form, split /\n/, $_);
627 gentextmodule("Arg$argcounter", $_);
630 die "bad usage: unknown option \`$_'\n";
634 $do_git //= defined($argcounter) ? '' : 'co';
636 gentextmodule_demo_start_batch();
637 gentextmodule('FontDemo', @demo);
642 p "module Commitid_2DDemo(){\n";
643 p " st = Commitid__scale() * [ 10, 5 ];\n";
644 p " e = Commitid_pixelsz();\n";
645 p $_ foreach @gtm_demo_o;
648 flush STDOUT or die $!;
649 close STDOUT or die $!;
663 /#\ r /#\ ##\ # # ### /# ### /#\ /#\
664 # # /# # # # # # # # # # # #
665 # # # /#/ ##< \## ##\ ##\ // >#< \##
666 # # # # # # # # # # # # #
667 \#/ /#\ ### ##/ # ##/ \#/ # \#/ ##/
673 /## ##\ # /## #r# ###
675 \## ##/ \## \## \#/ #