Compare commits

..

No commits in common. "master" and "v1.1.0" have entirely different histories.

19 changed files with 178 additions and 227 deletions

6
.gitignore vendored
View File

@ -1,7 +1 @@
# build files
/target
# test files
docker-compose.yml
docker-compose.yaml
docker-compose.yml.yml

2
Cargo.lock generated
View File

@ -673,7 +673,7 @@ dependencies = [
[[package]]
name = "reel-moby"
version = "1.2.1"
version = "1.0.0"
dependencies = [
"chrono",
"lazy_static",

View File

@ -1,8 +1,8 @@
[package]
name = "reel-moby"
version = "1.2.1"
edition = "2021"
version = "1.0.0"
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

Binary file not shown.

Before

Width:  |  Height:  |  Size: 64 KiB

After

Width:  |  Height:  |  Size: 41 KiB

View File

@ -1,28 +0,0 @@
pub trait DisplayDurationExt {
/// displays a duration in a human readable form
fn display(&self) -> String;
}
impl DisplayDurationExt for chrono::Duration {
fn display(&self) -> String {
if self.num_weeks() == 52 {
format!("{} Year", (self.num_weeks() / 52) as i32)
} else if self.num_weeks() > 103 {
format!("{} Years", (self.num_weeks() / 52) as i32)
} else if self.num_days() == 1 {
format!("{} Day", self.num_days())
} else if self.num_days() > 1 {
format!("{} Days", self.num_days())
} else if self.num_hours() == 1 {
format!("{} Hour", self.num_hours())
} else if self.num_hours() > 1 {
format!("{} Hours", self.num_hours())
} else if self.num_minutes() == 1 {
format!("{} Minute", self.num_minutes())
} else if self.num_minutes() > 1 {
format!("{} Minutes", self.num_minutes())
} else {
format!("{} Seconds", self.num_seconds())
}
}
}

View File

@ -1 +0,0 @@
pub mod display_duration_ext;

View File

@ -1,7 +1,6 @@
use std::path::PathBuf;
use structopt::StructOpt;
mod common;
mod repo;
mod repository;
mod ui;
@ -10,6 +9,10 @@ mod widget;
/// helps you searching or updating tags of your used docker images
#[derive(StructOpt, Debug)]
pub struct Opt {
/// Show architectures of images and their sizes
#[structopt(short, long)]
verbose: bool,
/// A custom path to a docker-compose file
#[structopt(short, long, parse(from_os_str))]
file: Option<PathBuf>,

View File

@ -25,9 +25,6 @@ pub enum Repo {
}
/// check if yaml line matches and returns the split of repo string and rest
/// the first &str is the image tag
/// it will be used to not change the identation
/// the second &str will the the identifier for the image
pub fn match_yaml_image(input: &str) -> Result<(&str, &str), Error> {
lazy_static::lazy_static! {
static ref REGEX: Regex = Regex::new(r"^( +image *: *)([a-z0-9\-\./:]+)").unwrap();
@ -40,7 +37,6 @@ pub fn match_yaml_image(input: &str) -> Result<(&str, &str), Error> {
Ok((caps.get(1).unwrap().as_str(), caps.get(2).unwrap().as_str()))
}
/// takes the identifier and splits off the tag it exists
pub fn split_tag_from_repo(input: &str) -> Result<(&str, &str), Error> {
lazy_static::lazy_static! {
static ref REGEX: Regex = Regex::new(r"^([a-z0-9\./[^:]]*):?([a-z0-9._\-]*)").unwrap();
@ -63,7 +59,6 @@ pub fn split_tag_from_repo(input: &str) -> Result<(&str, &str), Error> {
Ok((front, back))
}
/// takes an identifier and changes it to a Repo enum
pub fn split_repo_without_tag(repo: &str) -> Result<Repo, Error> {
let repo = repo.trim();
let split_repo: Vec<&str> = repo.split('/').collect();

View File

@ -5,8 +5,6 @@ use crate::repository::Error;
#[derive(Deserialize, Debug, Clone)]
struct ImageDetails {
architecture: String,
os: String,
variant: Option<String>,
size: usize,
}
@ -28,8 +26,6 @@ impl Images {
.iter()
.map(|d| super::TagDetails {
arch: Some(d.architecture.clone()),
variant: Some(d.variant.clone().unwrap_or_default()),
os: Some(d.os.clone()),
size: Some(d.size),
})
.collect(),

73
src/repository/ghcr.rs Normal file
View File

@ -0,0 +1,73 @@
use serde::Deserialize;
use crate::repository::Error;
#[derive(Deserialize)]
struct Token {
token: String,
}
#[derive(Deserialize)]
pub struct Ghcr {
tags: Vec<String>,
}
impl Ghcr {
/// fetches tag information with a repository name in the form of organization/repository or library/repository in the case of official images from docker
pub fn create_repo(repo: &str) -> Result<super::Repo, Error> {
let request_token = format!("https://ghcr.io/token?scope=repository:{}:pull", repo);
let response = match reqwest::blocking::get(request_token) {
Err(e) => return Err(Error::Fetching(format!("reqwest error: {}", e))),
Ok(response) => response,
};
let token = match response.json::<Token>() {
Err(e) => return Err(Error::Converting(format!("invalid token json: {}", e))),
Ok(token) => token.token,
};
let request = format!("https://ghcr.io/v2/{}/tags/list?n=100", repo);
let client = reqwest::blocking::Client::new();
let response = match client
.get(request)
.header(reqwest::header::AUTHORIZATION, format!("Bearer {}", token))
.send()
{
// let response = match reqwest::blocking::get(url) {
Ok(result) => result,
Err(e) => return Err(Error::Fetching(format!("reqwest error: {}", e))),
};
//convert it to json
let tags = match response.json::<Self>() {
Ok(result) => result,
Err(e) => return Err(Error::Converting(format!("invalid json: {}", e))),
};
if tags.tags.is_empty() {
return Err(Error::NoTagsFound);
}
Ok(super::Repo {
tags: tags
.tags
.iter()
.map(|t| super::Tag {
name: t.clone(),
details: vec![],
last_updated: None,
})
.collect(),
next_page: None,
})
}
}
#[cfg(test)]
mod tests {
use super::Ghcr;
#[test]
fn test_ghcr() {
Ghcr::create_repo("ghcr.io/linuxserver/beets").unwrap();
}
}

View File

@ -1,10 +1,10 @@
mod dockerhub;
mod ghcr;
use std::fmt;
use chrono::DateTime;
use crate::common::display_duration_ext::DisplayDurationExt;
use crate::repo;
#[derive(Debug, PartialEq)]
@ -27,12 +27,25 @@ impl fmt::Display for Error {
}
}
#[derive(Clone, PartialEq)]
#[derive(Clone)]
pub struct TagDetails {
pub arch: Option<String>,
pub variant: Option<String>,
pub os: Option<String>,
pub size: Option<usize>,
arch: Option<String>,
size: Option<usize>,
}
impl fmt::Display for TagDetails {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let size = match self.size {
None => "".to_string(),
Some(s) => (s / 1024 / 1024).to_string(),
};
write!(
f,
"{}|{}MB",
self.arch.as_ref().unwrap_or(&"".to_string()),
size
)
}
}
#[derive(Clone)]
@ -48,22 +61,32 @@ impl Tag {
}
pub fn get_name_with_details(&self) -> String {
//architecture infos
let mut arch = String::new();
for image in self.details.iter().take(1) {
arch.push_str(&format!("{}", image));
}
for image in self.details.iter().skip(1) {
arch.push_str(&format!(", {}", image));
}
let arch = if !arch.is_empty() {
format!(" [{}]", arch)
} else {
String::new()
};
let dif = match &self.last_updated {
None => "".to_string(),
Some(last_updated) => {
let now = chrono::Utc::now();
let rfc3339 = DateTime::parse_from_rfc3339(last_updated).unwrap();
let dif = now - rfc3339.with_timezone(&chrono::Utc);
format!(", {} old", dif.display())
format!(" vor {}", format_time_nice(dif))
}
};
if dif.is_empty() {}
format!("{}{}", self.name, dif)
}
pub fn get_details(&self) -> &Vec<TagDetails> {
&self.details
format!("{}{}{}", self.name, dif, arch)
}
}
@ -82,10 +105,10 @@ impl Repo {
Err(e) => return Err(Error::Converting(format!("{}", e))),
};
if registry.unwrap_or_default().is_empty() {
dockerhub::DockerHub::create_repo(&repo)
if registry.unwrap_or_default() == "ghcr.io" {
ghcr::Ghcr::create_repo(&repo)
} else {
return Err(Error::Converting("This registry is not supported".into()));
dockerhub::DockerHub::create_repo(&repo)
}
}
@ -109,6 +132,29 @@ impl Repo {
}
}
/// converts a given duration to a readable string
fn format_time_nice(time: chrono::Duration) -> String {
if time.num_weeks() == 52 {
format!("{} Jahr", (time.num_weeks() / 52) as i32)
} else if time.num_weeks() > 103 {
format!("{} Jahren", (time.num_weeks() / 52) as i32)
} else if time.num_days() == 1 {
format!("{} Tag", time.num_days())
} else if time.num_days() > 1 {
format!("{} Tagen", time.num_days())
} else if time.num_hours() == 1 {
format!("{} Stunde", time.num_hours())
} else if time.num_hours() > 1 {
format!("{} Stunden", time.num_hours())
} else if time.num_minutes() == 1 {
format!("{} Minute", time.num_minutes())
} else if time.num_minutes() > 1 {
format!("{} Minuten", time.num_minutes())
} else {
format!("{} Sekunden", time.num_seconds())
}
}
/// checks the repo name and may add a prefix for official images
pub fn check_repo(name: &str) -> Result<String, Error> {
let repo = match repo::split_tag_from_repo(name) {

View File

@ -18,7 +18,6 @@ pub struct Ui {
repo: crate::widget::repo_entry::RepoEntry,
tags: crate::widget::tag_list::TagList,
services: crate::widget::service_switcher::ServiceSwitcher,
details: crate::widget::details::Details,
info: crate::widget::info::Info,
}
@ -29,16 +28,6 @@ pub enum State {
SelectService,
}
impl std::fmt::Display for State {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
State::EditRepo => write!(f, "Edit repository"),
State::SelectTag => write!(f, "Select a tag"),
State::SelectService => write!(f, "Select a image"),
}
}
}
impl std::iter::Iterator for State {
type Item = Self;
@ -54,18 +43,23 @@ impl std::iter::Iterator for State {
impl Ui {
pub fn run(opt: &Opt) {
let repo_id = opt.repo.as_deref();
let (repo_id, load_repo) = match &opt.repo {
None => (
"enter a repository here or select one from file widget",
false,
),
Some(repo) => (String::as_str(repo), true),
};
let mut ui = Ui {
state: State::SelectService,
repo: repo_entry::RepoEntry::new(repo_id),
tags: tag_list::TagList::with_status("Tags are empty"),
services: service_switcher::ServiceSwitcher::new(&opt.file).unwrap(),
details: crate::widget::details::Details::new(),
info: info::Info::new("Select image of edit Repository"),
};
if opt.repo.is_none() {
if load_repo {
ui.tags = tag_list::TagList::with_repo_name(ui.repo.get());
}
@ -86,7 +80,7 @@ impl Ui {
.direction(Direction::Vertical)
.constraints(
[
Constraint::Length(10),
Constraint::Min(9),
Constraint::Length(3),
Constraint::Min(7),
Constraint::Length(2),
@ -99,12 +93,7 @@ impl Ui {
rect.render_stateful_widget(list, chunks[0], state);
rect.render_widget(ui.repo.render(ui.state == State::EditRepo), chunks[1]);
let (list, state) = ui.tags.render(ui.state == State::SelectTag);
let more_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Min(15), Constraint::Length(28)].as_ref())
.split(chunks[2]);
rect.render_stateful_widget(list, more_chunks[0], state);
rect.render_widget(ui.details.render(), more_chunks[1]);
rect.render_stateful_widget(list, chunks[2], state);
rect.render_widget(ui.info.render(), chunks[3]);
})
.unwrap();
@ -114,14 +103,13 @@ impl Ui {
Ok(Key::Ctrl('q')) => break 'core, //quit program without saving
Ok(Key::Char('\t')) => {
ui.state.next();
ui.info.set_info(&ui.state);
}
Ok(Key::Ctrl('s')) => match ui.services.save() {
Err(e) => {
ui.info.set_info(&format!("{}", e));
continue;
}
Ok(_) => ui.info.set_text("Saved compose file"),
Ok(_) => ui.info.set_info("Saved compose file"),
},
Ok(Key::Ctrl('r')) => {
ui.repo.confirm();
@ -151,7 +139,7 @@ impl Ui {
Ok(Key::Char(key)) => match ui.state {
State::SelectService => (),
State::EditRepo => {
ui.info.set_text("Editing Repository");
ui.info.set_info("Editing Repository");
ui.repo.handle_input(Key::Char(key));
}
State::SelectTag => (),
@ -159,7 +147,7 @@ impl Ui {
Ok(Key::Backspace) => match ui.state {
State::SelectService => (),
State::EditRepo => {
ui.info.set_text("Editing Repository");
ui.info.set_info("Editing Repository");
ui.repo.handle_input(Key::Backspace);
}
State::SelectTag => (),
@ -183,10 +171,7 @@ impl Ui {
}
State::SelectService => (),
State::EditRepo => (),
State::SelectTag => {
ui.tags.handle_input(Key::Up);
ui.details = ui.tags.create_detail_widget();
}
State::SelectTag => ui.tags.handle_input(Key::Up),
},
Ok(Key::Down) => match ui.state {
State::SelectService if ui.services.find_next_match() => {
@ -207,10 +192,7 @@ impl Ui {
}
State::SelectService => (),
State::EditRepo => (),
State::SelectTag => {
ui.tags.handle_input(Key::Down);
ui.details = ui.tags.create_detail_widget();
}
State::SelectTag => ui.tags.handle_input(Key::Down),
},
_ => (),
}

View File

@ -6,7 +6,6 @@ use tui::backend::TermionBackend;
use tui::layout::{Constraint, Direction, Layout};
use tui::Terminal;
use crate::widget::details;
use crate::widget::info;
use crate::widget::repo_entry;
use crate::widget::tag_list;
@ -18,15 +17,6 @@ pub enum State {
SelectTag,
}
impl std::fmt::Display for State {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
State::EditRepo => write!(f, "Edit repository"),
State::SelectTag => write!(f, "Select a tag"),
}
}
}
impl std::iter::Iterator for State {
type Item = Self;
@ -43,24 +33,30 @@ pub struct NoYaml {
state: State,
repo: repo_entry::RepoEntry,
tags: tag_list::TagList,
details: details::Details,
info: info::Info,
}
impl NoYaml {
pub fn run(opt: &Opt) {
let repo_id = opt.repo.as_deref();
let (repo, load_repo) = match &opt.repo {
None => (
repo_entry::RepoEntry::new(
"enter a repository or select one from docker-compose.yml",
),
false,
),
Some(repo_id) => (repo_entry::RepoEntry::new(repo_id), true),
};
let mut ui = NoYaml {
state: State::EditRepo,
repo: repo_entry::RepoEntry::new(repo_id),
repo,
tags: tag_list::TagList::with_status("Tags are empty"),
details: details::Details::new(),
info: info::Info::new("could not find a docker-compose file"),
};
// load tags if a repository was given thorugh paramter
if opt.repo.is_none() {
if load_repo {
ui.tags = tag_list::TagList::with_repo_name(ui.repo.get());
}
@ -91,12 +87,7 @@ impl NoYaml {
rect.render_widget(ui.repo.render(ui.state == State::EditRepo), chunks[0]);
let (list, state) = ui.tags.render(ui.state == State::SelectTag);
let more_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Min(15), Constraint::Length(28)].as_ref())
.split(chunks[1]);
rect.render_stateful_widget(list, more_chunks[0], state);
rect.render_widget(ui.details.render(), more_chunks[1]);
rect.render_stateful_widget(list, chunks[1], state);
rect.render_widget(ui.info.render(), chunks[2]);
})
.unwrap();
@ -106,7 +97,6 @@ impl NoYaml {
Ok(Key::Ctrl('q')) => break 'core,
Ok(Key::Char('\t')) => {
ui.state.next();
ui.info.set_info(&ui.state);
}
Ok(Key::Ctrl('r')) => {
ui.repo.confirm();
@ -121,7 +111,7 @@ impl NoYaml {
},
Ok(Key::Char(key)) => match ui.state {
State::EditRepo => {
ui.info.set_text("Editing Repository");
ui.info.set_info("Editing Repository");
ui.repo.handle_input(Key::Char(key));
}
State::SelectTag => {
@ -130,24 +120,18 @@ impl NoYaml {
},
Ok(Key::Backspace) => match ui.state {
State::EditRepo => {
ui.info.set_text("Editing Repository");
ui.info.set_info("Editing Repository");
ui.repo.handle_input(Key::Backspace);
}
State::SelectTag => (),
},
Ok(Key::Up) => match ui.state {
State::EditRepo => (),
State::SelectTag => {
ui.tags.handle_input(Key::Up);
ui.details = ui.tags.create_detail_widget();
}
State::SelectTag => ui.tags.handle_input(Key::Up),
},
Ok(Key::Down) => match ui.state {
State::EditRepo => (),
State::SelectTag => {
ui.tags.handle_input(Key::Down);
ui.details = ui.tags.create_detail_widget();
}
State::SelectTag => ui.tags.handle_input(Key::Down),
},
_ => (),
}

View File

@ -1,61 +0,0 @@
use tui::style::{Color, Style};
use tui::widgets::{Block, Borders, List};
use crate::repository;
pub struct Details {
details: Vec<repository::TagDetails>,
}
impl Details {
pub fn new() -> Self {
Self { details: vec![] }
}
pub fn with_list(details: &[crate::repository::TagDetails]) -> Self {
let mut detail = Self {
details: details.to_owned(),
};
detail.details.sort_by(|a, b| a.arch.cmp(&b.arch));
detail.details.dedup();
detail
}
pub fn get_details(&self) -> Vec<String> {
let mut lines = vec![format!("{:^10}|{:^6}|{:^6}", "ARCH", "OS", "SIZE")];
for d in &self.details {
lines.push(format!(
"{:^10}|{:^6}|{:^6}MB",
format!(
"{}{}",
d.arch.clone().unwrap_or_default(),
d.variant.clone().unwrap_or_default()
),
d.os.clone().unwrap_or_default(),
d.size.unwrap_or_default() / 1024 / 1024,
));
}
lines
}
pub fn render(&self) -> List {
let items: Vec<tui::widgets::ListItem> = self
.get_details()
.iter()
.map(|l| {
tui::widgets::ListItem::new(l.to_string())
.style(Style::default().fg(Color::White).bg(Color::Black))
})
.collect();
List::new(items)
.block(
Block::default()
.title("Details")
.borders(Borders::ALL)
.border_style(Style::default()),
)
.style(Style::default().fg(Color::White).bg(Color::Black))
}
}

View File

@ -27,13 +27,7 @@ impl Info {
.highlight_style(Style::default().bg(Color::Black))
}
/// set a text to display
pub fn set_text(&mut self, info: &str) {
pub fn set_info(&mut self, info: &str) {
self.info = String::from(info);
}
/// print a text to display
pub fn set_info(&mut self, text: &dyn std::fmt::Display) {
self.info = format!("{}", text);
}
}

View File

@ -1,4 +1,3 @@
pub mod details;
pub mod info;
pub mod repo_entry;
pub mod service_switcher;

View File

@ -7,17 +7,14 @@ pub struct RepoEntry {
text: String,
old_text: String,
changed: bool,
default_text: bool,
}
impl RepoEntry {
pub fn new(text: Option<&str>) -> Self {
let default_text = "enter a repository here or select one from file widget";
pub fn new(text: &str) -> Self {
Self {
text: String::from(text.unwrap_or(default_text)),
old_text: String::from(text.unwrap_or(default_text)),
text: String::from(text),
old_text: String::from(text),
changed: false,
default_text: text.is_none(),
}
}
@ -59,14 +56,9 @@ impl RepoEntry {
Key::Char(c) => {
self.text.push(c);
self.changed = true;
self.default_text = false;
}
Key::Backspace => {
if self.default_text {
self.text = String::new();
} else {
self.text.pop();
}
self.text.pop();
self.changed = true;
}
Key::Esc => {

View File

@ -34,7 +34,6 @@ pub struct ServiceSwitcher {
impl ServiceSwitcher {
pub fn new(file: &Option<PathBuf>) -> Option<Self> {
//gather possible filenames
let mut file_list = vec![
PathBuf::from("docker-compose.yml"),
PathBuf::from("docker-compose.yaml"),
@ -44,7 +43,6 @@ impl ServiceSwitcher {
Some(file) => file_list.insert(0, file.clone()),
}
//try filenames
for file in file_list {
let list = match File::open(&file) {
Err(_) => continue,

View File

@ -45,7 +45,6 @@ pub struct TagList {
}
impl TagList {
/// shows a text in the list and no tags
pub fn with_status(status: &str) -> Self {
Self {
lines: vec![Line::Status(String::from(status))],
@ -54,7 +53,6 @@ impl TagList {
}
}
/// list the tags of the repository if the input is valid
pub fn with_repo_name(repo: String) -> Self {
match repository::Repo::new(&repo) {
Ok(tags) => Self::with_tags(tags),
@ -62,8 +60,7 @@ impl TagList {
}
}
/// list the tags of the input
fn with_tags(mut tags: repository::Repo) -> Self {
pub fn with_tags(mut tags: repository::Repo) -> Self {
let mut lines: Vec<Line> = tags
.get_tags()
.iter()
@ -116,18 +113,6 @@ impl TagList {
(items, &mut self.state)
}
pub fn create_detail_widget(&self) -> crate::widget::details::Details {
use crate::widget::details::Details;
match self.state.selected() {
None => Details::new(),
Some(i) => match &self.lines[i] {
Line::Image(t) => Details::with_list(t.get_details()),
_ => Details::new(),
},
}
}
pub fn handle_input(&mut self, key: termion::event::Key) {
match key {
Key::Down => self.next(),