]> git.ipfire.org Git - pakfire.git/blame - pakfire/util.py
Fix download information.
[pakfire.git] / pakfire / util.py
CommitLineData
47a4cb89
MT
1#!/usr/bin/python
2
0a9a2371 3import fcntl
47a4cb89 4import os
4496b160 5import progressbar
47a4cb89 6import random
47a4cb89
MT
7import shutil
8import string
0a9a2371 9import struct
47a4cb89 10import sys
0a9a2371 11import termios
47a4cb89
MT
12import time
13
14from errors import Error
0a9a2371 15from packages.util import calc_hash1, format_size, format_speed, format_time
c0fd807c 16from i18n import _
47a4cb89 17
e9c20259
MT
18def cli_is_interactive():
19 """
20 Say weather a shell is interactive or not.
21 """
22 if sys.stdin.isatty() and sys.stdout.isatty() and sys.stderr.isatty():
23 return True
24
25 return False
26
c0fd807c
MT
27def ask_user(question):
28 """
29 Ask the user the question, he or she can answer with yes or no.
30
31 This function returns True for "yes" and False for "no".
32
33 If the software is running in a non-inteactive shell, no question
34 is asked at all and the answer is always "yes".
35 """
36 if not cli_is_interactive():
37 return True
38
39 print _("%s [y/N]") % question,
40 ret = raw_input()
41 print # Just an empty line.
42
43 return ret in ("y", "Y", "z", "Z", "j", "J")
44
7c8f2953
MT
45def random_string(length=20):
46 s = ""
47
48 for i in range(length):
49 s += random.choice(string.letters)
50
51 return s
52
4496b160
MT
53def make_progress(message, maxval):
54 # Return nothing if stdout is not a terminal.
55 if not sys.stdout.isatty():
56 return
57
58 widgets = [
59 " ",
60 "%-40s" % message,
61 " ",
62 progressbar.Bar(left="[", right="]"),
63 " ",
64 progressbar.ETA(),
65 " ",
66 ]
67
68 if not maxval:
69 maxval = 1
70
71 pb = progressbar.ProgressBar(widgets=widgets, maxval=maxval)
72 pb.start()
73
74 return pb
75
47a4cb89
MT
76def rm(path, *args, **kargs):
77 """
78 version of shutil.rmtree that ignores no-such-file-or-directory errors,
79 and tries harder if it finds immutable files
80 """
81 tryAgain = 1
82 failedFilename = None
83 while tryAgain:
84 tryAgain = 0
85 try:
86 shutil.rmtree(path, *args, **kargs)
87 except OSError, e:
88 if e.errno == 2: # no such file or directory
89 pass
90 elif e.errno==1 or e.errno==13:
91 tryAgain = 1
92 if failedFilename == e.filename:
93 raise
94 failedFilename = e.filename
95 os.system("chattr -R -i %s" % path)
96 else:
97 raise
0a9a2371
MT
98
99def ioctl_GWINSZ(fd):
100 try:
101 cr = struct.unpack("hh", fcntl.ioctl(fd, termios.TIOCGWINSZ, "1234"))
102 except:
103 return None
104
105 return cr
106
107def terminal_size():
108 cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
109
110 if not cr:
111 try:
112 fd = os.open(os.ctermid(), os.O_RDONLY)
113 cr = ioctl_GWINSZ(fd)
114 os.close(fd)
115 except:
116 pass
117
118 if not cr:
119 try:
120 cr = (os.environ['LINES'], os.environ['COLUMNS'])
121 except:
122 cr = (25, 80)
123
124 return int(cr[1]), int(cr[0])