дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-27 21:12:34 +02:00
Порівняти коміти
4
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
dc7109526b | ||
|
|
de0f9d6ecd | ||
|
|
6d55eb4aa9 | ||
|
|
a247f1ce67 |
No files matched your search
Створено
+1
-23
@@ -2163,15 +2163,6 @@ dependencies = [
|
||||
"rustc_version",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "file-id"
|
||||
version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e1fc6a637b6dc58414714eddd9170ff187ecb0933d4c7024d1abbd23a3cc26e9"
|
||||
dependencies = [
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "filedescriptor"
|
||||
version = "0.8.3"
|
||||
@@ -4691,7 +4682,7 @@ dependencies = [
|
||||
"globset",
|
||||
"ide-core",
|
||||
"ignore",
|
||||
"notify-debouncer-full",
|
||||
"notify",
|
||||
"parking_lot",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -5638,19 +5629,6 @@ dependencies = [
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "notify-debouncer-full"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "375bd3a138be7bfeff3480e4a623df4cbfb55b79df617c055cd810ba466fa078"
|
||||
dependencies = [
|
||||
"file-id",
|
||||
"log",
|
||||
"notify",
|
||||
"notify-types",
|
||||
"walkdir",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "notify-types"
|
||||
version = "2.1.0"
|
||||
|
||||
@@ -76,7 +76,6 @@ ignore = "0.4"
|
||||
base64 = "0.22"
|
||||
globset = "0.4"
|
||||
notify = "8"
|
||||
notify-debouncer-full = "0.6"
|
||||
trash = "5"
|
||||
blake3 = "1"
|
||||
dunce = "1"
|
||||
|
||||
+113
-15
@@ -213,6 +213,8 @@ pub struct DbManager {
|
||||
/// App-wide SSH connections and host-key trust.
|
||||
ssh: Arc<SshManager>,
|
||||
saved_passwords: SecretStore,
|
||||
/// Directory of the global data sources and their saved passwords ([`DbManager::with_global_sources`]).
|
||||
global: Option<(PathBuf, SecretStore)>,
|
||||
history: Arc<HistoryStore>,
|
||||
/// Records executed statements in the history off the async threads, in order.
|
||||
recorder: std::sync::mpsc::Sender<(String, String, f64)>,
|
||||
@@ -339,6 +341,7 @@ impl DbManager {
|
||||
}
|
||||
Self {
|
||||
saved_passwords: SecretStore::new(passwords, &root),
|
||||
global: None,
|
||||
history,
|
||||
recorder,
|
||||
root,
|
||||
@@ -351,8 +354,42 @@ impl DbManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Also lists the global data sources stored in `dir` (the app data directory).
|
||||
pub fn with_global_sources(mut self, dir: PathBuf) -> Self {
|
||||
let passwords = self.saved_passwords.scoped(&dir);
|
||||
self.global = Some((dir, passwords));
|
||||
self
|
||||
}
|
||||
|
||||
/// The project's data sources, then the global ones (a project one wins on the same id).
|
||||
pub fn sources(&self) -> IdeResult<Vec<DataSource>> {
|
||||
source::load(&self.root)
|
||||
let mut all = source::load(&self.root)?;
|
||||
let global: Vec<_> = self.global_sources().into_iter().filter(|g| all.iter().all(|s| s.id != g.id)).collect();
|
||||
all.extend(global);
|
||||
Ok(all)
|
||||
}
|
||||
|
||||
fn global_sources(&self) -> Vec<DataSource> {
|
||||
let Some((dir, _)) = &self.global else { return Vec::new() };
|
||||
source::load_global(dir).unwrap_or_else(|e| {
|
||||
tracing::warn!("global data sources: {}", e.message);
|
||||
Vec::new()
|
||||
})
|
||||
}
|
||||
|
||||
/// Where the saved passwords of data source `id` live: app-wide for a global one.
|
||||
fn saved_for(&self, id: &str) -> &SecretStore {
|
||||
match &self.global {
|
||||
Some((_, store)) if self.global_sources().iter().any(|s| s.id == id) => store,
|
||||
_ => &self.saved_passwords,
|
||||
}
|
||||
}
|
||||
|
||||
fn store_of(&self, source: &DataSource) -> &SecretStore {
|
||||
match &self.global {
|
||||
Some((_, store)) if source.global => store,
|
||||
_ => &self.saved_passwords,
|
||||
}
|
||||
}
|
||||
|
||||
/// The connection settings of target `target` ([`DataSource::resolved`]), with
|
||||
@@ -372,18 +409,43 @@ impl DbManager {
|
||||
}
|
||||
|
||||
/// Saves the data source list; connections of removed or changed sources are closed.
|
||||
/// Global ones (`global`) go to the app-wide list, the others to the project's.
|
||||
pub async fn save_sources(&self, sources: Vec<DataSource>) -> IdeResult<()> {
|
||||
let old = self.sources().unwrap_or_default();
|
||||
source::save(&self.root, &sources)?;
|
||||
let (global, project): (Vec<_>, Vec<_>) = sources.iter().cloned().partition(|s| s.global);
|
||||
match &self.global {
|
||||
// Rewritten only when it changes: other projects' windows edit the same file.
|
||||
Some((dir, _)) => {
|
||||
if global != old.iter().filter(|s| s.global).cloned().collect::<Vec<_>>() {
|
||||
source::save_global(dir, &global)?;
|
||||
}
|
||||
}
|
||||
None if !global.is_empty() => return Err(IdeError::invalid("global data sources are not available here")),
|
||||
None => {}
|
||||
}
|
||||
source::save(&self.root, &project)?;
|
||||
for o in old {
|
||||
match sources.iter().find(|s| s.id == o.id) {
|
||||
Some(n) if *n == o => {}
|
||||
gone_or_changed => {
|
||||
if gone_or_changed.is_none() {
|
||||
for k in [o.id.clone(), secrets::ssh_key(&o.id)] {
|
||||
self.session_passwords.lock().remove(&k);
|
||||
self.saved_passwords.delete(&k);
|
||||
let keys = [o.id.clone(), secrets::ssh_key(&o.id)];
|
||||
match gone_or_changed {
|
||||
None => {
|
||||
for k in &keys {
|
||||
self.session_passwords.lock().remove(k);
|
||||
self.store_of(&o).delete(k);
|
||||
}
|
||||
}
|
||||
// Made global or project-level: its saved passwords move along.
|
||||
Some(n) if n.global != o.global => {
|
||||
for k in &keys {
|
||||
if let Some(p) = self.store_of(&o).get(k) {
|
||||
self.store_of(n).set(k, &p)?;
|
||||
self.store_of(&o).delete(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
self.disconnect_source(&o.id).await;
|
||||
}
|
||||
@@ -395,7 +457,7 @@ impl DbManager {
|
||||
/// Remembers `password` for the session, and in the saved passwords when
|
||||
/// the data source saves passwords (`None` forgets it).
|
||||
pub async fn set_password(&self, id: &str, password: Option<String>, save: bool) -> IdeResult<()> {
|
||||
self.remember(id.to_owned(), password, save).await
|
||||
self.remember(id, id.to_owned(), password, save).await
|
||||
}
|
||||
|
||||
/// [`DbManager::set_password`] for the SSH password / key passphrase.
|
||||
@@ -407,10 +469,10 @@ impl DbManager {
|
||||
self.ssh.set_secret(&c, secret, save);
|
||||
return Ok(());
|
||||
}
|
||||
self.remember(secrets::ssh_key(id), secret, save).await
|
||||
self.remember(id, secrets::ssh_key(id), secret, save).await
|
||||
}
|
||||
|
||||
async fn remember(&self, key: String, secret: Option<String>, save: bool) -> IdeResult<()> {
|
||||
async fn remember(&self, id: &str, key: String, secret: Option<String>, save: bool) -> IdeResult<()> {
|
||||
match &secret {
|
||||
Some(p) => {
|
||||
self.session_passwords.lock().insert(key.clone(), p.clone());
|
||||
@@ -419,10 +481,11 @@ impl DbManager {
|
||||
self.session_passwords.lock().remove(&key);
|
||||
}
|
||||
}
|
||||
let store = self.saved_for(id);
|
||||
let result = match (secret, save) {
|
||||
(Some(p), true) => self.saved_passwords.set(&key, &p),
|
||||
(Some(p), true) => store.set(&key, &p),
|
||||
_ => {
|
||||
self.saved_passwords.delete(&key);
|
||||
store.delete(&key);
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
@@ -433,18 +496,18 @@ impl DbManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn secret(&self, key: String, saved: bool) -> Option<String> {
|
||||
async fn secret(&self, source: &DataSource, key: String, saved: bool) -> Option<String> {
|
||||
if let Some(p) = self.session_passwords.lock().get(&key) {
|
||||
return Some(p.clone());
|
||||
}
|
||||
if !saved {
|
||||
return None;
|
||||
}
|
||||
self.saved_passwords.get(&key)
|
||||
self.store_of(source).get(&key)
|
||||
}
|
||||
|
||||
async fn password(&self, source: &DataSource) -> Option<String> {
|
||||
match self.secret(source.id.clone(), source.driver != DbDriver::Sqlite && source.save_password).await {
|
||||
match self.secret(source, source.id.clone(), source.driver != DbDriver::Sqlite && source.save_password).await {
|
||||
Some(p) => Some(p),
|
||||
None => source.url_password(),
|
||||
}
|
||||
@@ -500,7 +563,7 @@ impl DbManager {
|
||||
let session = if config.is_empty() {
|
||||
let secret = match ssh_secret {
|
||||
Some(s) => Some(s),
|
||||
None => self.secret(secrets::ssh_key(&source.id), ssh.save_secret).await,
|
||||
None => self.secret(source, secrets::ssh_key(&source.id), ssh.save_secret).await,
|
||||
};
|
||||
let target = SshTarget {
|
||||
host: ssh.host.clone(),
|
||||
@@ -1099,6 +1162,41 @@ impl DbManager {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn global_data_sources_are_shared_by_projects_with_their_passwords() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (app, one, two) = (tmp.path().join("app"), tmp.path().join("one"), tmp.path().join("two"));
|
||||
let manager = |root: &std::path::Path| {
|
||||
let ssh = Arc::new(SshManager::new(app.join("ssh-passwords.json")));
|
||||
DbManager::new(root.to_path_buf(), app.join("passwords.json"), app.join("history.json"), ssh)
|
||||
.with_global_sources(app.clone())
|
||||
};
|
||||
let (a, b) = (manager(&one), manager(&two));
|
||||
let source = |id: &str, global: bool| DataSource {
|
||||
id: id.into(),
|
||||
name: id.into(),
|
||||
driver: DbDriver::Postgres,
|
||||
save_password: true,
|
||||
global,
|
||||
..Default::default()
|
||||
};
|
||||
a.save_sources(vec![source("local", false), source("shared", false)]).await.unwrap();
|
||||
a.set_password("shared", Some("pw".into()), true).await.unwrap();
|
||||
// Made global: listed in the other project too, with its saved password.
|
||||
a.save_sources(vec![source("local", false), source("shared", true)]).await.unwrap();
|
||||
let ids = |m: &DbManager| m.sources().unwrap().into_iter().map(|s| (s.id, s.global)).collect::<Vec<_>>();
|
||||
assert_eq!(ids(&a), [("local".into(), false), ("shared".into(), true)]);
|
||||
assert_eq!(ids(&b), [("shared".into(), true)]);
|
||||
assert_eq!(b.password(&b.source("shared").unwrap()).await.as_deref(), Some("pw"));
|
||||
let project_file = std::fs::read_to_string(one.join(".openidea/data-sources.toml")).unwrap();
|
||||
assert!(!project_file.contains("shared") && !project_file.contains("global"), "{project_file}");
|
||||
assert!(!std::fs::read_to_string(app.join("data-sources.toml")).unwrap().contains("global"));
|
||||
// Made project-level again: gone from the other project, the password stays with it.
|
||||
a.save_sources(vec![source("local", false), source("shared", false)]).await.unwrap();
|
||||
assert!(b.sources().unwrap().is_empty());
|
||||
assert_eq!(a.password(&a.source("shared").unwrap()).await.as_deref(), Some("pw"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn clickhouse_rejects_manual_transactions_and_table_edits_without_connecting() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -28,6 +28,11 @@ impl SecretStore {
|
||||
Self { path, project: root.to_string_lossy().into_owned() }
|
||||
}
|
||||
|
||||
/// The same file, keyed by `scope` instead (global data sources: the app data directory).
|
||||
pub fn scoped(&self, scope: &Path) -> Self {
|
||||
Self::new(self.path.clone(), scope)
|
||||
}
|
||||
|
||||
pub fn get(&self, key: &str) -> Option<String> {
|
||||
let _g = LOCK.lock();
|
||||
self.read().remove(&self.project)?.remove(key)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Data sources: per-project connection settings in `.openidea/data-sources.toml`.
|
||||
//! Passwords never go there: saved ones live in [`crate::secrets`], the others
|
||||
//! only in memory for the session.
|
||||
//! Data sources: per-project connection settings in `.openidea/data-sources.toml`, and
|
||||
//! global ones (IDEA's Make Global: listed in every project) in `data-sources.toml` of the
|
||||
//! app data directory. Passwords never go there: saved ones live in [`crate::secrets`],
|
||||
//! the others only in memory for the session.
|
||||
|
||||
use ide_core::{IdeError, IdeResult, IpcPath, project_dir};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -181,6 +182,9 @@ pub struct DataSource {
|
||||
pub options: DbOptions,
|
||||
pub introspection: DbIntrospection,
|
||||
pub properties: Vec<DbProperty>,
|
||||
/// Stored app-wide and listed in every project. Implied by the file it is read from,
|
||||
/// so not written to it.
|
||||
pub global: bool,
|
||||
}
|
||||
|
||||
impl Default for DataSource {
|
||||
@@ -209,6 +213,7 @@ impl Default for DataSource {
|
||||
options: DbOptions::default(),
|
||||
introspection: DbIntrospection::default(),
|
||||
properties: Vec::new(),
|
||||
global: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -397,9 +402,32 @@ struct SourcesFile {
|
||||
sources: Vec<DataSource>,
|
||||
}
|
||||
|
||||
/// The project's data sources.
|
||||
pub fn load(root: &Path) -> IdeResult<Vec<DataSource>> {
|
||||
let path = project_dir::path(root, FILE);
|
||||
let text = match std::fs::read_to_string(&path) {
|
||||
read(&project_dir::path(root, FILE))
|
||||
}
|
||||
|
||||
/// Saves the project's data sources.
|
||||
pub fn save(root: &Path, sources: &[DataSource]) -> IdeResult<()> {
|
||||
write(&project_dir::path(root, FILE), sources)
|
||||
}
|
||||
|
||||
/// The global data sources stored in `dir` (the app data directory).
|
||||
pub fn load_global(dir: &Path) -> IdeResult<Vec<DataSource>> {
|
||||
let mut sources = read(&dir.join(FILE))?;
|
||||
for s in &mut sources {
|
||||
s.global = true;
|
||||
}
|
||||
Ok(sources)
|
||||
}
|
||||
|
||||
/// Saves the global data sources in `dir`.
|
||||
pub fn save_global(dir: &Path, sources: &[DataSource]) -> IdeResult<()> {
|
||||
write(&dir.join(FILE), sources)
|
||||
}
|
||||
|
||||
fn read(path: &Path) -> IdeResult<Vec<DataSource>> {
|
||||
let text = match std::fs::read_to_string(path) {
|
||||
Ok(t) => t,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
|
||||
Err(e) => return Err(e.into()),
|
||||
@@ -408,19 +436,23 @@ pub fn load(root: &Path) -> IdeResult<Vec<DataSource>> {
|
||||
Ok(file.sources)
|
||||
}
|
||||
|
||||
pub fn save(root: &Path, sources: &[DataSource]) -> IdeResult<()> {
|
||||
fn write(path: &Path, sources: &[DataSource]) -> IdeResult<()> {
|
||||
for s in sources {
|
||||
if s.id.is_empty() || s.name.trim().is_empty() {
|
||||
return Err(IdeError::invalid("every data source needs an id and a name"));
|
||||
}
|
||||
}
|
||||
let path = project_dir::path(root, FILE);
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
let text = toml::to_string_pretty(&SourcesFile { sources: sources.to_vec() })
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
std::fs::write(path, text)?;
|
||||
let internal = |e: &dyn std::fmt::Display| IdeError::internal(e.to_string());
|
||||
let mut value = toml::Value::try_from(SourcesFile { sources: sources.to_vec() }).map_err(|e| internal(&e))?;
|
||||
if let Some(list) = value.get_mut("data-source").and_then(toml::Value::as_array_mut) {
|
||||
for table in list.iter_mut().filter_map(toml::Value::as_table_mut) {
|
||||
table.remove("global");
|
||||
}
|
||||
}
|
||||
std::fs::write(path, toml::to_string_pretty(&value).map_err(|e| internal(&e))?)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -364,7 +364,7 @@ pub fn package_hash(dir: &Path, files: &[PathBuf]) -> std::io::Result<String> {
|
||||
sorted.dedup();
|
||||
let mut hasher = blake3::Hasher::new();
|
||||
for rel in sorted {
|
||||
hasher.update(rel.to_string_lossy().as_bytes());
|
||||
hasher.update(hashed_path(rel).as_bytes());
|
||||
hasher.update(&[0]);
|
||||
hasher.update_reader(std::fs::File::open(dir.join(rel))?)?;
|
||||
hasher.update(&[0]);
|
||||
@@ -372,6 +372,12 @@ pub fn package_hash(dir: &Path, files: &[PathBuf]) -> std::io::Result<String> {
|
||||
Ok(hasher.finalize().to_hex().to_string())
|
||||
}
|
||||
|
||||
/// A package-relative path as hashed: `/`-separated on every OS, so a package has one digest
|
||||
/// (a walked `web\index.html` on Windows is `web/index.html` everywhere else).
|
||||
fn hashed_path(rel: &Path) -> String {
|
||||
rel.components().map(|c| c.as_os_str().to_string_lossy()).collect::<Vec<_>>().join("/")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -480,4 +486,20 @@ mod tests {
|
||||
let groups = by_risk(&caps(&["storage", "process:git", "net:x.io"]));
|
||||
assert_eq!(groups.iter().map(|g| g.0).collect::<Vec<_>>(), [Risk::High, Risk::Medium, Risk::Low]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hashes_paths_with_forward_slashes_on_every_os() {
|
||||
assert_eq!(hashed_path(Path::new("web/index.html")), "web/index.html");
|
||||
assert_eq!(hashed_path(Path::new("plugin.wasm")), "plugin.wasm");
|
||||
#[cfg(windows)]
|
||||
assert_eq!(hashed_path(Path::new(r"web\index.html")), "web/index.html");
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir(tmp.path().join("web")).unwrap();
|
||||
std::fs::write(tmp.path().join("web").join("index.html"), "<p>").unwrap();
|
||||
// A walked path (native separators) hashes like the manifest's `/` spelling.
|
||||
assert_eq!(
|
||||
package_hash(tmp.path(), &[Path::new("web").join("index.html")]).unwrap(),
|
||||
package_hash(tmp.path(), &["web/index.html".into()]).unwrap()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -520,12 +520,15 @@ impl Host {
|
||||
root: &Path,
|
||||
project_key: &str,
|
||||
) -> (Arc<ide_db::DbManager>, Arc<ide_http::History>, Arc<ide_agent::AgentManager>) {
|
||||
let db = Arc::new(ide_db::DbManager::new(
|
||||
root.to_path_buf(),
|
||||
self.data_dir.join("db-passwords.json"),
|
||||
self.data_dir.join("db-history.json"),
|
||||
self.ssh.clone(),
|
||||
));
|
||||
let db = Arc::new(
|
||||
ide_db::DbManager::new(
|
||||
root.to_path_buf(),
|
||||
self.data_dir.join("db-passwords.json"),
|
||||
self.data_dir.join("db-history.json"),
|
||||
self.ssh.clone(),
|
||||
)
|
||||
.with_global_sources(self.data_dir.clone()),
|
||||
);
|
||||
let http_history = Arc::new(ide_http::History::new(self.data_dir.join("http-history").join(project_key)));
|
||||
let agents = Arc::new(ide_agent::AgentManager::new(
|
||||
ide_agent::AgentPaths {
|
||||
|
||||
@@ -13,7 +13,7 @@ serde.workspace = true
|
||||
specta.workspace = true
|
||||
ignore.workspace = true
|
||||
globset.workspace = true
|
||||
notify-debouncer-full.workspace = true
|
||||
notify.workspace = true
|
||||
encoding_rs.workspace = true
|
||||
chardetng.workspace = true
|
||||
trash.workspace = true
|
||||
|
||||
@@ -12,9 +12,8 @@
|
||||
use crate::FsBatch;
|
||||
use crate::rules::{ExcludeMatcher, GitignoreStack};
|
||||
use ide_core::{IdeError, IdeEvent, IdeResult, SharedSink};
|
||||
use notify_debouncer_full::notify::event::{ModifyKind, RenameMode};
|
||||
use notify_debouncer_full::notify::{self, EventKind, PollWatcher, RecommendedWatcher, RecursiveMode, WatcherKind};
|
||||
use notify_debouncer_full::{DebounceEventResult, DebouncedEvent, Debouncer, NoCache, new_debouncer_opt};
|
||||
use notify::event::{ModifyKind, RenameMode};
|
||||
use notify::{Event, EventKind, PollWatcher, RecommendedWatcher, RecursiveMode, WatcherKind};
|
||||
use parking_lot::{Condvar, Mutex, RwLock};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
@@ -62,10 +61,9 @@ pub struct Watcher {
|
||||
|
||||
type SharedExcludes = Arc<RwLock<ExcludeMatcher>>;
|
||||
|
||||
enum Inner {
|
||||
Recursive(#[allow(dead_code)] Debouncer<RecommendedWatcher, NoCache>),
|
||||
Polling(#[allow(dead_code)] Debouncer<PollWatcher, NoCache>),
|
||||
PerDirectory { state: Arc<DirState>, thread: Option<JoinHandle<()>> },
|
||||
struct Inner {
|
||||
state: Arc<DirState>,
|
||||
thread: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl Watcher {
|
||||
@@ -131,80 +129,32 @@ impl Watcher {
|
||||
|
||||
/// Number of OS-level watches (1 in recursive and flat mode).
|
||||
pub fn watch_count(&self) -> usize {
|
||||
match &self.inner {
|
||||
Inner::Recursive(_) | Inner::Polling(_) => 1,
|
||||
Inner::PerDirectory { state, .. } => state.watched.lock().len(),
|
||||
}
|
||||
self.inner.state.watched.lock().len()
|
||||
}
|
||||
|
||||
fn start_native(root: &Path, filter: EventFilter, emit: Emit, mode: WatchMode) -> IdeResult<Inner> {
|
||||
let config = notify::Config::default();
|
||||
match mode {
|
||||
WatchMode::Recursive => {
|
||||
Self::start_debounced(root, filter, emit, RecursiveMode::Recursive, config).map(Inner::Recursive)
|
||||
}
|
||||
WatchMode::Flat => {
|
||||
Self::start_debounced(root, filter, emit, RecursiveMode::NonRecursive, config).map(Inner::Recursive)
|
||||
}
|
||||
WatchMode::PerDirectory => Self::start_per_directory::<RecommendedWatcher>(root, filter, emit, config),
|
||||
}
|
||||
Self::start_queued::<RecommendedWatcher>(root, filter, emit, mode, notify::Config::default())
|
||||
}
|
||||
|
||||
/// Polls per directory unless flat: a recursive poll would rescan
|
||||
/// `node_modules` and `target` every round.
|
||||
fn start_polling(root: &Path, filter: EventFilter, emit: Emit, mode: WatchMode) -> IdeResult<Inner> {
|
||||
let config = notify::Config::default().with_poll_interval(POLL_INTERVAL);
|
||||
match mode {
|
||||
WatchMode::Flat => {
|
||||
Self::start_debounced(root, filter, emit, RecursiveMode::NonRecursive, config).map(Inner::Polling)
|
||||
}
|
||||
WatchMode::Recursive | WatchMode::PerDirectory => {
|
||||
Self::start_per_directory::<PollWatcher>(root, filter, emit, config)
|
||||
}
|
||||
}
|
||||
let mode = if mode == WatchMode::Flat { mode } else { WatchMode::PerDirectory };
|
||||
Self::start_queued::<PollWatcher>(root, filter, emit, mode, config)
|
||||
}
|
||||
|
||||
fn start_debounced<W: notify::Watcher>(
|
||||
root: &Path,
|
||||
filter: EventFilter,
|
||||
emit: Emit,
|
||||
recursive: RecursiveMode,
|
||||
config: notify::Config,
|
||||
) -> IdeResult<Debouncer<W, NoCache>> {
|
||||
let polled = W::kind() == WatcherKind::PollWatcher;
|
||||
// No file-id cache: building it walks and stats the whole tree before `watch` returns,
|
||||
// which made opening large projects block for seconds. Renames arrive as remove + create.
|
||||
let handler = move |result: DebounceEventResult| match result {
|
||||
Ok(mut events) => {
|
||||
if polled {
|
||||
events.retain(|e| !is_dir_touch(&e.event));
|
||||
}
|
||||
let (batch, _) = filter.batch_detailed(&events);
|
||||
if !batch.is_empty() {
|
||||
emit(&batch);
|
||||
}
|
||||
}
|
||||
Err(errors) => {
|
||||
for e in errors {
|
||||
tracing::warn!("file watcher: {e}");
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut debouncer = new_debouncer_opt::<_, W, _>(DEBOUNCE, None, handler, NoCache, config)
|
||||
.map_err(|e| io_error(format!("cannot start file watcher: {e}")))?;
|
||||
debouncer.watch(root, recursive).map_err(|e| io_error(format!("cannot watch {}: {e}", root.display())))?;
|
||||
Ok(debouncer)
|
||||
}
|
||||
|
||||
fn start_per_directory<W: notify::Watcher + Send + 'static>(
|
||||
fn start_queued<W: notify::Watcher + Send + 'static>(
|
||||
root: &Path,
|
||||
filter: EventFilter,
|
||||
emit: Emit,
|
||||
mode: WatchMode,
|
||||
config: notify::Config,
|
||||
) -> IdeResult<Inner> {
|
||||
let polled = W::kind() == WatcherKind::PollWatcher;
|
||||
let state = Arc::new(DirState {
|
||||
filter,
|
||||
mode,
|
||||
watcher: Mutex::new(None),
|
||||
watched: Mutex::default(),
|
||||
queue: Mutex::default(),
|
||||
@@ -228,8 +178,11 @@ impl Watcher {
|
||||
)
|
||||
.map_err(|e| io_error(format!("cannot start file watcher: {e}")))?;
|
||||
*state.watcher.lock() = Some(Box::new(watcher));
|
||||
let mut created = Vec::new();
|
||||
state.watch_tree(root, false, &mut created);
|
||||
if mode == WatchMode::PerDirectory {
|
||||
state.watch_tree(root, false, &mut Vec::new());
|
||||
} else {
|
||||
state.add_watch(root);
|
||||
}
|
||||
if state.watched.lock().is_empty() {
|
||||
return Err(io_error(format!("cannot watch {}", root.display())));
|
||||
}
|
||||
@@ -240,20 +193,22 @@ impl Watcher {
|
||||
.spawn(move || state.run(&*emit))
|
||||
.map_err(|e| io_error(format!("cannot start file watcher: {e}")))?
|
||||
};
|
||||
Ok(Inner::PerDirectory { state, thread: Some(thread) })
|
||||
Ok(Inner { state, thread: Some(thread) })
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Watcher {
|
||||
impl Drop for Inner {
|
||||
fn drop(&mut self) {
|
||||
if let Inner::PerDirectory { state, thread } = &mut self.inner {
|
||||
let state = &self.state;
|
||||
{
|
||||
let _queue = state.queue.lock();
|
||||
state.stop.store(true, Ordering::SeqCst);
|
||||
state.wake.notify_all();
|
||||
let watcher = state.watcher.lock().take();
|
||||
drop(watcher);
|
||||
if let Some(t) = thread.take() {
|
||||
let _ = t.join();
|
||||
}
|
||||
}
|
||||
let watcher = state.watcher.lock().take();
|
||||
drop(watcher);
|
||||
if let Some(t) = self.thread.take() {
|
||||
let _ = t.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -268,10 +223,10 @@ fn is_dir_touch(event: ¬ify::Event) -> bool {
|
||||
matches!(event.kind, EventKind::Modify(_)) && event.paths.iter().all(|p| p.is_dir())
|
||||
}
|
||||
|
||||
/// State of the per-directory strategy, shared with the notify callback
|
||||
/// (weakly) and the debounce thread.
|
||||
/// Shared with the notify callback (weakly) and the debounce thread.
|
||||
struct DirState {
|
||||
filter: EventFilter,
|
||||
mode: WatchMode,
|
||||
watcher: Mutex<Option<Box<dyn notify::Watcher + Send>>>,
|
||||
watched: Mutex<HashSet<PathBuf>>,
|
||||
queue: Mutex<Vec<(notify::Event, Instant)>>,
|
||||
@@ -310,9 +265,13 @@ impl DirState {
|
||||
}
|
||||
std::mem::take(&mut *q)
|
||||
};
|
||||
let events: Vec<DebouncedEvent> = events.into_iter().map(|(e, t)| DebouncedEvent::new(e, t)).collect();
|
||||
// A scan may publish a path before its create event is delivered:
|
||||
// keep create + remove pairs so the consumer still sees the removal.
|
||||
let events: Vec<Event> = events.into_iter().map(|(e, _)| e).collect();
|
||||
let (mut batch, rule_dirs) = self.filter.batch_detailed(&events);
|
||||
self.update_watches(&mut batch, &rule_dirs);
|
||||
if self.mode == WatchMode::PerDirectory {
|
||||
self.update_watches(&mut batch, &rule_dirs);
|
||||
}
|
||||
if !batch.is_empty() && !self.stopped() {
|
||||
emit(&batch);
|
||||
}
|
||||
@@ -363,7 +322,9 @@ impl DirState {
|
||||
}
|
||||
let mut guard = self.watcher.lock();
|
||||
let Some(w) = guard.as_mut() else { return false };
|
||||
match w.watch(dir, RecursiveMode::NonRecursive) {
|
||||
let recursive =
|
||||
if self.mode == WatchMode::Recursive { RecursiveMode::Recursive } else { RecursiveMode::NonRecursive };
|
||||
match w.watch(dir, recursive) {
|
||||
Ok(()) => {
|
||||
self.watched.lock().insert(dir.to_path_buf());
|
||||
true
|
||||
@@ -555,17 +516,17 @@ impl EventFilter {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn batch(&self, events: &[DebouncedEvent]) -> FsBatch {
|
||||
pub fn batch(&self, events: &[Event]) -> FsBatch {
|
||||
self.batch_detailed(events).0
|
||||
}
|
||||
|
||||
/// The coalesced, filtered batch plus the directories whose ignore rules
|
||||
/// changed (their cached matchers have been rebuilt already).
|
||||
pub fn batch_detailed(&self, events: &[DebouncedEvent]) -> (FsBatch, Vec<PathBuf>) {
|
||||
pub fn batch_detailed(&self, events: &[Event]) -> (FsBatch, Vec<PathBuf>) {
|
||||
let mut changes: BTreeMap<PathBuf, Change> = BTreeMap::new();
|
||||
for ev in events {
|
||||
let paths = &ev.event.paths;
|
||||
match ev.event.kind {
|
||||
let paths = &ev.paths;
|
||||
match ev.kind {
|
||||
EventKind::Access(_) => {}
|
||||
EventKind::Create(_) => paths.iter().for_each(|p| self.classify(p, Change::Created, &mut changes)),
|
||||
EventKind::Remove(_) => paths.iter().for_each(|p| self.classify(p, Change::Removed, &mut changes)),
|
||||
@@ -601,7 +562,7 @@ impl EventFilter {
|
||||
rule_dirs.insert(dir.to_path_buf());
|
||||
}
|
||||
}
|
||||
if events.iter().flat_map(|e| &e.event.paths).any(|p| p.ends_with(".git/info/exclude")) {
|
||||
if events.iter().flat_map(|e| &e.paths).any(|p| p.ends_with(".git/info/exclude")) {
|
||||
self.gitignore.reload_repo_level();
|
||||
rule_dirs.insert(self.root.clone());
|
||||
}
|
||||
@@ -669,11 +630,125 @@ impl EventFilter {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use notify_debouncer_full::notify::Event;
|
||||
use notify_debouncer_full::notify::event::{CreateKind, DataChange, RemoveKind};
|
||||
use notify::event::{CreateKind, DataChange, RemoveKind};
|
||||
|
||||
fn ev(kind: EventKind, paths: Vec<PathBuf>) -> DebouncedEvent {
|
||||
DebouncedEvent::new(Event { kind, paths, attrs: Default::default() }, Instant::now())
|
||||
fn ev(kind: EventKind, paths: Vec<PathBuf>) -> Event {
|
||||
Event { kind, paths, attrs: Default::default() }
|
||||
}
|
||||
|
||||
const TRANSIENT_PATHS: &[&str] = &["fresh.txt", "src/fresh.rs", "src/tasks/fresh.py"];
|
||||
|
||||
/// Delivers a whole debounce window without depending on OS scheduling.
|
||||
struct TransientWatcher(Box<dyn notify::EventHandler>);
|
||||
|
||||
impl notify::Watcher for TransientWatcher {
|
||||
fn new<F: notify::EventHandler>(handler: F, _: notify::Config) -> notify::Result<Self> {
|
||||
Ok(Self(Box::new(handler)))
|
||||
}
|
||||
|
||||
fn watch(&mut self, root: &Path, _: RecursiveMode) -> notify::Result<()> {
|
||||
for rel in TRANSIENT_PATHS {
|
||||
for kind in [
|
||||
EventKind::Create(CreateKind::File),
|
||||
EventKind::Modify(ModifyKind::Data(DataChange::Content)),
|
||||
EventKind::Remove(RemoveKind::File),
|
||||
] {
|
||||
self.0.handle_event(Ok(Event::new(kind).add_path(root.join(rel))));
|
||||
}
|
||||
}
|
||||
for kind in [EventKind::Create(CreateKind::Folder), EventKind::Remove(RemoveKind::Folder)] {
|
||||
self.0.handle_event(Ok(Event::new(kind).add_path(root.join("new"))));
|
||||
}
|
||||
for (rel, kind) in [
|
||||
("from.py", EventKind::Create(CreateKind::File)),
|
||||
("from.py", EventKind::Modify(ModifyKind::Name(RenameMode::From))),
|
||||
("to.py", EventKind::Modify(ModifyKind::Name(RenameMode::To))),
|
||||
("to.py", EventKind::Remove(RemoveKind::File)),
|
||||
] {
|
||||
self.0.handle_event(Ok(Event::new(kind).add_path(root.join(rel))));
|
||||
}
|
||||
for kind in [EventKind::Remove(RemoveKind::File), EventKind::Create(CreateKind::File)] {
|
||||
self.0.handle_event(Ok(Event::new(kind).add_path(root.join("kept.py"))));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn unwatch(&mut self, _: &Path) -> notify::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn kind() -> WatcherKind {
|
||||
WatcherKind::NullWatcher
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debounce_preserves_transient_removals_and_atomic_replacements() {
|
||||
for mode in [WatchMode::Recursive, WatchMode::Flat, WatchMode::PerDirectory] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
std::fs::write(root.join("kept.py"), "class Kept: pass\n").unwrap();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let emit: Emit = Arc::new(move |b| tx.send(b.clone()).unwrap());
|
||||
let _watcher = Watcher::start_queued::<TransientWatcher>(
|
||||
&root,
|
||||
EventFilter::new(root.clone(), &[]),
|
||||
emit,
|
||||
mode,
|
||||
notify::Config::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let batch = rx.recv_timeout(Duration::from_secs(5)).unwrap();
|
||||
let removed: BTreeSet<_> = batch.removed.into_iter().collect();
|
||||
let expected =
|
||||
TRANSIENT_PATHS.iter().copied().chain(["new", "from.py", "to.py"]).map(|rel| root.join(rel)).collect();
|
||||
assert_eq!(removed, expected, "{mode:?}: scans may have already published transient paths");
|
||||
assert_eq!(batch.modified, vec![root.join("kept.py")]);
|
||||
assert!(batch.created.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn native_watch_reports_quickly_removed_files() {
|
||||
for mode in [WatchMode::Recursive, WatchMode::Flat, WatchMode::PerDirectory] {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
std::fs::create_dir_all(root.join("src/tasks")).unwrap();
|
||||
let batches: Arc<Mutex<Vec<FsBatch>>> = Arc::default();
|
||||
let watcher = {
|
||||
let batches = batches.clone();
|
||||
Watcher::start_with(
|
||||
&root,
|
||||
Vec::new(),
|
||||
Arc::new(ide_core::NullSink),
|
||||
Box::new(move |b| batches.lock().push(b.clone())),
|
||||
mode,
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
assert!(watcher.polling().is_none());
|
||||
assert_eq!(watcher.watch_count(), if mode == WatchMode::PerDirectory { 3 } else { 1 });
|
||||
let paths: Vec<_> = TRANSIENT_PATHS
|
||||
.iter()
|
||||
.filter(|rel| mode != WatchMode::Flat || !rel.contains('/'))
|
||||
.map(|rel| root.join(rel))
|
||||
.collect();
|
||||
for path in &paths {
|
||||
std::fs::write(path, "class FreshWidget:\n pass\n").unwrap();
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
assert!(
|
||||
wait_for(&batches, |b| paths.iter().all(|p| b.iter().any(|batch| batch.removed.contains(p)))),
|
||||
"{mode:?}: {:?}",
|
||||
batches.lock()
|
||||
);
|
||||
drop(watcher);
|
||||
let count = batches.lock().len();
|
||||
std::fs::write(root.join("after-drop.txt"), "x").unwrap();
|
||||
std::thread::sleep(DEBOUNCE * 2);
|
||||
assert_eq!(batches.lock().len(), count, "no callback after drop in {mode:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -822,8 +897,7 @@ mod tests {
|
||||
}
|
||||
let filter = EventFilter::new(root.clone(), &[]);
|
||||
let modify = EventKind::Modify(ModifyKind::Data(DataChange::Content));
|
||||
let touch =
|
||||
|paths: &[&str]| -> Vec<DebouncedEvent> { paths.iter().map(|p| ev(modify, vec![root.join(p)])).collect() };
|
||||
let touch = |paths: &[&str]| -> Vec<Event> { paths.iter().map(|p| ev(modify, vec![root.join(p)])).collect() };
|
||||
let (batch, rules) = filter.batch_detailed(&touch(&["pkg/a.tmp", "pkg/gen/x.rs", "pkg/keep.rs", "b.tmp"]));
|
||||
assert_eq!(batch.modified, vec![root.join("b.tmp"), root.join("pkg/keep.rs")]);
|
||||
assert_eq!(batch.ignored, vec![root.join("pkg/a.tmp")], "nested rules, but not inside ignored folders");
|
||||
@@ -873,10 +947,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn watcher_state(w: &Watcher) -> &DirState {
|
||||
match &w.inner {
|
||||
Inner::PerDirectory { state, .. } => state,
|
||||
Inner::Recursive(_) | Inner::Polling(_) => panic!("not per-directory"),
|
||||
}
|
||||
&w.inner.state
|
||||
}
|
||||
|
||||
fn wait_for(events: &Mutex<Vec<FsBatch>>, pred: impl Fn(&[FsBatch]) -> bool) -> bool {
|
||||
|
||||
@@ -2480,6 +2480,11 @@ export type DataSource = {
|
||||
options?: DbOptions,
|
||||
introspection?: DbIntrospection,
|
||||
properties?: DbProperty[],
|
||||
/**
|
||||
* Stored app-wide and listed in every project. Implied by the file it is read from,
|
||||
* so not written to it.
|
||||
*/
|
||||
global?: boolean,
|
||||
};
|
||||
|
||||
/** System Settings › Date Formats (Git log, Local History, blame). */
|
||||
|
||||
@@ -432,6 +432,11 @@ export function DatabaseView() {
|
||||
</span>
|
||||
)}
|
||||
<span className={labelClass}>{label(n)}</span>
|
||||
{n.kind === "source" && n.source.global && (
|
||||
<span className={styles.treeDetail} title={tx("Available in all projects")}>
|
||||
{tx("global")}
|
||||
</span>
|
||||
)}
|
||||
{d && (
|
||||
<span
|
||||
className={
|
||||
|
||||
@@ -1069,6 +1069,10 @@ export function SourceDialog({
|
||||
</span>
|
||||
)}
|
||||
/>
|
||||
{/* IDEA's Make Global: stored with the IDE and listed in every project. */}
|
||||
<span title={tx("Available in all projects")}>
|
||||
<Checkbox checked={!!s.global} onChange={(global) => set({ global })} label="Global" />
|
||||
</span>
|
||||
</div>
|
||||
<span />
|
||||
{showComment ? (
|
||||
|
||||
@@ -1956,10 +1956,9 @@ function x(lane: number) {
|
||||
return LANE / 2 + lane * LANE;
|
||||
}
|
||||
|
||||
/** Straight, also across lanes (IDEA's diagonal edges). */
|
||||
function seg(fromX: number, fromY: number, toX: number, toY: number) {
|
||||
if (fromX === toX) return `M${fromX} ${fromY}L${toX} ${toY}`;
|
||||
const mid = (fromY + toY) / 2;
|
||||
return `M${fromX} ${fromY}C${fromX} ${mid} ${toX} ${mid} ${toX} ${toY}`;
|
||||
return `M${fromX} ${fromY}L${toX} ${toY}`;
|
||||
}
|
||||
|
||||
export function GraphCell({
|
||||
@@ -2008,9 +2007,11 @@ export function GraphCell({
|
||||
if (canNavigate) onNavigate?.(s.targetRow!, target);
|
||||
else if (canFragment) onFragment?.(target!, !!s.dashed, s.source);
|
||||
};
|
||||
const fromX = x(s.fromX ?? s.from);
|
||||
const toX = x(s.toX ?? s.to);
|
||||
const path =
|
||||
seg(x(s.from), up ? 0 : cy, x(s.to), up ? cy : ROW) +
|
||||
(s.arrow ? arrowHead(x(up ? s.from : s.to), up ? 0 : ROW, up ? -1 : 1) : "");
|
||||
seg(fromX, up ? 0 : cy, toX, up ? cy : ROW) +
|
||||
(s.arrow ? arrowHead(up ? fromX : toX, up ? 0 : ROW, up ? -1 : 1) : "");
|
||||
return (
|
||||
<g
|
||||
key={`${up ? "u" : "d"}${i}`}
|
||||
@@ -2033,9 +2034,9 @@ export function GraphCell({
|
||||
>
|
||||
<title>{label}</title>
|
||||
<rect
|
||||
x={Math.min(x(s.from), x(s.to)) - 5}
|
||||
x={Math.min(fromX, toX) - 5}
|
||||
y={up ? 0 : cy}
|
||||
width={Math.max(10, Math.abs(x(s.from) - x(s.to)) + 10)}
|
||||
width={Math.max(10, Math.abs(fromX - toX) + 10)}
|
||||
height={cy}
|
||||
fill="transparent"
|
||||
pointerEvents="none"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { computeGraph } from "../graph";
|
||||
import { computeGraph, straightenLaneChanges } from "../graph";
|
||||
|
||||
const c = (id: string, ...parents: string[]) => ({ id, parents });
|
||||
|
||||
@@ -62,3 +62,47 @@ describe("computeGraph", () => {
|
||||
expect(m2.down).toContainEqual({ from: m2.lane, to: 0, color: rows[0]!.color });
|
||||
});
|
||||
});
|
||||
|
||||
describe("straightenLaneChanges", () => {
|
||||
it("draws a lane change as one diagonal across the row boundary, keeping the lanes", () => {
|
||||
// m merges f into main; f branched from a; b sits in lane 0 while lane 1 passes it.
|
||||
const rows = straightenLaneChanges(computeGraph([c("m", "b", "f"), c("f", "a"), c("b", "a"), c("a")]).rows);
|
||||
const [m, f, b, a] = rows;
|
||||
// m → f: leaves m's node towards lane 1 and reaches f's node in a straight line.
|
||||
expect(m!.down[1]).toMatchObject({ from: 0, to: 1, toX: 0.5 });
|
||||
expect(f!.up.find((s) => s.from === 1)).toMatchObject({ from: 1, to: 1, fromX: 0.5 });
|
||||
// Lane 1 converging into a: the vertical line of b's row meets it halfway.
|
||||
expect(a!.up[1]).toMatchObject({ from: 1, to: 0, fromX: 0.5 });
|
||||
expect(b!.down.find((s) => s.from === 1)).toMatchObject({ from: 1, to: 1, toX: 0.5 });
|
||||
// Straight lines stay where they are.
|
||||
expect(m!.down[0]!.toX).toBeUndefined();
|
||||
expect(a!.up[0]!.fromX).toBeUndefined();
|
||||
});
|
||||
|
||||
it("leaves a lane that another line also ends in, and arrows, as they are", () => {
|
||||
const rows = straightenLaneChanges([
|
||||
{
|
||||
lane: 0,
|
||||
color: 0,
|
||||
up: [],
|
||||
down: [
|
||||
{ from: 0, to: 1, color: 0 },
|
||||
{ from: 1, to: 1, color: 1 },
|
||||
],
|
||||
width: 2,
|
||||
},
|
||||
{
|
||||
lane: 1,
|
||||
color: 1,
|
||||
up: [{ from: 1, to: 1, color: 1 }],
|
||||
down: [{ from: 1, to: 2, color: 1, arrow: "down" }],
|
||||
width: 3,
|
||||
},
|
||||
{ lane: 2, color: 1, up: [{ from: 2, to: 2, color: 1 }], down: [], width: 3 },
|
||||
]);
|
||||
expect(rows[0]!.down[0]!.toX).toBeUndefined();
|
||||
expect(rows[1]!.up[0]!.fromX).toBeUndefined();
|
||||
expect(rows[1]!.down[0]!.toX).toBeUndefined();
|
||||
expect(rows[2]!.up[0]!.fromX).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -21,6 +21,9 @@ export interface GraphSegment {
|
||||
arrow?: "up" | "down";
|
||||
/** Destination row of a long-edge arrow in the displayed graph. */
|
||||
targetRow?: number;
|
||||
/** Drawn lane positions when they differ from `from` / `to` (see {@link straightenLaneChanges}). */
|
||||
fromX?: number;
|
||||
toX?: number;
|
||||
}
|
||||
|
||||
export interface GraphRow {
|
||||
@@ -503,6 +506,43 @@ export function hideLongEdges(rows: readonly GraphRow[], minLength = LONG_EDGE):
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws a lane change as one straight diagonal across the row boundary, like IDEA: a half-row
|
||||
* segment that changes lane and the vertical half of the neighbouring row that continues it meet
|
||||
* halfway between the two lanes. Only the drawn positions change; `from` / `to` stay the lanes.
|
||||
*/
|
||||
export function straightenLaneChanges(rows: readonly GraphRow[]): GraphRow[] {
|
||||
const out = rows.map((r) => ({ ...r, up: [...r.up], down: [...r.down] }));
|
||||
const vertical = (s: GraphSegment, lane: number) => s.from === lane && s.to === lane && !s.arrow;
|
||||
for (let r = 0; r < out.length; r++) {
|
||||
const row = out[r]!;
|
||||
// Leaving the node towards another lane: continues straight down in the next row.
|
||||
const next = out[r + 1];
|
||||
// Another line ending at the same lane (a merge into a lane that continues) keeps its position.
|
||||
const shared = (list: readonly GraphSegment[], lane: number, end: "from" | "to") =>
|
||||
list.filter((x) => x[end] === lane).length > 1;
|
||||
row.down.forEach((s, i) => {
|
||||
if (s.from === s.to || s.arrow || !next || shared(row.down, s.to, "to")) return;
|
||||
const j = next.up.findIndex((u) => vertical(u, s.to) && u.edge === s.edge && u.fromX === undefined);
|
||||
if (j < 0) return;
|
||||
const mid = (s.from + s.to) / 2;
|
||||
row.down[i] = { ...s, toX: mid };
|
||||
next.up[j] = { ...next.up[j]!, fromX: mid };
|
||||
});
|
||||
// Converging into the node from another lane: continues a vertical line of the previous row.
|
||||
const prev = out[r - 1];
|
||||
row.up.forEach((s, i) => {
|
||||
if (s.from === s.to || s.arrow || !prev || shared(prev.down, s.from, "to")) return;
|
||||
const j = prev.down.findIndex((d) => vertical(d, s.from) && d.edge === s.edge && d.toX === undefined);
|
||||
if (j < 0) return;
|
||||
const mid = (s.from + s.to) / 2;
|
||||
row.up[i] = { ...s, fromX: mid };
|
||||
prev.down[j] = { ...prev.down[j]!, toX: mid };
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Lane colours (tokens), cycled by colour index. */
|
||||
export const LANE_COLORS = [
|
||||
"var(--accent)",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { collapseLinear, computeGraph, hideLongEdges, linearizeMerges } from "./graph";
|
||||
import { collapseLinear, computeGraph, hideLongEdges, linearizeMerges, straightenLaneChanges } from "./graph";
|
||||
import { commitKey, graphCommit, type RepoCommit } from "./multiRoot";
|
||||
import type { LogOptions } from "./logOptions";
|
||||
|
||||
@@ -26,5 +26,6 @@ export function presentLogGraph(
|
||||
const byId = new Map(all.map((c) => [commitKey(c), c]));
|
||||
const commits = graph.map((c) => byId.get(c.id)!);
|
||||
const laid = computeGraph(graph).rows;
|
||||
return { commits, graph, rows: options.longEdges ? laid : hideLongEdges(laid), linear, collapsed };
|
||||
const rows = straightenLaneChanges(options.longEdges ? laid : hideLongEdges(laid));
|
||||
return { commits, graph, rows, linear, collapsed };
|
||||
}
|
||||
@@ -4242,6 +4242,8 @@
|
||||
"Root markers": "根标记",
|
||||
"Initialization options": "初始化选项",
|
||||
"Global": "全局",
|
||||
"global": "全局",
|
||||
"Available in all projects": "在所有项目中可用",
|
||||
"This project": "此项目",
|
||||
"Executable name or path": "可执行文件名或路径",
|
||||
"Select the server executable": "选择服务器可执行文件",
|
||||
|
||||
Reference in new issue
Заблокувати користувача