소스 검색

meli/main.rs: execute Opt subcommand in Opt::execute()

Move execution of opt.subcommand, if it is given, in a method of the Opt
struct. The main() function is already too long given that it sets up
and handles the event loop, so this reduces the complexity a bit.

Signed-off-by: Manos Pitsidianakis <manos@pitsidianak.is>
Manos Pitsidianakis 1 년 전
부모
커밋
738f7c4695
2개의 변경된 파일102개의 추가작업 그리고 77개의 파일을 삭제
  1. 93 0
      meli/src/args.rs
  2. 9 77
      meli/src/main.rs

+ 93 - 0
meli/src/args.rs

@@ -121,3 +121,96 @@ pub enum ToolOpt {
         account: String,
     },
 }
+
+impl Opt {
+    /// Execute `self.subcommand` if any, and return its result. Otherwise
+    /// return `None`.
+    pub fn execute(self) -> Option<Result<()>> {
+        macro_rules! ret_err {
+            ($sth:expr) => {
+                match $sth {
+                    Ok(v) => v,
+                    Err(err) => return Some(Err(err.into())),
+                }
+            };
+        }
+        Some(match self.subcommand? {
+            SubCommand::View { .. } => { return None ; }
+            SubCommand::TestConfig { path } => {
+                subcommands::test_config(path)
+            }
+            SubCommand::Tools(toolopt) => {
+                 subcommands::tool(self.config, toolopt)
+            }
+            SubCommand::CreateConfig { path } => {
+                subcommands::create_config(path)
+            }
+            SubCommand::EditConfig => {
+                subcommands::edit_config()
+            }
+            SubCommand::PrintConfigPath => {
+                let config_path = ret_err!(crate::conf::get_config_file());
+                println!("{}", config_path.display());
+                Ok(())
+            }
+            #[cfg(not(feature = "cli-docs"))]
+            SubCommand::Man(ManOpt {}) => {
+                 Err(Error::new("error: this version of meli was not build with embedded documentation (cargo feature `cli-docs`). You might have it installed as manpages (eg `man meli`), otherwise check https://meli-email.org"))
+            }
+            #[cfg(feature = "cli-docs")]
+            SubCommand::Man(ManOpt {
+                page,
+                no_raw,
+            }) => {
+                subcommands::man(page, false).and_then(|s| subcommands::pager(s, no_raw))
+            }
+            SubCommand::CompiledWith => {
+                subcommands::compiled_with()
+            }
+            SubCommand::PrintLoadedThemes => {
+                let s = ret_err!(conf::FileSettings::new());
+                print!("{}", s.terminal.themes);
+                Ok(())
+            }
+            SubCommand::PrintDefaultTheme => {
+                print!("{}", conf::Themes::default().key_to_string("dark", false));
+                Ok(())
+            }
+            SubCommand::PrintAppDirectories => {
+                println!(
+                    "{}",
+                    xdg::BaseDirectories::with_prefix("meli")
+                        .expect(
+                            "Could not find your XDG directories. If this is unexpected, please \
+                         report it as a bug."
+                        )
+                        .get_data_file("")
+                        .display()
+                );
+                let mut temp_dir = std::env::temp_dir();
+                temp_dir.push("meli");
+                println!("{}", temp_dir.display());
+                Ok(())
+            }
+            #[cfg(not(feature = "cli-docs"))]
+            SubCommand::InstallMan {
+                destination_path: _,
+            } => {
+                Err(Error::new("error: this version of meli was not build with embedded documentation (cargo feature `cli-docs`). You might have it installed as manpages (eg `man meli`), otherwise check https://meli-email.org"))
+            }
+            #[cfg(feature = "cli-docs")]
+            SubCommand::InstallMan { destination_path } => {
+                match crate::manpages::ManPages::install(destination_path) {
+                    Ok(p) => println!("Installed at {}.", p.display()),
+                    Err(err) => return Some(Err(err)),
+                }
+                Ok(())
+            }
+            SubCommand::PrintLogPath => {
+                let settings = ret_err!(crate::conf::Settings::new());
+                println!("{}", settings._logger.log_dest().display());
+                Ok(())
+            }
+        })
+    }
+}

+ 9 - 77
meli/src/main.rs

@@ -43,86 +43,18 @@ fn main() {
     });
 }
 
-fn run_app(opt: Opt) -> Result<()> {
+fn run_app(mut opt: Opt) -> Result<()> {
     if let Some(config_location) = opt.config.as_ref() {
         std::env::set_var("MELI_CONFIG", config_location);
     }
 
-    match opt.subcommand {
-        Some(SubCommand::TestConfig { path }) => {
-            return subcommands::test_config(path);
-        }
-        Some(SubCommand::Tools(toolopt)) => {
-            return subcommands::tool(opt.config, toolopt);
-        }
-        Some(SubCommand::CreateConfig { path }) => {
-            return subcommands::create_config(path);
-        }
-        Some(SubCommand::EditConfig) => {
-            return subcommands::edit_config();
-        }
-        Some(SubCommand::PrintConfigPath) => {
-            let config_path = crate::conf::get_config_file()?;
-            println!("{}", config_path.display());
-            return Ok(());
-        }
-        #[cfg(not(feature = "cli-docs"))]
-        Some(SubCommand::Man(ManOpt {})) => {
-            return Err(Error::new("error: this version of meli was not build with embedded documentation (cargo feature `cli-docs`). You might have it installed as manpages (eg `man meli`), otherwise check https://meli-email.org"));
-        }
-        #[cfg(feature = "cli-docs")]
-        Some(SubCommand::Man(ManOpt { page, no_raw })) => {
-            return subcommands::man(page, false).and_then(|s| subcommands::pager(s, no_raw));
-        }
-        Some(SubCommand::CompiledWith) => {
-            return subcommands::compiled_with();
-        }
-        Some(SubCommand::PrintLoadedThemes) => {
-            let s = conf::FileSettings::new()?;
-            print!("{}", s.terminal.themes);
-            return Ok(());
-        }
-        Some(SubCommand::PrintDefaultTheme) => {
-            print!("{}", conf::Themes::default().key_to_string("dark", false));
-            return Ok(());
-        }
-        Some(SubCommand::View { .. }) => {}
-        Some(SubCommand::PrintAppDirectories) => {
-            println!(
-                "{}",
-                xdg::BaseDirectories::with_prefix("meli")
-                    .expect(
-                        "Could not find your XDG directories. If this is unexpected, please \
-                         report it as a bug."
-                    )
-                    .get_data_file("")
-                    .display()
-            );
-            let mut temp_dir = std::env::temp_dir();
-            temp_dir.push("meli");
-            println!("{}", temp_dir.display());
-            return Ok(());
-        }
-        #[cfg(not(feature = "cli-docs"))]
-        Some(SubCommand::InstallMan {
-            destination_path: _,
-        }) => {
-            return Err(Error::new("error: this version of meli was not build with embedded documentation (cargo feature `cli-docs`). You might have it installed as manpages (eg `man meli`), otherwise check https://meli-email.org"));
-        }
-        #[cfg(feature = "cli-docs")]
-        Some(SubCommand::InstallMan { destination_path }) => {
-            match crate::manpages::ManPages::install(destination_path) {
-                Ok(p) => println!("Installed at {}.", p.display()),
-                Err(err) => return Err(err),
-            }
-            return Ok(());
-        }
-        Some(SubCommand::PrintLogPath) => {
-            let settings = crate::conf::Settings::new()?;
-            println!("{}", settings._logger.log_dest().display());
-            return Ok(());
-        }
-        None => {}
+    let view_subcmd = if matches!(opt.subcommand, Some(SubCommand::View { .. })) {
+        opt.subcommand.take()
+    } else {
+        None
+    };
+    if let Some(result) = opt.execute() {
+        return result;
     }
 
     /* Create a channel to communicate with other threads. The main process is
@@ -142,7 +74,7 @@ fn run_app(opt: Opt) -> Result<()> {
     /* Create the application State. */
     let mut state;
 
-    if let Some(SubCommand::View { path }) = opt.subcommand {
+    if let Some(SubCommand::View { path }) = view_subcmd {
         state = subcommands::view(path, sender, receiver.clone())?;
     } else {
         state = State::new(None, sender, receiver.clone())?;