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

Feat/completion #202

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ clap_complete = "3.1.4"
env_logger = "0.10.0"
console = "0.15.0"
indicatif = "0.17.0"
dialoguer = "0.10.0"
dialoguer = { version = "0.10", features = ["completion"] }
color-eyre = "0.6.0"
number_prefix = "0.4.0"
ctrlc = "3.2.1"
Expand Down
121 changes: 106 additions & 15 deletions cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,14 @@ use clap::{Args, CommandFactory, Parser, Subcommand};
use cli_clipboard::{ClipboardContext, ClipboardProvider};
use color_eyre::{eyre, eyre::Context};
use console::{style, Term};
use dialoguer::Input;
use futures::{future::Either, Future, FutureExt};
use indicatif::{MultiProgress, ProgressBar};
use std::{io::Write, path::PathBuf};
use magic_wormhole::PgpWordList;
use std::{
io::Write,
path::{Path, PathBuf},
};

use magic_wormhole::{
dilated_transfer, forwarding, transfer, transit, MailboxConnection, Wormhole,
Expand Down Expand Up @@ -570,7 +575,7 @@ async fn main() -> eyre::Result<()> {
out,
);

std::io::stdout().write_all(&out.as_bytes())?;
std::io::stdout().write_all(out.as_bytes())?;
},
shell => {
let mut out = std::io::stdout();
Expand Down Expand Up @@ -761,12 +766,14 @@ fn create_progress_handler(pb: ProgressBar) -> impl FnMut(u64, u64) {
}

fn enter_code() -> eyre::Result<String> {
use dialoguer::Input;

Input::new()
let completion = WordList::default();
let input = Input::new()
.with_prompt("Enter code")
.completion_with(&completion)
.interact_text()
.map_err(From::from)
.map_err(From::from);

input
}

fn print_welcome(term: &mut Term, welcome: &Option<String>) -> eyre::Result<()> {
Expand Down Expand Up @@ -1059,15 +1066,14 @@ async fn receive_inner_v1(
.truncate(true)
.open(&file_path)
.await?;
Ok(req
.accept(
&transit::log_transit_connection,
&mut file,
create_progress_handler(pb),
ctrl_c(),
)
.await
.context("Receive process failed")?)
req.accept(
&transit::log_transit_connection,
&mut file,
create_progress_handler(pb),
ctrl_c(),
)
.await
.context("Receive process failed")
}

async fn receive_inner_v2(
Expand Down Expand Up @@ -1172,6 +1178,74 @@ async fn receive_inner_v2(
Ok(())
}

use dialoguer::Completion;
use magic_wormhole::core::wordlist;
use std::{collections::HashMap, fs};

struct WordList(PgpWordList);

impl Default for WordList {
fn default() -> Self {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks like a re-implementation of load_pgpwords. Why not make use of that?

let json = fs::read_to_string("./src/core/pgpwords.json").unwrap();
let word_map: HashMap<String, Vec<String>> = serde_json::from_str(&json).unwrap();
let mut even_words: Vec<String> = vec![];
let mut odd_words: Vec<String> = vec![];
for (_idx, words) in word_map {
even_words.push(words[0].to_lowercase());
odd_words.push(words[1].to_lowercase());
}
let words = vec![even_words, odd_words];

WordList {
0: PgpWordList {
words: words.clone(),
num_words: words.len(),
},
}
}
}

impl Completion for WordList {
fn get(&self, input: &str) -> Option<String> {
let count_dashes = input.matches('-').count();
let mut completions = Vec::new();
let words = &self.0.words[count_dashes % self.0.words.len()];

let last_partial_word = input.split('-').last();
let lp = if let Some(w) = last_partial_word {
w.len()
} else {
0
};

for word in words {
let mut suffix: String = input.to_owned();
if word.starts_with(last_partial_word.unwrap()) {
if lp == 0 {
suffix.push_str(word);
} else {
let p = input.len() - lp;
suffix.truncate(p);
suffix.push_str(word);
}

if count_dashes + 1 < self.0.num_words {
suffix.push('-');
}

completions.push(suffix);
}
}
if completions.len() == 1 {
Some(completions.first().unwrap().clone())
} else {
// TODO: show vector of suggestions somehow
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd consider that out of scope for now.

// println!("Suggestions: {:#?}", &completions);
None
}
}
}

#[cfg(test)]
mod test {
use super::*;
Expand All @@ -1189,4 +1263,21 @@ mod test {
String::from_utf8(out).unwrap();
}
}

#[test]
fn test_passphrase_completion() {
let words: Vec<Vec<String>> = vec![
wordlist::vecstrings("purple green yellow"),
wordlist::vecstrings("sausages seltzer snobol"),
];

let w = WordList(PgpWordList {
words,
num_words: 2,
});
assert_eq!(w.get(""), None);
assert_eq!(w.get("pur").unwrap(), "purple-");
assert_eq!(w.get("blu"), None);
assert_eq!(w.get("purple-sa").unwrap(), "purple-sausages");
}
}
2 changes: 1 addition & 1 deletion cli/src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub async fn ask_user(message: impl std::fmt::Display, default_answer: bool) ->
let mut answer = String::new();
stdin.read_line(&mut answer).await.unwrap();

match &*answer.to_lowercase().trim() {
match answer.to_lowercase().trim() {
"y" | "yes" => break true,
"n" | "no" => break false,
"" => break default_answer,
Expand Down
10 changes: 5 additions & 5 deletions src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pub mod rendezvous;
mod server_messages;
#[cfg(test)]
pub(crate) mod test;
mod wordlist;
pub mod wordlist;

#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
Expand Down Expand Up @@ -694,9 +694,9 @@ impl Nameplate {
}
}

impl Into<String> for Nameplate {
fn into(self) -> String {
self.0
impl From<Nameplate> for String {
fn from(val: Nameplate) -> Self {
val.0
}
}

Expand All @@ -723,7 +723,7 @@ impl Code {
}

pub fn nameplate(&self) -> Nameplate {
Nameplate::new(self.0.splitn(2, '-').next().unwrap())
Nameplate::new(self.0.split('-').next().unwrap())
}
}

Expand Down
6 changes: 3 additions & 3 deletions src/core/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
*/
#[cfg(feature = "transit")]
pub fn derive_transit_key(&self, appid: &AppID) -> Key<crate::transit::TransitKey> {
let transit_purpose = format!("{}/transit-key", &*appid);
let transit_purpose = format!("{}/transit-key", appid);

let derived_key = self.derive_subkey_from_purpose(&transit_purpose);
trace!(
Expand All @@ -68,15 +68,15 @@
}

pub fn to_hex(&self) -> String {
hex::encode(&**self)
hex::encode(**self)
}

/**
* Derive a new sub-key from this one
*/
pub fn derive_subkey_from_purpose<NewP: KeyPurpose>(&self, purpose: &str) -> Key<NewP> {
Key(
Box::new(derive_key(&*self, purpose.as_bytes())),
Box::new(derive_key(self, purpose.as_bytes())),
std::marker::PhantomData,
)
}
Expand Down Expand Up @@ -135,7 +135,7 @@
self.app_versions = versions;
}

pub fn enable_dilation(&mut self) {

Check warning on line 138 in src/core/key.rs

View workflow job for this annotation

GitHub Actions / test (ubuntu-latest, 1.66.0)

associated function `enable_dilation` is never used

Check warning on line 138 in src/core/key.rs

View workflow job for this annotation

GitHub Actions / test (ubuntu-latest, 1.66.0)

associated function `enable_dilation` is never used

Check warning on line 138 in src/core/key.rs

View workflow job for this annotation

GitHub Actions / test (ubuntu-latest, 1.66.0)

associated function `enable_dilation` is never used

Check warning on line 138 in src/core/key.rs

View workflow job for this annotation

GitHub Actions / test (ubuntu-latest, 1.66.0)

associated function `enable_dilation` is never used

Check warning on line 138 in src/core/key.rs

View workflow job for this annotation

GitHub Actions / test (ubuntu-latest, stable)

method `enable_dilation` is never used

Check warning on line 138 in src/core/key.rs

View workflow job for this annotation

GitHub Actions / test (ubuntu-latest, stable)

method `enable_dilation` is never used

Check warning on line 138 in src/core/key.rs

View workflow job for this annotation

GitHub Actions / test (ubuntu-latest, stable)

method `enable_dilation` is never used

Check warning on line 138 in src/core/key.rs

View workflow job for this annotation

GitHub Actions / test (ubuntu-latest, nightly)

method `enable_dilation` is never used

Check warning on line 138 in src/core/key.rs

View workflow job for this annotation

GitHub Actions / test (ubuntu-latest, nightly)

method `enable_dilation` is never used

Check warning on line 138 in src/core/key.rs

View workflow job for this annotation

GitHub Actions / test (ubuntu-latest, nightly)

method `enable_dilation` is never used

Check warning on line 138 in src/core/key.rs

View workflow job for this annotation

GitHub Actions / test (windows-latest, 1.66.0)

associated function `enable_dilation` is never used

Check warning on line 138 in src/core/key.rs

View workflow job for this annotation

GitHub Actions / test (windows-latest, stable)

method `enable_dilation` is never used

Check warning on line 138 in src/core/key.rs

View workflow job for this annotation

GitHub Actions / test (windows-latest, stable)

method `enable_dilation` is never used

Check warning on line 138 in src/core/key.rs

View workflow job for this annotation

GitHub Actions / test (windows-latest, stable)

method `enable_dilation` is never used

Check warning on line 138 in src/core/key.rs

View workflow job for this annotation

GitHub Actions / test (windows-latest, stable)

method `enable_dilation` is never used

Check warning on line 138 in src/core/key.rs

View workflow job for this annotation

GitHub Actions / test (windows-latest, stable)

method `enable_dilation` is never used

Check warning on line 138 in src/core/key.rs

View workflow job for this annotation

GitHub Actions / test (windows-latest, nightly)

method `enable_dilation` is never used

Check warning on line 138 in src/core/key.rs

View workflow job for this annotation

GitHub Actions / test (windows-latest, nightly)

method `enable_dilation` is never used

Check warning on line 138 in src/core/key.rs

View workflow job for this annotation

GitHub Actions / test (windows-latest, nightly)

method `enable_dilation` is never used
self.can_dilate = Some([std::borrow::Cow::Borrowed("1")])
}

Expand Down
15 changes: 9 additions & 6 deletions src/core/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,8 +228,9 @@ pub async fn test_file_rust2rust_deprecated() -> eyre::Result<()> {
futures::future::pending(),
)
.await?
.unwrap()
else {panic!("v2 should be disabled for now")};
.unwrap() else {
panic!("v2 should be disabled for now")
};
req.accept(
&transit::log_transit_connection,
&mut answer,
Expand Down Expand Up @@ -302,8 +303,9 @@ pub async fn test_file_rust2rust() -> eyre::Result<()> {
futures::future::pending(),
)
.await?
.unwrap()
else {panic!("v2 should be disabled for now")};
.unwrap() else {
panic!("v2 should be disabled for now")
};
req.accept(
&transit::log_transit_connection,
&mut answer,
Expand Down Expand Up @@ -413,8 +415,9 @@ pub async fn test_send_many() -> eyre::Result<()> {
futures::future::pending(),
)
.await?
.unwrap()
else {panic!("v2 should be disabled for now")};
.unwrap() else {
panic!("v2 should be disabled for now")
};

// Hacky v1-compat conversion for now
let mut answer = (gen_accept()
Expand Down
Loading
Loading