Skip to content

Commit

Permalink
Merge pull request #93 from lotabout/ticket-90
Browse files Browse the repository at this point in the history
Ticket 90
  • Loading branch information
lotabout authored Oct 1, 2018
2 parents 64f6958 + c82c795 commit 929482e
Show file tree
Hide file tree
Showing 6 changed files with 57 additions and 15 deletions.
6 changes: 3 additions & 3 deletions ci/script.sh
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
set -ex

main() {
cross build --target $TARGET --release

if [ ! -z $DISABLE_TESTS ]; then
return
fi

cargo test --verbose
cross build --release --target $TARGET
mkdir -p target/release
cp target/$TARGET/release/sk target/release

case $TARGET in
x86_64-unknown-linux-gnu|i686-unknown-linux-gnu)
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ mod query;
mod reader;
mod score;
mod sender;
mod util;

use curses::Curses;
use event::Event::*;
Expand Down
23 changes: 17 additions & 6 deletions src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,16 @@ use std::sync::mpsc::Sender;
use std::sync::Arc;
use std::time::{Duration, Instant};
use unicode_width::UnicodeWidthChar;
use std::env;
use util::escape_single_quote;

pub type ClosureType = Box<Fn(&mut Window) + Send>;

const SPINNER_DURATION: u32 = 200;
const SPINNERS: [char; 8] = ['-', '\\', '|', '/', '-', '\\', '|', '/'];

lazy_static! {
static ref RE_FILEDS: Regex = Regex::new(r"(\{-?[0-9.,q]*?})").unwrap();
static ref RE_FILEDS: Regex = Regex::new(r"\\?(\{-?[0-9.,q]*?})").unwrap();
static ref REFRESH_DURATION: Duration = Duration::from_millis(200);
}

Expand Down Expand Up @@ -642,13 +644,21 @@ impl Model {
.expect("model:inject_preview_command: invalid preview command");
debug!("replace: {:?}, text: {:?}", cmd, text);
RE_FILEDS.replace_all(cmd, |caps: &Captures| {
// \{...
if &caps[0][0..1] == "\\" {
return caps[0].to_string();
}

// {1..} and other variant
assert!(caps[1].len() >= 2);
let range = &caps[1][1..caps[1].len() - 1];
if range == "" {
format!("'{}'", text)
let replacement = if range == "" {
text
} else {
format!("'{}'", get_string_by_range(&self.delimiter, text, range).unwrap_or(""))
}
get_string_by_range(&self.delimiter, text, range).unwrap_or("")
};

format!("'{}'", escape_single_quote(replacement))
})
}

Expand Down Expand Up @@ -777,7 +787,8 @@ impl Model {
}

fn get_command_output(cmd: &str, lines: u16, cols: u16) -> Result<String, Box<Error>> {
let output = Command::new("sh")
let shell = env::var("SHELL").unwrap_or("sh".to_string());
let output = Command::new(shell)
.env("LINES", lines.to_string())
.env("COLUMNS", cols.to_string())
.arg("-c")
Expand Down
4 changes: 3 additions & 1 deletion src/reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use field::FieldRange;
use options::SkimOptions;
use regex::Regex;
use sender::CachedSender;
use std::env;

struct ReaderOption {
pub use_ansi_color: bool,
Expand Down Expand Up @@ -180,7 +181,8 @@ impl Reader {
}

fn get_command_output(cmd: &str) -> Result<(Option<Child>, Box<BufRead + Send>), Box<Error>> {
let mut command = Command::new("sh")
let shell = env::var("SHELL").unwrap_or("sh".to_string());
let mut command = Command::new(shell)
.arg("-c")
.arg(cmd)
.stdout(Stdio::piped())
Expand Down
3 changes: 3 additions & 0 deletions src/util.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pub fn escape_single_quote(text: &str) -> String {
text.replace("'", "'\\''")
}
35 changes: 30 additions & 5 deletions test/test_skim.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,25 +10,28 @@
import time
import re
import inspect
import sys

INPUT_RECORD_SEPARATOR = '\n'
DEFAULT_TIMEOUT = 2000

SCRIPT_PATH = os.path.realpath(__file__)
BASE = os.path.expanduser(os.path.join(os.path.dirname(SCRIPT_PATH), '../'))
BASE = os.path.expanduser(os.path.join(os.path.dirname(SCRIPT_PATH), '..'))
os.chdir(BASE)
SK = f"SKIM_DEFAULT_OPTIONS= SKIM_DEFAULT_COMMAND= {BASE}/target/release/sk"

def now_mills():
return int(round(time.time() * 1000))

def wait(func):
def wait(func, timeout_handler=None):
since = now_mills()
while now_mills() - since < DEFAULT_TIMEOUT:
time.sleep(0.01)
time.sleep(0.02)
ret = func()
if ret is not None and ret:
return
if timeout_handler is not None:
timeout_handler()
raise BaseException('Timeout on wait')

class Shell(object):
Expand Down Expand Up @@ -94,7 +97,9 @@ def select_count(self):
return self.counts()[2]

def any_include(self, val):
if isinstance(val, re._pattern_type):
if hasattr(re, '_pattern_type') and isinstance(val, re._pattern_type):
method = lambda l: val.match(l)
if hasattr(re, 'Pattern') and isinstance(val, re.Pattern):
method = lambda l: val.match(l)
else:
method = lambda l: l.find(val) >= 0
Expand Down Expand Up @@ -175,7 +180,10 @@ def wait_callback():
if pred:
self.send_keys(Ctrl('l') if refresh else None)
return pred
wait(wait_callback)
def timeout_handler():
lines = self.capture()
print(lines)
wait(wait_callback, timeout_handler)

def prepare(self):
try:
Expand Down Expand Up @@ -353,6 +361,7 @@ def test_key_bindings(self):

def test_read0(self):
self.tmux.send_keys(f"find . | wc -l", Key('Enter'))
self.tmux.until(lambda lines: re.search('\d', lines[-1]) is not None)
lines = self.tmux.capture()
num_of_files = int(lines[-1])

Expand Down Expand Up @@ -750,5 +759,21 @@ def test_multiple_option_values_should_be_accepted(self):
self.tmux.until(lambda lines: lines[-1].startswith('>'))
self.tmux.send_keys(Key('Enter'))

def test_single_quote_of_preview_command(self):
# echo "'\"ABC\"'" | sk --preview="echo X{}X" => X'"ABC"'X
echo_command = '''echo "'\\"ABC\\"'" | '''
sk_command = self.sk('--preview=\"echo X{}X\"')
command = echo_command + sk_command
self.tmux.send_keys(command, Key('Enter'))
self.tmux.until(lambda lines: lines.any_include('''X'"ABC"'X'''))

# echo "'\"ABC\"'" | sk --preview="echo X\{}X" => X{}X
echo_command = '''echo "'\\"ABC\\"'" | '''
sk_command = self.sk('--preview=\"echo X\\{}X\"')
command = echo_command + sk_command
self.tmux.send_keys(command, Key('Enter'))
self.tmux.until(lambda lines: lines.any_include('''X{}X'''))


if __name__ == '__main__':
unittest.main()

0 comments on commit 929482e

Please sign in to comment.