-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathscript_configuration_entry.dart
More file actions
83 lines (72 loc) · 2.37 KB
/
script_configuration_entry.dart
File metadata and controls
83 lines (72 loc) · 2.37 KB
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
73
74
75
76
77
78
79
80
81
82
83
import 'dart:io';
/// {@template script_entry}
/// A script entry is a section of a file that starts with [_startComment] and
/// ends with [_endComment].
/// {@endtemplate}
class ScriptConfigurationEntry {
/// {@macro script_entry}
const ScriptConfigurationEntry(this.name)
: _startComment = '## [$name]',
_endComment = '## [/$name]';
/// The name of the entry.
final String name;
/// The start comment of the entry.
final String _startComment;
/// The end comment of the entry.
final String _endComment;
/// Whether there is an entry with [name] in [file].
///
/// If the [file] does not exist, this will return false.
bool existsIn(File file) {
if (!file.existsSync()) return false;
final content = file.readAsStringSync();
return content.contains(_startComment) && content.contains(_endComment);
}
/// Adds an entry with [name] to the end of the [file].
///
/// If the [file] does not exist, it will be created.
///
/// If [content] is not null, it will be added within the entry.
void appendTo(File file, {String? content}) {
if (!file.existsSync()) {
file.createSync(recursive: true);
}
final stringBuffer = StringBuffer()
..writeln()
..writeln(_startComment);
if (content != null) stringBuffer.writeln(content);
stringBuffer
..writeln(_endComment)
..writeln();
file.writeAsStringSync(
stringBuffer.toString(),
mode: FileMode.append,
);
}
/// Removes the entry with [name] from the [file].
///
/// If the [file] does not exist, this will do nothing.
///
/// If a file has multiple entries with the same [name], all of them will be
/// removed.
///
/// If [shouldDelete] is true, the [file] will be deleted if it is empty after
/// removing the entry. Otherwise, the [file] will be left empty.
void removeFrom(File file, {bool shouldDelete = false}) {
if (!file.existsSync()) return;
final content = file.readAsStringSync();
final stringPattern = '\n$_startComment.*$_endComment\n\n'
.replaceAll('[', r'\[')
.replaceAll(']', r'\]');
final pattern = RegExp(
stringPattern,
multiLine: true,
dotAll: true,
);
final newContent = content.replaceAllMapped(pattern, (_) => '');
file.writeAsStringSync(newContent);
if (shouldDelete && newContent.trim().isEmpty) {
file.deleteSync();
}
}
}