From 06fc3297399fdfad154d1af71cb2d2055d823996 Mon Sep 17 00:00:00 2001 From: Maxime Coste Date: Wed, 30 Jul 2014 00:03:01 +0100 Subject: [PATCH] Rewrite real_path, try to find an existing directory in the given path Never throw, return the given filename in the worst case. --- src/file.cc | 35 +++++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/src/file.cc b/src/file.cc index 0c13c471..c0ffd643 100644 --- a/src/file.cc +++ b/src/file.cc @@ -50,21 +50,28 @@ String parse_filename(StringView filename) String real_path(StringView filename) { - StringView dirname = "."; - StringView basename = filename; - - auto it = find(filename.rbegin(), filename.rend(), '/'); - if (it != filename.rend()) - { - dirname = StringView{filename.begin(), it.base()}; - basename = StringView{it.base(), filename.end()}; - } - char buffer[PATH_MAX+1]; - char* res = realpath(dirname.zstr(), buffer); - if (not res) - throw file_not_found{dirname}; - return res + "/"_str + basename; + + StringView existing = filename; + StringView non_existing; + + while (true) + { + char* res = realpath(existing.zstr(), buffer); + if (res) + { + if (non_existing.empty()) + return res; + return res + "/"_str + non_existing; + } + + auto it = find(existing.rbegin(), existing.rend(), '/'); + if (it == existing.rend()) + return filename; + + existing = StringView{existing.begin(), it.base()-1}; + non_existing = StringView{it.base(), filename.end()}; + } } String compact_path(StringView filename)