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
1061
1062
1063
#include "lix/libutil/archive.hh"
#include "lix/libutil/async-io.hh"
#include "lix/libutil/async.hh"
#include "lix/libutil/c-calls.hh"
#include "lix/libutil/error.hh"
#include "lix/libfetchers/fetchers.hh"
#include "lix/libfetchers/cache.hh"
#include "lix/libstore/globals.hh"
#include "lix/libfetchers/builtin-fetchers.hh"
#include "lix/libutil/processes.hh"
#include "lix/libutil/result.hh"
#include "lix/libutil/tarfile.hh"
#include "lix/libstore/store-api.hh"
#include "lix/libstore/temporary-dir.hh"
#include "lix/libutil/url-parts.hh"
#include "lix/libstore/pathlocks.hh"
#include "lix/libutil/users.hh"
#include "lix/libutil/git.hh"
#include "lix/libutil/logging.hh"
#include "lix/libutil/finally.hh"

#include "lix/libfetchers/fetch-settings.hh"

#include <optional>
#include <regex>
#include <string.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <unistd.h>

using namespace std::string_literals;

namespace nix::fetchers {

namespace {

// Explicit initial branch of our bare repo to suppress warnings from new version of git.
// The value itself does not matter, since we always fetch a specific revision or branch.
// It is set with `-c init.defaultBranch=` instead of `--initial-branch=` to stay compatible with
// old version of git, which will ignore unrecognized `-c` options.
const std::string gitInitialBranch = "__nix_dummy_branch";

bool isCacheFileWithinTtl(time_t now, const struct stat & st)
{
    return st.st_mtime + settings.tarballTtl > now;
}

bool touchCacheFile(const Path & path, time_t touch_time)
{
    struct timeval times[2];
    times[0].tv_sec = touch_time;
    times[0].tv_usec = 0;
    times[1].tv_sec = touch_time;
    times[1].tv_usec = 0;

    return sys::lutimes(path, times) == 0;
}

Path getCachePath(std::string_view key)
{
    return getCacheDir() + "/nix/gitv3/"
        + hashString(HashType::SHA256, key).to_string(HashFormat::Base32, false);
}

// Returns the name of the HEAD branch.
//
// Returns the head branch name as reported by git ls-remote --symref, e.g., if
// ls-remote returns the output below, "main" is returned based on the ref line.
//
//   ref: refs/heads/main       HEAD
//   ...
static kj::Promise<Result<std::optional<std::string>>> readHead(const Path & path)
try {
    auto output = TRY_AWAIT(runProgram(
        "git",
        true,
        // FIXME: use 'HEAD' to avoid returning all refs
        {"ls-remote", "--symref", path},
        true
    ));

    std::string_view line = output;
    line = line.substr(0, line.find("\n"));
    if (const auto parseResult = git::parseLsRemoteLine(line)) {
        switch (parseResult->kind) {
            case git::LsRemoteRefLine::Kind::Symbolic:
                debug("resolved HEAD ref '%s' for repo '%s'", parseResult->target, path);
                break;
            case git::LsRemoteRefLine::Kind::Object:
                debug("resolved HEAD rev '%s' for repo '%s'", parseResult->target, path);
                break;
        }
        co_return parseResult->target;
    }
    co_return std::nullopt;
} catch (ExecError &) {
    co_return std::nullopt;
} catch (...) {
    co_return result::current_exception();
}

// Persist the HEAD ref from the remote repo in the local cached repo.
static kj::Promise<Result<bool>>
storeCachedHead(const std::string & actualUrl, const std::string & headRef)
try {
    Path cacheDir = getCachePath(actualUrl);
    try {
        TRY_AWAIT(runProgram(
            "git", true, {"-C", cacheDir, "--git-dir", ".", "symbolic-ref", "--", "HEAD", headRef}
        ));
    } catch (ExecError & e) {
        if (!WIFEXITED(e.status)) {
            throw;
        }
        co_return false;
    }
    /* No need to touch refs/HEAD, because `git symbolic-ref` updates the mtime. */
    co_return true;
} catch (...) {
    co_return result::current_exception();
}

static kj::Promise<Result<std::optional<std::string>>> readHeadCached(const std::string & actualUrl)
try {
    // Create a cache path to store the branch of the HEAD ref. Append something
    // in front of the URL to prevent collision with the repository itself.
    Path cacheDir = getCachePath(actualUrl);
    Path headRefFile = cacheDir + "/HEAD";

    time_t now = time(0);
    struct stat st;
    std::optional<std::string> cachedRef;
    if (sys::stat(headRefFile, &st) == 0) {
        cachedRef = TRY_AWAIT(readHead(cacheDir));
        if (cachedRef != std::nullopt &&
            *cachedRef != gitInitialBranch &&
            isCacheFileWithinTtl(now, st))
        {
            debug("using cached HEAD ref '%s' for repo '%s'", *cachedRef, actualUrl);
            co_return cachedRef;
        }
    }

    auto ref = TRY_AWAIT(readHead(actualUrl));
    if (ref) {
        co_return ref;
    }

    if (cachedRef) {
        // If the cached git ref is expired in fetch() below, and the 'git fetch'
        // fails, it falls back to continuing with the most recent version.
        // This function must behave the same way, so we return the expired
        // cached ref here.
        printTaggedWarning(
            "could not get HEAD ref for repository '%s'; using expired cached ref '%s'",
            actualUrl,
            *cachedRef
        );
        co_return cachedRef;
    }

    co_return std::nullopt;
} catch (...) {
    co_return result::current_exception();
}

bool isNotDotGitDirectory(const Path & path)
{
    return baseNameOf(path) != ".git";
}

struct WorkdirInfo
{
    bool clean = false;
    bool hasHead = false;
};

// Returns whether a git workdir is clean and has commits.
static kj::Promise<Result<WorkdirInfo>> getWorkdirInfo(const Input & input, const Path & workdir)
try {
    const bool submodules = maybeGetBoolAttr(input.attrs, "submodules").value_or(false);
    std::string gitDir(".git");

    auto env = getEnv();
    // Set LC_ALL to C: because we rely on the error messages from git rev-parse to determine what went wrong
    // that way unknown errors can lead to a failure instead of continuing through the wrong code path
    env["LC_ALL"] = "C";

    /* Check whether HEAD points to something that looks like a commit,
       since that is the refrence we want to use later on. */
    auto result = TRY_AWAIT(runProgram(RunOptions{
        .program = "git",
        .args =
            {"-C",
             workdir,
             "--git-dir",
             gitDir,
             "rev-parse",
             "--verify",
             "--no-revs",
             "HEAD^{commit}"},
        .environment = env,
        .redirections = {{.dup = STDERR_FILENO, .from = STDOUT_FILENO}},
    }));
    auto exitCode = WEXITSTATUS(result.first);
    auto errorMessage = result.second;

    if (errorMessage.find("fatal: not a git repository") != std::string::npos) {
        throw Error("'%s' is not a Git repository", workdir);
    } else if (errorMessage.find("fatal: Needed a single revision") != std::string::npos) {
        // indicates that the repo does not have any commits
        // we want to proceed and will consider it dirty later
    } else if (exitCode != 0) {
        // any other errors should lead to a failure
        throw Error("getting the HEAD of the Git tree '%s' failed with exit code %d:\n%s", workdir, exitCode, errorMessage);
    }

    bool clean = false;
    bool hasHead = exitCode == 0;

    try {
        if (hasHead) {
            // Using git diff is preferrable over lower-level operations here,
            // because its conceptually simpler and we only need the exit code anyways.
            auto gitDiffOpts = Strings({ "-C", workdir, "--git-dir", gitDir, "diff", "HEAD", "--quiet"});
            if (!submodules) {
                // Changes in submodules should only make the tree dirty
                // when those submodules will be copied as well.
                gitDiffOpts.emplace_back("--ignore-submodules");
            }
            gitDiffOpts.emplace_back("--");
            TRY_AWAIT(runProgram("git", true, gitDiffOpts));

            clean = true;
        }
    } catch (ExecError & e) {
        if (!WIFEXITED(e.status) || WEXITSTATUS(e.status) != 1) throw;
    }

    co_return WorkdirInfo{.clean = clean, .hasHead = hasHead};
} catch (...) {
    co_return result::current_exception();
}

static kj::Promise<Result<std::pair<StorePath, Input>>> fetchFromWorkdir(ref<Store> store, Input & input, const Path & workdir, const WorkdirInfo & workdirInfo)
try {
    const bool submodules = maybeGetBoolAttr(input.attrs, "submodules").value_or(false);
    auto gitDir = ".git";

    if (!fetchSettings.allowDirty)
        throw Error("Git tree '%s' is dirty", workdir);

    if (fetchSettings.warnDirty) {
        printTaggedWarning("Git tree '%s' is dirty", workdir);
    }

    auto gitOpts = Strings({ "-C", workdir, "--git-dir", gitDir, "ls-files", "-z" });
    if (submodules)
        gitOpts.emplace_back("--recurse-submodules");

    auto files =
        tokenizeString<std::set<std::string>>(TRY_AWAIT(runProgram("git", true, gitOpts)), "\0"s);

    Path actualPath(absPath(workdir));

    PathFilter filter = [&](const Path & p) -> bool {
        assert(p.starts_with(actualPath));
        std::string file(p, actualPath.size() + 1);

        auto st = lstat(p);

        if (S_ISDIR(st.st_mode)) {
            auto prefix = file + "/";
            auto i = files.lower_bound(prefix);
            return (i != files.end() && (*i).starts_with(prefix)) || files.count(file);
        }

        return files.count(file);
    };

    auto storePath = TRY_AWAIT(store->addToStoreRecursive(
        input.getName(), *prepareDump(actualPath, filter), HashType::SHA256
    ));

    // FIXME: maybe we should use the timestamp of the last
    // modified dirty file?
    input.attrs.insert_or_assign(
        "lastModified",
        workdirInfo.hasHead ? std::stoull(TRY_AWAIT(runProgram(
                                  "git",
                                  true,
                                  {"-C",
                                   actualPath,
                                   "--git-dir",
                                   gitDir,
                                   "log",
                                   "-1",
                                   "--format=%ct",
                                   "--no-show-signature",
                                   "HEAD"}
                              )))
                            : 0
    );

    if (workdirInfo.hasHead) {
        input.attrs.insert_or_assign(
            "dirtyRev",
            chomp(TRY_AWAIT(runProgram(
                "git",
                true,
                {"-C", actualPath, "--git-dir", gitDir, "rev-parse", "--verify", "HEAD"}
            ))) + "-dirty"
        );
        input.attrs.insert_or_assign(
            "dirtyShortRev",
            chomp(TRY_AWAIT(runProgram(
                "git",
                true,
                {"-C", actualPath, "--git-dir", gitDir, "rev-parse", "--verify", "--short", "HEAD"}
            ))) + "-dirty"
        );
    }

    co_return {std::move(storePath), input};
} catch (...) {
    co_return result::current_exception();
}
}  // end namespace

static std::optional<Path> resolveRefToCachePath(
    Input & input,
    const Path & cacheDir,
    std::vector<Path> & gitRefFileCandidates,
    std::function<bool(const Path&)> condition)
{
    if (input.getRef()->starts_with("refs/")) {
        Path fullpath = cacheDir + "/" + *input.getRef();
        if (condition(fullpath)) {
            return fullpath;
        }
    }

    for (auto & candidate : gitRefFileCandidates) {
        if (condition(candidate)) {
            return candidate;
        }
    }

    return std::nullopt;
}

static const std::set<std::string> allowedGitAttrs = {
    "allRefs",
    "dirtyRev",
    "dirtyShortRev",
    "lastModified",
    "name",
    "ref",
    "rev",
    "revCount",
    "shallow",
    "submodules",
    "url",
};

struct GitInputScheme : InputScheme
{
    std::string schemeType() const override { return "git"; }

    const std::set<std::string> & allowedAttrs() const override {
        return allowedGitAttrs;
    }

    std::optional<Input> inputFromURL(const ParsedURL & url, bool requireTree) const override
    {
        if (url.scheme != "git" &&
            url.scheme != "git+http" &&
            url.scheme != "git+https" &&
            url.scheme != "git+ssh" &&
            url.scheme != "git+file") return {};

        auto url2(url);
        if (url2.scheme.starts_with("git+")) url2.scheme = std::string(url2.scheme, 4);
        url2.query.clear();

        Attrs attrs;
        attrs.emplace("type", "git");
        attrs.emplace("url", url2.to_string());

        emplaceURLQueryIntoAttrs(
            url,
            attrs,
            {"lastModified", "revCount"},
            {"shallow", "submodules", "allRefs"}
        );

        return inputFromAttrs(attrs);
    }

    Attrs preprocessAttrs(const Attrs & attrs) const override {
        parseURL(getStrAttr(attrs, "url"));
        maybeGetBoolAttr(attrs, "shallow");
        maybeGetBoolAttr(attrs, "submodules");
        maybeGetBoolAttr(attrs, "allRefs");

        if (auto ref = maybeGetStrAttr(attrs, "ref")) {
            if (std::regex_search(*ref, badGitRefRegex))
                throw BadURL("invalid Git branch/tag name '%s'", *ref);
        }

        return attrs;
    }

    ParsedURL toURL(const Input & input) const override
    {
        auto url = parseURL(getStrAttr(input.attrs, "url"));
        if (url.scheme != "git") url.scheme = "git+" + url.scheme;
        if (auto rev = input.getRev()) url.query.insert_or_assign("rev", rev->gitRev());
        if (auto ref = input.getRef()) url.query.insert_or_assign("ref", *ref);
        if (maybeGetBoolAttr(input.attrs, "shallow").value_or(false))
            url.query.insert_or_assign("shallow", "1");
        return url;
    }

    bool hasAllInfo(const Input & input) const override
    {
        bool maybeDirty = !input.getRef();
        bool shallow = maybeGetBoolAttr(input.attrs, "shallow").value_or(false);
        return
            maybeGetIntAttr(input.attrs, "lastModified")
            && (shallow || maybeDirty || maybeGetIntAttr(input.attrs, "revCount"));
    }

    Input applyOverrides(
        const Input & input,
        std::optional<std::string> ref,
        std::optional<Hash> rev) const override
    {
        auto res(input);
        if (rev) res.attrs.insert_or_assign("rev", rev->gitRev());
        if (ref) res.attrs.insert_or_assign("ref", *ref);
        if (!res.getRef() && res.getRev())
            throw Error("Git input '%s' has a commit hash but no branch/tag name", res.to_string());
        return res;
    }

