Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Side by Side Diff: sitescripts/web/sources.py

Issue 17817001: Simple CMS as Anwiki replacement (Closed)
Patch Set: Completed functionality Created Oct. 24, 2013, 9:32 p.m.
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 # coding: utf-8
2
3 # This file is part of the Adblock Plus web scripts,
4 # Copyright (C) 2006-2013 Eyeo GmbH
5 #
6 # Adblock Plus is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License version 3 as
8 # published by the Free Software Foundation.
9 #
10 # Adblock Plus is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>.
17
18 import sys, os, subprocess, zipfile, json, urlparse, codecs
19 from StringIO import StringIO
20 from ConfigParser import SafeConfigParser
21
22 class Source:
23 def resolve_link(self, url, locale):
24 parsed = urlparse.urlparse(url)
25 page = parsed.path
26 if parsed.scheme != "" or page.startswith("/") or page.startswith("."):
27 # Not a page link
28 return None, None
29
30 config = self.read_config()
31 default_locale = config.get("general", "defaultlocale")
32 default_page = config.get("general", "defaultpage")
33
34 checked_page = page
35 if config.has_option("locale_overrides", page):
36 checked_page = config.get("locale_overrides", page)
37
38 if self.has_localizable_file(default_locale, checked_page):
39 if not self.has_localizable_file(locale, checked_page):
40 locale = default_locale
41 elif self.has_locale(default_locale, checked_page):
42 if not self.has_locale(locale, checked_page):
43 locale = default_locale
44 else:
45 print >>sys.stderr, "Warning: Link to %s cannot be resolved" % page
46
47 if page == default_page:
48 page = ""
49
50 path = "/%s/%s" % (locale, page)
51 return locale, urlparse.urlunparse(list(parsed[0:2]) + [path] + list(parsed[ 3:]))
Sebastian Noack 2013/10/29 11:04:17 If you just wrap path in to a tuple instead of a l
52
53 def read_config(self):
54 configdata = self.read_file("settings.ini")
55 config = SafeConfigParser()
56 config.readfp(StringIO(configdata))
57 return config
58
59 #
60 # Page helpers
61 #
62
63 @staticmethod
64 def page_filename(page, format):
65 return "pages/%s.%s" % (page, format)
66
67 def list_pages(self):
68 for filename in self.list_files("pages"):
69 root, ext = os.path.splitext(filename)
70 format = ext[1:]
71 yield root, format
72
73 def has_page(self, page, format):
74 return self.has_file(self.page_filename(page, format))
75
76 def read_page(self, page, format):
77 return self.read_file(self.page_filename(page, format))
78
79 #
80 # Localizable files helpers
81 #
82
83 @staticmethod
84 def localizable_file_filename(locale, filename):
85 return "locales/%s/%s" % (locale, filename)
86
87 def list_localizable_files(self):
88 default_locale = self.read_config().get("general", "defaultlocale")
89 return filter(
90 lambda f: os.path.splitext(f)[1] != ".json",
91 self.list_files("locales/%s" % default_locale)
92 )
93
94 def has_localizable_file(self, locale, filename):
95 return self.has_file(self.localizable_file_filename(locale, filename))
96
97 def read_localizable_file(self, locale, filename):
98 return self.read_file(self.localizable_file_filename(locale, filename), bina ry=True)
99
100 #
101 # Static file helpers
102 #
103
104 @staticmethod
105 def static_filename(filename):
106 return "static/%s" % filename
107
108 def list_static(self):
109 return self.list_files("static")
110
111 def has_static(self, filename):
112 return self.has_file(self.static_filename(filename))
113
114 def read_static(self, filename):
115 return self.read_file(self.static_filename(filename), binary=True)
116
117 #
118 # Locale helpers
119 #
120
121 @staticmethod
122 def locale_filename(locale, page):
123 return "locales/%s/%s.json" % (locale, page)
Sebastian Noack 2013/10/29 11:04:17 Why don't you call localizable_file_filename() and
124
125 def list_locales(self):
126 result = set()
127 for filename in self.list_files("locales"):
128 if "/" in filename:
129 locale, path = filename.split("/", 1)
130 result.add(locale)
131 return result
132
133 def has_locale(self, locale, page):
134 config = self.read_config()
135 if config.has_option("locale_overrides", page):
136 page = config.get("locale_overrides", page)
137 return self.has_file(self.locale_filename(locale, page))
138
139 def read_locale(self, locale, page):
140 default_locale = self.read_config().get("general", "defaultlocale")
141 if locale == default_locale:
142 result = {}
143 else:
144 result = self.read_locale(default_locale, page)
145
146 if self.has_locale(locale, page):
147 filedata = self.read_file(self.locale_filename(locale, page))
148 localedata = json.loads(filedata)
149 for key, value in localedata.iteritems():
150 result[key] = value["message"]
151
152 return result
153
154 #
155 # Template helpers
156 #
157
158 @staticmethod
159 def template_filename(template):
160 return "templates/%s.tmpl" % template
161
162 def read_template(self, template):
163 return self.read_file(self.template_filename(template))
164
165 #
166 # Include helpers
167 #
168
169 @staticmethod
170 def include_filename(include, format):
171 return "includes/%s.%s" % (include, format)
172
173 def has_include(self, include, format):
174 return self.has_file(self.include_filename(include, format))
175
176 def read_include(self, include, format):
177 return self.read_file(self.include_filename(include, format))
178
179 class MercurialSource(Source):
180 def __init__(self, repo):
181 command = ["hg", "-R", repo, "archive", "-r", "default",
182 "-t", "uzip", "-p", ".", "-"]
183 data, _ = subprocess.Popen(command, stdout=subprocess.PIPE).communicate()
Sebastian Noack 2013/10/29 11:04:17 Have a look at subprocess.check_output(), which is
184 self._archive = zipfile.ZipFile(StringIO(data), mode="r")
185
186 command = ["hg", "-R", repo, "id", "-n", "-r", "default"]
187 self.version, _ = subprocess.Popen(command, stdout=subprocess.PIPE).communic ate()
188 self.version = self.version.strip()
189
190 def __enter__(self):
191 return self
192
193 def __exit__(self, type, value, traceback):
194 self.close()
195 return False
196
197 def close(self):
198 self._archive.close()
199
200 def has_file(self, filename):
201 try:
202 self._archive.getinfo("./%s" % filename)
203 except KeyError:
204 return False
205 return True
206
207 def read_file(self, filename, binary=False):
208 result = self._archive.read("./%s" % filename)
209 if not binary:
210 result = result.decode("utf-8")
211 return result
212
213 def list_files(self, subdir):
214 prefix = "./" + subdir + "/"
Sebastian Noack 2013/10/29 11:04:17 You should use format strings when concatenating m
215 for filename in self._archive.namelist():
216 if filename.startswith(prefix):
217 yield filename[len(prefix):]
218
219 class FileSource(Source):
220 def __init__(self, dir):
221 self._dir = dir
222
223 def __enter__(self):
224 return self
225
226 def __exit__(self, type, value, traceback):
227 return False
228
229 def close(self):
230 pass
231
232 def get_path(self, filename):
233 return os.path.join(self._dir, *filename.split("/"))
234
235 def has_file(self, filename):
236 return os.path.isfile(self.get_path(filename))
237
238 def read_file(self, filename, binary=False):
239 encoding = None if binary else "utf-8"
240 with codecs.open(self.get_path(filename), "rb", encoding=encoding) as handle :
241 return handle.read()
242
243 def list_files(self, subdir):
244 result = []
245 def do_list(dir, relpath):
246 files = os.listdir(dir)
247 for filename in files:
248 path = os.path.join(dir, filename)
249 if os.path.isfile(path):
250 result.append(relpath + filename)
251 elif os.path.isdir(path):
252 do_list(path, relpath + filename + "/")
253 do_list(self.get_path(subdir), "")
254 return result
OLDNEW

Powered by Google App Engine
This is Rietveld