Skip to content

Module dcm2bids.utils.tools⚓︎

This module checks whether a software is in PATH, for version, and for updates.

View Source
  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
# -*- coding: utf-8 -*-

"""This module checks whether a software is in PATH, for version, and for updates."""

import logging

import json

from urllib import error, request

from subprocess import getoutput

from shutil import which

from dcm2bids.version import __version__

logger = logging.getLogger(__name__)

def is_tool(name):

    """ Check if a program is in PATH

    Args:

        name (string): program name

    Returns:

        boolean

    """

    return which(name) is not None

def check_github_latest(github_repo, timeout=3):

    """

    Check the latest version of a github repository. Will skip the process if

    no connection can be established.

    Args:

        githubRepo (string): a github repository ("username/repository")

        timeout (int): time in seconds

    Returns:

        A string of the latest release tag that correspond to the version

    """

    req = request.Request(

      url=f"https://api.github.com/repos/{github_repo}/releases/latest")

    try:

        response = request.urlopen(req, timeout=timeout)

    except error.HTTPError as e:

        logger.warning(f"Checking latest version of {github_repo} was not possible, "

                       "the server couldn't fulfill the request.")

        logger.debug(f"Error code: {e.code}")

        return "no_internet"

    except error.URLError as e:

        logger.warning(f"Checking latest version of {github_repo} was not possible, "

                       "your machine is probably not connected to the Internet.")

        logger.debug(f"Reason {e.reason}")

        return "no_internet"

    else:

        content = json.loads(response.read())

        return content["tag_name"]

def check_latest(name="dcm2bids"):

    """ Check if a new version of a software exists and print some details

    Implemented for dcm2bids and dcm2niix

    Args:

        name (string): name of the software

    Returns:

        None

    """

    data = {

        "dcm2bids": {

            "repo": "UNFmontreal/Dcm2Bids",

            "host": "https://github.com",

            "current": __version__,

        },

        "dcm2niix": {

            "repo": "rordenlab/dcm2niix",

            "host": "https://github.com",

            "current": dcm2niix_version,

        },

    }

    repo = data.get(name)["repo"]

    host = data.get(name)["host"]

    current = data.get(name)["current"]

    if callable(current):

        current = current()

    latest = check_github_latest(repo)

    if latest != "no_internet" and latest > current:

        logger.warning(f"A newer version exists for {name}: {latest}")

        logger.warning(f"You should update it -> {host}/{repo}.")

    elif latest != "no_internet":

        logger.info(f"Currently using the latest version of {name}.")

def dcm2niix_version(name="dcm2niix"):

    """

    Check and raises an error if dcm2niix is not in PATH.

    Then check for the version installed.

    Returns:

        A string of the version of dcm2niix install on the system

    """

    if not is_tool(name):

        logger.error(f"{name} is not in your PATH or not installed.")

        logger.error("https://github.com/rordenlab/dcm2niix to troubleshoot.")

        raise FileNotFoundError(f"{name} is not in your PATH or not installed."

                                " -> https://github.com/rordenlab/dcm2niix"

                                " to troubleshoot.")

    try:

        output = getoutput("dcm2niix --version")

    except Exception:

        logger.exception("Checking dcm2niix version", exc_info=False)

        return

    else:

        return output.split()[-1]

Variables⚓︎

1
logger

Functions⚓︎

check_github_latest⚓︎

1
2
3
4
def check_github_latest(
    github_repo,
    timeout=3
)

Check the latest version of a github repository. Will skip the process if

no connection can be established.

Parameters:

Name Type Description Default
githubRepo string a github repository ("username/repository") None
timeout int time in seconds None

Returns:

Type Description
None A string of the latest release tag that correspond to the version
View Source
 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
def check_github_latest(github_repo, timeout=3):

    """

    Check the latest version of a github repository. Will skip the process if

    no connection can be established.

    Args:

        githubRepo (string): a github repository ("username/repository")

        timeout (int): time in seconds

    Returns:

        A string of the latest release tag that correspond to the version

    """

    req = request.Request(

      url=f"https://api.github.com/repos/{github_repo}/releases/latest")

    try:

        response = request.urlopen(req, timeout=timeout)

    except error.HTTPError as e:

        logger.warning(f"Checking latest version of {github_repo} was not possible, "

                       "the server couldn't fulfill the request.")

        logger.debug(f"Error code: {e.code}")

        return "no_internet"

    except error.URLError as e:

        logger.warning(f"Checking latest version of {github_repo} was not possible, "

                       "your machine is probably not connected to the Internet.")

        logger.debug(f"Reason {e.reason}")

        return "no_internet"

    else:

        content = json.loads(response.read())

        return content["tag_name"]

check_latest⚓︎

1
2
3
def check_latest(
    name='dcm2bids'
)

Check if a new version of a software exists and print some details

Implemented for dcm2bids and dcm2niix

Parameters:

Name Type Description Default
name string name of the software None

Returns:

Type Description
None None
View Source
 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
def check_latest(name="dcm2bids"):

    """ Check if a new version of a software exists and print some details

    Implemented for dcm2bids and dcm2niix

    Args:

        name (string): name of the software

    Returns:

        None

    """

    data = {

        "dcm2bids": {

            "repo": "UNFmontreal/Dcm2Bids",

            "host": "https://github.com",

            "current": __version__,

        },

        "dcm2niix": {

            "repo": "rordenlab/dcm2niix",

            "host": "https://github.com",

            "current": dcm2niix_version,

        },

    }

    repo = data.get(name)["repo"]

    host = data.get(name)["host"]

    current = data.get(name)["current"]

    if callable(current):

        current = current()

    latest = check_github_latest(repo)

    if latest != "no_internet" and latest > current:

        logger.warning(f"A newer version exists for {name}: {latest}")

        logger.warning(f"You should update it -> {host}/{repo}.")

    elif latest != "no_internet":

        logger.info(f"Currently using the latest version of {name}.")

dcm2niix_version⚓︎

1
2
3
def dcm2niix_version(
    name='dcm2niix'
)

Check and raises an error if dcm2niix is not in PATH.

Then check for the version installed.

Returns:

Type Description
None A string of the version of dcm2niix install on the system
View Source
 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
def dcm2niix_version(name="dcm2niix"):

    """

    Check and raises an error if dcm2niix is not in PATH.

    Then check for the version installed.

    Returns:

        A string of the version of dcm2niix install on the system

    """

    if not is_tool(name):

        logger.error(f"{name} is not in your PATH or not installed.")

        logger.error("https://github.com/rordenlab/dcm2niix to troubleshoot.")

        raise FileNotFoundError(f"{name} is not in your PATH or not installed."

                                " -> https://github.com/rordenlab/dcm2niix"

                                " to troubleshoot.")

    try:

        output = getoutput("dcm2niix --version")

    except Exception:

        logger.exception("Checking dcm2niix version", exc_info=False)

        return

    else:

        return output.split()[-1]

is_tool⚓︎

1
2
3
def is_tool(
    name
)

Check if a program is in PATH

Parameters:

Name Type Description Default
name string program name None

Returns:

Type Description
None boolean
View Source
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
def is_tool(name):

    """ Check if a program is in PATH

    Args:

        name (string): program name

    Returns:

        boolean

    """

    return which(name) is not None

Last update: 2023-08-31
Created: 2023-08-31