Ejemplo n.º 1
0
 def __init__(self, path, config, title, date="", categories="", tags="", content="", slug="", **extras):
     self.path = path
     self.title = title
     self.pub_time = datetime.strptime(date, "%Y-%m-%d %H:%M")
     self.categories = []
     self.raw_categories = self.__class__.generate_list(categories)
     self.tags = []
     self.raw_tags = self.__class__.generate_list(tags)
     md = markdown.Markdown(
         extensions=["fenced_code", "codehilite", "tables", ImgExtExtension()],
         extension_configs=MARKDOWN_EXTENSION_CONFIG,
     )
     md.config = config
     md.inlinePatterns["image_link"] = CheckImagePattern(IMAGE_LINK_RE, md, config)
     self.content = md.convert(content)
     self.images = md.images
     self.front_content = self.content.split("<!--more-->")[0]
     self.author = extras["author"] if "author" in extras else config.author
     if slug:
         self.slug = slug.replace(".", "")
     else:
         pinyin = PinYin()
         pinyin.load_word()
         self.slug = pinyin.hanzi2pinyin_split(string=self.title, split="-").lower().replace(".", "")
     self.url = self.generate_url(config.permalink)
     for name, value in extras.iteritems():
         setattr(self, name, value)
Ejemplo n.º 2
0
 def create_page():
     config = Command.load_config()
     title = logger.info_input("Page Title")
     url = logger.info_input("Page URL (.e.g, /foo/bar/):")
     description = logger.info_input("Page Description:")
     pinyin = PinYin()
     slug = pinyin.hanzi2pinyin_split(string=title, split="-")
     now = datetime.now()
     pub_date = now.strftime("%Y-%m-%d %H:%M")
     page = PAGE_SAMPLE.format(title, pub_date, url, description)
     file_path = os.path.join(config.pages_dir, "{0}.markdown".format(slug))
     open(os.path.join(config.base_dir, file_path), "w+").write(page)
     logger.success("You can browse the page by {0} After generating the site.".format(url))
Ejemplo n.º 3
0
 def create_post(post_title="sample post"):
     config = Command.load_config()
     now = datetime.now()
     pub_time = unicode(now.strftime("%Y-%m-%d %H:%M"))
     pinyin = PinYin()
     pinyin.load_word()
     slug = pinyin.hanzi2pinyin_split(string=post_title, split="-")
     new_post = POST_SAMPLE.format(post_title.decode("utf8"), pub_time, slug)
     file_title = "{0}-{1}.markdown".format(unicode(now.strftime("%Y-%m-%d")), post_title.decode("utf8"))
     absolute_file_path = os.path.join(config.base_dir, (os.path.join(config.posts_dir, file_title)))
     if not os.path.exists(absolute_file_path):
         open(os.path.join(config.base_dir, absolute_file_path.encode("utf8")), "w+").write(new_post.encode("utf8"))
     else:
         logger.error("File exists: {0}".format(absolute_file_path))
Ejemplo n.º 4
0
 def create_page():
     if not os.path.exists(settings.CONFIG_PATH):
         logger.error('No "_config.yml" file found for the current directory.')
         sys.exit()
     title = logger.info_input('Page Title')
     url = logger.info_input('Page URL (.e.g, /foo/bar/):')
     description = logger.info_input('Page Description:')
     pinyin = PinYin()
     slug = pinyin.hanzi2pinyin_split(string=title, split="-")
     now = datetime.now()
     pub_date = now.strftime("%Y-%m-%d %H:%M")
     page = PAGE_SAMPLE.format(title, pub_date, url, description)
     file_path = os.path.join(settings.PAGES_DIR, slug + '.markdown')
     open(os.path.join(settings.BASE_DIR, file_path), 'w+').write(page)
     logger.success('You can browse the page by {0} After generating the site.'.format(url))
Ejemplo n.º 5
0
    def save(self, content):
        get_header = re.compile(r'---[\s\S]*?---')
        self.header = get_header.findall(content)[0]
        self.content = content.replace(self.header, '', 1)
        self.save_html()
        self.header = self.header.replace('---', '')
        post_info = yaml.load(self.header)
        for item in post_info:
            '''
            if item is date, convert it to datetime object, then save it to post.pub_time.
            if item is categories, to save it to post.categories as a list.
            if item is tags, save it to post.tags as a list, too.
            '''
            if item == 'date':
                pub_time = datetime.strptime(
                    post_info['date'],
                    "%Y-%m-%d %H:%M")
                setattr(self, 'pub_time', pub_time)
            elif item == 'categories' or item == 'tags':
                if isinstance(post_info[item], str):
                    setattr(self, item, post_info[item].split(','))
                elif isinstance(post_info[item], list):
                    setattr(self, item, post_info[item])
                else:
                    setattr(self, item, [])
            elif item == 'title' or item == 'slug':
                if isinstance(item, int):
                    setattr(self, item, str(post_info[item]))
                else:
                    setattr(self, item, post_info[item])
            else:
                setattr(self, item, post_info[item])

        if 'author' not in post_info:
            self.author = self.config.author

        if 'slug' not in post_info:
            '''
            if there is key "slug" in post_info, use it as the url.
            if there isn't, we generate post url from title.
            PinYin is used for converting Chinese to Chinese pinyin.
            '''
            slug = PinYin()
            slug.load_word()
            self.slug = slug.hanzi2pinyin_split(string=self.title, split="-")
        self.generate_url()
