Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix timestamp formatting to match documentation #331

Merged
merged 5 commits into from
Jan 10, 2023
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
14 changes: 5 additions & 9 deletions .github/workflows/ci-on-push.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,13 @@ jobs:
uses: actions-rs/install@v0.1
with:
crate: wasm-pack

- name: Run cargo-tarpaulin
uses: actions-rs/tarpaulin@v0.1
- name: Set up just
uses: actions-rs/install@v0.1
with:
version: '0.15.0'
args: '-- --test-threads 1'
crate: just

- run: |
curl -Os https://uploader.codecov.io/latest/linux/codecov
chmod +x codecov
./codecov -t ${CODECOV_TOKEN}
- run: just _rust-test

js_tests:
name: "Run JS Tests"
Expand Down
2 changes: 1 addition & 1 deletion stork-cli/src/clap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ mod tests {
for input in valid_inputs {
app()
.get_matches_from_safe(input.split(' '))
.unwrap_or_else(|e| panic!("Error with input {:?}: {}", &input, e));
.unwrap_or_else(|e| panic!("Error with input {:?}: {e}", &input));
}
}
#[test]
Expand Down
4 changes: 2 additions & 2 deletions stork-cli/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ pub fn read_bytes_from_path(path: &str) -> Result<Bytes, StorkCommandLineError>

// TODO: Handle path == "" case
let pathbuf = std::path::PathBuf::from(path);
std::fs::read(&pathbuf)
std::fs::read(pathbuf)
.map(Bytes::from)
.map_err(|e| StorkCommandLineError::FileReadError(path.to_string(), e))
}
Expand All @@ -46,7 +46,7 @@ pub fn read_from_path(path: &str) -> Result<String, StorkCommandLineError> {
// handle ("", Some) or ("", None), perhaps
_ => {
let pathbuf = std::path::PathBuf::from(path);
std::fs::read_to_string(&pathbuf)
std::fs::read_to_string(pathbuf)
.map_err(|e| StorkCommandLineError::FileReadError(path.to_string(), e))
}
}
Expand Down
6 changes: 3 additions & 3 deletions stork-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ fn main() {
// Delete when releasing 2.0.0
(_, _) => {
fn print_nudging_string(errant_command: &str) {
eprintln!("{} The command line interface has been updated: please use `stork {}` instead of `stork --{}`. See `stork --help` for more.", "Warning:".yellow(), errant_command, errant_command);
eprintln!("{} The command line interface has been updated: please use `stork {errant_command}` instead of `stork --{errant_command}`. See `stork --help` for more.", "Warning:".yellow());
}

if let Some(config_path) = app_matches.value_of("build") {
Expand Down Expand Up @@ -90,7 +90,7 @@ fn main() {
};

if let Err(error) = result {
eprintln!("{} {}", "Error:".red(), error);
eprintln!("{} {error}", "Error:".red());
exit(EXIT_FAILURE);
}
}
Expand Down Expand Up @@ -149,7 +149,7 @@ fn search_handler(submatches: &ArgMatches) -> CmdResult {
match submatches.value_of("format") {
Some("json") => {
match serde_json::to_string_pretty(&results).map_err(StorkCommandLineError::from) {
Ok(json) => println!("{}", json),
Ok(json) => println!("{json}"),
Err(error) => {
return Err(error);
}
Expand Down
4 changes: 2 additions & 2 deletions stork-cli/src/pretty_print_search_results.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ fn highlight_string(string: &str, ranges: &Vec<HighlightRange>) -> String {
let mut last_end = 0;
for range in ranges {
highlighted.push_str(&string[last_end..range.beginning]);
highlighted.push_str(&string[range.beginning..range.end].yellow().to_string());
highlighted.push_str(&string[range.beginning..range.end].yellow());
last_end = range.end;
}
highlighted.push_str(&string[last_end..]);
Expand Down Expand Up @@ -86,7 +86,7 @@ mod tests {
}],
}],
total_hit_count: 21,
url_prefix: "".to_string(),
url_prefix: String::new(),
};

assert_eq!(
Expand Down
4 changes: 2 additions & 2 deletions stork-cli/src/test_server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,10 @@ pub fn serve(index: &Bytes, port: u16) -> Result<(), Box<dyn std::error::Error>>
let server = Server::bind(&addr).serve(make_svc);
let graceful = server.with_graceful_shutdown(shutdown_signal());

println!("Open <http://{}> in your web browser to visit the test page.\nPress ctrl-C to stop the server.", addr);
println!("Open <http://{addr}> in your web browser to visit the test page.\nPress ctrl-C to stop the server.");

if let Err(e) = graceful.await {
eprintln!("server error: {}", e);
eprintln!("server error: {e}");
}
Ok(())
})
Expand Down
2 changes: 1 addition & 1 deletion stork-lib/src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ mod tests {
input: InputConfig {
UNUSED_surrounding_word_count: None,
base_directory: "test/federalist".into(),
url_prefix: "".into(),
url_prefix: String::new(),
title_boost: TitleBoost::Moderate,
stemming: StemmingConfig::Language(
rust_stemmers::Algorithm::English,
Expand Down
1 change: 1 addition & 0 deletions stork-lib/src/config/srt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,5 @@ pub struct SRTConfig {
pub enum SRTTimestampFormat {
#[default]
NumberOfSeconds,
MinutesAndSeconds,
}
4 changes: 2 additions & 2 deletions stork-lib/src/config/stemming.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ impl TryFrom<&String> for StemmingConfig {
return Ok(StemmingConfig::None);
}

toml::from_str(format!("lang = \"{}\"", value).as_str())
toml::from_str(format!("lang = \"{value}\"").as_str())
.map(|t: TempAlgStructure| StemmingConfig::Language(t.lang))
}
}
Expand Down Expand Up @@ -58,7 +58,7 @@ impl From<StemmingConfig> for String {
fn from(stemming_config: StemmingConfig) -> Self {
let mut output = String::new();
let _result = match stemming_config {
StemmingConfig::Language(l) => write!(&mut output, "{:?}", l),
StemmingConfig::Language(l) => write!(&mut output, "{l:?}"),
StemmingConfig::None => write!(&mut output, "none"),
};
output
Expand Down
2 changes: 1 addition & 1 deletion stork-lib/src/index_v2/search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,6 @@ mod tests {
// IndexVersion::from(ParsedIndex::try_from(index_bytes.as_slice()).unwrap()),
// IndexVersion::V2
// );
assert_eq!(generated, expected, "{:?}", generated);
assert_eq!(generated, expected, "{generated:?}");
}
}
2 changes: 1 addition & 1 deletion stork-lib/src/index_v3/build/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ pub enum WordListGenerationError {
}

fn pluralize_with_count(count: usize, singular: &str, plural: &str) -> String {
format!("{} {}", count, if count == 1 { singular } else { plural })
format!("{count} {}", if count == 1 { singular } else { plural })
}

#[derive(Debug, Error)]
Expand Down
4 changes: 2 additions & 2 deletions stork-lib/src/index_v3/build/fill_containers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ fn fill_other_containers_alias_maps_with_reverse_stems(
.or_insert_with(Container::new)
.aliases
.entry(normalized_word.to_string())
.or_insert(STEM_SCORE as u8);
.or_insert(STEM_SCORE);
}
}
}
Expand Down Expand Up @@ -209,7 +209,7 @@ mod tests {
let intermediate_entry = NormalizedEntry {
annotated_word_list: AnnotatedWordList { word_list: vec![] },
title: "10 - Polymorphism".to_string(),
url: "".to_string(),
url: String::new(),
fields: HashMap::default(),
stem_algorithm: None,
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub(crate) fn read(
config: &ReaderConfig,
) -> Result<ReadResult, WordListGenerationError> {
let base_directory_path = Path::new(&config.global.base_directory);
let full_pathname = base_directory_path.join(&path);
let full_pathname = base_directory_path.join(path);

let file = File::open(&full_pathname)
.map_err(|_| WordListGenerationError::FileNotFound(full_pathname.clone()))?;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub fn parse_frontmatter(handling: &FrontmatterConfig, buffer: &str) -> (Fields,
.into_iter()
.map(|(k, v)| {
(
k.into_string().unwrap_or_else(|| "".to_string()),
k.into_string().unwrap_or_default(),
v.clone().into_string().unwrap_or_else(|| {
v.into_i64().map_or("error".to_string(), |i| i.to_string())
}),
Expand Down
8 changes: 4 additions & 4 deletions stork-lib/src/index_v3/build/fill_intermediate_entries/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ fn truncate_with_ellipsis_to_length(
ellipsis
};

format!("{}{}", short_message, ellipsis)
format!("{short_message}{ellipsis}")
};

truncated
Expand All @@ -217,7 +217,7 @@ mod tests {
#[test]
fn break_on_file_error_breaks() {
let invalid_file = File {
explicit_source: Some(DataSource::Contents("".to_string())), // Empty word list error,
explicit_source: Some(DataSource::Contents(String::new())), // Empty word list error,
..File::default()
};

Expand All @@ -243,14 +243,14 @@ mod tests {
&WordListGenerationError::EmptyWordList
);
} else {
panic!("Result is {:?}", r);
panic!("Result is {r:?}");
}
}

#[test]
fn false_break_on_file_error_does_not_break() {
let invalid_file = File {
explicit_source: Some(DataSource::Contents("".to_string())), // Empty word list error
explicit_source: Some(DataSource::Contents(String::new())), // Empty word list error
..File::default()
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ pub fn generate(
for elem in as_node.traverse_inclusive() {
if let kuchiki::iter::NodeEdge::Start(node_ref) = elem {
let contents: String = (|| {
let mut output = "".to_string();
let mut output = String::new();
if let Some(element_data) = node_ref.as_element() {
if config.output.save_nearest_html_id {
if let Some(id) = element_data.attributes.borrow().get("id") {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,83 @@ fn build_srt_url_time_suffix(time: &srtparse::Time, srt_config: &SRTConfig) -> S
SRTTimestampFormat::NumberOfSeconds => {
((time.hours) * 3600 + (time.minutes) * 60 + (time.seconds)).to_string()
}
SRTTimestampFormat::MinutesAndSeconds => {
if time.minutes > 0 {
format!("{}m{}s", time.hours * 60 + time.minutes, time.seconds)
} else {
format!("{}s", time.seconds)
}
}
};

srt_config
.timestamp_template_string
.replace("{ts}", &time_string)
.replace("{}", &time_string)
}

#[cfg(test)]
mod tests {
use pretty_assertions::assert_eq;

use crate::{
config::SRTConfig,
index_v3::build::fill_intermediate_entries::word_list_generators::srt_word_list_generator::build_srt_url_time_suffix,
};

#[test]
fn it_formats_time_suffix_correctly() {
let time = srtparse::Time {
hours: 0,
minutes: 16,
seconds: 12,
milliseconds: 0,
};
let config = SRTConfig {
timestamp_linking: true,
timestamp_template_string: "{}".to_string(),
timestamp_format: crate::config::SRTTimestampFormat::NumberOfSeconds,
};

let computed = build_srt_url_time_suffix(&time, &config);
let expected = "972";
assert_eq!(computed, expected);
}

#[test]
fn it_formats_time_suffix_correctly_minutes_and_seconds() {
let time = srtparse::Time {
hours: 0,
minutes: 16,
seconds: 12,
milliseconds: 0,
};
let config = SRTConfig {
timestamp_linking: true,
timestamp_template_string: "{}".to_string(),
timestamp_format: crate::config::SRTTimestampFormat::MinutesAndSeconds,
};

let computed = build_srt_url_time_suffix(&time, &config);
let expected = "16m12s";
assert_eq!(computed, expected);
}

#[test]
fn it_formats_time_suffix_correctly_minutes_and_seconds_for_time_over_one_hour() {
let time = srtparse::Time {
hours: 1,
minutes: 16,
seconds: 12,
milliseconds: 0,
};
let config = SRTConfig {
timestamp_linking: true,
timestamp_template_string: "{}".to_string(),
timestamp_format: crate::config::SRTTimestampFormat::MinutesAndSeconds,
};

let computed = build_srt_url_time_suffix(&time, &config);
let expected = "76m12s";
assert_eq!(computed, expected);
}
}
2 changes: 1 addition & 1 deletion stork-lib/src/index_v3/build/intermediate_entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ mod tests {
fields.insert("k2".to_string(), "v2".to_string());

let intended = Entry {
contents: "".to_string(),
contents: String::new(),
title: "My Title".to_string(),
url: "https://example.com".to_string(),
fields: fields.clone(),
Expand Down
6 changes: 3 additions & 3 deletions stork-lib/src/index_v3/build/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ pub fn build(config: &Config) -> Result<BuildResult, IndexGenerationError> {
.map(Entry::from)
.map(|mut entry| {
if config.output.excerpts_per_result == 0 {
entry.contents = "".to_string();
entry.contents = String::new();
}

entry
Expand Down Expand Up @@ -108,7 +108,7 @@ mod tests {

fn generate_invalid_file_missing_selector() -> File {
File {
explicit_source: Some(DataSource::Contents("".to_string())),
explicit_source: Some(DataSource::Contents(String::new())),
title: "Missing Selector".to_string(),
filetype: Some(Filetype::HTML),
html_selector_override: Some(".article".to_string()),
Expand All @@ -118,7 +118,7 @@ mod tests {

fn generate_invalid_file_empty_contents() -> File {
File {
explicit_source: Some(DataSource::Contents("".to_string())),
explicit_source: Some(DataSource::Contents(String::new())),
title: "Empty Contents".to_string(),
filetype: Some(Filetype::PlainText),
..File::default()
Expand Down
Loading