From 7777dce64be826d070b17312d7e82b6ce8eb21de Mon Sep 17 00:00:00 2001 From: Boris Kolpackov Date: Thu, 30 May 2013 19:57:03 -0400 Subject: Add posix_string() function to fs::basic_path class template --- cutl/fs/path.hxx | 10 +++++++++- cutl/fs/path.ixx | 9 +++++++++ cutl/fs/path.txx | 20 ++++++++++++++++++++ tests/fs/path/driver.cxx | 13 +++++++++++++ 4 files changed, 51 insertions(+), 1 deletion(-) diff --git a/cutl/fs/path.hxx b/cutl/fs/path.hxx index d96644e..cbe71a6 100644 --- a/cutl/fs/path.hxx +++ b/cutl/fs/path.hxx @@ -80,7 +80,6 @@ namespace cutl } }; - template class invalid_basic_path; @@ -275,6 +274,15 @@ namespace cutl return path_; } + // If possible, return a POSIX representation of the path. For example, + // for a Windows path in the form foo\bar this function will return + // foo/bar. If it is not possible to create a POSIX representation for + // this path (e.g., c:\foo), this function will throw the invalid_path + // exception. + // + string_type + posix_string () const; + private: void init (); diff --git a/cutl/fs/path.ixx b/cutl/fs/path.ixx index 38a486d..80d3bb3 100644 --- a/cutl/fs/path.ixx +++ b/cutl/fs/path.ixx @@ -43,6 +43,15 @@ namespace cutl return *this; } +#ifndef _WIN32 + template + inline typename basic_path::string_type basic_path:: + posix_string () const + { + return string (); + } +#endif + #ifdef _WIN32 template <> inline char basic_path:: diff --git a/cutl/fs/path.txx b/cutl/fs/path.txx index f7cdcc4..e95c890 100644 --- a/cutl/fs/path.txx +++ b/cutl/fs/path.txx @@ -64,6 +64,26 @@ namespace cutl return *this; } +#ifdef _WIN32 + template + typename basic_path::string_type basic_path:: + posix_string () const + { + if (absolute ()) + throw invalid_basic_path (path_); + + string_type r (path_); + + // Translate Windows-style separators to the POSIX ones. + // + for (size_type i (0), n (r.size ()); i != n; ++i) + if (r[i] == '\\') + r[i] = '/'; + + return r; + } +#endif + template basic_path& basic_path:: operator/= (basic_path const& r) diff --git a/tests/fs/path/driver.cxx b/tests/fs/path/driver.cxx index f35d3eb..6c77e67 100644 --- a/tests/fs/path/driver.cxx +++ b/tests/fs/path/driver.cxx @@ -119,6 +119,19 @@ main () assert (path ("C:\\Foo12//Bar").normalize ().string () == "c:\\foo12\\bar"); #endif + // posix_string + // + assert (path ("foo/bar/../baz").posix_string () == "foo/bar/../baz"); +#ifdef _WIN32 + assert (path ("foo\\bar\\..\\baz").posix_string () == "foo/bar/../baz"); + try + { + path ("c:\\foo\\bar\\..\\baz").posix_string (); + assert (false); + } + catch (const invalid_path&) {} +#endif + /* path p ("../foo"); p.complete (); -- cgit v1.1