]> arthur.barton.de Git - bup.git/blob - main.py
Move cmd-*.py to cmd/*-cmd.py.
[bup.git] / main.py
1 #!/usr/bin/env python
2 import sys, os, subprocess
3
4 argv = sys.argv
5 exe = argv[0]
6 exepath = os.path.split(exe)[0] or '.'
7
8 # fix the PYTHONPATH to include our lib dir
9 libpath = os.path.join(exepath, 'lib')
10 cmdpath = os.path.join(exepath, 'cmd')
11 sys.path[:0] = [libpath]
12 os.environ['PYTHONPATH'] = libpath + ':' + os.environ.get('PYTHONPATH', '')
13
14 from bup.helpers import *
15
16 def usage():
17     log('Usage: bup <subcmd> <options...>\n\n')
18     log('Available subcommands:\n')
19     for c in sorted(os.listdir(cmdpath) + os.listdir(exepath)):
20         if c.startswith('bup-') and c.find('.') < 0:
21             log('\t%s\n' % c[4:])
22     sys.exit(99)
23
24 if len(argv) < 2 or not argv[1] or argv[1][0] == '-':
25     usage()
26
27 subcmd = argv[1]
28 if subcmd == 'help':
29     usage()
30
31 def subpath(s):
32     sp = os.path.join(exepath, 'bup-%s' % s)
33     if not os.path.exists(sp):
34         sp = os.path.join(cmdpath, 'bup-%s' % s)
35     return sp
36
37 if not os.path.exists(subpath(subcmd)):
38     log('error: unknown command "%s"\n' % subcmd)
39     usage()
40
41
42 already_fixed = atoi(os.environ.get('BUP_FORCE_TTY'))
43 if subcmd in ['ftp']:
44     already_fixed = True
45 fix_stdout = not already_fixed and os.isatty(1)
46 fix_stderr = not already_fixed and os.isatty(2)
47
48 def force_tty():
49     if fix_stdout or fix_stderr:
50         os.environ['BUP_FORCE_TTY'] = '1'
51
52 if fix_stdout or fix_stderr:
53     realf = fix_stderr and 2 or 1
54     n = subprocess.Popen([subpath('newliner')],
55                          stdin=subprocess.PIPE, stdout=os.dup(realf),
56                          close_fds=True, preexec_fn=force_tty)
57     outf = fix_stdout and n.stdin.fileno() or 1
58     errf = fix_stderr and n.stdin.fileno() or 2
59 else:
60     n = None
61     outf = 1
62     errf = 2
63
64 ret = 95
65 try:
66     try:
67         p = subprocess.Popen([subpath(subcmd)] + argv[2:],
68                              stdout=outf, stderr=errf, preexec_fn=force_tty)
69         ret = p.wait()
70     except OSError, e:
71         log('%s: %s\n' % (subpath(subcmd), e))
72         ret = 98
73     except KeyboardInterrupt, e:
74         ret = 94
75 finally:
76     if n:
77         n.stdin.close()
78         try:
79             n.wait()
80         except:
81             pass
82 sys.exit(ret)