From 3e1c6e7e71441cc6e62457908cfd1db80d5ea421 Mon Sep 17 00:00:00 2001 From: Danilo Bargen Date: Fri, 18 Sep 2015 11:51:59 +0200 Subject: [PATCH] Use system error codes --- src/whoami/platform/unix.rs | 5 +++-- src/whoami/platform/windows.rs | 6 ++++-- src/whoami/whoami.rs | 5 ++++- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/whoami/platform/unix.rs b/src/whoami/platform/unix.rs index d24d02eca..009a7ef6b 100644 --- a/src/whoami/platform/unix.rs +++ b/src/whoami/platform/unix.rs @@ -7,6 +7,7 @@ * file that was distributed with this source code. */ +use std::io::{Result, Error}; use ::libc; use self::c_types::{c_passwd, getpwuid}; @@ -16,14 +17,14 @@ extern { pub fn geteuid() -> libc::uid_t; } -pub unsafe fn getusername() -> Result { +pub unsafe fn getusername() -> Result { // Get effective user id let uid = geteuid(); // Try to find username for uid let passwd: *const c_passwd = getpwuid(uid); 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 diff --git a/src/whoami/platform/windows.rs b/src/whoami/platform/windows.rs index 819da17bc..28d36cbfc 100644 --- a/src/whoami/platform/windows.rs +++ b/src/whoami/platform/windows.rs @@ -10,6 +10,8 @@ extern crate winapi; extern crate advapi32; +use std::io::{Result, Error}; + #[path = "../../common/wide.rs"] #[macro_use] mod wide; use std::mem; @@ -18,11 +20,11 @@ use std::ffi::OsString; use std::os::windows::ffi::OsStringExt; use self::wide::FromWide; -pub unsafe fn getusername() -> Result { +pub unsafe fn getusername() -> Result { let mut buffer: [winapi::WCHAR; winapi::UNLEN as usize + 1] = mem::uninitialized(); let mut len = buffer.len() as winapi::DWORD; 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]); Ok(username) diff --git a/src/whoami/whoami.rs b/src/whoami/whoami.rs index fdfc4f9ea..fbcf90f27 100644 --- a/src/whoami/whoami.rs +++ b/src/whoami/whoami.rs @@ -56,7 +56,10 @@ pub fn exec() { unsafe { match platform::getusername() { 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), + } } } }