Compare commits

..

35 Commits

Author SHA1 Message Date
Thomas Eppers
8f0eb3db4f removed faulty ghcr implementation
Some checks failed
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/tag/woodpecker Pipeline failed
2022-07-23 17:20:34 +02:00
Thomas Eppers
13350f872a Merge tag 'v1.2.1' into development 2022-07-23 00:50:57 +02:00
Thomas Eppers
c8915f828f bumped edition and version 2022-07-23 00:50:03 +02:00
Thomas Eppers
88070489f3 fixed clippy warnings 2022-07-23 00:47:25 +02:00
Thomas Eppers
d1ef5c6755 removed unused argument 2022-07-23 00:47:07 +02:00
Thomas Eppers
e98c5e7a12 changed format_time_nice to a trait that extends chrono::Duration 2022-07-23 00:38:44 +02:00
Thomas Eppers
6c83683a4a fixed clippy warnings
All checks were successful
continuous-integration/woodpecker the build was successful
2021-11-25 17:10:29 +01:00
Thomas Eppers
3bf2359392 added the ability to instantly delete default text in RepoEntry; simplified some code
All checks were successful
continuous-integration/woodpecker the build was successful
2021-11-25 17:08:22 +01:00
Thomas Eppers
bb5ea3a993 add variant information back to details view 2021-11-25 16:42:26 +01:00
Thomas Eppers
7d9cc21b6e removed old code 2021-11-25 14:06:43 +01:00
Thomas Eppers
e3865da563 removed old code; switched output to english 2021-11-25 14:02:56 +01:00
Thomas Eppers
881423e461 updated screenshot 2021-11-25 13:37:46 +01:00
Thomas Eppers
b6dbcd8eba Merge branch 'master' of ssh://gitea.eppixx.freeddns.org:10022/eppixx/reel-moby
All checks were successful
continuous-integration/woodpecker the build was successful
2021-11-24 18:06:04 +01:00
Thomas Eppers
04842af653 update gitignore file
All checks were successful
continuous-integration/woodpecker the build was successful
2021-11-24 17:57:52 +01:00
Thomas Eppers
bd60e57fea update 2021-11-24 17:56:15 +01:00
Thomas Eppers
e1d9cbe8c9 fixed some clippy warnings
All checks were successful
continuous-integration/woodpecker the build was successful
2021-11-24 17:49:23 +01:00
Thomas Eppers
987606d264 remove details in TagList; change ServiceSwitcher height 2021-11-24 17:47:06 +01:00
Thomas Eppers
b59c5f4ead added detail widget to no_yaml ui 2021-11-24 17:41:06 +01:00
Thomas Eppers
e3c6e01036 remove duplicate details 2021-11-24 17:34:43 +01:00
Thomas Eppers
a725161638 changed layout of default ui 2021-11-24 17:31:02 +01:00
Thomas Eppers
62f784fdb9 creating a widget for displaying tag details 2021-11-24 16:27:47 +01:00
Thomas Eppers
7720ed3102 restructured test; fixed a bug in regex for matching yaml image lines
All checks were successful
continuous-integration/woodpecker the build was successful
2021-11-16 13:12:12 +01:00
Thomas Eppers
6d40b03fbf added more comments
All checks were successful
continuous-integration/woodpecker the build was successful
2021-11-03 17:08:30 +01:00
Thomas Eppers
246124d4d1 added some comments
All checks were successful
continuous-integration/woodpecker the build was successful
2021-11-03 15:58:01 +01:00
Thomas Eppers
eec1836dd3 added some comments 2021-11-03 15:39:32 +01:00
Thomas Eppers
79577de0f9 take a generic object for displaying in the info widget 2021-11-03 15:06:54 +01:00
Thomas Eppers
72fd5ec46f updated screenshot
All checks were successful
continuous-integration/woodpecker the build was successful
2021-11-02 15:41:28 +01:00
Thomas Eppers
a41197562b nicer formatting for TagList
All checks were successful
continuous-integration/woodpecker the build was successful
2021-11-01 13:18:05 +01:00
Thomas Eppers
0ace41f545 removed clippy warnings 2021-11-01 13:09:09 +01:00
Thomas Eppers
cefe57b980 first working version with ghcr 2021-11-01 13:07:11 +01:00
Thomas Eppers
fe3f0579ad moved function to mod.rs; use generic structs in default.rs 2021-11-01 13:00:59 +01:00
Thomas Eppers
cb1a1c24b7 fixed some clippy warnings; added TODOs for later 2021-11-01 12:34:05 +01:00
Thomas Eppers
bc09317d4b fixed tests for DockerHub 2021-11-01 12:29:58 +01:00
Thomas Eppers
c0d376c79f created new generic structs for another registry than docker.hub 2021-11-01 12:27:51 +01:00
Thomas Eppers
cdb6babd48 bump version to version 1.0.0
All checks were successful
continuous-integration/woodpecker the build was successful
2021-10-31 22:52:06 +01:00
19 changed files with 507 additions and 271 deletions

6
.gitignore vendored
View File

@ -1 +1,7 @@
# build files
/target /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]] [[package]]
name = "reel-moby" name = "reel-moby"
version = "0.10.0" version = "1.2.1"
dependencies = [ dependencies = [
"chrono", "chrono",
"lazy_static", "lazy_static",

View File

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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 41 KiB

After

Width:  |  Height:  |  Size: 64 KiB

View File

@ -0,0 +1,28 @@
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())
}
}
}

1
src/common/mod.rs Normal file
View File

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

View File

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

View File

@ -25,9 +25,12 @@ pub enum Repo {
} }
/// check if yaml line matches and returns the split of repo string and rest /// 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> { pub fn match_yaml_image(input: &str) -> Result<(&str, &str), Error> {
lazy_static::lazy_static! { lazy_static::lazy_static! {
static ref REGEX: Regex = Regex::new(r"^( +image *: *)([a-z0-9\./:]+)").unwrap(); static ref REGEX: Regex = Regex::new(r"^( +image *: *)([a-z0-9\-\./:]+)").unwrap();
} }
let caps = match REGEX.captures(input) { let caps = match REGEX.captures(input) {
Some(caps) => caps, Some(caps) => caps,
@ -37,6 +40,7 @@ pub fn match_yaml_image(input: &str) -> Result<(&str, &str), Error> {
Ok((caps.get(1).unwrap().as_str(), caps.get(2).unwrap().as_str())) 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> { pub fn split_tag_from_repo(input: &str) -> Result<(&str, &str), Error> {
lazy_static::lazy_static! { lazy_static::lazy_static! {
static ref REGEX: Regex = Regex::new(r"^([a-z0-9\./[^:]]*):?([a-z0-9._\-]*)").unwrap(); static ref REGEX: Regex = Regex::new(r"^([a-z0-9\./[^:]]*):?([a-z0-9._\-]*)").unwrap();
@ -59,6 +63,7 @@ pub fn split_tag_from_repo(input: &str) -> Result<(&str, &str), Error> {
Ok((front, back)) Ok((front, back))
} }
/// takes an identifier and changes it to a Repo enum
pub fn split_repo_without_tag(repo: &str) -> Result<Repo, Error> { pub fn split_repo_without_tag(repo: &str) -> Result<Repo, Error> {
let repo = repo.trim(); let repo = repo.trim();
let split_repo: Vec<&str> = repo.split('/').collect(); let split_repo: Vec<&str> = repo.split('/').collect();
@ -98,58 +103,79 @@ mod tests {
#[test] #[test]
fn test_split_repo_without_tag() { fn test_split_repo_without_tag() {
use crate::repo::split_repo_without_tag as test_fn; let input: Vec<(&str, Result<Repo, Error>)> = vec![
assert_eq!(test_fn(""), Err(Error::MisformedInput)); ("", Err(Error::MisformedInput)),
assert_eq!(test_fn("NGINX"), Err(Error::MisformedInput)); ("NGINX", Err(Error::MisformedInput)),
assert_eq!(test_fn("nginx"), Ok(Repo::Project("nginx".into()))); ("nginx", Ok(Repo::Project("nginx".into()))),
assert_eq!( (
test_fn("library/nginx"), "library/nginx",
Ok(Repo::WithOrga("library".into(), "nginx".into())) Ok(Repo::WithOrga("library".into(), "nginx".into())),
); ),
assert_eq!( (
test_fn("ghcr.io/library/nginx"), "ghcr.io/library/nginx",
Ok(Repo::WithServer( Ok(Repo::WithServer(
"ghcr.io".into(), "ghcr.io".into(),
"library".into(), "library".into(),
"nginx".into(), "nginx".into(),
)) )),
); ),
(
"te-st/test-hypen",
Ok(Repo::WithOrga("te-st".into(), "test-hypen".into())),
),
(
"test/test.dot",
Ok(Repo::WithOrga("test".into(), "test.dot".into())),
),
];
for i in input {
assert_eq!(super::split_repo_without_tag(i.0), i.1);
}
} }
#[test] #[test]
fn test_match_yaml_image() { fn test_match_yaml_image() {
use crate::repo::match_yaml_image as test_fn; let input: Vec<(&str, Result<(&str, &str), Error>)> = vec![
assert_eq!(test_fn(""), Err(Error::NoTagFound)); ("", Err(Error::NoTagFound)),
assert_eq!(test_fn("version: '2'"), Err(Error::NoTagFound)); ("version: '2'", Err(Error::NoTagFound)),
assert_eq!(test_fn("image: "), Err(Error::NoTagFound)); ("image: ", Err(Error::NoTagFound)),
assert_eq!(test_fn(" image: "), Err(Error::NoTagFound)); (" image: ", Err(Error::NoTagFound)),
assert_eq!(test_fn(" image: nginx"), Ok((" image: ", "nginx"))); (" image: nginx", Ok((" image: ", "nginx"))),
assert_eq!( (" image: library/nginx", Ok((" image: ", "library/nginx"))),
test_fn(" image: library/nginx"), (
Ok((" image: ", "library/nginx")) " image: gchr.io/library/nginx",
); Ok((" image: ", "gchr.io/library/nginx")),
assert_eq!( ),
test_fn(" image: ghcr.io/library/nginx"), (" image: nginx # comment", Ok((" image: ", "nginx"))),
Ok((" image: ", "ghcr.io/library/nginx")) (" image: test-hyphen", Ok((" image: ", "test-hyphen"))),
); (" image: test.dot", Ok((" image: ", "test.dot"))),
assert_eq!(test_fn("# image: nginx"), Err(Error::NoTagFound)); ];
assert_eq!(
test_fn(" image: nginx #comment"), for i in input {
Ok((" image: ", "nginx")) assert_eq!(super::match_yaml_image(i.0), i.1);
); }
} }
#[test] #[test]
fn test_split_tag_from_repo() { fn test_split_tag_from_repo() {
use crate::repo::split_tag_from_repo as test_fn; let input: Vec<(&str, Result<(&str, &str), super::Error>)> = vec![
assert_eq!(test_fn("nginx"), Ok(("nginx", ""))); ("nginx", Ok(("nginx", ""))),
assert_eq!(test_fn("library/nginx"), Ok(("library/nginx", ""))); ("library/nginx", Ok(("library/nginx", ""))),
assert_eq!( ("ghcr.io/library/nginx", Ok(("ghcr.io/library/nginx", ""))),
test_fn("ghcr.io/library/nginx"), ("nginx:", Ok(("nginx", ""))),
Ok(("ghcr.io/library/nginx", "")) ("nginx:1", Ok(("nginx", "1"))),
); ("nginx:latest", Ok(("nginx", "latest"))),
assert_eq!(test_fn("nginx:"), Ok(("nginx", ""))); ("hy-phen:latest", Ok(("hy-phen", "latest"))),
assert_eq!(test_fn("nginx:1"), Ok(("nginx", "1"))); ("test.dot:latest", Ok(("test.dot", "latest"))),
assert_eq!(test_fn("nginx:latest"), Ok(("nginx", "latest"))); (
"woodpeckerci/woodpecker-server",
Ok(("woodpeckerci/woodpecker-server", "")),
),
];
for i in input {
assert_eq!(super::split_tag_from_repo(i.0), i.1);
}
} }
} }

View File

@ -0,0 +1,76 @@
use serde::Deserialize;
use crate::repository::Error;
#[derive(Deserialize, Debug, Clone)]
struct ImageDetails {
architecture: String,
os: String,
variant: Option<String>,
size: usize,
}
#[derive(Deserialize, Clone)]
pub struct Images {
images: Vec<ImageDetails>,
#[serde(rename(deserialize = "name"))]
tag_name: String,
last_updated: String,
}
impl Images {
pub fn convert(&self) -> super::Tag {
super::Tag {
name: self.tag_name.clone(),
last_updated: Some(self.last_updated.clone()),
details: self
.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(),
}
}
}
#[derive(Deserialize)]
pub struct DockerHub {
#[serde(rename(deserialize = "next"))]
next_page: Option<String>,
results: Vec<Images>,
}
impl DockerHub {
/// 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 = format!("https://hub.docker.com/v2/repositories/{}/tags", repo);
Self::with_url(&request)
}
/// fetches tag information from a url
pub fn with_url(url: &str) -> Result<super::Repo, Error> {
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.results.is_empty() {
return Err(Error::NoTagsFound);
}
Ok(super::Repo {
tags: tags.results.iter().map(|t| t.convert()).collect(),
next_page: tags.next_page,
})
}
}

137
src/repository/mod.rs Normal file
View File

@ -0,0 +1,137 @@
mod dockerhub;
use std::fmt;
use chrono::DateTime;
use crate::common::display_duration_ext::DisplayDurationExt;
use crate::repo;
#[derive(Debug, PartialEq)]
pub enum Error {
/// couldn't fetch json with reqwest
Fetching(String),
/// a serde error
Converting(String),
/// invalid repos show a valid json with 0 tags
NoTagsFound,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Fetching(s) => write!(f, "Fetching error: {}", s),
Error::Converting(s) => write!(f, "Converting error: {}", s),
Error::NoTagsFound => write!(f, "Given Repo has 0 tags. Is it valid?"),
}
}
}
#[derive(Clone, PartialEq)]
pub struct TagDetails {
pub arch: Option<String>,
pub variant: Option<String>,
pub os: Option<String>,
pub size: Option<usize>,
}
#[derive(Clone)]
pub struct Tag {
name: String,
details: Vec<TagDetails>,
last_updated: Option<String>,
}
impl Tag {
pub fn get_name(&self) -> &str {
&self.name
}
pub fn get_name_with_details(&self) -> String {
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())
}
};
if dif.is_empty() {}
format!("{}{}", self.name, dif)
}
pub fn get_details(&self) -> &Vec<TagDetails> {
&self.details
}
}
pub struct Repo {
tags: Vec<Tag>,
next_page: Option<String>,
}
impl Repo {
pub fn new(repo: &str) -> Result<Self, Error> {
use crate::repo::Repo;
let (registry, repo) = match crate::repo::split_repo_without_tag(repo) {
Ok(Repo::WithServer(reg, org, pro)) => (Some(reg), format!("{}/{}", org, pro)),
Ok(Repo::WithOrga(org, pro)) => (None, format!("{}/{}", org, pro)),
Ok(Repo::Project(pro)) => (None, format!("library/{}", pro)),
Err(e) => return Err(Error::Converting(format!("{}", e))),
};
if registry.unwrap_or_default().is_empty() {
dockerhub::DockerHub::create_repo(&repo)
} else {
return Err(Error::Converting("This registry is not supported".into()));
}
}
pub fn with_url(url: &str) -> Result<Self, Error> {
//TODO fix for other registries
dockerhub::DockerHub::with_url(url)
}
pub fn get_tags(&self) -> &Vec<Tag> {
&self.tags
}
pub fn next_page(&self) -> Option<Self> {
match &self.next_page {
Some(url) => match Self::with_url(url) {
Ok(tags) => Some(tags),
Err(_) => None,
},
None => None,
}
}
}
/// 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) {
Err(e) => return Err(Error::Converting(format!("{}", e))),
Ok((name, _)) => name,
};
match repo::split_repo_without_tag(name) {
Ok(repo::Repo::Project(s)) => Ok(format!("library/{}", s)),
Ok(_) => Ok(repo.to_string()),
Err(e) => Err(Error::Converting(format!("{}", e))),
}
}
#[cfg(test)]
mod tests {
#[test]
fn test_check_repo() {
assert_eq!(super::check_repo("nginx").unwrap(), "library/nginx");
assert_eq!(super::check_repo("library/nginx").unwrap(), "library/nginx");
assert_eq!(
super::check_repo("rocketchat/rocket.chat").unwrap(),
"rocketchat/rocket.chat"
);
}
}

