apt-mark 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #!/usr/bin/python
  2. from optparse import OptionParser
  3. try:
  4. import apt_pkg
  5. except ImportError:
  6. print "Error importing apt_pkg, is python-apt installed?"
  7. import sys
  8. import os.path
  9. actions = { "markauto" : 1,
  10. "unmarkauto": 0
  11. }
  12. def show_automatic(filename):
  13. if not os.path.exists(STATE_FILE):
  14. return
  15. auto = set()
  16. tagfile = apt_pkg.ParseTagFile(open(STATE_FILE))
  17. while tagfile.Step():
  18. pkgname = tagfile.Section.get("Package")
  19. autoInst = tagfile.Section.get("Auto-Installed")
  20. if int(autoInst):
  21. auto.add(pkgname)
  22. print "\n".join(sorted(auto))
  23. def mark_unmark_automatic(filename, action, pkgs):
  24. " mark or unmark automatic flag"
  25. # open the statefile
  26. if os.path.exists(STATE_FILE):
  27. tagfile = apt_pkg.ParseTagFile(open(STATE_FILE))
  28. outfile = open(STATE_FILE+".tmp","w")
  29. while tagfile.Step():
  30. pkgname = tagfile.Section.get("Package")
  31. autoInst = tagfile.Section.get("Auto-Installed")
  32. if pkgname in pkgs:
  33. if options.verbose:
  34. print "changing %s to %s" % (pkgname,action)
  35. newsec = apt_pkg.RewriteSection(tagfile.Section,
  36. [],
  37. [ ("Auto-Installed",str(action)) ]
  38. )
  39. outfile.write(newsec+"\n")
  40. else:
  41. outfile.write(str(tagfile.Section)+"\n")
  42. # all done, rename the tmpfile
  43. os.chmod(outfile.name, 0644)
  44. os.rename(outfile.name, STATE_FILE)
  45. os.chmod(STATE_FILE, 0644)
  46. if __name__ == "__main__":
  47. apt_pkg.init()
  48. # option parsing
  49. parser = OptionParser()
  50. parser.usage = "%prog [options] {markauto|unmarkauto} packages..."
  51. parser.add_option("-f", "--file", action="store", type="string",
  52. dest="filename",
  53. help="read/write a different file")
  54. parser.add_option("-v", "--verbose",
  55. action="store_true", dest="verbose", default=False,
  56. help="print verbose status messages to stdout")
  57. (options, args) = parser.parse_args()
  58. # get the state-file
  59. if not options.filename:
  60. STATE_FILE = apt_pkg.Config.FindDir("Dir::State") + "extended_states"
  61. else:
  62. STATE_FILE=options.filename
  63. if args[0] == "showauto":
  64. show_automatic(STATE_FILE)
  65. else:
  66. # get pkgs to change
  67. if args[0] not in actions.keys():
  68. parser.error("first argument must be 'markauto', 'unmarkauto' or 'showauto'")
  69. pkgs = args[1:]
  70. action = actions[args[0]]
  71. mark_unmark_automatic(STATE_FILE, action, pkgs)