coreutils/src/tty/tty.rs

84 lines
2.2 KiB
Rust
Raw Normal View History

2014-07-06 08:13:36 +00:00
#![crate_name = "tty"]
2014-01-10 08:23:12 +00:00
/*
* This file is part of the uutils coreutils package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Synced with http://lingrok.org/xref/coreutils/src/tty.c
*/
extern crate getopts;
extern crate libc;
2014-01-10 08:23:12 +00:00
2015-02-22 12:58:57 +00:00
use std::ffi::CStr;
use std::io::Write;
2014-02-23 22:17:48 +00:00
#[path = "../common/util.rs"]
2015-01-08 12:54:22 +00:00
#[macro_use]
mod util;
2014-01-10 08:23:12 +00:00
extern {
fn ttyname(filedesc: libc::c_int) -> *const libc::c_char;
2014-01-10 08:23:12 +00:00
fn isatty(filedesc: libc::c_int) -> libc::c_int;
}
static NAME: &'static str = "tty";
static VERSION: &'static str = "1.0.0";
pub fn uumain(args: Vec<String>) -> i32 {
let mut opts = getopts::Options::new();
2014-01-10 08:23:12 +00:00
opts.optflag("s", "silent", "print nothing, only return an exit status");
opts.optflag("h", "help", "display this help and exit");
opts.optflag("V", "version", "output version information and exit");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => { crash!(2, "{}", f) }
2014-01-10 08:23:12 +00:00
};
if matches.opt_present("help") {
println!("{} {}", NAME, VERSION);
println!("");
println!("Usage:");
println!(" {} [OPTION]...", NAME);
println!("");
print!("{}", opts.usage("Print the file name of the terminal connected to standard input."));
} else if matches.opt_present("version") {
println!("{} {}", NAME, VERSION);
} else {
let silent = matches.opt_present("s");
2014-01-10 08:23:12 +00:00
let tty = unsafe {
let ptr = ttyname(libc::STDIN_FILENO);
if !ptr.is_null() {
String::from_utf8_lossy(CStr::from_ptr(ptr).to_bytes()).to_string()
} else {
"".to_string()
}
};
if !silent {
if !tty.chars().all(|c| c.is_whitespace()) {
println!("{}", tty);
} else {
println!("not a tty");
}
2014-01-10 08:23:12 +00:00
}
return unsafe {
if isatty(libc::STDIN_FILENO) == 1 {
libc::EXIT_SUCCESS
} else {
libc::EXIT_FAILURE
}
};
}
2014-01-10 08:23:12 +00:00
0
2014-01-10 08:23:12 +00:00
}