git.day/10 • See all at git.day
When providing paths to
git add, the path is relative to the current directory, or absolute prefixed with
/ like any other command that takes a path. There are additional forms of paths to provide to various Git commands, such as git-add, one of which is to prefix the path with a colon.
Using a colon at the beginning of a path makes the path relative to the root of the repo, regardless of what the current directory is.
There's two great uses of this:
- Adding a specific path to a known file when cd'd deep into a repo. For example, when working on a Go repo and cd'd into a package deep in the hierarchy, but needing to add a change to go.mod in the module root made by
go get, one can
git add :/go.modrather than needing the right number of
- Adding all files in the working copy.
git add .would only add the current directory which may be a subdirectory of the repository if that is the current directory, but
git add :/would add all.
Git commands that take a path call the path a ‘pathspec’. A pathspec has additional capability over a regular path other commands may take on the command line — this colon behaviour being one of them, and the colon opens additional behaviour under it, such as
/ for the root of the repo.
/ is actually shorthand for
git add :(top)go.mod is equivalent to
git add :/go.mod. Here are my favourite pathspec-colon behaviours:
:(top)for adding paths from the root of the repo
:(literal)for adding paths that include glob characters,
?, literally rather than as wildcards
:(icase)for case insensitive path matching.
This makes pathspec more powerful for matching files, and easier to use in repositories with deep hierarchy.