Example #1
0
        def tzhandler(default, toconf):
            print("\nPlease choose the correct time zone for your blog. Nikola uses the tz database.")
            print("You can find your time zone here:")
            print("https://en.wikipedia.org/wiki/List_of_tz_database_time_zones")
            print("")
            answered = False
            while not answered:
                try:
                    lz = get_localzone()
                except:
                    lz = None
                answer = ask("Time zone", lz if lz else "UTC")
                tz = dateutil.tz.gettz(answer)

                if tz is None:
                    print("    WARNING: Time zone not found.  Searching list of time zones for a match.")
                    zonesfile = tarfile.open(fileobj=dateutil.zoneinfo.getzoneinfofile_stream())
                    zonenames = [zone for zone in zonesfile.getnames() if answer.lower() in zone.lower()]
                    if len(zonenames) == 1:
                        tz = dateutil.tz.gettz(zonenames[0])
                        answer = zonenames[0]
                        print("    Picking '{0}'.".format(answer))
                    elif len(zonenames) > 1:
                        print("    The following time zones match your query:")
                        print("        " + "\n        ".join(zonenames))
                        continue

                if tz is not None:
                    time = datetime.datetime.now(tz).strftime("%H:%M:%S")
                    print("    Current time in {0}: {1}".format(answer, time))
                    answered = ask_yesno("Use this time zone?", True)
                else:
                    print("    ERROR: No matches found.  Please try again.")

            SAMPLE_CONF["TIMEZONE"] = answer
Example #2
0
        def tzhandler(default, toconf):
            print("\nPlease choose the correct time zone for your blog. Nikola uses the tz database.")
            print("You can find your time zone here:")
            print("http://en.wikipedia.org/wiki/List_of_tz_database_time_zones")
            print("")
            answered = False
            while not answered:
                try:
                    lz = get_localzone()
                except:
                    lz = None
                answer = ask('Time zone', lz if lz else "UTC")
                tz = dateutil.tz.gettz(answer)

                if tz is None:
                    print("    WARNING: Time zone not found.  Searching most common timezones for a match.")
                    zonesfile = tarfile.TarFile.open(os.path.join(dateutil.zoneinfo.ZONEINFOFILE))
                    zonenames = [zone for zone in zonesfile.getnames() if answer.lower() in zone.lower()]
                    if len(zonenames) == 1:
                        tz = dateutil.tz.gettz(zonenames[0])
                    elif len(zonenames) > 1:
                        print("    Could not pick one timezone. Choose one of the following:")
                        print('        ' + '\n        '.join(zonenames))
                        continue

                if tz is not None:
                    time = datetime.datetime.now(tz).strftime('%H:%M:%S')
                    print("    Current time in {0}: {1}".format(answer, time))
                    answered = ask_yesno("Use this time zone?", True)
                else:
                    print("    ERROR: Time zone not found.  Please try again.  Time zones are case-sensitive.")

            SAMPLE_CONF['TIMEZONE'] = answer
Example #3
0
        def tzhandler(default, toconf):
            print(
                "\nPlease choose the correct time zone for your blog. Nikola uses the tz database."
            )
            print("You can find your time zone here:")
            print(
                "http://en.wikipedia.org/wiki/List_of_tz_database_time_zones")
            print("")
            answered = False
            while not answered:
                try:
                    lz = get_localzone()
                except:
                    lz = None
                answer = ask('Time zone', lz if lz else "UTC")
                tz = dateutil.tz.gettz(answer)
                if tz is not None:
                    time = datetime.datetime.now(tz).strftime('%H:%M:%S')
                    print("    Current time in {0}: {1}".format(answer, time))
                    answered = ask_yesno("Use this time zone?", True)
                else:
                    print(
                        "    ERROR: Time zone not found.  Please try again.  Time zones are case-sensitive."
                    )

            SAMPLE_CONF['TIMEZONE'] = answer
