| 1 |
# -*- coding: utf-8 -*- |
| 2 |
# |
| 3 |
# SPDX-FileCopyrightText: 2014 Aurélien Gâteau <[email protected]> |
| 4 |
# |
| 5 |
# SPDX-License-Identifier: BSD-2-Clause |
| 6 |
|
| 7 |
from fnmatch import fnmatch |
| 8 |
import logging |
| 9 |
import os |
| 10 |
import re |
| 11 |
import subprocess |
| 12 |
import shutil |
| 13 |
import sys |
| 14 |
import tempfile |
| 15 |
import requests |
| 16 |
|
| 17 |
|
| 18 |
## @package kapidox.utils |
| 19 |
# |
| 20 |
# Multiple usage utils. |
| 21 |
# |
| 22 |
# This module contains code which is shared between depdiagram-prepare and |
| 23 |
# other components. |
| 24 |
# |
| 25 |
# Code in this dir should not import any module which is not shipped with |
| 26 |
# Python because this module is used by depdiagram-prepare, which must be able |
| 27 |
# to run on builds.kde.org, which may not have all the required dependencies. |
| 28 |
# |
| 29 |
|
| 30 |
|
| 31 |
def setup_logging(): |
| 32 |
FORMAT = '%(asctime)s %(levelname)s %(message)s' |
| 33 |
logging.basicConfig(format=FORMAT, datefmt='%H:%M:%S', level=logging.DEBUG) |
| 34 |
|
| 35 |
|
| 36 |
def tolist(a): |
| 37 |
""" Return a list based on `a`. """ |
| 38 |
return a if type(a) is list else [a] |
| 39 |
|
| 40 |
|
| 41 |
def serialize_name(name): |
| 42 |
""" Return a serialized name. |
| 43 |
|
| 44 |
For now it only replaces ' ' with '_' and lower the letters. |
| 45 |
""" |
| 46 |
if name is not None: |
| 47 |
return '_'.join(name.lower().split(' ')) |
| 48 |
else: |
| 49 |
return None |
| 50 |
|
| 51 |
|
| 52 |
def set_repopath(id): |
| 53 |
""" Return the repopath for the repo id, queried from projects.kde.org |
| 54 |
|
| 55 |
Args: |
| 56 |
id: unique KDE repo identifier |
| 57 |
""" |
| 58 |
if id is None: |
| 59 |
return None |
| 60 |
|
| 61 |
try: |
| 62 |
r = requests.get('https://projects.kde.org/api/v1/identifier/' + id) |
| 63 |
return r.json()['repo'] |
| 64 |
except Exception as exc: |
| 65 |
# Catch all exceptions here: whatever fails in this function should not |
| 66 |
# cause the code to fail |
| 67 |
logging.warning(f"Failed to get repository url for {id!r} from projects.kde.org: {exc}") |
| 68 |
# This means there is no canonical repo identifier for this repo: |
| 69 |
# generally that means that the repo was checked out into a non- |
| 70 |
# canonical pathname. E.g. kitemviews checked out into a directory |
| 71 |
# called KItemViews or kitemviews.git, anything other than |
| 72 |
# kitemviews is not recognized. |
| 73 |
return None |
| 74 |
|
| 75 |
|
| 76 |
def set_maintainers(maintainer_keys, all_maintainers): |
| 77 |
""" Expend the name of the maintainers. |
| 78 |
|
| 79 |
Args: |
| 80 |
maintainer_keys: (string) Key of the dictionary where the name to expend is saved. |
| 81 |
all_maintainers: (dict of dict) Look-up table where the names and emails of |
| 82 |
the maintainers are stored. |
| 83 |
|
| 84 |
Examples: |
| 85 |
>>> maintainer_keys = ['arthur', 'toto'] |
| 86 |
|
| 87 |
>>> myteam = {'arthur': {'name': 'Arthur Pendragon', |
| 88 |
'email': '[email protected]'}, |
| 89 |
'toto': {'name': 'Toto', |
| 90 |
'email: '[email protected]'} |
| 91 |
} |
| 92 |
|
| 93 |
>>> set_maintainers(maintainer_keys, all_maintainers) |
| 94 |
""" |
| 95 |
|
| 96 |
if not maintainer_keys: |
| 97 |
maintainers = [] |
| 98 |
elif isinstance(maintainer_keys, list): |
| 99 |
maintainers = map(lambda x: all_maintainers.get(x, None), |
| 100 |
maintainer_keys) |
| 101 |
else: |
| 102 |
maintainers = [all_maintainers.get(maintainer_keys, None)] |
| 103 |
|
| 104 |
maintainers = [x for x in maintainers if x is not None] |
| 105 |
return maintainers |
| 106 |
|
| 107 |
|
| 108 |
def parse_fancyname(fw_dir): |
| 109 |
"""Return the framework name for a given source dir |
| 110 |
|
| 111 |
The framework name is the name of the toplevel CMake project |
| 112 |
""" |
| 113 |
cmakelists_path = os.path.join(fw_dir, "CMakeLists.txt") |
| 114 |
if not os.path.exists(cmakelists_path): |
| 115 |
for f in os.listdir(fw_dir): |
| 116 |
if ".qbs" in f and "Test" not in f: |
| 117 |
return f[:-4] |
| 118 |
logging.error(f"No CMakeLists.txt in {fw_dir}") |
| 119 |
return None |
| 120 |
project_re = re.compile(r"^\s*project\s*\(\s*([\w\-_]+)", re.I | re.M) |
| 121 |
with open(cmakelists_path) as f: |
| 122 |
cmakelists_content = f.read() |
| 123 |
match = project_re.search(cmakelists_content) |
| 124 |
if match: |
| 125 |
return match.group(1) |
| 126 |
|
| 127 |
logging.error(f"Failed to find framework name: Could not find a 'project()' command in {cmakelists_path}.") |
| 128 |
return None |
| 129 |
|
| 130 |
|
| 131 |
def cache_dir(): |
| 132 |
"""Find/create a semi-long-term cache directory. |
| 133 |
|
| 134 |
We do not use tempdir, except as a fallback, because temporary directories |
| 135 |
are intended for files that only last for the program's execution. |
| 136 |
""" |
| 137 |
cachedir = None |
| 138 |
if sys.platform == 'darwin': |
| 139 |
try: |
| 140 |
from AppKit import NSSearchPathForDirectoriesInDomains |
| 141 |
# http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html#//apple_ref/c/func/NSSearchPathForDirectoriesInDomains |
| 142 |
# NSApplicationSupportDirectory = 14 |
| 143 |
# NSUserDomainMask = 1 |
| 144 |
# True for expanding the tilde into a fully qualified path |
| 145 |
cachedir = os.path.join( |
| 146 |
NSSearchPathForDirectoriesInDomains(14, 1, True)[0], |
| 147 |
'KApiDox') |
| 148 |
except: |
| 149 |
pass |
| 150 |
elif os.name == "posix": |
| 151 |
if 'HOME' in os.environ and os.path.exists(os.environ['HOME']): |
| 152 |
cachedir = os.path.join(os.environ['HOME'], '.cache', 'kapidox') |
| 153 |
elif os.name == "nt": |
| 154 |
if 'APPDATA' in os.environ and os.path.exists(os.environ['APPDATA']): |
| 155 |
cachedir = os.path.join(os.environ['APPDATA'], 'KApiDox') |
| 156 |
if cachedir is None: |
| 157 |
cachedir = os.path.join(tempfile.gettempdir(), 'kapidox') |
| 158 |
if not os.path.isdir(cachedir): |
| 159 |
os.makedirs(cachedir) |
| 160 |
return cachedir |
| 161 |
|
| 162 |
|
| 163 |
def svn_export(remote, local, overwrite=False): |
| 164 |
"""Wraps svn export. |
| 165 |
|
| 166 |
Args: |
| 167 |
remote: (string) the remote url. |
| 168 |
local: (string) the local path where to download. |
| 169 |
overwrite: (bool) whether to overwrite `local` or not. (optional, |
| 170 |
default = False) |
| 171 |
|
| 172 |
Returns: |
| 173 |
True if success. |
| 174 |
|
| 175 |
Raises: |
| 176 |
FileNotFoundError: |
| 177 |
subprocess.CalledProcessError: |
| 178 |
""" |
| 179 |
try: |
| 180 |
import svn.core |
| 181 |
import svn.client |
| 182 |
logging.debug("Using Python libsvn bindings to fetch %s", remote) |
| 183 |
ctx = svn.client.create_context() |
| 184 |
ctx.auth_baton = svn.core.svn_auth_open([]) |
| 185 |
|
| 186 |
latest = svn.core.svn_opt_revision_t() |
| 187 |
latest.type = svn.core.svn_opt_revision_head |
| 188 |
|
| 189 |
svn.client.export(remote, local, latest, True, ctx) |
| 190 |
except ImportError: |
| 191 |
logging.debug("Using external svn client to fetch %s", remote) |
| 192 |
cmd = ['svn', 'export', '--quiet'] |
| 193 |
if overwrite: |
| 194 |
cmd.append('--force') |
| 195 |
cmd += [remote, local] |
| 196 |
try: |
| 197 |
subprocess.check_call(cmd, stderr=subprocess.STDOUT) |
| 198 |
except subprocess.CalledProcessError as e: |
| 199 |
raise subprocess.StandardException(e.output) |
| 200 |
except FileNotFoundError as e: |
| 201 |
logging.debug("External svn client not found") |
| 202 |
return False |
| 203 |
# subversion will set the timestamp to match the server |
| 204 |
os.utime(local, None) |
| 205 |
return True |
| 206 |
|
| 207 |
|
| 208 |
def copy_dir_contents(directory, dest): |
| 209 |
"""Copy the contents of a directory |
| 210 |
|
| 211 |
Args: |
| 212 |
directory: (string) the directory to copy the contents of. |
| 213 |
dest: (string) the directory to copy them into. |
| 214 |
""" |
| 215 |
ignored = ['CMakeLists.txt'] |
| 216 |
ignore = shutil.ignore_patterns(*ignored) |
| 217 |
for fn in os.listdir(directory): |
| 218 |
f = os.path.join(directory, fn) |
| 219 |
if os.path.isfile(f): |
| 220 |
docopy = True |
| 221 |
for i in ignored: |
| 222 |
if fnmatch(fn, i): |
| 223 |
docopy = False |
| 224 |
break |
| 225 |
if docopy: |
| 226 |
shutil.copy(f, dest) |
| 227 |
elif os.path.isdir(f): |
| 228 |
dest_f = os.path.join(dest, fn) |
| 229 |
if os.path.isdir(dest_f): |
| 230 |
shutil.rmtree(dest_f) |
| 231 |
shutil.copytree(f, dest_f, ignore=ignore) |
| 232 |
|
| 233 |
|
| 234 |
_KAPIDOX_VERSION = None |
| 235 |
|
| 236 |
|
| 237 |
def get_kapidox_version(): |
| 238 |
"""Get commit id of running code if it is running from git repository. |
| 239 |
|
| 240 |
May return an empty string if it failed to extract the commit id. |
| 241 |
|
| 242 |
Assumes .git/HEAD looks like this: |
| 243 |
|
| 244 |
ref: refs/heads/master |
| 245 |
|
| 246 |
and assumes .git/refs/heads/master contains the commit id |
| 247 |
""" |
| 248 |
global _KAPIDOX_VERSION |
| 249 |
|
| 250 |
if _KAPIDOX_VERSION is not None: |
| 251 |
return _KAPIDOX_VERSION |
| 252 |
|
| 253 |
_KAPIDOX_VERSION = "" |
| 254 |
bin_dir = os.path.dirname(sys.argv[0]) |
| 255 |
git_dir = os.path.join(bin_dir, "..", ".git") |
| 256 |
if not os.path.isdir(git_dir): |
| 257 |
# Looks like we are not running from the git repo, exit silently |
| 258 |
return _KAPIDOX_VERSION |
| 259 |
|
| 260 |
git_HEAD = os.path.join(git_dir, "HEAD") |
| 261 |
if not os.path.isfile(git_HEAD): |
| 262 |
logging.warning(f'Getting git info failed: {git_HEAD} is not a file') |
| 263 |
return _KAPIDOX_VERSION |
| 264 |
|
| 265 |
try: |
| 266 |
line = open(git_HEAD).readline() |
| 267 |
ref_name = line.split(": ")[1].strip() |
| 268 |
with open(os.path.join(git_dir, ref_name)) as f: |
| 269 |
_KAPIDOX_VERSION = f.read().strip() |
| 270 |
except Exception as exc: |
| 271 |
# Catch all exceptions here: whatever fails in this function should not |
| 272 |
# cause the code to fail |
| 273 |
logging.warning(f'Getting git info failed: {exc}') |
| 274 |
return _KAPIDOX_VERSION |
| 275 |
|
| 276 |
|
| 277 |
def find_dot_files(dot_dir): |
| 278 |
"""Returns a list of path to files ending with .dot in subdirs of `dot_dir`.""" |
| 279 |
lst = [] |
| 280 |
for (root, dirs, files) in os.walk(dot_dir): |
| 281 |
lst.extend([os.path.join(root, x) for x in files if x.endswith('.dot')]) |
| 282 |
return lst |