예제 #1
0
    def handle_noargs(self, *args, **options):
        locale = options.get('locale')
        domain = options.get('domain')
        verbosity = int(options.get('verbosity'))
        process_all = options.get('all')
        extensions = options.get('extensions')
        symlinks = options.get('symlinks')
        ignore_patterns = options.get('ignore_patterns')
        if options.get('use_default_ignore_patterns'):
            ignore_patterns += ['CVS', '.*', '*~']
        ignore_patterns = list(set(ignore_patterns))
        no_wrap = options.get('no_wrap')
        no_location = options.get('no_location')
        no_obsolete = options.get('no_obsolete')
        extra_keywords = options.get('extra_keywords')
        if domain == 'djangojs':
            exts = extensions if extensions else ['js']
        else:
            exts = extensions if extensions else ['html', 'txt']
        extensions = makemessages.handle_extensions(exts)

        if verbosity > 1:
            self.stdout.write('examining files with the extensions: %s\n'
                             % get_text_list(list(extensions), 'and'))

        _make_messages(locale, domain, verbosity, process_all, extensions,
            symlinks, ignore_patterns, no_wrap, no_location, no_obsolete, 
            self.stdout, extra_keywords)
예제 #2
0
    def handle_app(self, app, **options):
        extensions_option = options.get("extensions")
        if not extensions_option:
            # Default to process [".html", ".handlebars"] if extensions are not specified.
            extensions_option = ["html", "handlebars"]
        extensions = tuple(handle_extensions(extensions_option, ignored=()))
        parse_file = options.get("parse_file")
        ignores = options.get("ignores")
        if parse_file and isinstance(parse_file, list):
            parse_file = parse_file[0]

        # TODO(cpauya): Get the app name here.
        if parse_file:
            logging.info(
                "Will look for %s only at %s app with extensions: [%s]..."
                % (parse_file, app.__file__, ", ".join(extensions))
            )
        else:
            logging.info(
                "Will look for template files at %s app with extensions: [%s]..."
                % (app.__name__, ", ".join(extensions))
            )

        local_dir = os.path.dirname(app.__file__)
        i18nize_parser(parse_dir=local_dir, extensions=extensions, parse_file=parse_file, ignores=ignores)
예제 #3
0
    def handle(self, args):
        from django.core.management.commands.makemessages import make_messages, handle_extensions
        from django.db import models
        from djangojs.conf import settings

        if not args.apps:
            raise CommandError('Enter at least one application name.')

        if not (args.locale or args.all):
            raise CommandError('Enter a locale or use the --all switch.')

        ignore_patterns = args.ignore
        if args.no_default_ignore:
            ignore_patterns += ['CVS', '.*', '*~']
        ignore_patterns = list(set(ignore_patterns))

        extensions = handle_extensions(args.extensions)

        try:
            apps = [models.get_app(app) for app in args.apps]
        except (ImproperlyConfigured, ImportError) as e:
            raise CommandError("%s. Are you sure your INSTALLED_APPS setting is correct?" % e)

        for app in apps:
            app_dir = os.path.dirname(app.__file__)
            os.chdir(app_dir)

            catalogs = [self.build_catalog(root, ext, regexp) for ext, root, regexp in settings.JS_I18N_PATTERNS]

            make_messages(args.locale, b'djangojs', args.verbosity, args.all, extensions,
                          args.symlinks, ignore_patterns, args.no_wrap, args.no_location,
                          args.no_obsolete, self.stdout)

            for catalog in catalogs:
                os.remove(catalog)
예제 #4
0
    def handle(self, *args, **options):
        if len(args) != 0:
            raise CommandError("Command doesn't accept any arguments")

        locale = options.get('locale')
        domain = options.get('domain')
        verbosity = int(options.get('verbosity'))
        process_all = options.get('all')
        extensions = options.get('extensions') or ['html']

        if domain == 'djangojs':
            extensions = []
        else:
            extensions = handle_extensions(extensions)

        if '.js' in extensions:
            raise CommandError("JavaScript files should be examined by using the special 'djangojs' domain only.")

        # The hacking part is here
        if process_all:
            if os.path.isdir(os.path.join('conf', 'locale')):
                localedir = os.path.abspath(os.path.join('conf', 'locale'))
            elif os.path.isdir('locale'):
                localedir = os.path.abspath('locale')
            else:
                raise CommandError("This script should be run from the Transifex project tree.")

            # Only for directories under the locale dir, make_messages
            locale_dirs = filter(os.path.isdir, glob.glob('%s/*' % localedir))
            for locale_dir in locale_dirs:
                locale = os.path.basename(locale_dir)
                make_messages(locale, domain, verbosity, False, extensions)
        else:
            make_messages(locale, domain, verbosity, process_all, extensions)
예제 #5
0
    def handle(self, *args, **options):
        from thepian.conf import import_structure

        structure = import_structure(os.getcwd())
        try:
            import django
        except ImportError:
            if structure.DEVELOPING:
                site.addsitedir(structure.LIB_DIR)
        import django
        from django.core.management.commands.makemessages import make_messages, handle_extensions

        if len(args) != 0:
            raise CommandError("Command doesn't accept any arguments")

        locale = options.get("locale")
        domain = options.get("domain")
        verbosity = int(options.get("verbosity"))
        process_all = options.get("all")
        extensions = options.get("extensions") or ["html"]

        if domain == "djangojs":
            extensions = []
        else:
            extensions = handle_extensions(extensions)

        if ".js" in extensions:
            raise CommandError("JavaScript files should be examined by using the special 'djangojs' domain only.")

        # old_cwd = os.getcwd()
        # os.chdir(os.path.dirname(django.__file__))
        make_messages(locale, domain, verbosity, process_all, extensions)
예제 #6
0
    def handle_app(self, app, **options):
        extensions_option = options.get('extensions')
        if not extensions_option:
            # Default to process [".html", ".handlebars"] if extensions are not specified.
            extensions_option = ['html', 'handlebars']
        extensions = tuple(handle_extensions(extensions_option, ignored=()))
        parse_file = options.get("parse_file")
        if parse_file and isinstance(parse_file, list):
            parse_file = parse_file[0]

        # TODO(cpauya): Get the app name here.
        if parse_file:
            logging.info(
                "Will look for %s only at %s app with extensions: [%s]..." % (
                    parse_file,
                    app.__file__,
                    ', '.join(extensions),
                ))
        else:
            logging.info(
                "Will look for template files at %s app with extensions: [%s]..."
                % (app.__name__, ', '.join(extensions)))

        local_dir = os.path.dirname(app.__file__)
        i18nize_parser(parse_dir=local_dir,
                       extensions=extensions,
                       parse_file=parse_file)
예제 #7
0
    def handle_noargs(self, *args, **options):
        locale = options.get('locale')
        domain = options.get('domain')
        verbosity = int(options.get('verbosity'))
        process_all = options.get('all')
        extensions = options.get('extensions')
        symlinks = options.get('symlinks')
        ignore_patterns = options.get('ignore_patterns')
        if options.get('use_default_ignore_patterns'):
            ignore_patterns += ['CVS', '.*', '*~']
        ignore_patterns = list(set(ignore_patterns))
        no_wrap = options.get('no_wrap')
        no_location = options.get('no_location')
        no_obsolete = options.get('no_obsolete')
        extra_keywords = options.get('extra_keywords')
        if domain == 'djangojs':
            exts = extensions if extensions else ['js']
        else:
            exts = extensions if extensions else ['html', 'txt']
        extensions = makemessages.handle_extensions(exts)

        if verbosity > 1:
            self.stdout.write('examining files with the extensions: %s\n' %
                              get_text_list(list(extensions), 'and'))

        _make_messages(locale, domain, verbosity, process_all, extensions,
                       symlinks, ignore_patterns, no_wrap, no_location,
                       no_obsolete, self.stdout, extra_keywords)
    def handle(self, *args, **options):
        if len(args) != 0:
            raise CommandError("Command doesn't accept any arguments")

        locale = options.get('locale')
        domain = options.get('domain')
        verbosity = int(options.get('verbosity'))
        process_all = options.get('all')
        extensions = options.get('extensions') or ['html']

        if domain == 'djangojs':
            extensions = []
        else:
            extensions = handle_extensions(extensions)

        if '.js' in extensions:
            raise CommandError(
                "JavaScript files should be examined by using the special 'djangojs' domain only."
            )

        # The hacking part is here
        if process_all:
            if os.path.isdir(os.path.join('conf', 'locale')):
                localedir = os.path.abspath(os.path.join('conf', 'locale'))
            elif os.path.isdir('locale'):
                localedir = os.path.abspath('locale')
            else:
                raise CommandError(
                    "This script should be run from the Transifex project tree."
                )

            # Only for directories under the locale dir, make_messages
            locale_dirs = filter(os.path.isdir, glob.glob('%s/*' % localedir))
            for locale_dir in locale_dirs:
                locale = os.path.basename(locale_dir)
                make_messages(locale, domain, verbosity, False, extensions)
        else:
            make_messages(locale, domain, verbosity, process_all, extensions)
