Skip to content

Commit

Permalink
convert pkl to json in compilation time
Browse files Browse the repository at this point in the history
  • Loading branch information
tamada committed Jun 28, 2024
1 parent 78cbb7b commit be15479
Show file tree
Hide file tree
Showing 8 changed files with 104 additions and 14 deletions.
23 changes: 22 additions & 1 deletion build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ fn parse_cargo_toml() -> toml::Value {
file.parse().unwrap()
}

fn main() {
fn generate_completions() {
let table = parse_cargo_toml();
let appname = table["package"]["name"].as_str().unwrap();

Expand All @@ -38,3 +38,24 @@ fn main() {
generate(Shell::PowerShell, &mut app, appname, &outdir, format!("powershell/{}", appname));
generate(Shell::Zsh, &mut app, appname, &outdir, format!("zsh/_{}", appname));
}

fn convert_pkl_to_json() {
let output = std::process::Command::new("pkl")
.args(["eval", "-o", "testdata/config.json", "-f", "json", "testdata/config.pkl"])
.output();
match output {
Ok(o) => {
if !o.status.success() {
panic!("Failed to convert pkl to json: {:?}", o);
} else {
println!("Converted pkl to json");
}
}
Err(e) => panic!("{}", e),
}
}

fn main() {
generate_completions();
convert_pkl_to_json();
}
3 changes: 3 additions & 0 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -637,6 +637,9 @@ pub(crate) struct RecentOpts {
value_name = "NUMBER"
)]
pub(crate) number: Option<usize>,

#[clap(flatten)]
pub(crate) p_opts: RepositoryPrintingOpts,
}

#[derive(Parser, Debug)]
Expand Down
2 changes: 1 addition & 1 deletion src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ pub fn perform_repository(context: &mut Context, c: RepositoryOpts) -> Result<bo
}

pub fn perform_recent(context: &Context, c: RecentOpts) -> Result<bool> {
todo!();
list::perform_recent(context, c)
}

pub fn perform_rename(context: &mut Context, c: RenameOpts) -> Result<bool> {
Expand Down
36 changes: 30 additions & 6 deletions src/commands/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,30 @@ use crate::entities::{Repository, RepositoryWithGroups};
use crate::terminal::to_string_in_columns;
use crate::utils::format_humanize;

use super::RecentOpts;

pub(crate) fn perform_recent(context: &Context, mut c: RecentOpts) -> Result<bool> {
let result = context.db.repositories().unwrap().iter()
.sorted_by(|&a, &b| a.last_access.cmp(&b.last_access))
.take(c.number.unwrap_or(5))
.map(|r| build_repo_with_group(r, context))
.collect::<Vec<_>>();
let p_opts = &mut c.p_opts;
p_opts.update_entries();
p_opts.update_format(context.config.get_env("print_list_style"));
print_table_repo_group(result, &p_opts, &context.config)
}

fn build_repo_with_group(r: &Repository, context: &Context) -> RepositoryWithGroups {
let groups = context.db.find_relation_with_repository(&r.id).iter()
.map(|r| context.db.find_group(&r.group).unwrap())
.collect::<Vec<_>>();
RepositoryWithGroups {
repo: r.clone(),
groups,
}
}

pub(crate) fn perform_list(context: &Context, mut c: RepositoryListOpts) -> Result<bool> {
let mut errs = Vec::<RrhError>::new();
let mut result = HashMap::<String, Vec<Repository>>::new();
Expand All @@ -34,7 +58,7 @@ pub(crate) fn perform_list(context: &Context, mut c: RepositoryListOpts) -> Resu
let p_opts = &mut c.p_opts;
p_opts.update_entries();
p_opts.update_format(context.config.get_env("print_list_style"));
print_result(result, context, p_opts)
print_result(result, p_opts, context)
}

pub(crate) fn print_list(repos: Vec<RepositoryWithGroups>, config: &mut Config, p_opts: &mut RepositoryPrintingOpts) -> Result<bool> {
Expand All @@ -44,8 +68,8 @@ pub(crate) fn print_list(repos: Vec<RepositoryWithGroups>, config: &mut Config,

fn print_result(
result: HashMap<String, Vec<Repository>>,
context: &config::Context,
opts: &RepositoryPrintingOpts,
context: &config::Context,
) -> Result<bool> {
if opts.entries.len() == 1 && result.len() == 1 {
print_items_in_columns(
Expand All @@ -60,9 +84,9 @@ fn print_result(
None => break,
};
if group.is_abbrev() && result.len() > 1 {
print_abbrev(opts, repos, group_name, &context.config)
print_abbrev(repos, opts, group_name, &context.config)
} else {
print_table(opts, repos, group_name, &context.config)
print_table(repos, opts, group_name, &context.config)
}
}
Ok(true)
Expand Down Expand Up @@ -107,7 +131,7 @@ pub(crate) fn print_table_repo_group(repos: Vec<RepositoryWithGroups>, opts: &Re
Ok(false)
}

fn print_abbrev(opts: &RepositoryPrintingOpts, result: &Vec<Repository>, group_name: &str, _config: &config::Config) {
fn print_abbrev(result: &Vec<Repository>, opts: &RepositoryPrintingOpts, group_name: &str, _config: &config::Config) {
let mut builder = Builder::new();
let record = vec![String::from("Group"), group_name.to_string(), format!("{}", format_humanize(result.len(), "repository", "repositories"))];
builder.push_record(record);
Expand All @@ -116,8 +140,8 @@ fn print_abbrev(opts: &RepositoryPrintingOpts, result: &Vec<Repository>, group_n
}

fn print_table(
opts: &RepositoryPrintingOpts,
result: &Vec<Repository>,
opts: &RepositoryPrintingOpts,
g: &str,
config: &config::Config
) {
Expand Down
4 changes: 2 additions & 2 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,8 +251,8 @@ mod tests {
Ok(c) => {
assert_eq!(c.database_path, PathBuf::from("testdata/database.json"));
assert_eq!(c.from, Some(PathBuf::from("testdata/config.json")));
assert_eq!(c.envs.len(), 6);
assert_eq!(c.aliases.len(), 3);
assert_eq!(c.envs.len(), 8);
assert_eq!(c.aliases.len(), 2);
}
Err(e) => panic!("Error: {:?}", e),
}
Expand Down
21 changes: 19 additions & 2 deletions src/db/jsondb.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::collections::HashMap;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::time::SystemTime;

use itertools::Itertools;
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -27,7 +28,10 @@ impl JsonDB {

fn from_str(data: &str) -> Result<Self> {
match serde_json::from_str(data) {
Ok(db) => Ok(db),
Ok(mut db) => {
update_recent(&mut db);
Ok(db)
}
Err(e) => Err(RrhError::Json(e)),
}
}
Expand Down Expand Up @@ -312,6 +316,19 @@ fn relation_indexes<F>(db: &JsonDB, f: F) -> Vec<usize>
.collect::<Vec<usize>>()
}

fn update_recent(db: &mut JsonDB) {
db.repositories.iter_mut()
.for_each(|r| r.last_access = find_last_access(&r.path));
}

fn find_last_access(p: &PathBuf) -> Option<SystemTime> {
if let Ok(m) = p.metadata() {
m.accessed().ok()
} else {
None
}
}

pub(crate) fn find_orphan_repositories(db: &JsonDB) -> Vec<Repository> {
let result = db.relations.iter()
.map(|r| r.id.clone())
Expand Down
2 changes: 1 addition & 1 deletion src/terminal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ pub fn to_string_in_column_with(values: Vec<String>, cols: usize, spacer: usize)
let padding_values = padding(values, max);
let mut lines = Vec::new();
let mut line = Vec::<u8>::new();
let space = (0..spacer).into_iter().map(|i| " ").collect::<String>();
let space = (0..spacer).into_iter().map(|_| " ").collect::<String>();
for (i, item) in padding_values.iter().enumerate() {
line.extend(item.as_bytes());
if i % column_count == (column_count - 1) || i == padding_values.len() - 1 {
Expand Down
27 changes: 26 additions & 1 deletion testdata/config.json
Original file line number Diff line number Diff line change
@@ -1 +1,26 @@
{"home":"/Users/tamada/.config/rrh2","config_path":"testdata/config.json","database_path":"testdata/database.json","envs":{"auto_delete_group":true,"clone_directory":".","default_group":"no-group","print_list_style":"blank","time_format":"relative","auto_create_group":true,"last_access_reload_duration_secs":86400,"sort_on_update":true},"aliases":{"grlist":["group","list"],"hello":["exec","echo","Hello, world!"]}}
{
"database_path": "testdata/database.json",
"user_home": "/Users/tamada",
"home": "/Users/tamada/.config/rrh2",
"envs": {
"auto_create_group": true,
"auto_delete_group": true,
"last_access_reload_duration_secs": 86400,
"clone_directory": ".",
"default_group": "no-group",
"sort_on_update": true,
"print_list_style": "blank",
"last_access_format": "humanize"
},
"aliases": {
"hello": [
"exec",
"echo",
"Hello, world!"
],
"grlist": [
"group",
"list"
]
}
}

0 comments on commit be15479

Please sign in to comment.