Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix for symlinks bug #1840

Merged
merged 11 commits into from
Sep 14, 2024
20 changes: 20 additions & 0 deletions CodeEdit.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -466,6 +466,9 @@
77A01E2E2BB4261200F0EA38 /* CEWorkspaceSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = 77A01E2D2BB4261200F0EA38 /* CEWorkspaceSettings.swift */; };
77A01E432BBC3A2800F0EA38 /* CETask.swift in Sources */ = {isa = PBXBuildFile; fileRef = 77A01E422BBC3A2800F0EA38 /* CETask.swift */; };
77A01E6D2BC3EA2A00F0EA38 /* NSWindow+Child.swift in Sources */ = {isa = PBXBuildFile; fileRef = 77A01E6C2BC3EA2A00F0EA38 /* NSWindow+Child.swift */; };
77EF6C052C57DE4B00984B69 /* URL+ResouceValues.swift in Sources */ = {isa = PBXBuildFile; fileRef = 77EF6C032C57DE4B00984B69 /* URL+ResouceValues.swift */; };
77EF6C0B2C60C80800984B69 /* URL+Filename.swift in Sources */ = {isa = PBXBuildFile; fileRef = 77EF6C0A2C60C80800984B69 /* URL+Filename.swift */; };
77EF6C0D2C60E23400984B69 /* CEWorkspaceFileManager+DirectoryEvents.swift in Sources */ = {isa = PBXBuildFile; fileRef = 77EF6C0C2C60E23400984B69 /* CEWorkspaceFileManager+DirectoryEvents.swift */; };
850C631029D6B01D00E1444C /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 850C630F29D6B01D00E1444C /* SettingsView.swift */; };
850C631229D6B03400E1444C /* SettingsPage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 850C631129D6B03400E1444C /* SettingsPage.swift */; };
852C7E332A587279006BA599 /* SearchableSettingsPage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 852C7E322A587279006BA599 /* SearchableSettingsPage.swift */; };
Expand Down Expand Up @@ -1105,6 +1108,9 @@
77A01E2D2BB4261200F0EA38 /* CEWorkspaceSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CEWorkspaceSettings.swift; sourceTree = "<group>"; };
77A01E422BBC3A2800F0EA38 /* CETask.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CETask.swift; sourceTree = "<group>"; };
77A01E6C2BC3EA2A00F0EA38 /* NSWindow+Child.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "NSWindow+Child.swift"; sourceTree = "<group>"; };
77EF6C032C57DE4B00984B69 /* URL+ResouceValues.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "URL+ResouceValues.swift"; sourceTree = "<group>"; };
77EF6C0A2C60C80800984B69 /* URL+Filename.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "URL+Filename.swift"; sourceTree = "<group>"; };
77EF6C0C2C60E23400984B69 /* CEWorkspaceFileManager+DirectoryEvents.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CEWorkspaceFileManager+DirectoryEvents.swift"; sourceTree = "<group>"; };
850C630F29D6B01D00E1444C /* SettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsView.swift; sourceTree = "<group>"; };
850C631129D6B03400E1444C /* SettingsPage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsPage.swift; sourceTree = "<group>"; };
852C7E322A587279006BA599 /* SearchableSettingsPage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SearchableSettingsPage.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -2325,6 +2331,7 @@
5894E59629FEF7740077E59C /* CEWorkspaceFile+Recursion.swift */,
58A2E40629C3975D005CB615 /* CEWorkspaceFileIcon.swift */,
58710158298EB80000951BA4 /* CEWorkspaceFileManager.swift */,
77EF6C0C2C60E23400984B69 /* CEWorkspaceFileManager+DirectoryEvents.swift */,
6CB52DC82AC8DC3E002E75B3 /* CEWorkspaceFileManager+FileManagement.swift */,
6C049A362A49E2DB00D42923 /* DirectoryEventStream.swift */,
);
Expand Down Expand Up @@ -2407,6 +2414,7 @@
6C82D6C429C0129E00495C54 /* NSApplication */,
5831E3D02934036D00D5A6D2 /* NSTableView */,
77A01E922BCA9C0400F0EA38 /* NSWindow */,
77EF6C042C57DE4B00984B69 /* URL */,
58D01C8B293167DC00C5B6B4 /* String */,
5831E3CB2933E89A00D5A6D2 /* SwiftTerm */,
6CBD1BC42978DE3E006639D5 /* Text */,
Expand Down Expand Up @@ -2971,6 +2979,15 @@
path = NSWindow;
sourceTree = "<group>";
};
77EF6C042C57DE4B00984B69 /* URL */ = {
isa = PBXGroup;
children = (
77EF6C032C57DE4B00984B69 /* URL+ResouceValues.swift */,
77EF6C0A2C60C80800984B69 /* URL+Filename.swift */,
);
path = URL;
sourceTree = "<group>";
};
85E412282A46C8B900183F2B /* Models */ = {
isa = PBXGroup;
children = (
Expand Down Expand Up @@ -3850,6 +3867,7 @@
04BA7C192AE2D7C600584E1C /* GitClient+Branches.swift in Sources */,
587B9E8829301D8F00AC7927 /* GitHubFiles.swift in Sources */,
587B9DA729300ABD00AC7927 /* HelpButton.swift in Sources */,
77EF6C0B2C60C80800984B69 /* URL+Filename.swift in Sources */,
30B088172C0D53080063A882 /* LSPUtil.swift in Sources */,
6C5B63DE29C76213005454BA /* WindowCodeFileView.swift in Sources */,
58F2EB08292FB2B0004A9BDE /* TextEditingSettings.swift in Sources */,
Expand Down Expand Up @@ -4018,6 +4036,7 @@
201169E22837B3D800F92B46 /* SourceControlNavigatorChangesView.swift in Sources */,
850C631029D6B01D00E1444C /* SettingsView.swift in Sources */,
77A01E6D2BC3EA2A00F0EA38 /* NSWindow+Child.swift in Sources */,
77EF6C0D2C60E23400984B69 /* CEWorkspaceFileManager+DirectoryEvents.swift in Sources */,
581550CF29FBD30400684881 /* StandardTableViewCell.swift in Sources */,
B62AEDB82A1FE2DC009A9F52 /* UtilityAreaOutputView.swift in Sources */,
B67DB0FC2AFDF71F002DC647 /* IconToggleStyle.swift in Sources */,
Expand Down Expand Up @@ -4104,6 +4123,7 @@
58D01C94293167DC00C5B6B4 /* Color+HEX.swift in Sources */,
6C578D8729CD345900DC73B2 /* ExtensionSceneView.swift in Sources */,
617DB3D02C25AFAE00B58BFE /* TaskNotificationHandler.swift in Sources */,
77EF6C052C57DE4B00984B69 /* URL+ResouceValues.swift in Sources */,
B640A9A129E2188F00715F20 /* View+NavigationBarBackButtonVisible.swift in Sources */,
587B9E7929301D8F00AC7927 /* GitHubIssueRouter.swift in Sources */,
587B9E8029301D8F00AC7927 /* GitHubConfiguration.swift in Sources */,
Expand Down
43 changes: 35 additions & 8 deletions CodeEdit/Features/CEWorkspace/Models/CEWorkspaceFile.swift
armartinez marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,14 @@ import Combine
final class CEWorkspaceFile: Codable, Comparable, Hashable, Identifiable, EditorTabRepresentable {

/// The id of the ``CEWorkspaceFile``.
///
/// This is equal to `url.relativePath`
var id: String { url.relativePath }
var id: String

/// Returns the file name (e.g.: `Package.swift`)
var name: String { url.lastPathComponent.trimmingCharacters(in: .whitespacesAndNewlines) }
var name: String

/// Returns the extension of the file or an empty string if no extension is present.
var type: FileIcon.FileType {
let filename = url.lastPathComponent.trimmingCharacters(in: .whitespacesAndNewlines)
let filename = url.fileName

/// First, check if there is a valid file extension.
if let type = FileIcon.FileType(rawValue: filename) {
Expand All @@ -63,6 +61,11 @@ final class CEWorkspaceFile: Codable, Comparable, Hashable, Identifiable, Editor
/// Returns the URL of the ``CEWorkspaceFile``
let url: URL

/// Returns the resolved symlink url of this object.
lazy var linkedUrl: URL = {
url.isSymbolicLink ? url.resolvingSymlinksInPath() : url
}()

/// Return the icon of the file as `Image`
var icon: Image {
if let customImage = NSImage.symbol(named: systemImage) {
Expand Down Expand Up @@ -113,15 +116,15 @@ final class CEWorkspaceFile: Codable, Comparable, Hashable, Identifiable, Editor

/// Returns a boolean that is true if the resource represented by this object is a directory.
lazy var isFolder: Bool = {
(try? url.resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory == true
linkedUrl.isFolder
}()

/// Returns a boolean that is true if the contents of the directory at this path are
///
/// Does not indicate if this is a folder, see ``isFolder`` to first check if this object is also a directory.
var isEmptyFolder: Bool {
(try? CEWorkspaceFile.fileManager.contentsOfDirectory(
at: url,
at: linkedUrl,
includingPropertiesForKeys: nil,
options: .skipsSubdirectoryDescendants
).isEmpty) ?? true
Expand Down Expand Up @@ -151,7 +154,7 @@ final class CEWorkspaceFile: Codable, Comparable, Hashable, Identifiable, Editor

/// Return the file's UTType
var contentType: UTType? {
try? url.resourceValues(forKeys: [.contentTypeKey]).contentType
url.contentType
}

/// Returns a `Color` for a specific `fileType`
Expand All @@ -162,30 +165,54 @@ final class CEWorkspaceFile: Codable, Comparable, Hashable, Identifiable, Editor
}

init(
id: String,
name: String,
url: URL,
changeType: GitType? = nil,
staged: Bool? = false
) {
self.id = id
self.name = name
self.url = url
self.gitStatus = changeType
self.staged = staged
}

convenience init(
url: URL,
changeType: GitType? = nil,
staged: Bool? = false
) {
self.init(
id: url.relativePath,
name: url.fileName,
url: url,
changeType: changeType,
staged: staged
)
}

enum CodingKeys: String, CodingKey {
case id
case name
case url
case changeType
case staged
}

required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
id = try values.decode(String.self, forKey: .id)
name = try values.decode(String.self, forKey: .name)
url = try values.decode(URL.self, forKey: .url)
gitStatus = try values.decode(GitType.self, forKey: .changeType)
staged = try values.decode(Bool.self, forKey: .staged)
}

func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(id, forKey: .id)
try container.encode(name, forKey: .name)
try container.encode(url, forKey: .url)
try container.encode(gitStatus, forKey: .changeType)
try container.encode(staged, forKey: .staged)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
//
// CEWorkspaceFileManager+DirectoryEvents.swift
// CodeEdit
//
// Created by Axel Martinez on 5/8/24.
//

import Foundation

/// This extension handles the file system events triggered by changes in the root folder.
extension CEWorkspaceFileManager {
/// Called by `fsEventStream` when an event occurs.
///
/// This method may be called on a background thread, but all work done by this function will be queued on the main
/// thread.
/// - Parameter events: An array of events that occurred.
func fileSystemEventReceived(events: [DirectoryEventStream.Event]) {
DispatchQueue.main.async {
var files: Set<CEWorkspaceFile> = []
for event in events {
// Event returns file/folder that was changed, but in tree we need to update it's parent
let parentUrl = "/" + event.path.split(separator: "/").dropLast().joined(separator: "/")
// Find all folders poiting to the parent's file url.
armartinez marked this conversation as resolved.
Show resolved Hide resolved
let fileItems = self.flattenedFileItems.filter({
$0.value.linkedUrl.path == parentUrl
}).map { $0.value }

switch event.eventType {
case .changeInDirectory, .itemChangedOwner, .itemModified:
// Can be ignored for now, these I think not related to tree changes
continue
case .rootChanged:
// TODO: Handle workspace root changing.
thecoolwinter marked this conversation as resolved.
Show resolved Hide resolved
continue
case .itemCreated, .itemCloned, .itemRemoved, .itemRenamed:
for fileItem in fileItems {
try? self.rebuildFiles(fromItem: fileItem)
files.insert(fileItem)
}
}
}
if !files.isEmpty {
self.notifyObservers(updatedItems: files)
}

self.handleGitEvents(events: events)
}
}

func handleGitEvents(events: [DirectoryEventStream.Event]) {
// Changes excluding .git folder
let notGitChanges = events.filter({ !$0.path.contains(".git/") })

// .git folder was changed
let gitFolderChange = events.first(where: {
$0.path == "\(self.folderUrl.relativePath)/.git"
})

// Change made to git index file, staged/unstaged files
let gitIndexChange = events.first(where: {
$0.path == "\(self.folderUrl.relativePath)/.git/index"
})

// Change made to git stash
let gitStashChange = events.first(where: {
$0.path == "\(self.folderUrl.relativePath)/.git/refs/stash"
})

// Changes made to git branches
let gitBranchChange = events.first(where: {
$0.path.contains("\(self.folderUrl.relativePath)/.git/refs/heads")
})

// Changes made to git HEAD - current branch changed
let gitHeadChange = events.first(where: {
$0.path.contains("\(self.folderUrl.relativePath)/.git/HEAD")
})

// Change made to remotes by looking at .git/config
let gitConfigChange = events.first(where: {
$0.path == "\(self.folderUrl.relativePath)/.git/config"
})

// If changes were made to project OR files were staged, refresh changes
if !notGitChanges.isEmpty || gitIndexChange != nil {
Task {
await self.sourceControlManager?.refreshAllChangedFiles()
}
}

// If changes were stashed, refresh stashed entries
if gitStashChange != nil {
Task {
try await self.sourceControlManager?.refreshStashEntries()
}
}

// If branches were added or removed, refresh branches
if gitBranchChange != nil {
Task {
await self.sourceControlManager?.refreshBranches()
}
}

// If HEAD was changed, refresh the current branch
if gitHeadChange != nil {
Task {
await self.sourceControlManager?.refreshCurrentBranch()
}
}

// If git config changed, refresh remotes
if gitConfigChange != nil {
Task {
try await self.sourceControlManager?.refreshRemotes()
}
}

// If .git folder was added or removed, check if repository is valid
if gitFolderChange != nil {
Task {
try await self.sourceControlManager?.validate()
}
}
}

/// Creates or deletes children of the ``CEWorkspaceFile`` so that they are accurate with the file system,
/// instead of creating an entirely new ``CEWorkspaceFile``. Can optionally run a deep rebuild.
///
/// This method will return immediately if the given file item is not a directory.
/// This will also only rebuild *already cached* directories.
/// - Parameters:
/// - fileItem: The ``CEWorkspaceFile`` to correct the children of
/// - deep: Set to `true` if this should perform the rebuild recursively.
func rebuildFiles(fromItem fileItem: CEWorkspaceFile, deep: Bool = false) throws {
// Do not index directories that are not already loaded.
guard childrenMap[fileItem.id] != nil else { return }

// get the actual directory children
let directoryContentsUrls = try fileManager.contentsOfDirectory(
at: fileItem.linkedUrl,
includingPropertiesForKeys: nil
)

// test for deleted children, and remove them from the index
// Folders may or may not have slash at the end, this will normalize check
let directoryContentsUrlsRelativePaths = directoryContentsUrls.map({ $0.relativePath })
for (idx, oldURL) in (childrenMap[fileItem.id] ?? []).map({ URL(filePath: $0) }).enumerated().reversed()
where !directoryContentsUrlsRelativePaths.contains(oldURL.relativePath) {
flattenedFileItems.removeValue(forKey: oldURL.relativePath)
childrenMap[fileItem.id]?.remove(at: idx)
}

// test for new children, and index them
for newContent in directoryContentsUrls {
// if the child has already been indexed, continue to the next item.
guard !ignoredFilesAndFolders.contains(newContent.lastPathComponent) &&
!(childrenMap[fileItem.id]?.contains(newContent.relativePath) ?? true) else { continue }

if fileManager.fileExists(atPath: newContent.path) {
let newFileItem = createChild(newContent, forParent: fileItem)
flattenedFileItems[newFileItem.id] = newFileItem
childrenMap[fileItem.id]?.append(newFileItem.id)
}
}

childrenMap[fileItem.id] = childrenMap[fileItem.id]?
.map { URL(filePath: $0) }
.sortItems(foldersOnTop: true)
.map { $0.relativePath }

if deep && childrenMap[fileItem.id] != nil {
for child in (childrenMap[fileItem.id] ?? []).compactMap({ flattenedFileItems[$0] }) {
try rebuildFiles(fromItem: child)
}
}
}

/// Notify observers that an update occurred in the watched files.
func notifyObservers(updatedItems: Set<CEWorkspaceFile>) {
observers.allObjects.reversed().forEach { delegate in
guard let delegate = delegate as? CEWorkspaceFileManagerObserver else {
observers.remove(delegate)
return
}
delegate.fileManagerUpdated(updatedItems: updatedItems)
}
}

/// Add an observer for file system events.
/// - Parameter observer: The observer to add.
func addObserver(_ observer: CEWorkspaceFileManagerObserver) {
observers.add(observer as AnyObject)
}

/// Remove an observer for file system events.
/// - Parameter observer: The observer to remove.
func removeObserver(_ observer: CEWorkspaceFileManagerObserver) {
observers.remove(observer as AnyObject)
}
}
Loading
Loading