1 // Copyright (c) .NET Foundation. All rights reserved.
2 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3 
4 using System;
5 using System.Collections.Generic;
6 using System.IO;
7 using System.Runtime.CompilerServices;
8 
9 namespace Microsoft.NuGet.Build.Tasks.Tests.Helpers
10 {
11     public sealed class TempRoot : IDisposable
12     {
13         private readonly List<IDisposable> _temps = new List<IDisposable>();
14         public readonly string Root;
15 
TempRoot()16         public TempRoot()
17         {
18             Root = Path.Combine(Path.GetTempPath(), "NuGetBuildTests", Guid.NewGuid().ToString());
19 
20             Directory.CreateDirectory(Root);
21         }
22 
Dispose()23         public void Dispose()
24         {
25             if (_temps != null)
26             {
27                 DisposeAll(_temps);
28                 _temps.Clear();
29             }
30         }
31 
DisposeAll(IEnumerable<IDisposable> temps)32         private static void DisposeAll(IEnumerable<IDisposable> temps)
33         {
34             foreach (var temp in temps)
35             {
36                 try
37                 {
38                     if (temp != null)
39                     {
40                         temp.Dispose();
41                     }
42                 }
43                 catch
44                 {
45                     // ignore
46                 }
47             }
48         }
49 
CreateDirectory()50         public DisposableDirectory CreateDirectory()
51         {
52             var dir = new DisposableDirectory(this);
53             _temps.Add(dir);
54             return dir;
55         }
56 
CreateFile(TempRoot root, string prefix = null, string extension = null, string directory = null, [CallerFilePath]string callerSourcePath = null, [CallerLineNumber]int callerLineNumber = 0)57         public TempFile CreateFile(TempRoot root, string prefix = null, string extension = null, string directory = null, [CallerFilePath]string callerSourcePath = null, [CallerLineNumber]int callerLineNumber = 0)
58         {
59             return AddFile(new DisposableFile(root, prefix, extension, directory, callerSourcePath, callerLineNumber));
60         }
61 
AddFile(DisposableFile file)62         public DisposableFile AddFile(DisposableFile file)
63         {
64             _temps.Add(file);
65             return file;
66         }
67 
CreateStream(string fullPath)68         internal static void CreateStream(string fullPath)
69         {
70             using (var file = new FileStream(fullPath, FileMode.CreateNew)) { }
71         }
72     }
73 }
74