pastebin - collaborative debugging

pastebin is a collaborative debugging tool allowing you to share and modify code snippets while chatting on IRC, IM or a message board.

This site is developed to XHTML and CSS2 W3C standards. If you see this paragraph, your browser does not support those standards and you need to upgrade. Visit WaSP for a variety of options.

kahrn private pastebin - collaborative debugging tool What's a private pastebin?


Posted by kahrn on Fri 7 Nov 16:41 (modification of post by kahrn view diff)
report abuse | download | new post

  1. #!/usr/bin/env python
  2. ## appentry-optimize [0.3]
  3. ##
  4. ## A program to optimize .desktop files in freedesktop.org compliant
  5. ## desktops.
  6. ##
  7. ## Licensed under the GNU GPL
  8. ## Programming by Ricky Hewitt [kahrn]
  9. ##
  10. ## Changes in 0.3:
  11. ##  - Modified final report (now reports kB instead of bytes) and displays full original bytes.
  12. ##  - Checks to see if backup/ already exists before creating it.
  13. ##  - Multiple backups are now possible (rather than backup.tar.gz it will be backup[date-time].tar.gz)
  14. ##  - Added command line arguments. Use -b to enable backup, -h to display help and -v for increased verbosity.
  15. ##  - Verbosity by default is now decreased. Use the new option -v for increased verbosity.
  16. ##  - KDE 3.x and 4 support
  17. ##  - Only attempts to optimize .desktop files now.
  18. ##  - A check is now performed to help ensure a valid locale is given.
  19. ##
  20. ## 21:01 06 November 2008
  21. ## kahrny@gmail.com / kahrn.co.uk / kahrn.wordpress.com
  22.  
  23. ## Import
  24. import os, sys
  25. from time import strftime, gmtime
  26.  
  27. ##########################
  28. # User definable variables
  29. # Do not forget to update the locale section.
  30.  
  31. # locale defines the locale you wish to KEEP in the optimization process. All other locales
  32. # will be removed. If no locale is specified (or invalid), then it will remove ALL locales apart from the
  33. # one with no locale specification. (example: en_GB, fr, ca)
  34. locale = "en_GB"
  35.  
  36. # app_path defines where to look for the .desktop files used for the application menu
  37. app_path = "/usr/share/applications/" # Don't forget ending forward slash (/)!
  38.  
  39. # Filename for the archive (backup-day-month-year_hour-minute-second.tar.gz)
  40. filename_backup = "backup-" + strftime("%d-%m-%y_%H-%M-%S", gmtime()) + ".tar.gz"
  41. ##########################
  42.  
  43. class AppEntry:
  44.     # Set any variables we might need..
  45.     workingData = []
  46.     workingNameLocale = []
  47.          
  48.     def CheckDir(self, path):
  49.         """Search for the location of the .desktop files being used for the application menu."""
  50.         if os.access(path, 1) == True:
  51.             return 1
  52.         else:
  53.             return 0
  54.              
  55.     def ListFiles(self):
  56.         """List all the .desktop files used in app_path"""
  57.         freedesktop_listdir = os.listdir(app_path)
  58.         kde_listdir = os.listdir(app_path + "kde/")
  59.         kde4_listdir = os.listdir(app_path + "kde4/")
  60.         final_listdir = []
  61.         x = 0
  62.        
  63.         # Modify the paths for kde files
  64.         for i in kde_listdir:
  65.             # Filter by *.desktop files.
  66.             if i[len(i)-8:len(i)] == ".desktop":
  67.                 final_listdir.append("kde/" + i)
  68.                 x = x + 1
  69.  
  70.         # The same for kde4
  71.         for i in kde4_listdir:
  72.             if i[len(i)-8:len(i)] == ".desktop":
  73.                 final_listdir.append("kde4/" + i)
  74.                 x = x + 1
  75.  
  76.         # Finally for freedesktop/gnome/xfce, etc..
  77.         for i in freedesktop_listdir:
  78.             if i[len(i)-8:len(i)] == ".desktop":
  79.                 final_listdir.append(i)
  80.                 x = x + 1
  81.  
  82.         return final_listdir
  83.          
  84.     def Optimize(self, filename):
  85.         """Perform the optimization routines in the preferred order (and additional stuff)"""
  86.         self.OptimizeLocale(filename, "Comment")
  87.         self.OptimizeLocale(filename, "GenericName")
  88.         self.OptimizeLocale(filename, "Name")
  89.          
  90.     def OptimizeLocale(self, filename, field_type):
  91.         """Remove all locales (Name=) except from the one specified.
  92.        filename specified the filename we want to optimize (the .desktop file).."""
  93.         # Strip of Name entries and leave only the locales we want to keep.
  94.         file = open(filename, 'r')
  95.         for line in file.readlines():
  96.             if line.startswith(field_type+'=') or line.startswith(field_type+"["+locale+"]"):
  97.                 self.workingNameLocale.append(line[:-1])
  98.         file.close()
  99.                  
  100.         # Now grab all other lines so we can save them to the new file with the newly created locale data.
  101.         file = open(filename, 'r')
  102.         for line in file.readlines():
  103.             if not line.startswith(field_type):
  104.                 self.workingData.append(line[:-1])
  105.         file.close()
  106.          
  107.         # Write the new file..
  108.         file = open(filename, 'w')
  109.         file.write(self.workingData.pop(0)+"\n")
  110.         file.write(self.workingData.pop(0)+"\n")
  111.         for i in self.workingNameLocale:
  112.             file.write(i+"\n")
  113.         for i in self.workingData:
  114.             file.write(i+"\n")
  115.         file.close()
  116.          
  117.         # Reset variables
  118.         self.workingData = []
  119.         self.workingNameLocale = []
  120.              
  121.  
  122. def CheckRoot():
  123.     """This function will check to see if the user is running under root priviledges"""
  124.     if not os.geteuid()==0:
  125.         sys.exit("\n  Please run as root!\n")
  126.     else:
  127.         return 1
  128.          
  129. def CreateBackup(mode_backup):
  130.     """This function will create a backup and put it into a gziped tape archive."""
  131.     if mode_backup == 1 and AppEntry().CheckDir(app_path):
  132.         try:
  133.             print "Attempting to create backup in "+app_path+"backup"
  134.             os.chdir(app_path)
  135.  
  136.             # Create the backup directory if it does not exist.
  137.             if AppEntry().CheckDir(app_path+"backup/") == 0:
  138.                 os.system("mkdir ./backup/")
  139.             else:
  140.                 print "Backup directory already exists.. will continue to make backup."
  141.            
  142.             # Archive the files and place into backup/backup[date-time].tar.gz
  143.             os.system("tar -czf " + filename_backup + " ./*")
  144.             os.system("mv ./" + filename_backup + " ./backup/" + filename_backup)
  145.             print "Backup created in "+app_path+"backup/" + filename_backup
  146.             return 1
  147.         except:
  148.             print "Failed to create backup in CreateBackup().."
  149.             return 0
  150.     else:
  151.         print "Backup was disabled. Backup was not created."
  152.         return 1
  153.  
  154. def CheckLocale(locale):
  155.     """This function checks to see if a valid locale has been given, and quit if otherwise."""
  156.     # A list of default valid locales.
  157.     valid_locales = ["af", "be", "bg", "bn", "br", "bs", "ca", "cs", "csb", "da", "de", "el", "eo", "es", "et", "eu", "fa", "fi", "fr",
  158.              "fy", "ga", "gl", "he", "hi", "hr", "hu", "id", "is", "it", "ja", "ka", "kk", "km", "lb", "lt", "lv", "mk", "ms", "nb",
  159.              "nds", "ne", "nl", "nn", "pa", "pl", "pt", "pt_BR", "ro", "ru", "rw", "se", "sk", "sl", "sr", "sv", "ta", "te", "tg", "th",
  160.              "tr", "tt", "uk", "uz", "en_GB", "en_US"]
  161.  
  162.     for i in valid_locales:
  163.         if i == locale:
  164.             return 1
  165.     else:
  166.         print "Error!\nAn invalid locale was given. Locale \"" + locale + "\" was not found."
  167.         sys.exit(1)
  168.      
  169. def main():
  170.     # Show starting messages and version information..
  171.     print "xfce4-appentry-optimize [0.3]"
  172.     print "Programmed by Ricky Hewitt [kahrn] - Licensed under GNU GPL.\n"
  173.      
  174.     # Create instance of class AppEntry..
  175.     AppEntryInstance = AppEntry()
  176.     # Set some variables..
  177.     filelist = []
  178.     currentFile = ""
  179.     FileOriginalSize = 0
  180.     FileEndSize = 0
  181.     TotalOriginalBytes = 0
  182.     TotalSavedBytes = 0
  183.     x = 0 # number of shortcuts (to work out how many have been optimized at end)
  184.  
  185.     # Default argument values
  186.     mode_verbosity = 0
  187.     mode_backup = 0
  188.  
  189.     # Check arguments
  190.     for arg in sys.argv:
  191.         if arg == "--enable-verbosity" or arg == "-v":
  192.             mode_verbosity = 1
  193.         if arg == "--enable-backup" or arg == "-b":
  194.             mode_backup = 1
  195.         if arg == "--help" or arg == "-h":
  196.             print "Usage:"
  197.             print "  --enable-verbosity, -v | Enable verbose mode for more output."
  198.             print "  --enable-backup, -b    | Enable backup."
  199.             print "  --help, -h             | Display help.\n"
  200.             sys.exit(1)
  201.      
  202.     # Search for the location of the .desktop files..
  203.     if CheckRoot() and CreateBackup(mode_backup) and CheckLocale(locale):
  204.         for i in AppEntryInstance.ListFiles():
  205.             # Create a list of files (with full path) to optimize..
  206.             filelist.append(app_path+i)
  207.             currentFile=filelist.pop(0)
  208.             if mode_verbosity == 1:
  209.                 print "Optimizing \""+currentFile+"\":"
  210.              
  211.             # Deal with byte stat counting
  212.             FileOriginalSize = os.path.getsize(currentFile)
  213.             if mode_verbosity == 1:
  214.                 print "  Current size is: "+str(FileOriginalSize)+" bytes"
  215.              
  216.             # Optimize
  217.             if mode_verbosity == 1:
  218.                 print "  Optimizing locale data.."
  219.             try:
  220.                 AppEntryInstance.Optimize(currentFile)
  221.             except:
  222.                 "Could not optimize.. probably not a .desktop file."
  223.              
  224.             # Deal with byte stat counting
  225.             FileEndSize = os.path.getsize(currentFile)
  226.             FileSavedBytes = (FileOriginalSize-FileEndSize)
  227.             if mode_verbosity == 1:
  228.                 print "  Bytes Saved: "+str(FileSavedBytes)+" bytes\n"
  229.             TotalOriginalBytes = TotalOriginalBytes + FileOriginalSize
  230.             TotalSavedBytes = (TotalSavedBytes+FileSavedBytes)
  231.              
  232.             # Reset and increment some variables..
  233.             currentFile = ""
  234.             x = x+1
  235.        
  236.         # Display final results
  237.         print "\n  RESULTS:\n  Saved a total of "+str(TotalSavedBytes/1000)+" kB from " + str(TotalOriginalBytes/1000) + " kB, across "+str(x)+" shortcuts."
  238.     else:
  239.         sys.exit("\n  Something went wrong!\n")
  240.            
  241. if __name__ == "__main__":
  242.     main()

Submit a correction or amendment below (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:

To highlight particular lines, prefix each line with @@


Remember me so that I can delete my post