-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
wherefrom
executable file
·77 lines (61 loc) · 2.23 KB
/
wherefrom
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
#!/usr/bin/env python
from typing import Final, Iterator, Sequence, cast
import argparse
import platform
import plistlib
import re
import subprocess as sp
import sys
import click
KEY_ORIGIN_URL: Final[str] = 'user.xdg.origin.url'
KEY_WHERE_FROMS: Final[str] = 'com.apple.metadata:kMDItemWhereFroms'
def hexstr2bytes(s: str) -> bytes:
def chunks(seq: str, n: int) -> Iterator[str]:
for i in range(0, len(seq), n):
yield seq[i:i + n]
def hexstr2bytes_generator(s: str) -> Iterator[int]:
for hex_num in chunks(s, 2):
yield int(hex_num, 16)
return bytes(hexstr2bytes_generator(s))
def xattr_mac(key: str, filename: str) -> str:
return re.sub(
r'\s+', '',
sp.run(('xattr', '-p', key, filename), text=True, stdout=sp.PIPE, check=True).stdout)
def xattr_linux(key: str, filename: str) -> str | None:
return (sp.run(('getfattr', '-n', key, '--only-values', filename),
text=True,
check=True,
stderr=sp.DEVNULL,
stdout=sp.PIPE).stdout.strip() or None)
class Namespace(argparse.Namespace):
files: Sequence[str]
webpage: bool
@click.command('Determine where downloaded files came from.')
@click.argument('files',
metavar='FILE',
nargs=-1,
type=click.Path(exists=True, dir_okay=False, readable=True))
@click.option('-w', '--webpage', help='Print the webpage URL.')
def main(webpage: bool, files: list[str]) -> None:
has_multiple = len(files) > 1
index = 1 if webpage else 0
failed = False
for arg in files:
try:
if platform.uname().system == 'Linux':
val = xattr_linux(KEY_ORIGIN_URL, arg)
else:
val = cast(Sequence[str],
plistlib.loads(hexstr2bytes(xattr_mac(KEY_WHERE_FROMS, arg))))[index]
if has_multiple:
sys.stdout.write(f'{arg}: ')
sys.stdout.write(f'{val}\n')
except Exception:
if has_multiple:
click.echo(f'{arg}: unknown')
else:
failed = True
if not has_multiple and failed:
raise click.Abort()
if __name__ == '__main__':
sys.exit(main())