Skip to content

Commit 1272fa5

Browse files
feat(core): nurse clean up the global repository
Adding a new case for the coffe nurse command to clean up the global repository directory and move it insied the network subdirectory. Signed-off-by: Vincenzo Palazzo <[email protected]>
1 parent 472d9f6 commit 1272fa5

File tree

8 files changed

+91
-43
lines changed

8 files changed

+91
-43
lines changed

coffee_cmd/src/coffee_term/command_show.rs

+4
Original file line numberDiff line numberDiff line change
@@ -102,10 +102,14 @@ pub fn show_nurse_result(
102102
NurseStatus::RepositoryLocallyRemoved(_) => {
103103
"Removed from local storage".to_string()
104104
}
105+
NurseStatus::MovingGlobalRepostoryTo(_) => {
106+
"Moving Global repository directory".to_string()
107+
}
105108
};
106109
let repos_str = match status {
107110
NurseStatus::RepositoryLocallyRestored(repos)
108111
| NurseStatus::RepositoryLocallyRemoved(repos) => repos.join(", "),
112+
NurseStatus::MovingGlobalRepostoryTo(network) => network.to_owned(),
109113
};
110114

111115
table.push([

coffee_core/src/coffee.rs

+14-1
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
//! Coffee mod implementation
22
use std::collections::HashMap;
33
use std::fmt::Debug;
4+
use std::path::Path;
45
use std::vec::Vec;
5-
use tokio::fs;
66

77
use async_trait::async_trait;
88
use clightningrpc_common::client::Client;
@@ -12,6 +12,7 @@ use log;
1212
use serde::de::DeserializeOwned;
1313
use serde::{Deserialize, Serialize};
1414
use serde_json::json;
15+
use tokio::fs;
1516
use tokio::process::Command;
1617

1718
use coffee_github::repository::Github;
@@ -20,6 +21,7 @@ use coffee_lib::plugin_manager::PluginManager;
2021
use coffee_lib::repository::Repository;
2122
use coffee_lib::types::response::*;
2223
use coffee_lib::url::URL;
24+
use coffee_lib::utils::{copy_dir_if_exist, rm_dir_if_exist};
2325
use coffee_lib::{commit_id, error, get_repo_info, sh};
2426
use coffee_storage::model::repository::{Kind, Repository as RepositoryInfo};
2527
use coffee_storage::nosql_db::NoSQlStorage;
@@ -497,6 +499,17 @@ impl PluginManager for CoffeeManager {
497499
let mut actions = self.patch_repository_locally_absent(repos.to_vec()).await?;
498500
nurse_actions.append(&mut actions);
499501
}
502+
Defect::CoffeeGlobalrepoCleanup(networks) => {
503+
let global_repo = format!("{}/repositories", self.config.root_path);
504+
for (network, path) in networks {
505+
if !Path::exists(Path::new(&path)) {
506+
copy_dir_if_exist(&global_repo, path).await?;
507+
}
508+
nurse_actions
509+
.push(NurseStatus::MovingGlobalRepostoryTo(network.to_owned()));
510+
}
511+
rm_dir_if_exist(&global_repo).await?;
512+
}
500513
}
501514
}
502515
let mut nurse = CoffeeNurse {

coffee_core/src/config.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize};
44
use std::env;
55

66
use crate::CoffeeOperation;
7-
use coffee_lib::utils::{check_dir_or_make_if_missing, move_dir_if_exist};
7+
use coffee_lib::utils::{check_dir_or_make_if_missing, copy_dir_if_exist};
88
use coffee_lib::{errors::CoffeeError, plugin::Plugin};
99

1010
use crate::CoffeeArgs;
@@ -66,7 +66,9 @@ impl CoffeeConf {
6666
check_dir_or_make_if_missing(format!("{def_path}/{}", coffee.network)).await?;
6767
check_dir_or_make_if_missing(format!("{def_path}/{}/plugins", coffee.network)).await?;
6868
let repo_dir = format!("{def_path}/{}/repositories", coffee.network);
69-
move_dir_if_exist(&format!("{def_path}/repositories"), &repo_dir).await?;
69+
// older version of coffee has a repository inside the directory
70+
copy_dir_if_exist(&format!("{def_path}/repositories"), &repo_dir).await?;
71+
// FIXME: nurse should clean up the `{def_path}/repositories`.
7072
check_dir_or_make_if_missing(repo_dir).await?;
7173
// after we know all the information regarding
7274
// the configuration we try to see if there is

coffee_core/src/nurse/chain.rs

+5-2
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ use async_trait::async_trait;
3333
use coffee_lib::errors::CoffeeError;
3434
use coffee_lib::types::response::{ChainOfResponsibilityStatus, Defect};
3535

36-
use super::strategy::GitRepositoryLocallyAbsentStrategy;
36+
use super::strategy::{CoffeeRepositoryDirCleanUp, GitRepositoryLocallyAbsentStrategy};
3737
use crate::coffee::CoffeeManager;
3838

3939
#[async_trait]
@@ -52,7 +52,10 @@ impl RecoveryChainOfResponsibility {
5252
/// Create a new instance of the chain of responsibility
5353
pub async fn new() -> Result<Self, CoffeeError> {
5454
Ok(Self {
55-
handlers: vec![Arc::new(GitRepositoryLocallyAbsentStrategy)],
55+
handlers: vec![
56+
Arc::new(GitRepositoryLocallyAbsentStrategy),
57+
Arc::new(CoffeeRepositoryDirCleanUp),
58+
],
5659
})
5760
}
5861

coffee_core/src/nurse/strategy.rs

+31
Original file line numberDiff line numberDiff line change
@@ -74,3 +74,34 @@ impl Handler for GitRepositoryLocallyAbsentStrategy {
7474
}
7575
}
7676
}
77+
78+
/// Stategy for migration of the repository global directory
79+
/// to a local directory for each network, see [1]
80+
///
81+
/// This is a strategy tht return the list of network that
82+
/// needs to be migrated to to the new repository configuration.
83+
///
84+
/// [1] https://github.com/coffee-tools/coffee/issues/234
85+
pub struct CoffeeRepositoryDirCleanUp;
86+
87+
#[async_trait]
88+
impl Handler for CoffeeRepositoryDirCleanUp {
89+
async fn can_be_applied(
90+
self: Arc<Self>,
91+
coffee: &CoffeeManager,
92+
) -> Result<Option<Defect>, CoffeeError> {
93+
let networks = ["testnet", "signet", "bitcoin", "liquid"];
94+
// Check whether there exists a network-specific repositories folder for each network.
95+
let mut directory_moving = vec![];
96+
for network in networks {
97+
let subpath_repo = format!("{}/{network}/repositories", coffee.config.root_path);
98+
if !Path::exists(Path::new(&subpath_repo)) {
99+
directory_moving.push((network.to_string(), subpath_repo));
100+
}
101+
}
102+
if directory_moving.is_empty() {
103+
return Ok(None);
104+
}
105+
Ok(Some(Defect::CoffeeGlobalrepoCleanup(directory_moving)))
106+
}
107+
}

coffee_lib/src/types/mod.rs

+20
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,8 @@ pub mod response {
138138
// A patch operation when a git repository is present in the coffee configuration
139139
// but is absent from the local storage.
140140
RepositoryLocallyAbsent(Vec<String>),
141+
/// (Affected network, path)
142+
CoffeeGlobalrepoCleanup(Vec<(String, String)>),
141143
// TODO: Add more patch operations
142144
}
143145

@@ -166,6 +168,16 @@ pub mod response {
166168
write!(f, " {}", repo)?;
167169
}
168170
}
171+
Defect::CoffeeGlobalrepoCleanup(networks) => {
172+
writeln!(
173+
f,
174+
"Global repository migration completed for the networks: {}",
175+
networks
176+
.iter()
177+
.map(|(network, _)| network.to_owned())
178+
.collect::<String>()
179+
)?;
180+
}
169181
}
170182
}
171183
Ok(())
@@ -180,6 +192,7 @@ pub mod response {
180192
pub enum NurseStatus {
181193
RepositoryLocallyRestored(Vec<String>),
182194
RepositoryLocallyRemoved(Vec<String>),
195+
MovingGlobalRepostoryTo(String),
183196
}
184197

185198
#[derive(Clone, Debug, Serialize, Deserialize)]
@@ -206,6 +219,7 @@ pub mod response {
206219
NurseStatus::RepositoryLocallyRestored(repos) => {
207220
repositories_locally_restored.append(&mut repos.clone())
208221
}
222+
NurseStatus::MovingGlobalRepostoryTo(_) => {}
209223
}
210224
}
211225
if !repositories_locally_removed.is_empty() {
@@ -231,6 +245,12 @@ pub mod response {
231245
NurseStatus::RepositoryLocallyRemoved(val) => {
232246
write!(f, "Repositories removed locally: {}", val.join(" "))
233247
}
248+
NurseStatus::MovingGlobalRepostoryTo(net) => {
249+
write!(
250+
f,
251+
"Global repository directory moved to subdirectory for network `{net}`"
252+
)
253+
}
234254
}
235255
}
236256
}

coffee_lib/src/utils.rs

+13-6
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
use super::macros::error;
22
use std::path::Path;
33

4-
use tokio::fs::create_dir;
5-
use tokio::fs::rename;
4+
use tokio::fs;
65

76
use crate::errors::CoffeeError;
87

@@ -23,16 +22,24 @@ pub fn get_plugin_info_from_path(path: &Path) -> Result<(String, String), Coffee
2322

2423
pub async fn check_dir_or_make_if_missing(path: String) -> Result<(), CoffeeError> {
2524
if !Path::exists(Path::new(&path.to_owned())) {
26-
create_dir(path.clone()).await?;
25+
fs::create_dir(path.clone()).await?;
2726
log::debug!("created dir {path}");
2827
}
2928
Ok(())
3029
}
3130

32-
pub async fn move_dir_if_exist(origin: &str, destination: &str) -> Result<(), CoffeeError> {
31+
pub async fn copy_dir_if_exist(origin: &str, destination: &str) -> Result<(), CoffeeError> {
3332
if Path::exists(Path::new(&origin)) {
34-
rename(origin, destination).await?;
35-
log::debug!("move dir from {origin} to {destination}");
33+
fs::copy(origin, destination).await?;
34+
log::debug!("copying dir from {origin} to {destination}");
35+
}
36+
Ok(())
37+
}
38+
39+
pub async fn rm_dir_if_exist(origin: &str) -> Result<(), CoffeeError> {
40+
if Path::exists(Path::new(&origin)) {
41+
fs::remove_dir_all(origin).await?;
42+
log::debug!("rm dir from {origin}");
3643
}
3744
Ok(())
3845
}

git-bugreport-2024-02-07-1353.txt

-32
This file was deleted.

0 commit comments

Comments
 (0)