Using Swift for export scripts

This script showcases a straightforward way to customize your exported HTML using Swift. You can extend this script to include more complex logic based on your needs. The script is designed to be run as a Hype Export Script, where it gets triggered during the export process, and modifies the staging HTML file before it gets saved to the destination path.

It necessitates the use of development tools, and must be made executable, with the filename ending in FILENAME.hype-export.swift .


#!/usr/bin/swift

import Foundation

func exitWithResult(_ result: [String: Any]) {
    let resultData = try! JSONSerialization.data(withJSONObject: result, options: [])
    let resultString = String(data: resultData, encoding: .utf8)!
    print("====================")
    print(resultString)
    exit(0)
}

func addScriptTagToHead(of htmlFilePath: String) {
    var htmlContent = (try? String(contentsOfFile: htmlFilePath)) ?? ""
    let scriptTag = "<script>console.log('Hello, World!');</script>"
    if let headEndRange = htmlContent.range(of: "</head>", options: .caseInsensitive) {
        htmlContent.insert(contentsOf: scriptTag, at: headEndRange.lowerBound)
        try? htmlContent.write(toFile: htmlFilePath, atomically: true, encoding: .utf8)
    }
}

func main() {
    let arguments = CommandLine.arguments
    guard arguments.count > 1 else {
        print("No arguments provided.")
        return
    }
    
    let action = arguments[1]
    
    if action == "--modify_staging_path" {
        guard arguments.count >= 3 else {
            print("Insufficient arguments for --modify_staging_path action.")
            return
        }
        
        let stagingPath = arguments[2]
        let htmlFilePath = "\(stagingPath)/index.html" 
        addScriptTagToHead(of: htmlFilePath)
        
        exitWithResult(["success": true])
    }
}

main()
2 Likes

That's fun! I wasn't aware you could run swift like a script.

1 Like