Ejemplo n.º 1
0
def init(conf, *args, **opts):
    if not args:
        dest = os.getcwd()
    else:
        dest = os.path.normpath(os.path.join(os.getcwd(), args[0]))

    if dest is None:
        raise AppError('Unknown dest')

    if opts['empty'] and opts['template']:
        raise AppError('option "empty" cannot use with "template"')

    if util.iscouchapp(dest):
        raise AppError("can't create an app at '{0}'. "
                       "One already exists here.".format(dest))

    if util.findcouchapp(dest):
        raise AppError("can't create an app inside another app '{0}'.".format(
                       util.findcouchapp(dest)))

    # ``couchapp init -e dest``
    if opts['empty']:
        document(dest, create=True)

    # ``couchapp init -t template_name dest``
    elif opts['template']:
        generator.init_template(dest, template=opts['template'])

    # ``couchapp init dest``
    else:
        generator.init_basic(dest)

    logger.info('{0} created.'.format(dest))

    return 0
Ejemplo n.º 2
0
def init_basic(path):
    '''
    Generate a basic CouchApp which contain following files::

        /path/
            .couchapprc
            .couchappignore
            _attachments/
            lists/
            shows/
            updates/
            views/
    '''
    setup_dir(path, require_empty=True)

    for n in DEFAULT_APP_TREE:
        tp = os.path.join(path, n)
        os.makedirs(tp)

    fid = os.path.join(path, '_id')
    if not os.path.isfile(fid):
        with open(fid, 'wb') as f:
            f.write('_design/{0}'.format(os.path.split(path)[1]))

    localdoc.document(path, create=True)
Ejemplo n.º 3
0
def init(conf, *args, **opts):
    if not args:
        dest = os.getcwd()
    else:
        dest = os.path.normpath(os.path.join(os.getcwd(), args[0]))

    if dest is None:
        raise AppError('Unknown dest')

    if opts['empty'] and opts['template']:
        raise AppError('option "empty" cannot use with "template"')

    if util.iscouchapp(dest):
        raise AppError("can't create an app at '{0}'. "
                       "One already exists here.".format(dest))

    if util.findcouchapp(dest):
        raise AppError("can't create an app inside another app '{0}'.".format(
            util.findcouchapp(dest)))

    # ``couchapp init -e dest``
    if opts['empty']:
        document(dest, create=True)

    # ``couchapp init -t template_name dest``
    elif opts['template']:
        generator.init_template(dest, template=opts['template'])

    # ``couchapp init dest``
    else:
        generator.init_basic(dest)

    logger.info('{0} created.'.format(dest))

    return 0
Ejemplo n.º 4
0
def init_basic(path):
    '''
    Generate a basic CouchApp which contain following files::

        /path/
            .couchapprc
            .couchappignore
            _attachments/
            lists/
            shows/
            updates/
            views/
    '''
    setup_dir(path, require_empty=True)

    for n in DEFAULT_APP_TREE:
        tp = os.path.join(path, n)
        os.makedirs(tp)

    fid = os.path.join(path, '_id')
    if not os.path.isfile(fid):
        with open(fid, 'wb') as f:
            f.write('_design/{0}'.format(os.path.split(path)[1]))

    localdoc.document(path, create=True)
Ejemplo n.º 5
0
def init(conf, path, *args, **opts):
    if not args:
        dest = os.getcwd()
    else:
        dest = os.path.normpath(os.path.join(os.getcwd(), args[0]))
        
    if dest is None:
        raise AppError("Unknown dest")
        
    document(dest, True)
Ejemplo n.º 6
0
def init(conf, path, *args, **opts):
    if not args:
        dest = os.getcwd()
    else:
        dest = os.path.normpath(os.path.join(os.getcwd(), args[0]))

    if dest is None:
        raise AppError("Unknown dest")

    document(dest, True)
Ejemplo n.º 7
0
def generate_app(path, template=None, create=False):
    """ Generates a CouchApp in app_dir

    :attr verbose: boolean, default False
    :return: boolean, dict. { 'ok': True } if ok,
    { 'ok': False, 'error': message }
    if something was wrong.
    """

    TEMPLATES = ["app"]
    prefix = ""
    if template is not None:
        prefix = os.path.join(*template.split("/"))
    try:
        os.makedirs(path)
    except OSError as e:
        errno, message = e
        raise AppError("Can't create a CouchApp in %s: %s" % (path, message))

    for n in DEFAULT_APP_TREE:
        tp = os.path.join(path, n)
        os.makedirs(tp)

    for t in TEMPLATES:
        appdir = path
        if prefix:
            # we do the job twice for now to make sure an app or vendor
            # template exist in user template location
            # fast on linux since there is only one user dir location
            # but could be a little slower on windows
            for user_location in user_path():
                location = os.path.join(user_location, "templates", prefix, t)
                if os.path.exists(location):
                    t = os.path.join(prefix, t)
                    break

        copy_helper(appdir, t)

    # add vendor
    vendor_dir = os.path.join(appdir, "vendor")
    os.makedirs(vendor_dir)
    copy_helper(vendor_dir, "", tname="vendor")

    fid = os.path.join(appdir, "_id")
    if not os.path.isfile(fid):
        with open(fid, "wb") as f:
            f.write("_design/%s" % os.path.split(appdir)[1])

    if create:
        localdoc.document(path, create=True)

    logger.info("%s generated." % path)
Ejemplo n.º 8
0
    def setup(self):
        self.noatomic = self.opts.get('no_atomic', False)
        self.update_delay = self.opts.get('update_delay', 60)
        dest = None
        doc_path = None
        if len(self.args) < 2:
            doc_path = self.path
            if self.args:
                dest = self.args[0]
        else:
            doc_path = os.path.normpath(os.path.join(os.getcwd(),
                                                     self.args[0]))
            dest = self.args[1]

        if doc_path is None:
            raise AppError("You aren't in a couchapp.")

        self.conf.update(doc_path)

        self.doc_path = doc_path
        self.doc = document(doc_path,
                            create=False,
                            docid=self.opts.get('docid'))

        self.dbs = self.conf.get_dbs(dest)

        ignorefile = os.path.join(self.doc_path, '.couchappignore')
        if os.path.exists(ignorefile):
            # A .couchappignore file is a json file containing a
            # list of regexps for things to skip
            self.ignores = json.load(open(ignorefile, 'r'))
Ejemplo n.º 9
0
    def setup(self):
        self.noatomic = self.opts.get('no_atomic', False)
        self.update_delay = self.opts.get('update_delay', 60)
        dest = None
        doc_path = None
        if len(self.args) < 2:
            doc_path = self.path
            if self.args:
                dest = self.args[0]
        else:
            doc_path = os.path.normpath(os.path.join(os.getcwd(), self.args[0]))
            dest = self.args[1]

        if doc_path is None:
            raise AppError("You aren't in a couchapp.")


        self.conf.update(doc_path)

        self.doc_path = doc_path
        self.doc = document(doc_path, create=False, 
                        docid=self.opts.get('docid'))

        self.dbs = self.conf.get_dbs(dest)
       
        ignorefile = os.path.join(self.doc_path, '.couchappignore')
        if os.path.exists(ignorefile):
            # A .couchappignore file is a json file containing a
            # list of regexps for things to skip
            self.ignores = json.load(open(ignorefile, 'r'))
Ejemplo n.º 10
0
def autopush(conf, path, *args, **opts):
    doc_path = None
    dest = None
    if len(args) < 2:
        doc_path = path
        if args:
            dest = args[0]
    else:
        doc_path = os.path.normpath(os.path.join(os.getcwd(), args[0]))
        dest = args[1]

    if doc_path is None:
        raise AppError("You aren't in a couchapp.")

    conf.update(doc_path)
    doc = document(doc_path, create=False, docid=opts.get('docid'))
    dbs = conf.get_dbs(dest)

    update_delay = int(opts.get('update_delay', DEFAULT_UPDATE_DELAY))
    noatomic = opts.get('no_atomic', False)

    watcher = CouchappWatcher(doc,
                              dbs,
                              update_delay=update_delay,
                              noatomic=noatomic)
    watcher.run()
Ejemplo n.º 11
0
def autopush(conf, path, *args, **opts):
    doc_path = None
    dest = None
    if len(args) < 2:
        doc_path = path
        if args:
            dest = args[0]
    else:
        doc_path = os.path.normpath(os.path.join(os.getcwd(), 
            args[0]))
        dest = args[1]

    if doc_path is None:
        raise AppError("You aren't in a couchapp.")

    conf.update(doc_path)
    doc = document(doc_path, create=False, 
            docid=opts.get('docid'))
    dbs = conf.get_dbs(dest)

    update_delay = int(opts.get('update_delay', DEFAULT_UPDATE_DELAY))
    noatomic = opts.get('no_atomic', False)

    watcher = CouchappWatcher(doc, dbs, update_delay=update_delay,
            noatomic=noatomic)
    watcher.run()
Ejemplo n.º 12
0
def init_basic(path):
    '''
    Generate a basic CouchApp which contain following files::

        /path/
            .couchapprc
            .couchappignore
            _attachments/
            lists/
            shows/
            updates/
            views/

    .. versionadded:: 1.1
    '''
    setup_dir(path, require_empty=True)
    setup_dirs(os.path.join(path, n) for n in DEFAULT_APP_TREE)

    save_id(path, '_design/{0}'.format(os.path.split(path)[-1]))
    localdoc.document(path, create=True)
Ejemplo n.º 13
0
def test_browse_dest_only(document, iscouchapp, getcwd):
    '''
    $ couchapp browse {db url}
    '''
    conf = NonCallableMock(name='conf')
    dest = 'http://localhost:5984'
    doc = document()

    ret_code = commands.browse(conf, dest)
    iscouchapp.assert_called_with('/mock_dir/app')
    assert doc.browse.called
Ejemplo n.º 14
0
def test_browse_exist(document, iscouchapp):
    '''
    $ couchapp browse {not app dir} {db url}
    '''
    conf = NonCallableMock(name='conf')
    app = '/mock_dir/notapp'
    dest = 'http://localhost:5984'
    doc = document()

    ret_code = commands.browse(conf, app, dest)
    iscouchapp.assert_called_with('/mock_dir/notapp')
    assert not doc.browse.called
Ejemplo n.º 15
0
def test(conf, path, *args, **opts):
    export = opts.get('export', False)
    js = opts.get('spidermonkey', 'js');
    test_file = args[0]
    dest = None
    doc_path = None
    # print("path: {0}".format(path))
    # print("test_file: {0}".format(args))
    # print("conf: {0}".format(conf))
    if len(args) < 2:
        if export:
            if path is None and args:
                doc_path = args[0]
            else:
                doc_path = path
        else:
            doc_path = path
            if args:
                dest = args[0]
    else:
        doc_path = os.path.normpath(os.path.join(os.getcwd(), args[0]))
        dest = args[1]
    if doc_path is None:
        raise AppError("You aren't in a couchapp.")
    
    # print ("docPath:"+doc_path)
    conf.update(doc_path)

    doc = document(doc_path, create=False, 
                        docid=opts.get('docid'))
    if export:
        if opts.get('output'):
            util.write_json(opts.get('output'), str(doc))
        else:
            print str(doc)
        return 0

    with tempfile.NamedTemporaryFile(delete=False) as tmp:
        tmp.write("var couchdb_design_doc = {0};".format(str(doc)))
        tmp.flush()
        print(tmp.name)
        # util.write_json(tmp.name, str(doc))
        
        p = Popen([js, test_file, tmp.name], stdout=PIPE, stderr=PIPE)
        # status = 1
        # while status >= 0:
        stdout, stderr = p.communicate()
        print "OUT:\n"+stdout
        print "ERROR:\n"+stderr
            # status = p.poll()

    return 0
Ejemplo n.º 16
0
def init_template(path, template=None):
    '''
    Generates a CouchApp via template
    '''
    TEMPLATES = ['app']
    prefix = os.path.join(*template.split('/')) if template is not None else ''

    setup_dir(path, require_empty=True)

    for n in DEFAULT_APP_TREE:
        tp = os.path.join(path, n)
        os.makedirs(tp)

    for t in TEMPLATES:
        appdir = path
        if prefix:
            # we do the job twice for now to make sure an app or vendor
            # template exist in user template location
            # fast on linux since there is only one user dir location
            # but could be a little slower on windows
            for user_location in user_path():
                location = os.path.join(user_location, 'templates', prefix, t)
                if os.path.exists(location):
                    t = os.path.join(prefix, t)
                    break

        copy_helper(appdir, t)

    # add vendor
    vendor_dir = os.path.join(appdir, 'vendor')
    os.makedirs(vendor_dir)
    copy_helper(vendor_dir, '', tname="vendor")

    fid = os.path.join(appdir, '_id')
    if not os.path.isfile(fid):
        with open(fid, 'wb') as f:
            f.write('_design/{0}'.format(os.path.split(appdir)[1]))

    localdoc.document(path, create=True)
Ejemplo n.º 17
0
def init_template(path, template=None):
    '''
    Generates a CouchApp via template
    '''
    TEMPLATES = ['app']
    prefix = os.path.join(*template.split('/')) if template is not None else ''

    setup_dir(path, require_empty=True)

    for n in DEFAULT_APP_TREE:
        tp = os.path.join(path, n)
        os.makedirs(tp)

    for t in TEMPLATES:
        appdir = path
        if prefix:
            # we do the job twice for now to make sure an app or vendor
            # template exist in user template location
            # fast on linux since there is only one user dir location
            # but could be a little slower on windows
            for user_location in user_path():
                location = os.path.join(user_location, 'templates', prefix, t)
                if os.path.exists(location):
                    t = os.path.join(prefix, t)
                    break

        copy_helper(appdir, t)

    # add vendor
    vendor_dir = os.path.join(appdir, 'vendor')
    os.makedirs(vendor_dir)
    copy_helper(vendor_dir, '', tname="vendor")

    fid = os.path.join(appdir, '_id')
    if not os.path.isfile(fid):
        with open(fid, 'wb') as f:
            f.write('_design/{0}'.format(os.path.split(appdir)[1]))

    localdoc.document(path, create=True)
Ejemplo n.º 18
0
def pushapps(conf, source, dest=None, *args, **opts):
    export = opts.get('export', False)
    noatomic = opts.get('no_atomic', False)
    browse = opts.get('browse', False)
    dbs = conf.get_dbs(dest) if not export else None
    apps = []
    source = os.path.normpath(os.path.join(os.getcwd(), source))
    appdirs = util.discover_apps(source)

    logger.debug('Discovered apps: {0}'.format(appdirs))

    for appdir in appdirs:
        doc = document(appdir)
        # if export mode, the ``dbs`` will be None
        hook(conf, appdir, "pre-push", dbs=dbs, pushapps=True)
        if export or not noatomic:
            apps.append(doc)
        else:
            doc.push(dbs, True, browse)
        hook(conf, appdir, "post-push", dbs=dbs, pushapps=True)

    if not apps:
        return 0

    if export:
        docs = [doc.doc() for doc in apps]
        jsonobj = {'docs': docs}
        if opts.get('output'):
            util.write_json(opts.get('output'), jsonobj)
        else:
            print(util.json.dumps(jsonobj))
        return 0

    for db in dbs:
        docs = [doc.doc(db) for doc in apps]
        try:
            db.save_docs(docs)
        except BulkSaveError as e:
            docs1 = []
            for doc in e.errors:
                try:
                    doc['_rev'] = db.last_rev(doc['_id'])
                    docs1.append(doc)
                except ResourceNotFound:
                    pass
            if docs1:
                db.save_docs(docs1)
    return 0
Ejemplo n.º 19
0
def pushapps(conf, source, dest=None, *args, **opts):
    export = opts.get('export', False)
    noatomic = opts.get('no_atomic', False)
    browse = opts.get('browse', False)
    dbs = conf.get_dbs(dest) if not export else None
    apps = []
    source = os.path.normpath(os.path.join(os.getcwd(), source))
    appdirs = util.discover_apps(source)

    logger.debug('Discovered apps: {0}'.format(appdirs))

    for appdir in appdirs:
        doc = document(appdir)
        # if export mode, the ``dbs`` will be None
        hook(conf, appdir, "pre-push", dbs=dbs, pushapps=True)
        if export or not noatomic:
            apps.append(doc)
        else:
            doc.push(dbs, True, browse)
        hook(conf, appdir, "post-push", dbs=dbs, pushapps=True)

    if not apps:
        return 0

    if export:
        docs = [doc.doc() for doc in apps]
        jsonobj = {'docs': docs}
        if opts.get('output'):
            util.write_json(opts.get('output'), jsonobj)
        else:
            print(util.json.dumps(jsonobj))
        return 0

    for db in dbs:
        docs = [doc.doc(db) for doc in apps]
        try:
            db.save_docs(docs)
        except BulkSaveError as e:
            docs1 = []
            for doc in e.errors:
                try:
                    doc['_rev'] = db.last_rev(doc['_id'])
                    docs1.append(doc)
                except ResourceNotFound:
                    pass
            if docs1:
                db.save_docs(docs1)
    return 0
Ejemplo n.º 20
0
def pushapps(conf, source, dest, *args, **opts):
    export = opts.get("export", False)
    noatomic = opts.get("no_atomic", False)
    browse = opts.get("browse", False)
    dbs = conf.get_dbs(dest)
    apps = []
    source = os.path.normpath(os.path.join(os.getcwd(), source))
    appdirs = util.discover_apps(source)

    logger.debug("Discovered apps: {0}".format(appdirs))

    for appdir in appdirs:
        doc = document(appdir)
        hook(conf, appdir, "pre-push", dbs=dbs, pushapps=True)
        if export or not noatomic:
            apps.append(doc)
        else:
            doc.push(dbs, True, browse)
        hook(conf, appdir, "post-push", dbs=dbs, pushapps=True)

    if not apps:
        return 0

    if export:
        docs = [doc.doc() for doc in apps]
        jsonobj = {"docs": docs}
        if opts.get("output"):
            util.write_json(opts.get("output"), jsonobj)
        else:
            print util.json.dumps(jsonobj)
        return 0

    for db in dbs:
        docs = [doc.doc(db) for doc in apps]
        try:
            db.save_docs(docs)
        except BulkSaveError as e:
            docs1 = []
            for doc in e.errors:
                try:
                    doc["_rev"] = db.last_rev(doc["_id"])
                    docs1.append(doc)
                except ResourceNotFound:
                    pass
            if docs1:
                db.save_docs(docs1)
    return 0
Ejemplo n.º 21
0
def browse(conf, path, *args, **opts):
    if len(args) == 0:
        dest = path
        doc_path = '.'
    else:
        doc_path = path
        dest = args[0]

    doc_path = os.path.normpath(os.path.join(os.getcwd(), doc_path))
    if not util.iscouchapp(doc_path):
        raise AppError("Dir '{0}' is not a couchapp.".format(doc_path))

    conf.update(doc_path)

    doc = document(doc_path, create=False, docid=opts.get('docid'))

    dbs = conf.get_dbs(dest)
    doc.browse(dbs)
Ejemplo n.º 22
0
def browse(conf, path, *args, **opts):
    if len(args) == 0:
        dest = path
        doc_path = '.'
    else:
        doc_path = path
        dest = args[0]

    doc_path = os.path.normpath(os.path.join(os.getcwd(), doc_path))
    if not util.iscouchapp(doc_path):
        raise AppError("Dir '{0}' is not a couchapp.".format(doc_path))

    conf.update(doc_path)

    doc = document(doc_path, create=False, docid=opts.get('docid'))

    dbs = conf.get_dbs(dest)
    doc.browse(dbs)
Ejemplo n.º 23
0
def pushapps(conf, source, dest, *args, **opts):
    export = opts.get('export', False)
    noatomic = opts.get('no_atomic', False)
    browse = opts.get('browse', False)
    dbs = conf.get_dbs(dest)
    apps = []
    source = os.path.normpath(os.path.join(os.getcwd(), source))
    for d in os.listdir(source):
        appdir = os.path.join(source, d)
        if os.path.isdir(appdir) and os.path.isfile(os.path.join(appdir, 
                                        '.couchapprc')):
            doc = document(appdir)
            hook(conf, appdir, "pre-push", dbs=dbs, pushapps=True)
            if export or not noatomic:
                apps.append(doc)
            else:
                doc.push(dbs, True, browse)
            hook(conf, appdir, "post-push", dbs=dbs, pushapps=True)
    if apps:
        if export:
            docs = []
            docs.append([doc.doc() for doc in apps])
            jsonobj = {'docs': docs}
            if opts.get('output') is not None:
                util.write_json(opts.get('output'), json.dumps(jsonobj))
            else:
                print json.dumps(jsonobj)
            return 0
        else:
            for db in dbs:
                docs = []
                docs = [doc.doc(db) for doc in apps]
                try:
                    db.save_docs(docs)
                except BulkSaveError, e:
                    docs1 = []
                    for doc in e.errors:
                        try:
                            doc['_rev'] = db.last_rev(doc['_id'])
                            docs1.append(doc)
                        except ResourceNotFound:
                            pass 
                if docs1:
                    db.save_docs(docs1)
Ejemplo n.º 24
0
def pushapps(conf, source, dest, *args, **opts):
    export = opts.get('export', False)
    noatomic = opts.get('no_atomic', False)
    browse = opts.get('browse', False)
    dbs = conf.get_dbs(dest)
    apps = []
    source = os.path.normpath(os.path.join(os.getcwd(), source))
    for d in os.listdir(source):
        appdir = os.path.join(source, d)
        if os.path.isdir(appdir) and os.path.isfile(
                os.path.join(appdir, '.couchapprc')):
            doc = document(appdir)
            hook(conf, appdir, "pre-push", dbs=dbs, pushapps=True)
            if export or not noatomic:
                apps.append(doc)
            else:
                doc.push(dbs, True, browse)
            hook(conf, appdir, "post-push", dbs=dbs, pushapps=True)
    if apps:
        if export:
            docs = []
            docs.append([doc.doc() for doc in apps])
            jsonobj = {'docs': docs}
            if opts.get('output') is not None:
                util.write_json(opts.get('output'), util.json.dumps(jsonobj))
            else:
                print util.json.dumps(jsonobj)
            return 0
        else:
            for db in dbs:
                docs = []
                docs = [doc.doc(db) for doc in apps]
                try:
                    db.save_docs(docs)
                except BulkSaveError, e:
                    docs1 = []
                    for doc in e.errors:
                        try:
                            doc['_rev'] = db.last_rev(doc['_id'])
                            docs1.append(doc)
                        except ResourceNotFound:
                            pass
                    if docs1:
                        db.save_docs(docs1)
Ejemplo n.º 25
0
def push(conf, path, *args, **opts):
    export = opts.get('export', False)
    noatomic = opts.get('no_atomic', False)
    browse = opts.get('browse', False)
    force = opts.get('force', False)
    dest = None
    doc_path = None
    if len(args) < 2:
        if export:
            if path is None and args:
                doc_path = args[0]
            else:
                doc_path = path
        else:
            doc_path = path
            if args:
                dest = args[0]
    else:
        doc_path = os.path.normpath(os.path.join(os.getcwd(), args[0]))
        dest = args[1]
    if doc_path is None:
        raise AppError("You aren't in a couchapp.")

    conf.update(doc_path)

    doc = document(doc_path, create=False, docid=opts.get('docid'))
    if export:
        if opts.get('output'):
            util.write_json(opts.get('output'), doc)
        else:
            print(doc.to_json())
        return 0

    dbs = conf.get_dbs(dest)

    hook(conf, doc_path, "pre-push", dbs=dbs)
    doc.push(dbs, noatomic, browse, force)
    hook(conf, doc_path, "post-push", dbs=dbs)

    docspath = os.path.join(doc_path, '_docs')
    if os.path.exists(docspath):
        pushdocs(conf, docspath, dest, *args, **opts)
    return 0
Ejemplo n.º 26
0
def browse(conf, path, *args, **opts):
    dest = None
    doc_path = None
    if len(args) < 2:
        doc_path = path
        if args:
            dest = args[0]
    else:
        doc_path = os.path.normpath(os.path.join(os.getcwd(), args[0]))
        dest = args[1]
    if doc_path is None:
        raise AppError("You aren't in a couchapp.")

    conf.update(doc_path)

    doc = document(doc_path, create=False, docid=opts.get('docid'))

    dbs = conf.get_dbs(dest)
    doc.browse(dbs)
Ejemplo n.º 27
0
def browse(conf, path, *args, **opts):
    dest = None
    doc_path = None
    if len(args) < 2:
        doc_path = path
        if args:
            dest = args[0]
    else:
        doc_path = os.path.normpath(os.path.join(os.getcwd(), args[0]))
        dest = args[1]
    if doc_path is None:
        raise AppError("You aren't in a couchapp.")

    conf.update(doc_path)

    doc = document(doc_path, create=False, docid=opts.get('docid'))

    dbs = conf.get_dbs(dest)
    doc.browse(dbs)
