Browse Source

Basic stuff.

squeeze-backports
Bernd Zeimetz 8 years ago
commit
f63b1fa58a
2 changed files with 455 additions and 0 deletions
  1. +4
    -0
      .gitignore
  2. +451
    -0
      monkeystore.py

+ 4
- 0
.gitignore View File

@@ -0,0 +1,4 @@
*.pyc
*.shelve
*.shelve.lock
.*.swp

+ 451
- 0
monkeystore.py View File

@@ -0,0 +1,451 @@
#!/usr/bin/python
# Monkeystore client
#
# Copyright (c) 2012 Bernd Zeimetz <b.zeimetz@conova.com>
#
# Parts taken from reportbug:
#
# Written by Chris Lawrence <lawrencc@debian.org>
# (C) 2001-08 Chris Lawrence
# Copyright (C) 2008-2012 Sandro Tosi <morph@debian.org>
#
# This program is freely distributable per the following license:
#
## Permission to use, copy, modify, and distribute this software and its
## documentation for any purpose and without fee is hereby granted,
## provided that the above copyright notice appears in all copies and that
## both that copyright notice and this permission notice appear in
## supporting documentation.
##
## I DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
## IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL I
## BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
## DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
## WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
## ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
## SOFTWARE.

import sys
import os
import commands
import re
import math
import string
import errno
import glob
import getpass
import textwrap
import locale
try:
import readline
except ImportError:
readline = None

ISATTY = sys.stdin.isatty()
charset = 'us-ascii'

try:
r, c = commands.getoutput('stty size').split()
rows, columns = int(r) or 24, int(c) or 79
except:
rows, columns = 24, 79

def ewrite(message, *args):
if not ISATTY:
return

if args:
message = message % args

if isinstance(message, unicode):
message = message.encode(charset, 'replace')

sys.stderr.write(message)
sys.stderr.flush()

log_message = ewrite
display_failure = ewrite

def system(cmdline):
try:
x = os.getcwd()
except OSError:
os.chdir('/')
return os.system(cmdline)

def indent_wrap_text(text, starttext='', indent=0, linelen=None):
"""Wrapper for textwrap.fill to the existing API."""
if not linelen:
linelen = columns-1

if indent:
si = ' '*indent
else:
si = ''

text = ' '.join(text.split())
if not text:
return starttext+'\n'

output = textwrap.fill(text, width=linelen, initial_indent=starttext,
subsequent_indent=si)
if output.endswith('\n'):
return output
return output + '\n'

# Readline support, if available
if readline is not None:
readline.parse_and_bind("tab: complete")
try:
# minimize the word delimeter list if possible
readline.set_completer_delims(' ')
except:
pass


class our_completer(object):
def __init__(self, completions=None):
self.completions = None
if completions:
self.completions = tuple(map(str, completions))

def complete(self, text, i):
if not self.completions: return None

matching = [x for x in self.completions if x.startswith(text)]
if i < len(matching):
return matching[i]
else:
return None

def our_raw_input(prompt = None, completions=None, completer=None):
istty = sys.stdout.isatty()
if not istty:
sys.stderr.write(prompt)
sys.stderr.flush()
if readline:
if completions and not completer:
completer = our_completer(completions).complete
if completer:
readline.set_completer(completer)

try:
if istty:
ret = raw_input(prompt)
else:
ret = raw_input()
except EOFError:
ewrite('\nUser interrupt (^D).\n')
raise SystemExit

if readline:
readline.set_completer(None)
return ret.strip()

def select_options(msg, ok, help, allow_numbers=None, nowrap=False):
err_message = ''
for option in ok:
if option in string.ascii_uppercase:
default=option
break

if not help: help = {}

if '?' not in ok: ok = ok+'?'

if nowrap:
longmsg = msg+' ['+'|'.join(ok)+']?'+' '
else:
longmsg = indent_wrap_text(msg+' ['+'|'.join(ok)+']?').strip()+' '
ch = our_raw_input(longmsg, allow_numbers)
# Allow entry of a bug number here
if allow_numbers:
while ch and ch[0] == '#': ch = ch[1:]
if type(allow_numbers) == type(1):
try:
return str(int(ch))
except ValueError:
pass
else:
try:
number = int(ch)
if number in allow_numbers:
return str(number)
else:
nums = list(allow_numbers)
nums.sort()
err_message = 'Only the following entries are allowed: '+\
', '.join(map(str, nums))
except (ValueError, TypeError):
pass

if not ch: ch = default
ch = ch[0]
if ch=='?':
help['?'] = 'Display this help.'
for ch in ok:
if ch in string.ascii_uppercase:
desc = '(default) '
else:
desc = ''
desc += help.get(ch, help.get(ch.lower(),
'No help for this option.'))
ewrite(indent_wrap_text(desc+'\n', '%s - '% ch, 4))
return select_options(msg, ok, help, allow_numbers, nowrap)
elif (ch.lower() in ok) or (ch.upper() in ok):
return ch.lower()
elif err_message:
ewrite(indent_wrap_text(err_message))
else:
ewrite('Invalid selection.\n')

return select_options(msg, ok, help, allow_numbers, nowrap)

def yes_no(msg, yeshelp, nohelp, default=True, nowrap=False):
"Return True for yes, False for no."
if default:
ok = 'Ynq'
else:
ok = 'yNq'

res = select_options(msg, ok, {'y': yeshelp, 'n': nohelp, 'q' : 'Quit.'},
nowrap=nowrap)
if res == 'q':
raise SystemExit
return (res == 'y')

def long_message(text, *args):
if args:
ewrite(indent_wrap_text(text % args))
else:
ewrite(indent_wrap_text(text))

final_message = long_message

