-
Notifications
You must be signed in to change notification settings - Fork 73
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
26
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
26 commits
Select commit
Hold shift + click to select a range
67625f0
add FSharpLint.Client project
MrLuje 86288de
add client tests
MrLuje d09fd32
cleanup TestDaemonVersion
MrLuje 51adb1d
update README.md
MrLuje 99a252a
remove reference from FSharpLint.Client to FSharpLint.Core (which inc…
MrLuje a7de738
test: ensure FCS is not referenced by FSharpLint.Client
MrLuje 839ee03
add FSHARPLINT_SEARCH_PATH_OVERRIDE env var to override search location
MrLuje 8d4250f
PR feedback: -g -> --global
MrLuje 1a2c2e3
PR feedback: simplify DOTNET_CLI_UI_LANGUAGE env var usage
MrLuje c7670d9
PR feedback: clearer FSharpLintResponseCode
MrLuje 8cf9426
PR feedback: Folder check
MrLuje 261c643
PR feedback: UnexpectedException
MrLuje 49a5332
PR feedback: comment about Path.GetFullPath
MrLuje ee4f419
PR feedback: Path.GetFullPath readability
MrLuje 2653e11
PR feedback: reuse DirectoryInfo instance
MrLuje 1cc9edb
Сlient: introduce File type
webwarrior-ws 776f736
FL0084
MrLuje 24963dc
FL0043
MrLuje a5dba0f
FL0055
MrLuje bd88d1a
fix more rules
MrLuje 363292d
PR feedback: Folder FromFile/FromFolder
MrLuje 9d5c57c
WIP: remove disable-next-line RedundantNewKeyword
Mersho 4a98681
fix more rules
MrLuje a2378c6
fix: daemon cache
MrLuje a3429a0
FL0022
MrLuje 80b3462
PR feedbacks
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,256 @@ | ||
| 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 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) | ||
|
|
||
| let ps = ProcessStartInfo( | ||
| "dotnet", | ||
| Arguments = $"tool list %s{toolArguments}", | ||
| WorkingDirectory = Folder.Unwrap workingDir, | ||
| RedirectStandardOutput = true, | ||
| RedirectStandardError = true, | ||
| UseShellExecute = false, | ||
| CreateNoWindow = true | ||
| ) | ||
| ps.EnvironmentVariables.["DOTNET_CLI_UI_LANGUAGE"] <- "en-us" //ensure we have predictible output for parsing | ||
|
|
||
| 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([| Path.PathSeparator |], StringSplitOptions.RemoveEmptyEntries) | ||
| | None -> Array.empty | ||
| |> Seq.choose (fun folder -> | ||
| let fsharpLint = | ||
| if isWindows then Path.Combine(folder, $"{FSharpLintToolName}.exe") | ||
| else Path.Combine(folder, FSharpLintToolName) | ||
| if File.Exists fsharpLint then Some fsharpLint | ||
| else None) | ||
| |> Seq.tryHead | ||
| |> Option.bind File.From | ||
|
|
||
| let extractFsharpLintVersion 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 | ||
|
|
||
| fsharpLintExecutableOnPathOpt | ||
| |> Option.bind extractFsharpLintVersion | ||
|
|
||
| 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 -> | ||
| Console.Error.WriteLine(ex.ToString()) | ||
|
|
||
| let error = | ||
MrLuje marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| 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.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@MrLuje the consistency-chaser in me is wanting to suggest that we create here a similar type to Folder, e.g.
Filewhich uses FileInfo underneath (instead of DirectoryInfo)There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm all for consistency but IMHO there is less value for this one :
Folderwas only used internally) and it may be less intuitive to useErrFileNotFound, so we may want to change it if we go with theFileInfowayThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I know it has less value, but I'm just allergic to the PrimitiveObsession anti-pattern (since I came to know the type
FileInfo, seeing astringfor file paths makes my eyes bleed haha). I can make the change myself, I'll push to your branch yeah?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
FTR https://hackernoon.com/what-is-primitive-obsession-and-how-can-we-fix-it-wh2f33ki ;)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@knocte sure, go for it :)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@MrLuje sure, I'll do it this week. BTW can you rebase the PR? looks like there is some conflict
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@knocte done