Commits

coderanger committed 69e37fe

Add --user and --pass arguments to the push and pull commands. Use setuptools' script generation for Windows.

Comments (0)

Files changed (5)

     '': ['LICENSE', 'README'],
 }
 
-scripts = ['tx']
-
 install_requires = []
 try:
     import json
 setup(
     name="transifex-client",
     version=get_version(),
-    scripts=scripts,
     description="A command line interface for Transifex",
     long_description=long_description,
     author="Indifex Ltd.",
     include_package_data=True,
     package_data = package_data,
     keywords = ('translation', 'localization', 'internationalization',),
+    entry_points = """
+    [console_scripts]
+    tx = txclib.script:main
+    """
 )

tx

-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-
-from optparse import OptionParser
-import os
-import sys
-
-from txclib import utils
-from txclib import get_version
-
-reload(sys) # WTF? Otherwise setdefaultencoding doesn't work
-
-# This block ensures that ^C interrupts are handled quietly.
-try:
-    import signal
-
-    def exithandler(signum,frame):
-        signal.signal(signal.SIGINT, signal.SIG_IGN)
-        signal.signal(signal.SIGTERM, signal.SIG_IGN)
-        sys.exit(1)
-
-    signal.signal(signal.SIGINT, exithandler)
-    signal.signal(signal.SIGTERM, exithandler)
-    if hasattr(signal, 'SIGPIPE'):
-        signal.signal(signal.SIGPIPE, signal.SIG_DFL)
-
-except KeyboardInterrupt:
-    sys.exit(1)
-
-# When we open file with f = codecs.open we specifi FROM what encoding to read
-# This sets the encoding for the strings which are created with f.read()
-sys.setdefaultencoding('utf-8')
-
-def main(argv):
-    """
-    Here we parse the flags (short, long) and we instantiate the classes.
-    """
-    usage = "usage: %prog [options] command [cmd_options]"
-    description = "This is the Transifex command line client which"\
-		" allows you to manage your translations locally and sync"\
- 	 	" them with the master Transifex server.\nIf you'd like to"\
-		" check the available commands issue `%prog help` or if you"\
-		" just want help with a specific command issue `%prog help"\
-		" command`"
-
-    parser = OptionParser(usage=usage, version=get_version(), description=description)
-    parser.disable_interspersed_args()
-    parser.add_option("-q", "--quiet", 
-        action="store_true", dest="verbose", default=False,
-        help="don't print status messages to stdout")
-    parser.add_option("-r", "--root", action="store",
-        dest="root_dir", type="string", default=None,
-        help="change root directory (default is cwd)")
-    parser.add_option("--traceback", action="store_true",
-        dest="trace", default=False,
-        help="print full traceback on exceptions")
-    parser.add_option("--disable-colors", action="store_true",
-        dest="color_disable", default=(os.name == 'nt'),
-        help="print full traceback on exceptions")
-
-    (options, args) = parser.parse_args()
-
-    if len(args) < 1:
-        parser.error("No command was given")
-
-    utils.DISABLE_COLORS = options.color_disable
-
-    # find .tx
-    path_to_tx = options.root_dir or utils.find_dot_tx()
-
-   
-    cmd = args[0]
-    try:
-        utils.exec_command(cmd, args[1:], path_to_tx)
-    except KeyError:
-        utils.ERRMSG("tx: Command %s not found" % cmd)
-    except SystemExit:
-        sys.exit()
-    except:
-        import traceback
-        if options.trace:
-            traceback.print_exc()
-        else:
-            formatted_lines = traceback.format_exc().splitlines()    
-            utils.ERRMSG(formatted_lines[-1])
-        sys.exit(1)
-
-# Run baby :) ... run
-if __name__ == "__main__":
-    # sys.argv[0] is the name of the script that we’re running.
-    main(sys.argv[1:])

txclib/commands.py

         default=False, help="Push the translation files to the server")
     parser.add_option("--no-interactive", action="store_true", dest="no_interactive",
         default=False, help="Don't require user input when forcing a push.")
+    parser.add_option("--user", action="store", dest="user",
+        default=None, help="Specify username for Transifex server.")
+    parser.add_option("--pass", action="store", dest="password",
+        default=None, help="Specify password for Transifex server.")
 
     (options, args) = parser.parse_args(argv)
 
     prj.push(force=force_creation, resources=resources, languages=languages,
         skip=skip, source=options.push_source,
         translations=options.push_translations,
-        no_interactive=options.no_interactive)
+        no_interactive=options.no_interactive,
+        user=options.user, password=options.password)
 
     utils.MSG("Done.")
 
         help="By default transifex will fetch new translations files and"\
             " replace existing ones. Use this flag if you want to disable"\
             " this feature")
+    parser.add_option("--user", action="store", dest="user",
+        default=None, help="Specify username for Transifex server.")
+    parser.add_option("--pass", action="store", dest="password",
+        default=None, help="Specify password for Transifex server.")
 
     (options, args) = parser.parse_args(argv)
 
             raise Exception("Specified resource '%s' does not exist." % r)
 
     prj.pull(languages=languages, resources=resources, overwrite=options.overwrite,
-        fetchall=options.fetchall, force=options.force)
+        fetchall=options.fetchall, force=options.force, user=options.user,
+        password=options.password)
     prj.save()
 
     utils.MSG("Done.")

txclib/project.py

             return os.path.join(self.root, relpath)
 
     def pull(self, languages=[], resources=[], overwrite=True, fetchall=False,
-        force=False):
+        force=False, user=None, password=None):
         """
         Pull all translations file from transifex server
         """
                 raw = self.do_url_request('resource_details',
                     host=host,
                     project=project_slug,
-                    resource=resource_slug)
+                    resource=resource_slug,
+                    user=user,
+                    password=password)
 
                 details = parse_json(raw)
                 langs = details['available_languages']
                         host=host,
                         project=project_slug,
                         resource=resource_slug,
-                        language=lang)
+                        language=lang,
+                        user=user,
+                        password=password)
 
                     stats = parse_json(r)
                     if stats.has_key(lang):
                     host=host,
                     project=project_slug,
                     resource=resource_slug,
-                    language=lang)
+                    language=lang,
+                    user=user,
+                    password=password)
                 base_dir = os.path.split(local_file)[0]
                 mkdir_p(base_dir)
                 fd = open(local_file, 'w')
                         host=host,
                         project=project_slug,
                         resource=resource_slug,
-                        language=lang)
+                        language=lang,
+                        user=user,
+                        password=password)
 
                     base_dir = os.path.split(local_file)[0]
                     mkdir_p(base_dir)
 
 
     def push(self, source=False, translations=False, force=False, resources=[], languages=[],
-        skip=False, no_interactive=False):
+        skip=False, no_interactive=False, user=None, password=None):
         """
         Push all the resources
         """
                             files=[( "%s;%s" % (resource_slug, slang),
                             self.get_full_path(sfile))],
                             method="POST",
-                            project=project_slug)
+                            project=project_slug,
+                            user=user,
+                            password=password)
                     r = parse_json(r)
                     uuid = r['files'][0]['uuid']
                     self.do_url_request('extract_source',
                         data=compile_json({"uuid":uuid,"slug":resource_slug}),
                         encoding='application/json',
                         method="POST",
-                        project=project_slug)
+                        project=project_slug,
+                        user=user,
+                        password=password)
                 except Exception, e:
                     if not skip:
                         raise e
             else:
                 try:
                     self.do_url_request('resource_details', host=host,
-                        project=project_slug, resource=resource_slug)
+                        project=project_slug, resource=resource_slug,
+                        user=user, password=password)
                 except Exception, e:
                     try:
                         code = e.code
                                 host=host,
                                 project=project_slug,
                                 resource=resource_slug,
-                                language=lang)
+                                language=lang,
+                                user=user,
+                                password=password)
 
                             # Check remote timestamp for file and skip update if needed
                             stats = parse_json(r)
                             files=[( "%s;%s" % (resource_slug, lang),
                             self.get_full_path(local_file))],
                             method="POST",
