summaryrefslogtreecommitdiffstats
path: root/tool
diff options
context:
space:
mode:
authorJustus Winter <justus@sequoia-pgp.org>2019-11-20 19:02:34 +0100
committerJustus Winter <justus@sequoia-pgp.org>2019-11-21 16:25:30 +0100
commitb251f9e8857fba284f515061ac62013519997e30 (patch)
tree8cb3501b8cb32e43496e56dd76446ba7559c7eed /tool
parent13c437470cc7377d7b761b5bb9b8d4efb0ba385e (diff)
openpgp: Replace time crate with std::time.
- In sq and sqv, use chrono to interface with the user. - Fixes #341.
Diffstat (limited to 'tool')
-rw-r--r--tool/Cargo.toml2
-rw-r--r--tool/src/commands/dump.rs41
-rw-r--r--tool/src/commands/inspect.rs14
-rw-r--r--tool/src/commands/key.rs15
-rw-r--r--tool/src/commands/mod.rs18
-rw-r--r--tool/src/commands/sign.rs2
-rw-r--r--tool/src/sq.rs13
7 files changed, 55 insertions, 50 deletions
diff --git a/tool/Cargo.toml b/tool/Cargo.toml
index abc49e74..3e6979b4 100644
--- a/tool/Cargo.toml
+++ b/tool/Cargo.toml
@@ -26,6 +26,7 @@ sequoia-openpgp = { path = "../openpgp", version = "0.11" }
sequoia-core = { path = "../core", version = "0.11" }
sequoia-net = { path = "../net", version = "0.11" }
sequoia-store = { path = "../store", version = "0.11" }
+chrono = "0.4"
clap = "2.32.0"
failure = "0.1.2"
itertools = "0.8"
@@ -33,7 +34,6 @@ prettytable-rs = "0.8.0"
rpassword = "4.0"
tempfile = "3.0.4"
termsize = "0.1"
-time = "0.1.38"
tokio-core = "0.1"
[build-dependencies]
diff --git a/tool/src/commands/dump.rs b/tool/src/commands/dump.rs
index 915217cc..5ce50681 100644
--- a/tool/src/commands/dump.rs
+++ b/tool/src/commands/dump.rs
@@ -1,5 +1,4 @@
use std::io::{self, Read};
-use time;
extern crate sequoia_openpgp as openpgp;
use self::openpgp::constants::SymmetricAlgorithm;
@@ -13,8 +12,6 @@ use self::openpgp::packet::signature::subpacket::{Subpacket, SubpacketValue};
use self::openpgp::crypto::{SessionKey, s2k::S2K};
use self::openpgp::parse::{map::Map, Parse, PacketParserResult};
-use super::TIMEFMT;
-
#[derive(Debug)]
pub enum Kind {
Message {
@@ -25,6 +22,24 @@ pub enum Kind {
Unknown,
}
+/// Converts sequoia_openpgp types for rendering.
+pub trait Convert<T> {
+ /// Performs the conversion.
+ fn convert(self) -> T;
+}
+
+impl Convert<chrono::Duration> for std::time::Duration {
+ fn convert(self) -> chrono::Duration {
+ chrono::Duration::seconds(self.as_secs() as i64)
+ }
+}
+
+impl Convert<chrono::DateTime<chrono::offset::Utc>> for std::time::SystemTime {
+ fn convert(self) -> chrono::DateTime<chrono::offset::Utc> {
+ chrono::DateTime::<chrono::offset::Utc>::from(self)
+ }
+}
+
pub fn dump<W>(input: &mut dyn io::Read, output: &mut dyn io::Write,
mpis: bool, hex: bool, sk: Option<&SessionKey>,
width: W)
@@ -267,7 +282,7 @@ impl PacketDumper {
{
writeln!(output, "{} Version: {}", i, k.version())?;
writeln!(output, "{} Creation time: {}", i,
- time::strftime(TIMEFMT, k.creation_time()).unwrap())?;
+ k.creation_time().convert())?;
writeln!(output, "{} Pk algo: {}", i, k.pk_algo())?;
if let Some(bits) = k.mpis().bits() {
writeln!(output, "{} Pk size: {} bits", i, bits)?;
@@ -534,7 +549,7 @@ impl PacketDumper {
}
if let Some(timestamp) = l.date() {
writeln!(output, "{} Timestamp: {}", i,
- time::strftime(TIMEFMT, timestamp).unwrap())?;
+ timestamp.convert())?;
}
},
@@ -705,15 +720,14 @@ impl PacketDumper {
if s.critical() { " (critical)" } else { "" })?;
hexdump_unknown(output, b)?;
},
- SignatureCreationTime(ref t) =>
+ SignatureCreationTime(t) =>
write!(output, "{} Signature creation time: {}", i,
- time::strftime(TIMEFMT, t).unwrap())?,
- SignatureExpirationTime(ref t) =>
+ (*t).convert())?,
+ SignatureExpirationTime(t) =>
write!(output, "{} Signature expiration time: {} ({})",
- i, t,
+ i, t.convert(),
if let Some(creation) = sig.signature_creation_time() {
- time::strftime(TIMEFMT, &(creation + *t))
- .unwrap()
+ (creation + *t).convert().to_string()
} else {
" (no Signature Creation Time subpacket)".into()
})?,
@@ -727,8 +741,9 @@ impl PacketDumper {
String::from_utf8_lossy(r))?,
Revocable(r) =>
write!(output, "{} Revocable: {}", i, r)?,
- KeyExpirationTime(ref t) =>
- write!(output, "{} Key expiration time: {}", i, t)?,
+ KeyExpirationTime(t) =>
+ write!(output, "{} Key expiration time: {}", i,
+ t.convert())?,
PreferredSymmetricAlgorithms(ref c) =>
write!(output, "{} Symmetric algo preferences: {}", i,
c.iter().map(|c| format!("{:?}", c))
diff --git a/tool/src/commands/inspect.rs b/tool/src/commands/inspect.rs
index 23ebe8a5..3f75daf0 100644
--- a/tool/src/commands/inspect.rs
+++ b/tool/src/commands/inspect.rs
@@ -1,5 +1,4 @@
use std::io::{self, Read};
-use time;
use clap;
@@ -7,7 +6,7 @@ extern crate sequoia_openpgp as openpgp;
use crate::openpgp::{Packet, Result};
use crate::openpgp::parse::{Parse, PacketParserResult};
-use super::TIMEFMT;
+use super::dump::Convert;
pub fn inspect(m: &clap::ArgMatches, output: &mut dyn io::Write)
-> Result<()> {
@@ -151,7 +150,8 @@ fn inspect_tpk(output: &mut dyn io::Write, tpk: &openpgp::TPK,
if let Some(sig) = uidb.binding_signature(None) {
if sig.signature_expired(None) {
writeln!(output, " Expired")?;
- } else if ! sig.signature_alive(None, time::Duration::seconds(0)) {
+ } else if ! sig.signature_alive(None,
+ std::time::Duration::new(0, 0)) {
writeln!(output, " Not yet valid")?;
}
}
@@ -192,14 +192,14 @@ fn inspect_key<P, R>(output: &mut dyn io::Write,
writeln!(output, "{}Public-key size: {} bits", indent, bits)?;
}
writeln!(output, "{} Creation time: {}", indent,
- time::strftime(TIMEFMT, key.creation_time())?)?;
+ key.creation_time().convert())?;
if let Some(sig) = binding_signature {
if let Some(expires) = sig.key_expiration_time() {
- let expiration_time = *key.creation_time() + expires;
+ let expiration_time = key.creation_time() + expires;
writeln!(output, "{}Expiration time: {} (creation time + {})",
indent,
- time::strftime(TIMEFMT, &expiration_time)?,
- expires)?;
+ expiration_time.convert(),
+ expires.convert())?;
}
if let Some(keyflags) = inspect_key_flags(sig.key_flags()) {
diff --git a/tool/src/commands/key.rs b/tool/src/commands/key.rs
index 6b20d60f..f4afe93e 100644
--- a/tool/src/commands/key.rs
+++ b/tool/src/commands/key.rs
@@ -25,10 +25,10 @@ pub fn generate(m: &ArgMatches, force: bool) -> failure::Fallible<()> {
}
// Expiration.
- const SECONDS_IN_DAY : i64 = 24 * 60 * 60;
- const SECONDS_IN_YEAR : i64 =
+ const SECONDS_IN_DAY : u64 = 24 * 60 * 60;
+ const SECONDS_IN_YEAR : u64 =
// Average number of days in a year.
- (365.2422222 * SECONDS_IN_DAY as f64) as i64;
+ (365.2422222 * SECONDS_IN_DAY as f64) as u64;
let even_off = |s| {
if s < 7 * SECONDS_IN_DAY {
@@ -68,11 +68,11 @@ pub fn generate(m: &ArgMatches, force: bool) -> failure::Fallible<()> {
(try: '2y' for 2 years)"));
}
- let count : i64 = match digits.parse::<i32>() {
+ let count = match digits.parse::<i32>() {
Ok(count) if count < 0 =>
return Err(format_err!(
"--expiry: Expiration can't be in the past")),
- Ok(count) => count as i64,
+ Ok(count) => count as u64,
Err(err) =>
return Err(err.context(
"--expiry: count is out of range").into()),
@@ -103,13 +103,14 @@ pub fn generate(m: &ArgMatches, force: bool) -> failure::Fallible<()> {
}
builder = builder.set_expiration(
- Some(time::Duration::seconds(even_off(count * factor))));
+ Some(std::time::Duration::new(even_off(count * factor), 0)));
}
// Not specified. Use the default.
None => {
builder = builder.set_expiration(
- Some(time::Duration::seconds(even_off(3 * SECONDS_IN_YEAR))));
+ Some(std::time::Duration::new(even_off(3 * SECONDS_IN_YEAR), 0))
+ );
}
};
diff --git a/tool/src/commands/mod.rs b/tool/src/commands/mod.rs
index 4450c8d6..af7469ca 100644
--- a/tool/src/commands/mod.rs
+++ b/tool/src/commands/mod.rs
@@ -3,7 +3,6 @@ use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::{self, Write};
-use time;
use rpassword;
extern crate sequoia_openpgp as openpgp;
@@ -36,18 +35,13 @@ mod decrypt;
pub use self::decrypt::decrypt;
mod sign;
pub use self::sign::sign;
-mod dump;
+pub mod dump;
+use dump::Convert;
pub use self::dump::dump;
mod inspect;
pub use self::inspect::inspect;
pub mod key;
-const TIMEFMT: &'static str = "%Y-%m-%dT%H:%M";
-
-fn tm2str(t: &time::Tm) -> String {
- time::strftime(TIMEFMT, t).expect("TIMEFMT is correct")
-}
-
/// Returns suitable signing keys from a given list of TPKs.
fn get_signing_keys(tpks: &[openpgp::TPK])
-> Result<Vec<crypto::KeyPair<
@@ -506,20 +500,20 @@ pub fn mapping_print_stats(mapping: &store::Mapping, label: &str) -> Result<()>
fn print_stamps(st: &store::Stamps) -> Result<()> {
println!("{} messages using this key", st.count);
if let Some(t) = st.first {
- println!(" First: {}", tm2str(&time::at(t)));
+ println!(" First: {}", t.convert());
}
if let Some(t) = st.last {
- println!(" Last: {}", tm2str(&time::at(t)));
+ println!(" Last: {}", t.convert());
}
Ok(())
}
fn print_stats(st: &store::Stats) -> Result<()> {
if let Some(t) = st.created {
- println!(" Created: {}", tm2str(&time::at(t)));
+ println!(" Created: {}", t.convert());
}
if let Some(t) = st.updated {
- println!(" Updated: {}", tm2str(&time::at(t)));
+ println!(" Updated: {}", t.convert());
}
print!(" Encrypted ");
print_stamps(&st.encryption)?;
diff --git a/tool/src/commands/sign.rs b/tool/src/commands/sign.rs
index 59b1a3c1..787a7889 100644
--- a/tool/src/commands/sign.rs
+++ b/tool/src/commands/sign.rs
@@ -243,7 +243,7 @@ fn sign_message(input: &mut dyn io::Read, output_path: Option<&str>,
literal = literal.filename(f)?;
}
if let Some(d) = l.date() {
- literal = literal.date(*d)?;
+ literal = literal.date(d)?;
}
let mut literal = literal.build()
diff --git a/tool/src/sq.rs b/tool/src/sq.rs
index b3f78255..2cc870ba 100644
--- a/tool/src/sq.rs
+++ b/tool/src/sq.rs
@@ -8,7 +8,6 @@ extern crate prettytable;
extern crate rpassword;
extern crate tempfile;
extern crate termsize;
-extern crate time;
extern crate itertools;
extern crate tokio_core;
@@ -36,6 +35,7 @@ use store::{Mapping, LogIter};
mod sq_cli;
mod commands;
+use commands::dump::Convert;
fn open_or_stdin(f: Option<&str>) -> Result<Box<dyn io::Read>, failure::Error> {
match f {
@@ -495,8 +495,8 @@ fn real_main() -> Result<(), failure::Error> {
.context("Failed to get key stats")?;
table.add_row(Row::new(vec![
Cell::new(&fingerprint.to_string()),
- if let Some(ref t) = stats.updated {
- Cell::new(&format_time(t))
+ if let Some(t) = stats.updated {
+ Cell::new(&t.convert().to_string())
} else {
Cell::new("")
},
@@ -605,7 +605,7 @@ fn print_log(iter: LogIter, with_slug: bool) {
table.set_titles(head);
for entry in iter {
- let mut row = row![&format_time(&entry.timestamp),
+ let mut row = row![&entry.timestamp.convert().to_string(),
&entry.short()];
if with_slug {
row.insert_cell(1, Cell::new(&entry.slug));
@@ -616,11 +616,6 @@ fn print_log(iter: LogIter, with_slug: bool) {
table.printstd();
}
-fn format_time(t: &time::Timespec) -> String {
- time::strftime("%F %H:%M", &time::at(*t))
- .unwrap() // Only parse errors can happen.
-}
-
fn main() {
if let Err(e) = real_main() {
let mut cause = e.as_fail();