deps-core 0.11.0

Core abstractions for deps-lsp: caching, errors, and traits
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
//! Lock file parsing abstractions.
//!
//! Provides generic types and traits for parsing lock files across different
//! package ecosystems (Cargo.lock, package-lock.json, poetry.lock, etc.).
//!
//! Lock files contain resolved dependency versions, allowing instant display
//! without network requests to registries.

use crate::error::{DepsError, Result};
use dashmap::DashMap;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::{Instant, SystemTime};
use tower_lsp_server::ls_types::Uri;

/// Maximum depth to search for workspace root lock file.
const MAX_WORKSPACE_DEPTH: usize = 5;

/// Reads a lock file's contents, wrapping any I/O failure into a [`DepsError::ParseError`]
/// tagged with the ecosystem's `file_type` label and the file's path.
///
/// Every `LockFileProvider::parse_lockfile` implementation reads its lock file the same
/// way; this shares that boilerplate and keeps the error message format consistent
/// across ecosystems.
///
/// # Errors
///
/// Returns [`DepsError::ParseError`] if the file cannot be read (e.g. missing, unreadable,
/// invalid UTF-8).
///
/// # Examples
///
/// ```no_run
/// use deps_core::lockfile::read_lockfile_content;
/// use std::path::Path;
///
/// # async fn example() -> deps_core::error::Result<()> {
/// let content = read_lockfile_content(Path::new("Cargo.lock"), "Cargo.lock").await?;
/// println!("{} bytes read", content.len());
/// # Ok(())
/// # }
/// ```
pub async fn read_lockfile_content(path: &Path, file_type: &str) -> Result<String> {
    tokio::fs::read_to_string(path)
        .await
        .map_err(|e| DepsError::ParseError {
            file_type: format!("{file_type} at {}", path.display()),
            source: Box::new(e),
        })
}

/// Generic lock file locator.
///
/// Searches for lock files in the following order:
/// 1. Same directory as the manifest
/// 2. Parent directories (up to MAX_WORKSPACE_DEPTH levels) for workspace root
///
/// This function is ecosystem-agnostic and works with any lock file name.
///
/// # Arguments
///
/// * `manifest_uri` - URI of the manifest file
/// * `lockfile_names` - List of possible lock file names to search for
///
/// # Returns
///
/// Path to the first found lock file, or None if not found.
///
/// # Examples
///
/// ```no_run
/// use deps_core::lockfile::locate_lockfile_for_manifest;
/// use tower_lsp_server::ls_types::Uri;
///
/// let manifest_uri = Uri::from_file_path("/path/to/Cargo.toml").unwrap();
/// let lockfile_names = &["Cargo.lock"];
///
/// if let Some(path) = locate_lockfile_for_manifest(&manifest_uri, lockfile_names) {
///     println!("Found lock file at: {}", path.display());
/// }
/// ```
pub fn locate_lockfile_for_manifest(
    manifest_uri: &Uri,
    lockfile_names: &[&str],
) -> Option<PathBuf> {
    let manifest_path = manifest_uri.to_file_path()?;
    let manifest_dir = manifest_path.parent()?;

    // Reuse single PathBuf to avoid allocations in loops
    let mut lock_path = manifest_dir.to_path_buf();

    // Try same directory as manifest
    for &name in lockfile_names {
        lock_path.push(name);
        if lock_path.exists() {
            tracing::debug!("Found {} at: {}", name, lock_path.display());
            return Some(lock_path);
        }
        lock_path.pop();
    }

    // Search up the directory tree for workspace root
    let Some(mut current_dir) = manifest_dir.parent() else {
        tracing::debug!("No lock file found for: {:?}", manifest_uri);
        return None;
    };

    for depth in 0..MAX_WORKSPACE_DEPTH {
        lock_path.clear();
        lock_path.push(current_dir);

        for &name in lockfile_names {
            lock_path.push(name);
            if lock_path.exists() {
                tracing::debug!(
                    "Found workspace {} at depth {}: {}",
                    name,
                    depth + 1,
                    lock_path.display()
                );
                return Some(lock_path);
            }
            lock_path.pop();
        }

        match current_dir.parent() {
            Some(parent) => current_dir = parent,
            None => break,
        }
    }

    tracing::debug!("No lock file found for: {:?}", manifest_uri);
    None
}

