Added 'Verify integrity' action to cache browser (works like '0store verify').
[zeroinstall.git] / zeroinstall / zerostore / cli.py
blobf6850b0b742564541e84d47ace731b8e48f95cba
1 # Copyright (C) 2006, Thomas Leonard
2 # See the README file for details, or visit http://0install.net.
4 import sys, os, sha
5 from zeroinstall.zerostore.manifest import generate_manifest, verify
6 from zeroinstall import zerostore, SafeException
8 stores = None
10 def init_stores():
11 global stores
12 assert stores is None
13 if stores is None:
14 stores = zerostore.Stores()
16 class UsageError(SafeException): pass
18 def do_manifest(args):
19 """manifest DIRECTORY"""
20 if len(args) != 1: raise UsageError("Wrong number of arguments")
21 import sha
22 digest = sha.new()
23 for line in generate_manifest(args[0]):
24 print line
25 digest.update(line + '\n')
26 print "sha1=" + digest.hexdigest()
27 sys.exit(0)
29 def do_find(args):
30 """find DIGEST"""
31 if len(args) != 1: raise UsageError("Wrong number of arguments")
32 try:
33 print stores.lookup(args[0])
34 sys.exit(0)
35 except zerostore.BadDigest, ex:
36 print >>sys.stderr, ex
37 except zerostore.NotStored, ex:
38 print >>sys.stderr, ex
39 sys.exit(1)
41 def do_add(args):
42 """add DIGEST (DIRECTORY | (ARCHIVE [EXTRACT])"""
43 if len(args) < 2: raise UsageError("Missing arguments")
44 digest = args[0]
45 if os.path.isdir(args[1]):
46 if len(args) > 2: raise UsageError("Too many arguments")
47 stores.add_dir_to_cache(digest, args[1])
48 elif os.path.isfile(args[1]):
49 if len(args) > 3: raise UsageError("Too many arguments")
50 if len(args) > 2:
51 extract = args[2]
52 else:
53 extract = None
54 stores.add_archive_to_cache(digest, file(args[1]), args[1], extract)
55 else:
56 raise UsageError("No such file or directory '%s'" % args[1])
58 def do_verify(args):
59 """verify (DIGEST | DIRECTORY)"""
60 if len(args) != 1: raise UsageError("Missing DIGEST or DIRECTORY")
61 root = get_stored(args[0])
63 print "Verifying", root
64 try:
65 verify(root)
66 print "OK"
67 except zerostore.BadDigest, ex:
68 print str(ex)
69 if ex.detail:
70 print
71 print ex.detail
72 sys.exit(1)
74 def show_changes(actual, saved):
75 import difflib
76 for line in difflib.unified_diff(saved, actual, 'Recorded', 'Actual'):
77 print line,
79 def do_list(args):
80 """list"""
81 if args: raise UsageError("List takes no arguments")
82 print "User store (writable) : " + stores.stores[0].dir
83 for s in stores.stores[1:]:
84 print "System store : " + s.dir
85 if len(stores.stores) < 2:
86 print "No system stores."
88 def get_stored(dir_or_digest):
89 if os.path.isdir(dir_or_digest):
90 return dir_or_digest
91 else:
92 try:
93 return stores.lookup(dir_or_digest)
94 except zerostore.NotStored, ex:
95 print >>sys.stderr, ex
96 sys.exit(1)
98 commands = [do_add, do_find, do_list, do_manifest, do_verify]