summaryrefslogtreecommitdiff
path: root/src/driver.rs
diff options
context:
space:
mode:
authorNick Gerace <nickagerace@gmail.com>2020-11-26 11:28:41 -0500
committerNick Gerace <nickagerace@gmail.com>2020-11-26 11:36:47 -0500
commitb483f55b60f647893989289eef5b1cb90525ca6b (patch)
treef4dfe480285674f25f333fb7299029f5610c9075 /src/driver.rs
parent84962f609c1ea0e3255a778683e38f83b58f833c (diff)
downloadgfold-b483f55b60f647893989289eef5b1cb90525ca6b.zip
Refactor library into driver and util files
Refactor library into driver and util files. This library layout helps organize the gfold API.
Diffstat (limited to 'src/driver.rs')
-rw-r--r--src/driver.rs91
1 files changed, 91 insertions, 0 deletions
diff --git a/src/driver.rs b/src/driver.rs
new file mode 100644
index 0000000..56438e1
--- /dev/null
+++ b/src/driver.rs
@@ -0,0 +1,91 @@
+/*
+ * gfold
+ * https://github.com/nickgerace/gfold
+ * Author: Nick Gerace
+ * License: Apache 2.0
+ */
+
+use crate::util;
+
+use std::cmp::Ordering;
+use std::fs;
+use std::path::Path;
+
+use eyre::Result;
+
+#[derive(Debug)]
+pub struct Config {
+ pub no_color: bool,
+ pub recursive: bool,
+ pub skip_sort: bool,
+}
+
+pub struct TableWrapper {
+ pub path_string: String,
+ pub table: prettytable::Table,
+}
+
+pub struct Results(Vec<TableWrapper>);
+
+impl Results {
+ pub fn new(path: &Path, config: &Config) -> Result<Results> {
+ let mut results = Results(Vec::new());
+ results.execute_in_directory(&config, path)?;
+ if !&config.skip_sort {
+ results.sort_results();
+ }
+ Ok(results)
+ }
+
+ pub fn print_results(self) {
+ match self.0.len().cmp(&1) {
+ Ordering::Greater => {
+ for table_wrapper in self.0 {
+ println!("\n{}", table_wrapper.path_string);
+ table_wrapper.table.printstd();
+ }
+ }
+ Ordering::Equal => {
+ self.0[0].table.printstd();
+ }
+ Ordering::Less => {
+ println!("There are no results to display.");
+ }
+ };
+ }
+
+ fn execute_in_directory(&mut self, config: &Config, dir: &Path) -> Result<()> {
+ // FIXME: find ways to add concurrent programming (tokio, async, etc.) to this section.
+ let path_entries = fs::read_dir(dir)?;
+ let mut repos = Vec::new();
+
+ for entry in path_entries {
+ let subpath = &entry?.path();
+ if subpath.is_dir() {
+ if git2::Repository::open(subpath).is_ok() {
+ repos.push(subpath.to_owned());
+ } else if config.recursive {
+ self.execute_in_directory(&config, &subpath)?;
+ }
+ }
+ }
+ if !repos.is_empty() {
+ if !&config.skip_sort {
+ repos.sort();
+ }
+ if let Some(table_wrapper) =
+ util::create_table_from_paths(repos, &dir, &config.no_color)
+ {
+ self.0.push(table_wrapper);
+ }
+ }
+ Ok(())
+ }
+
+ fn sort_results(&mut self) {
+ if self.0.len() >= 2 {
+ // FIXME: find a way to do this without "clone()".
+ self.0.sort_by_key(|table| table.path_string.clone());
+ }
+ }
+}