coreutils/src/tty/tty.rs

85 lines
2.1 KiB
Rust
Raw Normal View History

2014-07-06 08:13:36 +00:00
#![crate_name = "tty"]
#![feature(rustc_private)]
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
use getopts::{getopts, optflag};
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 {
2014-01-10 08:23:12 +00:00
let options = [
optflag("s", "silent", "print nothing, only return an exit status"),
optflag("h", "help", "display this help and exit"),
optflag("V", "version", "output version information and exit")
2014-01-10 08:23:12 +00:00
];
let matches = match getopts(&args[1..], &options) {
Ok(m) => m,
2014-01-10 08:23:12 +00:00
Err(f) => {
crash!(2, "{}", f)
2014-01-10 08:23:12 +00:00
}
};
if matches.opt_present("help") {
let usage = getopts::usage("Print the file name of the terminal connected to standard input.", &options);
2014-01-10 08:23:12 +00:00
println!("Usage: {} [OPTION]...\n{}", NAME, usage);
} 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
}