Skip to content

Commit

Permalink
feat(main): add rust code for build
Browse files Browse the repository at this point in the history
  • Loading branch information
cuisongliu committed Dec 29, 2024
1 parent 7a69423 commit 6e092f0
Show file tree
Hide file tree
Showing 5 changed files with 87 additions and 59 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
target
.idea
Cargo.lock
files/sealos
files/kube_versions.json
sealos.tar.gz
7 changes: 6 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,15 @@ enum_dispatch = "0.3.13"
tracing-subscriber = "0.3.18"
anyhow = "1.0.95"
reqwest = "0.12.9"
pulldown-cmark = "0.12.2"
serde_json = "1.0"
[build-dependencies]
reqwest = "0.12.5"
tokio = { version = "1.0.0", features = ["rt", "rt-multi-thread", "macros"] }

anyhow = "1.0.95"
pulldown-cmark = "0.12.2"
serde = { version = "1", features = ["derive"] }
serde_json = "1.0"
[profile.release]
lto = true
strip = true
Expand Down
102 changes: 47 additions & 55 deletions build.rs
Original file line number Diff line number Diff line change
@@ -1,62 +1,54 @@
use std::fs::File;
use std::io::copy;
use std::path::Path;
use std::process::Command;
use std::{env, fs};

use anyhow::Error;
use pulldown_cmark::HeadingLevel::H1;
use pulldown_cmark::{Event, Options, Parser, Tag};
#[allow(clippy::single_component_path_imports)]
use reqwest;
use serde_json as json;
use std::fs::File;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let os = env::consts::OS;
if os == "macos" {
println!("cargo:warning=sealos only support linux");
return Ok(()); // macos 不支持 sealos
} else if os != "linux" {
println!("cargo:warning=sealos only support linux");
return Err("sealos only support linux".into());
}
let arch = env::consts::ARCH;
let url = match arch {
"x86_64" => "https://github.com/labring/sealos/releases/download/v4.3.7/sealos_4.3.7_linux_amd64.tar.gz",
"arm64" => "https://github.com/labring/sealos/releases/download/v4.3.7/sealos_4.3.7_linux_arm64.tar.gz",
"aarch64" => "https://github.com/labring/sealos/releases/download/v4.3.7/sealos_4.3.7_linux_arm64.tar.gz",
_ => "",
};

println!("cargo:rustc-env=ARCH={}", arch);
println!("cargo:rustc-env=URL={}", url);
let target_dir = Path::new("files");
let target_file = target_dir.join("sealos");
if target_file.exists() {
println!("File already exists: {:?}", target_file);
return Ok(());
async fn main() -> anyhow::Result<(), Error> {
let _support_versions = vec![
"1.16", "1.17", "1.18", "1.19", "1.20", "1.21", "1.22", "1.23", "1.24", "1.25", "1.26",
"1.27", "1.28", "1.29", "1.30", "1.31",
];
let mut versions = Vec::new();
for version in _support_versions {
let url = format!(
"https://raw.githubusercontent.com/kubernetes/kubernetes/refs/heads/master/CHANGELOG/CHANGELOG-{}.md",
version
);
println!("cargo:warning={}", url);
let resp = reqwest::get(&url).await?;
let body = resp.text().await?;
let h1 = parse_md(&body)?;
println!("cargo:warning=fetch version is {:?}", h1);
versions.push(h1);
}
let output_file = "sealos.tar.gz";
let response = reqwest::get(url).await?;
let path = Path::new(output_file);
let mut file = File::create(path)?;
let content = response.bytes().await?;
copy(&mut content.as_ref(), &mut file)?;
println!("临时文件已下载到: {:?}", path);
Command::new("tar")
.arg("-zxf")
.arg(output_file)
.arg("sealos")
.status()
.expect("Failed to execute tar");

// 删除下载的 tar.gz 文件
fs::remove_file(output_file).expect("Failed to remove sealos.tar.gz");

Command::new("chmod")
.arg("a+x")
.arg("sealos")
.status()
.expect("Failed to execute chmod");
let target_dir = Path::new("files");

fs::rename("sealos", target_dir.join("sealos")).expect("Failed to move sealos to files/");
let file = File::create("files/kube_versions.json")?;
json::to_writer(&file, &versions)?;
Ok(())
}
#[allow(clippy::redundant_guards)]
fn parse_md(markdown_input: &str) -> Result<Vec<String>, Error> {
let options = Options::all();
let parser = Parser::new_ext(markdown_input, options);
let mut titles = Vec::new();
let mut in_level_one_heading = false;
for event in parser {
match event {
Event::Start(Tag::Heading { level, .. }) if level == H1 => {
in_level_one_heading = true;
}
Event::Text(text) if in_level_one_heading => {
in_level_one_heading = false;
if text.contains('-') || !text.starts_with('v') {
continue;
}
titles.push(text.to_string());
}
_ => {}
}
}
Ok(titles)
}
28 changes: 27 additions & 1 deletion src/cli/cli_root.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ pub struct BaseOpts {
pub kube_version: String,
#[arg(long, default_value = "v4.3.7", long_help = "sealos version")]
pub sealos_version: String,
#[arg(long, default_value = "2.8.2", long_help = "registry version")]
#[arg(long, default_value = "2.8.2", long_help = "registry version",value_parser = verify_registry)]
pub registry_version: String,
#[arg(long,long_help="if using proxy address,use_proxy=true", default_value = "false",value_parser = parse_proxy)]
pub use_proxy: bool,
Expand All @@ -40,3 +40,29 @@ fn parse_proxy(s: &str) -> Result<bool, &'static str> {
_ => Err("invalid value, only true or false"),
}
}

fn verify_registry(registry: &str) -> Result<String, &'static str> {
let v = registry.split('.').collect::<Vec<&str>>();
if v.len() != 3 {
return Err("invalid registry version, must be x.x.x");
}
if v[0].parse::<u32>().is_err() || v[1].parse::<u32>().is_err() || v[2].parse::<u32>().is_err()
{
return Err("invalid registry version, must be x.x.x");
}
if let Ok(num) = v[0].parse::<u32>() {
if num < 2 {
return Err("registry version must be >= 2.0.0");
}
}
if let Ok(num) = v[1].parse::<u32>() {
if num < 8 {
return Err("registry version must be >= 2.8.0");
}
}
Ok(registry.to_string())
}

//kubeadm config images list --image-repository k8s.m.daocloud.io
//m.daocloud.io/ghcr.io/labring/lvscare:v4.0.0
//https://files.m.daocloud.io/dl.k8s.io/release/v1.23.0/bin/linux/amd64/kubeadm
7 changes: 6 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,12 @@ async fn main() -> anyhow::Result<()> {
#[cfg(test)]
mod tests {
#[test]
fn test_sealos_file() -> anyhow::Result<()> {
fn test_file() -> anyhow::Result<()> {
let asset = super::Asset::get("kube_versions.json").unwrap();
let s = serde_json::from_slice::<Vec<Vec<String>>>(&asset.data)?;
for v in s {
assert_ne!(v.len(), 0);
}
Ok(())
}
}

0 comments on commit 6e092f0

Please sign in to comment.