apt-mark 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. try:
  28. tagfile = apt_pkg.ParseTagFile(open(STATE_FILE))
  29. outfile = open(STATE_FILE+".tmp","w")
  30. except IOError, msg:
  31. print "%s, are you root?" % (msg)
  32. sys.exit(1)
  33. while tagfile.Step():
  34. pkgname = tagfile.Section.get("Package")
  35. autoInst = tagfile.Section.get("Auto-Installed")
  36. if pkgname in pkgs:
  37. if options.verbose:
  38. print "changing %s to %s" % (pkgname,action)
  39. newsec = apt_pkg.RewriteSection(tagfile.Section,
  40. [],
  41. [ ("Auto-Installed",str(action)) ]
  42. )
  43. outfile.write(newsec+"\n")
  44. else:
  45. outfile.write(str(tagfile.Section)+"\n")
  46. # all done, rename the tmpfile
  47. os.chmod(outfile.name, 0644)
  48. os.rename(outfile.name, STATE_FILE)
  49. os.chmod(STATE_FILE, 0644)
  50. if __name__ == "__main__":
  51. apt_pkg.init()
  52. # option parsing
  53. parser = OptionParser()
  54. parser.usage = "%prog [options] {markauto|unmarkauto} packages..."
  55. parser.add_option("-f", "--file", action="store", type="string",
  56. dest="filename",
  57. help="read/write a different file")
  58. parser.add_option("-v", "--verbose",
  59. action="store_true", dest="verbose", default=False,
  60. help="print verbose status messages to stdout")
  61. (options, args) = parser.parse_args()
  62. # get the state-file
  63. if not options.filename:
  64. STATE_FILE = apt_pkg.Config.FindDir("Dir::State") + "extended_states"
  65. else:
  66. STATE_FILE=options.filename
  67. if args[0] == "showauto":
  68. show_automatic(STATE_FILE)
  69. else:
  70. # get pkgs to change
  71. if args[0] not in actions.keys():
  72. parser.error("first argument must be 'markauto', 'unmarkauto' or 'showauto'")
  73. pkgs = args[1:]
  74. action = actions[args[0]]
  75. mark_unmark_automatic(STATE_FILE, action, pkgs)