| 1 | # ABSTRACT: Derive a claim-safe agent name from a checkout directory | ||
| 2 | |||
| 3 | package App::karr::AgentName; | ||
| 4 | our $VERSION = '0.602'; | ||
| 5 | 3 | ▶ | use strict; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 6 | 3 | ▶ | use warnings; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 7 | 3 | ▶ | use Path::Tiny (); |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 8 | 0 | ▶ | use App::karr::Git (); |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 9 | use Exporter qw( import ); | ||
| 10 | |||
| 11 | our @EXPORT_OK = qw( agent_name checkout_basename sanitize_claim_token ); | ||
| 12 | |||
| 13 | |||
| 14 | sub agent_name { | ||
| 15 | my (%args) = @_; | ||
| 16 | my $base = sanitize_claim_token( checkout_basename( dir => $args{dir} ) ); | ||
| 17 | $base = 'agent' unless length $base; | ||
| 18 | return $base unless $args{unique}; | ||
| 19 | return $base . '-' . _suffix(); | ||
| 20 | } | ||
| 21 | |||
| 22 | |||
| 23 | sub checkout_basename { | ||
| 24 | my (%args) = @_; | ||
| 25 | my $start = Path::Tiny::path( defined $args{dir} ? $args{dir} : '.' )->absolute; | ||
| 26 | my $git = App::karr::Git->new( dir => $start->stringify ); | ||
| 27 | my $root = eval { $git->repo_root }; | ||
| 28 | return $root ? $root->basename : $start->basename; | ||
| 29 | } | ||
| 30 | |||
| 31 | |||
| 32 | sub sanitize_claim_token { | ||
| 33 | my ($raw) = @_; | ||
| 34 | my $token = lc( defined $raw ? $raw : '' ); | ||
| 35 | $token =~ s/[^a-z0-9]+/-/g; | ||
| 36 | $token =~ s/\A-+//; | ||
| 37 | $token =~ s/-+\z//; | ||
| 38 | return $token; | ||
| 39 | } | ||
| 40 | |||
| 41 | # Three lowercase-alphanumeric characters, the "8fa" in ADR 0005's karr-8fa. | ||
| 42 | # rand seeds itself on first use, which is all this needs: the suffix only has | ||
| 43 | # to differ between two agents in one directory, not resist prediction. | ||
| 44 | sub _suffix { | ||
| 45 | my @chars = ( 0 .. 9, 'a' .. 'z' ); | ||
| 46 | return join '', map { $chars[ int rand @chars ] } 1 .. 3; | ||
| 47 | } | ||
| 48 | |||
| 49 | |||
| 50 | 1; | ||
| 51 | |||
| 52 | __END__ | ||