Files
action-gh-release/src/main.rs
T

112 lines
2.6 KiB
Rust
Raw Normal View History

2019-08-25 02:13:05 -04:00
mod github;
use github::{AssetUploader, Release, Releaser};
use reqwest::Client;
use serde::Deserialize;
2019-08-25 02:27:52 -04:00
use std::{error::Error, fs::File, path::Path};
2019-08-25 02:13:05 -04:00
#[derive(Deserialize, Default)]
struct Config {
// provided
github_token: String,
github_ref: String, // refs/heads/..., ref/tags/...
github_repository: String,
// optional
input_body: Option<String>,
input_files: Option<Vec<String>>,
}
fn release(conf: &Config) -> Release {
let Config {
github_ref,
input_body,
..
} = conf;
Release {
tag_name: github_ref.clone(),
body: input_body.clone(),
..Release::default()
}
}
2019-08-25 02:27:52 -04:00
fn is_tag<R>(gitref: R) -> bool
where
R: AsRef<str>,
{
2019-08-25 02:23:48 -04:00
gitref.as_ref().starts_with("refs/tags/")
}
2019-08-25 02:27:52 -04:00
fn mime_or_default<P>(path: P) -> mime::Mime
where
P: AsRef<Path>,
{
mime_guess::from_path(path).first_or(mime::APPLICATION_OCTET_STREAM)
}
2019-08-25 02:13:05 -04:00
fn run(
conf: Config,
releaser: &dyn Releaser,
uploader: &dyn AssetUploader,
) -> Result<(), Box<dyn Error>> {
2019-08-25 02:23:48 -04:00
if !is_tag(&conf.github_ref) {
2019-08-25 02:13:05 -04:00
log::error!("GH Releases require a tag");
return Ok(());
}
let release_id = releaser.release(
conf.github_token.as_str(),
conf.github_repository.as_str(),
release(&conf),
)?;
if let Some(patterns) = conf.input_files {
for pattern in patterns {
for path in glob::glob(pattern.as_str())? {
let resolved = path?;
uploader.upload(
conf.github_token.as_str(),
conf.github_repository.as_str(),
release_id,
2019-08-25 02:27:52 -04:00
mime_or_default(&resolved),
2019-08-25 02:13:05 -04:00
File::open(resolved)?,
)?;
}
}
}
Ok(())
}
fn main() -> Result<(), Box<dyn Error>> {
env_logger::init();
let client = Client::new();
run(envy::from_env()?, &client, &client)
}
#[cfg(test)]
mod tests {
use super::*;
2019-08-25 02:27:52 -04:00
#[test]
fn mime_or_default_defaults_to_octect_stream() {
assert_eq!(
mime_or_default("umbiguous-file"),
mime::APPLICATION_OCTET_STREAM
)
}
2019-08-25 02:13:05 -04:00
#[test]
fn release_constructs_a_release_from_a_config() -> Result<(), Box<dyn Error>> {
for (conf, expect) in vec![(Config::default(), Release::default())] {
assert_eq!(release(&conf), expect);
}
Ok(())
}
2019-08-25 02:23:48 -04:00
#[test]
fn is_tag_checks_refs() {
2019-08-25 02:27:52 -04:00
for (gitref, expect) in &[("refs/tags/foo", true), ("refs/heads/master", false)] {
2019-08-25 02:23:48 -04:00
assert_eq!(is_tag(gitref), *expect)
}
}
2019-08-25 02:13:05 -04:00
}