コード例 #1
0
def _set_source_file(path_to_tx, resource, lang, path_to_file):
    """Reusable method to set source file."""
    proj, res = resource.split('.')
    if not proj or not res:
        raise Exception("\"%s.%s\" is not a valid resource identifier. "
                        "It should be in the following format "
                        "project_slug.resource_slug." %
                        (proj, res))
    if not lang:
        raise Exception("You haven't specified a source language.")

    try:
        _go_to_dir(path_to_tx)
    except UnInitializedError as e:
        utils.logger.error(e)
        return

    if not os.path.exists(path_to_file):
        raise Exception("tx: File ( %s ) does not exist." %
                        os.path.join(path_to_tx, path_to_file))

    # instantiate the project.Project
    prj = project.Project(path_to_tx)
    root_dir = os.path.abspath(path_to_tx)

    if root_dir not in os.path.normpath(os.path.abspath(path_to_file)):
        raise Exception("File must be under the project root directory.")

    logger.info("Setting source file for resource %s.%s ( %s -> %s )." % (
        proj, res, lang, path_to_file))

    path_to_file = os.path.relpath(path_to_file, root_dir)

    prj = project.Project(path_to_tx)

    # FIXME: Check also if the path to source file already exists.
    try:
        try:
            prj.config.get("%s.%s" % (proj, res), "source_file")
        except configparser.NoSectionError:
            prj.config.add_section("%s.%s" % (proj, res))
        except configparser.NoOptionError:
            pass
    finally:
        prj.config.set(
            "%s.%s" % (proj, res), "source_file", posix_path(path_to_file)
        )
        prj.config.set("%s.%s" % (proj, res), "source_lang", lang)

    prj.save()
コード例 #2
0
ファイル: commands.py プロジェクト: surkova/transifex-client
def cmd_pull(argv, path_to_tx):
    """Pull files from remote server to local repository"""
    parser = pull_parser()
    (options, args) = parser.parse_args(argv)
    if options.fetchall and options.languages:
        parser.error("You can't user a language filter along with the "
                     "-a|--all option")
    languages = parse_csv_option(options.languages)
    resources = parse_csv_option(options.resources)
    pseudo = options.pseudo
    skip = options.skip_errors
    minimum_perc = options.minimum_perc or None

    try:
        _go_to_dir(path_to_tx)
    except UnInitializedError as e:
        utils.logger.error(e)
        return

    # instantiate the project.Project
    prj = project.Project(path_to_tx)
    prj.pull(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)
    logger.info("Done.")
コード例 #3
0
def home(name=None):
    "Print status of current project"
    from txclib import get_version
    txc_version = get_version()

    prj = project.Project(path_to_tx)

    # Let's create a resource list from our config file
    res_list = []
    prev_proj = ''
    for idx, res in enumerate(prj.get_resource_list()):
        hostname = prj.get_resource_host(res)
        p, r = res.split('.')
        p_url = '%s/projects/p/%s' % (hostname, p)
        r_url = '%s/resource/%s' % (p_url, r)
        sfile = prj.get_resource_option(res, 'source_file') or "N/A"
        expr = prj.config.get(res, "file_filter").replace('<lang>', '<span class="lang">&lt;lang&gt;</span>')
        expr_highlight = expr.replace('<lang>', '<span class="lang">&lt;lang&gt;</span>')
        res_list.append({'id': res,
                         'p_name': p,
                         'p_changed': (res_list and p != res_list[-1]['p_name']),
                         'p_url': p_url,
                         'r_name': r,
                         'r_url': r_url,
                         'source_file': sfile,
                         'expr': expr,
                         'expr_highlight': expr_highlight})
    res_list = sorted(res_list)

    return render_template('home.html',
        res_list=res_list, txc_version=txc_version)
コード例 #4
0
def pull(path, lang):
    skip_decode = False
    params = {}
    parallel = True

    prj = project.Project(path)
    resource_list = prj.get_chosen_resources([])
    for resource in resource_list:
        project_slug, resource_slug = resource.split(".", 1)
        host = prj.get_resource_host(resource)
        prj._set_url_info(host=host,
                          project=project_slug,
                          resource=resource_slug)

        files = prj.get_resource_files(resource)
        url = prj._get_url_by_pull_mode(None)
        local_file = files.get(lang)
        prj.do_url_request(
            url,
            language=lang,
            skip_decode=skip_decode,
            params=params,
            parallel=parallel,
            callback=prj._save_file,
            callback_args={"local_file": local_file},
        )

    perform_parallel_requests()
コード例 #5
0
ファイル: commands.py プロジェクト: club9822/rest
def cmd_push(argv, path_to_tx):
    """Push local files to remote server"""
    parser = push_parser()
    options = parser.parse_args(argv)
    force_creation = options.force_creation
    languages = parse_csv_option(options.languages)
    resources = parse_csv_option(options.resources)
    skip = options.skip_errors
    xliff = options.xliff
    parallel = options.parallel
    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, "
                     "-t|--translations flags with the push command.")

    branch = get_branch_from_options(options, prj.root)
    prj.push(force=force_creation,
             resources=resources,
             languages=languages,
             skip=skip,
             source=options.push_source,
             translations=options.push_translations,
             no_interactive=options.no_interactive,
             xliff=xliff,
             branch=branch,
             parallel=parallel)
    logger.info("Done.")
コード例 #6
0
ファイル: commands.py プロジェクト: club9822/rest
def _set_translation(path_to_tx, resource, lang, path_to_file):
    """Reusable method to set translation file."""

    proj, res = resource.split('.')
    if not project or not resource:
        raise Exception("\"%s\" is not a valid resource identifier. "
                        "It should be in the following format "
                        "project_slug.resource_slug." % resource)

    _go_to_dir(path_to_tx)

    # Warn the customuser if the file doesn't exist
    if not os.path.exists(path_to_file):
        logger.info("Warning: File '%s' doesn't exist." % path_to_file)

    # instantiate the project.Project
    prj = project.Project(path_to_tx)
    root_dir = os.path.abspath(path_to_tx)

    if root_dir not in os.path.normpath(os.path.abspath(path_to_file)):
        raise Exception("File must be under the project root directory.")

    if lang == prj.config.get("%s.%s" % (proj, res), "source_lang"):
        raise Exception("tx: You cannot set translation file for "
                        "the source language. Source languages contain "
                        "the strings which will be translated!")

    logger.info("Updating translations for resource %s ( %s -> %s )." %
                (resource, lang, path_to_file))
    path_to_file = os.path.relpath(path_to_file, root_dir)
    prj.config.set("%s.%s" % (proj, res), "trans.%s" % lang,
                   posix_path(path_to_file))

    prj.save()
コード例 #7
0
def cmd_pull(argv, path_to_tx):
    """Pull files from remote server to local repository"""
    parser = pull_parser()
    options = parser.parse_args(argv)
    if options.fetchall and options.languages:
        parser.error("You can't user a language filter along with the "
                     "-a|--all option")
    languages = parse_csv_option(options.languages)
    resources = parse_csv_option(options.resources)
    pseudo = options.pseudo
    # Should we download as xliff?
    xliff = options.xliff
    parallel = options.parallel
    skip = options.skip_errors
    minimum_perc = options.minimum_perc or None

    _go_to_dir(path_to_tx)

    # instantiate the project.Project
    prj = project.Project(path_to_tx)
    branch = get_branch_from_options(options, prj.root)
    prj.pull(
        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, xliff=xliff, branch=branch,
        parallel=parallel, no_interactive=options.no_interactive,
    )
    logger.info("Done.")
コード例 #8
0
def cmd_status(argv, path_to_tx):
    """Print status of current project"""
    parser = status_parser()
    options = parser.parse_args(argv)
    resources = parse_csv_option(options.resources)
    prj = project.Project(path_to_tx)
    resources = prj.get_chosen_resources(resources)
    resources_num = len(resources)
    for idx, res in enumerate(resources):
        p, r = res.split('.')
        print("%s -> %s (%s of %s)" % (p, r, idx + 1, resources_num))
        print("Translation Files:")
        slang = prj.get_resource_option(res, 'source_lang')
        sfile = prj.get_resource_option(res, 'source_file') or "N/A"
        lang_map = prj.get_resource_lang_mapping(res)
        print(" - %s: %s (%s)" % (utils.color_text(slang, "RED"),
              sfile, utils.color_text("source", "YELLOW")))
        files = prj.get_resource_files(res)
        fkeys = list(files.keys())
        fkeys.sort()
        for lang in fkeys:
            local_lang = lang
            if lang in list(lang_map.values()):
                local_lang = lang_map.flip[lang]
            print(" - %s: %s" % (utils.color_text(local_lang, "RED"),
                  files[lang]))
        print("")
コード例 #9
0
 def pull():
     #pull all selected resources
     #resources are all in one string and we split them by *//
     resourceLink = request.form["resources"]
     resources = resourceLink.split("*//")
     prj = project.Project(path_to_tx)
     prj.pull(resources=resources, fetchall=True, skip=True)
     return jsonify(result="OK")
コード例 #10
0
ファイル: commands.py プロジェクト: xrg/transifex-client
def cmd_init(argv, path_to_tx):
    "Initialize a new transifex project."
    parser = init_parser()
    (options, args) = parser.parse_args(argv)
    if len(args) > 1:
        parser.error("Too many arguments were provided. Aborting...")
    if args:
        path_to_tx = args[0]
    else:
        path_to_tx = os.getcwd()

    if os.path.isdir(os.path.join(path_to_tx,".tx")):
        logger.info("tx: There is already a tx folder!")
        reinit = raw_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 = raw_input("Do you want to delete it and reinit the project? [y/N]: ")
        if not reinit or reinit in ['N', 'n', 'NO', 'no', 'No']:
            return
        # Clean the old settings
        # FIXME: take a backup
        else:
            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 raw_input("Transifex instance [%s]: " % default_transifex)

    if not transifex_host:
        transifex_host = default_transifex
    if not transifex_host.startswith(('http://', 'https://')):
        transifex_host = 'https://' + transifex_host

    config_file = os.path.join(path_to_tx, ".tx", "config")
    if not os.path.exists(config_file):
        # The path to the config file (.tx/config)
        logger.info("Creating skeleton...")
        config = OrderedRawConfigParser()
        config.add_section('main')
        config.set('main', 'host', transifex_host)
        # Touch the file if it doesn't exist
        logger.info("Creating config file...")
        fh = open(config_file, 'w')
        config.write(fh)
        fh.close()

    prj = project.Project(path_to_tx)
    prj.getset_host_credentials(transifex_host, user=options.user,
        password=options.password)
    prj.save()
    logger.info("Done.")
コード例 #11
0
def pull():

    resourceLink = request.form["resources"]
    resources = resourceLink.split("*//")
    prj = project.Project(path_to_tx)
    #resource = request.args.get('resource')
    logger.info(resources[-1])
    #prj.pull(resources=[resource], fetchall=True, skip=True)
    return jsonify(result="OK")
コード例 #12
0
 def modify_expr():
     """Modify the file filter of a resource."""
     prj = project.Project(path_to_tx)
     res_id = request.form['res_id']
     expr = request.form['value']
     logger.info("Changing expression of %s to %s" % (res_id, expr))
     prj.config.set("%s" % res_id, "file_filter", expr)
     prj.save()
     return expr
