import random
import subprocess
import os
import json
import uuid
import tarfile
randomStr = lambda num: "".join(random.sample('zyxwvutsrqponmlkjihgfedcba',num))
def return_msg(error, msg):
return_data = {
"uuid": str(uuid.uuid1()),
"error": error,
"message": msg
}
print(return_data)
return return_data
def installGit():
targetDir = "/tmp/git"
dir_path = os.path.dirname(os.path.realpath(__file__))
tar = tarfile.open(os.path.join(dir_path, 'git-2.14.0.tar'))
tar.extractall(targetDir)
git_path = os.path.join(targetDir, 'git')
bin_path = os.path.join(git_path, 'bin')
template_dir = os.path.join(
git_path,
'share',
'git-core',
'templates'
)
exec_path = os.path.join(
git_path,
'libexec',
'git-core'
)
os.environ['PATH'] = bin_path + ':' + os.environ['PATH']
os.environ['GIT_TEMPLATE_DIR'] = template_dir
os.environ['GIT_EXEC_PATH'] = exec_path
installGit()
def doPopen(gitStr, path):
child = subprocess.Popen("cd %s && %s" % (path, gitStr), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return child.stdout.read().decode("utf-8")
def main_handler(event, context):
try:
path = "/tmp/%s" % (randomStr(5))
print("git clone %s %s" % (json.loads(event["body"])["url"], path))
child = subprocess.Popen("git clone %s %s" % (json.loads(event["body"])["url"], path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(child.stdout.read().decode("utf-8"))
users = {}
for eveCommit in doPopen("git log --format='%aN'", path).split("\n"):
if eveCommit:
if eveCommit not in users:
users[eveCommit] = {"commits": 1,
"added_lines": 0,
"removed_lines": 0,
"total_lines": 0}
for eveItem in doPopen('git log --author="%s" --pretty=tformat: --numstat'%eveCommit, path).split("\n"):
if eveItem:
eveItemList = eveItem.split("\t")
users[eveCommit]["added_lines"] = users[eveCommit]["added_lines"] + int(eveItemList[0])
users[eveCommit]["removed_lines"] = users[eveCommit]["removed_lines"] + int(eveItemList[1])
users[eveCommit]["total_lines"] = users[eveCommit]["added_lines"] - users[eveCommit]["removed_lines"]
else:
users[eveCommit]['commits'] = users[eveCommit]['commits'] + 1
return return_msg(False, users)
except Exception as e:
return return_msg(True, e)
评论 (2 条评论)