Skip to content

Commit

Permalink
fix(backup): compile errors
Browse files Browse the repository at this point in the history
  • Loading branch information
DaRacci committed Aug 18, 2023
1 parent f93c525 commit a3766de
Show file tree
Hide file tree
Showing 16 changed files with 80 additions and 102 deletions.
7 changes: 3 additions & 4 deletions crates/backup/src/application.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,17 @@
*/

use crate::config::runtime::RuntimeConfig;
use anyhow::{anyhow, Result};
use clap::{Parser, Subcommand};
use indicatif::MultiProgress;
use lib::anyhow::{anyhow, Result};
use lib::cli::Flags;
use lib::progress;
use lib::progress::spinner;
use tracing::error;
use std::fmt::Debug;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::spawn;
use tracing::error;
use tracing::{span, Instrument};

#[derive(Parser, Debug, Clone)]
Expand Down Expand Up @@ -73,8 +73,7 @@ pub async fn main(destination: PathBuf, cli: Cli, is_interactive: bool) -> Resul
Action::Run => {
let config = RuntimeConfig::get(cli, destination).await?;
let multi_bar = Arc::new(MultiProgress::new());
let total_progress =
Arc::new(multi_bar.add(progress::bar(config.config.exporters.len() as u64)));
let total_progress = Arc::new(multi_bar.add(progress::bar(config.config.exporters.len() as u64)));

let mut handles = vec![];
for exporter in config.config.exporters.clone() {
Expand Down
2 changes: 1 addition & 1 deletion crates/backup/src/config/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ use crate::sources::downloader::Downloader;
use crate::sources::exporter::Exporter;
use crate::sources::op::core::OnePasswordCore;
use crate::sources::s3::S3Core;
use anyhow::Result;
use indicatif::{MultiProgress, ProgressBar};
use lib::anyhow::Result;
use serde::{Deserialize, Serialize};
use std::fmt::{Display, Formatter};

Expand Down
30 changes: 11 additions & 19 deletions crates/backup/src/config/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ use crate::config::rules::{autoprune::AutoPrune, Rules};
use crate::config::Config;
use crate::continue_loop;
use crate::sources::exporter::ExporterSource;
use anyhow::{anyhow, Context, Result};
use clap::ValueEnum;
use inquire::validator::Validation;
use lib::anyhow::{anyhow, Context, Result};
use tracing::{error, info, trace};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use tracing::{error, info, trace};

#[derive(Clone, Debug)]
pub struct RuntimeConfig {
Expand Down Expand Up @@ -79,9 +79,9 @@ impl RuntimeConfig {
mutated: false,
directory: directory.to_path_buf(),
cli: cli.clone(),
config: std::fs::read(config_path).context("Reading settings.json").and_then(
|vec| serde_json::from_slice::<Config>(&vec).context("Parsing settings.json"),
)?,
config: std::fs::read(config_path)
.context("Reading settings.json")
.and_then(|vec| serde_json::from_slice::<Config>(&vec).context("Parsing settings.json"))?,
})
}

Expand All @@ -104,10 +104,7 @@ impl RuntimeConfig {
}

// TODO :: Allow removal of existing exporters
if inquire::Confirm::new("Do you want to modify the exporters?")
.with_default(true)
.prompt()?
{
if inquire::Confirm::new("Do you want to modify the exporters?").with_default(true).prompt()? {
let exporters = Self::new_exporters(&config).await?;
if !exporters.is_empty() {
config.config.exporters.extend(exporters);
Expand All @@ -124,22 +121,17 @@ impl RuntimeConfig {
return Ok(());
}

if inquire::Confirm::new("Do you want to save these settings?")
.with_default(true)
.prompt()
.is_ok_and(|b| !b)
{
if inquire::Confirm::new("Do you want to save these settings?").with_default(true).prompt().is_ok_and(|b| !b) {
trace!("Not saving settings");
return Ok(());
}

let destination = self.directory.join("settings.json");
if destination.exists() {
let overwrite =
inquire::Confirm::new("Do you want to overwrite the existing settings?")
.with_default(true)
.prompt()
.context("Prompt for if we should overwrite settings.")?;
let overwrite = inquire::Confirm::new("Do you want to overwrite the existing settings?")
.with_default(true)
.prompt()
.context("Prompt for if we should overwrite settings.")?;

if !overwrite {
trace!("Not overwriting settings");
Expand Down
2 changes: 1 addition & 1 deletion crates/backup/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
extern crate core;

use inquire::validator::StringValidator;
use lib::anyhow::{anyhow, Context, Result};
use anyhow::{anyhow, Context, Result};
use tracing::{trace, warn};

pub mod application;
Expand Down
17 changes: 12 additions & 5 deletions crates/backup/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@

#![feature(result_option_inspect)]

use anyhow::{Context, Result};
use backup::application;
use lib::anyhow::{Context, Result};
use lib::clap::Parser;
use tracing::{error, trace};
use clap::Parser;
use std::env;
use std::env::VarError;
use std::path::PathBuf;
use tracing::{error, trace};

#[tokio::main(flavor = "multi_thread")]
pub async fn main() -> Result<()> {
Expand All @@ -47,11 +47,18 @@ fn select_location() -> Result<PathBuf> {
env::var("BACKUP_DIR")
.map(PathBuf::from)
// TODO :: Verify writable
.and_then(|path| if path.exists() { Ok(path) } else { Err(VarError::NotPresent) })
.and_then(|path| {
if path.exists() {
Ok(path)
} else {
Err(VarError::NotPresent)
}
})
.inspect_err(|_err| {
error!("The path specified in BACKUP_DIR does not exist.");
error!("Please fix this, or unset the BACKUP_DIR environment variable to use the interactive mode.");
}).context("Failed to get backup directory from BACKUP_DIR environment variable")
})
.context("Failed to get backup directory from BACKUP_DIR environment variable")
// .or_else(|_| PathSelect::<&str>::new("Select your backup destination", None)
// .with_selection_mode(PathSelectionMode::Directory)
// .with_select_multiple(false)
Expand Down
43 changes: 22 additions & 21 deletions crates/backup/src/sources/auto_prune.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,9 @@
*/

use crate::config::runtime::RuntimeConfig;
use anyhow::Result;
use indicatif::MultiProgress;
use lib::anyhow::Result;
use std::path::PathBuf;
use tracing::{trace};

// TODO :: Implement logic from cleaner crate to handle this!
pub trait Prune {
Expand All @@ -34,7 +33,7 @@ pub trait Prune {
/// * `rules` - The `AutoPrune` struct which contains the rules for pruning.
/// # Returns
/// A `Result` with the `Vec<PathBuf>` of the files which were removed.
fn prune(&self, config: &RuntimeConfig, _progress_bar: &MultiProgress) -> Result<Vec<PathBuf>> {
fn prune(&self, _config: &RuntimeConfig, _progress_bar: &MultiProgress) -> Result<Vec<PathBuf>> {
// let files = self.files(config).sort_by(|a, b| {
// fn chrono(path: &PathBuf) -> Result<DateTime<FixedOffset>> {
// let meta = path.metadata().context("Get meta for comparing times")?;
Expand All @@ -53,24 +52,26 @@ pub trait Prune {
// let b = b.metadata();
// a.metadata()
// });
let files = self.files(config)?;
let mut files = files.iter();
let mut removed_files = vec![];

// TODO :: Add dry run option.
while let Some(file) = files.next() {
if !(config.config.rules.auto_prune.should_prune(file, files.len())?) {
trace!("Pruning rules prevented pruning for: {}", file.display());
continue;
}

trace!("Pruning file: {}", file.display());
if !config.cli.flags.dry_run {
std::fs::remove_file(file)?;
}
removed_files.push(file.clone());
}
// let files = self.files(config)?;
// let mut files = files.iter();
// let mut removed_files = vec![];
//
// // TODO :: Add dry run option.
// while let Some(file) = files.next() {
// if !(config.config.rules.auto_prune.should_prune(file, files.len())?) {
// trace!("Pruning rules prevented pruning for: {}", file.display());
// continue;
// }
//
// trace!("Pruning file: {}", file.display());
// if !config.cli.flags.dry_run {
// std::fs::remove_file(file)?;
// }
// removed_files.push(file.clone());
// }
//
// Ok(removed_files)

Ok(removed_files)
Ok(vec![])
}
}
6 changes: 2 additions & 4 deletions crates/backup/src/sources/bitwarden.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,21 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

use std::env;
use crate::config::backend::Backend;
use crate::config::runtime::RuntimeConfig;
use crate::sources::auto_prune::Prune;
use crate::sources::downloader::Downloader;
use crate::sources::exporter::Exporter;
use crate::sources::getter::CliGetter;
use anyhow::Result;
use anyhow::{Result, anyhow, Context};
use async_trait::async_trait;
use const_format::formatcp;
use indicatif::{MultiProgress, ProgressBar};
use inquire::PasswordDisplayMode;
use lib::anyhow;
use lib::anyhow::{anyhow, Context};
use lib::fs::normalise_path;
use lib::pathed::Pathed;
use serde::{Deserialize, Serialize};
use std::env;
use std::fmt::{Display, Formatter};
use std::path::PathBuf;
use std::process::Command;
Expand Down
10 changes: 3 additions & 7 deletions crates/backup/src/sources/downloader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@
use crate::config::runtime::RuntimeConfig;
use crate::sources::download;
use crate::sources::exporter::Exporter;
use anyhow::{anyhow, Context, Result};
use async_trait::async_trait;
use futures_util::StreamExt;
use indicatif::{MultiProgress, ProgressBar};
use lib::anyhow::{anyhow, Context, Result};
use lib::fs::create_parents;
use lib::{anyhow, progress};
use lib::progress;
use std::fs::File;
use std::io::copy;
use std::path::PathBuf;
Expand Down Expand Up @@ -56,11 +56,7 @@ pub trait Downloader: Exporter {
return Ok(());
}

debug!(
"Downloading CLI binary from {} to {}",
Self::URL,
&target.display()
);
debug!("Downloading CLI binary from {} to {}", Self::URL, &target.display());
let response = reqwest::Client::new().get(Self::URL).send().await?;
if !response.status().is_success() {
return Err(anyhow!("Failed to download CLI: {}", response.status()));
Expand Down
2 changes: 1 addition & 1 deletion crates/backup/src/sources/exporter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ use crate::sources::bitwarden::BitWardenCore;
use crate::sources::downloader::Downloader;
use crate::sources::op::core::OnePasswordCore;
use crate::sources::s3::S3Core;
use anyhow::Result;
use async_trait::async_trait;
use clap::ValueEnum;
use indicatif::{MultiProgress, ProgressBar};
use lib::anyhow::Result;
use lib::pathed::Pathed;
use serde::{Deserialize, Serialize};
use std::fmt::{Debug, Display, Formatter};
Expand Down
2 changes: 1 addition & 1 deletion crates/backup/src/sources/interactive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

use crate::config::runtime::RuntimeConfig;
use async_trait::async_trait;
use lib::anyhow::Result;
use anyhow::Result;

#[async_trait]
pub trait Interactive<T> {
Expand Down
12 changes: 5 additions & 7 deletions crates/backup/src/sources/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,28 +14,27 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

use anyhow::{anyhow, Context};
use bytes::Bytes;
use futures_util::stream::BoxStream;
use futures_util::StreamExt;
use indicatif::ProgressBar;
use lib::anyhow;
use lib::anyhow::{anyhow, Context};
use lib::fs::{create_parents, normalise_path};
use tracing::debug;
use rand::RngCore;
use std::cmp::min;
use std::error::Error;
use std::io::Write;
use std::path::PathBuf;
use std::{env, fs};
use tracing::debug;

pub mod auto_prune;
#[cfg(feature = "sources-bitwarden")]
pub mod bitwarden;
pub mod downloader;
pub mod exporter;
mod getter;
pub(crate) mod interactive;
#[cfg(feature = "sources-bitwarden")]
pub mod bitwarden;
#[cfg(feature = "sources-1password")]
pub mod op;
#[cfg(feature = "sources-s3")]
Expand All @@ -52,8 +51,7 @@ async fn download_to<E: Error>(

progress.set_length(total_size);
let mut downloaded = 0u64;
let mut file =
fs::File::create(path).with_context(|| format!("Create file {}", path.display()))?;
let mut file = fs::File::create(path).with_context(|| format!("Create file {}", path.display()))?;

progress.set_message(format!(
"Downloading {}...",
Expand Down
2 changes: 1 addition & 1 deletion crates/backup/src/sources/op/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use crate::sources::op::cli;
use crate::sources::op::core::OnePasswordCore;
use async_trait::async_trait;
use futures_util::TryFutureExt;
use lib::anyhow::{anyhow, Context, Result};
use anyhow::{anyhow, Context, Result};
use lib::pathed::Pathed;
use macros::CommonFields;
use serde::{Deserialize, Serialize};
Expand Down
4 changes: 2 additions & 2 deletions crates/backup/src/sources/op/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -504,8 +504,8 @@ pub mod item {
use super::super::one_pux;
use crate::config::runtime::RuntimeConfig;
use crate::sources::op::account::OnePasswordAccount;
use anyhow::{Context, Result};
use indicatif::{MultiProgress, ParallelProgressIterator, ProgressBar};
use lib::{anyhow, anyhow::Context, anyhow::Result};
use macros::CommonFields;
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -1114,9 +1114,9 @@ pub mod vault {
use crate::sources::op::cli::identifier::Identifier;
use crate::sources::op::core::OnePasswordCore;
use crate::sources::op::one_pux;
use anyhow::Result;
#[cfg(test)]
use fake::Dummy;
use lib::anyhow::Result;
use macros::CommonFields;
use serde::{Deserialize, Serialize};
use std::fmt::Display;
Expand Down
5 changes: 2 additions & 3 deletions crates/backup/src/sources/op/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,18 @@ use crate::sources::exporter::Exporter;
use crate::sources::interactive::Interactive;
use crate::sources::op::account::OnePasswordAccount;
use crate::sources::op::one_pux;
use anyhow::{anyhow, Context, Result};
use async_trait::async_trait;
use const_format::formatcp;
use indicatif::{MultiProgress, ProgressBar};
use lib::anyhow::Result;
use lib::anyhow::{anyhow, Context};
use lib::fs::normalise_path;
use lib::pathed::{ensure_directory_exists, ensure_permissions, Pathed};
use serde::{Deserialize, Serialize};
use serde_json::to_string_pretty;
use std::io::Write;
use std::path::PathBuf;
use std::process::Command;
use std::{env, fs};
use std::io::Write;
use zip::write::FileOptions;

#[derive(Debug, Clone, Serialize, Deserialize)]
Expand Down
Loading

0 comments on commit a3766de

Please sign in to comment.