Skip to content

Commit

Permalink
Fix the bug that line endings are poorly handled on Windows platform,…
Browse files Browse the repository at this point in the history
… which causes insidious bug like thlorenz#161
  • Loading branch information
MapleCCC committed Oct 21, 2021
1 parent ffbb04f commit 77a2d9c
Showing 1 changed file with 26 additions and 3 deletions.
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) {
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

0 comments on commit 77a2d9c

Please sign in to comment.