Example #4
0
        def tzhandler(default, toconf):
            print("\nPlease choose the correct time zone for your blog. Nikola uses the tz database.")
            print("You can find your time zone here:")
            print("https://en.wikipedia.org/wiki/List_of_tz_database_time_zones")
            print("")
            answered = False
            while not answered:
                try:
                    lz = get_localzone()
                except:
                    lz = None
                answer = ask('Time zone', lz if lz else "UTC")
                tz = dateutil.tz.gettz(answer)

                if tz is None:
                    print("    WARNING: Time zone not found.  Searching list of time zones for a match.")
                    zonesfile = tarfile.open(fileobj=dateutil.zoneinfo.getzoneinfofile_stream())
                    zonenames = [zone for zone in zonesfile.getnames() if answer.lower() in zone.lower()]
                    if len(zonenames) == 1:
                        tz = dateutil.tz.gettz(zonenames[0])
                        answer = zonenames[0]
                        print("    Picking '{0}'.".format(answer))
                    elif len(zonenames) > 1:
                        print("    The following time zones match your query:")
                        print('        ' + '\n        '.join(zonenames))
                        continue

                if tz is not None:
                    time = datetime.datetime.now(tz).strftime('%H:%M:%S')
                    print("    Current time in {0}: {1}".format(answer, time))
                    answered = ask_yesno("Use this time zone?", True)
                else:
                    print("    ERROR: No matches found.  Please try again.")

            SAMPLE_CONF['TIMEZONE'] = answer
Example #5
0
    def _execute(self, options, args):
        L = utils.get_logger('upgrade_metadata', utils.STDERR_HANDLER)
        nikola.post._UPGRADE_METADATA_ADVERTISED = True

        # scan posts
        self.site.scan_posts()
        flagged = []
        for post in self.site.timeline:
            if not post.newstylemeta:
                flagged.append(post)
        if flagged:
            if len(flagged) == 1:
                L.info(
                    '1 post (and/or its translations) contains old-style metadata:'
                )
            else:
                L.info(
                    '{0} posts (and/or their translations) contain old-style metadata:'
                    .format(len(flagged)))
            for post in flagged:
                L.info('    ' + post.metadata_path)
            if not options['yes']:
                yesno = utils.ask_yesno("Proceed with metadata upgrade?")
            if options['yes'] or yesno:
                for post in flagged:
                    for lang in self.site.config['TRANSLATIONS'].keys():
                        if lang == post.default_lang:
                            fname = post.metadata_path
                        else:
                            meta_path = os.path.splitext(
                                post.source_path)[0] + '.meta'
                            fname = utils.get_translation_candidate(
                                post.config, meta_path, lang)

                        if os.path.exists(fname):
                            with io.open(fname, 'r', encoding='utf-8') as fh:
                                meta = fh.readlines()

                            if not meta[min(1,
                                            len(meta) - 1)].startswith('.. '):
                                # check if we’re dealing with old style metadata
                                with io.open(fname, 'w',
                                             encoding='utf-8') as fh:
                                    for k, v in zip(self.fields, meta):
                                        fh.write('.. {0}: {1}'.format(k, v))
                                L.debug(fname)

                L.info('{0} posts upgraded.'.format(len(flagged)))
            else:
                L.info('Metadata not upgraded.')
        else:
            L.info(
                'No old-style metadata posts found.  No action is required.')
Example #6
0
 def do_uninstall(self, name):
     """Uninstall a theme."""
     try:
         path = utils.get_theme_path(name)
     except Exception:
         LOGGER.error('Unknown theme: {0}'.format(name))
         return 1
     LOGGER.warning('About to uninstall theme: {0}'.format(name))
     LOGGER.warning('This will delete {0}'.format(path))
     sure = utils.ask_yesno('Are you sure?')
     if sure:
         LOGGER.warning('Removing {0}'.format(path))
         shutil.rmtree(path)
         return 0
     return 1
Example #7
0
 def do_uninstall(self, name):
     """Uninstall a theme."""
     try:
         path = utils.get_theme_path_real(name, self.site.themes_dirs)
     except Exception:
         LOGGER.error('Unknown theme: {0}'.format(name))
         return 1
     LOGGER.warning('About to uninstall theme: {0}'.format(name))
     LOGGER.warning('This will delete {0}'.format(path))
     sure = utils.ask_yesno('Are you sure?')
     if sure:
         LOGGER.warning('Removing {0}'.format(path))
         shutil.rmtree(path)
         return 0
     return 1
Example #8
0
    def _prompt_continue(self):
        """ Show uncommitted changes, and ask if user wants to continue. """

        changes = uni_check_output(['git', 'status', '--porcelain'])
        if changes.strip():
            changes = uni_check_output(['git', 'status']).strip()
            message = (
                "You have the following changes:\n%s\n\n"
                "Anything not committed, and unknown to Nikola may be lost, "
                "or committed onto the wrong branch. Do you wish to continue?"
            ) % changes
            proceed = ask_yesno(message, False)
        else:
            proceed = True

        return proceed
Example #9
0
    def _prompt_continue(self):
        """ Show uncommitted changes, and ask if user wants to continue. """

        changes = uni_check_output(['git', 'status', '--porcelain'])
        if changes.strip():
            changes = uni_check_output(['git', 'status']).strip()
            message = (
                "You have the following changes:\n%s\n\n"
                "Anything not committed, and unknown to Nikola may be lost, "
                "or committed onto the wrong branch. Do you wish to continue?"
            ) % changes
            proceed = ask_yesno(message, False)
        else:
            proceed = True

        return proceed
Example #10
0
        def tzhandler(default, toconf):
            print(
                "\nPlease choose the correct time zone for your blog. Nikola uses the tz database."
            )
            print("You can find your time zone here:")
            print(
                "http://en.wikipedia.org/wiki/List_of_tz_database_time_zones")
            print("")
            answered = False
            while not answered:
                try:
                    lz = get_localzone()
                except:
                    lz = None
                answer = ask('Time zone', lz if lz else "UTC")
                tz = dateutil.tz.gettz(answer)

                if tz is None:
                    print(
                        "    WARNING: Time zone not found.  Searching most common timezones for a match."
                    )
                    zonesfile = tarfile.TarFile.open(
                        os.path.join(dateutil.zoneinfo.ZONEINFOFILE))
                    zonenames = [
                        zone for zone in zonesfile.getnames()
                        if answer.lower() in zone.lower()
                    ]
                    if len(zonenames) == 1:
                        tz = dateutil.tz.gettz(zonenames[0])
                    elif len(zonenames) > 1:
                        print(
                            "    Could not pick one timezone. Choose one of the following:"
                        )
                        print('        ' + '\n        '.join(zonenames))
                        continue

                if tz is not None:
                    time = datetime.datetime.now(tz).strftime('%H:%M:%S')
                    print("    Current time in {0}: {1}".format(answer, time))
                    answered = ask_yesno("Use this time zone?", True)
                else:
                    print(
                        "    ERROR: Time zone not found.  Please try again.  Time zones are case-sensitive."
                    )

            SAMPLE_CONF['TIMEZONE'] = answer
Example #11
0
File: init.py Project: rghv/nikola
        def tzhandler(default, toconf):
            print("\nPlease choose the correct time zone for your blog.  Nikola uses the tz database.")
            print("You can find your time zone here:")
            print("http://en.wikipedia.org/wiki/List_of_tz_database_time_zones")
            print("")
            answered = False
            while not answered:
                answer = ask("Time zone", "UTC")
                tz = dateutil.tz.gettz(answer)
                if tz is not None:
                    time = datetime.datetime.now(tz).strftime("%H:%M:%S")
                    print("    Current time in {0}: {1}".format(answer, time))
                    answered = ask_yesno("Use this time zone?", True)
                else:
                    print("    ERROR: Time zone not found.  Please try again.  Time zones are case-sensitive.")

            SAMPLE_CONF["TIMEZONE"] = answer
    def _execute(self, options, args):
        L = utils.get_logger('upgrade_metadata', self.site.loghandlers)
        nikola.post._UPGRADE_METADATA_ADVERTISED = True

        # scan posts
        self.site.scan_posts()
        flagged = []
        for post in self.site.timeline:
            if not post.newstylemeta:
                flagged.append(post)
        if flagged:
            if len(flagged) == 1:
                L.info('1 post contains old-style metadata:')
            else:
                L.info('{0} posts contain old-style metadata:'.format(
                    len(flagged)))
            for post in flagged:
                L.info('    ' + post.metadata_path)
            if not options['yes']:
                yesno = utils.ask_yesno("Proceed with metadata upgrade?")
            if options['yes'] or yesno:
                for post in flagged:
                    for lang in post.translated_to:
                        if lang == post.default_lang or len(
                                post.translated_to) == 1:
                            fname = post.metadata_path
                        else:
                            fname = self.site.config[
                                'TRANSLATIONS_PATTERN'].format(
                                    path=post.post_name, lang=lang, ext='meta')

                        with io.open(fname, 'r', encoding='utf-8') as fh:
                            meta = fh.readlines()
                        L.debug("post " + fname + " updated")

                        with io.open(fname, 'w', encoding='utf-8') as fh:
                            for k, v in zip(self.fields, meta):
                                fh.write('.. {0}: {1}'.format(k, v))

                L.info('{0} posts upgraded.'.format(len(flagged)))
            else:
                L.info('Metadata not upgraded.')
        else:
            L.info(
                'No old-style metadata posts found.  No action is required.')
Example #13
0
    def _execute(self, options, args):
        L = utils.get_logger('upgrade_metadata', utils.STDERR_HANDLER)
        nikola.post._UPGRADE_METADATA_ADVERTISED = True

        # scan posts
        self.site.scan_posts()
        flagged = []
        for post in self.site.timeline:
            if not post.newstylemeta:
                flagged.append(post)
        if flagged:
            if len(flagged) == 1:
                L.info('1 post (and/or its translations) contains old-style metadata:')
            else:
                L.info('{0} posts (and/or their translations) contain old-style metadata:'.format(len(flagged)))
            for post in flagged:
                L.info('    ' + post.metadata_path)
            if not options['yes']:
                yesno = utils.ask_yesno("Proceed with metadata upgrade?")
            if options['yes'] or yesno:
                for post in flagged:
                    for lang in self.site.config['TRANSLATIONS'].keys():
                        if lang == post.default_lang:
                            fname = post.metadata_path
                        else:
                            meta_path = os.path.splitext(post.source_path)[0] + '.meta'
                            fname = utils.get_translation_candidate(post.config, meta_path, lang)

                        if os.path.exists(fname):
                            with io.open(fname, 'r', encoding='utf-8') as fh:
                                meta = fh.readlines()

                            if not meta[min(1, len(meta) - 1)].startswith('.. '):
                                # check if we’re dealing with old style metadata
                                with io.open(fname, 'w', encoding='utf-8') as fh:
                                    for k, v in zip(self.fields, meta):
                                        fh.write('.. {0}: {1}'.format(k, v))
                                L.debug(fname)

                L.info('{0} posts upgraded.'.format(len(flagged)))
            else:
                L.info('Metadata not upgraded.')
        else:
            L.info('No old-style metadata posts found.  No action is required.')
Example #14
0
 def do_uninstall(self, name):
     """Uninstall a plugin."""
     for plugin in self.site.plugin_manager.getAllPlugins():  # FIXME: this is repeated thrice
         p = plugin.path
         if os.path.isdir(p):
             p = p + os.sep
         else:
             p = os.path.dirname(p)
         if name == plugin.name:  # Uninstall this one
             LOGGER.warning('About to uninstall plugin: {0}'.format(name))
             LOGGER.warning('This will delete {0}'.format(p))
             sure = utils.ask_yesno('Are you sure?')
             if sure:
                 LOGGER.warning('Removing {0}'.format(p))
                 shutil.rmtree(p)
                 return 0
             return 1
     LOGGER.error('Unknown plugin: {0}'.format(name))
     return 1
Example #15
0
 def do_uninstall(self, name):
     """Uninstall a plugin."""
     for plugin in self.site.plugin_manager.getAllPlugins():  # FIXME: this is repeated thrice
         p = plugin.path
         if os.path.isdir(p):
             p = p + os.sep
         else:
             p = os.path.dirname(p)
         if name == plugin.name:  # Uninstall this one
             LOGGER.warning('About to uninstall plugin: {0}'.format(name))
             LOGGER.warning('This will delete {0}'.format(p))
             sure = utils.ask_yesno('Are you sure?')
             if sure:
                 LOGGER.warning('Removing {0}'.format(p))
                 shutil.rmtree(p)
                 return 0
             return 1
     LOGGER.error('Unknown plugin: {0}'.format(name))
     return 1
Example #16
0
 def do_uninstall(self, name):
     """Uninstall a theme."""
     try:
         path = utils.get_theme_path_real(name, self.site.themes_dirs)
     except Exception:
         LOGGER.error('Unknown theme: {0}'.format(name))
         return 1
     # Don't uninstall builtin themes (Issue #2510)
     blocked = os.path.dirname(utils.__file__)
     if path.startswith(blocked):
         LOGGER.error("Can't delete builtin theme: {0}".format(name))
         return 1
     LOGGER.warning('About to uninstall theme: {0}'.format(name))
     LOGGER.warning('This will delete {0}'.format(path))
     sure = utils.ask_yesno('Are you sure?')
     if sure:
         LOGGER.warning('Removing {0}'.format(path))
         shutil.rmtree(path)
         return 0
     return 1
Example #17
0
 def do_uninstall(self, name):
     """Uninstall a theme."""
     try:
         path = utils.get_theme_path_real(name, self.site.themes_dirs)
     except Exception:
         LOGGER.error('Unknown theme: {0}'.format(name))
         return 1
     # Don't uninstall builtin themes (Issue #2510)
     blocked = os.path.dirname(utils.__file__)
     if path.startswith(blocked):
         LOGGER.error("Can't delete builtin theme: {0}".format(name))
         return 1
     LOGGER.warning('About to uninstall theme: {0}'.format(name))
     LOGGER.warning('This will delete {0}'.format(path))
     sure = utils.ask_yesno('Are you sure?')
     if sure:
         LOGGER.warning('Removing {0}'.format(path))
         shutil.rmtree(path)
         return 0
     return 1
    def _execute(self, options, args):
        L = utils.get_logger('upgrade_metadata', self.site.loghandlers)
        nikola.post._UPGRADE_METADATA_ADVERTISED = True

        # scan posts
        self.site.scan_posts()
        flagged = []
        for post in self.site.timeline:
            if not post.newstylemeta:
                flagged.append(post)
        if flagged:
            if len(flagged) == 1:
                L.info('1 post contains old-style metadata:')
            else:
                L.info('{0} posts contain old-style metadata:'.format(len(flagged)))
            for post in flagged:
                L.info('    ' + post.metadata_path)
            if not options['yes']:
                yesno = utils.ask_yesno("Proceed with metadata upgrade?")
            if options['yes'] or yesno:
                for post in flagged:
                    for lang in post.translated_to:
                        if lang == post.default_lang or len(post.translated_to) == 1:
                            fname = post.metadata_path
                        else:
                            ext = post.source_path.split(".")[-1]
                            fname = self.site.config['TRANSLATIONS_PATTERN'].format(path=post.post_name, lang=lang, ext='meta')
                    
                        with io.open(fname, 'r', encoding='utf-8') as fh:
                            meta = fh.readlines()
                        L.info("post " + fname + " updated")
                        
                        with io.open(fname, 'w', encoding='utf-8') as fh:
                            for k, v in zip(self.fields, meta):
                                fh.write('.. {0}: {1}'.format(k, v))
                        
                L.info('{0} posts upgraded.'.format(len(flagged)))
            else:
                L.info('Metadata not upgraded.')
        else:
            L.info('No old-style metadata posts found.  No action is required.')
Example #19
0
 def do_uninstall(self, name):
     """Uninstall a plugin."""
     for plugin in self.site.plugin_manager.getAllPlugins():  # FIXME: this is repeated thrice
         if name == plugin.name:  # Uninstall this one
             p = plugin.path
             if os.path.isdir(p):
                 # Plugins that have a package in them need to delete parent
                 # Issue #2356
                 p = p + os.sep
                 p = os.path.abspath(os.path.join(p, os.pardir))
             else:
                 p = os.path.dirname(p)
             LOGGER.warning('About to uninstall plugin: {0}'.format(name))
             LOGGER.warning('This will delete {0}'.format(p))
             sure = utils.ask_yesno('Are you sure?')
             if sure:
                 LOGGER.warning('Removing {0}'.format(p))
                 shutil.rmtree(p)
                 return 0
             return 1
     LOGGER.error('Unknown plugin: {0}'.format(name))
     return 1
Example #20
0
 def do_uninstall(self, name):
     """Uninstall a plugin."""
     for plugin in self.site.plugin_manager.getAllPlugins():  # FIXME: this is repeated thrice
         if name == plugin.name:  # Uninstall this one
             p = plugin.path
             if os.path.isdir(p):
                 # Plugins that have a package in them need to delete parent
                 # Issue #2356
                 p = p + os.sep
                 p = os.path.abspath(os.path.join(p, os.pardir))
             else:
                 p = os.path.dirname(p)
             LOGGER.warning('About to uninstall plugin: {0}'.format(name))
             LOGGER.warning('This will delete {0}'.format(p))
             sure = utils.ask_yesno('Are you sure?')
             if sure:
                 LOGGER.warning('Removing {0}'.format(p))
                 shutil.rmtree(p)
                 return 0
             return 1
     LOGGER.error('Unknown plugin: {0}'.format(name))
     return 1
Example #21
0
 def prettyhandler(default, toconf):
     SAMPLE_CONF['PRETTY_URLS'] = ask_yesno(
         'Enable pretty URLs (/page/ instead of /page.html) that don\'t need web server configuration?',
         default=True)
     SAMPLE_CONF['STRIP_INDEXES'] = SAMPLE_CONF['PRETTY_URLS']
Example #22
0
 def prettyhandler(default, toconf):
     SAMPLE_CONF["PRETTY_URLS"] = ask_yesno(
         "Enable pretty URLs (/page/ instead of /page.html) that don't need web server configuration?",
         default=True,
     )
     SAMPLE_CONF["STRIP_INDEXES"] = SAMPLE_CONF["PRETTY_URLS"]