/// Resolved package information from a lock file.
///
/// Contains the exact version and source information for a dependency
/// as resolved by the package manager.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedPackage {
    /// Package name
    pub name: String,
    /// Resolved version (exact version from lock file)
    pub version: String,
    /// Source information (registry URL, git commit, path)
    pub source: ResolvedSource,
    /// Dependencies of this package (for dependency tree analysis)
    pub dependencies: Vec<String>,
}

/// Source of a resolved dependency.
///
/// Indicates where the package was downloaded from or how it was resolved.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResolvedSource {
    /// From a registry with optional checksum
    Registry {
        /// Registry URL
        url: String,
        /// Checksum/integrity hash
        checksum: String,
    },
    /// From git with commit hash
    Git {
        /// Git repository URL
        url: String,
        /// Commit SHA or tag
        rev: String,
    },
    /// From local file system
    Path {
        /// Relative or absolute path
        path: String,
    },
}

/// Collection of resolved packages from a lock file.
///
/// Supports multiple versions per package name, returning the highest
/// semver version through public API methods.
///
/// # Examples
///
/// ```
/// use deps_core::lockfile::{ResolvedPackages, ResolvedPackage, ResolvedSource};
///
/// let mut packages = ResolvedPackages::new();
/// packages.insert(ResolvedPackage {
///     name: "serde".into(),
///     version: "1.0.195".into(),
///     source: ResolvedSource::Registry {
///         url: "https://github.com/rust-lang/crates.io-index".into(),
///         checksum: "abc123".into(),
///     },
///     dependencies: vec!["serde_derive".into()],
/// });
///
/// assert_eq!(packages.get_version("serde"), Some("1.0.195"));
/// assert_eq!(packages.len(), 1);
/// ```
#[derive(Debug, Default, Clone)]
pub struct ResolvedPackages {
    packages: HashMap<String, Vec<ResolvedPackage>>,
}

/// Returns the package with the highest semver version from a slice.
fn best_package(packages: &[ResolvedPackage]) -> Option<&ResolvedPackage> {
    packages.iter().max_by(|a, b| {
        match (
            semver::Version::parse(&a.version),
            semver::Version::parse(&b.version),
        ) {
            (Ok(va), Ok(vb)) => va.cmp(&vb),
            (Ok(_), Err(_)) => std::cmp::Ordering::Greater,
            (Err(_), Ok(_)) => std::cmp::Ordering::Less,
            (Err(_), Err(_)) => a.version.cmp(&b.version),
        }
    })
}

impl ResolvedPackages {
    /// Creates a new empty collection.
    pub fn new() -> Self {
        Self {
            packages: HashMap::new(),
        }
    }

    /// Inserts a resolved package, storing all versions per name.
    pub fn insert(&mut self, package: ResolvedPackage) {
        self.packages
            .entry(package.name.clone())
            .or_default()
            .push(package);
    }

    /// Gets the resolved package with the highest semver version.
    pub fn get(&self, name: &str) -> Option<&ResolvedPackage> {
        self.packages.get(name).and_then(|v| best_package(v))
    }

    /// Gets the highest resolved version string for a package.
    pub fn get_version(&self, name: &str) -> Option<&str> {
        self.get(name).map(|p| p.version.as_str())
    }

    /// Returns all stored versions for a package.
    pub fn get_all(&self, name: &str) -> Option<&[ResolvedPackage]> {
        self.packages.get(name).map(|v| v.as_slice())
    }

    /// Returns the number of unique package names.
    pub fn len(&self) -> usize {
        self.packages.len()
    }

    /// Returns true if there are no resolved packages.
    pub fn is_empty(&self) -> bool {
        self.packages.is_empty()
    }

    /// Returns an iterator yielding the best version per unique package name.
    pub fn iter(&self) -> impl Iterator<Item = (&String, &ResolvedPackage)> {
        self.packages.keys().filter_map(|name| {
            self.packages
                .get(name)
                .and_then(|v| best_package(v).map(|p| (name, p)))
        })
    }

    /// Converts into a HashMap with the best version per package name.
    pub fn into_map(self) -> HashMap<String, ResolvedPackage> {
        self.packages
            .into_iter()
            .filter_map(|(name, versions)| best_package(&versions).cloned().map(|p| (name, p)))
            .collect()
    }
}

/// Lock file provider trait for ecosystem-specific implementations.
///
/// Implementations parse lock files for a specific package ecosystem
/// (Cargo.lock, package-lock.json, etc.) and extract resolved versions.
///
/// # Examples
///
/// ```no_run
/// use deps_core::lockfile::{LockFileProvider, ResolvedPackages};
/// use std::path::{Path, PathBuf};
/// use tower_lsp_server::ls_types::Uri;
///
/// struct MyLockParser;
///
/// impl LockFileProvider for MyLockParser {
///     fn locate_lockfile(&self, manifest_uri: &Uri) -> Option<PathBuf> {
///         let manifest_path = manifest_uri.to_file_path()?;
///         let lock_path = manifest_path.with_file_name("my.lock");
///         lock_path.exists().then_some(lock_path)
///     }
///
///     fn parse_lockfile<'a>(&'a self, lockfile_path: &'a Path) -> std::pin::Pin<Box<dyn std::future::Future<Output = deps_core::error::Result<ResolvedPackages>> + Send + 'a>> {
///         Box::pin(async move {
///             // Parse lock file format and extract packages
///             Ok(ResolvedPackages::new())
///         })
///     }
/// }
/// ```
pub trait LockFileProvider: Send + Sync {
    /// Locates the lock file for a given manifest URI.
    ///
    /// Returns `None` if:
    /// - Lock file doesn't exist
    /// - Manifest path cannot be determined from URI
    /// - Workspace root search fails
    ///
    /// # Arguments
    ///
    /// * `manifest_uri` - URI of the manifest file (Cargo.toml, package.json, etc.)
    ///
    /// # Returns
    ///
    /// Path to lock file if found
    fn locate_lockfile(&self, manifest_uri: &Uri) -> Option<PathBuf>;

    /// Parses a lock file and extracts resolved packages.
    ///
    /// # Arguments
    ///
    /// * `lockfile_path` - Path to the lock file
    ///
    /// # Returns
    ///
    /// ResolvedPackages on success, error if parse fails
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - File cannot be read
    /// - File format is invalid
    /// - Required fields are missing
    fn parse_lockfile<'a>(
        &'a self,
        lockfile_path: &'a Path,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<ResolvedPackages>> + Send + 'a>>;

    /// Checks if lock file has been modified since last parse.
    ///
    /// Used for cache invalidation. Default implementation compares
    /// file modification time.
    ///
    /// # Arguments
    ///
    /// * `lockfile_path` - Path to the lock file
    /// * `last_modified` - Last known modification time
    ///
    /// # Returns
    ///
    /// `true` if file has been modified or cannot be stat'd, `false` otherwise
    fn is_lockfile_stale(&self, lockfile_path: &Path, last_modified: SystemTime) -> bool {
        if let Ok(metadata) = std::fs::metadata(lockfile_path)
            && let Ok(mtime) = metadata.modified()
        {
            return mtime > last_modified;
        }
        true
    }
}

/// Cached lock file entry with staleness detection.
struct CachedLockFile {
    packages: ResolvedPackages,
    modified_at: SystemTime,
    #[allow(dead_code)]
    parsed_at: Instant,
}

/// Cache for parsed lock files with automatic staleness detection.
///
/// Caches parsed lock file contents and checks file modification time
/// to avoid re-parsing unchanged files. Thread-safe for concurrent access.
///
/// # Examples
///
/// ```no_run
/// use deps_core::lockfile::LockFileCache;
/// use std::path::Path;
///
/// # async fn example() -> deps_core::error::Result<()> {
/// let cache = LockFileCache::new();
/// // First call parses the file
/// // Second call returns cached result if file hasn't changed
/// # Ok(())
/// # }
/// ```
pub struct LockFileCache {
    entries: DashMap<PathBuf, CachedLockFile>,
}

impl LockFileCache {
    /// Creates a new empty lock file cache.
    pub fn new() -> Self {
        Self {
            entries: DashMap::new(),
        }
    }

