Skip to content

Commit

Permalink
Add colors to error/success/info messages (#118)
Browse files Browse the repository at this point in the history
Move Logger to it's own module and make log out text with different color values.
drewknab authored Oct 18, 2022

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature. The key has expired.
1 parent 8a045cf commit 4187a38
Showing 4 changed files with 48 additions and 38 deletions.
44 changes: 25 additions & 19 deletions src/Fornax/Fornax.fs
Original file line number Diff line number Diff line change
@@ -13,17 +13,18 @@ open Suave.Sockets
open Suave.Sockets.Control
open Suave.WebSocket
open System.Reflection
open Logger

type FornaxExiter () =
interface IExiter with
member x.Name = "fornax exiter"
member x.Exit (msg, errorCode) =
if errorCode = ErrorCode.HelpText then
printfn "%s" msg
printf "%s" msg
exit 0
else
printfn "Error with code %A received - exiting." errorCode
printfn "%s" msg
errorfn "Error with code %A received - exiting." errorCode
printf "%s" msg
exit 1


@@ -91,16 +92,16 @@ let createFileWatcher dir handler =
/// Websocket function that a page listens to so it
/// knows when to refresh.
let ws (webSocket : WebSocket) (context: HttpContext) =
printfn "Opening WebSocket - new handShake"
informationfn "Opening WebSocket - new handShake"
socket {
try
while true do
do! Async.AwaitEvent signalContentChanged.Publish
printfn "Signalling content changed"
informationfn "Signalling content changed"
let emptyResponse = [||] |> ByteSegment
do! webSocket.send Close emptyResponse true
finally
printfn "Disconnecting WebSocket"
informationfn "Disconnecting WebSocket"
}

let getWebServerConfig port =
@@ -175,11 +176,11 @@ let main argv =
let results = parser.ParseCommandLine(inputs = argv).GetAllResults()

if List.isEmpty results then
printfn "No arguments provided. Try 'fornax help' for additional details."
errorfn "No arguments provided. Try 'fornax help' for additional details."
printfn "%s" <| parser.PrintUsage()
1
elif List.length results > 1 then
printfn "More than one command was provided. Please provide only a single command. Try 'fornax help' for additional details."
errorfn "More than one command was provided. Please provide only a single command. Try 'fornax help' for additional details."
printfn "%s" <| parser.PrintUsage()
1
else
@@ -207,7 +208,7 @@ let main argv =
// Copy the Fornax.Core.dll into _lib
// Some/most times Fornax.Core.dll already exists
File.Copy(corePath, outputDirectory + "/_lib/Fornax.Core.dll", true)
printfn "New project successfully created."
okfn "New project successfully created."
0
| Some Build ->
try
@@ -216,10 +217,10 @@ let main argv =
0
with
| FornaxGeneratorException message ->
Console.WriteLine message
message |> stringFormatter |> errorfn
1
| exn ->
printfn "An unexpected error happend: %O" exn
errorfn "An unexpected error happend: %O" exn
1
| Some (Watch watchOptions) ->
let mutable lastAccessed = Map.empty<string, DateTime>
@@ -233,9 +234,10 @@ let main argv =
do generateFolder sc cwd true
with
| FornaxGeneratorException message ->
printfn "%s%s%s" message Environment.NewLine waitingForChangesMessage
message |> stringFormatter |> errorfn
waitingForChangesMessage |> stringFormatter |> informationfn
| exn ->
printfn "An unexpected error happend: %O" exn
errorfn "An unexpected error happend: %O" exn
exit 1

guardedGenerate ()
@@ -259,15 +261,16 @@ let main argv =
match lastAccessed.TryFind e.FullPath with
| Some lt when Math.Abs((lt - lastTimeWrite).Seconds) < 1 -> ()
| _ ->
printfn "[%s] Changes detected: %s" (DateTime.Now.ToString("HH:mm:ss")) e.FullPath
informationfn "[%s] Changes detected: %s" (DateTime.Now.ToString("HH:mm:ss")) e.FullPath
lastAccessed <- lastAccessed.Add(e.FullPath, lastTimeWrite)
guardedGenerate ())

let webServerConfig = getWebServerConfig (watchOptions.TryPostProcessResult(<@ Port @>, uint16))
startWebServerAsync webServerConfig (router cwd) |> snd |> Async.Start
printfn "[%s] Watch mode started. Press any key to exit." (DateTime.Now.ToString("HH:mm:ss"))
okfn "[%s] Watch mode started." (DateTime.Now.ToString("HH:mm:ss"))
informationfn "Press any key to exit."
Console.ReadKey() |> ignore
printfn "Exiting..."
informationfn "Exiting..."
0
| Some Version ->
let assy = Assembly.GetExecutingAssembly()
@@ -277,13 +280,16 @@ let main argv =
| Some Clean ->
let publ = Path.Combine(cwd, "_public")
let sassCache = Path.Combine(cwd, ".sass-cache")
let deleter folder =
match Directory.Exists(folder) with
| true -> Directory.Delete(folder, true)
| _ -> ()
try
Directory.Delete(publ, true)
Directory.Delete(sassCache, true)
[publ ; sassCache] |> List.iter deleter
0
with
| _ -> 1
| None ->
printfn "Unknown argument"
errorfn "Unknown argument"
printfn "%s" <| parser.PrintUsage()
1
1 change: 1 addition & 0 deletions src/Fornax/Fornax.fsproj
Original file line number Diff line number Diff line change
@@ -10,6 +10,7 @@
<ProjectReference Include="..\Fornax.Core\Fornax.Core.fsproj" />

<Compile Include="FSIRefs.fs" />
<Compile Include="Logger.fs" />
<Compile Include="Generator.fs" />
<Compile Include="Fornax.fs" />
<!-- we want the include the raw template files
27 changes: 8 additions & 19 deletions src/Fornax/Generator.fs
Original file line number Diff line number Diff line change
@@ -7,6 +7,7 @@ open System.Diagnostics
open System.IO
open System.Text
open Config
open Logger

module EvaluatorHelpers =
open FSharp.Quotations.Evaluator
@@ -37,9 +38,9 @@ module EvaluatorHelpers =
FsiEvaluationSession.Create(fsiConfig, argv, inStream, outStream, errStream)
with
| ex ->
printfn "Error: %A" ex
printfn "Inner: %A" ex.InnerException
printfn "ErrorStream: %s" (errStream.ToString())
errorfn "Error: %A" ex
errorfn "Inner: %A" ex.InnerException
errorfn "ErrorStream: %s" (errStream.ToString())
raise ex


@@ -325,7 +326,6 @@ let pickGenerator (cfg: Config.Config) (siteContent : SiteContents) (projectRoo
Path.Combine(projectRoot, "_public", newPage)
Some(Simple (generatorPath, outputPath))


///`projectRoot` - path to the root of website
///`page` - path to page that should be generated
let generate fsi (cfg: Config.Config) (siteContent : SiteContents) (projectRoot : string) (page : string) =
@@ -426,17 +426,6 @@ let runOnceGenerators fsi (cfg: Config.Config) (siteContent : SiteContents) (pro
| _ -> failwith "Shouldn't happen"
)

// Module to print colored message in the console
module Logger =
let consoleColor (fc : ConsoleColor) =
let current = Console.ForegroundColor
Console.ForegroundColor <- fc
{ new IDisposable with
member x.Dispose() = Console.ForegroundColor <- current }

let informationfn str = Printf.kprintf (fun s -> use c = consoleColor ConsoleColor.Green in printfn "%s" s) str
let error str = Printf.kprintf (fun s -> use c = consoleColor ConsoleColor.Red in printf "%s" s) str
let errorfn str = Printf.kprintf (fun s -> use c = consoleColor ConsoleColor.Red in printfn "%s" s) str

///`projectRoot` - path to the root of website
let generateFolder (sc : SiteContents) (projectRoot : string) (isWatch: bool) =
@@ -469,16 +458,16 @@ let generateFolder (sc : SiteContents) (projectRoot : string) (isWatch: bool) =
| Ok sc ->
sc
| Error er ->
printfn "LOADER ERROR: %s" er
errorfn "LOADER ERROR: %s" er
state)
sc.Errors() |> List.iter (fun er -> printfn "BAD FILE: %s" er.Path)
sc.Errors() |> List.iter (fun er -> errorfn "BAD FILE: %s" er.Path)

let logResult (result : GeneratorResult) =
match result with
| GeneratorIgnored -> ()
| GeneratorSuccess None -> ()
| GeneratorSuccess (Some message) ->
Logger.informationfn "%s" message
okfn "%s" message
| GeneratorFailure message ->
// if one generator fails we want to exit early and report the problem to the operator
raise (FornaxGeneratorException message)
@@ -493,4 +482,4 @@ let generateFolder (sc : SiteContents) (projectRoot : string) (isWatch: bool) =
|> generate fsi config sc projectRoot
|> logResult)

Logger.informationfn "Generation time: %A" sw.Elapsed
informationfn "Generation time: %A" sw.Elapsed
14 changes: 14 additions & 0 deletions src/Fornax/Logger.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
module Logger

open System

let consoleColor (fc : ConsoleColor) =
let current = Console.ForegroundColor
Console.ForegroundColor <- fc
{ new IDisposable with
member x.Dispose() = Console.ForegroundColor <- current }

let stringFormatter str = Printf.StringFormat<_, unit>(str)
let informationfn str = Printf.kprintf (fun s -> use c = consoleColor ConsoleColor.Cyan in printfn "%s" s) str
let errorfn str = Printf.kprintf (fun s -> use c = consoleColor ConsoleColor.Red in printfn "%s" s) str
let okfn str = Printf.kprintf (fun s -> use c = consoleColor ConsoleColor.Green in printfn "%s" s) str

0 comments on commit 4187a38

Please sign in to comment.