Commits

David Tran  committed a5784d8

Miscellaneous Update Veresion 0.8.2.1

  • Participants
  • Parent commits d9d2238

Comments (0)

Files changed (5)

-#Executes WS! Remember to RENAME the file to _ws.py !
+#Executes WS. Remember to RENAME the file to _ws.py!
+# David Tran (unsignedzero)
 echo -e "Starting WS.py!\n"
-python ~/.bin/_ws.py $1 $2 $3
+python ~/bin/_ws.py $1 $2 $3

File WSv2.py

-# WonderSwan
-# Provides basic meta programing support
-# to python "format"
-# 07-24-2011
-# Version 0.5
-# 10-08-2011
-# Version 0.8
-# 10-18-2011
-# Version 0.8.0.1
-# 10-18-2011
-# Version 0.8.1.0
-# 10-25-2011
-# Version 0.8.2.0
-
-#DO NOT CHANGE BELOW THIS POINT
-
-class ZText_Error ( Exception ):
-  """Base class for exceptions in this module"""
-  pass
-  
-class UnbalancedBraces ( ZText_Error ):
-  """Exception for unbalanced braces
-  Attributes:
-    expr -- input expression in which the error occurred
-    msg  -- explanation of the error
-  """
-  def __init__(self, expr, msg):
-    self.expr = expr
-    self.msg = msg
-
-def pause():
-  """Correct pauses regardless of the os this function is running on."""
-  #import os,sys
-  #pau = "pause" if sys.platform[:3]=="win" else 
-    #"read -rsn 1 -p \"Press any key to continue...\\n\""
-  #os.system(pau)
-  raw_input("Press any key to continue...\n")
-
-#def formatter( fname, fout = None, space_count = 2, 
-  #*kargs, special = 0, NO_EXCEPTION = False ):
-def formatter( fname, fout = None, space_count = 2, 
-  special = 0, NO_EXCEPTION = False ):
-  r"""
-  formatter(...)
-     formatter( fname, fout = None, space_co unt = 2, 
-       *kargs, special = 0, NO_EXCEPTION = False )
-
-     Given a correct filename fname, this program auto-formats the program 
-     file. This function formats source code, in a similar fashion to    
-     Python, in which "proper" matching spacing is applied for each line 
-     between an opening and closing brace. 
-
-     fname is the ONLY required argument. If fout is not defined, the
-     output will have the same name as the input file except now with 
-     "_edit.txt" apprended to it.
-
-     ASUMPTIONS:
-       The file passed should have balanced braces. If this requirement is   
-       not met, the program will return an Exception, unless NO_EXCEPTIONS
-       is true!
-
-       All lines of the source code can and will be "reorder" even if they
-       are comments!
-
-     ATTRIBUTES:
-       fname -- This is the name of input file.
-
-       fout  -- This is the name of the output file. If not specificed,
-         then it will be fname + "_edit.txt"
-
-       space_count -- This is the amount of spaces, that each opening brace
-         will shift the lines below it.
-
-       special -- special arguments, see below
-
-       NO_EXCEPTION -- Disables exceptions messages of unbalanced braces
-       
-      SPECIAL:
-        Treat this variable as an array of bools.  (Represented as an integer)
-        This turns on/off additional functions, listed below.
-        
-         1 -- Comments after the end brace, what the opening brace was
-        
-         2 -- Use tabs, rather than spaces!
-
-         4 -- Treat /* */ comments as braces, for the purposes of     
-               indentation
-
-         8 -- Comment-only // lines are shifted -1 left
-
-        16 -- Non-braced, if/for/while will indent
-        
-  """
-  import sys
-  
-  shift       = 0
-  shift_delay = 0   #For   4
-  cond_shift  = 0   #For  16
-  mline_shift = 0   #Future Use
-  brace_start = '{'
-  brace_end   = '}'
-  stack       = []  #For   1
-  space_char  = ' ' #For   2
-
-  #Files 
-  source_code = open(fname)
-  fout = (fname + "_edit.txt") if (fout == None) else fout 
-  dest_code   = open(fout, "w" )
-  ###err_code    = open(fname + "_err.txt", "w" )
-
-  print("%s starting with %s. \nOutput is %s." % 
-    (sys._getframe(0).f_code.co_name , fname, fout) )
-
-  #SPECIAL
-  if special & 2 :
-    space_char = '\t'
-
-  for (count,line) in enumerate(source_code) :
-
-     ###err_code.write( '%03d | ' % len(line.strip() ) + line)
-
-    #Empty Line are Empty
-     empty_line = 1 if line.strip() else 0
-   
-     line = ( ( empty_line * ( shift + cond_shift + mline_shift  )*  
-              space_count * space_char                            ) 
-              + line.strip()                                      )
-              
-    #Insert Extra Formatting here
-     if special > 0:
-       if special & 1 :
-         if '{' in line and '}' not in line :
-           stack.append( line[:-1].strip() )
-         elif '{' not in line and '}' in line :
-           line += " // " + stack.pop()
-       if special & 4 :      
-         if r'/*' in line:
-           shift_delay +=1
-         if r'*/' in line:
-           shift_delay -=1
-       if special & 8 :
-         if (line.lstrip()).startswith('//'):
-           if (line[0] == ' ' or line[0] == '\t' ): #CHECK ME
-             line = line[1:]
-       if special & 16 :
-         if ( 'if' in line or 'else' in line 
-          or 'for' in line or 'else' in line ) and '{' not in line:
-           cond_shift = 1
-         else:
-           cond_shift = 0
-    #Write to File
-     dest_code.write( line + '\n' )
-
-    ##Calculate Shift for next line
-     if brace_start in line :
-       shift += 1
-     if brace_end   in line :
-       shift -= 1
-     if shift_delay != 0    :
-       shift += shift_delay
-       shift_delay = 0
-       
-     if NO_EXCEPTION and shift < 0 :
-       print( "\n  File \"%s\", line %i, in %s" % 
-         ( fname, count,  sys._getframe().f_code.co_name ) )
-       raise UnbalancedBraces( 0 , "Unbalanced Closing Braces in the file" )
-  if NO_EXCEPTION and shift != 0:
-    print( "\n  File \"%s\" , in %s" % 
-      ( fname,  sys._getframe().f_code.co_name ) )
-    raise UnbalancedBraces( 0 , "Unbalanced Opening Braces in the file!" )
-  print( "%s Compeleted!" % sys._getframe(0).f_code.co_name )
-
-#def lcount( fname , fout = None, width = 6, *kargs, code = "UTF-8" ) :
-def lcount( fname , fout = None, width = 6, code = "UTF-8" ) :
-  r"""
-  lcount(...)
-     lcount( fname , fout = None, width = 6, *kargs, code = "UTF-8" )
-
-     Writes the line number of each line into the output text file.
-
-     ATTRIBUTES:
-       fname -- This is the name of input file.
-       
-       fout  -- This is the name of the output file. If not specificed,
-         then it will be fname + "_counted.txt"
-         
-       width -- Sets the width of the number column
-       
-       code  -- Sets the default coding of the file
-
-  """
-
-  import sys
-
-  #Files
-  file_in  = open(fname, "r", 1, code)
-  fout = (fname + '_counted.txt') if (fout == None) else fout 
-  file_out = open(fout,"w" , 1, code)
-
-  print("%s starting with %s. Output is %s." % 
-    (sys._getframe(0).f_code.co_name , fname, fout) )
-    
-  width = "%0" + str(width) + "d | "
-
-  for (count,line) in enumerate(file_in) :
-    file_out.write( str( width % count) + line )  
-
-  print( "%s Compeleted!" % sys._getframe(0).f_code.co_name )  
-
-def rspace_killer ( fname, fout = None ) :
-  r"""
-  rspace_killer(...)
-     rspace_killer ( fname, fout = None )
-     
-     Removes excess white space on the right
-     
-     ATTRIBUTES:
-     
-     fname -- This is the name of the input file.
-     
-     fout  -- This is the name of the output file. If not specificed,
-       then it will be fname + "_wk.txt"     
-  """
-
-  import sys
-  
-  fin = open(source,"r")
-  fout = source + '_wk.txt' if ( fout == None ) else fout
-  dest = open(fout,"w")
-
-  print("%s starting with %s. Output is %s." % 
-    (sys._getframe(0).f_code.co_name , fname, fout) )
-    
-  for line in fin :
-    fout.write( line.rstrip() )
-    
-  print( "%s Compeleted!" % sys._getframe(0).f_code.co_name ) 
- 
-def ver_update():
-  import sys
-  if ( sys.version_info[0] == 2 ):
-    import __future__ 
-
-if __name__ == "__main__" :
-  import sys
-  #ver_update()
-  print("Starting WS")
-  try:
-    inf = sys.argv[1]
-    outf = (sys.argv[1] + "_edit.txt") if ( 
-      len(sys.argv[1:2]) == 1 ) else sys.argv[2]
-    spf = 0 if ( len(sys.argv[1:3]) < 3 ) else sys.argv[3]
-  except IndexError:
-    finput = raw_input("Please enter a file name\n")
-    finput = finput.split()
-    try:
-      mode = int(finput[1])
-    except IndexError:
-      mode = 0
-    finally:
-      if ( isinstance(finput,list) ) :
-        formatter(finput[0], special = int(mode))
-      else :
-        formatter(finput, special = 0)
-  else:
-    formatter(inf,outf, special = spf)
-  pause()
-  
-# WonderSwan
+# WonderSwan 
+# By David Tran (unsignedzero)
 # Provides basic meta programing support
 # to python "format"
-# 07-24-2011
-# Version 0.5
-# 10-08-2011
-# Version 0.8
-# 10-18-2011
-# Version 0.8.0.1
-# 10-18-2011
-# Version 0.8.1.0
-# 10-25-2011
-# Version 0.8.2.0
+# 10-31-2011
+# Version 0.8.2.1
 
 #DO NOT CHANGE BELOW THIS POINT
 
 class ZText_Error ( Exception ):
-  """Base class for exceptions in this module"""
+  r"""
+  ZText_Error
+
+      Base class for exceptions in this module
+  """
   pass
 
 class UnbalancedBraces ( ZText_Error ):
-  """Exception for unbalanced braces
-  Attributes:
-    expr -- input expression in which the error occurred
-    msg  -- explanation of the error
+  r"""
+  UnbalancedBraces
+
+      Exception for unbalanced braces for this module.
+
+      ARGUMENTS:
+        expr -- Input expression in which the error occurred
+
+        msg  -- explanation of the error
+
   """
   def __init__(self, expr, msg):
     self.expr = expr
     self.msg = msg
 
 def pause():
-  """Correct pauses regardless of the os this function is running on."""
+  r"""
+  pause()
+      pause()
+
+      Correct pauses regardless of the os this function is running on.
+  """
   #import os,sys
   #pau = "pause" if sys.platform[:3]=="win" else 
     #"read -rsn 1 -p \"Press any key to continue...\\n\""
   input("Press any key to continue...\n")
 
 def formatter( fname, fout = None, space_count = 2, 
-  *kargs, special = 0, NO_EXCEPTION = False ):
+  *kargs, special = 0, EXCEPTION = False ):
   r"""
   formatter(...)
      formatter( fname, fout = None, space_co unt = 2, 
-       *kargs, special = 0, NO_EXCEPTION = False )
+       *kargs, special = 0, EXCEPTION = False )
 
      Given a correct filename fname, this program auto-formats the program 
      file. This function formats source code, in a similar fashion to    
      output will have the same name as the input file except now with 
      "_edit.txt" apprended to it.
 
-     ASUMPTIONS:
+     ASSUMPTIONS:
        The file passed should have balanced braces. If this requirement is   
        not met, the program will return an Exception, unless NO_EXCEPTIONS
        is true!
        All lines of the source code can and will be "reorder" even if they
        are comments!
 
-     ATTRIBUTES:
-       fname -- This is the name of input file.
+     ARGUMENTS:
 
-       fout  -- This is the name of the output file. If not specificed,
-         then it will be fname + "_edit.txt"
+       fname        -- This is the name of input file.
+
+     Optional Arguments:
 
-       space_count -- This is the amount of spaces, that each opening brace
-         will shift the lines below it.
+       fout         -- This is the name of the output file. 
+         If not specificed, then it will be fname + "_edit.txt"
 
-       special -- special arguments, see below
+       space_count  -- This is the amount of spaces, that each 
+         opening brace will shift the lines below it. Default 2.
 
-       NO_EXCEPTION -- Disables exceptions messages of unbalanced braces
+      Optional Keyword Arguments:
+
+        special      -- special arguments, see special section below.
+
+        EXCEPTION -- Disables exceptions messages of unbalanced braces.
        
       SPECIAL:
-        Treat this variable as an array of bools.  (Represented as an integer)
-        This turns on/off additional functions, listed below.
+
+        Treat this variable as an array of bools.  (Represented as an  
+          integer) This turns on/off additional functions, listed below.
         
          1 -- Comments after the end brace, what the opening brace was
         
   shift       = 0
   shift_delay = 0   #For   4
   cond_shift  = 0   #For  16
+  cond_delay  = 0   #For  16
   mline_shift = 0   #Future Use
   brace_start = '{'
   brace_end   = '}'
     #Insert Extra Formatting here
      if special > 0:
        if special & 1 :
