Skip to content

Commit

Permalink
Use git credential helper
Browse files Browse the repository at this point in the history
  • Loading branch information
ChrisBr committed Aug 8, 2024
1 parent b854f3f commit 14a4a53
Showing 1 changed file with 43 additions and 6 deletions.
49 changes: 43 additions & 6 deletions crates/bin/src/gh_token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,15 @@ use tokio::process::Command;
use zeroize::Zeroizing;

pub(super) async fn get() -> io::Result<Zeroizing<Box<str>>> {
let Output { status, stdout, .. } = Command::new("gh")
.args(["auth", "token"])
.stdin(Stdio::null())
// Prepare the input for the git credential fill command
let input = "host=github.com\nprotocol=https";

let Output { status, stdout, .. } = Command::new("git")
.args(["credential", "fill"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.output()
.output_async_with_stdin(input.as_bytes())
.await?;

let stdout = Zeroizing::new(stdout);
Expand All @@ -25,12 +28,46 @@ pub(super) async fn get() -> io::Result<Zeroizing<Box<str>>> {
));
}

let s = str::from_utf8(&stdout).map_err(|err| {
// Assuming the password field is what's needed
let output_str = str::from_utf8(&stdout).map_err(|err| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("Invalid output, expected utf8: {err}"),
)
})?;

Ok(Zeroizing::new(s.trim().into()))
// Extract the password from the output
let password = output_str
.lines()
.find_map(|line| {
if line.starts_with("password=") {
Some(line.trim_start_matches("password=").to_owned())
} else {
None
}
})
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::Other,
"Password not found in the credential output",
)
})?;

Ok(Zeroizing::new(password.into()))
}

// Helper function to execute a command with input
async fn output_async_with_stdin(
cmd: &mut Command,
input: &[u8],
) -> io::Result<Output> {
let mut child = cmd.spawn()?;
let mut stdin = child.stdin.take().expect("Failed to open stdin");

tokio::spawn(async move {
use tokio::io::AsyncWriteExt;
let _ = stdin.write_all(input).await;
});

child.wait_with_output().await
}

0 comments on commit 14a4a53

Please sign in to comment.