mirror of
https://github.com/RGBCube/uutils-coreutils
synced 2025-08-03 14:37:45 +00:00
Return Result<String, String> from getusername
This commit is contained in:
parent
fe0a49f7a4
commit
a8f9b40674
3 changed files with 11 additions and 7 deletions
|
@ -16,9 +16,10 @@ extern {
|
||||||
pub fn geteuid() -> libc::uid_t;
|
pub fn geteuid() -> libc::uid_t;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub unsafe fn getusername() -> String {
|
pub unsafe fn getusername() -> Result<String, String> {
|
||||||
let passwd: *const c_passwd = getpwuid(geteuid());
|
let passwd: *const c_passwd = getpwuid(geteuid());
|
||||||
|
|
||||||
let pw_name: *const libc::c_char = (*passwd).pw_name;
|
let pw_name: *const libc::c_char = (*passwd).pw_name;
|
||||||
String::from_utf8_lossy(::std::ffi::CStr::from_ptr(pw_name).to_bytes()).to_string()
|
let username = String::from_utf8_lossy(::std::ffi::CStr::from_ptr(pw_name).to_bytes()).to_string();
|
||||||
|
Ok(username)
|
||||||
}
|
}
|
||||||
|
|
|
@ -18,11 +18,12 @@ 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() -> String {
|
pub unsafe fn getusername() -> Result<String, 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 {
|
||||||
crash!(1, "failed to get username");
|
return Err("failed to get username".to_string())
|
||||||
}
|
}
|
||||||
String::from_wide(&buffer[..len as usize - 1])
|
let username = String::from_wide(&buffer[..len as usize - 1]);
|
||||||
|
Ok(username)
|
||||||
}
|
}
|
||||||
|
|
|
@ -54,7 +54,9 @@ pub fn uumain(args: Vec<String>) -> i32 {
|
||||||
|
|
||||||
pub fn exec() {
|
pub fn exec() {
|
||||||
unsafe {
|
unsafe {
|
||||||
let username = platform::getusername();
|
match platform::getusername() {
|
||||||
println!("{}", username);
|
Ok(username) => println!("{}", username),
|
||||||
|
Err(msg) => crash!(libc::EXIT_FAILURE, "{}", msg),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue