vibe.core.path 9/227(3%) line coverage

      
10
20
30
40
50
60
70
80
90
100
110
120
130
140
150
160
170
180
190
200
210
220
230
240
250
260
270
280
290
300
310
320
330
340
350
360
370
380
390
400
410
420
430
440
450
460
470
480
490
500
510
520
530
540
550
560
570
580
590
600
610
620
630
640
650
660
670
680
690
700
710
720
730
740
750
760
770
780
790
800
810
820
830
840
850
860
870
880
890
900
910
920
930
940
950
960
970
980
990
1000
1010
1020
1030
1040
1050
1060
1070
1080
1090
1100
1110
1120
1130
1140
1150
1160
1170
1180
1190
1200
1210
1220
1230
1240
1250
1260
1270
1280
12925
1300
13125
13225
13325
1340
1350
1360
1370
1380
1390
1400
1410
1420
1430
1440
1450
1460
1470
1480
1490
1500
15125
1520
1530
1540
1550
1560
1570
1580
1590
1600
1610
1620
1630
1640
1650
1660
1670
1680
1690
1700
1710
1720
1730
1740
1750
1760
1770
1780
17925
18050
1810
1820
1830
1840
1850
1860
1870
1880
1890
1900
1910
1920
1930
1940
1950
1960
1970
1980
1990
2000
2010
2020
2030
2040
2050
2060
2070
2080
2090
2100
2110
2120
2130
2140
2150
2160
2170
2180
2190
2200
2210
2220
2230
2240
2250
2260
2270
2280
2290
2300
2310
2320
2330
2340
2350
2360
2370
2380
2390
2400
2410
2420
2430
2440
2450
2460
2470
2480
2490
2500
2510
2520
2530
2540
2550
2560
2570
2580
2590
2600
2610
2620
2630
2640
2650
2660
2670
2680
2690
2700
2710
2720
2730
2740
2750
2760
2770
2780
2790
2800
2810
2820
2830
2840
2850
2860
2870
2880
2890
2900
2910
2920
2930
2940
2950
2960
2970
2980
2990
3000
3010
3020
3030
3040
3050
3060
3070
3080
3090
3100
3110
3120
3130
3140
3150
3160
3170
3180
3190
3200
3210
3220
3230
3240
3250
3260
3270
3280
3290
3300
3310
3320
3330
3340
3350
3360
3370
3380
3390
3400
3410
3420
3430
3440
3450
3460
3470
3480
3490
3500
3510
3520
3530
3540
3550
3560
3570
3580
3590
3600
3610
3620
3630
3640
3650
3660
3670
3680
3690
3700
3710
3720
3730
3740
3750
3760
3770
3780
3790
3800
3810
3820
3830
3840
3850
3860
3870
3880
3890
3900
3910
3920
3930
3940
3950
3960
3970
3980
3990
4000
4010
4020
4030
4040
4050
4060
4070
4080
4090
4100
4110
4120
4130
4140
4150
4160
4170
4180
4190
4200
4210
4220
4230
4240
4250
4260
4270
4280
4290
4300
4310
4320
4330
4340
4350
4360
4370
4380
4390
4400
4410
4420
4430
4440
4450
4460
4470
4480
4490
4500
4510
4520
4530
4540
4550
4560
4570
4580
4590
4600
4610
4620
4630
4640
4650
4660
4670
4680
4690
4700
4710
4720
4730
4740
4750
4760
4770
4780
4790
4800
4810
4820
4830
48450
48550
4860
4870
4880
4890
4900
4910
4920
4930
4940
4950
4960
4970
4980
4990
5000
5010
5020
5030
5040
5050
5060
5070
5080
5090
5100
5110
5120
5130
5140
5150
5160
5170
5180
5190
5200
5210
5220
/** Contains routines for high level path handling. Copyright: © 2012-2015 RejectedSoftware e.K. License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file. Authors: Sönke Ludwig */ module vibe.core.path; import std.algorithm : canFind, min; import std.array; import std.conv; import std.exception; import std.string; /** Computes the relative path from `base_path` to this path. Params: path = The destination path base_path = The path from which the relative path starts See_also: `relativeToWeb` */ Path relativeTo(Path path, Path base_path) @safe{ assert(path.absolute && base_path.absolute); version (Windows) { // a path such as ..\C:\windows is not valid, so force the path to stay absolute in this case if (path.absolute && !path.empty && (path[0].toString().endsWith(":") && !base_path.startsWith(path[0 .. 1]) || path[0] == "\\" && !base_path.startsWith(path[0 .. min(2, $)]))) { return path; } } int nup = 0; while (base_path.length > nup && !path.startsWith(base_path[0 .. base_path.length-nup])) { nup++; } Path ret = Path(null, false); ret.m_endsWithSlash = true; foreach (i; 0 .. nup) ret ~= ".."; ret ~= Path(path.nodes[base_path.length-nup .. $], false); ret.m_endsWithSlash = path.m_endsWithSlash; return ret; } /// unittest { assert(Path("/some/path").relativeTo(Path("/")) == Path("some/path")); assert(Path("/some/path/").relativeTo(Path("/some/other/path/")) == Path("../../path/")); assert(Path("/some/path/").relativeTo(Path("/some/other/path")) == Path("../../path/")); } /** Computes the relative path to this path from `base_path` using web path rules. The difference to `relativeTo` is that a path not ending in a slash will not be considered as a path to a directory and the parent path will instead be used. Params: path = The destination path base_path = The path from which the relative path starts See_also: `relativeTo` */ Path relativeToWeb(Path path, Path base_path) @safe { if (!base_path.endsWithSlash) { if (base_path.length > 0) base_path = base_path[0 .. $-1]; else base_path = Path("/"); } return path.relativeTo(base_path); } /// unittest { assert(Path("/some/path").relativeToWeb(Path("/")) == Path("some/path")); assert(Path("/some/path/").relativeToWeb(Path("/some/other/path/")) == Path("../../path/")); assert(Path("/some/path/").relativeToWeb(Path("/some/other/path")) == Path("../path/")); } /// Forward compatibility alias for vibe-core alias NativePath = Path; /// ditto alias PosixPath = Path; /// ditto alias WindowsPath = Path; /// ditto alias InetPath = Path; /** Represents an absolute or relative file system path. This struct allows to do safe operations on paths, such as concatenation and sub paths. Checks are done to disallow invalid operations such as concatenating two absolute paths. It also validates path strings and allows for easy checking of malicious relative paths. */ struct Path { @safe: /// Forward compatibility alias for vibe-core alias Segment = PathEntry; private { immutable(PathEntry)[] m_nodes; bool m_absolute = false; bool m_endsWithSlash = false; } hash_t toHash() const nothrow @trusted { hash_t ret; auto strhash = &typeid(string).getHash; try foreach (n; nodes) ret ^= strhash(&n.m_name); catch (Throwable) assert(false); if (m_absolute) ret ^= 0xfe3c1738; if (m_endsWithSlash) ret ^= 0x6aa4352d; return ret; } pure: /// Constructs a Path object by parsing a path string. this(string pathstr) { m_nodes = splitPath(pathstr); m_absolute = (pathstr.startsWith("/") || m_nodes.length > 0 && (m_nodes[0].toString().canFind(':') || m_nodes[0] == "\\")); m_endsWithSlash = pathstr.endsWith("/"); } /// Constructs a path object from a list of PathEntry objects. this(immutable(PathEntry)[] nodes, bool absolute) { m_nodes = nodes; m_absolute = absolute; } /// Constructs a relative path with one path entry. this(PathEntry entry) { m_nodes = [entry]; m_absolute = false; } /// Determines if the path is absolute. @property bool absolute() const { return m_absolute; } /// Forward compatibility property for vibe-code @property immutable(PathEntry)[] bySegment() const { return nodes; } /// Resolves all '.' and '..' path entries as far as possible. void normalize() { immutable(PathEntry)[] newnodes; foreach( n; m_nodes ){ switch(n.toString()){ default: newnodes ~= n; break; case "", ".": break; case "..": enforce(!m_absolute || newnodes.length > 0, "Path goes below root node."); if( newnodes.length > 0 && newnodes[$-1] != ".." ) newnodes = newnodes[0 .. $-1]; else newnodes ~= n; break; } } m_nodes = newnodes; } /// Converts the Path back to a string representation using slashes. string toString() const { if (m_nodes.empty) return absolute ? "/" : endsWithSlash ? "./" : ""; Appender!string ret; // for absolute paths start with / if( absolute ) ret.put('/'); foreach( i, f; m_nodes ){ if( i > 0 ) ret.put('/'); ret.put(f.toString()); } if( m_nodes.length > 0 && m_endsWithSlash ) ret.put('/'); return ret.data; } /// Converts the Path object to a native path string (backslash as path separator on Windows). string toNativeString() nothrow const { Appender!string ret; // for absolute unix paths start with / version(Posix) { if (m_absolute) ret.put('/'); } foreach( i, f; m_nodes ){ version(Windows) { if( i > 0 ) ret.put('\\'); } else version(Posix) { if( i > 0 ) ret.put('/'); } else static assert(false, "Unsupported OS"); ret.put(f.toString()); } if( m_nodes.length > 0 && m_endsWithSlash ){ version(Windows) { ret.put('\\'); } version(Posix) { ret.put('/'); } } return ret.data; } /// Tests if `rhs` is an anchestor or the same as this path. bool startsWith(const Path rhs) const { if( rhs.m_nodes.length > m_nodes.length ) return false; foreach( i; 0 .. rhs.m_nodes.length ) if( m_nodes[i] != rhs.m_nodes[i] ) return false; return true; } /// The last entry of the path @property ref immutable(PathEntry) head() const { enforce(m_nodes.length > 0); return m_nodes[$-1]; } /// The parent path @property Path parentPath() const { return this[0 .. length-1]; } /// The ist of path entries of which this path is composed @property immutable(PathEntry)[] nodes() const { return m_nodes; } /// The number of path entries of which this path is composed @property size_t length() const { return m_nodes.length; } /// True if the path contains no entries @property bool empty() const { return m_nodes.length == 0; } /// Determines if the path ends with a slash (i.e. is a directory) @property bool endsWithSlash() const { return m_endsWithSlash; } /// ditto @property void endsWithSlash(bool v) { m_endsWithSlash = v; } /// Determines if this path goes outside of its base path (i.e. begins with '..'). @property bool external() const { return !m_absolute && m_nodes.length > 0 && m_nodes[0].m_name == ".."; } ref immutable(PathEntry) opIndex(size_t idx) const { return m_nodes[idx]; } Path opSlice(size_t start, size_t end) const { auto ret = Path(m_nodes[start .. end], start == 0 ? absolute : false); ret.m_endsWithSlash = end == m_nodes.length ? m_endsWithSlash : true; return ret; } size_t opDollar(int dim)() const if(dim == 0) { return m_nodes.length; } Path opBinary(string OP)(const Path rhs) const if( OP == "~" ) { assert(!rhs.absolute, "Trying to append absolute path."); if (!rhs.length) return this; Path ret; ret.m_nodes = m_nodes; ret.m_absolute = m_absolute; ret.m_endsWithSlash = rhs.m_endsWithSlash; ret.normalize(); // needed to avoid "."~".." become "" instead of ".." foreach (folder; rhs.m_nodes) { switch (folder.toString()) { default: ret.m_nodes = ret.m_nodes ~ folder; break; case "", ".": break; case "..": enforce(!ret.absolute || ret.m_nodes.length > 0, "Relative path goes below root node!"); if( ret.m_nodes.length > 0 && ret.m_nodes[$-1].toString() != ".." ) ret.m_nodes = ret.m_nodes[0 .. $-1]; else ret.m_nodes = ret.m_nodes ~ folder; break; } } return ret; } Path opBinary(string OP)(string rhs) const if( OP == "~" ) { return opBinary!"~"(Path(rhs)); } Path opBinary(string OP)(PathEntry rhs) const if( OP == "~" ) { return opBinary!"~"(Path(rhs)); } void opOpAssign(string OP)(string rhs) if( OP == "~" ) { opOpAssign!"~"(Path(rhs)); } void opOpAssign(string OP)(PathEntry rhs) if( OP == "~" ) { opOpAssign!"~"(Path(rhs)); } void opOpAssign(string OP)(immutable(PathEntry)[] rhs) if( OP == "~" ) { opOpAssign!"~"(Path(rhs, false)); } void opOpAssign(string OP)(Path rhs) if( OP == "~" ) { assert(!rhs.absolute, "Trying to append absolute path."); if (!rhs.length) return; auto p = this ~ rhs; m_nodes = p.m_nodes; m_endsWithSlash = rhs.m_endsWithSlash; } /// Tests two paths for equality using '=='. bool opEquals(ref const Path rhs) const { if( m_absolute != rhs.m_absolute ) return false; if( m_endsWithSlash != rhs.m_endsWithSlash ) return false; if( m_nodes.length != rhs.length ) return false; foreach( i; 0 .. m_nodes.length ) if( m_nodes[i] != rhs.m_nodes[i] ) return false; return true; } /// ditto bool opEquals(const Path other) const { return opEquals(other); } int opCmp(ref const Path rhs) const { if( m_absolute != rhs.m_absolute ) return cast(int)m_absolute - cast(int)rhs.m_absolute; foreach( i; 0 .. min(m_nodes.length, rhs.m_nodes.length) ) if( m_nodes[i] != rhs.m_nodes[i] ) return m_nodes[i].opCmp(rhs.m_nodes[i]); if( m_nodes.length > rhs.m_nodes.length ) return 1; if( m_nodes.length < rhs.m_nodes.length ) return -1; return 0; } } unittest { { auto unc = "\\\\server\\share\\path"; auto uncp = Path(unc); uncp.normalize(); version(Windows) assert(uncp.toNativeString() == unc); assert(uncp.absolute); assert(!uncp.endsWithSlash); } { auto abspath = "/test/path/"; auto abspathp = Path(abspath); assert(abspathp.toString() == abspath); version(Windows) {} else assert(abspathp.toNativeString() == abspath); assert(abspathp.absolute); assert(abspathp.endsWithSlash); assert(abspathp.length == 2); assert(abspathp[0] == "test"); assert(abspathp[1] == "path"); } { auto relpath = "test/path/"; auto relpathp = Path(relpath); assert(relpathp.toString() == relpath); version(Windows) assert(relpathp.toNativeString() == "test\\path\\"); else assert(relpathp.toNativeString() == relpath); assert(!relpathp.absolute); assert(relpathp.endsWithSlash); assert(relpathp.length == 2); assert(relpathp[0] == "test"); assert(relpathp[1] == "path"); } { auto winpath = "C:\\windows\\test"; auto winpathp = Path(winpath); assert(winpathp.toString() == "/C:/windows/test"); version(Windows) assert(winpathp.toNativeString() == winpath); else assert(winpathp.toNativeString() == "/C:/windows/test"); assert(winpathp.absolute); assert(!winpathp.endsWithSlash); assert(winpathp.length == 3); assert(winpathp[0] == "C:"); assert(winpathp[1] == "windows"); assert(winpathp[2] == "test"); } { auto dotpath = "/test/../test2/././x/y"; auto dotpathp = Path(dotpath); assert(dotpathp.toString() == "/test/../test2/././x/y"); dotpathp.normalize(); assert(dotpathp.toString() == "/test2/x/y"); } { auto dotpath = "/test/..////test2//./x/y"; auto dotpathp = Path(dotpath); assert(dotpathp.toString() == "/test/..////test2//./x/y"); dotpathp.normalize(); assert(dotpathp.toString() == "/test2/x/y"); } { auto parentpath = "/path/to/parent"; auto parentpathp = Path(parentpath); auto subpath = "/path/to/parent/sub/"; auto subpathp = Path(subpath); auto subpath_rel = "sub/"; assert(subpathp.relativeTo(parentpathp).toString() == subpath_rel); auto subfile = "/path/to/parent/child"; auto subfilep = Path(subfile); auto subfile_rel = "child"; assert(subfilep.relativeTo(parentpathp).toString() == subfile_rel); } { // relative paths across Windows devices are not allowed version (Windows) { auto p1 = Path("\\\\server\\share"); assert(p1.absolute); auto p2 = Path("\\\\server\\othershare"); assert(p2.absolute); auto p3 = Path("\\\\otherserver\\share"); assert(p3.absolute); auto p4 = Path("C:\\somepath"); assert(p4.absolute); auto p5 = Path("C:\\someotherpath"); assert(p5.absolute); auto p6 = Path("D:\\somepath"); assert(p6.absolute); assert(p4.relativeTo(p5) == Path("../somepath")); assert(p4.relativeTo(p6) == Path("C:\\somepath")); assert(p4.relativeTo(p1) == Path("C:\\somepath")); assert(p1.relativeTo(p2) == Path("../share")); assert(p1.relativeTo(p3) == Path("\\\\server\\share")); assert(p1.relativeTo(p4) == Path("\\\\server\\share")); } } { // relative path, trailing slash auto p1 = Path("/some/path"); auto p2 = Path("/some/path/"); assert(p1.relativeTo(p1).toString() == ""); assert(p1.relativeTo(p2).toString() == ""); assert(p2.relativeTo(p2).toString() == "./"); assert(p2.relativeTo(p1).toString() == "./"); } } struct PathEntry { @safe: pure: private { string m_name; } static PathEntry validateFilename(string fname) { enforce(fname.indexOfAny("/\\") < 0, "File name contains forward or backward slashes: "~fname); return PathEntry(fname); } this(string str) { assert(!str.canFind('/') && (!str.canFind('\\') || str.length == 1), "Invalid path entry: " ~ str); m_name = str; } string toString() const nothrow { return m_name; } Path opBinary(string OP)(PathEntry rhs) const if( OP == "~" ) { return Path([this, rhs], false); } @property string name() const nothrow { return m_name; } bool opEquals(ref const PathEntry rhs) const { return m_name == rhs.m_name; } bool opEquals(PathEntry rhs) const { return m_name == rhs.m_name; } bool opEquals(string rhs) const { return m_name == rhs; } int opCmp(ref const PathEntry rhs) const { return m_name.cmp(rhs.m_name); } int opCmp(string rhs) const { return m_name.cmp(rhs); } } private bool isValidFilename(string str) pure @safe { foreach( ch; str ) if( ch == '/' || /*ch == ':' ||*/ ch == '\\' ) return false; return true; } /// Joins two path strings. subpath must be relative. string joinPath(string basepath, string subpath) pure @safe { Path p1 = Path(basepath); Path p2 = Path(subpath); return (p1 ~ p2).toString(); } /// Splits up a path string into its elements/folders PathEntry[] splitPath(string path) pure @safe { if( path.startsWith("/") || path.startsWith("\\") ) path = path[1 .. $]; if( path.empty ) return null; if( path.endsWith("/") || path.endsWith("\\") ) path = path[0 .. $-1]; // count the number of path nodes size_t nelements = 0; foreach( i, char ch; path ) if( ch == '\\' || ch == '/' ) nelements++; nelements++; // reserve space for the elements PathEntry[] storage; /*if (alloc) { auto mem = alloc.alloc(nelements * PathEntry.sizeof); mem[] = 0; storage = cast(PathEntry[])mem; } else*/ storage = new PathEntry[nelements]; size_t startidx = 0; size_t eidx = 0; // detect UNC path if(path.startsWith("\\")) { storage[eidx++] = PathEntry(path[0 .. 1]); path = path[1 .. $]; } // read and return the elements foreach( i, char ch; path ) if( ch == '\\' || ch == '/' ){ storage[eidx++] = PathEntry(path[startidx .. i]); startidx = i+1; } storage[eidx++] = PathEntry(path[startidx .. $]); assert(eidx == nelements); return storage; }