Skip to content

Commit b6e3aa8

Browse files
committed
fix(all): keep watch running when a source file is locked
1 parent 8715547 commit b6e3aa8

8 files changed

Lines changed: 396 additions & 46 deletions

File tree

‎src/Fable.Cli/Main.fs‎

Lines changed: 139 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -416,23 +416,35 @@ type ProjectCracked(cliArgs: CliArgs, crackerResponse: CrackerResponse, sourceFi
416416
/// suppress nothing). Only valid once every file has been compiled, since a directive in one
417417
/// file can be what suppresses a warning raised while compiling another.
418418
member _.DirectiveDiagnostics(files: string seq) =
419-
warningSuppression.Value.GetDiagnostics(files)
420-
|> List.map (fun (file, d) ->
421-
let pos: Position =
422-
{
423-
line = d.Line
424-
column = 0
425-
}
419+
files
420+
|> Seq.collect (fun file ->
421+
try
422+
warningSuppression.Value.GetDiagnostics([ file ])
423+
|> List.map (fun (file, d) ->
424+
let pos: Position =
425+
{
426+
line = d.Line
427+
column = 0
428+
}
426429

427-
LogEntry.Make(
428-
Severity.Warning,
429-
d.Message,
430-
fileName = file,
431-
range = SourceLocation.Create(pos, pos, file),
432-
code = d.Code
433-
)
430+
LogEntry.Make(
431+
Severity.Warning,
432+
d.Message,
433+
fileName = file,
434+
range = SourceLocation.Create(pos, pos, file),
435+
code = d.Code
436+
)
437+
)
438+
with (:? IO.IOException | :? UnauthorizedAccessException) as ex ->
439+
[
440+
LogEntry.Make(
441+
Severity.Warning,
442+
$"Could not check the fable-disable directives of this file: {ex.Message}",
443+
fileName = file
444+
)
445+
]
434446
)
435-
|> Array.ofList
447+
|> Array.ofSeq
436448

437449
member _.MapSourceFiles(f) =
438450
ProjectCracked(cliArgs, crackerResponse, Array.map f sourceFiles)
@@ -491,6 +503,36 @@ type FableCompileResult =
491503
|}
492504
>
493505

506+
exception SourceFileReadError of file: string * error: exn
507+
508+
let private tagSourceReadErrors (sourceReader: string -> int * Lazy<string>) (file: string) =
509+
let tag (read: unit -> 'T) =
510+
try
511+
read ()
512+
with
513+
| :? IO.IOException
514+
| :? UnauthorizedAccessException as ex -> raise (SourceFileReadError(file, ex))
515+
516+
let hash, source = tag (fun () -> sourceReader file)
517+
hash, lazy (tag (fun () -> source.Value))
518+
519+
let private (|SourceReadFailure|_|) (ex: exn) =
520+
let pick (ex: exn) =
521+
match ex with
522+
| SourceFileReadError(file, error) -> Some(file, error)
523+
| _ -> None
524+
525+
match ex with
526+
// FCS can parse the files with Array.Parallel.map, which wraps the errors
527+
| :? AggregateException as ex ->
528+
let errors = ex.Flatten().InnerExceptions |> Seq.map pick |> Seq.toList
529+
530+
if List.forall Option.isSome errors then
531+
List.tryHead errors |> Option.flatten
532+
else
533+
None
534+
| ex -> pick ex
535+
494536
type ReplyChannel = AsyncReplyChannel<Result< (* fsharpLogs *) LogEntry[] * FableCompileResult list, exn>>
495537

496538
type FableCompilerMsg =
@@ -596,6 +638,12 @@ and FableCompiler(checker: InteractiveChecker, projCracked: ProjectCracked, fabl
596638
(fun () ->
597639
let filePaths, sourceReader = Fable.Compiler.File.MakeSourceReader sourceFiles
598640

641+
let sourceReader =
642+
if projCracked.CliArgs.IsWatch then
643+
tagSourceReadErrors sourceReader
644+
else
645+
sourceReader
646+
599647
let filePaths, sourceReader = CodeServices.checkerFileNames filePaths sourceReader
600648

601649
checker.ParseAndCheckProject(
@@ -668,7 +716,12 @@ and FableCompiler(checker: InteractiveChecker, projCracked: ProjectCracked, fabl
668716
let rec loop state =
669717
async {
670718
match! agent.Receive() with
671-
| UnexpectedError er -> state.ReplyChannel |> Option.iter (fun ch -> Error er |> ch.Reply)
719+
| UnexpectedError er ->
720+
state.ReplyChannel |> Option.iter (fun ch -> Error er |> ch.Reply)
721+
722+
match er with
723+
| SourceReadFailure _ -> return! loop state
724+
| _ -> ()
672725

673726
| GetFableProject channel ->
674727
channel.Reply(state.FableProj)
@@ -919,6 +972,7 @@ and FableCompiler(checker: InteractiveChecker, projCracked: ProjectCracked, fabl
919972
Log.always $"{Log.newLine}Fable compilation finished in %i{ms}ms{Log.newLine}"
920973

921974
results
975+
| Error(SourceReadFailure(file, ex)) -> raise (SourceFileReadError(file, ex))
922976
| Error e -> e.Message + Log.newLine + e.StackTrace |> Fable.FableError |> raise
923977
}
924978

@@ -1593,6 +1647,7 @@ let private compilationCycle (state: State) (changes: ISet<string>) =
15931647
ErrorLogs = [||]
15941648
OtherLogs = [||]
15951649
ExitCode = exitCode
1650+
SourceReadFailed = false
15961651
|}
15971652
else
15981653
// Optimization for watch mode, if files haven't changed run the process as with --runFast
@@ -1649,15 +1704,27 @@ let private compilationCycle (state: State) (changes: ISet<string>) =
16491704

16501705
setUnfinishedCompilation projCracked true
16511706

1652-
let! fsharpLogs, fableResults =
1653-
fableCompiler.StartCompilation(
1654-
projCracked.SourceFiles, // Make sure to pass the up-to-date source files (with cleared hashes for changed files)
1655-
filesToCompile,
1656-
state.GetPathResolver(?precompiledInfo = projCracked.PrecompiledInfo),
1657-
state.SilentCompilation,
1658-
(fun f -> state.TriggeredByDependency(f, changes)),
1659-
getSignatureDependents
1660-
)
1707+
let! sourceReadFailed, (fsharpLogs, fableResults) =
1708+
async {
1709+
try
1710+
let! results =
1711+
fableCompiler.StartCompilation(
1712+
projCracked.SourceFiles, // Make sure to pass the up-to-date source files (with cleared hashes for changed files)
1713+
filesToCompile,
1714+
state.GetPathResolver(?precompiledInfo = projCracked.PrecompiledInfo),
1715+
state.SilentCompilation,
1716+
(fun f -> state.TriggeredByDependency(f, changes)),
1717+
getSignatureDependents
1718+
)
1719+
1720+
return false, results
1721+
with SourceFileReadError(file, ex) ->
1722+
if Option.isSome state.Watcher then
1723+
let msg = $"Fable will try again to read this file: {ex.Message}"
1724+
return true, ([| LogEntry.MakeError(msg, fileName = file) |], [])
1725+
else
1726+
return ex.Message + Log.newLine + ex.StackTrace |> Fable.FableError |> raise
1727+
}
16611728

16621729
let logs, watchDependencies, signatureDependencies =
16631730
((fsharpLogs, state.WatchDependencies, state.SignatureDependencies), fableResults)
@@ -1683,7 +1750,11 @@ let private compilationCycle (state: State) (changes: ISet<string>) =
16831750
// Every file is compiled by now, so a directive that still hasn't suppressed anything
16841751
// really is unused - checking earlier would flag directives that only ever fire for a
16851752
// warning raised while some later file was being compiled.
1686-
let logs = Array.append logs (projCracked.DirectiveDiagnostics filesToCompile)
1753+
let logs =
1754+
if sourceReadFailed then
1755+
logs
1756+
else
1757+
Array.append logs (projCracked.DirectiveDiagnostics filesToCompile)
16871758

16881759
let state =
16891760
{ state with
@@ -1835,7 +1906,9 @@ let private compilationCycle (state: State) (changes: ISet<string>) =
18351906
{ state with
18361907
ProjectCrackedAndFableCompiler = Some(projCracked, fableCompiler)
18371908
PendingFiles =
1838-
if state.PendingFiles.Length = 0 then
1909+
if sourceReadFailed then
1910+
Set.toArray filesToCompile
1911+
elif state.PendingFiles.Length = 0 then
18391912
errorLogs |> Array.choose (fun l -> l.FileName) |> Array.distinct
18401913
else
18411914
state.PendingFiles
@@ -1847,10 +1920,15 @@ let private compilationCycle (state: State) (changes: ISet<string>) =
18471920
ErrorLogs = errorLogs
18481921
OtherLogs = otherLogs
18491922
ExitCode = exitCode
1923+
SourceReadFailed = sourceReadFailed
18501924
|}
18511925
}
18521926

1853-
type FileWatcherMsg = | Changes of timeStamp: DateTime * changes: ISet<string>
1927+
type FileWatcherMsg =
1928+
| Changes of timeStamp: DateTime * changes: ISet<string>
1929+
| RetryUnreadFiles of cycle: int
1930+
1931+
let private unreadFilesRetryDelayMs = 500
18541932

18551933
let startCompilationAsync state =
18561934
async {
@@ -1869,32 +1947,49 @@ let startCompilationAsync state =
18691947
| Some watcher ->
18701948
let agent =
18711949
MailboxProcessor<FileWatcherMsg>.Start(fun agent ->
1872-
let rec loop state =
1950+
let rec loop (state: State) (cycle: int) =
18731951
async {
1874-
match! agent.Receive() with
1875-
| Changes(timestamp, changes) ->
1876-
match state.Watcher with
1952+
let! msg = agent.Receive()
1953+
1954+
let changes =
1955+
match msg, state.Watcher with
18771956
// Discard changes that may have happened before we restarted the watcher
1878-
| Some w when w.StartedAt < timestamp ->
1879-
// TODO: Get all messages until QueueLength is 0 before starting the compilation cycle?
1880-
if changes.Count > 0 then
1881-
Log.verbose (
1882-
lazy
1883-
$"""Changes:{Log.newLine} {changes |> String.concat $"{Log.newLine} "}"""
1884-
)
1957+
| Changes(timestamp, changes), Some w when w.StartedAt < timestamp ->
1958+
Some changes
1959+
| RetryUnreadFiles failedCycle, Some _ when failedCycle = cycle ->
1960+
Some(HashSet() :> ISet<_>)
1961+
| _ -> None
1962+
1963+
match changes, state.Watcher with
1964+
| Some changes, Some w ->
1965+
// TODO: Get all messages until QueueLength is 0 before starting the compilation cycle?
1966+
if changes.Count > 0 then
1967+
Log.verbose (
1968+
lazy
1969+
$"""Changes:{Log.newLine} {changes |> String.concat $"{Log.newLine} "}"""
1970+
)
1971+
1972+
let! compilationResult = compilationCycle state changes
1973+
1974+
Log.always $"Watching {File.relPathToCurDir w.Watcher.BasePath}"
18851975

1886-
let! compilationResult = compilationCycle state changes
1976+
let cycle = cycle + 1
18871977

1888-
Log.always $"Watching {File.relPathToCurDir w.Watcher.BasePath}"
1978+
if compilationResult.SourceReadFailed then
1979+
async {
1980+
do! Async.Sleep unreadFilesRetryDelayMs
1981+
agent.Post(RetryUnreadFiles cycle)
1982+
}
1983+
|> Async.Start
18891984

1890-
return! loop compilationResult.State
1891-
| _ -> return! loop state
1985+
return! loop compilationResult.State cycle
1986+
| _ -> return! loop state cycle
18921987
}
18931988

18941989
let onChange changes =
18951990
Changes(DateTime.UtcNow, changes) |> agent.Post
18961991

1897-
loop { state with Watcher = Some { watcher with OnChange = onChange } }
1992+
loop { state with Watcher = Some { watcher with OnChange = onChange } } 0
18981993
)
18991994

19001995
// The watcher will remain active so we don't really need the reply channel, but leave loop on fatal errors

‎src/Fable.Compiler/File.fs‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
namespace Fable.Compiler
22

33
open System.IO
4+
open System.Threading
45

56
// TODO: Check the path is actually normalized?
67
type File(normalizedFullPath: string) =
@@ -17,13 +18,30 @@ type File(normalizedFullPath: string) =
1718
// Log.always("File does not exist: " + path)
1819
""
1920

21+
// Editors can hold a source file exclusively for a moment while saving it.
22+
let rec readAllTextWithRetry (retriesLeft: int) (path: string) =
23+
let text =
24+
try
25+
Some(readAllTextNonBlocking path)
26+
with
27+
| :? IOException
28+
| :? System.UnauthorizedAccessException when retriesLeft > 0 -> None
29+
30+
match text with
31+
| Some text -> text
32+
| None ->
33+
Thread.Sleep 100
34+
readAllTextWithRetry (retriesLeft - 1) path
35+
36+
let readSource (path: string) = readAllTextWithRetry 20 path
37+
2038
member _.NormalizedFullPath = normalizedFullPath
2139

2240
member _.ReadSource() =
2341
match sourceHash with
24-
| Some h -> h, lazy readAllTextNonBlocking normalizedFullPath
42+
| Some h -> h, lazy readSource normalizedFullPath
2543
| _ ->
26-
let source = readAllTextNonBlocking normalizedFullPath
44+
let source = readSource normalizedFullPath
2745
let h = hash source
2846
sourceHash <- Some h
2947
h, lazy source

‎tests/Integration/Compiler/Fable.Tests.Compiler.fsproj‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
<Compile Include="CompilerHelpersTests.fs" />
3232
<Compile Include="InflateTests.fs" />
3333
<Compile Include="WatchDependencyTests.fs" />
34+
<Compile Include="LockedSourceFileTests.fs" />
3435
<Compile Include="RegexOptionsTests.fs" />
3536
<Compile Include="Main.fs" />
3637
</ItemGroup>

0 commit comments

Comments
 (0)