コード例 #1
0
ファイル: setup.py プロジェクト: ashumeow/petroglyph
def generate_config():
    logger.log("Configuring settings...")
    if os.path.exists("config.yaml"):
        logger.log("The file " + os.path.join(os.getcwd(), "config.yaml") + " already exists.", logger.WARNING)
        print "Would you like to replace it? (y/n)",
        response = raw_input()
        if response.lower() != "y":
            return
    blog_config = {}
    blog_title = raw_input("Blog title: ").strip()
    if blog_title is not "":
        blog_config["title"] = blog_title
    blog_author = raw_input("Blog author: ").strip()
    if blog_author is not "":
        blog_config["author"] = blog_author
    blog_description = raw_input("Blog description: ").strip()
    if blog_description is not "":
        blog_config["description"] = blog_description
    import yaml

    f = open("config.yaml", "w")
    yaml.dump(blog_config, f, default_flow_style=False)
    logger.log("Saved configuration in config.yaml.", logger.SUCCESS)
コード例 #2
0
ファイル: petroglyph.py プロジェクト: ashumeow/petroglyph
parser.add_argument("--regenerate", action='store_true', help="force regeneration of all posts")
parser.add_argument("--dry-run", action='store_true', help="perform only a dry run")
parser.add_argument("--skin", default="monoblue", help="specify the skin to be used")

args = parser.parse_args()

def init():
    from petroglyph import setup
    setup.init(args.skin)

if args.command is None:
    args.command = 'generate'

if args.command == 'init':
    init()

elif args.command == 'generate':
    if not os.path.exists('config.yaml'):
        logger.log("Petroglyph has not been initialized.", logger.WARNING)
        print "Would you like to initialize it now? (y/n)",
        response = raw_input()
        if response == 'y':
            init()
        else:
            logger.log("Aborting.", logger.ERROR)
    else:
        from petroglyph import generator
        generator.generate(args.regenerate, args.dry_run)
else:
    logger.log("Invalid command '%s'." % args.command, logger.ERROR)
コード例 #3
0
ファイル: setup.py プロジェクト: ashumeow/petroglyph
def init(skin):
    skin = str(skin).strip()
    petroglyph_root = os.path.dirname(os.path.abspath(__file__))
    logger.log("Copying skin '%s'..." % skin)
    if not os.path.exists(os.path.join(petroglyph_root, "skins", skin)):
        logger.log("Skin '%s' does not exist. Exiting." % skin, logger.ERROR)
        import sys

        sys.exit(1)
    try:
        shutil.copytree(os.path.join(petroglyph_root, "skins", skin), "skin")
    except OSError:
        logger.log("The path " + os.path.join(os.getcwd(), "skin") + " already exists.", logger.WARNING)
        print "Would you like to replace it? (y/n)",
        response = raw_input()
        if response.lower() == "y":
            logger.log("Replacing skin...")
            try:
                shutil.rmtree("skin")
                shutil.copytree(os.path.join(petroglyph_root, "skins", skin), "skin")
            except OSError:
                logger.log("Error: Could not replace skin. Exiting.", logger.ERROR)
                exit()
    logger.log("Creating posts directory...")
    try:
        os.mkdir("posts")
    except OSError:
        logger.log("Directory exists.", logger.SUCCESS)
    generate_config()
    logger.log("Petroglyph initialized.", logger.SUCCESS)
