Skip to content

Commit a406bdd

Browse files
committed
Implement os.getlogin
1 parent 6d371ce commit a406bdd

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

vm/src/stdlib/os.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2329,6 +2329,30 @@ mod posix {
23292329
SupportFunc::new(vm, "execv", execv, None, None, None),
23302330
]
23312331
}
2332+
2333+
/// Return a string containing the name of the user logged in on the
2334+
/// controlling terminal of the process.
2335+
///
2336+
/// Exceptions:
2337+
///
2338+
/// - `OSError`: Raised if login name could not be determined (`getlogin()`
2339+
/// returned a null pointer).
2340+
/// - `UnicodeDecodeError`: Raised if login name contained invalid UTF-8 bytes.
2341+
#[pyfunction]
2342+
fn getlogin(vm: &VirtualMachine) -> PyResult<String> {
2343+
// Get a pointer to the login name string. The string is statically
2344+
// allocated and might be overwritten on subsequent calls to this
2345+
// function or to `cuserid()`. See man getlogin(3) for more information.
2346+
let ptr = unsafe { libc::getlogin() };
2347+
if ptr.is_null() {
2348+
return Err(vm.new_os_error("unable to determine login name".to_owned()));
2349+
}
2350+
let slice = unsafe { ffi::CStr::from_ptr(ptr) };
2351+
slice
2352+
.to_str()
2353+
.map(|s| s.to_owned())
2354+
.map_err(|e| vm.new_unicode_decode_error(format!("unable to decode login name: {}", e)))
2355+
}
23322356
}
23332357
#[cfg(unix)]
23342358
use posix as platform;

0 commit comments

Comments
 (0)