Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/codecov.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ coverage:
# Avoid false negatives
threshold: 1%

# Test files aren't important for coverage
ignore:
- "tests"
- "tests" # test fixtures
- "src/formats/json_lines.rs" # deprecated, migration only

# Make comments less noisy
comment:
Expand Down
78 changes: 77 additions & 1 deletion src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,11 @@ impl From<JsonLineEvent> for Event {
/// and this is only used to convert old history files to the binary format.
fn from(event: JsonLineEvent) -> Self {
let timestamp = event.timestamp.timestamp_millis();
let endtime = timestamp + (event.duration * 1000.) as i64;
Self {
timestamp_millis: timestamp,
command: event.command,
endtime: (timestamp + (event.duration as i64)),
endtime,
exit_code: event.exit_code,
folder: event.folder,
machine: event.machine,
Expand Down Expand Up @@ -78,3 +79,78 @@ impl Event {
writer.write(self)
}
}

#[cfg(test)]
mod tests {
use std::cmp::Ordering;

use super::*;

fn event_with_endtime(endtime: i64) -> Event {
Event {
timestamp_millis: 0,
command: String::new(),
endtime,
exit_code: 0,
folder: String::new(),
machine: String::new(),
session: String::new(),
}
}

#[test]
fn cmp_orders_by_endtime() {
let earlier = event_with_endtime(100);
let later = event_with_endtime(200);
assert_eq!(earlier.cmp(&later), Ordering::Less);
assert_eq!(later.cmp(&earlier), Ordering::Greater);
assert_eq!(earlier.cmp(&earlier), Ordering::Equal);
}

#[test]
fn partial_cmp_always_some() {
let a = event_with_endtime(100);
let b = event_with_endtime(200);
assert_eq!(a.partial_cmp(&b), Some(Ordering::Less));
assert_eq!(b.partial_cmp(&a), Some(Ordering::Greater));
assert_eq!(a.partial_cmp(&a), Some(Ordering::Equal));
}

#[allow(deprecated)]
#[test]
fn from_json_line_event() {
let timestamp = chrono::DateTime::from_timestamp_millis(1_000_000_000_000).unwrap();
let timestamp = timestamp.with_timezone(&chrono::Local);
let json_event = crate::formats::json_lines::JsonLineEvent {
timestamp,
command: "sleep 5".to_string(),
duration: 5.0,
exit_code: 0,
folder: "/".to_string(),
machine: "m".to_string(),
session: "s".to_string(),
};
let event = Event::from(json_event);
assert_eq!(event.timestamp_millis, 1_000_000_000_000);
assert_eq!(event.endtime, 1_000_000_000_000_i64 + 5 * 1000);
assert_eq!(event.command, "sleep 5");
assert_eq!(event.exit_code, 0);
assert_eq!(event.folder, "/");
assert_eq!(event.machine, "m");
assert_eq!(event.session, "s");
}

#[test]
fn sort_by_endtime() {
let mut events = vec![
event_with_endtime(300),
event_with_endtime(100),
event_with_endtime(200),
];
events.sort();
assert_eq!(
events.iter().map(|e| e.endtime).collect::<Vec<_>>(),
vec![100, 200, 300]
);
}
}
79 changes: 68 additions & 11 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
use std::{collections::HashSet, fs::File, os::fd::AsRawFd, path::PathBuf};
use std::{
collections::HashSet,
fs::File,
os::fd::AsRawFd,
path::{Path, PathBuf},
};

use anyhow::anyhow;
use glob::glob;
Expand Down Expand Up @@ -42,26 +47,30 @@ pub fn mmap(file: &File) -> &'_ [u8] {
}
}

