github.com/shashidharatd/test-infra@v0.0.0-20171006011030-71304e1ca560/queue_health/weekly_commit_stats.py (about) 1 # Copyright 2016 The Kubernetes Authors. 2 # 3 # Licensed under the Apache License, Version 2.0 (the "License"); 4 # you may not use this file except in compliance with the License. 5 # You may obtain a copy of the License at 6 # 7 # http://www.apache.org/licenses/LICENSE-2.0 8 # 9 # Unless required by applicable law or agreed to in writing, software 10 # distributed under the License is distributed on an "AS IS" BASIS, 11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 # See the License for the specific language governing permissions and 13 # limitations under the License. 14 15 """Lists weekly commits for a github org.""" 16 17 import collections 18 import datetime 19 import json 20 import sys 21 22 23 import requests # pip install requests 24 25 26 SESSION = requests.Session() 27 28 if len(sys.argv) != 3: 29 print >>sys.stderr, 'Usage: %s <path/to/token> <org>' % sys.argv[0] 30 print >>sys.stderr, ' Info at https://github.com/settings/tokens' 31 sys.exit(1) 32 33 TOKEN = open(sys.argv[1]).read().strip() 34 35 36 def get(path): 37 """Get the specified github api using TOKEN.""" 38 return SESSION.get( 39 'https://api.github.com/%s' % path, 40 headers={'Authorization': 'token %s' % TOKEN}) 41 42 43 def github_repos(org): 44 """List repos for the org.""" 45 print >>sys.stderr, 'Repos', org 46 resp = get('orgs/%s/repos' % org) 47 resp.raise_for_status() 48 return json.loads(resp.content) 49 50 51 def github_commits(owner, repo): 52 """List weekly commits for the repo.""" 53 print >>sys.stderr, 'Commits', owner, repo 54 resp = get('repos/%s/%s/stats/commit_activity' % (owner, repo)) 55 resp.raise_for_status() 56 return json.loads(resp.content) 57 58 def org_commits(org): 59 """Combine weekly commits for all repos in the org.""" 60 repos = [(r['owner']['login'], r['name']) for r in github_repos(org)] 61 commits = {r: github_commits(*r) for r in repos} 62 weekly_commits = collections.defaultdict(int) 63 for weeks in commits.values(): 64 for week in weeks: 65 date = datetime.datetime.fromtimestamp(week['week']) 66 weekly_commits[date] += week['total'] 67 print 'Week,commits' 68 for week, total in sorted(weekly_commits.items()): 69 print '%s,%d' % (week.strftime('%Y-%m-%d'), total) 70 71 org_commits(sys.argv[2])