From 28a5e67de720b758a534460d4f55e8448335bfb7 Mon Sep 17 00:00:00 2001
From: Jakub Jirutka <jakub@jirutka.cz>
Date: Fri, 27 Aug 2021 01:13:48 +0200
Subject: [PATCH] Run 'open' subcommand when handlr is invoked as xdg-open

This allows to simply symlink handlr to /usr/bin/xdg-open - no wrapper
script is needed.
---
 src/main.rs | 17 ++++++++++++++++-
 1 file changed, 16 insertions(+), 1 deletion(-)

diff --git a/src/main.rs b/src/main.rs
index 4bc38d4..c020aac 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,6 +1,11 @@
 use config::CONFIG;
 use error::{Error, Result};
 use once_cell::sync::Lazy;
+use std::{
+    ffi::OsStr,
+    ffi::OsString,
+    path::Path,
+};
 
 mod apps;
 mod cli;
@@ -20,8 +25,18 @@ fn main() -> Result<()> {
 
     let mut apps = (*apps::APPS).clone();
 
+    let mut args = std::env::args_os().collect::<Vec<OsString>>();
+    let cmd_name = Path::new(&args[0]).file_stem();
+
+    // If the program is invoked with name `xdg-open` (via symlink xdg-open -> handlr),
+    // rewrite arguments to `handlr open ...`.
+    if cmd_name == Some(OsStr::new("xdg-open")) {
+        args[0] = clap::crate_name!().into();  // fix program name in help message
+        args.insert(1, "open".into());
+    }
+
     let res = || -> Result<()> {
-        match Cmd::parse() {
+        match Cmd::parse_from(args) {
             Cmd::Set { mime, handler } => {
                 apps.set_handler(mime.0, handler);
                 apps.save()?;