forked from dotnet/interactive
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUserLevelCacheWriter.cs
More file actions
88 lines (78 loc) · 2.75 KB
/
Copy pathUserLevelCacheWriter.cs
File metadata and controls
88 lines (78 loc) · 2.75 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
77
78
79
80
81
82
83
84
85
86
87
88
// 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;
namespace Microsoft.DotNet.Interactive.Telemetry;
public sealed class UserLevelCacheWriter : IUserLevelCacheWriter
{
private readonly string _productVersion;
private readonly string _dotnetTryUserProfileFolderPath;
private readonly Func<string, bool> _fileExists;
private readonly Func<string, bool> _directoryExists;
private readonly Action<string> _createDirectory;
private readonly Action<string, string> _writeAllText;
private readonly Func<string, string> _readAllText;
public UserLevelCacheWriter(string productVersion) :
this(
productVersion,
Paths.DotnetUserProfileFolderPath,
File.Exists,
Directory.Exists,
path => Directory.CreateDirectory(path),
File.WriteAllText,
File.ReadAllText)
{
}
public UserLevelCacheWriter(
string productVersion,
string dotnetTryUserProfileFolderPath,
Func<string, bool> fileExists,
Func<string, bool> directoryExists,
Action<string> createDirectory,
Action<string, string> writeAllText,
Func<string, string> readAllText)
{
_productVersion = productVersion;
_dotnetTryUserProfileFolderPath = dotnetTryUserProfileFolderPath;
_fileExists = fileExists;
_directoryExists = directoryExists;
_createDirectory = createDirectory;
_writeAllText = writeAllText;
_readAllText = readAllText;
}
public string RunWithCache(string cacheKey, Func<string> getValueToCache)
{
var cacheFilepath = GetCacheFilePath(cacheKey);
try
{
if (!_fileExists(cacheFilepath))
{
if (!_directoryExists(_dotnetTryUserProfileFolderPath))
{
_createDirectory(_dotnetTryUserProfileFolderPath);
}
var runResult = getValueToCache();
_writeAllText(cacheFilepath, runResult);
return runResult;
}
else
{
return _readAllText(cacheFilepath);
}
}
catch (Exception ex)
{
if (ex is UnauthorizedAccessException
|| ex is PathTooLongException
|| ex is IOException)
{
return getValueToCache();
}
throw;
}
}
private string GetCacheFilePath(string cacheKey)
{
return Path.Combine(_dotnetTryUserProfileFolderPath, $"{_productVersion}_{cacheKey}.dotnetTryUserLevelCache");
}
}