Commits

Henrik Tunedal committed 2609c25

Added support for attaching comments to packages.

  • Participants
  • Parent commits e1e23f1

Comments (0)

Files changed (1)

File check_license.py

     pass
 
 # Duplicate some functionality from metadata.py
+# TODO: There can be more than one instance of some keys, e.g.
+# Build Version. None of those are used here, but maybe they
+# should be handled better..
 def parse_package_metadata(filename):
     f = open(filename, "r")
     multiline = None
             pass
     raise ValueError, "invalid package name: '%s'" % name
 
+# Safely save a file in the manner recommended by Theodore Ts'o.
+def save_file(filename, func, tempext=".temp"):
+    temp_filename = filename + tempext
+    try:
+        f = open(temp_filename, "w")
+        func(f)       # call the function that wants to save something
+        f.flush()
+        os.fsync(f.fileno())
+        f.close()
+        os.rename(temp_filename, filename)
+    except StandardError, e:
+        try:
+            os.remove(temp_filename)
+        except OSError:
+            pass                # not much we can do
+        raise e
+
 def rewrite_license(metadata, new_license):
     for i, rad in enumerate(metadata["original metadata"]):
         if rad[0] == "license":
     else:
         metadata["original metadata"][license_index] = new_meta
     metadata["license"] = new_license
-    filename = os.path.join(metadata_root, metadata["package id"]) + ".txt"
-    temp_filename = filename + ".temp"
     try:
-        f = open(temp_filename, "w")
-        f.writelines(v for k, v in metadata["original metadata"])
-        f.flush()
-        os.fsync(f.fileno())
-        f.close()
-        os.rename(temp_filename, filename)
+        save_file(
+            os.path.join(metadata_root, metadata["package id"]) + ".txt",
+            lambda f: f.writelines(v for k, v in metadata["original metadata"]))
     except IOError, e:
         print "Metadata update failed:", e
-        try:
-            os.remove(temp_filename)
-        except OSError:
-            pass                # not much we can do
+
+# Write a licensing comment contained in metadata to disk
+def save_comment(metadata):
+    dirname = os.path.join(os.path.expanduser("~"), ".licensecomments")
+    if not os.path.exists(dirname):
+        os.makedirs(dirname)
+    save_file(os.path.join(dirname, metadata["package id"]),
+              lambda f: f.write(metadata["license comment"]))
+
+# Load a licensing comment, modifying the metadata in place.
+# It also returns the comment if there is one or None otherwise.
+def load_comment(metadata):
+    try:
+        f = open(os.path.join(os.path.expanduser("~"), ".licensecomments",
+                              metadata["package id"]))
+    except IOError:
+        return None
+    data = f.read()
+    metadata["license comment"] = data
+    return data
+
+# Launch an external editor to edit a licensing comment
+def edit_comment(metadata):
+    for var in ("EDITOR", "VISUAL"):
+        if var in os.environ:
+            editor = os.environ[var]
+            break
+    else:
+        editor = "vi"
+    import tempfile
+    tmp_fd, tmp_name = tempfile.mkstemp()
+    f = os.fdopen(tmp_fd, "w")
+    if "license comment" in metadata:
+        f.write(metadata["license comment"])
+    f.close()
+    if subprocess.call([editor, tmp_name]) != 0:
+        raise StandardError, "Unable to launch editor."
+    else:
+        f = open(tmp_name, "r")
+        metadata["license comment"] = f.read()
+        save_comment(metadata)
+        f.close()
 
 def interactive_mode(packages):
     def print_info(meta, res):
         print "Summary: %s" % meta.get("summary")
         print "License: %s" % meta.get("license")
         print "Website: %s" % meta.get("web site")
+        if "license comment" in meta:
+            print "Comment:"
+            # TODO: rewrap and indent
+            print meta["license comment"]
         print "File analysis:",
         if sourcedir_for_id(meta["package id"]):
             print
     i = 0
     while i < len(packages):
         meta = metadata_for_id(packages[i])
+        comment = load_comment(meta)
         res = check_package(meta["package id"])
         print_info(meta, res)
         while True:
             print
             try:
-                input = raw_input("Action [mnpqrvw]> ")
+                input = raw_input("Action [cmnpqrvw]> ")
             except EOFError:
                 input = "q"
             if not input:
                 input = "n"
             args = input.split()
             action = args[0]
-            if action == "m":   # print metadata
+            if action == "c":   # edit comment
+                edit_comment(meta)
+            elif action == "m":   # print metadata
                 print_info(meta, res)
             elif action == "n": # next package
                 i += 1; break
                 else:
                     print "You must supply a new license name."
             elif action == "v": # view files
-                key = len(args) > 1 and args[1].strip().lower() or "unknown"
+                if len(args) > 1:
+                    key = " ".join(args[1:]).strip().lower()
+                else:
+                    key = "unknown"
                 matches = [v for k, v in res.items() if k.lower() == key]
                 if matches:
                     subprocess.call(["less"] + matches[0])
     elif args.interactive:
         interactive_mode(
             packages or
-            [p[:-4] for p in os.listdir(metadata_root) if p.endswith(".txt")])
+            sorted(p[:-4] for p in os.listdir(metadata_root)
+                   if p.endswith(".txt")))
     elif args.list:
         license_type = args.list.lower()
         for package in (packages or downloaded_packages()):