Skip to content

Commit

Permalink
chore: Implement strict mode (#453)
Browse files Browse the repository at this point in the history
  • Loading branch information
bartlomieju authored and ry committed May 30, 2019
1 parent e6793e4 commit be24677
Show file tree
Hide file tree
Showing 51 changed files with 466 additions and 371 deletions.
30 changes: 18 additions & 12 deletions archive/tar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,18 @@ const ustar = "ustar\u000000";
* Simple file reader
*/
export class FileReader implements Deno.Reader {
private file: Deno.File;
private file?: Deno.File;

constructor(private filePath: string, private mode: Deno.OpenMode = "r") {}

public async read(p: Uint8Array): Promise<Deno.ReadResult> {
if (!this.file) {
this.file = await Deno.open(this.filePath, this.mode);
}
const res = await Deno.read(this.file.rid, p);
if (res.eof) {
await Deno.close(this.file.rid);
this.file = null;
this.file = undefined;
}
return res;
}
Expand All @@ -54,18 +56,21 @@ export class FileReader implements Deno.Reader {
* Simple file writer (call FileWriter.dispose() after use)
*/
export class FileWriter implements Deno.Writer {
private file: Deno.File;
private file?: Deno.File;

constructor(private filePath: string, private mode: Deno.OpenMode = "w") {}

public async write(p: Uint8Array): Promise<number> {
if (!this.file) {
this.file = await Deno.open(this.filePath, this.mode);
}
return Deno.write(this.file.rid, p);
}

public dispose(): void {
if (!this.file) return;
Deno.close(this.file.rid);
this.file = null;
this.file = undefined;
}
}

Expand Down Expand Up @@ -191,7 +196,7 @@ function formatHeader(data: TarData): Uint8Array {
buffer = clean(512);
let offset = 0;
ustarStructure.forEach(function(value): void {
const entry = encoder.encode(data[value.field] || "");
const entry = encoder.encode(data[value.field as keyof TarData] || "");
buffer.set(entry, offset);
offset += value.length; // space it out with nulls
});
Expand Down Expand Up @@ -307,12 +312,13 @@ export class Tar {
}
i--;
}
if (i < 0 || fileName.length > 100 || fileNamePrefix.length > 155) {
if (i < 0 || fileName.length > 100 || fileNamePrefix!.length > 155) {
throw new Error(
"ustar format does not allow a long file name (length of [file name prefix] + / + [file name] must be shorter than 256 bytes)"
);
}
}
fileNamePrefix = fileNamePrefix!;

opts = opts || {};

Expand Down Expand Up @@ -344,7 +350,7 @@ export class Tar {
fileMode: pad(mode, 7),
uid: pad(uid, 7),
gid: pad(gid, 7),
fileSize: pad(info ? info.len : opts.contentSize, 11),
fileSize: pad((info ? info.len : opts.contentSize)!, 11),
mtime: pad(mtime, 11),
checksum: " ",
type: "0", // just a file
Expand All @@ -362,7 +368,7 @@ export class Tar {
.filter((key): boolean => ["filePath", "reader"].indexOf(key) < 0)
.forEach(function(key): void {
checksum += encoder
.encode(tarData[key])
.encode(tarData[key as keyof TarData])
.reduce((p, c): number => p + c, 0);
});

Expand All @@ -381,7 +387,7 @@ export class Tar {
headerArr = formatHeader(tarData);
readers.push(new Deno.Buffer(headerArr));
if (!reader) {
reader = new FileReader(filePath);
reader = new FileReader(filePath!);
}
readers.push(reader);

Expand All @@ -390,7 +396,7 @@ export class Tar {
new Deno.Buffer(
clean(
recordSize -
(parseInt(tarData.fileSize, 8) % recordSize || recordSize)
(parseInt(tarData.fileSize!, 8) % recordSize || recordSize)
)
)
);
Expand Down Expand Up @@ -451,15 +457,15 @@ export class Untar {
(key): void => {
const arr = trim(header[key]);
if (arr.byteLength > 0) {
meta[key] = parseInt(decoder.decode(arr), 8);
meta[key as keyof UntarOptions] = parseInt(decoder.decode(arr), 8);
}
}
);
["owner", "group"].forEach(
(key): void => {
const arr = trim(header[key]);
if (arr.byteLength > 0) {
meta[key] = decoder.decode(arr);
meta[key as keyof UntarOptions] = decoder.decode(arr);
}
}
);
Expand Down
6 changes: 3 additions & 3 deletions azure-pipelines.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ jobs:
- script: echo '##vso[task.prependpath]$(HOME)/.deno/bin/'
- script: npx eslint **/*.ts --max-warnings=0
- script: deno run --allow-run --allow-write --allow-read format.ts --check
- script: deno run --allow-run --allow-net --allow-write --allow-read test.ts
- script: deno run --allow-run --allow-net --allow-write --allow-read --config=tsconfig.test.json test.ts

- job: "Mac"
pool:
Expand All @@ -26,7 +26,7 @@ jobs:
- script: echo '##vso[task.prependpath]$(HOME)/.deno/bin/'
- script: eslint **/*.ts --max-warnings=0
- script: deno run --allow-run --allow-write --allow-read format.ts --check
- script: deno run --allow-run --allow-net --allow-write --allow-read test.ts
- script: deno run --allow-run --allow-net --allow-write --allow-read --config=tsconfig.test.json test.ts

- job: "Windows"
pool:
Expand All @@ -37,4 +37,4 @@ jobs:
- bash: echo "##vso[task.prependpath]C:\Users\VssAdministrator\.deno\\bin"
- bash: npx eslint **/*.ts --max-warnings=0
- bash: deno.exe run --allow-run --allow-write --allow-read format.ts --check
- bash: deno.exe run --allow-run --allow-net --allow-write --allow-read test.ts
- bash: deno.exe run --allow-run --allow-net --allow-write --allow-read --config=tsconfig.test.json test.ts
4 changes: 2 additions & 2 deletions encoding/csv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export interface ParseOptions {
function chkOptions(opt: ParseOptions): void {
if (
INVALID_RUNE.includes(opt.comma) ||
INVALID_RUNE.includes(opt.comment) ||
(opt.comment && INVALID_RUNE.includes(opt.comment)) ||
opt.comma === opt.comment
) {
throw new Error("Invalid Delimiter");
Expand Down Expand Up @@ -130,7 +130,7 @@ export async function readAll(
}

if (lineResult.length > 0) {
if (_nbFields && _nbFields !== lineResult.length) {
if (_nbFields! && _nbFields! !== lineResult.length) {
throw new ParseError(lineIndex, lineIndex, "wrong number of fields");
}
result.push(lineResult);
Expand Down
4 changes: 2 additions & 2 deletions encoding/csv_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ for (const t of testCases) {
if (t.Error) {
let err;
try {
actual = await readAll(new BufReader(new StringReader(t.Input)), {
actual = await readAll(new BufReader(new StringReader(t.Input!)), {
comma: comma,
comment: comment,
trimLeadingSpace: trim,
Expand All @@ -454,7 +454,7 @@ for (const t of testCases) {
assert(err);
assertEquals(err.message, t.Error);
} else {
actual = await readAll(new BufReader(new StringReader(t.Input)), {
actual = await readAll(new BufReader(new StringReader(t.Input!)), {
comma: comma,
comment: comment,
trimLeadingSpace: trim,
Expand Down
113 changes: 65 additions & 48 deletions encoding/toml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,19 @@ import { deepAssign } from "../util/deep_assign.ts";
import { pad } from "../strings/pad.ts";

class KeyValuePair {
key: string;
value: unknown;
constructor(public key: string, public value: unknown) {}
}

class ParserGroup {
type: string;
name: string;
arrValues: unknown[] = [];
objValues: object = {};
objValues: Record<string, unknown> = {};

constructor(public type: string, public name: string) {}
}

class ParserContext {
currentGroup?: ParserGroup;
output: object = {};
output: Record<string, unknown> = {};
}

class Parser {
Expand All @@ -27,7 +26,7 @@ class Parser {
this.context = new ParserContext();
}
_sanitize(): void {
const out = [];
const out: string[] = [];
for (let i = 0; i < this.tomlLines.length; i++) {
const s = this.tomlLines[i];
const trimmed = s.trim();
Expand Down Expand Up @@ -124,28 +123,30 @@ class Parser {
this.tomlLines = merged;
}
_unflat(keys: string[], values: object = {}, cObj: object = {}): object {
let out = {};
let out: Record<string, unknown> = {};
if (keys.length === 0) {
return cObj;
} else {
if (Object.keys(cObj).length === 0) {
cObj = values;
}
let key = keys.pop();
out[key] = cObj;
let key: string | undefined = keys.pop();
if (key) {
out[key] = cObj;
}
return this._unflat(keys, values, out);
}
}
_groupToOutput(): void {
const arrProperty = this.context.currentGroup.name
.replace(/"/g, "")
const arrProperty = this.context
.currentGroup!.name.replace(/"/g, "")
.replace(/'/g, "")
.split(".");
let u = {};
if (this.context.currentGroup.type === "array") {
u = this._unflat(arrProperty, this.context.currentGroup.arrValues);
if (this.context.currentGroup!.type === "array") {
u = this._unflat(arrProperty, this.context.currentGroup!.arrValues);
} else {
u = this._unflat(arrProperty, this.context.currentGroup.objValues);
u = this._unflat(arrProperty, this.context.currentGroup!.objValues);
}
deepAssign(this.context.output, u);
delete this.context.currentGroup;
Expand All @@ -167,22 +168,22 @@ class Parser {
if (this.context.currentGroup) {
this._groupToOutput();
}
let g = new ParserGroup();
g.name = line.match(captureReg)[1];
if (g.name.match(/\[.*\]/)) {
g.type = "array";
g.name = g.name.match(captureReg)[1];

let type;
let name = line.match(captureReg)![1];
if (name.match(/\[.*\]/)) {
type = "array";
name = name.match(captureReg)![1];
} else {
g.type = "object";
type = "object";
}
this.context.currentGroup = g;
this.context.currentGroup = new ParserGroup(type, name);
}
_processDeclaration(line: string): KeyValuePair {
let kv = new KeyValuePair();
const idx = line.indexOf("=");
kv.key = line.substring(0, idx).trim();
kv.value = this._parseData(line.slice(idx + 1));
return kv;
const key = line.substring(0, idx).trim();
const value = this._parseData(line.slice(idx + 1));
return new KeyValuePair(key, value);
}
// TODO (zekth) Need refactor using ACC
_parseData(dataString: string): unknown {
Expand Down Expand Up @@ -353,23 +354,27 @@ class Parser {
_cleanOutput(): void {
this._propertyClean(this.context.output);
}
_propertyClean(obj: object): void {
_propertyClean(obj: Record<string, unknown>): void {
const keys = Object.keys(obj);
for (let i = 0; i < keys.length; i++) {
let k = keys[i];
let v = obj[k];
let pathDeclaration = this._parseDeclarationName(k);
delete obj[k];
if (pathDeclaration.length > 1) {
k = pathDeclaration.shift();
k = k.replace(/"/g, "");
v = this._unflat(pathDeclaration, v as object);
} else {
k = k.replace(/"/g, "");
}
obj[k] = v;
if (v instanceof Object) {
this._propertyClean(v);
if (k) {
let v = obj[k];
let pathDeclaration = this._parseDeclarationName(k);
delete obj[k];
if (pathDeclaration.length > 1) {
const shift = pathDeclaration.shift();
if (shift) {
k = shift.replace(/"/g, "");
v = this._unflat(pathDeclaration, v as object);
}
} else {
k = k.replace(/"/g, "");
}
obj[k] = v;
if (v instanceof Object) {
this._propertyClean(v);
}
}
}
}
Expand All @@ -393,18 +398,26 @@ class Dumper {
this.output = this._format();
return this.output;
}
_parse(obj: object, path: string = ""): string[] {
_parse(obj: Record<string, unknown>, path: string = ""): string[] {
const out = [];
const props = Object.keys(obj);
const propObj = props.filter(
(e): boolean =>
(obj[e] instanceof Array && !this._isSimplySerializable(obj[e][0])) ||
!this._isSimplySerializable(obj[e])
(e: string): boolean => {
if (obj[e] instanceof Array) {
const d: unknown[] = obj[e] as unknown[];
return !this._isSimplySerializable(d[0]);
}
return !this._isSimplySerializable(obj[e]);
}
);
const propPrim = props.filter(
(e): boolean =>
!(obj[e] instanceof Array && !this._isSimplySerializable(obj[e][0])) &&
this._isSimplySerializable(obj[e])
(e: string): boolean => {
if (obj[e] instanceof Array) {
const d: unknown[] = obj[e] as unknown[];
return this._isSimplySerializable(d[0]);
}
return this._isSimplySerializable(obj[e]);
}
);
const k = propPrim.concat(propObj);
for (let i = 0; i < k.length; i++) {
Expand Down Expand Up @@ -435,7 +448,11 @@ class Dumper {
} else if (typeof value === "object") {
out.push("");
out.push(this._header(path + prop));
out.push(...this._parse(value, `${path}${prop}.`));
if (value) {
const toParse: Record<string, unknown> = value;
out.push(...this._parse(toParse, `${path}${prop}.`));
}
// out.push(...this._parse(value, `${path}${prop}.`));
}
}
out.push("");
Expand Down
2 changes: 1 addition & 1 deletion flags/all_bool_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ test(function flagBooleanTrue(): void {

// flag boolean true only affects double hyphen arguments without equals signs
test(function flagBooleanTrueOnlyAffectsDoubleDash(): void {
var argv = parse(["moo", "--honk", "cow", "-p", "55", "--tacos=good"], {
const argv = parse(["moo", "--honk", "cow", "-p", "55", "--tacos=good"], {
boolean: true
});

Expand Down
Loading

0 comments on commit be24677

Please sign in to comment.