Ejemplo n.º 1
0
    def process(self, app, model, *args, **kwargs):
        model_file = "%s/models.py" % app
        print("MODEL FILE: %s" % model_file)
        
        import_entry = False
        first_class_line = 0
        last_import_line = 0
        new_lines = []

        # MAKE SURE THE MODEL NAME'S FIRST LETTER IS CAPITALIZED
        model = class_name(model)
        
        # LOAD FILE
        if os.path.isfile( model_file ): 
            try:
                FILE = open( model_file, "r")
                data = FILE.read()

                if not import_line_check(self.import_line_regex, data, 'models'):
                    new_lines.append("from django.db import models")

                if not import_line_check(self.import_uget_regex, data, 'ugettext_lazy as _'):
                    new_lines.append("from django.utils.translation import ugettext_lazy as _")

                classes = self.class_regex.findall( data )
                FILE.close()

            except IOError as e:
                print "IO ERROR, CONTINUE"
                pass                    # May need to add something here
                                        # to handle a file locking issue
        else:
            print( "File Not Found: %s" % model_file )
            return

        # LOOK FOR CLASS WITH NAME
        if model in classes:
            print('Model Exists: %s' % model)
            return

        print('Creating Model: %s' % model)
        
        if not import_entry:
            # FIND WHERE TO ADD THE IMPORT LINES
            
            lines = []
            for m in re.finditer( self.func_regex, data ):
                lines.append( data.count("\n",0,m.start())+1 )
        
            if lines:
                lines.sort()
                first_class_line = lines[0]
        
            print "[%d]" % ( first_class_line )

            lines = []
            for m in re.finditer( self.imports_regex, data ):
                lineno = data.count("\n",0,m.start())+1
                if lineno < first_class_line:
                    lines.append(lineno)
                #print "[%d] %s" % (lineno, data[ m.start() : m.end() ] )
            if lines:
                lines.sort()
                last_import_line = lines[-1]
        
            print "[%d]" % ( last_import_line )
        
        # ADD THE MODEL TO THE LINES
        new_lines.append('\n\nclass %s(models.Model):\n    name = models.CharField(_("Name"), max_length=300)' % model)
        new_lines.append(" ")

        mf = open( model_file, "a" )
        # NEEDS TO LOAD AND REWRITE THE FILE RATHER THAN JUST APPEND
        mf.write( "\n".join(new_lines) )
        mf.close()
Ejemplo n.º 2
0
    def handle(self, *args, **options):
        if len(args) < 1:
            raise CommandError('Need to pass App.Page names')
            
        parts = args[0].split(".")

        # Using a Dictionary for clarity in strin replacements
        argDict = {'app':parts[0], 'page':parts[1].lower()}
        tab = "\t"
        argDict['tab'] = " " * 4
        
        use_class_based_views = version_check("gte", "1.3.0")        # SHOULD DEFAULT FOR 1.3+ TO True.  NEED ATTR IN settings.py TO CONFIG SET TO FALSE.
        
        #from django.views.generic import TemplateView
        view_file = "%(app)s/views.py" % argDict
        argDict['view_file'] = view_file

        views = []

        if use_class_based_views:
            url_entry_regex = re.compile("url\(\S+ (\S+)" )
        else:
            url_entry_regex = re.compile("url\(\S+ '(\S+)'" )
        
        # Get contents of views.py file
        if os.path.isfile(view_file): 
            try:
                FILE = open(view_file, "r")
                data = FILE.read()
                FILE.close()
            except IOError as e:
                print( "IO Error reading %s\n\t%s" % (view_file, tab, e) )
                return
        
        insert_line = None
        replace_line = None
        
        if use_class_based_views:
            views = [ x.name for x in ast.parse(data).body if isinstance(x, ast.ClassDef) ]   # BEST PYTHON WAY TO DO THIS
            view_name = ( "%sView" % ( class_name( argDict['page'] ) ) )
            view_import_path = "views.%s.as_view()" % (view_name)
            argDict['view_import_path'] = view_import_path
            
            # CHECK IMPORT LINES
            importers = { v.module : v for v in ast.parse(data).body if isinstance(v, ast.ImportFrom) }
            
            if not importers:
                insert_line = (0, "from django.views.generic import TemplateView\n\n")
            else:
                if "django.views.generic" in importers:
                    name_list = [ x.name for x in importers["django.views.generic"].names ]
                    
                    if "TemplateView" not in name_list:
                        print("Adde Module into line: %d -> %s" % (importers["django.views.generic"].lineno, "TemplateView" ) )     # NEED AUTOMATIC WAY TO INSERT THIS
                else:
                    # GET THE LAST IMPORT LINE
                    import_number = 0
                    insert_line = (import_number, "from django.views.generic import TemplateView\n")
            
        else:
            views = [ x.name for x in ast.parse(data).body if isinstance(x, ast.FunctionDef) ]   # BEST PYTHON WAY TO DO THIS
            view_name = ("%(page)s_view" % argDict)
            view_import_path = "%(app)s.views.%(page)s_view" % argDict
            argDict['view_import_path'] = view_import_path
            
        url_name = "%(app)s-%(page)s" % argDict
        argDict['url_name'] = url_name
        template = "%(app)s/%(page)s.html" % argDict
        
        FILE = open(view_file, "r")
        lines = FILE.readlines()
        FILE.close()
        #lines = [ x.strip() for x in FILE.readlines() ]    # WILL STRIP OFF TABS
        dirty = False

        if insert_line:
            lines.insert( insert_line[0], insert_line[1] )
            dirty = True
        
        # If the new page name is not in the views.py, add the stub
        if view_name not in views:
            self.stdout.write( "ADDING: %s to %s\n" % (argDict['page'], view_file) )
            dirty = True

            if use_class_based_views:
                # CHECK FOR IMPORT LINE IN FILE

                lines.extend( [ "class %s(TemplateView):\n" % view_name, 
                                argDict['tab'] + "template_name = '%s'\n\n\n" % template ] )
            else:
                lines.extend( [ "def %s(request):\n" % view_name, 
                                argDict['tab'] + "ctx = RequestContext(request)\n",
                                argDict['tab'] + "return render_to_response('%s', ctx )\n" % template ] )
            
        else:
            self.stdout.write( "EXISTING VIEWS: %s\n" % ", ".join(views) )

        if dirty:
            FILE = open(view_file, "w")
            FILE.writelines( lines )
            FILE.close()

        # Create the template stub
        template_file = "templates/%s" % template
        
        # Need to check for directory and add it if it is missing from the template directory
        if not os.path.isfile(template_file): 
            
            dest_path = "templates/%(app)s" % argDict
            if not os.path.exists(dest_path):
                os.makedirs(dest_path)

            self.stdout.write( "ADDING TEMPLATE FILE: %s\n" % template_file )
            FILE = open( template_file, "w" )
            html = ['<!DOCTYPE html>',
                    '<html>',
                    '<head>',
                    '<meta charset="utf-8">',
                    '\t<title>%(app)s - %(page)s</title>' % argDict,
                    '</head>',
                    '<body>',
                    '\t<h1>%(app)s - %(page)s, Stub Page</h1>' % argDict,
                    '\t<a href="{% url ' + "'%(url_name)s'" % argDict + ' %}">link</a>',
                    '</body>\n</html>']

            FILE.write( "\n".join(html) )

        url_file = "%(app)s/urls.py" % argDict

        #################
        # UPDATE THE urls.py FILE

        argDict['page_link'] = "%(page)s/" % argDict

        if argDict['page'] == "index":
            argDict['page_link'] = "/"

        if os.path.isfile(url_file):
            '''
            If there is a urls.py file do this
            '''
            try:
                FILE = open(url_file, "r")
                data = FILE.read()
                urls = url_entry_regex.findall( data )
                FILE.close()

            except IOError as e:
                print( "IO Error reading %s, Step Skipped.\n\t%s" % (view_file, e) )
            
            if argDict['view_import_path'] + "," not in urls:   # Make sure to add the comma, which is caught by the regex pattern
                FILE = open(url_file, "a")

                if use_class_based_views:
                    url_py = "urlpatterns += patterns('',\n%(tab)surl(r'^%(page_link)s$', %(view_import_path)s, name='%(url_name)s'),\n)" % (argDict)
                else:
                    url_py = "urlpatterns += patterns('',\n%(tab)surl(r'^%(page_link)s$', '%(view_import_path)s', name='%(url_name)s'),\n)" % (argDict)

                FILE.write( url_py + "\n" )
                FILE.close()

        else:
            '''
            If there is no urls.py file do this
            '''
            FILE = open(url_file, "w")

            if version_check("gte", "1.5.0"):
                url_py = ["from django.conf.urls import *", "from %(app)s import views\n" % argDict, "urlpatterns = patterns(''," ]
            else:
                url_py = ["from django.conf.urls import *\n", "urlpatterns = patterns(''," ]

            if use_class_based_views:
                url_py.append(   "%(tab)surl(r'^%(page_link)s$', %(view_import_path)s, name='%(url_name)s'),\n)" % ( argDict ) )
            else:
                url_py.append(   "%(tab)surl(r'^%(page_link)s$', '%(view_import_path)s', name='%(url_name)s'),\n)" % ( argDict ) )

            FILE.write( "\n".join(url_py) + "\n" )
            FILE.close()