forked from gitextensions/gitextensions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PathUtil.cs
94 lines (83 loc) · 3.32 KB
/
PathUtil.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
using System;
using System.Collections.Generic;
using System.IO;
using GitCommands.Utils;
namespace GitCommands
{
public static class PathUtil
{
/// <summary>Replaces native path separator with posix path separator.</summary>
public static string ToPosixPath(this string path)
{
return path.Replace(Path.DirectorySeparatorChar, AppSettings.PosixPathSeparator);
}
/// <summary>Replaces '\' with '/'.</summary>
public static string ToNativePath(this string path)
{
return path.Replace(AppSettings.PosixPathSeparator, Path.DirectorySeparatorChar);
}
/// <summary>
/// Code guideline: "A directory path should always end with / or \.
/// Better use Path.Combine instead of Setting.PathSeparator"
///
/// This method can be used to add (or keep) a trailing path separator character to a directory path.
/// </summary>
/// <param name="dirPath"></param>
/// <returns></returns>
public static string EnsureTrailingPathSeparator(this string dirPath)
{
if (!dirPath.IsNullOrEmpty() && dirPath[dirPath.Length - 1] != Path.DirectorySeparatorChar)
{
dirPath += Path.DirectorySeparatorChar;
}
return dirPath;
}
public static string GetFileName(string fileName)
{
var pathSeparators = new[] { Path.DirectorySeparatorChar, AppSettings.PosixPathSeparator };
var pos = fileName.LastIndexOfAny(pathSeparators);
if (pos != -1)
fileName = fileName.Substring(pos + 1);
return fileName;
}
public static string GetDirectoryName(string fileName)
{
var pathSeparators = new[] { Path.DirectorySeparatorChar, AppSettings.PosixPathSeparator };
var pos = fileName.LastIndexOfAny(pathSeparators);
if (pos != -1)
{
fileName = fileName.Substring(0, pos);
if (fileName.Length == 2 && char.IsLetter(fileName[0]) && fileName[1] == Path.VolumeSeparatorChar)
return "";
}
return fileName;
}
public static bool Equal(string path1, string path2)
{
path1 = Path.GetFullPath(path1).TrimEnd('\\');
path2 = Path.GetFullPath(path2).TrimEnd('\\');
StringComparison comprasion = EnvUtils.RunningOnUnix()
? StringComparison.InvariantCulture
: StringComparison.InvariantCultureIgnoreCase;
return String.Compare(path1, path2, comprasion) == 0;
}
private class PathEqualityComparer : IEqualityComparer<string>
{
public bool Equals(string path1, string path2)
{
return Equal(path1, path2);
}
public int GetHashCode(string path)
{
path = Path.GetFullPath(path).TrimEnd('\\');
if (!EnvUtils.RunningOnUnix())
path = path.ToLower();
return path.GetHashCode();
}
}
public static IEqualityComparer<string> CreatePathEqualityComparer()
{
return new PathEqualityComparer();
}
}
}