Ejemplo n.º 6
0
    def save(self, content):
        get_header = re.compile(r'---[\s\S]*?---')
        self.header = get_header.findall(content)[0]
        self.content = content.replace(self.header, '', 1)
        self.save_html()
        self.header = self.header.replace('---', '')
        post_info = yaml.load(self.header)
        for item in post_info:
            '''
            if item is date, convert it to datetime object, then save it to post.pub_time.
            if item is categories, to save it to post.categories as a list.
            if item is tags, save it to post.tags as a list, too.
            '''
            if item == 'date':
                pub_time = datetime.strptime(post_info['date'],
                                             "%Y-%m-%d %H:%M")
                setattr(self, 'pub_time', pub_time)
            elif item == 'categories' or item == 'tags':
                if isinstance(post_info[item], str):
                    setattr(self, item, post_info[item].split(','))
                elif isinstance(post_info[item], list):
                    setattr(self, item, post_info[item])
                else:
                    setattr(self, item, [])
            elif item == 'title' or item == 'slug':
                if isinstance(item, int):
                    setattr(self, item, str(post_info[item]))
                else:
                    setattr(self, item, post_info[item])
            else:
                setattr(self, item, post_info[item])

        if 'author' not in post_info:
            self.author = self.config.author

        if 'slug' not in post_info:
            '''
            if there is key "slug" in post_info, use it as the url.
            if there isn't, we generate post url from title.
            PinYin is used for converting Chinese to Chinese pinyin.
            '''
            slug = PinYin()
            slug.load_word()
            self.slug = slug.hanzi2pinyin_split(string=self.title, split="-")
        self.generate_url()
Ejemplo n.º 7
0
def create_page(config):
    flag = 0
    if len(sys.argv) == 1:
        title = raw_input('Page Title:')
        url = raw_input('Page URL(For example, /foo/bar/):')
        description = raw_input('Page Description(For SEO):')
        pinyin = PinYin()
        slug = pinyin.hanzi2pinyin_split(string=title, split="-")
        dt = datetime.now()
        date = dt.strftime("%Y-%m-%d %H:%M")
        open('source/pages/'+ slug +'.markdown', 'w+').write(SAMPLE % (title, date, url, description))
        print 'You can check browse the page by ' + config.url + '/' + url + ' After generating the site.'

    elif len(sys.argv) != 1:
        open('_posts/' + file_title, 'w+').write(new_post)
    else:
        usraccount = sys.argv[1]
        passwd = sys.argv[2]
Ejemplo n.º 8
0
 def create_page():
     if not os.path.exists(settings.CONFIG_PATH):
         logger.error(
             'No "_config.yml" file found for the current directory.')
         sys.exit()
     title = logger.info_input('Page Title')
     url = logger.info_input('Page URL (.e.g, /foo/bar/):')
     description = logger.info_input('Page Description:')
     pinyin = PinYin()
     slug = pinyin.hanzi2pinyin_split(string=title, split="-")
     now = datetime.now()
     pub_date = now.strftime("%Y-%m-%d %H:%M")
     page = PAGE_SAMPLE.format(title, pub_date, url, description)
     file_path = os.path.join(settings.PAGES_DIR, slug + '.markdown')
     open(os.path.join(settings.BASE_DIR, file_path), 'w+').write(page)
     logger.success(
         'You can browse the page by {0} After generating the site.'.format(
             url))
Ejemplo n.º 9
0
 def create_post():
     if not os.path.exists(settings.CONFIG_PATH):
         logger.error('No "_config.yml" file found for the current directory.')
         sys.exit()
     if len(sys.argv) != 3:
         logger.error('Please specify the post title.')
     else:
         title = sys.argv[2]
         now = datetime.now()
         pub_time = now.strftime('%Y-%m-%d %H:%M')
         pinyin = PinYin()
         pinyin.load_word()
         slug = pinyin.hanzi2pinyin_split(string=title, split='-')
         new_post = POST_SAMPLE.format(title, pub_time, slug)
         file_title = now.strftime("%Y-%m-%d") + '-' + slug + '.markdown'
         file_path = os.path.join(settings.POSTS_DIR, file_title)
         open(os.path.join(settings.BASE_DIR, file_path), 'w+').write(new_post)
         logger.success(' '.join([file_path, 'created.']))
