]> git.itanic.dy.fi Git - emerge-timer/commitdiff
Improve code readability
authorEsko Kokkonen <esko.kokkonen@gmail.com>
Sat, 13 Aug 2011 16:12:50 +0000 (19:12 +0300)
committerEsko Kokkonen <esko.kokkonen@gmail.com>
Sat, 13 Aug 2011 16:12:50 +0000 (19:12 +0300)
Add spaces, comments, functions definitions and other improvements to
make the code more readable by human eyes.

emerge-timer.py

index 3179ed5590716afc22ac44f00c486e955eb493e6..29f9d74087538b9b1cac7ca5a13e53e2b6acd098 100755 (executable)
@@ -1,17 +1,25 @@
 #!/usr/bin/python
 
+
 import sys, subprocess, datetime, os
 
+
 PORTDIR = "/usr/portage/"
 LOGFILE = "/var/log/emerge.log"
 
+
 emerge_number = 0
 times = []
 
+
 green_start = "\033[32m"
 color_stop = "\033[m"
 
+
+
 def write_times(emerge_times_list):
+    """Writes the emerge times into a file called 'times'."""
+
     with open('times', 'w') as g:
 
         for i in emerge_times_list:
@@ -21,7 +29,11 @@ def write_times(emerge_times_list):
     g.close()
 
 
+
 def organize_times(time):
+    """Takes the emerge time in seconds, organizes it into
+    days, hours, minutes or seconds and finally prints that out."""
+
     days = time/(3600*24)
     hours = (days - int(days))*24
     minutes = (hours - int(hours))*60
@@ -56,7 +68,11 @@ def organize_times(time):
     print printable_sec,
 
 
+
 def date_printer(emerge_start):
+    """Take the emerge startup time in seconds and turn it into a
+    correct date."""
+
     date = datetime.datetime.fromtimestamp(emerge_start)
 
     year = str(date.year)
@@ -76,15 +92,24 @@ def date_printer(emerge_start):
     minute = str(date.minute)
     second = str(date.second)
 
+    # This is in the format 'Mon 23.05.2011 00:20:14'
+
     date = weekday + "{:%d.%m.%Y %H:%M:%S}".format(date)
 
     return date
 
 
+
 def get_package(name):
+    """Take the user-input package name and search for it
+    in PORTDIR. """
+
     dirlist = os.listdir(PORTDIR)
     possible_package = []
 
+
+    # If the given name is in the format xxx/zzz
+    # assume that xxx is the package group
     if '/' in name:
         group = name.partition('/')[0]
         pkg = name.partition('/')[2]
@@ -95,6 +120,9 @@ def get_package(name):
             if pkg in dirs:
                 possible_package.append(name)
 
+
+    # Go through the directory listing searching for anything
+    # that matches the given name
     for i in dirlist:
         directory = PORTDIR + i
         if os.path.isdir(directory):
@@ -102,26 +130,38 @@ def get_package(name):
             if name in dirs:
                 possible_package.append(i + '/' + name)
 
+
     if len(possible_package) > 1:
         print("Multiple packages found for '" + name + "'.")
         print("Possible packages: ")
         for value in possible_package:
             print("\t" + value)
 
+
     elif len(possible_package) == 1:
         package = possible_package[0]
         return package
 
+
     else:
         print("No package '" + name + "' found")
 
+
     sys.exit(1)
 
 
+
 def print_times(package, times, silent):
+    """Print the maximum/minimum/average times of the given emerge package.
+    If we're in the 'current emerge stage' (the 'silent' flag is True)
+    print the appropriate comment for that package."""
+
+
     times.sort()
     times.reverse()
 
+
+    # This should be True if we're in current emerge stage
     if silent == True:
         if emerge_number == 0:
             print("\t  no previous emerges found for this package"),
@@ -172,7 +212,10 @@ def print_times(package, times, silent):
               package + color_stop)
 
 
+
 def open_log():
+    """Attempt to open the LOGFILE."""
+
     try:
         f = open(LOGFILE, 'r')
     except IOError as detail:
@@ -182,7 +225,12 @@ def open_log():
         return f
 
 
+
 def list_emerge_processes(f):
+    """Look for the ebuild process with ps. If the process is found parse
+    the command for the package. With this package search the LOGFILE for
+    the emerge startup time."""
+
 
     packages = []
     for i in os.popen("ps ax"):
@@ -191,6 +239,7 @@ def list_emerge_processes(f):
 
              packages.append([pack, 0])
 
+
     for line in f:
         if ((">>>" in line) and ("emerge" in line)):
             for p in packages:
@@ -200,25 +249,34 @@ def list_emerge_processes(f):
                     if time > p[1]:
                         p[1] = time
 
+
     if len(packages) == 0:
         print "No current emerge process found."
         return
 
+
+    # Here we go through all the packages we have found and
+    # printout the current emerge time
     a = 1
     for p in packages:
         now = datetime.datetime.today()
         timestamp = datetime.datetime.fromtimestamp(p[1])
+
         difference = now - timestamp
 
+
         if difference.total_seconds() < 12*60*60:
             if a:
                 print("Currently emerging: ")
                 a = 0
+
             print("\t" + green_start + p[0] + color_stop),
             print('\n\t  current emerge time: '),
+
             organize_times(difference.total_seconds())
             print
 
+
             name = (p[0].partition('-')[0] + '-' +
                     p[0].partition('-')[2].partition('-')[0])
             main_loop(f, name, True)
@@ -226,19 +284,24 @@ def list_emerge_processes(f):
 
 
 def main_loop(f, package, silent):
+    """The main loop which parses the LOGFILE and if needed prints out emerge times."""
+
     global emerge_number
     emerge_number = 0
-    f.seek(0)
+    f.seek(0) # Seek to the beginning of the file
+
 
     # MAIN LOOP
     for line in f:
         if package in line:
             st = line.split(' ')
+
             for string in st:
                 if ((package in string) and (len(string) > len(package)+1)
                     and (string[len(package)+1].isdigit())):
                     full_package = st[st.index(string)]
 
+
                     if ((">>>" in line) and ("emerge" in line)):
                         time_string = line.partition(">>>")
                         time = float(time_string[0].strip().strip(":"))
@@ -247,13 +310,16 @@ def main_loop(f, package, silent):
                         if (":::" in line) and ("completed emerge" in line):
                             emerge_number += 1
 
+
                             time_string = line.partition(":::")
                             time2 = float(time_string[0].strip().strip(":"))
 
+
                             emerge_time = time2-time
 
                             date = date_printer(time)
 
+
                             if silent == False:
                                 print(str(len(times)+1) + "."),
                                 print(green_start + full_package + color_stop + "  >>>  "
@@ -264,13 +330,16 @@ def main_loop(f, package, silent):
                                 print("\n" + '-'*90)
 
                             times.append((emerge_time, date))
-
-                    except IndexError: pass
+                    except IndexError:
+                        pass
 
     print_times(package, times, silent)
 
 
+
 def main(status):
+    """Change between current emerge stage and normal operating stage."""
+
     global emerge_number
 
     f = open_log()
@@ -294,6 +363,7 @@ def main(status):
     f.close()
 
 
+
 if __name__ == "__main__":
 
     if len(sys.argv) > 1: