Adding copy_contents functions.

This commit is contained in:
sergiotarxz 2022-07-06 19:08:14 +02:00
parent 81b3d61d1d
commit 038ea02eb5
2 changed files with 65 additions and 0 deletions

View File

@ -43,6 +43,30 @@ namespace Owl {
GLib.FileUtils.set_contents (this.get_path (), content);
}
public void copy_contents (Owl.Path destination) throws GLib.Error {
if (!this.is_dir ()) {
GLib.critical ("Destination is not a directory at copy_contents.\n");
return;
}
if (!destination.exists ()) {
destination.mkpath ();
}
this.visit (true, (inner_file) => {
try {
if (!inner_file.is_dir ()) {
var dest_file = destination.child(this.get_relative(inner_file));
dest_file.parent ().mkpath ();
inner_file.file.copy (dest_file.file, GLib.FileCopyFlags.OVERWRITE);
}
} catch (GLib.Error error) {
GLib.critical (error.message);
return false;
}
return true;
});
}
public string slurp () throws GLib.Error {
string output;
GLib.FileUtils.get_contents (this.get_path (), out output);
@ -62,6 +86,10 @@ namespace Owl {
return new Owl.Path (child_file);
}
public string? get_relative (Owl.Path descendant) {
return this.file.get_relative_path (descendant.file);
}
public void mkpath () throws GLib.Error {
this.file.make_directory_with_parents ();
}

View File

@ -66,5 +66,42 @@ int main (string[] args) {
GLib.Test.fail_printf ("%s\n", error.message);
}
});
GLib.Test.add_func ("/test/owl/path-get-relative", () => {
try {
var tmp = new Owl.Path.tempdir ();
var c = tmp.child (@"a$(S)b$(S)c");
var a = c.parent ().parent ();
assert (a.get_relative(c) == @"b$(S)c");
} catch (GLib.Error error) {
GLib.Test.fail_printf ("%s\n", error.message);
}
});
GLib.Test.add_func ("/test/owl/path-copy-contents", () => {
try {
string char_list = "abcde";
var tmp = new Owl.Path.tempdir ();
var source = tmp.child ("source");
var dest = tmp.child ("dest");
for (long i = 0; i<char_list.length; i++) {
char character = char_list[i];
var char_path = source.child (character.to_string ());
char_path.mkpath ();
var plain_file = char_path.child (character.to_string ());
plain_file.spew ("hola mundo");
}
source.copy_contents (dest);
int i = 0;
dest.visit (true, (file) => {
if (!file.is_dir () && file.slurp () == "hola mundo") {
i++;
}
return true;
});
assert (i == 5);
} catch (GLib.Error error) {
GLib.Test.fail_printf ("%s\n", error.message);
}
});
return GLib.Test.run ();
}