Skip to content

Commit

Permalink
Add to enable concise logging
Browse files Browse the repository at this point in the history
  • Loading branch information
engali94 committed May 1, 2021
1 parent 5a38ec8 commit c99d897
Show file tree
Hide file tree
Showing 10 changed files with 132 additions and 21 deletions.
3 changes: 2 additions & 1 deletion .swiftlint.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
opt_in_rules: # some rules are only opt-in
- empty_count
- redundant_nil_coalescing
- switch_case_on_newline
- force_unwrapping
- closure_spacing
- implicitly_unwrapped_optional
Expand Down Expand Up @@ -36,3 +35,5 @@ disabled_rules: # rule identifiers to exclude from running
- trailing_whitespace
- type_name
- identifier_name
- switch_case_on_newline
- switch_case_alignment
9 changes: 9 additions & 0 deletions Package.resolved
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,15 @@
"revision": "986d191f94cec88f6350056da59c2e59e83d1229",
"version": "0.4.3"
}
},
{
"package": "swift-log",
"repositoryURL": "https://github.com/apple/swift-log.git",
"state": {
"branch": null,
"revision": "5d66f7ba25daf4f94100e7022febf3c75e37a6c7",
"version": "1.4.2"
}
}
]
},
Expand Down
12 changes: 8 additions & 4 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,26 @@ import PackageDescription
let package = Package(
name: "ax-editor",
products: [
.executable(name: "ax", targets: ["ax-editor"])
.executable(name: "ax", targets: ["ax-editor"])
],

dependencies: [
.package(url: "https://github.com/apple/swift-argument-parser", from: "0.3.0")
.package(url: "https://github.com/apple/swift-argument-parser", from: "0.3.0"),
.package(url: "https://github.com/apple/swift-log.git", from: "1.2.0"),
],

targets: [
.target(
name: "Core",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser")
.product(name: "ArgumentParser", package: "swift-argument-parser"),
.product(name: "Logging", package: "swift-log")
]),
.target(
name: "ax-editor",
dependencies: ["Core"]
dependencies: [
"Core",
]
),
.testTarget(
name: "ax-editorTests",
Expand Down
2 changes: 1 addition & 1 deletion Sources/Core/Config/Language.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/**
/*
* Ax Editor
* Copyright (c) Ali Hilal 2020
* MIT license - see LICENSE.md
Expand Down
4 changes: 3 additions & 1 deletion Sources/Core/Editor.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
/**
/*
* Ax Editor
* Copyright (c) Ali Hilal 2020
* MIT license - see LICENSE.md
Expand Down Expand Up @@ -87,6 +87,7 @@ public final class Editor {
document.execute(.splitLine)
}
}

if event.code == .char("d") && event.modifiers == .some(.control) {
exitEditor()
return
Expand Down Expand Up @@ -149,6 +150,7 @@ public final class Editor {
frame.append(tilde)
}
}

terminal
.writeOnScreen(
frame
Expand Down
96 changes: 96 additions & 0 deletions Sources/Core/Helpers/Loger.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/*
* Ax Editor
* Copyright (c) Ali Hilal 2021
* MIT license - see LICENSE.md
*/

import Foundation
import Logging

public struct Logger {

public typealias Level = Logging.Logger.Level

private static let consoleLogger = Logging.Logger(
label: "com.alihilal.ax-editor",
factory: StreamLogHandler.standardError
)

public static func log(
event: Level,
destination: Destination = .console,
messages: Any...,
file: StaticString = #filePath,
line: UInt = #line
) {
switch destination {
case .console:
logToConsole(event: event, messages: messages, file: file, line: line)
case .disk:
logToDisk(event: event, messages: messages, file: file, line: line)
}
}

private static func logToConsole(
event: Level,
messages: Any...,
file: StaticString = #filePath,
line: UInt = #line
) {
let string = event.icon + " " + messages.map { "\($0) " }.joined()
consoleLogger.log(level: event, .init(stringLiteral: string))
}

private static func logToDisk(
event: Level,
messages: Any...,
file: StaticString = #filePath,
line: UInt = #line
) {
guard let desktopDir = NSSearchPathForDirectoriesInDomains(.desktopDirectory, .userDomainMask, true).last else { return }
let string = event.icon + " \(Date()): " + messages.map { "\($0) " }.joined()
try? string.write(toFile: desktopDir + "//log.txt", atomically: true, encoding: .utf8)
}

public func log(_ str: String) {

}

}

public extension Logger {
enum Destination {
case console
case disk
}
}

extension Logger {
enum Event {
case debug
case error
case success
}
}


extension Logger.Level {
var icon: String {
switch self {
case .debug:
return "⚙️"
case .error:
return "🚨"
case .info:
return ""
case .trace:
return "🔔"
case .notice:
return "ℹ️"
case .warning:
return "⚠️"
case .critical:
return "⛔️"
}
}
}
15 changes: 6 additions & 9 deletions Sources/Core/Highligher/Highlighter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,16 @@ public struct Highlighter {
public func highlight(code: String) -> String {
var code = code.uncolorized()
let tokens = tokenizer.tokinze(code)
log(tokens.map({
$0.kind.rawValue + " \($0.range.lowerBound) \($0.range.upperBound)"

}).joined(separator: " "))
let log = tokens
.map { $0.kind.rawValue + " \($0.range.lowerBound) \($0.range.upperBound)" }
.joined(separator: " ")
Logger.log(event: .debug, destination: .disk, messages: log)
tokens.forEach({ token in
let color = self.color(for: token.kind)
code.highlight(token.text, with: color, at: token.range)
})
log(code)

Logger.log(event: .debug, destination: .disk, messages: code)
return code
}
}
Expand All @@ -39,7 +40,3 @@ extension String {
self = replacingOccurrences(of: word, with: word.customForegroundColor(color))
}
}

public func log(_ str: String) {
try! str.write(toFile: FileManager.default.currentDirectoryPath + "//log.txt", atomically: true, encoding: .utf8)
}
2 changes: 2 additions & 0 deletions Sources/Core/Terminal/EventParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ private extension EventParser {
}
}

// swiftlint:disable cyclomatic_complexity
/// Translates the ASCII code from escape sequence to its coreeosponding `KeyCode`
/// - Parameter key: `UInt8` key to be mapped.
/// - Returns: A key code instance.
Expand Down Expand Up @@ -145,3 +146,4 @@ private extension EventParser {
}
}
}
// swiftlint:enable cyclomatic_complexity
2 changes: 1 addition & 1 deletion Sources/Core/Terminal/EventReader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public final class EventReader {
/// it returns `.failure(Error)``
/// - seeAlso: `poll`
public func readBuffer() -> Result<Event, Error> {
//sigaction(2, 1, 2)
// sigaction(2, 1, 2)
var chars: [UInt8] = Array(repeating: 0, count: bufferSize)
let readCount = read(STDIN_FILENO, &chars, bufferSize)
if readCount != -1 {
Expand Down
8 changes: 4 additions & 4 deletions Sources/Core/Terminal/Terminal.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ public final class Terminal {
public var onWindowSizeChange: ((Size) -> Void)?

public init() {
let struct_pointer = UnsafeMutablePointer<termios>.allocate(capacity: 1)
let struct_memory = struct_pointer.pointee
struct_pointer.deallocate()
originalTerminal = struct_memory
let termiosPointer = UnsafeMutablePointer<termios>.allocate(capacity: 1)
let termiosRef = termiosPointer.pointee
termiosPointer.deallocate()
originalTerminal = termiosRef
reader = EventReader(parser: EventParser())
listenToWindowSizeChange()
}
Expand Down

0 comments on commit c99d897

Please sign in to comment.