def get_string(prompt, options=None, title=None, empty_ok=False, force_prompt=False,
default='', completer=None):
if prompt and (len(prompt) < 2*columns/3) and not force_prompt:
if default:
prompt = '%s [%s]: ' % (prompt, default)
response = our_raw_input(prompt, options, completer) or default
else:
response = our_raw_input(prompt, options, completer)
else:
if prompt:
ewrite(indent_wrap_text(prompt))
if default:
response = our_raw_input('[%s]> ' % default, options, completer) or default
else:
response = our_raw_input('> ', options, completer)

# Translate the response into a Unicode string
if response is not None and not isinstance(response, unicode):
response = unicode(response, charset, 'replace')

return response

def get_multiline(prompt):
ewrite('\n')
ewrite(indent_wrap_text(prompt + " Press ENTER on a blank line to continue.\n"))
l = []
while 1:
entry = get_string('', force_prompt=True).strip()
if not entry:
break
l.append(entry)
ewrite('\n')
return l

def get_password(prompt=None):
return getpass.getpass(prompt)

def FilenameCompleter(text, i):
text = os.path.expanduser(text)
text = os.path.expandvars(text)
paths = glob.glob(text+'*')
if not paths: return None

if i < len(paths):
entry = paths[i]
if os.path.isdir(entry):
return entry+'/'
return entry
else:
return None

def get_filename(prompt, title=None, force_prompt=False, default=''):
return get_string(prompt, title=title, force_prompt=force_prompt,
default=default, completer=FilenameCompleter)

def select_multiple(par, options, prompt, title=None, order=None, extras=None):
return menu(par, options, prompt, title=title, order=order, extras=extras,
multiple=True, empty_ok=False)

def menu(par, options, prompt, default=None, title=None, any_ok=False,
order=None, extras=None, multiple=False, empty_ok=False):
selected = {}

if not extras:
extras = []
else:
extras = list(extras)

if title:
ewrite(title+'\n\n')

ewrite(indent_wrap_text(par, linelen=columns)+'\n')

if isinstance(options, dict):
options = options.copy()
# Convert to a list
if order:
olist = []
for key in order:
if options.has_key(key):
olist.append( (key, options[key]) )
del options[key]

# Append anything out of order
options = options.items()
options.sort()
for option in options:
olist.append( option )
options = olist
else:
options = options.items()
options.sort()

if multiple:
options.append( ('none', '') )
default = 'none'
extras += ['done']

allowed = map(lambda x: x[0], options)
allowed = allowed + extras

maxlen_name = min(max(map(len, allowed)), columns/3)
digits = int(math.ceil(math.log10(len(options)+1)))

i = 1
for name, desc in options:
text = indent_wrap_text(desc, indent=(maxlen_name+digits+3),
starttext=('%*d %-*.*s ' % (
digits, i, maxlen_name, maxlen_name, name)))
ewrite(text)
if len(options) < 5:
ewrite('\n')
i = i+1
if len(options) >= 5:
ewrite('\n')

if multiple:
prompt += '(one at a time) '

while 1:
if default:
aprompt = prompt + '[%s] ' % default
else:
aprompt = prompt

response = our_raw_input(aprompt, allowed)
if not response: response = default

try:
num = int(response)
if 1 <= num <= len(options):
response = options[num-1][0]
except (ValueError, TypeError):
pass

if response in allowed or (response == default and response):
if multiple:
if response == 'done':
return selected.keys()
elif response == 'none':
return []
elif selected.get(response):
del selected[response]
else:
selected[response]=1
ewrite('- selected: %s\n' % ', '.join(selected.keys()))
if len(selected):
default = 'done'
else:
default = 'none'
continue
else:
return response

if any_ok and response:
return response
elif empty_ok and not response:
return

ewrite('Invalid entry.\n')
return



def initialize ():
return True

def can_input():
return sys.stdin.isatty()


import gnupg
gpg=gnupg.GPG()

def __encrypt_data__(data, keys, passphrase=None, symmetric=False):
gpg_data = gpg.encrypt(data, keys, passphrase=passphrase, symmetric=symmetric, always_trust=True)
if not gpg_data.ok:
raise Exception("Failed to encrypt: \n%s" %(gpg_data.stderr,))
return gpg_data.data

def __decrypt_data__(gpg_data, passphrase=None):
data = gpg.decrypt(gpg_data, passphrase=passphrase, always_trust=True)
if not data.ok:
raise Exception("Failed to decrypt: \n%s" %(data.stderr,))
return data.data




def __menu_category__():
categories = {
'l' : 'linux',
'w' : 'windows',
'n' : 'networking'
}
return categories[select_options('Hi! Please choose a category!',
''.join(categories.keys()),
categories)]



if __name__ == '__main__':
if sys.platform.startswith('linux'):
import pwd
user = pwd.getpwuid( os.getuid() )[ 0 ]
else:
import win32api
user = win32api.GetUserName()

# x = select_options('foo', 'abcd',
# {'y': 'YESPLEASE',
# 'n': "Don't submit the bug report; instead, "
# "save it in a temporary file (exits reportbug).",
# 'q': "Save it in a temporary file and quit.",
# 'a': "Attach a file.",
# 'd': "Detach an attachment file.",
# 'i': "Include a text file.",
# 'c': "Change editor and re-edit.",
# 'e': 'Re-edit the bug report.',
# 'l': 'Pipe the message through the pager.',
# 'p': 'print message to stdout.',
# 't': 'Add tags.',
# 's': 'Add a X-Debbugs-CC recipient (a CC but after BTS processing).',
# 'm': "Choose a mailer to edit the report."})

category = __menu_category__()
print category

Loading…
Cancel
Save