forked from felixonmars/dnsmasq-china-list
-
Notifications
You must be signed in to change notification settings - Fork 0
/
updater.py
executable file
·71 lines (60 loc) · 2.02 KB
/
updater.py
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
#!/usr/bin/env python
from __future__ import unicode_literals
from argparse import ArgumentParser
import sys
if __name__ == "__main__":
parser = ArgumentParser(description="dnsmasq-china-list updater")
parser.add_argument(
'-a', '--add',
metavar="DOMAIN",
nargs="+",
help='Add one or more new domain(s) (implies -s)',
)
parser.add_argument(
'-d', '--delete',
metavar="DOMAIN",
nargs="+",
help='Remove one or more old domain(s) (implies -s)',
)
parser.add_argument(
'-s', '--sort',
action='store_true',
default=True,
help='Sort the list (default action)',
)
parser.add_argument(
'-f', '--file',
nargs=1,
default=["accelerated-domains.china.conf"],
help="Specify the file to update (accelerated-domains.china.conf by default)",
)
options = parser.parse_args()
with open(options.file[0]) as f:
lines = list(f)
changed = False
if options.add:
options.sort = True
for domain in options.add:
new_line = "server=/%s/114.114.114.114\n" % domain
if new_line in lines:
print("Domain already exists: " + domain)
else:
print("New domain added: " + domain)
lines.append(new_line)
changed = True
if options.delete:
options.sort = True
for domain in options.delete:
target_line = "server=/%s/114.114.114.114\n" % domain
if target_line not in lines:
print("Failed to remove domain " + domain + ": not found.")
else:
print("Domain removed: " + domain)
lines.remove(target_line)
changed = True
if (options.add or options.delete) and not changed:
sys.exit(1)
if options.sort:
lines.sort(key=lambda x: x.lstrip("#"))
with open(options.file[0], "w") as f:
f.write(''.join(filter(lambda line: line.strip(), lines)))