Subdomain Posts
Python | 493 days ago
Python | 493 days ago
Python | 493 days ago
Python | 493 days ago
Python | 493 days ago
Python | 533 days ago
Python | 533 days ago
Python | 533 days ago
Python | 579 days ago
Python | 579 days ago
Recent Posts
Lua | 38 sec ago
VisualBasic | 51 sec ago
None | 53 sec ago
None | 1 min ago
None | 1 min ago
None | 1 min ago
None | 1 min ago
HTML | 1 min ago
None | 1 min ago
C++ | 1 min ago
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:07:29 PM Download | Raw | Embed | Report
  1. #!/usr/bin/env python
  2. ## appentry-optimize [0.2.2]
  3. ##
  4. ## A program to optimize .desktop files in freedesktop.org compliant
  5. ## desktops.
  6.  
  7. ##
  8.  
  9. ## Licensed under the GNU GPL
  10.  
  11. ## Programming by Ricky Hewitt [kahrn]
  12. ##
  13. ## Changes in 0.3:
  14.  
  15. ##  - Modified final report (now reports kB instead of bytes) and displays full original bytes.
  16. ##  - Checks to see if backup/ already exists before creating it.
  17. ##  - Multiple backups are now possible (rather than backup.tar.gz it will be backup[date-time].tar.gz)
  18. ##  - Added command line arguments. Use -b to enable backup, -h to display help and -v for increased verbosity.
  19. ##  - Verbosity by default is now decreased. Use the new option -v for increased verbosity.
  20. ##  - KDE 3.x and 4 support
  21. ##  - Only attempts to optimize .desktop files now.
  22. ##  - A check is now performed to help ensure a valid locale is given.
  23.  
  24. ##
  25.  
  26. ## 21:01 06 November 2008
  27.  
  28. ## kahrny@gmail.com / kahrn.co.uk / kahrn.wordpress.com
  29.  
  30.  
  31.  
  32. ## Import
  33.  
  34. import os, sys
  35. from time import strftime, gmtime
  36.  
  37.  
  38.  
  39. ##########################
  40.  
  41. # User definable variables
  42.  
  43. # Do not forget to update the locale section.
  44.  
  45.  
  46.  
  47. # locale defines the locale you wish to KEEP in the optimization process. All other locales
  48.  
  49. # will be removed. If no locale is specified (or invalid), then it will remove ALL locales apart from the
  50.  
  51. # one with no locale specification. (example: en_GB, fr, ca)
  52.  
  53. locale = "en_GB"
  54.  
  55.  
  56.  
  57. # app_path defines where to look for the .desktop files used for the application menu
  58.  
  59. app_path = "/usr/share/applications/" # Don't forget ending forward slash (/)!
  60.  
  61. # Filename for the archive (backup-day-month-year_hour-minute-second.tar.gz)
  62. filename_backup = "backup-" + strftime("%d-%m-%y_%H-%M-%S", gmtime()) + ".tar.gz"
  63.  
  64. ##########################
  65.  
  66.  
  67.  
  68. class AppEntry:
  69.  
  70.         # Set any variables we might need..
  71.  
  72.         workingData = []
  73.  
  74.         workingNameLocale = []
  75.  
  76.                
  77.  
  78.         def CheckDir(self, path):
  79.  
  80.                 """Search for the location of the .desktop files being used for the application menu."""
  81.  
  82.                 if os.access(path, 1) == True:
  83.  
  84.                         return 1
  85.  
  86.                 else:
  87.  
  88.                         return 0
  89.  
  90.                
  91.  
  92.         def ListFiles(self):
  93.  
  94.                 """List all the .desktop files used in app_path"""
  95.                 freedesktop_listdir = os.listdir(app_path)
  96.                 kde_listdir = os.listdir(app_path + "kde/")
  97.                 kde4_listdir = os.listdir(app_path + "kde4/")
  98.                 final_listdir = []
  99.                 x = 0
  100.                
  101.                 # Modify the paths for kde files
  102.                 for i in kde_listdir:
  103.                         if i[len(i)-8:len(i)] == ".desktop":
  104.                                 final_listdir.append("kde/" + i)
  105.                                 x = x + 1
  106.  
  107.                 # The same for kde4
  108.                 for i in kde4_listdir:
  109.                         if i[len(i)-8:len(i)] == ".desktop":
  110.                                 final_listdir.append("kde4/" + i)
  111.                                 x = x + 1
  112.  
  113.                 # Finally for freedesktop/gnome/xfce, etc..
  114.                 for i in freedesktop_listdir:
  115.                         if i[len(i)-8:len(i)] == ".desktop":
  116.                                 final_listdir.append(i)
  117.                                 x = x + 1
  118.  
  119.  
  120.                 return final_listdir
  121.  
  122.                
  123.  
  124.         def Optimize(self, filename):
  125.  
  126.                 """Perform the optimization routines in the preferred order (and additional stuff)"""
  127.  
  128.                 self.OptimizeLocale(filename, "Comment")
  129.  
  130.                 self.OptimizeLocale(filename, "GenericName")
  131.  
  132.                 self.OptimizeLocale(filename, "Name")
  133.  
  134.                
  135.  
  136.         def OptimizeLocale(self, filename, field_type):
  137.  
  138.                 """Remove all locales (Name=) except from the one specified.
  139.  
  140.                 filename specified the filename we want to optimize (the .desktop file).."""
  141.  
  142.                 # Strip of Name entries and leave only the locales we want to keep.
  143.  
  144.                 file = open(filename, 'r')
  145.  
  146.                 for line in file.readlines():
  147.  
  148.                         if line.startswith(field_type+'=') or line.startswith(field_type+"["+locale+"]"):
  149.  
  150.                                 self.workingNameLocale.append(line[:-1])
  151.  
  152.                 file.close()
  153.  
  154.                                
  155.  
  156.                 # Now grab all other lines so we can save them to the new file with the newly created locale data.
  157.  
  158.                 file = open(filename, 'r')
  159.  
  160.                 for line in file.readlines():
  161.  
  162.                         if not line.startswith(field_type):
  163.  
  164.                                 self.workingData.append(line[:-1])
  165.  
  166.                 file.close()
  167.  
  168.                
  169.  
  170.                 # Write the new file..
  171.  
  172.                 file = open(filename, 'w')
  173.  
  174.                 file.write(self.workingData.pop(0)+"\n")
  175.  
  176.                 file.write(self.workingData.pop(0)+"\n")
  177.  
  178.                 for i in self.workingNameLocale:
  179.  
  180.                         file.write(i+"\n")
  181.  
  182.                 for i in self.workingData:
  183.  
  184.                         file.write(i+"\n")
  185.  
  186.                 file.close()
  187.  
  188.                
  189.  
  190.                 # Reset variables
  191.  
  192.                 self.workingData = []
  193.  
  194.                 self.workingNameLocale = []
  195.  
  196.                        
  197.  
  198.  
  199.  
  200. def CheckRoot():
  201.  
  202.         """This function will check to see if the user is running under root priviledges"""
  203.  
  204.         if not os.geteuid()==0:
  205.  
  206.                 sys.exit("\n  Please run as root!\n")
  207.  
  208.         else:
  209.  
  210.                 return 1
  211.  
  212.                
  213.  
  214. def CreateBackup(mode_backup):
  215.  
  216.         """This function will create a backup and put it into a gziped tape archive."""
  217.  
  218.         if mode_backup == 1 and AppEntry().CheckDir(app_path):
  219.  
  220.                 try:
  221.  
  222.                         print "Attempting to create backup in "+app_path+"backup"
  223.  
  224.                         os.chdir(app_path)
  225.  
  226.                         # Create the backup directory if it does not exist.
  227.                         if AppEntry().CheckDir(app_path+"backup/") == 0:
  228.  
  229.                                 os.system("mkdir ./backup/")
  230.                         else:
  231.                                 print "Backup directory already exists.. will continue to make backup."
  232.                        
  233.                         # Archive the files and place into backup/backup[date-time].tar.gz
  234.  
  235.                         os.system("tar -czf " + filename_backup + " ./*")
  236.  
  237.                         os.system("mv ./" + filename_backup + " ./backup/" + filename_backup)
  238.  
  239.                         print "Backup created in "+app_path+"backup/" + filename_backup
  240.  
  241.                         return 1
  242.  
  243.                 except:
  244.  
  245.                         print "Failed to create backup in CreateBackup().."
  246.  
  247.                         return 0
  248.  
  249.         else:
  250.  
  251.                 print "Backup was disabled. Backup was not created."
  252.  
  253.                 return 1
  254.  
  255. def CheckLocale(locale):
  256.         """This function checks to see if a valid locale has been given, and quit if otherwise."""
  257.         # A list of default valid locales.
  258.         valid_locales = ["af", "be", "bg", "bn", "br", "bs", "ca", "cs", "csb", "da", "de", "el", "eo", "es", "et", "eu", "fa", "fi", "fr",
  259.                          "fy", "ga", "gl", "he", "hi", "hr", "hu", "id", "is", "it", "ja", "ka", "kk", "km", "lb", "lt", "lv", "mk", "ms", "nb",
  260.                          "nds", "ne", "nl", "nn", "pa", "pl", "pt", "pt_BR", "ro", "ru", "rw", "se", "sk", "sl", "sr", "sv", "ta", "te", "tg", "th",
  261.                          "tr", "tt", "uk", "uz", "en_GB", "en_US"]
  262.  
  263.         for i in valid_locales:
  264.                 if i == locale:
  265.                         return 1
  266.         else:
  267.                 print "Error!\nAn invalid locale was given. Locale \"" + locale + "\" was not found."
  268.                 sys.exit(1)
  269.  
  270.        
  271.  
  272. def main():
  273.  
  274.         # Show starting messages and version information..
  275.  
  276.         print "xfce4-appentry-optimize [0.2.2]"
  277.  
  278.         print "Programmed by Ricky Hewitt [kahrn] - Licensed under GNU GPL.\n"
  279.  
  280.        
  281.  
  282.         # Create instance of class AppEntry..
  283.  
  284.         AppEntryInstance = AppEntry()
  285.  
  286.         # Set some variables..
  287.  
  288.         filelist = []
  289.  
  290.         currentFile = ""
  291.  
  292.         FileOriginalSize = 0
  293.  
  294.         FileEndSize = 0
  295.         TotalOriginalBytes = 0
  296.  
  297.         TotalSavedBytes = 0
  298.  
  299.         x = 0 # number of shortcuts (to work out how many have been optimized at end)
  300.  
  301.         # Default argument values
  302.         mode_verbosity = 0
  303.         mode_backup = 0
  304.  
  305.         # Check arguments
  306.         for arg in sys.argv:
  307.                 if arg == "--enable-verbosity" or arg == "-v":
  308.                         mode_verbosity = 1
  309.                 if arg == "--enable-backup" or arg == "-b":
  310.                         mode_backup = 1
  311.                 if arg == "--help" or arg == "-h":
  312.                         print "Usage:"
  313.                         print "  --enable-verbosity, -v | Enable verbose mode for more output."
  314.                         print "  --enable-backup, -b    | Enable backup."
  315.                         print "  --help, -h             | Display help.\n"
  316.                         sys.exit(1)
  317.  
  318.        
  319.  
  320.         # Search for the location of the .desktop files..
  321.  
  322.         if CheckRoot() and CreateBackup(mode_backup) and CheckLocale(locale):
  323.  
  324.                 for i in AppEntryInstance.ListFiles():
  325.  
  326.                         # Create a list of files (with full path) to optimize..
  327.  
  328.                         filelist.append(app_path+i)
  329.  
  330.                         currentFile=filelist.pop(0)
  331.                         if mode_verbosity == 1:
  332.  
  333.                                 print "Optimizing \""+currentFile+"\":"
  334.  
  335.                        
  336.  
  337.                         # Deal with byte stat counting
  338.  
  339.                         FileOriginalSize = os.path.getsize(currentFile)
  340.                         if mode_verbosity == 1:
  341.  
  342.                                 print "  Current size is: "+str(FileOriginalSize)+" bytes"
  343.  
  344.                        
  345.  
  346.                         # Optimize
  347.  
  348.                         if mode_verbosity == 1:
  349.                                 print "  Optimizing locale data.."
  350.  
  351.                         try:
  352.  
  353.                                 AppEntryInstance.Optimize(currentFile)
  354.  
  355.                         except:
  356.  
  357.                                 "Could not optimize.. probably not a .desktop file."
  358.  
  359.                        
  360.  
  361.                         # Deal with byte stat counting
  362.  
  363.                         FileEndSize = os.path.getsize(currentFile)
  364.  
  365.                         FileSavedBytes = (FileOriginalSize-FileEndSize)
  366.  
  367.                         if mode_verbosity == 1:
  368.                                 print "  Bytes Saved: "+str(FileSavedBytes)+" bytes\n"
  369.                         TotalOriginalBytes = TotalOriginalBytes + FileOriginalSize
  370.  
  371.                         TotalSavedBytes = (TotalSavedBytes+FileSavedBytes)
  372.  
  373.                        
  374.  
  375.                         # Reset and increment some variables..
  376.  
  377.                         currentFile = ""
  378.  
  379.                         x = x+1
  380.  
  381.                
  382.                 # Display final results
  383.  
  384.                 print "\n  RESULTS:\n  Saved a total of "+str(TotalSavedBytes/1000)+" kB from " + str(TotalOriginalBytes/1000) + " kB, across "+str(x)+" shortcuts."
  385.  
  386.         else:
  387.  
  388.                 sys.exit("\n  Something went wrong!\n")
  389.  
  390.            
  391.  
  392. if __name__ == "__main__":
  393.  
  394.     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: