A cli program to easily handle .gitignore files
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

104 lines
3.4 KiB

//! This module contains structs for working with the github templates
use crate::cache::Cache;
use log::{debug, trace};
use reqwest::blocking::Client;
use reqwest::header::{ACCEPT, CONTENT_TYPE, USER_AGENT};
use serde::{Deserialize, Serialize};
use crate::errors::*;
type CacheContents = Vec<Template>;
type CacheType = dyn Cache<CacheContents>;
/// Default user agent string used for api requests
pub const DEFAULT_USER_AGENT: &str = "gitig";
/// Default key used for cache
const CACHE_KEY: &str = "templates.json";
/// Response objects from github api
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[allow(clippy::missing_docs_in_private_items)]
pub struct Template {
pub name: String,
pub path: String,
pub sha: String,
pub size: i64,
pub url: String,
#[serde(rename = "html_url")]
pub html_url: String,
#[serde(rename = "git_url")]
pub git_url: String,
#[serde(rename = "download_url")]
pub download_url: Option<String>,
#[serde(rename = "type")]
pub type_field: String,
#[serde(rename = "_links")]
pub links: Links,
}
/// Part of github api response
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[allow(clippy::missing_docs_in_private_items)]
pub struct Links {
#[serde(rename = "self")]
pub self_field: String,
pub git: String,
pub html: String,
}
impl Template {
/// Checks if this template file is a gitignore template file
pub fn is_gitignore_template(&self) -> bool { self.name.ends_with(".gitignore") }
/// Returns the name of the file without the .gitignore ending
///
/// if `!self.is_gitignore_template()` the whole `self.name` is returned
pub fn pretty_name(&self) -> &str {
if let Some(dot_index) = self.name.rfind('.') {
return &self.name.get(0..dot_index).unwrap_or_else(|| self.name.as_str());
}
self.name.as_str()
}
}
/// This struct holds the information about the templates available at github
#[derive(Serialize, Deserialize)]
pub struct GithubTemplates {
/// The templates
templates: CacheContents,
}
impl GithubTemplates {
/// Loads the templates from the github api
fn from_server() -> Result<GithubTemplates> {
trace!("Loading templates from github api");
let client = Client::new();
let res = client
.get("https://api.github.com/repos/github/gitignore/contents//")
.header(ACCEPT, "application/jsonapplication/vnd.github.v3+json")
.header(CONTENT_TYPE, "application/json")
.header(USER_AGENT, format!("{} {}", DEFAULT_USER_AGENT, env!("CARGO_PKG_VERSION")))
.send()
.chain_err(|| "Error while sending request to query all templates")?;
let body: Vec<Template> = res.json().chain_err(|| "json")?;
debug!("Received and deserialized {} templates", body.len());
Ok(GithubTemplates { templates: body })
}
/// Creates a new struct with templates
pub fn new() -> Result<GithubTemplates> { Self::from_server() }
/// Returns a list of the template names
pub fn list_names(&self) -> Vec<&str> {
self.templates
.iter()
.filter(|t| t.is_gitignore_template())
.map(Template::pretty_name)
.collect()
}
}