-
Notifications
You must be signed in to change notification settings - Fork 75
Create an API layer for external process #637
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
MrLuje
wants to merge
23
commits into
fsprojects:master
Choose a base branch
from
MrLuje:api_layer_version
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
3662671
add FSharpLint.Client project
MrLuje b6f41e4
add client tests
MrLuje 17de4f9
cleanup TestDaemonVersion
MrLuje d44a4da
update README.md
MrLuje e2c1746
remove reference from FSharpLint.Client to FSharpLint.Core (which inc…
MrLuje 0e3e18a
test: ensure FCS is not referenced by FSharpLint.Client
MrLuje 53848f1
add FSHARPLINT_SEARCH_PATH_OVERRIDE env var to override search location
MrLuje 85f2e75
PR feedback: -g -> --global
MrLuje 24f10c1
PR feedback: simplify DOTNET_CLI_UI_LANGUAGE env var usage
MrLuje e5972aa
PR feedback: clearer FSharpLintResponseCode
MrLuje a87b8a9
PR feedback: Folder check
MrLuje a3411da
PR feedback: UnexpectedException
MrLuje ed5370b
PR feedback: comment about Path.GetFullPath
MrLuje 65235ca
PR feedback: Path.GetFullPath readability
MrLuje 82f9428
PR feedback: reuse DirectoryInfo instance
MrLuje 95b7e06
Сlient: introduce File type
webwarrior-ws c80d4bd
FL0084
MrLuje db1578f
FL0043
MrLuje 9306567
FL0055
MrLuje 523e820
fix more rules
MrLuje e84ffc6
PR feedback: Folder FromFile/FromFolder
MrLuje c1fb125
WIP: remove disable-next-line RedundantNewKeyword
Mersho bb70e3c
fix more rules
MrLuje File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| module FSharpLint.Client.Contracts | ||
|
|
||
| open System | ||
| open System.Threading | ||
| open System.Threading.Tasks | ||
|
|
||
| [<RequireQualifiedAccess>] | ||
| module Methods = | ||
| [<Literal>] | ||
| let Version = "fsharplint/version" | ||
|
|
||
| type VersionRequest = | ||
| { | ||
| FilePath: string | ||
| } | ||
|
|
||
| type FSharpLintResult = | ||
| | Content of string | ||
|
|
||
| type FSharpLintResponse = { | ||
| Code: int | ||
| FilePath: string | ||
| Result : FSharpLintResult | ||
| } | ||
|
|
||
| type IFSharpLintService = | ||
| interface | ||
| inherit IDisposable | ||
|
|
||
| abstract member VersionAsync: VersionRequest * ?cancellationToken: CancellationToken -> Task<FSharpLintResponse> | ||
| end |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| module FSharpLint.Client.Contracts | ||
|
|
||
| open System.Threading | ||
| open System.Threading.Tasks | ||
|
|
||
| module Methods = | ||
|
|
||
| [<Literal>] | ||
| val Version: string = "fsharplint/version" | ||
|
|
||
| type VersionRequest = | ||
| { | ||
| FilePath: string | ||
| } | ||
|
|
||
| type FSharpLintResult = | ||
| | Content of string | ||
|
|
||
| type FSharpLintResponse = { | ||
| Code: int | ||
| FilePath: string | ||
| Result : FSharpLintResult | ||
| } | ||
|
|
||
| type IFSharpLintService = | ||
| inherit System.IDisposable | ||
|
|
||
| abstract VersionAsync: VersionRequest * ?cancellationToken: CancellationToken -> Task<FSharpLintResponse> | ||
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <TargetFrameworks>net9.0;net8.0</TargetFrameworks> | ||
| <GenerateDocumentationFile>true</GenerateDocumentationFile> | ||
| <IsPackable>true</IsPackable> | ||
| <RootNamespace>FSharpLint.Client</RootNamespace> | ||
| <EnableDefaultItems>false</EnableDefaultItems> | ||
| <Title>FSharpLint.Client</Title> | ||
| <Description>Companion library to format using FSharpLint tool.</Description> | ||
| <PackageTags>F#;fsharp;lint;FSharpLint;fslint;api</PackageTags> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <Compile Include="Contracts.fsi" /> | ||
| <Compile Include="Contracts.fs" /> | ||
| <Compile Include="LSPFSharpLintServiceTypes.fsi" /> | ||
| <Compile Include="LSPFSharpLintServiceTypes.fs" /> | ||
| <Compile Include="FSharpLintToolLocator.fsi" /> | ||
| <Compile Include="FSharpLintToolLocator.fs" /> | ||
| <Compile Include="LSPFSharpLintService.fsi" /> | ||
| <Compile Include="LSPFSharpLintService.fs" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="..\FSharpLint.Core\FSharpLint.Core.fsproj" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="FSharp.Core" /> | ||
| <PackageReference Include="SemanticVersioning" /> | ||
| <PackageReference Include="StreamJsonRpc" /> | ||
| <PackageReference Include="System.Text.Json" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,254 @@ | ||
| module FSharpLint.Client.FSharpLintToolLocator | ||
|
|
||
| open System | ||
| open System.ComponentModel | ||
| open System.Diagnostics | ||
| open System.IO | ||
| open System.Text.RegularExpressions | ||
| open System.Runtime.InteropServices | ||
| open StreamJsonRpc | ||
| open FSharpLint.Client.LSPFSharpLintServiceTypes | ||
|
|
||
| let private supportedRange = SemanticVersioning.Range(">=v0.21.3") //TODO: proper version | ||
|
|
||
| let private (|CompatibleVersion|_|) (version: string) = | ||
| match SemanticVersioning.Version.TryParse version with | ||
| | true, parsedVersion -> | ||
| if supportedRange.IsSatisfied(parsedVersion, includePrerelease = true) then | ||
| Some version | ||
| else | ||
| None | ||
| | _ -> None | ||
| let [<Literal>] FSharpLintToolName = "dotnet-fsharplint" | ||
|
|
||
| let private (|CompatibleToolName|_|) toolName = | ||
| if toolName = FSharpLintToolName then | ||
| Some toolName | ||
| else | ||
| None | ||
|
|
||
| let private readOutputStreamAsLines (outputStream: StreamReader) : string list = | ||
| let rec readLines (outputStream: StreamReader) (continuation: string list -> string list) = | ||
| let nextLine = outputStream.ReadLine() | ||
|
|
||
| if isNull nextLine then | ||
| continuation List.Empty | ||
| else | ||
| readLines outputStream (fun lines -> nextLine :: lines |> continuation) | ||
|
|
||
| readLines outputStream id | ||
|
|
||
| let private startProcess (ps: ProcessStartInfo) : Result<Process, ProcessStartError> = | ||
| try | ||
| Ok(Process.Start ps) | ||
| with | ||
| | :? Win32Exception as win32ex -> | ||
| let pathEnv = Environment.GetEnvironmentVariable "PATH" | ||
|
|
||
| Error( | ||
| ProcessStartError.ExecutableFileNotFound( | ||
| ps.FileName, | ||
| ps.Arguments, | ||
| ps.WorkingDirectory, | ||
| pathEnv, | ||
| win32ex.Message | ||
| ) | ||
| ) | ||
| | ex -> Error(ProcessStartError.UnexpectedException(ps.FileName, ps.Arguments, ex.Message)) | ||
|
|
||
| let private runToolListCmd (workingDir: Folder) (globalFlag: bool) : Result<string list, DotNetToolListError> = | ||
| let ps = ProcessStartInfo("dotnet") | ||
| ps.WorkingDirectory <- Folder.Unwrap workingDir | ||
| ps.EnvironmentVariables.["DOTNET_CLI_UI_LANGUAGE"] <- "en-us" //ensure we have predictible output for parsing | ||
|
|
||
| let toolArguments = | ||
| Option.ofObj (Environment.GetEnvironmentVariable "FSHARPLINT_SEARCH_PATH_OVERRIDE") | ||
| |> Option.map(fun env -> $" --tool-path %s{env}") | ||
| |> Option.defaultValue (if globalFlag then "--global" else String.Empty) | ||
|
|
||
| ps.CreateNoWindow <- true | ||
| ps.Arguments <- $"tool list %s{toolArguments}" | ||
| ps.RedirectStandardOutput <- true | ||
| ps.RedirectStandardError <- true | ||
| ps.UseShellExecute <- false | ||
|
|
||
| match startProcess ps with | ||
| | Ok proc -> | ||
| proc.WaitForExit() | ||
| let exitCode = proc.ExitCode | ||
|
|
||
| if exitCode = 0 then | ||
| let output = readOutputStreamAsLines proc.StandardOutput | ||
| Ok output | ||
| else | ||
| let error = proc.StandardError.ReadToEnd() | ||
| Error(DotNetToolListError.ExitCodeNonZero(ps.FileName, ps.Arguments, exitCode, error)) | ||
| | Error err -> Error(DotNetToolListError.ProcessStartError err) | ||
|
|
||
| let private (|CompatibleTool|_|) lines = | ||
| let (|HeaderLine|_|) (line: String) = | ||
| if Regex.IsMatch(line, @"^Package\sId\s+Version.+$") then | ||
| Some() | ||
| else | ||
| None | ||
|
|
||
| let (|Dashes|_|) line = | ||
| if String.forall ((=) '-') line then Some() else None | ||
|
|
||
| let (|Tools|_|) lines = | ||
| let tools = | ||
| lines | ||
| |> List.choose (fun (line: string) -> | ||
| let parts = line.Split([| ' ' |], StringSplitOptions.RemoveEmptyEntries) | ||
|
|
||
| if parts.Length > 2 then | ||
| Some(parts.[0], parts.[1]) | ||
| else | ||
| None) | ||
|
|
||
| if List.isEmpty tools then None else Some tools | ||
|
|
||
| match lines with | ||
| | HeaderLine :: Dashes :: Tools tools -> | ||
| let tool = | ||
| List.tryFind | ||
| (fun (packageId, version) -> | ||
| match (packageId, version) with | ||
| | CompatibleToolName _, CompatibleVersion _ -> true | ||
| | _ -> false) | ||
| tools | ||
|
|
||
| Option.map (snd >> FSharpLintVersion) tool | ||
| | _ -> None | ||
|
|
||
| let private isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) | ||
|
|
||
| // Find an executable fsharplint file on the PATH | ||
| let private fsharpLintVersionOnPath () : (FSharpLintExecutableFile * FSharpLintVersion) option = | ||
| let fsharpLintExecutableOnPathOpt = | ||
| Option.ofObj (Environment.GetEnvironmentVariable("FSHARPLINT_SEARCH_PATH_OVERRIDE")) | ||
| |> Option.orElse (Option.ofObj (Environment.GetEnvironmentVariable("PATH"))) | ||
| |> function | ||
| | Some path -> path.Split([| if isWindows then ';' else ':' |], StringSplitOptions.RemoveEmptyEntries) | ||
| | None -> Array.empty | ||
| |> Seq.choose (fun folder -> | ||
| if isWindows then | ||
| let fsharpLintExe = Path.Combine(folder, $"{FSharpLintToolName}.exe") | ||
| if File.Exists fsharpLintExe then Some fsharpLintExe | ||
| else None | ||
| else | ||
| let fsharpLint = Path.Combine(folder, FSharpLintToolName) | ||
| if File.Exists fsharpLint then Some fsharpLint | ||
| else None) | ||
| |> Seq.tryHead | ||
| |> Option.bind File.From | ||
|
|
||
| fsharpLintExecutableOnPathOpt | ||
| |> Option.bind (fun fsharpLintExecutablePath -> | ||
| let processStart = ProcessStartInfo( | ||
| FileName = File.Unwrap fsharpLintExecutablePath, | ||
| Arguments = "--version", | ||
| CreateNoWindow = true, | ||
| RedirectStandardOutput = true, | ||
| RedirectStandardError = true, | ||
| UseShellExecute = false) | ||
|
|
||
| match startProcess processStart with | ||
| | Ok proc -> | ||
| proc.WaitForExit() | ||
| let stdOut = proc.StandardOutput.ReadToEnd() | ||
|
|
||
| stdOut | ||
| |> Option.ofObj | ||
| |> Option.bind (fun stdOut -> | ||
| if stdOut.Contains("Current version: ", StringComparison.CurrentCultureIgnoreCase) then | ||
| let version = stdOut.ToLowerInvariant().Replace("current version: ", String.Empty).Trim() | ||
| Some (FSharpLintExecutableFile(fsharpLintExecutablePath), FSharpLintVersion(version)) | ||
| else | ||
| None) | ||
| | Error(ProcessStartError.ExecutableFileNotFound _) | ||
| | Error(ProcessStartError.UnexpectedException _) -> None) | ||
|
|
||
| let findFSharpLintTool (workingDir: Folder) : Result<FSharpLintToolFound, FSharpLintToolError> = | ||
| // First try and find a local tool for the folder. | ||
| // Next see if there is a global tool. | ||
| // Lastly check if an executable is present on the PATH. | ||
| let localToolsListResult = runToolListCmd workingDir false | ||
|
|
||
| match localToolsListResult with | ||
| | Ok(CompatibleTool version) -> Ok(FSharpLintToolFound(version, FSharpLintToolStartInfo.LocalTool workingDir)) | ||
| | Error err -> Error(FSharpLintToolError.DotNetListError err) | ||
| | Ok _localToolListResult -> | ||
| let globalToolsListResult = runToolListCmd workingDir true | ||
|
|
||
| match globalToolsListResult with | ||
| | Ok(CompatibleTool version) -> Ok(FSharpLintToolFound(version, FSharpLintToolStartInfo.GlobalTool)) | ||
| | Error err -> Error(FSharpLintToolError.DotNetListError err) | ||
| | Ok _nonCompatibleGlobalVersion -> | ||
| let onPathVersion = fsharpLintVersionOnPath () | ||
|
|
||
| match onPathVersion with | ||
| | Some(executableFile, FSharpLintVersion(CompatibleVersion version)) -> | ||
| Ok(FSharpLintToolFound((FSharpLintVersion(version)), FSharpLintToolStartInfo.ToolOnPath executableFile)) | ||
| | _ -> Error FSharpLintToolError.NoCompatibleVersionFound | ||
|
|
||
| let createFor (startInfo: FSharpLintToolStartInfo) : Result<RunningFSharpLintTool, ProcessStartError> = | ||
| let processStart = | ||
| match startInfo with | ||
| | FSharpLintToolStartInfo.LocalTool(workingDirectory: Folder) -> | ||
| ProcessStartInfo( | ||
| FileName = "dotnet", | ||
| WorkingDirectory = Folder.Unwrap workingDirectory, | ||
| Arguments = $"{FSharpLintToolName} --daemon") | ||
| | FSharpLintToolStartInfo.GlobalTool -> | ||
| let userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) | ||
|
|
||
| let fsharpLintExecutable = | ||
| let fileName = if isWindows then $"{FSharpLintToolName}.exe" else FSharpLintToolName | ||
| Path.Combine(userProfile, ".dotnet", "tools", fileName) | ||
|
|
||
| ProcessStartInfo( | ||
| FileName = fsharpLintExecutable, | ||
| Arguments = "--daemon") | ||
| | FSharpLintToolStartInfo.ToolOnPath(FSharpLintExecutableFile executableFile) -> | ||
| ProcessStartInfo( | ||
| FileName = File.Unwrap executableFile, | ||
| Arguments = "--daemon") | ||
|
|
||
| processStart.UseShellExecute <- false | ||
| processStart.RedirectStandardInput <- true | ||
| processStart.RedirectStandardOutput <- true | ||
| processStart.RedirectStandardError <- true | ||
| processStart.CreateNoWindow <- true | ||
|
|
||
| match startProcess processStart with | ||
| | Ok daemonProcess -> | ||
| let handler = new HeaderDelimitedMessageHandler( | ||
| daemonProcess.StandardInput.BaseStream, | ||
| daemonProcess.StandardOutput.BaseStream) | ||
|
|
||
| let client = new JsonRpc(handler) | ||
|
|
||
| do client.StartListening() | ||
|
|
||
| try | ||
| // Get the version first as a sanity check that connection is possible | ||
| let _version = | ||
| client.InvokeAsync<string>(FSharpLint.Client.Contracts.Methods.Version) | ||
| |> Async.AwaitTask | ||
| |> Async.RunSynchronously | ||
|
|
||
| Ok | ||
| { RpcClient = client | ||
| Process = daemonProcess | ||
| StartInfo = startInfo } | ||
| with ex -> | ||
| let error = | ||
| if daemonProcess.HasExited then | ||
| let stdErr = daemonProcess.StandardError.ReadToEnd() | ||
| $"Daemon std error: {stdErr}.\nJsonRpc exception:{ex.Message}" | ||
| else | ||
| ex.Message | ||
|
|
||
| Error(ProcessStartError.UnexpectedException(processStart.FileName, processStart.Arguments, error)) | ||
| | Error err -> Error err |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| module FSharpLint.Client.FSharpLintToolLocator | ||
|
|
||
| open FSharpLint.Client.LSPFSharpLintServiceTypes | ||
|
|
||
| val findFSharpLintTool: workingDir: Folder -> Result<FSharpLintToolFound, FSharpLintToolError> | ||
|
|
||
| val createFor: startInfo: FSharpLintToolStartInfo -> Result<RunningFSharpLintTool, ProcessStartError> |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.