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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
# -*- coding: utf-8 -*-

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

import logging

import json

import time

from pathlib import Path

from urllib import error, request

from subprocess import getoutput

from shutil import which

from dcm2bids.version import __version__

from dcm2bids.utils.io import load_json, save_json

logger = logging.getLogger(__name__)

# How long a cached "latest version" is considered valid (seconds)

LATEST_VERSION_CACHE_TTL = 24 * 60 * 60  # 24 hours

def _version_cache_path(log_dir):

    """

    Return the path to the JSON file used to cache version check results

    inside the given log directory.

    """

    log_dir = Path(log_dir)

    return log_dir / "version_check.json"

def load_version_cache(log_dir):

    """

    Load the JSON cache of previous version checks from the given log directory.

    """

    path = _version_cache_path(log_dir)

    if not path.exists():

        return {}

    try:

        return load_json(path)

    except Exception:

        logger.debug(

            "Failed to read version cache; ignoring corrupted cache.",

            exc_info=True,

        )

        return {}

def save_version_cache(cache, log_dir) -> None:

    """

    Save the JSON cache of previous version checks to the given log directory.

    """

    path = _version_cache_path(log_dir)

    try:

        save_json(filename=path, data=cache)

    except Exception:

        logger.debug("Failed to write version cache; ignoring.", exc_info=True)

def normalize_version(value):

    """

    Normalize a version string into a tuple of integer parts, when possible.

    - Strips a leading 'v' (e.g. 'v1.11.0' -> '1.11.0')

    - Splits on '.'

    - Converts each part to int if possible

    - Returns the original value if it cannot be parsed in a simple numeric form

    """

    if not isinstance(value, str):

        return value

    s = value.strip()

    if not s:

        return value

    # BIDS tag style: v1.2.3

    s = s.lstrip("v")

    parts = s.split(".")

    normalized = []

    for p in parts:

        p = p.strip()

        if not p:

            # Empty segment; treat as zero

            normalized.append(0)

            continue

        try:

            normalized.append(int(p))

        except ValueError:

            # If any part is not numeric, bail return the original string

            return value

    return tuple(normalized)

def version_newer(latest, current):

    """

    Compare two versions, preferring normalized numeric comparison

    and falling back to string comparison.

    Returns True if `latest` is considered newer than `current`.

    """

    norm_latest = normalize_version(latest)

    norm_current = normalize_version(current)

    if isinstance(norm_latest, tuple) and isinstance(norm_current, tuple):

        # Padding to compare same length

        max_len = max(len(norm_latest), len(norm_current))

        norm_latest += (0,) * (max_len - len(norm_latest))

        norm_current += (0,) * (max_len - len(norm_current))

        return norm_latest > norm_current

    # Fallback: string comparison as before

    return str(latest) > str(current)

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 has_internet(timeout=3):

    """

    Check if the machine appears to have internet access by trying to reach api.github.com.

    Returns:

        bool: True if an external host can be reached, False otherwise.

    """

    req = request.Request("https://api.github.com", method="HEAD")

    try:

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

        status_ok = 200 <= response.getcode() < 400

        # Log at debug level to not spam

        logger.debug("has_internet status: %s", response.getcode())

        return status_ok

    except error.URLError as e:

        logger.warning(

            "No access to internet, GitHub or Read the Docs API. "

            "Check if there is an issue with your network/proxy/DNS. "

            "Skipping version check."

        )

        logger.debug("URLError: %s", e)

    except TimeoutError as e:

        logger.warning(

            "Timeout error, no access to internet or to GitHub or Read the Docs API: %s. "

            "Check if there is an issue with your network/proxy.",

            e,

        )

    return False

def check_github_latest(github_repo, timeout=3):

    """

    Check the latest version of a GitHub repository. Returns error if host can't be reached.

    Since has_internet() is used upstream, it would mean that host is unreachable but

    internet is ok.

    Args:

        github_repo (str): a GitHub repository ("username/repository")

        timeout (int): time in seconds

    Returns:

        str: latest release tag, or "unavailable" if the check could not be performed

    """

    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.debug(

            "Could not reach GitHub to verify latest version of %s. "

            "Skipping version check. (HTTPError: %s)",

            github_repo,

            e,

        )

        return "unavailable"

    except Exception:

        # Any other unexpected error in this specific request.

        logger.debug(

            "Checking latest version of %s was not possible due to an unexpected error.",

            github_repo,

        )

        logger.debug(

            "Unexpected exception while querying GitHub latest release",

            exc_info=True,

        )

        return "unavailable"

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

    return content.get("tag_name", "unavailable")

def check_latest(name="dcm2bids", log_dir=None):

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

    Implemented for dcm2bids and dcm2niix.

    Args:

        name (str): name of the software

        log_dir (str or Path, optional): directory where logs are written.

            If provided, a small JSON cache of version checks is stored there.

    """

    data = {

        "dcm2bids": {

            "repo": "UNFmontreal/Dcm2Bids",

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

            "current": __version__,

        },

        "dcm2niix": {

            "repo": "rordenlab/dcm2niix",

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

            "current": dcm2niix_version,

        },

    }

    info = data.get(name)

    if info is None:

        logger.debug("Version check: unknown software name '%s'; skipping.", name)

        return

    repo = info["repo"]

    host = info["host"]

    current = info["current"]

    if callable(current):

        current = current()

    logger.debug(

        "Version check: name=%s, current=%s, repo=%s, log_dir=%s",

        name,

        current,

        repo,

        log_dir,

    )

    latest = None

    if log_dir is not None:

        # Try cache first

        cache = load_version_cache(log_dir)

        cache_key = repo  # one entry per GitHub repo

        now = time.time()

        cached_entry = cache.get(cache_key)

        if isinstance(cached_entry, dict):

            ts = cached_entry.get("timestamp", 0)

            age = now - ts

            logger.debug(

                "Version check: found cached entry for %s (age=%.1fs, ttl=%ds)",

                cache_key,

                age,

                LATEST_VERSION_CACHE_TTL,

            )

            if age < LATEST_VERSION_CACHE_TTL:

                latest = cached_entry.get("latest", "unavailable")

                logger.debug(

                    "Version check: using cached latest=%s for %s", latest, name

                )

        else:

            logger.debug(

                "Version check: no cached entry for %s in %s", cache_key, log_dir

            )

        # If cache is missing/expired/unavailable, we may need to query GitHub.

        if latest is None or latest == "unavailable":

            logger.debug(

                "Version check: cache miss or unavailable for %s; checking internet.",

                name,

            )

            if not has_internet():

                logger.info(

                    "Skipping version check for %s (no internet and no valid cache).",

                    name,

                )

                return

            logger.debug(

                "Version check: internet OK; querying GitHub latest for %s", repo

            )

            latest = check_github_latest(repo)

            cache[cache_key] = {"latest": latest, "timestamp": now}

            save_version_cache(cache, log_dir)

            logger.debug(

                "Version check: updated cache for %s with latest=%s", cache_key, latest

            )

    else:

        # No caching: one-off.

        logger.debug(

            "Version check: no log_dir provided for %s; performing one-off check.",

            name,

        )

        if not has_internet():

            logger.info("Skipping version check for %s (no internet).", name)

            return

        logger.debug(

            "Version check: internet OK; querying GitHub latest for %s", repo

        )

        latest = check_github_latest(repo)

    if latest == "unavailable":

        logger.info("Could not determine latest version of %s (unavailable).", name)

        return

    if version_newer(latest, current):

        logger.warning("A newer version exists for %s: %s", name, latest)

        logger.warning("Consider updating it -> %s/%s.", host, repo)

    else:

        logger.info("Currently using the latest version of %s.", 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
LATEST_VERSION_CACHE_TTL
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. Returns error if host can't be reached.

Since has_internet() is used upstream, it would mean that host is unreachable but internet is ok.

Parameters:

Name Type Description Default
github_repo str a GitHub repository ("username/repository") None
timeout int time in seconds None

Returns:

Type Description
str latest release tag, or "unavailable" if the check could not be performed
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
def check_github_latest(github_repo, timeout=3):

    """

    Check the latest version of a GitHub repository. Returns error if host can't be reached.

    Since has_internet() is used upstream, it would mean that host is unreachable but

    internet is ok.

    Args:

        github_repo (str): a GitHub repository ("username/repository")

        timeout (int): time in seconds

    Returns:

        str: latest release tag, or "unavailable" if the check could not be performed

    """

    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.debug(

            "Could not reach GitHub to verify latest version of %s. "

            "Skipping version check. (HTTPError: %s)",

            github_repo,

            e,

        )

        return "unavailable"

    except Exception:

        # Any other unexpected error in this specific request.

        logger.debug(

            "Checking latest version of %s was not possible due to an unexpected error.",

            github_repo,

        )

        logger.debug(

            "Unexpected exception while querying GitHub latest release",

            exc_info=True,

        )

        return "unavailable"

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

    return content.get("tag_name", "unavailable")

check_latest⚓︎

1
2
3
4
def check_latest(
    name='dcm2bids',
    log_dir=None
)

Check if a new version of a software exists and log some details.

Implemented for dcm2bids and dcm2niix.

Parameters:

Name Type Description Default
name str name of the software None
log_dir str or Path directory where logs are written.
If provided, a small JSON cache of version checks is stored there.
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
 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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
def check_latest(name="dcm2bids", log_dir=None):

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

    Implemented for dcm2bids and dcm2niix.

    Args:

        name (str): name of the software

        log_dir (str or Path, optional): directory where logs are written.

            If provided, a small JSON cache of version checks is stored there.

    """

    data = {

        "dcm2bids": {

            "repo": "UNFmontreal/Dcm2Bids",

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

            "current": __version__,

        },

        "dcm2niix": {

            "repo": "rordenlab/dcm2niix",

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

            "current": dcm2niix_version,

        },

    }

    info = data.get(name)

    if info is None:

        logger.debug("Version check: unknown software name '%s'; skipping.", name)

        return

    repo = info["repo"]

    host = info["host"]

    current = info["current"]

    if callable(current):

        current = current()

    logger.debug(

        "Version check: name=%s, current=%s, repo=%s, log_dir=%s",

        name,

        current,

        repo,

        log_dir,

    )

    latest = None

    if log_dir is not None:

        # Try cache first

        cache = load_version_cache(log_dir)

        cache_key = repo  # one entry per GitHub repo

        now = time.time()

        cached_entry = cache.get(cache_key)

        if isinstance(cached_entry, dict):

            ts = cached_entry.get("timestamp", 0)

            age = now - ts

            logger.debug(

                "Version check: found cached entry for %s (age=%.1fs, ttl=%ds)",

                cache_key,

                age,

                LATEST_VERSION_CACHE_TTL,

            )

            if age < LATEST_VERSION_CACHE_TTL:

                latest = cached_entry.get("latest", "unavailable")

                logger.debug(

                    "Version check: using cached latest=%s for %s", latest, name

                )

        else:

            logger.debug(

                "Version check: no cached entry for %s in %s", cache_key, log_dir

            )

        # If cache is missing/expired/unavailable, we may need to query GitHub.

        if latest is None or latest == "unavailable":

            logger.debug(

                "Version check: cache miss or unavailable for %s; checking internet.",

                name,

            )

            if not has_internet():

                logger.info(

                    "Skipping version check for %s (no internet and no valid cache).",

                    name,

                )

                return

            logger.debug(

                "Version check: internet OK; querying GitHub latest for %s", repo

            )

            latest = check_github_latest(repo)

            cache[cache_key] = {"latest": latest, "timestamp": now}

            save_version_cache(cache, log_dir)

            logger.debug(

                "Version check: updated cache for %s with latest=%s", cache_key, latest

            )

    else:

        # No caching: one-off.

        logger.debug(

            "Version check: no log_dir provided for %s; performing one-off check.",

            name,

        )

        if not has_internet():

            logger.info("Skipping version check for %s (no internet).", name)

            return

        logger.debug(

            "Version check: internet OK; querying GitHub latest for %s", repo

        )

        latest = check_github_latest(repo)

    if latest == "unavailable":

        logger.info("Could not determine latest version of %s (unavailable).", name)

        return

    if version_newer(latest, current):

        logger.warning("A newer version exists for %s: %s", name, latest)

        logger.warning("Consider updating it -> %s/%s.", host, repo)

    else:

        logger.info("Currently using the latest version of %s.", 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]

has_internet⚓︎

1
2
3
def has_internet(
    timeout=3
)

Check if the machine appears to have internet access by trying to reach api.github.com.

Returns:

Type Description
bool True if an external host can be reached, False otherwise.
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 has_internet(timeout=3):

    """

    Check if the machine appears to have internet access by trying to reach api.github.com.

    Returns:

        bool: True if an external host can be reached, False otherwise.

    """

    req = request.Request("https://api.github.com", method="HEAD")

    try:

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

        status_ok = 200 <= response.getcode() < 400

        # Log at debug level to not spam

        logger.debug("has_internet status: %s", response.getcode())

        return status_ok

    except error.URLError as e:

        logger.warning(

            "No access to internet, GitHub or Read the Docs API. "

            "Check if there is an issue with your network/proxy/DNS. "

            "Skipping version check."

        )

        logger.debug("URLError: %s", e)

    except TimeoutError as e:

        logger.warning(

            "Timeout error, no access to internet or to GitHub or Read the Docs API: %s. "

            "Check if there is an issue with your network/proxy.",

            e,

        )

    return False

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

load_version_cache⚓︎

1
2
3
def load_version_cache(
    log_dir
)

Load the JSON cache of previous version checks from the given log directory.

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
def load_version_cache(log_dir):

    """

    Load the JSON cache of previous version checks from the given log directory.

    """

    path = _version_cache_path(log_dir)

    if not path.exists():

        return {}

    try:

        return load_json(path)

    except Exception:

        logger.debug(

            "Failed to read version cache; ignoring corrupted cache.",

            exc_info=True,

        )

        return {}

normalize_version⚓︎

1
2
3
def normalize_version(
    value
)

Normalize a version string into a tuple of integer parts, when possible.

  • Strips a leading 'v' (e.g. 'v1.11.0' -> '1.11.0')
  • Splits on '.'
  • Converts each part to int if possible
  • Returns the original value if it cannot be parsed in a simple numeric form
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
def normalize_version(value):

    """

    Normalize a version string into a tuple of integer parts, when possible.

    - Strips a leading 'v' (e.g. 'v1.11.0' -> '1.11.0')

    - Splits on '.'

    - Converts each part to int if possible

    - Returns the original value if it cannot be parsed in a simple numeric form

    """

    if not isinstance(value, str):

        return value

    s = value.strip()

    if not s:

        return value

    # BIDS tag style: v1.2.3

    s = s.lstrip("v")

    parts = s.split(".")

    normalized = []

    for p in parts:

        p = p.strip()

        if not p:

            # Empty segment; treat as zero

            normalized.append(0)

            continue

        try:

            normalized.append(int(p))

        except ValueError:

            # If any part is not numeric, bail return the original string

            return value

    return tuple(normalized)

save_version_cache⚓︎

1
2
3
4
def save_version_cache(
    cache,
    log_dir
) -> None

Save the JSON cache of previous version checks to the given log directory.

View Source
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
def save_version_cache(cache, log_dir) -> None:

    """

    Save the JSON cache of previous version checks to the given log directory.

    """

    path = _version_cache_path(log_dir)

    try:

        save_json(filename=path, data=cache)

    except Exception:

        logger.debug("Failed to write version cache; ignoring.", exc_info=True)

version_newer⚓︎

1
2
3
4
def version_newer(
    latest,
    current
)

Compare two versions, preferring normalized numeric comparison

and falling back to string comparison.

Returns True if latest is considered newer than current.

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
def version_newer(latest, current):

    """

    Compare two versions, preferring normalized numeric comparison

    and falling back to string comparison.

    Returns True if `latest` is considered newer than `current`.

    """

    norm_latest = normalize_version(latest)

    norm_current = normalize_version(current)

    if isinstance(norm_latest, tuple) and isinstance(norm_current, tuple):

        # Padding to compare same length

        max_len = max(len(norm_latest), len(norm_current))

        norm_latest += (0,) * (max_len - len(norm_latest))

        norm_current += (0,) * (max_len - len(norm_current))

        return norm_latest > norm_current

    # Fallback: string comparison as before

    return str(latest) > str(current)