This repository has been archived by the owner on Feb 16, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
xattr.swift
74 lines (51 loc) · 1.89 KB
/
xattr.swift
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
import Foundation
struct Xattr {
/** Error type */
struct Error: Swift.Error {
let localizedDescription = String(utf8String: strerror(errno))
}
/**
Set extended attribute at path
- Parameters:
- name: Name of extended attribute
- data: Data associated with the attribute
- path: Path to file, directory, symlink etc
*/
static func set(named name: String, data: Data, atPath path: String) throws {
if setxattr(path, name, (data as NSData).bytes, data.count, 0, 0) == -1 { throw Error() }
}
/**
Remove extended attribute at path
- Parameters:
- name: Name of extended attribute
- path: Path to file, directory, symlink etc
*/
static func remove(named name: String, atPath path: String) throws {
if removexattr(path, name, 0) == -1 { throw Error() }
}
/**
Get data for extended attribute at path
- Parameters:
- name: Name of extended attribute
- path: Path to file, directory, symlink etc
*/
static func dataFor(named name: String, atPath path: String) throws -> Data {
let bufLength = getxattr(path, name, nil, 0, 0, 0)
guard bufLength != -1, let buf = malloc(bufLength), getxattr(path, name, buf, bufLength, 0, 0) != -1 else { throw Error() }
return Data(bytes: buf, count: bufLength)
}
/**
Get names of extended attributes at path
- Parameters:
- path: Path to file, directory, symlink etc
*/
static func names(atPath path: String) throws -> [String]? {
let bufLength = listxattr(path, nil, 0, 0)
guard bufLength != -1 else { throw Error() }
let buf = UnsafeMutablePointer<Int8>.allocate(capacity: bufLength)
guard listxattr(path, buf, bufLength, 0) != -1 else { throw Error() }
var names = NSString(bytes: buf, length: bufLength, encoding: String.Encoding.utf8.rawValue)?.components(separatedBy: "\0")
names?.removeLast()
return names
}
}