summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorAylur <[email protected]>2024-06-20 15:16:59 +0200
committerAylur <[email protected]>2024-06-20 15:16:59 +0200
commit4e32f62dcd50c545670ef67f9b0f65ed87821426 (patch)
treec4160e311b91cd7bf5ae515db8315f322e99922a /src
parent976638c016eb21ade63779c9dade6110983dc75b (diff)
add file utils
Diffstat (limited to 'src')
-rw-r--r--src/file.vala68
-rw-r--r--src/meson.build1
2 files changed, 69 insertions, 0 deletions
diff --git a/src/file.vala b/src/file.vala
new file mode 100644
index 0000000..5f094b4
--- /dev/null
+++ b/src/file.vala
@@ -0,0 +1,68 @@
+namespace Astal {
+public string read_file(string path) throws Error {
+ var str = "";
+ FileUtils.get_contents(path, out str, null);
+ return str;
+}
+
+public async string read_file_async(string path) throws Error {
+ uint8[] content;
+ yield File.new_for_path(path).load_contents_async(null, out content, null);
+ return (string)content;
+}
+
+public void write_file(string path, string content) throws Error {
+ FileUtils.set_contents(path, content);
+}
+
+public async void write_file_async(string path, string content) throws Error {
+ yield File.new_for_path(path).replace_contents_async(
+ content.data,
+ null,
+ false,
+ GLib.FileCreateFlags.REPLACE_DESTINATION,
+ null,
+ null);
+}
+
+public FileMonitor monitor_file(string path, Closure callback) throws Error {
+ var file = File.new_for_path(path);
+ var mon = file.monitor(GLib.FileMonitorFlags.NONE);
+
+ mon.changed.connect((file, _file, event) => {
+ var f = Value(Type.STRING);
+ var e = Value(Type.INT);
+ var ret = Value(Type.POINTER);
+
+ f.set_string(file.get_path());
+ e.set_int(event);
+
+ callback.invoke(ref ret, { f, e });
+ });
+
+ if (FileUtils.test(path, FileTest.IS_DIR)) {
+ var enumerator = file.enumerate_children("standard::*",
+ FileQueryInfoFlags.NONE, null);
+
+ var i = enumerator.next_file(null);
+ while (i != null) {
+ if (i.get_file_type() == FileType.DIRECTORY) {
+ var filepath = file.get_child(i.get_name()).get_path();
+ if (filepath != null) {
+ var m = monitor_file(path, callback);
+ mon.notify["cancelled"].connect(() => {
+ m.cancel();
+ });
+ }
+ }
+ i = enumerator.next_file(null);
+ }
+ }
+
+ mon.ref();
+ mon.notify["cancelled"].connect(() => {
+ mon.unref();
+ });
+ return mon;
+}
+}
diff --git a/src/meson.build b/src/meson.build
index 80e5a33..bbce8b0 100644
--- a/src/meson.build
+++ b/src/meson.build
@@ -40,6 +40,7 @@ sources = [
'widget/widget.vala',
'widget/window.vala',
'astal.vala',
+ 'file.vala',
'process.vala',
'time.vala',
'variable.vala',