forked from dotnet/sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDotNetWatcher.cs
More file actions
153 lines (124 loc) · 6.66 KB
/
DotNetWatcher.cs
File metadata and controls
153 lines (124 loc) · 6.66 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Globalization;
using Microsoft.Build.Graph;
using Microsoft.Extensions.Logging;
namespace Microsoft.DotNet.Watch;
internal static class DotNetWatcher
{
public static async Task WatchAsync(DotNetWatchContext context, CancellationToken shutdownCancellationToken)
{
var cancelledTaskSource = new TaskCompletionSource();
shutdownCancellationToken.Register(state => ((TaskCompletionSource)state!).TrySetResult(),
cancelledTaskSource);
if (context.EnvironmentOptions.SuppressMSBuildIncrementalism)
{
context.Logger.LogDebug("MSBuild incremental optimizations suppressed.");
}
var environmentBuilder = new Dictionary<string, string>();
ChangedFile? changedFile = null;
var buildEvaluator = new BuildEvaluator(context);
for (var iteration = 0;;iteration++)
{
if (await buildEvaluator.EvaluateAsync(changedFile, shutdownCancellationToken) is not { } evaluationResult)
{
context.Logger.LogError("Failed to find a list of files to watch");
return;
}
StaticFileHandler? staticFileHandler;
ProjectGraphNode? projectRootNode;
if (evaluationResult.ProjectGraph != null)
{
projectRootNode = evaluationResult.ProjectGraph.Graph.GraphRoots.Single();
staticFileHandler = new StaticFileHandler(context.Logger, evaluationResult.ProjectGraph, context.BrowserRefreshServerFactory);
}
else
{
context.Logger.LogDebug("Unable to determine if this project is a webapp.");
projectRootNode = null;
staticFileHandler = null;
}
var processSpec = new ProcessSpec
{
Executable = context.EnvironmentOptions.GetMuxerPath(),
WorkingDirectory = context.EnvironmentOptions.WorkingDirectory,
IsUserApplication = true,
Arguments = buildEvaluator.GetProcessArguments(iteration),
EnvironmentVariables =
{
[EnvironmentVariables.Names.DotnetWatch] = "1",
[EnvironmentVariables.Names.DotnetWatchIteration] = (iteration + 1).ToString(CultureInfo.InvariantCulture),
}
};
var browserRefreshServer = projectRootNode != null && HotReloadAppModel.InferFromProject(context, projectRootNode) is WebApplicationAppModel webAppModel
? await context.BrowserRefreshServerFactory.GetOrCreateBrowserRefreshServerAsync(projectRootNode, webAppModel, shutdownCancellationToken)
: null;
browserRefreshServer?.ConfigureLaunchEnvironment(environmentBuilder, enableHotReload: false);
Action<OutputLine>? outputObserver = null;
if (projectRootNode != null)
{
Debug.Assert(context.MainProjectOptions != null);
outputObserver = context.BrowserLauncher.TryGetBrowserLaunchOutputObserver(projectRootNode, context.MainProjectOptions, browserRefreshServer, shutdownCancellationToken);
}
processSpec.RedirectOutput(outputObserver, context.ProcessOutputReporter, context.EnvironmentOptions, projectRootNode?.GetDisplayName() ?? "");
foreach (var (name, value) in environmentBuilder)
{
processSpec.EnvironmentVariables.Add(name, value);
}
// Reset for next run
buildEvaluator.RequiresRevaluation = false;
if (shutdownCancellationToken.IsCancellationRequested)
{
return;
}
using var currentRunCancellationSource = new CancellationTokenSource();
using var combinedCancellationSource = CancellationTokenSource.CreateLinkedTokenSource(shutdownCancellationToken, currentRunCancellationSource.Token);
using var fileSetWatcher = new FileWatcher(context.Logger, context.EnvironmentOptions);
fileSetWatcher.WatchContainingDirectories(evaluationResult.Files.Keys, includeSubdirectories: true);
var processTask = context.ProcessRunner.RunAsync(processSpec, context.Logger, launchResult: null, combinedCancellationSource.Token);
Task<ChangedFile?> fileSetTask;
Task finishedTask;
context.Logger.Log(MessageDescriptor.WaitingForChanges);
while (true)
{
fileSetTask = fileSetWatcher.WaitForFileChangeAsync(evaluationResult.Files, startedWatching: null, combinedCancellationSource.Token);
finishedTask = await Task.WhenAny(processTask, fileSetTask, cancelledTaskSource.Task);
if (staticFileHandler != null && finishedTask == fileSetTask && fileSetTask.Result.HasValue)
{
if (await staticFileHandler.HandleFileChangesAsync([fileSetTask.Result.Value], combinedCancellationSource.Token))
{
// We're able to handle the file change event without doing a full-rebuild.
continue;
}
}
break;
}
// Regardless of the which task finished first, make sure everything is cancelled
// and wait for dotnet to exit. We don't want orphan processes
currentRunCancellationSource.Cancel();
await Task.WhenAll(processTask, fileSetTask);
if (finishedTask == cancelledTaskSource.Task || shutdownCancellationToken.IsCancellationRequested)
{
return;
}
if (finishedTask == processTask)
{
// Process exited. Redo evalulation
buildEvaluator.RequiresRevaluation = true;
// Now wait for a file to change before restarting process
changedFile = await fileSetWatcher.WaitForFileChangeAsync(
evaluationResult.Files,
startedWatching: () => context.Logger.Log(MessageDescriptor.WaitingForFileChangeBeforeRestarting),
shutdownCancellationToken);
}
else
{
Debug.Assert(finishedTask == fileSetTask);
changedFile = fileSetTask.Result;
Debug.Assert(changedFile != null, "ChangedFile should only be null when cancelled");
context.Logger.LogInformation("File changed: {Path}", changedFile.Value.Item.FilePath);
}
}
}
}