Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(150)

Side by Side Diff: chrome/common/extensions/docs/server2/samples_data_source.py

Issue 10804036: Extensions Docs Server: Internationalized samples (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: handlebar Created 8 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 # Copyright (c) 2012 The Chromium Authors. All rights reserved. 1 # Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be 2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file. 3 # found in the LICENSE file.
4 4
5 import json 5 import json
6 import logging
6 import re 7 import re
7 8
8 class SamplesDataSource(object): 9 class SamplesDataSource(object):
9 """Constructs a list of samples and their respective files and api calls. 10 """Constructs a list of samples and their respective files and api calls.
10 """ 11 """
11 def __init__(self, fetcher, cache_builder, samples_path): 12
12 self._fetcher = fetcher 13 class Factory(object):
13 self._cache = cache_builder.build(self._MakeSamplesList) 14 """A factory to create SamplesDataSource instances bound to individual
15 Requests.
16 """
17 def __init__(self, file_system, cache_builder, samples_path):
18 self._file_system = file_system
19 self._cache = cache_builder.build(self._MakeSamplesList)
20 self._samples_path = samples_path
21
22 def Create(self, request):
23 """Returns a new SamplesDataSource bound to |request|.
24 """
25 return SamplesDataSource(self._cache,
26 self._samples_path,
27 request)
28
29 def _GetApiItems(self, js_file):
30 return set(re.findall('(chrome\.[a-zA-Z0-9\.]+)', js_file))
31
32 def _MakeApiLink(self, prefix, item):
33 api, name = item.replace('chrome.', '').split('.', 1)
34 return api + '.html#' + prefix + '-' + name
35
36 def _GetDataFromManifest(self, path):
37 manifest = self._file_system.ReadSingle(path + '/manifest.json')
38 manifest_json = json.loads(manifest)
39 l10n_data = {
40 'name': manifest_json.get('name', ''),
41 'description': manifest_json.get('description', ''),
42 'default_locale': manifest_json.get('default_locale', None),
43 'locales': {}
44 }
45 if not l10n_data['default_locale']:
46 return l10n_data
47 locales_path = path + '/_locales/'
48 locales_dir = self._file_system.ReadSingle(locales_path)
49 if locales_dir:
50 locales_files = self._file_system.Read(
51 [locales_path + f + 'messages.json' for f in locales_dir]).Get()
52 locales_json = [(path, json.loads(unicode(contents, 'latin-1')))
53 for path, contents in locales_files.iteritems()]
54 for path, json_ in locales_json:
55 l10n_data['locales'][path[len(locales_path):].split('/')[0]] = json_
56 return l10n_data
57
58 def _MakeSamplesList(self, files):
59 samples_list = []
60 for filename in sorted(files):
61 if filename.rsplit('/')[-1] != 'manifest.json':
62 continue
63 # This is a little hacky, but it makes a sample page.
64 sample_path = filename.rsplit('/', 1)[-2]
65 sample_files = [path for path in files
66 if path.startswith(sample_path + '/')]
67 js_files = [path for path in sample_files if path.endswith('.js')]
68 js_contents = self._file_system.Read(js_files).Get()
69 api_items = set()
70 for js in js_contents.values():
71 api_items.update(self._GetApiItems(js))
72
73 api_calls = []
74 for item in api_items:
75 if len(item.split('.')) < 3:
76 continue
77 if item.endswith('.addListener'):
78 item = item.replace('.addListener', '')
79 api_calls.append({
80 'name': item,
81 'link': self._MakeApiLink('event', item)
82 })
83 else:
84 api_calls.append({
85 'name': item,
86 'link': self._MakeApiLink('method', item)
87 })
88 l10n_data = self._GetDataFromManifest(sample_path)
89 l10n_data.update({
90 'path': sample_path.split('/', 1)[1],
91 'files': [f.replace(sample_path + '/', '') for f in sample_files],
92 'api_calls': api_calls
93 })
94 samples_list.append(l10n_data)
95
96 return samples_list
97
98 def __init__(self, cache, samples_path, request):
99 self._cache = cache
14 self._samples_path = samples_path 100 self._samples_path = samples_path
101 self._request = request
15 102
16 def _GetApiItems(self, js_file): 103 def _GetAcceptedLanguages(self):
17 return set(re.findall('(chrome\.[a-zA-Z0-9\.]+)', js_file)) 104 accept_language = self._request.headers.get('Accept-Language', None)
18 105 if accept_language is None:
19 def _MakeApiLink(self, prefix, item): 106 return []
20 api, name = item.replace('chrome.', '').split('.', 1) 107 return [lang_with_q.split(';')[0].strip()
21 return api + '.html#' + prefix + '-' + name 108 for lang_with_q in accept_language.split(',')]
22
23 def _GetDataFromManifest(self, path):
24 manifest_path = path + '/manifest.json'
25 manifest = self._fetcher.Read([manifest_path]).Get()[manifest_path]
26 manifest_json = json.loads(manifest)
27 return (manifest_json.get('name'), manifest_json.get('description'))
28
29 def _MakeSamplesList(self, files):
30 samples_list = []
31 for filename in sorted(files):
32 if filename.rsplit('/')[-1] != 'manifest.json':
33 continue
34 # This is a little hacky, but it makes a sample page.
35 sample_path = filename.rsplit('/', 1)[-2]
36 sample_files = filter(lambda x: x.startswith(sample_path + '/'), files)
37 js_files = filter(lambda x: x.endswith('.js'), sample_files)
38 js_contents = self._fetcher.Read(js_files).Get()
39 api_items = set()
40 for js in js_contents.values():
41 api_items.update(self._GetApiItems(js))
42
43 api_calls = []
44 for item in api_items:
45 if len(item.split('.')) < 3:
46 continue
47 if item.endswith('.addListener'):
48 item = item.replace('.addListener', '')
49 api_calls.append({
50 'name': item,
51 'link': self._MakeApiLink('event', item)
52 })
53 else:
54 api_calls.append({
55 'name': item,
56 'link': self._MakeApiLink('method', item)
57 })
58 name, description = self._GetDataFromManifest(sample_path)
59 samples_list.append({
60 'name': name,
61 'description': description,
62 'path': sample_path.split('/', 1)[1],
63 'files': [f.replace(sample_path + '/', '') for f in sample_files],
64 'api_calls': api_calls
65 })
66 return samples_list
67 109
68 def __getitem__(self, key): 110 def __getitem__(self, key):
69 return self.get(key) 111 return self.get(key)
70 112
71 def get(self, key): 113 def get(self, key):
72 return self._cache.GetFromFileListing(self._samples_path + '/') 114 samples_list = self._cache.GetFromFileListing(self._samples_path + '/')
115 return_list = []
116 for dict_ in samples_list:
117 # Copy the sample dict so we don't change the dict in the cache.
not at google - send to devlin 2012/07/24 01:23:31 comment needs to be moved...
cduvall 2012/07/24 21:22:46 Done.
118 name = dict_['name']
119 description = dict_['description']
120 if name.startswith('__MSG_') or description.startswith('__MSG_'):
121 try:
122 sample_data = dict_.copy()
123 name_key = name[len('__MSG_'):-len('__')]
124 description_key = description[len('__MSG_'):-len('__')]
125 locale = sample_data['default_locale']
126 logging.info(self._GetAcceptedLanguages())
not at google - send to devlin 2012/07/24 01:23:31 remove
cduvall 2012/07/24 21:22:46 Done.
127 for lang in self._GetAcceptedLanguages():
128 if lang in sample_data['locales']:
129 locale = lang
130 break
131 locale_data = sample_data['locales'][locale]
132 sample_data['name'] = locale_data[name_key]['message']
133 sample_data['description'] = locale_data[description_key]['message']
134 except Exception as e:
135 logging.info(e)
136 # Revert the sample to the original dict.
not at google - send to devlin 2012/07/24 01:23:31 Pretty heavy-handed way to do this :\ oh well. So
cduvall 2012/07/24 21:22:46 Done.
137 sample_data = dict_
138 return_list.append(sample_data)
139 else:
140 return_list.append(dict_)
141 return return_list
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698