[Python-modules-commits] [transifex-client] 02/07: Imported Upstream version 0.12.4

Hans-Christoph Steiner eighthave at moszumanska.debian.org
Fri Apr 14 19:24:21 UTC 2017


This is an automated email from the git hooks/post-receive script.

eighthave pushed a commit to branch master
in repository transifex-client.

commit 8e46068cffbf21b4c752f4b20832fe47b38d351e
Author: Hans-Christoph Steiner <hans at eds.org>
Date:   Fri Apr 14 21:09:52 2017 +0200

    Imported Upstream version 0.12.4
---
 MANIFEST.in                           |   2 +-
 PKG-INFO                              |  86 +++++++++---------
 README.md                             |  65 ++++++++++++++
 README.rst                            |  69 --------------
 setup.py                              |   3 +-
 tests/test_project.py                 |  61 +++++++++++--
 transifex_client.egg-info/PKG-INFO    |  86 +++++++++---------
 transifex_client.egg-info/SOURCES.txt |   2 +-
 txclib/__init__.py                    |   2 +-
 txclib/cmdline.py                     |   2 +
 txclib/commands.py                    |  41 +++++----
 txclib/parsers.py                     |  17 ++++
 txclib/project.py                     | 165 +++++++++++++++++++++++++++-------
 txclib/utils.py                       |  69 +++++++++++---
 14 files changed, 436 insertions(+), 234 deletions(-)

diff --git a/MANIFEST.in b/MANIFEST.in
index 4f0a350..13188a6 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -3,7 +3,7 @@ include txclib/cacert.pem
 include requirements.txt
 
 # Docs
-include LICENSE README.rst
+include LICENSE README.md
 recursive-include docs *
 
 # Tests
diff --git a/PKG-INFO b/PKG-INFO
index 20775a1..80853f5 100644
--- a/PKG-INFO
+++ b/PKG-INFO
@@ -1,80 +1,76 @@
 Metadata-Version: 1.1
 Name: transifex-client
-Version: 0.12.2
+Version: 0.12.4
 Summary: A command line interface for Transifex
 Home-page: https://www.transifex.com
 Author: Transifex
 Author-email: admin at transifex.com
 License: GPLv2
