Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Detect the original file newline style and apply it to rendered template #1159

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitattributes
@@ -0,0 +1,2 @@
* text=auto
*crlf.txt text eol=crlf
1 change: 1 addition & 0 deletions .gitignore
Expand Up @@ -44,6 +44,7 @@ nosetests.xml
coverage.xml
*,cover
.hypothesis/
.pytest_cache

# Translations
*.mo
Expand Down
7 changes: 6 additions & 1 deletion cookiecutter/generate.py
Expand Up @@ -170,9 +170,14 @@ def generate_file(project_dir, infile, context, env, skip_if_file_exists=False):
raise
rendered_file = tmpl.render(**context)

# Detect original file newline to output the rendered file
with io.open(infile, 'r', encoding='utf-8') as rd:
rd.readline() # Read the first line to load 'newlines' value
newline = getattr(rd, 'newlines')

logger.debug('Writing contents to file %s', outfile)

with io.open(outfile, 'w', encoding='utf-8') as fh:
with io.open(outfile, 'w', encoding='utf-8', newline=newline) as fh:
fh.write(rendered_file)

# Apply file permissions to output file
Expand Down
@@ -0,0 +1 @@
I eat {{ cookiecutter.food }}
19 changes: 19 additions & 0 deletions tests/test_generate_files.py
Expand Up @@ -84,6 +84,25 @@ def test_generate_files_with_trailing_newline():
with io.open(newline_file, 'r', encoding='utf-8') as f:
simple_text = f.read()
assert simple_text == 'I eat pizzä\n'
assert f.newlines == '\n'


@pytest.mark.usefixtures('clean_system', 'remove_additional_folders')
def test_generate_files_with_windows_newline():
generate.generate_files(
context={
'cookiecutter': {'food': 'pizzä'}
},
repo_dir='tests/test-generate-files'
)

newline_file = 'inputpizzä/simple-with-newline-crlf.txt'
assert os.path.isfile(newline_file)

with io.open(newline_file, 'r') as f:
f.read()

assert f.newlines == '\r\n'


@pytest.mark.usefixtures('clean_system', 'remove_additional_folders')
Expand Down