uv-git-types 0.0.73

This is an internal component crate of uv
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
pub use crate::github::GitHubRepository;
pub use crate::oid::{GitOid, OidParseError};
pub use crate::reference::GitReference;
use std::cmp::Ordering;
use std::sync::LazyLock;

use percent_encoding::percent_decode_str;
use thiserror::Error;
use uv_cache_key::RepositoryUrl;
use uv_redacted::DisplaySafeUrl;
use uv_static::EnvVars;

mod github;
mod oid;
mod reference;

/// Initialize [`GitLfs`] mode from `UV_GIT_LFS` environment.
static UV_GIT_LFS: LazyLock<GitLfs> = LazyLock::new(|| {
    // TODO(konsti): Parse this in `EnvironmentOptions`.
    if std::env::var_os(EnvVars::UV_GIT_LFS)
        .and_then(|v| v.to_str().map(str::to_lowercase))
        .is_some_and(|v| matches!(v.as_str(), "y" | "yes" | "t" | "true" | "on" | "1"))
    {
        GitLfs::Enabled
    } else {
        GitLfs::Disabled
    }
});

/// Configuration for Git LFS (Large File Storage) support.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
pub enum GitLfs {
    /// Git LFS is disabled (default).
    #[default]
    Disabled,
    /// Git LFS is enabled.
    Enabled,
}

impl GitLfs {
    /// Create a `GitLfs` configuration from environment variables.
    pub fn from_env() -> Self {
        *UV_GIT_LFS
    }

    /// Returns true if LFS is enabled.
    pub fn enabled(self) -> bool {
        matches!(self, Self::Enabled)
    }
}

impl From<Option<bool>> for GitLfs {
    fn from(value: Option<bool>) -> Self {
        match value {
            Some(true) => Self::Enabled,
            Some(false) => Self::Disabled,
            None => Self::from_env(),
        }
    }
}

impl From<bool> for GitLfs {
    fn from(value: bool) -> Self {
        if value { Self::Enabled } else { Self::Disabled }
    }
}

impl std::fmt::Display for GitLfs {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Enabled => write!(f, "enabled"),
            Self::Disabled => write!(f, "disabled"),
        }
    }
}

#[derive(Debug, Error)]
pub enum GitUrlParseError {
    #[error(
        "Unsupported Git URL scheme `{0}:` in `{1}` (expected one of `https:`, `ssh:`, or `file:`)"
    )]
    UnsupportedGitScheme(String, DisplaySafeUrl),
    #[error(
        "Ambiguous Git URL `{0}`: the path contains multiple `@` characters. If the Git revision contains `@`, percent-encode it as `%40`"
    )]
    AmbiguousRevision(DisplaySafeUrl),
    #[error(
        "Exact Git revision `{revision}` does not match precise commit `{precise}` for `{url}`"
    )]
    MismatchedRevision {
        revision: String,
        precise: GitOid,
        url: Box<DisplaySafeUrl>,
    },
}

/// A URL reference to a Git repository.
#[derive(Debug, Clone)]
pub struct GitUrl {
    /// The URL of the Git repository, with any query parameters, fragments, and leading `git+`
    /// removed.
    url: DisplaySafeUrl,
    /// The canonical repository identity used for comparison and hashing.
    repository: RepositoryUrl,
    /// The reference to the commit to use, which could be a branch, tag or revision.
    reference: GitReference,
    /// The precise commit to use, if known.
    precise: Option<GitOid>,
    /// Git LFS configuration for this repository.
    lfs: GitLfs,
}

impl GitUrl {
    /// Create a new [`GitUrl`] from a repository URL and a reference.
    fn from_reference(
        url: DisplaySafeUrl,
        reference: GitReference,
        lfs: GitLfs,
    ) -> Result<Self, GitUrlParseError> {
        Self::from_fields(url, reference, None, lfs)
    }

    /// Create a new [`GitUrl`] from a repository URL and a precise commit.
    pub fn from_commit(
        url: DisplaySafeUrl,
        reference: GitReference,
        precise: GitOid,
        lfs: GitLfs,
    ) -> Result<Self, GitUrlParseError> {
        Self::from_fields(url, reference, Some(precise), lfs)
    }

    /// Create a new [`GitUrl`] from a repository URL and a precise commit, if known.
    pub fn from_fields(
        url: DisplaySafeUrl,
        reference: GitReference,
        precise: Option<GitOid>,
        lfs: GitLfs,
    ) -> Result<Self, GitUrlParseError> {
        match url.scheme() {
            "http" | "https" | "ssh" | "file" => {}
            unsupported => {
                return Err(GitUrlParseError::UnsupportedGitScheme(
                    unsupported.to_string(),
                    url,
                ));
            }
        }

        let git = Self {
            repository: RepositoryUrl::new(url.clone()),
            url,
            reference,
            precise: None,
            lfs,
        };
        match precise {
            Some(precise) => git.with_precise(precise),
            None => Ok(git),
        }
    }

    /// Set the precise [`GitOid`] to use for this Git URL.
    pub fn with_precise(mut self, precise: GitOid) -> Result<Self, GitUrlParseError> {
        if let GitReference::BranchOrTagOrCommit(revision) = &self.reference
            && revision.parse::<GitOid>().is_ok()
            && !revision.eq_ignore_ascii_case(precise.as_str())
        {
            return Err(GitUrlParseError::MismatchedRevision {
                revision: revision.clone(),
                precise,
                url: Box::new(self.url.clone()),
            });
        }

        self.precise = Some(precise);
        Ok(self)
    }

    /// Set the [`GitReference`] to use for this Git URL, clearing any precise commit if it changes.
    #[must_use]
    pub fn with_reference(mut self, reference: GitReference) -> Self {
        if self.reference != reference {
            self.precise = None;
            self.reference = reference;
        }
        self
    }

    /// Return the [`Url`] of the Git repository.
    pub fn url(&self) -> &DisplaySafeUrl {
        &self.url
    }

    /// Return the canonical repository identity for this Git URL.
    pub fn repository(&self) -> &RepositoryUrl {
        &self.repository
    }

    /// Return the reference to the commit to use, which could be a branch, tag or revision.
    pub fn reference(&self) -> &GitReference {
        &self.reference
    }

    /// Return the precise commit, if known.
    pub fn precise(&self) -> Option<GitOid> {
        self.precise
    }

    /// Return the Git LFS configuration.
    pub fn lfs(&self) -> GitLfs {
        self.lfs
    }

    /// Set the Git LFS configuration.
    #[must_use]
    pub fn with_lfs(mut self, lfs: GitLfs) -> Self {
        self.lfs = lfs;
        self
    }
}

impl PartialEq for GitUrl {
    fn eq(&self, other: &Self) -> bool {
        self.repository == other.repository
            && self.reference == other.reference
            && self.precise == other.precise
            && self.lfs == other.lfs
    }
}

impl Eq for GitUrl {}

impl PartialOrd for GitUrl {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for GitUrl {
    fn cmp(&self, other: &Self) -> Ordering {
        self.repository
            .cmp(&other.repository)
            .then_with(|| self.reference.cmp(&other.reference))
            .then_with(|| self.precise.cmp(&other.precise))
            .then_with(|| self.lfs.cmp(&other.lfs))
    }
}

impl std::hash::Hash for GitUrl {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.repository.hash(state);
        self.reference.hash(state);
        self.precise.hash(state);
        self.lfs.hash(state);
    }
}

impl TryFrom<DisplaySafeUrl> for GitUrl {
    type Error = GitUrlParseError;

    /// Initialize a [`GitUrl`] source from a URL.
    fn try_from(mut url: DisplaySafeUrl) -> Result<Self, Self::Error> {
        // Remove any query parameters and fragments.
        url.set_fragment(None);
        url.set_query(None);

        if url.path().matches('@').nth(1).is_some() {
            return Err(GitUrlParseError::AmbiguousRevision(url));
        }

        // If the URL ends with a reference, like `https://git.example.com/MyProject.git@v1.0`,
        // extract it.
        let mut reference = GitReference::DefaultBranch;
        if let Some((prefix, suffix)) = url
            .path()
            .rsplit_once('@')
            .map(|(prefix, suffix)| (prefix.to_string(), suffix.to_string()))
        {
            let suffix = percent_decode_str(&suffix).decode_utf8_lossy().into_owned();
            reference = GitReference::from_rev(suffix);
            url.set_path(&prefix);
        }

        // TODO(samypr100): GitLfs::from_env() for now unless we want to support parsing lfs=true
        Self::from_reference(url, reference, GitLfs::from_env())
    }
}

impl From<GitUrl> for DisplaySafeUrl {
    fn from(git: GitUrl) -> Self {
        let mut url = git.url;

        // If we have a precise commit, add `@` and the commit hash to the URL.
        if let Some(precise) = git.precise {
            let path = format!("{}@{}", url.path(), precise);
            url.set_path(&path);
        } else {
            // Otherwise, add the branch or tag name.
            match git.reference {
                GitReference::Branch(rev)
                | GitReference::Tag(rev)
                | GitReference::BranchOrTag(rev)
                | GitReference::NamedRef(rev)
                | GitReference::BranchOrTagOrCommit(rev) => {
                    let rev = GitReference::encode_rev(&rev);
                    let path = format!("{}@{}", url.path(), rev);
                    url.set_path(&path);
                }
                GitReference::DefaultBranch => {}
            }
        }

        url
    }
}

impl std::fmt::Display for GitUrl {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.url)
    }
}

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

    #[test]
    fn parse_percent_encoded_reference() -> Result<(), Box<dyn std::error::Error>> {
        let url = DisplaySafeUrl::parse("https://example.com/pkg.git@dev%401%232")?;
        let git = GitUrl::try_from(url)?;

        assert_eq!(git.url().as_str(), "https://example.com/pkg.git");
        assert_eq!(git.reference().as_str(), Some("dev@1#2"));

        Ok(())
    }

    #[test]
    fn parse_ssh_url_with_username_and_percent_encoded_reference()
    -> Result<(), Box<dyn std::error::Error>> {
        let url = DisplaySafeUrl::parse("ssh://git@github.com/example/example.git@abc%401.2.3")?;
        let git = GitUrl::try_from(url)?;

        assert_eq!(
            git.url().as_str(),
            "ssh://git@github.com/example/example.git"
        );
        assert_eq!(git.reference().as_str(), Some("abc@1.2.3"));

        Ok(())
    }

    #[test]
    fn reject_ambiguous_reference() -> Result<(), Box<dyn std::error::Error>> {
        let url = DisplaySafeUrl::parse("https://example.com/pkg.git@dev@1.2.3")?;
        let err = GitUrl::try_from(url).unwrap_err();

        assert_eq!(
            err.to_string(),
            "Ambiguous Git URL `https://example.com/pkg.git@dev@1.2.3`: the path contains multiple `@` characters. If the Git revision contains `@`, percent-encode it as `%40`"
        );

        Ok(())
    }

    #[test]
    fn reject_mismatched_exact_revision() -> Result<(), Box<dyn std::error::Error>> {
        let url = DisplaySafeUrl::parse("https://git:secret-token@example.com/pkg.git")?;
        let requested_revision = "0dacfd662c64cb4ceb16e6cf65a157a8b715b979";
        let precise = "b270df1a2fb5d012294e9aaf05e7e0bab1e6a389".parse::<GitOid>()?;

        let error = GitUrl::from_commit(
            url.clone(),
            GitReference::from_rev(requested_revision.to_string()),
            precise,
            GitLfs::Disabled,
        )
        .expect_err("mismatched full revision must be rejected");
        assert_eq!(
            error.to_string(),
            "Exact Git revision `0dacfd662c64cb4ceb16e6cf65a157a8b715b979` does not match precise commit `b270df1a2fb5d012294e9aaf05e7e0bab1e6a389` for `https://git:****@example.com/pkg.git`"
        );

        let git = GitUrl::from_reference(
            url.clone(),
            GitReference::from_rev(requested_revision.to_string()),
            GitLfs::Disabled,
        )?;
        assert!(git.with_precise(precise).is_err());

        let uppercase_revision = requested_revision.to_ascii_uppercase();
        let expected = requested_revision.parse::<GitOid>()?;
        assert!(
            GitUrl::from_commit(
                url.clone(),
                GitReference::from_rev(uppercase_revision),
                expected,
                GitLfs::Disabled,
            )
            .is_ok()
        );

        assert!(
            GitUrl::from_commit(
                url.clone(),
                GitReference::from_rev("0dacfd6".to_string()),
                precise,
                GitLfs::Disabled,
            )
            .is_ok()
        );

        assert!(
            GitUrl::from_commit(
                url,
                GitReference::Branch(requested_revision.to_string()),
                precise,
                GitLfs::Disabled,
            )
            .is_ok()
        );

        Ok(())
    }

    #[test]
    fn changing_reference_clears_precise_commit() -> Result<(), Box<dyn std::error::Error>> {
        let url = DisplaySafeUrl::parse("https://example.com/pkg.git")?;
        let precise = "0dacfd662c64cb4ceb16e6cf65a157a8b715b979".parse::<GitOid>()?;
        let reference = GitReference::Branch("main".to_string());
        let git = GitUrl::from_commit(url, reference.clone(), precise, GitLfs::Disabled)?;

        assert_eq!(
            git.clone().with_reference(reference).precise(),
            Some(precise)
        );
        assert_eq!(
            git.with_reference(GitReference::from_rev(
                "b270df1a2fb5d012294e9aaf05e7e0bab1e6a389".to_string()
            ))
            .precise(),
            None
        );

        Ok(())
    }

    #[test]
    fn display_percent_encodes_reference() -> Result<(), Box<dyn std::error::Error>> {
        let git = GitUrl::from_reference(
            DisplaySafeUrl::parse("https://example.com/pkg.git")?,
            GitReference::from_rev("refs/pull/493/head@1#2%".to_string()),
            GitLfs::Disabled,
        )?;
        let url = DisplaySafeUrl::from(git);

        assert_eq!(
            url.as_str(),
            "https://example.com/pkg.git@refs/pull/493/head%401%232%25"
        );

        let git = GitUrl::try_from(url)?;
        assert_eq!(git.reference().as_str(), Some("refs/pull/493/head@1#2%"));

        Ok(())
    }
}