From 10817bfb5a99c3a926e6ece8e81aa30a6e272bb3 Mon Sep 17 00:00:00 2001 From: fcd Date: Mon, 6 Apr 2020 00:08:03 +0100 Subject: [PATCH] keep the order of the links --- Cargo.toml | 2 +- src/main.rs | 25 ++++++++++++++++++------- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 5495903..f934536 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "leth" -version = "0.1.6" +version = "0.2.0" authors = ["fcd "] edition = "2018" diff --git a/src/main.rs b/src/main.rs index a434f1a..77edc16 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,7 +1,7 @@ extern crate regex; extern crate skim; -use std::collections::HashSet; +use std::collections::HashMap; use std::io::Cursor; use std::io::{self, Read}; use std::process::Command; @@ -9,7 +9,7 @@ use std::process::Command; use regex::Regex; use skim::{Skim, SkimOptionsBuilder}; -const URL_REGEX: &str = r"(http(s)?://[a-zA-Z0-9_/?+&.=@%#;-]+)"; +const URL_REGEX: &str = r"(http(s)?://[a-zA-Z0-9_/?+&.=@%#;~-]+)"; pub fn main() { let options = SkimOptionsBuilder::default() @@ -23,18 +23,29 @@ pub fn main() { io::stdin().read_to_string(&mut buffer).unwrap(); let lines = buffer.split("\n"); - let mut matches: HashSet<&str> = HashSet::new(); + let mut matches: HashMap<&str, u8> = HashMap::new(); + let mut match_index = 1; for line in lines { for capture in re.captures_iter(line) { let url_match = capture.get(1).unwrap().as_str(); - matches.insert(url_match); + if matches.contains_key(url_match) { + continue; + } + matches.insert(url_match, match_index); + match_index += 1; } } - let unique_items: Vec<&str> = matches.into_iter().collect(); - let items = unique_items.join("\n"); - // `run_with` would read and show items from the stream + let mut ordered_items: Vec<_> = matches.into_iter() + .collect(); + ordered_items.sort_by(|a, b| a.1.cmp(&b.1)); + + let item_list: Vec<_> = ordered_items.iter() + .map(|item|item.0) + .collect(); + let items = item_list.join("\n"); + let selected_items = Skim::run_with(&options, Some(Box::new(Cursor::new(items)))) .map(|out| out.selected_items) .unwrap_or_else(|| Vec::new());