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

@ -33,11 +33,7 @@ fn parse_release_data(data: &LuneReleaseData) -> LuneReleaseFetched {
); );
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
@ -50,9 +46,9 @@ fn parse_release_data(data: &LuneReleaseData) -> LuneReleaseFetched {
"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,
@ -84,15 +80,12 @@ pub fn download_release(version: Option<String>) -> Result<(PathBuf, LuneRelease
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, artifact_name,
raw: None, raw: None,
} }
} else { } else {
parsed_release_data = parsed_release_data = parse_release_data(&GitHub::new(("filiptibell", "lune")).fetch_releases()?);
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");
} }
@ -107,11 +100,7 @@ pub fn download_release(version: Option<String>) -> Result<(PathBuf, LuneRelease
&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) => {
@ -123,23 +112,16 @@ pub fn download_release(version: Option<String>) -> Result<(PathBuf, LuneRelease
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<()> {
@ -163,10 +145,7 @@ pub fn install_lune(lune_archive_reader: impl Read + Seek, meta: LuneReleaseFetc
}; };
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,
"failed to create BaseDirs instance",
))?
.home_dir() .home_dir()
.join("bin"); .join("bin");

View file

@ -14,20 +14,15 @@ 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,
ctx: &FmtContext<'_, S, N>,
mut writer: format::Writer<'_>,
event: &Event<'_>,
) -> fmt::Result {
let meta = event.metadata(); 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 {

View file

@ -7,6 +7,7 @@ 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,
@ -17,30 +18,24 @@ impl GitHub {
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
.fetcher
.fetch::<_, LuneReleaseData>(Method::Get, api_uri, true)?
{
FetchResult::Result(res) => res, FetchResult::Result(res) => res,
FetchResult::Response(_) => { FetchResult::Response(_) => {
unreachable!("Fetcher returned Response instead of Result") 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,
@ -72,24 +67,23 @@ impl Repository {
} }
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")
@ -111,7 +105,13 @@ pub enum Method {
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 {
@ -126,12 +126,7 @@ impl Fetcher {
} }
} }
pub fn fetch<U, D>( pub fn fetch<U, D>(&self, method: Method, uri: U, to_deserialize: bool) -> Result<FetchResult<D>>
&self,
method: Method,
uri: U,
to_deserialize: bool,
) -> Result<FetchResult<D>>
where where
U: Into<url::Url>, U: Into<url::Url>,
D: DeserializeOwned, D: DeserializeOwned,
@ -144,10 +139,8 @@ impl Fetcher {
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

@ -26,20 +26,11 @@ fn main() {
.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!(
"failed to open downloaded lune release zip file @ {}",
zip_path.to_string_lossy().to_string()
)
.as_str(),
),
meta, meta,
) )
.expect_or_log( .expect_or_log("failed to install lune. did we not have perms to write to the required directories?");
"failed to install lune. did we not have perms to write to the required directories?",
);
} }