Skip to content

Commit

Permalink
Merge pull request #1 from watawuwu/feature/albert
Browse files Browse the repository at this point in the history
Feature/albert
  • Loading branch information
watawuwu authored Dec 22, 2018
2 parents e08b1c4 + 49f783e commit ef22034
Show file tree
Hide file tree
Showing 8 changed files with 193 additions and 16 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ CARGO_VERSION := stable
CARGO_OPTIONS :=
CARGO_SUB_OPTIONS :=
CARGO_COMMAND := cargo +$(CARGO_VERSION) $(CARGO_OPTIONS)
APP_ARGS := launcher hain
APP_ARGS := launcher albert

# Environment
#===============================================================
Expand Down
40 changes: 27 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,21 @@ If the cargo project is a binary crates, this tool can register the binary in th
- Register as workflow
- [Hain](https://hainproject.github.io/hain/docs/)
- Register as devplugin
- [Albert](https://albertlauncher.github.io/docs/extensions/python/)
- Register as Python extension


## TODO
- [ ] cargo workspace(Only single binary crates)
- [ ] customize launcher scripts

## Usage

### Alfred workflow
### Common

```
- Install CLI binary

``` shell
$ cd {your binary crates project}

# Install to local, or manually install
Expand All @@ -26,8 +31,13 @@ $ cd {your binary crates project}
$ cargo install --path .
...
Installing /Users/watawuwu/.cargo/bin/{your-binary}
```

### Alfred workflow

# Export to Alfred
- Generate Alfredworkflow file

```
$ cargo launcher alfred
```

Expand All @@ -39,19 +49,23 @@ $ cargo launcher alfred

### Hain plugin

```
$ cd {your binary crates project}
# Install to local, or manually install
# The script path is set as follows
# PATH=$HOME/.cargo/bin:$HOME/.local/bin:/usr/local/bin:$PATH
$ cargo install --path .
...
Installing /Users/watawuwu/.cargo/bin/{your-binary}
- Export to hain devplugin directory

# Export to hain devplugin
```
$ cargo launcher hain
```

- Restart Hain


### Albert plugin

- Export to albert module directory

```
$ cargo launcher albert
```

- Check the checkbox of the python extension list and activate the setting

<img src="albert.png" width="300px"/>
Binary file added albert.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
106 changes: 106 additions & 0 deletions src/albert.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
#[cfg(target_os = "linux")]
use failure::*;
#[cfg(target_os = "linux")]
use log::*;
#[cfg(target_os = "linux")]
use std::fs;
#[cfg(target_os = "linux")]
use std::path::PathBuf;

use crate::cargo::CargoConfig;
use crate::error::Result;
#[cfg(target_os = "linux")]
use crate::fs::write_file;
use crate::launcher::LauncherConfig;
#[cfg(target_os = "linux")]
use crate::tpl::{self, Param};
#[cfg(target_os = "linux")]
const MODULE_TEMPLATE: &[u8] = include_bytes!("asset/albert/__init__.py");

#[cfg(target_os = "linux")]
pub fn install(cargo_conf: &CargoConfig, launcher_conf: &LauncherConfig) -> Result<()> {
let workflow_path = make(cargo_conf, launcher_conf)?;
copy(cargo_conf, workflow_path)?;
Ok(())
}

#[cfg(target_os = "linux")]
fn make(cargo_conf: &CargoConfig, launcher_conf: &LauncherConfig) -> Result<Vec<PathBuf>> {
let module = module_path(&launcher_conf.work_dir)?;
write_file(&module, module_bin(cargo_conf)?.as_bytes())?;

let icon = icon_path(&launcher_conf.work_dir)?;
write_file(&icon, &launcher_conf.icon(cargo_conf)?[..])?;

Ok(vec![module, icon])
}

#[cfg(target_os = "linux")]
fn module_bin(config: &CargoConfig) -> Result<String> {
let mut params = Param::new();
params.insert("prettyname", config.name());
params.insert("version", config.version());
params.insert("trigger", config.name());
params.insert("author", &config.author());

let tpl = String::from_utf8_lossy(MODULE_TEMPLATE).into_owned();
let contents = tpl::render(&tpl, &params)?;

Ok(contents)
}

#[cfg(target_os = "linux")]
fn copy(conf: &CargoConfig, paths: Vec<PathBuf>) -> Result<()> {
let sink_dir = application_config(conf)?;
fs::create_dir_all(&sink_dir)?;
for path in paths {
debug!("path: {:?}", &path);
debug!("sink: {:?}", &sink_dir);
let name = path.file_name().ok_or_else(|| err_msg("Not file type"))?;
let mut sink = sink_dir.clone();
sink.push(name);
fs::copy(&path, sink)?;
}

show_help(&sink_dir);
Ok(())
}

#[cfg(target_os = "linux")]
fn show_help(path: &PathBuf) {
let msg = r#"
Install completed!!
Please check the checkbox of the python extension list and activate the setting.
Installed path: "#;
println!("{}{}", msg, path.to_string_lossy());
}

#[cfg(target_os = "linux")]
fn application_config(cargo_conf: &CargoConfig) -> Result<PathBuf> {
let mut path = dirs::home_dir().ok_or_else(|| err_msg("Notfound home dir"))?;
path.push(".local/share/albert/org.albert.extension.python/modules");
path.push(cargo_conf.name());
Ok(path)
}

#[cfg(target_os = "linux")]
fn module_path(dir: &PathBuf) -> Result<PathBuf> {
path(dir, "__init__.py")
}

#[cfg(target_os = "linux")]
fn icon_path(dir: &PathBuf) -> Result<PathBuf> {
path(dir, "icon.png")
}

#[cfg(target_os = "linux")]
fn path(dir: &PathBuf, name: &str) -> Result<PathBuf> {
let dir_s = dir.to_str().ok_or_else(|| err_msg("NotFound dir path"))?;
Ok(PathBuf::from(format!("{}/{}", dir_s, name)))
}

#[cfg(not(target_os = "linux"))]
pub fn install(_cargo_conf: &CargoConfig, _launcher_conf: &LauncherConfig) -> Result<()> {
failure::bail!("Albert supported only linux")
}
51 changes: 51 additions & 0 deletions src/asset/albert/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# -*- coding: utf-8 -*-

import os
import subprocess

from albertv0 import *

__iid__ = "PythonInterface/v0.2"
__prettyname__ = "{{prettyname}}"
__version__ = "{{version}}"
__trigger__ = "{{trigger}}"
__author__ = "{{author}}"
__dependencies__ = []

iconPath = os.path.join(os.path.dirname(__file__), 'icon.png')
pathlist = ["/usr/local/bin", "~/.local/bin", "~/.cargo/bin"]

def handleQuery(query):
if not query.isTriggered:
return None

if len(query.string) <= 1:
return None

os.environ["PATH"] += os.pathsep + os.pathsep.join(pathlist)
cmd = ["url"] + query.string.split()
pipes = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

items = []
if pipes.returncode != 0:
err_msg = "%s. exit code: %s" % (pipes.stderr.strip().decode("utf-8"), pipes.returncode)
items.append(Item(
id = __prettyname__,
icon = iconPath,
text = err_msg,
subtext = "Failed",
actions = []
))
else:
out = pipes.stdout.decode("utf-8")
items.append(Item(
id = __prettyname__,
icon = iconPath,
text = out,
subtext = "Success",
actions = [
ClipAction("Added to Clipboard", out)
]
))
return items

6 changes: 4 additions & 2 deletions src/hain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,10 @@ Installed path: "#;
#[cfg(target_os = "macos")]
fn application_config(cargo_conf: &CargoConfig) -> Result<PathBuf> {
let mut path = dirs::home_dir().ok_or_else(|| err_msg("Notfound home dir"))?;
path.push("Library/Application Support");
path.push("hain-user/devplugins");
path.push("Library");
path.push("Application Support");
path.push("hain-user");
path.push("devplugins");
path.push(plugin_name(cargo_conf.name()));
Ok(path)
}
Expand Down
3 changes: 3 additions & 0 deletions src/launcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use pretty_env_logger;
use std::path::PathBuf;
use structopt::clap::*;

use crate::albert;
use crate::alfred;
use crate::args::Args;
use crate::cargo::CargoConfig;
Expand All @@ -18,6 +19,7 @@ arg_enum! {
pub enum Launcher {
Alfred,
Hain,
Albert,
}
}

Expand Down Expand Up @@ -50,6 +52,7 @@ pub fn launch(args: &Args, cargo_config: &CargoConfig) -> Result<()> {
match args.launcher {
Launcher::Alfred => alfred::install(&cargo_config, &launcher_config)?,
Launcher::Hain => hain::install(&cargo_config, &launcher_config)?,
Launcher::Albert => albert::install(&cargo_config, &launcher_config)?,
}
Ok(())
}
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
mod albert;
mod alfred;
mod args;
mod cargo;
Expand Down

0 comments on commit ef22034

Please sign in to comment.