开发者

How to move a symlink to the trash?

开发者 https://www.devze.com 2022-12-31 14:44 出处:网络
I don\'t see any options for the FSPathMoveObjectToTrashSync() function for not follow开发者_C百科ing links.

I don't see any options for the FSPathMoveObjectToTrashSync() function for not follow开发者_C百科ing links.

Here is what I have tried

Create a link and a file

[ 21:32:41 /tmp ] $ touch my_file
[ 21:32:45 /tmp ] $ ln -s my_file my_link
[ 21:32:52 /tmp ] $ la
total 8
drwxrwxrwt   12 root     wheel   408 17 Maj 21:32 .
drwxr-xr-x@   6 root     wheel   204  9 Sep  2009 ..
-rw-r--r--    1 neoneye  wheel     0 17 Maj 21:32 my_file
lrwxr-xr-x    1 neoneye  wheel     7 17 Maj 21:32 my_link -> my_file

Move the link to the trash

OSStatus status = FSPathMoveObjectToTrashSync(
    "/tmp/my_link",
    NULL,
    kFSFileOperationDefaultOptions
);
NSLog(@"status: %i", (int)status);

Output is

status: 0

However the file got removed and not the link

[ 21:32:55 /tmp ] $ la
total 8
drwxrwxrwt   11 root     wheel   374 17 Maj 21:33 .
drwxr-xr-x@   6 root     wheel   204  9 Sep  2009 ..
lrwxr-xr-x    1 neoneye  wheel     7 17 Maj 21:32 my_link -> my_file
[ 21:33:05 /tmp ] $

How can I move move symlinks to the trash?


The Solution.. thanks to Rob Napier

NSString* path = @"/tmp/my_link";
OSStatus status = 0;

FSRef ref;
status = FSPathMakeRefWithOptions(
    (const UInt8 *)[path fileSystemRepresentation], 
    kFSPathMakeRefDoNotFollowLeafSymlink,
    &ref, 
    NULL
);  
NSAssert((status == 0), @"failed to make FSRef");

status = FSMoveObjectToTrashSync(
    &ref,
    NULL,
    kFSFileOperationDefaultOptions
);
NSLog(@"status: %i", (int)status);


Use FSPathMakeRefWithOptions() to generate an FSRef to the link. Then use FSMoveObjectToTrashSync() to delete it.


The other way would be to tell the NSWorkspace to “recycle” it, by sending it either a performFileOperation:source:destination:files:tag: message with the NSWorkspaceRecycleOperation operation or a recycleURLs:completionHandler: message.

I don't know how well either one of these would work on symlinks, but it's worth trying if you'd rather not deal with FSRefs.


my retro-futuristic approach

https://github.com/reklis/recycle

//
//  main.swift
//  recycle
//
//  usage: recycle <files or directories to throw out>
//

import Foundation
import AppKit

var args = NSProcessInfo.processInfo().arguments
args.removeAtIndex(0)   // first item in list is the program itself

var w = NSWorkspace.sharedWorkspace()
var fm = NSFileManager.defaultManager()

for arg in args {
    let path = arg.stringByStandardizingPath;

    let file = path.lastPathComponent
    let source = path.stringByDeletingLastPathComponent

    w.performFileOperation(NSWorkspaceRecycleOperation,
        source:source,
        destination: "",
        files: [file],
        tag: nil)
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号