A library for writing host-specific, single-binary configuration management and deployment tools
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

110 lines
2.8 KiB

use crate::command_runner::CommandRunner;
use crate::symbols::Symbol;
use async_trait::async_trait;
use regex::Regex;
use std::error::Error;
use std::fs::File as FsFile;
use std::io;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
#[derive(Debug)]
pub struct Plugin<'a, P, N, R> {
base: P,
name: N,
command_runner: &'a R,
}
impl<'a, P: AsRef<Path>, N: AsRef<str>, R: CommandRunner> Plugin<'a, P, N, R> {
pub fn new(base: P, name: N, command_runner: &'a R) -> Self {
Self {
base,
name,
command_runner,
}
}
fn get_path(&self) -> PathBuf {
self
.base
.as_ref()
.join("wp-content/plugins")
.join(self.name.as_ref())
}
}
#[async_trait(?Send)]
impl<P: AsRef<Path>, N: AsRef<str>, R: CommandRunner> Symbol for Plugin<'_, P, N, R> {
async fn target_reached(&self) -> Result<bool, Box<dyn Error>> {
let base_path = self.get_path();
if !base_path.exists() {
return Ok(false);
}
let path = base_path.join(self.name.as_ref().to_owned() + ".php");
let mut version = String::new();
let mut plugin_uri = String::new();
match FsFile::open(path) {
Err(e) => {
// Check if file exists
return if e.kind() == io::ErrorKind::NotFound {
Ok(false)
} else {
Err(Box::new(e))
};
}
Ok(file) => {
let reader = BufReader::new(file);
let regex = Regex::new("(?m)^(Plugin URI|Version): (.+)$")?;
for content in reader.lines() {
for matches in regex.captures_iter(&(content?)) {
if &matches[1] == "Plugin URI" {
plugin_uri = matches[2].to_string();
} else {
version = matches[2].to_string();
}
}
}
}
}
let upstream = self
.command_runner
.get_output(
"curl",
args![
"--form",
format!(
r###"plugins={{"plugins":{{"{0}/{0}.php":{{"Version":"{1}", "PluginURI":"{2}"}}}}}}"###,
self.name.as_ref(),
version,
plugin_uri
),
"https://api.wordpress.org/plugins/update-check/1.1/",
],
)
.await?;
Ok(String::from_utf8(upstream)?.contains(r###""plugins":[]"###))
}
async fn execute(&self) -> Result<(), Box<dyn Error>> {
let source = format!(
"https://downloads.wordpress.org/plugin/{}.zip",
self.name.as_ref()
);
let zip = format!("/tmp/{}.zip", self.name.as_ref());
self
.command_runner
.run_successfully("curl", args![source, "-o", zip])
.await?;
self
.command_runner
.run_successfully("rm", args!["-rf", self.get_path()])
.await?;
self
.command_runner
.run_successfully(
"unzip",
args![zip, "-d", self.base.as_ref().join("wp-content/plugins")],
)
.await
}
}