| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# (c) 2012, Michael DeHaan <[email protected]> |
| 4 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
|
| 9 |
DOCUMENTATION = """ |
| 10 |
--- |
| 11 |
module: git |
| 12 |
author: |
| 13 |
- "Ansible Core Team" |
| 14 |
- "Michael DeHaan" |
| 15 |
version_added: "0.0.1" |
| 16 |
short_description: Deploy software (or files) from git checkouts |
| 17 |
description: |
| 18 |
- Manage I(git) checkouts of repositories to deploy files or software. |
| 19 |
extends_documentation_fragment: action_common_attributes |
| 20 |
options: |
| 21 |
repo: |
| 22 |
description: |
| 23 |
- git, SSH, or HTTP(S) protocol address of the git repository. |
| 24 |
- Avoid embedding usernames and passwords within Git repository URLs. |
| 25 |
This practice is insecure and can lead to unauthorized access to your repositories. |
| 26 |
For secure authentication, configure SSH keys (recommended) or use a credential helper. |
| 27 |
See Git documentation on SSH keys/credential helpers for instructions. |
| 28 |
type: str |
| 29 |
required: true |
| 30 |
aliases: [ name ] |
| 31 |
dest: |
| 32 |
description: |
| 33 |
- The path of where the repository should be checked out. This |
| 34 |
is equivalent to C(git clone [repo_url] [directory]). The repository |
| 35 |
named in O(repo) is not appended to this path and the destination directory must be empty. This |
| 36 |
parameter is required, unless O(clone) is set to V(false). |
| 37 |
type: path |
| 38 |
required: true |
| 39 |
version: |
| 40 |
description: |
| 41 |
- What version of the repository to check out. This can be |
| 42 |
the literal string V(HEAD), a branch name, a tag name. |
| 43 |
It can also be a I(SHA-1) hash, in which case O(refspec) needs |
| 44 |
to be specified if the given revision is not already available. |
| 45 |
type: str |
| 46 |
default: "HEAD" |
| 47 |
accept_hostkey: |
| 48 |
description: |
| 49 |
- Will ensure or not that C(-o StrictHostKeyChecking=no) is present as an ssh option. |
| 50 |
- Be aware that this disables a protection against MITM attacks. |
| 51 |
- Those using OpenSSH >= 7.5 might want to use O(accept_newhostkey) or set O(ssh_opts) to V(StrictHostKeyChecking=accept-new) |
| 52 |
instead, it does not remove the MITM issue but it does restrict it to the first attempt. |
| 53 |
type: bool |
| 54 |
default: 'no' |
| 55 |
version_added: "1.5" |
| 56 |
accept_newhostkey: |
| 57 |
description: |
| 58 |
- As of OpenSSH 7.5, C(-o StrictHostKeyChecking=accept-new) can be |
| 59 |
used which is safer and will only accepts host keys which are |
| 60 |
not present or are the same. If V(true), ensure that |
| 61 |
C(-o StrictHostKeyChecking=accept-new) is present as an ssh option. |
| 62 |
type: bool |
| 63 |
default: 'no' |
| 64 |
version_added: "2.12" |
| 65 |
ssh_opts: |
| 66 |
description: |
| 67 |
- Options git will pass to ssh when used as protocol, it works via C(git)'s |
| 68 |
E(GIT_SSH)/E(GIT_SSH_COMMAND) environment variables. |
| 69 |
- For older versions it appends E(GIT_SSH_OPTS) (specific to this module) to the |
| 70 |
variables above or via a wrapper script. |
| 71 |
- Other options can add to this list, like O(key_file) and O(accept_hostkey). |
| 72 |
- An example value could be C(-o StrictHostKeyChecking=no) (although this particular |
| 73 |
option is better set by O(accept_hostkey)). |
| 74 |
- The module ensures that C(BatchMode=yes) is always present to avoid prompts. |
| 75 |
type: str |
| 76 |
version_added: "1.5" |
| 77 |
|
| 78 |
key_file: |
| 79 |
description: |
| 80 |
- Specify an optional private key file path, on the target host, to use for the checkout. |
| 81 |
- This ensures C(IdentitiesOnly=yes) is present in O(ssh_opts). |
| 82 |
type: path |
| 83 |
version_added: "1.5" |
| 84 |
reference: |
| 85 |
description: |
| 86 |
- Reference repository (see C(git clone --reference ...)). |
| 87 |
type: str |
| 88 |
version_added: "1.4" |
| 89 |
remote: |
| 90 |
description: |
| 91 |
- Name of the remote. |
| 92 |
type: str |
| 93 |
default: "origin" |
| 94 |
refspec: |
| 95 |
description: |
| 96 |
- Add an additional refspec to be fetched. |
| 97 |
If version is set to a I(SHA-1) not reachable from any branch |
| 98 |
or tag, this option may be necessary to specify the ref containing |
| 99 |
the I(SHA-1). |
| 100 |
Uses the same syntax as the C(git fetch) command. |
| 101 |
An example value could be "refs/meta/config". |
| 102 |
type: str |
| 103 |
version_added: "1.9" |
| 104 |
force: |
| 105 |
description: |
| 106 |
- If V(true), any modified files in the working repository and |
| 107 |
local commits will be discarded. Prior to 0.7, this was always |
| 108 |
V(true) and could not be disabled. Prior to 1.9, the default was |
| 109 |
V(true). |
| 110 |
type: bool |
| 111 |
default: 'no' |
| 112 |
version_added: "0.7" |
| 113 |
depth: |
| 114 |
description: |
| 115 |
- Create a shallow clone with a history truncated to the specified |
| 116 |
number or revisions. The minimum possible value is V(1), otherwise |
| 117 |
ignored. Needs I(git>=1.9.1) to work correctly. |
| 118 |
type: int |
| 119 |
version_added: "1.2" |
| 120 |
clone: |
| 121 |
description: |
| 122 |
- If V(false), do not clone the repository even if it does not exist locally. |
| 123 |
type: bool |
| 124 |
default: 'yes' |
| 125 |
version_added: "1.9" |
| 126 |
update: |
| 127 |
description: |
| 128 |
- If V(false), do not retrieve new revisions from the origin repository. |
| 129 |
- Operations like archive will work on the existing (old) repository and might |
| 130 |
not respond to changes to the options version or remote. |
| 131 |
type: bool |
| 132 |
default: 'yes' |
| 133 |
version_added: "1.2" |
| 134 |
executable: |
| 135 |
description: |
| 136 |
- Path to git executable to use. If not supplied, |
| 137 |
the normal mechanism for resolving binary paths will be used. |
| 138 |
type: path |
| 139 |
version_added: "1.4" |
| 140 |
bare: |
| 141 |
description: |
| 142 |
- If V(true), repository will be created as a bare repo, otherwise |
| 143 |
it will be a standard repo with a workspace. |
| 144 |
type: bool |
| 145 |
default: 'no' |
| 146 |
version_added: "1.4" |
| 147 |
umask: |
| 148 |
description: |
| 149 |
- The umask to set before doing any checkouts, or any other |
| 150 |
repository maintenance. |
| 151 |
type: raw |
| 152 |
version_added: "2.2" |
| 153 |
|
| 154 |
recursive: |
| 155 |
description: |
| 156 |
- If V(false), repository will be cloned without the C(--recursive) |
| 157 |
option, skipping sub-modules. |
| 158 |
type: bool |
| 159 |
default: 'yes' |
| 160 |
version_added: "1.6" |
| 161 |
|
| 162 |
single_branch: |
| 163 |
description: |
| 164 |
- Clone only the history leading to the tip of the specified revision. |
| 165 |
type: bool |
| 166 |
default: 'no' |
| 167 |
version_added: '2.11' |
| 168 |
|
| 169 |
track_submodules: |
| 170 |
description: |
| 171 |
- If V(true), submodules will track the latest commit on the branch specified in C(.gitmodules). |
| 172 |
If no branch is specified in C(.gitmodules), it will use the remote HEAD. |
| 173 |
- Currently, the value of remote is defaulted to C(origin). |
| 174 |
Specifying the remote for the submodules is not supported. |
| 175 |
- If V(false), submodules will be kept at the revision specified by the |
| 176 |
main project. This is equivalent to specifying the C(--remote) flag |
| 177 |
to git submodule update. |
| 178 |
type: bool |
| 179 |
default: 'no' |
| 180 |
version_added: "1.8" |
| 181 |
|
| 182 |
verify_commit: |
| 183 |
description: |
| 184 |
- If V(true), when cloning or checking out a O(version) verify the |
| 185 |
signature of a GPG signed commit. This requires git version>=2.1.0 |
| 186 |
to be installed. The commit MUST be signed and the public key MUST |
| 187 |
be present in the GPG keyring. |
| 188 |
type: bool |
| 189 |
default: 'no' |
| 190 |
version_added: "2.0" |
| 191 |
|
| 192 |
archive: |
| 193 |
description: |
| 194 |
- Specify archive file path with extension. If specified, creates an |
| 195 |
archive file of the specified format containing the tree structure |
| 196 |
for the source tree. |
| 197 |
Allowed archive formats ["zip", "tar.gz", "tar", "tgz"]. |
| 198 |
- This will clone and perform git archive from local directory as not |
| 199 |
all git servers support git archive. |
| 200 |
type: path |
| 201 |
version_added: "2.4" |
| 202 |
|
| 203 |
archive_prefix: |
| 204 |
description: |
| 205 |
- Specify a prefix to add to each file path in archive. Requires O(archive) to be specified. |
| 206 |
version_added: "2.10" |
| 207 |
type: str |
| 208 |
|
| 209 |
separate_git_dir: |
| 210 |
description: |
| 211 |
- The path to place the cloned repository. If specified, Git repository |
| 212 |
can be separated from working tree. |
| 213 |
type: path |
| 214 |
version_added: "2.7" |
| 215 |
|
| 216 |
gpg_allowlist: |
| 217 |
description: |
| 218 |
- A list of trusted GPG fingerprints to compare to the fingerprint of the |
| 219 |
GPG-signed commit. |
| 220 |
- Only used when O(verify_commit=yes). |
| 221 |
- Use of this feature requires Git 2.6+ due to its reliance on git's C(--raw) flag to C(verify-commit) and C(verify-tag). |
| 222 |
- Alias O(gpg_allowlist) is added in version 2.17. |
| 223 |
type: list |
| 224 |
elements: str |
| 225 |
default: [] |
| 226 |
version_added: "2.9" |
| 227 |
|
| 228 |
requirements: |
| 229 |
- git>=1.7.1 (the command line tool) |
| 230 |
attributes: |
| 231 |
check_mode: |
| 232 |
support: full |
| 233 |
diff_mode: |
| 234 |
support: full |
| 235 |
platform: |
| 236 |
platforms: posix |
| 237 |
notes: |
| 238 |
- "If the task seems to be hanging, first verify remote host is in C(known_hosts). |
| 239 |
SSH will prompt user to authorize the first contact with a remote host. To avoid this prompt, |
| 240 |
one solution is to use the option accept_hostkey. Another solution is to |
| 241 |
add the remote host public key in C(/etc/ssh/ssh_known_hosts) before calling |
| 242 |
the git module, with the following command: C(ssh-keyscan -H remote_host.com >> /etc/ssh/ssh_known_hosts)." |
| 243 |
""" |
| 244 |
|
| 245 |
EXAMPLES = """ |
| 246 |
- name: Git checkout |
| 247 |
ansible.builtin.git: |
| 248 |
repo: 'https://github.com/ansible/ansible.git' |
| 249 |
dest: /tmp/checkout |
| 250 |
version: release-0.22 |
| 251 |
|
| 252 |
- name: Read-write git checkout from github |
| 253 |
ansible.builtin.git: |
| 254 |
repo: [email protected]:ansible/ansible.git |
| 255 |
dest: /tmp/checkout |
| 256 |
|
| 257 |
- name: Just ensuring the repo checkout exists |
| 258 |
ansible.builtin.git: |
| 259 |
repo: 'https://github.com/ansible/ansible.git' |
| 260 |
dest: /tmp/checkout |
| 261 |
update: no |
| 262 |
|
| 263 |
- name: Just get information about the repository whether or not it has already been cloned locally |
| 264 |
ansible.builtin.git: |
| 265 |
repo: [email protected]:ansible/ansible.git |
| 266 |
dest: /tmp/checkout |
| 267 |
clone: no |
| 268 |
update: no |
| 269 |
|
| 270 |
- name: Checkout a github repo and use refspec to fetch all pull requests |
| 271 |
ansible.builtin.git: |
| 272 |
repo: 'https://github.com/ansible/ansible.git' |
| 273 |
dest: /tmp/checkout |
| 274 |
refspec: '+refs/pull/*:refs/heads/*' |
| 275 |
|
| 276 |
- name: Create git archive from repo |
| 277 |
ansible.builtin.git: |
| 278 |
repo: [email protected]:ansible/ansible.git |
| 279 |
dest: /tmp/checkout |
| 280 |
archive: /tmp/ansible.zip |
| 281 |
|
| 282 |
- name: Clone a repo with separate git directory |
| 283 |
ansible.builtin.git: |
| 284 |
repo: 'https://github.com/ansible/ansible.git' |
| 285 |
dest: /tmp/checkout |
| 286 |
separate_git_dir: /tmp/repo |
| 287 |
|
| 288 |
- name: Example clone of a single branch |
| 289 |
ansible.builtin.git: |
| 290 |
repo: [email protected]:ansible/ansible.git |
| 291 |
dest: /tmp/checkout |
| 292 |
single_branch: yes |
| 293 |
version: master |
| 294 |
|
| 295 |
- name: Avoid hanging when http(s) password is missing |
| 296 |
ansible.builtin.git: |
| 297 |
repo: 'https://github.com/ansible/ansible.git' |
| 298 |
dest: /tmp/checkout |
| 299 |
environment: |
| 300 |
GIT_TERMINAL_PROMPT: 0 # reports "terminal prompts disabled" on missing password |
| 301 |
# or GIT_ASKPASS: /bin/true # for git before version 2.3.0, reports "Authentication failed" on missing password |
| 302 |
""" |
| 303 |
|
| 304 |
RETURN = """ |
| 305 |
after: |
| 306 |
description: Last commit revision of the repository retrieved during the update. |
| 307 |
returned: success |
| 308 |
type: str |
| 309 |
sample: 4c020102a9cd6fe908c9a4a326a38f972f63a903 |
| 310 |
before: |
| 311 |
description: Commit revision before the repository was updated, "null" for new repository. |
| 312 |
returned: success |
| 313 |
type: str |
| 314 |
sample: 67c04ebe40a003bda0efb34eacfb93b0cafdf628 |
| 315 |
remote_url_changed: |
| 316 |
description: Contains True or False whether or not the remote URL was changed. |
| 317 |
returned: success |
| 318 |
type: bool |
| 319 |
sample: True |
| 320 |
git_dir_now: |
| 321 |
description: Contains the new path of .git directory if it is changed. |
| 322 |
returned: success |
| 323 |
type: str |
| 324 |
sample: /path/to/new/git/dir |
| 325 |
git_dir_before: |
| 326 |
description: Contains the original path of .git directory if it is changed. |
| 327 |
returned: success |
| 328 |
type: str |
| 329 |
sample: /path/to/old/git/dir |
| 330 |
""" |
| 331 |
|
| 332 |
import filecmp |
| 333 |
import os |
| 334 |
import pathlib |
| 335 |
import re |
| 336 |
import shlex |
| 337 |
import stat |
| 338 |
import sys |
| 339 |
import shutil |
| 340 |
import tempfile |
| 341 |
from ansible.module_utils.compat.version import LooseVersion |
| 342 |
|
| 343 |
from ansible.module_utils.common.text.converters import to_native, to_text |
| 344 |
from ansible.module_utils.basic import AnsibleModule |
| 345 |
from ansible.module_utils.common.locale import get_best_parsable_locale |
| 346 |
from ansible.module_utils.common.process import get_bin_path |
| 347 |
|
| 348 |
|
| 349 |
def relocate_repo(module, result, repo_dir, old_repo_dir, worktree_dir): |
| 350 |
if os.path.exists(repo_dir): |
| 351 |
module.fail_json(msg='Separate-git-dir path %s already exists.' % repo_dir) |
| 352 |
if worktree_dir: |
| 353 |
dot_git_file_path = os.path.join(worktree_dir, '.git') |
| 354 |
try: |
| 355 |
shutil.move(old_repo_dir, repo_dir) |
| 356 |
with open(dot_git_file_path, 'w') as dot_git_file: |
| 357 |
dot_git_file.write('gitdir: %s' % repo_dir) |
| 358 |
result['git_dir_before'] = old_repo_dir |
| 359 |
result['git_dir_now'] = repo_dir |
| 360 |
except OSError as ex: |
| 361 |
# if we already moved the .git dir, roll it back |
| 362 |
if os.path.exists(repo_dir): |
| 363 |
shutil.move(repo_dir, old_repo_dir) |
| 364 |
raise Exception('Unable to move git dir.') from ex |
| 365 |
|
| 366 |
|
| 367 |
def head_splitter(headfile, remote, module=None, fail_on_error=False): |
| 368 |
"""Extract the head reference""" |
| 369 |
# https://github.com/ansible/ansible-modules-core/pull/907 |
| 370 |
|
| 371 |
res = None |
| 372 |
if os.path.exists(headfile): |
| 373 |
rawdata = None |
| 374 |
try: |
| 375 |
with open(headfile, 'r') as f: |
| 376 |
rawdata = f.readline() |
| 377 |
except Exception: |
| 378 |
if fail_on_error and module: |
| 379 |
module.fail_json(msg="Unable to read %s" % headfile) |
| 380 |
if rawdata: |
| 381 |
try: |
| 382 |
rawdata = rawdata.replace('refs/remotes/%s' % remote, '', 1) |
| 383 |
refparts = rawdata.split(' ') |
| 384 |
newref = refparts[-1] |
| 385 |
nrefparts = newref.split('/', 2) |
| 386 |
res = nrefparts[-1].rstrip('\n') |
| 387 |
except Exception: |
| 388 |
if fail_on_error and module: |
| 389 |
module.fail_json(msg="Unable to split head from '%s'" % rawdata) |
| 390 |
return res |
| 391 |
|
| 392 |
|
| 393 |
def unfrackgitpath(path): |
| 394 |
if path is None: |
| 395 |
return None |
| 396 |
|
| 397 |
# copied from ansible.utils.path |
| 398 |
return os.path.normpath(os.path.realpath(os.path.expanduser(os.path.expandvars(path)))) |
| 399 |
|
| 400 |
|
| 401 |
def get_submodule_update_params(module, git_path, cwd): |
| 402 |
# or: git submodule [--quiet] update [--init] [-N|--no-fetch] |
| 403 |
# [-f|--force] [--rebase] [--reference <repository>] [--merge] |
| 404 |
# [--recursive] [--] [<path>...] |
| 405 |
|
| 406 |
params = [] |
| 407 |
|
| 408 |
# run a bad submodule command to get valid params |
| 409 |
cmd = "%s submodule update --help" % (git_path) |
| 410 |
rc, stdout, stderr = module.run_command(cmd, cwd=cwd) |
| 411 |
lines = stderr.split('\n') |
| 412 |
update_line = None |
| 413 |
for line in lines: |
| 414 |
if 'git submodule [--quiet] update ' in line: |
| 415 |
update_line = line |
| 416 |
if update_line: |
| 417 |
update_line = update_line.replace('[', '') |
| 418 |
update_line = update_line.replace(']', '') |
| 419 |
update_line = update_line.replace('|', ' ') |
| 420 |
parts = shlex.split(update_line) |
| 421 |
for part in parts: |
| 422 |
if part.startswith('--'): |
| 423 |
part = part.replace('--', '') |
| 424 |
params.append(part) |
| 425 |
|
| 426 |
return params |
| 427 |
|
| 428 |
|
| 429 |
def write_ssh_wrapper(module): |
| 430 |
""" |
| 431 |
This writes an shell wrapper for ssh options to be used with git |
| 432 |
this is only relevant for older versions of gitthat cannot |
| 433 |
handle the options themselves. Returns path to the script |
| 434 |
""" |
| 435 |
try: |
| 436 |
# make sure we have full permission to the module_dir, which |
| 437 |
# may not be the case if we're sudo'ing to a non-root user |
| 438 |
if os.access(module.tmpdir, os.W_OK | os.R_OK | os.X_OK): |
| 439 |
fd, wrapper_path = tempfile.mkstemp(prefix=module.tmpdir + '/') |
| 440 |
else: |
| 441 |
raise OSError |
| 442 |
except OSError: |
| 443 |
fd, wrapper_path = tempfile.mkstemp() |
| 444 |
|
| 445 |
# use existing git_ssh/ssh_command, fallback to 'ssh' |
| 446 |
template = """#!/bin/sh |
| 447 |
%s $GIT_SSH_OPTS "$@" |
| 448 |
""" % os.environ.get('GIT_SSH', os.environ.get('GIT_SSH_COMMAND', 'ssh')) |
| 449 |
|
| 450 |
# write it |
| 451 |
with os.fdopen(fd, 'w') as fh: |
| 452 |
fh.write(template) |
| 453 |
|
| 454 |
# set execute |
| 455 |
st = os.stat(wrapper_path) |
| 456 |
os.chmod(wrapper_path, st.st_mode | stat.S_IEXEC) |
| 457 |
|
| 458 |
module.debug('Wrote temp git ssh wrapper (%s): %s' % (wrapper_path, template)) |
| 459 |
|
| 460 |
# ensure we cleanup after ourselves |
| 461 |
module.add_cleanup_file(path=wrapper_path) |
| 462 |
|
| 463 |
return wrapper_path |
| 464 |
|
| 465 |
|
| 466 |
def set_git_ssh_env(key_file, ssh_opts, git_version, module): |
| 467 |
""" |
| 468 |
use environment variables to configure git's ssh execution, |
| 469 |
which varies by version but this function should handle all. |
| 470 |
""" |
| 471 |
|
| 472 |
# initialise to existing ssh opts and/or append user provided |
| 473 |
if ssh_opts is None: |
| 474 |
ssh_opts = os.environ.get('GIT_SSH_OPTS', '') |
| 475 |
else: |
| 476 |
ssh_opts = os.environ.get('GIT_SSH_OPTS', '') + ' ' + ssh_opts |
| 477 |
|
| 478 |
# hostkey acceptance |
| 479 |
accept_key = "StrictHostKeyChecking=no" |
| 480 |
if module.params['accept_hostkey'] and accept_key not in ssh_opts: |
| 481 |
ssh_opts += " -o %s" % accept_key |
| 482 |
|
| 483 |
# avoid prompts |
| 484 |
force_batch = 'BatchMode=yes' |
| 485 |
if force_batch not in ssh_opts: |
| 486 |
ssh_opts += ' -o %s' % (force_batch) |
| 487 |
|
| 488 |
# deal with key file |
| 489 |
if key_file: |
| 490 |
key_opt = '-i %s' % key_file |
| 491 |
if key_opt not in ssh_opts: |
| 492 |
ssh_opts += ' %s' % key_opt |
| 493 |
|
| 494 |
ikey = 'IdentitiesOnly=yes' |
| 495 |
if ikey not in ssh_opts: |
| 496 |
ssh_opts += ' -o %s' % ikey |
| 497 |
|
| 498 |
# older than 2.3 does not know how to use git_ssh_command, |
| 499 |
# so we force it into get_ssh var |
| 500 |
# https://github.com/gitster/git/commit/09d60d785c68c8fa65094ecbe46fbc2a38d0fc1f |
| 501 |
if git_version is not None and git_version < LooseVersion('2.3.0'): |
| 502 |
# for use in wrapper |
| 503 |
os.environ["GIT_SSH_OPTS"] = ssh_opts |
| 504 |
|
| 505 |
# these versions don't support GIT_SSH_OPTS so have to write wrapper |
| 506 |
wrapper = write_ssh_wrapper(module) |
| 507 |
|
| 508 |
# force use of git_ssh_opts via wrapper, git_ssh cannot not handle arguments |
| 509 |
os.environ['GIT_SSH'] = wrapper |
| 510 |
else: |
| 511 |
# we construct full finalized command string here |
| 512 |
full_cmd = os.environ.get('GIT_SSH', os.environ.get('GIT_SSH_COMMAND', 'ssh')) |
| 513 |
if ssh_opts: |
| 514 |
full_cmd += ' ' + ssh_opts |
| 515 |
# git_ssh_command can handle arguments to ssh |
| 516 |
os.environ["GIT_SSH_COMMAND"] = full_cmd |
| 517 |
|
| 518 |
|
| 519 |
def get_version(module, git_path, dest, ref="HEAD"): |
| 520 |
""" samples the version of the git repo """ |
| 521 |
|
| 522 |
cmd = "%s rev-parse %s" % (git_path, ref) |
| 523 |
rc, stdout, stderr = module.run_command(cmd, cwd=dest) |
| 524 |
sha = to_native(stdout).rstrip('\n') |
| 525 |
return sha |
| 526 |
|
| 527 |
|
| 528 |
def ssh_supports_acceptnewhostkey(module): |
| 529 |
try: |
| 530 |
ssh_path = get_bin_path('ssh') |
| 531 |
except ValueError as err: |
| 532 |
module.fail_json( |
| 533 |
msg='Remote host is missing ssh command, so you cannot ' |
| 534 |
'use acceptnewhostkey option.', details=to_text(err)) |
| 535 |
supports_acceptnewhostkey = True |
| 536 |
cmd = [ssh_path, '-o', 'StrictHostKeyChecking=accept-new', '-V'] |
| 537 |
rc, stdout, stderr = module.run_command(cmd) |
| 538 |
if rc != 0: |
| 539 |
supports_acceptnewhostkey = False |
| 540 |
return supports_acceptnewhostkey |
| 541 |
|
| 542 |
|
| 543 |
def get_submodule_versions(git_path, module, dest, version='HEAD'): |
| 544 |
cmd = [git_path, 'submodule', 'foreach', git_path, 'rev-parse', version] |
| 545 |
(rc, out, err) = module.run_command(cmd, cwd=dest) |
| 546 |
if rc != 0: |
| 547 |
module.fail_json( |
| 548 |
msg='Unable to determine hashes of submodules', |
| 549 |
stdout=out, |
| 550 |
stderr=err, |
| 551 |
rc=rc) |
| 552 |
submodules = {} |
| 553 |
subm_name = None |
| 554 |
for line in out.splitlines(): |
| 555 |
if line.startswith("Entering '"): |
| 556 |
subm_name = line[10:-1] |
| 557 |
elif len(line.strip()) == 40: |
| 558 |
if subm_name is None: |
| 559 |
module.fail_json() |
| 560 |
submodules[subm_name] = line.strip() |
| 561 |
subm_name = None |
| 562 |
else: |
| 563 |
module.fail_json(msg='Unable to parse submodule hash line: %s' % line.strip()) |
| 564 |
if subm_name is not None: |
| 565 |
module.fail_json(msg='Unable to find hash for submodule: %s' % subm_name) |
| 566 |
|
| 567 |
return submodules |
| 568 |
|
| 569 |
|
| 570 |
def get_submodule_branch(git_path, module, dest, submodule): |
| 571 |
"""Get the configured branch for a submodule from .gitmodules. |
| 572 |
|
| 573 |
Falls back to the remote HEAD if no branch is configured. |
| 574 |
""" |
| 575 |
cmd = [git_path, 'config', '-f', '.gitmodules', |
| 576 |
f'submodule.{submodule}.branch'] |
| 577 |
rc, out, _err = module.run_command(cmd, cwd=dest) |
| 578 |
if rc == 0 and out.strip(): |
| 579 |
return out.strip() |
| 580 |
|
| 581 |
# No branch configured in .gitmodules, use remote HEAD |
| 582 |
submodule_path = os.path.join(dest, submodule) |
| 583 |
cmd = [git_path, 'symbolic-ref', '--short', 'refs/remotes/origin/HEAD'] |
| 584 |
rc, out, _err = module.run_command(cmd, cwd=submodule_path) |
| 585 |
if rc == 0 and out.strip(): |
| 586 |
# Returns e.g. "origin/main", strip the remote prefix |
| 587 |
return out.strip().split('/', 1)[-1] |
| 588 |
|
| 589 |
return 'HEAD' |
| 590 |
|
| 591 |
|
| 592 |
def clone(git_path, module, repo, dest, remote, depth, version, bare, |
| 593 |
reference, refspec, git_version_used, verify_commit, separate_git_dir, result, gpg_allowlist, single_branch): |
| 594 |
""" makes a new git repo if it does not already exist """ |
| 595 |
dest_dirname = os.path.dirname(dest) |
| 596 |
try: |
| 597 |
os.makedirs(dest_dirname) |
| 598 |
except Exception: |
| 599 |
pass |
| 600 |
cmd = [git_path, 'clone'] |
| 601 |
|
| 602 |
if bare: |
| 603 |
cmd.append('--bare') |
| 604 |
else: |
| 605 |
cmd.extend(['--origin', remote]) |
| 606 |
|
| 607 |
is_branch_or_tag = is_remote_branch(git_path, module, dest, repo, version) or is_remote_tag(git_path, module, dest, repo, version) |
| 608 |
if depth: |
| 609 |
if version == 'HEAD' or refspec: |
| 610 |
cmd.extend(['--depth', str(depth)]) |
| 611 |
elif is_branch_or_tag: |
| 612 |
cmd.extend(['--depth', str(depth)]) |
| 613 |
cmd.extend(['--branch', version]) |
| 614 |
else: |
| 615 |
# only use depth if the remote object is branch or tag (i.e. fetchable) |
| 616 |
module.warn("Ignoring depth argument. " |
| 617 |
"Shallow clones are only available for " |
| 618 |
"HEAD, branches, tags or in combination with refspec.") |
| 619 |
if reference: |
| 620 |
cmd.extend(['--reference', str(reference)]) |
| 621 |
|
| 622 |
if single_branch: |
| 623 |
if git_version_used is None: |
| 624 |
module.fail_json(msg='Cannot find git executable at %s' % git_path) |
| 625 |
|
| 626 |
if git_version_used < LooseVersion('1.7.10'): |
| 627 |
module.warn("git version '%s' is too old to use 'single-branch'. Ignoring." % git_version_used) |
| 628 |
else: |
| 629 |
cmd.append("--single-branch") |
| 630 |
|
| 631 |
if is_branch_or_tag: |
| 632 |
cmd.extend(['--branch', version]) |
| 633 |
|
| 634 |
needs_separate_git_dir_fallback = False |
| 635 |
if separate_git_dir: |
| 636 |
if git_version_used is None: |
| 637 |
module.fail_json(msg='Cannot find git executable at %s' % git_path) |
| 638 |
if git_version_used < LooseVersion('1.7.5'): |
| 639 |
# git before 1.7.5 doesn't have separate-git-dir argument, do fallback |
| 640 |
needs_separate_git_dir_fallback = True |
| 641 |
else: |
| 642 |
cmd.append('--separate-git-dir=%s' % separate_git_dir) |
| 643 |
|
| 644 |
cmd.extend([repo, dest]) |
| 645 |
module.run_command(cmd, check_rc=True, cwd=dest_dirname) |
| 646 |
if needs_separate_git_dir_fallback: |
| 647 |
relocate_repo(module, result, separate_git_dir, os.path.join(dest, ".git"), dest) |
| 648 |
|
| 649 |
if bare and remote != 'origin': |
| 650 |
module.run_command([git_path, 'remote', 'add', remote, repo], check_rc=True, cwd=dest) |
| 651 |
|
| 652 |
if refspec: |
| 653 |
cmd = [git_path, 'fetch'] |
| 654 |
if depth: |
| 655 |
cmd.extend(['--depth', str(depth)]) |
| 656 |
cmd.extend([remote, refspec]) |
| 657 |
module.run_command(cmd, check_rc=True, cwd=dest) |
| 658 |
|
| 659 |
if verify_commit: |
| 660 |
verify_commit_sign(git_path, module, dest, version, gpg_allowlist) |
| 661 |
|
| 662 |
|
| 663 |
def has_local_mods(module, git_path, dest, bare): |
| 664 |
if bare: |
| 665 |
return False |
| 666 |
|
| 667 |
cmd = "%s status --porcelain" % (git_path) |
| 668 |
rc, stdout, stderr = module.run_command(cmd, cwd=dest) |
| 669 |
lines = stdout.splitlines() |
| 670 |
lines = list(filter(lambda c: not re.search('^\\?\\?.*$', c), lines)) |
| 671 |
|
| 672 |
return len(lines) > 0 |
| 673 |
|
| 674 |
|
| 675 |
def reset(git_path, module, dest): |
| 676 |
""" |
| 677 |
Resets the index and working tree to HEAD. |
| 678 |
Discards any changes to tracked files in working |
| 679 |
tree since that commit. |
| 680 |
""" |
| 681 |
cmd = "%s reset --hard HEAD" % (git_path,) |
| 682 |
return module.run_command(cmd, check_rc=True, cwd=dest) |
| 683 |
|
| 684 |
|
| 685 |
def get_diff(module, git_path, dest, repo, remote, depth, bare, before, after, refspec, force): |
| 686 |
""" Return the difference between 2 versions """ |
| 687 |
if before is None: |
| 688 |
return {'prepared': '>> Newly checked out %s' % after} |
| 689 |
elif before != after: |
| 690 |
# Ensure we have the object we are referring to during git diff ! |
| 691 |
git_version_used = git_version(git_path, module) |
| 692 |
fetch(git_path, module, repo, dest, after, remote, depth, bare, refspec, git_version_used, force) |
| 693 |
cmd = '%s diff %s %s' % (git_path, before, after) |
| 694 |
(rc, out, err) = module.run_command(cmd, cwd=dest) |
| 695 |
if rc == 0 and out: |
| 696 |
return {'prepared': out} |
| 697 |
elif rc == 0: |
| 698 |
return {'prepared': '>> No visual differences between %s and %s' % (before, after)} |
| 699 |
elif err: |
| 700 |
return {'prepared': '>> Failed to get proper diff between %s and %s:\n>> %s' % (before, after, err)} |
| 701 |
else: |
| 702 |
return {'prepared': '>> Failed to get proper diff between %s and %s' % (before, after)} |
| 703 |
return {} |
| 704 |
|
| 705 |
|
| 706 |
def get_sha_hash(module: AnsibleModule, git_path: str, remote: str, version: str, cwd: str) -> str: |
| 707 |
if cwd is None or not (working_dir := pathlib.Path(cwd)).exists(): |
| 708 |
working_dir = pathlib.Path(module.tmpdir) / "tmp_repo" |
| 709 |
working_dir.mkdir(exist_ok=True) |
| 710 |
module.run_command([git_path, 'init'], cwd=working_dir) # Create a bare repo |
| 711 |
module.run_command([git_path, 'remote', 'add', 'origin', remote], cwd=working_dir) |
| 712 |
|
| 713 |
# This command's error message is descriptive enough for our purposes, so we set check_rc to True and let it bail |
| 714 |
module.run_command([git_path, 'fetch', '--dry-run', remote, version], cwd=working_dir, check_rc=True) |
| 715 |
|
| 716 |
# Should only succeed when 'version' is a valid revision |
| 717 |
return version |
| 718 |
|
| 719 |
|
| 720 |
def get_remote_head(git_path, module, dest, version, remote, bare): |
| 721 |
cloning = False |
| 722 |
cwd = None |
| 723 |
tag = False |
| 724 |
if remote == module.params['repo']: |
| 725 |
cloning = True |
| 726 |
elif remote == 'file://' + os.path.expanduser(module.params['repo']): |
| 727 |
cloning = True |
| 728 |
else: |
| 729 |
cwd = dest |
| 730 |
if version == 'HEAD': |
| 731 |
if cloning: |
| 732 |
# cloning the repo, just get the remote's HEAD version |
| 733 |
cmd = '%s ls-remote %s -h HEAD' % (git_path, remote) |
| 734 |
else: |
| 735 |
head_branch = get_head_branch(git_path, module, dest, remote, bare) |
| 736 |
cmd = '%s ls-remote %s -h refs/heads/%s' % (git_path, remote, head_branch) |
| 737 |
elif is_remote_branch(git_path, module, dest, remote, version): |
| 738 |
cmd = '%s ls-remote %s -h refs/heads/%s' % (git_path, remote, version) |
| 739 |
elif is_remote_tag(git_path, module, dest, remote, version): |
| 740 |
tag = True |
| 741 |
cmd = '%s ls-remote %s -t refs/tags/%s*' % (git_path, remote, version) |
| 742 |
else: |
| 743 |
# Appears to be a sha hash. Checking requires special action |
| 744 |
rev = get_sha_hash(module, git_path, remote, version, cwd) |
| 745 |
|
| 746 |
return rev |
| 747 |
|
| 748 |
(rc, out, err) = module.run_command(cmd, check_rc=True, cwd=cwd) |
| 749 |
if len(out) < 1: |
| 750 |
module.fail_json(msg="Could not determine remote revision for %s" % version, stdout=out, stderr=err, rc=rc) |
| 751 |
|
| 752 |
out = to_native(out) |
| 753 |
|
| 754 |
if tag: |
| 755 |
# Find the dereferenced tag if this is an annotated tag. |
| 756 |
for tag in out.split('\n'): |
| 757 |
if tag.endswith(version + '^{}'): |
| 758 |
out = tag |
| 759 |
break |
| 760 |
elif tag.endswith(version): |
| 761 |
out = tag |
| 762 |
|
| 763 |
rev = out.split()[0] |
| 764 |
return rev |
| 765 |
|
| 766 |
|
| 767 |
def is_remote_tag(git_path, module, dest, remote, version): |
| 768 |
cmd = '%s ls-remote %s -t refs/tags/%s' % (git_path, remote, version) |
| 769 |
(rc, out, err) = module.run_command(cmd, check_rc=True, cwd=dest) |
| 770 |
if to_native(version, errors='surrogate_or_strict') in out: |
| 771 |
return True |
| 772 |
else: |
| 773 |
return False |
| 774 |
|
| 775 |
|
| 776 |
def get_branches(git_path, module, dest): |
| 777 |
branches = [] |
| 778 |
cmd = '%s branch --no-color -a' % (git_path,) |
| 779 |
(rc, out, err) = module.run_command(cmd, cwd=dest) |
| 780 |
if rc != 0: |
| 781 |
module.fail_json(msg="Could not determine branch data - received %s" % out, stdout=out, stderr=err) |
| 782 |
for line in out.split('\n'): |
| 783 |
if line.strip(): |
| 784 |
branches.append(line.strip()) |
| 785 |
return branches |
| 786 |
|
| 787 |
|
| 788 |
def get_annotated_tags(git_path, module, dest): |
| 789 |
tags = [] |
| 790 |
cmd = [git_path, 'for-each-ref', 'refs/tags/', '--format', '%(objecttype):%(refname:short)'] |
| 791 |
(rc, out, err) = module.run_command(cmd, cwd=dest) |
| 792 |
if rc != 0: |
| 793 |
module.fail_json(msg="Could not determine tag data - received %s" % out, stdout=out, stderr=err) |
| 794 |
for line in to_native(out).split('\n'): |
| 795 |
if line.strip(): |
| 796 |
tagtype, tagname = line.strip().split(':') |
| 797 |
if tagtype == 'tag': |
| 798 |
tags.append(tagname) |
| 799 |
return tags |
| 800 |
|
| 801 |
|
| 802 |
def is_remote_branch(git_path, module, dest, remote, version): |
| 803 |
cmd = '%s ls-remote %s -h refs/heads/%s' % (git_path, remote, version) |
| 804 |
(rc, out, err) = module.run_command(cmd, check_rc=True, cwd=dest) |
| 805 |
if to_native(version, errors='surrogate_or_strict') in out: |
| 806 |
return True |
| 807 |
else: |
| 808 |
return False |
| 809 |
|
| 810 |
|
| 811 |
def is_local_branch(git_path, module, dest, branch): |
| 812 |
branches = get_branches(git_path, module, dest) |
| 813 |
lbranch = '%s' % branch |
| 814 |
if lbranch in branches: |
| 815 |
return True |
| 816 |
elif '* %s' % branch in branches: |
| 817 |
return True |
| 818 |
else: |
| 819 |
return False |
| 820 |
|
| 821 |
|
| 822 |
def is_not_a_branch(git_path, module, dest): |
| 823 |
branches = get_branches(git_path, module, dest) |
| 824 |
for branch in branches: |
| 825 |
if branch.startswith('* ') and ('no branch' in branch or 'detached from' in branch or 'detached at' in branch): |
| 826 |
return True |
| 827 |
return False |
| 828 |
|
| 829 |
|
| 830 |
def get_repo_path(dest, bare): |
| 831 |
if bare: |
| 832 |
repo_path = dest |
| 833 |
else: |
| 834 |
repo_path = os.path.join(dest, '.git') |
| 835 |
# Check if the .git is a file. If it is a file, it means that the repository is in external directory respective to the working copy (e.g. we are in a |
| 836 |
# submodule structure). |
| 837 |
if os.path.isfile(repo_path): |
| 838 |
with open(repo_path, 'r') as gitfile: |
| 839 |
data = gitfile.read() |
| 840 |
ref_prefix, gitdir = data.rstrip().split('gitdir: ', 1) |
| 841 |
if ref_prefix: |
| 842 |
raise ValueError('.git file has invalid git dir reference format') |
| 843 |
|
| 844 |
# There is a possibility the .git file to have an absolute path. |
| 845 |
if os.path.isabs(gitdir): |
| 846 |
repo_path = gitdir |
| 847 |
else: |
| 848 |
# Use original destination directory with data from .git file. |
| 849 |
repo_path = os.path.join(dest, gitdir) |
| 850 |
if not os.path.isdir(repo_path): |
| 851 |
raise ValueError('%s is not a directory' % repo_path) |
| 852 |
return repo_path |
| 853 |
|
| 854 |
|
| 855 |
def get_head_branch(git_path, module, dest, remote, bare=False): |
| 856 |
""" |
| 857 |
Determine what branch HEAD is associated with. This is partly |
| 858 |
taken from lib/ansible/utils/__init__.py. It finds the correct |
| 859 |
path to .git/HEAD and reads from that file the branch that HEAD is |
| 860 |
associated with. In the case of a detached HEAD, this will look |
| 861 |
up the branch in .git/refs/remotes/<remote>/HEAD. |
| 862 |
""" |
| 863 |
try: |
| 864 |
repo_path = get_repo_path(dest, bare) |
| 865 |
except (OSError, ValueError) as ex: |
| 866 |
# No repo path found |
| 867 |
# ``.git`` file does not have a valid format for detached Git dir. |
| 868 |
module.fail_json( |
| 869 |
msg='Current repo does not have a valid reference to a ' |
| 870 |
'separate Git dir or it refers to the invalid path', |
| 871 |
details=str(ex), |
| 872 |
exception=ex, |
| 873 |
) |
| 874 |
# Read .git/HEAD for the name of the branch. |
| 875 |
# If we're in a detached HEAD state, look up the branch associated with |
| 876 |
# the remote HEAD in .git/refs/remotes/<remote>/HEAD |
| 877 |
headfile = os.path.join(repo_path, "HEAD") |
| 878 |
if is_not_a_branch(git_path, module, dest): |
| 879 |
headfile = os.path.join(repo_path, 'refs', 'remotes', remote, 'HEAD') |
| 880 |
branch = head_splitter(headfile, remote, module=module, fail_on_error=True) |
| 881 |
return branch |
| 882 |
|
| 883 |
|
| 884 |
def get_remote_url(git_path, module, dest, remote): |
| 885 |
"""Return URL of remote source for repo.""" |
| 886 |
command = [git_path, 'ls-remote', '--get-url', remote] |
| 887 |
(rc, out, err) = module.run_command(command, cwd=dest) |
| 888 |
if rc != 0: |
| 889 |
# There was an issue getting remote URL, most likely |
| 890 |
# command is not available in this version of Git. |
| 891 |
return None |
| 892 |
return to_native(out).rstrip('\n') |
| 893 |
|
| 894 |
|
| 895 |
def set_remote_url(git_path, module, repo, dest, remote): |
| 896 |
""" updates repo from remote sources """ |
| 897 |
# Return if remote URL isn't changing. |
| 898 |
remote_url = get_remote_url(git_path, module, dest, remote) |
| 899 |
if remote_url == repo or unfrackgitpath(remote_url) == unfrackgitpath(repo): |
| 900 |
return False |
| 901 |
|
| 902 |
command = [git_path, 'remote', 'set-url', remote, repo] |
| 903 |
(rc, out, err) = module.run_command(command, cwd=dest) |
| 904 |
if rc != 0: |
| 905 |
label = "set a new url %s for %s" % (repo, remote) |
| 906 |
module.fail_json(msg="Failed to %s: %s %s" % (label, out, err)) |
| 907 |
|
| 908 |
# Return False if remote_url is None to maintain previous behavior |
| 909 |
# for Git versions prior to 1.7.5 that lack required functionality. |
| 910 |
return remote_url is not None |
| 911 |
|
| 912 |
|
| 913 |
def fetch(git_path, module, repo, dest, version, remote, depth, bare, refspec, git_version_used, force=False): |
| 914 |
""" updates repo from remote sources """ |
| 915 |
set_remote_url(git_path, module, repo, dest, remote) |
| 916 |
commands = [] |
| 917 |
|
| 918 |
fetch_str = 'download remote objects and refs' |
| 919 |
fetch_cmd = [git_path, 'fetch'] |
| 920 |
|
| 921 |
refspecs = [] |
| 922 |
if depth: |
| 923 |
# try to find the minimal set of refs we need to fetch to get a |
| 924 |
# successful checkout |
| 925 |
currenthead = get_head_branch(git_path, module, dest, remote) |
| 926 |
if refspec: |
| 927 |
refspecs.append(refspec) |
| 928 |
elif version == 'HEAD': |
| 929 |
refspecs.append(currenthead) |
| 930 |
elif is_remote_branch(git_path, module, dest, repo, version): |
| 931 |
if currenthead != version: |
| 932 |
# this workaround is only needed for older git versions |
| 933 |
# 1.8.3 is broken, 1.9.x works |
| 934 |
# ensure that remote branch is available as both local and remote ref |
| 935 |
refspecs.append('+refs/heads/%s:refs/heads/%s' % (version, version)) |
| 936 |
refspecs.append('+refs/heads/%s:refs/remotes/%s/%s' % (version, remote, version)) |
| 937 |
elif is_remote_tag(git_path, module, dest, repo, version): |
| 938 |
refspecs.append('+refs/tags/' + version + ':refs/tags/' + version) |
| 939 |
if refspecs: |
| 940 |
# if refspecs is empty, i.e. version is neither heads nor tags |
| 941 |
# assume it is a version hash |
| 942 |
# fall back to a full clone, otherwise we might not be able to checkout |
| 943 |
# version |
| 944 |
fetch_cmd.extend(['--depth', str(depth)]) |
| 945 |
|
| 946 |
if not depth or not refspecs: |
| 947 |
# don't try to be minimalistic but do a full clone |
| 948 |
# also do this if depth is given, but version is something that can't be fetched directly |
| 949 |
if bare: |
| 950 |
refspecs = ['+refs/heads/*:refs/heads/*', '+refs/tags/*:refs/tags/*'] |
| 951 |
else: |
| 952 |
# ensure all tags are fetched |
| 953 |
if git_version_used is not None and git_version_used >= LooseVersion('1.9'): |
| 954 |
fetch_cmd.append('--tags') |
| 955 |
else: |
| 956 |
# old git versions have a bug in --tags that prevents updating existing tags |
| 957 |
commands.append((fetch_str, fetch_cmd + [remote])) |
| 958 |
refspecs = ['+refs/tags/*:refs/tags/*'] |
| 959 |
if refspec: |
| 960 |
refspecs.append(refspec) |
| 961 |
|
| 962 |
if force: |
| 963 |
fetch_cmd.append('--force') |
| 964 |
|
| 965 |
fetch_cmd.extend([remote]) |
| 966 |
|
| 967 |
commands.append((fetch_str, fetch_cmd + refspecs)) |
| 968 |
|
| 969 |
for (label, command) in commands: |
| 970 |
(rc, out, err) = module.run_command(command, cwd=dest) |
| 971 |
if rc != 0: |
| 972 |
module.fail_json(msg="Failed to %s: %s %s" % (label, out, err), cmd=command) |
| 973 |
|
| 974 |
|
| 975 |
def submodules_fetch(git_path, module, remote, track_submodules, dest): |
| 976 |
changed = False |
| 977 |
|
| 978 |
if not os.path.exists(os.path.join(dest, '.gitmodules')): |
| 979 |
# no submodules |
| 980 |
return changed |
| 981 |
|
| 982 |
gitmodules_file = open(os.path.join(dest, '.gitmodules'), 'r') |
| 983 |
for line in gitmodules_file: |
| 984 |
# Check for new submodules |
| 985 |
if not changed and line.strip().startswith('path'): |
| 986 |
path = line.split('=', 1)[1].strip() |
| 987 |
# Check that dest/path/.git exists |
| 988 |
if not os.path.exists(os.path.join(dest, path, '.git')): |
| 989 |
changed = True |
| 990 |
|
| 991 |
# Check for updates to existing modules |
| 992 |
if not changed: |
| 993 |
# Fetch updates |
| 994 |
begin = get_submodule_versions(git_path, module, dest) |
| 995 |
cmd = [git_path, 'submodule', 'foreach', git_path, 'fetch'] |
| 996 |
(rc, out, err) = module.run_command(cmd, check_rc=True, cwd=dest) |
| 997 |
if track_submodules: |
| 998 |
# Compare each submodule against its configured remote branch |
| 999 |
after = {} |
| 1000 |
for submodule in begin: |
| 1001 |
branch = get_submodule_branch(git_path, module, dest, submodule) |
| 1002 |
version_ref = f'{remote}/{branch}' if branch != 'HEAD' else 'HEAD' |
| 1003 |
submodule_path = os.path.join(dest, submodule) |
| 1004 |
cmd = [git_path, 'rev-parse', version_ref] |
| 1005 |
(rc, out, err) = module.run_command(cmd, cwd=submodule_path) |
| 1006 |
if rc != 0: |
| 1007 |
module.fail_json( |
| 1008 |
msg='Unable to determine hash of submodule %s at %s' % (submodule, version_ref), |
| 1009 |
stdout=out, stderr=err, rc=rc) |
| 1010 |
after[submodule] = out.strip() |
| 1011 |
if begin != after: |
| 1012 |
changed = True |
| 1013 |
else: |
| 1014 |
# Compare against the superproject's expectation |
| 1015 |
cmd = [git_path, 'submodule', 'status'] |
| 1016 |
(rc, out, err) = module.run_command(cmd, check_rc=True, cwd=dest) |
| 1017 |
for line in out.splitlines(): |
| 1018 |
if line[0] != ' ': |
| 1019 |
changed = True |
| 1020 |
break |
| 1021 |
return changed |
| 1022 |
|
| 1023 |
|
| 1024 |
def submodule_update(git_path, module, dest, track_submodules, force=False): |
| 1025 |
""" init and update any submodules """ |
| 1026 |
|
| 1027 |
# get the valid submodule params |
| 1028 |
params = get_submodule_update_params(module, git_path, dest) |
| 1029 |
|
| 1030 |
# skip submodule commands if .gitmodules is not present |
| 1031 |
if not os.path.exists(os.path.join(dest, '.gitmodules')): |
| 1032 |
return (0, '', '') |
| 1033 |
cmd = [git_path, 'submodule', 'sync'] |
| 1034 |
(rc, out, err) = module.run_command(cmd, check_rc=True, cwd=dest) |
| 1035 |
if 'remote' in params and track_submodules: |
| 1036 |
cmd = [git_path, 'submodule', 'update', '--init', '--recursive', '--remote'] |
| 1037 |
else: |
| 1038 |
cmd = [git_path, 'submodule', 'update', '--init', '--recursive'] |
| 1039 |
if force: |
| 1040 |
cmd.append('--force') |
| 1041 |
(rc, out, err) = module.run_command(cmd, cwd=dest) |
| 1042 |
if rc != 0: |
| 1043 |
module.fail_json(msg="Failed to init/update submodules: %s" % out + err) |
| 1044 |
return (rc, out, err) |
| 1045 |
|
| 1046 |
|
| 1047 |
def set_remote_branch(git_path, module, dest, remote, version, depth): |
| 1048 |
"""set refs for the remote branch version |
| 1049 |
|
| 1050 |
This assumes the branch does not yet exist locally and is therefore also not checked out. |
| 1051 |
Can't use git remote set-branches, as it is not available in git 1.7.1 (centos6) |
| 1052 |
""" |
| 1053 |
|
| 1054 |
branchref = "+refs/heads/%s:refs/heads/%s" % (version, version) |
| 1055 |
branchref += ' +refs/heads/%s:refs/remotes/%s/%s' % (version, remote, version) |
| 1056 |
cmd = "%s fetch --depth=%s %s %s" % (git_path, depth, remote, branchref) |
| 1057 |
(rc, out, err) = module.run_command(cmd, cwd=dest) |
| 1058 |
if rc != 0: |
| 1059 |
module.fail_json(msg="Failed to fetch branch from remote: %s" % version, stdout=out, stderr=err, rc=rc) |
| 1060 |
|
| 1061 |
|
| 1062 |
def switch_version(git_path, module, dest, remote, version, verify_commit, depth, gpg_allowlist, force=False): |
| 1063 |
cmd = '' |
| 1064 |
if version == 'HEAD': |
| 1065 |
branch = get_head_branch(git_path, module, dest, remote) |
| 1066 |
(rc, out, err) = module.run_command("%s checkout --force %s" % (git_path, branch), cwd=dest) |
| 1067 |
if rc != 0: |
| 1068 |
module.fail_json(msg="Failed to checkout branch %s" % branch, |
| 1069 |
stdout=out, stderr=err, rc=rc) |
| 1070 |
cmd = "%s reset --hard %s/%s --" % (git_path, remote, branch) |
| 1071 |
else: |
| 1072 |
# FIXME check for local_branch first, should have been fetched already |
| 1073 |
if is_remote_branch(git_path, module, dest, remote, version): |
| 1074 |
if depth and not is_local_branch(git_path, module, dest, version): |
| 1075 |
# git clone --depth implies --single-branch, which makes |
| 1076 |
# the checkout fail if the version changes |
| 1077 |
# fetch the remote branch, to be able to check it out next |
| 1078 |
set_remote_branch(git_path, module, dest, remote, version, depth) |
| 1079 |
if not is_local_branch(git_path, module, dest, version): |
| 1080 |
cmd = "%s checkout --track -b %s %s/%s" % (git_path, version, remote, version) |
| 1081 |
else: |
| 1082 |
(rc, out, err) = module.run_command("%s checkout --force %s" % (git_path, version), cwd=dest) |
| 1083 |
if rc != 0: |
| 1084 |
module.fail_json(msg="Failed to checkout branch %s" % version, stdout=out, stderr=err, rc=rc) |
| 1085 |
if ('ahead' in out or 'diverged' in out) and not force: |
| 1086 |
module.fail_json(msg=f"Unable to advance to {remote}/{version} because local commits will be lost. " |
| 1087 |
f"Use `force: yes` to overwrite local commits.") |
| 1088 |
if force: |
| 1089 |
cmd = f"{git_path} reset --hard {remote}/{version}" |
| 1090 |
else: |
| 1091 |
cmd = f"{git_path} merge --ff-only {remote}/{version}" |
| 1092 |
else: |
| 1093 |
cmd = "%s checkout --force %s" % (git_path, version) |
| 1094 |
(rc, out1, err1) = module.run_command(cmd, cwd=dest) |
| 1095 |
if rc != 0: |
| 1096 |
if version != 'HEAD': |
| 1097 |
module.fail_json(msg="Failed to checkout %s" % (version), |
| 1098 |
stdout=out1, stderr=err1, rc=rc, cmd=cmd) |
| 1099 |
else: |
| 1100 |
module.fail_json(msg="Failed to checkout branch %s" % (branch), |
| 1101 |
stdout=out1, stderr=err1, rc=rc, cmd=cmd) |
| 1102 |
|
| 1103 |
if verify_commit: |
| 1104 |
verify_commit_sign(git_path, module, dest, version, gpg_allowlist) |
| 1105 |
|
| 1106 |
return (rc, out1, err1) |
| 1107 |
|
| 1108 |
|
| 1109 |
def verify_commit_sign(git_path, module, dest, version, gpg_allowlist): |
| 1110 |
if version in get_annotated_tags(git_path, module, dest): |
| 1111 |
git_sub = "verify-tag" |
| 1112 |
else: |
| 1113 |
git_sub = "verify-commit" |
| 1114 |
cmd = "%s %s %s" % (git_path, git_sub, version) |
| 1115 |
if gpg_allowlist: |
| 1116 |
cmd += " --raw" |
| 1117 |
(rc, out, err) = module.run_command(cmd, cwd=dest) |
| 1118 |
if rc != 0: |
| 1119 |
module.fail_json(msg='Failed to verify GPG signature of commit/tag "%s"' % version, stdout=out, stderr=err, rc=rc) |
| 1120 |
if gpg_allowlist: |
| 1121 |
fingerprint = get_gpg_fingerprint(err) |
| 1122 |
if fingerprint not in gpg_allowlist: |
| 1123 |
module.fail_json(msg='The gpg_allowlist does not include the public key "%s" for this commit' % fingerprint, stdout=out, stderr=err, rc=rc) |
| 1124 |
return (rc, out, err) |
| 1125 |
|
| 1126 |
|
| 1127 |
def get_gpg_fingerprint(output): |
| 1128 |
"""Return a fingerprint of the primary key. |
| 1129 |
|
| 1130 |
Ref: |
| 1131 |
https://git.gnupg.org/cgi-bin/gitweb.cgi?p=gnupg.git;a=blob;f=doc/DETAILS;hb=HEAD#l482 |
| 1132 |
""" |
| 1133 |
for line in output.splitlines(): |
| 1134 |
data = line.split() |
| 1135 |
if data[1] != 'VALIDSIG': |
| 1136 |
continue |
| 1137 |
|
| 1138 |
# if signed with a subkey, this contains the primary key fingerprint |
| 1139 |
data_id = 11 if len(data) == 11 else 2 |
| 1140 |
return data[data_id] |
| 1141 |
|
| 1142 |
|
| 1143 |
def git_version(git_path, module): |
| 1144 |
"""return the installed version of git""" |
| 1145 |
cmd = "%s --version" % git_path |
| 1146 |
(rc, out, err) = module.run_command(cmd) |
| 1147 |
if rc != 0: |
| 1148 |
# one could fail_json here, but the version info is not that important, |
| 1149 |
# so let's try to fail only on actual git commands |
| 1150 |
return None |
| 1151 |
rematch = re.search('git version (.*)$', to_native(out)) |
| 1152 |
if not rematch: |
| 1153 |
return None |
| 1154 |
return LooseVersion(rematch.groups()[0]) |
| 1155 |
|
| 1156 |
|
| 1157 |
def git_archive(git_path, module, dest, archive, archive_fmt, archive_prefix, version): |
| 1158 |
""" Create git archive in given source directory """ |
| 1159 |
cmd = [git_path, 'archive', '--format', archive_fmt, '--output', archive, version] |
| 1160 |
if archive_prefix is not None: |
| 1161 |
cmd.insert(-1, '--prefix') |
| 1162 |
cmd.insert(-1, archive_prefix) |
| 1163 |
(rc, out, err) = module.run_command(cmd, cwd=dest) |
| 1164 |
if rc != 0: |
| 1165 |
module.fail_json(msg="Failed to perform archive operation", |
| 1166 |
details="Git archive command failed to create " |
| 1167 |
"archive %s using %s directory." |
| 1168 |
"Error: %s" % (archive, dest, err)) |
| 1169 |
return rc, out, err |
| 1170 |
|
| 1171 |
|
| 1172 |
def create_archive(git_path, module, dest, archive, archive_prefix, version, repo, result): |
| 1173 |
""" Helper function for creating archive using git_archive """ |
| 1174 |
all_archive_fmt = {'.zip': 'zip', '.gz': 'tar.gz', '.tar': 'tar', |
| 1175 |
'.tgz': 'tgz'} |
| 1176 |
dummy, archive_ext = os.path.splitext(archive) |
| 1177 |
archive_fmt = all_archive_fmt.get(archive_ext, None) |
| 1178 |
if archive_fmt is None: |
| 1179 |
module.fail_json(msg="Unable to get file extension from " |
| 1180 |
"archive file name : %s" % archive, |
| 1181 |
details="Please specify archive as filename with " |
| 1182 |
"extension. File extension can be one " |
| 1183 |
"of ['tar', 'tar.gz', 'zip', 'tgz']") |
| 1184 |
|
| 1185 |
repo_name = repo.split("/")[-1].replace(".git", "") |
| 1186 |
|
| 1187 |
if os.path.exists(archive): |
| 1188 |
# If git archive file exists, then compare it with new git archive file. |
| 1189 |
# if match, do nothing |
| 1190 |
# if does not match, then replace existing with temp archive file. |
| 1191 |
tempdir = tempfile.mkdtemp() |
| 1192 |
new_archive_dest = os.path.join(tempdir, repo_name) |
| 1193 |
new_archive = new_archive_dest + '.' + archive_fmt |
| 1194 |
git_archive(git_path, module, dest, new_archive, archive_fmt, archive_prefix, version) |
| 1195 |
|
| 1196 |
# filecmp is supposed to be efficient than md5sum checksum |
| 1197 |
if filecmp.cmp(new_archive, archive): |
| 1198 |
result.update(changed=False) |
| 1199 |
# Cleanup before exiting |
| 1200 |
try: |
| 1201 |
shutil.rmtree(tempdir) |
| 1202 |
except OSError: |
| 1203 |
pass |
| 1204 |
else: |
| 1205 |
try: |
| 1206 |
shutil.move(new_archive, archive) |
| 1207 |
shutil.rmtree(tempdir) |
| 1208 |
result.update(changed=True) |
| 1209 |
except OSError as e: |
| 1210 |
module.fail_json(msg="Failed to move %s to %s" % |
| 1211 |
(new_archive, archive), |
| 1212 |
details=u"Error occurred while moving : %s" |
| 1213 |
% to_text(e)) |
| 1214 |
else: |
| 1215 |
# Perform archive from local directory |
| 1216 |
git_archive(git_path, module, dest, archive, archive_fmt, archive_prefix, version) |
| 1217 |
result.update(changed=True) |
| 1218 |
|
| 1219 |
# =========================================== |
| 1220 |
|
| 1221 |
|
| 1222 |
def main(): |
| 1223 |
module = AnsibleModule( |
| 1224 |
argument_spec=dict( |
| 1225 |
dest=dict(type='path'), |
| 1226 |
repo=dict(required=True, aliases=['name']), |
| 1227 |
version=dict(default='HEAD'), |
| 1228 |
remote=dict(default='origin'), |
| 1229 |
refspec=dict(default=None), |
| 1230 |
reference=dict(default=None), |
| 1231 |
force=dict(default='no', type='bool'), |
| 1232 |
depth=dict(default=None, type='int'), |
| 1233 |
clone=dict(default='yes', type='bool'), |
| 1234 |
update=dict(default='yes', type='bool'), |
| 1235 |
verify_commit=dict(default='no', type='bool'), |
| 1236 |
gpg_allowlist=dict( |
| 1237 |
default=[], type='list', elements='str', |
| 1238 |
), |
| 1239 |
accept_hostkey=dict(default='no', type='bool'), |
| 1240 |
accept_newhostkey=dict(default='no', type='bool'), |
| 1241 |
key_file=dict(default=None, type='path', required=False), |
| 1242 |
ssh_opts=dict(default=None, required=False), |
| 1243 |
executable=dict(default=None, type='path'), |
| 1244 |
bare=dict(default='no', type='bool'), |
| 1245 |
recursive=dict(default='yes', type='bool'), |
| 1246 |
single_branch=dict(default=False, type='bool'), |
| 1247 |
track_submodules=dict(default='no', type='bool'), |
| 1248 |
umask=dict(default=None, type='raw'), |
| 1249 |
archive=dict(type='path'), |
| 1250 |
archive_prefix=dict(), |
| 1251 |
separate_git_dir=dict(type='path'), |
| 1252 |
), |
| 1253 |
mutually_exclusive=[('separate_git_dir', 'bare'), ('accept_hostkey', 'accept_newhostkey')], |
| 1254 |
required_by={'archive_prefix': ['archive']}, |
| 1255 |
supports_check_mode=True |
| 1256 |
) |
| 1257 |
|
| 1258 |
dest = module.params['dest'] |
| 1259 |
repo = module.params['repo'] |
| 1260 |
version = module.params['version'] |
| 1261 |
remote = module.params['remote'] |
| 1262 |
refspec = module.params['refspec'] |
| 1263 |
force = module.params['force'] |
| 1264 |
depth = module.params['depth'] |
| 1265 |
update = module.params['update'] |
| 1266 |
allow_clone = module.params['clone'] |
| 1267 |
bare = module.params['bare'] |
| 1268 |
verify_commit = module.params['verify_commit'] |
| 1269 |
gpg_allowlist = module.params['gpg_allowlist'] |
| 1270 |
reference = module.params['reference'] |
| 1271 |
single_branch = module.params['single_branch'] |
| 1272 |
git_path = module.params['executable'] or module.get_bin_path('git', True) |
| 1273 |
key_file = module.params['key_file'] |
| 1274 |
ssh_opts = module.params['ssh_opts'] |
| 1275 |
umask = module.params['umask'] |
| 1276 |
archive = module.params['archive'] |
| 1277 |
archive_prefix = module.params['archive_prefix'] |
| 1278 |
separate_git_dir = module.params['separate_git_dir'] |
| 1279 |
|
| 1280 |
result = dict(changed=False) |
| 1281 |
|
| 1282 |
if module.params['accept_hostkey']: |
| 1283 |
if ssh_opts is not None: |
| 1284 |
if ("-o StrictHostKeyChecking=no" not in ssh_opts) and ("-o StrictHostKeyChecking=accept-new" not in ssh_opts): |
| 1285 |
ssh_opts += " -o StrictHostKeyChecking=no" |
| 1286 |
else: |
| 1287 |
ssh_opts = "-o StrictHostKeyChecking=no" |
| 1288 |
|
| 1289 |
if module.params['accept_newhostkey']: |
| 1290 |
if not ssh_supports_acceptnewhostkey(module): |
| 1291 |
module.warn("Your ssh client does not support accept_newhostkey option, therefore it cannot be used.") |
| 1292 |
else: |
| 1293 |
if ssh_opts is not None: |
| 1294 |
if ("-o StrictHostKeyChecking=no" not in ssh_opts) and ("-o StrictHostKeyChecking=accept-new" not in ssh_opts): |
| 1295 |
ssh_opts += " -o StrictHostKeyChecking=accept-new" |
| 1296 |
else: |
| 1297 |
ssh_opts = "-o StrictHostKeyChecking=accept-new" |
| 1298 |
|
| 1299 |
# evaluate and set the umask before doing anything else |
| 1300 |
if umask is not None: |
| 1301 |
if not isinstance(umask, str): |
| 1302 |
module.fail_json(msg="umask must be defined as a quoted octal integer") |
| 1303 |
try: |
| 1304 |
umask = int(umask, 8) |
| 1305 |
except Exception: |
| 1306 |
module.fail_json(msg="umask must be an octal integer", |
| 1307 |
details=to_text(sys.exc_info()[1])) |
| 1308 |
os.umask(umask) |
| 1309 |
|
| 1310 |
# Certain features such as depth require a file:/// protocol for path based urls |
| 1311 |
# so force a protocol here ... |
| 1312 |
if os.path.expanduser(repo).startswith('/'): |
| 1313 |
repo = 'file://' + os.path.expanduser(repo) |
| 1314 |
|
| 1315 |
# We screenscrape a huge amount of git commands so use C locale anytime we |
| 1316 |
# call run_command() |
| 1317 |
locale = get_best_parsable_locale(module) |
| 1318 |
module.run_command_environ_update = dict(LANG=locale, LC_ALL=locale, LC_MESSAGES=locale, LC_CTYPE=locale, LANGUAGE=locale) |
| 1319 |
|
| 1320 |
if separate_git_dir: |
| 1321 |
separate_git_dir = os.path.realpath(separate_git_dir) |
| 1322 |
|
| 1323 |
gitconfig = None |
| 1324 |
if not dest and allow_clone: |
| 1325 |
module.fail_json(msg="the destination directory must be specified unless clone=no") |
| 1326 |
elif dest: |
| 1327 |
dest = os.path.abspath(dest) |
| 1328 |
try: |
| 1329 |
repo_path = get_repo_path(dest, bare) |
| 1330 |
if separate_git_dir and os.path.exists(repo_path) and separate_git_dir != repo_path: |
| 1331 |
result['changed'] = True |
| 1332 |
if not module.check_mode: |
| 1333 |
relocate_repo(module, result, separate_git_dir, repo_path, dest) |
| 1334 |
repo_path = separate_git_dir |
| 1335 |
except (OSError, ValueError) as ex: |
| 1336 |
# No repo path found |
| 1337 |
# ``.git`` file does not have a valid format for detached Git dir. |
| 1338 |
module.fail_json( |
| 1339 |
msg='Current repo does not have a valid reference to a ' |
| 1340 |
'separate Git dir or it refers to the invalid path', |
| 1341 |
details=str(ex), |
| 1342 |
exception=ex, |
| 1343 |
) |
| 1344 |
gitconfig = os.path.join(repo_path, 'config') |
| 1345 |
|
| 1346 |
# iface changes so need it to make decisions |
| 1347 |
git_version_used = git_version(git_path, module) |
| 1348 |
|
| 1349 |
# GIT_SSH=<path> as an environment variable, might create sh wrapper script for older versions. |
| 1350 |
set_git_ssh_env(key_file, ssh_opts, git_version_used, module) |
| 1351 |
|
| 1352 |
if depth is not None and git_version_used is not None and git_version_used < LooseVersion('1.9.1'): |
| 1353 |
module.warn("git version is too old to fully support the depth argument. Falling back to full checkouts.") |
| 1354 |
depth = None |
| 1355 |
|
| 1356 |
recursive = module.params['recursive'] |
| 1357 |
track_submodules = module.params['track_submodules'] |
| 1358 |
|
| 1359 |
result.update(before=None) |
| 1360 |
|
| 1361 |
local_mods = False |
| 1362 |
if (dest and not os.path.exists(gitconfig)) or (not dest and not allow_clone): |
| 1363 |
# if there is no git configuration, do a clone operation unless: |
| 1364 |
# * the user requested no clone (they just want info) |
| 1365 |
# * we're doing a check mode test |
| 1366 |
# In those cases we do an ls-remote |
| 1367 |
if module.check_mode or not allow_clone: |
| 1368 |
remote_head = get_remote_head(git_path, module, dest, version, repo, bare) |
| 1369 |
result.update(changed=True, after=remote_head) |
| 1370 |
if module._diff: |
| 1371 |
diff = get_diff(module, git_path, dest, repo, remote, depth, bare, result['before'], result['after'], refspec, force) |
| 1372 |
if diff: |
| 1373 |
result['diff'] = diff |
| 1374 |
module.exit_json(**result) |
| 1375 |
# there's no git config, so clone |
| 1376 |
clone(git_path, module, repo, dest, remote, depth, version, bare, reference, |
| 1377 |
refspec, git_version_used, verify_commit, separate_git_dir, result, gpg_allowlist, single_branch) |
| 1378 |
elif not update: |
| 1379 |
# Just return having found a repo already in the dest path |
| 1380 |
# this does no checking that the repo is the actual repo |
| 1381 |
# requested. |
| 1382 |
result['before'] = get_version(module, git_path, dest) |
| 1383 |
result.update(after=result['before']) |
| 1384 |
if archive: |
| 1385 |
# Git archive is not supported by all git servers, so |
| 1386 |
# we will first clone and perform git archive from local directory |
| 1387 |
if module.check_mode: |
| 1388 |
result.update(changed=True) |
| 1389 |
module.exit_json(**result) |
| 1390 |
|
| 1391 |
create_archive(git_path, module, dest, archive, archive_prefix, version, repo, result) |
| 1392 |
|
| 1393 |
module.exit_json(**result) |
| 1394 |
else: |
| 1395 |
# else do a pull |
| 1396 |
local_mods = has_local_mods(module, git_path, dest, bare) |
| 1397 |
result['before'] = get_version(module, git_path, dest) |
| 1398 |
if local_mods: |
| 1399 |
# failure should happen regardless of check mode |
| 1400 |
if not force: |
| 1401 |
module.fail_json(msg="Local modifications exist in the destination: " + dest + " (force=no).", **result) |
| 1402 |
# if force and in non-check mode, do a reset |
| 1403 |
if not module.check_mode: |
| 1404 |
reset(git_path, module, dest) |
| 1405 |
result.update(changed=True, msg='Local modifications exist in the destination: ' + dest) |
| 1406 |
|
| 1407 |
# exit if already at desired sha version |
| 1408 |
if module.check_mode: |
| 1409 |
remote_url = get_remote_url(git_path, module, dest, remote) |
| 1410 |
remote_url_changed = remote_url and remote_url != repo and unfrackgitpath(remote_url) != unfrackgitpath(repo) |
| 1411 |
else: |
| 1412 |
remote_url_changed = set_remote_url(git_path, module, repo, dest, remote) |
| 1413 |
result.update(remote_url_changed=remote_url_changed) |
| 1414 |
|
| 1415 |
if module.check_mode: |
| 1416 |
remote_head = get_remote_head(git_path, module, dest, version, remote, bare) |
| 1417 |
result.update(changed=(result['before'] != remote_head or remote_url_changed), after=remote_head) |
| 1418 |
# FIXME: This diff should fail since the new remote_head is not fetched yet?! |
| 1419 |
if module._diff: |
| 1420 |
diff = get_diff(module, git_path, dest, repo, remote, depth, bare, result['before'], result['after'], refspec, force) |
| 1421 |
if diff: |
| 1422 |
result['diff'] = diff |
| 1423 |
module.exit_json(**result) |
| 1424 |
else: |
| 1425 |
fetch(git_path, module, repo, dest, version, remote, depth, bare, refspec, git_version_used, force=force) |
| 1426 |
|
| 1427 |
result['after'] = get_version(module, git_path, dest) |
| 1428 |
|
| 1429 |
# switch to version specified regardless of whether |
| 1430 |
# we got new revisions from the repository |
| 1431 |
if not bare: |
| 1432 |
switch_version(git_path, module, dest, remote, version, verify_commit, depth, gpg_allowlist, force=force) |
| 1433 |
|
| 1434 |
# Deal with submodules |
| 1435 |
submodules_updated = False |
| 1436 |
if recursive and not bare: |
| 1437 |
submodules_updated = submodules_fetch(git_path, module, remote, track_submodules, dest) |
| 1438 |
if submodules_updated: |
| 1439 |
result.update(submodules_changed=submodules_updated) |
| 1440 |
|
| 1441 |
if module.check_mode: |
| 1442 |
result.update(changed=True, after=remote_head) |
| 1443 |
module.exit_json(**result) |
| 1444 |
|
| 1445 |
# Switch to version specified |
| 1446 |
submodule_update(git_path, module, dest, track_submodules, force=force) |
| 1447 |
|
| 1448 |
# determine if we changed anything |
| 1449 |
result['after'] = get_version(module, git_path, dest) |
| 1450 |
|
| 1451 |
if result['before'] != result['after'] or local_mods or submodules_updated or remote_url_changed: |
| 1452 |
result.update(changed=True) |
| 1453 |
if module._diff: |
| 1454 |
diff = get_diff(module, git_path, dest, repo, remote, depth, bare, result['before'], result['after'], refspec, force) |
| 1455 |
if diff: |
| 1456 |
result['diff'] = diff |
| 1457 |
|
| 1458 |
if archive: |
| 1459 |
# Git archive is not supported by all git servers, so |
| 1460 |
# we will first clone and perform git archive from local directory |
| 1461 |
if module.check_mode: |
| 1462 |
result.update(changed=True) |
| 1463 |
module.exit_json(**result) |
| 1464 |
|
| 1465 |
create_archive(git_path, module, dest, archive, archive_prefix, version, repo, result) |
| 1466 |
|
| 1467 |
module.exit_json(**result) |
| 1468 |
|
| 1469 |
|
| 1470 |
if __name__ == '__main__': |
| 1471 |
main() |