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
5 changes: 1 addition & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ aws-sdk-s3 = { version = "1.161.0", default-features = false, features = [
] }
aws-smithy-http-client = { version = "1.5.3", default-features = false, features = ["rustls-aws-lc"] }
chardetng = "1.0.0"
chrono = "0.4.45"
clap = { version = "4.6.10", features = ["derive"] }
console = "0.16.6"
crossterm = { version = "0.29.0", features = ["event-stream"] }
Expand Down Expand Up @@ -59,6 +58,7 @@ image = { version = "0.25.10", default-features = false, features = [
indexmap = { version = "2.14.2", features = ["serde"] }
infer = { version = "0.22.0", default-features = false }
itsuki = "0.2.1"
jiff = "1.0.3"
laurier = "0.4.0"
once_cell = "1.21.4"
open = "5.4.5"
Expand Down Expand Up @@ -91,7 +91,6 @@ toml = { version = "1.2.2", default-features = false, features = [
tracing = "0.1.44"
tracing-subscriber = { version = "0.3.23", default-features = false, features = [
"fmt",
"chrono",
"tracing-log",
] }
tui-input = { version = "0.15.5", default-features = false, features = [
Expand Down
4 changes: 2 additions & 2 deletions docs/src/configurations/config-file-format.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ The default sort order of the bucket list.
### `ui.object_list.date_format`

The date format of a last modified in the object list.
The format must be specified in [strftime format](https://docs.rs/chrono/latest/chrono/format/strftime/index.html).
The format must be specified using [Jiff's strftime format specifiers](https://docs.rs/jiff/latest/jiff/fmt/strtime/index.html).

- type: `string`
- default: `%Y-%m-%d %H:%M:%S`
Expand Down Expand Up @@ -138,7 +138,7 @@ The default sort order of the object list.
### `ui.object_detail.date_format`

The date format of a last modified in the object detail.
The format must be specified in [strftime format](https://docs.rs/chrono/latest/chrono/format/strftime/index.html).
The format must be specified using [Jiff's strftime format specifiers](https://docs.rs/jiff/latest/jiff/fmt/strtime/index.html).

- type: `string`
- default: `%Y-%m-%d %H:%M:%S`
Expand Down
9 changes: 1 addition & 8 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1077,14 +1077,14 @@ impl App {
mod tests {
use std::rc::Rc;

use chrono::{DateTime, Local, NaiveDateTime};
use ratatui::{
backend::TestBackend,
crossterm::event::{KeyCode, KeyEvent},
Terminal,
};

use super::*;
use crate::test_support::parse_datetime;
use crate::{
client::AddressingStyle,
event::{
Expand Down Expand Up @@ -1558,13 +1558,6 @@ mod tests {
}
}

fn parse_datetime(s: &str) -> DateTime<Local> {
NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S")
.unwrap()
.and_local_timezone(Local)
.unwrap()
}

fn object_file_item(name: &str) -> ObjectItem {
ObjectItem::File {
name: name.to_string(),
Expand Down
97 changes: 57 additions & 40 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use aws_smithy_http_client::{
tls::{self, rustls_provider::CryptoMode},
ConnectorBuilder,
};
use chrono::TimeZone;
use jiff::{tz::TimeZone, Timestamp, ZonedDateTime};

use crate::{
ca_bundle,
Expand Down Expand Up @@ -192,7 +192,7 @@ impl Client {
let dirs = objects_output_to_dirs(&self.region, bucket, &output);
dirs_vec.push(dirs);

let files = objects_output_to_files(&self.region, bucket, &output);
let files = objects_output_to_files(&self.region, bucket, &output)?;
files_vec.push(files);

token = output.next_continuation_token().map(String::from);
Expand Down Expand Up @@ -223,7 +223,7 @@ impl Client {

let name = name.to_owned();
let size_byte = output.content_length().unwrap() as usize;
let last_modified = convert_datetime(output.last_modified().unwrap());
let last_modified = convert_datetime(output.last_modified().unwrap())?;
let e_tag = output.e_tag().unwrap().trim_matches('"').to_string();
let http_headers = object_http_headers(&output);
let user_metadata = output
Expand Down Expand Up @@ -265,26 +265,25 @@ impl Client {
.await;
let output = result.map_err(|e| AppError::new("Failed to load object versions", e))?;

let versions = output
output
.versions()
.iter()
.filter(|v| v.key() == Some(key))
.map(|v| {
let version_id = v.version_id().map(String::from);
let size_byte = v.size().unwrap() as usize;
let last_modified = convert_datetime(v.last_modified().unwrap());
let last_modified = convert_datetime(v.last_modified().unwrap())?;
let e_tag = v.e_tag().unwrap().trim_matches('"').to_string();
let is_latest = v.is_latest().unwrap();
FileVersion {
Ok(FileVersion {
version_id,
size_byte,
last_modified,
e_tag,
is_latest,
}
})
})
.collect();
Ok(versions)
.collect()
}

pub async fn download_object<W: std::io::Write + Send, F: Fn(usize) + Send>(
Expand Down Expand Up @@ -437,36 +436,36 @@ fn objects_output_to_files(
region: &str,
bucket: &str,
output: &ListObjectsV2Output,
) -> Vec<ObjectItem> {
let objects = output.contents();
objects
.iter()
.map(|file| {
let path = file.key().unwrap();
let paths = parse_path(path, false);
let name = paths.last().unwrap().to_owned();
let size_byte = file.size().unwrap() as usize;
let last_modified = convert_datetime(file.last_modified().unwrap());
) -> Result<Vec<ObjectItem>> {
let mut files = Vec::new();
for file in output.contents() {
let path = file.key().unwrap();
let paths = parse_path(path, false);
let name = paths.last().unwrap().to_owned();
if name.is_empty() {
continue; // skip dummy empty object
}
let size_byte = file.size().unwrap() as usize;
let last_modified = convert_datetime(file.last_modified().unwrap())?;

let key = file.key().unwrap().to_owned();
let s3_uri = build_object_s3_uri(bucket, &key);
let arn = build_object_arn(bucket, &key);
let object_url = build_object_url(region, bucket, &key);
let e_tag = file.e_tag().unwrap().trim_matches('"').to_string();
let key = file.key().unwrap().to_owned();
let s3_uri = build_object_s3_uri(bucket, &key);
let arn = build_object_arn(bucket, &key);
let object_url = build_object_url(region, bucket, &key);
let e_tag = file.e_tag().unwrap().trim_matches('"').to_string();

ObjectItem::File {
name,
size_byte,
last_modified,
key,
s3_uri,
arn,
object_url,
e_tag,
}
})
.filter(|f| !f.name().is_empty()) // skip dummy empty object
.collect()
files.push(ObjectItem::File {
name,
size_byte,
last_modified,
key,
s3_uri,
arn,
object_url,
e_tag,
});
}
Ok(files)
}

fn parse_path(path: &str, dir: bool) -> Vec<String> {
Expand All @@ -479,9 +478,10 @@ fn parse_path(path: &str, dir: bool) -> Vec<String> {
}
}

fn convert_datetime(dt: &aws_sdk_s3::primitives::DateTime) -> chrono::DateTime<chrono::Local> {
let nanos = dt.as_nanos();
chrono::Local.timestamp_nanos(nanos as i64)
fn convert_datetime(dt: &aws_sdk_s3::primitives::DateTime) -> Result<ZonedDateTime> {
let timestamp = Timestamp::from_nanosecond(dt.as_nanos())
.map_err(|e| AppError::new("Failed to convert object timestamp", e))?;
Ok(timestamp.to_zoned_datetime(TimeZone::system()))
}

fn build_bucket_s3_uri(bucket: &str) -> String {
Expand Down Expand Up @@ -510,8 +510,25 @@ fn build_object_url(region: &str, bucket: &str, key: &str) -> String {

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

use super::*;

#[rstest]
#[case(0, 0, "1970-01-01T00:00:00Z")]
#[case(-1, 999_999_999, "1969-12-31T23:59:59.999999999Z")]
#[case(9_500_000_000, 123_456_789, "2271-01-16T16:53:20.123456789Z")]
fn converts_object_timestamp(
#[case] seconds: i64,
#[case] nanoseconds: u32,
#[case] expected: &str,
) {
let dt = aws_sdk_s3::primitives::DateTime::from_secs_and_nanos(seconds, nanoseconds);
let actual = convert_datetime(&dt).unwrap();

assert_eq!(actual.timestamp().to_string(), expected);
}

#[test]
fn object_headers_preserve_values_in_display_order() {
let output = HeadObjectOutput::builder()
Expand Down
62 changes: 59 additions & 3 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::{
};

use anyhow::Context;
use jiff::{fmt::strtime, ZonedDateTime};
use serde::Deserialize;
use smart_default::SmartDefault;
use umbra::optional;
Expand Down Expand Up @@ -148,16 +149,35 @@ impl Config {
std::fs::create_dir_all(&dir)?;
}
let path = dir.join(CONFIG_FILE_NAME);
if path.exists() {
let config = if path.exists() {
let content = std::fs::read_to_string(path)?;
let mut config: OptionalConfig = toml::from_str(&content)?;
if let Some(ref mut download_dir) = config.download_dir {
*download_dir = Self::expand_env_vars(download_dir)?;
}
Ok(config.into())
config.into()
} else {
Ok(Config::default())
Config::default()
};
config.validate()?;
Ok(config)
}

fn validate(&self) -> anyhow::Result<()> {
for (key, format) in [
(
"ui.object_list.date_format",
&self.ui.object_list.date_format,
),
(
"ui.object_detail.date_format",
&self.ui.object_detail.date_format,
),
] {
strtime::format(format, &ZonedDateTime::UNIX_EPOCH)
.with_context(|| format!("Invalid date format for {key}"))?;
}
Ok(())
}

fn expand_env_vars(path: &str) -> anyhow::Result<String> {
Expand Down Expand Up @@ -225,6 +245,7 @@ impl Config {
#[cfg(test)]
mod tests {
use ratatui::style::Color;
use rstest::rstest;

use super::*;

Expand All @@ -233,6 +254,41 @@ mod tests {
config.into()
}

#[test]
fn default_config_is_valid() {
Config::default().validate().unwrap();
}

#[rstest]
#[case("%Y-%m-%d %H:%M:%S %:z")]
#[case("%Q")]
#[case("date %%")]
fn accepts_date_formats(#[case] format: &str) {
let mut config = Config::default();
config.ui.object_list.date_format = format.into();
config.ui.object_detail.date_format = format.into();

config.validate().unwrap();
}

#[rstest]
#[case("object_list", "%J")]
#[case("object_detail", "%")]
fn invalid_date_format_reports_the_config_key(#[case] section: &str, #[case] format: &str) {
let config = parse_config(&format!(
r#"
[ui.{section}]
date_format = "{format}"
"#
));

let error = config.validate().unwrap_err();
assert_eq!(
error.to_string(),
format!("Invalid date format for ui.{section}.date_format")
);
}

#[test]
fn theme_defaults_when_omitted() {
let config = parse_config("");
Expand Down
9 changes: 5 additions & 4 deletions src/file.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use arboard::Clipboard;
use chrono::Local;
use jiff::ZonedDateTime;
use std::{
fs::{File, OpenOptions},
io::{BufWriter, Write},
Expand All @@ -20,14 +20,15 @@ pub fn save_error_log<P: AsRef<Path>>(path: P, e: &AppError) -> Result<()> {
let mut f =
open_or_create_append_file(path).map_err(|e| AppError::new("Failed to open file", e))?;

let now = Local::now();
let now = ZonedDateTime::now();
let timestamp = now.strftime("%Y-%m-%d %H:%M:%S%.f %:z");

match &e.cause {
Some(cause) => {
writeln!(f, "{} {}: {:?}", now, e.msg, cause)
writeln!(f, "{} {}: {:?}", timestamp, e.msg, cause)
}
None => {
writeln!(f, "{} {}", now, e.msg)
writeln!(f, "{} {}", timestamp, e.msg)
}
}
.map_err(|e| AppError::new("Failed to write file", e))
Expand Down
Loading
Loading