    kj::Promise<Result<void>> clone(const Input & input, const Path & destDir) const override
    try {
        auto [isLocal, actualUrl] = getActualUrl(input);

        Strings args = {"clone"};

        args.push_back(actualUrl);

        if (auto ref = input.getRef()) {
            args.push_back("--branch");
            args.push_back(*ref);
        }

        if (input.getRev()) throw UnimplementedError("cloning a specific revision is not implemented");

        args.push_back(destDir);

        TRY_AWAIT(runProgram("git", true, args, true));
        co_return result::success();
    } catch (...) {
        co_return result::current_exception();
    }

    std::optional<Path> getSourcePath(const Input & input) const override
    {
        auto url = parseURL(getStrAttr(input.attrs, "url"));
        if (url.scheme == "file" && !input.getRef() && !input.getRev())
            return url.path;
        return {};
    }

    kj::Promise<Result<void>> putFile(
        const Input & input,
        const CanonPath & path,
        std::string_view contents,
        std::optional<std::string> commitMsg
    ) const override
    try {
        auto root = getSourcePath(input);
        if (!root)
            throw Error("cannot commit '%s' to Git repository '%s' because it's not a working tree", path, input.to_string());

        writeFile((CanonPath(*root) + path).abs(), contents);

        auto gitDir = ".git";

        auto result = TRY_AWAIT(runProgram(RunOptions{
            .program = "git",
            .args =
                {"-C",
                 *root,
                 "--git-dir",
                 gitDir,
                 "check-ignore",
                 "--quiet",
                 std::string(path.rel())},
        }));
        auto exitCode = WEXITSTATUS(result.first);

        if (exitCode != 0) {
            // The path is not `.gitignore`d, we can add the file.
            TRY_AWAIT(runProgram(
                "git",
                true,
                {"-C",
                 *root,
                 "--git-dir",
                 gitDir,
                 "add",
                 "--intent-to-add",
                 "--",
                 std::string(path.rel())}
            ));

            if (commitMsg) {
                auto [_fd, msgPath] = createTempFile("nix-msg");
                AutoDelete const _delete{msgPath};
                writeFile(msgPath, *commitMsg);

                TRY_AWAIT(runProgram(
                    "git",
                    true,
                    {"-C",
                     *root,
                     "--git-dir",
                     gitDir,
                     "commit",
                     std::string(path.rel()),
                     "-F",
                     msgPath},
                    true
                ));
            }
        }

        co_return result::success();
    } catch (...) {
        co_return result::current_exception();
    }

    std::pair<bool, std::string> getActualUrl(const Input & input) const
    {
        // file:// URIs are normally not cloned (but otherwise treated the
        // same as remote URIs, i.e. we don't use the working tree or
        // HEAD). Exception: If _NIX_FORCE_HTTP is set, or the repo is a bare git
        // repo, treat as a remote URI to force a clone.
        static bool forceHttp = getEnv("_NIX_FORCE_HTTP") == "1"; // for testing
        auto url = parseURL(getStrAttr(input.attrs, "url"));
        bool isBareRepository = url.scheme == "file" && !pathExists(url.path + "/.git");
        bool isLocal = url.scheme == "file" && !forceHttp && !isBareRepository;
        return {isLocal, isLocal ? url.path : url.base};
    }

    kj::Promise<Result<std::pair<StorePath, Input>>>
    fetch(ref<Store> store, const Input & _input) override
    try {
        Input input(_input);
        auto gitDir = ".git";

        std::string name = input.getName();

        bool shallow = maybeGetBoolAttr(input.attrs, "shallow").value_or(false);
        bool submodules = maybeGetBoolAttr(input.attrs, "submodules").value_or(false);
        bool allRefs = maybeGetBoolAttr(input.attrs, "allRefs").value_or(false);

        std::string cacheType = "git";
        if (shallow) cacheType += "-shallow";
        if (submodules) cacheType += "-submodules";
        if (allRefs) cacheType += "-all-refs";

        auto checkHashType = [&](const std::optional<Hash> & hash)
        {
            if (hash.has_value() && !(hash->type == HashType::SHA1 || hash->type == HashType::SHA256))
                throw Error(
                    "Hash '%s' is not supported by Git. Supported types are sha1 and sha256.",
                    hash->to_string(HashFormat::Base16)
                );
        };

        auto getLockedAttrs = [&]()
        {
            checkHashType(input.getRev());

            return Attrs({
                {"type", cacheType},
                {"name", name},
                {"rev", input.getRev()->gitRev()},
            });
        };

        auto makeResult = [&](const Attrs & infoAttrs, StorePath && storePath)
            -> std::pair<StorePath, Input>
        {
            assert(input.getRev());
            assert(!_input.getRev() || _input.getRev() == input.getRev());
            if (!shallow)
                input.attrs.insert_or_assign("revCount", getIntAttr(infoAttrs, "revCount"));
            input.attrs.insert_or_assign("lastModified", getIntAttr(infoAttrs, "lastModified"));
            return {std::move(storePath), input};
        };

        if (input.getRev()) {
            if (auto res = TRY_AWAIT(getCache()->lookup(store, getLockedAttrs())))
                co_return makeResult(res->first, std::move(res->second));
        }

        auto [isLocal, actualUrl_] = getActualUrl(input);
        auto actualUrl = actualUrl_; // work around clang bug

        /* If this is a local directory and no ref or revision is given,
           allow fetching directly from a dirty workdir. */
        if (!input.getRef() && !input.getRev() && isLocal) {
            auto workdirInfo = TRY_AWAIT(getWorkdirInfo(input, actualUrl));
            if (!workdirInfo.clean) {
                co_return TRY_AWAIT(fetchFromWorkdir(store, input, actualUrl, workdirInfo));
            }
        }

        Attrs unlockedAttrs({
            {"type", cacheType},
            {"name", name},
            {"url", actualUrl},
        });

        Path repoDir;

        if (isLocal) {
            if (!input.getRef()) {
                auto head = TRY_AWAIT(readHead(actualUrl));
                if (!head) {
                    printTaggedWarning(
                        "could not read HEAD ref from repo at '%s', using 'master'", actualUrl
                    );
                    head = "master";
                }
                input.attrs.insert_or_assign("ref", *head);
                unlockedAttrs.insert_or_assign("ref", *head);
            }

            if (!input.getRev())
                input.attrs.insert_or_assign(
                    "rev",
                    Hash::parseAny(
                        chomp(TRY_AWAIT(runProgram(
                            "git",
                            true,
                            {"-C", actualUrl, "--git-dir", gitDir, "rev-parse", *input.getRef()}
                        ))),
                        HashType::SHA1
                    )
                        .gitRev()
                );

            repoDir = actualUrl;
        } else {
            const bool useHeadRef = !input.getRef();
            if (useHeadRef) {
                auto head = TRY_AWAIT(readHeadCached(actualUrl));
                if (!head) {
                    printTaggedWarning(
                        "could not read HEAD ref from repo at '%s', using 'master'", actualUrl
                    );
                    head = "master";
                }
                input.attrs.insert_or_assign("ref", *head);
                unlockedAttrs.insert_or_assign("ref", *head);
            } else {
                if (!input.getRev()) {
                    unlockedAttrs.insert_or_assign("ref", input.getRef().value());
                }
            }

            if (auto res = TRY_AWAIT(getCache()->lookup(store, unlockedAttrs))) {
                auto rev2 = Hash::parseAny(getStrAttr(res->first, "rev"), HashType::SHA1);
                if (!input.getRev() || input.getRev() == rev2) {
                    input.attrs.insert_or_assign("rev", rev2.gitRev());
                    co_return makeResult(res->first, std::move(res->second));
                }
            }

            Path cacheDir = getCachePath(actualUrl);
            repoDir = cacheDir;
            gitDir = ".";

            createDirs(dirOf(cacheDir));
            PathLock cacheDirLock = TRY_AWAIT(lockPathAsync(cacheDir + ".lock"));

            if (!pathExists(cacheDir)) {
                TRY_AWAIT(runProgram(
                    "git",
                    true,
                    {"-c", "init.defaultBranch=" + gitInitialBranch, "init", "--bare", repoDir}
                ));
            }

            std::vector<Path> gitRefFileCandidates;
            for (auto & infix : {"", "tags/", "heads/"}) {
                Path p = cacheDir + "/refs/" + infix + *input.getRef();
                gitRefFileCandidates.push_back(p);
            }

            Path localRefFile;

            bool doFetch;
            time_t now = time(0);

            /* If a rev was specified, we need to fetch if it's not in the
               repo. */
            if (input.getRev()) {
                try {
                    TRY_AWAIT(runProgram(
                        "git",
                        true,
                        {"-C",
                         repoDir,
                         "--git-dir",
                         gitDir,
                         "cat-file",
                         "-e",
                         input.getRev()->gitRev()}
                    ));
                    doFetch = false;
                } catch (ExecError & e) {
                    if (WIFEXITED(e.status)) {
                        doFetch = true;
                    } else {
                        throw;
                    }
                }
            } else {
                if (allRefs) {
                    doFetch = true;
                } else {
                    std::function<bool(const Path&)> condition;
                    condition = [&now](const Path & path) {
                        /* If the local ref is older than ‘tarball-ttl’ seconds, do a
                           git fetch to update the local ref to the remote ref. */
                        struct stat st;
                        return sys::stat(path, &st) == 0 && isCacheFileWithinTtl(now, st);
                    };
                    if (auto result = resolveRefToCachePath(
                        input,
                        cacheDir,
                        gitRefFileCandidates,
                        condition
                    )) {
                        localRefFile = *result;
                        doFetch = false;
                    } else {
                        doFetch = true;
                    }
                }
            }

            // When having to fetch, we don't know `localRefFile` yet.
            // Because git needs to figure out what we're fetching
            // (i.e. is it a rev? a branch? a tag?)
            if (doFetch) {
                auto act = logger->startActivity(
                    lvlTalkative, actUnknown, fmt("fetching Git repository '%s'", actualUrl)
                );

                auto ref = input.getRef();
                std::string fetchRef;
                if (allRefs) {
                    fetchRef = "refs/*";
                } else if (
                    ref->starts_with("refs/")
                    || *ref == "HEAD"
                    || std::regex_match(*ref, revRegex))
                {
                    fetchRef = *ref;
                } else {
                    fetchRef = "refs/*/" + *ref;
                }

                try {
                    Finally finally([&]() {
                        if (auto p = resolveRefToCachePath(
                            input,
                            cacheDir,
                            gitRefFileCandidates,
                            pathExists
                        )) {
                            localRefFile = *p;
                        }
                    });

                    // FIXME: git stderr messes up our progress indicator, so
                    // we're using --quiet for now. Should process its stderr.
                    TRY_AWAIT(runProgram(
                        "git",
                        true,
                        {"-C",
                         repoDir,
                         "--git-dir",
                         gitDir,
                         "fetch",
                         "--quiet",
                         "--force",
                         "--",
                         actualUrl,
                         fmt("%s:%s", fetchRef, fetchRef)},
                        true
                    ));
                } catch (Error & e) {
                    if (!pathExists(localRefFile)) throw;
                    printTaggedWarning(
                        "could not update local clone of Git repository '%s'; continuing with the "
                        "most recent version",
                        actualUrl
                    );
                }

                if (!touchCacheFile(localRefFile, now))
                    printTaggedWarning(
                        "could not update mtime for file '%s': %s", localRefFile, strerror(errno)
                    );
                if (useHeadRef && !TRY_AWAIT(storeCachedHead(actualUrl, *input.getRef()))) {
                    printTaggedWarning(
                        "could not update cached head '%s' for '%s'", *input.getRef(), actualUrl
                    );
                }
            }

            if (!input.getRev()) {
                auto rev = chomp(TRY_AWAIT(runProgram(
                    "git",
                    true,
                    {"-C", repoDir, "--git-dir", gitDir, "rev-list", "--max-count=1", *input.getRef()}
                )));
                input.attrs.insert_or_assign("rev", rev);
            }

            // cache dir lock is removed at scope end; we will only use read-only operations on specific revisions in the remainder
        }

        bool isShallow =
            chomp(TRY_AWAIT(runProgram(
                "git",
                true,
                {"-C", repoDir, "--git-dir", gitDir, "rev-parse", "--is-shallow-repository"}
            )))
            == "true";

        if (isShallow && !shallow)
            throw Error("'%s' is a shallow Git repository, but shallow repositories are only allowed when `shallow = true;` is specified.", actualUrl);

        // FIXME: check whether rev is an ancestor of ref.

        printTalkative("using revision %s of repo '%s'", input.getRev()->gitRev(), actualUrl);

        /* Now that we know the ref, check again whether we have it in
           the store. */
        if (auto res = TRY_AWAIT(getCache()->lookup(store, getLockedAttrs())))
            co_return makeResult(res->first, std::move(res->second));

        Path tmpDir = createTempDir();
        AutoDelete delTmpDir(tmpDir, true);
        PathFilter filter = defaultPathFilter;

        auto result = TRY_AWAIT(runProgram(RunOptions{
            .program = "git",
            .args =
                {"-C", repoDir, "--git-dir", gitDir, "cat-file", "commit", input.getRev()->gitRev()
                },
            .redirections = {{.dup = STDERR_FILENO, .from = STDOUT_FILENO}},
        }));
        if (WEXITSTATUS(result.first) == 128
            && result.second.find("bad file") != std::string::npos)
        {
            throw Error(
                "Cannot find Git revision '%s' in ref '%s' of repository '%s'! "
                "Please make sure that the " ANSI_BOLD "rev" ANSI_NORMAL " exists on the "
                ANSI_BOLD "ref" ANSI_NORMAL " you've specified or add " ANSI_BOLD
                "allRefs = true;" ANSI_NORMAL " to " ANSI_BOLD "fetchGit" ANSI_NORMAL ".",
                input.getRev()->gitRev(),
                *input.getRef(),
                actualUrl
            );
        }

        if (submodules) {
            Path tmpGitDir = createTempDir();
            AutoDelete delTmpGitDir(tmpGitDir, true);

            TRY_AWAIT(runProgram(
                "git",
                true,
                {"-c",
                 "init.defaultBranch=" + gitInitialBranch,
                 "init",
                 tmpDir,
                 "--separate-git-dir",
                 tmpGitDir}
            ));

            {
                // TODO: repoDir might lack the ref (it only checks if rev
                // exists, see FIXME above) so use a big hammer and fetch
                // everything to ensure we get the rev.
                auto act = logger->startActivity(
                    lvlTalkative, actUnknown, fmt("making temporary clone of '%s'", repoDir)
                );
                TRY_AWAIT(runProgram(
                    "git",
                    true,
                    {"-C",
                     tmpDir,
                     "fetch",
                     "--quiet",
                     "--force",
                     "--update-head-ok",
                     "--",
                     repoDir,
                     "refs/*:refs/*"},
                    true
                ));
            }

            TRY_AWAIT(runProgram(
                "git", true, {"-C", tmpDir, "checkout", "--quiet", input.getRev()->gitRev()}
            ));

            /* Ensure that we use the correct origin for fetching
               submodules. This matters for submodules with relative
               URLs. */
            if (isLocal) {
                writeFile(tmpGitDir + "/config", readFile(repoDir + "/" + gitDir + "/config"));

                /* Restore the config.bare setting we may have just
                   copied erroneously from the user's repo. */
                TRY_AWAIT(runProgram("git", true, {"-C", tmpDir, "config", "core.bare", "false"}));
            } else
                TRY_AWAIT(runProgram(
                    "git", true, {"-C", tmpDir, "config", "remote.origin.url", actualUrl}
                ));

            /* As an optimisation, copy the modules directory of the
               source repo if it exists. */
            auto modulesPath = repoDir + "/" + gitDir + "/modules";
            if (pathExists(modulesPath)) {
                auto act = logger->startActivity(
                    lvlTalkative, actUnknown, fmt("copying submodules of '%s'", actualUrl)
                );
                TRY_AWAIT(runProgram("cp", true, {"-R", "--", modulesPath, tmpGitDir + "/modules"})
                );
            }

            {
                auto act = logger->startActivity(
                    lvlTalkative, actUnknown, fmt("fetching submodules of '%s'", actualUrl)
                );
                TRY_AWAIT(runProgram(
                    "git",
                    true,
                    {"-C", tmpDir, "submodule", "--quiet", "update", "--init", "--recursive"},
                    true
                ));
            }

            filter = isNotDotGitDirectory;
        } else {
            auto proc = runProgram2({
                .program = "git",
                .args = { "-C", repoDir, "--git-dir", gitDir, "archive", input.getRev()->gitRev() },
                .captureStdout = true,
            });
            Finally const _wait([&] { proc.waitAndCheck(); });

            TRY_AWAIT(unpackTarfile(*proc.getStdout(), tmpDir));
        }

        auto storePath = TRY_AWAIT(
            store->addToStoreRecursive(name, *prepareDump(tmpDir, filter), HashType::SHA256)
        );

        auto lastModified = std::stoull(TRY_AWAIT(runProgram(
            "git",
            true,
            {"-C",
             repoDir,
             "--git-dir",
             gitDir,
             "log",
             "-1",
             "--format=%ct",
             "--no-show-signature",
             input.getRev()->gitRev()}
        )));

        Attrs infoAttrs({
            {"rev", input.getRev()->gitRev()},
            {"lastModified", lastModified},
        });

        if (!shallow)
            infoAttrs.insert_or_assign(
                "revCount",
                std::stoull(TRY_AWAIT(runProgram(
                    "git",
                    true,
                    {"-C",
                     repoDir,
                     "--git-dir",
                     gitDir,
                     "rev-list",
                     "--count",
                     input.getRev()->gitRev()}
                )))
            );

        if (!_input.getRev())
            getCache()->add(
                store,
                unlockedAttrs,
                infoAttrs,
                storePath,
                false);

        getCache()->add(
            store,
            getLockedAttrs(),
            infoAttrs,
            storePath,
            true);

        co_return makeResult(infoAttrs, std::move(storePath));
    } catch (...) {
        co_return result::current_exception();
    }
};

std::unique_ptr<InputScheme> makeGitInputScheme()
{
    return std::make_unique<GitInputScheme>();
}

struct GitLockedInputScheme : GitInputScheme {

    std::string schemeType() const override {
        using namespace std::literals::string_literals;
        return "\0git-locked"s;
    }

    bool hasAllInfo(const Input & input) const override {
        return true;
    }

};

std::unique_ptr<InputScheme> makeGitLockedInputScheme()
{
    return std::make_unique<GitLockedInputScheme>();
}

}