Skip to content

Commit

Permalink
Added EOL detect / format
Browse files Browse the repository at this point in the history
  • Loading branch information
zekth committed Mar 18, 2019
1 parent 0bb040e commit bd3948b
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
42 changes: 42 additions & 0 deletions 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);
}
}
}
25 changes: 25 additions & 0 deletions 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);
});

0 comments on commit bd3948b

Please sign in to comment.