Ejemplo n.º 10
0
def create_post(config):
    flag = 0
    if len(sys.argv) == 1:
        usage()
    elif len(sys.argv) != 1:
        post = Post(config)
        pinyin = PinYin()
        pinyin.load_word()
        string = sys.argv[1]  # Assume that argv[1] is the title user inputed.
        post.title = string
        post.slug = pinyin.hanzi2pinyin_split(string=string, split="-")
        dt = datetime.now()
        post.pub_time = dt.strftime("%Y-%m-%d %H:%M")
        new_post = SAMPLE % (post.title, post.pub_time, post.slug)
        file_title = dt.strftime("%Y-%m-%d") + '-' + post.slug + '.markdown'
        target = os.path.normpath(os.path.join('source/posts', file_title))
        open(target, 'w+').write(new_post)
    else:
        usage()
Ejemplo n.º 11
0
def create_post(config):
    flag = 0
    if len(sys.argv) == 1:
        usage()
    elif len(sys.argv) != 1:
        post = Post(config)
        pinyin = PinYin()
        pinyin.load_word()
        string = sys.argv[1]  # Assume that argv[1] is the title user inputed.
        post.title = string
        post.slug = pinyin.hanzi2pinyin_split(string=string, split="-")
        dt = datetime.now()
        post.pub_time = dt.strftime("%Y-%m-%d %H:%M")
        new_post = SAMPLE % (post.title, post.pub_time, post.slug)
        file_title = dt.strftime("%Y-%m-%d") + '-' + post.slug + '.markdown'
        target = os.path.normpath(os.path.join('source/posts', file_title))
        open(target, 'w+').write(new_post)
    else:
        usage()
Ejemplo n.º 12
0
 def create_post():
     if not os.path.exists(settings.CONFIG_PATH):
         logger.error(
             'No "_config.yml" file found for the current directory.')
         sys.exit()
     if len(sys.argv) != 3:
         logger.error('Please specify the post title.')
     else:
         title = sys.argv[2]
         now = datetime.now()
         pub_time = now.strftime('%Y-%m-%d %H:%M')
         pinyin = PinYin()
         pinyin.load_word()
         slug = pinyin.hanzi2pinyin_split(string=title, split='-')
         new_post = POST_SAMPLE.format(title, pub_time, slug)
         file_title = now.strftime("%Y-%m-%d") + '-' + slug + '.markdown'
         file_path = os.path.join(settings.POSTS_DIR, file_title)
         open(os.path.join(settings.BASE_DIR, file_path),
              'w+').write(new_post)
         logger.success(' '.join([file_path, 'created.']))
Ejemplo n.º 13
0
def create_page(config):
    flag = 0
    if len(sys.argv) == 1:
        title = raw_input('Page Title:')
        url = raw_input('Page URL(For example, /foo/bar/):')
        description = raw_input('Page Description(For SEO):')
        pinyin = PinYin()
        slug = pinyin.hanzi2pinyin_split(string=title, split="-")
        dt = datetime.now()
        date = dt.strftime("%Y-%m-%d %H:%M")
        target = os.path.normpath(
            os.path.join(
                "source/pages",
                slug +
                '.markdown'))
        open(target, 'w+').write(SAMPLE % (title, date, url, description))
        print 'You can check browse the page by ' + config.url + '/' + url + ' After generating the site.'

    elif len(sys.argv) != 1:
        open(os.path.join('_posts', file_title), 'w+').write(new_post)
    else:
        usraccount = sys.argv[1]
        passwd = sys.argv[2]
Ejemplo n.º 14
0
                    setattr(self, item, str(post_info[item]))
                else:
                    setattr(self, item, post_info[item])
            else:
                setattr(self, item, post_info[item])

        if 'author' not in post_info:
            self.author = settings.author

        if 'slug' not in post_info:
            '''
            if there is key "slug" in post_info, use it as the url.
            if there isn't, we generate post url from title.
            PinYin is used for converting Chinese to Chinese pinyin.
            '''
            slug = PinYin()
            slug.load_word()
            self.slug = slug.hanzi2pinyin_split(string=self.title, split="-")
        self.generate_url()

    def generate_url(self):
        '''
        Save the post url, refering to the permalink in the config file.
        The permalink is seperated into servel parts from '/'.
        If one part of it startswith ':', then we should find whether there
            is attribute with the same name in the post.
        If not, we regard it as a string

        example:
        post/:year/:month/:title
        will be generated to a url like 'crotal.org/post/2013/11/hello-world/'