forked from ansible/ansible
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgit
executable file
·269 lines (241 loc) · 8.65 KB
/
git
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2012, Michael DeHaan <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
DOCUMENTATION = '''
---
module: git
author: Michael DeHaan
version_added: 0.0.1
short_description: Deploy software (or files) from git checkouts
description:
- Manage git checkouts of repositories to deploy files or software.
options:
repo:
required: true
aliases: [ name ]
description:
- git, ssh, or http protocol address of the git repository.
dest:
required: true
description:
- Absolute path of where the repository should be checked out to.
version:
required: false
default: "HEAD"
description:
- What version of the repository to check out. This can be the
git I(SHA), the literal string I(HEAD), branch name, or a tag name.
remote:
required: false
default: "origin"
description:
- Name of the remote branch.
force:
required: false
default: "yes"
choices: [ yes, no ]
description:
- (New in 0.7) If yes, any modified files in the working
repository will be discarded. Prior to 0.7, this was always
'yes' and could not be disabled.
examples:
- code: "git: repo=git://foosball.example.org/path/to/repo.git dest=/srv/checkout version=release-0.22"
description: Example git checkout from Ansible Playbooks
'''
import re
import tempfile
def get_version(dest):
''' samples the version of the git repo '''
os.chdir(dest)
cmd = "git show --abbrev-commit"
sha = os.popen(cmd).read().split("\n")
sha = sha[0].split()[1]
return sha
def clone(repo, dest):
''' makes a new git repo if it does not already exist '''
try:
os.makedirs(os.path.dirname(dest))
except:
pass
cmd = "git clone %s %s" % (repo, dest)
cmd = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=tempfile.gettempdir())
(out, err) = cmd.communicate()
rc = cmd.returncode
return (rc, out, err)
def has_local_mods(dest):
os.chdir(dest)
cmd = "git status -s"
lines = os.popen(cmd).read().splitlines()
lines = filter(lambda c: re.search('^\\?\\?.*$',c) == None,lines)
return len(lines) > 0
def reset(module,dest,force):
'''
Resets the index and working tree to HEAD.
Discards any changes to tracked files in working
tree since that commit.
'''
os.chdir(dest)
if not force and has_local_mods(dest):
module.fail_json(msg="Local modifications exist in repository (force=no).")
cmd = "git reset --hard HEAD"
cmd = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = cmd.communicate()
rc = cmd.returncode
return (rc, out, err)
def get_branches(module, dest):
os.chdir(dest)
branches = []
cmd = "git branch -a"
cmd = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = cmd.communicate()
if cmd.returncode != 0:
module.fail_json(msg="Could not determine branch data - received %s" % out)
for line in out.split('\n'):
branches.append(line.strip())
return branches
def is_remote_branch(module, dest, remote, branch):
branches = get_branches(module, dest)
rbranch = 'remotes/%s/%s' % (remote, branch)
if rbranch in branches:
return True
else:
return False
def is_local_branch(module, dest, branch):
branches = get_branches(module, dest)
lbranch = '%s' % branch
if lbranch in branches:
return True
elif '* %s' % branch in branches:
return True
else:
return False
def is_current_branch(module, dest, branch):
branches = get_branches(module, dest)
for b in branches:
if b.startswith('* '):
cur_branch = b
if branch == cur_branch or '* %s' % branch == cur_branch:
return True
else:
return True
def is_not_a_branch(module, dest):
branches = get_branches(module, dest)
for b in branches:
if b.startswith('* ') and 'no branch' in b:
return True
return False
def get_head_branch(module, dest, remote):
os.chdir(dest)
head = ''
cmd = "git remote show %s" % remote
cmd = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = cmd.communicate()
if cmd.returncode != 0:
module.fail_json(msg="Could not determine HEAD branch via git remote show")
for line in out.split('\n'):
if 'HEAD branch' in line:
head = line.split()[-1].strip()
return head
def pull(module, repo, dest, version, remote):
''' updates repo from remote sources '''
os.chdir(dest)
branches = get_branches(module, dest)
cur_branch = ''
for b in branches:
if b.startswith('* '):
cur_branch = b
if is_local_branch(module, dest, version) and not is_current_branch(module, dest, version):
(rc, out, err) = switch_version(module, dest, remote, version)
if rc != 0:
module.fail_json(msg=err)
if is_not_a_branch(module, dest):
head_branch = get_head_branch(module, dest, remote)
(rc, out, err) = switch_version(module, dest, remote, head_branch)
if rc != 0:
module.fail_json(msg=err)
cmd = "git pull -u %s" % remote
cmd = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = cmd.communicate()
rc = cmd.returncode
return (rc, out, err)
def switch_version(module, dest, remote, version):
''' once pulled, switch to a particular SHA, tag, or branch '''
os.chdir(dest)
cmd = ''
if version != 'HEAD':
if not is_local_branch(module, dest, version) and is_remote_branch(module, dest, remote, version):
cmd = "git checkout --track -b %s %s/%s" % (version, remote, version)
else:
cmd = "git checkout --force %s" % version
else:
# is there a better way to do this?
cmd = "git rebase %s" % remote
cmd = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = cmd.communicate()
rc = cmd.returncode
return (rc, out, err)
# ===========================================
def main():
module = AnsibleModule(
argument_spec = dict(
dest=dict(required=True),
repo=dict(required=True, aliases=['name']),
version=dict(default='HEAD'),
remote=dict(default='origin'),
force=dict(default='yes', choices=['yes', 'no'], aliases=['force'])
)
)
dest = os.path.expanduser(module.params['dest'])
repo = module.params['repo']
version = module.params['version']
remote = module.params['remote']
force = module.boolean(module.params['force'])
gitconfig = os.path.join(dest, '.git', 'config')
rc, out, err, status = (0, None, None, None)
# if there is no git configuration, do a clone operation
# else pull and switch the version
before = None
local_mods = False
if not os.path.exists(gitconfig):
(rc, out, err) = clone(repo, dest)
if rc != 0:
module.fail_json(msg=err)
else:
# else do a pull
local_mods = has_local_mods(dest)
before = get_version(dest)
(rc, out, err) = reset(module,dest,force)
if rc != 0:
module.fail_json(msg=err)
(rc, out, err) = pull(module, repo, dest, version, remote)
if rc != 0:
module.fail_json(msg=err)
# switch to version specified regardless of whether
# we cloned or pulled
(rc, out, err) = switch_version(module, dest, remote, version)
if rc != 0:
module.fail_json(msg=err)
# determine if we changed anything
after = get_version(dest)
changed = False
if before != after or local_mods:
changed = True
module.exit_json(changed=changed, before=before, after=after)
# include magic from lib/ansible/module_common.py
#<<INCLUDE_ANSIBLE_MODULE_COMMON>>
main()