-
Notifications
You must be signed in to change notification settings - Fork 495
Expand file tree
/
Copy pathDirectoryHelpers.cs
More file actions
76 lines (63 loc) · 2.71 KB
/
DirectoryHelpers.cs
File metadata and controls
76 lines (63 loc) · 2.71 KB
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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
namespace Amazon.Lambda.TestTool.UnitTests.Utilities;
/// <summary>
/// A set of helper functions for tests.
/// </summary>
public static class DirectoryHelpers
{
/// <summary>
/// Creates a temp directory and copies the working directory to that temp directory.
/// </summary>
/// <param name="workingDirectory">The working directory of the test</param>
/// <returns>A new temp directory with the files from the working directory</returns>
public static string GetTempTestAppDirectory(string workingDirectory)
{
var customTestAppPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".temp", Path.GetRandomFileName());
Directory.CreateDirectory(customTestAppPath);
// Ensure the directory is not read-only
File.SetAttributes(customTestAppPath, FileAttributes.Normal);
var currentDir = new DirectoryInfo(workingDirectory);
CopyDirectory(currentDir, customTestAppPath);
return customTestAppPath;
}
/// <summary>
/// Deletes the provided directory.
/// </summary>
/// <param name="directory">The directory to delete.</param>
public static void CleanUp(string directory)
{
if (!string.IsNullOrEmpty(directory) && Directory.Exists(directory))
{
Directory.Delete(directory, true);
}
}
/// <summary>
/// <see cref="https://docs.microsoft.com/en-us/dotnet/standard/io/how-to-copy-directories"/>
/// </summary>
private static void CopyDirectory(DirectoryInfo dir, string destDirName)
{
if (!dir.Exists)
{
throw new DirectoryNotFoundException($"Source directory does not exist or could not be found: {dir.FullName}");
}
var dirs = dir.GetDirectories();
Directory.CreateDirectory(destDirName);
var files = dir.GetFiles();
foreach (var file in files)
{
var tempPath = Path.Combine(destDirName, file.Name);
file.CopyTo(tempPath, false);
// Ensure copied file is not read-only
File.SetAttributes(tempPath, FileAttributes.Normal);
}
foreach (var subdir in dirs.Where(x => !x.Name.Equals(".git") && !x.Name.Equals(".vs")))
{
var tempPath = Path.Combine(destDirName, subdir.Name);
var subDir = new DirectoryInfo(subdir.FullName);
CopyDirectory(subDir, tempPath);
}
// Ensure the directory itself is not read-only
File.SetAttributes(destDirName, FileAttributes.Normal);
}
}