OSDN Git Service

AppliStation-All,長音表記の変更(-er/-orで終わる語には長音記号を付ける)
[applistation/AppliStation.git] / na-get-lib / NaGet / Utils.cs
1 using System;\r
2 using System.Collections.Generic;\r
3 using System.IO;\r
4 using System.Text;\r
5 using System.Globalization;\r
6 using System.Security.Principal;\r
7 using System.Security.AccessControl;\r
8 using System.Reflection;\r
9 using System.Diagnostics;\r
10 using Microsoft.Win32;\r
11 \r
12 namespace NaGet\r
13 {\r
14 \r
15         /// <summary>\r
16         /// 雑多な便利メソッドを集めたクラス\r
17         /// </summary>\r
18         public sealed class Utils\r
19         {\r
20                 /// <summary>\r
21                 /// 呼び出し禁止\r
22                 /// </summary>\r
23                 private Utils()\r
24                 {\r
25                 }\r
26                 \r
27                 #region 汎用的なオブジェクト操作メソッド\r
28                 \r
29                 /// <summary>\r
30                 /// オブジェクトのフィールドをコピーしてクローン化する\r
31                 /// </summary>\r
32                 /// <param name="from">コピー元</param>\r
33                 /// <param name="target">コピー先。コピー元のクラスと同一か継承している型でなければならない</param>\r
34                 public static void FieldCopy<T,U>(T from, ref U target) where U : T\r
35                 {\r
36                         foreach(FieldInfo member in typeof(T).GetFields()) {\r
37                                 try {\r
38                                         member.SetValue(target, member.GetValue(from));\r
39                                 } catch (FieldAccessException) {} // アクセス不能は無視\r
40                         }\r
41                 }\r
42                 \r
43                 #endregion\r
44                 \r
45                 #region リスト関連関数\r
46                 \r
47                 /// <summary>\r
48                 /// イテレータを結合して、返す\r
49                 /// </summary>\r
50                 /// <param name="enus">元となる複数のイテレータ</param>\r
51                 /// <returns>結合されたイテレータ</returns>\r
52                 public static IEnumerable<T> MergeEnumerable<T>(params IEnumerable<T>[] enus)\r
53                 {\r
54                         foreach (IEnumerable<T> enu in enus) {\r
55                                 if (enu == null) continue;\r
56                                 \r
57                                 foreach (T elem in enu) {\r
58                                         yield return elem;\r
59                                 }\r
60                         }\r
61                 }\r
62 \r
63                 /// <summary>\r
64                 /// イテレータを結合して、返す\r
65                 /// </summary>\r
66                 /// <param name="enus">元となる複数のイテレータ</param>\r
67                 /// <returns>結合されたイテレータ</returns>\r
68                 public static IEnumerable<T> MergeEnumerable<T>(params IEnumerator<T>[] enus)\r
69                 {\r
70                         foreach (IEnumerator<T> enu in enus) {\r
71                                 if (enu == null) continue;\r
72                                 \r
73                                 try {\r
74                                         while (enu.MoveNext()) {\r
75                                                 yield return enu.Current;\r
76                                         }\r
77                                 } finally {\r
78                                         enu.Dispose();\r
79                                 }\r
80                         }\r
81                 }\r
82                 \r
83                 /// <summary>\r
84                 /// イテレータを結合して、Listとして返す\r
85                 /// </summary>\r
86                 /// <param name="enus">元となる複数のイテレータ</param>\r
87                 /// <returns>結合されたイテレータ</returns>\r
88                 public static List<T> MergeList<T>(params IEnumerable<T>[] enus)\r
89                 {\r
90                         List<T> list = new List<T>();\r
91                         \r
92                         foreach (IEnumerable<T> enu in enus) {\r
93                                 if (enu == null) continue;\r
94                         \r
95                                 list.AddRange(enu);\r
96                         }\r
97                         return list;\r
98                 }\r
99                 \r
100                 /// <summary>\r
101                 /// イテレータを配列に効率的に変換する\r
102                 /// </summary>\r
103                 /// <remarks>与えられる型が具体的にわかっているならば、それに特化した手続きをとる方が好ましい</remarks>\r
104                 /// <param name="enu">元となるイテレータ</param>\r
105                 /// <returns>変換された配列</returns>\r
106                 public static T[] IEnumerable2Array<T>(IEnumerable<T> enu) {\r
107                         T[] retval = enu as T[];\r
108                         \r
109                         if (retval == null) {\r
110                                 List<T> list = enu as List<T>;\r
111                                 if (list == null) {\r
112                                         list = new List<T>(enu);\r
113                                 }\r
114                                 retval = list.ToArray();\r
115                         }\r
116                         \r
117                         return retval;\r
118                 }\r
119                 \r
120                 /// <summary>\r
121                 /// リストに対して指定した2つの要素の位置を入れ替える\r
122                 /// </summary>\r
123                 /// <param name="list">操作対象のリスト</param>\r
124                 /// <param name="indexA">位置</param>\r
125                 /// <param name="indexB">位置</param>\r
126                 public static void ListSwap(System.Collections.IList list, int indexA, int indexB)\r
127                 {\r
128                         if ((indexA < 0) || (list.Count <= indexA) || (indexB < 0) || (list.Count <= indexB)) {\r
129                                 throw new IndexOutOfRangeException();\r
130                         } else if (indexA != indexB) {\r
131                                 object temp = list[indexA];\r
132                                 list[indexA] = list[indexB];\r
133                                 list[indexB] = temp;\r
134                         }\r
135                 }\r
136                 \r
137                 #endregion\r
138                                 \r
139                 #region ファイル情報関連ユーテイリティ関数\r
140                 \r
141                 /// <summary>\r
142                 /// パス変数に指定のフォルダーを追加する\r
143                 /// </summary>\r
144                 /// <param name="dir">追加するフォルダー</param>\r
145                 public static void AddDirectoryToPath(string dir)\r
146                 {\r
147                         string path = Environment.GetEnvironmentVariable("PATH");\r
148                         \r
149                         if (path.IndexOf(dir) < 0) {\r
150                                 path = dir + Path.PathSeparator + path;\r
151                                 Environment.SetEnvironmentVariable("PATH", path);\r
152                         }\r
153                 }\r
154                 \r
155                 /// <summary>\r
156                 /// バイト単位で表現された容量を接尾語を活用して適切な文字列に変換\r
157                 /// </summary>\r
158                 /// <param name="bytes">バイト単位の容量</param>\r
159                 /// <returns>読みやすい形に直された容量文字列</returns>\r
160         public static string FormatSize(double bytes)\r
161         {\r
162                 string[] units = new string[] {"B", "KB", "MB", "GB", "TB"};\r
163                 \r
164                 double size = bytes;\r
165                 int i;\r
166                 for (i = 0; size >= 1024 && i < units.Length-1 ; i++) {\r
167                         size /= 1024.0;\r
168                 }\r
169                 \r
170                 return string.Format("{0:F2}{1}", size, units[i]);\r
171         }\r
172         \r
173         public static string FormatSize(long bytes)\r
174         {\r
175                 return FormatSize((double) bytes);\r
176         }\r
177                 \r
178                 /// <summary>\r
179                 /// URLからそのファイル名を生成する\r
180                 /// </summary>\r
181                 /// <param name="url">対象のurl</param>\r
182                 public static string Url2filename(Uri url)\r
183                 {\r
184                         string filename = Path.GetFileName(System.Web.HttpUtility.UrlDecode(url.ToString(), Encoding.UTF8));\r
185                         \r
186                         int pos;\r
187                         if ((pos = filename.IndexOfAny(Path.GetInvalidFileNameChars())) >= 0) {\r
188                                 // 不正な文字が含まれているならば、それ以降を削除\r
189                                 filename = filename.Substring(0, pos);\r
190                                 // そうしてしまったら文字の内容がまったくなくなってしまったら、ランダムな名に\r
191                                 if (filename.Length == 0) {\r
192                                         filename = Path.GetFileName(Path.GetTempFileName());\r
193                                 }\r
194                         }\r
195                         return filename;\r
196                         //return UrlDecode(Path.GetFileName(url), Encoding.UTF8);\r
197                 }\r
198                 \r
199                 /// <summary>\r
200                 /// 再帰的にファイルの属性を指定します。強制的にフォルダーの再帰削除の前に読み込み専用属性を消すのに使います。\r
201                 /// </summary>\r
202                 /// <param name="path">設定するフォルダー</param>\r
203                 /// <param name="attr">設定する属性値</param>\r
204                 public static void SetAttributeRecursive(string path, FileAttributes attr)\r
205                 {\r
206                         // 自分自身の属性を変更\r
207                         File.SetAttributes(path, attr);\r
208                         \r
209                         // 子ファイルの属性変更\r
210                         foreach (string file in Directory.GetFiles(path)) {\r
211                                 File.SetAttributes(file, attr);\r
212                         }\r
213                         \r
214                         // 子フォルダーを再帰的に属性変更\r
215                         foreach (string file in Directory.GetDirectories(path)) {\r
216                                 SetAttributeRecursive(file, attr);\r
217                         }\r
218                 }\r
219                 \r
220                 /// <summary>\r
221                 /// 再帰的にファイルのアクセス権限(ユーザ権限など)を設定します\r
222                 /// </summary>\r
223                 /// <param name="path">設定するフォルダー</param>\r
224                 /// <param name="filesec">変更先権限</param>\r
225                 public static void SetAccessControlRecursive(string path, FileSecurity filesec)\r
226                 {\r
227                         // 自分自身の権限を変更\r
228                         File.SetAccessControl(path, filesec);\r
229                         \r
230                         // 子ファイルの権限を変更\r
231                         foreach (string file in Directory.GetFiles(path)) {\r
232                                 File.SetAccessControl(file, filesec);\r
233                         }\r
234                         \r
235                         // 子フォルダーを再帰的に権限変更\r
236                         foreach (string file in Directory.GetDirectories(path)) {\r
237                                 SetAccessControlRecursive(file, filesec);\r
238                         }\r
239                 }\r
240                 \r
241                 /// <summary>\r
242                 /// ファイルまたはフォルダーの容量を算出して返す\r
243                 /// </summary>\r
244                 /// <param name="path">\r
245                 /// 対象ファイル及びフォルダーのパス\r
246                 /// </param>\r
247                 /// <returns>\r
248                 /// 計算された容量(バイト単位)\r
249                 /// </returns>\r
250                 public static ulong GetFileSize(string path)\r
251                 {\r
252                         return ((File.GetAttributes(path) & FileAttributes.Directory) != 0)?\r
253                                 GetDirectoryFileSize(new DirectoryInfo(path)) : ((ulong) (new FileInfo(path)).Length);\r
254                 }\r
255                 \r
256                 /// <summary>\r
257                 /// フォルダーの容量を算出して返す\r
258                 /// </summary>\r
259                 /// <param name="dirInfo">\r
260                 /// 対象フォルダー\r
261                 /// </param>\r
262                 /// <returns>\r
263                 /// 計算された容量(バイト単位)\r
264                 /// </returns>\r
265                 public static ulong GetDirectoryFileSize(DirectoryInfo dirInfo)\r
266                 {\r
267                         ulong size = 0;\r
268                         foreach (FileInfo child in dirInfo.GetFiles("*", SearchOption.AllDirectories)) {\r
269                                 size += (ulong) child.Length;\r
270                         }\r
271                         return size;\r
272                 }\r
273                                 \r
274                 /// <summary>\r
275                 /// ワイルドカードを展開したファイルパス文字列を作り出す。\r
276                 /// 戻り値のそれぞれの文字列はフルパスとなる。\r
277                 /// </summary>\r
278                 /// <param name="baseDir">ベース(基点)のディレクトリ</param>\r
279                 /// <param name="pattern">ワイルドカードパターン</param>\r
280                 /// <returns>展開したファイルパス</returns>\r
281                 public static string[] ExtendWildcardFile(string baseDir, string pattern)\r
282                 {\r
283                         if (pattern.IndexOfAny(new char[]{'*','?'}) < 0) {\r
284                                 return new string[]{Path.Combine(baseDir, pattern)}; // ワイルドカードがなければそのまま返す\r
285                         }\r
286 \r
287                         string[] pathArray = pattern.Split(Path.DirectorySeparatorChar);\r
288                         List<string> extended = new List<string>();\r
289                         try {\r
290                                 if (pathArray.Length == 1) {\r
291                                         extended.AddRange(Directory.GetFiles(baseDir, pathArray[0], SearchOption.TopDirectoryOnly));\r
292                                         extended.AddRange(Directory.GetDirectories(baseDir, pathArray[0], SearchOption.TopDirectoryOnly));\r
293                                 } else { // pathArray.Length > 1\r
294                                         string subPattern = string.Join(Path.DirectorySeparatorChar.ToString(), pathArray, 1, pathArray.Length-1);\r
295                                         \r
296                                         foreach (string subDir in Directory.GetDirectories(baseDir, pathArray[0], SearchOption.TopDirectoryOnly)) {\r
297                                                 // 再帰的に追加してゆく\r
298                                                 extended.AddRange(ExtendWildcardFile(subDir, subPattern));\r
299                                         }\r
300                                 }\r
301                         } catch (UnauthorizedAccessException) {\r
302                         }\r
303                         \r
304                         // 存在しないパスは消去する\r
305                         extended.RemoveAll(\r
306                                 delegate(string path) {\r
307                                         return ! File.Exists(path);\r
308                                 }\r
309                         );\r
310                         \r
311                         return extended.ToArray();\r
312                 }\r
313                 \r
314                 /// <summary>\r
315                 /// パスをパス区切り文字列ごとに分割した配列を返す\r
316                 /// </summary>\r
317                 /// <param name="path">パス文字列。相対・絶対は区別しない</param>\r
318                 /// <returns>フォルダー名ごとに分けられた文字列配列</returns>\r
319                 private static string[] splitPath(string path)\r
320                 {\r
321                         return path.Split(new char[]{Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar});\r
322                 }\r
323                 \r
324                 /// <summary>\r
325                 /// パスがフォルダーのとき、最後がパスセパレータで終了するようにする。\r
326                 /// </summary>\r
327                 /// <param name="path">パス</param>\r
328                 /// <returns>処理されたパス</returns>\r
329                 private static string fixLastPathCharForDirectory(string path)\r
330                 {\r
331                         string fixedPath = path;\r
332                         if (Directory.Exists(path) && path[path.Length-1] != Path.DirectorySeparatorChar) {\r
333                                 fixedPath += Path.DirectorySeparatorChar;\r
334                         }\r
335                         return fixedPath;\r
336                 }\r
337                 \r
338                 /// <summary>\r
339                 /// 絶対パスを相対パスに変換して返します。\r
340                 /// </summary>\r
341                 /// <param name="baseDirectoryPath">相対パスの基準のフォルダー</param>\r
342                 /// <param name="absPath">絶対パス</param>\r
343                 /// <returns><code>absPath</code>の絶対パス表現</returns>\r
344                 public static string GetRelativePath(string baseDirectoryPath, string absPath)\r
345                 {\r
346                         Uri baseuri     = new Uri(fixLastPathCharForDirectory(baseDirectoryPath));\r
347                         Uri absuri      = new Uri(fixLastPathCharForDirectory(absPath));\r
348                         \r
349                         string relative = baseuri.MakeRelativeUri(absuri).ToString();\r
350                         relative = System.Web.HttpUtility.UrlDecode(relative);\r
351                         relative = relative.Replace('/', Path.DirectorySeparatorChar);\r
352                         \r
353                         return relative;\r
354                 }\r
355                 \r
356                 /// <summary>\r
357                 /// 相対パスに含まれている".."などを消去する\r
358                 /// </summary>\r
359                 /// <param name="aPath"></param>\r
360                 /// <returns></returns>\r
361                 public static string GetDotsRemovedPath(string aPath)\r
362                 {\r
363                         string[] folders = splitPath(aPath);\r
364                         List<string> newFolders = new List<string>();\r
365                         \r
366                         foreach (string fol in folders) {\r
367                                 if (fol == ".") {\r
368                                         // 無視\r
369                                 } else if (fol == "..") {\r
370                                         // 一つ前のフォルダーを消す\r
371                                         newFolders.RemoveAt(newFolders.Count-1);\r
372                                 } else {\r
373                                         newFolders.Add(fol);\r
374                                 }\r
375                         }\r
376                         \r
377                         return string.Join(Path.DirectorySeparatorChar.ToString(), newFolders.ToArray());\r
378                 }\r
379                 \r
380                 #endregion\r
381                 \r
382                 #region シリアル化関連\r
383                 \r
384                 /// <summary>\r
385                 /// XMLでシリアル化したオブジェクトのXMLファイルを読み込み、デシリアル化したオブジェクトを取得する\r
386                 /// </summary>\r
387                 /// <param name="path">XMLファイルのパス</param>\r
388                 /// <returns>デシリアル化されたオブジェクト</returns>\r
389                 public static T GetDeserializedObject<T>(string path)\r
390                 {\r
391                         T retVal = default(T);\r
392                         using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) {\r
393                                 System.Xml.Serialization.XmlSerializer sr = new System.Xml.Serialization.XmlSerializer(typeof(T));\r
394                                 retVal = (T) sr.Deserialize(fs);\r
395                         }\r
396                         return retVal;\r
397                 }\r
398                 \r
399                 /// <summary>\r
400                 /// オブジェクトをXMLでシリアル化してファイルに書き込む\r
401                 /// </summary>\r
402                 /// <param name="path">XMLファイルのパス</param>\r
403                 /// <param name="obj">シリアル化する対象のオブジェクト</param>\r
404                 public static void PutSerializeObject<T>(string path, T obj)\r
405                 {\r
406                         using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write)) {\r
407                                 System.Xml.Serialization.XmlSerializer sr = new System.Xml.Serialization.XmlSerializer(typeof(T));\r
408                                 sr.Serialize(fs, obj);\r
409                         }\r
410                 }\r
411                 \r
412                 #endregion\r
413                 \r
414                 #region 権限関連関数群\r
415                 \r
416                 /// <summary>\r
417                 /// 現在のユーザがAdministrators権限を持っているか否かを返す。\r
418                 /// </summary>\r
419                 /// <remarks>UAC有効時には権限昇格後になってtrueを返すようになります</remarks>\r
420                 public static bool IsAdministrators()\r
421                 {\r
422                         // 現在の Windows ユーザーを現在のスレッドのプリンシパルに反映する\r
423                         AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal );\r
424                         IPrincipal prin = System.Threading.Thread.CurrentPrincipal;\r
425                         return prin.IsInRole(@"BUILTIN\Administrators");\r
426                 }\r
427                 \r
428                 /// <summary>\r
429                 /// 現在のPCがUACが有効になっているか否かを返す。\r
430                 /// レジストリのHKLM\SOFTWARE¥Microsoft¥Windows¥CurrentVersion¥Policies¥System\EnableLUAの値を見る。\r
431                 /// </summary>\r
432                 /// <returns>UACが有効ならばtrue</returns>\r
433                 public static bool IsUACEnabled()\r
434                 {\r
435                         try {\r
436                                 using(RegistryKey key = Registry.LocalMachine.CreateSubKey(@"SOFTWARE¥Microsoft¥Windows¥CurrentVersion¥Policies¥System")) {\r
437                                         return ((int) key.GetValue("EnableLUA", 0)) == 1;\r
438                                 }\r
439                         } catch (Exception) {\r
440                                 return false;\r
441                         }\r
442                 }\r
443                 \r
444                 #endregion\r
445 \r
446                 #region プロセス関連便利メソッド群\r
447                 \r
448                 /// <summary>\r
449                 /// プロセスに出力をリダイレクトした上で実行\r
450                 /// </summary>\r
451                 /// <param name="procInfo">プロセス起動情報</param>\r
452                 /// <param name="outputReceived">標準出力用リスナ(null可)</param>\r
453                 /// <param name="errorReceived">エラー出力用リスナ(null可)</param>\r
454                 /// <returns>実行プロセス</returns>\r
455                 public static Process ProcessStartWithOutputCapture(ProcessStartInfo procInfo,\r
456                                                   DataReceivedEventHandler outputReceived,\r
457                                                   DataReceivedEventHandler errorReceived)\r
458                 {\r
459                         if (outputReceived != null) {\r
460                                 procInfo.RedirectStandardOutput = true;\r
461                         }\r
462                         if (errorReceived != null) {\r
463                                 procInfo.RedirectStandardError = true;\r
464                         }\r
465                         procInfo.UseShellExecute = false;\r
466                         \r
467                         Process hProcess = Process.Start(procInfo);\r
468                         if (outputReceived != null) {\r
469                                 hProcess.OutputDataReceived += outputReceived;\r
470                                 hProcess.BeginOutputReadLine();\r
471                         }\r
472                         if (errorReceived != null) {\r
473                                 hProcess.ErrorDataReceived += errorReceived;    \r
474                                 hProcess.BeginErrorReadLine();\r
475                         }\r
476                         \r
477                         return hProcess;\r
478                 }\r
479                 \r
480                 \r
481                 /// <summary>\r
482                 /// プロセスに出力をリダイレクトした上で実行\r
483                 /// </summary>\r
484                 /// <param name="procInfo">プロセス起動情報</param>\r
485                 /// <param name="outputReceived">標準出力用リスナ(null可)</param>\r
486                 /// <param name="errorReceived">エラー出力用リスナ(null可)</param>\r
487                 /// <returns>実行プロセス</returns>\r
488                 public static Process ProcessStartWithOutputCapture(ProcessStartInfo procInfo,\r
489                                                   EventHandler<AnyDataEventArgs<string>> outputReceived,\r
490                                                   EventHandler<AnyDataEventArgs<string>> errorReceived)\r
491                 {\r
492                         return ProcessStartWithOutputCapture(procInfo,\r
493                                                              ConvertToDataReceivedEventHandler(outputReceived),\r
494                                                              ConvertToDataReceivedEventHandler(errorReceived));\r
495                 }\r
496                 \r
497                 public static DataReceivedEventHandler ConvertToDataReceivedEventHandler(EventHandler<AnyDataEventArgs<string>> handler)\r
498                 {\r
499                         if (handler == null) return null;\r
500                         return delegate (object sender, DataReceivedEventArgs e) {\r
501                                 AnyDataEventArgs<string> args = new AnyDataEventArgs<string>(e.Data);\r
502                                 handler.Invoke(sender, args);\r
503                         };\r
504                 }\r
505                 \r
506                 #endregion\r
507 \r
508                 #region イベント情報\r
509                 \r
510                 /// <summary>\r
511                 /// 任意データのイベント情報を表現するクラス\r
512                 /// </summary>\r
513                 public class AnyDataEventArgs<T> : EventArgs\r
514                 {\r
515                         /// <summary>\r
516                         /// データ\r
517                         /// </summary>\r
518                         T data;\r
519                         \r
520                         public AnyDataEventArgs(T data)\r
521                         {\r
522                                 this.data = data;\r
523                         }\r
524                         \r
525                         /// <summary>\r
526                         /// データを返す\r
527                         /// </summary>\r
528                         public T Data {\r
529                                 get { return data; }\r
530                         }\r
531                 }\r
532 \r
533                 #endregion\r
534         }\r
535 }\r