Skip to content

Instantly share code, notes, and snippets.

@s3thi
Created August 28, 2023 16:22
Show Gist options
  • Save s3thi/ad98b2a90636f32576f7c400ff59d9f8 to your computer and use it in GitHub Desktop.
Save s3thi/ad98b2a90636f32576f7c400ff59d9f8 to your computer and use it in GitHub Desktop.
# Sort a flat directory full of Markdown files named using the
# YYYY-MM-DD format into a directory tree that looks something like
# the following:
#
# 2023/
# 01 - January/
# 2023-01-12.md
# 2023-01-19.md
# 2023-01-28.md
# 02 - February/
# 2023-02-05.md
# 2023-02-16.md
#
use File::Directory::Tree;
use Date::Names;
my $src = '/Users/s3thi/Desktop/Notes/'.IO;
my $dest = '/Users/s3thi/Desktop/NotesFolderized/'.IO;
my $d = Date::Names.new;
rmtree($dest) if $dest.d;
$dest.mkdir;
# Split a filename like '2023-08-12' into <2023 8 12>.
sub parts(IO::Path $logfile) {
return $logfile.basename.subst('.md', '').split('-');
}
# Turns a month number like '8' into a string like '08 - August'.
sub month-dir(Str $month) {
my $month-padded = sprintf("%02d", Int($month));
return "$month-padded - $d.mon(Int($month))";
}
my %hierarchy;
my @weird-files;
for $src.dir -> $f {
my ($year, $month, $day) = parts($f);
if $day.chars != 2 {
@weird-files.push($f);
next;
}
%hierarchy{$year} = {} if !%hierarchy{$year};
%hierarchy{$year}{$month} = True if !%hierarchy{$year}{$month};
}
for %hierarchy.keys -> $year {
my $year-dir = $dest.add($year);
$year-dir.mkdir if !$year-dir.d;
for %hierarchy{$year}.keys -> $month {
my $month-dir = $dest.add($year).add(month-dir($month));
$month-dir.mkdir if !$month-dir.d;
}
}
for $src.dir -> $f {
next if $f ~~ any @weird-files;
my ($year, $month, $day) = parts($f);
my $final-dest = $dest.add($year).add(month-dir($month)).add($f.basename);
$f.copy($final-dest);
}
say "Not moved: ";
say "\t$_" for @weird-files;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment