diff --git a/fs/eol.ts b/fs/eol.ts new file mode 100644 index 000000000000..af5e81ead824 --- /dev/null +++ b/fs/eol.ts @@ -0,0 +1,31 @@ +// 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; + +/** + * 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 { + return content.replace(regDetect, eol); +} diff --git a/fs/eol_test.ts b/fs/eol_test.ts new file mode 100644 index 000000000000..eafdb697e507 --- /dev/null +++ b/fs/eol_test.ts @@ -0,0 +1,32 @@ +// 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"; + +const CRLFinput = "deno\r\nis not\r\nnode"; +const Mixedinput = "deno\nis not\r\nnode"; +const Mixedinput2 = "deno\r\nis not\nnode"; +const LFinput = "deno\nis not\nnode"; +const NoNLinput = "deno is not node"; + +test(function detectCRLF() { + assertEquals(detect(CRLFinput), EOL.CRLF); +}); +test(function detectLF() { + assertEquals(detect(LFinput), EOL.LF); +}); +test(function detectNoNewLine() { + assertEquals(detect(NoNLinput), null); +}); +test(function testFormat() { + assertEquals(format(CRLFinput, EOL.LF), LFinput); + assertEquals(format(LFinput, EOL.LF), LFinput); + assertEquals(format(LFinput, EOL.CRLF), CRLFinput); + assertEquals(format(CRLFinput, EOL.CRLF), CRLFinput); + assertEquals(format(CRLFinput, EOL.CRLF), CRLFinput); + assertEquals(format(NoNLinput, EOL.CRLF), NoNLinput); + assertEquals(format(Mixedinput, EOL.CRLF), CRLFinput); + assertEquals(format(Mixedinput, EOL.LF), LFinput); + assertEquals(format(Mixedinput2, EOL.CRLF), CRLFinput); + assertEquals(format(Mixedinput2, EOL.LF), LFinput); +}); diff --git a/fs/test.ts b/fs/test.ts index 5cff8e17467a..dac0d350ddde 100644 --- a/fs/test.ts +++ b/fs/test.ts @@ -3,6 +3,7 @@ import "./path/test.ts"; import "./walk_test.ts"; import "./globrex_test.ts"; import "./glob_test.ts"; +import "./eol_test.ts"; import "./exists_test.ts"; import "./empty_dir_test.ts"; import "./ensure_dir_test.ts";