1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-08-03 14:37:45 +00:00

Use system error codes

This commit is contained in:
Danilo Bargen 2015-09-18 11:51:59 +02:00
parent 0e7223cfb0
commit 3e1c6e7e71
3 changed files with 11 additions and 5 deletions

View file

@ -7,6 +7,7 @@
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
use std::io::{Result, Error};
use ::libc; use ::libc;
use self::c_types::{c_passwd, getpwuid}; use self::c_types::{c_passwd, getpwuid};
@ -16,14 +17,14 @@ extern {
pub fn geteuid() -> libc::uid_t; pub fn geteuid() -> libc::uid_t;
} }
pub unsafe fn getusername() -> Result<String, String> { pub unsafe fn getusername() -> Result<String> {
// Get effective user id // Get effective user id
let uid = geteuid(); let uid = geteuid();
// Try to find username for uid // Try to find username for uid
let passwd: *const c_passwd = getpwuid(uid); let passwd: *const c_passwd = getpwuid(uid);
if passwd.is_null() { if passwd.is_null() {
return Err(format!("cannot find name for user ID {}", uid)) return Err(Error::last_os_error())
} }
// Extract username from passwd struct // Extract username from passwd struct

View file

@ -10,6 +10,8 @@
extern crate winapi; extern crate winapi;
extern crate advapi32; extern crate advapi32;
use std::io::{Result, Error};
#[path = "../../common/wide.rs"] #[macro_use] mod wide; #[path = "../../common/wide.rs"] #[macro_use] mod wide;
use std::mem; use std::mem;
@ -18,11 +20,11 @@ use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt; use std::os::windows::ffi::OsStringExt;
use self::wide::FromWide; use self::wide::FromWide;
pub unsafe fn getusername() -> Result<String, String> { pub unsafe fn getusername() -> Result<String> {
let mut buffer: [winapi::WCHAR; winapi::UNLEN as usize + 1] = mem::uninitialized(); let mut buffer: [winapi::WCHAR; winapi::UNLEN as usize + 1] = mem::uninitialized();
let mut len = buffer.len() as winapi::DWORD; let mut len = buffer.len() as winapi::DWORD;
if advapi32::GetUserNameW(buffer.as_mut_ptr(), &mut len) == 0 { if advapi32::GetUserNameW(buffer.as_mut_ptr(), &mut len) == 0 {
return Err("failed to get username".to_string()) return Err(Error::last_os_error())
} }
let username = String::from_wide(&buffer[..len as usize - 1]); let username = String::from_wide(&buffer[..len as usize - 1]);
Ok(username) Ok(username)

View file

@ -56,7 +56,10 @@ pub fn exec() {
unsafe { unsafe {
match platform::getusername() { match platform::getusername() {
Ok(username) => println!("{}", username), Ok(username) => println!("{}", username),
Err(msg) => crash!(libc::EXIT_FAILURE, "{}", msg), Err(err) => match err.raw_os_error() {
Some(0) | None => crash!(1, "failed to get username"),
Some(_) => crash!(1, "failed to get username: {}", err),
}
} }
} }
} }