[codex-rs] fix: exit code 1 if no api key (#697)

This commit is contained in:
Fouad Matin
2025-04-28 21:42:06 -07:00
committed by GitHub
parent b9bba09819
commit 19928bc257
3 changed files with 31 additions and 9 deletions

View File

@@ -24,3 +24,4 @@ tokio = { version = "1", features = [
] }
tracing = { version = "0.1.41", features = ["log"] }
tracing-subscriber = { version = "0.3.19", features = ["env-filter"] }
owo-colors = "4.2.0"

View File

@@ -12,11 +12,23 @@ use codex_core::protocol::FileChange;
use codex_core::protocol::InputItem;
use codex_core::protocol::Op;
use codex_core::util::is_inside_git_repo;
use owo_colors::OwoColorize;
use tracing::debug;
use tracing::error;
use tracing::info;
use tracing_subscriber::EnvFilter;
/// Returns `true` if a recognised API key is present in the environment.
///
/// At present we only support `OPENAI_API_KEY`, mirroring the behaviour of the
/// Node-based `codex-cli`. Additional providers can be added here when the
/// Rust implementation gains first-class support for them.
fn has_api_key() -> bool {
std::env::var("OPENAI_API_KEY")
.map(|s| !s.trim().is_empty())
.unwrap_or(false)
}
pub async fn run_main(cli: Cli) -> anyhow::Result<()> {
// TODO(mbolin): Take a more thoughtful approach to logging.
let default_level = "error";
@@ -41,6 +53,20 @@ pub async fn run_main(cli: Cli) -> anyhow::Result<()> {
..
} = cli;
// ---------------------------------------------------------------------
// API key handling
// ---------------------------------------------------------------------
if !has_api_key() {
eprintln!(
"\n{msg}\n\nSet the environment variable {var} and re-run this command.\nYou can create a key here: {url}\n",
msg = "Missing OpenAI API key.".red(),
var = "OPENAI_API_KEY".bold(),
url = "https://platform.openai.com/account/api-keys".bold().underline(),
);
std::process::exit(1);
}
if !skip_git_repo_check && !is_inside_git_repo() {
eprintln!("Not inside a Git repo and --skip-git-repo-check was not specified.");
std::process::exit(1);