예제 #9
0
파일: templates.py 프로젝트: Ichroid/django
    def handle(self, app_or_project, name, target=None, **options):
        self.app_or_project = app_or_project
        self.paths_to_remove = []
        self.verbosity = int(options.get('verbosity'))

        self.validate_name(name, app_or_project)

        # if some directory is given, make sure it's nicely expanded
        if target is None:
            top_dir = path.join(os.getcwd(), name)
            try:
                os.makedirs(top_dir)
            except OSError as e:
                if e.errno == errno.EEXIST:
                    message = "'%s' already exists" % top_dir
                else:
                    message = e
                raise CommandError(message)
        else:
            top_dir = os.path.abspath(path.expanduser(target))
            if not os.path.exists(top_dir):
                raise CommandError("Destination directory '%s' does not "
                                   "exist, please create it first." % top_dir)

        extensions = tuple(
            handle_extensions(options.get('extensions'), ignored=()))
        extra_files = []
        for file in options.get('files'):
            extra_files.extend(map(lambda x: x.strip(), file.split(',')))
        if self.verbosity >= 2:
            self.stdout.write("Rendering %s template files with "
                              "extensions: %s\n" %
                              (app_or_project, ', '.join(extensions)))
            self.stdout.write("Rendering %s template files with "
                              "filenames: %s\n" %
                              (app_or_project, ', '.join(extra_files)))

        base_name = '%s_name' % app_or_project
        base_subdir = '%s_template' % app_or_project
        base_directory = '%s_directory' % app_or_project

        context = Context(dict(options, **{
            base_name: name,
            base_directory: top_dir,
        }), autoescape=False)

        # Setup a stub settings environment for template rendering
        from django.conf import settings
        if not settings.configured:
            settings.configure()

        template_dir = self.handle_template(options.get('template'),
                                            base_subdir)
        prefix_length = len(template_dir) + 1

        for root, dirs, files in os.walk(template_dir):

            path_rest = root[prefix_length:]
            relative_dir = path_rest.replace(base_name, name)
            if relative_dir:
                target_dir = path.join(top_dir, relative_dir)
                if not path.exists(target_dir):
                    os.mkdir(target_dir)

            for dirname in dirs[:]:
                if dirname.startswith('.') or dirname == '__pycache__':
                    dirs.remove(dirname)

            for filename in files:
                if filename.endswith(('.pyo', '.pyc', '.py.class')):
                    # Ignore some files as they cause various breakages.
                    continue
                old_path = path.join(root, filename)
                new_path = path.join(top_dir, relative_dir,
                                     filename.replace(base_name, name))
                if path.exists(new_path):
                    raise CommandError("%s already exists, overlaying a "
                                       "project or app into an existing "
                                       "directory won't replace conflicting "
                                       "files" % new_path)

                # Only render the Python files, as we don't want to
                # accidentally render Django templates files
                with open(old_path, 'rb') as template_file:
                    content = template_file.read()
                if filename.endswith(extensions) or filename in extra_files:
                    content = content.decode('utf-8')
                    template = Template(content)
                    content = template.render(context)
                    content = content.encode('utf-8')
                with open(new_path, 'wb') as new_file:
                    new_file.write(content)

                if self.verbosity >= 2:
                    self.stdout.write("Creating %s\n" % new_path)
                try:
                    shutil.copymode(old_path, new_path)
                    self.make_writeable(new_path)
                except OSError:
                    self.stderr.write(
                        "Notice: Couldn't set permission bits on %s. You're "
                        "probably using an uncommon filesystem setup. No "
                        "problem." % new_path, self.style.NOTICE)

        if self.paths_to_remove:
            if self.verbosity >= 2:
                self.stdout.write("Cleaning up temporary files.\n")
            for path_to_remove in self.paths_to_remove:
                if path.isfile(path_to_remove):
                    os.remove(path_to_remove)
                else:
                    shutil.rmtree(path_to_remove,
                                  onerror=rmtree_errorhandler)
예제 #10
0
        if target is None:
            top_dir = path.join(os.getcwd(), name)
            try:
                os.makedirs(top_dir)
            except OSError, e:
                if e.errno == errno.EEXIST:
                    message = "'%s' already exists" % top_dir
                else:
                    message = e
                raise CommandError(message)
        else:
            top_dir = path.expanduser(target)


        extensions = tuple(
            handle_extensions(options.get('extensions'), ignored=()))
        extra_files = []
        for file in options.get('files'):
            extra_files.extend(map(lambda x: x.strip(), file.split(',')))
        if self.verbosity >= 2:
            self.stdout.write("Rendering %s template files with "
                              "extensions: %s\n" %
                              (app_or_project, ', '.join(extensions)))
            self.stdout.write("Rendering %s template files with "
                              "filenames: %s\n" %
                              (app_or_project, ', '.join(extra_files)))

        base_name = '%s_name' % app_or_project
        base_subdir = '%s_template' % app_or_project
        base_directory = '%s_directory' % app_or_project
예제 #11
0
        # if some directory is given, make sure it's nicely expanded
        if target is None:
            top_dir = path.join(os.getcwd(), name)
            try:
                os.makedirs(top_dir)
            except OSError, e:
                if e.errno == errno.EEXIST:
                    message = "'%s' already exists" % top_dir
                else:
                    message = e
                raise CommandError(message)
        else:
            top_dir = path.expanduser(target)

        extensions = tuple(
            handle_extensions(options.get('extensions'), ignored=()))
        if self.verbosity >= 2:
            self.stdout.write("Rendering %s template files with "
                              "extensions: %s\n" %
                              (app_or_project, ', '.join(extensions)))

        base_name = '%s_name' % app_or_project
        base_subdir = '%s_template' % app_or_project
        base_directory = '%s_directory' % app_or_project

        context = Context(
            dict(options, **{
                base_name: name,
                base_directory: top_dir,
            }))
예제 #12
0
    def handle(self, app_or_project, name, target=None, **options):
        self.app_or_project = app_or_project
        self.paths_to_remove = []
        self.verbosity = int(options.get('verbosity'))

        self.validate_name(name, app_or_project)

        # if some directory is given, make sure it's nicely expanded
        if target is None:
            top_dir = path.join(os.getcwd(), name)
            try:
                os.makedirs(top_dir)
            except OSError as e:
                if e.errno == errno.EEXIST:
                    message = "'%s' already exists" % top_dir
                else:
                    message = e
                raise CommandError(message)
        else:
            top_dir = os.path.abspath(path.expanduser(target))
            if not os.path.exists(top_dir):
                raise CommandError("Destination directory '%s' does not "
                                   "exist, please create it first." % top_dir)

        extensions = tuple(
            handle_extensions(options.get('extensions'), ignored=()))
        extra_files = []
        for file in options.get('files'):
            extra_files.extend(map(lambda x: x.strip(), file.split(',')))
        if self.verbosity >= 2:
            self.stdout.write("Rendering %s template files with "
                              "extensions: %s\n" %
                              (app_or_project, ', '.join(extensions)))
            self.stdout.write("Rendering %s template files with "
                              "filenames: %s\n" %
                              (app_or_project, ', '.join(extra_files)))

        base_name = '%s_name' % app_or_project
        base_subdir = '%s_template' % app_or_project
        base_directory = '%s_directory' % app_or_project
        if django.VERSION[-1] == 0:
            docs_version = 'dev'
        else:
            docs_version = '%d.%d' % django.VERSION[:2]

        context = Context(dict(
            options, **{
                base_name: name,
                base_directory: top_dir,
                'docs_version': docs_version,
            }),
                          autoescape=False)

        # Setup a stub settings environment for template rendering
        from django.conf import settings
        if not settings.configured:
            settings.configure()

        template_dir = self.handle_template(options.get('template'),
                                            base_subdir)
        prefix_length = len(template_dir) + 1

        for root, dirs, files in os.walk(template_dir):

            path_rest = root[prefix_length:]
            relative_dir = path_rest.replace(base_name, name)
            if relative_dir:
                target_dir = path.join(top_dir, relative_dir)
                if not path.exists(target_dir):
                    os.mkdir(target_dir)

            for dirname in dirs[:]:
                if dirname.startswith('.') or dirname == '__pycache__':
                    dirs.remove(dirname)

            for filename in files:
                if filename.endswith(('.pyo', '.pyc', '.py.class')):
                    # Ignore some files as they cause various breakages.
                    continue
                old_path = path.join(root, filename)
                new_path = path.join(top_dir, relative_dir,
                                     filename.replace(base_name, name))
                if path.exists(new_path):
                    raise CommandError("%s already exists, overlaying a "
                                       "project or app into an existing "
                                       "directory won't replace conflicting "
                                       "files" % new_path)

                # Only render the Python files, as we don't want to
                # accidentally render Django templates files
                with open(old_path, 'rb') as template_file:
                    content = template_file.read()
                if filename.endswith(extensions) or filename in extra_files:
                    content = content.decode('utf-8')
                    template = Template(content)
                    content = template.render(context)
                    content = content.encode('utf-8')
                with open(new_path, 'wb') as new_file:
                    new_file.write(content)

                if self.verbosity >= 2:
                    self.stdout.write("Creating %s\n" % new_path)
                try:
                    shutil.copymode(old_path, new_path)
                    self.make_writeable(new_path)
                except OSError:
                    self.stderr.write(
                        "Notice: Couldn't set permission bits on %s. You're "
                        "probably using an uncommon filesystem setup. No "
                        "problem." % new_path, self.style.NOTICE)

        if self.paths_to_remove:
            if self.verbosity >= 2:
                self.stdout.write("Cleaning up temporary files.\n")
            for path_to_remove in self.paths_to_remove:
                if path.isfile(path_to_remove):
                    os.remove(path_to_remove)
                else:
                    shutil.rmtree(path_to_remove, onerror=rmtree_errorhandler)
예제 #13
0
    def handle(self, app_name, template_dir, destination=None, app_path=None,
            extra_context=None, *args, **options):
        self.verbosity = int(options.get('verbosity'))
        self.app_name = app_name

        if app_path is None:
            self.app_path = __import__(app_name).__path__[0]
        else:
            self.app_path = app_path

        if destination is None:
            destination = self.app_path

        extra_context = extra_context or {}

        extensions = tuple(
            handle_extensions(options.get('extensions'), ignored=()))

        extra_files = []
        for f in options.get('files'):
            extra_files.extend(map(lambda x: x.strip(), f.split(',')))

        context = self.build_context(extra_context, *args, **options)

        source = os.path.join(yourlabs.__path__[0], 'templates', 'yourlabs',
                              template_dir)

        for root, dirnames, filenames in os.walk(source):
            relative_root = root.replace(source, '')

            if relative_root != '' and relative_root[0] == '/':
                relative_root = relative_root[1:]

            destination_dirpath = os.path.join(destination,
                                               self.source_rename(relative_root))

            if not options.get('dry_run', False):
                if not os.path.exists(destination_dirpath):
                    os.makedirs(destination_dirpath)

            for source_filename in filenames:
                if source_filename[-4:] == '.pyc':
                    continue

                destination_filepath = os.path.join(destination_dirpath,
                    self.source_rename(source_filename))
                source_filepath = os.path.join(root, source_filename)

                if os.path.exists(destination_filepath):
                    self.stdout.write("Skipping existing %s\n" %
                                    destination_filepath)
                    continue

                if (self.source_rename(source_filename).endswith(extensions) or
                    source_filename in extra_files):
                    template = loader.get_template(
                        os.path.join('yourlabs', template_dir, relative_root,
                                     source_filename))
                    content = template.render(context)
                    content = content.encode('utf-8')
                else:
                    with open(source_filepath, 'rb') as template_file:
                        content = template_file.read()

                if options.get('dry_run', False):
                    print ('=' * 40)
                    print (destination_filepath)
                    print ('-' * 40)
                    print (content)
                    print ('=' * 40)
                else:
                    with open(destination_filepath, 'wb') as new_file:
                        new_file.write(content)

                    self.stdout.write("Creating %s\n" % destination_filepath)

                    try:
                        shutil.copymode(source_filepath, destination_filepath)
                    except OSError:
                        self.stderr.write(
                            "Notice: Couldn't set permission bits on %s. You're "
                            "probably using an uncommon filesystem setup. No "
                            "problem." % destination_filepath, self.style.NOTICE)
