use crate::git::{self, Opts};
use crate::model::{Config, Level};
use crate::{input, screen, ui};
use anyhow::{bail, Result};
use std::path::{Path, PathBuf};
use std::sync::atomic::AtomicBool;
use std::time::Duration;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Context {
Outside,
Repo,
Bare,
}
pub fn detect_context(inside_work_tree: &str, is_bare: &str) -> Context {
if is_bare.trim() == "true" {
Context::Bare
} else if inside_work_tree.trim() == "true" {
Context::Repo
} else {
Context::Outside
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct StartState {
pub in_repo: bool,
pub bare: bool,
pub identity_name: bool,
pub identity_email: bool,
pub has_gitignore: bool,
pub has_commit: bool,
pub remotes: Vec<String>,
pub has_upstream: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Row {
pub label: &'static str,
pub done: bool,
pub note: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Step {
Init,
Identity,
Ignore,
Commit,
Remote,
Push,
}
const STEPS: [Step; 6] = [
Step::Init,
Step::Identity,
Step::Ignore,
Step::Commit,
Step::Remote,
Step::Push,
];
pub fn checklist(s: &StartState) -> Vec<Row> {
let repo = s.in_repo && !s.bare;
let row = |label: &'static str, done: bool, yes: &str, no: &str| Row {
label,
done,
note: if done { yes } else { no }.to_string(),
};
let missing = match (s.identity_name, s.identity_email) {
(false, false) => "user.name and user.email are missing",
(false, true) => "user.name is missing",
_ => "user.email is missing",
};
let identity = s.identity_name && s.identity_email;
let remote_note = if s.remotes.is_empty() {
"no remote yet".to_string()
} else {
s.remotes.join(", ")
};
vec![
row(
"Repository exists",
repo,
"this folder is a git repository",
"not a repository yet",
),
row("Identity set (name + email)", identity, "done", missing),
row(
".gitignore present",
repo && s.has_gitignore,
"done",
"no .gitignore yet",
),
row(
"First commit made",
repo && s.has_commit,
"done",
"nothing committed yet",
),
Row {
label: "Remote added",
done: repo && !s.remotes.is_empty(),
note: remote_note,
},
row(
"Branch has an upstream (pushed)",
repo && s.has_upstream,
"done",
"not pushed yet",
),
]
}
pub fn repo_name_from_url(url: &str) -> Option<String> {
let t = url.trim().trim_end_matches(['/', '\\']);
let t = t
.strip_suffix(".git")
.unwrap_or(t)
.trim_end_matches(['/', '\\']);
let name = t.rsplit(['/', '\\', ':']).next().unwrap_or("");
if name.is_empty() || name == "." || name == ".." {
None
} else {
Some(name.to_string())
}
}
pub fn valid_remote_url(url: &str) -> bool {
if url.trim().is_empty() || url.starts_with('-') || url.chars().any(char::is_control) {
return false;
}
let plain = !url.chars().any(char::is_whitespace);
for scheme in ["https://", "http://", "ssh://"] {
if let Some(rest) = url.strip_prefix(scheme) {
return plain && !rest.is_empty();
}
}
if let Some((left, path)) = url.split_once(':') {
if let Some((user, host)) = left.split_once('@') {
if !left.contains('/') && !user.is_empty() && !host.is_empty() {
return plain && !path.is_empty();
}
}
}
Path::new(url).exists()
}
pub fn valid_folder_name(name: &str) -> bool {
let n = name.trim();
!n.is_empty()
&& n == name
&& !n.starts_with('-')
&& n != "."
&& !n.contains("..")
&& !n.contains(['/', '\\', ':'])
&& !n.chars().any(char::is_control)
}
pub fn valid_branch_shape(name: &str) -> bool {
!name.is_empty()
&& !name.starts_with('-')
&& !name.chars().any(|c| c.is_whitespace() || c.is_control())
}
fn norm(p: &Path) -> String {
let s = p.to_string_lossy().replace('\\', "/");
let s = s.trim_end_matches('/').to_string();
if cfg!(windows) {
s.to_lowercase()
} else {
s
}
}
pub fn is_risky_init_dir(path: &Path, home: Option<&Path>) -> bool {
let n = norm(path);
if path.parent().is_none() || n.is_empty() || n.ends_with(':') {
return true;
}
home.is_some_and(|h| !norm(h).is_empty() && norm(h) == n)
}
pub fn init_guard(inside_work_tree: bool, risky: bool) -> Vec<&'static str> {
let mut reasons = Vec::new();
if inside_work_tree {
reasons
.push("This folder is already inside a repository; a new one would be nested in it.");
}
if risky {
reasons.push("This is your home folder or a drive/filesystem root; a repository here would track everything in it.");
}
reasons
}
pub fn parse_untracked(raw: &[u8]) -> Vec<String> {
let mut out = Vec::new();
let mut parts = raw.split(|b| *b == 0).filter(|p| !p.is_empty());
while let Some(p) = parts.next() {
if p.len() < 4 {
continue;
}
let (xy, path) = (&p[..2], &p[3..]);
if xy == b"??" {
out.push(String::from_utf8_lossy(path).into_owned());
} else if xy[0] == b'R' || xy[0] == b'C' || xy[1] == b'R' || xy[1] == b'C' {
parts.next(); }
}
out
}
pub fn junk_candidates(paths: &[String]) -> Vec<String> {
let mut found = Vec::new();
let mut add = |name: &str| {
if !found.iter().any(|f| f == name) {
found.push(name.to_string());
}
};
let has_dir = |dir: &str| {
paths.iter().any(|p| {
let p = p.replace('\\', "/");
p.starts_with(&format!("{dir}/")) || p.contains(&format!("/{dir}/"))
})
};
let base = |p: &String| {
p.replace('\\', "/")
.rsplit('/')
.next()
.unwrap_or("")
.to_string()
};
for dir in ["node_modules", "target", "__pycache__", ".venv", "dist"] {
if has_dir(dir) {
add(&format!("{dir}/"));
}
}
if paths.iter().any(|p| base(p) == ".env") {
add(".env");
}
if paths.iter().any(|p| base(p).ends_with(".log")) {
add("*.log");
}
found.sort_by_key(|f| {
[
"node_modules/",
"target/",
".env",
"*.log",
"__pycache__/",
".venv/",
"dist/",
]
.iter()
.position(|k| k == f)
});
found
}
pub fn is_auth_error(text: &str) -> bool {
[
"Authentication failed",
"could not read Username",
"terminal prompts disabled",
]
.iter()
.any(|m| text.contains(m))
}
fn home_dir() -> Option<PathBuf> {
std::env::var_os("USERPROFILE")
.or_else(|| std::env::var_os("HOME"))
.map(PathBuf::from)
}
pub fn inside_work_tree(dir: &Path) -> bool {
let d = dir.to_string_lossy();
git::git_raw(
&["-C", &d, "rev-parse", "--is-inside-work-tree"],
&Opts::default(),
)
.map(|o| o.ok() && o.text() == "true")
.unwrap_or(false)
}
pub fn default_branch() -> String {
git::git_raw(&["config", "--get", "init.defaultBranch"], &Opts::default())
.ok()
.filter(|o| o.ok())
.map(|o| o.text())
.filter(|t| !t.is_empty() && valid_branch_shape(t))
.unwrap_or_else(|| "main".to_string())
}
pub fn check_branch(name: &str) -> Result<()> {
if !valid_branch_shape(name) {
bail!("'{name}' is not a usable branch name");
}
let out = git::git_raw(&["check-ref-format", "--branch", name], &Opts::default())?;
if !out.ok() {
bail!("'{name}' is not a valid branch name");
}
Ok(())
}
pub fn init_repo(dir: &Path, branch: &str) -> Result<String> {
check_branch(branch)?;
let d = dir.to_string_lossy();
if d.starts_with('-') {
bail!("Folder path must not start with '-'");
}
git::git_ok(&["init", "-b", branch, &d], &Opts::default())
}
pub fn init_new_folder(parent: &Path, name: &str, branch: &str) -> Result<PathBuf> {
if !valid_folder_name(name) {
bail!("'{name}' is not a valid folder name");
}
check_branch(branch)?;
let dir = parent.join(name);
std::fs::create_dir(&dir)
.map_err(|e| anyhow::anyhow!("Could not create {}: {e}", dir.display()))?;
init_repo(&dir, branch)?;
Ok(dir)
}
pub fn check_clone_target(dir: &Path) -> Result<()> {
if dir.exists() {
let non_empty = !dir.is_dir()
|| std::fs::read_dir(dir)
.map(|mut d| d.next().is_some())
.unwrap_or(true);
if non_empty {
bail!("{} already exists and is not empty", dir.display());
}
}
Ok(())
}
pub fn clone_repo(url: &str, dir: &Path, cancel: Option<&AtomicBool>) -> Result<String> {
if !valid_remote_url(url) {
bail!("That does not look like a repository URL");
}
check_clone_target(dir)?;
let o = Opts {
timeout: Some(Duration::from_secs(600)),
cancel,
..Opts::default()
};
git::git_ok(&["clone", "--", url, &dir.to_string_lossy()], &o)
}
pub fn load_state() -> StartState {
let q = |args: &[&str]| git::git_raw(args, &Opts::default()).ok().filter(|o| o.ok());
let inside = q(&["rev-parse", "--is-inside-work-tree"])
.map(|o| o.text())
.unwrap_or_default();
let bare = q(&["rev-parse", "--is-bare-repository"])
.map(|o| o.text())
.unwrap_or_default();
let ctx = detect_context(&inside, &bare);
if ctx != Context::Repo {
return StartState {
bare: ctx == Context::Bare,
in_repo: ctx == Context::Bare,
..StartState::default()
};
}
let set = |key: &str| q(&["config", "--get", key]).is_some_and(|o| !o.text().is_empty());
let top = q(&["rev-parse", "--show-toplevel"])
.map(|o| o.text())
.unwrap_or_default();
StartState {
in_repo: true,
bare: false,
identity_name: set("user.name"),
identity_email: set("user.email"),
has_gitignore: !top.is_empty() && Path::new(&top).join(".gitignore").exists(),
has_commit: q(&["rev-parse", "--verify", "-q", "HEAD"]).is_some(),
remotes: q(&["remote"])
.map(|o| {
o.text()
.lines()
.map(str::to_string)
.filter(|l| !l.is_empty())
.collect()
})
.unwrap_or_default(),
has_upstream: q(&["rev-parse", "--abbrev-ref", "@{u}"]).is_some(),
}
}
pub fn untracked_files() -> Result<Vec<String>> {
let out = git::git_raw(
&["status", "--porcelain=v1", "-z", "-uall"],
&Opts::default(),
)?;
Ok(parse_untracked(&out.stdout))
}
fn current_context() -> Context {
let q = |a: &str| {
git::git_raw(&["rev-parse", a], &Opts::default())
.ok()
.filter(|o| o.ok())
.map(|o| o.text())
.unwrap_or_default()
};
detect_context(&q("--is-inside-work-tree"), &q("--is-bare-repository"))
}
fn step_help(step: Step) -> &'static [&'static str] {
match step {
Step::Init => &["A repository is a folder git tracks. Its history lives in a hidden .git folder inside it."],
Step::Identity => &["Every commit records who made it. Set your name and email once."],
Step::Ignore => &["A .gitignore lists files git should never track, like build output or secrets."],
Step::Commit => &["A commit is a saved snapshot of your files with a message. You pick what goes in."],
Step::Remote => &["A remote is a copy of the repository on a server such as GitHub. Its usual name is origin."],
Step::Push => &["Pushing uploads your commits to the remote. The first push also links your branch to it."],
}
}
fn intro(cfg: &Config, title: &str, step: Step) -> Result<bool> {
let lines = ui::explain(cfg, step_help(step));
if lines.is_empty() {
return Ok(true);
}
Ok(ui::choose(title, &lines, &["Continue", "Back"])? == Some(0))
}
fn report(title: &str, err: &anyhow::Error) -> Result<()> {
if input::is_cancel(err) {
return Err(anyhow::anyhow!("{err}"));
}
let text = format!("{err:#}");
let mut lines = vec![screen::danger(text.clone())];
if is_auth_error(&text) {
lines.push(String::new());
lines.push("Sign-in is needed. Add an account with `gct --account` (Accounts mode), then try again.".into());
}
ui::notice(title, &lines)
}
fn ask_branch() -> Result<Option<String>> {
let mut initial = default_branch();
loop {
let Some(name) = ui::ask("Name of the first branch", &initial)? else {
return Ok(None);
};
let name = name.trim().to_string();
match check_branch(&name) {
Ok(()) => return Ok(Some(name)),
Err(e) => {
ui::notice("Branch name", &[e.to_string()])?;
initial = name;
}
}
}
}
fn confirm_init(cfg: &Config, dir: &Path, branch: &str) -> Result<bool> {
let reasons = init_guard(
inside_work_tree(dir),
is_risky_init_dir(dir, home_dir().as_deref()),
);
if reasons.is_empty() {
return Ok(true);
}
let what = reasons.join(" ");
ui::confirm_danger(
cfg,
&what,
&format!("git init -b {branch} {}", dir.display()),
)
}
fn init_here(cfg: &Config) -> Result<()> {
let dir = std::env::current_dir()?;
let Some(branch) = ask_branch()? else {
return Ok(());
};
if !confirm_init(cfg, &dir, &branch)? {
return Ok(());
}
match ui::git_job("Creating repository...", || init_repo(&dir, &branch)) {
Ok(msg) => ui::notice("Repository created", &[msg]),
Err(e) => report("Could not create repository", &e),
}
}
fn init_in_new_folder(cfg: &Config) -> Result<()> {
let parent = std::env::current_dir()?;
let Some(name) = ui::ask("New folder name", "")? else {
return Ok(());
};
if !valid_folder_name(&name) {
return ui::notice(
"New folder",
&["Use a plain name: no slashes, no '..', not starting with '-'.".into()],
);
}
if parent.join(&name).exists() {
return ui::notice("New folder", &[format!("{name} already exists here.")]);
}
let Some(branch) = ask_branch()? else {
return Ok(());
};
if !confirm_init(cfg, &parent.join(&name), &branch)? {
return Ok(());
}
match ui::git_job("Creating repository...", || {
init_new_folder(&parent, &name, &branch)
}) {
Ok(dir) => {
std::env::set_current_dir(&dir)?;
ui::notice(
"Repository created",
&[format!("Now working in {}", dir.display())],
)
}
Err(e) => report("Could not create repository", &e),
}
}
fn clone_flow() -> Result<()> {
let Some(url) = ui::ask("Repository URL (https://..., git@host:owner/repo.git)", "")? else {
return Ok(());
};
let url = url.trim().to_string();
if !valid_remote_url(&url) {
return ui::notice(
"Clone",
&["That does not look like a valid URL or existing path.".into()],
);
}
let initial = repo_name_from_url(&url).unwrap_or_default();
let Some(target) = ui::ask("Folder to clone into", &initial)? else {
return Ok(());
};
let target = target.trim().to_string();
if target.is_empty() || target.starts_with('-') {
return ui::notice(
"Clone",
&["Pick a folder name that does not start with '-'.".into()],
);
}
let dir = std::env::current_dir()?.join(&target);
if let Err(e) = check_clone_target(&dir) {
return ui::notice("Clone", &[e.to_string()]);
}
match ui::git_job_cancellable("Cloning...", |cancel| clone_repo(&url, &dir, Some(cancel))) {
Ok(_) => {
std::env::set_current_dir(&dir)?;
ui::notice("Cloned", &[format!("Now working in {}", dir.display())])
}
Err(e) => report("Clone failed", &e),
}
}
fn first_commit(cfg: &mut Config) -> Result<()> {
let files = untracked_files().unwrap_or_default();
if !files.is_empty() {
let junk = junk_candidates(&files);
let mut lines = vec![format!("{} untracked file(s), for example:", files.len())];
lines.extend(files.iter().take(8).map(|f| format!(" {f}")));
if files.len() > 8 {
lines.push(format!(" ... and {} more", files.len() - 8));
}
if !junk.is_empty() {
lines.push(String::new());
lines.push(screen::warning(format!(
"These usually should not be committed: {}",
junk.join(", ")
)));
}
let options: &[&str] = if junk.is_empty() {
&["Continue to commit", "Back"]
} else {
&["Open Ignore first", "Continue to commit", "Back"]
};
match (
ui::choose("Before the first commit", &lines, options)?,
junk.is_empty(),
) {
(None, _) => return Ok(()),
(Some(0), false) => {
crate::modes::open("ignore", cfg)?;
}
(Some(i), j) if i == usize::from(!j) => {}
_ => return Ok(()),
}
}
crate::modes::open("commit", cfg)
}
fn run_step(cfg: &mut Config, step: Step, state: &StartState) -> Result<()> {
match step {
Step::Init => return Ok(()),
Step::Push if !state.has_commit || state.remotes.is_empty() => {
let what = if state.has_commit {
"Add a remote first."
} else {
"Make the first commit first."
};
return ui::notice("Not ready to push", &[what.to_string()]);
}
_ => {}
}
let titles = [
"",
"Identity",
".gitignore",
"First commit",
"Remote",
"First push",
];
let index = STEPS.iter().position(|s| *s == step).unwrap_or(0);
if !intro(cfg, titles[index], step)? {
return Ok(());
}
match step {
Step::Identity => crate::modes::gitcfg::edit_identity(cfg),
Step::Ignore => crate::modes::open("ignore", cfg),
Step::Commit => first_commit(cfg),
Step::Remote => crate::modes::sync::add_remote(cfg),
Step::Push => crate::modes::sync::push_current(cfg, true),
Step::Init => Ok(()),
}
}
fn outside_menu(cfg: &mut Config) -> Result<bool> {
let mut context = vec!["This folder is not a git repository yet.".to_string()];
context.extend(ui::explain(cfg, step_help(Step::Init)));
match ui::choose(
"Start",
&context,
&[
"Create a repository here",
"Create a repository in a new folder",
"Clone a repository from a URL",
"Back",
],
)? {
Some(0) => init_here(cfg)?,
Some(1) => init_in_new_folder(cfg)?,
Some(2) => clone_flow()?,
_ => return Ok(false),
}
Ok(true)
}
fn render(rows: &[Row]) -> Vec<String> {
rows.iter()
.map(|r| {
let mark = if r.done {
screen::success("[x]")
} else {
screen::warning("[ ]")
};
format!("{mark} {} - {}", r.label, screen::muted(&r.note))
})
.collect()
}
pub fn run(config: &mut Config) -> Result<()> {
let mut index = 0;
loop {
match current_context() {
Context::Bare => {
return ui::notice(
"Start",
&[
"This is a bare repository (no working folder). Nothing to set up here."
.into(),
],
);
}
Context::Outside => {
if !outside_menu(config)? {
return Ok(());
}
if current_context() != Context::Repo {
continue;
}
}
Context::Repo => {}
}
let state = load_state();
let rows = checklist(&state);
let mut header = vec!["Enter on an unchecked step to do it.".to_string()];
if config.level() == Level::Beginner {
header.push(screen::muted(
"Work from top to bottom: each step builds on the one before.",
));
}
let keys = [ui::Key {
key: 'r',
label: "refresh",
}];
match ui::action_list("Start", &header, &render(&rows), &keys, &mut index)? {
ui::Choice::Back => return Ok(()),
ui::Choice::Action(_, _) => {}
ui::Choice::Open(i) => {
let Some(step) = STEPS.get(i).copied() else {
continue;
};
if rows[i].done {
ui::notice(rows[i].label, &[format!("Already done: {}", rows[i].note)])?;
} else {
run_step(config, step, &state)?;
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testutil::TempRepo;
#[test]
fn repo_names() {
let t = [
("https://github.com/o/repo", Some("repo")),
("https://github.com/o/repo.git", Some("repo")),
("https://github.com/o/repo/", Some("repo")),
("git@github.com:owner/repo.git", Some("repo")),
("git@host:repo.git", Some("repo")),
("C:\\work\\proj.git", Some("proj")),
("C:\\work\\proj\\", Some("proj")),
("", None),
("/", None),
(".git", None),
];
for (u, want) in t {
assert_eq!(repo_name_from_url(u).as_deref(), want, "{u}");
}
}
#[test]
fn urls() {
for ok in [
"https://a.com/o/r.git",
"http://a/b",
"ssh://git@a.com/o/r",
"git@github.com:o/r.git",
] {
assert!(valid_remote_url(ok), "{ok}");
}
let tmp = TempRepo::outside();
assert!(valid_remote_url(&tmp.path().to_string_lossy()));
for bad in [
"",
" ",
"-oProxy=x",
"--upload-pack=x",
"https://",
"https://a b",
"a\u{7}b",
"no/such/dir-xyz",
"git@host:",
"https://a\nb",
] {
assert!(!valid_remote_url(bad), "{bad:?}");
}
}
#[test]
fn names_and_branches() {
for ok in ["proj", "my proj", "a.b"] {
assert!(valid_folder_name(ok), "{ok}");
}
for bad in ["", " ", "-x", "a/b", "a\\b", "..", "a..b", ".", "C:x", " x"] {
assert!(!valid_folder_name(bad), "{bad:?}");
}
assert!(
valid_branch_shape("main")
&& !valid_branch_shape("-m")
&& !valid_branch_shape("a b")
&& !valid_branch_shape("")
);
}
#[test]
fn risky_dirs() {
let home = Path::new("/home/me");
assert!(is_risky_init_dir(Path::new("/home/me"), Some(home)));
assert!(is_risky_init_dir(Path::new("/home/me/"), Some(home)));
assert!(is_risky_init_dir(Path::new("/"), None));
assert!(!is_risky_init_dir(Path::new("/home/me/proj"), Some(home)));
assert!(!is_risky_init_dir(Path::new("/home/me/proj"), None));
if cfg!(windows) {
assert!(is_risky_init_dir(Path::new("C:\\"), None));
assert!(is_risky_init_dir(
Path::new("c:\\Users\\Me"),
Some(Path::new("C:\\Users\\me\\"))
));
assert!(!is_risky_init_dir(
Path::new("C:\\Users\\Me\\proj"),
Some(Path::new("C:\\Users\\Me"))
));
}
}
#[test]
fn guard_decisions() {
assert!(init_guard(false, false).is_empty());
assert_eq!(init_guard(true, false).len(), 1);
assert_eq!(init_guard(false, true).len(), 1);
assert_eq!(init_guard(true, true).len(), 2);
}
#[test]
fn contexts() {
assert_eq!(detect_context("true", "false"), Context::Repo);
assert_eq!(detect_context("false", "true"), Context::Bare);
assert_eq!(detect_context("", ""), Context::Outside);
assert_eq!(detect_context("false", "false"), Context::Outside);
}
#[test]
fn checklist_boundaries() {
let none = checklist(&StartState::default());
assert_eq!(none.len(), 6);
assert!(none.iter().all(|r| !r.done));
let mut s = StartState {
in_repo: true,
..StartState::default()
};
let d = |s: &StartState| checklist(s).iter().map(|r| r.done).collect::<Vec<_>>();
assert_eq!(d(&s), [true, false, false, false, false, false]);
s.identity_name = true;
assert!(!d(&s)[1]);
assert!(checklist(&s)[1].note.contains("user.email"));
s.identity_email = true;
s.has_gitignore = true;
s.has_commit = true;
assert_eq!(d(&s), [true, true, true, true, false, false]);
s.remotes = vec!["origin".into(), "up".into()];
assert_eq!(checklist(&s)[4].note, "origin, up");
s.has_upstream = true;
assert!(d(&s).iter().all(|x| *x));
s.in_repo = false;
assert_eq!(d(&s), [false, true, false, false, false, false]);
}
#[test]
fn untracked_parsing() {
let raw = b"?? a.txt\0 M b.txt\0R new.txt\0old.txt\0?? dir/c d.txt\0?? \xc3\xa9.txt\0";
assert_eq!(parse_untracked(raw), ["a.txt", "dir/c d.txt", "\u{e9}.txt"]);
assert!(parse_untracked(b"").is_empty());
}
#[test]
fn junk() {
let p = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
assert!(junk_candidates(&p(&["src/main.rs", "targets.txt", "env.txt"])).is_empty());
assert_eq!(
junk_candidates(&p(&[
"web\\node_modules\\x.js",
"target/debug/a",
".env",
"sub/.env",
"a.log",
"dist/b",
".venv/c",
"pkg/__pycache__/d.pyc"
])),
[
"node_modules/",
"target/",
".env",
"*.log",
"__pycache__/",
".venv/",
"dist/"
]
);
}
#[test]
fn auth_errors() {
assert!(is_auth_error(
"fatal: could not read Username for 'https://x': terminal prompts disabled"
));
assert!(is_auth_error("remote: Authentication failed"));
assert!(!is_auth_error("fatal: repository not found"));
}
#[test]
fn init_outside_creates_repo() {
let t = TempRepo::outside();
t.run(|| {
assert_eq!(load_state(), StartState::default());
init_repo(t.path(), "trunk").unwrap();
assert_eq!(
git::git_ok(&["symbolic-ref", "--short", "HEAD"], &Opts::default()).unwrap(),
"trunk"
);
assert!(git::git_ok(&["status", "--porcelain"], &Opts::default()).is_ok());
let s = load_state();
assert!(s.in_repo && !s.has_commit && s.remotes.is_empty() && !s.has_upstream);
assert!(init_repo(t.path(), "-bad").is_err());
assert!(init_repo(t.path(), "a b").is_err());
});
}
#[test]
fn init_new_folder_works() {
let t = TempRepo::outside();
t.run(|| {
let dir = init_new_folder(t.path(), "proj", "main").unwrap();
assert!(dir.join(".git").exists());
assert!(inside_work_tree(&dir));
assert!(init_new_folder(t.path(), "proj", "main").is_err());
assert!(init_new_folder(t.path(), "../x", "main").is_err());
assert!(init_new_folder(t.path(), "-x", "main").is_err());
});
}
#[test]
fn nested_repo_detected() {
let t = TempRepo::new(1);
t.run(|| {
assert!(inside_work_tree(t.path()));
let sub = t.path().join("sub");
std::fs::create_dir(&sub).unwrap();
assert_eq!(init_guard(inside_work_tree(&sub), false).len(), 1);
});
}
#[test]
fn clone_local_and_refuse_nonempty() {
let t = TempRepo::new(2).with_remote();
let url = t.remote_path().to_string_lossy().into_owned();
let parent = t.path().parent().unwrap().to_path_buf();
t.run(|| {
let fresh = parent.join("fresh");
std::fs::create_dir(&fresh).unwrap();
clone_repo(&url, &fresh, None).unwrap();
assert!(fresh.join("f1.txt").exists());
let again = clone_repo(&url, &fresh, None).unwrap_err();
assert!(again.to_string().contains("not empty"));
assert!(clone_repo("-x", &parent.join("zz"), None).is_err());
assert!(!parent.join("zz").exists());
});
}
#[test]
fn state_in_populated_repo() {
let t = TempRepo::new(2).with_remote();
t.run(|| {
let s = load_state();
assert!(s.in_repo && s.has_commit && s.has_upstream);
assert_eq!(s.remotes, ["origin"]);
assert!(!s.has_gitignore);
t.write("x.log", "1");
assert_eq!(untracked_files().unwrap(), ["x.log"]);
});
}
}