1use std::process;
2
3#[derive(Clone)]
4pub struct AuthToken(String);
5
6impl AuthToken {
7 pub fn access(&self) -> &str {
8 &self.0
9 }
10}
11
12pub fn get_token_from_command(command: &str) -> Result<AuthToken, String> {
13 let output = process::Command::new("/usr/bin/env")
14 .arg("sh")
15 .arg("-c")
16 .arg(command)
17 .output()
18 .map_err(|error| format!("Failed to run token-command: {error}"))?;
19
20 let stderr = String::from_utf8(output.stderr).map_err(|error| error.to_string())?;
21 let stdout = String::from_utf8(output.stdout).map_err(|error| error.to_string())?;
22
23 if !output.status.success() {
24 return if !stderr.is_empty() {
25 Err(format!("Token command failed: {stderr}"))
26 } else {
27 Err(String::from("Token command failed."))
28 };
29 }
30
31 if !stderr.is_empty() {
32 return Err(format!("Token command produced stderr: {stderr}"));
33 }
34
35 if stdout.is_empty() {
36 return Err(String::from("Token command did not produce output"));
37 }
38
39 let token = stdout
40 .split('\n')
41 .next()
42 .ok_or_else(|| String::from("Output did not contain any newline"))?;
43
44 Ok(AuthToken(token.to_string()))
45}