forked from charleso/git-cc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.py
168 lines (143 loc) · 4.63 KB
/
common.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
from distutils import __version__
v30 = __version__.find("3.") == 0
from subprocess import Popen, PIPE
import os, sys
from os.path import join, exists, abspath, dirname
if v30:
from configparser import SafeConfigParser
else:
from ConfigParser import SafeConfigParser
IS_CYGWIN = sys.platform == 'cygwin'
if IS_CYGWIN:
FS = '\\'
else:
FS = os.sep
CFG_CC = 'clearcase'
CC_DIR = None
ENCODING = None
if hasattr(sys.stdin, 'encoding'):
ENCODING = sys.stdin.encoding
if ENCODING is None:
import locale
locale_name, ENCODING = locale.getdefaultlocale()
if ENCODING is None:
ENCODING = "ISO8859-1"
DEBUG = False
def fail(string):
print(string)
sys.exit(2)
def doStash(f, stash):
if(stash):
git_exec(['stash'])
f()
if(stash):
git_exec(['stash', 'pop'])
def debug(string):
if DEBUG:
print(string)
def git_exec(cmd, **args):
return popen('git', cmd, GIT_DIR, encoding='UTF-8', **args)
def cc_exec(cmd, **args):
return popen('cleartool', cmd, CC_DIR, **args)
def popen(exe, cmd, cwd, env=None, decode=True, errors=True, encoding=None):
cmd.insert(0, exe)
if DEBUG:
f = lambda a: a if not a.count(' ') else '"%s"' % a
debug('> ' + ' '.join(map(f, cmd)))
pipe = Popen(cmd, cwd=cwd, stdout=PIPE, stderr=PIPE, env=env)
(stdout, stderr) = pipe.communicate()
if encoding == None:
encoding = ENCODING
if errors and pipe.returncode > 0:
raise Exception(decodeString(encoding, stderr + stdout))
return stdout if not decode else decodeString(encoding, stdout)
def decodeString(encoding, encodestr):
try:
return encodestr.decode(encoding)
except UnicodeDecodeError as e:
print >> sys.stderr, encodestr, ":", e
return encodestr.decode(encoding, "ignore")
def tag(tag, id="HEAD"):
git_exec(['tag', '-f', tag, id])
def reset(tag=None):
git_exec(['reset', '--hard', tag or CC_TAG])
def getBlob(sha, file):
return git_exec(['ls-tree', '-z', sha, file]).split(' ')[2].split('\t')[0]
def gitDir():
def findGitDir(dir):
if not exists(dir) or dirname(dir) == dir:
return '.'
if exists(join(dir, '.git')):
return dir
return findGitDir(dirname(dir))
return findGitDir(abspath('.'))
def getCurrentBranch():
for branch in git_exec(['branch']).split('\n'):
if branch.startswith('*'):
branch = branch[2:]
if branch == '(no branch)':
fail("Why aren't you on a branch?")
return branch
return ""
class GitConfigParser():
CORE = 'core'
def __init__(self, branch):
self.section = branch
self.file = join(GIT_DIR, '.git', 'gitcc')
self.parser = SafeConfigParser();
self.parser.add_section(self.section)
def set(self, name, value):
self.parser.set(self.section, name, value)
def read(self):
self.parser.read(self.file)
def write(self):
self.parser.write(open(self.file, 'w'))
def getCore(self, name, *args):
return self._get(self.CORE, name, *args)
def get(self, name, *args):
return self._get(self.section, name, *args)
def _get(self, section, name, default=None):
if not self.parser.has_option(section, name):
return default
return self.parser.get(section, name)
def getList(self, name, default=None):
return self.get(name, default).split('|')
def getInclude(self):
return self.getCore('include', '.').split('|')
def getExclude(self):
return self.getCore('exclude', '.').split('|')
def getBranches(self):
return self.getList('branches', 'main')
def getExtraBranches(self):
return self.getList('_branches', 'main')
def write(file, blob):
_write(file, blob)
def _write(file, blob):
f = open(file, 'wb')
f.write(blob)
f.close()
def mkdirs(file):
dir = dirname(file)
if not exists(dir):
os.makedirs(dir)
def removeFile(file):
if exists(file):
os.remove(file)
def validateCC():
if not CC_DIR:
fail("No 'clearcase' variable found for branch '%s'" % CURRENT_BRANCH)
def path(path, args='-m'):
if IS_CYGWIN:
return os.popen('cygpath %s "%s"' %(args, path)).readlines()[0].strip()
else:
return path
GIT_DIR = path(gitDir())
if not exists(join(GIT_DIR, '.git')):
fail("fatal: Not a git repository (or any of the parent directories): .git")
CURRENT_BRANCH = getCurrentBranch() or 'master'
cfg = GitConfigParser(CURRENT_BRANCH)
cfg.read()
CC_DIR = path(cfg.get(CFG_CC))
DEBUG = cfg.getCore('debug', True)
CC_TAG = CURRENT_BRANCH + '_cc'
CI_TAG = CURRENT_BRANCH + '_ci'