#include <string>
#include <algorithm>
using namespace std;
#include "utx.h"
//defined in other snippets
extern string toDosPath(const string& path);
extern string toLowerCase(const string& s);
string torelativepath(const string& path, const string& prefix)
{
string fqpath = toLowerCase(toDosPath(path));
string root = toLowerCase(toDosPath(prefix));
if (fqpath.find(root) == string::npos)
throw exception("path does not start with given prefix");
if (root.length() == fqpath.length()) return "";
return path.substr(prefix.length() + (fqpath[root.length()] == '\\' ? 1 : 0));
}
//--- Tests
TEST(emptycases)
{
utxassert(torelativepath("", ""), "");
utxassert(torelativepath("c:\\", "c:\\"), "");
}
TEST(normal)
{
utxassert(torelativepath("c:\\abc", "c:\\"), "abc");
utxassert(torelativepath("c:\\abc\\def", "c:\\abc"), "def");
utxassert(torelativepath("c:\\abc\\def", "c:\\"), "abc\\def");
utxassert(torelativepath("c:\\abc\\def", "c:"), "abc\\def");
}
TEST(ignorecaseinprefix)
{
utxassert(torelativepath("c:\\abc", "c:\\"), "abc");
utxassert(torelativepath("c:\\abc", "C:\\"), "abc");
utxassert(torelativepath("C:\\abc", "c:\\"), "abc");
utxassert(torelativepath("C:\\abc", "C:\\"), "abc");
utxassert(torelativepath("c:\\aBc\\def", "c:\\abC"), "def");
}
TEST(preservecaseinpath)
{
utxassert(torelativepath("c:\\Abc", "c:\\"), "Abc");
}
TEST(notaprefix)
{
try
{
utxassert(torelativepath("c:\\abc\\def", "c:\\xyz"), "def");
utxBoolAssert(false);
}
catch(exception /*ex*/)
{
utxBoolAssert(true);
}
}
|