Skip to content

Instantly share code, notes, and snippets.

@chrisbrandow
Created July 13, 2016 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisbrandow/910b475681826c08016223d0d8598779 to your computer and use it in GitHub Desktop.
Save chrisbrandow/910b475681826c08016223d0d8598779 to your computer and use it in GitHub Desktop.
#!/usr/bin/swift
// Swift 3.0
//
// main.swift
// CSVToTables
//
// Created by Christopher Brandow on 7/12/16.
// Copyright © 2016 flouu. All rights reserved.
//
import Foundation
let separators: [Character: String] = ["=": ":---:", ">": "----:", "<": ":----"]
let separatorSet = CharacterSet(charactersIn: "><,= ")
func titleAndEntriesFrom(string: String) -> (String, String?, [String])? {
var lines = string.components(separatedBy: "\n")
guard lines.count > 1, let titleLine = lines.first else {
print("need more than one line ->")
return nil
}
lines.removeFirst()
let separatorMarkdown: String?
if let second = lines.first where CharacterSet(charactersIn: second).isSubset(of: separatorSet) {
separatorMarkdown = separatorFrom(line: second)
lines.removeFirst()
} else {
separatorMarkdown = nil
}
return (titleLine, separatorMarkdown, lines)
}
func mdTableFrom(components: (String, String?, [String])) -> String? {
let titleMarkdown = markdownFrom(line: components.0)
let titleEntries = components.0.components(separatedBy: ",")
let separatorMarkdown = components.1 ?? titleEntries.reduce("\n| "){prev, sep in "\(prev) :---: | "}
let bodyMarkdown = components.2.reduce(""){prev, line in "\(prev) \(markdownFrom(line: line))"}
return titleMarkdown + separatorMarkdown + bodyMarkdown
}
func separatorFrom(line: String) -> String {
let entries = line.components(separatedBy: ",")
let things = entries.flatMap({$0.trimmingCharacters(in: CharacterSet.whitespaces).characters.first})
let markdown = things.reduce("\n|"){prev, entry in "\(prev) \(separators[entry] ?? ":xxx:") |"}
return markdown
}
func markdownFrom(line: String) -> String {
guard line.characters.count > 0 else {
return "\n"
}
let entries = line.components(separatedBy: ",")
return entries.reduce("\n| "){prev, entry in "\(prev) \(entry.trimmingCharacters(in: CharacterSet.whitespaces)) |"}
}
var string = ""
while let thing = readLine(strippingNewline: false) {
string += thing
}
if let titleAndBody = titleAndEntriesFrom(string: string), output = mdTableFrom(components: titleAndBody) {
print(output)
} else {
print(string)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment