From: Matt S Trout Date: Fri, 15 May 2009 02:07:30 +0000 (+0100) Subject: CSV name mangling utilities X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=ed30161693b55126c3cd065747e383486a9136cf;p=engit%2FIron-Munger.git CSV name mangling utilities --- diff --git a/lib/IronMunger/CSVUtils.pm b/lib/IronMunger/CSVUtils.pm new file mode 100644 index 0000000..881616e --- /dev/null +++ b/lib/IronMunger/CSVUtils.pm @@ -0,0 +1,48 @@ +package IronMunger::CSVUtils; + +use strict; +use warnings; +use Carp qw(confess); +use namespace::clean; +use Sub::Exporter -setup => { + exports => [ qw(filename_to_name_and_nick name_and_nick_to_filename) ], +}; + +use signatures; + +# So our plagger setup is weird. The filenames are of the form - +# +# my_${name}__${nick}_.csv +# my_${name}.csv +# my_${nick}.csv +# +# This corresponds to either 'My Name (mynick)', 'My Name' or 'mynick' +# in the plagger config. +# Rather than annoy people, I thought I'd just live with it by assuming +# any name has two or more sections. + +sub filename_to_name_and_nick ($filename) { + my ($body) = ($filename =~ m/^my_(.*?)_?\.csv$/); + confess "Couldn't unpick ${filename} - see comments" unless $body; + my ($name, $nick) = split(/__/, $body); + if (!defined $nick && $name !~ /_/) { + ($name, $nick) = (undef, $name); + } + $name = join(' ', split('_', $name)) if defined $name; + return ($name, $nick); +} + +sub name_and_nick_to_filename ($name, $nick) { + $name = join('_', split(' ', $name)) if defined $name; + my $body = do { + my @def = (grep defined, $name, $nick); + if (@def == 2) { + "${name}__${nick}_"; + } else { + $def[0]; + } + }; + return "my_${body}.csv"; +} + +1; diff --git a/t/csv_utils.t b/t/csv_utils.t new file mode 100644 index 0000000..184ff4d --- /dev/null +++ b/t/csv_utils.t @@ -0,0 +1,37 @@ +use strict; +use warnings; +use Test::More qw(no_plan); +use Test::Deep; + +BEGIN { + use_ok 'IronMunger::CSVUtils', ':all'; +} + +use signatures; + +sub filename ($fname, $means) { + my $descr = join(' ', map +($_||'(undef)'), '=>', $fname, @$means); + cmp_deeply( + [ filename_to_name_and_nick($fname) ], $means, + "Filename to name and nick for ${descr}", + ); + is( + name_and_nick_to_filename(@$means), $fname, + "Name and nick to filename for ${descr}" + ); +} + +sub means (%means) { [ @means{qw(name nick)} ] } + +filename 'my_Jess_Robinson.csv', + means + name => 'Jess Robinson'; + +filename 'my_drrho.csv', + means + nick => 'drrho'; + +filename 'my_Wolfgang_Wiese__xwolf_.csv', + means + name => 'Wolfgang Wiese', + nick => 'xwolf';