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