-         if '{' in line and '}' not in line :
+         if brace_start in line and brace_end not in line :
            stack.append( line[:-1].strip() )
-         elif '{' not in line and '}' in line :
+         elif brace_start not in line and brace_end in line :
            line += " // " + stack.pop()
        if special & 4 :      
          if r'/*' in line:
            shift_delay -=1
        if special & 8 :
          if (line.lstrip()).startswith('//'):
-           if (line[0] == ' ' or line[0] == '\t' ):
+           if (line[0] == ' ' or line[0] == '\t' ): #CHECK ME
              line = line[1:]
-       if special & 16 :
+       if special & 16:
          if ( 'if' in line or 'else' in line 
-          or 'for' in line or 'else' in line ) and '{' not in line:
+          or 'for' in line or 'while' in line ) and brace_start not in line:
            cond_shift = 1
          else:
            cond_shift = 0
+           
     #Write to File
      dest_code.write( line + '\n' )
 
        shift += shift_delay
        shift_delay = 0
        
-     if NO_EXCEPTION and shift < 0 :
+     #Check if negative shift
+     if EXCEPTION and shift < 0 :
        print( "\n  File \"%s\", line %i, in %s" % 
          ( fname, count,  sys._getframe().f_code.co_name ) )
        raise UnbalancedBraces( 0 , "Unbalanced Closing Braces in the file" )
-  if NO_EXCEPTION and shift != 0:
+       
+  #Check if there is extra shift at end.
+  if EXCEPTION and shift != 0:
     print( "\n  File \"%s\" , in %s" % 
       ( fname,  sys._getframe().f_code.co_name ) )
     raise UnbalancedBraces( 0 , "Unbalanced Opening Braces in the file!" )
 
      Writes the line number of each line into the output text file.
 
-     ATTRIBUTES:
+     ARGUMENTS:
+
        fname -- This is the name of input file.
        
        fout  -- This is the name of the output file. If not specificed,
      
      Removes excess white space on the right
      
-     ATTRIBUTES:
+     ARGUMENTS:
      
      fname -- This is the name of the input file.
      
     
   print( "%s Compeleted!" % sys._getframe(0).f_code.co_name ) 
  
-def ver_update():
-  import sys
-  if ( sys.version_info[0] == 2 ):
-    import __future__ 
-
 if __name__ == "__main__" :
   import sys
-  #ver_update()
   print("Starting WS")
   try:
+    #We test and see if, upon execution, some arguments are passed.
+    #
+    #Written this way, the code will run, if at least one argument is
+    #passed. The other parameter(s), will be default ones.
+    #If not, we will load our manual CLI prompt.
     inf = sys.argv[1]
     outf = (sys.argv[1] + "_edit.txt") if ( 
       len(sys.argv[1:2]) == 1 ) else sys.argv[2]
     finput = input("Please enter a file name\n")
     finput = finput.split()
     try:
-      mode = int(finput[1])
-    except IndexError:
+      foutput = None
       mode = 0
+      foutput = str(finput[1])
+      mode = int(finput[2])
+    except IndexError:
+      pass
     finally:
+      if ( foutput == '0' ) :
+        #'0' is an escape variable that can be typed in as input and
+        #remapped to None, so that the programmer can use the default 
+        #output file
+        foutput = None
       if ( isinstance(finput,list) ) :
-        formatter(finput[0], special = int(mode))
+        #Note that strings can be accessed as lists with the [] operator
+        #so we must check if the input is a legit list or just an array
+        #of chars!
+        formatter(finput[0], foutput, special = int(mode))
       else :
         formatter(finput, special = 0)
   else:
 
 Version 0.5.0.0 07-24-2011 Foundation
 Original Work Code Created.
-All functions in seperate files
+All functions in separate files
 
 Version 0.8.0.0 10-09-2011 Raiser
 All code now in one file.
 Two versions of code, one for v2 python and one for v3 python.
 Codes both work and annoying split bug is also fixed.
 
-
 Version 0.8.2.0 10-25-2011
 Fixed bad input to the script
 Included .sh script to run the code manually
 Calling the script will automatically run if there are 1 or 2 arguments passed.
 Added new mode (16) to formatter
 All lines in code are 80 characters or less
+
+Version 0.8.2.1 10-31-2011
+Added additional comments to code.
+*Will update 16 and add debug soon.
+Grammar fixed on all files.
+
 script. Until they are converted back into if/else statements, the WSv2
 will ONLY run on Python version 2.5+.
 
+Special 16 has a few bugs to iron out.