Add iptables systemd units
[shutils.git] / bib2html.py
1 #!/usr/bin/env python2
2 """Creates a webpage with all entries of a .bib file"""
3
4 __version__ = "1.0"
5
6 __author__ = "Stefan Huber"
7 __email__ = "shuber@sthu.org"
8 __copyright__ = "Copyright 2013, Stefan Huber"
9
10 __license__ = "MIT"
11
12 # Permission is hereby granted, free of charge, to any person
13 # obtaining a copy of this software and associated documentation
14 # files (the "Software"), to deal in the Software without
15 # restriction, including without limitation the rights to use,
16 # copy, modify, merge, publish, distribute, sublicense, and/or sell
17 # copies of the Software, and to permit persons to whom the
18 # Software is furnished to do so, subject to the following
19 # conditions:
20 #
21 # The above copyright notice and this permission notice shall be
22 # included in all copies or substantial portions of the Software.
23 #
24 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
26 # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
28 # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
29 # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
30 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
31 # OTHER DEALINGS IN THE SOFTWARE.
32
33
34 import os, sys, getopt
35
36
37 def format_latex(text):
38 return text.replace('{', '').replace('}', '').replace('\\', '')
39
40 def format_field_span(type, value):
41 return "<span class=bibentry_" + type + ">" + format_latex(value) + "</span>"
42
43 def format_field(bibentry, field, pre='', post=''):
44 if field in bibentry.fields:
45 return format_field_span(field, pre + bibentry.fields[field] + post)
46 return ""
47
48 def format_author(a):
49 return ' '.join(' '.join(p) for p in (a.first(), a.middle(), a.prelast(), a.last(), a.lineage()) if p)
50
51 def format_authors(entry):
52 return ", ".join([format_author(a) for a in entry.persons['author']])
53
54
55 def format_details_article(entry):
56
57 where = format_field(entry, 'journal')
58
59 line = []
60 line.append(format_field(entry, 'pages', pre='pp. '))
61 line.append(format_field(entry, 'volume', pre='vol. ') + \
62 format_field(entry, 'number', pre='(', post=')'))
63 line.append(format_field(entry, 'month', post=' ') + \
64 format_field(entry, 'year'))
65 line = filter(lambda l: l != "", line)
66
67 return [where, ", ".join(line)]
68
69 def format_details_inproceedings(entry):
70 where = format_field(entry, 'booktitle')
71
72 line = []
73 line.append(format_field(entry, 'pages', pre='pp. '))
74 line.append(format_field(entry, 'address'))
75 line.append(format_field(entry, 'month', post=' ') + \
76 format_field(entry, 'year'))
77 line = filter(lambda l: l != "", line)
78 return [where, ", ".join(line)]
79
80 def format_details_thesis(entry):
81 line = []
82 line.append(format_field(entry, 'school'))
83 line.append(format_field(entry, 'month', post=' ') + \
84 format_field(entry, 'year'))
85 line = filter(lambda l: l != "", line)
86 return [", ".join(line)]
87
88 def format_details_book(entry):
89 line = []
90 line.append(format_field(entry, 'publisher'))
91 line.append(format_field(entry, 'isbn', pre='ISBN '))
92 line.append(format_field(entry, 'month', post=' ') + \
93 format_field(entry, 'year'))
94 line = filter(lambda l: l != "", line)
95 return [", ".join(line)]
96
97 def format_links(entry):
98 webpdf = format_field(entry, 'webpdf', pre='<a href="', post='">[PDF]</a>')
99 weblink = format_field(entry, 'weblink', pre='<a href="', post='">[link]</a>')
100 webslides = format_field(entry, 'webslides', pre='<a href="', post='">[slides]</a>')
101 weberrata = format_field(entry, 'weberrata', pre='<a href="',
102 post='">[errata]</a>')
103 return " ".join([webpdf, weblink, webslides, weberrata])
104
105 def format_entry(entry):
106 lines = []
107 lines.append(format_field(entry, 'title', pre="<b>", post="</b>"))
108 lines.append(format_field_span('author', format_authors(entry)))
109
110 if entry.type=='article':
111 lines.extend(format_details_article(entry))
112 elif entry.type=='inproceedings':
113 lines.extend(format_details_inproceedings(entry))
114 elif entry.type=='book':
115 lines.extend(format_details_book(entry))
116 elif entry.type in ['mastersthesis', 'phdthesis']:
117 lines.extend(format_details_thesis(entry))
118 else:
119 lines.append("Unknown type <b>'" + entry.type + "'</b>")
120
121 lines.append(format_field(entry, 'webnote'))
122 lines.append(format_links(entry))
123
124 lines = filter(lambda l: l != "", lines)
125 return "<br/>\n".join(lines)
126
127
128 def entryCompareDate(p1, p2):
129 k1, e1 = p1
130 k2, e2 = p2
131
132
133 def toStr(e):
134 month = { 'jan' : '01', 'feb' : '02', 'mar' : '03', \
135 'apr' : '04', 'may' : '05', 'jun' : '06', \
136 'jul' : '07', 'aug' : '08', 'sep' : '09', \
137 'oct' : '10', 'nov' : '11', 'dec' : '12'}
138 return e.fields['year'] + "-" + month[e.fields['month'].lower()[0:3]]
139
140 return cmp(toStr(e1), toStr(e2))
141
142
143 def usage():
144 """Print usage text of this program"""
145
146 print("""Usage:
147 {0} -i FILE
148 {0} -h
149
150 OPTIONS:
151 -h print this text
152 -i .bib file
153 """.format(sys.argv[0]))
154
155 if __name__ == "__main__":
156
157 bibfile = None
158
159 try:
160 opts, args = getopt.getopt(sys.argv[1:], "hi:")
161
162 for opt, arg in opts:
163 if opt == "-h":
164 usage()
165 sys.exit(os.EX_OK)
166 elif opt == "-i":
167 bibfile = arg
168 else:
169 print("Unknown option '", opt, "'.")
170
171 except getopt.GetoptError as e:
172 print("Error parsing arguments:", e)
173 usage()
174
175 if bibfile == None:
176 print("You need to specify a bibfile")
177 usage()
178 sys.exit(os.EX_USAGE)
179
180
181 from pybtex.database.input import bibtex
182 parser = bibtex.Parser()
183
184 from pybtex.style.formatting.unsrt import Style
185
186 bib_data = parser.parse_file(bibfile)
187 entries = bib_data.entries
188
189 years = list(set([ b.fields['year'] for b in entries.values() ]))
190 years.sort(reverse=True)
191
192 for year in years:
193
194 print("<h2>" + year + "</h2>")
195
196 iteritems = list(entries.iteritems())
197 iteritems.sort(cmp=entryCompareDate, reverse=True)
198 for key, entry in iteritems:
199
200 if entry.fields['year'] != year:
201 continue
202
203 print("<div class=bibentry>")
204 print("<a class=bibentry_key id=" + key + ">[" + key + "]</a><br/>")
205
206 print(format_entry(entry).encode('utf8'))
207
208 print("</div>\n")
209