Skip to content

Commit

Permalink
add glossary push command
Browse files Browse the repository at this point in the history
  • Loading branch information
jamesni committed Aug 25, 2011
1 parent 11175a2 commit ab04594
Show file tree
Hide file tree
Showing 4 changed files with 141 additions and 4 deletions.
17 changes: 15 additions & 2 deletions zanataclient/publicanutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,20 @@ def pofile_to_json(self, filepath):

return json.dumps(items)

def glossary_to_json(self, filepath, lang):
pofile = self.create_pofile(filepath)
entries = []

for item in pofile:
terms = [{'locale':lang, 'content':item.msgstr, 'comments':[]}, {'locale':'en-US',
'content':item.msgid, 'comments':[]}]
entry= {'srcLang':'en-US','glossaryTerms':terms, 'sourcereference':''}
entries.append(entry)

glossary = {'glossaryEntries':entries}

return json.dumps(glossary)

def save_to_pofile(self, path, translations, pot):
"""
Save PO file to path, based on json objects of pot and translations
Expand Down Expand Up @@ -294,5 +308,4 @@ def save_to_pofile(self, path, translations, pot):
po.save()
# pylint: disable-msg=E1103
self.log.info("Writing po file to %s"%(path))



50 changes: 48 additions & 2 deletions zanataclient/zanata.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,8 @@
'publican': ['push', 'pull'],
'po': ['push', 'pull'],
'push':[],
'pull':[]
'pull':[],
'glossary':['push']
}

usage = """Client for talking to a Zanata Server
Expand Down Expand Up @@ -1172,6 +1173,50 @@ def pull(command_options, args, project_type = None):

zanatacmd = ZanataCommand()
zanatacmd.pull_command(zanata, locale_map, project_id, iteration_id, filelist, lang_list, outpath, command_type)

def glossary_push(command_options, args):
"""
Usage: zanata glossary push [OPTIONS] GLOSSARY_POFILE
Push glossary file in po format to zanata server
Options:
--url: URL of zanata server
--username: user name
--apikey: api key of user
--lang: language of glossary file
"""
zanatacmd = ZanataCommand()
project_config = read_project_config(command_options)

if not project_config:
log.info("Can not find zanata.xml, please specify the path of zanata.xml")

url = process_url(project_config, command_options)
username, apikey = read_user_config(url, command_options)
if args:
path = os.path.join(os.getcwd(), args[0])
if not os.path.isfile(path):
log.error("Can not find glossary file %s under current path"%args[0])
sys.exit(1)
else:
log.info("Please specify the file name of glossary file")
sys.exit(1)

if command_options.has_key('lang'):
locale = command_options['lang'][0]['value'].split(',')[0]
else:
log.error("Please specify the language with '--lang' option")
sys.exit(1)

if project_config.has_key('locale_map'):
locale_map = project_config['locale_map']
if locale in locale_map:
lang = locale_map[locale]
else:
lang = locale

zanatacmd.glossary_push(path, url, username, apikey, lang)

command_handler_factories = {
'help': makeHandler(help_info),
Expand All @@ -1185,7 +1230,8 @@ def pull(command_options, args, project_type = None):
'publican_pull': makeHandler(publican_pull),
'publican_push': makeHandler(publican_push),
'push': makeHandler(push),
'pull': makeHandler(pull)
'pull': makeHandler(pull),
'glossary_push': makeHandler(glossary_push)
}

def signal_handler(signal, frame):
Expand Down
20 changes: 20 additions & 0 deletions zanataclient/zanatacmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import os

from publicanutil import PublicanUtility
from zanatalib.glossaryservice import GlossaryService
from zanatalib.project import Project
from zanatalib.project import Iteration
from zanatalib.logger import Logger
Expand All @@ -36,6 +37,7 @@
from zanatalib.error import NotAllowedException
from zanatalib.error import ProjectExistException
from zanatalib.error import UnexpectedStatusException
from zanatalib.error import UnavailableServiceError

class ZanataCommand:
def __init__(self):
Expand Down Expand Up @@ -409,3 +411,21 @@ def pull_command(self, zanata, locale_map, project_id, iteration_id, filelist, l
self.log.error(e.msg)

publicanutil.save_to_pofile(pofile, result, pot)

def glossary_push(self, path, url, username, apikey, lang):
publicanutil = PublicanUtility()

json = publicanutil.glossary_to_json(path, lang)
glossary = GlossaryService(url)

try:
content = glossary.commit_glossary(username, apikey, json)
if content:
self.log.info("Successfully pushed glossary to the server")
except UnAvaliableResourceException:
log.error("Can not push")
except UnavailableServiceError:
log.error("Service Temporarily Unavailable, stop processing!")
sys.exit(1)
except UnexpectedStatusException, e:
self.log.error(e.msg)
58 changes: 58 additions & 0 deletions zanataclient/zanatalib/glossaryservice.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
#vim:set et sts=4 sw=4:
#
# Zanata Python Client
#
# Copyright (c) 2011 Jian Ni <jni@redhat.com>
# Copyright (c) 2011 Red Hat, Inc.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330,
# Boston, MA 02111-1307 USA


__all__ = (
"GlossaryService",
)

try:
import json
except ImportError:
import simplejson as json
from rest.client import RestClient
from error import UnAuthorizedException
from error import BadRequestBodyException
from error import UnavailableServiceError
from error import UnexpectedStatusException

class GlossaryService:
def __init__(self, base_url):
self.restclient = RestClient(base_url)

def commit_glossary(self, username, apikey, resources):
headers = {}
headers['X-Auth-User'] = username
headers['X-Auth-Token'] = apikey

res, content = self.restclient.request_put('/seam/resource/restv1/glossary', args=resources, headers=headers)

if res['status'] == '201':
return True
elif res['status'] == '401':
raise UnAuthorizedException('Error 401', 'This operation is not authorized, please check username and apikey')
elif res['status'] == '400':
raise BadRequestBodyException('Error 400', content)
elif res['status'] == '503':
raise UnavailableServiceError('Error 503', 'Service Temporarily Unavailable')
else:
raise UnexpectedStatusException('Error', 'Unexpected Status, failed to push')

0 comments on commit ab04594

Please sign in to comment.