コード例 #13
0
ファイル: commands.py プロジェクト: xrg/transifex-client
def _auto_remote(path_to_tx, url):
    """
    Initialize a remote release/project/resource to the current directory.
    """
    logger.info("Auto configuring local project from remote URL...")

    type, vars = utils.parse_tx_url(url)
    prj = project.Project(path_to_tx)
    username, password = prj.getset_host_credentials(vars['hostname'])

    if type == 'project':
        logger.info("Getting details for project %s" % vars['project'])
        proj_info = utils.get_details('project_details',
            username, password,
            hostname = vars['hostname'], project = vars['project'])
        resources = [ '.'.join([vars['project'], r['slug']]) for r in proj_info['resources'] ]
        logger.info("%s resources found. Configuring..." % len(resources))
    elif type == 'release':
        logger.info("Getting details for release %s" % vars['release'])
        rel_info = utils.get_details('release_details',
            username, password, hostname = vars['hostname'],
            project = vars['project'], release = vars['release'])
        resources = []
        for r in rel_info['resources']:
            if r.has_key('project'):
                resources.append('.'.join([r['project']['slug'], r['slug']]))
            else:
                resources.append('.'.join([vars['project'], r['slug']]))
        logger.info("%s resources found. Configuring..." % len(resources))
    elif type == 'resource':
        logger.info("Getting details for resource %s" % vars['resource'])
        resources = [ '.'.join([vars['project'], vars['resource']]) ]
    else:
        raise("Url '%s' is not recognized." % url)

    for resource in resources:
        logger.info("Configuring resource %s." % resource)
        proj, res = resource.split('.')
        res_info = utils.get_details('resource_details',
             username, password, hostname = vars['hostname'],
             project = proj, resource=res)
        try:
            source_lang = res_info['source_language_code']
            i18n_type = res_info['i18n_type']
        except KeyError:
            raise Exception("Remote server seems to be running an unsupported version"
                " of Transifex. Either update your server software of fallback"
                " to a previous version of transifex-client.")
        prj.set_remote_resource(
            resource=resource,
            host = vars['hostname'],
            source_lang = source_lang,
            i18n_type = i18n_type)

    prj.save()
コード例 #14
0
ファイル: commands.py プロジェクト: club9822/rest
def cmd_init(argv, path_to_tx):
    """Initialize a new Transifex project."""
    parser = init_parser()
    options = parser.parse_args(argv)
    path_to_tx = options.path_to_tx or os.getcwd()

    print(messages.init_intro)
    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
    config_file = os.path.join(path_to_tx, ".tx", "config")
    if os.path.isfile(config_file):
        if not save:
            if options.no_interactive:
                parser.error("Project already initialized.")
            logger.info(messages.init_initialized)
            if not utils.confirm(messages.init_reinit):
                return
        os.remove(config_file)

    if not os.path.isdir(os.path.join(path_to_tx, ".tx")):
        logger.info("Creating .tx folder...")
        os.mkdir(os.path.join(path_to_tx, ".tx"))

    default_transifex = "https://www.transifex.com"
    transifex_host = options.host or default_transifex

    if not transifex_host.startswith(('http://', 'https://')):
        transifex_host = 'https://' + transifex_host

    if not os.path.exists(config_file):
        # Handle the credentials through transifexrc
        config = OrderedRawConfigParser()
        config.add_section('main')
        config.set('main', 'host', transifex_host)
        # Touch the file if it doesn't exist
        logger.info("Creating config file...")
        fh = open(config_file, 'w')
        config.write(fh)
        fh.close()

    if not options.skipsetup and not options.no_interactive:
        logger.info(messages.running_tx_set)
        cmd_config([], path_to_tx)
    else:
        prj = project.Project(path_to_tx)
        prj.getset_host_credentials(transifex_host,
                                    username=options.user,
                                    password=options.password,
                                    token=options.token,
                                    force=options.save,
                                    no_interactive=options.no_interactive)
        prj.save()
        logger.info("Done.")
コード例 #15
0
def cmd_delete(argv, path_to_tx):
    """Delete an accessible resource or translation in a remote server."""
    parser = delete_parser()
    options = parser.parse_args(argv)
    languages = parse_csv_option(options.languages)
    resources = parse_csv_option(options.resources)
    skip = options.skip_errors
    force = options.force_delete
    prj = project.Project(path_to_tx)
    prj.delete(resources, languages, skip, force)
    logger.info("Done.")
