gittools.py 4.47 KB
Newer Older
1
# -*- coding: utf-8 -*-
2
# vim: set et sts=2:
Marco Mariani's avatar
Marco Mariani committed
3 4
# pylint: disable-msg=W0311,C0301,C0103,C0111

5

6 7 8
import os
import re
import shutil
Marco Mariani's avatar
Marco Mariani committed
9

Marco Mariani's avatar
Marco Mariani committed
10
from git import Repo
Marco Mariani's avatar
Marco Mariani committed
11 12
from flask import jsonify

13

14
def cloneRepo(data):
Marco Mariani's avatar
Marco Mariani committed
15
  """Clone a repository
Alain Takoudjou's avatar
Alain Takoudjou committed
16
  Args:
Marco Mariani's avatar
Marco Mariani committed
17
    data: a dictionary of parameters to use:
Alain Takoudjou's avatar
Alain Takoudjou committed
18 19
      data['path'] is the path of the new project
      data['repo'] is the url of the repository to be cloned
Marco Mariani's avatar
Marco Mariani committed
20
      data['email'] is the user's email
Alain Takoudjou's avatar
Alain Takoudjou committed
21 22 23
      data['user'] is the name of the user
  Returns:
    a jsonify data"""
24
  workDir = data['path']
25 26
  if not workDir:
    return jsonify(code=0,
27
                   result="Can not create project folder.")
28 29 30 31
  code = 0
  json = ""
  try:
    if os.path.exists(workDir) and len(os.listdir(workDir)) < 2:
Marco Mariani's avatar
Marco Mariani committed
32
      shutil.rmtree(workDir)  # delete useless files
33 34 35
    repo = Repo.clone_from(data["repo"], workDir)
    config_writer = repo.config_writer()
    config_writer.add_section("user")
36
    if data["user"] != "":
37
      config_writer.set_value("user", "name", data["user"].encode("utf-8"))
38 39
    if data["email"] != "":
      config_writer.set_value("user", "email", data["email"])
40
    code = 1
41
  except Exception as e:
42
    json = safeResult(str(e))
43 44
  return jsonify(code=code, result=json)

Marco Mariani's avatar
Marco Mariani committed
45

46
def gitStatus(project):
Alain Takoudjou's avatar
Alain Takoudjou committed
47 48
  """Run git status and return status of specified project folder
  Args:
Marco Mariani's avatar
Marco Mariani committed
49
    project: path of the projet to get status
Alain Takoudjou's avatar
Alain Takoudjou committed
50 51
  Returns:
    a parsed string that contains the result of git status"""
52 53 54 55 56
  code = 0
  json = ""
  try:
    repo = Repo(project)
    git = repo.git
57
    json = git.status().replace('#', '')
58 59 60
    branch = git.branch().replace(' ', '').split('\n')
    isdirty = repo.is_dirty(untracked_files=True)
    code = 1
61
  except Exception as e:
62
    json = safeResult(str(e))
63 64
  return jsonify(code=code, result=json, branch=branch, dirty=isdirty)

Marco Mariani's avatar
Marco Mariani committed
65

66
def switchBranch(project, name):
Alain Takoudjou's avatar
Alain Takoudjou committed
67 68 69 70 71 72
  """Switch a git branch
  Args:
    project: directory of the local git repository
    name: switch from current branch to `name` branch
  Returns:
    a jsonify data"""
73
  code = 0
74
  json = ""
75 76 77 78 79 80
  try:
    repo = Repo(project)
    current_branch = repo.active_branch.name
    if name == current_branch:
      json = "This is already your active branch for this project"
    else:
Marco Mariani's avatar
Marco Mariani committed
81
      git = repo.git
82
      git.checkout(name)
83
      code = 1
84
  except Exception as e:
85
    json = safeResult(str(e))
86 87
  return jsonify(code=code, result=json)

Marco Mariani's avatar
Marco Mariani committed
88

89
def addBranch(project, name, onlyCheckout=False):
Alain Takoudjou's avatar
Alain Takoudjou committed
90 91 92 93 94 95 96
  """Add new git branch to the repository
  Args:
    project: directory of the local git repository
    name: name of the new branch
    onlyCheckout: if True then the branch `name` is created before checkout
  Returns:
    a jsonify data"""
97 98 99 100
  code = 0
  json = ""
  try:
    repo = Repo(project)
Marco Mariani's avatar
Marco Mariani committed
101
    git = repo.git
102 103 104 105
    if not onlyCheckout:
      git.checkout('-b', name)
    else:
      git.checkout(name)
106
    code = 1
107
  except Exception as e:
108
    json = safeResult(str(e))
109 110
  return jsonify(code=code, result=json)

Marco Mariani's avatar
Marco Mariani committed
111

112
def getDiff(project):
Alain Takoudjou's avatar
Alain Takoudjou committed
113
  """Get git diff for the specified project directory"""
114 115 116 117 118 119
  result = ""
  try:
    repo = Repo(project)
    git = repo.git
    current_branch = repo.active_branch.name
    result = git.diff(current_branch)
120
  except Exception as e:
121
    result = safeResult(str(e))
122 123
  return result

124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
def gitCommit(project, msg):
  """Commit changes for the specified repository
  Args:
    project: directory of the local repository
    msg: commit message"""
  code = 0
  json = ""
  repo = Repo(project)
  if repo.is_dirty:
    git = repo.git
    #add file to be commited
    files = repo.untracked_files
    for f in files:
      git.add(f)
    #Commit all modified and untracked files
    git.commit('-a', '-m', msg)
  else:
    code = 1
    json = "Nothing to be commited"
  return jsonify(code=code, result=json)
Marco Mariani's avatar
Marco Mariani committed
144

145 146
def gitPush(project):
  """Push changes for the specified repository
Alain Takoudjou's avatar
Alain Takoudjou committed
147 148 149
  Args:
    project: directory of the local repository
    msg: commit message"""
150 151 152
  code = 0
  json = ""
  try:
153 154 155 156
    #push changes to repo
    current_branch = repo.active_branch.name
    git.push('origin', current_branch)
    code = 1
157
  except Exception as e:
158
    json = safeResult(str(e))
159 160
  return jsonify(code=code, result=json)

Marco Mariani's avatar
Marco Mariani committed
161

162 163 164 165 166 167 168 169
def gitPull(project):
  result = ""
  code = 0
  try:
    repo = Repo(project)
    git = repo.git
    git.pull()
    code = 1
170
  except Exception as e:
171 172 173
    result = safeResult(str(e))
  return jsonify(code=code, result=result)

Marco Mariani's avatar
Marco Mariani committed
174

175
def safeResult(result):
Alain Takoudjou's avatar
Alain Takoudjou committed
176
  """Parse string and remove credential of the user"""
Marco Mariani's avatar
Marco Mariani committed
177
  regex = re.compile("(https:\/\/)([\w\d\._-]+:[\w\d\._-]+)\@([\S]+\s)", re.VERBOSE)
178
  return regex.sub(r'\1\3', result)