source: trunk/tests/extractTranslations.py @ 1335

Revision 1335, 11.7 KB checked in by pjotr, 13 years ago (diff)

Well, deleted my own code

Line 
1# Copyright 2006 by the LeMill Team (see AUTHORS)
2#
3# This file is part of LeMill.
4#
5# LeMill is free software; you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation; either version 2 of the License, or
8# (at your option) any later version.
9#
10# LeMill 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 LeMill; if not, write to the Free Software
17# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
18
19import os, sys, re
20if __name__ == '__main__':
21    execfile(os.path.join(sys.path[0], 'framework.py'))
22
23from Testing import ZopeTestCase
24from Testing.ZopeTestCase.functional import Functional
25from LeMillTestCase import LeMillTestCase
26
27from Products.CMFCore.utils import getToolByName
28from Products.DCWorkflow import States, Transitions
29from Products.Archetypes.Schema import getSchemata
30from Products.Archetypes.Field import ReferenceField
31from Products.Archetypes.utils import DisplayList
32from Products.CMFDynamicViewFTI.interfaces import IDynamicViewTypeInformation
33try:
34    from Products.i18ndude import catalog
35    from Products.i18ndude.catalog import MAX_OCCUR
36except ImportError:
37    from i18ndude import catalog
38    from i18ndude.catalog import MAX_OCCUR
39
40class TranslationExtractor(LeMillTestCase):
41
42    def afterSetUp(self):
43        #self.addProduct('PloneLanguageTool')
44        #self.addProduct('LinguaPlone')
45        self.action_tool = self.portal.portal_actions
46        self.wf_tool = self.portal.portal_workflow
47        self.types_tool = self.portal.portal_types
48        self.at_tool = self.portal.archetype_tool
49        self.atct_tool = self.portal.portal_atct
50        self.ai_tool = self.portal.portal_actionicons
51        self.cp_tool = self.portal.portal_controlpanel
52
53    def testI18Ngenerator(self):
54        '''Runs the i18ngenerator'''
55
56        ctl = {}
57        ctl['lemill'] = catalog.MessageCatalog(domain='lemill')
58
59        # global actions
60        for provider in self.action_tool.listActionProviders():
61            provider_tool = getToolByName(self.portal, provider, None)
62            for action in provider_tool.listActions():
63                title = norm(action.title)
64                if action.visible:
65                    ctl['lemill'].add(title, msgstr=title, references=['action defined in %s' % provider])
66
67        # description of action icons
68        for icon in self.ai_tool.listActionIcons():
69            title= icon.getTitle()
70            ctl['lemill'].add(title, msgstr=title, references=['action_icon id %s - category %s' % (icon.getIconURL(), icon.getCategory())])
71
72
73        # workflow states and worflow transitions
74        for workflow in self.wf_tool.listWorkflows():
75            wf = self.wf_tool.getWorkflowById(workflow)
76            for obj in wf.objectValues():
77                if isinstance(obj, States.States):
78                    for state in obj.objectValues():
79                        ctl['lemill'].add(state.getId(), msgstr=state.getId(), references=['workflow state defined in %s - title %s' % (workflow, state.title)])
80                        ctl['lemill'].add(state.title, msgstr=state.title, references=['workflow state defined in %s - id %s' % (workflow, state.getId())])
81                elif isinstance(obj, Transitions.Transitions):
82                    for transition in obj.objectValues():
83                        ctl['lemill'].add(transition.getId(), msgstr=transition.getId(), references=['workflow transition defined in %s - title %s new state %s' % (workflow, transition.title, transition.new_state_id)])
84                        ctl['lemill'].add(transition.title, msgstr=transition.title, references=['workflow transition defined in %s - id %s new state %s' % (workflow, transition.getId(), transition.new_state_id)])
85                        ctl['lemill'].add(transition.actbox_name, msgstr=transition.actbox_name, references=['workflow action defined in %s - title %s new state %s' % (workflow, transition.title, transition.new_state_id)])
86
87
88        # portal types and types actions
89        types = [t for t in self.types_tool.listContentTypes() if not t.startswith('CMF ')] # filter out CMF types
90
91        for type in types:
92            typeObj = self.types_tool.getTypeInfo(type)
93
94            methods = []
95            try:
96                methods = typeObj.view_methods
97            except AttributeError:
98                # this type doesn't support the DynamicViewFTI
99                pass
100
101            for method in methods:
102                mid = getattr(typeObj, method, None)
103                title = mid.aq_inner.aq_explicit.title_or_id()
104                if type.endswith('Folder') or type == 'Topic': # XXX Need a better way to filter out unused views
105                    ctl['lemill'].add(title, msgstr=title, references=['dynamic view name template %s on type %s' % (method, type)])
106
107            title = norm(typeObj.Title())
108            desc = norm(typeObj.Description())
109            #ctl['lemill'].add(title, msgstr=title, references=['portal type title of type with description %s' % desc])
110            ctl['lemill'].add(desc, msgstr=desc, references=['portal type description of type with title %s' % title])
111
112            # don't show actions definied on criteria
113            if title.lower().find('criteri') == -1:
114                for action in typeObj.listActions():
115                    actionTitle = norm(action.title)
116                    ctl['lemill'].add(actionTitle, msgstr=actionTitle, references=['type action defined on %s' % title])
117
118        # portal_controlpanel categories
119        for group in self.cp_tool.getGroups():
120            id = group.get('id')
121            title = group.get('title')
122            ctl['lemill'].add(title, msgstr=title, references=['controlpanel category-id %s' % id])
123
124        # indexes and metadata and smart folder options
125        domain = 'lemill'
126        # DisplayList properties XXX This takes only static DisplayLists for now. Need to look at dynamically generated ones (which need a content object to be present)
127
128        for attype in self.at_tool.listRegisteredTypes():
129            # typename = attype['name']
130            schema = attype['schema']
131            for field in schema.fields():
132                if not isinstance(field, ReferenceField):
133                    domain = field.widget.__dict__.get('i18n_domain')
134                    vocab = field.Vocabulary()
135                    if isinstance(vocab, DisplayList):
136                        for key in vocab:
137                            value = vocab.getValue(key)
138                            if len(value) > 1:
139                                msgid = vocab.getMsgId(key)
140                                if domain == None:
141                                    domain = 'lemill'
142                                if not domain in ctl.keys():
143                                    ctl[domain] = catalog.MessageCatalog(domain=domain)
144                                ctl[domain].add(msgid, msgstr=value, references=['DisplayList entry for field %s' % field.getName()])
145
146        # archetypes widgets XXX Should be merged with the DisplayList stuff
147
148        for widget in self.at_tool.getWidgets():
149            w = widget._args.get('widget')
150            dict = w.__dict__
151            domain = dict.get('i18n_domain')
152            if domain:
153                if not domain in ctl.keys():
154                    ctl[domain] = catalog.MessageCatalog(domain=domain)
155                label = dict.get('label')
156                label_msgid = dict.get('label_msgid')
157                desc = norm(dict.get('description'))
158                desc_msgid = dict.get('description_msgid')
159
160                if label_msgid and label:
161                    ctl[domain].add(label_msgid, label, references=['widget label of %s - description \"%s\"' % (w.getName(), desc)])
162                if desc_msgid and desc:
163                    ctl[domain].add(desc_msgid, desc, references=['widget description of %s for label %s' % (w.getName(), label)])
164
165        # Custom extraction
166        from Products.LeMill.config import FIELD_METHODS_DISPLAY_STRINGS, TYPE_NAMES, TEMPLATES
167        for dt in (FIELD_METHODS_DISPLAY_STRINGS,TYPE_NAMES):
168            for (key,val) in dt.items():
169                msgid = val[0] # We only use the singular forms, apparently, plus plural forms give us trouble
170                ctl['lemill'].add(msgid,msgid,references=['Singular/plural name, shown as part of a sentence',])
171
172        def deCapitalize(s):
173            if s.isupper():
174                return s
175            return s.lower()
176               
177        for values in TEMPLATES.values():
178            for s in ('title','description'):
179                msgid=values[s]
180                ctl['lemill'].add(msgid,msgid,references=['Learning resource template %s' % s,])
181            for s in ("Add","Edit"):
182                msgid="%s %s" % (s,deCapitalize(values['title']))
183                ctl['lemill'].add(msgid,msgid,references=['Heading for learning resource edit form',])
184
185        for (typ,values) in TYPE_NAMES.items():
186            for prefix in ("Add","Edit"):
187                msgid="%s %s" % (prefix,deCapitalize(values[0]))
188                ctl['lemill'].add(msgid,msgid,references=['Heading for resource edit form',])
189
190        prefixes = ["My draft","My published"]
191        folders = ["content","activities","tools"]
192        community_folders = ["community","members","groups","blog posts","tips for use"]
193        topics = ["tags","language"]
194        material_topics = ["target group","subject area"]
195        member_topics = ["country","skills","interests"]
196        # My published [folders]
197        for suffix in folders:
198            msgid=" ".join((prefixes[1],suffix))
199            ctl['lemill'].add(msgid,msgid,references=["Heading",])
200        # My draft content
201        msgid=" ".join((prefixes[0],folders[0]))
202        ctl['lemill'].add(msgid,msgid,references=["Heading",])
203        # Browse [types]
204        for suffix in folders+community_folders:
205            msgid=" ".join(("Browse",suffix))
206            ctl['lemill'].add(msgid,msgid,references=['Heading',])
207        # Browse [folder] by [topic]
208        for fol in folders+community_folders:
209            for top in topics:
210                msgid=" ".join(("Browse",fol,"by",top))
211                ctl['lemill'].add(msgid,msgid,references=['Heading',])
212        # Browse [folder] where ${criteria_list}
213        for fol in folders+community_folders:
214            msgid=" ".join(("Browse",fol,"where"))
215            ctl['lemill'].add(msgid,msgid,references=['Start of heading, followed by a list of criteria, like \'language is English and tag is learning\'',])
216        # Browse members by [topic]
217        for suffix in member_topics:
218            msgid=" ".join(("Browse",community_folders[0],"by",suffix))
219            ctl['lemill'].add(msgid,msgid,references=["Heading",])
220        # Browse material by [topic]
221        for suffix in material_topics:
222            msgid=" ".join(("Browse content by",suffix))
223            ctl['lemill'].add(msgid,msgid,references=["Heading",])
224        # Browse x made by [name]
225        for fol in folders+community_folders:
226            msgid=" ".join(("Browse",fol,"made by"))
227            ctl['lemill'].add(msgid,msgid,references=['f.ex. Browse activities made by [username]'])
228
229        for domain in ['lemill',]:
230            file = open('%s-generated.pot' % domain, 'w')
231            writer = catalog.POWriter(file, ctl[domain])
232            writer.write(sort=True, msgstrToComment=True)
233
234def norm(str):
235    return str.strip().replace('\n','')
236
237def test_suite():
238    from unittest import TestSuite, makeSuite
239    suite = TestSuite()
240    suite.addTest(makeSuite(TranslationExtractor))
241    return suite
242
243if __name__ == '__main__':
244    framework()
Note: See TracBrowser for help on using the repository browser.