Example #23
0
    def _execute(self, options, args):
        L = utils.get_logger('upgrade_metadata_v8', utils.STDERR_HANDLER)

        if not self.site.config['USE_TAG_METADATA']:
            L.error('This plugin can only be used if USE_TAG_METADATA is set to True.')
            sys.exit(-1)
        self.site.config['WARN_ABOUT_TAG_METADATA'] = False

        # scan posts
        self.site.scan_posts()
        flagged = []
        for post in self.site.timeline:
            flag = False
            if post.has_oldstyle_metadata_tags:
                flag = True
            for lang in self.site.config['TRANSLATIONS'].keys():
                if 'section' in post.meta[lang]:
                    flag = True
            if flag:
                flagged.append(post)
        if flagged:
            if len(flagged) == 1:
                L.info('1 post (and/or its translations) contains old-style metadata or has section metadata:')
            else:
                L.info('{0} posts (and/or their translations) contain old-style metadata or have section metadata:'.format(len(flagged)))
            for post in flagged:
                L.info('    ' + (post.metadata_path if post.is_two_file else post.source_path))
            L.warn('Please make a backup before running this plugin. It might eat your data.')
            if not options['yes']:
                yesno = utils.ask_yesno("Proceed with metadata upgrade?")
            if options['yes'] or yesno:
                number_converted = 0
                number_converted_partial = 0
                for post in flagged:
                    converted = False
                    fully_converted = True
                    for lang in self.site.config['TRANSLATIONS'].keys():
                        # Get file names and extractor
                        extractor = post.used_extractor[lang]
                        is_two_file = post.is_two_file
                        if lang == post.default_lang:
                            fname = post.metadata_path if is_two_file else post.source_path
                        else:
                            meta_path = os.path.splitext(post.source_path)[0] + '.meta' if is_two_file else post.source_path
                            fname = utils.get_translation_candidate(post.config, meta_path, lang)

                        # We don't handle compilers which extract metadata for now
                        if post.compiler is extractor:
                            L.warn('Cannot convert {0} (language {1}), as metadata was extracted by compiler.'.format(fname, lang))
                            fully_converted = False
                            continue

                        # Read metadata and text from post file
                        if not os.path.exists(fname):
                            L.debug("File {0} does not exist, skipping.".format(fname))
                            continue

                        with io.open(fname, "r", encoding="utf-8-sig") as meta_file:
                            source_text = meta_file.read()
                        if not is_two_file:
                            _, content_str = extractor.split_metadata_from_text(source_text)
                        meta = extractor.extract_text(source_text)

                        # Consider metadata mappings
                        sources = {}
                        for m in ('tags', 'status', 'has_math', 'section', 'category'):
                            sources[m] = m
                        for foreign, ours in self.site.config.get('METADATA_MAPPING', {}).get(extractor.map_from, {}).items():
                            if ours in sources:
                                sources[ours] = foreign
                        for meta_key, hook in self.site.config.get('METADATA_VALUE_MAPPING', {}).get(extractor.map_from, {}).items():
                            if meta_key in sources.values():
                                L.warn('Cannot convert {0} (language {1}): a metadata value mapping is defined for "{2}"!'.format(fname, lang, meta_key))

                        # Update metadata
                        updated = False
                        tags = meta.get(sources['tags'], [])
                        tags_are_string = False
                        if not isinstance(tags, list):
                            tags_are_string = True
                            tags = [tag.strip() for tag in tags.split(',') if tag.strip()]

                        if 'draft' in [_.lower() for _ in tags]:
                            tags.remove('draft')
                            meta[sources['status']] = 'draft'
                            updated = True

                        if 'private' in tags:
                            tags.remove('private')
                            meta[sources['status']] = 'private'
                            updated = True

                        if 'mathjax' in tags:
                            tags.remove('mathjax')
                            meta[sources['has_math']] = 'yes'
                            updated = True

                        if meta.get(sources['section']):
                            if meta.get(sources['category']):
                                L.warn('Cannot completely {0} (language {1}): both section and category are specified. Please determine the correct category to use yourself!'.format(fname, lang))
                                fully_converted = False
                            else:
                                meta[sources['category']] = meta[sources['section']]
                                del meta[sources['section']]
                                updated = True

                        if tags_are_string:
                            meta[sources['tags']] = ', '.join(tags)

                        if not updated:
                            # Nothing to do (but successful)!
                            converted = True
                            continue

                        # Recombine metadata with post text if necessary, and write back to file
                        meta_str = utils.write_metadata(meta, metadata_format=extractor.name, compiler=post.compiler,
                                                        comment_wrap=(post.compiler.name != 'rest'), site=self.site)
                        final_str = meta_str if is_two_file else (meta_str + content_str)

                        with io.open(fname, "w", encoding="utf-8") as meta_file:
                            meta_file.write(final_str)
                            converted = True

                    if converted:
                        if fully_converted:
                            number_converted += 1
                        else:
                            number_converted_partial += 1

                L.info('{0} out of {2} posts upgraded; {1} only converted partially '
                       '(see above output).'.format(number_converted + number_converted_partial, number_converted_partial, len(flagged)))
            else:
                L.info('Metadata not upgraded.')
        else:
            L.info('No posts found with special tags or section metadata.  No action is required.')
            L.info('You can safely set the USE_TAG_METADATA and the WARN_ABOUT_TAG_METADATA settings to False.')
Example #24
0
 def prettyhandler(default, toconf):
     SAMPLE_CONF['PRETTY_URLS'] = ask_yesno('Enable pretty URLs (/page/ instead of /page.html) that don\'t need web server configuration?', default=True)
     SAMPLE_CONF['STRIP_INDEXES'] = SAMPLE_CONF['PRETTY_URLS']