aboutsummaryrefslogtreecommitdiff
path: root/ggoto
blob: 1948eb702ea4f0846d25e33109cc2068b83edc44 (plain) (blame)
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
#!/usr/bin/python3

import hashlib
import os.path
import subprocess
import sys


exec_verbose = False


def get_file_sha1sum(filename):
    hash = hashlib.sha1()

    try:
        with open(filename, 'rb') as f:
            for chunk in iter(lambda: f.read(4096), b''):
                hash.update(chunk)
    except FileNotFoundError:
        return None

    return hash.hexdigest()


class FileStates:
    def __init__(self, filenames=None):
        self.states = {}

        if filenames:
            for f in filenames:
                self.remember(f)


    def remember(self, filename):
        self.states[filename] = get_file_sha1sum(filename)


    def changed(self, filename):
        sum = get_file_sha1sum(filename)
        prev = self.states.get(filename, None)
        return sum != prev


    def any_changed(self, filenames):
        for f in filenames:
            if self.changed(f):
                return True
        return False


def parse_args(argv):
    rv = {
        'force': False,
        'help': False,
        'verbose': False,
    }

    for i, arg in enumerate(argv):
        if arg == '-f':
            rv['force'] = True
        elif arg == '-h' or arg == '--help':
            rv['help'] = True
        elif arg == '-v':
            rv['verbose'] = True
        elif 'ref' not in rv:
            rv['ref'] = arg
        else:
            raise ValueError('unexpected argument {} at position #{}'.format(arg, i))

    return rv


def parse_git_ref(ref):
    split = ref.split('/', 1)

    if len(split) == 2:
        return (split[0], split[1])
    else:
        return (None, split[0])


def exec(args):
    out = subprocess.DEVNULL

    if exec_verbose:
        out = subprocess.PIPE
        print('$ ' + ' '.join(args))

    cp = subprocess.run(args, stdout=out, stderr=out)
    cp.check_returncode()
    return cp


def git_fetch(remote, rev):
    exec(['git', 'fetch', remote, rev])


def git_pull(remote, rev):
    exec(['git', 'pull', '--rebase', remote, rev])


def git_checkout(rev, force=False):
    args = []

    if force:
        args.append('-f')

    exec(['git', *args, 'checkout', rev])


def git_get_symbolic_ref(name):
    """
    Get the short symbolic ref for a name. Returns None if name does not have a
    symbolic ref.
    """
    cp = subprocess.run(['git', 'symbolic-ref', '--short', name],
            stdout=subprocess.PIPE,
            stderr=subprocess.DEVNULL,
            text=True)

    if cp.returncode == 0:
        return cp.stdout.strip()


def needs_npm_install(file_states=None):
    if not os.path.isfile('package.json'):
        return False

    if file_states is None:
        return False

    return file_states.any_changed([
        'package.json',
        'package-lock.json',
    ])


def needs_composer_install(file_states=None):
    if not os.path.isfile('composer.json'):
        return False

    if file_states is None:
        return False

    return file_states.any_changed([
        'composer.json',
        'composer.lock',
    ])


if __name__ == '__main__':
    args = parse_args(sys.argv[1:])
    file_states = FileStates([
        'package.json',
        'package-lock.json',
    ])

    if args['verbose']:
        exec_verbose = True

    if 'ref' in args:
        (remote, rev) = parse_git_ref(args['ref'])
    else:
        remote = None
        rev = git_get_symbolic_ref('HEAD')

        if not rev:
            print('HEAD is not at a symbolic ref', file=sys.stderr)
            sys.exit(1)

    if remote:
        git_fetch(remote, rev)
        git_checkout(remote + '/' + rev, args['force'])
    else:
        git_checkout(rev, args['force'])
        git_pull('origin', rev)

    if needs_npm_install(file_states):
        exec(['npm', 'i'])

    if needs_composer_install(file_states):
        exec(['composer', '--ignore-platform-reqs', 'install'])
    elif os.path.isfile('composer.json'):
        exec(['composer', '--ignore-platform-reqs', 'dumpautoload'])