summaryrefslogtreecommitdiff
path: root/library/assemble
blob: c28ef8120ef0804c1ec684da0f2f79a97f780476 (plain)
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
#!/usr/bin/python

# (c) 2012, Stephen Fromm <sfromm@gmail.com>
#
# 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/>.

import os
import os.path
import shutil
import tempfile

# ===========================================
# Support methods

def assemble_from_fragments(path):
    ''' assemble a file from a directory of fragments '''
    assembled = []
    for f in sorted(os.listdir(path)):
        fragment = "%s/%s" % (path, f)
        if os.path.isfile(fragment):
            assembled.append(file(fragment).read())
    return "".join(assembled)

def write_temp_file(data):
    fd, path = tempfile.mkstemp()
    os.write(fd, data)
    os.close(fd)
    return path

# ==============================================================
# main

def main():
    
    module = AnsibleModule(
        argument_spec = dict(
            src = dict(required=True),
            dest = dict(required=True),
        )
    )
    
    changed=False
    pathmd5 = None
    destmd5 = None
    src = os.path.expanduser(module.params['src'])
    dest = os.path.expanduser(module.params['dest'])
  
    if not os.path.exists(src):
        module.fail_json(msg="Source (%s) does not exist" % src)
    
    if not os.path.isdir(src):
        module.fail_json(msg="Source (%s) is not a directory" % src)
    
    path = write_temp_file(assemble_from_fragments(src))
    pathmd5 = module.md5(path)
    
    if os.path.exists(dest):
        destmd5 = module.md5(dest)
    
    if pathmd5 != destmd5:
        shutil.copy(path, dest)
        changed = True
    

    # Mission complete
    module.exit_json(src=src, dest=dest, md5sum=destmd5, 
        changed=changed, msg="OK",
        daisychain="file", daisychain_args=module.params)

# this is magic, see lib/ansible/module_common.py
#<<INCLUDE_ANSIBLE_MODULE_COMMON>>

main()