Exemplo n.º 1
0
    def _init(self, path_to_tx=None):
        # The path to the root of the project, where .tx lives!
        self.root = path_to_tx or find_dot_tx()
        logger.debug("Path to tx is %s." % self.root)
        if not self.root:
            MSG("Cannot find any .tx directory!")
            MSG("Run 'tx init' to initialize your project first!")
            raise ProjectNotInit()

        # The path to the config file (.tx/config)
        self.config_file = os.path.join(self.root, ".tx", "config")
        logger.debug("Config file is %s" % self.config_file)
        # Touch the file if it doesn't exist
        if not os.path.exists(self.config_file):
            MSG("Cannot find the config file (.tx/config)!")
            MSG("Run 'tx init' to fix this!")
            raise ProjectNotInit()

        # The dictionary which holds the config parameters after deser/tion.
        # Read the config in memory
        self.config = OrderedRawConfigParser()
        try:
            self.config.read(self.config_file)
        except Exception, err:
            MSG("WARNING: Cannot open/parse .tx/config file", err)
            MSG("Run 'tx init' to fix this!")
            raise ProjectNotInit()
Exemplo n.º 2
0
def main():
    # Pull latest translations
    cmd_pull(['-a'], find_dot_tx())

    print('Finding translations...')
    translations = {}
    for dirpath, _dirnames, filenames in os.walk(TRANSLATION_DIR):
        for filename in filenames:
            if os.path.splitext(filename)[1] != '{}po'.format(os.path.extsep):
                continue
            po = polib.pofile(os.path.join(dirpath, filename))
            entries = translations.setdefault(po.metadata['Language'], {})
            for entry in po:
                entries[entry.msgid] = entry.msgstr

    print('Generating new translation files...')
    for lang, entries in translations.items():
        filename = os.path.join(TINYMCE_DIR, 'langs', '{}.js'.format(lang))
        print(filename)
        with open(filename, 'w') as outfile:
            outfile.write(TEMPLATE.format(
                lang=lang,
                entries=json.dumps(entries, indent=0, separators=(',', ': '))
                ))
    print('Done.')
Exemplo n.º 3
0
def main():
    # Pull latest translations
    cmd_pull(['-a'], find_dot_tx())

    print('Finding translations...')
    translations = {}
    for dirpath, _dirnames, filenames in os.walk(TRANSLATION_DIR):
        for filename in filenames:
            print('Filename' + filename)
            if os.path.splitext(filename)[1] != '{}po'.format(os.path.extsep):
                continue
            po = polib.pofile(os.path.join(dirpath, filename))
            entries = translations.setdefault(po.metadata['Language'], {})
            for entry in po:
                entries[entry.msgid] = entry.msgstr

    print('Generating new translation files...')
    for lang, entries in translations.items():
        filename = os.path.join(TINYMCE_DIR, 'langs', '{}.js'.format(lang))
        print(filename)
        with open(filename, 'w') as outfile:
            outfile.write(
                TEMPLATE.format(lang=lang,
                                entries=json.dumps(entries,
                                                   indent=0,
                                                   separators=(',', ': '))))
    print('Done.')
Exemplo n.º 4
0
    def _init(self, path_to_tx=None):
        # The path to the root of the project, where .tx lives!
        self.root = path_to_tx or find_dot_tx()
        logger.debug("Path to tx is %s." % self.root)
        if not self.root:
            MSG("Cannot find any .tx directory!")
            MSG("Run 'tx init' to initialize your project first!")
            raise ProjectNotInit()

        # The path to the config file (.tx/config)
        self.config_file = os.path.join(self.root, ".tx", "config")
        logger.debug("Config file is %s" % self.config_file)
        # Touch the file if it doesn't exist
        if not os.path.exists(self.config_file):
            MSG("Cannot find the config file (.tx/config)!")
            MSG("Run 'tx init' to fix this!")
            raise ProjectNotInit()

        # The dictionary which holds the config parameters after deser/tion.
        # Read the config in memory
        self.config = OrderedRawConfigParser()
        try:
            self.config.read(self.config_file)
        except Exception, err:
            MSG("WARNING: Cannot open/parse .tx/config file", err)
            MSG("Run 'tx init' to fix this!")
            raise ProjectNotInit()