Ejemplo n.º 28
0
def push(conf, path, *args, **opts):
    export = opts.get('export', False)
    noatomic = opts.get('no_atomic', False)
    browse = opts.get('browse', False)
    force = opts.get('force', False)
    dest = None
    doc_path = None
    if len(args) < 2:
        if export:
            if path is None and args:
                doc_path = args[0]
            else:
                doc_path = path
        else:
            doc_path = path
            if args:
                dest = args[0]
    else:
        doc_path = os.path.normpath(os.path.join(os.getcwd(), args[0]))
        dest = args[1]
    if doc_path is None:
        raise AppError("You aren't in a couchapp.")

    conf.update(doc_path)

    doc = document(doc_path, create=False, docid=opts.get('docid'))
    if export:
        if opts.get('output'):
            util.write_json(opts.get('output'), doc)
        else:
            print(doc.to_json())
        return 0

    dbs = conf.get_dbs(dest)

    hook(conf, doc_path, "pre-push", dbs=dbs)
    doc.push(dbs, noatomic, browse, force)
    hook(conf, doc_path, "post-push", dbs=dbs)

    docspath = os.path.join(doc_path, '_docs')
    if os.path.exists(docspath):
        pushdocs(conf, docspath, dest, *args, **opts)
    return 0
Ejemplo n.º 29
0
def init_template(path, template='default'):
    '''
    Generates a CouchApp via template

    :param str path: the app dir
    :param str template: the templates set name. In following example, it is
                         ``mytmpl``.

    We expect template dir has following structure::

        templates/
            app/
            functions/
            vendor/

            mytmpl/
                app/
                functions/
                vendor/

            vuejs/
                myvue/
                    app/
                    functions/
                    vendor/
                vueform/
                    app/
                    functions/
                    vendor/

    The ``templates/app`` will be used as default app template.
    ``templates/functions`` and ``templates/vender`` are default, also.

    And we can create a dir ``mytmpl`` as custom template set.
    The template set name can be nested, e.g. ``vuejs/myvue``.

    ..versionadded:: 1.1
    '''
    if template in TEMPLATE_TYPES:
        raise AppError('template name connot be {0}.'.format(TEMPLATE_TYPES))

    tmpl_name = os.path.normpath(template) if template else ''

    # copy ``<template set>/app``
    src_dir = find_template_dir(tmpl_name, 'app', raise_error=True)
    copy_helper(src_dir, path)

    # construct basic dirs
    setup_dirs((os.path.join(path, n) for n in DEFAULT_APP_TREE),
               require_empty=False)

    # add vendor
    src_dir = find_template_dir(tmpl_name, tmpl_type='vendor')
    if src_dir is None:
        logger.debug('vendor not found in template set "{0}". '
                     'fallback to default vendor.'.format(tmpl_name))
        src_dir = find_template_dir(tmpl_type='vendor')
    vendor_dir = os.path.join(path, 'vendor')
    copy_helper(src_dir, vendor_dir)

    save_id(path, '_design/{0}'.format(os.path.split(path)[-1]))
    localdoc.document(path, create=True)
Ejemplo n.º 30
0
def pushdocs(conf, source, dest, *args, **opts):
    export = opts.get('export', False)
    noatomic = opts.get('no_atomic', False)
    browse = opts.get('browse', False)
    dbs = conf.get_dbs(dest)
    docs = []
    for d in os.listdir(source):
        docdir = os.path.join(source, d)
        if docdir.startswith('.'):
            continue
        elif os.path.isfile(docdir):
            if d.endswith(".json"):
                doc = util.read_json(docdir)
                docid, ext = os.path.splitext(d)
                doc.setdefault('_id', docid)
                doc.setdefault('couchapp', {})
                if export or not noatomic:
                    docs.append(doc)
                else:
                    for db in dbs:
                        db.save_doc(doc, force_update=True)
        else:
            doc = document(docdir, is_ddoc=False)
            if export or not noatomic:
                docs.append(doc)
            else:
                doc.push(dbs, True, browse)
    if docs:
        if export:
            docs1 = []
            for doc in docs:
                if hasattr(doc, 'doc'):
                    docs1.append(doc.doc())
                else:
                    docs1.append(doc)
            jsonobj = {'docs': docs}
            if opts.get('output') is not None:
                util.write_json(opts.get('output'), util.json.dumps(jsonobj))
            else:
                print util.json.dumps(jsonobj)
        else:
            for db in dbs:
                docs1 = []
                for doc in docs:
                    if hasattr(doc, 'doc'):
                        docs1.append(doc.doc(db))
                    else:
                        newdoc = doc.copy()
                        try:
                            rev = db.last_rev(doc['_id'])
                            newdoc.update({'_rev': rev})
                        except ResourceNotFound:
                            pass
                        docs1.append(newdoc)
                try:
                    db.save_docs(docs1)
                except BulkSaveError, e:
                    # resolve conflicts
                    docs1 = []
                    for doc in e.errors:
                        try:
                            doc['_rev'] = db.last_rev(doc['_id'])
                            docs1.append(doc)
                        except ResourceNotFound:
                            pass
                if docs1:
                    db.save_docs(docs1)
Ejemplo n.º 31
0
    try:
        os.makedirs(path)
    except OSError, e:
        errno, message = e
        raise AppError("Can't create a CouchApp in %s: %s" % (path, message))

    for n in DEFAULT_APP_TREE:
        tp = os.path.join(path, n)
        os.makedirs(tp)

    fid = os.path.join(path, '_id')
    if not os.path.isfile(fid):
        with open(fid, 'wb') as f:
            f.write('_design/%s' % os.path.split(path)[1])

    doc = localdoc.document(path, create=True)
    logger.info("%s created." % path)


def generate_app(path, template=None, create=False):
    """ Generates a CouchApp in app_dir 
    
    :attr verbose: boolean, default False
    :return: boolean, dict. { 'ok': True } if ok, { 'ok': False, 'error': message } 
    if something was wrong.
    """

    TEMPLATES = ['app']
    prefix = ''
    if template is not None:
        prefix = os.path.join(*template.split('/'))
Ejemplo n.º 32
0
def pushdocs(conf, source, dest, *args, **opts):
    export = opts.get('export', False)
    noatomic = opts.get('no_atomic', False)
    browse = opts.get('browse', False)
    dbs = conf.get_dbs(dest)
    docs = []
    for d in os.listdir(source):
        docdir = os.path.join(source, d)
        if d.startswith('.'):
            continue
        elif os.path.isfile(docdir):
            if d.endswith(".json"):
                doc = util.read_json(docdir)
                docid, ext = os.path.splitext(d)
                doc.setdefault('_id', docid)
                doc.setdefault('couchapp', {})
                if export or not noatomic:
                    docs.append(doc)
                else:
                    for db in dbs:
                        db.save_doc(doc, force_update=True)
        else:
            doc = document(docdir, is_ddoc=False)
            if export or not noatomic:
                docs.append(doc)
            else:
                doc.push(dbs, True, browse)
    if docs:
        if export:
            docs1 = []
            for doc in docs:
                if hasattr(doc, 'doc'):
                    docs1.append(doc.doc())
                else:
                    docs1.append(doc)
            jsonobj = {'docs': docs}
            if opts.get('output'):
                util.write_json(opts.get('output'), jsonobj)
            else:
                print(util.json.dumps(jsonobj))
        else:
            for db in dbs:
                docs1 = []
                for doc in docs:
                    if hasattr(doc, 'doc'):
                        docs1.append(doc.doc(db))
                    else:
                        newdoc = doc.copy()
                        try:
                            rev = db.last_rev(doc['_id'])
                            newdoc.update({'_rev': rev})
                        except ResourceNotFound:
                            pass
                        docs1.append(newdoc)
                try:
                    db.save_docs(docs1)
                except BulkSaveError, e:
                    # resolve conflicts
                    docs1 = []
                    for doc in e.errors:
                        try:
                            doc['_rev'] = db.last_rev(doc['_id'])
                            docs1.append(doc)
                        except ResourceNotFound:
                            pass
                if docs1:
                    db.save_docs(docs1)
Ejemplo n.º 33
0
    try:
        os.makedirs(path)
    except OSError, e:
        errno, message = e
        raise AppError("Can't create a CouchApp in %s: %s" % (path, message))

    for n in DEFAULT_APP_TREE:
        tp = os.path.join(path, n)
        os.makedirs(tp)

    fid = os.path.join(path, '_id')
    if not os.path.isfile(fid):
        with open(fid, 'wb') as f:
            f.write('_design/%s' % os.path.split(path)[1])

    localdoc.document(path, create=True)
    logger.info("%s created." % path)


def generate_app(path, template=None, create=False):
    """ Generates a CouchApp in app_dir

    :attr verbose: boolean, default False
    :return: boolean, dict. { 'ok': True } if ok,
    { 'ok': False, 'error': message }
    if something was wrong.
    """

    TEMPLATES = ['app']
    prefix = ''
    if template is not None: