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 Tue 4 Sep 19:09
report abuse | download | new post

  1. ## xfce4-appentry-optimize [0.2.1]
  2. ##
  3. ## Licensed under the GNU GPL
  4. ## Programming by Ricky Hewitt [kahrn]
  5. ##
  6. ## Changes in 0.2.1:
  7. ##      - Cleaned up and optimized the source code a little.
  8. ##
  9. ## Mon 27 Aug 2007 11:28:04 BST
  10. ## kahrny@gmail.com / kahrn.co.uk / kahrn.wordpress.com
  11.  
  12. ## Import
  13. import os, sys
  14.  
  15. ##########################
  16. # User definable variables
  17. # Do not forget to update the locale section.
  18.  
  19. # locale defines the locale you wish to KEEP in the optimization process. All other locales
  20. # will be removed. If no locale is specified (or invalid), then it will remove ALL locales apart from the
  21. # one with no locale specification. (example: en_GB, fr, ca)
  22. locale = "en_GB"
  23.  
  24. # app_path defines where to look for the .desktop files used for the application menu
  25. app_path = "/usr/share/applications/" # Don't forget ending forward slash (/)!
  26.  
  27. # Enable backup (to disable backup, set to 0). Backups are saved in app_path/backup/backup.tar.gz..
  28. enable_backup = 0
  29. ##########################
  30.  
  31. class AppEntry:
  32.         # Set any variables we might need..
  33.         workingData = []
  34.         workingNameLocale = []
  35.                
  36.         def CheckDir(self):
  37.                 """Search for the location of the .desktop files being used for the application menu."""
  38.                 if os.access(app_path, 1) == True:
  39.                         return 1
  40.                 else:
  41.                         return 0
  42.                
  43.         def ListFiles(self):
  44.                 """List all the .desktop files used in app_path"""
  45.                 return os.listdir(app_path)
  46.                
  47.         def Optimize(self, filename):
  48.                 """Perform the optimization routines in the preferred order (and additional stuff)"""
  49.                 self.OptimizeLocale(filename, "Comment")
  50.                 self.OptimizeLocale(filename, "GenericName")
  51.                 self.OptimizeLocale(filename, "Name")
  52.                
  53.         def OptimizeLocale(self, filename, field_type):
  54.                 """Remove all locales (Name=) except from the one specified.
  55.                 filename specified the filename we want to optimize (the .desktop file).."""
  56.                 # Strip of Name entries and leave only the locales we want to keep.
  57.                 file = open(filename, 'r')
  58.                 for line in file.readlines():
  59.                         if line.startswith(field_type+'=') or line.startswith(field_type+"["+locale+"]"):
  60.                                 self.workingNameLocale.append(line[:-1])
  61.                 file.close()
  62.                                
  63.                 # Now grab all other lines so we can save them to the new file with the newly created locale data.
  64.                 file = open(filename, 'r')
  65.                 for line in file.readlines():
  66.                         if not line.startswith(field_type):
  67.                                 self.workingData.append(line[:-1])
  68.                 file.close()
  69.                
  70.                 # Write the new file..
  71.                 file = open(filename, 'w')
  72.                 file.write(self.workingData.pop(0)+"\n")
  73.                 file.write(self.workingData.pop(0)+"\n")
  74.                 for i in self.workingNameLocale:
  75.                         file.write(i+"\n")
  76.                 for i in self.workingData:
  77.                         file.write(i+"\n")
  78.                 file.close()
  79.                
  80.                 # Reset variables
  81.                 self.workingData = []
  82.                 self.workingNameLocale = []
  83.                        
  84.  
  85. def CheckRoot():
  86.         """This function will check to see if the user is running under root priviledges"""
  87.         if not os.geteuid()==0:
  88.                 sys.exit("\n  Please run as root!\n")
  89.         else:
  90.                 return 1
  91.                
  92. def CreateBackup():
  93.         """This function will create a backup and put it into a gziped tape archive."""
  94.         if enable_backup == 1:
  95.                 try:
  96.                         print "Attempting to create backup in "+app_path+"backup"
  97.                         os.chdir(app_path)
  98.                         os.system("mkdir ./backup/")
  99.                         os.system("tar -czf backup.tar.gz ./*.desktop")
  100.                         os.system("mv ./backup.tar.gz ./backup/backup.tar.gz")
  101.                         print "Backup created in "+app_path+"backup/backup.tar.gz"
  102.                         return 1
  103.                 except:
  104.                         print "Failed to create backup in CreateBackup().."
  105.                         return 0
  106.         else:
  107.                 print "Backup was disabled. Backup was not created."
  108.                 return 1
  109.        
  110. def main():
  111.         # Show starting messages and version information..
  112.         print "xfce4-appentry-optimize [0.2.1]"
  113.         print "Programmed by Ricky Hewitt [kahrn] - Licensed under GNU GPL."
  114.        
  115.         # Create instance of class AppEntry..
  116.         AppEntryInstance = AppEntry()
  117.         # Set some variables..
  118.         filelist = []
  119.         currentFile = ""
  120.         FileOriginalSize = 0
  121.         FileEndSize = 0
  122.         TotalSavedBytes = 0
  123.         x = 0 # number of shortcuts (to work out how many have been optimized at end)
  124.        
  125.         # Search for the location of the .desktop files..
  126.         if AppEntryInstance.CheckDir() and CheckRoot() and CreateBackup():
  127.                 for i in AppEntryInstance.ListFiles():
  128.                         # Create a list of files (with full path) to optimize..
  129.                         filelist.append(app_path+i)
  130.                         currentFile=filelist.pop(0)
  131.                         print " Optimizing \""+currentFile+"\":"
  132.                        
  133.                         # Deal with byte stat counting
  134.                         FileOriginalSize = os.path.getsize(currentFile)
  135.                         print "   Current size is: "+str(FileOriginalSize)+" bytes"
  136.                        
  137.                         # Optimize
  138.                         print "   Optimizing locale data.."
  139.                         try:
  140.                                 AppEntryInstance.Optimize(currentFile)
  141.                         except:
  142.                                 "Could not optimize.. probably not a .desktop file."
  143.                        
  144.                         # Deal with byte stat counting
  145.                         FileEndSize = os.path.getsize(currentFile)
  146.                         FileSavedBytes = (FileOriginalSize-FileEndSize)
  147.                         print "   Bytes Saved: "+str(FileSavedBytes)+" bytes"
  148.                         TotalSavedBytes = (TotalSavedBytes+FileSavedBytes)
  149.                        
  150.                         # Reset and increment some variables..
  151.                         currentFile = ""
  152.                         x = x+1
  153.                 # Display results
  154.                 print "\n  RESULTS:\n  Saved a total of "+str(TotalSavedBytes)+" bytes across "+str(x)+" shortcuts."
  155.         sys.exit("\n  Something went wrong!\n")
  156.            
  157. if __name__ == "__main__":
  158.     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