Skip to content

Instantly share code, notes, and snippets.

@loganmoseley
Created January 8, 2018 19:31
Show Gist options
  • Save loganmoseley/bb4e9d9478338ba68b4469c57bee0195 to your computer and use it in GitHub Desktop.
Save loganmoseley/bb4e9d9478338ba68b4469c57bee0195 to your computer and use it in GitHub Desktop.
Remove headers from all .c .h .m and .swift templates in Xcode.
#!/usr/bin/swift
/// Args:
/// --xcode {XCODE_PATH}
import Foundation
extension Array {
func paired() -> [(Element, Element)] {
return stride(from: 0, to: count - 1, by: 2).map {
(self[$0], self[$0 + 1])
}
}
}
// naïve, assumes one key per one value
func argDict(fromCommandLineArgs args: [String]) -> [String : String] {
let tail = Array(args.dropFirst())
return Dictionary(uniqueKeysWithValues: tail.paired() )
}
// copies the URL if the item does not already exist
func backup(_ url: URL) throws {
let urlOrig = url.appendingPathExtension("orig")
try FileManager.default.copyItem(at: url, to: urlOrig)
}
func hasExtension(any exts: [String]) -> (URL) -> Bool {
return { exts.contains($0.pathExtension) }
}
func removingFileHeader(from str: String) -> String {
if let r = str.range(of: "//___FILEHEADER___\n\n") {
var new = str
new.removeSubrange(r)
return new
}
return str
}
func urls(enumerator: FileManager.DirectoryEnumerator) -> [URL] {
var ret = [URL]()
while let url = enumerator.nextObject() as? URL {
ret.append(url)
}
return ret
}
// MARK: Do it
let argsDict = argDict(fromCommandLineArgs: CommandLine.arguments)
let userXcodePath = argsDict["--xcode"].map(URL.init(fileURLWithPath:))
guard let xcodePath = userXcodePath else {
print("""
Please point me to an Xcode app you'd like to patch. Use '--xcode {XCODE_PATH}'. For example,
./remove-fileheader.swift --xcode /Applications/Xcode.app
""")
exit(0)
}
let templates = xcodePath.appendingPathComponent("Contents/Developer/Library/Xcode/Templates/File Templates/Source", isDirectory: true)
try? backup(templates)
guard let en = FileManager.default.enumerator(at: templates, includingPropertiesForKeys: nil) else {
print("ABORT: Could not enumerate template dir: \(templates)")
exit(0)
}
let all = urls(enumerator: en)
let code = all.filter(hasExtension(any: ["c", "h", "m", "swift"]))
code.forEach { url in
let str = try! String(contentsOf: url)
let new = removingFileHeader(from: str)
try! new.write(to: url, atomically: true, encoding: .utf8)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment