apt-mark 2.8 KB

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