    /// Gets parsed packages from cache or parses the lock file.
    ///
    /// Checks file modification time to detect changes. If the file
    /// has been modified since last parse, re-parses it. Otherwise,
    /// returns the cached result.
    ///
    /// # Arguments
    ///
    /// * `provider` - Lock file provider implementation
    /// * `lockfile_path` - Path to the lock file
    ///
    /// # Returns
    ///
    /// Resolved packages on success
    ///
    /// # Errors
    ///
    /// Returns error if file cannot be read or parsed
    pub async fn get_or_parse(
        &self,
        provider: &dyn LockFileProvider,
        lockfile_path: &Path,
    ) -> Result<ResolvedPackages> {
        // Extract owned data from the cache entry before awaiting: the DashMap shard
        // `Ref` returned by `entries.get` must not be held across `.await`, or a
        // concurrent access to the same key blocks for the duration (#350, same hazard
        // class as #333).
        let cached = self
            .entries
            .get(lockfile_path)
            .map(|entry| (entry.modified_at, entry.packages.clone()));

        // Check cache first
        if let Some((cached_modified_at, cached_packages)) = cached
            && let Ok(metadata) = tokio::fs::metadata(lockfile_path).await
            && let Ok(mtime) = metadata.modified()
            && mtime <= cached_modified_at
        {
            tracing::debug!("Lock file cache hit: {}", lockfile_path.display());
            return Ok(cached_packages);
        }

        // Cache miss - parse and store.
        //
        // Stat the file *before* parsing and use that pre-parse mtime as the cache
        // key's freshness marker. If we stat'd after `parse_lockfile` instead, a
        // concurrent rewrite landing mid-parse would let us store content read from
        // the old version of the file under the new version's mtime, making the
        // entry look fresh when it is actually stale (#359).
        tracing::debug!("Lock file cache miss: {}", lockfile_path.display());
        let metadata = tokio::fs::metadata(lockfile_path).await?;
        let modified_at = metadata.modified()?;

        let packages = provider.parse_lockfile(lockfile_path).await?;

        self.entries.insert(
            lockfile_path.to_path_buf(),
            CachedLockFile {
                packages: packages.clone(),
                modified_at,
                parsed_at: Instant::now(),
            },
        );

        Ok(packages)
    }

    /// Invalidates cached entry for a lock file.
    ///
    /// Forces next access to re-parse the file. Use when you know
    /// the file has changed but modification time might not reflect it.
    pub fn invalidate(&self, lockfile_path: &Path) {
        self.entries.remove(lockfile_path);
    }

    /// Returns the number of cached lock files.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns true if the cache is empty.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

impl Default for LockFileCache {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[tokio::test]
    async fn test_read_lockfile_content_success() {
        let temp_dir = tempfile::tempdir().unwrap();
        let lock_path = temp_dir.path().join("Cargo.lock");
        std::fs::write(&lock_path, "version = 4").unwrap();

        let content = read_lockfile_content(&lock_path, "Cargo.lock")
            .await
            .unwrap();

        assert_eq!(content, "version = 4");
    }

    #[tokio::test]
    async fn test_read_lockfile_content_missing_file_wraps_error() {
        let temp_dir = tempfile::tempdir().unwrap();
        let lock_path = temp_dir.path().join("Cargo.lock");

        let err = read_lockfile_content(&lock_path, "Cargo.lock")
            .await
            .unwrap_err();

        match err {
            DepsError::ParseError { file_type, .. } => {
                assert_eq!(file_type, format!("Cargo.lock at {}", lock_path.display()));
            }
            other => panic!("Expected ParseError, got: {other:?}"),
        }
    }

    #[test]
    fn test_resolved_packages_new() {
        let packages = ResolvedPackages::new();
        assert!(packages.is_empty());
        assert_eq!(packages.len(), 0);
    }

    #[test]
    fn test_resolved_packages_insert_and_get() {
        let mut packages = ResolvedPackages::new();

        let pkg = ResolvedPackage {
            name: "serde".into(),
            version: "1.0.195".into(),
            source: ResolvedSource::Registry {
                url: "https://github.com/rust-lang/crates.io-index".into(),
                checksum: "abc123".into(),
            },
            dependencies: vec!["serde_derive".into()],
        };

        packages.insert(pkg);

        assert_eq!(packages.len(), 1);
        assert!(!packages.is_empty());
        assert_eq!(packages.get_version("serde"), Some("1.0.195"));

        let retrieved = packages.get("serde");
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().name, "serde");
        assert_eq!(retrieved.unwrap().dependencies.len(), 1);
    }