View File

@ -1,168 +0,0 @@
use std::fmt;
use crate::repo;
use chrono::DateTime;
use serde::Deserialize;
#[derive(Deserialize, Debug, Clone)]
struct ImageDetails {
architecture: String,
size: usize,
}
impl fmt::Display for ImageDetails {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}|{}MB", self.architecture, self.size / 1024 / 1024)
}
}
#[derive(Deserialize, Clone)]
pub struct Images {
images: Vec<ImageDetails>,
#[serde(rename(deserialize = "name"))]
pub tag_name: String,
last_updated: String,
}
impl fmt::Display for Images {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
//architecture infos
let mut arch = String::new();
for image in self.images.iter().take(1) {
arch.push_str(&format!("{}", image));
}
for image in self.images.iter().skip(1) {
arch.push_str(&format!(", {}", image));
}
let now = chrono::Utc::now();
let rfc3339 = DateTime::parse_from_rfc3339(&self.last_updated).unwrap();
let dif = now - rfc3339.with_timezone(&chrono::Utc);
write!(
f,
"{} vor {} [{}]",
self.tag_name,
format_time_nice(dif),
arch
)
}
}
#[derive(Deserialize)]
pub struct Tags {
count: usize,
#[serde(rename(deserialize = "next"))]
pub next_page: Option<String>,
pub results: Vec<Images>,
}
#[derive(Debug, PartialEq)]
pub enum Error {
/// couldn't fetch json with reqwest
Fetching(String),
/// a serde error
Converting(String),
/// invalid repos show a valid json with 0 tags
NoTagsFound,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Fetching(s) => write!(f, "Fetching error: {}", s),
Error::Converting(s) => write!(f, "Converting error: {}", s),
Error::NoTagsFound => write!(f, "Given Repo has 0 tags. Is it valid?"),
}
}
}
impl Tags {
/// 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 new(repo: String) -> Result<Self, Error> {
let request = format!("https://hub.docker.com/v2/repositories/{}/tags", repo);
Self::with_url(&request)
}
/// fetches tag information from a url
fn with_url(url: &str) -> Result<Self, Error> {
let res = match reqwest::blocking::get(url) {
Ok(result) => result,
Err(e) => return Err(Error::Fetching(format!("reqwest error: {}", e))),
};
//convert it to json
let raw = res.text().unwrap();
let tags: Self = match serde_json::from_str(&raw) {
Ok(result) => result,
Err(e) => return Err(Error::Converting(format!("invalid json: {}", e))),
};
if tags.count == 0 {
return Err(Error::NoTagsFound);
}
Ok(tags)
}
/// 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) {
Err(e) => return Err(Error::Converting(format!("{}", e))),
Ok((name, _)) => name,
};
match repo::split_repo_without_tag(name) {
Ok(repo::Repo::Project(s)) => Ok(format!("library/{}", s)),
Ok(_) => Ok(repo.to_string()),
Err(e) => Err(Error::Converting(format!("{}", e))),
}
}
/// returns tags of next page
pub fn next_page(&self) -> Option<Self> {
match &self.next_page {
Some(url) => match Self::with_url(url) {
Ok(tags) => Some(tags),
Err(_) => None,
},
None => None,
}
}
}
/// 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())
}
}
#[cfg(test)]
mod tests {
use crate::tags::Tags;
#[test]
fn test_check_repo() {
assert_eq!(Tags::check_repo("nginx").unwrap(), "library/nginx");
assert_eq!(Tags::check_repo("library/nginx").unwrap(), "library/nginx");
assert_eq!(
Tags::check_repo("rocketchat/rocket.chat").unwrap(),
"rocketchat/rocket.chat"
);
}
}

View File

@ -7,6 +7,7 @@ use tui::backend::TermionBackend;
use tui::layout::{Constraint, Direction, Layout}; use tui::layout::{Constraint, Direction, Layout};
use tui::Terminal; use tui::Terminal;
use crate::repository;
use crate::widget::info; use crate::widget::info;
use crate::widget::repo_entry; use crate::widget::repo_entry;
use crate::widget::service_switcher; use crate::widget::service_switcher;
@ -17,6 +18,7 @@ pub struct Ui {
repo: crate::widget::repo_entry::RepoEntry, repo: crate::widget::repo_entry::RepoEntry,
tags: crate::widget::tag_list::TagList, tags: crate::widget::tag_list::TagList,
services: crate::widget::service_switcher::ServiceSwitcher, services: crate::widget::service_switcher::ServiceSwitcher,
details: crate::widget::details::Details,
info: crate::widget::info::Info, info: crate::widget::info::Info,
} }
@ -27,6 +29,16 @@ pub enum State {
SelectService, 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 { impl std::iter::Iterator for State {
type Item = Self; type Item = Self;
@ -42,23 +54,18 @@ impl std::iter::Iterator for State {
impl Ui { impl Ui {
pub fn run(opt: &Opt) { pub fn run(opt: &Opt) {
let (repo_id, load_repo) = match &opt.repo { let repo_id = opt.repo.as_deref();
None => (
"enter a repository here or select one from file widget",
false,
),
Some(repo) => (String::as_str(repo), true),
};
let mut ui = Ui { let mut ui = Ui {
state: State::SelectService, state: State::SelectService,
repo: repo_entry::RepoEntry::new(repo_id), repo: repo_entry::RepoEntry::new(repo_id),
tags: tag_list::TagList::with_status("Tags are empty"), tags: tag_list::TagList::with_status("Tags are empty"),
services: service_switcher::ServiceSwitcher::new(&opt.file).unwrap(), services: service_switcher::ServiceSwitcher::new(&opt.file).unwrap(),
details: crate::widget::details::Details::new(),
info: info::Info::new("Select image of edit Repository"), info: info::Info::new("Select image of edit Repository"),
}; };
if load_repo { if opt.repo.is_none() {
ui.tags = tag_list::TagList::with_repo_name(ui.repo.get()); ui.tags = tag_list::TagList::with_repo_name(ui.repo.get());
} }
@ -79,7 +86,7 @@ impl Ui {
.direction(Direction::Vertical) .direction(Direction::Vertical)
.constraints( .constraints(
[ [
Constraint::Min(9), Constraint::Length(10),
Constraint::Length(3), Constraint::Length(3),
Constraint::Min(7), Constraint::Min(7),
Constraint::Length(2), Constraint::Length(2),
@ -92,7 +99,12 @@ impl Ui {
rect.render_stateful_widget(list, chunks[0], state); rect.render_stateful_widget(list, chunks[0], state);
rect.render_widget(ui.repo.render(ui.state == State::EditRepo), chunks[1]); rect.render_widget(ui.repo.render(ui.state == State::EditRepo), chunks[1]);
let (list, state) = ui.tags.render(ui.state == State::SelectTag); let (list, state) = ui.tags.render(ui.state == State::SelectTag);
rect.render_stateful_widget(list, chunks[2], state); 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_widget(ui.info.render(), chunks[3]); rect.render_widget(ui.info.render(), chunks[3]);
}) })
.unwrap(); .unwrap();
@ -102,13 +114,14 @@ impl Ui {
Ok(Key::Ctrl('q')) => break 'core, //quit program without saving Ok(Key::Ctrl('q')) => break 'core, //quit program without saving
Ok(Key::Char('\t')) => { Ok(Key::Char('\t')) => {
ui.state.next(); ui.state.next();
ui.info.set_info(&ui.state);
} }
Ok(Key::Ctrl('s')) => match ui.services.save() { Ok(Key::Ctrl('s')) => match ui.services.save() {
Err(e) => { Err(e) => {
ui.info.set_info(&format!("{}", e)); ui.info.set_info(&format!("{}", e));
continue; continue;
} }
Ok(_) => ui.info.set_info("Saved compose file"), Ok(_) => ui.info.set_text("Saved compose file"),
}, },
Ok(Key::Ctrl('r')) => { Ok(Key::Ctrl('r')) => {
ui.repo.confirm(); ui.repo.confirm();
@ -138,7 +151,7 @@ impl Ui {
Ok(Key::Char(key)) => match ui.state { Ok(Key::Char(key)) => match ui.state {
State::SelectService => (), State::SelectService => (),
State::EditRepo => { State::EditRepo => {
ui.info.set_info("Editing Repository"); ui.info.set_text("Editing Repository");
ui.repo.handle_input(Key::Char(key)); ui.repo.handle_input(Key::Char(key));
} }
State::SelectTag => (), State::SelectTag => (),
@ -146,7 +159,7 @@ impl Ui {
Ok(Key::Backspace) => match ui.state { Ok(Key::Backspace) => match ui.state {
State::SelectService => (), State::SelectService => (),
State::EditRepo => { State::EditRepo => {
ui.info.set_info("Editing Repository"); ui.info.set_text("Editing Repository");
ui.repo.handle_input(Key::Backspace); ui.repo.handle_input(Key::Backspace);
} }
State::SelectTag => (), State::SelectTag => (),
@ -156,7 +169,7 @@ impl Ui {
match ui.services.extract_repo() { match ui.services.extract_repo() {
Err(e) => ui.info.set_info(&format!("{}", e)), Err(e) => ui.info.set_info(&format!("{}", e)),
Ok(s) => { Ok(s) => {
let repo = match crate::tags::Tags::check_repo(&s) { let repo = match repository::check_repo(&s) {
Err(e) => { Err(e) => {
ui.info.set_info(&format!("{}", e)); ui.info.set_info(&format!("{}", e));
continue; continue;
@ -170,14 +183,17 @@ impl Ui {
} }
State::SelectService => (), State::SelectService => (),
State::EditRepo => (), State::EditRepo => (),
State::SelectTag => ui.tags.handle_input(Key::Up), State::SelectTag => {
ui.tags.handle_input(Key::Up);
ui.details = ui.tags.create_detail_widget();
}
}, },
Ok(Key::Down) => match ui.state { Ok(Key::Down) => match ui.state {
State::SelectService if ui.services.find_next_match() => { State::SelectService if ui.services.find_next_match() => {
match ui.services.extract_repo() { match ui.services.extract_repo() {
Err(e) => ui.info.set_info(&format!("{}", e)), Err(e) => ui.info.set_info(&format!("{}", e)),
Ok(s) => { Ok(s) => {
let repo = match crate::tags::Tags::check_repo(&s) { let repo = match repository::check_repo(&s) {
Err(e) => { Err(e) => {
ui.info.set_info(&format!("{}", e)); ui.info.set_info(&format!("{}", e));
continue; continue;
@ -191,7 +207,10 @@ impl Ui {
} }
State::SelectService => (), State::SelectService => (),
State::EditRepo => (), State::EditRepo => (),
State::SelectTag => ui.tags.handle_input(Key::Down), State::SelectTag => {
ui.tags.handle_input(Key::Down);
ui.details = ui.tags.create_detail_widget();
}
}, },
_ => (), _ => (),
} }

View File

@ -6,6 +6,7 @@ use tui::backend::TermionBackend;
use tui::layout::{Constraint, Direction, Layout}; use tui::layout::{Constraint, Direction, Layout};
use tui::Terminal; use tui::Terminal;
use crate::widget::details;
use crate::widget::info; use crate::widget::info;
use crate::widget::repo_entry; use crate::widget::repo_entry;
use crate::widget::tag_list; use crate::widget::tag_list;
@ -17,6 +18,15 @@ pub enum State {
SelectTag, 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 { impl std::iter::Iterator for State {
type Item = Self; type Item = Self;
@ -33,30 +43,24 @@ pub struct NoYaml {
state: State, state: State,
repo: repo_entry::RepoEntry, repo: repo_entry::RepoEntry,
tags: tag_list::TagList, tags: tag_list::TagList,
details: details::Details,
info: info::Info, info: info::Info,
} }
impl NoYaml { impl NoYaml {
pub fn run(opt: &Opt) { pub fn run(opt: &Opt) {
let (repo, load_repo) = match &opt.repo { let repo_id = opt.repo.as_deref();
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 { let mut ui = NoYaml {
state: State::EditRepo, state: State::EditRepo,
repo, repo: repo_entry::RepoEntry::new(repo_id),
tags: tag_list::TagList::with_status("Tags are empty"), tags: tag_list::TagList::with_status("Tags are empty"),
details: details::Details::new(),
info: info::Info::new("could not find a docker-compose file"), info: info::Info::new("could not find a docker-compose file"),
}; };
// load tags if a repository was given thorugh paramter // load tags if a repository was given thorugh paramter
if load_repo { if opt.repo.is_none() {
ui.tags = tag_list::TagList::with_repo_name(ui.repo.get()); ui.tags = tag_list::TagList::with_repo_name(ui.repo.get());
} }
@ -87,7 +91,12 @@ impl NoYaml {
rect.render_widget(ui.repo.render(ui.state == State::EditRepo), chunks[0]); rect.render_widget(ui.repo.render(ui.state == State::EditRepo), chunks[0]);
let (list, state) = ui.tags.render(ui.state == State::SelectTag); let (list, state) = ui.tags.render(ui.state == State::SelectTag);
rect.render_stateful_widget(list, chunks[1], state); 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_widget(ui.info.render(), chunks[2]); rect.render_widget(ui.info.render(), chunks[2]);
}) })
.unwrap(); .unwrap();
@ -97,6 +106,7 @@ impl NoYaml {
Ok(Key::Ctrl('q')) => break 'core, Ok(Key::Ctrl('q')) => break 'core,
Ok(Key::Char('\t')) => { Ok(Key::Char('\t')) => {
ui.state.next(); ui.state.next();
ui.info.set_info(&ui.state);
} }
Ok(Key::Ctrl('r')) => { Ok(Key::Ctrl('r')) => {
ui.repo.confirm(); ui.repo.confirm();
@ -111,7 +121,7 @@ impl NoYaml {
}, },
Ok(Key::Char(key)) => match ui.state { Ok(Key::Char(key)) => match ui.state {
State::EditRepo => { State::EditRepo => {
ui.info.set_info("Editing Repository"); ui.info.set_text("Editing Repository");
ui.repo.handle_input(Key::Char(key)); ui.repo.handle_input(Key::Char(key));
} }
State::SelectTag => { State::SelectTag => {
@ -120,18 +130,24 @@ impl NoYaml {
}, },
Ok(Key::Backspace) => match ui.state { Ok(Key::Backspace) => match ui.state {
State::EditRepo => { State::EditRepo => {
ui.info.set_info("Editing Repository"); ui.info.set_text("Editing Repository");
ui.repo.handle_input(Key::Backspace); ui.repo.handle_input(Key::Backspace);
} }
State::SelectTag => (), State::SelectTag => (),
}, },
Ok(Key::Up) => match ui.state { Ok(Key::Up) => match ui.state {
State::EditRepo => (), State::EditRepo => (),
State::SelectTag => ui.tags.handle_input(Key::Up), State::SelectTag => {
ui.tags.handle_input(Key::Up);
ui.details = ui.tags.create_detail_widget();
}
}, },
Ok(Key::Down) => match ui.state { Ok(Key::Down) => match ui.state {
State::EditRepo => (), State::EditRepo => (),
State::SelectTag => ui.tags.handle_input(Key::Down), State::SelectTag => {
ui.tags.handle_input(Key::Down);
ui.details = ui.tags.create_detail_widget();
}
}, },
_ => (), _ => (),
} }

61
src/widget/details.rs Normal file
View File

@ -0,0 +1,61 @@
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,7 +27,13 @@ impl Info {
.highlight_style(Style::default().bg(Color::Black)) .highlight_style(Style::default().bg(Color::Black))
} }
pub fn set_info(&mut self, info: &str) { /// set a text to display
pub fn set_text(&mut self, info: &str) {
self.info = String::from(info); 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,3 +1,4 @@
pub mod details;
pub mod info; pub mod info;
pub mod repo_entry; pub mod repo_entry;
pub mod service_switcher; pub mod service_switcher;

View File

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

View File

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

View File

@ -4,7 +4,7 @@ use termion::event::Key;
use tui::style::{Color, Style}; use tui::style::{Color, Style};
use tui::widgets::{Block, Borders, List, ListState}; use tui::widgets::{Block, Borders, List, ListState};
use crate::tags; use crate::repository;
pub enum Error { pub enum Error {
NoneSelected, NoneSelected,
@ -24,7 +24,7 @@ impl fmt::Display for Error {
enum Line { enum Line {
Status(String), Status(String),
Image(tags::Images), Image(repository::Tag),
NextPage(String), NextPage(String),
} }
@ -32,7 +32,7 @@ impl fmt::Display for Line {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
Line::Status(s) => write!(f, "{}", s), Line::Status(s) => write!(f, "{}", s),
Line::Image(i) => write!(f, "{}", i), Line::Image(i) => write!(f, "{}", i.get_name_with_details()),
Line::NextPage(s) => write!(f, "{}", s), Line::NextPage(s) => write!(f, "{}", s),
} }
} }
@ -41,10 +41,11 @@ impl fmt::Display for Line {
pub struct TagList { pub struct TagList {
lines: Vec<Line>, lines: Vec<Line>,
state: ListState, state: ListState,
tags: Option<tags::Tags>, tags: Option<repository::Repo>,
} }
impl TagList { impl TagList {
/// shows a text in the list and no tags
pub fn with_status(status: &str) -> Self { pub fn with_status(status: &str) -> Self {
Self { Self {
lines: vec![Line::Status(String::from(status))], lines: vec![Line::Status(String::from(status))],
@ -53,16 +54,18 @@ impl TagList {
} }
} }
/// list the tags of the repository if the input is valid
pub fn with_repo_name(repo: String) -> Self { pub fn with_repo_name(repo: String) -> Self {
match tags::Tags::new(repo) { match repository::Repo::new(&repo) {
Ok(tags) => Self::with_tags(tags), Ok(tags) => Self::with_tags(tags),
Err(_) => Self::with_status("input repo was not found"), Err(_) => Self::with_status("input repo was not found"),
} }
} }
pub fn with_tags(mut tags: tags::Tags) -> Self { /// list the tags of the input
fn with_tags(mut tags: repository::Repo) -> Self {
let mut lines: Vec<Line> = tags let mut lines: Vec<Line> = tags
.results .get_tags()
.iter() .iter()
.map(|r| Line::Image(r.clone())) .map(|r| Line::Image(r.clone()))
.collect(); .collect();
@ -113,6 +116,18 @@ impl TagList {
(items, &mut self.state) (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) { pub fn handle_input(&mut self, key: termion::event::Key) {
match key { match key {
Key::Down => self.next(), Key::Down => self.next(),
@ -136,7 +151,7 @@ impl TagList {
None => Err(Error::NoneSelected), None => Err(Error::NoneSelected),
Some(i) => match &self.lines[i] { Some(i) => match &self.lines[i] {
Line::Status(_) => Err(Error::SelectedStatus), Line::Status(_) => Err(Error::SelectedStatus),
Line::Image(i) => Ok(i.tag_name.clone()), Line::Image(i) => Ok(i.get_name().to_string()),
Line::NextPage(_) => { Line::NextPage(_) => {
self.load_next_page(); self.load_next_page();
Err(Error::NextPageSelected) Err(Error::NextPageSelected)
@ -158,12 +173,17 @@ impl TagList {
let next_page = self.lines.pop(); let next_page = self.lines.pop();
//add tags //add tags
for image in &self.tags.as_ref().unwrap().results { match &self.tags {
None => (),
Some(tags) => {
for image in tags.get_tags().iter() {
self.lines.push(Line::Image(image.clone())); self.lines.push(Line::Image(image.clone()));
} }
}
}
//readd next page //readd next page
match self.tags.as_ref().unwrap().next_page { match self.tags.as_ref().unwrap().next_page() {
None => (), None => (),
Some(_) => self.lines.push(next_page.unwrap()), Some(_) => self.lines.push(next_page.unwrap()),
} }