Exemplo n.º 5
0
 def _get_tx_dir_path(self, path_to_tx):
     """Check the .tx directory exists."""
     root_path = path_to_tx or utils.find_dot_tx()
     logger.debug("Path to tx is %s." % root_path)
     if not root_path:
         msg = "Cannot find any .tx directory!"
         raise ProjectNotInit(msg)
     return root_path
Exemplo n.º 6
0
 def _get_tx_dir_path(self, path_to_tx):
     """Check the .tx directory exists."""
     root_path = path_to_tx or utils.find_dot_tx()
     logger.debug("Path to tx is %s." % root_path)
     if not root_path:
         msg = "Cannot find any .tx directory!"
         raise ProjectNotInit(msg)
     return root_path
Exemplo n.º 7
0
def main(argv=None):
    """
    Here we parse the flags (short, long) and we instantiate the classes.
    """
    parser = tx_main_parser()
    options, rest = parser.parse_known_args()
    if not options.command:
        parser.print_help()
        sys.exit(1)

    utils.DISABLE_COLORS = options.color_disable

    # set log level
    if options.quiet:
        set_log_level('WARNING')
    elif options.debug:
        set_log_level('DEBUG')

    web.cacerts_file = options.cacert

    # find .tx
    path_to_tx = options.root_dir or utils.find_dot_tx()

    cmd = options.command
    try:
        utils.exec_command(cmd, rest, path_to_tx)
    except SSLError as e:
        logger.error("SSL error %s" % e)
    except utils.UnknownCommandError:
        logger.error("Command %s not found" % cmd)
    except AuthenticationError:
        authentication_failed_message = """
Error: Authentication failed. Please make sure your credentials are valid.
For more information, visit:
https://docs.transifex.com/client/client-configuration#-transifexrc.
"""
        logger.error(authentication_failed_message)
    except Exception as e:
        import traceback
        if options.trace:
            traceback.print_exc()
        else:
            msg = "Unknown error" if not str(e) else str(e)
            logger.error(msg)
    # The else statement will be executed only if the command raised no
    # exceptions. If an exception was raised, we want to return a non-zero exit
    # code
    else:
        return
    sys.exit(1)
Exemplo n.º 8
0
def main(argv=None):
    """
    Here we parse the flags (short, long) and we instantiate the classes.
    """
    parser = tx_main_parser()
    options, rest = parser.parse_known_args()
    if not options.command:
        parser.print_help()
        sys.exit(1)

    utils.DISABLE_COLORS = options.color_disable

    # set log level
    if options.quiet:
        set_log_level('WARNING')
    elif options.debug:
        set_log_level('DEBUG')

    # find .tx
    path_to_tx = options.root_dir or utils.find_dot_tx()

    cmd = options.command
    try:
        utils.exec_command(cmd, rest, path_to_tx)
    except SSLError as e:
        logger.error("SSL error %s" % e)
    except utils.UnknownCommandError:
        logger.error("Command %s not found" % cmd)
    except AuthenticationError:
        authentication_failed_message = """
Error: Authentication failed. Please make sure your credentials are valid.
For more information, visit:
https://docs.transifex.com/client/client-configuration#-transifexrc.
"""
        logger.error(authentication_failed_message)
    except Exception as e:
        import traceback
        if options.trace:
            traceback.print_exc()
        else:
            msg = "Unknown error" if not str(e) else str(e)
            logger.error(msg)
    # The else statement will be executed only if the command raised no
    # exceptions. If an exception was raised, we want to return a non-zero exit
    # code
    else:
        return
    sys.exit(1)
Exemplo n.º 9
0
def translations(data):
    if data["name"] != "django-countries":
        return

    if not ask("Pull translations from transifex and compile", default=True):
        return

    _handlers = logger.handlers
    logger.handlers = []
    try:
        cmd_pull(argv=["-a", "--minimum-perc=60"], path_to_tx=find_dot_tx())
    finally:
        logger.handlers = _handlers
    _cwd = os.getcwd()
    os.chdir(os.path.dirname(django_countries.__file__))
    try:
        call_command("compilemessages")
        execute_command(["git", "add", "locale"])
    finally:
        os.chdir(_cwd)
Exemplo n.º 10
0
def translations(data):
    if data['name'] != 'django-countries':
        return

    if not ask('Pull translations from transifex and compile', default=True):
        return

    _handlers = logger.handlers
    logger.handlers = []
    try:
        cmd_pull(argv=['-a', '--minimum-perc=60'], path_to_tx=find_dot_tx())
    finally:
        logger.handlers = _handlers

    _cwd = os.getcwd()
    os.chdir(os.path.dirname(django_countries.__file__))
    try:
        call_command('compilemessages')
        execute_command(['git', 'add', 'locale'])
    finally:
        os.chdir(_cwd)
Exemplo n.º 11
0
def translations(data):
    if data["name"] != "django-countries":
        return

    if not ask("Pull translations from transifex and compile", default=True):
        return

    _handlers = logger.handlers
    logger.handlers = []
    try:
        cmd_pull(argv=["-a", "--minimum-perc=60"], path_to_tx=find_dot_tx())
    finally:
        logger.handlers = _handlers

    _cwd = os.getcwd()
    os.chdir(os.path.dirname(django_countries.__file__))
    try:
        call_command("compilemessages")
        execute_command(["git", "add", "locale"])
    finally:
        os.chdir(_cwd)
Exemplo n.º 12
0
def main(argv=None):
    """
    Here we parse the flags (short, long) and we instantiate the classes.
    """
    if argv is None:
        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=txclib.__version__,
                          description=description)
    parser.disable_interspersed_args()
    parser.add_option("-d",
                      "--debug",
                      action="store_true",
                      dest="debug",
                      default=False,
                      help=("enable debug messages"))
    parser.add_option("-q",
                      "--quiet",
                      action="store_true",
                      dest="quiet",
                      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' or not sys.stdout.isatty()),
                      help="disable colors in the output of commands")
    (options, args) = parser.parse_args()

    if len(args) < 1:
        parser.error("No command was given")

    utils.DISABLE_COLORS = options.color_disable

    # set log level
    if options.quiet:
        set_log_level('WARNING')
    elif options.debug:
        set_log_level('DEBUG')

    # 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 SSLError as e:
        logger.error("SSl error %s" % e)
        sys.exit(1)
    except utils.UnknownCommandError:
        logger.error("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()
            logger.error(formatted_lines[-1])
        sys.exit(1)
def main(argv=None):
    """
    Export translation files and push them to Transifex
    The transifex password should be encrypted in .travis.yml
    If not, export exits early.
    """
    if argv is None:
        argv = sys.argv

    transifex_user = os.environ.get("TRANSIFEX_USER", "*****@*****.**")
    transifex_password = os.environ.get("TRANSIFEX_PASSWORD")

    if not transifex_user:
        print(
            yellow_light("WARNING! Transifex user not defined- "
                         "exiting early."))
        return 1

    if not transifex_password:
        print(
            yellow_light("WARNING! Transifex password not recognized- "
                         "exiting early."))
        return 1

    travis_home = os.environ.get("HOME", "~/")
    travis_build_dir = os.environ.get("TRAVIS_BUILD_DIR", "../..")
    travis_repo_slug = os.environ.get("TRAVIS_REPO_SLUG")
    travis_repo_owner = travis_repo_slug.split("/")[0]
    travis_repo_shortname = travis_repo_slug.split("/")[1]
    odoo_unittest = False
    odoo_exclude = os.environ.get("EXCLUDE")
    odoo_include = os.environ.get("INCLUDE")
    install_options = os.environ.get("INSTALL_OPTIONS", "").split()
    odoo_version = os.environ.get("VERSION")
    langs = parse_list(os.environ.get("LANG_ALLOWED", ""))

    if not odoo_version:
        # For backward compatibility, take version from parameter
        # if it's not globally set
        odoo_version = argv[1]
        print(
            yellow_light("WARNING: no env variable set for VERSION. "
                         "Using '%s'" % odoo_version))

    default_project_slug = "%s-%s" % (travis_repo_slug.replace(
        '/', '-'), odoo_version.replace('.', '-'))
    transifex_project_slug = os.environ.get("TRANSIFEX_PROJECT_SLUG",
                                            default_project_slug)
    transifex_project_name = "%s (%s)" % (travis_repo_shortname, odoo_version)
    transifex_organization = os.environ.get("TRANSIFEX_ORGANIZATION",
                                            travis_repo_owner)
    transifex_fill_up_resources = os.environ.get("TRANSIFEX_FILL_UP_RESOURCES",
                                                 "True")
    transifex_team = os.environ.get("TRANSIFEX_TEAM", "45447")
    repository_url = "https://github.com/%s" % travis_repo_slug

    odoo_full = os.environ.get("ODOO_REPO", "odoo/odoo")
    server_path = get_server_path(odoo_full, odoo_version, travis_home)
    addons_path = get_addons_path(travis_home, travis_build_dir, server_path)
    addons_list = get_addons_to_check(travis_build_dir, odoo_include,
                                      odoo_exclude)
    addons_path_list = parse_list(addons_path)
    all_depends = get_depends(addons_path_list, addons_list)
    main_modules = set(os.listdir(travis_build_dir))
    main_depends = main_modules & all_depends
    addons_list = list(main_depends)
    addons = ','.join(addons_list)
    create_server_conf({'addons_path': addons_path}, odoo_version)

    print("\nWorking in %s" % travis_build_dir)
    print("Using repo %s and addons path %s" % (odoo_full, addons_path))

    if not addons:
        print(yellow_light("WARNING! Nothing to translate- exiting early."))
        return 0

    # Create Transifex project if it doesn't exist
    print()
    print(yellow("Creating Transifex project if it doesn't exist"))
    auth = (transifex_user, transifex_password)
    api_url = "https://www.transifex.com/api/2/"
    api = API(api_url, auth=auth)
    project_data = {
        "slug": transifex_project_slug,
        "name": transifex_project_name,
        "source_language_code": "en",
        "description": transifex_project_name,
        "repository_url": repository_url,
        "organization": transifex_organization,
        "license": "permissive_open_source",
        "fill_up_resources": transifex_fill_up_resources,
        "team": transifex_team,
    }
    try:
        api.project(transifex_project_slug).get()
        print('This Transifex project already exists.')
    except exceptions.HttpClientError:
        try:
            api.projects.post(project_data)
            print('Transifex project has been successfully created.')
        except exceptions.HttpClientError:
            print('Transifex organization: %s' % transifex_organization)
            print('Transifex username: %s' % transifex_user)
            print('Transifex project slug: %s' % transifex_project_slug)
            print(
                red('Error: Authentication failed. Please verify that '
                    'Transifex organization, user and password are '
                    'correct. You can change these variables in your '
                    '.travis.yml file.'))
            raise

    print("\nModules to translate: %s" % addons)

    # Install the modules on the database
    database = "openerp_test"
    script_name = get_server_script(odoo_version)
    setup_server(database, odoo_unittest, addons, server_path, script_name,
                 addons_path, install_options, addons_list)

    # Initialize Transifex project
    print()
    print(yellow('Initializing Transifex project'))
    init_args = [
        '--host=https://www.transifex.com',
        '--user=%s' % transifex_user,
        '--pass=%s' % transifex_password
    ]
    commands.cmd_init(init_args, path_to_tx=None)
    path_to_tx = utils.find_dot_tx()

    # Use by default version 10 connection context
    connection_context = context_mapping.get(odoo_version, Odoo10Context)
    with connection_context(server_path, addons_path, database) \
            as odoo_context:
        for module in addons_list:
            print()
            print(yellow("Obtaining POT file for %s" % module))
            i18n_folder = os.path.join(travis_build_dir, module, 'i18n')
            source_filename = os.path.join(i18n_folder, module + ".pot")
            # Create i18n/ directory if doesn't exist
            if not os.path.exists(os.path.dirname(source_filename)):
                os.makedirs(os.path.dirname(source_filename))
            with open(source_filename, 'w') as f:
                f.write(odoo_context.get_pot_contents(module))
            # Put the correct timestamp for letting known tx client which
            # translations to update
            for po_file_name in os.listdir(i18n_folder):
                if not po_file_name.endswith('.po'):
                    continue
                if langs and os.path.splitext(po_file_name)[0] not in langs:
                    # Limit just allowed languages if is defined
                    os.remove(os.path.join(i18n_folder, po_file_name))
                    continue
                po_file_name = os.path.join(i18n_folder, po_file_name)
                command = [
                    'git', 'log', '--pretty=format:%cd', '-n1', '--date=raw',
                    po_file_name
                ]
                timestamp = float(subprocess.check_output(command).split()[0])
                # This converts to UTC the timestamp
                timestamp = time.mktime(time.gmtime(timestamp))
                os.utime(po_file_name, (timestamp, timestamp))

            print()
            print(yellow("Linking POT file and Transifex resource"))
            set_args = [
                '-t', 'PO', '--auto-local', '-r',
                '%s.%s' % (transifex_project_slug, module),
                '%s/i18n/<lang>.po' % module, '--source-lang', 'en',
                '--source-file', source_filename, '--execute'
            ]
            commands.cmd_set(set_args, path_to_tx)

    print()
    print(yellow('Pushing translation files to Transifex'))
    push_args = ['-s', '-t', '--skip']
    commands.cmd_push(push_args, path_to_tx)

    return 0
import requests
from txclib.parsers import status_parser
from txclib.project import Project
from txclib.utils import find_dot_tx

project_slug = 'documentation-5'
organization_slug = 'opendatasoft'

prj = Project(find_dot_tx())

api_auth = prj.getset_host_credentials('https://api.transifex.com')

offset = 0
remote_resources = []
while True:
    r = requests.get(
        'https://api.transifex.com/organizations/{}/projects/{}/resources/?offset={}'
        .format(organization_slug, project_slug, offset),
        auth=api_auth)
    results = r.json()
    if len(results) == 0:
        break
    remote_resources.extend(results)
    offset += 100

remote_resources_set = set([res['slug'] for res in remote_resources])

local_resources_set = set(
    [res.split('.')[1] for res in prj.get_chosen_resources([])])

print "remote resources count: {}".format(len(remote_resources_set))
import requests
from txclib.parsers import status_parser
from txclib.project import Project
from txclib.utils import find_dot_tx

project_slug = 'documentation-5'
organization_slug = 'opendatasoft'


prj = Project(find_dot_tx())

api_auth = prj.getset_host_credentials('https://api.transifex.com')

offset = 0
remote_resources = []
while True:
  r = requests.get('https://api.transifex.com/organizations/{}/projects/{}/resources/?offset={}'.format(organization_slug, project_slug, offset), auth=api_auth)
  results = r.json()
  if len(results) == 0:
    break
  remote_resources.extend(results)
  offset += 100

remote_resources_set = set([res['slug'] for res in remote_resources])

local_resources_set = set([res.split('.')[1] for res in prj.get_chosen_resources([])])

print "remote resources count: {}".format(len(remote_resources_set))
print "local resources count: {}".format(len(local_resources_set))

outdated_resources = remote_resources_set - local_resources_set
Exemplo n.º 16
0
def main(argv=None):
    """
    Export translation files and push them to Transifex
    The transifex password should be encrypted in .travis.yml
    If not, export exits early.
    """
    if argv is None:
        argv = sys.argv

    transifex_user = os.environ.get("TRANSIFEX_USER")
    transifex_password = os.environ.get("TRANSIFEX_PASSWORD")

    if not transifex_user:
        print(
            yellow_light("WARNING! Transifex user not defined- "
                         "exiting early."))
        return 1

    if not transifex_password:
        print(
            yellow_light("WARNING! Transifex password not recognized- "
                         "exiting early."))
        return 1

    travis_home = os.environ.get("HOME", "~/")
    travis_build_dir = os.environ.get("TRAVIS_BUILD_DIR", "../..")
    travis_repo_slug = os.environ.get("TRAVIS_REPO_SLUG")
    travis_repo_owner = travis_repo_slug.split("/")[0]
    travis_repo_shortname = travis_repo_slug.split("/")[1]
    odoo_unittest = False
    odoo_exclude = os.environ.get("EXCLUDE")
    odoo_include = os.environ.get("INCLUDE")
    install_options = os.environ.get("INSTALL_OPTIONS", "").split()
    odoo_version = os.environ.get("VERSION")

    if not odoo_version:
        # For backward compatibility, take version from parameter
        # if it's not globally set
        odoo_version = sys.argv[1]
        print(
            yellow_light("WARNING: no env variable set for VERSION. "
                         "Using '%s'" % odoo_version))

    default_project_slug = "%s-%s" % (travis_repo_slug.replace(
        '/', '-'), odoo_version.replace('.', '-'))
    transifex_project_slug = os.environ.get("TRANSIFEX_PROJECT_SLUG",
                                            default_project_slug)
    transifex_project_name = "%s (%s)" % (travis_repo_shortname, odoo_version)
    transifex_organization = os.environ.get("TRANSIFEX_ORGANIZATION",
                                            travis_repo_owner)
    transifex_fill_up_resources = os.environ.get("TRANSIFEX_FILL_UP_RESOURCES",
                                                 "True")
    transifex_team = os.environ.get("TRANSIFEX_TEAM", "23907")
    repository_url = "https://github.com/%s" % travis_repo_slug

    odoo_full = os.environ.get("ODOO_REPO", "odoo/odoo")
    server_path = get_server_path(odoo_full, odoo_version, travis_home)
    addons_path = get_addons_path(travis_home, travis_build_dir, server_path)
    addons_list = get_addons_to_check(travis_build_dir, odoo_include,
                                      odoo_exclude)
    addons = ','.join(addons_list)

    print("\nWorking in %s" % travis_build_dir)
    print("Using repo %s and addons path %s" % (odoo_full, addons_path))

    if not addons:
        print(yellow_light("WARNING! Nothing to translate- exiting early."))
        return 0

    # Create Transifex project if it doesn't exist
    print()
    print(yellow("Creating Transifex project if it doesn't exist"))
    auth = (transifex_user, transifex_password)
    api_url = "https://www.transifex.com/api/2/"
    api = API(api_url, auth=auth)
    project_data = {
        "slug": transifex_project_slug,
        "name": transifex_project_name,
        "source_language_code": "en",
        "description": transifex_project_name,
        "repository_url": repository_url,
        "organization": transifex_organization,
        "license": "permissive_open_source",
        "fill_up_resources": transifex_fill_up_resources,
        "team": transifex_team,
    }
    try:
        api.project(transifex_project_slug).get()
        print('This Transifex project already exists.')
    except exceptions.HttpClientError:
        try:
            api.projects.post(project_data)
            print('Transifex project has been successfully created.')
        except exceptions.HttpClientError:
            print('Transifex organization: %s' % transifex_organization)
            print('Transifex username: %s' % transifex_user)
            print('Transifex project slug: %s' % transifex_project_slug)
            print(
                red('Error: Authentication failed. Please verify that '
                    'Transifex organization, user and password are '
                    'correct. You can change these variables in your '
                    '.travis.yml file.'))
            raise

    print("\nModules to translate: %s" % addons)

    # Install the modules on the database
    database = "openerp_i18n"
    setup_server(database, odoo_unittest, addons, server_path, addons_path,
                 install_options, addons_list)

    # Initialize Transifex project
    print()
    print(yellow('Initializing Transifex project'))
    init_args = [
        '--host=https://www.transifex.com',
        '--user=%s' % transifex_user,
        '--pass=%s' % transifex_password
    ]
    commands.cmd_init(init_args, path_to_tx=None)
    path_to_tx = utils.find_dot_tx()

    connection_context = context_mapping[odoo_version]
    with connection_context(server_path, addons_path, database) \
            as odoo_context:
        for module in addons_list:
            print()
            print(yellow("Downloading PO file for %s" % module))
            source_filename = os.path.join(travis_build_dir, module, 'i18n',
                                           module + ".pot")
            # Create i18n/ directory if doesn't exist
            if not os.path.exists(os.path.dirname(source_filename)):
                os.makedirs(os.path.dirname(source_filename))
            with open(source_filename, 'w') as f:
                f.write(odoo_context.get_pot_contents(module))

            print()
            print(yellow("Linking PO file and Transifex resource"))
            set_args = [
                '-t', 'PO', '--auto-local', '-r',
                '%s.%s' % (transifex_project_slug, module),
                '%s/i18n/<lang>.po' % module, '--source-lang', 'en',
                '--source-file', source_filename, '--execute'
            ]
            commands.cmd_set(set_args, path_to_tx)

    print()
    print(yellow('Pushing translation files to Transifex'))
    push_args = ['-s', '-t', '--skip']
    commands.cmd_push(push_args, path_to_tx)

    return 0
Exemplo n.º 17
0
def main():
    """
    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`"
    argv = sys.argv[1:]
    parser = OptionParser(
        usage=usage, version=get_version(), description=description
    )
    parser.disable_interspersed_args()
    parser.add_option(
        "-d", "--debug", action="store_true", dest="debug",
        default=False, help=("enable debug messages")
    )
    parser.add_option(
        "-q", "--quiet", action="store_true", dest="quiet",
        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' or not sys.stdout.isatty()),
        help="disable colors in the output of commands"
    )
    (options, args) = parser.parse_args()

    if len(args) < 1:
        parser.error("No command was given")

    utils.DISABLE_COLORS = options.color_disable

    # set log level
    if options.quiet:
        set_log_level('WARNING')
    elif options.debug:
        set_log_level('DEBUG')

    # 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 utils.UnknownCommandError:
        logger.error("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()
            logger.error(formatted_lines[-1])
        sys.exit(1)
def main(argv=None):
    """
    Export translation files and push them to Transifex
    The transifex password should be encrypted in .travis.yml
    If not, export exits early.
    """
    if argv is None:
        argv = sys.argv

    transifex_user = os.environ.get("TRANSIFEX_USER")
    transifex_password = os.environ.get("TRANSIFEX_PASSWORD")

    if not transifex_user:
        print(yellow_light("WARNING! Transifex user not defined- "
              "exiting early."))
        return 1

    if not transifex_password:
        print(yellow_light("WARNING! Transifex password not recognized- "
              "exiting early."))
        return 1

    travis_home = os.environ.get("HOME", "~/")
    travis_dependencies_dir = os.path.join(travis_home, 'dependencies')
    travis_build_dir = os.environ.get("TRAVIS_BUILD_DIR", "../..")
    travis_repo_slug = os.environ.get("TRAVIS_REPO_SLUG")
    travis_repo_owner = travis_repo_slug.split("/")[0]
    travis_repo_shortname = travis_repo_slug.split("/")[1]
    odoo_unittest = False
    odoo_exclude = os.environ.get("EXCLUDE")
    odoo_include = os.environ.get("INCLUDE")
    install_options = os.environ.get("INSTALL_OPTIONS", "").split()
    odoo_version = os.environ.get("VERSION")

    if not odoo_version:
        # For backward compatibility, take version from parameter
        # if it's not globally set
        odoo_version = argv[1]
        print(yellow_light("WARNING: no env variable set for VERSION. "
              "Using '%s'" % odoo_version))

    default_project_slug = "%s-%s" % (travis_repo_slug.replace('/', '-'),
                                      odoo_version.replace('.', '-'))
    transifex_project_slug = os.environ.get("TRANSIFEX_PROJECT_SLUG",
                                            default_project_slug)
    transifex_project_name = "%s (%s)" % (travis_repo_shortname, odoo_version)
    transifex_organization = os.environ.get("TRANSIFEX_ORGANIZATION",
                                            travis_repo_owner)
    transifex_fill_up_resources = os.environ.get(
        "TRANSIFEX_FILL_UP_RESOURCES", "True"
    )
    transifex_team = os.environ.get(
        "TRANSIFEX_TEAM", "23907"
    )
    repository_url = "https://github.com/%s" % travis_repo_slug

    odoo_full = os.environ.get("ODOO_REPO", "odoo/odoo")
    server_path = get_server_path(odoo_full, odoo_version, travis_home)
    addons_path = get_addons_path(travis_dependencies_dir,
                                  travis_build_dir,
                                  server_path)
    addons_list = get_addons_to_check(travis_build_dir, odoo_include,
                                      odoo_exclude)
    addons = ','.join(addons_list)
    create_server_conf({'addons_path': addons_path}, odoo_version)

    print("\nWorking in %s" % travis_build_dir)
    print("Using repo %s and addons path %s" % (odoo_full, addons_path))

    if not addons:
        print(yellow_light("WARNING! Nothing to translate- exiting early."))
        return 0

    # Create Transifex project if it doesn't exist
    print()
    print(yellow("Creating Transifex project if it doesn't exist"))
    auth = (transifex_user, transifex_password)
    api_url = "https://www.transifex.com/api/2/"
    api = API(api_url, auth=auth)
    project_data = {"slug": transifex_project_slug,
                    "name": transifex_project_name,
                    "source_language_code": "en",
                    "description": transifex_project_name,
                    "repository_url": repository_url,
                    "organization": transifex_organization,
                    "license": "permissive_open_source",
                    "fill_up_resources": transifex_fill_up_resources,
                    "team": transifex_team,
                    }
    try:
        api.project(transifex_project_slug).get()
        print('This Transifex project already exists.')
    except exceptions.HttpClientError:
        try:
            api.projects.post(project_data)
            print('Transifex project has been successfully created.')
        except exceptions.HttpClientError:
            print('Transifex organization: %s' % transifex_organization)
            print('Transifex username: %s' % transifex_user)
            print('Transifex project slug: %s' % transifex_project_slug)
            print(red('Error: Authentication failed. Please verify that '
                      'Transifex organization, user and password are '
                      'correct. You can change these variables in your '
                      '.travis.yml file.'))
            raise

    print("\nModules to translate: %s" % addons)

    # Install the modules on the database
    database = "openerp_i18n"
    setup_server(database, odoo_unittest, addons, server_path, addons_path,
                 install_options, addons_list)

    # Initialize Transifex project
    print()
    print(yellow('Initializing Transifex project'))
    init_args = ['--host=https://www.transifex.com',
                 '--user=%s' % transifex_user,
                 '--pass=%s' % transifex_password]
    commands.cmd_init(init_args, path_to_tx=None)
    path_to_tx = utils.find_dot_tx()

    connection_context = context_mapping[odoo_version]
    with connection_context(server_path, addons_path, database) \
            as odoo_context:
        for module in addons_list:
            print()
            print(yellow("Downloading POT file for %s" % module))
            source_filename = os.path.join(travis_build_dir, module, 'i18n',
                                           module + ".pot")
            # Create i18n/ directory if doesn't exist
            if not os.path.exists(os.path.dirname(source_filename)):
                os.makedirs(os.path.dirname(source_filename))
            with open(source_filename, 'w') as f:
                f.write(odoo_context.get_pot_contents(module))

            print()
            print(yellow("Linking POT file and Transifex resource"))
            set_args = ['-t', 'PO',
                        '--auto-local',
                        '-r', '%s.%s' % (transifex_project_slug, module),
                        '%s/i18n/<lang>.po' % module,
                        '--source-lang', 'en',
                        '--source-file', source_filename,
                        '--execute']
            commands.cmd_set(set_args, path_to_tx)

    print()
    print(yellow('Pushing translation files to Transifex'))
    push_args = ['-s', '-t', '--skip']
    commands.cmd_push(push_args, path_to_tx)

    return 0
Exemplo n.º 19
0
def main(argv):
    path_to_tx = utils.find_dot_tx()

    check = UiLanguagesCheck(path_to_tx)
    check.run()