-
Notifications
You must be signed in to change notification settings - Fork 0
/
IniFIle.ts
72 lines (66 loc) · 2.61 KB
/
IniFIle.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { BiniDataView } from "./BiniDataView";
import { IniComment, Entry, Section } from "./ini";
export class IniFile {
public sections: Section[] = [];
public comments: IniComment[] = [];
constructor(public filePath: string) { }
public static fromString(filePath: string, content: string) {
const ini = new IniFile(filePath);
const lines = content.split(/\r?\n/);
let currentSection: Section | null = null;
for (const [index, line] of lines.entries()) {
if (line) {
const firstChar = line.charAt(0);
switch (firstChar) {
case ';':
// Handle comment
if (currentSection) {
currentSection.comments.push({
lineNum: index,
content: line
});
} else {
ini.comments.push({
lineNum: index,
content: line
})
}
break;
case '[':
// Handle section
if (currentSection) {
ini.sections.push(currentSection);
}
const sectionName = /\[(.*?)\]/.exec(line)?.at(1) ?? 'Null';
currentSection = new Section(sectionName);
break;
default:
// Handle entry
if (currentSection) {
currentSection.entries.push(Entry.fromString(line));
}
break;
}
}
}
ini.sections.push(currentSection);
return ini;
}
public static fromBinary(filePath: string, content: ArrayBuffer) {
const ini = new IniFile(filePath);
const buf = new Uint8Array(content);
const dataView = new BiniDataView(buf, filePath);
const sections = dataView.readBiniFile(content.byteLength);
if (sections) {
ini.sections = sections;
}
return ini;
}
public toString() {
const text = this.sections.join("\n\n").split(/\r?\n/);
this.comments.forEach(c => {
text.splice(c.lineNum, 0, c.content);
})
return text.join('\n');
}
}