use std::{
io::{self, BufRead, IsTerminal, Read, Write},
path::Path,
};
use clap::Subcommand;
use serde_json::json;
use super::print_json;
use crate::{
auth::remote::{self, Share},
platform::HiddenInput,
};
#[derive(Debug, Subcommand)]
pub enum RemoteCommand {
Login {
url: String,
#[arg(long, value_enum, default_value = "summary")]
share: Share,
},
Logout,
Status,
Push {
#[arg(long)]
dry_run: bool,
},
}
pub(super) async fn execute(
state: Option<&Path>,
repo: Option<&Path>,
command: RemoteCommand,
json: bool,
) -> Result<u8, String> {
let mut out = io::stdout();
match command {
RemoteCommand::Login { url, share } => {
let url = remote::parse_url(&url)?;
let token = read_token()?;
let (remote, principal) = remote::login(state, repo, url, share, token).await?;
if json {
print_json(&json!({
"url": remote.url,
"share": share,
"principal": principal.principal,
"scopes": principal.scopes,
}))?;
} else {
writeln!(
out,
"Signed in to {} as {} (scopes: {}).",
remote.url,
principal.principal,
principal
.scopes
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(", ")
)
.map_err(|e| e.to_string())?;
}
Ok(0)
}
RemoteCommand::Logout => {
remote::logout(state, repo)?;
if json {
print_json(&json!({"signedIn": false}))?;
} else {
writeln!(
out,
"Signed out of the remote review store. The server keeps the token valid until `artifactize server token revoke`."
)
.map_err(|e| e.to_string())?;
}
Ok(0)
}
RemoteCommand::Push { dry_run } => {
let report = crate::remote::push(state, repo, dry_run).await?;
if json {
print_json(&report)?;
} else {
writeln!(
out,
"{} {}, already in the store {}, skipped {}.",
if dry_run { "Would push" } else { "Pushed" },
report.pushed,
report.existing,
report.skipped
)
.map_err(|e| e.to_string())?;
}
Ok(0)
}
RemoteCommand::Status => {
let Some(status) = remote::status(state, repo).await? else {
if json {
print_json(&json!({"configured": false}))?;
} else {
writeln!(out, "No remote review store is configured.")
.map_err(|e| e.to_string())?;
}
return Ok(1);
};
if json {
let mut value = json!(status);
value["configured"] = json!(true);
print_json(&value)?;
} else {
writeln!(
out,
"Remote: {}\nShare: {}\nToken: {}\nReachable: {}",
status.url,
json!(status.share).as_str().unwrap_or_default(),
json!(status.token_source).as_str().unwrap_or_default(),
if status.reachable() { "yes" } else { "no" }
)
.map_err(|e| e.to_string())?;
match &status.connection {
remote::Connection::SignedIn { principal, scopes } => writeln!(
out,
"Principal: {} (scopes: {})",
principal,
scopes
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(", ")
),
remote::Connection::Refused { error }
| remote::Connection::Unreachable { error } => writeln!(out, "Error: {error}"),
}
.map_err(|e| e.to_string())?;
}
Ok(u8::from(!status.signed_in()))
}
}
}
const TOKEN_STDIN_BYTES: u64 = 8192;
fn read_token() -> Result<String, String> {
let stdin = io::stdin().lock();
let hidden = if stdin.is_terminal() {
let hidden = match HiddenInput::new() {
Ok(hidden) => Some(hidden),
Err(error) if crate::platform::VISIBLE_INPUT_FALLBACK => {
writeln!(
io::stderr().lock(),
"Warning: this terminal cannot hide input ({error}); the token will be visible."
)
.map_err(|e| e.to_string())?;
None
}
Err(error) => return Err(error.to_string()),
};
write!(
io::stderr().lock(),
"Paste the remote token, then press Enter: "
)
.map_err(|e| e.to_string())?;
hidden
} else {
None
};
let mut token = String::new();
let read = stdin.take(TOKEN_STDIN_BYTES).read_line(&mut token);
if hidden.is_some() {
drop(hidden);
let _ = writeln!(io::stderr().lock());
}
read.map_err(|_| "Cannot read the remote token from stdin.".to_owned())?;
Ok(token.trim().to_owned())
}