feat(core): the project folder, remembered per environment

CODE-HEALTH-SPEC §3 persists the folder Health runs in per environment, and gives the
detection order for declared dependencies. Both land here, ahead of anything that runs a
tool.

Per environment rather than globally because deptry's question is "declared versus
installed" — the same folder against a different env is a different answer, so one
remembered folder would make the second env's report quietly wrong.

Its own table rather than a `kv` row: `kv` is documented for scalars that do not deserve
one, and this is keyed and carries a second column. The upsert is the mechanism, not a
detail — env_hash is the primary key, so a plain INSERT would fail the second time the user
picked a folder and their choice would silently not stick. SCHEMA_VERSION 2 -> 3, which is
bookkeeping: migrate() is one idempotent CREATE TABLE IF NOT EXISTS batch and nothing reads
user_version back.

pyproject.toml wins outright over a requirements.txt beside it rather than merging with it,
because that is deptry's own precedence and reporting both would invite the UI to explain a
distinction deptry did not make. Requirements matching is case-insensitive: Windows
filesystems are, and a case-sensitive check would report "nothing declared" for a project
that plainly declares things.

Declaring nothing is a state, not a failure — §3's limited-mode notice. Only a folder that
cannot be read at all is an error.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 5 committed 2026-08-12 23:31:37 +07:00
1 parent 90863d8459
commit 15b5ed292f
3 files changed
+260 -3

No files matched your search

+4
View File
@@ -4,6 +4,10 @@
//! **report-only**, and the sole write path is `ruff --fix` / `ruff format` behind an explicit
//! confirm. PipDock never edits `pyproject.toml` or `requirements.txt` for the user.
pub mod project;
pub use project::{DeclaredSource, declared_source};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
+163
View File
@@ -0,0 +1,163 @@
//! The project folder Code Health runs in, and what it declares its dependencies in.
//!
//! CODE-HEALTH-SPEC §3: the folder is persisted per environment, and the detection order for
//! declared dependencies is `pyproject.toml` → `requirements*.txt` → none.
use std::path::Path;
use crate::errors::{Code, PdError, Result};
/// Where the project declares its dependencies, if anywhere.
///
/// deptry needs one of these to have anything to compare against. `None` is not an error — it is
/// the "limited-mode notice" §3 asks the UI to show, and the other two tools do not care.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum DeclaredSource {
/// A `pyproject.toml`, which is what deptry prefers.
Pyproject,
/// One or more `requirements*.txt`, named so the UI can say which.
#[serde(rename_all = "camelCase")]
Requirements {
/// File names, sorted, relative to the project folder.
files: Vec<String>,
},
/// Neither. deptry runs in limited mode and its findings mean less.
None,
}
impl DeclaredSource {
/// Whether deptry has anything to compare imports against.
#[must_use]
pub const fn is_declared(&self) -> bool {
!matches!(self, Self::None)
}
}
/// What `project` declares its dependencies in (CODE-HEALTH-SPEC §3's detection order).
///
/// `pyproject.toml` wins outright when present, rather than being merged with any
/// `requirements*.txt` beside it. That is deptry's own precedence, and reporting both would invite
/// the UI to explain a distinction deptry did not make.
///
/// # Errors
/// `PD-ENV-003` when the folder cannot be read at all — a path that is not a directory, or one the
/// user cannot list. Health has nothing to run against in either case.
pub fn declared_source(project: &Path) -> Result<DeclaredSource> {
let unreadable = |e: &dyn std::fmt::Display| {
PdError::new(
Code::EnvProbeFailed,
format!(
"could not read the project folder {}: {e}",
project.display()
),
)
};
if !project.is_dir() {
return Err(unreadable(&"not a directory"));
}
if project.join("pyproject.toml").is_file() {
return Ok(DeclaredSource::Pyproject);
}
let mut files: Vec<String> = std::fs::read_dir(project)
.map_err(|e| unreadable(&e))?
.filter_map(std::result::Result::ok)
.filter(|entry| entry.path().is_file())
.filter_map(|entry| entry.file_name().into_string().ok())
.filter(|name| is_requirements(name))
.collect();
if files.is_empty() {
return Ok(DeclaredSource::None);
}
files.sort();
Ok(DeclaredSource::Requirements { files })
}
/// `requirements*.txt`, matched case-insensitively.
///
/// Windows filesystems are case-insensitive, so `Requirements.txt` is the same file to everyone
/// except a case-sensitive comparison — which would report "no declared dependencies" for a
/// project that plainly has some.
fn is_requirements(name: &str) -> bool {
let lower = name.to_ascii_lowercase();
lower.starts_with("requirements") && lower.ends_with(".txt")
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
#[test]
fn pyproject_wins_over_requirements_beside_it() {
// deptry's own precedence. Reporting both would invite the UI to explain a distinction
// deptry did not make.
let dir = scratch("both");
write(&dir, "pyproject.toml");
write(&dir, "requirements.txt");
assert_eq!(
declared_source(&dir).expect("readable"),
DeclaredSource::Pyproject
);
}
#[test]
fn every_requirements_file_is_named_and_sorted() {
let dir = scratch("reqs");
write(&dir, "requirements-dev.txt");
write(&dir, "requirements.txt");
write(&dir, "notes.txt"); // not a requirements file
write(&dir, "requirements.in"); // not .txt
assert_eq!(
declared_source(&dir).expect("readable"),
DeclaredSource::Requirements {
files: vec!["requirements-dev.txt".into(), "requirements.txt".into()],
}
);
}
#[test]
fn casing_does_not_hide_a_requirements_file() {
// Windows filesystems are case-insensitive; a case-sensitive match would report "nothing
// declared" for a project that plainly declares things.
let dir = scratch("case");
write(&dir, "Requirements.TXT");
assert!(declared_source(&dir).expect("readable").is_declared());
}
#[test]
fn a_folder_declaring_nothing_is_a_state_not_a_failure() {
// §3's limited-mode notice: deptry still runs, its findings just mean less.
let dir = scratch("bare");
write(&dir, "main.py");
assert_eq!(
declared_source(&dir).expect("readable"),
DeclaredSource::None
);
assert!(!DeclaredSource::None.is_declared());
}
#[test]
fn a_path_that_is_not_a_folder_is_a_catalog_code() {
let err = declared_source(&scratch("missing").join("nope")).expect_err("not a directory");
assert_eq!(err.code, Code::EnvProbeFailed);
}
fn scratch(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("pd-proj-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("create scratch dir");
dir
}
fn write(dir: &Path, name: &str) {
std::fs::write(dir.join(name), "").expect("write");
}
}
+93 -3
View File
@@ -11,7 +11,7 @@
use std::path::{Path, PathBuf};
use rusqlite::Connection;
use rusqlite::{Connection, OptionalExtension as _};
use crate::errors::{Code, PdError, Result};
@@ -19,7 +19,7 @@ use crate::errors::{Code, PdError, Result};
pub const DB_FILE: &str = "index.db";
/// Schema version this build expects. Bump when adding a migration.
pub const SCHEMA_VERSION: i64 = 2;
pub const SCHEMA_VERSION: i64 = 3;
/// An open store.
#[derive(Debug)]
@@ -153,6 +153,16 @@ impl Store {
PRIMARY KEY (env_hash, pkg)
);
-- The project folder Code Health runs its tools in, per environment
-- (CODE-HEALTH-SPEC §3). Its own table rather than a `kv` row because it is
-- keyed and carries a second column; `kv` is for scalars. Same env_hash the
-- pins use, case-folded upstream (SP-6).
CREATE TABLE IF NOT EXISTS health_projects (
env_hash TEXT PRIMARY KEY,
folder TEXT NOT NULL,
last_run TEXT
);
-- Small scalars that do not deserve a table of their own: when the name index
-- was last refreshed, how many projects it holds.
CREATE TABLE IF NOT EXISTS kv (
@@ -250,6 +260,42 @@ impl Store {
pub fn default_env(&self) -> Result<Option<RecentEnv>> {
Ok(self.recent_envs()?.into_iter().find(|e| e.is_default))
}
/// The project folder Code Health last ran in for this environment (CODE-HEALTH-SPEC §3).
///
/// Per environment, because deptry compares declared dependencies against what is *installed*
/// — the same folder against a different env is a different question.
///
/// # Errors
/// `PD-INT-001` when the read fails.
pub fn health_project(&self, env_hash: &str) -> Result<Option<String>> {
self.conn
.query_row(
"SELECT folder FROM health_projects WHERE env_hash = ?1",
[env_hash],
|row| row.get(0),
)
.optional()
.map_err(|e| PdError::new(Code::IntUnexpected, format!("read health project: {e}")))
}
/// Remember the folder, and when it was last run in.
///
/// `last_run` is written on every save rather than only on success: the question it answers is
/// "when did we last do this here", and a run that failed still happened.
///
/// # Errors
/// `PD-INT-001` when the write fails.
pub fn set_health_project(&self, env_hash: &str, folder: &str, now: &str) -> Result<()> {
self.conn
.execute(
"INSERT INTO health_projects (env_hash, folder, last_run) VALUES (?1, ?2, ?3)
ON CONFLICT(env_hash) DO UPDATE SET folder = ?2, last_run = ?3",
[env_hash, folder, now],
)
.map(|_| ())
.map_err(|e| PdError::new(Code::IntUnexpected, format!("save health project: {e}")))
}
}
/// Default app data root, `%LOCALAPPDATA%\PipDock` (ARCHITECTURE §6).
@@ -278,7 +324,7 @@ mod tests {
.filter_map(std::result::Result::ok)
.collect();
for expected in ["envs", "meta_cache", "names", "pins"] {
for expected in ["envs", "health_projects", "meta_cache", "names", "pins"] {
assert!(
tables.contains(&expected.to_owned()),
"missing {expected}: {tables:?}"
@@ -286,6 +332,50 @@ mod tests {
}
}
#[test]
fn a_project_folder_is_remembered_per_environment() {
// Per environment, not per folder: deptry compares declared dependencies against what is
// *installed*, so the same folder against a different env is a different question.
let store = Store::in_memory().expect("open");
assert_eq!(store.health_project("aaa").expect("read"), None);
store
.set_health_project("aaa", r"C:\proj\one", "2026-08-12T00:00:00Z")
.expect("write");
store
.set_health_project("bbb", r"C:\proj\two", "2026-08-12T00:00:00Z")
.expect("write");
assert_eq!(
store.health_project("aaa").expect("read").as_deref(),
Some(r"C:\proj\one")
);
assert_eq!(
store.health_project("bbb").expect("read").as_deref(),
Some(r"C:\proj\two")
);
}
#[test]
fn choosing_a_different_folder_replaces_rather_than_duplicates() {
// env_hash is the primary key, so the upsert is the whole mechanism — a plain INSERT would
// fail on the second save and the user's new choice would silently not stick.
let store = Store::in_memory().expect("open");
store
.set_health_project("aaa", r"C:\proj\one", "2026-08-12T00:00:00Z")
.expect("first");
store
.set_health_project("aaa", r"C:\proj\two", "2026-08-12T01:00:00Z")
.expect("second");
assert_eq!(
store.health_project("aaa").expect("read").as_deref(),
Some(r"C:\proj\two")
);
}
#[test]
fn migrating_twice_is_harmless() {
// Migrations run on every open, so they must be idempotent or the second launch fails.