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

feat: install packages from crosup config in a github repo #78

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
824 changes: 751 additions & 73 deletions Cargo.lock

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion crates/cli/src/cmd/add.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ use owo_colors::OwoColorize;
use crate::{cmd::print_diff, macros::install, types::InstallArgs};

pub async fn execute_add(tools: Vec<String>, ask: bool) -> Result<(), Error> {
let (mut current_config, filename, content, is_present) = verify_if_config_file_is_present()?;
let (mut current_config, filename, content, is_present) =
verify_if_config_file_is_present(None).await?;

current_config.packages = match current_config.packages {
Some(ref mut packages) => {
Expand Down
2 changes: 1 addition & 1 deletion crates/cli/src/cmd/diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::cmd::print_diff;
use super::get_database_connection;

pub async fn execute_diff() -> Result<(), Error> {
let (_, filename, content, _) = verify_if_config_file_is_present()?;
let (_, filename, content, _) = verify_if_config_file_is_present(None).await?;

let db: DatabaseConnection = get_database_connection().await?;
migration::Migrator::up(&db, None).await?;
Expand Down
2 changes: 1 addition & 1 deletion crates/cli/src/cmd/history.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use owo_colors::OwoColorize;
use sea_orm::DatabaseConnection;

pub async fn execute_history() -> Result<(), Error> {
let (_, filename, _, _) = verify_if_config_file_is_present()?;
let (_, filename, _, _) = verify_if_config_file_is_present(None).await?;

let db: DatabaseConnection = get_database_connection().await?;

Expand Down
11 changes: 9 additions & 2 deletions crates/cli/src/cmd/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,14 @@ pub fn execute_init(

let mut file = std::fs::File::create(&filename).unwrap();
file.write_all(serialized.as_bytes()).unwrap();
println!("Created {} ✨", filename.bright_green());

println!(
"{} Created {} ✨",
"[✓]".bright_green(),
filename.bright_green()
);
println!(
"Run {} to install packages",
"`crosup install`".bright_green()
);
Ok(())
}
3 changes: 2 additions & 1 deletion crates/cli/src/cmd/install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ use ssh2::Session;
use crate::{macros::install, types::InstallArgs};

pub async fn execute_install(args: InstallArgs) -> Result<(), Error> {
let (config, filename, content, _) = verify_if_config_file_is_present()?;
let (config, filename, content, _) =
verify_if_config_file_is_present(args.from.clone()).await?;

let mut config = match args.tools.clone() {
Some(packages) => Configuration {
Expand Down
21 changes: 12 additions & 9 deletions crates/cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,20 +28,21 @@ Quickly install your development tools on your new Chromebook, MacOS or any Linu
.subcommand(
Command::new("init")
.arg(arg!(--toml "Generate a default configuration file in toml format"))
.arg(arg!(--inventory -i "Generate a default inventory file"))
.arg(arg!(-i --inventory "Generate a default inventory file"))
.arg(arg!([packages]... "List of packages to install"))
.about("Generate a default configuration file"),
)
.subcommand(
Command::new("install")
.arg(arg!(--ask -a "Ask for confirmation before installing tools"))
.arg(arg!(-a --ask "Ask for confirmation before installing tools"))
.arg(arg!([tools]... "List of tools to install, e.g. docker, nix, devbox, homebrew, fish, vscode, ble.sh ..."))
.arg(arg!(--remote -r [ip] "Install tools on a remote machine"))
.arg(arg!(--port -p [port] "Port to use when connecting to the remote machine"))
.arg(arg!(-r --remote [ip] "Install tools on a remote machine"))
.arg(arg!(-p --port [port] "Port to use when connecting to the remote machine"))
.arg(
arg!(--username -u [username] "Username to use when connecting to the remote machine"),
arg!(-u --username [username] "Username to use when connecting to the remote machine"),
)
.arg(arg!(--invetory -i [inventory] "Path to the inventory file (list of remote machines) in HCL or TOML format"))
.arg(arg!(-i --inventory [inventory] "Path to the inventory file (list of remote machines) in HCL or TOML format"))
.arg(arg!(-f --from [from] "A Github repository to install tools from, e.g. tsirysndr/crosup-example"))
.about(
"Install developer tools, e.g. docker, nix, devbox, homebrew, fish, vscode, ble.sh ...",
),
Expand All @@ -56,14 +57,14 @@ Quickly install your development tools on your new Chromebook, MacOS or any Linu
)
.subcommand(
Command::new("add")
.arg(arg!(--ask -a "Ask for confirmation before adding a new tool"))
.arg(arg!(-a --ask "Ask for confirmation before adding a new tool"))
.arg(arg!(<tools>... "Tools to add to the configuration file, e.g. gh, vim, tig ..."))
.about("Add a new tool to the configuration file"),
)
.subcommand(
Command::new("search")
.arg(arg!(--channel -c [channel] "Channel to use when searching for a package"))
.arg(arg!(--max-results -m [max_results] "Maximum number of results to return"))
.arg(arg!(-c --channel [channel] "Channel to use when searching for a package"))
.arg(arg!(-m --max [max_results] "Maximum number of results to return"))
.arg(arg!(<package> "Package to search for"))
.about("Search for a package in the nixpkgs repository"),
)
Expand Down Expand Up @@ -92,6 +93,7 @@ async fn main() -> Result<(), Error> {
let inventory = args
.value_of("inventory")
.map(|inventory| inventory.to_string());
let from = args.value_of("from").map(|from| from.to_string());

execute_install(InstallArgs {
ask,
Expand All @@ -101,6 +103,7 @@ async fn main() -> Result<(), Error> {
username,
inventory,
port,
from,
})
.await?;
}
Expand Down
1 change: 1 addition & 0 deletions crates/cli/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ pub struct InstallArgs {
pub port: Option<u16>,
pub username: Option<String>,
pub inventory: Option<String>,
pub from: Option<String>
}

#[derive(Clone, Default)]
Expand Down
2 changes: 2 additions & 0 deletions crates/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,7 @@ crosup-types = {path = "../types", version = "0.2.0"}
hcl-rs = "0.14.2"
os-release = "0.1.0"
owo-colors = "3.5.0"
reqwest = { version = "0.11.24", features = ["rustls-tls", "blocking"] }
ssh2 = {version = "0.9.4", features = ["vendored-openssl"]}
toml = "0.7.4"
zip = "0.6.6"
83 changes: 79 additions & 4 deletions crates/core/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,26 @@
use anyhow::Error;
use owo_colors::OwoColorize;
use std::path::Path;
use reqwest::Client;
use std::{
fs::{create_dir_all, File},
io::Write,
path::{Path, PathBuf},
};
use zip::ZipArchive;

use crosup_types::{
configuration::Configuration, inventory::Inventory, CROSFILE_HCL, CROSFILE_TOML, INVENTORY_HCL,
INVENTORY_TOML,
};

pub fn verify_if_config_file_is_present() -> Result<(Configuration, String, String, bool), Error> {
pub async fn verify_if_config_file_is_present(
github_repo: Option<String>,
) -> Result<(Configuration, String, String, bool), Error> {
let current_dir = match github_repo {
Some(repo) => download_github_repo(&repo).await?,
None => std::env::current_dir()?,
};

if !Path::new(CROSFILE_HCL).exists() && !Path::new(CROSFILE_TOML).exists() {
let config = Configuration::default();
return Ok((
Expand All @@ -18,8 +31,6 @@ pub fn verify_if_config_file_is_present() -> Result<(Configuration, String, Stri
));
}

let current_dir = std::env::current_dir()?;

if Path::new(CROSFILE_HCL).exists() {
let config = std::fs::read_to_string(current_dir.join(CROSFILE_HCL))?;
let content = config.clone();
Expand Down Expand Up @@ -53,3 +64,67 @@ pub fn verify_if_inventory_config_file_is_present() -> Result<Inventory, Error>
let config = toml::from_str(&config)?;
return Ok(config);
}

pub async fn download_github_repo(github_repo: &str) -> Result<PathBuf, Error> {
let home = std::env::var("HOME").unwrap();
let cache_dir = format!("{}/.crosup/cache", home);

create_dir_all(&cache_dir)?;

println!(
"{} {} ...",
"Downloading".bold().bright_green(),
github_repo
);

// download the repo as a zip file using reqwest
// and extract it to the cache_dir
let client = Client::new();
let response = client
.get(format!(
"https://api.github.com/repos/{}/zipball",
github_repo
))
.header("User-Agent", "Mozilla/5.0 (X11; CrOS x86_64 14541.0.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
.send()
.await?;
let mut file = File::create(format!(
"{}/{}.zip",
cache_dir,
github_repo.replace("/", "_")
))?;
file.write_all(&response.bytes().await?)?;

let file = File::open(format!(
"{}/{}.zip",
cache_dir,
github_repo.replace("/", "_")
))?;

let mut archive = ZipArchive::new(file)?;

for i in 0..archive.len() {
let mut file = archive.by_index(i)?;
let outpath = file.mangled_name();

println!(
"{} {} ...",
"Extracting".bold().bright_green(),
outpath.display()
);

if (&*file.name()).ends_with('/') {
create_dir_all(format!("{}/{}", cache_dir, outpath.display()))?;
} else {
if let Some(p) = outpath.parent() {
if !p.exists() {
create_dir_all(format!("{}/{}", cache_dir, p.display()))?;
}
}
let mut outfile = File::create(format!("{}/{}", cache_dir, outpath.display()))?;
std::io::copy(&mut file, &mut outfile)?;
}
}

std::env::current_dir().map_err(|e| Error::msg(e.to_string()))
}