This repository has been archived by the owner on Apr 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
NuGetCacheSentinel.cs
106 lines (88 loc) · 3.23 KB
/
NuGetCacheSentinel.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// 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.IO;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.Extensions.EnvironmentAbstractions;
using NuGet.Configuration;
namespace Microsoft.DotNet.Configurer
{
public class NuGetCacheSentinel : INuGetCacheSentinel
{
public static readonly string SENTINEL = $"{Product.Version}.dotnetSentinel";
public static readonly string INPROGRESS_SENTINEL = $"{Product.Version}.inprogress.dotnetSentinel";
private readonly IFile _file;
private string _nugetCachePath;
private string NuGetCachePath
{
get
{
if (string.IsNullOrEmpty(_nugetCachePath))
{
_nugetCachePath = NuGetPathContext.Create(new NullSettings()).UserPackageFolder;
}
return _nugetCachePath;
}
}
private string SentinelPath => Path.Combine(NuGetCachePath, SENTINEL);
private string InProgressSentinelPath => Path.Combine(NuGetCachePath, INPROGRESS_SENTINEL);
private Stream InProgressSentinel { get; set; }
public NuGetCacheSentinel() : this(string.Empty, FileSystemWrapper.Default.File)
{
}
internal NuGetCacheSentinel(string nugetCachePath, IFile file)
{
_file = file;
_nugetCachePath = nugetCachePath;
SetInProgressSentinel();
}
public bool InProgressSentinelAlreadyExists()
{
return CouldNotGetAHandleToTheInProgressSentinel();
}
public bool Exists()
{
return _file.Exists(SentinelPath);
}
public void CreateIfNotExists()
{
if (!Exists())
{
_file.CreateEmptyFile(SentinelPath);
}
}
private bool CouldNotGetAHandleToTheInProgressSentinel()
{
return InProgressSentinel == null;
}
private void SetInProgressSentinel()
{
try
{
if(!Directory.Exists(NuGetCachePath))
{
Directory.CreateDirectory(NuGetCachePath);
}
// open an exclusive handle to the in-progress sentinel and mark it for delete on close.
// we open with exclusive FileShare.None access to indicate that the operation is in progress.
// buffer size is minimum since we won't be reading or writing from the file.
// delete on close is to indicate that the operation is no longer in progress when we dispose
// this.
InProgressSentinel = _file.OpenFile(
InProgressSentinelPath,
FileMode.OpenOrCreate,
FileAccess.ReadWrite,
FileShare.None,
1,
FileOptions.DeleteOnClose);
}
catch { }
}
public void Dispose()
{
if (InProgressSentinel != null)
{
InProgressSentinel.Dispose();
}
}
}
}