From f557825656739b37375862f71c2e2bc73cba1ab6 Mon Sep 17 00:00:00 2001 From: Tom Ludwig Date: Mon, 12 Feb 2024 18:55:52 +0100 Subject: [PATCH] Ensure Folder Existence; Create Missing Parent Folders as Needed (#33) --- Sources/CodeEditCLI/Open.swift | 41 ++++++++++++++++++++++++++++------ Sources/CodeEditCLI/main.swift | 2 -- 2 files changed, 34 insertions(+), 9 deletions(-) diff --git a/Sources/CodeEditCLI/Open.swift b/Sources/CodeEditCLI/Open.swift index fd988e4..81f4e71 100644 --- a/Sources/CodeEditCLI/Open.swift +++ b/Sources/CodeEditCLI/Open.swift @@ -26,19 +26,46 @@ extension CodeEditCLI { func run() throws { let task = Process() + let fileManager = FileManager.default // use the `open` cli as the executable task.launchPath = "/usr/bin/open" - if let path { - let (path, line, column) = try extractLineColumn(path) - let openURL = try absolutePath(path, for: task) + if let path = path { + let (filePath, line, column) = try extractLineColumn(path) + let openURL = try absolutePath(filePath, for: task) + + // Create directories if they don't exist + let directoryURL = openURL.deletingLastPathComponent() + do { + try fileManager.createDirectory( + at: directoryURL, + withIntermediateDirectories: true, + attributes: nil + ) + } catch { + print("Failed to create directory at \(directoryURL.path): \(error)") + return + } - // open CodeEdit using the url scheme - if let line, !openURL.hasDirectoryPath { - task.arguments = ["-u", "codeedit://\(openURL.path):\(line):\(column ?? 1)"] + if fileManager.fileExists(atPath: openURL.path) { + // File exists, proceed to open it + if let line = line, !openURL.hasDirectoryPath { + task.arguments = ["-u", "codeedit://\(openURL.path):\(line):\(column ?? 1)"] + } else { + task.arguments = ["-u", "codeedit://\(openURL.path)"] + } } else { - task.arguments = ["-u", "codeedit://\(openURL.path)"] + // File doesn't exist, create one + let success = fileManager.createFile(atPath: openURL.path, contents: nil, attributes: nil) + if success { + // Proceed to open the newly created file + task.arguments = ["-u", "codeedit://\(openURL.path)"] + } else { + // Handle error if file creation fails + print("Failed to create file at \(openURL.path)") + return + } } } else { task.arguments = ["-a", "CodeEdit.app"] diff --git a/Sources/CodeEditCLI/main.swift b/Sources/CodeEditCLI/main.swift index 0919243..336cf24 100644 --- a/Sources/CodeEditCLI/main.swift +++ b/Sources/CodeEditCLI/main.swift @@ -26,8 +26,6 @@ struct CodeEditCLI: ParsableCommand { defaultSubcommand: Open.self ) - init() {} - enum CLIError: Error { case invalidWorkingDirectory case invalidFileURL