about summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorAndinus <andinus@nand.sh>2020-08-21 14:41:18 +0530
committerAndinus <andinus@nand.sh>2020-08-21 14:41:18 +0530
commita7bd114aeb9fed876b8fdacd5a5f50d0c02427a5 (patch)
tree4c7fc9faa19d6a5a45ffba070d49f9e5db80aad8
parent9fd9771b55be514d6ac1bbff2b842d969184b7d5 (diff)
downloadlyra-a7bd114aeb9fed876b8fdacd5a5f50d0c02427a5.tar.gz
Add edit feature, unveil_fortune_file function
unveil_fortune_file will unveil the file & return the path.
-rwxr-xr-xlyra.pl36
1 files changed, 30 insertions, 6 deletions
diff --git a/lyra.pl b/lyra.pl
index a4e17a1..8a4d2b2 100755
--- a/lyra.pl
+++ b/lyra.pl
@@ -5,6 +5,7 @@ use warnings;
 use feature 'say';
 
 use Path::Tiny;
+use IPC::Run3;
 
 use constant is_OpenBSD => $^O eq "openbsd";
 require OpenBSD::Unveil
@@ -24,26 +25,49 @@ foreach my $path (@INC) {
 }
 
 my %dispatch = (
+    "edit" => \&edit,
     "random" => \&random,
     "help" => \&HelpMessage,
 );
 
 sub HelpMessage {
     say qq{Usage:
+    edit
+        Edit the file. (opens in \$EDITOR)
     random
         Print a random fortune.
     help
         Show this text.}
 }
 
-# Print a random fortune from $path.
-sub random {
-    my $path = "$ENV{HOME}/quotes.txt";
-    $path = $ARGV[1] if $ARGV[1]; # Use $ARGV[1] as path if it exists.
-    unveil( $path, "r" )
+sub unveil_fortune_file {
+    my $fortune_file = "$ENV{HOME}/quotes.txt";
+    $fortune_file = $ARGV[1] if $ARGV[1]; # Use $ARGV[1] as path if it exists.
+    unveil( $fortune_file, "r" )
         or die "Unable to unveil: $!\n"; # Unveil $path as read-only.
+    return $fortune_file;
+}
+
+# Open fortune file with a text editor.
+sub edit {
+    # Unveil $PATH.
+    foreach my $path ( split(/:/, $ENV{PATH}) ) {
+        unveil( $path, "rx" )
+            or die "Unable to unveil: $!\n";
+    }
 
-    my $file = path($path)->absolute;
+    my @editor = split(/ /, $ENV{EDITOR});
+    push @editor, "vi"
+        unless scalar @editor; # Push "vi" if @editor is empty.
+
+    my $fortune_file = unveil_fortune_file();
+    run3 [ @editor, $fortune_file ];
+}
+
+# Print a random fortune from $path.
+sub random {
+    my $fortune_file = unveil_fortune_file();
+    my $file = path($fortune_file)->absolute;
     my @fortunes = split/\n%\n/, $file->slurp;
 
     say $fortunes[ rand @fortunes ]; # Print random fortune.