コード例 #4
0
ファイル: generator.py プロジェクト: ashumeow/petroglyph
def generate(regenerate=False, dry_run=False):
    cwd = os.getcwd()
    with open(os.path.join(cwd, 'config.yaml'), 'rb') as f:
        config = yaml.safe_load(f)
    drafts = [file for file in os.listdir(os.path.join(cwd, 'posts')) if file[0] != '.']
    posts = []
    for draft in drafts:
        posts.append(Post(file=os.path.join('posts', draft)))
    skin = {}
    with open(os.path.join('skin', 'post.html'), 'rb') as f:
        skin['post'] = f.read()
    with open(os.path.join('skin', 'post-peek.html'), 'rb') as f:
        skin['post-peek'] = f.read()
    with open(os.path.join('skin', 'home.html')) as f:
        skin['home'] = f.read()
    if not os.path.isdir('blog'):
        os.mkdir('blog')
    if os.path.exists('.petroglyph-metadata'):
        with open('.petroglyph-metadata', 'rb') as f:
            posts_meta = yaml.safe_load(f)
    else:
        posts_meta = {}
    post_previews_text = []
    os.chdir('blog')
    logger.log("Found %d post%s." % (len(posts), '' if len(posts) == 1 else 's'))
    stats = {}
    stats['new_posts'] = 0
    stats['changed_posts'] = 0
    stats['regenerated_posts'] = 0
    stats['generated_posts'] = 0
    current_posts_slugs = []

    for post in posts:
        current_posts_slugs.append(post.slug)
        if post.slug in posts_meta:
            post.mtime = posts_meta[post.slug]['mtime']
            new = False
        else:
            new = True
            stats['new_posts'] += 1
        if not os.path.exists(post.slug):
            os.mkdir(post.slug)
        post_hash = post.get_hash()
        if not new and post_hash != posts_meta[post.slug]['hash']:
            stats['changed_posts'] += 1
        if regenerate or new or post_hash != posts_meta[post.slug]['hash']:
            posts_meta[post.slug] = {'mtime': post.mtime, 'hash': post_hash}
            post_args = {
                'title': post.title,
                'tags': ''.join(
                    ['<span class="tag">#' + tag + '</span>' for tag in post.tags]
                ),
                'blog_title': config['title'],
                'date': post.getmtime(),
                'content': post.get_html()
            }
            if not dry_run:
                if not new:
                    stats['regenerated_posts'] += 1
                else:
                    stats['generated_posts'] += 1
                with open(os.path.join(post.slug, 'index.html'), 'wb') as post_file:
                    post_file.write(process_template(skin['post'], post_args))

    posts.sort(key=lambda p: p.get_time(), reverse=True)
    for post in posts:
        post_peek_args = {
            'slug': post.slug,
            'title': post.title,
            'date': post.getmtime(),
            'peek': post.get_preview(),
            'tags': ''.join(
                ['<span class="tag">#' + tag + '</span>' for tag in post.tags]
            )
        }
        post_previews_text.append(process_template(skin['post-peek'], post_peek_args))
    home_args = {
        'title': config['title'],
        'author': config['author'],
        'description': config['description'],
        'posts': "\n".join(post_previews_text)
    }
    if stats['new_posts']:
        logger.log(
            "%s new post%s." % (
                stats['new_posts'],
                '' if stats['new_posts'] == 1 else 's'
            ),
            logger.SUCCESS
        )
    if stats['changed_posts']:
        logger.log(
            "%s changed post%s." % (
                stats['changed_posts'],
                '' if stats['changed_posts'] == 1 else 's'
            ),
            logger.WARNING
        )
    if not dry_run and (regenerate or stats['new_posts'] + stats['changed_posts'] > 0):
        with open('index.html', 'wb') as f:
            f.write(process_template(skin['home'], home_args))

    deleted_posts = set(posts_meta).difference(current_posts_slugs)
    stats['deleted_posts'] = len(deleted_posts)

    if stats['deleted_posts']:
        logger.log(
            "%s deleted post%s." % (
                stats['deleted_posts'],
                '' if stats['deleted_posts'] == 1 else 's'
            ),
            logger.ERROR
        )

    if stats['new_posts'] + stats['changed_posts'] + stats['deleted_posts'] == 0:
        logger.log("No changes to make.")

    if not dry_run:
        for deleted_post in deleted_posts:
            del posts_meta[deleted_post]
            try:
                shutil.rmtree(deleted_post)
            except:
                logger.log("Failed to delete '%s'." % deleted_post, logger.ERROR)
        if stats['deleted_posts']:
            logger.log(
                "Deleted %s old post%s." % (
                    stats['deleted_posts'],
                    '' if stats['deleted_posts'] == 1 else 's'
                ),
                logger.SUCCESS
            )
    os.chdir(os.pardir)
    if not dry_run:
        with open('.petroglyph-metadata', 'wb') as f:
            yaml.dump(posts_meta, f)
        paths = os.listdir('skin')
        for path in paths:
            if os.path.isdir(os.path.join('skin', path)):
                if os.path.exists(os.path.join('blog', path)):
                    shutil.rmtree(os.path.join('blog', path))
                shutil.copytree(os.path.join('skin', path), os.path.join('blog', path))
    if ((stats['generated_posts'] or stats['regenerated_posts'] or stats['deleted_posts'])
            and not dry_run):
        if stats['generated_posts']:
            logger.log(
                "Generated %s new post%s." % (
                    stats['generated_posts'],
                    '' if stats['generated_posts'] == 1 else 's'
                ),
                logger.SUCCESS
            )
        if stats['regenerated_posts']:
            logger.log(
                "Regenerated %s post%s." % (
                    stats['regenerated_posts'],
                    '' if stats['regenerated_posts'] == 1 else 's'
                ),
                logger.SUCCESS
            )
    if not dry_run:
        logger.log("Done.", logger.SUCCESS)