-                            project=project_slug)
+                            project=project_slug,
+                            user=user,
+                            password=password)
                         r = parse_json(r)
                         uuid = r['files'][0]['uuid']
                         self.do_url_request('extract_translation',
                             method="PUT",
                             project=project_slug,
                             resource=resource_slug,
-                            language=lang)
+                            language=lang,
+                            user=user,
+                            password=password)
                     except Exception, e:
                         if not skip:
                             raise e
 
 
     def do_url_request(self, api_call, host=None, multipart=False, data=None,
-                       files=[], encoding=None, method="GET", **kwargs):
+                       files=[], encoding=None, method="GET", user=None, password=None, **kwargs):
         """
         Issues a url request.
         """
         # Read the credentials from the config file (.transifexrc)
         
         try:
-            username = self.txrc.get(host, 'username')
-            passwd = self.txrc.get(host, 'password')
-            token = self.txrc.get(host, 'token')
-            hostname = self.txrc.get(host, 'hostname')
+            username = user or self.txrc.get(host, 'username')
+            passwd = password or self.txrc.get(host, 'password')
+            token = self.txrc.has_option(host, 'token') and self.txrc.get(host, 'token') or ''
+            hostname = self.txrc.has_option(host, 'hostname') and self.txrc.get(host, 'hostname') or host
         except ConfigParser.NoSectionError:
             raise Exception("No user credentials found for host %s. Edit"
                 " ~/.transifexrc and add the appropriate info in there." %
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+from optparse import OptionParser
+import os
+import sys
+
+from txclib import utils
+from txclib import get_version
+
+reload(sys) # WTF? Otherwise setdefaultencoding doesn't work
+
+# This block ensures that ^C interrupts are handled quietly.
+try:
+    import signal
+
+    def exithandler(signum,frame):
+        signal.signal(signal.SIGINT, signal.SIG_IGN)
+        signal.signal(signal.SIGTERM, signal.SIG_IGN)
+        sys.exit(1)
+
+    signal.signal(signal.SIGINT, exithandler)
+    signal.signal(signal.SIGTERM, exithandler)
+    if hasattr(signal, 'SIGPIPE'):
+        signal.signal(signal.SIGPIPE, signal.SIG_DFL)
+
+except KeyboardInterrupt:
+    sys.exit(1)
+
+# When we open file with f = codecs.open we specifi FROM what encoding to read
+# This sets the encoding for the strings which are created with f.read()
+sys.setdefaultencoding('utf-8')
+
+def main(argv=None):
+    """
+    Here we parse the flags (short, long) and we instantiate the classes.
+    """
+    if not argv:
+        argv = sys.argv[1:]
+    usage = "usage: %prog [options] command [cmd_options]"
+    description = "This is the Transifex command line client which"\
+		" allows you to manage your translations locally and sync"\
+ 	 	" them with the master Transifex server.\nIf you'd like to"\
+		" check the available commands issue `%prog help` or if you"\
+		" just want help with a specific command issue `%prog help"\
+		" command`"
+
+    parser = OptionParser(usage=usage, version=get_version(), description=description)
+    parser.disable_interspersed_args()
+    parser.add_option("-q", "--quiet", 
+        action="store_true", dest="verbose", default=False,
+        help="don't print status messages to stdout")
+    parser.add_option("-r", "--root", action="store",
+        dest="root_dir", type="string", default=None,
+        help="change root directory (default is cwd)")
+    parser.add_option("--traceback", action="store_true",
+        dest="trace", default=False,
+        help="print full traceback on exceptions")
+    parser.add_option("--disable-colors", action="store_true",
+        dest="color_disable", default=(os.name == 'nt'),
+        help="print full traceback on exceptions")
+
+    (options, args) = parser.parse_args()
+
+    if len(args) < 1:
+        parser.error("No command was given")
+
+    utils.DISABLE_COLORS = options.color_disable
+
+    # find .tx
+    path_to_tx = options.root_dir or utils.find_dot_tx()
+
+   
+    cmd = args[0]
+    try:
+        utils.exec_command(cmd, args[1:], path_to_tx)
+    except KeyError:
+        utils.ERRMSG("tx: Command %s not found" % cmd)
+    except SystemExit:
+        sys.exit()
+    except:
+        import traceback
+        if options.trace:
+            traceback.print_exc()
+        else:
+            formatted_lines = traceback.format_exc().splitlines()    
+            utils.ERRMSG(formatted_lines[-1])
+        sys.exit(1)
+
+# Run baby :) ... run
+if __name__ == "__main__":
+    # sys.argv[0] is the name of the script that we’re running.
+    main(sys.argv[1:])