mirror of
https://github.com/wesnoth/wesnoth
synced 2025-05-03 17:51:05 +00:00
Added function normalize_path to convert filenames to an absolute path.
This commit is contained in:
parent
efd508477c
commit
7b8971f952
@ -1103,6 +1103,83 @@ std::string get_wml_location(const std::string &filename, const std::string &cur
|
||||
return result;
|
||||
}
|
||||
|
||||
static bool is_path_sep(char c)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
if (c == '/' || c == '\\') return true;
|
||||
#else
|
||||
if (c == '/') return true;
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string normalize_path(const std::string &p1)
|
||||
{
|
||||
if (p1.empty()) return p1;
|
||||
|
||||
std::string p2;
|
||||
#ifdef _WIN32
|
||||
if (p1.size() >= 2 && p1[1] == ':')
|
||||
// Windows relative paths with explicit drive name are not handled.
|
||||
p2 = p1;
|
||||
else
|
||||
#endif
|
||||
if (!is_path_sep(p1[0]))
|
||||
p2 = std::string(get_cwd()) + "/" + p1;
|
||||
else
|
||||
p2 = p1;
|
||||
|
||||
#ifdef _WIN32
|
||||
std::string drive;
|
||||
if (p2.size() >= 2 && p2[1] == ':') {
|
||||
drive = p2.substr(0, 2);
|
||||
p2.erase(0, 2);
|
||||
}
|
||||
#endif
|
||||
|
||||
const char *p3 = p2.c_str();
|
||||
|
||||
std::vector<std::string> components(1);
|
||||
for (int i = 0, i_end = p2.size(); i <= i_end; ++i)
|
||||
{
|
||||
std::string &last = components[components.size() - 1];
|
||||
char c = p2[i];
|
||||
if (is_path_sep(c) || c == 0)
|
||||
{
|
||||
if (last == ".")
|
||||
last.clear();
|
||||
else if (last == "..")
|
||||
{
|
||||
if (components.size() >= 2) {
|
||||
components.pop_back();
|
||||
components[components.size() - 1].clear();
|
||||
} else
|
||||
last.clear();
|
||||
}
|
||||
else if (!last.empty())
|
||||
components.push_back(std::string());
|
||||
}
|
||||
else
|
||||
last += c;
|
||||
}
|
||||
|
||||
std::ostringstream p4;
|
||||
components.pop_back();
|
||||
|
||||
#ifdef _WIN32
|
||||
p4 << drive;
|
||||
#endif
|
||||
|
||||
foreach (const std::string &s, components)
|
||||
{
|
||||
p4 << '/' << s;
|
||||
}
|
||||
|
||||
DBG_FS << "Normalizing '" << p2 << "' to '" << p4.str() << "'\n";
|
||||
|
||||
return p4.str();
|
||||
}
|
||||
|
||||
scoped_istream& scoped_istream::operator=(std::istream *s)
|
||||
{
|
||||
delete stream;
|
||||
|
@ -165,6 +165,11 @@ std::string file_name(const std::string& file);
|
||||
*/
|
||||
std::string directory_name(const std::string& file);
|
||||
|
||||
/**
|
||||
* Returns the absolute path of a file.
|
||||
*/
|
||||
std::string normalize_path(const std::string &path);
|
||||
|
||||
/**
|
||||
* The paths manager is responsible for recording the various paths
|
||||
* that binary files may be located at.
|
||||
|
Loading…
x
Reference in New Issue
Block a user