#![forbid(unsafe_code)]
#![allow(
clippy::doc_markdown,
reason = "GitCode is a platform brand name, not a Rust code item"
)]
#![cfg_attr(
test,
allow(
clippy::expect_used,
clippy::unwrap_used,
clippy::indexing_slicing,
clippy::useless_format,
clippy::clone_on_copy,
reason = "Tests legitimately need to unwrap fixture data and index into known-shape \
collections"
)
)]
use std::sync::OnceLock;
use tracing::debug;
pub(crate) const GITCODE_API_MAX_PER_PAGE: u32 = 100;
pub mod auth;
pub mod commit;
pub mod error;
pub mod issue;
pub mod label;
pub mod pipeline;
pub mod pr;
pub mod release;
pub mod review;
pub mod runner;
pub use auth::GitCodeAuthProvider;
pub use commit::GitCodeCommitProvider;
pub use error::parse_gitcode_error;
pub use issue::GitCodeIssueProvider;
pub use label::{GitCodeLabelProvider, GitCodeMilestoneProvider};
pub use pipeline::GitCodePipelineProvider;
pub use pr::GitCodePrProvider;
pub use release::GitCodeReleaseProvider;
pub use review::GitCodeReviewProvider;
pub(crate) const FALLBACK_BINARY: &str = "gitcode";
static GITCODE_BINARY: OnceLock<String> = OnceLock::new();
pub(crate) fn gitcode_binary() -> String {
GITCODE_BINARY
.get_or_init(|| resolve_gitcode_binary(locate_candidate, identifies_as_gitcode_cli))
.clone()
}
fn resolve_gitcode_binary<L, P>(lookup: L, probe: P) -> String
where
L: Fn(&str) -> Option<std::path::PathBuf>,
P: Fn(&std::path::Path) -> bool,
{
const CANDIDATES: &[&str] = &["gitcode", "gc"];
for &candidate in CANDIDATES {
if let Some(path) = lookup(candidate)
&& probe(&path)
{
return path.to_string_lossy().into_owned();
}
}
FALLBACK_BINARY.into()
}
#[allow(
clippy::disallowed_methods,
reason = "one-time synchronous PATH lookup, memoized behind `GITCODE_BINARY`"
)]
fn locate_candidate(candidate: &str) -> Option<std::path::PathBuf> {
if let Ok(path) = which::which(candidate) {
return Some(path);
}
let home = std::env::var("HOME").ok()?;
let lib = std::path::PathBuf::from(&home).join("Library/Python");
if let Ok(entries) = std::fs::read_dir(&lib) {
for entry in entries.flatten() {
let path = entry.path().join("bin").join(candidate);
if path.exists() {
return Some(path);
}
}
}
let path = std::path::PathBuf::from(&home)
.join(".local/bin")
.join(candidate);
path.exists().then_some(path)
}
#[allow(
clippy::disallowed_types,
reason = "one-time synchronous probe, memoized behind `GITCODE_BINARY`, called from sync \
context"
)]
fn identifies_as_gitcode_cli(path: &std::path::Path) -> bool {
let Ok(output) = std::process::Command::new(path).arg("--help").output() else {
debug!(
candidate = %path.display(),
"candidate could not be executed for the --help probe"
);
return false;
};
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let accepted = is_gitcode_help_output(output.status.success(), &stdout, &stderr);
if !accepted {
debug!(
candidate = %path.display(),
exit_success = output.status.success(),
"candidate rejected: `--help` did not identify it as the GitCode CLI"
);
}
accepted
}
fn is_gitcode_help_output(success: bool, stdout: &str, stderr: &str) -> bool {
success
&& format!("{stdout}{stderr}")
.to_lowercase()
.contains("gitcode")
}
#[cfg(test)]
mod tests {
use std::path::{Path, PathBuf};
use super::*;
#[test]
fn test_should_return_non_empty_binary_name() {
let binary = gitcode_binary();
assert!(!binary.is_empty());
}
#[test]
fn test_should_cache_binary_discovery_across_calls() {
assert_eq!(
gitcode_binary(),
gitcode_binary(),
"discovery is memoized, so repeated calls must not re-probe"
);
assert!(
GITCODE_BINARY.get().is_some(),
"the first call must populate the cache so no later call forks a subprocess"
);
}
#[test]
fn test_should_prefer_gitcode_over_gc_when_both_resolve() {
let lookup = |candidate: &str| Some(PathBuf::from(format!("/usr/bin/{candidate}")));
let probe = |_: &Path| true;
assert_eq!(
resolve_gitcode_binary(lookup, probe),
"/usr/bin/gitcode",
"the unambiguous name must win so an unrelated `gc` cannot shadow the CLI"
);
}
#[test]
fn test_should_reject_candidate_that_fails_probe() {
let lookup =
|candidate: &str| (candidate == "gc").then(|| PathBuf::from("/opt/homebrew/bin/gc"));
let probe = |_: &Path| false;
assert_eq!(
resolve_gitcode_binary(lookup, probe),
FALLBACK_BINARY,
"a binary that does not identify as the GitCode CLI must be rejected"
);
}
#[test]
fn test_should_accept_gc_when_it_passes_probe() {
let lookup =
|candidate: &str| (candidate == "gc").then(|| PathBuf::from("/usr/local/bin/gc"));
let probe = |_: &Path| true;
assert_eq!(resolve_gitcode_binary(lookup, probe), "/usr/local/bin/gc");
}
#[test]
fn test_should_fall_back_to_unambiguous_name_when_nothing_resolves() {
let lookup = |_: &str| None;
let probe = |_: &Path| true;
assert_eq!(
resolve_gitcode_binary(lookup, probe),
"gitcode",
"falling back to `gc` would re-introduce the shadowing bug"
);
}
#[test]
fn test_should_identify_real_gitcode_cli_from_help_output() {
let stdout = "gitcode is a command line tool for GitCode.\n\nIt provides convenient \
access to GitCode features including:\n - Authentication management (auth \
login, auth status)\n";
assert!(is_gitcode_help_output(true, stdout, ""));
}
#[test]
fn test_should_reject_graphviz_gc_help_output() {
let stdout = "Usage: gc [-necCaDUrsv?] <files>\n -n - print number of nodes\n";
let stderr = "gc: option -- unrecognized\n";
assert!(
!is_gitcode_help_output(false, stdout, stderr),
"Graphviz gc must never be mistaken for the GitCode CLI"
);
}
#[test]
fn test_should_reject_successful_help_without_gitcode_marker() {
assert!(
!is_gitcode_help_output(true, "Usage: gc [-necCaDUrsv?] <files>", ""),
"exit 0 alone is not enough — the output must name GitCode"
);
}
#[test]
fn test_should_match_gitcode_marker_case_insensitively() {
assert!(is_gitcode_help_output(true, "A CLI for GitCode.", ""));
}
}