/// discover all parsable osh files under `~/.osh` for a specific format
pub fn osh_files(kind: formats::Kind) -> anyhow::Result<HashSet<PathBuf>> {
// TODO when can this really fail?
let home_dir = home::home_dir().ok_or(anyhow!("no home directory"))?;
let home = home_dir
.to_str()
.ok_or(anyhow!("home directory contains invalid chars"))?;
let pattern = format!("{home}/.osh/**/*.{}", kind.extension());

/// discover all osh files of `kind` under `root`, recursively.
fn discover_files(root: &Path, kind: &formats::Kind) -> anyhow::Result<HashSet<PathBuf>> {
let pattern = format!(
"{}/**/*.{}",
root.to_str()
.ok_or(anyhow!("root path contains invalid chars"))?,
kind.extension()
);
let files = match glob(&pattern) {
Err(_) => unreachable!("pattern is valid"),
Ok(matches) => matches
.filter_map(Result::ok)
.filter_map(|path| path.canonicalize().ok())
.collect(),
};

Ok(files)
}

/// discover all parsable osh files under `~/.osh` for a specific format
pub fn osh_files(kind: formats::Kind) -> anyhow::Result<HashSet<PathBuf>> {
let home_dir = home::home_dir().ok_or(anyhow!("no home directory"))?;
discover_files(&home_dir.join(".osh"), &kind)
}

/// load all binary osh files in `~/.osh` and return a merged and sorted vector of all events
pub fn load_sorted() -> anyhow::Result<Vec<Event>> {
let oshs = osh_files(Kind::Rmp)?;
Expand All @@ -79,3 +88,51 @@ pub fn load_sorted() -> anyhow::Result<Vec<Event>> {
all_items.par_sort_unstable_by(|a, b| b.cmp(a));
Ok(all_items)
}

#[cfg(test)]
mod tests {
use std::io::Write;

use tempfile::TempDir;

use super::*;

#[test]
fn mmap_reads_file_contents() {
let mut file = tempfile::tempfile().unwrap();
let data = b"hello mmap";
file.write_all(data).unwrap();
let mapped = mmap(&file);
assert_eq!(mapped, data);
}

#[test]
fn discover_mixed_extensions() {
let dir = TempDir::new().unwrap();
std::fs::create_dir_all(dir.path().join("machine1")).unwrap();
std::fs::File::create(dir.path().join("machine1/history.bosh")).unwrap();
std::fs::File::create(dir.path().join("machine1/history.osh")).unwrap();

let found = discover_files(dir.path(), &Kind::Rmp).unwrap();
assert_eq!(found.len(), 1);
assert!(found.iter().all(|p| p.extension().unwrap() == "bosh"));
}

#[test]
fn discover_empty_dir() {
let dir = TempDir::new().unwrap();
let found = discover_files(dir.path(), &Kind::Rmp).unwrap();
assert!(found.is_empty());
}

#[test]
fn discover_nested() {
let dir = TempDir::new().unwrap();
std::fs::create_dir_all(dir.path().join("a/b")).unwrap();
std::fs::File::create(dir.path().join("a/one.bosh")).unwrap();
std::fs::File::create(dir.path().join("a/b/two.bosh")).unwrap();

let found = discover_files(dir.path(), &Kind::Rmp).unwrap();
assert_eq!(found.len(), 2);
}
}
73 changes: 72 additions & 1 deletion src/matcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ impl FuzzyIndex {
}
}

/// crates an index from a matcher result
/// crates an index from a sorted matcher result
pub fn new(scored_indices: Vec<(usize, i64)>, highlight_indices: Vec<Vec<usize>>) -> Self {
let (indices, scores) = scored_indices.into_iter().unzip();
Self {
Expand Down Expand Up @@ -374,6 +374,77 @@ impl FuzzyIndex {
mod tests {
use super::*;

#[test]
fn fuzzy_index_identity_get() {
let index = FuzzyIndex::identity();
assert_eq!(index.get(0), Some(0));
assert_eq!(index.get(42), Some(42));
}

#[test]
fn fuzzy_index_identity_len_and_empty() {
let index = FuzzyIndex::identity();
assert_eq!(index.len(), None);
assert!(index.is_empty());
}

#[test]
fn fuzzy_index_identity_first_n() {
let index = FuzzyIndex::identity();
let result: Vec<usize> = index.first_n(3).collect();
assert_eq!(result, vec![0, 1, 2]);
}

#[test]
fn fuzzy_index_identity_no_highlights_or_scores() {
let index = FuzzyIndex::identity();
assert_eq!(index.highlight_indices(0), None);
assert_eq!(index.matcher_score(0), None);
}

#[test]
fn fuzzy_index_filtered_get() {
let index = FuzzyIndex::new(vec![(5, 100), (2, 50)], vec![vec![0, 1], vec![3]]);
assert_eq!(index.get(0), Some(5));
assert_eq!(index.get(1), Some(2));
assert_eq!(index.get(2), None);
}

#[test]
fn fuzzy_index_filtered_len() {
let index = FuzzyIndex::new(vec![(5, 100), (2, 50)], vec![vec![], vec![]]);
assert_eq!(index.len(), Some(2));
assert!(!index.is_empty());
}

#[test]
fn fuzzy_index_filtered_first_n() {
let index = FuzzyIndex::new(
vec![(5, 100), (2, 50), (8, 10)],
vec![vec![], vec![], vec![]],
);
let result: Vec<usize> = index.first_n(2).collect();
assert_eq!(result, vec![5, 2]);
}

#[test]
fn fuzzy_index_filtered_first_n_clamps_to_available() {
let index = FuzzyIndex::new(vec![(1, 10)], vec![vec![]]);
let result: Vec<usize> = index.first_n(10).collect();
assert_eq!(result, vec![1]);
}

#[test]
fn fuzzy_index_filtered_scores_and_highlights() {
let index = FuzzyIndex::new(vec![(5, 100), (2, 50)], vec![vec![0, 1], vec![3, 4]]);
assert_eq!(index.matcher_score(0), Some(100));
assert_eq!(index.matcher_score(1), Some(50));
assert_eq!(index.matcher_score(2), None);
assert_eq!(index.highlight_indices(0), Some(&vec![0, 1]));
assert_eq!(index.highlight_indices(1), Some(&vec![3, 4]));
assert_eq!(index.highlight_indices(2), None);
}

#[test]
fn single_term_matches() {
let engine = FuzzyEngine::new("git".to_string());
Expand Down
Loading
Loading