Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathProcessCommandLine.fs
More file actions
Latest commit
333 lines (293 loc) · 15.8 KB
/
Copy pathProcessCommandLine.fs
File metadata and controls
333 lines (293 loc) · 15.8 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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
// Copyright 2018 Fabulous contributors. See LICENSE.md for license.
// F# PortaCode command processing (e.g. used by Fabulous.Cli)
moduleFSharp.Compiler.PortaCode.ProcessCommandLine
openFSharp.Compiler.PortaCode.CodeModel
openFSharp.Compiler.PortaCode.Interpreter
openFSharp.Compiler.PortaCode.FromCompilerService
openSystem
openSystem.Reflection
openSystem.Collections.Generic
openSystem.IO
openFSharp.Compiler.SourceCodeServices
openFSharp.Compiler.Text
openSystem.Net
openSystem.Text
letchecker= FSharpChecker.Create(keepAssemblyContents =true)
letProcessCommandLine(argv:string[])=
let mutablefsproj= None
let mutabledump=false
let mutablelivecheck=false
let mutabledyntypes=false
let mutablewatch=true
let mutableuseEditFiles=false
let mutablewriteinfo=true
let mutablewebhook= None
let mutableotherFlags=[]
let mutablemsbuildArgs=[]
letdefaultUrl="http://localhost:9867/update"
letfsharpArgs=
let mutablehaveDashes=false
[|for arg in argv do
letarg= arg.Trim()
if arg.StartsWith("@")then
for line in File.ReadAllLines(arg.[1..])do
letline= line.Trim()
ifnot(String.IsNullOrWhiteSpace(line))then
yield line
elif arg.EndsWith(".fsproj")then
fsproj <- Some arg
elif arg ="--"then haveDashes <-true
elif arg.StartsWith "--projarg:"then msbuildArgs <- msbuildArgs @[ arg.["----projarg:".Length ..]]
elif arg.StartsWith "--define:"then otherFlags <- otherFlags @[ arg ]
elif arg ="--once"then watch <-false
elif arg ="--dump"then dump <-true
elif arg ="--livecheck"then
dyntypes <-true
livecheck <-true
writeinfo <-true
//useEditFiles <- true
elif arg ="--enablelivechecks"then
livecheck <-true
elif arg ="--useeditfles"then
useEditFiles <-true
elif arg ="--dyntypes"then
dyntypes <-true
elif arg ="--writeinfo"then
writeinfo <-true
elif arg.StartsWith "--send:"then webhook <- Some arg.["--send:".Length ..]
elif arg ="--send"then webhook <- Some defaultUrl
elif arg ="--version"then
printfn ""
printfn "*** NOTE: if sending the code to a device the versions of CodeModel.fs and Interpreter.fs on the device must match ***"
printfn ""
printfn "CLI tool assembly version: %A"(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version)
printfn "CLI tool name: %s"(System.Reflection.Assembly.GetExecutingAssembly().GetName().Name)
printfn ""
elif arg ="--help"then
printfn "Command line tool for watching and interpreting F# projects"
printfn ""
printfn "Usage: <tool> arg .. arg [-- <other-args>]"
printfn " <tool> @args.rsp [-- <other-args>]"
printfn " <tool> ... Project.fsproj ... [-- <other-args>]"
printfn ""
printfn "The default source is a single project file in the current directory."
printfn "The default output is a JSON dump of the PortaCode."
printfn ""
printfn "Arguments:"
printfn " --once Don't enter watch mode (default: watch the source files of the project for changes)"
printfn " --send:<url> Send the JSON-encoded contents of the PortaCode to the webhook"
printfn " --send Equivalent to --send:%s" defaultUrl
printfn " --projarg:arg An MSBuild argument e.g. /p:Configuration=Release"
printfn " --dump Dump the contents to console after each update"
printfn " --livecheck Only evaluate those with a *CheckAttribute (e.g. LiveCheck or ShapeCheck)"
printfn " This uses on-demand execution semantics for top-level declarations"
printfn " Also write an info file based on results of evaluation."
printfn " Also watch for .fsharp/foo.fsx.edit files and use the contents of those in preference to the source file"
printfn " --dyntypes Dynamically compile and load so full .NET types exist"
printfn " <other-args> All other args are assumed to be extra F# command line arguments, e.g. --define:FOO"
exit 1
elseyield arg |]
if fsharpArgs.Length =0&& fsproj.IsNone then
match Seq.toList (Directory.EnumerateFiles(Environment.CurrentDirectory,"*.fsproj"))with
|[]->
failwithf "no project file found, no compilation arguments given and no project file found in \"%s\"" Environment.CurrentDirectory
|[ file ]->
printfn "fslive: using implicit project file '%s'" file
fsproj <- Some file
| file1 :: file2 ::_->
failwithf "multiple project files found, e.g. %s and %s" file1 file2
leteditDirAndFile(fileName:string)=
assert useEditFiles
letinfoDir= Path.Combine(Path.GetDirectoryName fileName,".fsharp")
leteditFile= Path.Combine(infoDir,Path.GetFileName fileName +".edit")
ifnot(Directory.Exists infoDir)then
Directory.CreateDirectory infoDir |> ignore
infoDir, editFile
letreadFile(fileName:string)=
if useEditFiles && watch then
letinfoDir,editFile = editDirAndFile fileName
letpreferEditFile=
try
Directory.Exists infoDir && File.Exists editFile && File.Exists fileName && File.GetLastWriteTime(editFile)> File.GetLastWriteTime(fileName)
with_->
false
if preferEditFile then
printfn "*** preferring %s to %s ***" editFile fileName
File.ReadAllText editFile
else
File.ReadAllText fileName
else
File.ReadAllText fileName
letoptions=
match fsproj with
| Some fsprojFile ->
if fsharpArgs.Length >1then failwith "can't give both project file and compilation arguments"
match FSharpDaemon.ProjectCracker.load (new System.Collections.Concurrent.ConcurrentDictionary<_,_>()) fsprojFile msbuildArgs with
| Ok (options, sourceFiles,_log)->
letoptions={ options with SourceFiles = Array.ofList sourceFiles }
letsourceFilesSet= Set.ofList sourceFiles
letoptions={ options with OtherOptions = options.OtherOptions |> Array.filter (fun s ->not(sourceFilesSet.Contains(s)))}
Result.Ok options
| Error err ->
failwithf "Couldn't parse project file: %A" err
| None ->
letsourceFiles,otherFlags2 = fsharpArgs |> Array.partition (fun arg -> arg.EndsWith(".fs")|| arg.EndsWith(".fsi")|| arg.EndsWith(".fsx"))
letotherFlags=[|yield! otherFlags;yield! otherFlags2 |]
letsourceFiles= sourceFiles |> Array.map Path.GetFullPath
printfn "CurrentDirectory = %s" Environment.CurrentDirectory
match sourceFiles with
|[| script |]when script.EndsWith(".fsx")->
lettext= readFile script
letotherFlags= Array.append otherFlags [|"--targetprofile:netcore";|]
letoptions,errors = checker.GetProjectOptionsFromScript(script, SourceText.ofString text, otherFlags=otherFlags, assumeDotNetFramework=false)|> Async.RunSynchronously
letoptions={ options with OtherOptions = Array.append options.OtherOptions [|"--target:library"|]}
if errors.Length >0then
for error in errors do
printfn "%s"(error.ToString())
Result.Error ()
else
Result.Ok options
|_->
letoptions= checker.GetProjectOptionsFromCommandLineArgs("tmp.fsproj", otherFlags)
letoptions={ options with SourceFiles = sourceFiles }
Result.Ok options
match options with
| Result.Error ()->
printfn "fslive: error processing project options or script"
-1
| Result.Ok options ->
letoptions={ options with OtherOptions = Array.append options.OtherOptions (Array.ofList otherFlags)}
//printfn "options = %A" options
let reccheckFile count sourceFile =
try
letparseResults,checkResults = checker.ParseAndCheckFileInProject(sourceFile,0, SourceText.ofString (readFile sourceFile), options)|> Async.RunSynchronously
match checkResults with
| FSharpCheckFileAnswer.Aborted ->
for e in parseResults.Errors do
printfn "Error: %A" e
failwith "unexpected aborted"
Result.Error (parseResults.ParseTree, None, None, None)
| FSharpCheckFileAnswer.Succeeded res ->
let mutablehasErrors=false
for error in res.Errors do
printfn "%s"(error.ToString())
if error.Severity = FSharpErrorSeverity.Error then
hasErrors <-true
if hasErrors then
Result.Error (parseResults.ParseTree, None, Some res.Errors, res.ImplementationFile)
else
Result.Ok (parseResults.ParseTree, res.ImplementationFile)
with
|:? System.IO.IOException when count =0->
System.Threading.Thread.Sleep 500
checkFile 1 sourceFile
| exn ->
printfn "%s"(exn.ToString())
Result.Error (None, Some exn, None, None)
letkeepRanges=not dump
lettolerateIncompleteExpressions= livecheck && watch
letconvFile(i:FSharpImplementationFileContents)=
//(i.QualifiedName, i.FileName
i.FileName,{ Code = Convert(keepRanges, tolerateIncompleteExpressions).ConvertDecls i.Declarations }
letcheckFiles files =
let recloop rest acc =
match rest with
| file :: rest ->
match checkFile 0(Path.GetFullPath(file))with
// Note, if livecheck are on, we continue on regardless of errors
| Result.Error iopt whennot livecheck ->
printfn "fslive: ERRORS for %s" file
Result.Error iopt
| Result.Error ((_,_,_, None)as info)-> Result.Error info
| Result.Ok (_, None)-> Result.Error (None, None, None, None)
| Result.Error (parseTree,_,_, Some implFile)
| Result.Ok (parseTree, Some implFile)->
printfn "fslive: GOT PortaCode for %s" file
loop rest ((parseTree, implFile):: acc)
|[]-> Result.Ok (List.rev acc)
loop (List.ofArray files)[]
letjsonFiles(impls:FSharpImplementationFileContents[])=
letdata= Array.map convFile impls
letjson= Newtonsoft.Json.JsonConvert.SerializeObject(data)
json
letsendToWebHook(hook:string)fileContents =
try
letjson= jsonFiles (Array.ofList fileContents)
printfn "fslive: GOT JSON, length = %d" json.Length
use webClient =new WebClient(Encoding = Encoding.UTF8)
printfn "fslive: SENDING TO WEBHOOK... "// : <<<%s>>>... --> %s" json.[0 .. min (json.Length - 1) 100] hook
letresp= webClient.UploadString (hook,"Put",json)
printfn "fslive: RESP FROM WEBHOOK: %s" resp
with err ->
printfn "fslive: ERROR SENDING TO WEBHOOK: %A"(err.ToString())
let mutablelastCompileStart= System.DateTime.Now
letchanged why _ =
try
printfn "fslive: COMPILING (%s)...." why
lastCompileStart <- System.DateTime.Now
match checkFiles options.SourceFiles with
| Result.Error res -> Result.Error res
| Result.Ok allFileContents ->
letparseTrees= List.choose fst allFileContents
letimplFiles= List.map snd allFileContents
match webhook with
| Some hook ->
sendToWebHook hook implFiles
Result.Ok()
| None ->
ifnot dump && webhook.IsNone then
printfn "fslive: EVALUATING ALL INPUTS...."
letevaluator= LiveCheckEvaluation(options.OtherOptions, dyntypes, writeinfo, keepRanges, livecheck, tolerateIncompleteExpressions)
match evaluator.EvaluateDecls implFiles with
| Error _whennot watch -> exit 1
|_->()
// The default is to dump
if dump && webhook.IsNone then
letfileConvContents= jsonFiles (Array.ofList implFiles)
printfn "%A" fileConvContents
Result.Ok()
with err when watch ->
printfn "fslive: exception: %A"(err.ToString())
for loc in err.EvalLocationStack do
printfn " --> %O" loc
Result.Error (None, Some err, None, None)
for o in options.OtherOptions do
printfn "compiling, option %s" o
if watch then
// Send an immediate changed() event
if webhook.IsNone then
printfn "Sending initial changes... "
changed "initial"()|> ignore
letmkWatcher(sourceFile:string)=
letpath= Path.GetDirectoryName(sourceFile)
letfileName= Path.GetFileName(sourceFile)
printfn "fslive: WATCHING %s in %s" fileName path
letwatcher=new FileSystemWatcher(path, fileName)
watcher.NotifyFilter <- NotifyFilters.Attributes ||| NotifyFilters.CreationTime ||| NotifyFilters.FileName ||| NotifyFilters.LastAccess ||| NotifyFilters.LastWrite ||| NotifyFilters.Size ||| NotifyFilters.Security;
letfileChange msg e =
letlastWriteTime=try max (File.GetCreationTime(sourceFile))(File.GetLastWriteTime(sourceFile))with_-> DateTime.MaxValue
printfn "change %s, lastCOmpileStart=%A, lastWriteTime = %O" sourceFile lastCompileStart lastWriteTime
if lastWriteTime > lastCompileStart then
printfn "changed %s" sourceFile
changed msg e |> ignore
watcher.Changed.Add (fileChange (sprintf "Changed %s" fileName))
watcher.Created.Add (fileChange (sprintf "Created %s" fileName))
watcher.Deleted.Add (fileChange (sprintf "Deleted %s" fileName))
watcher.Renamed.Add (fileChange (sprintf "Renamed %s" fileName))
watcher
letwatchers=
[for sourceFile in options.SourceFiles do
yield mkWatcher sourceFile
if useEditFiles then
yield mkWatcher sourceFile ]
for watcher in watchers do
watcher.EnableRaisingEvents <-true
printfn "Waiting for changes... press any key to exit"
System.Console.ReadLine()|> ignore
for watcher in watchers do
watcher.EnableRaisingEvents <-false
0
else
match changed "once"()with
| Error _->1
| Ok _->0