diff --git a/fs/eol.ts b/fs/eol.ts new file mode 100644 index 000000000000..9a450fdcbb0c --- /dev/null +++ b/fs/eol.ts @@ -0,0 +1,42 @@ +// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. + +/** EndOfLine character enum */ +export enum EOL { + LF = "\n", + CRLF = "\r\n" +} + +const regDetect = /(?:\r?\n)/g; +const regCRLF = /\r\n/g; +const regLF = /\n/g; + +/** + * Detect the EOL character for string input. + * returns null if no newline + */ +export function detect(content: string): EOL | null { + const d = content.match(regDetect); + if (!d || d.length === 0) { + return null; + } + const crlf = d.filter(x => x === EOL.CRLF); + if (crlf.length > 0) { + return EOL.CRLF; + } else { + return EOL.LF; + } +} + +/** Format the file to the targeted EOL */ +export function format(content: string, eol: EOL): string { + const _eol = detect(content); + if (_eol === eol) { + return content; + } else { + if (_eol === EOL.CRLF) { + return content.replace(regCRLF, eol); + } else { + return content.replace(regLF, eol); + } + } +} diff --git a/fs/eol_test.ts b/fs/eol_test.ts new file mode 100644 index 000000000000..ac353693291b --- /dev/null +++ b/fs/eol_test.ts @@ -0,0 +1,25 @@ +// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. +import { test } from "../testing/mod.ts"; +import { assertEquals } from "../testing/asserts.ts"; +import { format, detect, EOL } from "./eol.ts"; + +test(function detectCRLF() { + const input = "deno\r\nis not\r\nnode"; + assertEquals(detect(input), EOL.CRLF); +}); +test(function detectLF() { + const input = "deno\nis not\nnode"; + assertEquals(detect(input), EOL.LF); +}); +test(function detectNoNewLine() { + const input = "deno is not node"; + assertEquals(detect(input), null); +}); +test(function testFormat() { + const CRLFinput = "deno\r\nis not\r\nnode"; + const LFinput = "deno\nis not\nnode"; + assertEquals(format(CRLFinput, EOL.LF), LFinput); + assertEquals(format(LFinput, EOL.LF), LFinput); + assertEquals(format(LFinput, EOL.CRLF), CRLFinput); + assertEquals(format(CRLFinput, EOL.CRLF), CRLFinput); +});