/
HostInteraction.cs
91 lines (74 loc) · 3.31 KB
/
HostInteraction.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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using EnvDTE;
using Microsoft.Web.LibraryManager.Contracts;
namespace Microsoft.Web.LibraryManager.Vsix
{
public class HostInteraction : IHostInteraction
{
public HostInteraction(string configFilePath)
{
string cwd = Path.GetDirectoryName(configFilePath);
WorkingDirectory = cwd;
}
public string WorkingDirectory { get; }
public string CacheDirectory => Constants.CacheFolder;
public ILogger Logger { get; } = new Logger();
public async Task<bool> WriteFileAsync(string path, Func<Stream> content, ILibraryInstallationState state, CancellationToken cancellationToken)
{
var absolutePath = new FileInfo(Path.Combine(WorkingDirectory, path));
if (absolutePath.Exists)
return true;
if (!absolutePath.FullName.StartsWith(WorkingDirectory))
throw new UnauthorizedAccessException();
absolutePath.Directory.Create();
using (Stream stream = content.Invoke())
{
if (stream == null)
return false;
VsHelpers.CheckFileOutOfSourceControl(absolutePath.FullName);
using (FileStream writer = File.Create(absolutePath.FullName, 4096, FileOptions.Asynchronous))
{
if (stream.CanSeek)
{
stream.Seek(0, SeekOrigin.Begin);
}
await stream.CopyToAsync(writer, 8192, cancellationToken).ConfigureAwait(false);
}
}
Logger.Log(string.Format(LibraryManager.Resources.Text.FileWrittenToDisk, path.Replace(Path.DirectorySeparatorChar, '/')), LogLevel.Operation);
return true;
}
public void DeleteFiles(params string[] relativeFilePaths)
{
foreach (string relativeFilePath in relativeFilePaths)
{
string absoluteFile = new FileInfo(Path.Combine(WorkingDirectory, relativeFilePath)).FullName;
try
{
ProjectItem item = VsHelpers.DTE.Solution.FindProjectItem(absoluteFile);
Project project = item?.ContainingProject;
if (project != null)
{
item.Delete();
}
else
{
VsHelpers.CheckFileOutOfSourceControl(absoluteFile);
File.Delete(absoluteFile);
}
Logger.Log(string.Format(LibraryManager.Resources.Text.FileDeleted, relativeFilePath.Replace(Path.DirectorySeparatorChar, '/')), LogLevel.Operation);
}
catch (Exception ex)
{
Logger.Log(string.Format(LibraryManager.Resources.Text.FileDeleteFail, relativeFilePath.Replace(Path.DirectorySeparatorChar, '/')), LogLevel.Operation);
Telemetry.TrackException("deletefilefailed", ex);
}
}
}
}
}