gittools.py 4.43 KB
Newer Older
1
# -*- coding: utf-8 -*-
Marco Mariani's avatar
Marco Mariani committed
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):
Alain Takoudjou's avatar
Alain Takoudjou committed
15 16
  """Clonne a repository
  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 20 21 22 23
      data['path'] is the path of the new project
      data['repo'] is the url of the repository to be cloned
      data['email'] is the user email
      data['user'] is the name of the user
  Returns:
    a jsonify data"""
24
  workDir = data['path']
25 26 27
  if not workDir:
    return jsonify(code=0,
                   result="Can not create project folder: Permission Denied")
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
Marco Mariani's avatar
Marco Mariani committed
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 49 50 51
  """Run git status and return status of specified project folder
  Args:
    project: path of the projet ti get status
  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
Marco Mariani's avatar
Marco Mariani committed
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
Marco Mariani's avatar
Marco Mariani committed
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
Marco Mariani's avatar
Marco Mariani committed
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)
Marco Mariani's avatar
Marco Mariani committed
120
  except Exception as e:
121
    result = safeResult(str(e))
122 123
  return result

Marco Mariani's avatar
Marco Mariani committed
124

125
def gitPush(project, msg):
Alain Takoudjou's avatar
Alain Takoudjou committed
126 127 128 129
  """Commit and Push changes for the specified repository
  Args:
    project: directory of the local repository
    msg: commit message"""
130 131
  code = 0
  json = ""
132
  undo_commit = False
133 134 135 136
  try:
    repo = Repo(project)
    if repo.is_dirty:
      git = repo.git
137
      current_branch = repo.active_branch.name
138 139 140 141 142 143
      #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)
144
      undo_commit = True
145 146 147 148 149 150
      #push changes to repo
      git.push('origin', current_branch)
      code = 1
    else:
      json = "Nothing to be commited"
      code = 1
Marco Mariani's avatar
Marco Mariani committed
151
  except Exception as e:
152
    if undo_commit:
Marco Mariani's avatar
Marco Mariani committed
153
      git.reset("HEAD~")  # undo previous commit
154
    json = safeResult(str(e))
155 156
  return jsonify(code=code, result=json)

Marco Mariani's avatar
Marco Mariani committed
157

158 159 160 161 162 163 164 165
def gitPull(project):
  result = ""
  code = 0
  try:
    repo = Repo(project)
    git = repo.git
    git.pull()
    code = 1
Marco Mariani's avatar
Marco Mariani committed
166
  except Exception as e:
167 168 169
    result = safeResult(str(e))
  return jsonify(code=code, result=result)

Marco Mariani's avatar
Marco Mariani committed
170

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