Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ cargo test
```

The system libraries you need are in the [README](README.md#building).
Three hundred and eighty tests, most of them against real repositories
Three hundred and eighty-two tests, most of them against real repositories
made in `/tmp`, so they are slow and they are honest. CI runs them on Linux
on every pull request; macOS and Windows are built there and not tested,
which is a gap and not a decision.
Expand Down
84 changes: 84 additions & 0 deletions crates/gitrust-core/src/home.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
//! Where this person's files are.
//!
//! One answer, asked in one place. It used to be asked by each file that
//! wanted it, and they did not all ask the same way: the settings looked for
//! `HOME` and then for `USERPROFILE`, the list of known repositories and the
//! profiles looked for `HOME` and stopped. A Windows program started from
//! the desktop has no `HOME`, so on Windows the first was written and the
//! other two never were -- and nothing said so, because a file with nowhere
//! to go is not an error anywhere in this program, on purpose.

use std::ffi::OsString;
use std::path::PathBuf;

/// The home folder: `HOME`, or `USERPROFILE` where there is none.
///
/// `HOME` goes first on every system. On Windows it is only there when
/// something put it there -- Git Bash does -- and whoever set it meant it.
pub fn folder() -> Option<PathBuf> {
first(std::env::var_os("HOME"), std::env::var_os("USERPROFILE"))
}

/// The folder gitrust keeps its own files in.
///
/// `$XDG_CONFIG_HOME/gitrust`, or `.config/gitrust` under the home folder --
/// on Windows too, where `%APPDATA%` would be the custom. The settings were
/// already being written under `.config` there, and three files in one
/// folder beat two folders with one of them in the proper place.
pub fn config() -> Option<PathBuf> {
config_under(std::env::var_os("XDG_CONFIG_HOME"), folder())
}

/// A variable that is set to nothing says nothing: a shell that exports
/// `HOME=` has not named the root of the disk.
fn first(home: Option<OsString>, profile: Option<OsString>) -> Option<PathBuf> {
[home, profile]
.into_iter()
.flatten()
.find(|value| !value.is_empty())
.map(PathBuf::from)
}

fn config_under(xdg: Option<OsString>, home: Option<PathBuf>) -> Option<PathBuf> {
let base = match xdg {
Some(dir) if !dir.is_empty() => PathBuf::from(dir),
_ => home?.join(".config"),
};
Some(base.join("gitrust"))
}

#[cfg(test)]
mod tests {
use super::*;

fn said(value: &str) -> Option<OsString> {
Some(OsString::from(value))
}

// The variables are handed in rather than set: the environment belongs
// to the whole test process, and a test that changed HOME would change
// it under every other test running beside it.

#[test]
fn a_machine_with_no_home_variable_still_has_a_home_folder() {
assert_eq!(first(None, said("C:\\Users\\ana")), Some(PathBuf::from("C:\\Users\\ana")));
assert_eq!(first(said(""), said("C:\\Users\\ana")), Some(PathBuf::from("C:\\Users\\ana")));
assert_eq!(first(said("/home/ana"), said("C:\\Users\\ana")), Some(PathBuf::from("/home/ana")));
assert_eq!(first(None, None), None);
assert_eq!(first(said(""), said("")), None);
}

#[test]
fn the_files_go_under_the_home_folder_unless_somewhere_else_was_named() {
let home = Some(PathBuf::from("/home/ana"));
assert_eq!(
config_under(None, home.clone()),
Some(PathBuf::from("/home/ana").join(".config").join("gitrust"))
);
assert_eq!(config_under(said(""), home.clone()), config_under(None, home.clone()));
assert_eq!(config_under(said("/etc/xdg"), home), Some(PathBuf::from("/etc/xdg").join("gitrust")));
// Named outright, it needs no home folder to hang from.
assert_eq!(config_under(said("/etc/xdg"), None), Some(PathBuf::from("/etc/xdg").join("gitrust")));
assert_eq!(config_under(None, None), None);
}
}
15 changes: 6 additions & 9 deletions crates/gitrust-core/src/known.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@
//!
//! # Where
//!
//! `$XDG_CONFIG_HOME/gitrust/known`, or `$HOME/.config/gitrust/known`. No
//! crate is used to find it: the rule is two lines of `std::env`, and a
//! dependency for that would be a sixth in a project that has five on
//! purpose.
//! `$XDG_CONFIG_HOME/gitrust/known`, or `$HOME/.config/gitrust/known`, with
//! `%USERPROFILE%` standing in for a `HOME` that Windows does not set. No
//! crate is used to find it: the rule is a few lines of `std::env` in
//! [`crate::home`], and a dependency for that would be a sixth in a project
//! that has five on purpose.
//!
//! # What
//!
Expand Down Expand Up @@ -114,11 +115,7 @@ impl Known {

/// Where the file lives, whether or not it is there yet.
pub fn file() -> Option<PathBuf> {
let base = match std::env::var_os("XDG_CONFIG_HOME") {
Some(dir) if !dir.is_empty() => PathBuf::from(dir),
_ => PathBuf::from(std::env::var_os("HOME")?).join(".config"),
};
Some(base.join("gitrust").join("known"))
Some(crate::home::config()?.join("known"))
}

/// Every repository the machine knows, favourites first and newest after.
Expand Down
1 change: 1 addition & 0 deletions crates/gitrust-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ pub mod foresee;
pub mod forge;
pub mod graph;
pub mod history;
pub mod home;
pub mod known;
pub mod merge;
pub mod message;
Expand Down
16 changes: 5 additions & 11 deletions crates/gitrust-core/src/profile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -257,8 +257,7 @@ impl Profile {
let Some(rest) = key.strip_prefix("~/") else {
return Some(PathBuf::from(key));
};
let home = std::env::var_os("HOME")?;
Some(PathBuf::from(home).join(rest))
Some(crate::home::folder()?.join(rest))
}

/// The public half of that key, beside it on the disk.
Expand All @@ -280,9 +279,8 @@ impl Profile {
if let Some(key) = self.key_file() {
return Some(key);
}
let home = std::env::var_os("HOME")?;
Some(
PathBuf::from(home)
crate::home::folder()?
.join(".ssh")
.join(format!("{}_ed25519", slug(&self.name))),
)
Expand Down Expand Up @@ -378,11 +376,7 @@ pub struct Profiles {

/// Where the file lives, whether or not it is there yet.
pub fn file() -> Option<PathBuf> {
let base = match std::env::var_os("XDG_CONFIG_HOME") {
Some(dir) if !dir.is_empty() => PathBuf::from(dir),
_ => PathBuf::from(std::env::var_os("HOME")?).join(".config"),
};
Some(base.join("gitrust").join("profiles"))
Some(crate::home::config()?.join("profiles"))
}

impl Profiles {
Expand Down Expand Up @@ -646,10 +640,10 @@ pub fn public_of(key: &Path) -> PathBuf {
/// afterwards says `~/.ssh/acme_ed25519` and not their home folder spelled
/// out in full.
pub fn shorten(path: &Path) -> String {
let Some(home) = std::env::var_os("HOME") else {
let Some(home) = crate::home::folder() else {
return path.display().to_string();
};
match path.strip_prefix(PathBuf::from(home)) {
match path.strip_prefix(home) {
Ok(rest) => format!("~/{}", rest.display()),
Err(_) => path.display().to_string(),
}
Expand Down
12 changes: 3 additions & 9 deletions crates/gitrust-core/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
//! # Where
//!
//! `$XDG_CONFIG_HOME/gitrust/settings`, or `$HOME/.config/gitrust/settings`,
//! beside the list of known repositories and found the same way.
//! beside the list of known repositories and found the same way, which is
//! [`crate::home::config`].
//!
//! # What
//!
Expand Down Expand Up @@ -248,14 +249,7 @@ impl Default for Settings {

/// Where the file lives, whether or not it is there yet.
pub fn file() -> Option<PathBuf> {
let base = match std::env::var_os("XDG_CONFIG_HOME") {
Some(dir) if !dir.is_empty() => PathBuf::from(dir),
_ => PathBuf::from(
std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?,
)
.join(".config"),
};
Some(base.join("gitrust").join("settings"))
Some(crate::home::config()?.join("settings"))
}

impl Settings {
Expand Down
13 changes: 5 additions & 8 deletions crates/gitrust-core/src/ssh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

use std::io::{Read, Write};
use std::net::TcpStream;
use std::path::{Path, PathBuf};
use std::path::Path;
use std::time::Duration;

use anyhow::{bail, Context, Result};
Expand Down Expand Up @@ -244,11 +244,10 @@ fn verify_host(raw: &RawSession, login: &Login, trust_new_host: bool, known_host
let file = match known_hosts {
Some(file) => file.to_path_buf(),
None => {
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"));
let Some(home) = home else {
let Some(home) = crate::home::folder() else {
bail!("could not find known_hosts to verify {}", login.host)
};
PathBuf::from(home).join(".ssh").join("known_hosts")
home.join(".ssh").join("known_hosts")
}
};
let mut known = raw.known_hosts().context("could not read known_hosts")?;
Expand Down Expand Up @@ -302,10 +301,8 @@ fn fingerprint(raw: &RawSession) -> String {
/// Reads aliases from `~/.ssh/config`, or `%USERPROFILE%\\.ssh\\config` when
/// HOME is unavailable (as is common on native Windows).
pub fn configured_hosts() -> Result<Vec<Host>> {
let home = std::env::var_os("HOME")
.or_else(|| std::env::var_os("USERPROFILE"))
.context("could not find your home folder")?;
let path = PathBuf::from(home).join(".ssh").join("config");
let home = crate::home::folder().context("could not find your home folder")?;
let path = home.join(".ssh").join("config");
match std::fs::read_to_string(&path) {
Ok(text) => Ok(parse_hosts(&text)),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
Expand Down
2 changes: 1 addition & 1 deletion crates/gitrust-ui/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -690,7 +690,7 @@ impl App {
Browsing::Folder { .. } => chooser::folder("Choose a repository folder"),
Browsing::Key { .. } => chooser::file(
"Choose a private key",
std::env::var_os("HOME").map(|home| std::path::PathBuf::from(home).join(".ssh")),
gitrust_core::home::folder().map(|home| home.join(".ssh")),
),
});
});
Expand Down
4 changes: 3 additions & 1 deletion crates/gitrust-ui/src/picker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,9 @@ fn buttons(
// Somewhere to start from, since a clone needs a folder
// to land beside and typing a whole path to say "here" is
// a lot of typing.
state.beside = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
state.beside = gitrust_core::home::folder()
.map(|home| home.display().to_string())
.unwrap_or_else(|| ".".to_string());
}
}
}
Expand Down
Loading