~rafalcieslak256/ubuntu-accomplishments-daemon/970273

« back to all changes in this revision

Viewing changes to accomplishments/util/__init__.py

  • Committer: Jono Bacon
  • Date: 2012-04-12 00:20:10 UTC
  • Revision ID: jono@ubuntu.com-20120412002010-pnskd8wtsnpnqfe7
Fixing packaging issues.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
import logging
 
2
import optparse
 
3
import os
 
4
 
 
5
import gettext
 
6
from gettext import gettext as _
 
7
 
 
8
from twisted.internet import defer
 
9
from twisted.internet import protocol
 
10
from twisted.internet import reactor
 
11
from twisted.python import log
 
12
 
 
13
import accomplishments
 
14
from accomplishments import config
 
15
from accomplishments import exceptions
 
16
 
 
17
 
 
18
gettext.textdomain('accomplishments-daemon')
 
19
 
 
20
 
 
21
def get_version():
 
22
    return config.__version__
 
23
 
 
24
 
 
25
class NullHandler(logging.Handler):
 
26
    """
 
27
    """
 
28
    def emit(self, record):
 
29
        pass
 
30
 
 
31
 
 
32
def set_up_logging(opts):
 
33
    # add a handler to prevent basicConfig
 
34
    root = logging.getLogger()
 
35
    null_handler = NullHandler()
 
36
    root.addHandler(null_handler)
 
37
 
 
38
    formatter = logging.Formatter(
 
39
        "%(levelname)s:%(name)s: %(funcName)s() '%(message)s'")
 
40
 
 
41
    logger = logging.getLogger('accomplishments-daemon')
 
42
    logger_sh = logging.StreamHandler()
 
43
    logger_sh.setFormatter(formatter)
 
44
    logger.addHandler(logger_sh)
 
45
 
 
46
    # Set the logging level to show debug messages.
 
47
    if opts.verbose:
 
48
        logger.setLevel(logging.DEBUG)
 
49
        logger.debug('logging enabled')
 
50
    if opts.verbose > 1:
 
51
        logger.setLevel(logging.DEBUG)
 
52
 
 
53
 
 
54
def get_data_path():
 
55
    """Retrieve accomplishments-daemon data path
 
56
 
 
57
    This path is by default <accomplishments_daemon_lib_path>/../data/ in trunk
 
58
    and /usr/share/ubuntu-accomplishments-daemon in an installed version but this path
 
59
    is specified at installation time.
 
60
    """
 
61
 
 
62
    # Get pathname absolute or relative.
 
63
    path = os.path.join(
 
64
        os.path.dirname(accomplishments.__path__[0]),
 
65
        config.__ubuntu_accomplishments_daemon_data_directory__)
 
66
    abs_data_path = os.path.abspath(path)
 
67
    if not os.path.exists(abs_data_path):
 
68
        msg = "Could not find the project data directory."
 
69
        raise exceptions.PathNotFound(msg)
 
70
    return abs_data_path
 
71
 
 
72
 
 
73
def get_data_file(*path_segments):
 
74
    """Get the full path to a data file.
 
75
 
 
76
    Returns the path to a file underneath the data directory (as defined by
 
77
    `get_data_path`). Equivalent to os.path.join(get_data_path(),
 
78
    *path_segments).
 
79
    """
 
80
    return os.path.join(get_data_path(), *path_segments)
 
81
 
 
82
 
 
83
def parse_options():
 
84
    """Support for command line options"""
 
85
    parser = optparse.OptionParser(version="%%prog %s" % get_version())
 
86
    parser.add_option(
 
87
        "-v", "--verbose", action="count", dest="verbose",
 
88
        help=_("Show debug messages (-vv debugs accomplishments_daemon_lib also)"))
 
89
    parser.add_option(
 
90
        "-c", "--clear-trophies", action="count", dest="clear",
 
91
        help=_("Clear your trophies collection"))
 
92
    (options, args) = parser.parse_args()
 
93
    return options
 
94
 
 
95
 
 
96
class SubprocessReturnCodeProtocol(protocol.ProcessProtocol):
 
97
    """
 
98
    """
 
99
    def __init__(self, command=""):
 
100
        self.command = command
 
101
 
 
102
    def connectionMade(self):
 
103
        self.returnCodeDeferred = defer.Deferred()
 
104
 
 
105
    def processEnded(self, reason):
 
106
        self.returnCodeDeferred.callback(reason.value.exitCode)
 
107
 
 
108
    def outReceived(self, data):
 
109
        log.msg("Got process results: %s" % data)
 
110
 
 
111
    def errReceived(self, data):
 
112
        log.err("Got non-zero exit code for process: %s" % (
 
113
            " ".join(self.command),))
 
114
        log.msg(data)
 
115
 
 
116
 
 
117
def import_gpg_key(pub_key):
 
118
    """
 
119
    """
 
120
    cmd = ["gpg", "--import", pub_key]
 
121
    gpg = SubprocessReturnCodeProtocol(cmd)
 
122
    gpg.deferred = defer.Deferred()
 
123
    process = reactor.spawnProcess(gpg, cmd[0], cmd, env=None)
 
124
    return gpg.deferred