예제 #14
0
    def handle(self, app_or_project, name, target=None, **options):
        self.app_or_project = app_or_project
        self.paths_to_remove = []
        self.verbosity = int(options.get("verbosity"))

        # If it's not a valid directory name.
        if not re.search(r"^[_a-zA-Z]\w*$", name):
            # Provide a smart error message, depending on the error.
            if not re.search(r"^[_a-zA-Z]", name):
                message = "make sure the name begins " "with a letter or underscore"
            else:
                message = "use only numbers, letters and underscores"
            raise CommandError("%r is not a valid %s name. Please %s." % (name, app_or_project, message))

        # if some directory is given, make sure it's nicely expanded
        if target is None:
            top_dir = path.join(os.getcwd(), name)
            try:
                os.makedirs(top_dir)
            except OSError as e:
                if e.errno == errno.EEXIST:
                    message = "'%s' already exists" % top_dir
                else:
                    message = e
                raise CommandError(message)
        else:
            top_dir = os.path.abspath(path.expanduser(target))
            if not os.path.exists(top_dir):
                raise CommandError("Destination directory '%s' does not " "exist, please create it first." % top_dir)

        extensions = tuple(handle_extensions(options.get("extensions"), ignored=()))
        extra_files = []
        for file in options.get("files"):
            extra_files.extend(map(lambda x: x.strip(), file.split(",")))
        if self.verbosity >= 2:
            self.stdout.write(
                "Rendering %s template files with " "extensions: %s\n" % (app_or_project, ", ".join(extensions))
            )
            self.stdout.write(
                "Rendering %s template files with " "filenames: %s\n" % (app_or_project, ", ".join(extra_files))
            )

        base_name = "%s_name" % app_or_project
        base_subdir = "%s_template" % app_or_project
        base_directory = "%s_directory" % app_or_project

        context = Context(dict(options, **{base_name: name, base_directory: top_dir}), autoescape=False)

        # Setup a stub settings environment for template rendering
        from django.conf import settings

        if not settings.configured:
            settings.configure()

        template_dir = self.handle_template(options.get("template"), base_subdir)
        prefix_length = len(template_dir) + 1

        for root, dirs, files in os.walk(template_dir):

            path_rest = root[prefix_length:]
            relative_dir = path_rest.replace(base_name, name)
            if relative_dir:
                target_dir = path.join(top_dir, relative_dir)
                if not path.exists(target_dir):
                    os.mkdir(target_dir)

            for dirname in dirs[:]:
                if dirname.startswith(".") or dirname == "__pycache__":
                    dirs.remove(dirname)

            for filename in files:
                if filename.endswith((".pyo", ".pyc", ".py.class")):
                    # Ignore some files as they cause various breakages.
                    continue
                old_path = path.join(root, filename)
                new_path = path.join(top_dir, relative_dir, filename.replace(base_name, name))
                if path.exists(new_path):
                    raise CommandError(
                        "%s already exists, overlaying a "
                        "project or app into an existing "
                        "directory won't replace conflicting "
                        "files" % new_path
                    )

                # Only render the Python files, as we don't want to
                # accidentally render Django templates files
                with codecs.open(old_path, "r", "utf-8") as template_file:
                    content = template_file.read()
                if filename.endswith(extensions) or filename in extra_files:
                    template = Template(content)
                    content = template.render(context)
                with codecs.open(new_path, "w", "utf-8") as new_file:
                    new_file.write(content)

                if self.verbosity >= 2:
                    self.stdout.write("Creating %s\n" % new_path)
                try:
                    shutil.copymode(old_path, new_path)
                    self.make_writeable(new_path)
                except OSError:
                    self.stderr.write(
                        "Notice: Couldn't set permission bits on %s. You're "
                        "probably using an uncommon filesystem setup. No "
                        "problem." % new_path,
                        self.style.NOTICE,
                    )

        if self.paths_to_remove:
            if self.verbosity >= 2:
                self.stdout.write("Cleaning up temporary files.\n")
            for path_to_remove in self.paths_to_remove:
                if path.isfile(path_to_remove):
                    os.remove(path_to_remove)
                else:
                    shutil.rmtree(path_to_remove, onerror=rmtree_errorhandler)
예제 #15
0
    def get_context_data(self, **kwargs):
        context = super(GenerateTranslationMessagesView, self).get_context_data(**kwargs)
        
        if hasattr(self, 'error') and self.error:
            context['error'] = self.error
            return context
        
        #locate the current directory
        curr_dir = os.curdir
        domain_dict = {'django' : ['html','txt'], 'djangojs' : ['js']}
        
        lang_files = []
        #iterate over the installed applications and copy their po files
        #for this language to the appropriate folder 
        for app_name in settings.INSTALLED_APPS:    
            
            mod = import_module(app_name)
            mod_root = os.path.dirname(mod.__file__)

            if not os.path.exists(os.path.join(mod_root, 'locale')):
                continue
            
            original_path = os.path.join(mod_root, 'locale', to_locale(self.language.name), 'LC_MESSAGES')
            delete_at_the_end = False
            
            if not os.path.exists(original_path):
                if not app_name.startswith('django.contrib'):
                    try: #try to create language directory for the app
                        os.makedirs(original_path)
                        delete_at_the_end = True
                    except:
                        continue
                else:
                    continue
            
            if not app_name.startswith('django.contrib'):
                #move original files to a temp file
                for file_ in list(os.listdir(original_path)):
                        if file_.endswith('.po'):
                            shutil.copy(os.path.join(original_path, file_), os.path.join(original_path, 'original-%s' % file_))
                
                #copy the project-wise files to the appropriate directory
                if not self.request.GET.get('delete', 0):
                    #replace original file with the yawd version
                    #so that it gets updated
                    for f in list(os.listdir(self.po_path)):
                        if f.startswith('%s-' % app_name) and f.endswith('.po'):
                            shutil.copy(os.path.join(self.po_path, f), os.path.join(original_path, f.replace('%s-' % app_name, '')))  

                #makemessages excluding the core applications
                os.chdir(mod_root)
                for key, value in domain_dict.items():
                    make_messages(locale=self.locale, domain=key, extensions=handle_extensions(value), verbosity=0)
                os.chdir(curr_dir)

            #iterate over the application po files
            for file_ in list(os.listdir(original_path)):
                if not file_.startswith('original-') and file_.endswith('.po'):
                    original_file_path = os.path.join(original_path, file_)
                    file_name = '%s-%s' % (app_name, file_)
                    
                    #copy file
                    copy_path = os.path.join(self.po_path, file_name)
                    if self.request.GET.get('delete', 0) or not (app_name.startswith('django.contrib') and os.path.exists(copy_path)):
                        shutil.copy(original_file_path, copy_path)
                        os.chmod(copy_path, 0664)
                    
                    #unlink updated file
                    if not app_name.startswith('django.contrib'):
                        os.unlink(original_file_path)
                    
                    lang_files.append(file_name)
            
            if not app_name.startswith('django.contrib'):
                if delete_at_the_end:
                    shutil.rmtree(os.path.join(mod_root, 'locale', to_locale(self.language.name)))
                else:
                    for file_ in os.listdir(original_path):
                        #put back the original application files
                        if file_.startswith('original-') and file_.endswith('.po'):
                            shutil.move(os.path.join(original_path, file_), os.path.join(original_path, file_.replace('original-','')))
                
        #concat all messages in a single .po file for each domain
        for domain in domain_dict:
            file_name = '%s.po' % domain
            uni_django_path = os.path.join(self.po_path, file_name)

            if os.path.exists(uni_django_path):
                os.unlink(uni_django_path)

            source_files = [os.path.join(self.po_path, f) for f in lang_files if f.endswith(file_name)]
            if source_files:
                #merge .po files
                concat_message_files(source_files, uni_django_path)
                #compile django.po
                if not has_bom(uni_django_path):
                    compile_message_file(uni_django_path)

        #reset the cached translation messages so that
        #we do not need to restart the web server
        reset_translations(self.language.name)
        
        context['lang_files'] = sorted(lang_files)
        return context
예제 #16
0
class TemplateCommand(BaseCommand):
    """
    Copies either a Django application layout template or a Django project
    layout template into the specified directory.

    :param style: A color style object (see django.core.management.color).
    :param app_or_project: The string 'app' or 'project'.
    :param name: The name of the application or project.
    :param directory: The directory to which the template should be copied.
    :param options: The additional variables passed to project or app templates
    """
    args = "[name] [optional destination directory]"
    option_list = BaseCommand.option_list + (
        make_option('--template',
                    action='store',
                    dest='template',
                    help='The dotted import path to load the template from.'),
        make_option('--extension',
                    '-e',
                    dest='extensions',
                    action='append',
                    default=['py'],
                    help='The file extension(s) to render (default: "py") '
                    'Separate multiple extensions with commas, or use '
                    '-e multiple times.'),
    )
    requires_model_validation = False
    # Can't import settings during this command, because they haven't
    # necessarily been created.
    can_import_settings = False
    # The supported URL schemes
    url_schemes = ['http', 'https', 'ftp']

    def handle(self, app_or_project, name, target=None, **options):
        self.app_or_project = app_or_project
        self.paths_to_remove = []
        self.verbosity = int(options.get('verbosity'))

        # If it's not a valid directory name.
        if not re.search(r'^[_a-zA-Z]\w*$', name):
            # Provide a smart error message, depending on the error.
            if not re.search(r'^[_a-zA-Z]', name):
                message = ('make sure the name begins '
                           'with a letter or underscore')
            else:
                message = 'use only numbers, letters and underscores'
            raise CommandError("%r is not a valid %s name. Please %s." %
                               (name, app_or_project, message))

        # if some directory is given, make sure it's nicely expanded
        if target is None:
            target = os.getcwd()
        else:
            target = path.expanduser(target)

        top_dir = path.join(target, name)
        try:
            os.makedirs(top_dir)
        except OSError, e:
            raise CommandError(e)

        extensions = tuple(
            handle_extensions(options.get('extensions'), ignored=()))
        if self.verbosity >= 2:
            self.stdout.write("Rendering %s template files with "
                              "extensions: %s\n" %
                              (app_or_project, ', '.join(extensions)))

        base_name = '%s_name' % app_or_project
        base_subdir = '%s_template' % app_or_project
        base_directory = '%s_directory' % app_or_project

        context = Context(
            dict(options, **{
                base_name: name,
                base_directory: top_dir,
            }))

        # Setup a stub settings environment for template rendering
        from django.conf import settings
        if not settings.configured:
            settings.configure()

        template_dir = self.handle_template(options.get('template'),
                                            base_subdir)
        prefix_length = len(template_dir) + 1

        for root, dirs, files in os.walk(template_dir):

            path_rest = root[prefix_length:]
            relative_dir = path_rest.replace(base_name, name)
            if relative_dir:
                target_dir = path.join(top_dir, relative_dir)
                if not path.exists(target_dir):
                    os.mkdir(target_dir)

            for dirname in dirs[:]:
                if dirname.startswith('.'):
                    dirs.remove(dirname)

            for filename in files:
                if filename.endswith(('.pyo', '.pyc', '.py.class')):
                    # Ignore some files as they cause various breakages.
                    continue
                old_path = path.join(root, filename)
                new_path = path.join(top_dir, relative_dir,
                                     filename.replace(base_name, name))
                if path.exists(new_path):
                    raise CommandError("%s already exists, overlaying a "
                                       "project or app into an existing "
                                       "directory won't replace conflicting "
                                       "files" % new_path)

                # Only render the Python files, as we don't want to
                # accidentally render Django templates files
                with open(old_path, 'r') as template_file:
                    content = template_file.read()
                if filename.endswith(extensions):
                    template = Template(content)
                    content = template.render(context)
                with open(new_path, 'w') as new_file:
                    new_file.write(content)

                if self.verbosity >= 2:
                    self.stdout.write("Creating %s\n" % new_path)
                try:
                    shutil.copymode(old_path, new_path)
                    self.make_writeable(new_path)
                except OSError:
                    notice = self.style.NOTICE(
                        "Notice: Couldn't set permission bits on %s. You're "
                        "probably using an uncommon filesystem setup. No "
                        "problem.\n" % new_path)
                    sys.stderr.write(smart_str(notice))

        if self.paths_to_remove:
            if self.verbosity >= 2:
                self.stdout.write("Cleaning up temporary files.\n")
            for path_to_remove in self.paths_to_remove:
                if path.isfile(path_to_remove):
                    os.remove(path_to_remove)
                else:
                    shutil.rmtree(path_to_remove, onerror=rmtree_errorhandler)
예제 #17
0
        if target is None:
            top_dir = path.join(os.getcwd(), name)
            try:
                os.makedirs(top_dir)
            except OSError, e:
                if e.errno == errno.EEXIST:
                    message = "'%s' already exists" % top_dir
                else:
                    message = e
                raise CommandError(message)
        else:
            top_dir = os.path.abspath(path.expanduser(target))
            if not os.path.exists(top_dir):
                raise CommandError("Destination directory '%s' does not " "exist, please create it first." % top_dir)

        extensions = tuple(handle_extensions(options.get("extensions"), ignored=()))
        extra_files = []
        for file in options.get("files"):
            extra_files.extend(map(lambda x: x.strip(), file.split(",")))
        if self.verbosity >= 2:
            self.stdout.write(
                "Rendering %s template files with " "extensions: %s\n" % (app_or_project, ", ".join(extensions))
            )
            self.stdout.write(
                "Rendering %s template files with " "filenames: %s\n" % (app_or_project, ", ".join(extra_files))
            )

        base_name = "%s_name" % app_or_project
        base_subdir = "%s_template" % app_or_project
        base_directory = "%s_directory" % app_or_project