diff --git a/core/file.c b/core/file.c index e86eee75..6b8f9a5e 100644 --- a/core/file.c +++ b/core/file.c @@ -268,6 +268,20 @@ int cache_file_write(struct cache_file *file, const void *data, size_t len) return -1; } +bool cache_file_import(struct cache_file *file, const gchar *srcpath) +{ + gchar *contents = NULL; + gsize length = 0; + + if (!file->cf_file || !srcpath) + return false; + if (!g_file_get_contents(srcpath, &contents, &length, NULL)) + return false; + + cache_file_write(file, contents, length); + return true; +} + bool file_remove(struct file *file) { int ret = -1; diff --git a/include/core/file.h b/include/core/file.h index 9516283b..4b327e14 100644 --- a/include/core/file.h +++ b/include/core/file.h @@ -141,6 +141,9 @@ int file_writef(struct file *, const char *, ...); */ int cache_file_write(struct cache_file *, const void *, size_t); +/* Import a file into the cache. */ +bool cache_file_import(struct cache_file *, const gchar *); + /* Removes a closed file from disk. */ bool file_remove(struct file *); diff --git a/tests/core/file.c b/tests/core/file.c index e282c878..a0d00ad8 100644 --- a/tests/core/file.c +++ b/tests/core/file.c @@ -151,6 +151,7 @@ static void test_versioning() static void test_cache() { struct cache_file file = CACHE_FILE_INIT("dir", "file.txt"); + struct cache_file copy = CACHE_FILE_INIT("dir", "copy.txt"); gchar *basepath, *filepath, *writepath; basepath = g_strjoin("/", g_get_user_cache_dir(), OCARINA_NAME, NULL); @@ -164,6 +165,7 @@ static void test_cache() test_str_equal(cache_file_path(&file), filepath); test_str_equal(cache_file_write_path(&file), writepath); + /* Test writing data to a cache file. */ test_equal(cache_file_exists(&file), (bool)false); test_equal(cache_file_open(&file, OPEN_READ), (bool)false); test_equal(cache_file_open(&file, OPEN_WRITE), (bool)true); @@ -175,6 +177,17 @@ static void test_cache() cache_file_close(&file); test_equal((void *)file.cf_file, NULL); test_equal(cache_file_exists(&file), (bool)true); + + /* Test importing a file into the cache. */ + test_equal(cache_file_exists(©), (bool)false); + test_equal(cache_file_import(©, filepath), (bool)false); + test_equal(cache_file_exists(©), (bool)false); + test_equal(cache_file_open(©, OPEN_WRITE), (bool)true); + test_equal(cache_file_import(©, NULL), (bool)false); + test_equal(cache_file_import(©, filepath), (bool)true); + test_equal(cache_file_exists(©), (bool)false); + cache_file_close(©); + test_equal(cache_file_exists(©), (bool)true); } DECLARE_UNIT_TESTS(