forked from dotnet/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UserLevelCacheWriter.cs
73 lines (63 loc) · 2.33 KB
/
UserLevelCacheWriter.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
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.Extensions.EnvironmentAbstractions;
namespace Microsoft.DotNet.Configurer
{
public class UserLevelCacheWriter : IUserLevelCacheWriter
{
private readonly IFile _file;
private readonly IDirectory _directory;
private string _dotnetUserProfileFolderPath;
public UserLevelCacheWriter(CliFolderPathCalculator cliFolderPathCalculator) :
this(
CliFolderPathCalculator.DotnetUserProfileFolderPath,
FileSystemWrapper.Default.File,
FileSystemWrapper.Default.Directory)
{
}
public string RunWithCache(string cacheKey, Func<string> getValueToCache)
{
var cacheFilepath = GetCacheFilePath(cacheKey);
try
{
if (!_file.Exists(cacheFilepath))
{
if (!_directory.Exists(_dotnetUserProfileFolderPath))
{
_directory.CreateDirectory(_dotnetUserProfileFolderPath);
}
var runResult = getValueToCache();
_file.WriteAllText(cacheFilepath, runResult);
return runResult;
}
else
{
return _file.ReadAllText(cacheFilepath);
}
}
catch (Exception ex)
{
if (ex is UnauthorizedAccessException
|| ex is PathTooLongException
|| ex is IOException)
{
return getValueToCache();
}
throw;
}
}
internal UserLevelCacheWriter(string dotnetUserProfileFolderPath, IFile file, IDirectory directory)
{
_file = file;
_directory = directory;
_dotnetUserProfileFolderPath = dotnetUserProfileFolderPath;
}
private string GetCacheFilePath(string cacheKey)
{
return Path.Combine(_dotnetUserProfileFolderPath, $"{Product.Version}_{cacheKey}.dotnetUserLevelCache");
}
}
}