skim icon indicating copy to clipboard operation
skim copied to clipboard

Question: how to display file content as options

Open JiangWeixian opened this issue 3 years ago • 0 comments

Hey, thanks for your awesome work.

I want to use this lib to display package.json name as options instead of filepath. But, I can't found out how to convert default options into PkgItem options.

extern crate skim;
use skim::prelude::*;
use std::error::Error;
use serde::{Deserialize};
use serde_json;
use std::fs::File;
use std::io::BufReader;
use std::path::Path;

#[derive(Deserialize, Debug)]
struct Pkg {
    name: String
}

fn read_pkg_from_file<P: AsRef<Path>>(path: P) -> Result<Cow<'static, str>, Box<dyn Error>> {
    let file = File::open(path)?;
    let reader = BufReader::new(file);

    let u: Pkg = serde_json::from_reader(reader)?;

    Ok(Cow::Owned(u.name))
}

struct PkgItem {
    text: String,
}

impl SkimItem for PkgItem {
    fn text(&self) -> Cow<str> {
        let name = read_pkg_from_file(&self.text).unwrap();
        name
    }

    fn output(&self) -> Cow<str> {
        Cow::Borrowed(&self.text)
    }
    
}

pub fn main() {
    let options = SkimOptionsBuilder::default()
        .query(Some("package.json"))
        .build()
        .unwrap();

    let (tx, _): (SkimItemSender, SkimItemReceiver) = unbounded();

    tx.send(Arc::new(PkgItem { text: "a".to_string() })).unwrap();

    let selected_items = Skim::run_with(&options, None)
        .map(|out| out.selected_items)
        .unwrap_or_else(|| Vec::new());

    for item in selected_items.iter() {
        print!("{}{}", item.output(), "\n");
    }
}

JiangWeixian avatar Dec 23 '21 13:12 JiangWeixian