chore: setup tooling & lint codebase

This commit is contained in:
Erica Marigold 2023-09-30 15:23:42 +05:30
parent 1438be4231
commit d3e948ee00
No known key found for this signature in database
GPG key ID: 7843994FD1386E35
9 changed files with 312 additions and 328 deletions

View file

@ -0,0 +1,11 @@
root = true
[*]
end_of_line = lf
insert_final_newline = true
charset = utf-8
indent_style = tab
[{*.yaml,*.yml, *.md}]
indent_style = space
indent_size = 2

View file

@ -0,0 +1,3 @@
{
"recommendations": ["rust-lang.rust-analyzer", "esbenp.prettier-vscode"]
}

View file

@ -1,5 +1,12 @@
{ {
"rust-analyzer.linkedProjects": [ "rust-analyzer.check.command": "clippy",
"./Cargo.toml" "rust-analyzer.linkedProjects": ["./Cargo.toml"],
] "editor.formatOnSave": true,
} "prettier.tabWidth": 2,
"[json][jsonc][markdown][yaml]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[rust]": {
"editor.defaultFormatter": "rust-lang.rust-analyzer"
}
}

View file

@ -0,0 +1,5 @@
max_width = 150
hard_tabs = true
#normalize_comments = false
#match_block_trailing_comma = true
#closure_block_indent_threshold = 1

View file

@ -1,9 +1,9 @@
use std::{ use std::{
env, env,
fs::File, fs::File,
io::{Error, ErrorKind, Read, Seek, Write}, io::{Error, ErrorKind, Read, Seek, Write},
path::PathBuf, path::PathBuf,
str::FromStr, str::FromStr,
}; };
use anyhow::Result; use anyhow::Result;
@ -12,185 +12,164 @@ use url::Url;
use zip::ZipArchive; use zip::ZipArchive;
use crate::{ use crate::{
github::{FetchResult, Fetcher, GitHub, Method}, github::{FetchResult, Fetcher, GitHub, Method},
types::{LuneReleaseData, LuneReleaseFetched}, types::{LuneReleaseData, LuneReleaseFetched},
}; };
fn parse_release_data(data: &LuneReleaseData) -> LuneReleaseFetched { fn parse_release_data(data: &LuneReleaseData) -> LuneReleaseFetched {
const TARGET: &str = "download::parse_release_data"; const TARGET: &str = "download::parse_release_data";
tracing::info!(target: TARGET, "Parsing received LuneReleaseData"); tracing::info!(target: TARGET, "Parsing received LuneReleaseData");
let unknown = &String::from("UNKNOWN"); let unknown = &String::from("UNKNOWN");
let mut version = unknown.to_owned(); let mut version = unknown.to_owned();
let mut download = unknown.to_owned(); let mut download = unknown.to_owned();
let mut artifact_name = unknown.to_owned(); let mut artifact_name = unknown.to_owned();
tracing::info!( tracing::info!(
target: TARGET, target: TARGET,
"Defaulting to `unknown` values before parsing" "Defaulting to `unknown` values before parsing"
); );
for asset in &data.assets { for asset in &data.assets {
let parts = asset let parts = asset.name.split('-').map(|s| s.to_string()).collect::<Vec<String>>();
.name
.split("-")
.map(|s| s.to_string())
.collect::<Vec<String>>();
// [0] => always "lune" // [0] => always "lune"
// [1] => version // [1] => version
// [2] => platform // [2] => platform
// [3] => arch .. ".zip" // [3] => arch .. ".zip"
if parts[2] == env::consts::OS && parts[3].trim_end_matches(".zip") == env::consts::ARCH { if parts[2] == env::consts::OS && parts[3].trim_end_matches(".zip") == env::consts::ARCH {
tracing::info!( tracing::info!(
target: TARGET, target: TARGET,
"Supported platform found, overwriting `unknown` values" "Supported platform found, overwriting `unknown` values"
); );
version = (&parts[1]).to_owned(); version = (parts[1]).to_owned();
download = (&asset.browser_download_url).to_owned(); download = (asset.browser_download_url).to_owned();
artifact_name = (&asset.name).to_owned(); artifact_name = (asset.name).to_owned();
} else { } else {
tracing::warn!( tracing::warn!(
target: TARGET, target: TARGET,
"Supported platform not found for asset {:?}", "Supported platform not found for asset {:?}",
asset asset
); );
} }
} }
tracing::info!(target: TARGET, "Done."); tracing::info!(target: TARGET, "Done.");
LuneReleaseFetched { LuneReleaseFetched {
version, version,
download, download,
artifact_name, artifact_name,
raw: Some(data.clone()), raw: Some(data.clone()),
} }
} }
pub fn download_release(version: Option<String>) -> Result<(PathBuf, LuneReleaseFetched)> { pub fn download_release(version: Option<String>) -> Result<(PathBuf, LuneReleaseFetched)> {
const TARGET: &str = "download::download_release"; const TARGET: &str = "download::download_release";
tracing::info!(target: TARGET, "Initializing routine"); tracing::info!(target: TARGET, "Initializing routine");
let parsed_release_data: LuneReleaseFetched; let parsed_release_data: LuneReleaseFetched;
if let Some(ver) = version { if let Some(ver) = version {
let artifact_name = format!("lune-{ver}-{}-{}.zip", env::consts::OS, env::consts::ARCH); let artifact_name = format!("lune-{ver}-{}-{}.zip", env::consts::OS, env::consts::ARCH);
parsed_release_data = LuneReleaseFetched { parsed_release_data = LuneReleaseFetched {
version: ver.to_string(), version: ver.to_string(),
download: format!( download: format!("https://github.com/filiptibell/lune/releases/download/v{ver}/{artifact_name}"),
"https://github.com/filiptibell/lune/releases/download/v{ver}/{artifact_name}" artifact_name,
), raw: None,
artifact_name, }
raw: None, } else {
} parsed_release_data = parse_release_data(&GitHub::new(("filiptibell", "lune")).fetch_releases()?);
} else {
parsed_release_data =
parse_release_data(&GitHub::new(("filiptibell", "lune")).fetch_releases()?);
tracing::info!(target: TARGET, "Received API resp and parsed release data"); tracing::info!(target: TARGET, "Received API resp and parsed release data");
} }
tracing::info!(target: TARGET, "Got lune {}", parsed_release_data.version); tracing::info!(target: TARGET, "Got lune {}", parsed_release_data.version);
let fetcher = Fetcher::new(); let fetcher = Fetcher::new();
tracing::info!( tracing::info!(
target: TARGET, target: TARGET,
"Proceeding to download release from API resp (url = {})", "Proceeding to download release from API resp (url = {})",
&parsed_release_data.download &parsed_release_data.download
); );
let resp = fetcher.fetch::<_, ()>( let resp = fetcher.fetch::<_, ()>(Method::Get, Url::from_str(parsed_release_data.download.as_str())?, false)?;
Method::Get,
Url::from_str(&parsed_release_data.download.as_str())?,
false,
)?;
match resp { match resp {
FetchResult::Response(res) => { FetchResult::Response(res) => {
tracing::info!( tracing::info!(
target: TARGET, target: TARGET,
"Received download resp, proceeding to write zip to disk at {}", "Received download resp, proceeding to write zip to disk at {}",
&parsed_release_data.artifact_name &parsed_release_data.artifact_name
); );
let mut zip_archive = File::create(&parsed_release_data.artifact_name)?; let mut zip_archive = File::create(&parsed_release_data.artifact_name)?;
let mut bytes = res let bytes = res.into_reader().bytes().map(|elem| elem.unwrap()).collect::<Vec<u8>>();
.into_reader()
.bytes()
.map(|elem| elem.unwrap())
.collect::<Vec<u8>>();
zip_archive.write_all(&mut bytes)?; zip_archive.write_all(&bytes)?;
tracing::info!(target: TARGET, "Successfully downloaded release"); tracing::info!(target: TARGET, "Successfully downloaded release");
} }
FetchResult::Result(_) => unreachable!("Fetcher returned Result instead of Response"), FetchResult::Result(_) => unreachable!("Fetcher returned Result instead of Response"),
}; };
Ok(( Ok((PathBuf::from(&parsed_release_data.artifact_name), parsed_release_data))
PathBuf::from(&parsed_release_data.artifact_name),
parsed_release_data,
))
} }
pub fn install_lune(lune_archive_reader: impl Read + Seek, meta: LuneReleaseFetched) -> Result<()> { pub fn install_lune(lune_archive_reader: impl Read + Seek, meta: LuneReleaseFetched) -> Result<()> {
const TARGET: &str = "download::install_lune"; const TARGET: &str = "download::install_lune";
tracing::info!(target: TARGET, "Initializing routine"); tracing::info!(target: TARGET, "Initializing routine");
let dir_name = meta.artifact_name.trim_end_matches(".zip"); let dir_name = meta.artifact_name.trim_end_matches(".zip");
tracing::info!(target: TARGET, "Proceeding to extract release zip"); tracing::info!(target: TARGET, "Proceeding to extract release zip");
let mut lune_zip = ZipArchive::new(lune_archive_reader)?; let mut lune_zip = ZipArchive::new(lune_archive_reader)?;
lune_zip.extract(dir_name)?; lune_zip.extract(dir_name)?;
tracing::info!(target: TARGET, "Successfully extracted release zip"); tracing::info!(target: TARGET, "Successfully extracted release zip");
let bin_name = match env::consts::OS { let bin_name = match env::consts::OS {
"windows" => "lune.exe", "windows" => "lune.exe",
"macos" | "linux" => "lune", "macos" | "linux" => "lune",
_ => panic!("unsupported platform"), _ => panic!("unsupported platform"),
}; };
let bin_base_dir = BaseDirs::new() let bin_base_dir = BaseDirs::new()
.ok_or(Error::new( .ok_or(Error::new(ErrorKind::NotFound, "failed to create BaseDirs instance"))?
ErrorKind::NotFound, .home_dir()
"failed to create BaseDirs instance", .join("bin");
))?
.home_dir()
.join("bin");
if !bin_base_dir.exists() { if !bin_base_dir.exists() {
tracing::warn!(target: TARGET, "bin_base_dir nonexistent, creating"); tracing::warn!(target: TARGET, "bin_base_dir nonexistent, creating");
std::fs::create_dir(&bin_base_dir)?; std::fs::create_dir(&bin_base_dir)?;
} }
tracing::warn!( tracing::warn!(
target: TARGET, target: TARGET,
"macOS and windows support for this action is incomplete" "macOS and windows support for this action is incomplete"
); );
// TODO: macOS and windows support // TODO: macOS and windows support
let lune_bin_path = bin_base_dir.join(bin_name); let lune_bin_path = bin_base_dir.join(bin_name);
File::create(&lune_bin_path)?; File::create(&lune_bin_path)?;
std::fs::rename(PathBuf::from(dir_name).join(bin_name), &lune_bin_path)?; std::fs::rename(PathBuf::from(dir_name).join(bin_name), &lune_bin_path)?;
tracing::info!( tracing::info!(
target: TARGET, target: TARGET,
"Installed lune bin to {}", "Installed lune bin to {}",
lune_bin_path.to_string_lossy() lune_bin_path.to_string_lossy()
); );
Ok(()) Ok(())
} }

View file

@ -2,8 +2,8 @@ use colored::Colorize;
use std::fmt; use std::fmt;
use tracing_core::{Event, Level, Subscriber}; use tracing_core::{Event, Level, Subscriber};
use tracing_subscriber::fmt::{ use tracing_subscriber::fmt::{
format::{self, FormatEvent, FormatFields}, format::{self, FormatEvent, FormatFields},
FmtContext, FormattedFields, FmtContext, FormattedFields,
}; };
use tracing_subscriber::registry::LookupSpan; use tracing_subscriber::registry::LookupSpan;
@ -11,51 +11,46 @@ pub struct LogFormatter;
impl<S, N> FormatEvent<S, N> for LogFormatter impl<S, N> FormatEvent<S, N> for LogFormatter
where where
S: Subscriber + for<'a> LookupSpan<'a>, S: Subscriber + for<'a> LookupSpan<'a>,
N: for<'a> FormatFields<'a> + 'static, N: for<'a> FormatFields<'a> + 'static,
{ {
fn format_event( fn format_event(&self, ctx: &FmtContext<'_, S, N>, mut writer: format::Writer<'_>, event: &Event<'_>) -> fmt::Result {
&self, let meta = event.metadata();
ctx: &FmtContext<'_, S, N>,
mut writer: format::Writer<'_>,
event: &Event<'_>,
) -> fmt::Result {
let meta = event.metadata();
let scope = match meta.level() { let scope = match *meta.level() {
&Level::DEBUG => "?".purple().bold(), Level::DEBUG => "?".purple().bold(),
&Level::ERROR => "!".red().bold(), Level::ERROR => "!".red().bold(),
&Level::INFO => "*".green().bold(), Level::INFO => "*".green().bold(),
&Level::TRACE => ".".white().bold(), Level::TRACE => ".".white().bold(),
&Level::WARN => "#".yellow().bold(), Level::WARN => "#".yellow().bold(),
}; };
let target = if meta.level() != &Level::INFO { let target = if meta.level() != &Level::INFO {
let mut sep = "::".to_owned(); let mut sep = "::".to_owned();
sep.push_str(&meta.target().italic().underline()); sep.push_str(&meta.target().italic().underline());
sep sep
} else { } else {
"::main".to_string() "::main".to_string()
}; };
write!(&mut writer, "[{}][{}] ", scope, target)?; write!(&mut writer, "[{}][{}] ", scope, target)?;
if let Some(scope) = ctx.event_scope() { if let Some(scope) = ctx.event_scope() {
for span in scope.from_root() { for span in scope.from_root() {
write!(writer, "{}", span.name())?; write!(writer, "{}", span.name())?;
let ext = span.extensions(); let ext = span.extensions();
let fields = &ext.get::<FormattedFields<N>>().unwrap(); let fields = &ext.get::<FormattedFields<N>>().unwrap();
if !fields.is_empty() { if !fields.is_empty() {
write!(writer, "{{{}}}", fields)?; write!(writer, "{{{}}}", fields)?;
} }
write!(writer, " ")?; write!(writer, " ")?;
} }
} }
ctx.field_format().format_fields(writer.by_ref(), event)?; ctx.field_format().format_fields(writer.by_ref(), event)?;
writeln!(writer) writeln!(writer)
} }
} }

View file

@ -7,147 +7,140 @@ use url::Url;
use crate::types::LuneReleaseData; use crate::types::LuneReleaseData;
#[derive(Debug, Default, Clone)]
pub struct GitHub { pub struct GitHub {
fetcher: Fetcher, fetcher: Fetcher,
repository: Repository, repository: Repository,
} }
impl GitHub { impl GitHub {
pub fn new(repo: (&str, &str)) -> Self { pub fn new(repo: (&str, &str)) -> Self {
let fetcher = Fetcher::new(); let fetcher = Fetcher::new();
Self { Self {
fetcher: (&fetcher).to_owned(), fetcher: fetcher.to_owned(),
repository: Repository::new(repo.0, repo.1, fetcher), repository: Repository::new(repo.0, repo.1, fetcher),
} }
} }
pub fn fetch_releases(&self) -> Result<LuneReleaseData> { pub fn fetch_releases(&self) -> Result<LuneReleaseData> {
let api_uri = Url::from_str(self.repository.api_url().as_str())? let api_uri = Url::from_str(self.repository.api_url().as_str())?.join("releases/")?.join("latest")?;
.join("releases/")?
.join("latest")?;
Ok( Ok(match self.fetcher.fetch::<_, LuneReleaseData>(Method::Get, api_uri, true)? {
match self FetchResult::Result(res) => res,
.fetcher FetchResult::Response(_) => {
.fetch::<_, LuneReleaseData>(Method::Get, api_uri, true)? unreachable!("Fetcher returned Response instead of Result")
{ }
FetchResult::Result(res) => res, })
FetchResult::Response(_) => { }
unreachable!("Fetcher returned Response instead of Result")
}
},
)
}
} }
#[derive(Debug, Default, Clone)]
pub struct Repository { pub struct Repository {
fetcher: Fetcher, fetcher: Fetcher,
scope: String, scope: String,
repo: String, repo: String,
} }
#[derive(Debug, Deserialize, Clone)] #[derive(Debug, Deserialize, Clone)]
pub struct RepositoryMeta { pub struct RepositoryMeta {
pub full_name: String, pub full_name: String,
pub name: String, pub name: String,
pub description: String, pub description: String,
pub license: HashMap<String, String>, pub license: HashMap<String, String>,
pub topics: Vec<String>, pub topics: Vec<String>,
pub forks: u32, pub forks: u32,
pub open_issues: u32, pub open_issues: u32,
pub stars: u32, pub stars: u32,
} }
impl Repository { impl Repository {
pub fn new<T>(scope: T, repo: T, fetcher: Fetcher) -> Self pub fn new<T>(scope: T, repo: T, fetcher: Fetcher) -> Self
where where
T: ToString, T: ToString,
{ {
Self { Self {
fetcher, fetcher,
scope: scope.to_string(), scope: scope.to_string(),
repo: repo.to_string(), repo: repo.to_string(),
} }
} }
pub fn scope(&self) -> &String { pub fn scope(&self) -> &String {
return &self.scope; &self.scope
} }
pub fn repo(&self) -> &String { pub fn repo(&self) -> &String {
return &self.repo; &self.repo
} }
pub fn api_url(&self) -> String { pub fn api_url(&self) -> String {
return format!("https://api.github.com/repos/{}/{}/", self.scope, self.repo); format!("https://api.github.com/repos/{}/{}/", self.scope, self.repo)
} }
pub fn fetch_meta(&self) -> Result<RepositoryMeta> { pub fn fetch_meta(&self) -> Result<RepositoryMeta> {
Ok( Ok(
match self.fetcher.fetch::<_, RepositoryMeta>( match self
Method::Get, .fetcher
Url::from_str(self.api_url().as_str())?, .fetch::<_, RepositoryMeta>(Method::Get, Url::from_str(self.api_url().as_str())?, true)?
true, {
)? { FetchResult::Result(deserialized) => deserialized,
FetchResult::Result(deserialized) => deserialized, FetchResult::Response(_) => {
FetchResult::Response(_) => { unreachable!("Fetcher returned Response instead of Result")
unreachable!("Fetcher returned Response instead of Result") }
} },
}, )
) }
}
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Fetcher { pub struct Fetcher {
client: ureq::Agent, client: ureq::Agent,
} }
pub enum Method { pub enum Method {
Get, Get,
Post, Post,
} }
pub enum FetchResult<D> { pub enum FetchResult<D> {
Result(D), Result(D),
Response(Response), Response(Box<Response>),
}
impl Default for Fetcher {
fn default() -> Self {
Self::new()
}
} }
impl Fetcher { impl Fetcher {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
client: ureq::builder() client: ureq::builder()
.redirects(2) .redirects(2)
.https_only(true) .https_only(true)
.timeout(Duration::from_secs(30)) .timeout(Duration::from_secs(30))
.user_agent("lune-action/0.1.0") .user_agent("lune-action/0.1.0")
.build(), .build(),
} }
} }
pub fn fetch<U, D>( pub fn fetch<U, D>(&self, method: Method, uri: U, to_deserialize: bool) -> Result<FetchResult<D>>
&self, where
method: Method, U: Into<url::Url>,
uri: U, D: DeserializeOwned,
to_deserialize: bool, {
) -> Result<FetchResult<D>> let method = match method {
where Method::Get => "GET",
U: Into<url::Url>, Method::Post => "POST",
D: DeserializeOwned, };
{
let method = match method {
Method::Get => "GET",
Method::Post => "POST",
};
let req = self.client.request_url(method, &uri.into()); let req = self.client.request_url(method, &uri.into());
Ok(match to_deserialize { Ok(match to_deserialize {
true => { true => FetchResult::Result(serde_json::from_reader::<_, D>(req.call()?.into_reader())?),
FetchResult::Result(serde_json::from_reader::<_, D>(req.call()?.into_reader())?) false => FetchResult::Response(Box::new(req.call()?)),
} })
false => FetchResult::Response(req.call()?), }
})
}
} }

View file

@ -2,44 +2,35 @@ use std::fs::File;
use actions_core as core; use actions_core as core;
use setup_lune::{ use setup_lune::{
download::{download_release, install_lune}, download::{download_release, install_lune},
fmt::LogFormatter, fmt::LogFormatter,
}; };
use tracing::Level; use tracing::Level;
use tracing_unwrap::ResultExt; use tracing_unwrap::ResultExt;
fn main() { fn main() {
let version = match core::input("version") { let version = match core::input("version") {
Ok(val) => Some(val), Ok(val) => Some(val),
Err(_) => None, Err(_) => None,
}; };
if cfg!(debug_assertions) { if cfg!(debug_assertions) {
better_panic::install(); better_panic::install();
} }
tracing_subscriber::fmt() tracing_subscriber::fmt()
.with_max_level(match core::is_debug() || cfg!(debug_assertions) { .with_max_level(match core::is_debug() || cfg!(debug_assertions) {
true => Level::DEBUG, true => Level::DEBUG,
false => Level::INFO, false => Level::INFO,
}) })
.event_format(LogFormatter) .event_format(LogFormatter)
.init(); .init();
let (zip_path, meta) = let (zip_path, meta) = download_release(version).expect_or_log("failed to download latest lune release");
download_release(version).expect_or_log("failed to download latest lune release");
install_lune( install_lune(
File::open(&zip_path).expect( File::open(&zip_path).unwrap_or_else(|_| panic!("failed to open downloaded lune release zip file @ {}", zip_path.to_string_lossy())),
format!( meta,
"failed to open downloaded lune release zip file @ {}", )
zip_path.to_string_lossy().to_string() .expect_or_log("failed to install lune. did we not have perms to write to the required directories?");
)
.as_str(),
),
meta,
)
.expect_or_log(
"failed to install lune. did we not have perms to write to the required directories?",
);
} }

View file

@ -2,20 +2,20 @@ use serde::Deserialize;
#[derive(Deserialize, Debug, Clone)] #[derive(Deserialize, Debug, Clone)]
pub struct LuneReleaseData { pub struct LuneReleaseData {
pub name: String, pub name: String,
pub assets: Vec<LuneAssetData>, pub assets: Vec<LuneAssetData>,
} }
#[derive(Deserialize, Debug, Clone)] #[derive(Deserialize, Debug, Clone)]
pub struct LuneAssetData { pub struct LuneAssetData {
pub browser_download_url: String, pub browser_download_url: String,
pub name: String, pub name: String,
} }
#[derive(Deserialize, Debug, Clone)] #[derive(Deserialize, Debug, Clone)]
pub struct LuneReleaseFetched { pub struct LuneReleaseFetched {
pub version: String, pub version: String,
pub download: String, pub download: String,
pub artifact_name: String, pub artifact_name: String,
pub raw: Option<LuneReleaseData>, pub raw: Option<LuneReleaseData>,
} }