1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-12-27 01:29:14 -05:00

Added EOL detect / format (#289)

This commit is contained in:
Vincent LE GOFF 2019-04-07 03:06:07 +02:00 committed by Ryan Dahl
parent 24f41f67bd
commit 1d53fb4d79
3 changed files with 64 additions and 0 deletions

31
fs/eol.ts Normal file
View file

@ -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);
}

32
fs/eol_test.ts Normal file
View file

@ -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);
});

View file

@ -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";