soldeer-core 0.10.0

Core functionality for Soldeer
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
//! Lockfile handling.
//!
//! The lockfile contains the resolved dependencies of a project. It is a TOML file with an array of
//! dependencies, each containing the name, version, and other information about the dependency.
//!
//! The lockfile is used to ensure that the same versions of dependencies are installed across
//! different machines. It is also used to skip the installation of dependencies that are already
//! installed.
use crate::{config::Dependency, errors::LockError, utils::sanitize_filename};
use log::{debug, warn};
use serde::{Deserialize, Serialize};
use std::{
    fs,
    path::{Path, PathBuf},
};

pub type Result<T> = std::result::Result<T, LockError>;

/// A trait implemented by lockfile entries to provide the install path
pub trait Integrity {
    /// Returns the install path of the dependency.
    fn install_path(&self, deps: impl AsRef<Path>) -> PathBuf;

    /// Returns the integrity checksum if relevant.
    fn integrity(&self) -> Option<&String>;
}

/// A lock entry for a git dependency.
#[derive(Debug, Clone, PartialEq, Eq, Hash, bon::Builder)]
#[builder(on(String, into))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[non_exhaustive]
pub struct GitLockEntry {
    /// The name of the dependency.
    pub name: String,

    /// The version (this corresponds to the version requirement of the dependency).
    pub version: String,

    /// The git url of the dependency.
    pub git: String,

    /// The resolved git commit hash.
    pub rev: String,
}

impl Integrity for GitLockEntry {
    /// Returns the install path of the dependency.
    ///
    /// The directory does not need to exist. Since the lock entry contains the version,
    /// the install path can be calculated without needing to check the actual directory.
    fn install_path(&self, deps: impl AsRef<Path>) -> PathBuf {
        format_install_path(&self.name, &self.version, deps)
    }

    /// There is no integrity checksum for git lock entries
    fn integrity(&self) -> Option<&String> {
        None
    }
}

/// A lock entry for an HTTP dependency.
#[derive(Debug, Clone, PartialEq, Eq, Hash, bon::Builder)]
#[builder(on(String, into))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[non_exhaustive]
pub struct HttpLockEntry {
    /// The name of the dependency.
    pub name: String,

    /// The resolved version of the dependency (not necessarily matches the version requirement of
    /// the dependency).
    ///
    /// If the version req is a semver range, then this will be the exact version that was
    /// resolved.
    pub version: String,

    /// The URL from where the dependency was downloaded.
    pub url: String,

    /// The checksum of the downloaded zip file.
    pub checksum: String,

    /// The integrity hash of the downloaded zip file after extraction.
    pub integrity: String,
}

impl Integrity for HttpLockEntry {
    /// Returns the install path of the dependency.
    ///
    /// The directory does not need to exist. Since the lock entry contains the version,
    /// the install path can be calculated without needing to check the actual directory.
    fn install_path(&self, deps: impl AsRef<Path>) -> PathBuf {
        format_install_path(&self.name, &self.version, deps)
    }

    /// Returns the integrity checksum
    fn integrity(&self) -> Option<&String> {
        Some(&self.integrity)
    }
}

/// A lock entry for a private dependency.
///
/// The link is not stored in the lockfile as it must be fetched from the registry with a valid
/// token before each download.
#[derive(Debug, Clone, PartialEq, Eq, Hash, bon::Builder)]
#[builder(on(String, into))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[non_exhaustive]
pub struct PrivateLockEntry {
    /// The name of the dependency.
    pub name: String,

    /// The resolved version of the dependency (not necessarily matches the version requirement of
    /// the dependency).
    ///
    /// If the version req is a semver range, then this will be the exact version that was
    /// resolved.
    pub version: String,

    /// The checksum of the downloaded zip file.
    pub checksum: String,

    /// The integrity hash of the downloaded zip file after extraction.
    pub integrity: String,
}

impl Integrity for PrivateLockEntry {
    /// Returns the install path of the dependency.
    ///
    /// The directory does not need to exist. Since the lock entry contains the version,
    /// the install path can be calculated without needing to check the actual directory.
    fn install_path(&self, deps: impl AsRef<Path>) -> PathBuf {
        format_install_path(&self.name, &self.version, deps)
    }

    /// Returns the integrity checksum
    fn integrity(&self) -> Option<&String> {
        Some(&self.integrity)
    }
}

/// A lock entry for a dependency.
///
/// A builder should be used to create the underlying [`HttpLockEntry`] or [`GitLockEntry`] and then
/// converted into this type with `.into()`.
///
/// # Examples
///
/// ```
/// # use soldeer_core::lock::{LockEntry, HttpLockEntry};
/// let dep: LockEntry = HttpLockEntry::builder()
///     .name("my-dep")
///     .version("1.2.3")
///     .url("https://...")
///     .checksum("dead")
///     .integrity("beef")
///     .build()
///     .into();
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
#[non_exhaustive]
pub enum LockEntry {
    /// A lock entry for an HTTP dependency.
    Http(HttpLockEntry),

    /// A lock entry for a git dependency.
    Git(GitLockEntry),

    /// A lock entry for a git dependency.
    Private(PrivateLockEntry),
}

/// A TOML representation of a lock entry, which merges all fields from the two variants of
/// [`LockEntry`].
///
/// This is used to serialize and deserialize lock entries to and from TOML. All fields which are
/// not present in both variants are optional.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct TomlLockEntry {
    pub name: String,
    pub version: String,
    pub git: Option<String>,
    pub url: Option<String>,
    pub rev: Option<String>,
    pub checksum: Option<String>,
    pub integrity: Option<String>,
}

impl From<LockEntry> for TomlLockEntry {
    /// Convert a [`LockEntry`] into a [`TomlLockEntry`].
    fn from(value: LockEntry) -> Self {
        match value {
            LockEntry::Http(lock) => Self {
                name: lock.name,
                version: lock.version,
                git: None,
                url: Some(lock.url),
                rev: None,
                checksum: Some(lock.checksum),
                integrity: Some(lock.integrity),
            },
            LockEntry::Git(lock) => Self {
                name: lock.name,
                version: lock.version,
                git: Some(lock.git),
                url: None,
                rev: Some(lock.rev),
                checksum: None,
                integrity: None,
            },
            LockEntry::Private(lock) => Self {
                name: lock.name,
                version: lock.version,
                git: None,
                url: None,
                rev: None,
                checksum: Some(lock.checksum),
                integrity: Some(lock.integrity),
            },
        }
    }
}

impl TryFrom<TomlLockEntry> for LockEntry {
    type Error = LockError;

    /// Convert a [`TomlLockEntry`] into a [`LockEntry`] if possible.
    fn try_from(value: TomlLockEntry) -> std::result::Result<Self, Self::Error> {
        match (value.url, value.git) {
            (None, None) => Ok(PrivateLockEntry::builder()
                .name(&value.name)
                .version(value.version)
                .checksum(value.checksum.ok_or(LockError::MissingField {
                    field: "checksum".to_string(),
                    dep: value.name.clone(),
                })?)
                .integrity(value.integrity.ok_or(LockError::MissingField {
                    field: "integrity".to_string(),
                    dep: value.name,
                })?)
                .build()
                .into()),
            (None, Some(git)) => {
                Ok(GitLockEntry::builder()
                    .name(&value.name)
                    .version(value.version)
                    .git(git)
                    .rev(value.rev.ok_or(LockError::MissingField {
                        field: "rev".to_string(),
                        dep: value.name,
                    })?)
                    .build()
                    .into())
            }
            (Some(url), None) => Ok(HttpLockEntry::builder()
                .name(&value.name)
                .version(value.version)
                .url(url)
                .checksum(value.checksum.ok_or(LockError::MissingField {
                    field: "checksum".to_string(),
                    dep: value.name.clone(),
                })?)
                .integrity(value.integrity.ok_or(LockError::MissingField {
                    field: "integrity".to_string(),
                    dep: value.name,
                })?)
                .build()
                .into()),
            (Some(_), Some(_)) => Err(LockError::InvalidLockEntry),
        }
    }
}

impl LockEntry {
    /// The name of the dependency.
    pub fn name(&self) -> &str {
        match self {
            Self::Git(lock) => &lock.name,
            Self::Http(lock) => &lock.name,
            Self::Private(lock) => &lock.name,
        }
    }

    /// The version of the dependency.
    pub fn version(&self) -> &str {
        match self {
            Self::Git(lock) => &lock.version,
            Self::Http(lock) => &lock.version,
            Self::Private(lock) => &lock.version,
        }
    }

    /// The install path of the dependency.
    pub fn install_path(&self, deps: impl AsRef<Path>) -> PathBuf {
        match self {
            Self::Git(lock) => lock.install_path(deps),
            Self::Http(lock) => lock.install_path(deps),
            Self::Private(lock) => lock.install_path(deps),
        }
    }

    /// Get the underlying [`HttpLockEntry`] if this is an HTTP lock entry.
    pub fn as_http(&self) -> Option<&HttpLockEntry> {
        if let Self::Http(l) = self { Some(l) } else { None }
    }

    /// Get the underlying [`GitLockEntry`] if this is a git lock entry.
    pub fn as_git(&self) -> Option<&GitLockEntry> {
        if let Self::Git(l) = self { Some(l) } else { None }
    }

    /// Get the underlying [`PrivateLockEntry`] if this is a private package lock entry.
    pub fn as_private(&self) -> Option<&PrivateLockEntry> {
        if let Self::Private(l) = self { Some(l) } else { None }
    }
}

impl From<HttpLockEntry> for LockEntry {
    /// Wrap an [`HttpLockEntry`] in a [`LockEntry`].
    fn from(value: HttpLockEntry) -> Self {
        Self::Http(value)
    }
}

impl From<GitLockEntry> for LockEntry {
    /// Wrap a [`GitLockEntry`] in a [`LockEntry`].
    fn from(value: GitLockEntry) -> Self {
        Self::Git(value)
    }
}

impl From<PrivateLockEntry> for LockEntry {
    /// Wrap a [`PrivateLockEntry`] in a [`LockEntry`].
    fn from(value: PrivateLockEntry) -> Self {
        Self::Private(value)
    }
}

/// A parsed TOML lock file.
///
/// The lockfile is a table with one entry `dependencies` containing an array of [`TomlLockEntry`]s.
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, Hash)]
struct LockFileParsed {
    dependencies: Vec<TomlLockEntry>,
}

/// The result of reading and parsing a lock file.
///
/// The [`TomlLockEntry`]s are converted into [`LockEntry`]s. A copy of the text contents of
/// the lockfile is provided for diffing purposes.
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct LockFile {
    /// The parsed lock entries.
    pub entries: Vec<LockEntry>,

    /// The raw contents of the lockfile.
    pub raw: String,
}

/// Read a lockfile from disk.
pub fn read_lockfile(path: impl AsRef<Path>) -> Result<LockFile> {
    if !path.as_ref().exists() {
        debug!(path:? = path.as_ref(); "lockfile does not exist");
        return Ok(LockFile::default());
    }
    let contents = fs::read_to_string(&path)?;

    let data: LockFileParsed = toml_edit::de::from_str(&contents)
        .inspect_err(|err| {
            warn!(err:?; "error while parsing lockfile contents, it will be ignored");
        })
        .unwrap_or_default();
    Ok(LockFile {
        entries: data.dependencies.into_iter().filter_map(|d| d.try_into().ok()).collect(),
        raw: contents,
    })
}

/// Generate the contents of a lockfile from a list of lock entries.
///
/// The entries do not need to be sorted, they will be sorted by name.
pub fn generate_lockfile_contents(mut entries: Vec<LockEntry>) -> String {
    entries.sort_unstable_by(|a, b| a.name().cmp(b.name()));
    let data = LockFileParsed { dependencies: entries.into_iter().map(Into::into).collect() };
    toml_edit::ser::to_string_pretty(&data).expect("Lock entries should be serializable")
}

/// Add a lock entry to a lockfile.
///
/// If an entry with the same name already exists, it will be replaced.
/// The entries are sorted by name before being written back to the file.
pub fn add_to_lockfile(entry: LockEntry, path: impl AsRef<Path>) -> Result<()> {
    let mut lockfile = read_lockfile(&path)?;
    if let Some(index) = lockfile.entries.iter().position(|e| e.name() == entry.name()) {
        debug!(name = entry.name(); "replacing existing lockfile entry");
        let _ = std::mem::replace(&mut lockfile.entries[index], entry);
    } else {
        debug!(name = entry.name(); "adding new lockfile entry");
        lockfile.entries.push(entry);
    }
    let new_contents = generate_lockfile_contents(lockfile.entries);
    fs::write(&path, new_contents)?;
    debug!(path:? = path.as_ref(); "lockfile modified");
    Ok(())
}

/// Remove a lock entry from a lockfile, matching on the name.
///
/// If the entry is the last entry in the lockfile, the lockfile will be removed.
pub fn remove_lock(dependency: &Dependency, path: impl AsRef<Path>) -> Result<()> {
    let lockfile = read_lockfile(&path)?;

    let entries: Vec<_> = lockfile
        .entries
        .into_iter()
        .filter_map(|e| if e.name() != dependency.name() { Some(e.into()) } else { None })
        .collect();

    if entries.is_empty() {
        // remove lock file if there are no deps left
        debug!(path:? = path.as_ref(); "no remaining lockfile entry, deleting file");
        let _ = fs::remove_file(&path);
        return Ok(());
    }

    let file_contents =
        toml_edit::ser::to_string_pretty(&LockFileParsed { dependencies: entries })?;

    // replace contents of lockfile with new contents
    fs::write(&path, file_contents)?;
    debug!(path:? = path.as_ref(); "lockfile modified");
    Ok(())
}

/// Format the install path of a dependency.
///
/// The folder name is sanitized to remove disallowed characters.
pub fn format_install_path(name: &str, version: &str, deps: impl AsRef<Path>) -> PathBuf {
    deps.as_ref().join(sanitize_filename(&format!("{name}-{version}")))
}

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

    #[test]
    fn test_toml_to_lock_entry_conversion_http() {
        let toml_entry = TomlLockEntry {
            name: "test".to_string(),
            version: "1.0.0".to_string(),
            git: None,
            url: Some("https://example.com/zip.zip".to_string()),
            rev: None,
            checksum: Some("123456".to_string()),
            integrity: Some("beef".to_string()),
        };
        let entry: Result<LockEntry> = toml_entry.try_into();
        assert!(entry.is_ok(), "{entry:?}");
        let entry = entry.unwrap();
        assert_eq!(entry.name(), "test");
        assert_eq!(entry.version(), "1.0.0");
        let http = entry.as_http().unwrap();
        assert_eq!(http.url, "https://example.com/zip.zip");
        assert_eq!(http.checksum, "123456");
        assert_eq!(http.integrity, "beef");
    }

    #[test]
    fn test_toml_to_lock_entry_conversion_git() {
        let toml_entry = TomlLockEntry {
            name: "test".to_string(),
            version: "1.0.0".to_string(),
            git: Some("git@github.com:test/test.git".to_string()),
            url: None,
            rev: Some("123456".to_string()),
            checksum: None,
            integrity: None,
        };
        let entry: Result<LockEntry> = toml_entry.try_into();
        assert!(entry.is_ok(), "{entry:?}");
        let entry = entry.unwrap();
        assert_eq!(entry.name(), "test");
        assert_eq!(entry.version(), "1.0.0");
        let git = entry.as_git().unwrap();
        assert_eq!(git.git, "git@github.com:test/test.git");
        assert_eq!(git.rev, "123456");
    }

    #[test]
    fn test_toml_lock_entry_bad_http() {
        let toml_entry = TomlLockEntry {
            name: "test".to_string(),
            version: "1.0.0".to_string(),
            git: None,
            url: Some("https://example.com/zip.zip".to_string()),
            rev: None,
            checksum: None,
            integrity: None,
        };
        let entry: Result<LockEntry> = toml_entry.try_into();
        assert!(
            matches!(entry, Err(LockError::MissingField { ref field, dep: _ }) if field == "checksum"),
            "{entry:?}"
        );

        let toml_entry = TomlLockEntry {
            name: "test".to_string(),
            version: "1.0.0".to_string(),
            git: None,
            url: Some("https://example.com/zip.zip".to_string()),
            rev: None,
            checksum: Some("123456".to_string()),
            integrity: None,
        };
        let entry: Result<LockEntry> = toml_entry.try_into();
        assert!(
            matches!(entry, Err(LockError::MissingField { ref field, dep: _ }) if field == "integrity"),
            "{entry:?}"
        );
    }

    #[test]
    fn test_toml_lock_entry_bad_private() {
        let toml_entry = TomlLockEntry {
            name: "test".to_string(),
            version: "1.0.0".to_string(),
            git: None,
            url: None,
            rev: None,
            checksum: None,
            integrity: None,
        };
        let entry: Result<LockEntry> = toml_entry.try_into();
        assert!(
            matches!(entry, Err(LockError::MissingField { ref field, dep: _ }) if field == "checksum"),
            "{entry:?}"
        );
    }

    #[test]
    fn test_toml_lock_entry_bad_git() {
        let toml_entry = TomlLockEntry {
            name: "test".to_string(),
            version: "1.0.0".to_string(),
            git: Some("git@github.com:test/test.git".to_string()),
            url: Some("https://example.com/zip.zip".to_string()),
            rev: None,
            checksum: None,
            integrity: None,
        };
        let entry: Result<LockEntry> = toml_entry.try_into();
        assert!(matches!(entry, Err(LockError::InvalidLockEntry)), "{entry:?}");

        let toml_entry = TomlLockEntry {
            name: "test".to_string(),
            version: "1.0.0".to_string(),
            git: Some("git@github.com:test/test.git".to_string()),
            url: None,
            rev: None,
            checksum: None,
            integrity: None,
        };
        let entry: Result<LockEntry> = toml_entry.try_into();
        assert!(
            matches!(entry, Err(LockError::MissingField { ref field, dep: _ }) if field == "rev"),
            "{entry:?}"
        );
    }

    #[test]
    fn test_read_lockfile() {
        let dir = testdir!();
        let file_path = dir.join("soldeer.lock");
        // last entry is invalid and should be skipped
        let content = r#"[[dependencies]]
name = "test"
version = "1.0.0"
git = "git@github.com:test/test.git"
rev = "123456"

[[dependencies]]
name = "test2"
version = "1.0.0"
url = "https://example.com/zip.zip"
checksum = "123456"
integrity = "beef"

[[dependencies]]
name = "test3"
version = "1.0.0"
"#;
        fs::write(&file_path, content).unwrap();
        let res = read_lockfile(&file_path);
        assert!(res.is_ok(), "{res:?}");
        let lockfile = res.unwrap();
        assert_eq!(lockfile.entries.len(), 2);
        assert_eq!(lockfile.entries[0].name(), "test");
        assert_eq!(lockfile.entries[0].version(), "1.0.0");
        let git = lockfile.entries[0].as_git().unwrap();
        assert_eq!(git.git, "git@github.com:test/test.git");
        assert_eq!(git.rev, "123456");
        assert_eq!(lockfile.entries[1].name(), "test2");
        assert_eq!(lockfile.entries[1].version(), "1.0.0");
        let http = lockfile.entries[1].as_http().unwrap();
        assert_eq!(http.url, "https://example.com/zip.zip");
        assert_eq!(http.checksum, "123456");
        assert_eq!(http.integrity, "beef");
        assert_eq!(lockfile.raw, content);
    }

    #[test]
    fn test_generate_lockfile_content() {
        let dir = testdir!();
        let file_path = dir.join("soldeer.lock");
        let content = r#"[[dependencies]]
name = "test"
version = "1.0.0"
git = "git@github.com:test/test.git"
rev = "123456"

[[dependencies]]
name = "test2"
version = "1.0.0"
url = "https://example.com/zip.zip"
checksum = "123456"
integrity = "beef"
"#;
        fs::write(&file_path, content).unwrap();
        let lockfile = read_lockfile(&file_path).unwrap();
        let new_content = generate_lockfile_contents(lockfile.entries);
        assert_eq!(new_content, content);
    }

    #[test]
    fn test_add_to_lockfile() {
        let dir = testdir!();
        let file_path = dir.join("soldeer.lock");
        let content = r#"[[dependencies]]
name = "test"
version = "1.0.0"
git = "git@github.com:test/test.git"
rev = "123456"
"#;
        fs::write(&file_path, content).unwrap();
        let entry: LockEntry = HttpLockEntry::builder()
            .name("test2")
            .version("1.0.0")
            .url("https://example.com/zip.zip")
            .checksum("123456")
            .integrity("beef")
            .build()
            .into();
        let res = add_to_lockfile(entry.clone(), &file_path);
        assert!(res.is_ok(), "{res:?}");
        let lockfile = read_lockfile(&file_path).unwrap();
        assert_eq!(lockfile.entries.len(), 2);
        assert_eq!(lockfile.entries[1], entry);
    }

    #[test]
    fn test_replace_in_lockfile() {
        let dir = testdir!();
        let file_path = dir.join("soldeer.lock");
        let content = r#"[[dependencies]]
name = "test"
version = "1.0.0"
git = "git@github.com:test/test.git"
rev = "123456"
"#;
        fs::write(&file_path, content).unwrap();
        let entry: LockEntry = HttpLockEntry::builder()
            .name("test")
            .version("2.0.0")
            .url("https://example.com/zip.zip")
            .checksum("123456")
            .integrity("beef")
            .build()
            .into();
        let res = add_to_lockfile(entry.clone(), &file_path);
        assert!(res.is_ok(), "{res:?}");
        let lockfile = read_lockfile(&file_path).unwrap();
        assert_eq!(lockfile.entries.len(), 1);
        assert_eq!(lockfile.entries[0], entry);
    }

    #[test]
    fn test_remove_lock() {
        let dir = testdir!();
        let file_path = dir.join("soldeer.lock");
        let content = r#"[[dependencies]]
name = "test"
version = "1.0.0"
git = "git@github.com:test/test.git"
rev = "123456"

[[dependencies]]
name = "test2"
version = "1.0.0"
url = "https://example.com/zip.zip"
checksum = "123456"
integrity = "beef"
"#;
        fs::write(&file_path, content).unwrap();
        let dep = Dependency::from_name_version("test2~2.0.0", None, None).unwrap();
        let res = remove_lock(&dep, &file_path);
        assert!(res.is_ok(), "{res:?}");
        let lockfile = read_lockfile(&file_path).unwrap();
        assert_eq!(lockfile.entries.len(), 1);
        assert_eq!(lockfile.entries[0].name(), "test");
    }

    #[test]
    fn test_remove_lock_empty() {
        let dir = testdir!();
        let file_path = dir.join("soldeer.lock");
        let content = r#"[[dependencies]]
name = "test"
version = "1.0.0"
git = "git@github.com:test/test.git"
rev = "123456"
"#;
        fs::write(&file_path, content).unwrap();
        let dep = Dependency::from_name_version("test~1.0.0", None, None).unwrap();
        let res = remove_lock(&dep, &file_path);
        assert!(res.is_ok(), "{res:?}");
        assert!(!file_path.exists());
    }
}