__init__.py 2.91 KB
Newer Older
1
2
#!/usr/bin/env python
#
3
# __init__.py - Miscellaneous functions used throughout fsl_ci.
4
5
6
7
8
#
# Author: Paul McCarthy <pauldmccarthy@gmail.com>
#


9
import os.path    as op
10
import               os
11
import               errno
12
import               shlex
13
import               string
14
import               time
15
16
17
18
19
import               tempfile
import contextlib as ctxlib
import subprocess as sp


20
21
22
23
__version__ = '0.1.0'
"""Current version of the fsl-ci-rules."""


24
25
26
27
28
29
30
31
USERNAME = 'fsl-ci-rules'
"""Username to be used for all git interactions which require one. """


EMAIL = 'fsl-ci-rules@git.fmrib.ox.ac.uk'
"""Password to be used for all git interactions which require one. """


32
33
34
35
36
def fprint(*args, **kwargs):
    """Print with flush=True. """
    print(*args, **kwargs, flush=True)


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
@ctxlib.contextmanager
def tempdir():
    """Context manager to create, and change into, a temporary directory, and
    then afterwards delete it and change back to the original working
    directory.
    """
    with tempfile.TemporaryDirectory() as td:
        prevdir = os.getcwd()
        os.chdir(td)
        try:
            yield td
        finally:
            os.chdir(prevdir)


@ctxlib.contextmanager
def indir(dirname):
    """Context manager to change into a directory, and then afterwards
    change back to the original working directory.
    """
    prevdir = os.getcwd()
    os.chdir(dirname)
    try:
        yield
    finally:
        os.chdir(prevdir)


def sprun(cmd, **kwargs):
    """Runs the given command with subprocess.run. """
67
    fprint(f'Running {cmd}')
68
69
    cmd = shlex.split(cmd)
    return sp.run(cmd, check=True, **kwargs)
70
71
72
73
74
75
76
77
78
79
80
81
82
83


def is_valid_project_version(version):
    """Return True if the given version/tag is "valid" - it must
    be a sequence of integers, separated by periods, with an optional
    leading 'v'.
    """
    if version.lower().startswith('v'):
        version = version[1:]

    for part in version.split('.'):
        if not all([c in string.digits for c in part]):
            return False
    return True
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


@ctxlib.contextmanager
def lockdir(dirname):
    """Primitive mechanism by which concurrent access to a directory can be
    prevented. Attempts to create a semaphore file in the directory, but waits
    if that file already exists. Removes the file when finished.
    """

    delay    = 10
    lockfile = op.join(dirname, '.fsl_ci.lockdir')

    while True:
        try:
            fprint(f'Attempting to lock {dirname} for exclusive access.')
            fd = os.open(os.O_CREAT | os.O_EXCL | os.O_RDWR)
            break
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise e
            fprint(f'{dirname} is already locked - '
                   f'trying again in {delay} seconds ...')
        time.sleep(10)

    fprint(f'Exclusive access acquired for {dirname} ...')
    try:
        yield

    finally:
        fprint(f'Relinquishing lock on {dirname}')
        os.close( fd)
        os.unlink(lockfile)