Skip to content

Commit 22c03b7

Browse files
committed
feat: no longer needs /** for dir
Signed-off-by: lxl66566 <lxl66566@gmail.com>
1 parent 76b976e commit 22c03b7

File tree

10 files changed

+116
-119
lines changed

10 files changed

+116
-119
lines changed

Cargo.lock

Lines changed: 28 additions & 8 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ license = "MIT"
99
name = "git-simple-encrypt"
1010
readme = "./README.md"
1111
repository = "https://github.com/lxl66566/git-simple-encrypt"
12-
version = "2.0.0"
12+
version = "1.5.0"
1313

1414
[dependencies]
1515
aes-gcm-siv = "0.11.1"
@@ -22,7 +22,7 @@ const-str = "0.6.2"
2222
copy-metadata = "0.1.0"
2323
die-exit = { version = "0.5.0", features = ["red"] }
2424
enum-tools = "0.5.5"
25-
glob = "0.3.2"
25+
fuck-backslash = "0.1.0"
2626
log = "0.4"
2727
num_cpus = "1.16.0"
2828
path-absolutize = "3.1.1"
@@ -32,6 +32,7 @@ rayon = "1.10.0"
3232
serde = { version = "1.0.219", features = ["derive"] }
3333
sha3 = "0.10.8"
3434
tap = "1.0.1"
35+
walkdir = "2.5.0"
3536
zstd = "0.13.3"
3637

3738
[target.'cfg(target_arch = "aarch64")'.dependencies]

src/cli.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,12 +54,12 @@ pub enum SubCommand {
5454
#[clap(alias("d"))]
5555
Decrypt {
5656
/// The files or folders to be decrypted, use wildcard matches.
57-
path: Option<String>,
57+
path: Option<PathBuf>,
5858
},
5959
/// Mark files or folders as need-to-be-crypted.
6060
Add {
6161
#[clap(required = true)]
62-
paths: Vec<String>,
62+
paths: Vec<PathBuf>,
6363
},
6464
/// Set key or other config items.
6565
Set {

src/config.rs

Lines changed: 39 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,10 @@ use assert2::assert;
44
use colored::Colorize;
55
use config_file2::StoreConfigFile;
66
use log::{debug, info, warn};
7-
use path_absolutize::Absolutize;
7+
use path_absolutize::Absolutize as _;
88
use pathdiff::diff_paths;
99
use serde::{Deserialize, Serialize};
10+
use walkdir::WalkDir;
1011

1112
use crate::{
1213
crypt::{COMPRESSED_EXTENSION, ENCRYPTED_EXTENSION},
@@ -41,12 +42,15 @@ impl Default for Config {
4142
}
4243

4344
impl Config {
44-
pub fn new(path: impl Into<PathBuf>) -> Self {
45-
let path = path.into();
45+
pub fn new(path: impl AsRef<Path>) -> Self {
4646
Self::default().with_repo_path(path)
4747
}
48-
pub fn with_repo_path(mut self, path: impl Into<PathBuf>) -> Self {
49-
self.repo_path = path.into();
48+
pub fn with_repo_path(mut self, path: impl AsRef<Path>) -> Self {
49+
self.repo_path = path
50+
.as_ref()
51+
.absolutize()
52+
.expect("path absolutize failed")
53+
.to_path_buf();
5054
self
5155
}
5256
/// The absolute path of the config file.
@@ -56,11 +60,9 @@ impl Config {
5660
/// Add one path to crypt list
5761
///
5862
/// path: relative path to a file or dir.
59-
pub fn add_one_file_to_crypt_list(&mut self, path: &str) {
63+
pub fn add_one_file_to_crypt_list(&mut self, path: impl AsRef<Path>) {
6064
// path is the relative path to the current dir (or absolute path)
61-
let path = Path::new(path)
62-
.absolutize()
63-
.expect("path absolutize failed");
65+
let path = path.as_ref().absolutize().expect("path absolutize failed");
6466

6567
debug!("add_one_file_to_crypt_list: {}", path.display());
6668
assert!(
@@ -96,37 +98,35 @@ impl Config {
9698
"Add to crypt list: {}",
9799
format!("{}", path_relative_to_repo.display()).green()
98100
);
99-
self.crypt_list.push(
100-
path_relative_to_repo.to_string_lossy().replace('\\', "/")
101-
+ if path.is_dir() { "/**" } else { "" },
102-
);
101+
self.crypt_list
102+
.push(path_relative_to_repo.to_string_lossy().replace('\\', "/"));
103103

104104
// check extension
105105
if path.is_dir() {
106-
if let Ok(glob_result) = glob::glob(path.join("**").to_string_lossy().as_ref()) {
107-
glob_result
108-
.filter_map(std::result::Result::ok)
109-
.for_each(|p| {
110-
if let Some(ext) = p.extension().and_then(|ext| ext.to_str())
111-
&& [COMPRESSED_EXTENSION, ENCRYPTED_EXTENSION].contains(&ext)
112-
{
113-
warn!(
114-
"{}",
115-
format!(
116-
"adding dir that contains file with no-good extension: {}",
117-
p.display()
118-
)
119-
.yellow()
120-
);
121-
}
122-
});
106+
for entry in WalkDir::new(path)
107+
.into_iter()
108+
.filter_map(std::result::Result::ok)
109+
{
110+
if let Some(ext) = entry.path().extension().and_then(|ext| ext.to_str())
111+
&& [COMPRESSED_EXTENSION, ENCRYPTED_EXTENSION].contains(&ext)
112+
{
113+
warn!(
114+
"{}",
115+
format!(
116+
"adding dir that contains file with no-good extension: {}",
117+
entry.path().display()
118+
)
119+
.yellow()
120+
);
121+
}
123122
}
124123
}
125124
}
126-
pub fn add_to_crypt_list(&mut self, paths: &[&str]) -> anyhow::Result<()> {
125+
126+
pub fn add_to_crypt_list(&mut self, paths: &[impl AsRef<Path>]) -> anyhow::Result<()> {
127127
paths
128128
.iter()
129-
.for_each(|x| self.add_one_file_to_crypt_list(x));
129+
.for_each(|x| self.add_one_file_to_crypt_list(x.as_ref()));
130130
self.store(CONFIG_FILE_NAME).map_err(|e| anyhow::anyhow!(e))
131131
}
132132
}
@@ -170,11 +170,14 @@ mod tests {
170170
let path_to_add = temp_dir.join("testdir");
171171
fs::create_dir(&path_to_add)?;
172172
config.add_one_file_to_crypt_list(path_to_add.as_os_str().to_string_lossy().as_ref());
173-
println!("{:?}", config.crypt_list.first());
173+
println!("{:?}", config.crypt_list.first().unwrap());
174174
assert!(
175-
config.crypt_list[0].ends_with("/**"),
176-
"needs to be dir pattern: `{}`",
177-
config.crypt_list[0]
175+
config
176+
.repo_path
177+
.join(config.crypt_list.first().unwrap())
178+
.is_dir(),
179+
"needs to be dir: {}",
180+
config.crypt_list.first().unwrap()
178181
);
179182
Ok(())
180183
}

src/crypt.rs

Lines changed: 18 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,7 @@ use aes_gcm_siv::{
1111
use anyhow::{Context, Result, anyhow};
1212
use colored::Colorize;
1313
use copy_metadata::copy_metadata;
14-
use die_exit::{DieWith, die};
15-
use glob::Pattern;
14+
use die_exit::die;
1615
use log::{debug, info};
1716
use rayon::{iter::IntoParallelRefIterator, prelude::*};
1817
use sha3::{Digest, Sha3_224};
@@ -24,7 +23,7 @@ extern crate test;
2423
use crate::utils::format_hex;
2524
use crate::{
2625
repo::{GitCommand, Repo},
27-
utils::pathutils::{Git2Patch, PathAppendExt},
26+
utils::pathutils::PathAppendExt,
2827
};
2928

3029
static NONCE: Lazy<&Nonce> = Lazy::new(|| Nonce::from_slice(b"samenonceplz"));
@@ -220,39 +219,28 @@ pub fn encrypt_repo(repo: &'static Repo) -> anyhow::Result<()> {
220219
Ok(())
221220
}
222221

223-
pub fn decrypt_repo(repo: &'static Repo, path: Option<&String>) -> anyhow::Result<()> {
222+
pub fn decrypt_repo(repo: &'static Repo, path: Option<impl AsRef<Path>>) -> anyhow::Result<()> {
224223
assert!(!repo.get_key().is_empty(), "Key must not be empty");
225-
let dot_pattern = String::from("*.") + ENCRYPTED_EXTENSION;
226-
227-
// partial decrypt filter
228-
let pattern: Option<Pattern> = path.as_ref().map(|x| {
229-
glob::Pattern::new(
230-
repo.path
231-
.join(Path::new(x.as_str()).patch())
232-
.to_string_lossy()
233-
.as_ref()
234-
.tap(|x| println!("Decrypting with pattern: {}", x.green())),
235-
)
236-
.die_with(|e| format!("Invalid pattern: {e}"))
237-
});
238224

239-
let decrypt_futures = repo
240-
.ls_files_absolute_with_given_patterns(&[dot_pattern.as_str()])?
225+
let pattern = if let Some(path) = path {
226+
let path = path.as_ref();
227+
if path.is_dir() {
228+
format!("{}/*.{ENCRYPTED_EXTENSION}", path.to_path_buf().display(),)
229+
} else {
230+
decrypt_file(path, repo.get_key_sha())?;
231+
repo.add_all()?;
232+
return Ok(());
233+
}
234+
} else {
235+
format!("*.{ENCRYPTED_EXTENSION}")
236+
};
237+
let decrypt_results = repo
238+
.ls_files_absolute_with_given_patterns(&[pattern.as_str()])?
241239
.par_iter()
242240
.filter(|x| x.is_file())
243-
.filter(|x| {
244-
if path.is_some() {
245-
pattern
246-
.as_ref()
247-
.expect("path must be Some in this case")
248-
.matches(x.to_string_lossy().as_ref())
249-
} else {
250-
true
251-
}
252-
})
253241
.map(|f| decrypt_file(f, repo.get_key_sha()))
254242
.collect::<Vec<_>>();
255-
decrypt_futures.par_iter().for_each(|ret| {
243+
decrypt_results.par_iter().for_each(|ret| {
256244
if let Err(err) = ret {
257245
eprintln!(
258246
"{}",

src/lib.rs

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,20 +17,15 @@ use repo::Repo;
1717
pub use crate::cli::{Cli, SetField, SubCommand};
1818

1919
#[allow(clippy::missing_panics_doc, clippy::missing_errors_doc)]
20-
pub fn run(cli: &Cli) -> Result<()> {
20+
pub fn run(cli: Cli) -> Result<()> {
2121
let repo = Repo::open(&cli.repo)?;
2222
let repo = Box::leak(Box::new(repo));
2323
let num_cpus = num_cpus::get();
2424
debug!("using blocking thread size: {}", num_cpus * 2);
25-
match &cli.command {
25+
match cli.command {
2626
SubCommand::Encrypt => encrypt_repo(repo)?,
27-
SubCommand::Decrypt { path } => decrypt_repo(repo, path.as_ref())?,
28-
SubCommand::Add { paths } => repo.conf.add_to_crypt_list(
29-
&paths
30-
.iter()
31-
.map(std::convert::AsRef::as_ref)
32-
.collect::<Vec<_>>(),
33-
)?,
27+
SubCommand::Decrypt { path } => decrypt_repo(repo, path)?,
28+
SubCommand::Add { paths } => repo.conf.add_to_crypt_list(&paths)?,
3429
SubCommand::Set { field } => field.set(repo)?,
3530
SubCommand::Pwd => repo.set_key_interactive()?,
3631
}

src/main.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use log::LevelFilter;
44

55
fn main() -> anyhow::Result<()> {
66
log_init();
7-
run(&Cli::parse())
7+
run(Cli::parse())
88
}
99

1010
#[inline]

0 commit comments

Comments
 (0)