Source

vimpire / vimpire.py

Full commit
#!/usr/bin/env python3

import os
import re

from os.path import exists, expanduser, join, basename
from subprocess import check_call
from urllib.request import urlretrieve

HOME = expanduser('~')

VIMRC = join(HOME, '.vimrc')
VIMRUNTIME = join(HOME, '.vim')
AUTOLOAD = join(VIMRUNTIME, 'autoload')
BUNDLE_DIR = join(VIMRUNTIME, 'bundle')

PATHOGEN = join(AUTOLOAD, 'pathogen.vim')
PATHOGEN_URL = ('https://raw.github.com/tpope/vim-pathogen'
                '/HEAD/autoload/pathogen.vim')

PLUGIN_RE = re.compile(r'" plugin: (ht|git|svn|vim) (\S+) ?(\S+)?')


def sh(cmd, *args, **kwargs):
    print('Executing: %s' % ' '.join(cmd))
    check_call(cmd, *args, **kwargs)


def check_env():
    if not os.path.exists(PATHOGEN):
        if not os.path.exists(AUTOLOAD):
            os.makedirs(AUTOLOAD)
        print('Installing pathogen.vim...')
        urlretrieve(PATHOGEN_URL, PATHOGEN)

    if not os.path.exists(BUNDLE_DIR):
        os.makedirs(BUNDLE_DIR)


def get_plugins(extra_lines=5):
    plugins = []
    read_more = extra_lines
    pathogen_found = False
    with open(VIMRC) as f:
        for line in f:
            if line.startswith('" plugin: '):
                m = PLUGIN_RE.match(line)
                if m:
                    plugins.append(m.groups())
                    read_more = extra_lines
            elif line.startswith('call pathogen#infect'):
                pathogen_found = True

            if read_more <= 0:
                break

            read_more -= 1

    if not pathogen_found:
        raise Exception('It seems, that pathogen is not configured.\n'
                        'Make sure, that you have\n'
                        '\n'
                        '    call pathogen#infect()\n'
                        '\n'
                        'line at the top of your ~/.vimrc file.\n')

    return plugins


def handle_git(path, name):
    if name is None:
        if path.endswith('.git'):
            name = basename(path)[:-4]
        else:
            name = basename(path)

    if not exists(join(BUNDLE_DIR, name)):
        sh(['git', 'clone', path, name])
        return True

    return False

        
def main():
    plugins = get_plugins()
    check_env()

    handlers = {
        'git': handle_git,
    }

    os.chdir(BUNDLE_DIR)

    installed_plugins = []
    for plugin in plugins:
        args = list(plugin)
        handler = handlers[args.pop(0)]
        if handler(*args):
            installed_plugins.append(args[0])

    # Update help tags
    if len(installed_plugins):
        sh(['vim', '-c', 'Helptags', '-c', 'q'])


if __name__ == '__main__':
    main()