1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
|
%global _empty_manifest_terminate_build 0
Name: python-osxmetadata
Version: 1.3.0
Release: 1
Summary: Read and write meta data, such as tags/keywords, Finder comments, etc. on MacOS files
License: MIT
URL: https://github.com/RhetTbull/osxmetadata
Source0: https://mirrors.aliyun.com/pypi/web/packages/1b/f0/8c0b0978a917de1601b729849d2e150505036b0db5ab30cad0efe67bd869/osxmetadata-1.3.0.tar.gz
BuildArch: noarch
Requires: python3-bitstring
Requires: python3-click
Requires: python3-py-applescript
Requires: python3-pyobjc-core
Requires: python3-pyobjc-framework-AVFoundation
Requires: python3-pyobjc-framework-AppleScriptKit
Requires: python3-pyobjc-framework-AppleScriptObjC
Requires: python3-pyobjc-framework-CoreMedia
Requires: python3-pyobjc-framework-CoreServices
Requires: python3-pyobjc-framework-Quartz
Requires: python3-pyobjc-framework-ScriptingBridge
Requires: python3-twine
Requires: python3-wheel
Requires: python3-xattr
%description
# osxmetadata
[](https://github.com/python/black)
[](https://opensource.org/licenses/MIT)
[](#contributors-)
## What is osxmetadata?
osxmetadata provides a simple interface to access various metadata about MacOS / OS X files. Currently supported metadata attributes include tags/keywords, Finder comments, authors, etc.
## Why osxmetadata?
Apple provides rich support for file metadata through the [MDItem](https://developer.apple.com/documentation/coreservices/file_metadata/mditem) class and the [NSURL getResourceValue:forKey:error:](https://developer.apple.com/documentation/foundation/nsurl/1408874-getresourcevalue?language=objc) method. However, Apple does not provide a way to easily set much of the metadata. For example, while there is a documented [MDItem MDItemCopyAttribute](https://developer.apple.com/documentation/coreservices/1427080-mditemcopyattribute?language=objc) to copy metadata attributes such as [kMDItemAuthors](https://developer.apple.com/documentation/coreservices/kmditemauthors?language=objc), Apple does not provide a public interface to set this data. Other data, such as Finder comments, can only be set through sending AppleScript commands to the Finder and others, like Finder tags can be retrieved but cannot be set through the public API.
osxmetadata provides a unified interface to get and set most of the metadata available on your Mac from python. It uses a combination of documented and undocumented APIs to access the metadata. It also provides a simple interface to set Finder tags and Finder comments.
MacOS provides some tools to view these various metadata attributes. For example, `mdls` lists the MDItem Spotlight metadata associated with a file but doesn't let you edit the data. osxmetadata makes it easy to to both view and manipulate the macOS metadata attributes, either programmatically or through an included `osxmetadata` command line tool.
## Supported operating systems
Only works on MacOS. Requires Python 3.8+. Tested on macOS 10.15.7 (Catalina); should work on all versions of macOS 10.15 and later.
## Installation instructions
### Installation using pipx
If you aren't familiar with installing python applications, I recommend you install `osxmetadata` with [pipx](https://github.com/pipxproject/pipx). If you use `pipx`, you will not need to create a virtual environment as `pipx` takes care of this. The easiest way to do this on a Mac is to use [homebrew](https://brew.sh/):
- Open `Terminal` (search for `Terminal` in Spotlight or look in `Applications/Utilities`)
- Install `homebrew` according to instructions at [https://brew.sh/](https://brew.sh/)
- Type the following into Terminal: `brew install pipx`
- Then type this: `pipx install osxmetadata`
- Now you should be able to run `osxmetadata` by typing: `osxmetadata`
Once you've installed osxmetadata with pipx, to upgrade to the latest version:
pipx upgrade osxmetadata
### Installation using pip
You can also install directly from [pypi](https://pypi.org/project/osxmetadata/):
pip install osxmetadata
Once you've installed osxmetadata with pip, to upgrade to the latest version:
pip install --upgrade osxmetadata
### Installation from git repository
OSXMetaData uses setuptools, thus simply run:
git clone https://github.com/RhetTbull/osxmetadata.git
cd osxmetadata
pip install poetry
poetry install
I recommend you create a [virtual environment](https://docs.python.org/3/tutorial/venv.html) before installing osxmetadata.
## Using the API
```pycon
>>> import datetime
>>> import pathlib
>>> from osxmetadata import *
>>> pathlib.Path("test_file.txt").touch()
>>> md = OSXMetaData("test_file.txt")
>>> md.set(kMDItemAuthors, ["Jane Smith", "John Doe"])
>>> md.get(kMDItemAuthors)
['Jane Smith', 'John Doe']
>>> md.kMDItemFinderComment = "This is my comment"
>>> md.kMDItemFinderComment
'This is my comment'
>>> md.tags = [Tag("Test", FINDER_COLOR_NONE), Tag("ToDo", FINDER_COLOR_RED)]
>>> md.tags
[Tag(name='Test', color=0), Tag(name='ToDo', color=6)]
>>> md[kMDItemDueDate] = datetime.datetime(2022,10,1)
>>> md[kMDItemDueDate]
datetime.datetime(2022, 10, 1, 0, 0)
>>>
```
Somewhat contrary to the [Zen of Python](https://peps.python.org/pep-0020/), osxmetadata provides more than one way to access metadata attributes. You can get and set metadata attributes using the `get()`/`set()` getter/setter methods, using the attribute name as a dictionary key on the OSXMetaData object, or using the attribute name as an attribute on the `OSXMetaData()` object. For example, the following are all equivalent:
- `OSXMetaData.get(attribute)` - get the value of the metadata attribute `attribute`
- `OSXMetaData[attribute]` - get the value of the metadata attribute `attribute`
- `OSXMetaData.attribute` - get the value of the metadata attribute `attribute`
As are the following:
- `OSXMetaData.set(attribute, value)` - set the value of the metadata attribute `attribute` to `value`
- `OSXMetaData[attribute] = value` - set the value of the metadata attribute `attribute` to `value`
- `OSXMetaData.attribute = value` - set the value of the metadata attribute `attribute` to `value`
This allows you to use osxmetadata in accordance with your own code style preferences.
Supported attribute names include all attributes defined for [MDItem](https://developer.apple.com/documentation/coreservices/file_metadata/mditem) and all resource keys defined for [NSURL](https://developer.apple.com/documentation/foundation/nsurl?language=objc). Additionally, the metadata constants defined in the [MDImporter](https://developer.apple.com/documentation/coreservices/file_metadata/mdimporter?language=objc) are supported as well as the following additional attributes:
- `_kMDItemUserTags` - list of Finder tags
- `kMDItemDownloadedDate` - list of datetime objects for when the file was downloaded
Additionally, osxmetadata defines a "shortcut name" attribute for each MDItem attribute that can be used as a shortcut `OSXMetaData` class attribute. The shortcut name is the lowercase value of text following `kMDItem` for each attribute. For example, `kMDItemAuthors` has a short name of `authors` so you can set the authors like this:
```pycon
>>> from osxmetadata import *
>>> md = OSXMetaData("test_file.txt")
>>> md.authors = ["Jane Smith", "John Doe"]
>>> md.authors
['Jane Smith', 'John Doe']
>>>
```
and `kMDItemDueDate` would have a short name of `duedate`:
```pycon
>>> from osxmetadata import *
>>> import datetime
>>> md = OSXMetaData("test_file.txt")
>>> md.duedate = datetime.datetime(2022, 10, 1)
>>> md.duedate
datetime.datetime(2022, 10, 1, 0, 0)
>>>
```
The names of all supported attributes are available in the `osxmetadata.ALL_ATTRIBUTES` set:
```pycon
>>> from osxmetadata import ALL_ATTRIBUTES
>>> "kMDItemDueDate" in ALL_ATTRIBUTES
True
>>> "NSURLTagNamesKey" in ALL_ATTRIBUTES
True
>>> "findercomment" in ALL_ATTRIBUTES
True
>>>
```
The class attributes are handled dynamically which, unfortunately, means that IDEs like PyCharm and Visual Studio Code cannot provide tab-completion for them.
## Finder Tags
Unlike other attributes, which are mapped to native Python types appropriate for the source Objective C type, Finder tags (`_kMDItemUserTags` or `tags`) have two components: a name (str) and a color ID (unsigned int in range 0 to 7) representing a color tag in the Finder. Reading tags returns a list of `Tag` namedtuples and setting tags requires a list of `Tag` namedtuples.
```pycon
>>> from osxmetadata import *
>>> md = OSXMetaData("test_file.txt")
>>> md.tags = [Tag("Test", FINDER_COLOR_NONE), Tag("ToDo", FINDER_COLOR_RED)]
>>> md.tags
[Tag(name='Test', color=0), Tag(name='ToDo', color=6)]
>>> md.get("_kMDItemUserTags")
[Tag(name='Test', color=0), Tag(name='ToDo', color=6)]
>>>
```
Tag names (but not colors) can also be accessed through the [NSURLTagNamesKey](https://developer.apple.com/documentation/foundation/nsurltagnameskey) resource key and the label color ID is accessible through `NSURLLabelNumberKey`; the localized label color name is accessible through `NSURLLocalizedLabelKey` though these latter two resource keys only return a single color whereas a file may have more than one color tag. For most purposes, I recommend using the `tags` attribute as it is more convenient and provides access to both the name and color ID of the tag.
```pycon
>>> from osxmetadata import *
>>> md = OSXMetaData("test_file.txt")
>>> md.tags = [Tag("Test", FINDER_COLOR_NONE), Tag("ToDo", FINDER_COLOR_RED)]
>>> md.tags
[Tag(name='Test', color=0), Tag(name='ToDo', color=6)]
>>> md.NSURLTagNamesKey
(
Test,
ToDo
)
>>> md.NSURLLabelNumberKey
6
>>> md.NSURLLocalizedLabelKey
'Red'
>>> md.NSURLTagNamesKey = ["NewTag"]
>>> md.NSURLTagNamesKey
(
NewTag
)
>>> md.tags
[Tag(name='NewTag', color=0)]
>>>
```
### Create a Tag namedtuple
`Tag(name, color)`
- `name`: tag name (str)
- `color`: color ID for Finder color label associated with tag (int)
Valid color constants (exported by osxmetadata):
- `FINDER_COLOR_NONE` = 0
- `FINDER_COLOR_GRAY` = 1
- `FINDER_COLOR_GREEN` = 2
- `FINDER_COLOR_PURPLE` = 3
- `FINDER_COLOR_BLUE` = 4
- `FINDER_COLOR_YELLOW` = 5
- `FINDER_COLOR_RED` = 6
- `FINDER_COLOR_ORANGE` = 7
## Finder Comments
Finder comments can be access via the `kMDItemFinderComment` attribute or the `findercomment` shortcut attribute. Apple provides a public API for getting Finder comments but does not provide a programmatic method for setting Finder comments and I have not been able to find a private API for doing so. osxmetadata works around this by send AppleScript events to the Finder to set the Finder comment. This means that setting Finder comments is slower than setting other attributes and may not work in all circumstances. The first time you set a Finder comment, your terminal app may need to prompt you to allow AppleScript to control the Finder. If you include osxmetadata in a standalone app, for example, one created with [py2app](https://py2app.readthedocs.io/en/latest/), you will need to include the `com.apple.security.automation.apple-events` entitlement and the `NSAppleEventsUsageDescription` key in your app's `Info.plist` file. See the [Apple Developer Documentation](https://developer.apple.com/documentation/bundleresources/information_property_list/nsappleeventsusagedescription?language=objc) for more information.
```pycon
>>> from osxmetadata import *
>>> md = OSXMetaData("test_file.txt")
>>> md.kMDItemFinderComment = "Hello World!"
>>> md.kMDItemFinderComment
'Hello World!'
>>> md.findercomment
'Hello World!'
>>>
```
## Dates/Times
Metadata attributes which return date/times such as `kMDItemDueDate` or `kMDItemDownloadedDate` return a `datetime.datetime` object. The `datetime.datetime` object is timezone-naive (does not contain timezone) and returns the time in the local timezone. Internally, Apple appears to store these as [CFDate](https://developer.apple.com/documentation/corefoundation/cfdate?language=objc) objects in the UTC timezone but when retrieved, they are returned in the local time. You may pass a timezone-aware datetime object to set these attributes and it will be converted appropriately.
```pycon
>>> from osxmetadata import *
>>> md = OSXMetaData("test_file.txt")
>>> import datetime
>>> md.kMDItemDueDate = datetime.datetime(2022, 10, 1)
>>> md.kMDItemDueDate
datetime.datetime(2022, 10, 1, 0, 0)
>>> md.kMDItemDownloadedDate = datetime.datetime(2022, 10, 1, tzinfo=datetime.timezone.utc)
>>>
```
## Extended Attributes
In addition to `MDItem` and `NSURL` metadata attributes, osxmetadata can also read & write metadata saved in extended attributes. For many MDItem attributes, Apple stores the same data in both the MDItem and extended attribute (with name `com.apple.metadata:AttributeName`). For example, the `kMDItemWhereFroms` attribute can be accessed both via MDItemCopyAttribute (exposed via osxmetadata's `get()` method) and via the `com.apple.metadata:kMDItemWhereFroms` extended attribute. The extended attribute is a binary plist (BPLIST) and can be read using the `xattr` command line tool. The `get_xattr()` method will return the value of the extended attribute and the `set_xattr()` method will set it. Extended attributes can be removed with the `remove_xattr()` method. `get_xattr()` provides for an optional callable argument, `decode`, which will be called on the returned value. `set_xattr()` provides an optional callable argument `encode`. This is useful for encoding/decoding binary plist data. For example, to decode the `com.apple.metadata:kMDItemWhereFroms` extended attribute, you can use the `plistlib.loads()` function:
```pycon
>>> from osxmetadata import *
>>> import plistlib
>>> from plistlib import FMT_BINARY
>>> from functools import partial
>>> md = OSXMetaData("test_file.txt")
>>> md.kMDItemWhereFroms = ["apple.com"]
>>> md.kMDItemWhereFroms
['apple.com']
>>> decode = partial(plistlib.loads, fmt=FMT_BINARY)
>>> encode = partial(plistlib.dumps, fmt=FMT_BINARY)
>>> md.get_xattr("com.apple.metadata:kMDItemWhereFroms")
b'bplist00\xa1\x01Yapple.com\x08\n\x00\x00\x00\x00\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x14'
>>> md.get_xattr("com.apple.metadata:kMDItemWhereFroms", decode=decode)
['apple.com']
>>> md.set_xattr("com.apple.metadata:kMDItemWhereFroms", ["google.com"], encode=encode)
>>> md.get_xattr("com.apple.metadata:kMDItemWhereFroms", decode=decode)
['google.com']
>>> md.remove_xattr("com.apple.metadata:kMDItemWhereFroms")
>>>
```
For most use cases, it is recommended you do not directly access the Apple metadata related extended attributes and instead use the getter/setter methods provided by osxmetadata.
## Finder Info
The Finder keeps some legacy Finder info data about files in a bitstring stored in the `com.apple.FinderInfo` extended attribute. osxmetadata provides some attributes for working with this data.
- `stationerypad`: True if the file is a stationery pad (file template) otherwise False; setting this attribute has the same effect as setting the `Stationery pad` checkbox in the Finder's `Get Info` window.
- `findercolor`: The color of the file as an integer; setting this attribute has the same effect as applying a color label in the Finder's `Get Info` window. osxmetadata will set this attribute automatically when setting user tags; it is recommended you do not set this attribute directly.
- `finderinfo`: The raw Finder info data as a bytes object; you should only manipulate this attribute if you know what you are doing.
## Temporary Files
Spotlight does not appear to index temporary files (those in `/tmp` or `/private/var/tmp`). Setting metadata using osxmetadata on temporary files in these locations will not fail but but it appears the metadata will not be indexed and a subsequent read will return the default value as if the metadata had not been written. This is not a limitation of osxmetadata but rather a limitation of Spotlight. If you need to set metadata on temporary files, you should use a different location.
## Command Line Usage
Installs command line tool called `osxmetadata` which provides a simple interface to view/edit metadata supported by osxmetadata.
If you only care about the command line tool, I recommend installing with [pipx](https://github.com/pipxproject/pipx)
The command line tool can also be run via `python -m osxmetadata`. Running it with no arguments or with --help option will print a help message:
<!-- [[[cog
import cog
from osxmetadata.__main__ import cli
from click.testing import CliRunner
runner = CliRunner()
result = runner.invoke(cli, ["--help"])
help = result.output.replace("Usage: cli", "Usage: osxmetadata")
cog.out(
"```\n{}\n```".format(help)
)
]]] -->
```
Usage: osxmetadata [OPTIONS] FILE
Read/write metadata from file(s).
Options:
-v, --version Show the version and exit.
-w, --walk Walk directory tree, processing each file in
the tree.
-j, --json Print output in JSON format, for use with
--list and --get.
-X, --wipe Wipe all metadata attributes from FILE.
-s, --set ATTRIBUTE VALUE Set ATTRIBUTE to VALUE. If ATTRIBUTE is a
multi-value attribute, such as keywords
(kMDItemKeywords), you may specify --set
multiple times to add to the array of values:
'--set keywords foo --set keywords bar' will
set keywords to ['foo', 'bar']. Not that this
will overwrite any existing values for the
attribute; see also --append.
-l, --list List all metadata attributes for FILE.
-c, --clear ATTRIBUTE Remove attribute from FILE.
-a, --append ATTRIBUTE VALUE Append VALUE to ATTRIBUTE; for multi-valued
attributes, appends only if VALUE is not
already present. May be used in combination
with --set to add to an existing value: '--set
keywords foo --append keywords bar' will set
keywords to ['foo', 'bar'], overwriting any
existing values for the attribute.
-g, --get ATTRIBUTE Get value of ATTRIBUTE.
-r, --remove ATTRIBUTE VALUE Remove VALUE from ATTRIBUTE; only applies to
multi-valued attributes.
-m, --mirror ATTRIBUTE1 ATTRIBUTE2
Mirror values between ATTRIBUTE1 and
ATTRIBUTE2 so that ATTRIBUTE1 = ATTRIBUTE2;
for multi-valued attributes, merges values;
for string attributes, sets ATTRIBUTE1 =
ATTRIBUTE2 overwriting any value in
ATTRIBUTE1. For example: '--mirror keywords
tags' sets tags and keywords to same values.
-B, --backup Backup FILE attributes. Backup file
'.osxmetadata.json' will be created in same
folder as FILE. Only backs up attributes known
to osxmetadata unless used with --all.
-R, --restore Restore FILE attributes from backup file.
Restore will look for backup file
'.osxmetadata.json' in same folder as FILE.
Only restores attributes known to osxmetadata
unless used with --all.
-V, --verbose Print verbose output.
-f, --copyfrom SOURCE_FILE Copy attributes from file SOURCE_FILE (only
updates destination attributes that are not
null in SOURCE_FILE).
--files-only Do not apply metadata commands to directories
themselves, only files in a directory.
-p, --pattern PATTERN Only process files matching PATTERN; only
applies to --walk. If specified, only files
matching PATTERN will be processed as each
directory is walked. May be used for than once
to specify multiple patterns. For example, tag
all *.pdf files in projectdir and subfolders
with tag 'project': osxmetadata --append tags
'project' --walk projectdir/ --pattern '*.pdf'
--help Show this message and exit.
Valid attributes for ATTRIBUTE: Each attribute has a short name, a constant
name, and a long constant name. Any of these may be used for ATTRIBUTE
For example: --set findercomment "Hello world"
or: --set kMDItemFinderComment "Hello world"
or: --set com.apple.metadata:kMDItemFinderComment "Hello world"
Attributes that are strings can only take one value for --set; --append will
append to the existing value. Attributes that are arrays can be set multiple
times to add to the array: e.g. --set keywords 'foo' --set keywords 'bar' will
set keywords to ['foo', 'bar']
Options are executed in the following order regardless of order passed on the
command line: restore, wipe, copyfrom, clear, set, append, remove, mirror, get,
list, backup. --backup and --restore are mutually exclusive. Other options may
be combined or chained together.
Finder tags (tags attribute) contain both a name and an optional color. To
specify the color, append comma + color name (e.g. 'red') after the tag name.
For example --set tags Foo,red. Valid color names are: gray, green, purple,
blue, yellow, red, orange. If color is not specified but a tag of the same name
has already been assigned a color in the Finder, the same color will
automatically be assigned.
com.apple.FinderInfo (finderinfo) value is a key:value dictionary. To set
finderinfo, pass value in format key1:value1,key2:value2,etc. For example:
'osxmetadata --set finderinfo color:2 file.ext'.
Short Name Description
acquisitionmake kMDItemAcquisitionMake;
com.apple.metadata:kMDItemAcquisitionMake; The
manufacturer of the device used to aquire the
document contents.; string
acquisitionmodel kMDItemAcquisitionModel;
com.apple.metadata:kMDItemAcquisitionModel; The
model of the device used to aquire the document
contents. For example, 100, 200, 400, etc.; string
album kMDItemAlbum; com.apple.metadata:kMDItemAlbum; The
title for a collection of media. This is analagous
to a record album, or photo album.; string
altitude kMDItemAltitude;
com.apple.metadata:kMDItemAltitude; The altitude of
the item in meters above sea level, expressed using
the WGS84 datum. Negative values lie below sea
level.; string
aperture kMDItemAperture;
com.apple.metadata:kMDItemAperture; The aperture
setting used to acquire the document contents. This
unit is the APEX value.; number
appleloopdescriptors kMDItemAppleLoopDescriptors;
com.apple.metadata:kMDItemAppleLoopDescriptors;
Specifies multiple pieces of descriptive
information about a loop.; list of strings
appleloopskeyfiltertype kMDItemAppleLoopsKeyFilterType;
com.apple.metadata:kMDItemAppleLoopsKeyFilterType;
Specifies key filtering information about a loop.
Loops are matched against projects that often in a
major or minor key.; string
appleloopsloopmode kMDItemAppleLoopsLoopMode;
com.apple.metadata:kMDItemAppleLoopsLoopMode;
Specifies how a file should be played.; string
appleloopsrootkey kMDItemAppleLoopsRootKey;
com.apple.metadata:kMDItemAppleLoopsRootKey;
Specifies the loop's original key. The key is the
root note or tonic for the loop, and does not
include the scale type.; string
attributechangedate kMDItemAttributeChangeDate;
com.apple.metadata:kMDItemAttributeChangeDate; The
date and time of the last change made to a metadata
attribute.; date/time
audiences kMDItemAudiences;
com.apple.metadata:kMDItemAudiences; The audience
for which the file is intended. The audience may be
determined by the creator or the publisher or by a
third party.; list of strings
audiobitrate kMDItemAudioBitRate;
com.apple.metadata:kMDItemAudioBitRate; The audio
bit rate.; number
audiochannelcount kMDItemAudioChannelCount;
com.apple.metadata:kMDItemAudioChannelCount; Number
of channels in the audio data contained in the
file.; number
audioencodingapplication kMDItemAudioEncodingApplication;
com.apple.metadata:kMDItemAudioEncodingApplication;
The name of the application that encoded the data
contained in the audio file.; string
audiosamplerate kMDItemAudioSampleRate;
com.apple.metadata:kMDItemAudioSampleRate; Sample
rate of the audio data contained in the file. The
sample rate is a float value representing hz
(audio_frames/second). For example: 44100. 0,
22254. 54.; number
audiotracknumber kMDItemAudioTrackNumber;
com.apple.metadata:kMDItemAudioTrackNumber; The
track number of a song or composition when it is
part of an album.; number
authoraddresses kMDItemAuthorAddresses;
com.apple.metadata:kMDItemAuthorAddresses; This
attribute indicates the author addresses of the
document.; list of strings
authoremailaddresses kMDItemAuthorEmailAddresses;
com.apple.metadata:kMDItemAuthorEmailAddresses;
This attribute indicates the author of the emails
message addresses. (This is always the email
address, and not the human readable version).; list
of strings
authors kMDItemAuthors; com.apple.metadata:kMDItemAuthors;
The author, or authors, of the contents of the
file.; list of strings
bitspersample kMDItemBitsPerSample;
com.apple.metadata:kMDItemBitsPerSample; The number
of bits per sample. For example, the bit depth of
an image (8-bit, 16-bit etc. . . ) or the bit depth
per audio sample of uncompressed audio data (8, 16,
24, 32, 64, etc. . ).; number
cfbundleidentifier kMDItemCFBundleIdentifier;
com.apple.metadata:kMDItemCFBundleIdentifier; If
this item is a bundle, then this is the
CFBundleIdentifier.; string
city kMDItemCity; com.apple.metadata:kMDItemCity;
Identifies city of origin according to guidelines
established by the provider.; string
codecs kMDItemCodecs; com.apple.metadata:kMDItemCodecs;
The codecs used to encode/decode the media.; list
of strings
colorspace kMDItemColorSpace;
com.apple.metadata:kMDItemColorSpace; The color
space model used by the document contents. For
example, "RGB", "CMYK", "YUV", or "YCbCr".; string
comment kMDItemComment; com.apple.metadata:kMDItemComment;
A comment related to the file. This differs from
the Finder comment, kMDItemFinderComment.; string
composer kMDItemComposer;
com.apple.metadata:kMDItemComposer; The composer of
the music contained in the audio file.; string
contactkeywords kMDItemContactKeywords;
com.apple.metadata:kMDItemContactKeywords; A list
of contacts that are associated with this document,
not including the authors.; list of strings
contentcreationdate kMDItemContentCreationDate;
com.apple.metadata:kMDItemContentCreationDate; The
creation date of an edited or optimized version of
the song or composition.; date/time
contentmodificationdate kMDItemContentModificationDate;
com.apple.metadata:kMDItemContentModificationDate;
The date and time that the contents of the file
were last modified.; date/time
contenttype kMDItemContentType;
com.apple.metadata:kMDItemContentType; The UTI
pedigree of a file.; string
contributors kMDItemContributors;
com.apple.metadata:kMDItemContributors; The
entities responsible for making contributions to
the content of the resource.; list of strings
copyright kMDItemCopyright;
com.apple.metadata:kMDItemCopyright; The copyright
owner of the file contents.; string
country kMDItemCountry; com.apple.metadata:kMDItemCountry;
The full, publishable name of the country or region
where the intellectual property of the item was
created, according to guidelines of the provider.;
string
coverage kMDItemCoverage;
com.apple.metadata:kMDItemCoverage; The extent or
scope of the content of the resource.; string
creator kMDItemCreator; com.apple.metadata:kMDItemCreator;
Application used to create the document content
(for example "Word", "Pages", and so on).; string
deliverytype kMDItemDeliveryType;
com.apple.metadata:kMDItemDeliveryType; The
delivery type. Values are "Fast start" or "RTSP".;
string
description kMDItemDescription;
com.apple.metadata:kMDItemDescription; A
description of the content of the resource. The
description may include an abstract, table of
contents, reference to a graphical representation
of content or a free-text account of the content.;
string
director kMDItemDirector;
com.apple.metadata:kMDItemDirector; Directory of
the movie.; string
displayname kMDItemDisplayName;
com.apple.metadata:kMDItemDisplayName; The
localized version of the file name.; string
downloadeddate kMDItemDownloadedDate;
com.apple.metadata:kMDItemDownloadedDate; Date the
item was downloaded.; list of date/time
duedate kMDItemDueDate; com.apple.metadata:kMDItemDueDate;
Date this item is due.; date/time
durationseconds kMDItemDurationSeconds;
com.apple.metadata:kMDItemDurationSeconds; The
duration, in seconds, of the content of file. A
value of 10. 5 represents media that is 10 and 1/2
seconds long.; number
exifgpsversion kMDItemEXIFGPSVersion;
com.apple.metadata:kMDItemEXIFGPSVersion; The
version of GPSInfoIFD in EXIF used to generate the
metadata.; string
exifversion kMDItemEXIFVersion;
com.apple.metadata:kMDItemEXIFVersion; The version
of the EXIF header used to generate the metadata.;
string
emailaddresses kMDItemEmailAddresses;
com.apple.metadata:kMDItemEmailAddresses; Email
addresses related to this item.; list of strings
encodingapplications kMDItemEncodingApplications;
com.apple.metadata:kMDItemEncodingApplications;
Application used to convert the original content
into it's current form. For example, a PDF file
might have an encoding application set to
"Distiller".; list of strings
exposuremode kMDItemExposureMode;
com.apple.metadata:kMDItemExposureMode; The
exposure mode used to acquire the document
contents.; number
exposureprogram kMDItemExposureProgram;
com.apple.metadata:kMDItemExposureProgram; The
class of the exposure program used by the camera to
set exposure when the image is taken. Possible
values include: Manual, Normal, and Aperture
priority.; string
exposuretimeseconds kMDItemExposureTimeSeconds;
com.apple.metadata:kMDItemExposureTimeSeconds; The
exposure time, in seconds, used to acquire the
document contents.; number
exposuretimestring kMDItemExposureTimeString;
com.apple.metadata:kMDItemExposureTimeString; The
time of the exposure.; string
fnumber kMDItemFNumber; com.apple.metadata:kMDItemFNumber;
The diameter of the diaphragm aperture in terms of
the effective focal length of the lens.; number
fscontentchangedate kMDItemFSContentChangeDate;
com.apple.metadata:kMDItemFSContentChangeDate; The
date the file contents last changed.; date/time
fscreationdate kMDItemFSCreationDate;
com.apple.metadata:kMDItemFSCreationDate; The date
and time that the file was created.; date/time
fshascustomicon kMDItemFSHasCustomIcon;
com.apple.metadata:kMDItemFSHasCustomIcon; Boolean
indicating if this file has a custom icon.; boolean
fsinvisible kMDItemFSInvisible;
com.apple.metadata:kMDItemFSInvisible; Indicates
whether the file is invisible.; boolean
fsisextensionhidden kMDItemFSIsExtensionHidden;
com.apple.metadata:kMDItemFSIsExtensionHidden;
Indicates whether the file extension of the file is
hidden.; boolean
fsisstationery kMDItemFSIsStationery;
com.apple.metadata:kMDItemFSIsStationery; Boolean
indicating if this file is stationery.; boolean
fslabel kMDItemFSLabel; com.apple.metadata:kMDItemFSLabel;
Index of the Finder label of the file. Possible
values are 0 through 7.; number
fsname kMDItemFSName; com.apple.metadata:kMDItemFSName;
The file name of the item.; string
fsnodecount kMDItemFSNodeCount;
com.apple.metadata:kMDItemFSNodeCount; Number of
files in a directory.; number
fsownergroupid kMDItemFSOwnerGroupID;
com.apple.metadata:kMDItemFSOwnerGroupID; The group
ID of the owner of the file.; number
fsowneruserid kMDItemFSOwnerUserID;
com.apple.metadata:kMDItemFSOwnerUserID; The user
ID of the owner of the file.; number
fssize kMDItemFSSize; com.apple.metadata:kMDItemFSSize;
The size, in bytes, of the file on disk.; number
findercomment kMDItemFinderComment;
com.apple.metadata:kMDItemFinderComment; Finder
comments for this file.; string
flashonoff kMDItemFlashOnOff;
com.apple.metadata:kMDItemFlashOnOff; Indicates if
a camera flash was used.; number
focallength kMDItemFocalLength;
com.apple.metadata:kMDItemFocalLength; The actual
focal length of the lens, in millimeters.; number
fonts kMDItemFonts; com.apple.metadata:kMDItemFonts;
Fonts used in this item. You should store the
font's full name, the postscript name, or the font
family name, based on the available information.;
list of strings
gpstrack kMDItemGPSTrack;
com.apple.metadata:kMDItemGPSTrack; The direction
of travel of the item, in degrees from true north.;
string
genre kMDItemGenre; com.apple.metadata:kMDItemGenre;
Genre of the movie.; string
hasalphachannel kMDItemHasAlphaChannel;
com.apple.metadata:kMDItemHasAlphaChannel;
Indicates if this image file has an alpha channel.;
boolean
headline kMDItemHeadline;
com.apple.metadata:kMDItemHeadline; A publishable
entry providing a synopsis of the contents of the
file. For example, "Apple Introduces the iPod
Photo".; string
isospeed kMDItemISOSpeed;
com.apple.metadata:kMDItemISOSpeed; The ISO speed
used to acquire the document contents.; number
identifier kMDItemIdentifier;
com.apple.metadata:kMDItemIdentifier; A formal
identifier used to reference the resource within a
given context.; string
imagedirection kMDItemImageDirection;
com.apple.metadata:kMDItemImageDirection; The
direction of the item's image, in degrees from true
north.; string
information kMDItemInformation;
com.apple.metadata:kMDItemInformation; Information
about the item.; string
instantmessageaddresses kMDItemInstantMessageAddresses;
com.apple.metadata:kMDItemInstantMessageAddresses;
Instant message addresses related to this item.;
list of strings
instructions kMDItemInstructions;
com.apple.metadata:kMDItemInstructions; Editorial
instructions concerning the use of the item, such
as embargoes and warnings. For example, "Second of
four stories".; string
isgeneralmidisequence kMDItemIsGeneralMIDISequence;
com.apple.metadata:kMDItemIsGeneralMIDISequence;
Indicates whether the MIDI sequence contained in
the file is setup for use with a General MIDI
device.; boolean
keysignature kMDItemKeySignature;
com.apple.metadata:kMDItemKeySignature; The key of
the music contained in the audio file. For example:
C, Dm, F#m, Bb.; string
keywords kMDItemKeywords;
com.apple.metadata:kMDItemKeywords; Keywords
associated with this file. For example, "Birthday",
"Important", etc.; list of strings
kind kMDItemKind; com.apple.metadata:kMDItemKind; A
description of the kind of item this file
represents.; string
languages kMDItemLanguages;
com.apple.metadata:kMDItemLanguages; Indicates the
languages of the intellectual content of the
resource. Recommended best practice for the values
of the Language element is defined by RFC 3066.;
list of strings
lastuseddate kMDItemLastUsedDate;
com.apple.metadata:kMDItemLastUsedDate; The date
and time that the file was last used. This value is
updated automatically by LaunchServices everytime a
file is opened by double clicking, or by asking
LaunchServices to open a file.; date/time
latitude kMDItemLatitude;
com.apple.metadata:kMDItemLatitude; The latitude of
the item in degrees north of the equator, expressed
using the WGS84 datum. Negative values lie south of
the equator.; string
layernames kMDItemLayerNames;
com.apple.metadata:kMDItemLayerNames; The names of
the layers in the file.; list of strings
longitude kMDItemLongitude;
com.apple.metadata:kMDItemLongitude; The longitude
of the item in degrees east of the prime meridian,
expressed using the WGS84 datum. Negative values
lie west of the prime meridian.; string
lyricist kMDItemLyricist;
com.apple.metadata:kMDItemLyricist; The lyricist,
or text writer, of the music contained in the audio
file.; string
maxaperture kMDItemMaxAperture;
com.apple.metadata:kMDItemMaxAperture; The smallest
f-number of the lens. Ordinarily it is given in the
range of 00. 00 to 99. 99.; number
mediatypes kMDItemMediaTypes;
com.apple.metadata:kMDItemMediaTypes; The media
types present in the content.; list of strings
meteringmode kMDItemMeteringMode;
com.apple.metadata:kMDItemMeteringMode; The
metering mode used to take the image.; string
musicalgenre kMDItemMusicalGenre;
com.apple.metadata:kMDItemMusicalGenre; The musical
genre of the song or composition contained in the
audio file. For example: Jazz, Pop, Rock,
Classical.; string
musicalinstrumentcategory kMDItemMusicalInstrumentCategory; com.apple.metadat
a:kMDItemMusicalInstrumentCategory; Specifies the
category of an instrument.; string
musicalinstrumentname kMDItemMusicalInstrumentName;
com.apple.metadata:kMDItemMusicalInstrumentName;
Specifies the name of instrument relative to the
instrument category.; string
namedlocation kMDItemNamedLocation;
com.apple.metadata:kMDItemNamedLocation; The name
of the location or point of interest associated
with the item. The name may be user provided.;
string
numberofpages kMDItemNumberOfPages;
com.apple.metadata:kMDItemNumberOfPages; Number of
pages in the document.; number
organizations kMDItemOrganizations;
com.apple.metadata:kMDItemOrganizations; The
company or organization that created the document.;
list of strings
orientation kMDItemOrientation;
com.apple.metadata:kMDItemOrientation; The
orientation of the document contents. Possible
values are 0 (landscape) and 1 (portrait).; number
originalformat kMDItemOriginalFormat;
com.apple.metadata:kMDItemOriginalFormat; Original
format of the movie.; string
originalsource kMDItemOriginalSource;
com.apple.metadata:kMDItemOriginalSource; Original
source of the movie.; string
pageheight kMDItemPageHeight;
com.apple.metadata:kMDItemPageHeight; Height of the
document page, in points (72 points per inch). For
PDF files this indicates the height of the first
page only.; number
pagewidth kMDItemPageWidth;
com.apple.metadata:kMDItemPageWidth; Width of the
document page, in points (72 points per inch). For
PDF files this indicates the width of the first
page only.; number
participants kMDItemParticipants;
com.apple.metadata:kMDItemParticipants; The list of
people who are visible in an image or movie or
written about in a document.; list of strings
path kMDItemPath; com.apple.metadata:kMDItemPath; The
complete path to the file.; string
performers kMDItemPerformers;
com.apple.metadata:kMDItemPerformers; Performers in
the movie.; list of strings
phonenumbers kMDItemPhoneNumbers;
com.apple.metadata:kMDItemPhoneNumbers; Phone
numbers related to this item.; list of strings
pixelcount kMDItemPixelCount;
com.apple.metadata:kMDItemPixelCount; The total
number of pixels in the contents. Same as
kMDItemPixelWidth x kMDItemPixelHeight.; number
pixelheight kMDItemPixelHeight;
com.apple.metadata:kMDItemPixelHeight; The height,
in pixels, of the contents. For example, the image
height or the video frame height.; number
pixelwidth kMDItemPixelWidth;
com.apple.metadata:kMDItemPixelWidth; The width, in
pixels, of the contents. For example, the image
width or the video frame width.; number
producer kMDItemProducer;
com.apple.metadata:kMDItemProducer; Producer of the
content.; string
profilename kMDItemProfileName;
com.apple.metadata:kMDItemProfileName; The name of
the color profile used by the document contents.;
string
projects kMDItemProjects;
com.apple.metadata:kMDItemProjects; The list of
projects that this file is part of. For example, if
you were working on a movie all of the files could
be marked as belonging to the project "My Movie".;
list of strings
publishers kMDItemPublishers;
com.apple.metadata:kMDItemPublishers; The entity
responsible for making the resource available. For
example, a person, an organization, or a service.
Typically, the name of a publisher should be used
to indicate the entity.; list of strings
recipientaddresses kMDItemRecipientAddresses;
com.apple.metadata:kMDItemRecipientAddresses; This
attribute indicates the recipient addresses of the
document.; list of strings
recipientemailaddresses kMDItemRecipientEmailAddresses;
com.apple.metadata:kMDItemRecipientEmailAddresses;
This attribute indicates the recipients email
addresses. (This is always the email address, and
not the human readable version).; list of strings
recipients kMDItemRecipients;
com.apple.metadata:kMDItemRecipients; Recipients of
this item.; list of strings
recordingdate kMDItemRecordingDate;
com.apple.metadata:kMDItemRecordingDate; The
recording date of the song or composition.;
date/time
recordingyear kMDItemRecordingYear;
com.apple.metadata:kMDItemRecordingYear; Indicates
the year the item was recorded. For example, 1964,
2003, etc.; number
redeyeonoff kMDItemRedEyeOnOff;
com.apple.metadata:kMDItemRedEyeOnOff; Indicates if
red-eye reduction was used to take the picture.;
boolean
resolutionheightdpi kMDItemResolutionHeightDPI;
com.apple.metadata:kMDItemResolutionHeightDPI;
Resolution height, in DPI, of this image.; number
resolutionwidthdpi kMDItemResolutionWidthDPI;
com.apple.metadata:kMDItemResolutionWidthDPI;
Resolution width, in DPI, of this image.; number
rights kMDItemRights; com.apple.metadata:kMDItemRights;
Provides a link to information about rights held in
and over the resource.; string
securitymethod kMDItemSecurityMethod;
com.apple.metadata:kMDItemSecurityMethod; The
security or encryption method used for the file.;
string
speed kMDItemSpeed; com.apple.metadata:kMDItemSpeed; The
speed of the item, in kilometers per hour.; string
starrating kMDItemStarRating;
com.apple.metadata:kMDItemStarRating; User rating
of this item. For example, the stars rating of an
iTunes track.; number
stateorprovince kMDItemStateOrProvince;
com.apple.metadata:kMDItemStateOrProvince;
Identifies the province or state of origin
according to guidelines established by the
provider. For example, "CA", "Ontario", or
"Sussex".; string
streamable kMDItemStreamable;
com.apple.metadata:kMDItemStreamable; Whether the
content is prepared for streaming.; boolean
subject kMDItemSubject; com.apple.metadata:kMDItemSubject;
Subject of the this item.; string
tempo kMDItemTempo; com.apple.metadata:kMDItemTempo; A
float value that specifies the beats per minute of
the music contained in the audio file.; number
textcontent kMDItemTextContent;
com.apple.metadata:kMDItemTextContent; Contains a
text representation of the content of the document.
Data in multiple fields should be combined using a
whitespace character as a separator.; string
theme kMDItemTheme; com.apple.metadata:kMDItemTheme;
Theme of the this item.; string
timesignature kMDItemTimeSignature;
com.apple.metadata:kMDItemTimeSignature; The time
signature of the musical composition contained in
the audio/MIDI file. For example: "4/4", "7/8".;
string
timestamp kMDItemTimestamp;
com.apple.metadata:kMDItemTimestamp; The timestamp
on the item. This generally is used to indicate the
time at which the event captured by the item took
place.; string
title kMDItemTitle; com.apple.metadata:kMDItemTitle; The
title of the file. For example, this could be the
title of a document, the name of a song, or the
subject of an email message.; string
totalbitrate kMDItemTotalBitRate;
com.apple.metadata:kMDItemTotalBitRate; The total
bit rate, audio and video combined, of the media.;
number
url kMDItemURL; com.apple.metadata:kMDItemURL; Url of
the item.; string
version kMDItemVersion; com.apple.metadata:kMDItemVersion;
The version number of this file.; string
videobitrate kMDItemVideoBitRate;
com.apple.metadata:kMDItemVideoBitRate; The video
bit rate.; number
wherefroms kMDItemWhereFroms;
com.apple.metadata:kMDItemWhereFroms; Describes
where the file was obtained from.; list of strings
whitebalance kMDItemWhiteBalance;
com.apple.metadata:kMDItemWhiteBalance; The white
balance setting used to acquire the document
contents. Possible values are 0 (auto white
balance) and 1 (manual).; number
```
<!-- [[[end]]] -->
## Notes on backup/restore
When run with `--backup`, osxmetadata backs up the metadata of each file in a file called `.osxmetadata.json`. A backup file is created in every directory that includes files being backup up. The format is plain JSON text with a record for each file that was backed up. If you delete a file then run the `--backup` again, the deleted file's record is not deleted from the `.osxmetadata.json` backup file. The backup file is kept in each directory/sub-directory and only the filename is used for `--restore` which means you can move/rename the directory (along with the `.osxmetadata.json` file) and the restore will still work correctly.
**Note**: Prior to version 0.99.38, the backup file was not well-formed JSON which meant that some apps/viewers could not process the JSON file. Version 0.99.38 fixes this and will silently update any `.osxmetadata.json` file encountered during `--backup` to be well-formed JSON but this breaks backwards compatibility with older versions of osxmetadata. If you use osxmetadata to sync data across multiple Macs, you must ensure all Macs are running the updated version. For additional details, see [issue #57](https://github.com/RhetTbull/osxmetadata/issues/57).
## Usage Notes
This will only work on file systems that support Mac OS X extended attributes.
## Related Projects
- [tag](https://github.com/jdberry/tag) A command line tool to manipulate tags on Mac OS X files, and to query for files with those tags.
- [osx-tags](https://github.com/scooby/osx-tags) Python module to manipulate Finder tags in OS X.
## Acknowledgements
This module was inspired by [osx-tags](https://github.com/scooby/osx-tags) by "Ben S / scooby". I leveraged osx-tags to bootstrap the design of this module. I wanted a more general OS X metadata library so I rolled my own. This module is published under the same MIT license as osx-tags.
## License
MIT License
Copyright (c) 2020 Rhet Turnbull
## Contributing
Contributions of all kinds are welcome. Please submit a pull request or open an issue.
## Contributors β¨
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<table>
<tbody>
<tr>
<td align="center"><a href="http://www.borja.glezseoane.es"><img src="https://avatars.githubusercontent.com/u/24481419?v=4?s=75" width="75px;" alt="Borja GonzΓ‘lez Seoane"/><br /><sub><b>Borja GonzΓ‘lez Seoane</b></sub></a><br /><a href="https://github.com/RhetTbull/osxmetadata/commits?author=bglezseoane" title="Code">π»</a></td>
<td align="center"><a href="https://github.com/porg"><img src="https://avatars.githubusercontent.com/u/737143?v=4?s=75" width="75px;" alt="porg"/><br /><sub><b>porg</b></sub></a><br /><a href="https://github.com/RhetTbull/osxmetadata/issues?q=author%3Aporg" title="Bug reports">π</a> <a href="#ideas-porg" title="Ideas, Planning, & Feedback">π€</a></td>
<td align="center"><a href="https://github.com/nk9"><img src="https://avatars.githubusercontent.com/u/3646730?v=4?s=75" width="75px;" alt="Nick Kocharhook"/><br /><sub><b>Nick Kocharhook</b></sub></a><br /><a href="https://github.com/RhetTbull/osxmetadata/issues?q=author%3Ank9" title="Bug reports">π</a></td>
<td align="center"><a href="https://jakewilliami.github.io/"><img src="https://avatars.githubusercontent.com/u/54291317?v=4?s=75" width="75px;" alt="Jake Ireland"/><br /><sub><b>Jake Ireland</b></sub></a><br /><a href="#ideas-jakewilliami" title="Ideas, Planning, & Feedback">π€</a></td>
<td align="center"><a href="https://github.com/luckman212"><img src="https://avatars.githubusercontent.com/u/1992842?v=4?s=75" width="75px;" alt="Luke Hamburg"/><br /><sub><b>Luke Hamburg</b></sub></a><br /><a href="https://github.com/RhetTbull/osxmetadata/issues?q=author%3Aluckman212" title="Bug reports">π</a> <a href="https://github.com/RhetTbull/osxmetadata/commits?author=luckman212" title="Code">π»</a></td>
</tr>
</tbody>
</table>
<!-- markdownlint-restore -->
<!-- prettier-ignore-end -->
<!-- ALL-CONTRIBUTORS-LIST:END -->
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
%package -n python3-osxmetadata
Summary: Read and write meta data, such as tags/keywords, Finder comments, etc. on MacOS files
Provides: python-osxmetadata
BuildRequires: python3-devel
BuildRequires: python3-setuptools
BuildRequires: python3-pip
%description -n python3-osxmetadata
# osxmetadata
[](https://github.com/python/black)
[](https://opensource.org/licenses/MIT)
[](#contributors-)
## What is osxmetadata?
osxmetadata provides a simple interface to access various metadata about MacOS / OS X files. Currently supported metadata attributes include tags/keywords, Finder comments, authors, etc.
## Why osxmetadata?
Apple provides rich support for file metadata through the [MDItem](https://developer.apple.com/documentation/coreservices/file_metadata/mditem) class and the [NSURL getResourceValue:forKey:error:](https://developer.apple.com/documentation/foundation/nsurl/1408874-getresourcevalue?language=objc) method. However, Apple does not provide a way to easily set much of the metadata. For example, while there is a documented [MDItem MDItemCopyAttribute](https://developer.apple.com/documentation/coreservices/1427080-mditemcopyattribute?language=objc) to copy metadata attributes such as [kMDItemAuthors](https://developer.apple.com/documentation/coreservices/kmditemauthors?language=objc), Apple does not provide a public interface to set this data. Other data, such as Finder comments, can only be set through sending AppleScript commands to the Finder and others, like Finder tags can be retrieved but cannot be set through the public API.
osxmetadata provides a unified interface to get and set most of the metadata available on your Mac from python. It uses a combination of documented and undocumented APIs to access the metadata. It also provides a simple interface to set Finder tags and Finder comments.
MacOS provides some tools to view these various metadata attributes. For example, `mdls` lists the MDItem Spotlight metadata associated with a file but doesn't let you edit the data. osxmetadata makes it easy to to both view and manipulate the macOS metadata attributes, either programmatically or through an included `osxmetadata` command line tool.
## Supported operating systems
Only works on MacOS. Requires Python 3.8+. Tested on macOS 10.15.7 (Catalina); should work on all versions of macOS 10.15 and later.
## Installation instructions
### Installation using pipx
If you aren't familiar with installing python applications, I recommend you install `osxmetadata` with [pipx](https://github.com/pipxproject/pipx). If you use `pipx`, you will not need to create a virtual environment as `pipx` takes care of this. The easiest way to do this on a Mac is to use [homebrew](https://brew.sh/):
- Open `Terminal` (search for `Terminal` in Spotlight or look in `Applications/Utilities`)
- Install `homebrew` according to instructions at [https://brew.sh/](https://brew.sh/)
- Type the following into Terminal: `brew install pipx`
- Then type this: `pipx install osxmetadata`
- Now you should be able to run `osxmetadata` by typing: `osxmetadata`
Once you've installed osxmetadata with pipx, to upgrade to the latest version:
pipx upgrade osxmetadata
### Installation using pip
You can also install directly from [pypi](https://pypi.org/project/osxmetadata/):
pip install osxmetadata
Once you've installed osxmetadata with pip, to upgrade to the latest version:
pip install --upgrade osxmetadata
### Installation from git repository
OSXMetaData uses setuptools, thus simply run:
git clone https://github.com/RhetTbull/osxmetadata.git
cd osxmetadata
pip install poetry
poetry install
I recommend you create a [virtual environment](https://docs.python.org/3/tutorial/venv.html) before installing osxmetadata.
## Using the API
```pycon
>>> import datetime
>>> import pathlib
>>> from osxmetadata import *
>>> pathlib.Path("test_file.txt").touch()
>>> md = OSXMetaData("test_file.txt")
>>> md.set(kMDItemAuthors, ["Jane Smith", "John Doe"])
>>> md.get(kMDItemAuthors)
['Jane Smith', 'John Doe']
>>> md.kMDItemFinderComment = "This is my comment"
>>> md.kMDItemFinderComment
'This is my comment'
>>> md.tags = [Tag("Test", FINDER_COLOR_NONE), Tag("ToDo", FINDER_COLOR_RED)]
>>> md.tags
[Tag(name='Test', color=0), Tag(name='ToDo', color=6)]
>>> md[kMDItemDueDate] = datetime.datetime(2022,10,1)
>>> md[kMDItemDueDate]
datetime.datetime(2022, 10, 1, 0, 0)
>>>
```
Somewhat contrary to the [Zen of Python](https://peps.python.org/pep-0020/), osxmetadata provides more than one way to access metadata attributes. You can get and set metadata attributes using the `get()`/`set()` getter/setter methods, using the attribute name as a dictionary key on the OSXMetaData object, or using the attribute name as an attribute on the `OSXMetaData()` object. For example, the following are all equivalent:
- `OSXMetaData.get(attribute)` - get the value of the metadata attribute `attribute`
- `OSXMetaData[attribute]` - get the value of the metadata attribute `attribute`
- `OSXMetaData.attribute` - get the value of the metadata attribute `attribute`
As are the following:
- `OSXMetaData.set(attribute, value)` - set the value of the metadata attribute `attribute` to `value`
- `OSXMetaData[attribute] = value` - set the value of the metadata attribute `attribute` to `value`
- `OSXMetaData.attribute = value` - set the value of the metadata attribute `attribute` to `value`
This allows you to use osxmetadata in accordance with your own code style preferences.
Supported attribute names include all attributes defined for [MDItem](https://developer.apple.com/documentation/coreservices/file_metadata/mditem) and all resource keys defined for [NSURL](https://developer.apple.com/documentation/foundation/nsurl?language=objc). Additionally, the metadata constants defined in the [MDImporter](https://developer.apple.com/documentation/coreservices/file_metadata/mdimporter?language=objc) are supported as well as the following additional attributes:
- `_kMDItemUserTags` - list of Finder tags
- `kMDItemDownloadedDate` - list of datetime objects for when the file was downloaded
Additionally, osxmetadata defines a "shortcut name" attribute for each MDItem attribute that can be used as a shortcut `OSXMetaData` class attribute. The shortcut name is the lowercase value of text following `kMDItem` for each attribute. For example, `kMDItemAuthors` has a short name of `authors` so you can set the authors like this:
```pycon
>>> from osxmetadata import *
>>> md = OSXMetaData("test_file.txt")
>>> md.authors = ["Jane Smith", "John Doe"]
>>> md.authors
['Jane Smith', 'John Doe']
>>>
```
and `kMDItemDueDate` would have a short name of `duedate`:
```pycon
>>> from osxmetadata import *
>>> import datetime
>>> md = OSXMetaData("test_file.txt")
>>> md.duedate = datetime.datetime(2022, 10, 1)
>>> md.duedate
datetime.datetime(2022, 10, 1, 0, 0)
>>>
```
The names of all supported attributes are available in the `osxmetadata.ALL_ATTRIBUTES` set:
```pycon
>>> from osxmetadata import ALL_ATTRIBUTES
>>> "kMDItemDueDate" in ALL_ATTRIBUTES
True
>>> "NSURLTagNamesKey" in ALL_ATTRIBUTES
True
>>> "findercomment" in ALL_ATTRIBUTES
True
>>>
```
The class attributes are handled dynamically which, unfortunately, means that IDEs like PyCharm and Visual Studio Code cannot provide tab-completion for them.
## Finder Tags
Unlike other attributes, which are mapped to native Python types appropriate for the source Objective C type, Finder tags (`_kMDItemUserTags` or `tags`) have two components: a name (str) and a color ID (unsigned int in range 0 to 7) representing a color tag in the Finder. Reading tags returns a list of `Tag` namedtuples and setting tags requires a list of `Tag` namedtuples.
```pycon
>>> from osxmetadata import *
>>> md = OSXMetaData("test_file.txt")
>>> md.tags = [Tag("Test", FINDER_COLOR_NONE), Tag("ToDo", FINDER_COLOR_RED)]
>>> md.tags
[Tag(name='Test', color=0), Tag(name='ToDo', color=6)]
>>> md.get("_kMDItemUserTags")
[Tag(name='Test', color=0), Tag(name='ToDo', color=6)]
>>>
```
Tag names (but not colors) can also be accessed through the [NSURLTagNamesKey](https://developer.apple.com/documentation/foundation/nsurltagnameskey) resource key and the label color ID is accessible through `NSURLLabelNumberKey`; the localized label color name is accessible through `NSURLLocalizedLabelKey` though these latter two resource keys only return a single color whereas a file may have more than one color tag. For most purposes, I recommend using the `tags` attribute as it is more convenient and provides access to both the name and color ID of the tag.
```pycon
>>> from osxmetadata import *
>>> md = OSXMetaData("test_file.txt")
>>> md.tags = [Tag("Test", FINDER_COLOR_NONE), Tag("ToDo", FINDER_COLOR_RED)]
>>> md.tags
[Tag(name='Test', color=0), Tag(name='ToDo', color=6)]
>>> md.NSURLTagNamesKey
(
Test,
ToDo
)
>>> md.NSURLLabelNumberKey
6
>>> md.NSURLLocalizedLabelKey
'Red'
>>> md.NSURLTagNamesKey = ["NewTag"]
>>> md.NSURLTagNamesKey
(
NewTag
)
>>> md.tags
[Tag(name='NewTag', color=0)]
>>>
```
### Create a Tag namedtuple
`Tag(name, color)`
- `name`: tag name (str)
- `color`: color ID for Finder color label associated with tag (int)
Valid color constants (exported by osxmetadata):
- `FINDER_COLOR_NONE` = 0
- `FINDER_COLOR_GRAY` = 1
- `FINDER_COLOR_GREEN` = 2
- `FINDER_COLOR_PURPLE` = 3
- `FINDER_COLOR_BLUE` = 4
- `FINDER_COLOR_YELLOW` = 5
- `FINDER_COLOR_RED` = 6
- `FINDER_COLOR_ORANGE` = 7
## Finder Comments
Finder comments can be access via the `kMDItemFinderComment` attribute or the `findercomment` shortcut attribute. Apple provides a public API for getting Finder comments but does not provide a programmatic method for setting Finder comments and I have not been able to find a private API for doing so. osxmetadata works around this by send AppleScript events to the Finder to set the Finder comment. This means that setting Finder comments is slower than setting other attributes and may not work in all circumstances. The first time you set a Finder comment, your terminal app may need to prompt you to allow AppleScript to control the Finder. If you include osxmetadata in a standalone app, for example, one created with [py2app](https://py2app.readthedocs.io/en/latest/), you will need to include the `com.apple.security.automation.apple-events` entitlement and the `NSAppleEventsUsageDescription` key in your app's `Info.plist` file. See the [Apple Developer Documentation](https://developer.apple.com/documentation/bundleresources/information_property_list/nsappleeventsusagedescription?language=objc) for more information.
```pycon
>>> from osxmetadata import *
>>> md = OSXMetaData("test_file.txt")
>>> md.kMDItemFinderComment = "Hello World!"
>>> md.kMDItemFinderComment
'Hello World!'
>>> md.findercomment
'Hello World!'
>>>
```
## Dates/Times
Metadata attributes which return date/times such as `kMDItemDueDate` or `kMDItemDownloadedDate` return a `datetime.datetime` object. The `datetime.datetime` object is timezone-naive (does not contain timezone) and returns the time in the local timezone. Internally, Apple appears to store these as [CFDate](https://developer.apple.com/documentation/corefoundation/cfdate?language=objc) objects in the UTC timezone but when retrieved, they are returned in the local time. You may pass a timezone-aware datetime object to set these attributes and it will be converted appropriately.
```pycon
>>> from osxmetadata import *
>>> md = OSXMetaData("test_file.txt")
>>> import datetime
>>> md.kMDItemDueDate = datetime.datetime(2022, 10, 1)
>>> md.kMDItemDueDate
datetime.datetime(2022, 10, 1, 0, 0)
>>> md.kMDItemDownloadedDate = datetime.datetime(2022, 10, 1, tzinfo=datetime.timezone.utc)
>>>
```
## Extended Attributes
In addition to `MDItem` and `NSURL` metadata attributes, osxmetadata can also read & write metadata saved in extended attributes. For many MDItem attributes, Apple stores the same data in both the MDItem and extended attribute (with name `com.apple.metadata:AttributeName`). For example, the `kMDItemWhereFroms` attribute can be accessed both via MDItemCopyAttribute (exposed via osxmetadata's `get()` method) and via the `com.apple.metadata:kMDItemWhereFroms` extended attribute. The extended attribute is a binary plist (BPLIST) and can be read using the `xattr` command line tool. The `get_xattr()` method will return the value of the extended attribute and the `set_xattr()` method will set it. Extended attributes can be removed with the `remove_xattr()` method. `get_xattr()` provides for an optional callable argument, `decode`, which will be called on the returned value. `set_xattr()` provides an optional callable argument `encode`. This is useful for encoding/decoding binary plist data. For example, to decode the `com.apple.metadata:kMDItemWhereFroms` extended attribute, you can use the `plistlib.loads()` function:
```pycon
>>> from osxmetadata import *
>>> import plistlib
>>> from plistlib import FMT_BINARY
>>> from functools import partial
>>> md = OSXMetaData("test_file.txt")
>>> md.kMDItemWhereFroms = ["apple.com"]
>>> md.kMDItemWhereFroms
['apple.com']
>>> decode = partial(plistlib.loads, fmt=FMT_BINARY)
>>> encode = partial(plistlib.dumps, fmt=FMT_BINARY)
>>> md.get_xattr("com.apple.metadata:kMDItemWhereFroms")
b'bplist00\xa1\x01Yapple.com\x08\n\x00\x00\x00\x00\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x14'
>>> md.get_xattr("com.apple.metadata:kMDItemWhereFroms", decode=decode)
['apple.com']
>>> md.set_xattr("com.apple.metadata:kMDItemWhereFroms", ["google.com"], encode=encode)
>>> md.get_xattr("com.apple.metadata:kMDItemWhereFroms", decode=decode)
['google.com']
>>> md.remove_xattr("com.apple.metadata:kMDItemWhereFroms")
>>>
```
For most use cases, it is recommended you do not directly access the Apple metadata related extended attributes and instead use the getter/setter methods provided by osxmetadata.
## Finder Info
The Finder keeps some legacy Finder info data about files in a bitstring stored in the `com.apple.FinderInfo` extended attribute. osxmetadata provides some attributes for working with this data.
- `stationerypad`: True if the file is a stationery pad (file template) otherwise False; setting this attribute has the same effect as setting the `Stationery pad` checkbox in the Finder's `Get Info` window.
- `findercolor`: The color of the file as an integer; setting this attribute has the same effect as applying a color label in the Finder's `Get Info` window. osxmetadata will set this attribute automatically when setting user tags; it is recommended you do not set this attribute directly.
- `finderinfo`: The raw Finder info data as a bytes object; you should only manipulate this attribute if you know what you are doing.
## Temporary Files
Spotlight does not appear to index temporary files (those in `/tmp` or `/private/var/tmp`). Setting metadata using osxmetadata on temporary files in these locations will not fail but but it appears the metadata will not be indexed and a subsequent read will return the default value as if the metadata had not been written. This is not a limitation of osxmetadata but rather a limitation of Spotlight. If you need to set metadata on temporary files, you should use a different location.
## Command Line Usage
Installs command line tool called `osxmetadata` which provides a simple interface to view/edit metadata supported by osxmetadata.
If you only care about the command line tool, I recommend installing with [pipx](https://github.com/pipxproject/pipx)
The command line tool can also be run via `python -m osxmetadata`. Running it with no arguments or with --help option will print a help message:
<!-- [[[cog
import cog
from osxmetadata.__main__ import cli
from click.testing import CliRunner
runner = CliRunner()
result = runner.invoke(cli, ["--help"])
help = result.output.replace("Usage: cli", "Usage: osxmetadata")
cog.out(
"```\n{}\n```".format(help)
)
]]] -->
```
Usage: osxmetadata [OPTIONS] FILE
Read/write metadata from file(s).
Options:
-v, --version Show the version and exit.
-w, --walk Walk directory tree, processing each file in
the tree.
-j, --json Print output in JSON format, for use with
--list and --get.
-X, --wipe Wipe all metadata attributes from FILE.
-s, --set ATTRIBUTE VALUE Set ATTRIBUTE to VALUE. If ATTRIBUTE is a
multi-value attribute, such as keywords
(kMDItemKeywords), you may specify --set
multiple times to add to the array of values:
'--set keywords foo --set keywords bar' will
set keywords to ['foo', 'bar']. Not that this
will overwrite any existing values for the
attribute; see also --append.
-l, --list List all metadata attributes for FILE.
-c, --clear ATTRIBUTE Remove attribute from FILE.
-a, --append ATTRIBUTE VALUE Append VALUE to ATTRIBUTE; for multi-valued
attributes, appends only if VALUE is not
already present. May be used in combination
with --set to add to an existing value: '--set
keywords foo --append keywords bar' will set
keywords to ['foo', 'bar'], overwriting any
existing values for the attribute.
-g, --get ATTRIBUTE Get value of ATTRIBUTE.
-r, --remove ATTRIBUTE VALUE Remove VALUE from ATTRIBUTE; only applies to
multi-valued attributes.
-m, --mirror ATTRIBUTE1 ATTRIBUTE2
Mirror values between ATTRIBUTE1 and
ATTRIBUTE2 so that ATTRIBUTE1 = ATTRIBUTE2;
for multi-valued attributes, merges values;
for string attributes, sets ATTRIBUTE1 =
ATTRIBUTE2 overwriting any value in
ATTRIBUTE1. For example: '--mirror keywords
tags' sets tags and keywords to same values.
-B, --backup Backup FILE attributes. Backup file
'.osxmetadata.json' will be created in same
folder as FILE. Only backs up attributes known
to osxmetadata unless used with --all.
-R, --restore Restore FILE attributes from backup file.
Restore will look for backup file
'.osxmetadata.json' in same folder as FILE.
Only restores attributes known to osxmetadata
unless used with --all.
-V, --verbose Print verbose output.
-f, --copyfrom SOURCE_FILE Copy attributes from file SOURCE_FILE (only
updates destination attributes that are not
null in SOURCE_FILE).
--files-only Do not apply metadata commands to directories
themselves, only files in a directory.
-p, --pattern PATTERN Only process files matching PATTERN; only
applies to --walk. If specified, only files
matching PATTERN will be processed as each
directory is walked. May be used for than once
to specify multiple patterns. For example, tag
all *.pdf files in projectdir and subfolders
with tag 'project': osxmetadata --append tags
'project' --walk projectdir/ --pattern '*.pdf'
--help Show this message and exit.
Valid attributes for ATTRIBUTE: Each attribute has a short name, a constant
name, and a long constant name. Any of these may be used for ATTRIBUTE
For example: --set findercomment "Hello world"
or: --set kMDItemFinderComment "Hello world"
or: --set com.apple.metadata:kMDItemFinderComment "Hello world"
Attributes that are strings can only take one value for --set; --append will
append to the existing value. Attributes that are arrays can be set multiple
times to add to the array: e.g. --set keywords 'foo' --set keywords 'bar' will
set keywords to ['foo', 'bar']
Options are executed in the following order regardless of order passed on the
command line: restore, wipe, copyfrom, clear, set, append, remove, mirror, get,
list, backup. --backup and --restore are mutually exclusive. Other options may
be combined or chained together.
Finder tags (tags attribute) contain both a name and an optional color. To
specify the color, append comma + color name (e.g. 'red') after the tag name.
For example --set tags Foo,red. Valid color names are: gray, green, purple,
blue, yellow, red, orange. If color is not specified but a tag of the same name
has already been assigned a color in the Finder, the same color will
automatically be assigned.
com.apple.FinderInfo (finderinfo) value is a key:value dictionary. To set
finderinfo, pass value in format key1:value1,key2:value2,etc. For example:
'osxmetadata --set finderinfo color:2 file.ext'.
Short Name Description
acquisitionmake kMDItemAcquisitionMake;
com.apple.metadata:kMDItemAcquisitionMake; The
manufacturer of the device used to aquire the
document contents.; string
acquisitionmodel kMDItemAcquisitionModel;
com.apple.metadata:kMDItemAcquisitionModel; The
model of the device used to aquire the document
contents. For example, 100, 200, 400, etc.; string
album kMDItemAlbum; com.apple.metadata:kMDItemAlbum; The
title for a collection of media. This is analagous
to a record album, or photo album.; string
altitude kMDItemAltitude;
com.apple.metadata:kMDItemAltitude; The altitude of
the item in meters above sea level, expressed using
the WGS84 datum. Negative values lie below sea
level.; string
aperture kMDItemAperture;
com.apple.metadata:kMDItemAperture; The aperture
setting used to acquire the document contents. This
unit is the APEX value.; number
appleloopdescriptors kMDItemAppleLoopDescriptors;
com.apple.metadata:kMDItemAppleLoopDescriptors;
Specifies multiple pieces of descriptive
information about a loop.; list of strings
appleloopskeyfiltertype kMDItemAppleLoopsKeyFilterType;
com.apple.metadata:kMDItemAppleLoopsKeyFilterType;
Specifies key filtering information about a loop.
Loops are matched against projects that often in a
major or minor key.; string
appleloopsloopmode kMDItemAppleLoopsLoopMode;
com.apple.metadata:kMDItemAppleLoopsLoopMode;
Specifies how a file should be played.; string
appleloopsrootkey kMDItemAppleLoopsRootKey;
com.apple.metadata:kMDItemAppleLoopsRootKey;
Specifies the loop's original key. The key is the
root note or tonic for the loop, and does not
include the scale type.; string
attributechangedate kMDItemAttributeChangeDate;
com.apple.metadata:kMDItemAttributeChangeDate; The
date and time of the last change made to a metadata
attribute.; date/time
audiences kMDItemAudiences;
com.apple.metadata:kMDItemAudiences; The audience
for which the file is intended. The audience may be
determined by the creator or the publisher or by a
third party.; list of strings
audiobitrate kMDItemAudioBitRate;
com.apple.metadata:kMDItemAudioBitRate; The audio
bit rate.; number
audiochannelcount kMDItemAudioChannelCount;
com.apple.metadata:kMDItemAudioChannelCount; Number
of channels in the audio data contained in the
file.; number
audioencodingapplication kMDItemAudioEncodingApplication;
com.apple.metadata:kMDItemAudioEncodingApplication;
The name of the application that encoded the data
contained in the audio file.; string
audiosamplerate kMDItemAudioSampleRate;
com.apple.metadata:kMDItemAudioSampleRate; Sample
rate of the audio data contained in the file. The
sample rate is a float value representing hz
(audio_frames/second). For example: 44100. 0,
22254. 54.; number
audiotracknumber kMDItemAudioTrackNumber;
com.apple.metadata:kMDItemAudioTrackNumber; The
track number of a song or composition when it is
part of an album.; number
authoraddresses kMDItemAuthorAddresses;
com.apple.metadata:kMDItemAuthorAddresses; This
attribute indicates the author addresses of the
document.; list of strings
authoremailaddresses kMDItemAuthorEmailAddresses;
com.apple.metadata:kMDItemAuthorEmailAddresses;
This attribute indicates the author of the emails
message addresses. (This is always the email
address, and not the human readable version).; list
of strings
authors kMDItemAuthors; com.apple.metadata:kMDItemAuthors;
The author, or authors, of the contents of the
file.; list of strings
bitspersample kMDItemBitsPerSample;
com.apple.metadata:kMDItemBitsPerSample; The number
of bits per sample. For example, the bit depth of
an image (8-bit, 16-bit etc. . . ) or the bit depth
per audio sample of uncompressed audio data (8, 16,
24, 32, 64, etc. . ).; number
cfbundleidentifier kMDItemCFBundleIdentifier;
com.apple.metadata:kMDItemCFBundleIdentifier; If
this item is a bundle, then this is the
CFBundleIdentifier.; string
city kMDItemCity; com.apple.metadata:kMDItemCity;
Identifies city of origin according to guidelines
established by the provider.; string
codecs kMDItemCodecs; com.apple.metadata:kMDItemCodecs;
The codecs used to encode/decode the media.; list
of strings
colorspace kMDItemColorSpace;
com.apple.metadata:kMDItemColorSpace; The color
space model used by the document contents. For
example, "RGB", "CMYK", "YUV", or "YCbCr".; string
comment kMDItemComment; com.apple.metadata:kMDItemComment;
A comment related to the file. This differs from
the Finder comment, kMDItemFinderComment.; string
composer kMDItemComposer;
com.apple.metadata:kMDItemComposer; The composer of
the music contained in the audio file.; string
contactkeywords kMDItemContactKeywords;
com.apple.metadata:kMDItemContactKeywords; A list
of contacts that are associated with this document,
not including the authors.; list of strings
contentcreationdate kMDItemContentCreationDate;
com.apple.metadata:kMDItemContentCreationDate; The
creation date of an edited or optimized version of
the song or composition.; date/time
contentmodificationdate kMDItemContentModificationDate;
com.apple.metadata:kMDItemContentModificationDate;
The date and time that the contents of the file
were last modified.; date/time
contenttype kMDItemContentType;
com.apple.metadata:kMDItemContentType; The UTI
pedigree of a file.; string
contributors kMDItemContributors;
com.apple.metadata:kMDItemContributors; The
entities responsible for making contributions to
the content of the resource.; list of strings
copyright kMDItemCopyright;
com.apple.metadata:kMDItemCopyright; The copyright
owner of the file contents.; string
country kMDItemCountry; com.apple.metadata:kMDItemCountry;
The full, publishable name of the country or region
where the intellectual property of the item was
created, according to guidelines of the provider.;
string
coverage kMDItemCoverage;
com.apple.metadata:kMDItemCoverage; The extent or
scope of the content of the resource.; string
creator kMDItemCreator; com.apple.metadata:kMDItemCreator;
Application used to create the document content
(for example "Word", "Pages", and so on).; string
deliverytype kMDItemDeliveryType;
com.apple.metadata:kMDItemDeliveryType; The
delivery type. Values are "Fast start" or "RTSP".;
string
description kMDItemDescription;
com.apple.metadata:kMDItemDescription; A
description of the content of the resource. The
description may include an abstract, table of
contents, reference to a graphical representation
of content or a free-text account of the content.;
string
director kMDItemDirector;
com.apple.metadata:kMDItemDirector; Directory of
the movie.; string
displayname kMDItemDisplayName;
com.apple.metadata:kMDItemDisplayName; The
localized version of the file name.; string
downloadeddate kMDItemDownloadedDate;
com.apple.metadata:kMDItemDownloadedDate; Date the
item was downloaded.; list of date/time
duedate kMDItemDueDate; com.apple.metadata:kMDItemDueDate;
Date this item is due.; date/time
durationseconds kMDItemDurationSeconds;
com.apple.metadata:kMDItemDurationSeconds; The
duration, in seconds, of the content of file. A
value of 10. 5 represents media that is 10 and 1/2
seconds long.; number
exifgpsversion kMDItemEXIFGPSVersion;
com.apple.metadata:kMDItemEXIFGPSVersion; The
version of GPSInfoIFD in EXIF used to generate the
metadata.; string
exifversion kMDItemEXIFVersion;
com.apple.metadata:kMDItemEXIFVersion; The version
of the EXIF header used to generate the metadata.;
string
emailaddresses kMDItemEmailAddresses;
com.apple.metadata:kMDItemEmailAddresses; Email
addresses related to this item.; list of strings
encodingapplications kMDItemEncodingApplications;
com.apple.metadata:kMDItemEncodingApplications;
Application used to convert the original content
into it's current form. For example, a PDF file
might have an encoding application set to
"Distiller".; list of strings
exposuremode kMDItemExposureMode;
com.apple.metadata:kMDItemExposureMode; The
exposure mode used to acquire the document
contents.; number
exposureprogram kMDItemExposureProgram;
com.apple.metadata:kMDItemExposureProgram; The
class of the exposure program used by the camera to
set exposure when the image is taken. Possible
values include: Manual, Normal, and Aperture
priority.; string
exposuretimeseconds kMDItemExposureTimeSeconds;
com.apple.metadata:kMDItemExposureTimeSeconds; The
exposure time, in seconds, used to acquire the
document contents.; number
exposuretimestring kMDItemExposureTimeString;
com.apple.metadata:kMDItemExposureTimeString; The
time of the exposure.; string
fnumber kMDItemFNumber; com.apple.metadata:kMDItemFNumber;
The diameter of the diaphragm aperture in terms of
the effective focal length of the lens.; number
fscontentchangedate kMDItemFSContentChangeDate;
com.apple.metadata:kMDItemFSContentChangeDate; The
date the file contents last changed.; date/time
fscreationdate kMDItemFSCreationDate;
com.apple.metadata:kMDItemFSCreationDate; The date
and time that the file was created.; date/time
fshascustomicon kMDItemFSHasCustomIcon;
com.apple.metadata:kMDItemFSHasCustomIcon; Boolean
indicating if this file has a custom icon.; boolean
fsinvisible kMDItemFSInvisible;
com.apple.metadata:kMDItemFSInvisible; Indicates
whether the file is invisible.; boolean
fsisextensionhidden kMDItemFSIsExtensionHidden;
com.apple.metadata:kMDItemFSIsExtensionHidden;
Indicates whether the file extension of the file is
hidden.; boolean
fsisstationery kMDItemFSIsStationery;
com.apple.metadata:kMDItemFSIsStationery; Boolean
indicating if this file is stationery.; boolean
fslabel kMDItemFSLabel; com.apple.metadata:kMDItemFSLabel;
Index of the Finder label of the file. Possible
values are 0 through 7.; number
fsname kMDItemFSName; com.apple.metadata:kMDItemFSName;
The file name of the item.; string
fsnodecount kMDItemFSNodeCount;
com.apple.metadata:kMDItemFSNodeCount; Number of
files in a directory.; number
fsownergroupid kMDItemFSOwnerGroupID;
com.apple.metadata:kMDItemFSOwnerGroupID; The group
ID of the owner of the file.; number
fsowneruserid kMDItemFSOwnerUserID;
com.apple.metadata:kMDItemFSOwnerUserID; The user
ID of the owner of the file.; number
fssize kMDItemFSSize; com.apple.metadata:kMDItemFSSize;
The size, in bytes, of the file on disk.; number
findercomment kMDItemFinderComment;
com.apple.metadata:kMDItemFinderComment; Finder
comments for this file.; string
flashonoff kMDItemFlashOnOff;
com.apple.metadata:kMDItemFlashOnOff; Indicates if
a camera flash was used.; number
focallength kMDItemFocalLength;
com.apple.metadata:kMDItemFocalLength; The actual
focal length of the lens, in millimeters.; number
fonts kMDItemFonts; com.apple.metadata:kMDItemFonts;
Fonts used in this item. You should store the
font's full name, the postscript name, or the font
family name, based on the available information.;
list of strings
gpstrack kMDItemGPSTrack;
com.apple.metadata:kMDItemGPSTrack; The direction
of travel of the item, in degrees from true north.;
string
genre kMDItemGenre; com.apple.metadata:kMDItemGenre;
Genre of the movie.; string
hasalphachannel kMDItemHasAlphaChannel;
com.apple.metadata:kMDItemHasAlphaChannel;
Indicates if this image file has an alpha channel.;
boolean
headline kMDItemHeadline;
com.apple.metadata:kMDItemHeadline; A publishable
entry providing a synopsis of the contents of the
file. For example, "Apple Introduces the iPod
Photo".; string
isospeed kMDItemISOSpeed;
com.apple.metadata:kMDItemISOSpeed; The ISO speed
used to acquire the document contents.; number
identifier kMDItemIdentifier;
com.apple.metadata:kMDItemIdentifier; A formal
identifier used to reference the resource within a
given context.; string
imagedirection kMDItemImageDirection;
com.apple.metadata:kMDItemImageDirection; The
direction of the item's image, in degrees from true
north.; string
information kMDItemInformation;
com.apple.metadata:kMDItemInformation; Information
about the item.; string
instantmessageaddresses kMDItemInstantMessageAddresses;
com.apple.metadata:kMDItemInstantMessageAddresses;
Instant message addresses related to this item.;
list of strings
instructions kMDItemInstructions;
com.apple.metadata:kMDItemInstructions; Editorial
instructions concerning the use of the item, such
as embargoes and warnings. For example, "Second of
four stories".; string
isgeneralmidisequence kMDItemIsGeneralMIDISequence;
com.apple.metadata:kMDItemIsGeneralMIDISequence;
Indicates whether the MIDI sequence contained in
the file is setup for use with a General MIDI
device.; boolean
keysignature kMDItemKeySignature;
com.apple.metadata:kMDItemKeySignature; The key of
the music contained in the audio file. For example:
C, Dm, F#m, Bb.; string
keywords kMDItemKeywords;
com.apple.metadata:kMDItemKeywords; Keywords
associated with this file. For example, "Birthday",
"Important", etc.; list of strings
kind kMDItemKind; com.apple.metadata:kMDItemKind; A
description of the kind of item this file
represents.; string
languages kMDItemLanguages;
com.apple.metadata:kMDItemLanguages; Indicates the
languages of the intellectual content of the
resource. Recommended best practice for the values
of the Language element is defined by RFC 3066.;
list of strings
lastuseddate kMDItemLastUsedDate;
com.apple.metadata:kMDItemLastUsedDate; The date
and time that the file was last used. This value is
updated automatically by LaunchServices everytime a
file is opened by double clicking, or by asking
LaunchServices to open a file.; date/time
latitude kMDItemLatitude;
com.apple.metadata:kMDItemLatitude; The latitude of
the item in degrees north of the equator, expressed
using the WGS84 datum. Negative values lie south of
the equator.; string
layernames kMDItemLayerNames;
com.apple.metadata:kMDItemLayerNames; The names of
the layers in the file.; list of strings
longitude kMDItemLongitude;
com.apple.metadata:kMDItemLongitude; The longitude
of the item in degrees east of the prime meridian,
expressed using the WGS84 datum. Negative values
lie west of the prime meridian.; string
lyricist kMDItemLyricist;
com.apple.metadata:kMDItemLyricist; The lyricist,
or text writer, of the music contained in the audio
file.; string
maxaperture kMDItemMaxAperture;
com.apple.metadata:kMDItemMaxAperture; The smallest
f-number of the lens. Ordinarily it is given in the
range of 00. 00 to 99. 99.; number
mediatypes kMDItemMediaTypes;
com.apple.metadata:kMDItemMediaTypes; The media
types present in the content.; list of strings
meteringmode kMDItemMeteringMode;
com.apple.metadata:kMDItemMeteringMode; The
metering mode used to take the image.; string
musicalgenre kMDItemMusicalGenre;
com.apple.metadata:kMDItemMusicalGenre; The musical
genre of the song or composition contained in the
audio file. For example: Jazz, Pop, Rock,
Classical.; string
musicalinstrumentcategory kMDItemMusicalInstrumentCategory; com.apple.metadat
a:kMDItemMusicalInstrumentCategory; Specifies the
category of an instrument.; string
musicalinstrumentname kMDItemMusicalInstrumentName;
com.apple.metadata:kMDItemMusicalInstrumentName;
Specifies the name of instrument relative to the
instrument category.; string
namedlocation kMDItemNamedLocation;
com.apple.metadata:kMDItemNamedLocation; The name
of the location or point of interest associated
with the item. The name may be user provided.;
string
numberofpages kMDItemNumberOfPages;
com.apple.metadata:kMDItemNumberOfPages; Number of
pages in the document.; number
organizations kMDItemOrganizations;
com.apple.metadata:kMDItemOrganizations; The
company or organization that created the document.;
list of strings
orientation kMDItemOrientation;
com.apple.metadata:kMDItemOrientation; The
orientation of the document contents. Possible
values are 0 (landscape) and 1 (portrait).; number
originalformat kMDItemOriginalFormat;
com.apple.metadata:kMDItemOriginalFormat; Original
format of the movie.; string
originalsource kMDItemOriginalSource;
com.apple.metadata:kMDItemOriginalSource; Original
source of the movie.; string
pageheight kMDItemPageHeight;
com.apple.metadata:kMDItemPageHeight; Height of the
document page, in points (72 points per inch). For
PDF files this indicates the height of the first
page only.; number
pagewidth kMDItemPageWidth;
com.apple.metadata:kMDItemPageWidth; Width of the
document page, in points (72 points per inch). For
PDF files this indicates the width of the first
page only.; number
participants kMDItemParticipants;
com.apple.metadata:kMDItemParticipants; The list of
people who are visible in an image or movie or
written about in a document.; list of strings
path kMDItemPath; com.apple.metadata:kMDItemPath; The
complete path to the file.; string
performers kMDItemPerformers;
com.apple.metadata:kMDItemPerformers; Performers in
the movie.; list of strings
phonenumbers kMDItemPhoneNumbers;
com.apple.metadata:kMDItemPhoneNumbers; Phone
numbers related to this item.; list of strings
pixelcount kMDItemPixelCount;
com.apple.metadata:kMDItemPixelCount; The total
number of pixels in the contents. Same as
kMDItemPixelWidth x kMDItemPixelHeight.; number
pixelheight kMDItemPixelHeight;
com.apple.metadata:kMDItemPixelHeight; The height,
in pixels, of the contents. For example, the image
height or the video frame height.; number
pixelwidth kMDItemPixelWidth;
com.apple.metadata:kMDItemPixelWidth; The width, in
pixels, of the contents. For example, the image
width or the video frame width.; number
producer kMDItemProducer;
com.apple.metadata:kMDItemProducer; Producer of the
content.; string
profilename kMDItemProfileName;
com.apple.metadata:kMDItemProfileName; The name of
the color profile used by the document contents.;
string
projects kMDItemProjects;
com.apple.metadata:kMDItemProjects; The list of
projects that this file is part of. For example, if
you were working on a movie all of the files could
be marked as belonging to the project "My Movie".;
list of strings
publishers kMDItemPublishers;
com.apple.metadata:kMDItemPublishers; The entity
responsible for making the resource available. For
example, a person, an organization, or a service.
Typically, the name of a publisher should be used
to indicate the entity.; list of strings
recipientaddresses kMDItemRecipientAddresses;
com.apple.metadata:kMDItemRecipientAddresses; This
attribute indicates the recipient addresses of the
document.; list of strings
recipientemailaddresses kMDItemRecipientEmailAddresses;
com.apple.metadata:kMDItemRecipientEmailAddresses;
This attribute indicates the recipients email
addresses. (This is always the email address, and
not the human readable version).; list of strings
recipients kMDItemRecipients;
com.apple.metadata:kMDItemRecipients; Recipients of
this item.; list of strings
recordingdate kMDItemRecordingDate;
com.apple.metadata:kMDItemRecordingDate; The
recording date of the song or composition.;
date/time
recordingyear kMDItemRecordingYear;
com.apple.metadata:kMDItemRecordingYear; Indicates
the year the item was recorded. For example, 1964,
2003, etc.; number
redeyeonoff kMDItemRedEyeOnOff;
com.apple.metadata:kMDItemRedEyeOnOff; Indicates if
red-eye reduction was used to take the picture.;
boolean
resolutionheightdpi kMDItemResolutionHeightDPI;
com.apple.metadata:kMDItemResolutionHeightDPI;
Resolution height, in DPI, of this image.; number
resolutionwidthdpi kMDItemResolutionWidthDPI;
com.apple.metadata:kMDItemResolutionWidthDPI;
Resolution width, in DPI, of this image.; number
rights kMDItemRights; com.apple.metadata:kMDItemRights;
Provides a link to information about rights held in
and over the resource.; string
securitymethod kMDItemSecurityMethod;
com.apple.metadata:kMDItemSecurityMethod; The
security or encryption method used for the file.;
string
speed kMDItemSpeed; com.apple.metadata:kMDItemSpeed; The
speed of the item, in kilometers per hour.; string
starrating kMDItemStarRating;
com.apple.metadata:kMDItemStarRating; User rating
of this item. For example, the stars rating of an
iTunes track.; number
stateorprovince kMDItemStateOrProvince;
com.apple.metadata:kMDItemStateOrProvince;
Identifies the province or state of origin
according to guidelines established by the
provider. For example, "CA", "Ontario", or
"Sussex".; string
streamable kMDItemStreamable;
com.apple.metadata:kMDItemStreamable; Whether the
content is prepared for streaming.; boolean
subject kMDItemSubject; com.apple.metadata:kMDItemSubject;
Subject of the this item.; string
tempo kMDItemTempo; com.apple.metadata:kMDItemTempo; A
float value that specifies the beats per minute of
the music contained in the audio file.; number
textcontent kMDItemTextContent;
com.apple.metadata:kMDItemTextContent; Contains a
text representation of the content of the document.
Data in multiple fields should be combined using a
whitespace character as a separator.; string
theme kMDItemTheme; com.apple.metadata:kMDItemTheme;
Theme of the this item.; string
timesignature kMDItemTimeSignature;
com.apple.metadata:kMDItemTimeSignature; The time
signature of the musical composition contained in
the audio/MIDI file. For example: "4/4", "7/8".;
string
timestamp kMDItemTimestamp;
com.apple.metadata:kMDItemTimestamp; The timestamp
on the item. This generally is used to indicate the
time at which the event captured by the item took
place.; string
title kMDItemTitle; com.apple.metadata:kMDItemTitle; The
title of the file. For example, this could be the
title of a document, the name of a song, or the
subject of an email message.; string
totalbitrate kMDItemTotalBitRate;
com.apple.metadata:kMDItemTotalBitRate; The total
bit rate, audio and video combined, of the media.;
number
url kMDItemURL; com.apple.metadata:kMDItemURL; Url of
the item.; string
version kMDItemVersion; com.apple.metadata:kMDItemVersion;
The version number of this file.; string
videobitrate kMDItemVideoBitRate;
com.apple.metadata:kMDItemVideoBitRate; The video
bit rate.; number
wherefroms kMDItemWhereFroms;
com.apple.metadata:kMDItemWhereFroms; Describes
where the file was obtained from.; list of strings
whitebalance kMDItemWhiteBalance;
com.apple.metadata:kMDItemWhiteBalance; The white
balance setting used to acquire the document
contents. Possible values are 0 (auto white
balance) and 1 (manual).; number
```
<!-- [[[end]]] -->
## Notes on backup/restore
When run with `--backup`, osxmetadata backs up the metadata of each file in a file called `.osxmetadata.json`. A backup file is created in every directory that includes files being backup up. The format is plain JSON text with a record for each file that was backed up. If you delete a file then run the `--backup` again, the deleted file's record is not deleted from the `.osxmetadata.json` backup file. The backup file is kept in each directory/sub-directory and only the filename is used for `--restore` which means you can move/rename the directory (along with the `.osxmetadata.json` file) and the restore will still work correctly.
**Note**: Prior to version 0.99.38, the backup file was not well-formed JSON which meant that some apps/viewers could not process the JSON file. Version 0.99.38 fixes this and will silently update any `.osxmetadata.json` file encountered during `--backup` to be well-formed JSON but this breaks backwards compatibility with older versions of osxmetadata. If you use osxmetadata to sync data across multiple Macs, you must ensure all Macs are running the updated version. For additional details, see [issue #57](https://github.com/RhetTbull/osxmetadata/issues/57).
## Usage Notes
This will only work on file systems that support Mac OS X extended attributes.
## Related Projects
- [tag](https://github.com/jdberry/tag) A command line tool to manipulate tags on Mac OS X files, and to query for files with those tags.
- [osx-tags](https://github.com/scooby/osx-tags) Python module to manipulate Finder tags in OS X.
## Acknowledgements
This module was inspired by [osx-tags](https://github.com/scooby/osx-tags) by "Ben S / scooby". I leveraged osx-tags to bootstrap the design of this module. I wanted a more general OS X metadata library so I rolled my own. This module is published under the same MIT license as osx-tags.
## License
MIT License
Copyright (c) 2020 Rhet Turnbull
## Contributing
Contributions of all kinds are welcome. Please submit a pull request or open an issue.
## Contributors β¨
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<table>
<tbody>
<tr>
<td align="center"><a href="http://www.borja.glezseoane.es"><img src="https://avatars.githubusercontent.com/u/24481419?v=4?s=75" width="75px;" alt="Borja GonzΓ‘lez Seoane"/><br /><sub><b>Borja GonzΓ‘lez Seoane</b></sub></a><br /><a href="https://github.com/RhetTbull/osxmetadata/commits?author=bglezseoane" title="Code">π»</a></td>
<td align="center"><a href="https://github.com/porg"><img src="https://avatars.githubusercontent.com/u/737143?v=4?s=75" width="75px;" alt="porg"/><br /><sub><b>porg</b></sub></a><br /><a href="https://github.com/RhetTbull/osxmetadata/issues?q=author%3Aporg" title="Bug reports">π</a> <a href="#ideas-porg" title="Ideas, Planning, & Feedback">π€</a></td>
<td align="center"><a href="https://github.com/nk9"><img src="https://avatars.githubusercontent.com/u/3646730?v=4?s=75" width="75px;" alt="Nick Kocharhook"/><br /><sub><b>Nick Kocharhook</b></sub></a><br /><a href="https://github.com/RhetTbull/osxmetadata/issues?q=author%3Ank9" title="Bug reports">π</a></td>
<td align="center"><a href="https://jakewilliami.github.io/"><img src="https://avatars.githubusercontent.com/u/54291317?v=4?s=75" width="75px;" alt="Jake Ireland"/><br /><sub><b>Jake Ireland</b></sub></a><br /><a href="#ideas-jakewilliami" title="Ideas, Planning, & Feedback">π€</a></td>
<td align="center"><a href="https://github.com/luckman212"><img src="https://avatars.githubusercontent.com/u/1992842?v=4?s=75" width="75px;" alt="Luke Hamburg"/><br /><sub><b>Luke Hamburg</b></sub></a><br /><a href="https://github.com/RhetTbull/osxmetadata/issues?q=author%3Aluckman212" title="Bug reports">π</a> <a href="https://github.com/RhetTbull/osxmetadata/commits?author=luckman212" title="Code">π»</a></td>
</tr>
</tbody>
</table>
<!-- markdownlint-restore -->
<!-- prettier-ignore-end -->
<!-- ALL-CONTRIBUTORS-LIST:END -->
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
%package help
Summary: Development documents and examples for osxmetadata
Provides: python3-osxmetadata-doc
%description help
# osxmetadata
[](https://github.com/python/black)
[](https://opensource.org/licenses/MIT)
[](#contributors-)
## What is osxmetadata?
osxmetadata provides a simple interface to access various metadata about MacOS / OS X files. Currently supported metadata attributes include tags/keywords, Finder comments, authors, etc.
## Why osxmetadata?
Apple provides rich support for file metadata through the [MDItem](https://developer.apple.com/documentation/coreservices/file_metadata/mditem) class and the [NSURL getResourceValue:forKey:error:](https://developer.apple.com/documentation/foundation/nsurl/1408874-getresourcevalue?language=objc) method. However, Apple does not provide a way to easily set much of the metadata. For example, while there is a documented [MDItem MDItemCopyAttribute](https://developer.apple.com/documentation/coreservices/1427080-mditemcopyattribute?language=objc) to copy metadata attributes such as [kMDItemAuthors](https://developer.apple.com/documentation/coreservices/kmditemauthors?language=objc), Apple does not provide a public interface to set this data. Other data, such as Finder comments, can only be set through sending AppleScript commands to the Finder and others, like Finder tags can be retrieved but cannot be set through the public API.
osxmetadata provides a unified interface to get and set most of the metadata available on your Mac from python. It uses a combination of documented and undocumented APIs to access the metadata. It also provides a simple interface to set Finder tags and Finder comments.
MacOS provides some tools to view these various metadata attributes. For example, `mdls` lists the MDItem Spotlight metadata associated with a file but doesn't let you edit the data. osxmetadata makes it easy to to both view and manipulate the macOS metadata attributes, either programmatically or through an included `osxmetadata` command line tool.
## Supported operating systems
Only works on MacOS. Requires Python 3.8+. Tested on macOS 10.15.7 (Catalina); should work on all versions of macOS 10.15 and later.
## Installation instructions
### Installation using pipx
If you aren't familiar with installing python applications, I recommend you install `osxmetadata` with [pipx](https://github.com/pipxproject/pipx). If you use `pipx`, you will not need to create a virtual environment as `pipx` takes care of this. The easiest way to do this on a Mac is to use [homebrew](https://brew.sh/):
- Open `Terminal` (search for `Terminal` in Spotlight or look in `Applications/Utilities`)
- Install `homebrew` according to instructions at [https://brew.sh/](https://brew.sh/)
- Type the following into Terminal: `brew install pipx`
- Then type this: `pipx install osxmetadata`
- Now you should be able to run `osxmetadata` by typing: `osxmetadata`
Once you've installed osxmetadata with pipx, to upgrade to the latest version:
pipx upgrade osxmetadata
### Installation using pip
You can also install directly from [pypi](https://pypi.org/project/osxmetadata/):
pip install osxmetadata
Once you've installed osxmetadata with pip, to upgrade to the latest version:
pip install --upgrade osxmetadata
### Installation from git repository
OSXMetaData uses setuptools, thus simply run:
git clone https://github.com/RhetTbull/osxmetadata.git
cd osxmetadata
pip install poetry
poetry install
I recommend you create a [virtual environment](https://docs.python.org/3/tutorial/venv.html) before installing osxmetadata.
## Using the API
```pycon
>>> import datetime
>>> import pathlib
>>> from osxmetadata import *
>>> pathlib.Path("test_file.txt").touch()
>>> md = OSXMetaData("test_file.txt")
>>> md.set(kMDItemAuthors, ["Jane Smith", "John Doe"])
>>> md.get(kMDItemAuthors)
['Jane Smith', 'John Doe']
>>> md.kMDItemFinderComment = "This is my comment"
>>> md.kMDItemFinderComment
'This is my comment'
>>> md.tags = [Tag("Test", FINDER_COLOR_NONE), Tag("ToDo", FINDER_COLOR_RED)]
>>> md.tags
[Tag(name='Test', color=0), Tag(name='ToDo', color=6)]
>>> md[kMDItemDueDate] = datetime.datetime(2022,10,1)
>>> md[kMDItemDueDate]
datetime.datetime(2022, 10, 1, 0, 0)
>>>
```
Somewhat contrary to the [Zen of Python](https://peps.python.org/pep-0020/), osxmetadata provides more than one way to access metadata attributes. You can get and set metadata attributes using the `get()`/`set()` getter/setter methods, using the attribute name as a dictionary key on the OSXMetaData object, or using the attribute name as an attribute on the `OSXMetaData()` object. For example, the following are all equivalent:
- `OSXMetaData.get(attribute)` - get the value of the metadata attribute `attribute`
- `OSXMetaData[attribute]` - get the value of the metadata attribute `attribute`
- `OSXMetaData.attribute` - get the value of the metadata attribute `attribute`
As are the following:
- `OSXMetaData.set(attribute, value)` - set the value of the metadata attribute `attribute` to `value`
- `OSXMetaData[attribute] = value` - set the value of the metadata attribute `attribute` to `value`
- `OSXMetaData.attribute = value` - set the value of the metadata attribute `attribute` to `value`
This allows you to use osxmetadata in accordance with your own code style preferences.
Supported attribute names include all attributes defined for [MDItem](https://developer.apple.com/documentation/coreservices/file_metadata/mditem) and all resource keys defined for [NSURL](https://developer.apple.com/documentation/foundation/nsurl?language=objc). Additionally, the metadata constants defined in the [MDImporter](https://developer.apple.com/documentation/coreservices/file_metadata/mdimporter?language=objc) are supported as well as the following additional attributes:
- `_kMDItemUserTags` - list of Finder tags
- `kMDItemDownloadedDate` - list of datetime objects for when the file was downloaded
Additionally, osxmetadata defines a "shortcut name" attribute for each MDItem attribute that can be used as a shortcut `OSXMetaData` class attribute. The shortcut name is the lowercase value of text following `kMDItem` for each attribute. For example, `kMDItemAuthors` has a short name of `authors` so you can set the authors like this:
```pycon
>>> from osxmetadata import *
>>> md = OSXMetaData("test_file.txt")
>>> md.authors = ["Jane Smith", "John Doe"]
>>> md.authors
['Jane Smith', 'John Doe']
>>>
```
and `kMDItemDueDate` would have a short name of `duedate`:
```pycon
>>> from osxmetadata import *
>>> import datetime
>>> md = OSXMetaData("test_file.txt")
>>> md.duedate = datetime.datetime(2022, 10, 1)
>>> md.duedate
datetime.datetime(2022, 10, 1, 0, 0)
>>>
```
The names of all supported attributes are available in the `osxmetadata.ALL_ATTRIBUTES` set:
```pycon
>>> from osxmetadata import ALL_ATTRIBUTES
>>> "kMDItemDueDate" in ALL_ATTRIBUTES
True
>>> "NSURLTagNamesKey" in ALL_ATTRIBUTES
True
>>> "findercomment" in ALL_ATTRIBUTES
True
>>>
```
The class attributes are handled dynamically which, unfortunately, means that IDEs like PyCharm and Visual Studio Code cannot provide tab-completion for them.
## Finder Tags
Unlike other attributes, which are mapped to native Python types appropriate for the source Objective C type, Finder tags (`_kMDItemUserTags` or `tags`) have two components: a name (str) and a color ID (unsigned int in range 0 to 7) representing a color tag in the Finder. Reading tags returns a list of `Tag` namedtuples and setting tags requires a list of `Tag` namedtuples.
```pycon
>>> from osxmetadata import *
>>> md = OSXMetaData("test_file.txt")
>>> md.tags = [Tag("Test", FINDER_COLOR_NONE), Tag("ToDo", FINDER_COLOR_RED)]
>>> md.tags
[Tag(name='Test', color=0), Tag(name='ToDo', color=6)]
>>> md.get("_kMDItemUserTags")
[Tag(name='Test', color=0), Tag(name='ToDo', color=6)]
>>>
```
Tag names (but not colors) can also be accessed through the [NSURLTagNamesKey](https://developer.apple.com/documentation/foundation/nsurltagnameskey) resource key and the label color ID is accessible through `NSURLLabelNumberKey`; the localized label color name is accessible through `NSURLLocalizedLabelKey` though these latter two resource keys only return a single color whereas a file may have more than one color tag. For most purposes, I recommend using the `tags` attribute as it is more convenient and provides access to both the name and color ID of the tag.
```pycon
>>> from osxmetadata import *
>>> md = OSXMetaData("test_file.txt")
>>> md.tags = [Tag("Test", FINDER_COLOR_NONE), Tag("ToDo", FINDER_COLOR_RED)]
>>> md.tags
[Tag(name='Test', color=0), Tag(name='ToDo', color=6)]
>>> md.NSURLTagNamesKey
(
Test,
ToDo
)
>>> md.NSURLLabelNumberKey
6
>>> md.NSURLLocalizedLabelKey
'Red'
>>> md.NSURLTagNamesKey = ["NewTag"]
>>> md.NSURLTagNamesKey
(
NewTag
)
>>> md.tags
[Tag(name='NewTag', color=0)]
>>>
```
### Create a Tag namedtuple
`Tag(name, color)`
- `name`: tag name (str)
- `color`: color ID for Finder color label associated with tag (int)
Valid color constants (exported by osxmetadata):
- `FINDER_COLOR_NONE` = 0
- `FINDER_COLOR_GRAY` = 1
- `FINDER_COLOR_GREEN` = 2
- `FINDER_COLOR_PURPLE` = 3
- `FINDER_COLOR_BLUE` = 4
- `FINDER_COLOR_YELLOW` = 5
- `FINDER_COLOR_RED` = 6
- `FINDER_COLOR_ORANGE` = 7
## Finder Comments
Finder comments can be access via the `kMDItemFinderComment` attribute or the `findercomment` shortcut attribute. Apple provides a public API for getting Finder comments but does not provide a programmatic method for setting Finder comments and I have not been able to find a private API for doing so. osxmetadata works around this by send AppleScript events to the Finder to set the Finder comment. This means that setting Finder comments is slower than setting other attributes and may not work in all circumstances. The first time you set a Finder comment, your terminal app may need to prompt you to allow AppleScript to control the Finder. If you include osxmetadata in a standalone app, for example, one created with [py2app](https://py2app.readthedocs.io/en/latest/), you will need to include the `com.apple.security.automation.apple-events` entitlement and the `NSAppleEventsUsageDescription` key in your app's `Info.plist` file. See the [Apple Developer Documentation](https://developer.apple.com/documentation/bundleresources/information_property_list/nsappleeventsusagedescription?language=objc) for more information.
```pycon
>>> from osxmetadata import *
>>> md = OSXMetaData("test_file.txt")
>>> md.kMDItemFinderComment = "Hello World!"
>>> md.kMDItemFinderComment
'Hello World!'
>>> md.findercomment
'Hello World!'
>>>
```
## Dates/Times
Metadata attributes which return date/times such as `kMDItemDueDate` or `kMDItemDownloadedDate` return a `datetime.datetime` object. The `datetime.datetime` object is timezone-naive (does not contain timezone) and returns the time in the local timezone. Internally, Apple appears to store these as [CFDate](https://developer.apple.com/documentation/corefoundation/cfdate?language=objc) objects in the UTC timezone but when retrieved, they are returned in the local time. You may pass a timezone-aware datetime object to set these attributes and it will be converted appropriately.
```pycon
>>> from osxmetadata import *
>>> md = OSXMetaData("test_file.txt")
>>> import datetime
>>> md.kMDItemDueDate = datetime.datetime(2022, 10, 1)
>>> md.kMDItemDueDate
datetime.datetime(2022, 10, 1, 0, 0)
>>> md.kMDItemDownloadedDate = datetime.datetime(2022, 10, 1, tzinfo=datetime.timezone.utc)
>>>
```
## Extended Attributes
In addition to `MDItem` and `NSURL` metadata attributes, osxmetadata can also read & write metadata saved in extended attributes. For many MDItem attributes, Apple stores the same data in both the MDItem and extended attribute (with name `com.apple.metadata:AttributeName`). For example, the `kMDItemWhereFroms` attribute can be accessed both via MDItemCopyAttribute (exposed via osxmetadata's `get()` method) and via the `com.apple.metadata:kMDItemWhereFroms` extended attribute. The extended attribute is a binary plist (BPLIST) and can be read using the `xattr` command line tool. The `get_xattr()` method will return the value of the extended attribute and the `set_xattr()` method will set it. Extended attributes can be removed with the `remove_xattr()` method. `get_xattr()` provides for an optional callable argument, `decode`, which will be called on the returned value. `set_xattr()` provides an optional callable argument `encode`. This is useful for encoding/decoding binary plist data. For example, to decode the `com.apple.metadata:kMDItemWhereFroms` extended attribute, you can use the `plistlib.loads()` function:
```pycon
>>> from osxmetadata import *
>>> import plistlib
>>> from plistlib import FMT_BINARY
>>> from functools import partial
>>> md = OSXMetaData("test_file.txt")
>>> md.kMDItemWhereFroms = ["apple.com"]
>>> md.kMDItemWhereFroms
['apple.com']
>>> decode = partial(plistlib.loads, fmt=FMT_BINARY)
>>> encode = partial(plistlib.dumps, fmt=FMT_BINARY)
>>> md.get_xattr("com.apple.metadata:kMDItemWhereFroms")
b'bplist00\xa1\x01Yapple.com\x08\n\x00\x00\x00\x00\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x14'
>>> md.get_xattr("com.apple.metadata:kMDItemWhereFroms", decode=decode)
['apple.com']
>>> md.set_xattr("com.apple.metadata:kMDItemWhereFroms", ["google.com"], encode=encode)
>>> md.get_xattr("com.apple.metadata:kMDItemWhereFroms", decode=decode)
['google.com']
>>> md.remove_xattr("com.apple.metadata:kMDItemWhereFroms")
>>>
```
For most use cases, it is recommended you do not directly access the Apple metadata related extended attributes and instead use the getter/setter methods provided by osxmetadata.
## Finder Info
The Finder keeps some legacy Finder info data about files in a bitstring stored in the `com.apple.FinderInfo` extended attribute. osxmetadata provides some attributes for working with this data.
- `stationerypad`: True if the file is a stationery pad (file template) otherwise False; setting this attribute has the same effect as setting the `Stationery pad` checkbox in the Finder's `Get Info` window.
- `findercolor`: The color of the file as an integer; setting this attribute has the same effect as applying a color label in the Finder's `Get Info` window. osxmetadata will set this attribute automatically when setting user tags; it is recommended you do not set this attribute directly.
- `finderinfo`: The raw Finder info data as a bytes object; you should only manipulate this attribute if you know what you are doing.
## Temporary Files
Spotlight does not appear to index temporary files (those in `/tmp` or `/private/var/tmp`). Setting metadata using osxmetadata on temporary files in these locations will not fail but but it appears the metadata will not be indexed and a subsequent read will return the default value as if the metadata had not been written. This is not a limitation of osxmetadata but rather a limitation of Spotlight. If you need to set metadata on temporary files, you should use a different location.
## Command Line Usage
Installs command line tool called `osxmetadata` which provides a simple interface to view/edit metadata supported by osxmetadata.
If you only care about the command line tool, I recommend installing with [pipx](https://github.com/pipxproject/pipx)
The command line tool can also be run via `python -m osxmetadata`. Running it with no arguments or with --help option will print a help message:
<!-- [[[cog
import cog
from osxmetadata.__main__ import cli
from click.testing import CliRunner
runner = CliRunner()
result = runner.invoke(cli, ["--help"])
help = result.output.replace("Usage: cli", "Usage: osxmetadata")
cog.out(
"```\n{}\n```".format(help)
)
]]] -->
```
Usage: osxmetadata [OPTIONS] FILE
Read/write metadata from file(s).
Options:
-v, --version Show the version and exit.
-w, --walk Walk directory tree, processing each file in
the tree.
-j, --json Print output in JSON format, for use with
--list and --get.
-X, --wipe Wipe all metadata attributes from FILE.
-s, --set ATTRIBUTE VALUE Set ATTRIBUTE to VALUE. If ATTRIBUTE is a
multi-value attribute, such as keywords
(kMDItemKeywords), you may specify --set
multiple times to add to the array of values:
'--set keywords foo --set keywords bar' will
set keywords to ['foo', 'bar']. Not that this
will overwrite any existing values for the
attribute; see also --append.
-l, --list List all metadata attributes for FILE.
-c, --clear ATTRIBUTE Remove attribute from FILE.
-a, --append ATTRIBUTE VALUE Append VALUE to ATTRIBUTE; for multi-valued
attributes, appends only if VALUE is not
already present. May be used in combination
with --set to add to an existing value: '--set
keywords foo --append keywords bar' will set
keywords to ['foo', 'bar'], overwriting any
existing values for the attribute.
-g, --get ATTRIBUTE Get value of ATTRIBUTE.
-r, --remove ATTRIBUTE VALUE Remove VALUE from ATTRIBUTE; only applies to
multi-valued attributes.
-m, --mirror ATTRIBUTE1 ATTRIBUTE2
Mirror values between ATTRIBUTE1 and
ATTRIBUTE2 so that ATTRIBUTE1 = ATTRIBUTE2;
for multi-valued attributes, merges values;
for string attributes, sets ATTRIBUTE1 =
ATTRIBUTE2 overwriting any value in
ATTRIBUTE1. For example: '--mirror keywords
tags' sets tags and keywords to same values.
-B, --backup Backup FILE attributes. Backup file
'.osxmetadata.json' will be created in same
folder as FILE. Only backs up attributes known
to osxmetadata unless used with --all.
-R, --restore Restore FILE attributes from backup file.
Restore will look for backup file
'.osxmetadata.json' in same folder as FILE.
Only restores attributes known to osxmetadata
unless used with --all.
-V, --verbose Print verbose output.
-f, --copyfrom SOURCE_FILE Copy attributes from file SOURCE_FILE (only
updates destination attributes that are not
null in SOURCE_FILE).
--files-only Do not apply metadata commands to directories
themselves, only files in a directory.
-p, --pattern PATTERN Only process files matching PATTERN; only
applies to --walk. If specified, only files
matching PATTERN will be processed as each
directory is walked. May be used for than once
to specify multiple patterns. For example, tag
all *.pdf files in projectdir and subfolders
with tag 'project': osxmetadata --append tags
'project' --walk projectdir/ --pattern '*.pdf'
--help Show this message and exit.
Valid attributes for ATTRIBUTE: Each attribute has a short name, a constant
name, and a long constant name. Any of these may be used for ATTRIBUTE
For example: --set findercomment "Hello world"
or: --set kMDItemFinderComment "Hello world"
or: --set com.apple.metadata:kMDItemFinderComment "Hello world"
Attributes that are strings can only take one value for --set; --append will
append to the existing value. Attributes that are arrays can be set multiple
times to add to the array: e.g. --set keywords 'foo' --set keywords 'bar' will
set keywords to ['foo', 'bar']
Options are executed in the following order regardless of order passed on the
command line: restore, wipe, copyfrom, clear, set, append, remove, mirror, get,
list, backup. --backup and --restore are mutually exclusive. Other options may
be combined or chained together.
Finder tags (tags attribute) contain both a name and an optional color. To
specify the color, append comma + color name (e.g. 'red') after the tag name.
For example --set tags Foo,red. Valid color names are: gray, green, purple,
blue, yellow, red, orange. If color is not specified but a tag of the same name
has already been assigned a color in the Finder, the same color will
automatically be assigned.
com.apple.FinderInfo (finderinfo) value is a key:value dictionary. To set
finderinfo, pass value in format key1:value1,key2:value2,etc. For example:
'osxmetadata --set finderinfo color:2 file.ext'.
Short Name Description
acquisitionmake kMDItemAcquisitionMake;
com.apple.metadata:kMDItemAcquisitionMake; The
manufacturer of the device used to aquire the
document contents.; string
acquisitionmodel kMDItemAcquisitionModel;
com.apple.metadata:kMDItemAcquisitionModel; The
model of the device used to aquire the document
contents. For example, 100, 200, 400, etc.; string
album kMDItemAlbum; com.apple.metadata:kMDItemAlbum; The
title for a collection of media. This is analagous
to a record album, or photo album.; string
altitude kMDItemAltitude;
com.apple.metadata:kMDItemAltitude; The altitude of
the item in meters above sea level, expressed using
the WGS84 datum. Negative values lie below sea
level.; string
aperture kMDItemAperture;
com.apple.metadata:kMDItemAperture; The aperture
setting used to acquire the document contents. This
unit is the APEX value.; number
appleloopdescriptors kMDItemAppleLoopDescriptors;
com.apple.metadata:kMDItemAppleLoopDescriptors;
Specifies multiple pieces of descriptive
information about a loop.; list of strings
appleloopskeyfiltertype kMDItemAppleLoopsKeyFilterType;
com.apple.metadata:kMDItemAppleLoopsKeyFilterType;
Specifies key filtering information about a loop.
Loops are matched against projects that often in a
major or minor key.; string
appleloopsloopmode kMDItemAppleLoopsLoopMode;
com.apple.metadata:kMDItemAppleLoopsLoopMode;
Specifies how a file should be played.; string
appleloopsrootkey kMDItemAppleLoopsRootKey;
com.apple.metadata:kMDItemAppleLoopsRootKey;
Specifies the loop's original key. The key is the
root note or tonic for the loop, and does not
include the scale type.; string
attributechangedate kMDItemAttributeChangeDate;
com.apple.metadata:kMDItemAttributeChangeDate; The
date and time of the last change made to a metadata
attribute.; date/time
audiences kMDItemAudiences;
com.apple.metadata:kMDItemAudiences; The audience
for which the file is intended. The audience may be
determined by the creator or the publisher or by a
third party.; list of strings
audiobitrate kMDItemAudioBitRate;
com.apple.metadata:kMDItemAudioBitRate; The audio
bit rate.; number
audiochannelcount kMDItemAudioChannelCount;
com.apple.metadata:kMDItemAudioChannelCount; Number
of channels in the audio data contained in the
file.; number
audioencodingapplication kMDItemAudioEncodingApplication;
com.apple.metadata:kMDItemAudioEncodingApplication;
The name of the application that encoded the data
contained in the audio file.; string
audiosamplerate kMDItemAudioSampleRate;
com.apple.metadata:kMDItemAudioSampleRate; Sample
rate of the audio data contained in the file. The
sample rate is a float value representing hz
(audio_frames/second). For example: 44100. 0,
22254. 54.; number
audiotracknumber kMDItemAudioTrackNumber;
com.apple.metadata:kMDItemAudioTrackNumber; The
track number of a song or composition when it is
part of an album.; number
authoraddresses kMDItemAuthorAddresses;
com.apple.metadata:kMDItemAuthorAddresses; This
attribute indicates the author addresses of the
document.; list of strings
authoremailaddresses kMDItemAuthorEmailAddresses;
com.apple.metadata:kMDItemAuthorEmailAddresses;
This attribute indicates the author of the emails
message addresses. (This is always the email
address, and not the human readable version).; list
of strings
authors kMDItemAuthors; com.apple.metadata:kMDItemAuthors;
The author, or authors, of the contents of the
file.; list of strings
bitspersample kMDItemBitsPerSample;
com.apple.metadata:kMDItemBitsPerSample; The number
of bits per sample. For example, the bit depth of
an image (8-bit, 16-bit etc. . . ) or the bit depth
per audio sample of uncompressed audio data (8, 16,
24, 32, 64, etc. . ).; number
cfbundleidentifier kMDItemCFBundleIdentifier;
com.apple.metadata:kMDItemCFBundleIdentifier; If
this item is a bundle, then this is the
CFBundleIdentifier.; string
city kMDItemCity; com.apple.metadata:kMDItemCity;
Identifies city of origin according to guidelines
established by the provider.; string
codecs kMDItemCodecs; com.apple.metadata:kMDItemCodecs;
The codecs used to encode/decode the media.; list
of strings
colorspace kMDItemColorSpace;
com.apple.metadata:kMDItemColorSpace; The color
space model used by the document contents. For
example, "RGB", "CMYK", "YUV", or "YCbCr".; string
comment kMDItemComment; com.apple.metadata:kMDItemComment;
A comment related to the file. This differs from
the Finder comment, kMDItemFinderComment.; string
composer kMDItemComposer;
com.apple.metadata:kMDItemComposer; The composer of
the music contained in the audio file.; string
contactkeywords kMDItemContactKeywords;
com.apple.metadata:kMDItemContactKeywords; A list
of contacts that are associated with this document,
not including the authors.; list of strings
contentcreationdate kMDItemContentCreationDate;
com.apple.metadata:kMDItemContentCreationDate; The
creation date of an edited or optimized version of
the song or composition.; date/time
contentmodificationdate kMDItemContentModificationDate;
com.apple.metadata:kMDItemContentModificationDate;
The date and time that the contents of the file
were last modified.; date/time
contenttype kMDItemContentType;
com.apple.metadata:kMDItemContentType; The UTI
pedigree of a file.; string
contributors kMDItemContributors;
com.apple.metadata:kMDItemContributors; The
entities responsible for making contributions to
the content of the resource.; list of strings
copyright kMDItemCopyright;
com.apple.metadata:kMDItemCopyright; The copyright
owner of the file contents.; string
country kMDItemCountry; com.apple.metadata:kMDItemCountry;
The full, publishable name of the country or region
where the intellectual property of the item was
created, according to guidelines of the provider.;
string
coverage kMDItemCoverage;
com.apple.metadata:kMDItemCoverage; The extent or
scope of the content of the resource.; string
creator kMDItemCreator; com.apple.metadata:kMDItemCreator;
Application used to create the document content
(for example "Word", "Pages", and so on).; string
deliverytype kMDItemDeliveryType;
com.apple.metadata:kMDItemDeliveryType; The
delivery type. Values are "Fast start" or "RTSP".;
string
description kMDItemDescription;
com.apple.metadata:kMDItemDescription; A
description of the content of the resource. The
description may include an abstract, table of
contents, reference to a graphical representation
of content or a free-text account of the content.;
string
director kMDItemDirector;
com.apple.metadata:kMDItemDirector; Directory of
the movie.; string
displayname kMDItemDisplayName;
com.apple.metadata:kMDItemDisplayName; The
localized version of the file name.; string
downloadeddate kMDItemDownloadedDate;
com.apple.metadata:kMDItemDownloadedDate; Date the
item was downloaded.; list of date/time
duedate kMDItemDueDate; com.apple.metadata:kMDItemDueDate;
Date this item is due.; date/time
durationseconds kMDItemDurationSeconds;
com.apple.metadata:kMDItemDurationSeconds; The
duration, in seconds, of the content of file. A
value of 10. 5 represents media that is 10 and 1/2
seconds long.; number
exifgpsversion kMDItemEXIFGPSVersion;
com.apple.metadata:kMDItemEXIFGPSVersion; The
version of GPSInfoIFD in EXIF used to generate the
metadata.; string
exifversion kMDItemEXIFVersion;
com.apple.metadata:kMDItemEXIFVersion; The version
of the EXIF header used to generate the metadata.;
string
emailaddresses kMDItemEmailAddresses;
com.apple.metadata:kMDItemEmailAddresses; Email
addresses related to this item.; list of strings
encodingapplications kMDItemEncodingApplications;
com.apple.metadata:kMDItemEncodingApplications;
Application used to convert the original content
into it's current form. For example, a PDF file
might have an encoding application set to
"Distiller".; list of strings
exposuremode kMDItemExposureMode;
com.apple.metadata:kMDItemExposureMode; The
exposure mode used to acquire the document
contents.; number
exposureprogram kMDItemExposureProgram;
com.apple.metadata:kMDItemExposureProgram; The
class of the exposure program used by the camera to
set exposure when the image is taken. Possible
values include: Manual, Normal, and Aperture
priority.; string
exposuretimeseconds kMDItemExposureTimeSeconds;
com.apple.metadata:kMDItemExposureTimeSeconds; The
exposure time, in seconds, used to acquire the
document contents.; number
exposuretimestring kMDItemExposureTimeString;
com.apple.metadata:kMDItemExposureTimeString; The
time of the exposure.; string
fnumber kMDItemFNumber; com.apple.metadata:kMDItemFNumber;
The diameter of the diaphragm aperture in terms of
the effective focal length of the lens.; number
fscontentchangedate kMDItemFSContentChangeDate;
com.apple.metadata:kMDItemFSContentChangeDate; The
date the file contents last changed.; date/time
fscreationdate kMDItemFSCreationDate;
com.apple.metadata:kMDItemFSCreationDate; The date
and time that the file was created.; date/time
fshascustomicon kMDItemFSHasCustomIcon;
com.apple.metadata:kMDItemFSHasCustomIcon; Boolean
indicating if this file has a custom icon.; boolean
fsinvisible kMDItemFSInvisible;
com.apple.metadata:kMDItemFSInvisible; Indicates
whether the file is invisible.; boolean
fsisextensionhidden kMDItemFSIsExtensionHidden;
com.apple.metadata:kMDItemFSIsExtensionHidden;
Indicates whether the file extension of the file is
hidden.; boolean
fsisstationery kMDItemFSIsStationery;
com.apple.metadata:kMDItemFSIsStationery; Boolean
indicating if this file is stationery.; boolean
fslabel kMDItemFSLabel; com.apple.metadata:kMDItemFSLabel;
Index of the Finder label of the file. Possible
values are 0 through 7.; number
fsname kMDItemFSName; com.apple.metadata:kMDItemFSName;
The file name of the item.; string
fsnodecount kMDItemFSNodeCount;
com.apple.metadata:kMDItemFSNodeCount; Number of
files in a directory.; number
fsownergroupid kMDItemFSOwnerGroupID;
com.apple.metadata:kMDItemFSOwnerGroupID; The group
ID of the owner of the file.; number
fsowneruserid kMDItemFSOwnerUserID;
com.apple.metadata:kMDItemFSOwnerUserID; The user
ID of the owner of the file.; number
fssize kMDItemFSSize; com.apple.metadata:kMDItemFSSize;
The size, in bytes, of the file on disk.; number
findercomment kMDItemFinderComment;
com.apple.metadata:kMDItemFinderComment; Finder
comments for this file.; string
flashonoff kMDItemFlashOnOff;
com.apple.metadata:kMDItemFlashOnOff; Indicates if
a camera flash was used.; number
focallength kMDItemFocalLength;
com.apple.metadata:kMDItemFocalLength; The actual
focal length of the lens, in millimeters.; number
fonts kMDItemFonts; com.apple.metadata:kMDItemFonts;
Fonts used in this item. You should store the
font's full name, the postscript name, or the font
family name, based on the available information.;
list of strings
gpstrack kMDItemGPSTrack;
com.apple.metadata:kMDItemGPSTrack; The direction
of travel of the item, in degrees from true north.;
string
genre kMDItemGenre; com.apple.metadata:kMDItemGenre;
Genre of the movie.; string
hasalphachannel kMDItemHasAlphaChannel;
com.apple.metadata:kMDItemHasAlphaChannel;
Indicates if this image file has an alpha channel.;
boolean
headline kMDItemHeadline;
com.apple.metadata:kMDItemHeadline; A publishable
entry providing a synopsis of the contents of the
file. For example, "Apple Introduces the iPod
Photo".; string
isospeed kMDItemISOSpeed;
com.apple.metadata:kMDItemISOSpeed; The ISO speed
used to acquire the document contents.; number
identifier kMDItemIdentifier;
com.apple.metadata:kMDItemIdentifier; A formal
identifier used to reference the resource within a
given context.; string
imagedirection kMDItemImageDirection;
com.apple.metadata:kMDItemImageDirection; The
direction of the item's image, in degrees from true
north.; string
information kMDItemInformation;
com.apple.metadata:kMDItemInformation; Information
about the item.; string
instantmessageaddresses kMDItemInstantMessageAddresses;
com.apple.metadata:kMDItemInstantMessageAddresses;
Instant message addresses related to this item.;
list of strings
instructions kMDItemInstructions;
com.apple.metadata:kMDItemInstructions; Editorial
instructions concerning the use of the item, such
as embargoes and warnings. For example, "Second of
four stories".; string
isgeneralmidisequence kMDItemIsGeneralMIDISequence;
com.apple.metadata:kMDItemIsGeneralMIDISequence;
Indicates whether the MIDI sequence contained in
the file is setup for use with a General MIDI
device.; boolean
keysignature kMDItemKeySignature;
com.apple.metadata:kMDItemKeySignature; The key of
the music contained in the audio file. For example:
C, Dm, F#m, Bb.; string
keywords kMDItemKeywords;
com.apple.metadata:kMDItemKeywords; Keywords
associated with this file. For example, "Birthday",
"Important", etc.; list of strings
kind kMDItemKind; com.apple.metadata:kMDItemKind; A
description of the kind of item this file
represents.; string
languages kMDItemLanguages;
com.apple.metadata:kMDItemLanguages; Indicates the
languages of the intellectual content of the
resource. Recommended best practice for the values
of the Language element is defined by RFC 3066.;
list of strings
lastuseddate kMDItemLastUsedDate;
com.apple.metadata:kMDItemLastUsedDate; The date
and time that the file was last used. This value is
updated automatically by LaunchServices everytime a
file is opened by double clicking, or by asking
LaunchServices to open a file.; date/time
latitude kMDItemLatitude;
com.apple.metadata:kMDItemLatitude; The latitude of
the item in degrees north of the equator, expressed
using the WGS84 datum. Negative values lie south of
the equator.; string
layernames kMDItemLayerNames;
com.apple.metadata:kMDItemLayerNames; The names of
the layers in the file.; list of strings
longitude kMDItemLongitude;
com.apple.metadata:kMDItemLongitude; The longitude
of the item in degrees east of the prime meridian,
expressed using the WGS84 datum. Negative values
lie west of the prime meridian.; string
lyricist kMDItemLyricist;
com.apple.metadata:kMDItemLyricist; The lyricist,
or text writer, of the music contained in the audio
file.; string
maxaperture kMDItemMaxAperture;
com.apple.metadata:kMDItemMaxAperture; The smallest
f-number of the lens. Ordinarily it is given in the
range of 00. 00 to 99. 99.; number
mediatypes kMDItemMediaTypes;
com.apple.metadata:kMDItemMediaTypes; The media
types present in the content.; list of strings
meteringmode kMDItemMeteringMode;
com.apple.metadata:kMDItemMeteringMode; The
metering mode used to take the image.; string
musicalgenre kMDItemMusicalGenre;
com.apple.metadata:kMDItemMusicalGenre; The musical
genre of the song or composition contained in the
audio file. For example: Jazz, Pop, Rock,
Classical.; string
musicalinstrumentcategory kMDItemMusicalInstrumentCategory; com.apple.metadat
a:kMDItemMusicalInstrumentCategory; Specifies the
category of an instrument.; string
musicalinstrumentname kMDItemMusicalInstrumentName;
com.apple.metadata:kMDItemMusicalInstrumentName;
Specifies the name of instrument relative to the
instrument category.; string
namedlocation kMDItemNamedLocation;
com.apple.metadata:kMDItemNamedLocation; The name
of the location or point of interest associated
with the item. The name may be user provided.;
string
numberofpages kMDItemNumberOfPages;
com.apple.metadata:kMDItemNumberOfPages; Number of
pages in the document.; number
organizations kMDItemOrganizations;
com.apple.metadata:kMDItemOrganizations; The
company or organization that created the document.;
list of strings
orientation kMDItemOrientation;
com.apple.metadata:kMDItemOrientation; The
orientation of the document contents. Possible
values are 0 (landscape) and 1 (portrait).; number
originalformat kMDItemOriginalFormat;
com.apple.metadata:kMDItemOriginalFormat; Original
format of the movie.; string
originalsource kMDItemOriginalSource;
com.apple.metadata:kMDItemOriginalSource; Original
source of the movie.; string
pageheight kMDItemPageHeight;
com.apple.metadata:kMDItemPageHeight; Height of the
document page, in points (72 points per inch). For
PDF files this indicates the height of the first
page only.; number
pagewidth kMDItemPageWidth;
com.apple.metadata:kMDItemPageWidth; Width of the
document page, in points (72 points per inch). For
PDF files this indicates the width of the first
page only.; number
participants kMDItemParticipants;
com.apple.metadata:kMDItemParticipants; The list of
people who are visible in an image or movie or
written about in a document.; list of strings
path kMDItemPath; com.apple.metadata:kMDItemPath; The
complete path to the file.; string
performers kMDItemPerformers;
com.apple.metadata:kMDItemPerformers; Performers in
the movie.; list of strings
phonenumbers kMDItemPhoneNumbers;
com.apple.metadata:kMDItemPhoneNumbers; Phone
numbers related to this item.; list of strings
pixelcount kMDItemPixelCount;
com.apple.metadata:kMDItemPixelCount; The total
number of pixels in the contents. Same as
kMDItemPixelWidth x kMDItemPixelHeight.; number
pixelheight kMDItemPixelHeight;
com.apple.metadata:kMDItemPixelHeight; The height,
in pixels, of the contents. For example, the image
height or the video frame height.; number
pixelwidth kMDItemPixelWidth;
com.apple.metadata:kMDItemPixelWidth; The width, in
pixels, of the contents. For example, the image
width or the video frame width.; number
producer kMDItemProducer;
com.apple.metadata:kMDItemProducer; Producer of the
content.; string
profilename kMDItemProfileName;
com.apple.metadata:kMDItemProfileName; The name of
the color profile used by the document contents.;
string
projects kMDItemProjects;
com.apple.metadata:kMDItemProjects; The list of
projects that this file is part of. For example, if
you were working on a movie all of the files could
be marked as belonging to the project "My Movie".;
list of strings
publishers kMDItemPublishers;
com.apple.metadata:kMDItemPublishers; The entity
responsible for making the resource available. For
example, a person, an organization, or a service.
Typically, the name of a publisher should be used
to indicate the entity.; list of strings
recipientaddresses kMDItemRecipientAddresses;
com.apple.metadata:kMDItemRecipientAddresses; This
attribute indicates the recipient addresses of the
document.; list of strings
recipientemailaddresses kMDItemRecipientEmailAddresses;
com.apple.metadata:kMDItemRecipientEmailAddresses;
This attribute indicates the recipients email
addresses. (This is always the email address, and
not the human readable version).; list of strings
recipients kMDItemRecipients;
com.apple.metadata:kMDItemRecipients; Recipients of
this item.; list of strings
recordingdate kMDItemRecordingDate;
com.apple.metadata:kMDItemRecordingDate; The
recording date of the song or composition.;
date/time
recordingyear kMDItemRecordingYear;
com.apple.metadata:kMDItemRecordingYear; Indicates
the year the item was recorded. For example, 1964,
2003, etc.; number
redeyeonoff kMDItemRedEyeOnOff;
com.apple.metadata:kMDItemRedEyeOnOff; Indicates if
red-eye reduction was used to take the picture.;
boolean
resolutionheightdpi kMDItemResolutionHeightDPI;
com.apple.metadata:kMDItemResolutionHeightDPI;
Resolution height, in DPI, of this image.; number
resolutionwidthdpi kMDItemResolutionWidthDPI;
com.apple.metadata:kMDItemResolutionWidthDPI;
Resolution width, in DPI, of this image.; number
rights kMDItemRights; com.apple.metadata:kMDItemRights;
Provides a link to information about rights held in
and over the resource.; string
securitymethod kMDItemSecurityMethod;
com.apple.metadata:kMDItemSecurityMethod; The
security or encryption method used for the file.;
string
speed kMDItemSpeed; com.apple.metadata:kMDItemSpeed; The
speed of the item, in kilometers per hour.; string
starrating kMDItemStarRating;
com.apple.metadata:kMDItemStarRating; User rating
of this item. For example, the stars rating of an
iTunes track.; number
stateorprovince kMDItemStateOrProvince;
com.apple.metadata:kMDItemStateOrProvince;
Identifies the province or state of origin
according to guidelines established by the
provider. For example, "CA", "Ontario", or
"Sussex".; string
streamable kMDItemStreamable;
com.apple.metadata:kMDItemStreamable; Whether the
content is prepared for streaming.; boolean
subject kMDItemSubject; com.apple.metadata:kMDItemSubject;
Subject of the this item.; string
tempo kMDItemTempo; com.apple.metadata:kMDItemTempo; A
float value that specifies the beats per minute of
the music contained in the audio file.; number
textcontent kMDItemTextContent;
com.apple.metadata:kMDItemTextContent; Contains a
text representation of the content of the document.
Data in multiple fields should be combined using a
whitespace character as a separator.; string
theme kMDItemTheme; com.apple.metadata:kMDItemTheme;
Theme of the this item.; string
timesignature kMDItemTimeSignature;
com.apple.metadata:kMDItemTimeSignature; The time
signature of the musical composition contained in
the audio/MIDI file. For example: "4/4", "7/8".;
string
timestamp kMDItemTimestamp;
com.apple.metadata:kMDItemTimestamp; The timestamp
on the item. This generally is used to indicate the
time at which the event captured by the item took
place.; string
title kMDItemTitle; com.apple.metadata:kMDItemTitle; The
title of the file. For example, this could be the
title of a document, the name of a song, or the
subject of an email message.; string
totalbitrate kMDItemTotalBitRate;
com.apple.metadata:kMDItemTotalBitRate; The total
bit rate, audio and video combined, of the media.;
number
url kMDItemURL; com.apple.metadata:kMDItemURL; Url of
the item.; string
version kMDItemVersion; com.apple.metadata:kMDItemVersion;
The version number of this file.; string
videobitrate kMDItemVideoBitRate;
com.apple.metadata:kMDItemVideoBitRate; The video
bit rate.; number
wherefroms kMDItemWhereFroms;
com.apple.metadata:kMDItemWhereFroms; Describes
where the file was obtained from.; list of strings
whitebalance kMDItemWhiteBalance;
com.apple.metadata:kMDItemWhiteBalance; The white
balance setting used to acquire the document
contents. Possible values are 0 (auto white
balance) and 1 (manual).; number
```
<!-- [[[end]]] -->
## Notes on backup/restore
When run with `--backup`, osxmetadata backs up the metadata of each file in a file called `.osxmetadata.json`. A backup file is created in every directory that includes files being backup up. The format is plain JSON text with a record for each file that was backed up. If you delete a file then run the `--backup` again, the deleted file's record is not deleted from the `.osxmetadata.json` backup file. The backup file is kept in each directory/sub-directory and only the filename is used for `--restore` which means you can move/rename the directory (along with the `.osxmetadata.json` file) and the restore will still work correctly.
**Note**: Prior to version 0.99.38, the backup file was not well-formed JSON which meant that some apps/viewers could not process the JSON file. Version 0.99.38 fixes this and will silently update any `.osxmetadata.json` file encountered during `--backup` to be well-formed JSON but this breaks backwards compatibility with older versions of osxmetadata. If you use osxmetadata to sync data across multiple Macs, you must ensure all Macs are running the updated version. For additional details, see [issue #57](https://github.com/RhetTbull/osxmetadata/issues/57).
## Usage Notes
This will only work on file systems that support Mac OS X extended attributes.
## Related Projects
- [tag](https://github.com/jdberry/tag) A command line tool to manipulate tags on Mac OS X files, and to query for files with those tags.
- [osx-tags](https://github.com/scooby/osx-tags) Python module to manipulate Finder tags in OS X.
## Acknowledgements
This module was inspired by [osx-tags](https://github.com/scooby/osx-tags) by "Ben S / scooby". I leveraged osx-tags to bootstrap the design of this module. I wanted a more general OS X metadata library so I rolled my own. This module is published under the same MIT license as osx-tags.
## License
MIT License
Copyright (c) 2020 Rhet Turnbull
## Contributing
Contributions of all kinds are welcome. Please submit a pull request or open an issue.
## Contributors β¨
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<table>
<tbody>
<tr>
<td align="center"><a href="http://www.borja.glezseoane.es"><img src="https://avatars.githubusercontent.com/u/24481419?v=4?s=75" width="75px;" alt="Borja GonzΓ‘lez Seoane"/><br /><sub><b>Borja GonzΓ‘lez Seoane</b></sub></a><br /><a href="https://github.com/RhetTbull/osxmetadata/commits?author=bglezseoane" title="Code">π»</a></td>
<td align="center"><a href="https://github.com/porg"><img src="https://avatars.githubusercontent.com/u/737143?v=4?s=75" width="75px;" alt="porg"/><br /><sub><b>porg</b></sub></a><br /><a href="https://github.com/RhetTbull/osxmetadata/issues?q=author%3Aporg" title="Bug reports">π</a> <a href="#ideas-porg" title="Ideas, Planning, & Feedback">π€</a></td>
<td align="center"><a href="https://github.com/nk9"><img src="https://avatars.githubusercontent.com/u/3646730?v=4?s=75" width="75px;" alt="Nick Kocharhook"/><br /><sub><b>Nick Kocharhook</b></sub></a><br /><a href="https://github.com/RhetTbull/osxmetadata/issues?q=author%3Ank9" title="Bug reports">π</a></td>
<td align="center"><a href="https://jakewilliami.github.io/"><img src="https://avatars.githubusercontent.com/u/54291317?v=4?s=75" width="75px;" alt="Jake Ireland"/><br /><sub><b>Jake Ireland</b></sub></a><br /><a href="#ideas-jakewilliami" title="Ideas, Planning, & Feedback">π€</a></td>
<td align="center"><a href="https://github.com/luckman212"><img src="https://avatars.githubusercontent.com/u/1992842?v=4?s=75" width="75px;" alt="Luke Hamburg"/><br /><sub><b>Luke Hamburg</b></sub></a><br /><a href="https://github.com/RhetTbull/osxmetadata/issues?q=author%3Aluckman212" title="Bug reports">π</a> <a href="https://github.com/RhetTbull/osxmetadata/commits?author=luckman212" title="Code">π»</a></td>
</tr>
</tbody>
</table>
<!-- markdownlint-restore -->
<!-- prettier-ignore-end -->
<!-- ALL-CONTRIBUTORS-LIST:END -->
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
%prep
%autosetup -n osxmetadata-1.3.0
%build
%py3_build
%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
find usr/lib -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
find usr/lib64 -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
find usr/bin -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
find usr/sbin -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
find usr/share/man -type f -printf "\"/%h/%f.gz\"\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .
%files -n python3-osxmetadata -f filelist.lst
%dir %{python3_sitelib}/*
%files help -f doclist.lst
%{_docdir}/*
%changelog
* Thu Jun 08 2023 Python_Bot <Python_Bot@openeuler.org> - 1.3.0-1
- Package Spec generated
|