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: added plugin to launch nix applications without installing them #83

Open
wants to merge 7 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
1,167 changes: 582 additions & 585 deletions Cargo.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,5 @@ members = [
"plugins/stdin",
"plugins/dictionary",
"plugins/websearch",
"plugins/nix-run",
]
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ The flake provides multiple packages:
- symbols - the symbols plugin
- translate - the translate plugin
- websearch - the websearch plugin
- nix-run - the nix-run plugin

#### home-manager module

Expand Down Expand Up @@ -176,6 +177,8 @@ Anyrun requires plugins to function, as they provide the results for input. The
- Look up definitions for words
- [Websearch](plugins/websearch/README.md)
- Search the web with configurable engines: Google, Ecosia, Bing, DuckDuckGo.
- [Nix-Run](plugins/nix-run/README.md)
- Run applications ephemerally from nixpkgs.

## Configuration

Expand Down
12 changes: 6 additions & 6 deletions flake.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,12 @@
inherit inputs lockFile;
name = "websearch";
};

nix-run = pkgs.callPackage ./nix/plugins/default.nix {
inherit inputs lockFile;
name = "nix-run";
};

};
};

Expand Down
18 changes: 18 additions & 0 deletions plugins/nix-run/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
[package]
name = "nix-run"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib"]

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
anyrun-plugin = { path = "../../anyrun-plugin" }
abi_stable = "0.11.1"
sublime_fuzzy = "0.7.0"
fuzzy-matcher = "0.3.7"
regex = "1.9.3"
ron = "0.8.0"
serde = { version = "1.0.159", features = ["derive"] }
18 changes: 18 additions & 0 deletions plugins/nix-run/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Nix-Run

Launch nix applications without installing them.

## Usage

Simply search for the application you wish to launch.

## Configuration

```ron
// <Anyrun config dir>/nix-run.ron
Config(
// The prefix that the search needs to begin with to yield results
prefix: "nixpkgs#"
max_entries: 5,
)
```
182 changes: 182 additions & 0 deletions plugins/nix-run/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
use abi_stable::{rvec, std_types::{ROption, RString, RVec}};
use anyrun_plugin::{anyrun_interface::HandleResult, *};
use fuzzy_matcher::FuzzyMatcher;
use serde::{Serialize, Deserialize};
use regex::{Captures, Regex};
use std::{fs, process::Command};

#[derive(Deserialize)]
pub struct Config {
prefix: String,
max_entries: usize,
}

impl Default for Config {
fn default() -> Self {
Self {
prefix: String::from("nixpkgs#"),
max_entries: 5,
}
}
}

pub struct State {
config: Config,
entries: RVec<NixEntry>,
}

#[derive(Serialize, Deserialize)]
pub struct NixEntry {
name: RString,
desc: RString,
}
impl NixEntry {
fn get_command(&self) -> RString {
let mut cmd = RString::from("nixpkgs#");
cmd.push_str(&self.name);
cmd
}
}

#[handler]
pub fn handler(selection: Match, state: &State) -> HandleResult {
let entry = state
.entries
.iter()
.find_map(|entry| {
if *entry.name == selection.title {
Some(entry)
} else {
None
}
})
.unwrap();

if let Err(why) = Command::new("nix")
.arg("--experimental-features")
.arg("nix-command flakes")
.arg("run")
.arg(&*entry.get_command())
.spawn()
{
eprintln!("Error running desktop entry: {}", why);
}

HandleResult::Close
}

#[init]
pub fn init(config_dir: RString) -> State {
let config: Config = match fs::read_to_string(format!("{}/nix-run.ron", config_dir)) {
Ok(content) => ron::from_str(&content).unwrap_or_else(|why| {
eprintln!("Error parsing applications plugin config: {}", why);
Config::default()
}),
Err(why) => {
eprintln!("Error reading applications plugin config: {}", why);
Config::default()
}
};

let entries: RVec<NixEntry> = match fs::read_to_string(format!("{}/nix-pkgs.ron", config_dir)) {
Ok(content) => ron::from_str(&content).unwrap_or_else(|why| {
eprintln!("Error parsing applications plugin cache: {}\nBuilding new cache...", why);
let entries = get_entries();
fs::write(
format!("{}/nix-pkgs.ron", config_dir), ron::to_string(&entries)
.expect("Nix plugin could not parse entries to RON format!").as_bytes()
).expect("Updater could not write cache file!");
entries
}),
Err(why) => {
eprintln!("Error reading applications plugin cache: {}\nBuilding new cache...", why);
let entries = get_entries();
fs::write(
format!("{}/nix-pkgs.ron", config_dir), ron::to_string(&entries)
.expect("Nix plugin could not parse entries to RON format!").as_bytes()
).expect("Updater could not write cache file!");
entries
}
};

State { config, entries }
}

fn get_entries() -> RVec<NixEntry> {
let output = Command::new("nix-env")
.args(["-qaP", "--description"])
.output().unwrap();

let output_str = String::from_utf8(output.stdout).unwrap();
let re = Regex::new(r"^[^\.]*.(\S*)\s*\S*\s*(.*)$").unwrap();

let mut entries: RVec<NixEntry> = rvec![];
for line in output_str.lines() {
let captures: Captures = re
.captures(line)
.expect("Nix could not collect Regex captures for entry!");

entries.push(NixEntry {
name: RString::from(
captures
.get(1)
.expect("Nix failed to read a package name!")
.as_str(),
),
desc: RString::from(
captures
.get(2)
.expect("Nix failed to read a package description!")
.as_str(),
)
});
}
entries
}

#[get_matches]
pub fn get_matches(input: RString, state: &State) -> RVec<Match> {
let input = if let Some(input) = input.strip_prefix(&state.config.prefix) {
input.trim()
} else {
return RVec::new();
};

let matcher = fuzzy_matcher::skim::SkimMatcherV2::default().smart_case();
let mut entries = state
.entries
.iter()
.filter_map(|entry| {
let score: i64 = matcher.fuzzy_match(&entry.name, &input).unwrap_or(0)
+ matcher.fuzzy_match(&entry.desc, &input).unwrap_or(0);

if score > 0 {
Some((entry, score))
} else {
None
}
})
.collect::<Vec<_>>();

entries.sort_by(|a, b| b.1.cmp(&a.1));

entries.truncate(state.config.max_entries);
entries
.into_iter()
.map(|(entry, _)| Match {
title: entry.name.clone().into(),
description: ROption::RSome(entry.desc.clone().into()),
use_pango: false,
icon: ROption::RNone,
id: ROption::RNone,
})
.collect()
}

#[info]
pub fn info() -> PluginInfo {
PluginInfo {
name: "Nix-Run".into(),
icon: "application-x-executable".into(),
}
}