Swift - How to modify file metadata like kMDItemDisplayName? - swift

I'm trying to find a way to change a file's metadata attributes (those with the prefix of "kMDItem", listed by mdls), but I didn't find any solution for it. ToT
At first, I've tried using FileManager.default.setAttributes(_attributes:ofItemAtPath:), but this method only gives me few options, it only gives me ability to modify a file's modification date, creation date and posix permissions etc., which is not enough.
Then, I tried using NSMetadataItem with setValue(_value:forKey:) function to change the metadata value, this is my code:
var attributes = NSMetadataItem(url: URL(fileURLWithPath: "/path/to/file")
if let metadata = attributes {
metadata.setValue(newValue, forKey: kMDItemDisplayName as String)
metadata.setValue(newValue, forKey: NSMetadataItemDisplayNameKey)
// I've tried both of them from above (different keys), they both does not work at all
}
I noticed that setValue(_value:forKey:) does not do anything here by repeatedly getting this returning error: error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
Finally, I red this post on StackOverflow, which led my way to this code:
_ = setxattr("/path/to/file".cString(using: .utf8), "kMDItemDisplayName", newValue.cString(using: .utf8), newValue.lengthOfBytes(using: .utf8), 0, 0)
After executing it, I used mdls and xattr -l to check the result, I realized that this is only the solution for adding extended attributes to a file, the metadata didn't change, only the extended attribute with the name of "kMDItemDisplayName" is successfully added.
The result is not what I want (I'm just using kMDItemDisplayName as an example for my question), I do not just want to find a way to add extended attributes to a file, but a way to edit the attributes listed by mdls. Maybe there is no solution for this? Or maybe I should do it in a completely different way?

Not all metadata can be changed. Much of it is not stored directly, it's derived or computed based on other metadata.
The display name for a simple file is derived from its name on disk and the system settings, like whether extensions are hidden or shown. The display name for a bundle (like an app) is slightly more complicated, but, assuming you don't find changing the contents of the bundle (which would break its code signature) acceptable, amounts to the same thing. Those are subject to the system language(s).
There are also certain folders whose names can be localized for display, but that's still based on their on-disk name.
So, to change a file's display name, change its actual name on disk.
For other properties, you can look at URL.setResourceValues(_:) and URLResourceValues to see which properties are settable. You can also look at URLResourceKey to see which are documented as "read-write".

Related

How can I manually edit the list of recently opened files in VS Code?

I rely heavily on the File: Open Recent… command to open frequently used files, but yesterday my local Google Drive folder got moved to a new location and now I can no longer access any of the files in that folder through the Open Recent panel because the paths don't match.
The fix would be as simple as replacing "/Google Drive/" with "/Google Drive/My Drive/" but I have no idea what file contains the list of files that appears in the recently opened panel.
I'm assuming it's somewhere in ~/Library/Application Support/Code but not sure where.
I was wondering the same thing the other day and found this while searching for a solution, so I took some time to investigate it today.
It's been a a few weeks since you posted, so hopefully this will still be of help to you.
Also, I'm using Windows and I'm not familiar with macOS, but I think it should be easy enough adjust the solution.
Location of settings
Those setting are stored in the following file: %APPDATA%\Code\User\globalStorage\state.vscdb.
The file is an sqlite3 database, which is used as a key-value store.
It has a single table named ItemTable and the relevant key is history.recentlyOpenedPathsList.
The value has the following structure:
{
"entries": [
{
"folderUri": "/path/to/folder",
"label": "...",
"remoteAuthority": "..."
}
]
}
To view the current list, you can run the following command:
sqlite3.exe -readonly "%APPDATA%\Code\User\globalStorage\state.vscdb" "SELECT [value] FROM ItemTable WHERE [key] = 'history.recentlyOpenedPathsList'" | jq ".entries[].label"
Modifying the settings
Specifically, I was interested in changing the way it's displayed (the label), so I'll detail how I did that, but it should be just as easy to update the path.
Here's the Python code I used to make those edits:
import json, sqlite3
# open the db, get the value and parse it
db = sqlite3.connect('C:/Users/<username>/AppData/Roaming/Code/User/globalStorage/state.vscdb')
history_raw = db.execute("SELECT [value] FROM ItemTable WHERE [key] = 'history.recentlyOpenedPathsList'").fetchone()[0]
history = json.loads(history_raw)
# make the changes you'd like
# ...
# stringify and update
history_raw = json.dumps(history)
db.execute(f"UPDATE ItemTable SET [value] = '{history_raw}' WHERE key = 'history.recentlyOpenedPathsList'")
db.commit()
db.close()
Code references
For reference (mostly for my future self), here are the relevant source code areas.
The settings are read here.
The File->Open Recent uses those values as-is (see here).
However when using the Get Started page, the Recents area is populated here. In the Get Started, the label is presented in a slightly different way:
vscode snapshot
The folder name is the link, and the parent folder is the the text beside it.
This is done by the splitName method.
Notes
Before messing around with the settings file, it would be wise to back it up.
I'm not sure how vscode handles and caches the settings, so I think it's best to close all vscode instances before making any changes.
I haven't played around with it too much, so not sure how characters that need to be json-encoded or html-encoded will play out.
Keep in mind that there might be some state saved by other extensions, so if anything weird happens, blame it on that.
For reference, I'm using vscode 1.74.2.
Links
SQLite command-line tools
jq - command-line JSON processor

How can you add additional values to a URL directory in Swift?

I want to create a GUI which displays folders in different colors. I dont know how to store a color value to a directory. I already tried URL Extended Attributes but these one are only stored locally and iCloud strips them aways for some reason.
I found a solution. You have to add #s at the end of your extended name. This ensures that it will be synched.
S: XATTR_FLAG_SYNCABLE, which ensures the xattr is preserved even during syncing. Default behaviour is for xattrs to be stripped during syncing, to minimise the amount of data to be transferred, but this will override that default.
You can read more about it here :
https://eclecticlight.co/2020/03/18/which-extended-attributes-does-icloud-preserve-and-which-get-stripped/

TYPO3 - Extbase - Detect missing files for a given FileReference

I've tried three different ways to detect if a FileReference's original file is still existing (i.e. file has been deleted outside TYPO3 using SFTP or similar):
if($fileReference instanceof \TYPO3\CMS\Extbase\Domain\Model\FileReference) {
$isMissing = $fileReference->getOriginalResource()->getStorage()->getFile($fileReference->getOriginalResource()->getIdentifier())->isMissing();
$isMissing = $fileReference->getOriginalResource()->getOriginalFile()->isMissing();
$isMissing = $fileReference->getOriginalResource()->isMissing();
}
Only the first one give me the right isMissing() value.
The property isMissing is an database value, which is set if the storage detect an missing file. On getFile the storage check if the file is missing and set "isMissing" for the file. If you dont persist this to the database, the setting is get loose with the next call.
You can also call $isMissing = $fileReference->getOriginalResource()->getStorage()->hasFile($fileReference->getOriginalResource()->getIdentifier());
You can run the file indexer scheduler (TYPO3\CMS\Scheduler\Task\FileStorageIndexingTask) if you want to check frequently for deleted files. This should be required if you let change files externaly (like ftp).

Creating a translator/dictionary in IOS

So Im importing a text file that contains a list of character sets. These sets have a meaning they refer to a status of an object. For example TOMTOM100 means Delivery announced. Ones i import he text file the status is presented in 0-5 labels(depends on how many status updates are available).
At first i wanted to do this with a if statement but quickly realized that it would be to much.
if ((trackTraceStatusone.text = #"TOMTOM100"))
{
trackTraceStatusone.text = #"Delivery announced.";
}
Is there a way to create some kind of translator that automatically translates the status in a readable format?
TOMTOM100 > Delivery announced
TOMTOM101 > Delivery Scanned
and so on.
Sounds like a job for NSLocalizedStringFromTable() or the corresponding NSBundle method -localizedStringForKey:value:table:. This will let you load the string from a .strings file in your bundle, which will look something like this:
"TOMTOM100" = "Delivery Announced";
"TOMTOM101" = "Delivery Scanned";
This will also make it easy to provide different strings for different languages. For more information, see the String Resources section of the Resource Programming Guide.

How to add an extra plist property using CMake?

I'm trying to add the item
<key>UIStatusBarHidden</key><true/>
to my plist that's auto-generated by CMake. For certain keys, it appears there are pre-defined ways to add an item; for example:
set(MACOSX_BUNDLE_ICON_FILE ${ICON})
But I can't find a way to add an arbitrary property.
I tried using the MACOSX_BUNDLE_INFO_PLIST target property as follows: I'd like the resulting plist to be identical to the old one, except with the new property I want, so I just copied the auto-generated plist and set that as my template. But the plist uses some Xcode variables, which also look like ${foo}, and CMake grumbles about this:
Syntax error in cmake code when
parsing string
<string>com.bedaire.${PRODUCT_NAME:identifier}</string>
syntax error, unexpected cal_SYMBOL,
expecting } (47)
Policy CMP0010 is not set: Bad
variable reference syntax is an error.
Run "cmake --help-policy CMP0010"
for policy details. Use the
cmake_policy command to set the
policy and suppress this warning. This
warning is for project developers.
Use -Wno-dev to suppress it.
In any case, I'm not even sure that this is the right thing to do. I can't find a good example or any good documentation about this. Ideally, I'd just let CMake generate everything as before, and just add a single extra line. What can I do?
Have you looked into copying the relevant *.plist.in file in /opt/local/share/cmake-2.8/Modules (such as MacOSXBundleInfo.plist.in), editing it to put <key>UIStatusBarHidden</key><true/> (or #VAR_TO_REPLACE_BY_CMAKE#), and adding the directory of the edited version in the CMAKE_MODULE_PATH?
If you have CMake installed as an app bundle, then the location of that file is /Applications/CMake.app/Contents/share/cmake-N.N/Modules
You can add your values using # and pass #ONLY to configure_file.
Unfortunately there is no simple way to add custom line to generated file.