-Description: .. image:: https://circleci.com/gh/transifex/transifex-client/tree/master.svg?style=shield&circle-token=33aafd984726261eff1b73278a0cf761382c478a
-            :target: https://circleci.com/gh/transifex/transifex-client/tree/master
-        .. image:: https://ci.appveyor.com/api/projects/status/github/transifex/transifex-client?branch=master&svg=true
-            :target: https://ci.appveyor.com/project/transifex/transifex-client/branch/master
-        .. image:: https://codecov.io/gh/transifex/transifex-client/branch/master/graph/badge.svg
-            :target: https://codecov.io/gh/transifex/transifex-client
-        
-        
-        
-        =============================
-         Transifex Command-Line Tool
-        =============================
-        
+Description: Transifex Command-Line Tool
+        ===========================
+        [![image](https://circleci.com/gh/transifex/transifex-client/tree/master.svg?style=shield&circle-token=33aafd984726261eff1b73278a0cf761382c478a)](https://circleci.com/gh/transifex/transifex-client/tree/master)
+        [![image](https://ci.appveyor.com/api/projects/status/github/transifex/transifex-client?branch=master&svg=true)](https://ci.appveyor.com/project/transifex/transifex-client/branch/master)
+        [![codecov](https://codecov.io/gh/transifex/transifex-client/branch/master/graph/badge.svg)](https://codecov.io/gh/transifex/transifex-client)
+        [![PyPI version](https://badge.fury.io/py/transifex-client.svg)](https://badge.fury.io/py/transifex-client)
+        
+        Description
+        ---
         The Transifex Command-line Tool enables you to manage your translations within a project without the need of an elaborate UI system.
         
-        You can use the command line tool to create new resources, map locale files to translations, and synchronize your Transifex project with your local repository. Translators and localization managers can use it to handle large volumes of translation files. The Transifex Command-line Tool can help to enable continuous integration workflows and can be run from CI servers like Jenkins and Bamboo.
-        
-        Check the full documentation at http://docs.transifex.com/client/
+        You can use the command line tool to create new resources, map locale files to translations, and synchronize your Transifex project with your local repository. Translators and localization managers can use it to handle large volumes of translation files.  The Transifex Command-line Tool can help to enable continuous integration workflows and can be run from CI servers like Jenkins and Bamboo.
         
-        Installing
-        ==========
+        [Click  here](http://docs.transifex.com/client/) for complete documentation on the Transifex Command-line Tool via our documentation site.
         
-        You can install the latest version of transifex-client running ``pip
-        install transifex-client`` or ``easy_install transifex-client``.
+        Installation
+        ----------
         
+        You can install the latest version of transifex-client running `pip install transifex-client` or `easy_install transifex-client`.
         
         Build transifex-client for Windows
-        ==================================
-        
-        1. Download transifex-client sources via git or github archive.
+        ----------------------------------
         
-           a. ``git clone https://github.com/transifex/transifex-client.git``
-           b. Download and unpack https://github.com/transifex/transifex-client/archive/master.zip
+        1.  Download transifex-client sources via git or github archive.
+            1.  `git clone https://github.com/transifex/transifex-client.git`
+            2.  Download and unpack <https://github.com/transifex/transifex-client/archive/master.zip>
         
-        2. Download and install Python_.
+        2.  Download and install [Python](https://www.python.org/downloads/windows/).
         
-           At this step choose right version of python: 2 or 3 and x86 or x86-64 instruction set.
+            At this step choose right version of python: 2 or 3 and x86 or x86-64 instruction set.
         
-           Make sure pip marked for installation(default for latest installers).
+            Make sure pip marked for installation(default for latest installers).
         
-        3. Install PyInstaller_.
+        3.  Install [PyInstaller](http://www.pyinstaller.org).
         
-           Suppose that Python installed to ``C:\\Program Files\\Python35-32``
+            Suppose that Python installed to `C:\\Program Files\\Python35-32`
         
-           Make ``python.exe`` accessible via PATH environment variable or cd to directory containing python.exe.
+            Make `python.exe` accessible via PATH environment variable or cd to directory containing python.exe.
         
-           ::
+                python -m pip install pyinstaller
         
-             python -m pip install pyinstaller
+            This command will install `PyInstaller` package and its dependencies.
         
-           This command will install ``PyInstaller`` package and its dependencies.
+        4.  Build `transifex-client` distribution.
         
-        4. Build ``transifex-client`` distribution.
+            Change directory to transifex-client folder and run command:
         
-           Change directory to transifex-client folder and run command:
+                python -m PyInstaller contrib/tx.spec
+                # or
+                pyinstaller contrib/tx.spec
         
-           ::
+        5.  `tx.exe`
         
-             python -m PyInstaller contrib/tx.spec
-             # or
-             pyinstaller contrib/tx.spec
+            `dist/tx.exe` will be created as the result of build process.
         
-        5. ``tx.exe``
         
-           ``dist/tx.exe`` will be created as the result of build process.
+        Getting Help
+        ---
+        You can always get additional help via [GitHub issues](https://github.com/transifex/txgh/issues) or [Transifex support](https://www.transifex.com/contact/)
         
+        License
+        ---
+        Transifex Client is primarily distributed under the terms of the GPL License (Version 2.0).
         
-        .. _Python: https://www.python.org/downloads/windows/
-        .. _PyInstaller: http://www.pyinstaller.org
+        See [LICENSE](https://github.com/transifex/transifex-client/blob/master/LICENSE) for details.
         
 Keywords: translation,localization,internationalization
 Platform: UNKNOWN
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..f38b443
--- /dev/null
+++ b/README.md
@@ -0,0 +1,65 @@
+Transifex Command-Line Tool
+===========================
+[![image](https://circleci.com/gh/transifex/transifex-client/tree/master.svg?style=shield&circle-token=33aafd984726261eff1b73278a0cf761382c478a)](https://circleci.com/gh/transifex/transifex-client/tree/master)
+[![image](https://ci.appveyor.com/api/projects/status/github/transifex/transifex-client?branch=master&svg=true)](https://ci.appveyor.com/project/transifex/transifex-client/branch/master)
+[![codecov](https://codecov.io/gh/transifex/transifex-client/branch/master/graph/badge.svg)](https://codecov.io/gh/transifex/transifex-client)
+[![PyPI version](https://badge.fury.io/py/transifex-client.svg)](https://badge.fury.io/py/transifex-client)
+
+Description
+---
+The Transifex Command-line Tool enables you to manage your translations within a project without the need of an elaborate UI system.
+
+You can use the command line tool to create new resources, map locale files to translations, and synchronize your Transifex project with your local repository. Translators and localization managers can use it to handle large volumes of translation files.  The Transifex Command-line Tool can help to enable continuous integration workflows and can be run from CI servers like Jenkins and Bamboo.
+
+[Click  here](http://docs.transifex.com/client/) for complete documentation on the Transifex Command-line Tool via our documentation site.
+
+Installation
+----------
+
+You can install the latest version of transifex-client running `pip install transifex-client` or `easy_install transifex-client`.
+
+Build transifex-client for Windows
+----------------------------------
+
+1.  Download transifex-client sources via git or github archive.
+    1.  `git clone https://github.com/transifex/transifex-client.git`
+    2.  Download and unpack <https://github.com/transifex/transifex-client/archive/master.zip>
+
+2.  Download and install [Python](https://www.python.org/downloads/windows/).
+
+    At this step choose right version of python: 2 or 3 and x86 or x86-64 instruction set.
+
+    Make sure pip marked for installation(default for latest installers).
+
+3.  Install [PyInstaller](http://www.pyinstaller.org).
+
+    Suppose that Python installed to `C:\\Program Files\\Python35-32`
+
+    Make `python.exe` accessible via PATH environment variable or cd to directory containing python.exe.
+
+        python -m pip install pyinstaller
+
+    This command will install `PyInstaller` package and its dependencies.
+
+4.  Build `transifex-client` distribution.
+
+    Change directory to transifex-client folder and run command:
+
+        python -m PyInstaller contrib/tx.spec
+        # or
+        pyinstaller contrib/tx.spec
+
+5.  `tx.exe`
+
+    `dist/tx.exe` will be created as the result of build process.
+
+
+Getting Help
+---
+You can always get additional help via [GitHub issues](https://github.com/transifex/txgh/issues) or [Transifex support](https://www.transifex.com/contact/)
+
+License
+---
+Transifex Client is primarily distributed under the terms of the GPL License (Version 2.0).
+
+See [LICENSE](https://github.com/transifex/transifex-client/blob/master/LICENSE) for details.
diff --git a/README.rst b/README.rst
deleted file mode 100644
index 39188c1..0000000
--- a/README.rst
+++ /dev/null
@@ -1,69 +0,0 @@
-.. image:: https://circleci.com/gh/transifex/transifex-client/tree/master.svg?style=shield&circle-token=33aafd984726261eff1b73278a0cf761382c478a
-    :target: https://circleci.com/gh/transifex/transifex-client/tree/master
-.. image:: https://ci.appveyor.com/api/projects/status/github/transifex/transifex-client?branch=master&svg=true
-    :target: https://ci.appveyor.com/project/transifex/transifex-client/branch/master
-.. image:: https://codecov.io/gh/transifex/transifex-client/branch/master/graph/badge.svg
-    :target: https://codecov.io/gh/transifex/transifex-client
-
-
-
-=============================
- Transifex Command-Line Tool
-=============================
-
-The Transifex Command-line Tool enables you to manage your translations within a project without the need of an elaborate UI system.
-
-You can use the command line tool to create new resources, map locale files to translations, and synchronize your Transifex project with your local repository. Translators and localization managers can use it to handle large volumes of translation files. The Transifex Command-line Tool can help to enable continuous integration workflows and can be run from CI servers like Jenkins and Bamboo.
-
-Check the full documentation at http://docs.transifex.com/client/
-
-Installing
-==========
-
-You can install the latest version of transifex-client running ``pip
-install transifex-client`` or ``easy_install transifex-client``.
-
-
-Build transifex-client for Windows
-==================================
-
-1. Download transifex-client sources via git or github archive.
-
-   a. ``git clone https://github.com/transifex/transifex-client.git``
-   b. Download and unpack https://github.com/transifex/transifex-client/archive/master.zip
-
-2. Download and install Python_.
-
-   At this step choose right version of python: 2 or 3 and x86 or x86-64 instruction set.
-
-   Make sure pip marked for installation(default for latest installers).
-
-3. Install PyInstaller_.
-
-   Suppose that Python installed to ``C:\\Program Files\\Python35-32``
-
-   Make ``python.exe`` accessible via PATH environment variable or cd to directory containing python.exe.
-
-   ::
-
-     python -m pip install pyinstaller
-
-   This command will install ``PyInstaller`` package and its dependencies.
-
-4. Build ``transifex-client`` distribution.
-
-   Change directory to transifex-client folder and run command:
-
-   ::
-
-     python -m PyInstaller contrib/tx.spec
-     # or
-     pyinstaller contrib/tx.spec
-
-5. ``tx.exe``
-
-   ``dist/tx.exe`` will be created as the result of build process.
-
-
-.. _Python: https://www.python.org/downloads/windows/
-.. _PyInstaller: http://www.pyinstaller.org
diff --git a/setup.py b/setup.py
index 5bb1452..6a27901 100755
--- a/setup.py
+++ b/setup.py
@@ -10,12 +10,13 @@ def get_file_content(filename):
     with open(filename, 'r', encoding='UTF-8') as f:
         return f.read()
 
+
 setup(
     name="transifex-client",
     version=txclib.__version__,
     entry_points={'console_scripts': ['tx=txclib.cmdline:main']},
     description="A command line interface for Transifex",
-    long_description=get_file_content('README.rst'),
+    long_description=get_file_content('README.md'),
     author="Transifex",
     author_email="admin at transifex.com",
     url="https://www.transifex.com",
diff --git a/tests/test_project.py b/tests/test_project.py
index beb9c65..823d902 100644
--- a/tests/test_project.py
+++ b/tests/test_project.py
@@ -8,12 +8,66 @@ except ImportError:
     import simplejson as json
 from mock import Mock, patch
 
-from txclib.project import Project
+from txclib.project import Project, ProjectNotInit
 from txclib.config import Flipdict
 
 
 class TestProject(unittest.TestCase):
 
+    @patch('txclib.utils.find_dot_tx')
+    def test_get_tx_dir_path(self, m_find_dot_tx):
+        """Test _get_tx_dir_path function"""
+        expected_path = '/tmp/'
+        m_find_dot_tx.return_value = expected_path
+        p = Project(init=False)
+        path = p._get_tx_dir_path(path_to_tx=None)
+        self.assertEqual(path, expected_path)
+        m_find_dot_tx.assert_called_once_with()
+
+        expected_path = '/opt/'
+        path = p._get_tx_dir_path(path_to_tx=expected_path)
+        self.assertEqual(path, expected_path)
+        # make sure it has not been called twice
+        m_find_dot_tx.assert_called_once_with()
+
+    @patch('os.path.exists')
+    def test_get_config_file_path(self, m_exists):
+        """Test _get_config_file_path function"""
+        p = Project(init=False)
+        m_exists.return_value = True
+        p._get_config_file_path('/tmp/')
+        m_exists.assert_called_once_with('/tmp/.tx/config')
+
+        m_exists.return_value = False
+        with self.assertRaises(ProjectNotInit):
+            p._get_config_file_path('/tmp/')
+
+    @patch('txclib.utils.confirm')
+    @patch('txclib.config.configparser')
+    def test_getset_host_credentials(self, m_parser, m_confirm):
+        p = Project(init=False)
+        # let suppose a token has been set at the config
+        dummy_token = 'salala'
+        p.txrc = m_parser
+        p.txrc.add_section = Mock()
+        p.txrc.set = Mock()
+        p.txrc.get = Mock()
+        p.txrc.get.side_effect = ['api', dummy_token, None, None]
+        p.txrc_file = '/tmp'
+        username, password = p.getset_host_credentials('test')
+        self.assertEqual(username, 'api')
+        self.assertEqual(password, dummy_token)
+
+        # let's try to get credentials for someone without
+        # a token
+        p.txrc.get.side_effect = [
+            'username',
+            'passw0rdz'
+        ]
+        username, password = p.getset_host_credentials('test')
+        self.assertEqual(username, 'username')
+        self.assertEqual(password, 'passw0rdz')
+
     def test_extract_fields(self):
         """Test the functions that extract a field from a stats object."""
         stats = {
@@ -379,7 +433,6 @@ class TestProjectPull(unittest.TestCase):
         """Test finding new transaltions to add."""
         with patch.object(self.p, 'do_url_request') as resource_mock:
             resource_mock.return_value = json.dumps(self.details), "utf-8"
-            files_keys = self.langs
             new_trans = self.p._new_translations_to_add
             for force in [True, False]:
                 res = new_trans(
@@ -510,8 +563,7 @@ class TestProjectPull(unittest.TestCase):
             res = self.p._should_download('en', self.stats, None, True)
             self.assertEqual(res, True)
 
-            with patch.object(self.p, '_remote_is_newer') as local_file_mock:
-                local_file_mock = False
+            with patch.object(self.p, '_remote_is_newer'):
                 res = self.p._should_download('pt', self.stats, None, False)
                 self.assertEqual(res, True)
                 res = self.p._should_download('pt', self.stats, None, True)
@@ -565,7 +617,6 @@ class TestConfigurationOptions(unittest.TestCase):
 
     def test_i18n_type(self):
         p = Project(init=False)
-        type_string = 'type'
         i18n_type = 'PO'
         with patch.object(p, 'config', create=True) as config_mock:
             p.set_i18n_type([], i18n_type)
diff --git a/transifex_client.egg-info/PKG-INFO b/transifex_client.egg-info/PKG-INFO
index 20775a1..80853f5 100644
--- a/transifex_client.egg-info/PKG-INFO
+++ b/transifex_client.egg-info/PKG-INFO
@@ -1,80 +1,76 @@
 Metadata-Version: 1.1
 Name: transifex-client
-Version: 0.12.2
+Version: 0.12.4
 Summary: A command line interface for Transifex
 Home-page: https://www.transifex.com
 Author: Transifex
 Author-email: admin at transifex.com
 License: GPLv2
-Description: .. image:: https://circleci.com/gh/transifex/transifex-client/tree/master.svg?style=shield&circle-token=33aafd984726261eff1b73278a0cf761382c478a
-            :target: https://circleci.com/gh/transifex/transifex-client/tree/master
-        .. image:: https://ci.appveyor.com/api/projects/status/github/transifex/transifex-client?branch=master&svg=true
-            :target: https://ci.appveyor.com/project/transifex/transifex-client/branch/master
-        .. image:: https://codecov.io/gh/transifex/transifex-client/branch/master/graph/badge.svg
-            :target: https://codecov.io/gh/transifex/transifex-client
-        
-        
-        
-        =============================
-         Transifex Command-Line Tool
-        =============================
-        
+Description: Transifex Command-Line Tool
+        ===========================
+        [![image](https://circleci.com/gh/transifex/transifex-client/tree/master.svg?style=shield&circle-token=33aafd984726261eff1b73278a0cf761382c478a)](https://circleci.com/gh/transifex/transifex-client/tree/master)
+        [![image](https://ci.appveyor.com/api/projects/status/github/transifex/transifex-client?branch=master&svg=true)](https://ci.appveyor.com/project/transifex/transifex-client/branch/master)
+        [![codecov](https://codecov.io/gh/transifex/transifex-client/branch/master/graph/badge.svg)](https://codecov.io/gh/transifex/transifex-client)
+        [![PyPI version](https://badge.fury.io/py/transifex-client.svg)](https://badge.fury.io/py/transifex-client)
+        
+        Description
+        ---
         The Transifex Command-line Tool enables you to manage your translations within a project without the need of an elaborate UI system.
         
-        You can use the command line tool to create new resources, map locale files to translations, and synchronize your Transifex project with your local repository. Translators and localization managers can use it to handle large volumes of translation files. The Transifex Command-line Tool can help to enable continuous integration workflows and can be run from CI servers like Jenkins and Bamboo.
-        
-        Check the full documentation at http://docs.transifex.com/client/
+        You can use the command line tool to create new resources, map locale files to translations, and synchronize your Transifex project with your local repository. Translators and localization managers can use it to handle large volumes of translation files.  The Transifex Command-line Tool can help to enable continuous integration workflows and can be run from CI servers like Jenkins and Bamboo.
         
-        Installing
-        ==========
+        [Click  here](http://docs.transifex.com/client/) for complete documentation on the Transifex Command-line Tool via our documentation site.
         
-        You can install the latest version of transifex-client running ``pip
-        install transifex-client`` or ``easy_install transifex-client``.
+        Installation
+        ----------
         
+        You can install the latest version of transifex-client running `pip install transifex-client` or `easy_install transifex-client`.
         
         Build transifex-client for Windows
-        ==================================
-        
-        1. Download transifex-client sources via git or github archive.
+        ----------------------------------
         
-           a. ``git clone https://github.com/transifex/transifex-client.git``
-           b. Download and unpack https://github.com/transifex/transifex-client/archive/master.zip
+        1.  Download transifex-client sources via git or github archive.
+            1.  `git clone https://github.com/transifex/transifex-client.git`
+            2.  Download and unpack <https://github.com/transifex/transifex-client/archive/master.zip>
         
-        2. Download and install Python_.
+        2.  Download and install [Python](https://www.python.org/downloads/windows/).
         
-           At this step choose right version of python: 2 or 3 and x86 or x86-64 instruction set.
+            At this step choose right version of python: 2 or 3 and x86 or x86-64 instruction set.
         
-           Make sure pip marked for installation(default for latest installers).
+            Make sure pip marked for installation(default for latest installers).
         
-        3. Install PyInstaller_.
+        3.  Install [PyInstaller](http://www.pyinstaller.org).
         
-           Suppose that Python installed to ``C:\\Program Files\\Python35-32``
+            Suppose that Python installed to `C:\\Program Files\\Python35-32`
         
-           Make ``python.exe`` accessible via PATH environment variable or cd to directory containing python.exe.
+            Make `python.exe` accessible via PATH environment variable or cd to directory containing python.exe.
         
-           ::
+                python -m pip install pyinstaller
         
-             python -m pip install pyinstaller
+            This command will install `PyInstaller` package and its dependencies.
         
-           This command will install ``PyInstaller`` package and its dependencies.
+        4.  Build `transifex-client` distribution.
         
-        4. Build ``transifex-client`` distribution.
+            Change directory to transifex-client folder and run command:
         
-           Change directory to transifex-client folder and run command:
+                python -m PyInstaller contrib/tx.spec
+                # or
+                pyinstaller contrib/tx.spec
         
-           ::
+        5.  `tx.exe`
         
-             python -m PyInstaller contrib/tx.spec
-             # or
-             pyinstaller contrib/tx.spec
+            `dist/tx.exe` will be created as the result of build process.
         
-        5. ``tx.exe``
         
-           ``dist/tx.exe`` will be created as the result of build process.
+        Getting Help
+        ---
+        You can always get additional help via [GitHub issues](https://github.com/transifex/txgh/issues) or [Transifex support](https://www.transifex.com/contact/)
         
+        License
+        ---
+        Transifex Client is primarily distributed under the terms of the GPL License (Version 2.0).
         
-        .. _Python: https://www.python.org/downloads/windows/
-        .. _PyInstaller: http://www.pyinstaller.org
+        See [LICENSE](https://github.com/transifex/transifex-client/blob/master/LICENSE) for details.
         
 Keywords: translation,localization,internationalization
 Platform: UNKNOWN
diff --git a/transifex_client.egg-info/SOURCES.txt b/transifex_client.egg-info/SOURCES.txt
index fc9876b..882f6f1 100644
--- a/transifex_client.egg-info/SOURCES.txt
+++ b/transifex_client.egg-info/SOURCES.txt
@@ -1,6 +1,6 @@
 LICENSE
 MANIFEST.in
-README.rst
+README.md
 requirements.txt
 setup.py
 tests/__init__.py
diff --git a/txclib/__init__.py b/txclib/__init__.py
index d5a6ece..793ef97 100644
--- a/txclib/__init__.py
+++ b/txclib/__init__.py
@@ -1,4 +1,4 @@
 # -*- coding: utf-8 -*-
 
 # https://www.python.org/dev/peps/pep-0440/#examples-of-compliant-version-schemes
-__version__ = '0.12.2'
+__version__ = '0.12.4'
diff --git a/txclib/cmdline.py b/txclib/cmdline.py
index 71c2d19..7011ff4 100755
--- a/txclib/cmdline.py
+++ b/txclib/cmdline.py
@@ -104,6 +104,7 @@ def main(argv=None):
     try:
         utils.exec_command(cmd, args[1:], path_to_tx)
     except SSLError as e:
+        logger.error("SSl error %s" % e)
         sys.exit(1)
     except utils.UnknownCommandError:
         logger.error("tx: Command %s not found" % cmd)
@@ -118,6 +119,7 @@ def main(argv=None):
             logger.error(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.
diff --git a/txclib/commands.py b/txclib/commands.py
index b99928e..7be513f 100644
--- a/txclib/commands.py
+++ b/txclib/commands.py
@@ -18,7 +18,6 @@ import os
 import re
 import shutil
 import sys
-from optparse import OptionParser, OptionGroup
 
 try:
     import configparser
@@ -28,7 +27,6 @@ except ImportError:
 from six.moves import input
 
 from txclib import utils, project
-from txclib.utils import parse_json, compile_json, files_in_project
 from txclib.config import OrderedRawConfigParser
 from txclib.exceptions import UnInitializedError
 from txclib.parsers import delete_parser, help_parser, parse_csv_option, \
@@ -48,30 +46,26 @@ def cmd_init(argv, path_to_tx):
     else:
         path_to_tx = os.getcwd()
 
-    if os.path.isdir(os.path.join(path_to_tx, ".tx")):
+    save = options.save
+    # if we already have a config file and we are not told to override it
+    # in the args we have to ask
+    if os.path.isdir(os.path.join(path_to_tx, ".tx")) and not save:
         logger.info("tx: There is already a tx folder!")
-        reinit = input("Do you want to delete it and "
-                       "reinit the project? [y/N]: ")
-        while (reinit != 'y' and reinit != 'Y' and reinit != 'N'
-               and reinit != 'n' and reinit != ''):
-            reinit = input("Do you want to delete it and "
-                           "reinit the project? [y/N]: ")
-        if not reinit or reinit in ['N', 'n', 'NO', 'no', 'No']:
+        if not utils.confirm(
+            prompt='Do you want to delete it and reinit the project?',
+            default=False
+        ):
             return
         # Clean the old settings
         # FIXME: take a backup
         else:
+            save = True
             rm_dir = os.path.join(path_to_tx, ".tx")
             shutil.rmtree(rm_dir)
 
     logger.info("Creating .tx folder...")
     os.mkdir(os.path.join(path_to_tx, ".tx"))
 
-    # Handle the credentials through transifexrc
-    home = os.path.expanduser("~")
-    txrc = os.path.join(home, ".transifexrc")
-    config = OrderedRawConfigParser()
-
     default_transifex = "https://www.transifex.com"
     transifex_host = options.host or input("Transifex instance [%s]: " %
                                            default_transifex)
@@ -85,6 +79,7 @@ def cmd_init(argv, path_to_tx):
     if not os.path.exists(config_file):
         # The path to the config file (.tx/config)
         logger.info("Creating skeleton...")
+        # Handle the credentials through transifexrc
         config = OrderedRawConfigParser()
         config.add_section('main')
         config.set('main', 'host', transifex_host)
@@ -95,8 +90,9 @@ def cmd_init(argv, path_to_tx):
         fh.close()
 
     prj = project.Project(path_to_tx)
-    prj.getset_host_credentials(transifex_host, user=options.user,
-                                password=options.password)
+    prj.getset_host_credentials(transifex_host, username=options.user,
+                                password=options.password,
+                                token=options.token, save=save)
     prj.save()
     logger.info("Done.")
 
@@ -213,7 +209,7 @@ def _auto_local(path_to_tx, resource, source_language, expression,
     # First, let's construct a dictionary of all matching files.
     # Note: Only the last matching file of a language will be stored.
     translation_files = {}
-    for f_path in files_in_project(curpath):
+    for f_path in utils.files_in_project(curpath):
         match = expr_rec.match(posix_path(f_path))
         if match:
             lang = match.group(1)
@@ -240,7 +236,6 @@ def _auto_local(path_to_tx, resource, source_language, expression,
             'file': os.path.relpath(source_file, curpath)})
 
     prj = project.Project(path_to_tx)
-    root_dir = os.path.abspath(path_to_tx)
 
     if execute:
         try:
@@ -342,6 +337,7 @@ def cmd_push(argv, path_to_tx):
     languages = parse_csv_option(options.languages)
     resources = parse_csv_option(options.resources)
     skip = options.skip_errors
+    xliff = options.xliff
     prj = project.Project(path_to_tx)
     if not (options.push_source or options.push_translations):
         parser.error("You need to specify at least one of the -s|--source, "
@@ -351,7 +347,8 @@ def cmd_push(argv, path_to_tx):
         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,
+        xliff=xliff
     )
     logger.info("Done.")
 
@@ -366,6 +363,8 @@ def cmd_pull(argv, path_to_tx):
     languages = parse_csv_option(options.languages)
     resources = parse_csv_option(options.resources)
     pseudo = options.pseudo
+    # Should we download as xliff?
+    xliff = options.xliff
     skip = options.skip_errors
     minimum_perc = options.minimum_perc or None
 
@@ -381,7 +380,7 @@ def cmd_pull(argv, path_to_tx):
         languages=languages, resources=resources, overwrite=options.overwrite,
         fetchall=options.fetchall, fetchsource=options.fetchsource,
         force=options.force, skip=skip, minimum_perc=minimum_perc,
-        mode=options.mode, pseudo=pseudo
+        mode=options.mode, pseudo=pseudo, xliff=xliff
     )
     logger.info("Done.")
 
diff --git a/txclib/parsers.py b/txclib/parsers.py
index b0a483d..b2c4647 100644
--- a/txclib/parsers.py
+++ b/txclib/parsers.py
@@ -67,6 +67,17 @@ def init_parser():
                       help="Specify username for Transifex server.")
     parser.add_option("--pass", action="store", dest="password", default=None,
                       help="Specify password for Transifex server.")
+    parser.add_option(
+        "--force-save",
+        action="store_true",
+        dest="save",
+        default=False,
+        help="Override .transifexrc file with the given credentials."
+    )
+
+    parser.add_option("--token", action="store", dest="token", default=None,
+                      help="Specify an api token.\nYou can get one from"
+                      " user's settings")
     return parser
 
 
@@ -118,6 +129,9 @@ def pull_parser():
             "'reviewed'). See http://bit.ly/pullmode for available values."
         )
     )
+    parser.add_option("-x", "--xliff", action="store_true", dest="xliff",
+                      default=False, help="Apply this option to download "
+                      "file as xliff.")
     return parser
 
 
@@ -156,6 +170,9 @@ def push_parser():
     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("-x", "--xliff", action="store_true", dest="xliff",
+                      default=False, help="Apply this option to upload "
+                      "file as xliff.")
     return parser
 
 
diff --git a/txclib/project.py b/txclib/project.py
index c71d1af..c105f23 100644
--- a/txclib/project.py
+++ b/txclib/project.py
@@ -11,6 +11,12 @@ import urllib3
 import six
 
 try:
+    import urlparse
+    from urllib import urlencode
+except:  # For Python 3
+    import urllib.parse as urlparse
+    from urllib.parse import urlencode
+try:
     import configparser
 except ImportError:
     import ConfigParser as configparser
@@ -24,8 +30,7 @@ from txclib.config import OrderedRawConfigParser, Flipdict, CERT_REQUIRED
 from txclib.log import logger
 from txclib.processors import visit_hostname
 from txclib.paths import posix_path, native_path, posix_sep
-
-
+from txclib.utils import confirm
 
 
 class ProjectNotInit(Exception):
@@ -147,36 +152,90 @@ class Project(object):
             mask = os.umask(0o077)
             open(txrc_file, 'w').close()
             os.umask(mask)
+            if os.path.exists(txrc_file):
+                logger.info('Created %s ' % txrc_file)
+            else:
+                logger.info('Could not create %s ' % txrc_file)
         return txrc_file
 
     def validate_config(self):
         """To ensure the json structure is correctly formed."""
         pass
 
-    def getset_host_credentials(self, host, user=None, password=None):
+    def getset_host_credentials(
+        self,
+        host,
+        username=None,
+        password=None,
+        token=None,
+        save=False
+    ):
         """Read .transifexrc and report user,
-        pass for a specific host else ask the user for input.
+        pass or a token for a specific host else ask the user for input.
         """
-        try:
-            username = self.txrc.get(host, 'username')
-            passwd = self.txrc.get(host, 'password')
-        except (configparser.NoOptionError, configparser.NoSectionError):
-            logger.info("No entry found for host %s. Creating..." % host)
-            username = user or input("Please enter your transifex username: ")
-            while (not username):
-                username = input("Please enter your transifex username: ")
-            passwd = password
-            while (not passwd):
-                passwd = getpass.getpass()
+        # from_config is a flag that tells us if we got the credentials
+        # from the config file
+        from_config = False
+        # first check if a token has been given it should override everything
+        if token:
+            password = token
+            username = 'api'
+        # if neither a token nor a username or a password were given
+        # try to get them from the rc file
+        elif not (username and password):
+            try:
+                username = self.txrc.get(host, 'username')
+                password = self.txrc.get(host, 'password')
+            except (configparser.NoOptionError, configparser.NoSectionError):
+                # if the rc has no credentials, we have to ask the user and
+                # update the rc file
+                save = True
+                # Ask the user if they have an api token
+                if confirm(
+                    prompt="\nDid you know that you can create an api"
+                    "token under your transifex user's settings?\n"
+                    "(Read more at https://docs.transifex.com/api/"
+                    "introduction#authentication)\n"
+                    "So, do you have an api token?",
+                    default=False
+
+                ):
+                    token_msg = "Please enter your api token: "
+                    while not token:
+                        token = input(token_msg)
+                    # Since we got a token, we use api as the username
+                    # and the token as the password
+                    username = 'api'
+                    password = token
+                else:
+                    username_msg = "Please enter your transifex username: "
+                    while not username:
+                        username = input(username_msg)
+                    while (not password):
+                        password = getpass.getpass()
+            else:
+                from_config = True
+
+        # lets see if there is a default username or a password
+        # unless we got the files from the config
+        if not from_config:
+            try:
+                username = self.txrc.get(host, 'username')
+                password = self.txrc.get(host, 'password')
+            except (configparser.NoOptionError, configparser.NoSectionError):
+                # if we do not have defaults, save the give credentials
+                save = True
 
+        if save:
             logger.info("Updating %s file..." % self.txrc_file)
-            self.txrc.add_section(host)
+            if not self.txrc.has_section(host):
+                logger.info("No entry found for host %s. Creating..." % host)
+                self.txrc.add_section(host)
             self.txrc.set(host, 'username', username)
-            self.txrc.set(host, 'password', passwd)
-            self.txrc.set(host, 'token', '')
+            self.txrc.set(host, 'password', password)
             self.txrc.set(host, 'hostname', host)
-
-        return username, passwd
+            self.save()
+        return username, password
 
     def set_remote_resource(self, resource, source_lang, i18n_type, host,
                             file_filter=None):
@@ -261,7 +320,7 @@ class Project(object):
             else:
                 return native_path(source_file)
 
-    def get_resource_files(self, resource):
+    def get_resource_files(self, resource, xliff=False):
         """Get a dict for all files assigned to a resource.
         First we calculate the files matching the file expression and
         then we apply all translation excpetions.
@@ -279,6 +338,9 @@ class Project(object):
                 file_filter = self.config.get(resource, "file_filter")
             except configparser.NoOptionError:
                 file_filter = "$^"
+            if xliff:
+                # update the file-path in case of xliff option
+                file_filter += '.xlf'
             source_lang = self.config.get(resource, "source_lang")
             source_file = self.get_source_file(resource)
             expr_re = utils.regex_from_filefilter(file_filter, self.root)
@@ -380,11 +442,12 @@ class Project(object):
 
     def pull(self, languages=[], resources=[], overwrite=True, fetchall=False,
              fetchsource=False, force=False, skip=False, minimum_perc=0,
-             mode=None, pseudo=False):
+             mode=None, pseudo=False, xliff=False):
         """Pull all translations file from transifex server."""
         self.minimum_perc = minimum_perc
         resource_list = self.get_chosen_resources(resources)
         skip_decode = False
+        params = {}
 
         if mode == 'reviewed':
             url = 'pull_reviewed_file'
@@ -472,8 +535,13 @@ class Project(object):
             if pull_languages:
                 logger.debug("Pulling languages for: %s" % pull_languages)
                 msg = "Pulling translations for resource %s (source: %s)"
+                if xliff:
+                    msg += " [xliff format]"
                 logger.info(msg % (resource, sfile))
 
+            if xliff:
+                params.update({'file': 'xliff'})
+
             for lang in pull_languages:
                 local_lang = lang
                 if lang in list(lang_map.values()):
@@ -496,7 +564,9 @@ class Project(object):
                     'force': force,
                     'mode': mode,
                 }
-                if not self._should_update_translation(**kwargs):
+
+                # xliff files should be always pulled
+                if not xliff and not self._should_update_translation(**kwargs):
                     msg = "Skipping '%s' translation (file: %s)."
                     logger.info(
                         msg % (utils.color_text(remote_lang, "RED"),
@@ -504,6 +574,9 @@ class Project(object):
                     )
                     continue
 
+                if xliff:
+                    local_file += '.xlf'
+
                 if not overwrite:
                     local_file = ("%s.new" % local_file)
                 logger.warning(
@@ -512,7 +585,8 @@ class Project(object):
                 )
                 try:
                     r, charset = self.do_url_request(
-                        url, language=remote_lang, skip_decode=skip_decode
+                        url, language=remote_lang, skip_decode=skip_decode,
+                        params=params
                     )
                 except Exception as e:
                     if isinstance(e, SSLError) or not skip:
@@ -562,20 +636,30 @@ class Project(object):
                     )
 
                     r, charset = self.do_url_request(
-                        url, language=remote_lang, skip_decode=skip_decode
+                        url, language=remote_lang, skip_decode=skip_decode,
+                        params=params
                     )
+                    if xliff:
+                        local_file += '.xlf'
+
                     self._save_file(local_file, charset, r)
 
     def push(self, source=False, translations=False, force=False,
-             resources=[], languages=[], skip=False, no_interactive=False):
+             resources=[], languages=[], skip=False, no_interactive=False,
+             xliff=False):
         """Push all the resources"""
         resource_list = self.get_chosen_resources(resources)
... 239 lines suppressed ...

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/python-modules/packages/transifex-client.git



More information about the Python-modules-commits mailing list