LookupFile.cxx 1.88 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2021 The Music Player Daemon Project
3
 * http://www.musicpd.org
4 5 6 7 8 9 10 11 12 13
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
14 15 16 17
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 19
 */

20 21
#include "LookupFile.hxx"
#include "FileInfo.hxx"
22
#include "system/Error.hxx"
23

24
gcc_pure
25 26
static PathTraitsFS::pointer
FindSlash(PathTraitsFS::pointer p, size_t i) noexcept
27 28 29 30 31 32 33 34
{
	for (; i > 0; --i)
		if (p[i] == '/')
			return p + i;

	return nullptr;
}

35
ArchiveLookupResult
36
LookupFile(Path pathname)
37
{
38
	PathTraitsFS::string buffer(pathname.c_str());
39
	size_t idx = buffer.size();
40

41
	PathTraitsFS::pointer slash = nullptr;
42

43
	while (true) {
44 45
		try {
			//try to stat if its real directory
46
			const FileInfo file_info(Path::FromFS(buffer.c_str()));
47

48
			//is something found ins original path (is not an archive)
49
			if (slash == nullptr)
50
				return {};
51

52
			//its a file ?
53
			if (file_info.IsRegular()) {
54
				//so the upper should be file
55
				return {AllocatedPath::FromFS(buffer), AllocatedPath::FromFS(slash + 1)};
56
			} else {
57
				return {};
58
			}
59 60 61
		} catch (const std::system_error &e) {
			if (!IsPathNotFound(e))
				throw;
62
		}
63

64
		//find one dir up
65 66 67
		if (slash != nullptr)
			*slash = '/';

68
		slash = FindSlash(&buffer.front(), idx - 1);
69
		if (slash == nullptr)
70
			return {};
71 72

		*slash = 0;
73
		idx = slash - buffer.c_str();
74 75 76
	}
}