Upstream version 8.36.161.0
[platform/framework/web/crosswalk.git] / src / third_party / chromite / lib / tracker_access.py
1 #!/usr/bin/python
2 # Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
3 # Use of this source code is governed by a BSD-style license that can be
4 # found in the LICENSE file.
5
6 """Helper functions for accessing the issue tracker in a pythonic way."""
7
8 import pprint
9 import sys
10
11 # pylint: disable=F0401
12 import gdata.client
13 import gdata.projecthosting.client
14 # pylint: enable=F0401
15
16
17 DEFAULT_TRACKER_SOURCE = "chromite-tracker-access-1.0"
18 VERBOSE = True  # Set to True to get extra debug info...
19
20
21 class TrackerAccess(object):
22   """Class for accessing the tracker on code.google.com."""
23
24   def __init__(self, email="", password="",
25                tracker_source=DEFAULT_TRACKER_SOURCE):
26     """TrackerAccess constructor.
27
28     Args:
29       email: The email address to Login with; may be "" for anonymous access.
30       password: The password that goes with the email address; may be "" if
31                 the email is "".
32       tracker_source: A string describing this program.  This can be anything
33                       you like but should should give some indication of which
34                       app is making the request.
35     """
36     # Save parameters...
37     self._email = email
38     self._password = password
39     self._tracker_source = tracker_source
40
41     # This will be initted on first login...
42     self._tracker_client = None
43
44   def Login(self):
45     """Login, if needed.  This may be safely called more than once.
46
47     Commands will call this function as their first line, so the client
48     of this class need not call it themselves unless trying to debug login
49     problems.
50
51     This function should be called even if we're accessing anonymously.
52     """
53     # Bail immediately if we've already logged in...
54     if self._tracker_client is not None:
55       return
56
57     self._tracker_client = gdata.projecthosting.client.ProjectHostingClient()
58     if self._email and self._password:
59       self._tracker_client.client_login(self._email, self._password,
60                                         source=self._tracker_source,
61                                         service="code", account_type='GOOGLE')
62
63   def GetKeyedLabels(self, project_name, issue_id):
64     """Get labels of the form "Key-Value" attached to the given issue.
65
66     Any labels that don't have a dash in them are ignored.
67
68     Args:
69       project_name: The tracker project to query.
70       issue_id: The ID of the issue to query; should be an int but a string
71           will probably work too.
72
73     Returns:
74       A dictionary mapping key/value pairs from the issue's labels, like:
75
76       {'Area': 'Build',
77        'Iteration': '15',
78        'Mstone': 'R9.x',
79        'Pri': '1',
80        'Type': 'Bug'}
81     """
82     # Login if needed...
83     self.Login()
84
85     # Construct the query...
86     query = gdata.projecthosting.client.Query(issue_id=issue_id)
87     try:
88       feed = self._tracker_client.get_issues(project_name, query=query)
89     except gdata.client.RequestError as e:
90       if VERBOSE:
91         print >> sys.stderr, "ERROR: Unable to access bug %s:%s: %s" % (
92             project_name, issue_id, str(e))
93       return {}
94
95     # There should be exactly one result...
96     assert len(feed.entry) == 1, "Expected exactly 1 result"
97     (entry,) = feed.entry
98
99     # We only care about labels that look like: Key-Value
100     # We'll return a dictionary of those.
101     keyed_labels = {}
102     for label in entry.label:
103       if "-" in label.text:
104         label_key, label_val = label.text.split("-", 1)
105         keyed_labels[label_key] = label_val
106
107     return keyed_labels
108
109
110 def _TestGetKeyedLabels(project_name, email, passwordFile, *args):
111   """Test code for GetKeyedLabels().
112
113   Args:
114     project_name: The name of the project we're looking at.
115     email: The email address to use to login.  May be ""
116     passwordFile: A file containing the password for the email address.
117                   May be "" if email is "" for anon access.
118     args: A list of bug IDs to query.
119   """
120   bug_ids = args
121   # If password was specified as a file, read it.
122   if passwordFile:
123     password = open(passwordFile, "r").read().strip()
124   else:
125     password = ""
126
127   ta = TrackerAccess(email, password)
128
129   if not bug_ids:
130     print "No bugs were specified"
131   else:
132     for bug_id in bug_ids:
133       print bug_id, ta.GetKeyedLabels(project_name, int(bug_id))
134
135
136 def _DoHelp(commands, *args):
137   """Print help for the script."""
138
139   if len(args) >= 2 and args[0] == "help" and args[1] in commands:
140     # If called with arguments 'help' and 'command', show that commands's doc.
141     command_name = args[1]
142     print commands[command_name].__doc__
143   else:
144     # Something else: show generic help...
145     print (
146         "Usage %s <command> <command args>\n"
147         "\n"
148         "Known commands: \n"
149         "  %s\n"
150     ) % (sys.argv[0], pprint.pformat(["help"] + sorted(commands)))
151
152
153 def main():
154   """Main function of the script."""
155
156   commands = {
157       "TestGetKeyedLabels": _TestGetKeyedLabels,
158   }
159
160   if len(sys.argv) <= 1 or sys.argv[1] not in commands:
161     # Argument 1 isn't in list of commands; show help and pass all arguments...
162     _DoHelp(commands, *sys.argv[1:])
163   else:
164     command_name = sys.argv[1]
165     commands[command_name](*sys.argv[2:])
166
167 if __name__ == "__main__":
168   main()