    #[test]
    fn test_resolved_packages_get_nonexistent() {
        let packages = ResolvedPackages::new();
        assert_eq!(packages.get("nonexistent"), None);
        assert_eq!(packages.get_version("nonexistent"), None);
    }

    #[test]
    fn test_resolved_packages_replace() {
        let mut packages = ResolvedPackages::new();

        packages.insert(ResolvedPackage {
            name: "serde".into(),
            version: "1.0.0".into(),
            source: ResolvedSource::Registry {
                url: "test".into(),
                checksum: "old".into(),
            },
            dependencies: vec![],
        });

        packages.insert(ResolvedPackage {
            name: "serde".into(),
            version: "1.0.195".into(),
            source: ResolvedSource::Registry {
                url: "test".into(),
                checksum: "new".into(),
            },
            dependencies: vec![],
        });

        // Both versions stored, but len counts unique names
        assert_eq!(packages.len(), 1);
        assert_eq!(packages.get_version("serde"), Some("1.0.195"));
        // Both versions accessible via get_all
        assert_eq!(packages.get_all("serde").unwrap().len(), 2);
    }

    #[test]
    fn test_resolved_packages_multiple_versions() {
        let mut packages = ResolvedPackages::new();

        packages.insert(ResolvedPackage {
            name: "serde".into(),
            version: "1.0.195".into(),
            source: ResolvedSource::Registry {
                url: "test".into(),
                checksum: "a".into(),
            },
            dependencies: vec![],
        });

        packages.insert(ResolvedPackage {
            name: "serde".into(),
            version: "0.9.0".into(),
            source: ResolvedSource::Registry {
                url: "test".into(),
                checksum: "b".into(),
            },
            dependencies: vec![],
        });

        packages.insert(ResolvedPackage {
            name: "serde".into(),
            version: "2.0.0-beta.1".into(),
            source: ResolvedSource::Registry {
                url: "test".into(),
                checksum: "c".into(),
            },
            dependencies: vec![],
        });

        assert_eq!(packages.len(), 1);
        assert_eq!(packages.get_version("serde"), Some("2.0.0-beta.1"));
        assert_eq!(packages.get_all("serde").unwrap().len(), 3);
    }

    #[test]
    fn test_resolved_packages_non_semver_fallback() {
        let mut packages = ResolvedPackages::new();

        packages.insert(ResolvedPackage {
            name: "weird".into(),
            version: "abc".into(),
            source: ResolvedSource::Path { path: ".".into() },
            dependencies: vec![],
        });

        packages.insert(ResolvedPackage {
            name: "weird".into(),
            version: "xyz".into(),
            source: ResolvedSource::Path { path: ".".into() },
            dependencies: vec![],
        });

        // Falls back to string comparison: "xyz" > "abc"
        assert_eq!(packages.get_version("weird"), Some("xyz"));
    }

    #[test]
    fn test_resolved_packages_semver_preferred_over_non_semver() {
        let mut packages = ResolvedPackages::new();

        packages.insert(ResolvedPackage {
            name: "mixed".into(),
            version: "not-a-version".into(),
            source: ResolvedSource::Path { path: ".".into() },
            dependencies: vec![],
        });

        packages.insert(ResolvedPackage {
            name: "mixed".into(),
            version: "1.0.0".into(),
            source: ResolvedSource::Path { path: ".".into() },
            dependencies: vec![],
        });

        // Parseable semver is preferred over non-parseable
        assert_eq!(packages.get_version("mixed"), Some("1.0.0"));
    }

    #[test]
    fn test_resolved_source_equality() {
        let source1 = ResolvedSource::Registry {
            url: "https://test.com".into(),
            checksum: "abc".into(),
        };
        let source2 = ResolvedSource::Registry {
            url: "https://test.com".into(),
            checksum: "abc".into(),
        };
        let source3 = ResolvedSource::Git {
            url: "https://github.com/test".into(),
            rev: "abc123".into(),
        };

        assert_eq!(source1, source2);
        assert_ne!(source1, source3);
    }

    #[test]
    fn test_resolved_packages_iter() {
        let mut packages = ResolvedPackages::new();

        packages.insert(ResolvedPackage {
            name: "serde".into(),
            version: "1.0.0".into(),
            source: ResolvedSource::Registry {
                url: "test".into(),
                checksum: "a".into(),
            },
            dependencies: vec![],
        });

        packages.insert(ResolvedPackage {
            name: "tokio".into(),
            version: "1.0.0".into(),
            source: ResolvedSource::Registry {
                url: "test".into(),
                checksum: "b".into(),
            },
            dependencies: vec![],
        });

        let count = packages.iter().count();
        assert_eq!(count, 2);

        let names: Vec<_> = packages.iter().map(|(name, _)| name.as_str()).collect();
        assert!(names.contains(&"serde"));
        assert!(names.contains(&"tokio"));
    }

    #[test]
    fn test_resolved_packages_into_map() {
        let mut packages = ResolvedPackages::new();

        packages.insert(ResolvedPackage {
            name: "serde".into(),
            version: "1.0.0".into(),
            source: ResolvedSource::Registry {
                url: "test".into(),
                checksum: "a".into(),
            },
            dependencies: vec![],
        });

        let map = packages.into_map();
        assert_eq!(map.len(), 1);
        assert!(map.contains_key("serde"));
    }

    #[test]
    fn test_lockfile_cache_new() {
        let cache = LockFileCache::new();
        assert!(cache.is_empty());
        assert_eq!(cache.len(), 0);
    }

    #[test]
    fn test_lockfile_cache_invalidate() {
        let cache = LockFileCache::new();
        let test_path = PathBuf::from("/test/Cargo.lock");

        cache.entries.insert(
            test_path.clone(),
            CachedLockFile {
                packages: ResolvedPackages::new(),
                modified_at: SystemTime::now(),
                parsed_at: Instant::now(),
            },
        );

        assert_eq!(cache.len(), 1);

        cache.invalidate(&test_path);
        assert_eq!(cache.len(), 0);
        assert!(cache.is_empty());
    }

    #[test]
    fn test_locate_lockfile_for_manifest_same_directory() {
        let temp_dir = tempfile::tempdir().unwrap();
        let manifest_path = temp_dir.path().join("Cargo.toml");
        let lock_path = temp_dir.path().join("Cargo.lock");

        std::fs::write(&manifest_path, "[package]\nname = \"test\"").unwrap();
        std::fs::write(&lock_path, "version = 4").unwrap();

        let manifest_uri = Uri::from_file_path(&manifest_path).unwrap();
        let located = locate_lockfile_for_manifest(&manifest_uri, &["Cargo.lock"]);

        assert!(located.is_some());
        assert_eq!(located.unwrap(), lock_path);
    }

    #[test]
    fn test_locate_lockfile_for_manifest_workspace_root() {
        let temp_dir = tempfile::tempdir().unwrap();
        let workspace_lock = temp_dir.path().join("Cargo.lock");
        let member_dir = temp_dir.path().join("crates").join("member");
        std::fs::create_dir_all(&member_dir).unwrap();
        let member_manifest = member_dir.join("Cargo.toml");

        std::fs::write(&workspace_lock, "version = 4").unwrap();
        std::fs::write(&member_manifest, "[package]\nname = \"member\"").unwrap();

        let manifest_uri = Uri::from_file_path(&member_manifest).unwrap();
        let located = locate_lockfile_for_manifest(&manifest_uri, &["Cargo.lock"]);

        assert!(located.is_some());
        assert_eq!(located.unwrap(), workspace_lock);
    }

    #[test]
    fn test_locate_lockfile_for_manifest_not_found() {
        let temp_dir = tempfile::tempdir().unwrap();
        let manifest_path = temp_dir.path().join("Cargo.toml");
        std::fs::write(&manifest_path, "[package]\nname = \"test\"").unwrap();

        let manifest_uri = Uri::from_file_path(&manifest_path).unwrap();
        let located = locate_lockfile_for_manifest(&manifest_uri, &["Cargo.lock"]);

        assert!(located.is_none());
    }

    #[test]
    fn test_locate_lockfile_for_manifest_multiple_names() {
        let temp_dir = tempfile::tempdir().unwrap();
        let manifest_path = temp_dir.path().join("pyproject.toml");
        let uv_lock = temp_dir.path().join("uv.lock");

        std::fs::write(&manifest_path, "[project]\nname = \"test\"").unwrap();
        std::fs::write(&uv_lock, "version = 1").unwrap();

        let manifest_uri = Uri::from_file_path(&manifest_path).unwrap();
        // poetry.lock doesn't exist, but uv.lock does - should find uv.lock
        let located = locate_lockfile_for_manifest(&manifest_uri, &["poetry.lock", "uv.lock"]);

        assert!(located.is_some());
        assert_eq!(located.unwrap(), uv_lock);
    }

    /// Stub [`LockFileProvider`] that counts `parse_lockfile` invocations and returns
    /// a package whose version is the lock file's trimmed content, so tests can
    /// observe both call count and which content was actually parsed.
    struct CountingLockFileProvider {
        parse_count: std::sync::atomic::AtomicUsize,
    }

    impl CountingLockFileProvider {
        fn new() -> Self {
            Self {
                parse_count: std::sync::atomic::AtomicUsize::new(0),
            }
        }

        fn parse_count(&self) -> usize {
            self.parse_count.load(std::sync::atomic::Ordering::SeqCst)
        }
    }

    impl LockFileProvider for CountingLockFileProvider {
        fn locate_lockfile(&self, _manifest_uri: &Uri) -> Option<PathBuf> {
            None
        }

        fn parse_lockfile<'a>(
            &'a self,
            lockfile_path: &'a Path,
        ) -> std::pin::Pin<
            Box<dyn std::future::Future<Output = Result<ResolvedPackages>> + Send + 'a>,
        > {
            Box::pin(async move {
                self.parse_count
                    .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                let content = read_lockfile_content(lockfile_path, "test.lock").await?;

                let mut packages = ResolvedPackages::new();
                packages.insert(ResolvedPackage {
                    name: "test-package".into(),
                    version: content.trim().to_string(),
                    source: ResolvedSource::Path { path: ".".into() },
                    dependencies: vec![],
                });
                Ok(packages)
            })
        }
    }

    #[tokio::test]
    async fn test_get_or_parse_cache_hit_does_not_reparse() {
        let temp_dir = tempfile::tempdir().unwrap();
        let lock_path = temp_dir.path().join("test.lock");
        std::fs::write(&lock_path, "1.0.0").unwrap();

        let provider = CountingLockFileProvider::new();
        let cache = LockFileCache::new();

        let first = cache.get_or_parse(&provider, &lock_path).await.unwrap();
        let second = cache.get_or_parse(&provider, &lock_path).await.unwrap();

        assert_eq!(provider.parse_count(), 1, "second call should hit cache");
        assert_eq!(first.get_version("test-package"), Some("1.0.0"));
        assert_eq!(second.get_version("test-package"), Some("1.0.0"));
    }

    #[tokio::test]
    async fn test_get_or_parse_reparses_when_mtime_advances() {
        let temp_dir = tempfile::tempdir().unwrap();
        let lock_path = temp_dir.path().join("test.lock");
        std::fs::write(&lock_path, "1.0.0").unwrap();

        let provider = CountingLockFileProvider::new();
        let cache = LockFileCache::new();

        let first = cache.get_or_parse(&provider, &lock_path).await.unwrap();
        assert_eq!(first.get_version("test-package"), Some("1.0.0"));

        std::fs::write(&lock_path, "2.0.0").unwrap();
        // Explicitly bump mtime into the future rather than relying on filesystem
        // mtime resolution (coarse on some platforms) to observe the change.
        let future_mtime = SystemTime::now() + std::time::Duration::from_secs(5);
        std::fs::OpenOptions::new()
            .write(true)
            .open(&lock_path)
            .unwrap()
            .set_modified(future_mtime)
            .unwrap();

        let second = cache.get_or_parse(&provider, &lock_path).await.unwrap();

        assert_eq!(
            provider.parse_count(),
            2,
            "stale mtime should trigger reparse"
        );
        assert_eq!(second.get_version("test-package"), Some("2.0.0"));
    }

    /// Stub [`LockFileProvider`] that simulates a concurrent writer racing the parse:
    /// each `parse_lockfile` call reads the file's *current* content first, then — as
    /// a side effect before returning — rewrites the file to `"2.0.0"` and bumps its
    /// mtime into the future, then returns packages parsed from the content it read
    /// *before* that rewrite. This reproduces the only await point between the
    /// `get_or_parse` stat and cache insert, entirely under test control.
    struct RewritingDuringParseProvider {
        parse_count: std::sync::atomic::AtomicUsize,
    }

    impl RewritingDuringParseProvider {
        fn new() -> Self {
            Self {
                parse_count: std::sync::atomic::AtomicUsize::new(0),
            }
        }

        fn parse_count(&self) -> usize {
            self.parse_count.load(std::sync::atomic::Ordering::SeqCst)
        }
    }

    impl LockFileProvider for RewritingDuringParseProvider {
        fn locate_lockfile(&self, _manifest_uri: &Uri) -> Option<PathBuf> {
            None
        }

        fn parse_lockfile<'a>(
            &'a self,
            lockfile_path: &'a Path,
        ) -> std::pin::Pin<
            Box<dyn std::future::Future<Output = Result<ResolvedPackages>> + Send + 'a>,
        > {
            Box::pin(async move {
                self.parse_count
                    .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                let content = read_lockfile_content(lockfile_path, "test.lock").await?;

                // Simulate a writer rewriting the lock file mid-parse.
                std::fs::write(lockfile_path, "2.0.0").unwrap();
                let future_mtime = SystemTime::now() + std::time::Duration::from_secs(5);
                std::fs::OpenOptions::new()
                    .write(true)
                    .open(lockfile_path)
                    .unwrap()
                    .set_modified(future_mtime)
                    .unwrap();

                let mut packages = ResolvedPackages::new();
                packages.insert(ResolvedPackage {
                    name: "test-package".into(),
                    version: content.trim().to_string(),
                    source: ResolvedSource::Path { path: ".".into() },
                    dependencies: vec![],
                });
                Ok(packages)
            })
        }
    }

    /// Regression test for #359: discriminates the stat-before-parse fix from the
    /// original stat-after-parse ordering.
    ///
    /// With the fix, `get_or_parse` stats the file *before* calling `parse_lockfile`,
    /// so the cached `modified_at` reflects the pre-rewrite mtime tied to the
    /// `"1.0.0"` content actually parsed. A second call then sees the file's mtime is
    /// newer than the cached one, so it re-parses and observes `"2.0.0"`.
    ///
    /// On the pre-fix ordering (stat after parse), the post-parse stat would pick up
    /// the mtime bump this same call just made, storing the *new* mtime alongside the
    /// *old* (`"1.0.0"`) content. The second call would then incorrectly hit cache and
    /// return stale `"1.0.0"` content without re-parsing — exactly the bug #359
    /// describes. This test would have failed on that code.
    #[tokio::test]
    async fn test_get_or_parse_detects_rewrite_during_parse() {
        let temp_dir = tempfile::tempdir().unwrap();
        let lock_path = temp_dir.path().join("test.lock");
        std::fs::write(&lock_path, "1.0.0").unwrap();

        let provider = RewritingDuringParseProvider::new();
        let cache = LockFileCache::new();

        let first = cache.get_or_parse(&provider, &lock_path).await.unwrap();
        assert_eq!(first.get_version("test-package"), Some("1.0.0"));

        let second = cache.get_or_parse(&provider, &lock_path).await.unwrap();

        assert_eq!(
            provider.parse_count(),
            2,
            "rewrite during first parse must be detected and trigger a reparse"
        );
        assert_eq!(second.get_version("test-package"), Some("2.0.0"));
    }

    #[test]
    fn test_locate_lockfile_for_manifest_first_match_wins() {
        let temp_dir = tempfile::tempdir().unwrap();
        let manifest_path = temp_dir.path().join("pyproject.toml");
        let poetry_lock = temp_dir.path().join("poetry.lock");
        let uv_lock = temp_dir.path().join("uv.lock");

        std::fs::write(&manifest_path, "[project]\nname = \"test\"").unwrap();
        std::fs::write(&poetry_lock, "# poetry lock").unwrap();
        std::fs::write(&uv_lock, "version = 1").unwrap();

        let manifest_uri = Uri::from_file_path(&manifest_path).unwrap();
        // Both exist, poetry.lock should be found first (listed first)
        let located = locate_lockfile_for_manifest(&manifest_uri, &["poetry.lock", "uv.lock"]);

        assert!(located.is_some());
        assert_eq!(located.unwrap(), poetry_lock);
    }
}