Skip to content

Instantly share code, notes, and snippets.

@malleusinferni
Last active February 19, 2016 06:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malleusinferni/cd403b30d6ddd97203d9 to your computer and use it in GitHub Desktop.
Save malleusinferni/cd403b30d6ddd97203d9 to your computer and use it in GitHub Desktop.
use std::ffi::{OsString};
use std::path::{Path};
const MARKPATH_KEY: &'static str = "MARKPATH";
const COMPLETE_ARG: &'static str = "--complete";
///
/// Port of some zsh code that reads a directory full of symlinks
/// and prints their names, followed by their destinations
///
/// Original code:
///
/// ```zsh
/// #!/bin/zsh
/// tab="$(printf "\t")"
/// cd "$MARKPATH"
/// stat -f"%N$tab%SY" * | column -ts "$tab"
/// ```
///
/// Example output (depending on what's in $MARKPATH):
///
/// ```text
/// rustsrc -> /usr/local/src/rustc-1.6.0
/// todo -> /home/psmith/Documents/Todo
/// bsg -> /home/psmith/Downloads/Battlestar Galactica Seasons 1-5
/// ```
///
fn main() {
let args: Vec<OsString> = std::env::args_os().collect();
//let exec_name = &args[0];
let mut complete = false;
if args.len() > 1 {
let option_complete = OsString::from(COMPLETE_ARG);
for arg in args.iter().skip(1) {
if arg == &option_complete {
complete = true;
} else {
panic!("Can't understand argument \"{:?}\"", arg);
}
}
}
let env_value = match std::env::var_os(MARKPATH_KEY) {
Some(pathname) => pathname,
None => panic!("Environment variable ${} is not defined", MARKPATH_KEY)
};
let markpath = Path::new(&env_value);
if !markpath.is_dir() {
panic!("${} ({}) is not a directory", MARKPATH_KEY, markpath.display());
}
let mappings: Vec<(String, String)> = markpath.read_dir().unwrap().map(|dir_entry| {
let dir_entry = dir_entry.unwrap();
let path = dir_entry.path();
let linkname = String::from(path.file_name().unwrap().to_str().unwrap());
let realpath = path.read_link().unwrap();
let realname = String::from(realpath.to_str().unwrap());
(linkname, realname)
}).collect();
if mappings.len() < 1 { return; }
if complete {
let fakenames: Vec<String> = mappings.iter().map(|&(ref f, _)| {
f.clone()
}).collect();
println!("{}", fakenames.join(" "));
} else {
let max_len = mappings.iter().map(|&(ref s, _)| s.len()).max().unwrap();
for (fake, real) in mappings {
let mut fake = fake.clone();
while fake.len() < max_len { fake.push(' '); }
println!("{} -> {}", fake, real);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment