TagSpaces is an offline, open source, document manager with tagging support
chore: redesign the mac os tag extraction with added tests
Ilian Sapundshievb497bf813fbb
diff --git a/src/main/macUserTags.ts b/src/main/macUserTags.tsnew file mode 100644index 000000000..d6cedff61--- /dev/null+++ b/src/main/macUserTags.ts@@ -0,0 +1,94 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2017-present TagSpaces GmbH+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License (version 3) as+ * published by the Free Software Foundation.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ */++/**+ * macOS Finder tags. Kept out of `util.ts` (which imports electron) so the pure+ * parser can be unit-tested in plain Node; `readMacOSTags` only needs+ * `child_process`.+ */+import { execFile } from 'child_process';++const MAC_USER_TAGS_ATTR = 'com.apple.metadata:_kMDItemUserTags';++/**+ * Pure parser for macOS Finder tags. Finder tags live in the+ * `com.apple.metadata:_kMDItemUserTags` extended attribute as a binary plist+ * holding an array of strings. Each entry is either a bare tag name+ * (`"Important"`) or, when a Finder color is assigned, `"Name\nColorIndex"`+ * (e.g. `"Important\n4"`). This takes the already-decoded array (e.g. plutil's+ * JSON output) and returns clean tag objects.+ */+export function parseMacUserTags(parsed: unknown): { title: string }[] {+ if (!Array.isArray(parsed)) {+ return [];+ }+ return parsed+ .map((entry) => String(entry).split('\n')[0].trim())+ .filter((title) => title.length > 0)+ .map((title) => ({ title }));+}++/**+ * Read macOS Finder tags for a file.+ *+ * Reads the `com.apple.metadata:_kMDItemUserTags` extended attribute directly+ * (a binary plist) instead of `mdls`. `mdls` only surfaces tags that Spotlight+ * has indexed, so it returns "could not find …" / null on volumes or folders+ * that aren't indexed (Spotlight disabled, external/network drives, freshly+ * written files) even though the tags are present on disk — which made the+ * Finder-tag import silently return nothing. The xattr is the source of truth.+ *+ * @param filename absolute path+ * @returns {Promise<{ title: string }[]>}+ */+export async function readMacOSTags(filename) {+ return new Promise((resolve, reject) => {+ // Dump the attribute as hex (the binary plist). Missing attribute → xattr+ // exits non-zero → no tags.+ execFile(+ '/usr/bin/xattr',+ ['-px', MAC_USER_TAGS_ATTR, filename],+ (xErr, xOut) => {+ if (xErr) {+ return resolve([]);+ }+ const hex = (xOut || '').replace(/\s+/g, '');+ if (!hex) {+ return resolve([]);+ }+ // Decode the binary plist to JSON via plutil (reads bytes from stdin).+ const plutil = execFile(+ '/usr/bin/plutil',+ ['-convert', 'json', '-o', '-', '-'],+ (pErr, pOut) => {+ if (pErr) {+ return reject(pErr);+ }+ try {+ resolve(parseMacUserTags(JSON.parse(pOut)));+ } catch (e) {+ reject(e);+ }+ },+ );+ plutil.stdin.write(Buffer.from(hex, 'hex'));+ plutil.stdin.end();+ },+ );+ });+}diff --git a/src/main/mainEvents.ts b/src/main/mainEvents.tsindex 25d2f8560..5cf6c8d22 100644--- a/src/main/mainEvents.ts+++ b/src/main/mainEvents.ts@@ -41,8 +41,8 @@ import {ollamaGetRequest,ollamaPostRequest,postRequest,- readMacOSTags,} from './util';+import { readMacOSTags } from './macUserTags';import os from 'os';import registerSecureStorageEvents from './secureStorage';diff --git a/src/main/util.ts b/src/main/util.tsindex aa4e89845..de2020683 100644--- a/src/main/util.ts+++ b/src/main/util.ts@@ -2,7 +2,6 @@import { URL } from 'url';import path from 'path';import { BrowserWindow } from 'electron';-import { execFile } from 'child_process';import http from 'http';import settings from './settings';@@ -323,35 +322,6 @@ export function ollamaPostRequest(});}-/**- * @param filename- * @returns {Promise<TS.Tag[]>}- */-export async function readMacOSTags(filename) {- return new Promise((resolve, reject) => {- const args = ['-raw', '-name', 'kMDItemUserTags', filename];- execFile('mdls', args, (error, stdout, stderr) => {- if (error) {- if (error.code === 1 && !stderr) {- return resolve([]);- }- return reject(error);- }- if (stderr) return reject(new Error(stderr));-- const text = stdout.trim();- if (!text || text === '(null)') {- return resolve([]);- }- const tags = text- .replace(/^\(|\)$/g, '')- .split(',')- .map((item) => ({ title: item.trim() }));- resolve(tags);- });- });-}-/*** needs to run in init this function always return false first time*/diff --git a/src/renderer/components/dialogs/ImportMacTagDialog.tsx b/src/renderer/components/dialogs/ImportMacTagDialog.tsxindex 8f573fb7d..9211861af 100644--- a/src/renderer/components/dialogs/ImportMacTagDialog.tsx+++ b/src/renderer/components/dialogs/ImportMacTagDialog.tsx@@ -22,6 +22,7 @@ import DialogCloseButton from '-/components/dialogs/DialogCloseButton';import TsDialogActions from '-/components/dialogs/components/TsDialogActions';import { useProgressDialogContext } from '-/components/dialogs/hooks/useProgressDialogContext';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';import { useNotificationContext } from '-/hooks/useNotificationContext';import { useTaggingActionsContext } from '-/hooks/useTaggingActionsContext';import TsSwitch from '-/components/TsSwitch';@@ -49,7 +50,8 @@ function ImportMacTagDialog(props: Props) {useProgressDialogContext();const { showNotification } = useNotificationContext();const { currentLocation } = useCurrentLocationContext();- const { addTags } = useTaggingActionsContext();+ const { openCurrentDirectory } = useDirectoryContentContext();+ const { addTagsToFsEntry } = useTaggingActionsContext();const recursive = useRef<boolean>(false);const [ignored, forceUpdate] = useReducer((x) => x + 1, 0, undefined);@@ -70,18 +72,29 @@ Do you want to continue?`)}*/openProgressDialog('importingMacTags');- const entryCallback = (entry) => {+ // Persist each file's tags WITHOUT reflecting per file: the walk visits+ // many entries concurrently and each setReflectActions() replaces the+ // previous one, so per-file reflects clobber each other (only the last+ // file would update, and from the walk entry which lacks a thumbPath).+ // Persist quietly, then refresh the directory once at the end so every+ // file shows its tags — and its thumbnail.+ let appliedCount = 0;+ const entryCallback = (entry) =>readMacOSTags(entry.path).then((tags) => {if (tags.length > 0) {- addTags([entry], tags);+ appliedCount += 1;+ // reflect=false → no per-file UI update; collectTags=true keeps+ // the imported tags in the tag library as before.+ return addTagsToFsEntry(entry, tags, false, true);}- return tags;+ return undefined;}).catch((err) => {console.log('Error creating tags: ' + err);+ return undefined;});- };+Pro.MacTagsImport.importTags(directoryPath,currentLocation.listDirectoryPromise,@@ -89,8 +102,16 @@ Do you want to continue?`)recursive.current,).then(() => {- closeProgressDialog();console.log('Import tags succeeded ' + directoryPath);+ // Single refresh re-reads the on-disk sidecars (tags) and resolves+ // thumbnails for the whole directory at once.+ if (appliedCount > 0) {+ return openCurrentDirectory();+ }+ return true;+ })+ .then(() => {+ closeProgressDialog();showNotification('Tags from ' + directoryPath + ' are imported successfully.','default',diff --git a/tests/unit/macUserTags.test.js b/tests/unit/macUserTags.test.jsnew file mode 100644index 000000000..9dc8be5b3--- /dev/null+++ b/tests/unit/macUserTags.test.js@@ -0,0 +1,39 @@+import { describe, expect, test } from '@playwright/test';+import { parseMacUserTags } from '../../src/main/macUserTags';++// The arrays below mirror what `plutil -convert json` produces when decoding the+// com.apple.metadata:_kMDItemUserTags binary plist, e.g. the payload+// plistlib.dumps(['Important\n4', 'Two Words\n6']) decodes to+// ['Important\n4', 'Two Words\n6'].+describe('parseMacUserTags', () => {+ test('strips the "\\nColorIndex" suffix, trims and drops empties', () => {+ expect(+ parseMacUserTags([+ 'Important\n4',+ 'Two Words\n6',+ 'Plain',+ ' Spaced \n2',+ '',+ ]),+ ).toEqual([+ { title: 'Important' },+ { title: 'Two Words' },+ { title: 'Plain' },+ { title: 'Spaced' },+ ]);+ });++ test('tags without a color index pass through unchanged', () => {+ expect(parseMacUserTags(['Red', 'Blue'])).toEqual([+ { title: 'Red' },+ { title: 'Blue' },+ ]);+ });++ test('non-array / empty input → []', () => {+ expect(parseMacUserTags(null)).toEqual([]);+ expect(parseMacUserTags(undefined)).toEqual([]);+ expect(parseMacUserTags('Important')).toEqual([]);+ expect(parseMacUserTags([])).toEqual([]);+ });+});