Skip to content

Add checkout & pull commands, changes and fixes to fetch - #527

Merged
technoweenie merged 31 commits into
git-lfs:masterfrom
sinbad:fetch-pull-checkout
Jul 30, 2015
Merged

technoweenie merged 31 commits into
git-lfs:masterfrom
sinbad:fetch-pull-checkout

Conversation

@sinbad

@sinbad sinbad commented Jul 27, 2015

Copy link
Copy Markdown
Contributor
  1. fetch no longer updates the working copy, it only downloads files
  2. Added checkout command which updates the working copy with content if files are missing or are matching pointers. Modified files are left alone (user should reset if they want)
  3. Added pull command which performs fetch and checkout for the current ref
  4. fetch now supports multiple refs as arguments
  5. checkout will correctly populate multiple local files with the same content (old fetch would only populate the first one returned from git rev-list)
  6. fetch only adds missing or incorrect objects to the download queue, not all of them. This improves the progress reporting; previously fetch would appear to be trying to download all objects referenced at a ref then only have to download the missing ones as the download queue figured out they were already local. Also means fetch reports nothing at all if you're completely up to date already, instead of reporting "(0 of 1000 files)".
  7. A side effect is that 'pull' does all fetching first, then all checkout (not interleaved as before). This is because there may be more objects to checkout than to fetch (missing in working copy but already in store). Coupling these has unwanted edge cases & it's better to simplify & do what it says on the tin i.e. the same as running fetch then checkout.

Note that the ScanTree does something similar to ScanRefs but reports pointers for every file that uses the content and not just one where multiple files share the same content. I'm not sure if this is the intended behaviour elsewhere but for now I've left it as a separate method. It also doesn't have the race conditions on nameMap that I believe ScanRefs has (commented elsewhere).

sinbad added 13 commits July 24, 2015 14:56
…size locally

Previously fetch over-reported what it needed to download before eliminating
existing items later when processing the queue, this was misleading.
…in parallel of fetched items

Now that we're not pretending to download objects we already have, we wouldn't
check out objects missing in the working copy but which were already present.
It's better to do exactly what it says on the tin anyway, identical to
separate fetch & pull.
…se in checkout

ScanRefs only reports a blob once even if used by many files in the tree,
which is no good for checkout (only one file would be checked out)
@sinbad

sinbad commented Jul 27, 2015

Copy link
Copy Markdown
Contributor Author

Hrm, didn't spot the pre-push test fail until now, will investigate.

Comment thread lfs/util.go Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typo

@technoweenie

Copy link
Copy Markdown
Contributor

I think this looks good. Nothing major in my comments.

@rubyist: Would love for you to check this out too. What do you think about removing ScanRefs() in favor of ScanTree()? That should be a quick PR as long as the ScanTree() behavior is the same. If this happens though, I'd probably rename ScanTree() to ScanRefs().

@technoweenie technoweenie self-assigned this Jul 27, 2015
@rubyist

rubyist commented Jul 27, 2015

Copy link
Copy Markdown
Contributor

I'll review more thoroughly shortly, but just from reading the text here the big difference between ScanRefs() and ScanTree() is that the former only cares about the Git LFS files themselves where ScanTree() is also concerned with mapping Git LFS files to working directory files, am I correct in that?

I think ScanTree() is good and definitely works here, and would probably be a good fit for the ls-files and fsck commands. However, the transferring functions, fetch, pre-push, etc, aren't concerned with with working directory files. I suspect we can't just replace one with the other as is (since fetch was left using ScanRefs() in this PR). I'm not sure if combining the functions would be very clear, but they could perhaps use better names.

@technoweenie

Copy link
Copy Markdown
Contributor

Hmm, I think you're right about ScanTree() vs ScanRefs() 👍

@technoweenie technoweenie mentioned this pull request Jul 30, 2015
@technoweenie technoweenie removed their assignment Jul 21, 2016
chrisd8088 added a commit to chrisd8088/git-lfs that referenced this pull request Mar 11, 2021
The blobSizeCutoff limit is defined such that "any file
with a size below this cutoff will be scanned" when looking
for LFS pointer blobs.  In general this is true, but there
are few instances where the check is applied such that blobs
matching the cutoff limit are also scanned.

We therefore adjust these to match the same comparison logic
used elsewhere with this limit.

Two of these checks are in the PointerScanner.next() method
used by the runCatFileBatch() function; they were introduced
in commit 844c0b0 in
PR git-lfs#2070 and scan Git objects for eligible LFS pointers
when reading the output of "git cat-file --batch".  Note
that the corresponding runCatFileBatchCheck() function's
catFileBatchCheckScanner.next() method excludes blobs whose
size is above or equal to the limit (with a default limit of
blobSizeCutoff); this aligns with other usage and checks
of the blobSizeCutoff maximum as well.

The other check is in the DecodePointerFromFile()
function where it is used to exclude from consideration as
Git LFS pointers any files larger than blobSizeCutoff.
This function is ultimately called by the "git lfs checkout"
command; the original implementation was added in commit
001ddcd in PR git-lfs#527.
pcal43 pushed a commit to pcal43/git-lfs-hack that referenced this pull request Jul 22, 2021
The blobSizeCutoff limit is defined such that "any file
with a size below this cutoff will be scanned" when looking
for LFS pointer blobs.  In general this is true, but there
are few instances where the check is applied such that blobs
matching the cutoff limit are also scanned.

We therefore adjust these to match the same comparison logic
used elsewhere with this limit.

Two of these checks are in the PointerScanner.next() method
used by the runCatFileBatch() function; they were introduced
in commit 844c0b0 in
PR git-lfs#2070 and scan Git objects for eligible LFS pointers
when reading the output of "git cat-file --batch".  Note
that the corresponding runCatFileBatchCheck() function's
catFileBatchCheckScanner.next() method excludes blobs whose
size is above or equal to the limit (with a default limit of
blobSizeCutoff); this aligns with other usage and checks
of the blobSizeCutoff maximum as well.

The other check is in the DecodePointerFromFile()
function where it is used to exclude from consideration as
Git LFS pointers any files larger than blobSizeCutoff.
This function is ultimately called by the "git lfs checkout"
command; the original implementation was added in commit
001ddcd in PR git-lfs#527.
chrisd8088 added a commit that referenced this pull request Oct 16, 2025
In PR #527 we introduced the "git lfs checkout" and "git lfs pull"
commands and added some initial tests of those commands to our
test suite, which we have subsequently expanded over time.  Before
we adjust how these commands check and create files, we want to
further revise and expand their test suites to validate a broader
range of conditions.

As a first step, we reformat the initial "checkout" and "pull" tests
in the t/t-checkout.sh and t/t-pull.sh test scripts, specifically the
blocks where these tests perform checks after changing the current
working directory.

In the case of the "checkout" test in the t/t-checkout.sh test script,
we use the "pushd" and "popd" shell built-ins to change the current
working directory and then reverse that change.  However, the
intervening commands are not indented, so we do that now to bring the
formatting of this test in line with many of our other tests which
also use these shell built-ins.

In order to improve the consistency between our tests, we then update
the "pull" test in the t/t-pull.sh test script to also use the "pushd"
and "popd" shell built-ins around the "git lfs pull" commands we
want to run in a subdirectory of the test repository's working tree.

We also take the opportunity to remove several unnecessary ls(1) commands
which are left over from development of the tests.
chrisd8088 added a commit that referenced this pull request Oct 16, 2025
In PR #527 we introduced the "git lfs checkout" and "git lfs pull"
commands and added some initial tests of those commands to our test
suite, which we have subsequently expanded over time.  Before we adjust
how these commands check and creates files, we want to further revise
and expand their test suites to validate a broader range of conditions.

In the initial "checkout" test of the t/t-checkout.sh test script we
expand two sets of tests, both those we perform within a subdirectory
of the current working tree, and those we perform with various "glob"
file pattern arguments.

After changing the working directory to a subdirectory of the working
tree, at present the test suite only checks the behaviour of the
"git lfs checkout" command when passed either a single relative file
name and or the "." current directory name.  We now add similar checks
using first a bare ".." parent directory name and then using a relative
path pattern to a sibling subdirectory combined with a trailing "/**"
component, following the gitignore(5) rules we support for pattern
matching.

We also run the "git lfs checkout" command in the root of the working
tree and check that it behaves as expected when passed the name of
a subdirectory which already exists, and when that subdirectory's
name is followed by a trailing "/**" pattern component.

When the "git lfs checkout" command internally converts its file path
pattern arguments into file path patterns that are relative to the root
of the repository, rather being relative to the current working directory,
it appends a trailing "/" character if the pattern is actually just the
path to a directory (or a symbolic link to a directory).  This change is
implemented in the Convert() method of the currentToRepoPatternConverter
structure in our "lfs" package, and was added in commit
56abb71 of PR #4556 so as to ensure
that arguments which resolve to specific directories are properly
converted into patterns that match both the directories and all of
their contents.

Note, though, when we run the "git lfs checkout" command with a "."
directory name argument while in a subdirectory of the working tree,
the internal addition of a trailing "/" character does not actually
affect the success of the command.  This is because the Convert()
of the currentToRepoPatternConverter structure first creates a path
relative to the root of the repository, which necessarily includes
the subdirectory's name as its final component.  When used as a
path pattern according to the gitignore(5) rules, then even without
a trailing "/" character the pattern will still match the subdirectory
and therefore its contents.

On the other hand, the internal additional of a trailing "/" character
does affect the success of the "git lfs checkout" command when we
run the command in a subdirectory and provide a ".." argument.  In this
case, the Convert() method first converts the path into one relative to
the root of the repository, which is simply the "." directory name, the
same as if the user had supplied a "." argument to a "git lfs checkout"
command run in the root of the working tree.

Although "." is a valid file path, when treated as a pattern according
to the gitignore(5) rules, it does not work to match a directory and
all of its contents.  To allow users to provide simple a "." argument
and have it work as expected, the Convert() method first appends the
"/" character, and then strips any leading "./" path component.  If the
result is an empty path, it is replaced with the "**" pattern component
so the final pattern matches everything in the root of the repository.

Thus our new check in the initial "checkout" test of the t/t-checkout.sh
script where we run the "git lfs checkout" command in a subdirectory and
pass a ".." argument, we validate the behaviour described above.  The
check would fail unless the command converted the ".." argument into
a "." path relative to the root of the repository, and into into a
"./" path, and then into the "**" pattern component.

In parallel with our changes to the t/t-checkout.sh test script, we
make a number of changes to the initial "pull" test of the t/t-pull.sh
test script to ensure that test performs all its checks under a common
set of conditions.  We will further enlarge this set of conditions in
subsequent commits.

First, we correct a typo in the refute_server_object() assertion call
that was added to the "pull" test in commit
7158e3b of PR #2641.  This commit
revised the "git lfs pull" and "git lfs checkout" commands so that the
paths they passed to the "git update-index" command were relative to
the current working directory.  To confirm this new behaviour worked
as expected, the "pull" test was updated so it creates a third test
file named "dir/dir.dat", and some of the checks in the test were then
revised to reference this new file.  However, the refute_server_object()
assertion which is intended to prove that the corresponding Git LFS
object does not exist on the test remote server passes an incorrect
variable name, so we fix that now.

Because the "dir/dir.dat" file and corresponding local Git LFS object
file are not comprehensively referenced in all the checks of the
"git lfs pull" command, we add the appropriate assertions for it into
those checks.  (As well, we revise several invocations of the rm(1)
command to align with others in the same test and elsewhere.)

The same commit 7158e3b also extended
the "pull" test to run the "git lfs pull" command with its -I option
under several conditions, but without removing the local Git LFS object
files and working tree files, or checking that they have been re-created
after the "git lfs pull" command is run.  As a consequence, these checks
effectively only confirm that the command does not fail.

To rectify this limitation we delete all the relevant local files
before each of these checks, and then verify that they have been
restored by the "git lfs pull" command.  We also run the "git lfs pull"
command with a more restricted set of file path patterns to confirm that
files which do not match those patterns are not fetched from the remote
server; we then run the command again to fetch those files.  Previously
our checks did not actually test the file path filtering capability of
the command.

As well, we use a file path pattern which is relative to the root of
the repository, so that when we run the "git lfs pull" command in a
subdirectory of the current working tree and pass this pattern, our test
now ascertains that patterns specified with the -I option are correctly
matched with file paths starting from the root of the repository.
(For the moment we do not check that the "git lfs pull" command accepts
"glob" pattern components such as "**", but in a subsequent commit we
will add patterns of this type to the arguments we pass to the -I option.)

Making these changes, however, exposes another concern which would cause
the "pull: with missing object" test to fail unless we adjust it as well.
This test appears later in the same t/t-pull.sh test script, and depends
on the repository clone created by the "pull" test in the local "clone"
test directory.  (Ideally, our tests should not depend on each other in
this way, so that the failure of one test doesn't cause a series of
otherwise unrelated tests to also fail.  For the moment, though, we
defer this issue to a future PR.)

The "pull: with missing object" test was introduced in commit
68ac0f5 of PR #2237 and checks that if
a Git LFS object is missing both locally and on the remote server, the
"git lfs pull" command should report the missing object and return a
non-zero exit code, but should retrieve all other requested Git LFS
objects.  To simulate this condition, the test removes the Git LFS object
corresponding to the "a.dat" test file in the local storage directories
and from the remote test server, and then runs the "git lfs pull"
command.

However, the test does not remove the "a.dat" file from the working
tree, and as noted above, is dependent on the state of the cloned
repository left by the initial "pull" test.  These two factors combine
to make the test vulnerable to transient failures, particularly now
that we have revised the "pull" test such that the final "git lfs pull"
commands in that test re-create all the files in the working tree,
except that we have also changed the "pull" test to drop the commit
which adds an empty file, as we explain below.

In commit d97c785 of PR #4654 the
"pull" test was revised to commit an empty file which matches the
Git LFS file patterns, and then confirm that the "git lfs pull" command
handles that case without trying to fetch the object.  This check
was added before the final checks of the "git lfs pull" command, which
occur within a subdirectory of the working tree.  As a result, those
checks used to run with the empty file as one of the Git LFS objects,
and so did the "pull: with missing object" test.

In these instances, when "git lfs pull" runs, it finds the empty file
matches the defined Git LFS file patterns, and is considered to exist
locally by the LFSObjectExists() method of the Configuration structure
in our "config" package.  Therefore the command passes the object's
pointer data to the Run() method of the singleCheckout structure,
which invokes the DecodePointerFromFile() function in our "lfs" package.
That function returns a successful result because it detects that the
pointer refers to a zero-byte object, and so the RunToPath() method
of the singleCheckout structure is executed, and then the file's path
is passed to the Add() method of the gitIndexer structure.  That
method starts a "git update-index" command and writes the file's path
to the Git command on its standard input file descriptor.

We start the "git update-index" command with the --refresh option, so
it reviews all of its cached index entries, including the one for the
"a.dat" file.  If that file in the working tree has the same modification
timestamp as the Git index file (at least to within the same second,
assuming Git was not compiled with the USE_NSEC macro definition)
then Git considers the file to potentially be "racily clean", because
it's file size and modification timestamp are insufficient to determine
whether the file has changed since the index entry was cached.

The "git update-index" command therefore reads the contents of the
"a.dat" file in the working tree. Because the file's path matches a Git
LFS file pattern, the data is streamed to the "git-lfs-filter-process"
command, which regenerates a new object file in the local storage
directories under ".git/lfs/objects".

Unfortunately, the "pull: with missing object" test starts by removing
the local and remote copies of the "a.dat" file's Git LFS object file,
and expects that running the "git lfs pull" command will not result
in a new local copy being generated, as none can be fetched from the
remote test server.  But if the "pull" test leaves the "a.dat" file
in the working tree with an identical timestamp as the Git index file,
and has also committed the "empty.dat" file to the Git history,
then as described above, the "git lfs pull" invokes "git update-index"
with the --refresh option, which finds the "a.dat" file and re-creates
the local Git LFS object file, and so the test will fail.

Note that without the presence of an empty file in the commit history,
the "git lfs pull" command does not find any local Git LFS object files,
and so it calls the Run() method of the singleCheckout structure after
fetching the available objects from the remote server.  The Run() method
then executes the DecodePointerFromFile() function, which returns an
error because the file in the working tree is not a raw Git LFS pointer,
and so the Run() method skips calling the RunToPath() method and
also does not pass the file's path to the "git update-index" command.
In fact, the "git update-index" command will not be started at all,
as there are no files in the working tree which could be considered to
contain raw Git LFS pointer data, like the empty file is.  Since the
"git update-index" command does not run, the "git-lfs-filter-process"
command is also never invoked, and so a local Git LFS object file is
never re-created for the "a.dat" file, and the test succeeds.

For this reason, we change the "pull" test so that it removes the
"empty.dat" file from the Git commit history after performing the
appropriate check of the "git lfs pull" command's behaviour with
regard to empty files.

To further guard against a potential regression of our tests and
ensure the "pull: with missing object" test passes, we update that
test to remove the "a.dat" file from the working tree as well
as removing its Git LFS object files from both local and remote
storage.  Without the "a.dat" file in the working tree, it now becomes
impossible for the local object file to be re-created under any
circumstances.

Finally, we strengthen our check of the log message output by the
"git lfs pull" command so that we require a specific "does not exist"
message rather than just the raw OID of the missing Git LFS object.
chrisd8088 added a commit that referenced this pull request Oct 16, 2025
In PR #527 we introduced the "git lfs checkout" and "git lfs pull"
commands and added some initial tests of those commands to our
test suite, which we have subsequently expanded over time.  Before
we adjust how these commands check and create files, we want to
further revise and expand their test suites to validate a broader
range of conditions.

As a first step, we reformat the initial "checkout" and "pull" tests
in the t/t-checkout.sh and t/t-pull.sh test scripts, specifically the
blocks where these tests perform checks after changing the current
working directory.

In the case of the "checkout" test in the t/t-checkout.sh test script,
we use the "pushd" and "popd" shell built-ins to change the current
working directory and then reverse that change.  However, the
intervening commands are not indented, so we do that now to bring the
formatting of this test in line with many of our other tests which
also use these shell built-ins.

In order to improve the consistency between our tests, we then update
the "pull" test in the t/t-pull.sh test script to also use the "pushd"
and "popd" shell built-ins around the "git lfs pull" commands we
want to run in a subdirectory of the test repository's working tree.

We also take the opportunity to remove several unnecessary ls(1) commands
which are left over from development of the tests.
chrisd8088 added a commit that referenced this pull request Oct 16, 2025
In PR #527 we introduced the "git lfs checkout" and "git lfs pull"
commands and added some initial tests of those commands to our test
suite, which we have subsequently expanded over time.  Before we adjust
how these commands check and creates files, we want to further revise
and expand their test suites to validate a broader range of conditions.

In the initial "checkout" test of the t/t-checkout.sh test script we
expand two sets of tests, both those we perform within a subdirectory
of the current working tree, and those we perform with various "glob"
file pattern arguments.

After changing the working directory to a subdirectory of the working
tree, at present the test suite only checks the behaviour of the
"git lfs checkout" command when passed either a single relative file
name and or the "." current directory name.  We now add similar checks
using first a bare ".." parent directory name and then using a relative
path pattern to a sibling subdirectory combined with a trailing "/**"
component, following the gitignore(5) rules we support for pattern
matching.

We also run the "git lfs checkout" command in the root of the working
tree and check that it behaves as expected when passed the name of
a subdirectory which already exists, and when that subdirectory's
name is followed by a trailing "/**" pattern component.

When the "git lfs checkout" command internally converts its file path
pattern arguments into file path patterns that are relative to the root
of the repository, rather being relative to the current working directory,
it appends a trailing "/" character if the pattern is actually just the
path to a directory (or a symbolic link to a directory).  This change is
implemented in the Convert() method of the currentToRepoPatternConverter
structure in our "lfs" package, and was added in commit
56abb71 of PR #4556 so as to ensure
that arguments which resolve to specific directories are properly
converted into patterns that match both the directories and all of
their contents.

Note, though, when we run the "git lfs checkout" command with a "."
directory name argument while in a subdirectory of the working tree,
the internal addition of a trailing "/" character does not actually
affect the success of the command.  This is because the Convert()
of the currentToRepoPatternConverter structure first creates a path
relative to the root of the repository, which necessarily includes
the subdirectory's name as its final component.  When used as a
path pattern according to the gitignore(5) rules, then even without
a trailing "/" character the pattern will still match the subdirectory
and therefore its contents.

On the other hand, the internal additional of a trailing "/" character
does affect the success of the "git lfs checkout" command when we
run the command in a subdirectory and provide a ".." argument.  In this
case, the Convert() method first converts the path into one relative to
the root of the repository, which is simply the "." directory name, the
same as if the user had supplied a "." argument to a "git lfs checkout"
command run in the root of the working tree.

Although "." is a valid file path, when treated as a pattern according
to the gitignore(5) rules, it does not work to match a directory and
all of its contents.  To allow users to provide simple a "." argument
and have it work as expected, the Convert() method first appends the
"/" character, and then strips any leading "./" path component.  If the
result is an empty path, it is replaced with the "**" pattern component
so the final pattern matches everything in the root of the repository.

Thus our new check in the initial "checkout" test of the t/t-checkout.sh
script where we run the "git lfs checkout" command in a subdirectory and
pass a ".." argument, we validate the behaviour described above.  The
check would fail unless the command converted the ".." argument into
a "." path relative to the root of the repository, and into into a
"./" path, and then into the "**" pattern component.

In parallel with our changes to the t/t-checkout.sh test script, we
make a number of changes to the initial "pull" test of the t/t-pull.sh
test script to ensure that test performs all its checks under a common
set of conditions.  We will further enlarge this set of conditions in
subsequent commits.

First, we correct a typo in the refute_server_object() assertion call
that was added to the "pull" test in commit
7158e3b of PR #2641.  This commit
revised the "git lfs pull" and "git lfs checkout" commands so that the
paths they passed to the "git update-index" command were relative to
the current working directory.  To confirm this new behaviour worked
as expected, the "pull" test was updated so it creates a third test
file named "dir/dir.dat", and some of the checks in the test were then
revised to reference this new file.  However, the refute_server_object()
assertion which is intended to prove that the corresponding Git LFS
object does not exist on the test remote server passes an incorrect
variable name, so we fix that now.

Because the "dir/dir.dat" file and corresponding local Git LFS object
file are not comprehensively referenced in all the checks of the
"git lfs pull" command, we add the appropriate assertions for it into
those checks.  (As well, we revise several invocations of the rm(1)
command to align with others in the same test and elsewhere.)

The same commit 7158e3b also extended
the "pull" test to run the "git lfs pull" command with its -I option
under several conditions, but without removing the local Git LFS object
files and working tree files, or checking that they have been re-created
after the "git lfs pull" command is run.  As a consequence, these checks
effectively only confirm that the command does not fail.

To rectify this limitation we delete all the relevant local files
before each of these checks, and then verify that they have been
restored by the "git lfs pull" command.  We also run the "git lfs pull"
command with a more restricted set of file path patterns to confirm that
files which do not match those patterns are not fetched from the remote
server; we then run the command again to fetch those files.  Previously
our checks did not actually test the file path filtering capability of
the command.

As well, we use a file path pattern which is relative to the root of
the repository, so that when we run the "git lfs pull" command in a
subdirectory of the current working tree and pass this pattern, our test
now ascertains that patterns specified with the -I option are correctly
matched with file paths starting from the root of the repository.
(For the moment we do not check that the "git lfs pull" command accepts
"glob" pattern components such as "**", but in a subsequent commit we
will add patterns of this type to the arguments we pass to the -I option.)

Making these changes, however, exposes another concern which would cause
the "pull: with missing object" test to fail unless we adjust it as well.
This test appears later in the same t/t-pull.sh test script, and depends
on the repository clone created by the "pull" test in the local "clone"
test directory.  (Ideally, our tests should not depend on each other in
this way, so that the failure of one test doesn't cause a series of
otherwise unrelated tests to also fail.  For the moment, though, we
defer this issue to a future PR.)

The "pull: with missing object" test was introduced in commit
68ac0f5 of PR #2237 and checks that if
a Git LFS object is missing both locally and on the remote server, the
"git lfs pull" command should report the missing object and return a
non-zero exit code, but should retrieve all other requested Git LFS
objects.  To simulate this condition, the test removes the Git LFS object
corresponding to the "a.dat" test file in the local storage directories
and from the remote test server, and then runs the "git lfs pull"
command.

However, the test does not remove the "a.dat" file from the working
tree, and as noted above, is dependent on the state of the cloned
repository left by the initial "pull" test.  These two factors combine
to make the test vulnerable to transient failures, particularly now
that we have revised the "pull" test such that the final "git lfs pull"
commands in that test re-create all the files in the working tree,
except that we have also changed the "pull" test to drop the commit
which adds an empty file, as we explain below.

In commit d97c785 of PR #4654 the
"pull" test was revised to commit an empty file which matches the
Git LFS file patterns, and then confirm that the "git lfs pull" command
handles that case without trying to fetch the object.  This check
was added before the final checks of the "git lfs pull" command, which
occur within a subdirectory of the working tree.  As a result, those
checks used to run with the empty file as one of the Git LFS objects,
and so did the "pull: with missing object" test.

In these instances, when "git lfs pull" runs, it finds the empty file
matches the defined Git LFS file patterns, and is considered to exist
locally by the LFSObjectExists() method of the Configuration structure
in our "config" package.  Therefore the command passes the object's
pointer data to the Run() method of the singleCheckout structure,
which invokes the DecodePointerFromFile() function in our "lfs" package.
That function returns a successful result because it detects that the
pointer refers to a zero-byte object, and so the RunToPath() method
of the singleCheckout structure is executed, and then the file's path
is passed to the Add() method of the gitIndexer structure.  That
method starts a "git update-index" command and writes the file's path
to the Git command on its standard input file descriptor.

We start the "git update-index" command with the --refresh option, so
it reviews all of its cached index entries, including the one for the
"a.dat" file.  If that file in the working tree has the same modification
timestamp as the Git index file (at least to within the same second,
assuming Git was not compiled with the USE_NSEC macro definition)
then Git considers the file to potentially be "racily clean", because
it's file size and modification timestamp are insufficient to determine
whether the file has changed since the index entry was cached.

The "git update-index" command therefore reads the contents of the
"a.dat" file in the working tree. Because the file's path matches a Git
LFS file pattern, the data is streamed to the "git-lfs-filter-process"
command, which regenerates a new object file in the local storage
directories under ".git/lfs/objects".

Unfortunately, the "pull: with missing object" test starts by removing
the local and remote copies of the "a.dat" file's Git LFS object file,
and expects that running the "git lfs pull" command will not result
in a new local copy being generated, as none can be fetched from the
remote test server.  But if the "pull" test leaves the "a.dat" file
in the working tree with an identical timestamp as the Git index file,
and has also committed the "empty.dat" file to the Git history,
then as described above, the "git lfs pull" invokes "git update-index"
with the --refresh option, which finds the "a.dat" file and re-creates
the local Git LFS object file, and so the test will fail.

Note that without the presence of an empty file in the commit history,
the "git lfs pull" command does not find any local Git LFS object files,
and so it calls the Run() method of the singleCheckout structure after
fetching the available objects from the remote server.  The Run() method
then executes the DecodePointerFromFile() function, which returns an
error because the file in the working tree is not a raw Git LFS pointer,
and so the Run() method skips calling the RunToPath() method and
also does not pass the file's path to the "git update-index" command.
In fact, the "git update-index" command will not be started at all,
as there are no files in the working tree which could be considered to
contain raw Git LFS pointer data, like the empty file is.  Since the
"git update-index" command does not run, the "git-lfs-filter-process"
command is also never invoked, and so a local Git LFS object file is
never re-created for the "a.dat" file, and the test succeeds.

For this reason, we change the "pull" test so that it removes the
"empty.dat" file from the Git commit history after performing the
appropriate check of the "git lfs pull" command's behaviour with
regard to empty files.

To further guard against a potential regression of our tests and
ensure the "pull: with missing object" test passes, we update that
test to remove the "a.dat" file from the working tree as well
as removing its Git LFS object files from both local and remote
storage.  Without the "a.dat" file in the working tree, it now becomes
impossible for the local object file to be re-created under any
circumstances.

Finally, we strengthen our check of the log message output by the
"git lfs pull" command so that we require a specific "does not exist"
message rather than just the raw OID of the missing Git LFS object.
chrisd8088 added a commit that referenced this pull request Oct 16, 2025
In PR #527 we introduced the "git lfs checkout" and "git lfs pull"
commands and added some initial tests of those commands to our
test suite, starting with the "checkout" test in what is now our
t/t-checkout.sh test script.  Since that test first appeared in commit
1d05552, it has validated the
behaviour of the "git lfs checkout" command with a number of
example files tracked as Git LFS objects, two of which are located
within subdirectories.

We later added a similar test of the "git lfs pull" command in commit
096b6da of the same PR, but without any
files tracked as Git LFS objects that were not at the top level of the
test repository.  We eventually expanded this test to include one such
file in commit 7158e3b of PR #2641.

However, none of the tests in our t/t-checkout.sh or t/t-pull.sh test
scripts exercise the relevant Git LFS commands with files that are
contained within multiple levels of subdirectories.

Before we adjust how our "git lfs checkout" and "git lfs pull" commands
create subdirectories, we first revise our "checkout" and "pull" tests
to create files within multiple levels of subdirectories, and to confirm
that commands recreate the full set of subdirectories when they do not
exist.

Note that in our "pull" test in particular we now check that
the -I option accepts arguments containing "**" pattern components,
matching the checks we added to our "checkout" test in a previous commit.
chrisd8088 added a commit that referenced this pull request Oct 16, 2025
In PR #527 we introduced the "git lfs checkout" and "git lfs pull"
commands and added some initial tests of those commands to our
test suite, which we have subsequently expanded over time.

At present, we do not have any tests of these commands' behaviour
when they unable to create a subdirectory because a regular file
already exists with the same name.  In these cases, we expect the
commands to report an error but otherwise continue and ultimately
return a zero exit code.

This has been true since commit e909264
of PR #570, when we revised the "git lfs checkout" command so it would
not panic if the DecodePointerFromFile() function in our "lfs" package
returned an error other than an ErrNotExist error.  In particular, the
stat(2) system call, which is invoked by the DecodePointerFromFile()
function via the Stat() function of the "os" package in the standard Go
library, will return an ENOTDIR error number on Unix systems when any of
the components of a given path prefix are not directories.

Before we adjust how the "git lfs checkout" and "git lfs pull" commands
check and create files, we add a pair of new tests which validate that
the commands make no changes when a file exists in place of a directory
which would otherwise be created by the commands.

After each time these tests run a "git lfs checkout" or "git lfs pull"
command, they also check that none of the pre-existing alterations to
the working tree have been accidentally staged in the Git index.  In the
normal case, when these commands successfully update a Git LFS file in
the working tree, they should then call the "git update-index" command to
refresh the modification timestamp Git has cached for the file.  However,
when a directory in the path between the root of the working tree and a
Git LFS file has been replaced with a file, our commands should not update
the Git index.  In order for our tests to confirm this is the case they
call a new assert_clean_index() test helper function which runs a
"git diff-index --cached HEAD" command to check that no unexpected
changes have been staged in the index.

When our new tests run on Unix systems, we expect the "stat" system call
to appear in the error messages output by the "git lfs checkout" and
"git lfs pull" commands, along with a file path relative to the current
working directory and a generic "Checkout error" message.  This log
message is reported by the Run() method of the singleCheckout structure
in our "commands" package when the DecodePointerFromFile() function
returns an error that the "os" package's IsNotExist() function considers
not equivalent to an ErrNotExist error.  (Note that in subsequent commits
we will adjust the text of the log message and change the reported file
path to be relative to the root of the repository.)

On Windows, our new tests expect a different error message, however,
because under the same test conditions the Stat() function of the "os"
package does return an error that the IsNotExist() function considers
equivalent to an ErrNotExist error.  As a result, the Run() method of
our singleCheckout structure handles the errors differently, and proceeds
to call the RunToPath() method of the same structure, which invokes the
SmudgeToFile() method of the GitFilter structure in our "lfs" package.
That method performs another Stat() call to check the size and
permissions mode of any extant file at the given path, but ignores any
errors which might be returned.

Next, the SmudgeToFile() method runs the Create() function from the
"os" package to try to create or truncate a file at the provided path.
When an ancestor in the path is not a directory but a file this function
returns an error, which the SmudgeToFile() method then returns wrapped
with a "could not create working directory file" message.  Finally, the
Run() method of the singleCheckout structure reports this error message
along with its own "could not check out" message and a file path
relative to the root of the repository.  Therefore these are the
messages and file paths our new tests check for on Windows.

The Stat() and Lstat() functions of the "os" package share a common
internal implementation on Windows, and the details of this internal
stat() function and the "syscall" package of the Go standard library
explain why, given our test conditions, the Stat() function returns
an error equivalent to an ErrNotExist error on Windows but not on
Unix systems.

The internal implementation of the Stat() and Lstat() functions on Windows
invokes the CreateFileW() Windows API function with the OPEN_EXISTING
flag, and that system call returns an ERROR_FILE_NOT_FOUND error number
when no file exists at the given path.  The "syscall" package in the Go
standard library then maps this error number to an ErrNotExist error,
unlike how it handles the ENOTDIR error number on Unix systems:

  https://github.com/golang/go/blob/go1.24.4/src/os/stat_windows.go#L66-L71
  https://github.com/golang/go/blob/go1.24.4/src/os/stat_windows.go#L80-L85
  https://github.com/golang/go/blob/go1.24.4/src/syscall/syscall_windows.go#L182-L186
  https://github.com/golang/go/blob/go1.24.4/src/syscall/syscall_unix.go#L126-L127
  https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea#parameters
chrisd8088 added a commit that referenced this pull request Oct 16, 2025
In PR #527 we introduced the "git lfs checkout" and "git lfs pull"
commands and added some initial tests of those commands to our
test suite, which we have subsequently expanded over time.

Since that PR, these commands have consistently used the
DecodePointerFromFile() function in our "lfs" package to check whether
they should replace a file in the working tree with the contents of
a Git LFS object.  This function checks whether a file exists at a
specific location, and if it does, tries to parse the file's content as
a Git LFS pointer.

If no file is found, the object's data will be written to a new file
when the command calls the SmudgeToFile() method of the GitFilter
structure in the same "lfs" package.  Otherwise, the existing file will
only be overwritten with the object's data if the current file contents
are a valid Git LFS pointer to the given object.  Under other conditions,
such as when files have altered content or have been replaced by
directories, the commands should make no changes to the working tree.

The "checkout" and "pull" tests in our t/t-checkout.sh and t/t-pull.sh
test scripts, respectively, confirm that the commands will write new
files with the expected content when there are no files at the
corresponding locations in the working tree, and the "pull" test
also checks that no changes are made when a file has been replaced
with an empty one.

However, we do not have any tests which more explicitly test that
our "git lfs checkout" and "git lfs pull" commands do not alter files
that have been modified or replaced in the working tree.

Before we adjust how these commands check and create files, we add a
pair of new tests which validate that the commands make no changes when
a file has new content or has been replaced with a directory, including
when the commands are run from within such a directory.  Our tests also
use the assert_clean_index() test helper function we introduced in a
previous commit to confirm that the commands do not add the paths of
the changed files to the Git index.

By changing the current working directory to be a directory that has
replaced a Git LFS file, our tests verify that the "git lfs checkout"
and "git lfs pull" commands will not remove the directory within which
the user ran the commands.  While this is not especially significant
at the moment, it will become more so in a subsequent commit when
we revise our commands to change their current working directory to
the root of the work tree before writing any files.
chrisd8088 added a commit that referenced this pull request Oct 16, 2025
In PR #527 we introduced the "git lfs checkout" and "git lfs pull"
commands and added some initial tests of those commands to our
test suite, starting with the "checkout" test in what is now our
t/t-checkout.sh test script.  Since that test first appeared in commit
1d05552, it has validated the
behaviour of the "git lfs checkout" command with a number of
example files tracked as Git LFS objects, two of which are located
within subdirectories.

We later added a similar test of the "git lfs pull" command in commit
096b6da of the same PR, but without any
files tracked as Git LFS objects that were not at the top level of the
test repository.  We eventually expanded this test to include one such
file in commit 7158e3b of PR #2641.

However, none of the tests in our t/t-checkout.sh or t/t-pull.sh test
scripts exercise the relevant Git LFS commands with files that are
contained within multiple levels of subdirectories.

Before we adjust how our "git lfs checkout" and "git lfs pull" commands
create subdirectories, we first revise our "checkout" and "pull" tests
to create files within multiple levels of subdirectories, and to confirm
that commands recreate the full set of subdirectories when they do not
exist.

Note that in our "pull" test in particular we now check that
the -I option accepts arguments containing "**" pattern components,
matching the checks we added to our "checkout" test in a previous commit.
chrisd8088 added a commit that referenced this pull request Oct 16, 2025
Our "git lfs checkout" and "git lfs pull" commands, at present,
follow any extant symbolic links when they populate the current working
tree with files containing the content of Git LFS objects, even if
the symbolic links point to locations outside of the working tree.
This vulnerability has been assigned the identifier CVE-2025-26625.

In a previous commit we partially addressed this vulnerability by
adjusting the DecodePointerFromBlob() function in our "lfs" package to
check whether an irregular file or other directory entry exists at the
location where the commands intend to create or update a file.

While this change handles cases where a symbolic link already exists
the working tree before we try to create or update a file at the same
location, it does not entirely prevent TOCTOU (time-of-check/time-of-use)
races where a symbolic link might be created immediately after we check
for its existence and before we attempt to create or open a file.

One reason is that the "git lfs checkout" and "git lfs pull" commands
use the Create() function from the Go standard library's "os" package
to create or open the files they intend to populate with the contents
of Git LFS objects.  This function follows symbolic links when
determining whether it should create a new file or truncate an existing
one.  If the last segment of the path passed to the function is a
symbolic link, the link will be dereferenced, and a new file will be
created at the link's target path or, if a file already exists at that
target path, then that file will be opened and truncated.

Further, because the Create() function opens and truncates any existing
file it finds, if that file is hard-linked to one or more other
paths, then once the file is closed the new content our commands have
written into it will be visible through all of those paths, regardless
of whether they reside inside or outside the Git working tree.

Our "git lfs checkout" and "git lfs pull" commands have exhibited these
behaviours since they were first implemented in PR #527.  That PR
added a PointerSmudgeToFile() function to the "lfs" package, which was
later refactored by PR #2687 into the SmudgeToFile() method of the
GitFilter structure in the current version of our "lfs" package.  The
original PointerSmudgeToFile() function made use of the "os" package's
Create() function to create a new file or truncate an existing one,
and the contemporary SmudgeToFile() method follows suit.

For performance and compatibility reasons, Git does not try to
completely eliminate all TOCTOU races involving symbolic links, and
for similar reasons we do not expect to prevent every possible race
which might allow the Git LFS client to unintentionally write through
a symbolic link.  We do, though, intend to limit the chances of this
occurring as far as we reasonably can.

Therefore, to address the problems with symbolic and hard links described
above, we revise the SmudgeToFile() method so that it first removes any
existing file at the path it is given, and if that succeeds, then attempts
to atomically create a new file, reporting an error if that cannot be done
because a file or other directory entry already exists at the same path.

Specifically, we use the OpenFile() function from the "os" package
instead of the Create() function, and we pass both the O_CREATE and
O_EXCL flags to guarantee that the function either creates a new file
or returns an error.  Before calling OpenFile() we first call the
"os" package's Remove() function and report an error if it fails for
any reason other than that there is no file found at the given path.

This approach mirrors that taken by Git when it updates files in the
working tree.  In particular, when the "git checkout" command is
asked to update a specific pathspec (e.g., with a command such as
"git checkout -- file.txt"), the checkout_entry_ca() function first
calls the unlink(2) system call, and then the create_file() function
invokes the open(2) system call with the O_CREATE and O_EXCL flags:

  https://github.com/git/git/blob/cb96e1697ad6e54d11fc920c95f82977f8e438f8/entry.c#L552-L578
  https://github.com/git/git/blob/cb96e1697ad6e54d11fc920c95f82977f8e438f8/entry.c#L88-L89

Note that Git is actually more aggressive than the Git LFS client
in how it handles conflicting content when checking out specific
paths.  For instance, if it finds a directory in place of a file it
intends to write, its remove_subtree() function will be used to try
to recursively remove the directory and all of its contents.

By constrast, while our SmudgeToFile() method will now remove existing
files (whether regular or irregular), symbolic links, and empty
directories which conflict with the file it intends to create, the
function will will not remove non-empty directories.

Moreover, the SmudgeToFile() method will only take this action if one
of these types of directory entries has been created in the brief
time interval since the DecodePointerFromBlob() function was called,
since we use that function to determine whether to proceed to call
the SmudgeToFile() method.

The sole caller of the SmudgeToFile() method is the RunToPath()
method of the singleCheckout structure in our "commands" package,
which is used only by the "git lfs checkout" and "git lfs pull"
commands.  Except when "git lfs checkout" is called with a --to
option, the RunToPath() method is only called from the Run() method
of the same singleCheckout structure.  That method first invokes
the DecodePointerFromBlob() function, and proceeds to call the
SmudgeToFile() method only if no regular file was found, or if
a regular file was found and its contained a valid Git LFS pointer
whose ID matches that of the corresponding object.

For this reason, we are guaranteed that when the SmudgeToFile() method
is called, the path it is passed is either one provided by the user
with the --to option of the "git lfs checkout" command, or has just
been checked by the DecodePointerFromBlob() function.  In either case
we can be confident that it is reasonable to delete anything which now
exists at that location.  Note, too, that prior to the changes in this
commit, any regular file or file referenced by a final symbolic link
in the path would be truncated and overwritten regardless of its contents
by the SmudgeToFile() method, so removing any directory entry (except
for non-empty subdirectories) we find and creating a new file is not
substantially different in this respect.

However, there are several key advantages to our new approach.  First,
we can now be certain we will never dereference a final symbolic link
in the given path and write to the link's target.  Note, though, that
we do still traverse symbolic links when they are found in place of
directories in path segments other than the final segment.  We will
partially address this concern in a subsequent commit, with the same
caveats that apply to Git's handling of symbolic links in non-terminal
path segments.

Second, by always creating a new file we can be certain the content
we write will not be visible through hard links to an existing file.
We therefore add a pair of new tests to our t/t-checkout.sh and
t/t-pull.sh test suite which exercise the "git lfs checkout" and
"git lfs pull" commands and confirm that they replace existing files
with multiple hard links and effectively break those links.  Both of
our new tests use the assert_clean_status() test helper function to
confirm that the "git lfs checkout" and "git lfs pull" commands continue
to update the Git index entries for any Git LFS files they recreate in
the working tree.

We also expand the checks performed by the "checkout: conflicts" test
in our t/t-checkout.sh test script to check that symbolic links as well
as hard links are broken by our changes to the SmudgeToFile() method.
We are able to use this test for this purpose because it runs the
"git lfs checkout" command with the --to option, which means the
Run() method of the singleCheckout structure is not used and the
RunToPath() method is called directly.  In turn, that implies that
the DecodePointerFromBlob() function is never invoked, so the command
does not simply detect the symbolic link in that function and therefore
skip making a call to the SmudgeToFile() method, as occurs in our
"checkout: skip file symlink conflicts" and "pull: skip file symlink
conflicts" tests.  Instead, the RunToPath() method calls the
SmudgeToFile() method, which then removes the symbolic link and
creates a new file in its place.  Hence we can use this test to confirm
that our changes are effective in breaking symbolic links as well as
hard links.

And third, our new approach means we can eliminate two calls to the
"os" package's Chmod() function, which were added to the SmudgeToFile()
method in commit 686bda3 of PR #3120
in order to handle pointer files to which our "lockable" Git attribute
applies, but which the user has not yet locked, and so the pointer files
have read-only permissions we want to retain while also replacing the
file's contents with the corresponding Git LFS object data.

We do not need to call the Chmod() function before invoking the
Remove() function, because that function should be able to delete any
existing file, even one with read-only permissions, so long as the
parent directory permits changes to its list of entries.

Note that our previous implementation might succeed even if the
parent directory did not allow changes to its list of entries, and
our new implementation will not.  This does imply a partial change
in the behaviour of the Git LFS client when directories in the
working tree are themselves marked read-only.  However, neither our
old or new implementations could succeed in creating new files within
such directories.  Moreover, we expect Git working trees to normally
have read-write directory permissions, since many regular Git commands
will not function otherwise.  We therefore consider the altered
behaviour of the Git LFS client to be an acceptable change given
that it will remediate several security concerns.

We also do not need to call the Chmod() function at the end of the
SmudgeToFile() method, because we instead pass the file permissions
we want directly to the OpenFile() function.

In the case where an existing file is found, prior to our deletion of
that file, we read its permissions with the Lstat() function of the
"os" package, and then pass those permissions to the OpenFile()
function.  If a symbolic link or some other type of directory entry
is found, though, we ignore its permissions and use a default setting
of 0666 instead.  (On Unix systems, the current "umask" setting will
then be applied to whatever permissions we pass to the OpenFile()
function.)

While the use of a default permissions mode of 0666 matches that used
by the Create() function of the "os" package, and so aligns with the
legacy behaviour of the Git LFS client, this is not actually the ideal
implementation.  Rather, we should respect the mode defined for the
file in Git, which may have the executable mode set.  For now, though,
we leave this as improvement for a future PR, and just include a
comment to remind us of this oversight in our implementation.

Finally, because the "git lfs checkout" command will now attempt to
remove and replace the file or other directory entry it finds at the
path supplied with the --to option, we update our git-lfs-checkout(1)
manual page to reflect this new behaviour.
chrisd8088 added a commit that referenced this pull request Oct 16, 2025
In PR #527 we introduced the "git lfs checkout" and "git lfs pull"
commands and added some initial tests of those commands to our
test suite, which we have subsequently expanded over time.

At present, we do not have any tests of these commands' behaviour
when they unable to create a subdirectory because a regular file
already exists with the same name.  In these cases, we expect the
commands to report an error but otherwise continue and ultimately
return a zero exit code.

This has been true since commit e909264
of PR #570, when we revised the "git lfs checkout" command so it would
not panic if the DecodePointerFromFile() function in our "lfs" package
returned an error other than an ErrNotExist error.  In particular, the
stat(2) system call, which is invoked by the DecodePointerFromFile()
function via the Stat() function of the "os" package in the standard Go
library, will return an ENOTDIR error number on Unix systems when any of
the components of a given path prefix are not directories.

Before we adjust how the "git lfs checkout" and "git lfs pull" commands
check and create files, we add a pair of new tests which validate that
the commands make no changes when a file exists in place of a directory
which would otherwise be created by the commands.

After each time these tests run a "git lfs checkout" or "git lfs pull"
command, they also check that none of the pre-existing alterations to
the working tree have been accidentally staged in the Git index.  In the
normal case, when these commands successfully update a Git LFS file in
the working tree, they should then call the "git update-index" command to
refresh the modification timestamp Git has cached for the file.  However,
when a directory in the path between the root of the working tree and a
Git LFS file has been replaced with a file, our commands should not update
the Git index.  In order for our tests to confirm this is the case they
call a new assert_clean_index() test helper function which runs a
"git diff-index --cached HEAD" command to check that no unexpected
changes have been staged in the index.

When our new tests run on Unix systems, we expect the "stat" system call
to appear in the error messages output by the "git lfs checkout" and
"git lfs pull" commands, along with a file path relative to the current
working directory and a generic "Checkout error" message.  This log
message is reported by the Run() method of the singleCheckout structure
in our "commands" package when the DecodePointerFromFile() function
returns an error that the "os" package's IsNotExist() function considers
not equivalent to an ErrNotExist error.  (Note that in subsequent commits
we will adjust the text of the log message and change the reported file
path to be relative to the root of the repository.)

On Windows, our new tests expect a different error message, however,
because under the same test conditions the Stat() function of the "os"
package does return an error that the IsNotExist() function considers
equivalent to an ErrNotExist error.  As a result, the Run() method of
our singleCheckout structure handles the errors differently, and proceeds
to call the RunToPath() method of the same structure, which invokes the
SmudgeToFile() method of the GitFilter structure in our "lfs" package.
That method performs another Stat() call to check the size and
permissions mode of any extant file at the given path, but ignores any
errors which might be returned.

Next, the SmudgeToFile() method runs the Create() function from the
"os" package to try to create or truncate a file at the provided path.
When an ancestor in the path is not a directory but a file this function
returns an error, which the SmudgeToFile() method then returns wrapped
with a "could not create working directory file" message.  Finally, the
Run() method of the singleCheckout structure reports this error message
along with its own "could not check out" message and a file path
relative to the root of the repository.  Therefore these are the
messages and file paths our new tests check for on Windows.

The Stat() and Lstat() functions of the "os" package share a common
internal implementation on Windows, and the details of this internal
stat() function and the "syscall" package of the Go standard library
explain why, given our test conditions, the Stat() function returns
an error equivalent to an ErrNotExist error on Windows but not on
Unix systems.

The internal implementation of the Stat() and Lstat() functions on Windows
invokes the CreateFileW() Windows API function with the OPEN_EXISTING
flag, and that system call returns an ERROR_FILE_NOT_FOUND error number
when no file exists at the given path.  The "syscall" package in the Go
standard library then maps this error number to an ErrNotExist error,
unlike how it handles the ENOTDIR error number on Unix systems:

  https://github.com/golang/go/blob/go1.24.4/src/os/stat_windows.go#L66-L71
  https://github.com/golang/go/blob/go1.24.4/src/os/stat_windows.go#L80-L85
  https://github.com/golang/go/blob/go1.24.4/src/syscall/syscall_windows.go#L182-L186
  https://github.com/golang/go/blob/go1.24.4/src/syscall/syscall_unix.go#L126-L127
  https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea#parameters
chrisd8088 added a commit that referenced this pull request Oct 16, 2025
In PR #527 we introduced the "git lfs checkout" and "git lfs pull"
commands and added some initial tests of those commands to our
test suite, which we have subsequently expanded over time.

Since that PR, these commands have consistently used the
DecodePointerFromFile() function in our "lfs" package to check whether
they should replace a file in the working tree with the contents of
a Git LFS object.  This function checks whether a file exists at a
specific location, and if it does, tries to parse the file's content as
a Git LFS pointer.

If no file is found, the object's data will be written to a new file
when the command calls the SmudgeToFile() method of the GitFilter
structure in the same "lfs" package.  Otherwise, the existing file will
only be overwritten with the object's data if the current file contents
are a valid Git LFS pointer to the given object.  Under other conditions,
such as when files have altered content or have been replaced by
directories, the commands should make no changes to the working tree.

The "checkout" and "pull" tests in our t/t-checkout.sh and t/t-pull.sh
test scripts, respectively, confirm that the commands will write new
files with the expected content when there are no files at the
corresponding locations in the working tree, and the "pull" test
also checks that no changes are made when a file has been replaced
with an empty one.

However, we do not have any tests which more explicitly test that
our "git lfs checkout" and "git lfs pull" commands do not alter files
that have been modified or replaced in the working tree.

Before we adjust how these commands check and create files, we add a
pair of new tests which validate that the commands make no changes when
a file has new content or has been replaced with a directory, including
when the commands are run from within such a directory.  Our tests also
use the assert_clean_index() test helper function we introduced in a
previous commit to confirm that the commands do not add the paths of
the changed files to the Git index.

By changing the current working directory to be a directory that has
replaced a Git LFS file, our tests verify that the "git lfs checkout"
and "git lfs pull" commands will not remove the directory within which
the user ran the commands.  While this is not especially significant
at the moment, it will become more so in a subsequent commit when
we revise our commands to change their current working directory to
the root of the work tree before writing any files.
chrisd8088 added a commit that referenced this pull request Oct 16, 2025
Our "git lfs checkout" and "git lfs pull" commands retrieve a list of
Git LFS pointer files from the ScanLFSFiles() method of the GitScanner
structure type in our "lfs" package, and for each file, invoke the Run()
method of the singleCheckout structure type in our "commands" package.

For a given Git LFS pointer file, the Run() method determines whether
or not to write the contents of the object referenced by the pointer
into a file in the working tree at the appropriate path.

Because the user may execute the "git lfs checkout" and "git lfs pull"
commands from any location within a Git repository, the Run() method
tries to convert the file path of pointer, which is always relative
to the root of the repository, into a path relative to the current
working directory.  To do this, it calls the Convert() method of the
repoToCurrentPathConverter structure type in our "lfs" package, which
first prepends the absolute path to the root of the current working
tree, and then generates a relative path to that location from the
current working directory.

The repoToCurrentPathConverter structure and its methods were refactored
in commit 68efd05 of PR #1771 from the
original ConvertRepoFilesRelativeToCwd() function.  That function was
added in commit 760c7d7 of PR #527,
the same PR which introduced the "git lfs checkout" and "git lfs pull"
commands.

After calling the Convert() method to generate a path relative to the
current working directory, the Run() method passes that path to
several other functions and methods, while also using the original
input path (the one relative to the root of the repository) in other
function calls and error messages.

Because the Convert() method assumes that a current working tree is
defined (and that the current working directory is within this tree),
it will return invalid paths when these conditions are not true, such
as when the user is working in a bare repository.  In a prior commit
we therefore added a check to the Run() method so that it will not
execute the Convert() method when the no working tree is defined, which
resolved a bug whereby under unusual conditions the "git lfs checkout"
and "git lfs pull" commands could write to a file outside a bare
repository.  (In another prior commit we then also updated the
"git lfs checkout" command so that it will exit immediately when run
in a bare repository.)

The Run() method now checks the state of a "hasWorkTree" element in the
singleCheckout structure and returns without taking further action if
the element's value is "false".  When we initialize a new singleCheckout
structure in the newSingleCheckout() function of our "commands" package,
we set the value of the "hasWorkTree" element to "true" only if the
the LocalWorkingDir() method of the Configuration structure type from
our "config" package returns a non-empty path.

The LocalWorkingDir() method returns the absolute path to the root of
the current working tree, or an empty path if no working tree is defined,
as determined by the GitAndRootDirs() function in our "git" package.
The GitAndRootDirs() function runs the "git rev-parse" command with the
--show-toplevel option, and then interprets that command's output and
exit code so that if no working tree is defined, an empty path is
returned instead of a path to the work tree's root directory.

If a working tree exists and so the "hasWorkTree" element is "true",
the Run() method will proceed to invoke the Convert() method and then
pass the resultant path, which is relative to the current working
directory, to the DecodePointerFromFile() function from our "lfs"
package, and then to the RunToPath() method of the singleCheckout
structure, which passes it to the SmudgeToFile() method of the GitFilter
structure in our "lfs" package.  The Run() method later also passes the
path to the Add() method of the gitIndexer structure in our "commands"
package, which writes the path to a "git update-index" command on its
standard input file descriptor.

In a prior commit we updated the SmudgeToFile() method so that it
always creates a new file, rather than writing Git LFS object data into
an existing file, which ensures that the method will not write through
a symbolic link which exists in the place of the final filename component
of a given Git LFS pointer's file path.

In subsequent commits we will next revise the Run() method and add new
methods for the singleCheckout structure so that we check each ancestor
component of a Git LFS pointer's file path to verify that none of the
directory components of the path are symbolic links.  If a symbolic link
is found, we will report it in a new error message log format, and the
RunToPath() method will then not be invoked, nor will the gitIndexer
structure's Add() method.

With our current design, performing these checks for symbolic links,
which must be made on each path component from the root of the current
working tree to the parent directory of a given file, is complicated
by the fact that the current working directory may be located anywhere
within the work tree.  We either have to prepend zero or more ".."
path components to reach the root of the working tree, or construct an
absolute path to the root of the tree and then prepend that path to
each Git LFS pointer's file path within the repository.

To simplify both the future implementation of our checks for symbolic
links in file paths and the overall design of the Run() method, we
first adopt the approach taken by Git, which is to change the current
working directory to the root of the working tree, if one exists, before
checking for symbolic links and creating files in the work tree:

  https://github.com/git/git/blob/v2.50.1/setup.c#L1759-L1760
  https://github.com/git/git/blob/v2.50.1/symlinks.c#L63-L193

Git runs its setup_git_directory_gently() function shortly after
starting, and when it detects that the current working directory is
within a work tree, it changes the working directory to that root of
that work tree.

Since we only need to change the working directory once, we revise the
newSingleCheckout() function so it attempts to do this if a working
tree was detected and it has therefore set the "hasWorkTree" flag to
"true".  If the Chdir() function from the "os" package in the Go
standard library returns an error, the newSingleCheckout() function
reports the error and sets the "hasWorkTree" flag to "false" so that
the Run() method will always return immediately and never try to read
or write any files.

Note that when the Chdir() function returns an error, we explicitly
do not cause the current Git LFS command to exit, because we want
the command to continue even if it is unable to read or write files
in the current working tree.  In the case of the "git lfs checkout"
command, the command may have been invoked with the --to option, in
which case it should write its output to the file specified by the
user rather than into a Git LFS file within the working tree.  In the
case of the "git lfs pull" command, the command should try to fetch
any Git LFS objects that not present in the local storage directories
even if their contents can not be written into files in the working
tree.  In either case, we do not want the newSingleCheckout() function
to cause the commands to exit prematurely, even if an error occurs.

Also note that we do not need to keep a record of the original current
working directory and avoid deleting that directory, because a change
we made in a previous commit to the DecodePointerFromFile() function
ensures that we detect whether the file path passed to the Run() method
is a directory, and if so, returns an error.  Therefore, if the user
has created a directory in place of a Git LFS file, and set that
directory as the working directory, we will not remove it when trying
to check out that file.  The "checkout: skip changed files" and
"pull: skip changed files" tests we added in a previous commit to our
t/t-checkout.sh and t/t-pull.sh test scripts include checks which
verify this behaviour by running the respective commands from within
a directory which has replaced a Git LFS file in the working tree.

Our revisions to the newSingleCheckout() function mean that the Run()
method will only proceed if a working tree is defined and the current
working directory is the root of that tree.  One key consequence of
this change is that the method no longer need to construct a path
relative to the current working directory, as it can simply use the
path provided by Git, which is stored in the "Name" element of the
WrappedPointer structure passed to the Run() method as its sole
parameter, named "p".

As a result, the Run() method can use the "Name" element of its "p"
parameter in all in the instances where it previously used the
"cwdfilepath" variable which stored the result of the call to the
Convert() method of the repoToCurrentPathConverter structure.

Further, because the Run() method was the only caller of the Convert()
method, and the singleCheckout structure's "pathConverter" element
was the only instance of a repoToCurrentPathConverter structure in our
codebase, we can now remove that structure type and all of its methods
from the "lfs" package.

We make two alterations in this commit to the initial steps performed by
the "git lfs checkout" command so that it continues to support the use
of command-line arguments that are specified as file paths relative to
the directory in which the command is run.

First, in the checkoutCommand() function we now call the rootedPaths()
function before calling the newSingleCheckout() function, since the
newSingleCheckout() function now changes the current working directory.
By calling the rootedPaths() function first, it can convert any file
path pattern arguments provided by the user that are relative to the
initial working directory into path patterns relative to the root
of the repository at a time before the newSingleCheckout() function
changes the current working directory.

In a prior commit we added checks to the initial "checkout" test in our
t/t-checkout.sh test script which run the "git lfs checkout" command in
a subdirectory of the working tree and pass relative path arguments like
".." and "../folder2/**", and then verify that the command updates the
appropriate files in the work tree.  These checks now serve to confirm
that our revisions to the operation of the "git lfs checkout" command in
this commit do not cause any regression in the command's support for
relative file path pattern arguments, regardless of the whether the
command is run in the root of the working tree or in one of its
subdirectories.

Second, if the --to option is specified, we invoke the Abs() function
from the "path/filepath" package on its argument to generate an absolute
path, which we then pass to the RunToPath() method of the singleCheckout
structure as its "path" parameter, instead of passing the original
command-line argument.  This allows the newSingleCheckout() function
to change the working directory without causing problems if the user
supplies a relative path argument with the --to option.  Otherwise,
we would have to convert the provided path from one which was relative
to the original working directory into one which was relative to the
root of the working tree, which might even point outside of the work
tree since the user is free to supply a path to any location in their
system.  Given this, using an absolute path is our simplest approach
to handling the --to option's argument.

The checks we added in a prior commit to the "checkout: conflicts" test
in our t/t-checkout.sh test script now help verify that the "git lfs
checkout" command continues to supports the use of relative paths with
the --to option and that when this option is supplied an output file is
written to the same location as before, even if the command is run in
a subdirectory of the working tree.

In addition to the foregoing, by altering the "git lfs checkout" and
"git lfs pull" commands to change the current working directory to the
root of the work tree before they begin processing any Git LFS files,
we gain one further benefit with regard to how we handle Git LFS pointer
extension programs.  If such programs are configured, we invoke them
while performing "clean" and "smudge" operations, including the "smudge"
operations initiated by the SmudgeToFile() method when it is invoked by
the "git lfs checkout" and "git lfs pull" commands.

We first introduced support for pointer extension programs in PR #486,
at which time we modelled their configuration on that of Git's own
"clean" and "smudge" filters.  In particular, Git provides filter
programs with the path to the file they are processing in place of any
"%f" specifiers in the command lines specified by the "filter.*.clean"
and "filter.*.smudge" configuration entries.  For long-running filter
programs configured using "filter.*.process" entries, Git sends the path
to each file they process as the value of a "pathname" key in the stream
of data piped to the programs, using the protocol designed for these
types of filter programs.

In all cases, the file paths provided by Git are relative to the root
of the repository, not to the user's current working directory at the time
the initial Git command was started.  Moreover, Git changes the current
working directory to the root of the working tree before invoking any
filter processes, so the file paths it passes to the processes correspond
with the files Git will read or write in the working tree.  However,
the gitattributes(5) manual page notes that files may not actually exist
at these file paths, or may have different contents than the ones Git
pipes to the filter process, and so filter programs should not attempt
to access files at these paths:

  https://github.com/git/git/blob/v2.50.1/Documentation/gitattributes.adoc?plain=1#L503-L507

The Smudge() method of the GitFilter structure in our "lfs" package is
used by both of our "git lfs smudge" and "git lfs filter-process"
commands, and is responsible for writing the contents of a Git LFS object
as a data stream to its "writer" parameter.  This output data is then
piped back to the Git process which executed the Git LFS filter command.
In such a context, the "workingfile" parameter of the Smudge() process
contains a file path provided by Git, either in place of a "%f"
command-line specifier or as the value of a "pathname" key, per the
long-running filter protocol.

As the Git documentation states, files may not exist at these file
paths, or may have different content than the filter would expect, so
our Smudge() method is careful to only use the file paths passed to it
in its "workingfile" parameter for informational and error logging
purposes.  Likewise, all the methods and functions to which the Smudge()
method passes this parameter also only use it for logging purposes,
or at least that is our intention.

One particular use of this "workingfile" parameter's value pertains to
our support for Git LFS pointer extensions.  Like Git, the Git LFS client
will pass a file path in place of a "%f" command-line specifier if one
is found in the configuration setting for a pointer extension program.
(The actual contents of the pointer file, however, will be piped to the
extension program on its standard input file descriptor.)

When our Smudge() method invokes the readLocalFile() method of the
GitFilter structure, it passes its "workingfile" parameter.  If Git
has supplied this path to a "git lfs smudge" or "git lfs filter-process"
command, the path will be relative to the root of the repository.  Should
any Git LFS pointer extensions be configured, the readLocalFile() method
will use its "workingfile" parameter to populate the "fileName" elements
of new "pipeRequest" structures, which are then passed one at a time to
the pipeExtensions() function.  That function executes the given
extension program and substitutes the "%f" specifier in the program's
configured command line with the value from the "fileName" element
of the "pipeRequest" structure.

When the Git LFS client is not run by Git as a filter program but
executed directly via the "git lfs checkout" or "git lfs pull" commands,
however, we previously did not change the current working directory
before invoking pointer extension programs.  We also substituted for
the "%f" specifier file paths that were relative to the current working
directory (unless an absolute file path was specified by the user as
the argument of the "git lfs checkout" command's --to option).

Like Git filter programs, Git LFS pointer extension programs should not
expect to access an actual file at the paths passed in place of the "%f"
command-line specifiers.  At present, though, we do not make this
explicit.

To confirm that our changes in this commit function as expected when
Git LFS pointer extension programs are configured, we update the
lfstest-caseinverterextension test utility we added in a prior commit
so that it now reports an error and exits if it does not find a ".git"
directory in its current working directory, which would imply it is not
executing within the top-level directory of a work tree.

We also update our "checkout: pointer extension" and "pull: pointer
extension" tests so they check that the paths received and logged by
the lfstest-caseinverterextension test utility are relative to the
root of the repository even if the "git lfs checkout" or "git lfs pull"
command is executed in a subdirectory within the working tree.

However, we update our "checkout: pointer extension with conflict"
test so that it checks that the paths received and logged by the
lfstest-caseinverterextension test utility are absolute paths, because
now always convert the file path argument of the "git lfs checkout"
command's --to option into an absolute path before passing it to
the RunToPath() method.  This is the only use case in which the
RunToPath() method is invoked directly and not by the Run() method,
and thus the only instance in which the file paths of the RunToPath()
method's "path" parameter does not correspond in any way with the
file path of the given Git LFS pointer file.  This exceptional
behaviour dates from the introduction of the --to option in commit
cf7f967 of PR #3296, and we will
address this issue in a subsequent PR.
chrisd8088 added a commit that referenced this pull request Oct 16, 2025
Our "git lfs checkout" and "git lfs pull" commands, at present,
follow any extant symbolic links when they populate the current working
tree with files containing the content of Git LFS objects, even if
the symbolic links point to locations outside of the working tree.
This vulnerability has been assigned the identifier CVE-2025-26625.

In a previous commit we partially addressed this vulnerability by
adjusting the DecodePointerFromBlob() function in our "lfs" package to
check whether an irregular file or other directory entry exists at the
location where the commands intend to create or update a file.

While this change handles cases where a symbolic link already exists
the working tree before we try to create or update a file at the same
location, it does not entirely prevent TOCTOU (time-of-check/time-of-use)
races where a symbolic link might be created immediately after we check
for its existence and before we attempt to create or open a file.

One reason is that the "git lfs checkout" and "git lfs pull" commands
use the Create() function from the Go standard library's "os" package
to create or open the files they intend to populate with the contents
of Git LFS objects.  This function follows symbolic links when
determining whether it should create a new file or truncate an existing
one.  If the last segment of the path passed to the function is a
symbolic link, the link will be dereferenced, and a new file will be
created at the link's target path or, if a file already exists at that
target path, then that file will be opened and truncated.

Further, because the Create() function opens and truncates any existing
file it finds, if that file is hard-linked to one or more other
paths, then once the file is closed the new content our commands have
written into it will be visible through all of those paths, regardless
of whether they reside inside or outside the Git working tree.

Our "git lfs checkout" and "git lfs pull" commands have exhibited these
behaviours since they were first implemented in PR #527.  That PR
added a PointerSmudgeToFile() function to the "lfs" package, which was
later refactored by PR #2687 into the SmudgeToFile() method of the
GitFilter structure in the current version of our "lfs" package.  The
original PointerSmudgeToFile() function made use of the "os" package's
Create() function to create a new file or truncate an existing one,
and the contemporary SmudgeToFile() method follows suit.

For performance and compatibility reasons, Git does not try to
completely eliminate all TOCTOU races involving symbolic links, and
for similar reasons we do not expect to prevent every possible race
which might allow the Git LFS client to unintentionally write through
a symbolic link.  We do, though, intend to limit the chances of this
occurring as far as we reasonably can.

Therefore, to address the problems with symbolic and hard links described
above, we revise the SmudgeToFile() method so that it first removes any
existing file at the path it is given, and if that succeeds, then attempts
to atomically create a new file, reporting an error if that cannot be done
because a file or other directory entry already exists at the same path.

Specifically, we use the OpenFile() function from the "os" package
instead of the Create() function, and we pass both the O_CREATE and
O_EXCL flags to guarantee that the function either creates a new file
or returns an error.  Before calling OpenFile() we first call the
"os" package's Remove() function and report an error if it fails for
any reason other than that there is no file found at the given path.

This approach mirrors that taken by Git when it updates files in the
working tree.  In particular, when the "git checkout" command is
asked to update a specific pathspec (e.g., with a command such as
"git checkout -- file.txt"), the checkout_entry_ca() function first
calls the unlink(2) system call, and then the create_file() function
invokes the open(2) system call with the O_CREATE and O_EXCL flags:

  https://github.com/git/git/blob/cb96e1697ad6e54d11fc920c95f82977f8e438f8/entry.c#L552-L578
  https://github.com/git/git/blob/cb96e1697ad6e54d11fc920c95f82977f8e438f8/entry.c#L88-L89

Note that Git is actually more aggressive than the Git LFS client
in how it handles conflicting content when checking out specific
paths.  For instance, if it finds a directory in place of a file it
intends to write, its remove_subtree() function will be used to try
to recursively remove the directory and all of its contents.

By constrast, while our SmudgeToFile() method will now remove existing
files (whether regular or irregular), symbolic links, and empty
directories which conflict with the file it intends to create, the
function will will not remove non-empty directories.

Moreover, the SmudgeToFile() method will only take this action if one
of these types of directory entries has been created in the brief
time interval since the DecodePointerFromBlob() function was called,
since we use that function to determine whether to proceed to call
the SmudgeToFile() method.

The sole caller of the SmudgeToFile() method is the RunToPath()
method of the singleCheckout structure in our "commands" package,
which is used only by the "git lfs checkout" and "git lfs pull"
commands.  Except when "git lfs checkout" is called with a --to
option, the RunToPath() method is only called from the Run() method
of the same singleCheckout structure.  That method first invokes
the DecodePointerFromBlob() function, and proceeds to call the
SmudgeToFile() method only if no regular file was found, or if
a regular file was found and its contained a valid Git LFS pointer
whose ID matches that of the corresponding object.

For this reason, we are guaranteed that when the SmudgeToFile() method
is called, the path it is passed is either one provided by the user
with the --to option of the "git lfs checkout" command, or has just
been checked by the DecodePointerFromBlob() function.  In either case
we can be confident that it is reasonable to delete anything which now
exists at that location.  Note, too, that prior to the changes in this
commit, any regular file or file referenced by a final symbolic link
in the path would be truncated and overwritten regardless of its contents
by the SmudgeToFile() method, so removing any directory entry (except
for non-empty subdirectories) we find and creating a new file is not
substantially different in this respect.

However, there are several key advantages to our new approach.  First,
we can now be certain we will never dereference a final symbolic link
in the given path and write to the link's target.  Note, though, that
we do still traverse symbolic links when they are found in place of
directories in path segments other than the final segment.  We will
partially address this concern in a subsequent commit, with the same
caveats that apply to Git's handling of symbolic links in non-terminal
path segments.

Second, by always creating a new file we can be certain the content
we write will not be visible through hard links to an existing file.
We therefore add a pair of new tests to our t/t-checkout.sh and
t/t-pull.sh test suite which exercise the "git lfs checkout" and
"git lfs pull" commands and confirm that they replace existing files
with multiple hard links and effectively break those links.  Both of
our new tests use the assert_clean_status() test helper function to
confirm that the "git lfs checkout" and "git lfs pull" commands continue
to update the Git index entries for any Git LFS files they recreate in
the working tree.

We also expand the checks performed by the "checkout: conflicts" test
in our t/t-checkout.sh test script to check that symbolic links as well
as hard links are broken by our changes to the SmudgeToFile() method.
We are able to use this test for this purpose because it runs the
"git lfs checkout" command with the --to option, which means the
Run() method of the singleCheckout structure is not used and the
RunToPath() method is called directly.  In turn, that implies that
the DecodePointerFromBlob() function is never invoked, so the command
does not simply detect the symbolic link in that function and therefore
skip making a call to the SmudgeToFile() method, as occurs in our
"checkout: skip file symlink conflicts" and "pull: skip file symlink
conflicts" tests.  Instead, the RunToPath() method calls the
SmudgeToFile() method, which then removes the symbolic link and
creates a new file in its place.  Hence we can use this test to confirm
that our changes are effective in breaking symbolic links as well as
hard links.

And third, our new approach means we can eliminate two calls to the
"os" package's Chmod() function, which were added to the SmudgeToFile()
method in commit 686bda3 of PR #3120
in order to handle pointer files to which our "lockable" Git attribute
applies, but which the user has not yet locked, and so the pointer files
have read-only permissions we want to retain while also replacing the
file's contents with the corresponding Git LFS object data.

We do not need to call the Chmod() function before invoking the
Remove() function, because that function should be able to delete any
existing file, even one with read-only permissions, so long as the
parent directory permits changes to its list of entries.

Note that our previous implementation might succeed even if the
parent directory did not allow changes to its list of entries, and
our new implementation will not.  This does imply a partial change
in the behaviour of the Git LFS client when directories in the
working tree are themselves marked read-only.  However, neither our
old or new implementations could succeed in creating new files within
such directories.  Moreover, we expect Git working trees to normally
have read-write directory permissions, since many regular Git commands
will not function otherwise.  We therefore consider the altered
behaviour of the Git LFS client to be an acceptable change given
that it will remediate several security concerns.

We also do not need to call the Chmod() function at the end of the
SmudgeToFile() method, because we instead pass the file permissions
we want directly to the OpenFile() function.

In the case where an existing file is found, prior to our deletion of
that file, we read its permissions with the Lstat() function of the
"os" package, and then pass those permissions to the OpenFile()
function.  If a symbolic link or some other type of directory entry
is found, though, we ignore its permissions and use a default setting
of 0666 instead.  (On Unix systems, the current "umask" setting will
then be applied to whatever permissions we pass to the OpenFile()
function.)

While the use of a default permissions mode of 0666 matches that used
by the Create() function of the "os" package, and so aligns with the
legacy behaviour of the Git LFS client, this is not actually the ideal
implementation.  Rather, we should respect the mode defined for the
file in Git, which may have the executable mode set.  For now, though,
we leave this as improvement for a future PR, and just include a
comment to remind us of this oversight in our implementation.

Finally, because the "git lfs checkout" command will now attempt to
remove and replace the file or other directory entry it finds at the
path supplied with the --to option, we update our git-lfs-checkout(1)
manual page to reflect this new behaviour.
chrisd8088 added a commit that referenced this pull request Oct 16, 2025
Our "git lfs checkout" and "git lfs pull" commands retrieve a list of
Git LFS pointer files from the ScanLFSFiles() method of the GitScanner
structure type in our "lfs" package, and for each file, invoke the Run()
method of the singleCheckout structure type in our "commands" package.

For a given Git LFS pointer file, the Run() method determines whether
or not to write the contents of the object referenced by the pointer
into a file in the working tree at the appropriate path.

Because the user may execute the "git lfs checkout" and "git lfs pull"
commands from any location within a Git repository, the Run() method
tries to convert the file path of pointer, which is always relative
to the root of the repository, into a path relative to the current
working directory.  To do this, it calls the Convert() method of the
repoToCurrentPathConverter structure type in our "lfs" package, which
first prepends the absolute path to the root of the current working
tree, and then generates a relative path to that location from the
current working directory.

The repoToCurrentPathConverter structure and its methods were refactored
in commit 68efd05 of PR #1771 from the
original ConvertRepoFilesRelativeToCwd() function.  That function was
added in commit 760c7d7 of PR #527,
the same PR which introduced the "git lfs checkout" and "git lfs pull"
commands.

After calling the Convert() method to generate a path relative to the
current working directory, the Run() method passes that path to
several other functions and methods, while also using the original
input path (the one relative to the root of the repository) in other
function calls and error messages.

Because the Convert() method assumes that a current working tree is
defined (and that the current working directory is within this tree),
it will return invalid paths when these conditions are not true, such
as when the user is working in a bare repository.  In a prior commit
we therefore added a check to the Run() method so that it will not
execute the Convert() method when the no working tree is defined, which
resolved a bug whereby under unusual conditions the "git lfs checkout"
and "git lfs pull" commands could write to a file outside a bare
repository.  (In another prior commit we then also updated the
"git lfs checkout" command so that it will exit immediately when run
in a bare repository.)

The Run() method now checks the state of a "hasWorkTree" element in the
singleCheckout structure and returns without taking further action if
the element's value is "false".  When we initialize a new singleCheckout
structure in the newSingleCheckout() function of our "commands" package,
we set the value of the "hasWorkTree" element to "true" only if the
the LocalWorkingDir() method of the Configuration structure type from
our "config" package returns a non-empty path.

The LocalWorkingDir() method returns the absolute path to the root of
the current working tree, or an empty path if no working tree is defined,
as determined by the GitAndRootDirs() function in our "git" package.
The GitAndRootDirs() function runs the "git rev-parse" command with the
--show-toplevel option, and then interprets that command's output and
exit code so that if no working tree is defined, an empty path is
returned instead of a path to the work tree's root directory.

If a working tree exists and so the "hasWorkTree" element is "true",
the Run() method will proceed to invoke the Convert() method and then
pass the resultant path, which is relative to the current working
directory, to the DecodePointerFromFile() function from our "lfs"
package, and then to the RunToPath() method of the singleCheckout
structure, which passes it to the SmudgeToFile() method of the GitFilter
structure in our "lfs" package.  The Run() method later also passes the
path to the Add() method of the gitIndexer structure in our "commands"
package, which writes the path to a "git update-index" command on its
standard input file descriptor.

In a prior commit we updated the SmudgeToFile() method so that it
always creates a new file, rather than writing Git LFS object data into
an existing file, which ensures that the method will not write through
a symbolic link which exists in the place of the final filename component
of a given Git LFS pointer's file path.

In subsequent commits we will next revise the Run() method and add new
methods for the singleCheckout structure so that we check each ancestor
component of a Git LFS pointer's file path to verify that none of the
directory components of the path are symbolic links.  If a symbolic link
is found, we will report it in a new error message log format, and the
RunToPath() method will then not be invoked, nor will the gitIndexer
structure's Add() method.

With our current design, performing these checks for symbolic links,
which must be made on each path component from the root of the current
working tree to the parent directory of a given file, is complicated
by the fact that the current working directory may be located anywhere
within the work tree.  We either have to prepend zero or more ".."
path components to reach the root of the working tree, or construct an
absolute path to the root of the tree and then prepend that path to
each Git LFS pointer's file path within the repository.

To simplify both the future implementation of our checks for symbolic
links in file paths and the overall design of the Run() method, we
first adopt the approach taken by Git, which is to change the current
working directory to the root of the working tree, if one exists, before
checking for symbolic links and creating files in the work tree:

  https://github.com/git/git/blob/v2.50.1/setup.c#L1759-L1760
  https://github.com/git/git/blob/v2.50.1/symlinks.c#L63-L193

Git runs its setup_git_directory_gently() function shortly after
starting, and when it detects that the current working directory is
within a work tree, it changes the working directory to that root of
that work tree.

Since we only need to change the working directory once, we revise the
newSingleCheckout() function so it attempts to do this if a working
tree was detected and it has therefore set the "hasWorkTree" flag to
"true".  If the Chdir() function from the "os" package in the Go
standard library returns an error, the newSingleCheckout() function
reports the error and sets the "hasWorkTree" flag to "false" so that
the Run() method will always return immediately and never try to read
or write any files.

Note that when the Chdir() function returns an error, we explicitly
do not cause the current Git LFS command to exit, because we want
the command to continue even if it is unable to read or write files
in the current working tree.  In the case of the "git lfs checkout"
command, the command may have been invoked with the --to option, in
which case it should write its output to the file specified by the
user rather than into a Git LFS file within the working tree.  In the
case of the "git lfs pull" command, the command should try to fetch
any Git LFS objects that not present in the local storage directories
even if their contents can not be written into files in the working
tree.  In either case, we do not want the newSingleCheckout() function
to cause the commands to exit prematurely, even if an error occurs.

Also note that we do not need to keep a record of the original current
working directory and avoid deleting that directory, because a change
we made in a previous commit to the DecodePointerFromFile() function
ensures that we detect whether the file path passed to the Run() method
is a directory, and if so, returns an error.  Therefore, if the user
has created a directory in place of a Git LFS file, and set that
directory as the working directory, we will not remove it when trying
to check out that file.  The "checkout: skip changed files" and
"pull: skip changed files" tests we added in a previous commit to our
t/t-checkout.sh and t/t-pull.sh test scripts include checks which
verify this behaviour by running the respective commands from within
a directory which has replaced a Git LFS file in the working tree.

Our revisions to the newSingleCheckout() function mean that the Run()
method will only proceed if a working tree is defined and the current
working directory is the root of that tree.  One key consequence of
this change is that the method no longer need to construct a path
relative to the current working directory, as it can simply use the
path provided by Git, which is stored in the "Name" element of the
WrappedPointer structure passed to the Run() method as its sole
parameter, named "p".

As a result, the Run() method can use the "Name" element of its "p"
parameter in all in the instances where it previously used the
"cwdfilepath" variable which stored the result of the call to the
Convert() method of the repoToCurrentPathConverter structure.

Further, because the Run() method was the only caller of the Convert()
method, and the singleCheckout structure's "pathConverter" element
was the only instance of a repoToCurrentPathConverter structure in our
codebase, we can now remove that structure type and all of its methods
from the "lfs" package.

We make two alterations in this commit to the initial steps performed by
the "git lfs checkout" command so that it continues to support the use
of command-line arguments that are specified as file paths relative to
the directory in which the command is run.

First, in the checkoutCommand() function we now call the rootedPaths()
function before calling the newSingleCheckout() function, since the
newSingleCheckout() function now changes the current working directory.
By calling the rootedPaths() function first, it can convert any file
path pattern arguments provided by the user that are relative to the
initial working directory into path patterns relative to the root
of the repository at a time before the newSingleCheckout() function
changes the current working directory.

In a prior commit we added checks to the initial "checkout" test in our
t/t-checkout.sh test script which run the "git lfs checkout" command in
a subdirectory of the working tree and pass relative path arguments like
".." and "../folder2/**", and then verify that the command updates the
appropriate files in the work tree.  These checks now serve to confirm
that our revisions to the operation of the "git lfs checkout" command in
this commit do not cause any regression in the command's support for
relative file path pattern arguments, regardless of the whether the
command is run in the root of the working tree or in one of its
subdirectories.

Second, if the --to option is specified, we invoke the Abs() function
from the "path/filepath" package on its argument to generate an absolute
path, which we then pass to the RunToPath() method of the singleCheckout
structure as its "path" parameter, instead of passing the original
command-line argument.  This allows the newSingleCheckout() function
to change the working directory without causing problems if the user
supplies a relative path argument with the --to option.  Otherwise,
we would have to convert the provided path from one which was relative
to the original working directory into one which was relative to the
root of the working tree, which might even point outside of the work
tree since the user is free to supply a path to any location in their
system.  Given this, using an absolute path is our simplest approach
to handling the --to option's argument.

The checks we added in a prior commit to the "checkout: conflicts" test
in our t/t-checkout.sh test script now help verify that the "git lfs
checkout" command continues to supports the use of relative paths with
the --to option and that when this option is supplied an output file is
written to the same location as before, even if the command is run in
a subdirectory of the working tree.

In addition to the foregoing, by altering the "git lfs checkout" and
"git lfs pull" commands to change the current working directory to the
root of the work tree before they begin processing any Git LFS files,
we gain one further benefit with regard to how we handle Git LFS pointer
extension programs.  If such programs are configured, we invoke them
while performing "clean" and "smudge" operations, including the "smudge"
operations initiated by the SmudgeToFile() method when it is invoked by
the "git lfs checkout" and "git lfs pull" commands.

We first introduced support for pointer extension programs in PR #486,
at which time we modelled their configuration on that of Git's own
"clean" and "smudge" filters.  In particular, Git provides filter
programs with the path to the file they are processing in place of any
"%f" specifiers in the command lines specified by the "filter.*.clean"
and "filter.*.smudge" configuration entries.  For long-running filter
programs configured using "filter.*.process" entries, Git sends the path
to each file they process as the value of a "pathname" key in the stream
of data piped to the programs, using the protocol designed for these
types of filter programs.

In all cases, the file paths provided by Git are relative to the root
of the repository, not to the user's current working directory at the time
the initial Git command was started.  Moreover, Git changes the current
working directory to the root of the working tree before invoking any
filter processes, so the file paths it passes to the processes correspond
with the files Git will read or write in the working tree.  However,
the gitattributes(5) manual page notes that files may not actually exist
at these file paths, or may have different contents than the ones Git
pipes to the filter process, and so filter programs should not attempt
to access files at these paths:

  https://github.com/git/git/blob/v2.50.1/Documentation/gitattributes.adoc?plain=1#L503-L507

The Smudge() method of the GitFilter structure in our "lfs" package is
used by both of our "git lfs smudge" and "git lfs filter-process"
commands, and is responsible for writing the contents of a Git LFS object
as a data stream to its "writer" parameter.  This output data is then
piped back to the Git process which executed the Git LFS filter command.
In such a context, the "workingfile" parameter of the Smudge() process
contains a file path provided by Git, either in place of a "%f"
command-line specifier or as the value of a "pathname" key, per the
long-running filter protocol.

As the Git documentation states, files may not exist at these file
paths, or may have different content than the filter would expect, so
our Smudge() method is careful to only use the file paths passed to it
in its "workingfile" parameter for informational and error logging
purposes.  Likewise, all the methods and functions to which the Smudge()
method passes this parameter also only use it for logging purposes,
or at least that is our intention.

One particular use of this "workingfile" parameter's value pertains to
our support for Git LFS pointer extensions.  Like Git, the Git LFS client
will pass a file path in place of a "%f" command-line specifier if one
is found in the configuration setting for a pointer extension program.
(The actual contents of the pointer file, however, will be piped to the
extension program on its standard input file descriptor.)

When our Smudge() method invokes the readLocalFile() method of the
GitFilter structure, it passes its "workingfile" parameter.  If Git
has supplied this path to a "git lfs smudge" or "git lfs filter-process"
command, the path will be relative to the root of the repository.  Should
any Git LFS pointer extensions be configured, the readLocalFile() method
will use its "workingfile" parameter to populate the "fileName" elements
of new "pipeRequest" structures, which are then passed one at a time to
the pipeExtensions() function.  That function executes the given
extension program and substitutes the "%f" specifier in the program's
configured command line with the value from the "fileName" element
of the "pipeRequest" structure.

When the Git LFS client is not run by Git as a filter program but
executed directly via the "git lfs checkout" or "git lfs pull" commands,
however, we previously did not change the current working directory
before invoking pointer extension programs.  We also substituted for
the "%f" specifier file paths that were relative to the current working
directory (unless an absolute file path was specified by the user as
the argument of the "git lfs checkout" command's --to option).

Like Git filter programs, Git LFS pointer extension programs should not
expect to access an actual file at the paths passed in place of the "%f"
command-line specifiers.  At present, though, we do not make this
explicit.

To confirm that our changes in this commit function as expected when
Git LFS pointer extension programs are configured, we update the
lfstest-caseinverterextension test utility we added in a prior commit
so that it now reports an error and exits if it does not find a ".git"
directory in its current working directory, which would imply it is not
executing within the top-level directory of a work tree.

We also update our "checkout: pointer extension" and "pull: pointer
extension" tests so they check that the paths received and logged by
the lfstest-caseinverterextension test utility are relative to the
root of the repository even if the "git lfs checkout" or "git lfs pull"
command is executed in a subdirectory within the working tree.

However, we update our "checkout: pointer extension with conflict"
test so that it checks that the paths received and logged by the
lfstest-caseinverterextension test utility are absolute paths, because
now always convert the file path argument of the "git lfs checkout"
command's --to option into an absolute path before passing it to
the RunToPath() method.  This is the only use case in which the
RunToPath() method is invoked directly and not by the Run() method,
and thus the only instance in which the file paths of the RunToPath()
method's "path" parameter does not correspond in any way with the
file path of the given Git LFS pointer file.  This exceptional
behaviour dates from the introduction of the --to option in commit
cf7f967 of PR #3296, and we will
address this issue in a subsequent PR.
hswong3i pushed a commit to alvistack/git-lfs-git-lfs that referenced this pull request Oct 18, 2025
In PR git-lfs#527 we introduced the "git lfs checkout" and "git lfs pull"
commands and added some initial tests of those commands to our
test suite, which we have subsequently expanded over time.  Before
we adjust how these commands check and create files, we want to
further revise and expand their test suites to validate a broader
range of conditions.

As a first step, we reformat the initial "checkout" and "pull" tests
in the t/t-checkout.sh and t/t-pull.sh test scripts, specifically the
blocks where these tests perform checks after changing the current
working directory.

In the case of the "checkout" test in the t/t-checkout.sh test script,
we use the "pushd" and "popd" shell built-ins to change the current
working directory and then reverse that change.  However, the
intervening commands are not indented, so we do that now to bring the
formatting of this test in line with many of our other tests which
also use these shell built-ins.

In order to improve the consistency between our tests, we then update
the "pull" test in the t/t-pull.sh test script to also use the "pushd"
and "popd" shell built-ins around the "git lfs pull" commands we
want to run in a subdirectory of the test repository's working tree.

We also take the opportunity to remove several unnecessary ls(1) commands
which are left over from development of the tests.
hswong3i pushed a commit to alvistack/git-lfs-git-lfs that referenced this pull request Oct 18, 2025
In PR git-lfs#527 we introduced the "git lfs checkout" and "git lfs pull"
commands and added some initial tests of those commands to our test
suite, which we have subsequently expanded over time.  Before we adjust
how these commands check and creates files, we want to further revise
and expand their test suites to validate a broader range of conditions.

In the initial "checkout" test of the t/t-checkout.sh test script we
expand two sets of tests, both those we perform within a subdirectory
of the current working tree, and those we perform with various "glob"
file pattern arguments.

After changing the working directory to a subdirectory of the working
tree, at present the test suite only checks the behaviour of the
"git lfs checkout" command when passed either a single relative file
name and or the "." current directory name.  We now add similar checks
using first a bare ".." parent directory name and then using a relative
path pattern to a sibling subdirectory combined with a trailing "/**"
component, following the gitignore(5) rules we support for pattern
matching.

We also run the "git lfs checkout" command in the root of the working
tree and check that it behaves as expected when passed the name of
a subdirectory which already exists, and when that subdirectory's
name is followed by a trailing "/**" pattern component.

When the "git lfs checkout" command internally converts its file path
pattern arguments into file path patterns that are relative to the root
of the repository, rather being relative to the current working directory,
it appends a trailing "/" character if the pattern is actually just the
path to a directory (or a symbolic link to a directory).  This change is
implemented in the Convert() method of the currentToRepoPatternConverter
structure in our "lfs" package, and was added in commit
56abb71 of PR git-lfs#4556 so as to ensure
that arguments which resolve to specific directories are properly
converted into patterns that match both the directories and all of
their contents.

Note, though, when we run the "git lfs checkout" command with a "."
directory name argument while in a subdirectory of the working tree,
the internal addition of a trailing "/" character does not actually
affect the success of the command.  This is because the Convert()
of the currentToRepoPatternConverter structure first creates a path
relative to the root of the repository, which necessarily includes
the subdirectory's name as its final component.  When used as a
path pattern according to the gitignore(5) rules, then even without
a trailing "/" character the pattern will still match the subdirectory
and therefore its contents.

On the other hand, the internal additional of a trailing "/" character
does affect the success of the "git lfs checkout" command when we
run the command in a subdirectory and provide a ".." argument.  In this
case, the Convert() method first converts the path into one relative to
the root of the repository, which is simply the "." directory name, the
same as if the user had supplied a "." argument to a "git lfs checkout"
command run in the root of the working tree.

Although "." is a valid file path, when treated as a pattern according
to the gitignore(5) rules, it does not work to match a directory and
all of its contents.  To allow users to provide simple a "." argument
and have it work as expected, the Convert() method first appends the
"/" character, and then strips any leading "./" path component.  If the
result is an empty path, it is replaced with the "**" pattern component
so the final pattern matches everything in the root of the repository.

Thus our new check in the initial "checkout" test of the t/t-checkout.sh
script where we run the "git lfs checkout" command in a subdirectory and
pass a ".." argument, we validate the behaviour described above.  The
check would fail unless the command converted the ".." argument into
a "." path relative to the root of the repository, and into into a
"./" path, and then into the "**" pattern component.

In parallel with our changes to the t/t-checkout.sh test script, we
make a number of changes to the initial "pull" test of the t/t-pull.sh
test script to ensure that test performs all its checks under a common
set of conditions.  We will further enlarge this set of conditions in
subsequent commits.

First, we correct a typo in the refute_server_object() assertion call
that was added to the "pull" test in commit
7158e3b of PR git-lfs#2641.  This commit
revised the "git lfs pull" and "git lfs checkout" commands so that the
paths they passed to the "git update-index" command were relative to
the current working directory.  To confirm this new behaviour worked
as expected, the "pull" test was updated so it creates a third test
file named "dir/dir.dat", and some of the checks in the test were then
revised to reference this new file.  However, the refute_server_object()
assertion which is intended to prove that the corresponding Git LFS
object does not exist on the test remote server passes an incorrect
variable name, so we fix that now.

Because the "dir/dir.dat" file and corresponding local Git LFS object
file are not comprehensively referenced in all the checks of the
"git lfs pull" command, we add the appropriate assertions for it into
those checks.  (As well, we revise several invocations of the rm(1)
command to align with others in the same test and elsewhere.)

The same commit 7158e3b also extended
the "pull" test to run the "git lfs pull" command with its -I option
under several conditions, but without removing the local Git LFS object
files and working tree files, or checking that they have been re-created
after the "git lfs pull" command is run.  As a consequence, these checks
effectively only confirm that the command does not fail.

To rectify this limitation we delete all the relevant local files
before each of these checks, and then verify that they have been
restored by the "git lfs pull" command.  We also run the "git lfs pull"
command with a more restricted set of file path patterns to confirm that
files which do not match those patterns are not fetched from the remote
server; we then run the command again to fetch those files.  Previously
our checks did not actually test the file path filtering capability of
the command.

As well, we use a file path pattern which is relative to the root of
the repository, so that when we run the "git lfs pull" command in a
subdirectory of the current working tree and pass this pattern, our test
now ascertains that patterns specified with the -I option are correctly
matched with file paths starting from the root of the repository.
(For the moment we do not check that the "git lfs pull" command accepts
"glob" pattern components such as "**", but in a subsequent commit we
will add patterns of this type to the arguments we pass to the -I option.)

Making these changes, however, exposes another concern which would cause
the "pull: with missing object" test to fail unless we adjust it as well.
This test appears later in the same t/t-pull.sh test script, and depends
on the repository clone created by the "pull" test in the local "clone"
test directory.  (Ideally, our tests should not depend on each other in
this way, so that the failure of one test doesn't cause a series of
otherwise unrelated tests to also fail.  For the moment, though, we
defer this issue to a future PR.)

The "pull: with missing object" test was introduced in commit
68ac0f5 of PR git-lfs#2237 and checks that if
a Git LFS object is missing both locally and on the remote server, the
"git lfs pull" command should report the missing object and return a
non-zero exit code, but should retrieve all other requested Git LFS
objects.  To simulate this condition, the test removes the Git LFS object
corresponding to the "a.dat" test file in the local storage directories
and from the remote test server, and then runs the "git lfs pull"
command.

However, the test does not remove the "a.dat" file from the working
tree, and as noted above, is dependent on the state of the cloned
repository left by the initial "pull" test.  These two factors combine
to make the test vulnerable to transient failures, particularly now
that we have revised the "pull" test such that the final "git lfs pull"
commands in that test re-create all the files in the working tree,
except that we have also changed the "pull" test to drop the commit
which adds an empty file, as we explain below.

In commit d97c785 of PR git-lfs#4654 the
"pull" test was revised to commit an empty file which matches the
Git LFS file patterns, and then confirm that the "git lfs pull" command
handles that case without trying to fetch the object.  This check
was added before the final checks of the "git lfs pull" command, which
occur within a subdirectory of the working tree.  As a result, those
checks used to run with the empty file as one of the Git LFS objects,
and so did the "pull: with missing object" test.

In these instances, when "git lfs pull" runs, it finds the empty file
matches the defined Git LFS file patterns, and is considered to exist
locally by the LFSObjectExists() method of the Configuration structure
in our "config" package.  Therefore the command passes the object's
pointer data to the Run() method of the singleCheckout structure,
which invokes the DecodePointerFromFile() function in our "lfs" package.
That function returns a successful result because it detects that the
pointer refers to a zero-byte object, and so the RunToPath() method
of the singleCheckout structure is executed, and then the file's path
is passed to the Add() method of the gitIndexer structure.  That
method starts a "git update-index" command and writes the file's path
to the Git command on its standard input file descriptor.

We start the "git update-index" command with the --refresh option, so
it reviews all of its cached index entries, including the one for the
"a.dat" file.  If that file in the working tree has the same modification
timestamp as the Git index file (at least to within the same second,
assuming Git was not compiled with the USE_NSEC macro definition)
then Git considers the file to potentially be "racily clean", because
it's file size and modification timestamp are insufficient to determine
whether the file has changed since the index entry was cached.

The "git update-index" command therefore reads the contents of the
"a.dat" file in the working tree. Because the file's path matches a Git
LFS file pattern, the data is streamed to the "git-lfs-filter-process"
command, which regenerates a new object file in the local storage
directories under ".git/lfs/objects".

Unfortunately, the "pull: with missing object" test starts by removing
the local and remote copies of the "a.dat" file's Git LFS object file,
and expects that running the "git lfs pull" command will not result
in a new local copy being generated, as none can be fetched from the
remote test server.  But if the "pull" test leaves the "a.dat" file
in the working tree with an identical timestamp as the Git index file,
and has also committed the "empty.dat" file to the Git history,
then as described above, the "git lfs pull" invokes "git update-index"
with the --refresh option, which finds the "a.dat" file and re-creates
the local Git LFS object file, and so the test will fail.

Note that without the presence of an empty file in the commit history,
the "git lfs pull" command does not find any local Git LFS object files,
and so it calls the Run() method of the singleCheckout structure after
fetching the available objects from the remote server.  The Run() method
then executes the DecodePointerFromFile() function, which returns an
error because the file in the working tree is not a raw Git LFS pointer,
and so the Run() method skips calling the RunToPath() method and
also does not pass the file's path to the "git update-index" command.
In fact, the "git update-index" command will not be started at all,
as there are no files in the working tree which could be considered to
contain raw Git LFS pointer data, like the empty file is.  Since the
"git update-index" command does not run, the "git-lfs-filter-process"
command is also never invoked, and so a local Git LFS object file is
never re-created for the "a.dat" file, and the test succeeds.

For this reason, we change the "pull" test so that it removes the
"empty.dat" file from the Git commit history after performing the
appropriate check of the "git lfs pull" command's behaviour with
regard to empty files.

To further guard against a potential regression of our tests and
ensure the "pull: with missing object" test passes, we update that
test to remove the "a.dat" file from the working tree as well
as removing its Git LFS object files from both local and remote
storage.  Without the "a.dat" file in the working tree, it now becomes
impossible for the local object file to be re-created under any
circumstances.

Finally, we strengthen our check of the log message output by the
"git lfs pull" command so that we require a specific "does not exist"
message rather than just the raw OID of the missing Git LFS object.
hswong3i pushed a commit to alvistack/git-lfs-git-lfs that referenced this pull request Oct 18, 2025
In PR git-lfs#527 we introduced the "git lfs checkout" and "git lfs pull"
commands and added some initial tests of those commands to our
test suite, starting with the "checkout" test in what is now our
t/t-checkout.sh test script.  Since that test first appeared in commit
1d05552, it has validated the
behaviour of the "git lfs checkout" command with a number of
example files tracked as Git LFS objects, two of which are located
within subdirectories.

We later added a similar test of the "git lfs pull" command in commit
096b6da of the same PR, but without any
files tracked as Git LFS objects that were not at the top level of the
test repository.  We eventually expanded this test to include one such
file in commit 7158e3b of PR git-lfs#2641.

However, none of the tests in our t/t-checkout.sh or t/t-pull.sh test
scripts exercise the relevant Git LFS commands with files that are
contained within multiple levels of subdirectories.

Before we adjust how our "git lfs checkout" and "git lfs pull" commands
create subdirectories, we first revise our "checkout" and "pull" tests
to create files within multiple levels of subdirectories, and to confirm
that commands recreate the full set of subdirectories when they do not
exist.

Note that in our "pull" test in particular we now check that
the -I option accepts arguments containing "**" pattern components,
matching the checks we added to our "checkout" test in a previous commit.
hswong3i pushed a commit to alvistack/git-lfs-git-lfs that referenced this pull request Oct 18, 2025
In PR git-lfs#527 we introduced the "git lfs checkout" and "git lfs pull"
commands and added some initial tests of those commands to our
test suite, which we have subsequently expanded over time.

At present, we do not have any tests of these commands' behaviour
when they unable to create a subdirectory because a regular file
already exists with the same name.  In these cases, we expect the
commands to report an error but otherwise continue and ultimately
return a zero exit code.

This has been true since commit e909264
of PR git-lfs#570, when we revised the "git lfs checkout" command so it would
not panic if the DecodePointerFromFile() function in our "lfs" package
returned an error other than an ErrNotExist error.  In particular, the
stat(2) system call, which is invoked by the DecodePointerFromFile()
function via the Stat() function of the "os" package in the standard Go
library, will return an ENOTDIR error number on Unix systems when any of
the components of a given path prefix are not directories.

Before we adjust how the "git lfs checkout" and "git lfs pull" commands
check and create files, we add a pair of new tests which validate that
the commands make no changes when a file exists in place of a directory
which would otherwise be created by the commands.

After each time these tests run a "git lfs checkout" or "git lfs pull"
command, they also check that none of the pre-existing alterations to
the working tree have been accidentally staged in the Git index.  In the
normal case, when these commands successfully update a Git LFS file in
the working tree, they should then call the "git update-index" command to
refresh the modification timestamp Git has cached for the file.  However,
when a directory in the path between the root of the working tree and a
Git LFS file has been replaced with a file, our commands should not update
the Git index.  In order for our tests to confirm this is the case they
call a new assert_clean_index() test helper function which runs a
"git diff-index --cached HEAD" command to check that no unexpected
changes have been staged in the index.

When our new tests run on Unix systems, we expect the "stat" system call
to appear in the error messages output by the "git lfs checkout" and
"git lfs pull" commands, along with a file path relative to the current
working directory and a generic "Checkout error" message.  This log
message is reported by the Run() method of the singleCheckout structure
in our "commands" package when the DecodePointerFromFile() function
returns an error that the "os" package's IsNotExist() function considers
not equivalent to an ErrNotExist error.  (Note that in subsequent commits
we will adjust the text of the log message and change the reported file
path to be relative to the root of the repository.)

On Windows, our new tests expect a different error message, however,
because under the same test conditions the Stat() function of the "os"
package does return an error that the IsNotExist() function considers
equivalent to an ErrNotExist error.  As a result, the Run() method of
our singleCheckout structure handles the errors differently, and proceeds
to call the RunToPath() method of the same structure, which invokes the
SmudgeToFile() method of the GitFilter structure in our "lfs" package.
That method performs another Stat() call to check the size and
permissions mode of any extant file at the given path, but ignores any
errors which might be returned.

Next, the SmudgeToFile() method runs the Create() function from the
"os" package to try to create or truncate a file at the provided path.
When an ancestor in the path is not a directory but a file this function
returns an error, which the SmudgeToFile() method then returns wrapped
with a "could not create working directory file" message.  Finally, the
Run() method of the singleCheckout structure reports this error message
along with its own "could not check out" message and a file path
relative to the root of the repository.  Therefore these are the
messages and file paths our new tests check for on Windows.

The Stat() and Lstat() functions of the "os" package share a common
internal implementation on Windows, and the details of this internal
stat() function and the "syscall" package of the Go standard library
explain why, given our test conditions, the Stat() function returns
an error equivalent to an ErrNotExist error on Windows but not on
Unix systems.

The internal implementation of the Stat() and Lstat() functions on Windows
invokes the CreateFileW() Windows API function with the OPEN_EXISTING
flag, and that system call returns an ERROR_FILE_NOT_FOUND error number
when no file exists at the given path.  The "syscall" package in the Go
standard library then maps this error number to an ErrNotExist error,
unlike how it handles the ENOTDIR error number on Unix systems:

  https://github.com/golang/go/blob/go1.24.4/src/os/stat_windows.go#L66-L71
  https://github.com/golang/go/blob/go1.24.4/src/os/stat_windows.go#L80-L85
  https://github.com/golang/go/blob/go1.24.4/src/syscall/syscall_windows.go#L182-L186
  https://github.com/golang/go/blob/go1.24.4/src/syscall/syscall_unix.go#L126-L127
  https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea#parameters
hswong3i pushed a commit to alvistack/git-lfs-git-lfs that referenced this pull request Oct 18, 2025
In PR git-lfs#527 we introduced the "git lfs checkout" and "git lfs pull"
commands and added some initial tests of those commands to our
test suite, which we have subsequently expanded over time.

Since that PR, these commands have consistently used the
DecodePointerFromFile() function in our "lfs" package to check whether
they should replace a file in the working tree with the contents of
a Git LFS object.  This function checks whether a file exists at a
specific location, and if it does, tries to parse the file's content as
a Git LFS pointer.

If no file is found, the object's data will be written to a new file
when the command calls the SmudgeToFile() method of the GitFilter
structure in the same "lfs" package.  Otherwise, the existing file will
only be overwritten with the object's data if the current file contents
are a valid Git LFS pointer to the given object.  Under other conditions,
such as when files have altered content or have been replaced by
directories, the commands should make no changes to the working tree.

The "checkout" and "pull" tests in our t/t-checkout.sh and t/t-pull.sh
test scripts, respectively, confirm that the commands will write new
files with the expected content when there are no files at the
corresponding locations in the working tree, and the "pull" test
also checks that no changes are made when a file has been replaced
with an empty one.

However, we do not have any tests which more explicitly test that
our "git lfs checkout" and "git lfs pull" commands do not alter files
that have been modified or replaced in the working tree.

Before we adjust how these commands check and create files, we add a
pair of new tests which validate that the commands make no changes when
a file has new content or has been replaced with a directory, including
when the commands are run from within such a directory.  Our tests also
use the assert_clean_index() test helper function we introduced in a
previous commit to confirm that the commands do not add the paths of
the changed files to the Git index.

By changing the current working directory to be a directory that has
replaced a Git LFS file, our tests verify that the "git lfs checkout"
and "git lfs pull" commands will not remove the directory within which
the user ran the commands.  While this is not especially significant
at the moment, it will become more so in a subsequent commit when
we revise our commands to change their current working directory to
the root of the work tree before writing any files.
hswong3i pushed a commit to alvistack/git-lfs-git-lfs that referenced this pull request Oct 18, 2025
Our "git lfs checkout" and "git lfs pull" commands, at present,
follow any extant symbolic links when they populate the current working
tree with files containing the content of Git LFS objects, even if
the symbolic links point to locations outside of the working tree.
This vulnerability has been assigned the identifier CVE-2025-26625.

In a previous commit we partially addressed this vulnerability by
adjusting the DecodePointerFromBlob() function in our "lfs" package to
check whether an irregular file or other directory entry exists at the
location where the commands intend to create or update a file.

While this change handles cases where a symbolic link already exists
the working tree before we try to create or update a file at the same
location, it does not entirely prevent TOCTOU (time-of-check/time-of-use)
races where a symbolic link might be created immediately after we check
for its existence and before we attempt to create or open a file.

One reason is that the "git lfs checkout" and "git lfs pull" commands
use the Create() function from the Go standard library's "os" package
to create or open the files they intend to populate with the contents
of Git LFS objects.  This function follows symbolic links when
determining whether it should create a new file or truncate an existing
one.  If the last segment of the path passed to the function is a
symbolic link, the link will be dereferenced, and a new file will be
created at the link's target path or, if a file already exists at that
target path, then that file will be opened and truncated.

Further, because the Create() function opens and truncates any existing
file it finds, if that file is hard-linked to one or more other
paths, then once the file is closed the new content our commands have
written into it will be visible through all of those paths, regardless
of whether they reside inside or outside the Git working tree.

Our "git lfs checkout" and "git lfs pull" commands have exhibited these
behaviours since they were first implemented in PR git-lfs#527.  That PR
added a PointerSmudgeToFile() function to the "lfs" package, which was
later refactored by PR git-lfs#2687 into the SmudgeToFile() method of the
GitFilter structure in the current version of our "lfs" package.  The
original PointerSmudgeToFile() function made use of the "os" package's
Create() function to create a new file or truncate an existing one,
and the contemporary SmudgeToFile() method follows suit.

For performance and compatibility reasons, Git does not try to
completely eliminate all TOCTOU races involving symbolic links, and
for similar reasons we do not expect to prevent every possible race
which might allow the Git LFS client to unintentionally write through
a symbolic link.  We do, though, intend to limit the chances of this
occurring as far as we reasonably can.

Therefore, to address the problems with symbolic and hard links described
above, we revise the SmudgeToFile() method so that it first removes any
existing file at the path it is given, and if that succeeds, then attempts
to atomically create a new file, reporting an error if that cannot be done
because a file or other directory entry already exists at the same path.

Specifically, we use the OpenFile() function from the "os" package
instead of the Create() function, and we pass both the O_CREATE and
O_EXCL flags to guarantee that the function either creates a new file
or returns an error.  Before calling OpenFile() we first call the
"os" package's Remove() function and report an error if it fails for
any reason other than that there is no file found at the given path.

This approach mirrors that taken by Git when it updates files in the
working tree.  In particular, when the "git checkout" command is
asked to update a specific pathspec (e.g., with a command such as
"git checkout -- file.txt"), the checkout_entry_ca() function first
calls the unlink(2) system call, and then the create_file() function
invokes the open(2) system call with the O_CREATE and O_EXCL flags:

  https://github.com/git/git/blob/cb96e1697ad6e54d11fc920c95f82977f8e438f8/entry.c#L552-L578
  https://github.com/git/git/blob/cb96e1697ad6e54d11fc920c95f82977f8e438f8/entry.c#L88-L89

Note that Git is actually more aggressive than the Git LFS client
in how it handles conflicting content when checking out specific
paths.  For instance, if it finds a directory in place of a file it
intends to write, its remove_subtree() function will be used to try
to recursively remove the directory and all of its contents.

By constrast, while our SmudgeToFile() method will now remove existing
files (whether regular or irregular), symbolic links, and empty
directories which conflict with the file it intends to create, the
function will will not remove non-empty directories.

Moreover, the SmudgeToFile() method will only take this action if one
of these types of directory entries has been created in the brief
time interval since the DecodePointerFromBlob() function was called,
since we use that function to determine whether to proceed to call
the SmudgeToFile() method.

The sole caller of the SmudgeToFile() method is the RunToPath()
method of the singleCheckout structure in our "commands" package,
which is used only by the "git lfs checkout" and "git lfs pull"
commands.  Except when "git lfs checkout" is called with a --to
option, the RunToPath() method is only called from the Run() method
of the same singleCheckout structure.  That method first invokes
the DecodePointerFromBlob() function, and proceeds to call the
SmudgeToFile() method only if no regular file was found, or if
a regular file was found and its contained a valid Git LFS pointer
whose ID matches that of the corresponding object.

For this reason, we are guaranteed that when the SmudgeToFile() method
is called, the path it is passed is either one provided by the user
with the --to option of the "git lfs checkout" command, or has just
been checked by the DecodePointerFromBlob() function.  In either case
we can be confident that it is reasonable to delete anything which now
exists at that location.  Note, too, that prior to the changes in this
commit, any regular file or file referenced by a final symbolic link
in the path would be truncated and overwritten regardless of its contents
by the SmudgeToFile() method, so removing any directory entry (except
for non-empty subdirectories) we find and creating a new file is not
substantially different in this respect.

However, there are several key advantages to our new approach.  First,
we can now be certain we will never dereference a final symbolic link
in the given path and write to the link's target.  Note, though, that
we do still traverse symbolic links when they are found in place of
directories in path segments other than the final segment.  We will
partially address this concern in a subsequent commit, with the same
caveats that apply to Git's handling of symbolic links in non-terminal
path segments.

Second, by always creating a new file we can be certain the content
we write will not be visible through hard links to an existing file.
We therefore add a pair of new tests to our t/t-checkout.sh and
t/t-pull.sh test suite which exercise the "git lfs checkout" and
"git lfs pull" commands and confirm that they replace existing files
with multiple hard links and effectively break those links.  Both of
our new tests use the assert_clean_status() test helper function to
confirm that the "git lfs checkout" and "git lfs pull" commands continue
to update the Git index entries for any Git LFS files they recreate in
the working tree.

We also expand the checks performed by the "checkout: conflicts" test
in our t/t-checkout.sh test script to check that symbolic links as well
as hard links are broken by our changes to the SmudgeToFile() method.
We are able to use this test for this purpose because it runs the
"git lfs checkout" command with the --to option, which means the
Run() method of the singleCheckout structure is not used and the
RunToPath() method is called directly.  In turn, that implies that
the DecodePointerFromBlob() function is never invoked, so the command
does not simply detect the symbolic link in that function and therefore
skip making a call to the SmudgeToFile() method, as occurs in our
"checkout: skip file symlink conflicts" and "pull: skip file symlink
conflicts" tests.  Instead, the RunToPath() method calls the
SmudgeToFile() method, which then removes the symbolic link and
creates a new file in its place.  Hence we can use this test to confirm
that our changes are effective in breaking symbolic links as well as
hard links.

And third, our new approach means we can eliminate two calls to the
"os" package's Chmod() function, which were added to the SmudgeToFile()
method in commit 686bda3 of PR git-lfs#3120
in order to handle pointer files to which our "lockable" Git attribute
applies, but which the user has not yet locked, and so the pointer files
have read-only permissions we want to retain while also replacing the
file's contents with the corresponding Git LFS object data.

We do not need to call the Chmod() function before invoking the
Remove() function, because that function should be able to delete any
existing file, even one with read-only permissions, so long as the
parent directory permits changes to its list of entries.

Note that our previous implementation might succeed even if the
parent directory did not allow changes to its list of entries, and
our new implementation will not.  This does imply a partial change
in the behaviour of the Git LFS client when directories in the
working tree are themselves marked read-only.  However, neither our
old or new implementations could succeed in creating new files within
such directories.  Moreover, we expect Git working trees to normally
have read-write directory permissions, since many regular Git commands
will not function otherwise.  We therefore consider the altered
behaviour of the Git LFS client to be an acceptable change given
that it will remediate several security concerns.

We also do not need to call the Chmod() function at the end of the
SmudgeToFile() method, because we instead pass the file permissions
we want directly to the OpenFile() function.

In the case where an existing file is found, prior to our deletion of
that file, we read its permissions with the Lstat() function of the
"os" package, and then pass those permissions to the OpenFile()
function.  If a symbolic link or some other type of directory entry
is found, though, we ignore its permissions and use a default setting
of 0666 instead.  (On Unix systems, the current "umask" setting will
then be applied to whatever permissions we pass to the OpenFile()
function.)

While the use of a default permissions mode of 0666 matches that used
by the Create() function of the "os" package, and so aligns with the
legacy behaviour of the Git LFS client, this is not actually the ideal
implementation.  Rather, we should respect the mode defined for the
file in Git, which may have the executable mode set.  For now, though,
we leave this as improvement for a future PR, and just include a
comment to remind us of this oversight in our implementation.

Finally, because the "git lfs checkout" command will now attempt to
remove and replace the file or other directory entry it finds at the
path supplied with the --to option, we update our git-lfs-checkout(1)
manual page to reflect this new behaviour.
hswong3i pushed a commit to alvistack/git-lfs-git-lfs that referenced this pull request Oct 18, 2025
Our "git lfs checkout" and "git lfs pull" commands retrieve a list of
Git LFS pointer files from the ScanLFSFiles() method of the GitScanner
structure type in our "lfs" package, and for each file, invoke the Run()
method of the singleCheckout structure type in our "commands" package.

For a given Git LFS pointer file, the Run() method determines whether
or not to write the contents of the object referenced by the pointer
into a file in the working tree at the appropriate path.

Because the user may execute the "git lfs checkout" and "git lfs pull"
commands from any location within a Git repository, the Run() method
tries to convert the file path of pointer, which is always relative
to the root of the repository, into a path relative to the current
working directory.  To do this, it calls the Convert() method of the
repoToCurrentPathConverter structure type in our "lfs" package, which
first prepends the absolute path to the root of the current working
tree, and then generates a relative path to that location from the
current working directory.

The repoToCurrentPathConverter structure and its methods were refactored
in commit 68efd05 of PR git-lfs#1771 from the
original ConvertRepoFilesRelativeToCwd() function.  That function was
added in commit 760c7d7 of PR git-lfs#527,
the same PR which introduced the "git lfs checkout" and "git lfs pull"
commands.

After calling the Convert() method to generate a path relative to the
current working directory, the Run() method passes that path to
several other functions and methods, while also using the original
input path (the one relative to the root of the repository) in other
function calls and error messages.

Because the Convert() method assumes that a current working tree is
defined (and that the current working directory is within this tree),
it will return invalid paths when these conditions are not true, such
as when the user is working in a bare repository.  In a prior commit
we therefore added a check to the Run() method so that it will not
execute the Convert() method when the no working tree is defined, which
resolved a bug whereby under unusual conditions the "git lfs checkout"
and "git lfs pull" commands could write to a file outside a bare
repository.  (In another prior commit we then also updated the
"git lfs checkout" command so that it will exit immediately when run
in a bare repository.)

The Run() method now checks the state of a "hasWorkTree" element in the
singleCheckout structure and returns without taking further action if
the element's value is "false".  When we initialize a new singleCheckout
structure in the newSingleCheckout() function of our "commands" package,
we set the value of the "hasWorkTree" element to "true" only if the
the LocalWorkingDir() method of the Configuration structure type from
our "config" package returns a non-empty path.

The LocalWorkingDir() method returns the absolute path to the root of
the current working tree, or an empty path if no working tree is defined,
as determined by the GitAndRootDirs() function in our "git" package.
The GitAndRootDirs() function runs the "git rev-parse" command with the
--show-toplevel option, and then interprets that command's output and
exit code so that if no working tree is defined, an empty path is
returned instead of a path to the work tree's root directory.

If a working tree exists and so the "hasWorkTree" element is "true",
the Run() method will proceed to invoke the Convert() method and then
pass the resultant path, which is relative to the current working
directory, to the DecodePointerFromFile() function from our "lfs"
package, and then to the RunToPath() method of the singleCheckout
structure, which passes it to the SmudgeToFile() method of the GitFilter
structure in our "lfs" package.  The Run() method later also passes the
path to the Add() method of the gitIndexer structure in our "commands"
package, which writes the path to a "git update-index" command on its
standard input file descriptor.

In a prior commit we updated the SmudgeToFile() method so that it
always creates a new file, rather than writing Git LFS object data into
an existing file, which ensures that the method will not write through
a symbolic link which exists in the place of the final filename component
of a given Git LFS pointer's file path.

In subsequent commits we will next revise the Run() method and add new
methods for the singleCheckout structure so that we check each ancestor
component of a Git LFS pointer's file path to verify that none of the
directory components of the path are symbolic links.  If a symbolic link
is found, we will report it in a new error message log format, and the
RunToPath() method will then not be invoked, nor will the gitIndexer
structure's Add() method.

With our current design, performing these checks for symbolic links,
which must be made on each path component from the root of the current
working tree to the parent directory of a given file, is complicated
by the fact that the current working directory may be located anywhere
within the work tree.  We either have to prepend zero or more ".."
path components to reach the root of the working tree, or construct an
absolute path to the root of the tree and then prepend that path to
each Git LFS pointer's file path within the repository.

To simplify both the future implementation of our checks for symbolic
links in file paths and the overall design of the Run() method, we
first adopt the approach taken by Git, which is to change the current
working directory to the root of the working tree, if one exists, before
checking for symbolic links and creating files in the work tree:

  https://github.com/git/git/blob/v2.50.1/setup.c#L1759-L1760
  https://github.com/git/git/blob/v2.50.1/symlinks.c#L63-L193

Git runs its setup_git_directory_gently() function shortly after
starting, and when it detects that the current working directory is
within a work tree, it changes the working directory to that root of
that work tree.

Since we only need to change the working directory once, we revise the
newSingleCheckout() function so it attempts to do this if a working
tree was detected and it has therefore set the "hasWorkTree" flag to
"true".  If the Chdir() function from the "os" package in the Go
standard library returns an error, the newSingleCheckout() function
reports the error and sets the "hasWorkTree" flag to "false" so that
the Run() method will always return immediately and never try to read
or write any files.

Note that when the Chdir() function returns an error, we explicitly
do not cause the current Git LFS command to exit, because we want
the command to continue even if it is unable to read or write files
in the current working tree.  In the case of the "git lfs checkout"
command, the command may have been invoked with the --to option, in
which case it should write its output to the file specified by the
user rather than into a Git LFS file within the working tree.  In the
case of the "git lfs pull" command, the command should try to fetch
any Git LFS objects that not present in the local storage directories
even if their contents can not be written into files in the working
tree.  In either case, we do not want the newSingleCheckout() function
to cause the commands to exit prematurely, even if an error occurs.

Also note that we do not need to keep a record of the original current
working directory and avoid deleting that directory, because a change
we made in a previous commit to the DecodePointerFromFile() function
ensures that we detect whether the file path passed to the Run() method
is a directory, and if so, returns an error.  Therefore, if the user
has created a directory in place of a Git LFS file, and set that
directory as the working directory, we will not remove it when trying
to check out that file.  The "checkout: skip changed files" and
"pull: skip changed files" tests we added in a previous commit to our
t/t-checkout.sh and t/t-pull.sh test scripts include checks which
verify this behaviour by running the respective commands from within
a directory which has replaced a Git LFS file in the working tree.

Our revisions to the newSingleCheckout() function mean that the Run()
method will only proceed if a working tree is defined and the current
working directory is the root of that tree.  One key consequence of
this change is that the method no longer need to construct a path
relative to the current working directory, as it can simply use the
path provided by Git, which is stored in the "Name" element of the
WrappedPointer structure passed to the Run() method as its sole
parameter, named "p".

As a result, the Run() method can use the "Name" element of its "p"
parameter in all in the instances where it previously used the
"cwdfilepath" variable which stored the result of the call to the
Convert() method of the repoToCurrentPathConverter structure.

Further, because the Run() method was the only caller of the Convert()
method, and the singleCheckout structure's "pathConverter" element
was the only instance of a repoToCurrentPathConverter structure in our
codebase, we can now remove that structure type and all of its methods
from the "lfs" package.

We make two alterations in this commit to the initial steps performed by
the "git lfs checkout" command so that it continues to support the use
of command-line arguments that are specified as file paths relative to
the directory in which the command is run.

First, in the checkoutCommand() function we now call the rootedPaths()
function before calling the newSingleCheckout() function, since the
newSingleCheckout() function now changes the current working directory.
By calling the rootedPaths() function first, it can convert any file
path pattern arguments provided by the user that are relative to the
initial working directory into path patterns relative to the root
of the repository at a time before the newSingleCheckout() function
changes the current working directory.

In a prior commit we added checks to the initial "checkout" test in our
t/t-checkout.sh test script which run the "git lfs checkout" command in
a subdirectory of the working tree and pass relative path arguments like
".." and "../folder2/**", and then verify that the command updates the
appropriate files in the work tree.  These checks now serve to confirm
that our revisions to the operation of the "git lfs checkout" command in
this commit do not cause any regression in the command's support for
relative file path pattern arguments, regardless of the whether the
command is run in the root of the working tree or in one of its
subdirectories.

Second, if the --to option is specified, we invoke the Abs() function
from the "path/filepath" package on its argument to generate an absolute
path, which we then pass to the RunToPath() method of the singleCheckout
structure as its "path" parameter, instead of passing the original
command-line argument.  This allows the newSingleCheckout() function
to change the working directory without causing problems if the user
supplies a relative path argument with the --to option.  Otherwise,
we would have to convert the provided path from one which was relative
to the original working directory into one which was relative to the
root of the working tree, which might even point outside of the work
tree since the user is free to supply a path to any location in their
system.  Given this, using an absolute path is our simplest approach
to handling the --to option's argument.

The checks we added in a prior commit to the "checkout: conflicts" test
in our t/t-checkout.sh test script now help verify that the "git lfs
checkout" command continues to supports the use of relative paths with
the --to option and that when this option is supplied an output file is
written to the same location as before, even if the command is run in
a subdirectory of the working tree.

In addition to the foregoing, by altering the "git lfs checkout" and
"git lfs pull" commands to change the current working directory to the
root of the work tree before they begin processing any Git LFS files,
we gain one further benefit with regard to how we handle Git LFS pointer
extension programs.  If such programs are configured, we invoke them
while performing "clean" and "smudge" operations, including the "smudge"
operations initiated by the SmudgeToFile() method when it is invoked by
the "git lfs checkout" and "git lfs pull" commands.

We first introduced support for pointer extension programs in PR git-lfs#486,
at which time we modelled their configuration on that of Git's own
"clean" and "smudge" filters.  In particular, Git provides filter
programs with the path to the file they are processing in place of any
"%f" specifiers in the command lines specified by the "filter.*.clean"
and "filter.*.smudge" configuration entries.  For long-running filter
programs configured using "filter.*.process" entries, Git sends the path
to each file they process as the value of a "pathname" key in the stream
of data piped to the programs, using the protocol designed for these
types of filter programs.

In all cases, the file paths provided by Git are relative to the root
of the repository, not to the user's current working directory at the time
the initial Git command was started.  Moreover, Git changes the current
working directory to the root of the working tree before invoking any
filter processes, so the file paths it passes to the processes correspond
with the files Git will read or write in the working tree.  However,
the gitattributes(5) manual page notes that files may not actually exist
at these file paths, or may have different contents than the ones Git
pipes to the filter process, and so filter programs should not attempt
to access files at these paths:

  https://github.com/git/git/blob/v2.50.1/Documentation/gitattributes.adoc?plain=1#L503-L507

The Smudge() method of the GitFilter structure in our "lfs" package is
used by both of our "git lfs smudge" and "git lfs filter-process"
commands, and is responsible for writing the contents of a Git LFS object
as a data stream to its "writer" parameter.  This output data is then
piped back to the Git process which executed the Git LFS filter command.
In such a context, the "workingfile" parameter of the Smudge() process
contains a file path provided by Git, either in place of a "%f"
command-line specifier or as the value of a "pathname" key, per the
long-running filter protocol.

As the Git documentation states, files may not exist at these file
paths, or may have different content than the filter would expect, so
our Smudge() method is careful to only use the file paths passed to it
in its "workingfile" parameter for informational and error logging
purposes.  Likewise, all the methods and functions to which the Smudge()
method passes this parameter also only use it for logging purposes,
or at least that is our intention.

One particular use of this "workingfile" parameter's value pertains to
our support for Git LFS pointer extensions.  Like Git, the Git LFS client
will pass a file path in place of a "%f" command-line specifier if one
is found in the configuration setting for a pointer extension program.
(The actual contents of the pointer file, however, will be piped to the
extension program on its standard input file descriptor.)

When our Smudge() method invokes the readLocalFile() method of the
GitFilter structure, it passes its "workingfile" parameter.  If Git
has supplied this path to a "git lfs smudge" or "git lfs filter-process"
command, the path will be relative to the root of the repository.  Should
any Git LFS pointer extensions be configured, the readLocalFile() method
will use its "workingfile" parameter to populate the "fileName" elements
of new "pipeRequest" structures, which are then passed one at a time to
the pipeExtensions() function.  That function executes the given
extension program and substitutes the "%f" specifier in the program's
configured command line with the value from the "fileName" element
of the "pipeRequest" structure.

When the Git LFS client is not run by Git as a filter program but
executed directly via the "git lfs checkout" or "git lfs pull" commands,
however, we previously did not change the current working directory
before invoking pointer extension programs.  We also substituted for
the "%f" specifier file paths that were relative to the current working
directory (unless an absolute file path was specified by the user as
the argument of the "git lfs checkout" command's --to option).

Like Git filter programs, Git LFS pointer extension programs should not
expect to access an actual file at the paths passed in place of the "%f"
command-line specifiers.  At present, though, we do not make this
explicit.

To confirm that our changes in this commit function as expected when
Git LFS pointer extension programs are configured, we update the
lfstest-caseinverterextension test utility we added in a prior commit
so that it now reports an error and exits if it does not find a ".git"
directory in its current working directory, which would imply it is not
executing within the top-level directory of a work tree.

We also update our "checkout: pointer extension" and "pull: pointer
extension" tests so they check that the paths received and logged by
the lfstest-caseinverterextension test utility are relative to the
root of the repository even if the "git lfs checkout" or "git lfs pull"
command is executed in a subdirectory within the working tree.

However, we update our "checkout: pointer extension with conflict"
test so that it checks that the paths received and logged by the
lfstest-caseinverterextension test utility are absolute paths, because
now always convert the file path argument of the "git lfs checkout"
command's --to option into an absolute path before passing it to
the RunToPath() method.  This is the only use case in which the
RunToPath() method is invoked directly and not by the Run() method,
and thus the only instance in which the file paths of the RunToPath()
method's "path" parameter does not correspond in any way with the
file path of the given Git LFS pointer file.  This exceptional
behaviour dates from the introduction of the --to option in commit
cf7f967 of PR git-lfs#3296, and we will
address this issue in a subsequent PR.
chrisd8088 added a commit to chrisd8088/git-lfs that referenced this pull request Nov 1, 2025
Since the "git lfs checkout" command was introduced in PR git-lfs#527, it has
accepted zero or more command-line arguments which are expected to be
file path patterns.  If any such arguments are supplied, they are used
to filter the set of Git LFS files that will be processed by the command.

When the command is run in a subdirectory within a repository's working
tree, we expect that the user will provide path patterns which are
expressed relative to their current working directory.  However, as
noted in commit 760c7d7 of PR git-lfs#527,
we need to convert these path patterns so they are relative to the
root of the repository before we can use them to filter the file list
returned by Git.  (This list is either generated by a "git ls-files"
command, if the installed version of Git is 2.42.0 or higher, or by
a "git ls-tree" command.)

In PR git-lfs#1771 we refactored the logic we use to perform these relative
path conversions and created the rootedPath() helper function in our
"commands" package.  This function iterated over the set of
command-line "pathspec" arguments and converted each using the
Convert() method of the currentToRepoPathConverter structure in our
"lfs" package.

Later, in commit 56abb71 of PR git-lfs#4556,
we revised the rootedPaths() function to instead call the Convert()
method of the new currentToRepoPatternConverter structure in our "lfs"
package.  This structure's conversion method first calls the Convert()
method of a currentToRepoPathConverter structure, but then checks
whether the result references a directory or not, and if so, adjusts
the returned value to conform to Git's pattern-matching rules, as
defined in the gitignore(5) manual page.

While this treatment of path pattern arguments is correct for most use
cases, it is not valid when the "git lfs checkout" command's --to option
is specified by the user, but the rootedPaths() function is nevertheless
used to process the command's final file path argument in this case.

In a subsequent commit in this PR we will address this problem, but
first we rename the rootedPaths() function to rootedPathPatterns()
and make the same change to the equivalent names of the local variables,
so as to clearly identify the purpose of the function and its expected
input and output.
chrisd8088 added a commit to chrisd8088/git-lfs that referenced this pull request Nov 1, 2025
Since the "git lfs checkout" command was introduced in PR git-lfs#527, it has
accepted zero or more command-line arguments which are expected to be
file path patterns.  If any such arguments are supplied, they are used
to filter the set of Git LFS files that will be processed by the command.

When the command is run in a subdirectory within a repository's working
tree, we expect that the user will provide path patterns which are
expressed relative to their current working directory.  However, as
noted in commit 760c7d7 of PR git-lfs#527,
we need to convert these path patterns so they are relative to the
root of the repository before we can use them to filter the file list
returned by Git.  (This list is either generated by a "git ls-files"
command, if the installed version of Git is 2.42.0 or higher, or by
a "git ls-tree" command.)

In PR git-lfs#1771 we refactored the logic we use to perform these relative
path conversions and created the rootedPath() helper function in our
"commands" package.  This function iterated over the set of
command-line "pathspec" arguments and converted each using the
Convert() method of the currentToRepoPathConverter structure in our
"lfs" package.

Later, in commit 56abb71 of PR git-lfs#4556,
we revised the rootedPaths() function to instead call the Convert()
method of the new currentToRepoPatternConverter structure in our "lfs"
package.  This structure's conversion method first calls the Convert()
method of a currentToRepoPathConverter structure, but then checks
whether the result references a directory or not, and if so, adjusts
the returned value to conform to Git's pattern-matching rules, as
defined in the gitignore(5) manual page.

While this treatment of path pattern arguments is correct for most use
cases, it is not valid when the "git lfs checkout" command's --to option
is specified by the user, but the rootedPaths() function is nevertheless
used to process the command's final file path argument in this case.

In a subsequent commit in this PR we will address this problem, but
first we rename the rootedPaths() function to rootedPathPatterns()
and make the same change to the equivalent names of the local variables,
so as to clearly identify the purpose of the function and its expected
input and output.
chrisd8088 added a commit to chrisd8088/git-lfs that referenced this pull request Nov 2, 2025
Since the "git lfs checkout" command was introduced in PR git-lfs#527, it has
accepted zero or more command-line arguments which are expected to be
file path patterns.  If any such arguments are supplied, they are used
to filter the set of Git LFS files that will be processed by the command.

When the command is run in a subdirectory within a repository's working
tree, we expect that the user will provide path patterns which are
expressed relative to their current working directory.  However, as
noted in commit 760c7d7 of PR git-lfs#527,
we need to convert these path patterns so they are relative to the
root of the repository before we can use them to filter the file list
returned by Git.  (This list is either generated by a "git ls-files"
command, if the installed version of Git is 2.42.0 or higher, or by
a "git ls-tree" command.)

In PR git-lfs#1771 we refactored the logic we use to perform these relative
path conversions and created the rootedPath() helper function in our
"commands" package.  This function iterated over the set of
command-line "pathspec" arguments and converted each using the
Convert() method of the currentToRepoPathConverter structure in our
"lfs" package.

Later, in commit 56abb71 of PR git-lfs#4556,
we revised the rootedPaths() function to instead call the Convert()
method of the new currentToRepoPatternConverter structure in our "lfs"
package.  This structure's conversion method first calls the Convert()
method of a currentToRepoPathConverter structure, but then checks
whether the result references a directory or not, and if so, adjusts
the returned value to conform to Git's pattern-matching rules, as
defined in the gitignore(5) manual page.

While this treatment of path pattern arguments is correct for most use
cases, it is not valid when the "git lfs checkout" command's --to option
is specified by the user, but the rootedPaths() function is nevertheless
used to process the command's final file path argument in this case.

In a subsequent commit in this PR we will address this problem, but
first we rename the rootedPaths() function to rootedPathPatterns()
and make the same change to the equivalent names of the local variables,
so as to clearly identify the purpose of the function and its expected
input and output.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants