Metin Akdere yazdı 01-11-2011 15:47 tarihinde:
> 01-11-2011 15:25 tarihinde, Fatih Arslan yazdı:
> 
>> Buradaki "-n" diğer Pisi alt komutlarındaki gibi "-N" olarak yapsak nasıl 
>> olur ?
>> Tutarlılık sağlanmış olur. Benim elim doğrudan "-N" opsiyonuna gitti mesela,
>> böyle bir şey yok diye hata verdi haliyle :)
> 
> Haklısın, tutarlılık açısından -N kullanmak daha doğru olur.

Bu değişikliği içeren yamanın son halini ekliyorum.

-- 
Metin Akdere
Index: scripts/lspisi
===================================================================
--- scripts/lspisi	(revision 38426)
+++ scripts/lspisi	(working copy)
@@ -10,51 +10,142 @@
 #
 # Please read the COPYING file.
 
+from optparse import OptionParser
+
+import glob
 import os
 import sys
 import pisi
 
+
+class PackageNotFoundError(Exception):
+    def __init__(self, message):
+        print colorize("%s\n" % message, "red")
+        sys.exit(1)
+
+
+desc = """lspisi is a utility script that lists the content of the PiSi packages.
+You can supply arbitrary number of PiSi packages or directories that contain
+PiSi packages.
+lspisi lists the results seperately for each package.
+lspisi utility can list only directories in the package as well,
+which is useful for package developer.
+"""
+
+def colorize(msg, color, no_color=False):
+    """Colorizes the given message."""
+
+    if no_color:
+        return msg
+
+    colors = {'green'   : '\x1b[32;01m%s\x1b[0m',
+              'red'     : '\x1b[31;01m%s\x1b[0m',
+              'yellow'  : '\x1b[33;01m%s\x1b[0m',
+              'bold'    : '\x1b[1;01m%s\x1b[0m',
+              'none'    : '\x1b[0m%s\x1b[0m',
+             }
+    return colors[color if sys.stdout.isatty() else 'none'] % msg
+
 def show_info(filename):
+    """ Get file paths in the package """
+
     metadata, files = pisi.api.info_file(filename)
 
     paths = [fileinfo.path for fileinfo in files.list]
     paths.sort()
     return paths
 
+def show_dirs(filename):
+    """ Get only directories in the package. This is a option esp. for
+        package developers
+    """
+
+    dirlist = []
+    for file in show_info(filename):
+        dirlist.append(os.path.dirname(file))
+
+    return uniq(dirlist)
+
 def uniq(alist):
     set = {}
     return [set.setdefault(e, e) for e in alist if e not in set]
 
-def usage(errmsg):
-    print """
-    Error: %s
+def parse_options():
+    """ Parse command line options """
 
-    Usage:
-      lspisi PiSi_package.PiSi         (lists the content of package)
-      lspisi dirs PiSi_package.PiSi    (lists directories in the package for the package developer)
-    """ % (errmsg)
+    # To parse command line options, first instantiate OptionParser
+    parser = OptionParser(description=desc,
+                          usage= "Usage:  %prog [OPTION] [foo.pisi foo2.pisi..] \
+                          \n\t%prog [OPTION] [--dirs]")
 
-    sys.exit(1)
+    # Add option for directory listing
+    parser.add_option("-d", "--dirs",
+                      action="store_true",
+                      dest="dirs",
+                      default=False,
+                      help= "List directories in the package, useful for the \
+                             package developers")
+    # Use colorful output or not
+    parser.add_option("-N", "--no-color",
+                      action="store_true",
+                      dest="no_color",
+                      default=False,
+                      help= "Do not use colorful output")
 
+   # Return parse results
+    return parser
 
-def main():
-    if len(sys.argv) < 2 or ("dirs" in sys.argv and len(sys.argv) < 3):
-        usage("PiSi package required...")
+def print_header(package, no_color=False):
+    """ Common printing properties to display results per package """
 
-    if sys.argv[1] == "dirs":
-        dirlist = []
-        for file in show_info(sys.argv[2]):
-            dirlist.append(os.path.dirname(file))
+    header = "\nPackage: %s"
 
-        for dir in uniq(dirlist):
-            print "<Path fileType=\"\">/%s</Path>" % dir
+    pisi_package = pisi.package.Package(package)
+    package_name = pisi_package.get_metadata().package.name
+    print colorize(header % package_name, "yellow", no_color)
+    print colorize("%s\n" % (len(header + package_name) * "="), "yellow", \
+                             no_color)
 
-    elif not os.path.exists(sys.argv[1]):
-        print "File %s not found" % sys.argv[1]
+def main():
+    # Parse options
+    parser = parse_options()
+    options, args = parser.parse_args()
+    no_color = options.no_color
 
+    if len(args) == 0:
+        print colorize("You need to specify at least one PiSi package\n", \
+                       "red", no_color)
+        parser.print_usage()
+        sys.exit(1)
     else:
-        for file in show_info(sys.argv[1]):
-            print "/%s" % file
+        pisi_packages = []
 
+        for arg in args:
+            # Handle each argument. Maybe PiSi packages or directories
+            if os.path.exists(arg):
+                if os.path.isdir(arg):
+                    # A directory is given as an argument. List contents of
+                    # packages in that directory
+                    dirname = os.path.dirname(arg + "/")
+                    ret = glob.glob("%s/*.pisi" % dirname)
+                    if len(ret) > 0:
+                        pisi_packages.extend(ret)
+                elif arg.endswith(".pisi"):
+                    pisi_packages.append(arg)
+            else:
+                raise PackageNotFoundError("Cannot open package file %s" % arg)
+
+        for package in pisi_packages:
+            print_header(package, no_color)
+            if options.dirs:
+                # Print only directories in the packages
+                for path in show_dirs(package):
+                    print "<Path fileType=\"\">/%s</Path>" % path
+            else:
+                # List all files in the package
+                for _file in show_info(package):
+                    print "/%s" % _file
+
+
 if __name__ == "__main__":
     sys.exit(main())

Attachment: signature.asc
Description: OpenPGP digital signature

_______________________________________________
Gelistirici mailing list
Gelistirici@pardus.org.tr
http://liste.pardus.org.tr/mailman/listinfo/gelistirici

Cevap