Created
October 24, 2021 23:52
-
-
Save JustinGrote/cbb0d9285c023574ec85495d0ffc64e1 to your computer and use it in GitHub Desktop.
A version of Add-Type for F# in PowerShell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace AddFSharpType | |
module AddFSharpType = | |
open System.IO | |
open FSharp.Compiler.CodeAnalysis | |
open System | |
/// This is basically the compiler so we name it that way | |
let compiler = FSharpChecker.Create() | |
let AddFromFile (sourceFile : string) = | |
let destination = "ThisIsIgnoredForDynamicAssemblyCompliation.dll" | |
let initializeOpts = Some(stderr, stdout) | |
let errors, exitCode, assembly = | |
compiler.CompileToDynamicAssembly([| | |
"fsc.dll" | |
"--noframework" | |
"-a"; sourceFile | |
"-o"; destination | |
"-I"; "C:/Users/JGrote/Projects/FSharp/out" | |
"-I"; "C:/Program Files/dotnet/sdk/6.0.100-rc.2.21505.57/Microsoft/Microsoft.NET.Build.Extensions/net461/lib" | |
|], initializeOpts) | |
|> Async.RunSynchronously | |
// TODO: Better error handling | |
if exitCode > 0 then raise (InvalidOperationException(errors.[0].ToString())) | |
assembly.Value | |
let AddType (typeDefinition : string) = | |
let tempName = Path.GetTempFileName() | |
let tempFile = Path.ChangeExtension(tempName, ".fsx") | |
File.WriteAllText(tempFile, typeDefinition) | |
AddFromFile(tempFile) | |
/// The PowerShell Cmdlet to implement the above | |
open System.Management.Automation | |
[<Cmdlet("Add", "FSharpType")>] | |
type AddFSharpTypeCommand () = | |
inherit PSCmdlet () | |
[<Parameter>] | |
member val TypeDefinition : string = "" with get, set | |
override this.EndProcessing() = | |
let assembly = AddFSharpType.AddType(this.TypeDefinition) | |
this.WriteObject(assembly) | |
base.EndProcessing() |
Author
JustinGrote
commented
Oct 24, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment