Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions doc/cli/clone.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,10 @@ If nothing changed, it does nothing and says "already up to date".
- Without `--recurse-submodules`, submodules of upstream stay empty, and
git-nested warns about it. See [Upstream submodules](../guides/submodules.md).
- If your `.gitattributes` would change files of the nested repository,
for example `*.bat text eol=crlf`, `clone` and `pull` add `-text` for
for example `*.bat text eol=crlf`, `clone` and `pull` add `-text -eol` for
these files to `.gitattributes`, in a commit of their own. So the files
stay as upstream has them, in git and in your checkout.
stay as upstream has them, in git and in your checkout. Files that
upstream's own `.gitattributes` treat the same way get no rule.
- With `--recurse-submodules`, a submodule with `update = none` in
`.gitmodules` stays a submodule, as in git.
- If upstream is empty, `clone` stops. Use [`init`](init.md) and then
Expand Down
2 changes: 1 addition & 1 deletion doc/cli/submodules.md
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ changes.
- If upstream adds a submodule at a path you use already, it is not nested.
A warning says so.
- If your `.gitattributes` would change files of a nested repository, for
example `*.bat text eol=crlf`, git-nested adds `-text` for these files to
example `*.bat text eol=crlf`, git-nested adds `-text -eol` for these files to
`.gitattributes`. So they stay as upstream has them, as in a submodule.
`update` keeps this block at the end of the file, also when upstream adds
rules there.
Expand Down
61 changes: 54 additions & 7 deletions src/git_nested/content.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from __future__ import annotations

import dataclasses
import os
import tempfile
from pathlib import Path, PurePosixPath
from typing import cast

Expand Down Expand Up @@ -210,15 +212,19 @@ def keep_upstream_bytes(git: GitRunner, flags: Flags, subdir: Path) -> None:

For a submodule, the parent's attributes do not count. For a nested
repo they do. A rule like '*.bat text eol=crlf' then shows upstream's
files as changed, or checks out LF files with CRLF. This adds '-text'
for them to .gitattributes, in a commit of its own.
files as changed, or checks out LF files with CRLF. This adds
'-text -eol' for them to .gitattributes, in a commit of its own.
Files whose attributes are the same as in upstream alone get no rule.
"""
changed = [path for path in git.check_output(['diff', '--name-only', '-z', '--', subdir]).split('\0') if path]
converted = _converted_on_checkout(git, subdir)
paths = sorted({path for path in changed if _only_attributes_differ(git, path)} | set(converted))
text = _GITATTRIBUTES.read_text(encoding='utf-8') if _GITATTRIBUTES.is_file() else ''
candidates = {path for path in changed if _only_attributes_differ(git, path)} | set(converted)
rules = set(text.splitlines(keepends=True))
paths = [path for path in _parent_changes(git, subdir, candidates) if _rule(path) not in rules]
if not paths:
return
text = _GITATTRIBUTES.read_text(encoding='utf-8') if _GITATTRIBUTES.is_file() else ''
converted = [path for path in converted if path in paths]
with _GITATTRIBUTES.open('w', encoding='utf-8', newline='\n') as f:
f.write(_with_rules(text, paths))
# Check them out again, now with upstream's bytes
Expand All @@ -234,12 +240,53 @@ def keep_upstream_bytes(git: GitRunner, flags: Flags, subdir: Path) -> None:


def _with_rules(text: str, paths: list[str]) -> str:
"""`text` of .gitattributes, with '-text' for `paths` at the end."""
"""`text` of .gitattributes, with the rules for `paths` at the end."""
if text and not text.endswith('\n'):
text += '\n'
# An older git-nested wrote only '-text'. The new rule takes its place.
old = {_rule(path).replace(' -eol', '') for path in paths}
text = ''.join(line for line in text.splitlines(keepends=True) if line not in old)
if _KEEP_BYTES_HEADER not in text:
text += _KEEP_BYTES_HEADER
return text + ''.join(f"{_attribute_pattern(path)} -text\n" for path in paths)
return text + ''.join(_rule(path) for path in paths)


def _rule(path: str) -> str:
"""The line of .gitattributes that keeps `path` as upstream has it.

Upstream's own .gitattributes win over the parent's. With 'text' there,
'-text' alone does nothing, so the rule also unsets 'eol'.
"""
return f"{_attribute_pattern(path)} -text -eol\n"


def _parent_changes(git: GitRunner, subdir: Path, paths: set[str]) -> list[str]:
"""The `paths` in subdir whose 'text' or 'eol' the parent's attributes change."""
if not paths:
return []
here = _text_and_eol(git, sorted(paths))
prefix = f'{subdir.as_posix()}/'
with tempfile.TemporaryDirectory() as tmp:
# An index with only subdir's tree, at the top: the attributes of upstream alone
env = {**os.environ, 'GIT_INDEX_FILE': str(Path(tmp) / 'index')}
tree = git.check_output(['write-tree', f'--prefix={prefix}'])
git.run(['read-tree', tree], env=env)
alone = _text_and_eol(git, [path[len(prefix) :] for path in sorted(paths)], '--cached', env=env)
return [path for path in sorted(paths) if here[path] != alone[path[len(prefix) :]]]


def _text_and_eol(
git: GitRunner, paths: list[str], *options: str, env: dict[str, str] | None = None
) -> dict[str, list[str]]:
"""{path: its 'text' and 'eol' attributes}, as `git check-attr` gives them."""
out = git.check_output(
['check-attr', '-z', '--stdin', *options, 'text', 'eol'], input=''.join(f'{path}\0' for path in paths), env=env
)
fields = out.rstrip('\0').split('\0')
found: dict[str, list[str]] = {}
for path, value in zip(fields[0::3], fields[2::3], strict=True):
found.setdefault(path, []).append(value)
return found


def _converted_on_checkout(git: GitRunner, subdir: Path) -> list[str]:
Expand All @@ -259,7 +306,7 @@ def split_keep_block(text: str) -> tuple[str, str]:
if _KEEP_BYTES_HEADER not in lines:
return text, ''
start = end = lines.index(_KEEP_BYTES_HEADER)
while end + 1 < len(lines) and lines[end + 1].rstrip().endswith(' -text'):
while end + 1 < len(lines) and lines[end + 1].rstrip().endswith((' -text', ' -text -eol')):
end += 1
return ''.join(lines[:start] + lines[end + 1 :]), ''.join(lines[start : end + 1])

Expand Down
82 changes: 82 additions & 0 deletions tests/e2e/test_attributes.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,85 @@ def test_a_file_name_with_special_characters(foo_bar_cloned):

assert '"/bar/my \\\\[x] file.bat" -text' in (foo / '.gitattributes').read_text()
assert env.run(['git', 'status', '--porcelain'], cwd=foo).output == ''


def _upstream_attributes(env, text):
bar = env.workspace / 'bar'
(bar / '.gitattributes').write_text(text)
env.run(['git', 'add', '.gitattributes'], cwd=bar)
env.run(['git', 'commit', '-qm', 'attributes'], cwd=bar)
env.run(['git', 'push', '-q'], cwd=bar)


def _as_plain_checkout(env, name):
"""`name` as a plain clone of upstream bar has it, as in a submodule. On Windows that is CRLF."""
clone = env.workspace / 'plain'
if not clone.exists():
env.run(['git', 'clone', '-q', env.upstream / 'bar', clone])
env.run(['git', 'pull', '-q'], cwd=clone)
return (clone / name).read_bytes()


def test_upstream_text_auto_does_not_take_the_parent_eol(foo_bar_cloned):
"""Upstream's own 'text' wins over '-text'. So the rule also unsets eol."""
env = foo_bar_cloned
foo = _parent_wants_crlf(env)
_upstream_attributes(env, "* text=auto\n")
_upstream_bat(env, 'plain.bat', b"echo plain\n")

cmd_git_nested(['clone', (env.upstream / 'bar').as_posix()], foo)

assert "/bar/plain.bat -text -eol" in (foo / '.gitattributes').read_text()
assert (foo / 'bar' / 'plain.bat').read_bytes() == _as_plain_checkout(env, 'plain.bat')
assert env.run(['git', 'status', '--porcelain'], cwd=foo).output == ''


def test_no_rule_when_upstream_has_the_same_attributes(foo_bar_cloned):
"""A plain checkout of upstream gives CRLF here too."""
env = foo_bar_cloned
foo = _parent_wants_crlf(env)
_upstream_attributes(env, "*.bat text eol=crlf\n")
_upstream_bat(env, 'make.bat', b"echo hi\n")

result = cmd_git_nested(['clone', (env.upstream / 'bar').as_posix()], foo)

assert "keeps" not in result.output
assert "git-nested" not in (foo / '.gitattributes').read_text()
assert (foo / 'bar' / 'make.bat').read_bytes() == _as_plain_checkout(env, 'make.bat') == b"echo hi\r\n"


def test_pull_does_not_repeat_the_rules(foo_bar_cloned):
env = foo_bar_cloned
foo = _parent_wants_crlf(env)
_upstream_attributes(env, "* text=auto\n")
_upstream_bat(env, 'plain.bat', b"echo plain\n")
cmd_git_nested(['clone', (env.upstream / 'bar').as_posix()], foo)
_upstream_bat(env, 'plain.bat', b"echo changed\n")

cmd_git_nested('pull bar', cwd=foo)

assert (foo / '.gitattributes').read_text().count("/bar/plain.bat") == 1
assert (foo / 'bar' / 'plain.bat').read_bytes() == _as_plain_checkout(env, 'plain.bat')
assert env.run(['git', 'status', '--porcelain'], cwd=foo).output == ''


def test_pull_turns_an_old_rule_into_the_new_one(foo_bar_cloned):
"""An older git-nested wrote only '-text'."""
env = foo_bar_cloned
foo = _parent_wants_crlf(env)
_upstream_attributes(env, "* text=auto\n")
_upstream_bat(env, 'plain.bat', b"echo plain\n")
cmd_git_nested(['clone', (env.upstream / 'bar').as_posix()], foo)
attributes = foo / '.gitattributes'
attributes.write_text(attributes.read_text().replace(" -text -eol", " -text"))
env.run(['git', 'commit', '-qam', 'old rule'], cwd=foo)
(foo / 'bar' / 'plain.bat').unlink()
env.run(['git', 'checkout', '--', 'bar/plain.bat'], cwd=foo)
_upstream_bat(env, 'plain.bat', b"echo changed\n")

cmd_git_nested('pull bar', cwd=foo)

rules = attributes.read_text()
assert rules.count("/bar/plain.bat") == 1
assert "/bar/plain.bat -text -eol" in rules
assert (foo / 'bar' / 'plain.bat').read_bytes() == _as_plain_checkout(env, 'plain.bat')
2 changes: 1 addition & 1 deletion tests/e2e/test_submodules_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -1445,7 +1445,7 @@ def test_the_gitattributes_block_does_not_conflict(foo_bar_cloned):

rules = (env.fork / '.gitattributes').read_text()
assert rules.index('*.bin binary') < rules.index('# git-nested')
assert rules.rstrip().endswith('/sub/make.bat -text')
assert rules.rstrip().endswith('/sub/make.bat -text -eol')
assert env.run(['git', 'status', '--porcelain'], cwd=env.fork).output == ''


Expand Down
Loading