Skip to content
This repository was archived by the owner on Oct 19, 2026. It is now read-only.

Commit 3683fab

Browse files
jackieismpcclaude
andauthored
Fix/orion bugs fix (#2051)
* test: Add comprehensive test coverage for root cell path resolution Add test cases to verify that configuration files in the root directory (BUCK, Cargo.toml, .buckconfig) are correctly resolved when root cell is configured as ".". Tests added: - cells.rs: test_unresolve_root_cell_with_dot_prefix * Verifies BUCK, Cargo.toml, .buckconfig resolution * Includes regression test for src/main.rs (CL OB6W18SK) * Tests empty path edge case - cells.rs: test_unresolve_multi_cell_priority * Verifies correct cell matching priority in multi-cell setup * Tests that more specific paths match first - changes.rs: test_changes_with_root_directory_files * Integration test for Changes::new() with root directory files * Verifies all paths are resolved correctly - changes.rs: test_changes_preserves_status * Verifies that file status (Modified/Added/Removed) is preserved - changes.rs: test_regression_cl_ob6w18sk * Ensures CL OB6W18SK scenario continues to work All tests pass, indicating current implementation handles these cases. This establishes baseline before investigating production environment differences. Related to: CL 2NY0WW96, CL 9TNTRBBQ, CL OB6W18SK Signed-off-by: jackie <jackieismpc@gmail.com> Signed-off-by: jackieismpc <jackieismpc@gmail.com> * fix: Improve root cell path resolution in CellInfo::unresolve() This commit enhances the path matching logic to explicitly handle root cells (prefix = "" or ".") with proper semantics. Problem: In production environments, configuration files in the root directory (BUCK, Cargo.toml) were not triggering incremental builds when modified. Analysis of production logs showed: - CL 2NY0WW96 (BUCK modified): 0 targets discovered - CL 9TNTRBBQ (Cargo.toml modified): 0 targets discovered - CL OB6W18SK (src/main.rs modified): 1 target discovered Root Cause: The original implementation relied on strip_prefix() which works when parse_cells_data() converts "." to "", but the logic was implicit and fragile. The semantics of root cell matching were not clearly expressed. Solution: Explicitly handle root cell (empty or "." prefix) with clear semantics: - Root cell matches "all paths without a more specific prefix" - Check for more specific matches first (longest prefix priority) - Only assign to root cell if no better match exists - Non-root cells use standard prefix matching Benefits: 1. Explicit semantics: Code clearly expresses the intent 2. Robust: Works regardless of how parse_cells_data() normalizes paths 3. Maintainable: Future developers understand the root cell logic 4. Correct priority: Ensures longest-prefix-first matching The fix ensures all root directory files (BUCK, Cargo.toml, .buckconfig) are correctly resolved to the root cell, enabling proper incremental build detection. Related: CL 2NY0WW96, CL 9TNTRBBQ, CL OB6W18SK Signed-off-by: jackie <jackieismpc@gmail.com> Signed-off-by: jackieismpc <jackieismpc@gmail.com> * fix: Make contains_package detect BUCK file changes Problem: When BUCK files are modified, the changes contain paths like "root//BUCK", but contains_package("root//") only checked for the exact package path, causing BUCK file changes to be missed. Solution: Modified contains_package to also check if any BUCK or BUCK.v2 files within the package directory are in the changes. This ensures that build file modifications are properly detected as package changes. Tests: - test_contains_package_with_buck_file: Verifies BUCK detection - test_contains_package_with_buck_v2_file: Verifies BUCK.v2 detection - test_contains_package_with_subdirectory_buck_file: Ensures subdirectory isolation - test_contains_package_without_buck_file: Ensures non-BUCK files don't trigger All 53 tests pass. Signed-off-by: jackieismpc <jackieismpc@gmail.com> * chore: Apply cargo fmt and fix clippy warnings Signed-off-by: jackieismpc <jackieismpc@gmail.com> * test: Add integration tests for real-world path resolution flow These tests simulate the ACTUAL production flow that was failing: Git change → ProjectRelativePath → unresolve() → CellPath → contains_package() The previous tests used Changes::from_paths() which bypassed the unresolve() step, so they passed even though production was failing. Test cases added: - test_real_world_buck_file_change_with_unresolve: Simulates CL 2NY0WW96 - test_real_world_cargo_toml_change_with_unresolve: Simulates CL 9TNTRBBQ - test_real_world_subdirectory_file_with_unresolve: Simulates CL OB6W18SK These tests verify the complete fix: 1. unresolve() correctly handles root cell files (BUCK, Cargo.toml) 2. Changes::new() successfully resolves paths (not skipped with warnings) 3. contains_package() correctly detects BUCK file changes Signed-off-by: jackie <jackieismpc@gmail.com> Signed-off-by: jackieismpc <jackieismpc@gmail.com> * fmt Signed-off-by: jackie <jackieismpc@gmail.com> Signed-off-by: jackieismpc <jackieismpc@gmail.com> * test: Add comprehensive integration tests for edge cases Added tests for additional scenarios mentioned in orion.md: - .buckconfig file changes (root config file) - BUCK.v2 variant support - Multi-cell environment with priority matching - Mixed changes (multiple files in one commit) All tests simulate the complete production flow: Git change → ProjectRelativePath → unresolve() → CellPath → contains_package() Test coverage now includes: ✅ Root directory files (BUCK, Cargo.toml, .buckconfig) ✅ BUCK file variants (BUCK, BUCK.v2) ✅ Subdirectory files (src/main.rs) ✅ Multi-cell priority (toolchains cell vs root cell) ✅ Mixed changes (multiple files at once) All 60 tests passing. Signed-off-by: jackie <jackieismpc@gmail.com> Signed-off-by: jackieismpc <jackieismpc@gmail.com> * chore: Apply cargo fmt formatting Apply rustfmt to ensure consistent code style across the codebase. Signed-off-by: jackie <jackieismpc@gmail.com> Signed-off-by: jackieismpc <jackieismpc@gmail.com> * fix: Handle package paths without trailing slash in contains_package The contains_package method now correctly handles both package formats: - "cell//dir/" (with trailing slash) - "cell//dir" (without trailing slash, the real-world format) When strip_prefix("cell//dir") is applied to "cell//dir/BUCK", it yields "/BUCK" (with leading slash). The fix strips this leading slash before checking if the relative path is a BUCK file. This ensures BUCK file changes in non-root packages correctly trigger package-level impact detection in immediate_target_changes. Added test: test_contains_package_without_trailing_slash Signed-off-by: jackie <jackieismpc@gmail.com> Signed-off-by: jackieismpc <jackieismpc@gmail.com> * fix: Normalize cell prefix trailing slashes in unresolve() When cell paths in JSON have trailing slashes (e.g., "toolchains": "./toolchains/"), the unresolve() method would fail to match paths correctly because it would test against "toolchains//" instead of "toolchains/". This fix normalizes prefix strings by trimming trailing slashes before matching, ensuring consistent path resolution regardless of whether the cell configuration includes trailing slashes. Test: test_unresolve_cell_with_trailing_slash Signed-off-by: jackie <jackieismpc@gmail.com> Signed-off-by: jackieismpc <jackieismpc@gmail.com> * fix: Restrict BUCK file detection to package-root files only The contains_package() method was incorrectly matching files inside BUCK.* directories (e.g., BUCK.gen/subdir/file.rs) as BUCK file changes. This caused non-build-file changes to be misclassified as package changes, triggering incorrect recursive impact propagation. This fix adds a check to ensure the relative path contains no '/' character, restricting matches to actual BUCK files (BUCK, BUCK.v2, BUCK.*) in the package root directory only. Test: test_contains_package_rejects_buck_directory Signed-off-by: jackie <jackieismpc@gmail.com> Signed-off-by: jackieismpc <jackieismpc@gmail.com> * fix review Signed-off-by: jackie <jackieismpc@gmail.com> Signed-off-by: jackieismpc <jackieismpc@gmail.com> * fix review Signed-off-by: jackie <jackieismpc@gmail.com> Signed-off-by: jackieismpc <jackieismpc@gmail.com> * test: add failing test for Cargo.toml package detection Extend test_real_world_cargo_toml_change_with_unresolve to verify that Cargo.toml changes are detected as package changes by contains_package(). This test currently fails because contains_package() only checks for BUCK files, not Cargo.toml. The test verifies the complete flow: 1. Git detects Cargo.toml change (ProjectRelativePath) 2. unresolve() converts to CellPath (root//Cargo.toml) ✅ 3. contains_package() should detect it as package change ❌ FAILS Related: CL GIVWFTLA (Cargo.toml changes not triggering builds) Signed-off-by: jackie <jackieismpc@gmail.com> Signed-off-by: jackieismpc <jackieismpc@gmail.com> * fix: detect Cargo.toml changes as package changes Extend contains_package() to recognize Cargo.toml as a package-level configuration file, similar to BUCK files. Root Cause: The previous fix only added BUCK file detection to contains_package(), but didn't consider other package-level manifest files like Cargo.toml. Why This Matters: Cargo.toml defines dependencies and build configuration for Rust projects. Changes to it should trigger rebuilds just like BUCK file changes do. Implementation: - Add Cargo.toml check alongside BUCK file checks - Use same pattern: check if file is in package root (no '/' in relative path) - Add trace logging for debugging Flow After Fix: 1. unresolve("Cargo.toml") → root//Cargo.toml ✅ 2. contains_package("root//") → detects root//Cargo.toml ✅ 3. Returns RootImpactKind::Package ✅ 4. Marks targets as impacted ✅ 5. Triggers incremental build ✅ Fixes: CL GIVWFTLA (Cargo.toml changes not triggering builds) Maintains: CL BUYRPBLK (BUCK changes continue to work) Signed-off-by: jackie <jackieismpc@gmail.com> Signed-off-by: jackieismpc <jackieismpc@gmail.com> * chore: apply cargo fmt Signed-off-by: jackie <jackieismpc@gmail.com> Signed-off-by: jackieismpc <jackieismpc@gmail.com> * refactor: replace hardcoded file list with pattern-based package-level file detection Replace the hardcoded list of package-level files (BUCK, Cargo.toml) with a comprehensive, pattern-based approach that supports all common manifest and build files. Root Cause: The previous implementation hardcoded specific file names, requiring code changes for every new file type. This is not scalable or maintainable. Solution: Introduce is_package_level_file() function that recognizes: - Build system files: BUCK, BUILD, CMakeLists.txt, Makefile - Rust manifests: Cargo.toml, Cargo.lock - JavaScript/Node: package.json, package-lock.json, yarn.lock, pnpm-lock.yaml - Python: requirements.txt, setup.py, pyproject.toml, Pipfile - Go: go.mod, go.sum - Java/Maven/Gradle: pom.xml, build.gradle, settings.gradle - Configuration: .buckconfig, .bazelrc, .buckversion Benefits: - One-time fix for all manifest file types - No code changes needed for new file types - Centralized, maintainable logic - Comprehensive test coverage (36 tests passing) Fixes: CL 8OU2UOEX (Cargo.lock now supported) Fixes: Future manifest files automatically supported Maintains: All existing functionality (BUCK, Cargo.toml, etc.) Signed-off-by: jackie <jackieismpc@gmail.com> Signed-off-by: jackieismpc <jackieismpc@gmail.com> * docs: improve is_package_level_file documentation and test coverage Enhance the implementation with: 1. Comprehensive function documentation listing all supported file types 2. Additional unit tests for CMakeLists.txt and Makefile 3. Integration tests for CMake, Makefile, and .buckconfig files This ensures all supported file types are properly documented and tested, making the codebase more maintainable and easier to understand. Test coverage: 40 tests passing (4 new tests added) Signed-off-by: jackie <jackieismpc@gmail.com> Signed-off-by: jackieismpc <jackieismpc@gmail.com> * feat(orion): add .mega_cedar.json to package-level file detection Add support for .mega_cedar.json as a package-level configuration file that triggers full package rebuilds when modified. Changes: - Add .mega_cedar.json detection in is_package_level_file() - Update function documentation to include Mega configuration - Add unit test for .mega_cedar.json detection - Add integration test for contains_package() behavior This ensures that changes to .mega_cedar.json properly trigger incremental compilation for affected packages. Signed-off-by: jackie <jackieismpc@gmail.com> Signed-off-by: jackieismpc <jackieismpc@gmail.com> * fix(orion): query targets from all cells, not just root cell Problem: When modifying files in non-root cells (e.g., toolchains/BUCK), Orion reported 'No impacted Buck targets detected'. This was because buck2 targets command only queried the root cell ('//...'), missing targets in other cells like toolchains, prelude, etc. Root Cause: The targets_arguments() function hardcoded '//...' pattern, which only queries the root cell. When toolchains/BUCK was modified: 1. Path was correctly resolved to 'toolchains//BUCK' ✓ 2. changes.contains_package(&toolchains_package) returned true ✓ 3. But diff.targets() had NO toolchains cell targets ✗ Solution: 1. Add CellInfo::get_all_cell_patterns() to generate patterns for all cells (e.g., ['root//...', 'toolchains//...', 'prelude//...']) 2. Modify get_repo_targets() to accept optional CellInfo parameter 3. When CellInfo is provided, query all cells; otherwise default to root cell only (for backward compatibility with tests) 4. Remove hardcoded '//...' from targets_arguments() Impact: - Fixes toolchains/BUCK not triggering incremental builds - Fixes any other non-root cell file changes not being detected - Maintains backward compatibility for tests without cell info Test: Added test_get_all_cell_patterns() and test_contains_package_toolchains_cell() Related: CL HM7ZXVEV (toolchains/BUCK), CL M0YGTOEO (.mega_cedar.json) Signed-off-by: jackieismpc <jackieismpc@gmail.com> * docs(orion): add analysis document for non-root cell detection fix Signed-off-by: jackieismpc <jackieismpc@gmail.com> * fmt Signed-off-by: jackieismpc <jackieismpc@gmail.com> * fix(buck): exclude prelude cell from target queries to avoid parsing errors The prelude cell contains build rule definitions and may have parsing issues when queried directly (e.g., "Object of type 'struct' has no attribute 'go_unittest'"). Since prelude is a special cell that doesn't contain user targets, we exclude it from the target query patterns. This allows us to successfully query targets from all user-defined cells (root, toolchains, etc.) without hitting prelude parsing errors. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> Signed-off-by: jackieismpc <jackieismpc@gmail.com> * fix(orion): capture and log buck2 stderr to prevent pipe deadlock When buck2 targets command fails, stderr was not captured. More critically, stderr was not consumed even on success, which could cause pipe deadlock if buck2 writes more than 64KB to stderr. This change: - Spawns background thread to consume stderr, preventing pipe deadlock - Logs stderr on failure for diagnostics - Logs stderr on success (debug level) if non-empty Fixes issues like: - Cell configuration errors when CL modifies .buckconfig or toolchains/BUCK - FUSE mount issues - Buck2 daemon startup failures Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> Signed-off-by: jackieismpc <jackieismpc@gmail.com> * fix: add mut to stderr variable for compilation Signed-off-by: jackieismpc <jackieismpc@gmail.com> * fix(orion): exclude 'none' placeholder cell from target queries Problem: After commit fa81285 (query targets from all cells), buck2 targets command started failing with: Error resolving recursive spec `none///...` This happened because the buck2_test project uses a "none" placeholder cell for cell aliases (fbcode, fbsource, etc.), and buck2 tried to query targets from this non-existent directory. Root Cause: The get_all_cell_patterns() method included ALL cells from the configuration, including placeholder cells like "none" that don't contain actual build targets. When buck2 tried to query "none//...", it failed because the directory doesn't exist or is just a placeholder. Solution: Extend the filter in get_all_cell_patterns() to exclude both: - "prelude": Special cell with build rule definitions (already excluded) - "none": Placeholder cell used for cell aliases (newly excluded) This is a targeted fix that uses a simple hardcoded filter, which is appropriate given: 1. Only 2 known special cells need exclusion 2. These are well-known Buck2 conventions 3. Simple and maintainable Impact: - Fixes all CL builds that were failing with "none//..." error - Allows Cargo.lock, BUCK, and other file modifications to work again - No impact on normal cells (root, toolchains, etc.) Test: Added test_get_all_cell_patterns_excludes_none_placeholder() Related CLs: FTB5APYJ, RTXQJQS8, OPJ2PRVU (all were failing) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> Signed-off-by: jackieismpc <jackieismpc@gmail.com> * test: replace local absolute paths with generic paths in unit tests - Changed /Users/jackie/work/project/buck2_test to /repo in all test cases - Ensures tests are portable across different development environments - Follows best practice of using generic paths in unit tests Signed-off-by: jackieismpc <jackieismpc@gmail.com> * fix(buck): exclude toolchains cell from target queries to avoid directory errors The toolchains cell is defined in .buckconfig but the directory doesn't exist in the main project (only in test fixtures). When querying targets from all cells, buck2 tries to access the non-existent toolchains directory and fails with 'No such file or directory' error. This fix excludes the toolchains cell from target queries, similar to how we exclude prelude and none cells. Test fixtures with their own .buckconfig are not affected. Fixes the error: Error resolving recursive spec `toolchains///...` Caused by: read_dir(/home/jackie/mega/toolchains) No such file or directory (os error 2) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> Signed-off-by: jackieismpc <jackieismpc@gmail.com> * fix(orion): only query cells with existing directories When buck2 cells are defined in .buckconfig but their directories don't exist, querying them causes "No such file or directory" errors. This happens in monorepo setups where root .buckconfig defines cells that only exist in subprojects. Changes: - Modified get_all_cell_patterns() to accept repo_root parameter - Added directory existence check before including cells in queries - Updated buck_controller.rs to pass repo_path to get_all_cell_patterns() - Added test coverage for directory existence validation This fixes the issue where modifying project/buck2_test/toolchains/BUCK failed because root .buckconfig defined "toolchains = toolchains" but the directory didn't exist at root level. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> Signed-off-by: jackieismpc <jackieismpc@gmail.com> * fix: add --no-remote-cache to prevent stale cache in incremental builds Signed-off-by: jackieismpc <jackieismpc@gmail.com> * docs: add comment explaining why --no-remote-cache is needed Signed-off-by: jackieismpc <jackieismpc@gmail.com> * test: add test to verify --no-remote-cache flag in build command Signed-off-by: jackieismpc <jackieismpc@gmail.com> * fix: kill buck2 daemon and use isolation-dir to prevent local cache Buck2 has two layers of caching that can prevent syntax errors from being detected: 1. Remote cache (already disabled via --no-remote-cache) 2. Local daemon cache (still active, causing issues) This commit implements a comprehensive cache prevention strategy: - Kill buck2 daemon before each build to clear local action cache - Use unique isolation-dir per build to prevent cache sharing - Keep --no-remote-cache to prevent remote cache usage This ensures that syntax errors are always detected immediately in incremental builds. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> Signed-off-by: jackieismpc <jackieismpc@gmail.com> * fix: add isolation-dir cleanup to prevent disk space leak Add cleanup logic after build completes to remove .buck-isolation directories, preventing disk space accumulation from multiple builds. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> Signed-off-by: jackieismpc <jackieismpc@gmail.com> * chore: add .buck-isolation to .gitignore Prevent buck2 isolation directories from being tracked in git. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> Signed-off-by: jackieismpc <jackieismpc@gmail.com> * fix: replace local absolute paths with generic paths in tests Signed-off-by: jackieismpc <jackieismpc@gmail.com> * chore: fix import order in cells.rs Signed-off-by: jackieismpc <jackieismpc@gmail.com> * fix: capture buck2 build stdout/stderr for better error reporting Signed-off-by: jackieismpc <jackieismpc@gmail.com> * fix: use simple directory name for buck2 --isolation-dir parameter Buck2 requires --isolation-dir to be a simple directory name without path separators. Changed from '.buck-isolation/{id}' to 'buck-isolation-{id}' to comply with this requirement. This fixes the issue where buck2 commands would fail with invalid isolation-dir format when the parameter contained '/' characters. Signed-off-by: jackieismpc <jackieismpc@gmail.com> * cl test Signed-off-by: jackieismpc <jackieismpc@gmail.com> * fix some bugs Signed-off-by: jackieismpc <jackieismpc@gmail.com> * clippy Signed-off-by: jackieismpc <jackieismpc@gmail.com> * fmt Signed-off-by: jackieismpc <jackieismpc@gmail.com> --------- Signed-off-by: jackie <jackieismpc@gmail.com> Signed-off-by: jackieismpc <jackieismpc@gmail.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent 2d05717 commit 3683fab

15 files changed

Lines changed: 2098 additions & 39 deletions

File tree

‎.gitignore‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,9 @@ docker/**/.env
3232
# buck2 out
3333
buck-out
3434

35+
# buck2 isolation directories
36+
.buck-isolation
37+
3538
# Gtk4 resource files
3639
**/*.gresource
3740
monobean/resources/lib
@@ -55,4 +58,7 @@ orion-server/docker-compose.override.yml
5558
# local dev environment
5659
/scripts/dev/.env
5760

58-
.buildx-cache
61+
.buildx-cache
62+
63+
# Claude Code configuration and cache
64+
.claude

‎Cargo.lock‎

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎ceres/src/api_service/blob_ops.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,7 @@ async fn get_files_content_hashes_internal<T: ApiHandler + ?Sized>(
277277

278278
// Batch read blob contents
279279
let max_concurrent = handler.get_context().get_recommended_batch_concurrency();
280-
let mut blob_stream = stream::iter(blob_ids.into_iter())
280+
let mut blob_stream = stream::iter(blob_ids)
281281
.map(|(path, blob_hash)| {
282282
// Use into_iter to get ownership, no clone needed
283283
let blob_hash_str = blob_hash.to_string();

‎jupiter/src/service/code_review_service.rs‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -482,12 +482,11 @@ pub fn try_tier2_diff_hunk_shift(
482482
}
483483
orig_pos += 1;
484484
}
485-
Some('+') => {
485+
Some('+') if orig_pos <= anchor_orig_line_position => {
486486
// Added lines before anchor increase offset
487-
if orig_pos <= anchor_orig_line_position {
488-
line_offset += 1;
489-
}
487+
line_offset += 1;
490488
}
489+
Some('+') => {}
491490
Some(' ') | None => {
492491
// Context line
493492
if orig_pos == anchor_orig_line_position {

‎orion/Cargo.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ dotenvy = { workspace = true }
2020
tokio-tungstenite = { workspace = true, features = ["native-tls"] }
2121
tungstenite = { workspace = true }
2222
serde_json = { workspace = true }
23+
reqwest = { workspace = true, features = ["json"] }
24+
url = { workspace = true }
2325
uuid = { workspace = true, features = ["v4"] }
2426
anyhow = { workspace = true }
2527
itertools = { workspace = true }

‎orion/buck/cells.rs‎

Lines changed: 256 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -206,13 +206,48 @@ impl CellInfo {
206206
}
207207

208208
pub fn unresolve(&self, path: &ProjectRelativePath) -> anyhow::Result<CellPath> {
209-
// because we know self.paths has the longest match first, we just find the first match
209+
let path_str = path.as_str();
210+
211+
// self.paths is sorted by path length (longest first) for priority matching
210212
for (cell, prefix) in &self.paths {
211-
if let Some(x) = path.as_str().strip_prefix(prefix.as_str()) {
212-
let x = x.strip_prefix('/').unwrap_or(x);
213-
return Ok(cell.join(&CellRelativePath::new(x)));
213+
let prefix_str = prefix.as_str();
214+
// Normalize: remove trailing slashes from prefix for consistent matching
215+
let prefix_normalized = prefix_str.trim_end_matches('/');
216+
217+
// Special handling: empty prefix or "." represents the root cell
218+
// Semantically, it means "match all paths that don't have a more specific prefix"
219+
if prefix_normalized.is_empty() || prefix_normalized == "." {
220+
// Check if there's a more specific prefix that matches this path
221+
let has_more_specific_match = self.paths.iter().any(|(_, other_prefix)| {
222+
let other_str = other_prefix.as_str().trim_end_matches('/');
223+
!other_str.is_empty()
224+
&& other_str != "."
225+
&& (path_str == other_str
226+
|| path_str.starts_with(&format!("{}/", other_str)))
227+
});
228+
229+
// If no more specific match exists, this path belongs to the root cell
230+
if !has_more_specific_match {
231+
tracing::debug!(
232+
"Resolved path '{}' to root cell '{}' (prefix: '{}')",
233+
path_str,
234+
cell.as_str(),
235+
prefix_str
236+
);
237+
return Ok(cell.join(&CellRelativePath::new(path_str)));
238+
}
239+
} else {
240+
// Non-root cell: use standard prefix matching
241+
if path_str == prefix_normalized {
242+
// Exact match: path is the cell's root directory
243+
return Ok(cell.join(&CellRelativePath::new("")));
244+
} else if let Some(x) = path_str.strip_prefix(&format!("{}/", prefix_normalized)) {
245+
// Prefix match: path is in a subdirectory of the cell
246+
return Ok(cell.join(&CellRelativePath::new(x)));
247+
}
214248
}
215249
}
250+
216251
Err(CellError::UnknownPath(path.clone()).into())
217252
}
218253

@@ -229,6 +264,44 @@ impl CellInfo {
229264
Some(data) => data.ignore.is_match(path.path().as_str()),
230265
}
231266
}
267+
268+
/// Returns target patterns for all cells (e.g., ["root//...", ...])
269+
/// This is used to query targets from all cells, not just the root cell.
270+
///
271+
/// Note: Excludes special cells:
272+
/// - "prelude": Contains build rule definitions, may have parsing issues
273+
/// - "none": Placeholder cell used for cell aliases, doesn't contain actual build targets
274+
///
275+
/// Also excludes cells whose directories don't exist in the project root.
276+
/// This prevents errors when querying cells that are defined in .buckconfig
277+
/// but don't have corresponding directories (e.g., toolchains in test fixtures).
278+
pub fn get_all_cell_patterns(&self, project_root: &Path) -> Vec<String> {
279+
self.cells
280+
.iter()
281+
.filter(|(cell_name, cell_data)| {
282+
let cell_str = cell_name.as_str();
283+
284+
// Exclude known special/placeholder cells
285+
if cell_str == "prelude" || cell_str == "none" {
286+
return false;
287+
}
288+
289+
// Check if the cell directory actually exists
290+
let cell_path = project_root.join(cell_data.path.as_str());
291+
if !cell_path.exists() {
292+
tracing::debug!(
293+
"Excluding cell '{}' from query: directory {:?} does not exist",
294+
cell_str,
295+
cell_path
296+
);
297+
return false;
298+
}
299+
300+
true
301+
})
302+
.map(|(cell_name, _)| format!("{}//...", cell_name.as_str()))
303+
.collect()
304+
}
232305
}
233306

234307
#[cfg(test)]
@@ -338,4 +411,183 @@ mod tests {
338411
assert!(!cells.is_ignored(&CellPath::new("root//cell1/bar/baz/file.txt")));
339412
assert!(!cells.is_ignored(&CellPath::new("cell1//cell1/bar/baz/file.txt")));
340413
}
414+
415+
#[test]
416+
fn test_unresolve_root_cell_with_dot_prefix() {
417+
// 模拟实际的 cell 配置:root = .
418+
let cells = CellInfo::parse(r#"{"root": "."}"#).unwrap();
419+
420+
// Case 1: BUCK 文件(CL 2NY0WW96 - 当前失败)
421+
let result = cells.unresolve(&ProjectRelativePath::new("BUCK"));
422+
assert!(result.is_ok(), "BUCK should be resolved to root cell");
423+
assert_eq!(result.unwrap(), CellPath::new("root//BUCK"));
424+
425+
// Case 2: Cargo.toml(CL 9TNTRBBQ - 当前失败)
426+
let result = cells.unresolve(&ProjectRelativePath::new("Cargo.toml"));
427+
assert!(result.is_ok(), "Cargo.toml should be resolved to root cell");
428+
assert_eq!(result.unwrap(), CellPath::new("root//Cargo.toml"));
429+
430+
// Case 3: .buckconfig(配置文件)
431+
let result = cells.unresolve(&ProjectRelativePath::new(".buckconfig"));
432+
assert!(
433+
result.is_ok(),
434+
".buckconfig should be resolved to root cell"
435+
);
436+
assert_eq!(result.unwrap(), CellPath::new("root//.buckconfig"));
437+
438+
// Case 4: src/main.rs(CL OB6W18SK - 回归测试,应该继续工作)
439+
let result = cells.unresolve(&ProjectRelativePath::new("src/main.rs"));
440+
assert!(
441+
result.is_ok(),
442+
"src/main.rs should be resolved to root cell"
443+
);
444+
assert_eq!(result.unwrap(), CellPath::new("root//src/main.rs"));
445+
446+
// Case 5: 空路径
447+
let result = cells.unresolve(&ProjectRelativePath::new(""));
448+
assert!(result.is_ok(), "empty path should be resolved to root cell");
449+
assert_eq!(result.unwrap(), CellPath::new("root//"));
450+
}
451+
452+
#[test]
453+
fn test_unresolve_cell_with_trailing_slash() {
454+
// Test that cells with trailing slashes in JSON are handled correctly
455+
let cell_json = serde_json::json!({
456+
"root": ".",
457+
"toolchains": "./toolchains/" // Note: trailing slash
458+
});
459+
let cell_info = CellInfo::parse(&serde_json::to_string(&cell_json).unwrap()).unwrap();
460+
461+
// File in toolchains directory should match toolchains cell
462+
let result = cell_info.unresolve(&ProjectRelativePath::new("toolchains/BUCK"));
463+
assert!(result.is_ok(), "Should resolve toolchains/BUCK");
464+
465+
let cell_path = result.unwrap();
466+
assert_eq!(
467+
cell_path.as_str(),
468+
"toolchains//BUCK",
469+
"Should resolve to toolchains cell, not root"
470+
);
471+
}
472+
473+
#[test]
474+
fn test_unresolve_multi_cell_priority() {
475+
// 模拟多 cell 配置,使用绝对路径格式
476+
// 在实际场景中,. 会被解析为某个绝对路径,这里用 /repo 模拟
477+
let cells = CellInfo::parse(
478+
r#"{
479+
"root": "/repo",
480+
"toolchains": "/repo/toolchains"
481+
}"#,
482+
)
483+
.unwrap();
484+
485+
// Case 1: toolchains 目录下的文件应该匹配 toolchains cell(更具体的匹配)
486+
let result = cells.unresolve(&ProjectRelativePath::new("toolchains/BUCK"));
487+
assert!(
488+
result.is_ok(),
489+
"toolchains/BUCK should be resolved to toolchains cell"
490+
);
491+
assert_eq!(result.unwrap(), CellPath::new("toolchains//BUCK"));
492+
493+
// Case 2: 根目录的 BUCK 应该匹配 root cell
494+
let result = cells.unresolve(&ProjectRelativePath::new("BUCK"));
495+
assert!(result.is_ok(), "BUCK should be resolved to root cell");
496+
assert_eq!(result.unwrap(), CellPath::new("root//BUCK"));
497+
498+
// Case 3: src 目录下的文件应该匹配 root cell(没有更具体的匹配)
499+
let result = cells.unresolve(&ProjectRelativePath::new("src/main.rs"));
500+
assert!(
501+
result.is_ok(),
502+
"src/main.rs should be resolved to root cell"
503+
);
504+
assert_eq!(result.unwrap(), CellPath::new("root//src/main.rs"));
505+
}
506+
507+
#[test]
508+
fn test_get_all_cell_patterns() {
509+
use std::{env, fs};
510+
511+
let temp_dir = env::temp_dir().join("buck_cells_test_1");
512+
let _ = fs::remove_dir_all(&temp_dir); // Clean up if exists
513+
fs::create_dir_all(&temp_dir).unwrap();
514+
fs::create_dir_all(temp_dir.join("toolchains")).unwrap();
515+
fs::create_dir_all(temp_dir.join("prelude")).unwrap();
516+
517+
let cell_json = serde_json::json!({
518+
"root": temp_dir.to_str().unwrap(),
519+
"toolchains": temp_dir.join("toolchains").to_str().unwrap(),
520+
"prelude": temp_dir.join("prelude").to_str().unwrap()
521+
});
522+
let cells = CellInfo::parse(&serde_json::to_string(&cell_json).unwrap()).unwrap();
523+
524+
let patterns = cells.get_all_cell_patterns(&temp_dir);
525+
526+
// Should have patterns for root and toolchains (both exist), but not prelude (special)
527+
assert_eq!(patterns.len(), 2);
528+
assert!(patterns.contains(&"root//...".to_string()));
529+
assert!(patterns.contains(&"toolchains//...".to_string()));
530+
assert!(!patterns.contains(&"prelude//...".to_string()));
531+
532+
// Clean up
533+
let _ = fs::remove_dir_all(&temp_dir);
534+
}
535+
536+
#[test]
537+
fn test_get_all_cell_patterns_excludes_none_placeholder() {
538+
use std::{env, fs};
539+
540+
let temp_dir = env::temp_dir().join("buck_cells_test_2");
541+
let _ = fs::remove_dir_all(&temp_dir); // Clean up if exists
542+
fs::create_dir_all(&temp_dir).unwrap();
543+
fs::create_dir_all(temp_dir.join("toolchains")).unwrap();
544+
fs::create_dir_all(temp_dir.join("prelude")).unwrap();
545+
fs::create_dir_all(temp_dir.join("none")).unwrap();
546+
547+
let cell_json = serde_json::json!({
548+
"root": temp_dir.to_str().unwrap(),
549+
"toolchains": temp_dir.join("toolchains").to_str().unwrap(),
550+
"prelude": temp_dir.join("prelude").to_str().unwrap(),
551+
"none": temp_dir.join("none").to_str().unwrap()
552+
});
553+
let cells = CellInfo::parse(&serde_json::to_string(&cell_json).unwrap()).unwrap();
554+
555+
let patterns = cells.get_all_cell_patterns(&temp_dir);
556+
557+
// Should exclude prelude (special) and none (placeholder), even though directories exist
558+
assert_eq!(patterns.len(), 2);
559+
assert!(patterns.contains(&"root//...".to_string()));
560+
assert!(patterns.contains(&"toolchains//...".to_string()));
561+
assert!(!patterns.contains(&"prelude//...".to_string()));
562+
assert!(!patterns.contains(&"none//...".to_string()));
563+
564+
// Clean up
565+
let _ = fs::remove_dir_all(&temp_dir);
566+
}
567+
568+
#[test]
569+
fn test_get_all_cell_patterns_excludes_nonexistent_dirs() {
570+
use std::{env, fs};
571+
572+
let temp_dir = env::temp_dir().join("buck_cells_test_3");
573+
let _ = fs::remove_dir_all(&temp_dir); // Clean up if exists
574+
fs::create_dir_all(&temp_dir).unwrap();
575+
// Only create root, not toolchains
576+
577+
let cell_json = serde_json::json!({
578+
"root": temp_dir.to_str().unwrap(),
579+
"toolchains": temp_dir.join("toolchains").to_str().unwrap(),
580+
});
581+
let cells = CellInfo::parse(&serde_json::to_string(&cell_json).unwrap()).unwrap();
582+
583+
let patterns = cells.get_all_cell_patterns(&temp_dir);
584+
585+
// Should only have root, since toolchains directory doesn't exist
586+
assert_eq!(patterns.len(), 1);
587+
assert!(patterns.contains(&"root//...".to_string()));
588+
assert!(!patterns.contains(&"toolchains//...".to_string()));
589+
590+
// Clean up
591+
let _ = fs::remove_dir_all(&temp_dir);
592+
}
341593
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
use td_util_buck::types::{CellPath, Package};
2+
3+
fn main() {
4+
// 测试 toolchains cell 的 package
5+
let toolchains_package = Package::new("toolchains//");
6+
println!("Package: {}", toolchains_package.as_str());
7+
println!(
8+
"As CellPath: {}",
9+
toolchains_package.as_cell_path().as_str()
10+
);
11+
12+
// 测试 toolchains/BUCK 的 CellPath
13+
let buck_path = CellPath::new("toolchains//BUCK");
14+
println!("\nBUCK path: {}", buck_path.as_str());
15+
16+
// 测试 strip_prefix
17+
let package_str = toolchains_package.as_str();
18+
let path_str = buck_path.as_str();
19+
20+
println!("\nTesting strip_prefix:");
21+
println!(" package_str: '{}'", package_str);
22+
println!(" path_str: '{}'", path_str);
23+
24+
if let Some(relative) = path_str.strip_prefix(package_str) {
25+
println!(" ✓ Stripped: '{}'", relative);
26+
let relative = relative.strip_prefix('/').unwrap_or(relative);
27+
println!(" After removing leading '/': '{}'", relative);
28+
println!(" Contains '/': {}", relative.contains('/'));
29+
println!(" Is 'BUCK': {}", relative == "BUCK");
30+
} else {
31+
println!(" ✗ strip_prefix failed");
32+
}
33+
}

0 commit comments

Comments
 (0)