LIMA
Libre Multilingual Analyzer — C++ API
Loading...
Searching...
No Matches
FileUtils.cpp
Go to the documentation of this file.
1// Copyright 2015 CEA LIST
2// SPDX-FileCopyrightText: 2022 CEA LIST <gael.de-chalendar@cea.fr>
3//
4// SPDX-License-Identifier: MIT
5
6/************************************************************************
7 * @file FileUtils.h
8 * @author Gael de Chalendar
9 * @date Tue Jul 7 2015
10 * copyright Copyright (C) 2015 by CEA LIST
11 ***********************************************************************/
12
13#include "FileUtils.h"
14
15#include <QFileInfo>
16#include <QDir>
17#include <QStandardPaths>
18
19#ifdef Q_OS_WIN
20#include <windows.h>
21#elif defined(Q_OS_MACOS)
22#include <dlfcn.h>
23#endif
24
25namespace Lima {
26namespace Common {
27namespace Misc {
28
29uint64_t countLines(std::istream& file)
30{
31 uint64_t result = 0;
32 std::streampos initialPosition = file.tellg();
33 int c = file.get();
34 while (c != -1)
35 {
36 while (c != -1 && c != '\n')
37 {
38 c = file.get();
39 }
40 result = result + 1;
41 c = file.get();
42 }
43 file.clear();
44 file.seekg(initialPosition, std::ios_base::beg);
45 return result;
46}
47
48uint64_t countLines(QFile& file)
49{
50 uint64_t result = 0;
51 qint64 initialPosition = file.pos();
52 char c = '\0';
53 while (!file.atEnd())
54 {
55 while (!file.atEnd() && c != '\n')
56 {
57 file.getChar(&c);
58 }
59 result = result + 1;
60 file.getChar(&c);
61 }
62 file.seek(initialPosition);
63 return result;
64}
65
66// Appends paths from source to target if following conditions are met:
67// - path isn't empty
68// - path isn't appended previously
69// - path exists
70void appendNonEmptyDirs(QStringList& target, const QStringList& source)
71{
72 for (const auto& path: source)
73 {
74 if ( !path.isEmpty() && !target.contains(path) && QDir(path).exists() )
75 {
76 target << path;
77 }
78 }
79}
80
81QString getEnvVar(const QString& name)
82{
83 return QString::fromUtf8(qgetenv((name.toUpper()).toStdString().c_str()).constData());
84}
85
86QString getDataHome()
87{
88 QString dataHome = QString::fromUtf8(qgetenv("XDG_DATA_HOME"));
89 if (dataHome.isEmpty())
90 {
91#ifdef Q_OS_WIN
92 // As Python's os.path.expanduser (used by lima_models.py to install the
93 // models): HOME is usually not set on Windows.
94 dataHome = QString::fromUtf8(qgetenv("USERPROFILE"));
95#else
96 dataHome = QString::fromUtf8(qgetenv("HOME"));
97#endif
98 if (!dataHome.isEmpty())
99 {
100 dataHome += "/.local/share/";
101 }
102 }
103 return dataHome;
104}
105
106// Appends path in case it exists. Otherwise appends alt_path
107void appendFirstOrSecond(QStringList& target, const QString& path, const QString& alt_path)
108{
109 if ( QDir( path ).exists() )
110 {
111 appendNonEmptyDirs(target, QStringList(path));
112 }
113 else
114 {
115 appendNonEmptyDirs(target, QStringList(alt_path));
116 }
117}
118
119// Install prefix deduced from the location of this library
120// (<prefix>/bin/lima-common-tools.dll, <prefix>/lib/liblima-common-tools.dylib),
121// or an empty string. Used on Windows and macOS, where LIMA is not installed in
122// a system location like /usr, so that an installed LIMA
123// works without LIMA_CONF/LIMA_RESOURCES, whatever the executable (e.g. the
124// Python interpreter for the Python bindings).
126{
127#ifdef Q_OS_WIN
128 HMODULE module = nullptr;
129 if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
130 | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
131 reinterpret_cast<LPCWSTR>(&libraryInstallPrefix),
132 &module))
133 {
134 wchar_t path[4096];
135 auto length = GetModuleFileNameW(module, path, sizeof(path) / sizeof(path[0]));
136 if (length > 0 && length < sizeof(path) / sizeof(path[0]))
137 {
138 QDir binDir = QFileInfo(QString::fromWCharArray(path, length)).absoluteDir();
139 return QDir::cleanPath(binDir.absoluteFilePath(".."));
140 }
141 }
142#elif defined(Q_OS_MACOS)
143 // <prefix>/lib/liblima-common-tools.dylib
144 Dl_info info;
145 if (dladdr(reinterpret_cast<const void*>(&libraryInstallPrefix), &info) != 0
146 && info.dli_fname != nullptr)
147 {
148 QDir libDir = QFileInfo(QString::fromUtf8(info.dli_fname)).absoluteDir();
149 return QDir::cleanPath(libDir.absoluteFilePath(".."));
150 }
151#endif
152 return QString();
153}
154
155// Appends the project directory under $<PROJECT>_DIST if it exists, else
156// under the install prefix of this library (Windows) if it exists, else under
157// /usr.
158void appendFirstOrSecondForProject(QStringList& target,
159 const QString& project,
160 const QString& path_prefix,
161 const QString& path_postfix = QString(""))
162{
163 QString systemPath = QString::fromUtf8("/usr/") + path_prefix + project + path_postfix;
164 QString prefix = libraryInstallPrefix();
165 if (!prefix.isEmpty()
166 && QDir(prefix + path_prefix + project + path_postfix).exists())
167 {
168 systemPath = prefix + path_prefix + project + path_postfix;
169 }
170 appendFirstOrSecond(target,
171 getEnvVar(project + "_DIST") + path_prefix + project + path_postfix,
172 systemPath);
173}
174
175void buildDirectoriesListForProject(QStringList& target,
176 const QString& project,
177 const QString& env_postfix, // "_CONF" or "_RESOURCES"
178 const QString& path_prefix, // "/share/config/" or "/share/apps"
179 const QString& path_postfix = QString("") // "" or "/resources
180 )
181{
182 QStringList dirs;
183 QString var = getEnvVar(project + env_postfix);
184 if ( !var.isEmpty() )
185 {
186 dirs << var.split(LIMA_PATH_SEPARATOR);
187 }
188
189 appendNonEmptyDirs(target, dirs);
190
191 if ( dirs.isEmpty() )
192 {
193 appendFirstOrSecondForProject(target, project, path_prefix, path_postfix);
194 }
195
196}
197
198QStringList buildConfigurationDirectoriesList(const QStringList& projects,
199 const QStringList& paths)
200{
201 // qDebug() << "buildConfigurationDirectoriesList" << projects << paths;
202 QStringList configDirs;
203
204 // 1. Add the paths explicitly given
205 appendNonEmptyDirs(configDirs, paths);
206
207 // 2. Add dirs from LIMA_CONF if no project is given
208 if (projects.empty())
209 {
210 QString var = getEnvVar(QString::fromStdString("lima") + "_CONF");
211 if ( !var.isEmpty() )
212 {
213 configDirs << var.split(LIMA_PATH_SEPARATOR);
214 }
215 }
216 else
217 {
218 // 3. Add dirs from each PROJECT_CONF
219 for (const auto& project: projects)
220 {
221 QString var = getEnvVar(project.toUpper() + "_CONF");
222 if ( !var.isEmpty() )
223 {
224 configDirs << var.split(LIMA_PATH_SEPARATOR);
225 }
226 }
227 }
228 // 4. Add conf dir in XDG_DATA_HOME or ~/.local/share/ after LIMA_CONF but before /usr
229 QString dataHome = getDataHome();
230 appendNonEmptyDirs(configDirs, QStringList(dataHome + "/lima/config/"));
231
232 // 5. Then add the *_CONF for each given project and complete if necessary with *_DIST/… or /usr/…
233 if ( configDirs.isEmpty() )
234 {
235 for (const auto& project: projects)
236 {
237 appendFirstOrSecondForProject(configDirs, project, "/share/config/", "");
238 }
239 }
240
241 QString var = getEnvVar(QString::fromStdString("LIMA_SHOW_CONFIG_PATH"));
242 if ( !var.isEmpty() )
243 {
244 qDebug() << "LIMA Configuration directories list built is:" << configDirs;
245 }
246
247 return configDirs;
248}
249
250QStringList buildResourcesDirectoriesList(const QStringList& projects,
251 const QStringList& paths)
252{
253 // qDebug() << "buildResourcesDirectoriesList" << projects << paths;
254 QStringList resourcesDirs;
255 QString dataHome = getDataHome();
256
257 appendNonEmptyDirs(resourcesDirs, QStringList(dataHome + "/lima/resources/"));
258
259 for (const auto& project: projects)
260 {
261 buildDirectoriesListForProject(resourcesDirs, project, "_RESOURCES",
262 "/share/apps/", "/resources");
263 }
264
265 appendNonEmptyDirs(resourcesDirs, paths);
266
267 QString var = getEnvVar(QString::fromStdString("LIMA_SHOW_CONFIG_PATH"));
268 if ( !var.isEmpty() )
269 {
270 qDebug() << "LIMA Resources directories list built is:" << resourcesDirs;
271 }
273 LINFO << "LIMA Resources directories list built is:" << resourcesDirs;
274 return resourcesDirs;
275}
276
277QString findFileInPaths(const QString& paths, const QString& fileName, const QChar& separator)
278{
279 auto pathsList = paths.split(separator);
280 auto filesList =fileName.split(separator);
281 for (const auto& path: pathsList)
282 {
283 for (const auto& file: filesList)
284 {
285 if (QFileInfo::exists(path + "/" + file))
286 {
287 #ifndef WIN32 // Windows do not support circular dependency between qslog and tools libraries
288 {
290 LDEBUG << "File found:" << path + "/" + file;
291 }
292 #endif
293 return path + "/" + file;
294 }
295 }
296 }
298 LINFO << "findFileInPaths no '" << fileName << "' found in '" << paths
299 << "' separated by '" << separator << "'";
300 return QString();
301}
302
303
304} // end namespace
305} // end namespace
306} // end namespace
#define FILESREPORTLOGINIT
Definition FileUtils.h:28
#define LIMA_PATH_SEPARATOR
Definition FileUtils.h:25
#define LDEBUG
Definition LimaCommon.h:157
#define LINFO
Definition LimaCommon.h:158
QString libraryInstallPrefix()
void buildDirectoriesListForProject(QStringList &target, const QString &project, const QString &env_postfix, const QString &path_prefix, const QString &path_postfix=QString(""))
void appendFirstOrSecondForProject(QStringList &target, const QString &project, const QString &path_prefix, const QString &path_postfix=QString(""))
QString getEnvVar(const QString &name)
Definition FileUtils.cpp:81
QStringList buildResourcesDirectoriesList(const QStringList &projects, const QStringList &paths)
Build a list of resources directories from a list of project names and a list of paths.
QString getDataHome()
Definition FileUtils.cpp:86
void appendFirstOrSecond(QStringList &target, const QString &path, const QString &alt_path)
uint64_t countLines(std::istream &file)
Count the number of lines in the given file from the current position.
Definition FileUtils.cpp:29
void appendNonEmptyDirs(QStringList &target, const QStringList &source)
Definition FileUtils.cpp:70
QString findFileInPaths(const QString &paths, const QString &fileName, const QChar &separator)
Find the given file in the given paths.
QStringList buildConfigurationDirectoriesList(const QStringList &projects, const QStringList &paths)
Build a list of configuration directories from a list of project names and a list of paths.
NAUTITIA.