コード例 #16
0
def push():
    resourceLink = request.form["resources"]
    resources = resourceLink.split("*//")
    logger.info("zaab")
    prj = project.Project(path_to_tx)
    try:
	    prj.push(resources=resources, source=True)
	    prj.push(resources=resources, skip=True, translations=True, source=False)
	    return "success"
    except: 
	    return "failed"
コード例 #17
0
def _set_project_option(resource, name, value, path_to_tx, func_name):
    """Save the option to the project configuration file."""
    if value is None:
        return
    if not resource:
        logger.debug("Setting the %s for all resources." % name)
        resources = []
    else:
        logger.debug("Setting the %s for resource %s." % (name, resource))
        resources = [resource, ]
    prj = project.Project(path_to_tx)
    getattr(prj, func_name)(resources, value)
    prj.save()
コード例 #18
0
def cmd_delete(argv, path_to_tx):
    "Delete an accessible resource or translation in a remote server."

    class EpilogParser(OptionParser):
        def format_epilog(self, formatter):
            return self.epilog

    usage = "usage: %prog [tx_options] delete OPTION [OPTIONS]"
    description = "This command deletes either a resource (if no language has been specified)"
    " or specific translations for a resource in the remote server."
    epilog="\nExamples:\n"\
        " To delete a translation:\n  $ tx delete -r project.resource -l <lang_code>\n\n"\
        " To delete a resource:\n  $ tx delete -r project.resource\n"
    parser = EpilogParser(usage=usage, description=description, epilog=epilog)
    parser.add_option(
        "-r",
        "--resource",
        action="store",
        dest="resources",
        default=None,
        help="Specify the resource you want to delete (defaults to all)")
    parser.add_option("-l",
                      "--language",
                      action="store",
                      dest="languages",
                      default=None,
                      help="Specify the translation you want to delete")
    parser.add_option("--skip",
                      action="store_true",
                      dest="skip_errors",
                      default=False,
                      help="Don't stop on errors.")

    (options, args) = parser.parse_args(argv)

    if options.languages:
        languages = options.languages.split(',')
    else:
        languages = []

    if options.resources:
        resources = options.resources.split(',')
    else:
        resources = []

    skip = options.skip_errors

    prj = project.Project(path_to_tx)
    prj.delete(resources, languages, skip)
    utils.MSG("Done.")
コード例 #19
0
    def push():
        #push all selected resources
        #resource names are in one string and split them with *//
        resourceLink = request.form["resources"]
        resources = resourceLink.split("*//")

        prj = project.Project(path_to_tx)
        try:
            prj.push(resources=resources, source=True)
            prj.push(resources=resources,
                     skip=True,
                     translations=True,
                     source=False)
            return "success"
        except:
            return "failed"
コード例 #20
0
    def pullResource():
        #pull for particular resource and particular languages of that resource
        #languages are in one string and we split them by *// also at the end of that string we have the resource name
        resourceLanguages = request.form["resourceLanguages"]
        languages = resourceLanguages.split("*//")
        resource = languages[-1]
        logger.info("shit")
        languages.pop()

        prj = project.Project(path_to_tx)
        try:
            prj.pull(resources=[resource],
                     fetchall=True,
                     skip=True,
                     languages=languages)
            return "success"
        except:
            return "failed"
コード例 #21
0
def cmd_status(argv, path_to_tx):
    "Print status of current project"

    usage = "usage: %prog [tx_options] status [options]"
    description="Prints the status of the current project by reading the"\
        " data in the configuration file."
    parser = OptionParser(usage=usage, description=description)
    parser.add_option("-r",
                      "--resource",
                      action="store",
                      dest="resources",
                      default=[],
                      help="Specify resources")

    (options, args) = parser.parse_args(argv)
    if options.resources:
        resources = options.resources.split(',')
    else:
        resources = []

    prj = project.Project(path_to_tx)
    resources = prj.get_chosen_resources(resources)
    resources_num = len(resources)
    for id, res in enumerate(resources):
        p, r = res.split('.')
        utils.MSG("%s -> %s (%s of %s)" % (p, r, id + 1, resources_num))
        utils.MSG("Translation Files:")
        slang = prj.get_resource_option(res, 'source_lang')
        sfile = prj.get_resource_option(res, 'source_file') or "N/A"
        lang_map = prj.get_resource_lang_mapping(res)
        utils.MSG(" - %s: %s (%s)" % (utils.color_text(
            slang, "RED"), sfile, utils.color_text("source", "YELLOW")))
        files = prj.get_resource_files(res)
        fkeys = files.keys()
        fkeys.sort()
        for lang in fkeys:
            local_lang = lang
            if lang in lang_map.values():
                local_lang = lang_map.flip[lang]
            utils.MSG(" - %s: %s" %
                      (utils.color_text(local_lang, "RED"), files[lang]))

        utils.MSG("")
コード例 #22
0
ファイル: commands.py プロジェクト: xrg/transifex-client
def cmd_push(argv, path_to_tx):
    "Push local files to remote server"
    parser = push_parser()
    (options, args) = parser.parse_args(argv)
    force_creation = options.force_creation
    languages = parse_csv_option(options.languages)
    resources = parse_csv_option(options.resources)
    skip = options.skip_errors
    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,"
            " -t|--translations flags with the push command.")

    prj.push(
        force=force_creation, resources=resources, languages=languages,
        skip=skip, source=options.push_source, num=options.num,
        translations=options.push_translations,
        no_interactive=options.no_interactive
    )
    logger.info("Done.")
コード例 #23
0
    def pushResource():
        #push for particular reource and particular languages of that resource
        #languges are in one string and we split them by *// also at the end of tha string we have the resource name
        locale = request.form["locales"]
        prj = project.Project(path_to_tx)

        locales = locale.split("*//")
        resource = locales[-1]
        locales.pop()

        try:
            prj.push(resources=[resource], source=True)
            prj.push(resources=[resource],
                     skip=True,
                     translations=True,
                     source=False,
                     languages=locales)
            return "success"
        except:
            return "failed"
コード例 #24
0
    def rename():
        """Rename a resource."""
        prj = project.Project(path_to_tx)
        res_old = request.form['elementid']
        res_new = request.form['value']

        # Raise error with invalid resource ID
        if res_new.count('.') != 1:
            error_msg = u"New resource ID should have one dot in it."
            flash(error_msg, 'error')
            logger.warning(error_msg)
            return (res_old)

        # Avoid deleting the same resource if unchanged:
        if res_new == res_old:
            return (res_old)

        logger.info("Renaming %s to %s" % (res_old, res_new))
        prj.config._sections[res_new] = prj.config._sections[res_old]
        prj.config._sections.pop(res_old)
        prj.save()
        return res_new
コード例 #25
0
    if options.fetchall and options.languages:
        parser.error("You can't user a language filter along with the"\
            " -a|--all option")
    languages = parse_csv_option(options.languages)
    resources = parse_csv_option(options.resources)
    skip = options.skip_errors
    minimum_perc = options.minimum_perc or None

    try:
        _go_to_dir(path_to_tx)
    except UnInitializedError, e:
        utils.logger.error(e)
        return

    # instantiate the project.Project
    prj = project.Project(path_to_tx)
    prj.pull(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)
    logger.info("Done.")


def _set_source_file(path_to_tx, resource, lang, path_to_file):
    """Reusable method to set source file."""
    proj, res = resource.split('.')
コード例 #26
0
def _auto_local(path_to_tx, resource, source_language, expression,
                execute=False, source_file=None, regex=False):
    """Auto configure local project."""
    # The path everything will be relative to
    curpath = os.path.abspath(os.curdir)

    # Force expr to be a valid regex expr (escaped) but keep <lang> intact
    if not expression:
        raise Exception("You need to specify an expression to define where "
                        "translation files should be saved.")

    if not execute:
        logger.info("Only printing the commands which will be run if the "
                    "--execute switch is specified.")

    # 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, lang in utils.get_project_files(curpath, expression):
        if lang == source_language and not source_file:
            source_file = f_path
        else:
            translation_files[lang] = f_path

    if not source_file:
        raise Exception("Could not find a source language file. Please run "
                        "set --source manually and then re-run this command "
                        "or provide the source file with the -s flag.")
    if execute:
        logger.info("Updating source for resource %s ( %s -> %s )." % (
                    resource, source_language, os.path.relpath(
                        source_file, path_to_tx)
                    ))
        _set_source_file(path_to_tx, resource, source_language,
                         os.path.relpath(source_file, path_to_tx))
    else:
        logger.info('\ntx set --source -r %(res)s -l %(lang)s %(file)s\n' % {
            'res': resource,
            'lang': source_language,
            'file': os.path.relpath(source_file, curpath)})

    prj = project.Project(path_to_tx)

    if execute:
        try:
            prj.config.get("%s" % resource, "source_file")
        except configparser.NoSectionError:
            raise Exception("No resource with slug \"%s\" was found.\nRun "
                            "'tx set auto-local -r %s \"expression\"' to "
                            "do the initial configuration." % resource)

    # Now let's handle the translation files.
    if execute:
        logger.info("Updating file expression for resource %s ( %s )." % (
                    resource, expression))
        # Evaluate file_filter relative to root dir
        file_filter = posix_path(
            os.path.relpath(os.path.join(curpath, expression), path_to_tx)
        )
        prj.config.set("%s" % resource, "file_filter", file_filter)
    else:
        for (lang, f_path) in sorted(translation_files.items()):
            logger.info('tx set -r %(res)s -l %(lang)s %(file)s' % {
                'res': resource,
                'lang': lang,
                'file': os.path.relpath(f_path, curpath)})

    if execute:
        prj.save()
コード例 #27
0
def _print_instructions(resource, path_to_tx):
    keys = ['source_file', 'file_filter', 'source_lang', 'type']
    prj = project.Project(path_to_tx)
    fmt_kwargs = {k: prj.config.get(resource, k) for k in keys}
    fmt_kwargs.update({'resource': resource})
    print(messages.final_instr.format(**fmt_kwargs))
コード例 #28
0
#! /bin/env python
import txclib.project as project
import json
STATUS_FILE = './client/app/locales/status-frontend.json'
prj = project.Project()
prj.pull()
s = prj._get_stats_for_resource()
with open(STATUS_FILE, 'w') as f:
    json.dump(s, f, sort_keys=True, indent=2)
    print("Updated", STATUS_FILE)
コード例 #29
0
def cmd_init(argv, path_to_tx):
    """Initialize a new transifex project."""
    parser = init_parser()
    (options, args) = parser.parse_args(argv)
    if len(args) > 1:
        parser.error("Too many arguments were provided. Aborting...")
    if args:
        path_to_tx = args[0]
    else:
        path_to_tx = os.getcwd()

    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!")
        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"))

    default_transifex = "https://www.transifex.com"
    transifex_host = options.host or input(
        "Transifex instance [%s]: " % default_transifex)

    if not transifex_host:
        transifex_host = default_transifex
    if not transifex_host.startswith(('http://', 'https://')):
        transifex_host = 'https://' + transifex_host

    config_file = os.path.join(path_to_tx, ".tx", "config")
    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)
        # Touch the file if it doesn't exist
        logger.info("Creating config file...")
        fh = open(config_file, 'w')
        config.write(fh)
        fh.close()

    prj = project.Project(path_to_tx)
    prj.getset_host_credentials(transifex_host,
                                username=options.user,
                                password=options.password,
                                token=options.token,
                                save=save)
    prj.save()
    logger.info("Done.")
コード例 #30
0
#! /bin/env python
import json
import txclib.project as project

STATUS_FILE = './src/locales/status-frontend.json'
PRJ = project.Project()
PRJ.pull()
STATS = PRJ._get_stats_for_resource()
with open(STATUS_FILE, 'w') as f:
    json.dump(STATS, f, sort_keys=True, indent=2)
    print("Updated", STATUS_FILE)