This repository has been archived by the owner on Jan 3, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
add_pressreview.py
executable file
·129 lines (106 loc) · 3.63 KB
/
add_pressreview.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
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
#!/usr/bin/env python3
import argparse
import io
import os
import re
import sys
import unicodedata
import urllib.error
import urllib.request
class PressReview:
"""
Model for a press review entry.
"""
_punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+')
def __init__(self, date, publisher, title, url):
self.date = date
self.publisher = publisher
self.title = title
self.url = url
self.lang = 'de'
@property
def slug(self):
result = []
for word in self._punct_re.split(self.publisher.lower()):
word = unicodedata.normalize('NFKD', word)
if word:
result.append(word)
slug = '%s_%s' % (self.date, '-'.join(result))
return slug.encode('ascii', 'ignore').decode('ascii')
@property
def filename(self):
return '%s.md' % self.slug
def get_text(self):
text = io.StringIO()
text.write('Title: %s\n' % self.title)
text.write('Slug: %s\n' % self.slug)
text.write('Date: %s\n' % self.date)
text.write('Lang: %s\n' % self.lang)
text.write('Publisher: %s\n' % self.publisher)
text.write('Ext_url: %s' % self.url)
return text.getvalue()
def get_parser():
"""
Build an argument parser.
"""
parser = argparse.ArgumentParser(description='Add a new press review entry.')
parser.add_argument('date', help='The publication date (YYYY-MM-DD)')
parser.add_argument('publisher', help='The publisher, e.g. "20 Minuten" or "NZZ"')
parser.add_argument('title', help='The publication title')
parser.add_argument('url', help='The URL')
parser.add_argument('-d', '--dry-run', action='store_true', default=False,
help='Only print press review entry, don\'t save it')
parser.add_argument('-f', '--force', action='store_true', default=False,
help='Skip validation')
return parser
class Validator:
"""
A class to validate the arguments.
"""
def __init__(self, args):
self.args = args
def _validate_date(self):
year_re = r'(19|20)\d\d'
month_re = r'(0[1-9]|1[012])'
day_re = r'(0[1-9]|[12][0-9]|3[01])'
if not re.match('^%s-%s-%s$' % (year_re, month_re, day_re), self.args.date):
print('Invalid date: %s' % self.args.date)
print('Date must be in the YYYY-MM-DD format.')
sys.exit(1)
def _validate_url(self):
try:
urllib.request.urlopen(self.args.url)
except urllib.error.URLError as e:
print('Invalid or dead URL: %s' % self.args.url)
print(str(e))
sys.exit(1)
def validate(self):
self._validate_date()
self._validate_url()
if __name__ == '__main__':
# Parse arguments
parser = get_parser()
args = parser.parse_args()
# Validate arguments
if not args.force:
v = Validator(args)
v.validate()
# Create press review entry
pr = PressReview(args.date, args.publisher, args.title, args.url)
text = pr.get_text()
# Dry run
if args.dry_run:
print(text)
sys.exit(0)
# Calculate target filepath
module_path = os.path.dirname(os.path.abspath(__file__))
target_dir = os.path.join(module_path, 'content/de/pressreview/')
target_file = os.path.join(target_dir, pr.filename)
print('Writing %s...' % target_file)
# Verify that file does not yet exist
if os.path.isfile(target_file):
print('Target file already exists! Aborting.')
sys.exit(1)
# Write file
with open(target_file, 'w', encoding='utf-8') as f:
f.write(text)