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

Fix several bugs due to line endings not properly handled on Windows platform #216

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
29 changes: 26 additions & 3 deletions doctoc.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

'use strict';

var path = require('path')
var os = require('os')
, path = require('path')
, fs = require('fs')
, minimist = require('minimist')
, file = require('./lib/file')
Expand All @@ -16,6 +17,28 @@ function cleanPath(path) {
return homeExpanded.replace(/\s/g, '\\ ');
}

function readFile(path, encoding) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

I think a name like xFileWithCRLFHandling would be more self-documenting.

var content = fs.readFileSync(path, encoding);

// On Windows platform, convert CRLF line endings to LF line endings.
// The line ending style is unified for easier handling.
if (os.EOL === '\r\n') {
content = content.replace(/\r\n/g, '\n');
}

return content;
}

function writeFile(path, data, encoding) {

// On Windows platform, convert LF line endings to CRLF line endings.
if (os.EOL === '\r\n') {
data = data.replace(/(?<!\r)\n/g, '\r\n');
}

fs.writeFileSync(path, data, encoding);
}

function transformAndSave(files, mode, maxHeaderLevel, title, notitle, entryPrefix, processAll, stdOut, updateOnly) {
if (processAll) {
console.log('--all flag is enabled. Including headers before the TOC location.')
Expand All @@ -29,7 +52,7 @@ function transformAndSave(files, mode, maxHeaderLevel, title, notitle, entryPref

var transformed = files
.map(function (x) {
var content = fs.readFileSync(x.path, 'utf8')
var content = readFile(x.path, 'utf8')
, result = transform(content, mode, maxHeaderLevel, title, notitle, entryPrefix, processAll, updateOnly);
result.path = x.path;
return result;
Expand All @@ -53,7 +76,7 @@ function transformAndSave(files, mode, maxHeaderLevel, title, notitle, entryPref
console.log('==================\n\n"%s" should be updated', x.path)
} else {
console.log('"%s" will be updated', x.path);
fs.writeFileSync(x.path, x.data, 'utf8');
writeFile(x.path, x.data, 'utf8');
}
});
}
Expand Down