Subdomain Posts
Python | 497 days ago
Python | 498 days ago
Python | 498 days ago
Python | 498 days ago
Python | 498 days ago
Python | 537 days ago
Python | 537 days ago
Python | 537 days ago
Python | 583 days ago
Python | 583 days ago
Recent Posts
None | 36 sec ago
None | 2 min ago
None | 3 min ago
None | 3 min ago
JavaScript | 3 min ago
None | 4 min ago
Lua | 4 min ago
None | 4 min ago
MySQL | 5 min ago
None | 5 min ago
Sitereport
Find cool info about any domain on the internet?
visit sitereport
Free Subdomains
Want a pastebin.com sub-domain for your community?
learn more...
What is pastebin?
Pastebin is a website that hosts all your text & code on dedicated servers for easy sharing.
learn more...
Learn a little bit about the new Pastebin.com on our help page. hide message
By kahrn on the 6th of Nov 2008 09:17:02 PM Download | Raw | Embed | Report
  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.             if i[len(i)-8:len(i)] == ".desktop":
  66.                 final_listdir.append("kde/" + i)
  67.                 x = x + 1
  68.  
  69.         # The same for kde4
  70.         for i in kde4_listdir:
  71.             if i[len(i)-8:len(i)] == ".desktop":
  72.                 final_listdir.append("kde4/" + i)
  73.                 x = x + 1
  74.  
  75.         # Finally for freedesktop/gnome/xfce, etc..
  76.         for i in freedesktop_listdir:
  77.             if i[len(i)-8:len(i)] == ".desktop":
  78.                 final_listdir.append(i)
  79.                 x = x + 1
  80.  
  81.         return final_listdir
  82.          
  83.     def Optimize(self, filename):
  84.         """Perform the optimization routines in the preferred order (and additional stuff)"""
  85.         self.OptimizeLocale(filename, "Comment")
  86.         self.OptimizeLocale(filename, "GenericName")
  87.         self.OptimizeLocale(filename, "Name")
  88.          
  89.     def OptimizeLocale(self, filename, field_type):
  90.         """Remove all locales (Name=) except from the one specified.
  91.        filename specified the filename we want to optimize (the .desktop file).."""
  92.         # Strip of Name entries and leave only the locales we want to keep.
  93.         file = open(filename, 'r')
  94.         for line in file.readlines():
  95.             if line.startswith(field_type+'=') or line.startswith(field_type+"["+locale+"]"):
  96.                 self.workingNameLocale.append(line[:-1])
  97.         file.close()
  98.                  
  99.         # Now grab all other lines so we can save them to the new file with the newly created locale data.
  100.         file = open(filename, 'r')
  101.         for line in file.readlines():
  102.             if not line.startswith(field_type):
  103.                 self.workingData.append(line[:-1])
  104.         file.close()
  105.          
  106.         # Write the new file..
  107.         file = open(filename, 'w')
  108.         file.write(self.workingData.pop(0)+"\n")
  109.         file.write(self.workingData.pop(0)+"\n")
  110.         for i in self.workingNameLocale:
  111.             file.write(i+"\n")
  112.         for i in self.workingData:
  113.             file.write(i+"\n")
  114.         file.close()
  115.          
  116.         # Reset variables
  117.         self.workingData = []
  118.         self.workingNameLocale = []
  119.              
  120.  
  121. def CheckRoot():
  122.     """This function will check to see if the user is running under root priviledges"""
  123.     if not os.geteuid()==0:
  124.         sys.exit("\n  Please run as root!\n")
  125.     else:
  126.         return 1
  127.          
  128. def CreateBackup(mode_backup):
  129.     """This function will create a backup and put it into a gziped tape archive."""
  130.     if mode_backup == 1 and AppEntry().CheckDir(app_path):
  131.         try:
  132.             print "Attempting to create backup in "+app_path+"backup"
  133.             os.chdir(app_path)
  134.  
  135.             # Create the backup directory if it does not exist.
  136.             if AppEntry().CheckDir(app_path+"backup/") == 0:
  137.                 os.system("mkdir ./backup/")
  138.             else:
  139.                 print "Backup directory already exists.. will continue to make backup."
  140.            
  141.             # Archive the files and place into backup/backup[date-time].tar.gz
  142.             os.system("tar -czf " + filename_backup + " ./*")
  143.             os.system("mv ./" + filename_backup + " ./backup/" + filename_backup)
  144.             print "Backup created in "+app_path+"backup/" + filename_backup
  145.             return 1
  146.         except:
  147.             print "Failed to create backup in CreateBackup().."
  148.             return 0
  149.     else:
  150.         print "Backup was disabled. Backup was not created."
  151.         return 1
  152.  
  153. def CheckLocale(locale):
  154.     """This function checks to see if a valid locale has been given, and quit if otherwise."""
  155.     # A list of default valid locales.
  156.     valid_locales = ["af", "be", "bg", "bn", "br", "bs", "ca", "cs", "csb", "da", "de", "el", "eo", "es", "et", "eu", "fa", "fi", "fr",
  157.              "fy", "ga", "gl", "he", "hi", "hr", "hu", "id", "is", "it", "ja", "ka", "kk", "km", "lb", "lt", "lv", "mk", "ms", "nb",
  158.              "nds", "ne", "nl", "nn", "pa", "pl", "pt", "pt_BR", "ro", "ru", "rw", "se", "sk", "sl", "sr", "sv", "ta", "te", "tg", "th",
  159.              "tr", "tt", "uk", "uz", "en_GB", "en_US"]
  160.  
  161.     for i in valid_locales:
  162.         if i == locale:
  163.             return 1
  164.     else:
  165.         print "Error!\nAn invalid locale was given. Locale \"" + locale + "\" was not found."
  166.         sys.exit(1)
  167.      
  168. def main():
  169.     # Show starting messages and version information..
  170.     print "xfce4-appentry-optimize [0.2.2]"
  171.     print "Programmed by Ricky Hewitt [kahrn] - Licensed under GNU GPL.\n"
  172.      
  173.     # Create instance of class AppEntry..
  174.     AppEntryInstance = AppEntry()
  175.     # Set some variables..
  176.     filelist = []
  177.     currentFile = ""
  178.     FileOriginalSize = 0
  179.     FileEndSize = 0
  180.     TotalOriginalBytes = 0
  181.     TotalSavedBytes = 0
  182.     x = 0 # number of shortcuts (to work out how many have been optimized at end)
  183.  
  184.     # Default argument values
  185.     mode_verbosity = 0
  186.     mode_backup = 0
  187.  
  188.     # Check arguments
  189.     for arg in sys.argv:
  190.         if arg == "--enable-verbosity" or arg == "-v":
  191.             mode_verbosity = 1
  192.         if arg == "--enable-backup" or arg == "-b":
  193.             mode_backup = 1
  194.         if arg == "--help" or arg == "-h":
  195.             print "Usage:"
  196.             print "  --enable-verbosity, -v | Enable verbose mode for more output."
  197.             print "  --enable-backup, -b    | Enable backup."
  198.             print "  --help, -h             | Display help.\n"
  199.             sys.exit(1)
  200.      
  201.     # Search for the location of the .desktop files..
  202.     if CheckRoot() and CreateBackup(mode_backup) and CheckLocale(locale):
  203.         for i in AppEntryInstance.ListFiles():
  204.             # Create a list of files (with full path) to optimize..
  205.             filelist.append(app_path+i)
  206.             currentFile=filelist.pop(0)
  207.             if mode_verbosity == 1:
  208.                 print "Optimizing \""+currentFile+"\":"
  209.              
  210.             # Deal with byte stat counting
  211.             FileOriginalSize = os.path.getsize(currentFile)
  212.             if mode_verbosity == 1:
  213.                 print "  Current size is: "+str(FileOriginalSize)+" bytes"
  214.              
  215.             # Optimize
  216.             if mode_verbosity == 1:
  217.                 print "  Optimizing locale data.."
  218.             try:
  219.                 AppEntryInstance.Optimize(currentFile)
  220.             except:
  221.                 "Could not optimize.. probably not a .desktop file."
  222.              
  223.             # Deal with byte stat counting
  224.             FileEndSize = os.path.getsize(currentFile)
  225.             FileSavedBytes = (FileOriginalSize-FileEndSize)
  226.             if mode_verbosity == 1:
  227.                 print "  Bytes Saved: "+str(FileSavedBytes)+" bytes\n"
  228.             TotalOriginalBytes = TotalOriginalBytes + FileOriginalSize
  229.             TotalSavedBytes = (TotalSavedBytes+FileSavedBytes)
  230.              
  231.             # Reset and increment some variables..
  232.             currentFile = ""
  233.             x = x+1
  234.        
  235.         # Display final results
  236.         print "\n  RESULTS:\n  Saved a total of "+str(TotalSavedBytes/1000)+" kB from " + str(TotalOriginalBytes/1000) + " kB, across "+str(x)+" shortcuts."
  237.     else:
  238.         sys.exit("\n  Something went wrong!\n")
  239.            
  240. if __name__ == "__main__":
  241.     main()
Submit a correction or amendment below. [ previous version ] | [ difference ] | Make A New Post
To highlight particular lines, prefix each line with @h@
Syntax highlighting:
Post expiration:
Post exposure:
Name / Title:
Email: