Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

coffee: fix the upgrade commands #228

Merged
merged 5 commits into from
Feb 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,074 changes: 572 additions & 502 deletions Cargo.lock

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions coffee_cmd/src/coffee_term/command_show.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ pub fn show_list(coffee_list: Result<CoffeeList, CoffeeError>) -> Result<(), Cof
let remotes = coffee_list?;

term::println(
term::format::tertiary_bold("●"),
term::format::bold("●"),
term::format::tertiary("Plugin installed"),
);
let mut table = radicle_term::Table::new(TableOptions::bordered());
Expand Down Expand Up @@ -45,7 +45,7 @@ pub fn show_remote_list(remote_list: Result<CoffeeRemote, CoffeeError>) -> Resul
};

term::println(
term::format::tertiary_bold("●"),
term::format::bold("●"),
term::format::tertiary("List of repositories"),
);
let mut table = radicle_term::Table::new(TableOptions::bordered());
Expand Down
4 changes: 2 additions & 2 deletions coffee_cmd/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,10 @@ async fn main() -> Result<(), CoffeeError> {
Ok(res) => {
spinner.and_then(|splinner| Some(splinner.finish()));
match res.status {
UpgradeStatus::UpToDate => {
UpgradeStatus::UpToDate(_, _) => {
term::info!("Remote repository `{}` is already up to date!", res.repo)
}
UpgradeStatus::Updated => {
UpgradeStatus::Updated(_, _) => {
term::success!(
"Remote repository `{}` was successfully upgraded!",
res.repo
Expand Down
2 changes: 1 addition & 1 deletion coffee_core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,5 @@ serde = { version = "1.0", features = ["derive"] }
serde_json = "1"
clightningrpc-conf = "0.0.3"
clightningrpc-common = "0.3.0-beta.4"
git2 = "0.16.1"
git2 = "^0.18.1"
chrono = { version = "0.4", features = ["std"], default-features = false }
3 changes: 1 addition & 2 deletions coffee_core/src/coffee.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ use std::vec::Vec;
use tokio::fs;

use async_trait::async_trait;
use chrono::{TimeZone, Utc};
use clightningrpc_common::client::Client;
use clightningrpc_common::json_utils;
use clightningrpc_conf::{CLNConf, SyncCLNConf};
Expand Down Expand Up @@ -352,7 +351,7 @@ impl PluginManager for CoffeeManager {
.get_mut(repo)
.ok_or_else(|| error!("Repository with name: `{}` not found", repo))?;

let status = repository.upgrade(&self.config.plugins).await?;
let status = repository.upgrade(&self.config.plugins, verbose).await?;
for plugins in status.plugins_effected.iter() {
self.remove(plugins).await?;
self.install(plugins, verbose, false).await?;
Expand Down
2 changes: 1 addition & 1 deletion coffee_github/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ coffee_lib = { path = "../coffee_lib" }
coffee_storage = { path = "../coffee_storage" }
async-trait = "0.1.57"
tokio = { version = "1.22.0", features = ["fs"] }
git2 = "0.16.1"
git2 = "^0.18.1"
log = "0.4.17"
env_logger = "0.9.3"
serde_yaml = "^0.9.0"
Expand Down
22 changes: 10 additions & 12 deletions coffee_github/src/repository.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
use std::any::Any;

use async_trait::async_trait;
use chrono::{TimeZone, Utc};
use coffee_lib::types::response::CoffeeUpgrade;
use git2;
use log::debug;
use tokio::fs::File;
Expand All @@ -16,13 +14,14 @@ use coffee_lib::plugin::Plugin;
use coffee_lib::plugin::PluginLang;
use coffee_lib::plugin_conf::Conf;
use coffee_lib::repository::Repository;
use coffee_lib::types::response::CoffeeUpgrade;
use coffee_lib::url::URL;
use coffee_lib::utils::get_plugin_info_from_path;
use coffee_storage::model::repository::Kind;
use coffee_storage::model::repository::Repository as StorageRepository;

use crate::utils::clone_recursive_fix;
use crate::utils::fast_forward;
use crate::utils::git_upgrade;

pub struct Github {
/// the url of the repository to be able
Expand Down Expand Up @@ -231,7 +230,11 @@ impl Repository for Github {
}
}

async fn upgrade(&mut self, plugins: &Vec<Plugin>) -> Result<CoffeeUpgrade, CoffeeError> {
async fn upgrade(
&mut self,
plugins: &Vec<Plugin>,
verbose: bool,
) -> Result<CoffeeUpgrade, CoffeeError> {
// get the list of the plugins installed from this repository
// TODO: add a field of installed plugins in the repository struct instead
let mut plugins_effected: Vec<String> = vec![];
Expand All @@ -253,14 +256,9 @@ impl Repository for Github {
}
}
// pull the changes from the repository
let status = fast_forward(&self.url.path_string, &self.branch)?;
// update the git information
// (git HEAD and date of the last commit)
let repo = git2::Repository::open(&self.url.path_string)
.map_err(|err| error!("{}", err.message()))?;
let (commit, date) = get_repo_info!(repo);
self.git_head = Some(commit.clone());
self.last_activity = Some(date.clone());
let status = git_upgrade(&self.url.path_string, &self.branch, verbose).await?;
self.git_head = Some(status.commit_id());
self.last_activity = Some(status.date());
Ok(CoffeeUpgrade {
repo: self.name(),
status,
Expand Down
51 changes: 16 additions & 35 deletions coffee_github/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use coffee_lib::errors::CoffeeError;
use coffee_lib::macros::error;
use coffee_lib::url::URL;
use coffee_lib::{commit_id, get_repo_info, sh};
use log::debug;

use coffee_lib::types::response::UpgradeStatus;
Expand All @@ -24,46 +25,26 @@ pub async fn clone_recursive_fix(repo: git2::Repository, url: &URL) -> Result<()
Ok(())
}

pub fn fast_forward(path: &str, branch: &str) -> Result<UpgradeStatus, CoffeeError> {
let repo = git2::Repository::open(path).map_err(|err| error!("{}", err.message()))?;

repo.find_remote("origin")
.map_err(|err| error!("{}", err.message()))?
.fetch(&[branch], None, None)
.map_err(|err| error!("{}", err.message()))?;

let fetch_head = repo
.find_reference("FETCH_HEAD")
.map_err(|err| error!("{}", err.message()))?;
pub async fn git_upgrade(
path: &str,
branch: &str,
verbose: bool,
) -> Result<UpgradeStatus, CoffeeError> {
use tokio::process::Command;

let fetch_commit = repo
.reference_to_annotated_commit(&fetch_head)
.map_err(|err| error!("{}", err.message()))?;

let analysis = repo
.merge_analysis(&[&fetch_commit])
.map_err(|err| error!("{}", err.message()))?;
let repo = git2::Repository::open(path).map_err(|err| error!("{}", err.message()))?;

if analysis.0.is_up_to_date() {
Ok(UpgradeStatus::UpToDate)
} else if analysis.0.is_fast_forward() {
let refname = format!("refs/heads/{}", branch);
let mut reference = repo
.find_reference(&refname)
.map_err(|err| error!("{}", err.message()))?;
let (local_commit, _) = get_repo_info!(repo);

reference
.set_target(fetch_commit.id(), "Fast-Forward")
.map_err(|err| error!("{}", err.message()))?;
let mut cmd = format!("git fetch origin\n");
cmd += &format!("git reset --hard origin/{branch}");
sh!(path, cmd, verbose);

repo.set_head(&refname)
.map_err(|err| error!("{}", err.message()))?;
let (upstream_commit, date) = get_repo_info!(repo);

match repo.checkout_head(Some(git2::build::CheckoutBuilder::default().force())) {
Ok(()) => return Ok(UpgradeStatus::Updated),
Err(err) => return Err(error!("{}", err.message())),
}
if local_commit == upstream_commit {
Ok(UpgradeStatus::UpToDate(upstream_commit, date))
} else {
Err(error!("{}", "Error trying to pull the latest changes",))
Ok(UpgradeStatus::Updated(upstream_commit, date))
}
}
4 changes: 2 additions & 2 deletions coffee_lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ edition = "2021"
async-trait = "^0.1.57"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
git2 = "0.16.1"
git2 = "^0.18.1"
log = "0.4.17"
env_logger = "0.9.3"
tokio = { version = "1.22.0", features = ["process"] }
tokio = { version = "1.22.0", features = ["process", "fs"] }
paperclip = { version = "0.8.0", features = ["actix4"], optional = true }

[features]
Expand Down
4 changes: 3 additions & 1 deletion coffee_lib/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ macro_rules! commit_id {
#[macro_export]
macro_rules! get_repo_info {
($repo:ident) => {{
use chrono::TimeZone;

let commit_id = commit_id!($repo);

let oid = git2::Oid::from_str(&commit_id).map_err(|err| error!("{}", err.message()))?;
Expand All @@ -70,7 +72,7 @@ macro_rules! get_repo_info {
.map_err(|err| error!("{}", err.message()))?;
let commit_time = commit.time();
let timestamp = commit_time.seconds();
let date_time = Utc.timestamp_opt(timestamp, 0).single();
let date_time = chrono::Utc.timestamp_opt(timestamp, 0).single();

if let Some(date_time) = date_time {
let formatted_date = date_time.format("%d/%m/%Y").to_string();
Expand Down
5 changes: 0 additions & 5 deletions coffee_lib/src/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,11 +148,6 @@ impl Plugin {
Ok(exec_path)
}

/// upgrade the plugin to a new version.
pub async fn upgrade(&mut self, _: bool) -> Result<(), CoffeeError> {
todo!("not implemented yet")
}

/// remove the plugin and clean up all the data.
async fn remove(&mut self) -> Result<(), CoffeeError> {
todo!("not implemented yet")
Expand Down
6 changes: 5 additions & 1 deletion coffee_lib/src/repository.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,11 @@ pub trait Repository: Any {
async fn list(&self) -> Result<Vec<Plugin>, CoffeeError>;

/// upgrade the repository
async fn upgrade(&mut self, plugins: &Vec<Plugin>) -> Result<CoffeeUpgrade, CoffeeError>;
async fn upgrade(
&mut self,
plugins: &Vec<Plugin>,
verbose: bool,
) -> Result<CoffeeUpgrade, CoffeeError>;

/// recover the repository from the commit id.
async fn recover(&mut self) -> Result<(), CoffeeError>;
Expand Down
21 changes: 19 additions & 2 deletions coffee_lib/src/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,25 @@ pub mod response {

#[derive(Debug, Serialize, Deserialize)]
pub enum UpgradeStatus {
UpToDate,
Updated,
/// CommitId, Date
UpToDate(String, String),
/// CommitId, Date
Updated(String, String),
}

impl UpgradeStatus {
pub fn date(&self) -> String {
match self {
UpgradeStatus::UpToDate(_, date) => date.clone(),
UpgradeStatus::Updated(_, date) => date.clone(),
}
}
pub fn commit_id(&self) -> String {
match self {
UpgradeStatus::UpToDate(commit_id, _) => commit_id.clone(),
UpgradeStatus::Updated(commit_id, _) => commit_id.clone(),
}
}
}

#[derive(Debug, Serialize, Deserialize)]
vincenzopalazzo marked this conversation as resolved.
Show resolved Hide resolved
Expand Down
Loading