Advertisement
Guest User

Untitled

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