[libcalamares] Apply current coding style to libcalamares/utils/

- String.cpp needs special handling since part of it should
   remain unchanged, the formatting is "special" there.
This commit is contained in:
Adriaan de Groot 2019-08-04 21:22:54 +02:00
parent 29b9a21f59
commit b8a74657f4
20 changed files with 623 additions and 496 deletions

View File

@ -19,10 +19,10 @@
#include "CalamaresUtilsSystem.h"
#include "utils/Logger.h"
#include "GlobalStorage.h"
#include "JobQueue.h"
#include "Settings.h"
#include "utils/Logger.h"
#include <QCoreApplication>
#include <QDir>
@ -34,8 +34,8 @@
#endif
#ifdef Q_OS_FREEBSD
#include <sys/types.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#endif
/** @brief When logging commands, don't log everything.
@ -48,12 +48,12 @@
struct RedactedList
{
RedactedList( const QStringList& l )
: list(l)
: list( l )
{
}
const QStringList& list;
} ;
};
QDebug&
operator<<( QDebug& s, const RedactedList& l )
@ -63,12 +63,18 @@ operator<<( QDebug& s, const RedactedList& l )
{
for ( const auto& item : l.list )
if ( item.startsWith( "$6$" ) )
{
s << "<password>";
}
else
{
s << item;
}
}
else
{
s << l.list;
}
return s;
}
@ -92,8 +98,7 @@ System::System( bool doChroot, QObject* parent )
}
System::~System()
{}
System::~System() {}
System*
@ -111,18 +116,22 @@ System::instance()
int
System::mount( const QString& devicePath,
const QString& mountPoint,
const QString& filesystemName,
const QString& options )
const QString& mountPoint,
const QString& filesystemName,
const QString& options )
{
if ( devicePath.isEmpty() || mountPoint.isEmpty() )
{
if ( devicePath.isEmpty() )
{
cWarning() << "Can't mount an empty device.";
}
if ( mountPoint.isEmpty() )
{
cWarning() << "Can't mount on an empty mountpoint.";
}
return static_cast<int>(ProcessResult::Code::NoWorkingDirectory);
return static_cast< int >( ProcessResult::Code::NoWorkingDirectory );
}
QDir mountPointDir( mountPoint );
@ -132,7 +141,7 @@ System::mount( const QString& devicePath,
if ( !ok )
{
cWarning() << "Could not create mountpoint" << mountPoint;
return static_cast<int>(ProcessResult::Code::NoWorkingDirectory);
return static_cast< int >( ProcessResult::Code::NoWorkingDirectory );
}
}
@ -140,28 +149,31 @@ System::mount( const QString& devicePath,
QStringList args = { devicePath, mountPoint };
if ( !filesystemName.isEmpty() )
{
args << "-t" << filesystemName;
}
if ( !options.isEmpty() )
{
args << "-o" << options;
}
return QProcess::execute( program, args );
}
ProcessResult
System::runCommand(
System::RunLocation location,
const QStringList& args,
const QString& workingPath,
const QString& stdInput,
std::chrono::seconds timeoutSec )
System::runCommand( System::RunLocation location,
const QStringList& args,
const QString& workingPath,
const QString& stdInput,
std::chrono::seconds timeoutSec )
{
QString output;
Calamares::GlobalStorage* gs = Calamares::JobQueue::instance() ? Calamares::JobQueue::instance()->globalStorage() : nullptr;
Calamares::GlobalStorage* gs
= Calamares::JobQueue::instance() ? Calamares::JobQueue::instance()->globalStorage() : nullptr;
if ( ( location == System::RunLocation::RunInTarget ) &&
( !gs || !gs->contains( "rootMountPoint" ) ) )
if ( ( location == System::RunLocation::RunInTarget ) && ( !gs || !gs->contains( "rootMountPoint" ) ) )
{
cWarning() << "No rootMountPoint in global storage";
return ProcessResult::Code::NoWorkingDirectory;
@ -197,7 +209,9 @@ System::runCommand(
if ( !workingPath.isEmpty() )
{
if ( QDir( workingPath ).exists() )
{
process.setWorkingDirectory( QDir( workingPath ).absolutePath() );
}
else
{
cWarning() << "Invalid working directory:" << workingPath;
@ -219,10 +233,10 @@ System::runCommand(
}
process.closeWriteChannel();
if ( !process.waitForFinished( timeoutSec > std::chrono::seconds::zero() ? ( std::chrono::milliseconds( timeoutSec ).count() ) : -1 ) )
if ( !process.waitForFinished(
timeoutSec > std::chrono::seconds::zero() ? ( std::chrono::milliseconds( timeoutSec ).count() ) : -1 ) )
{
cWarning().noquote().nospace() << "Timed out. Output so far:\n" <<
process.readAllStandardOutput();
cWarning().noquote().nospace() << "Timed out. Output so far:\n" << process.readAllStandardOutput();
return ProcessResult::Code::TimedOut;
}
@ -242,7 +256,7 @@ System::runCommand(
cDebug() << "Target cmd:" << RedactedList( args );
cDebug().noquote().nospace() << "Target output:\n" << output;
}
return ProcessResult(r, output);
return ProcessResult( r, output );
}
QString
@ -252,7 +266,8 @@ System::targetPath( const QString& path ) const
if ( doChroot() )
{
Calamares::GlobalStorage* gs = Calamares::JobQueue::instance() ? Calamares::JobQueue::instance()->globalStorage() : nullptr;
Calamares::GlobalStorage* gs
= Calamares::JobQueue::instance() ? Calamares::JobQueue::instance()->globalStorage() : nullptr;
if ( !gs || !gs->contains( "rootMountPoint" ) )
{
@ -309,28 +324,32 @@ System::createTargetFile( const QString& path, const QByteArray& contents ) cons
}
QPair<quint64, float>
QPair< quint64, float >
System::getTotalMemoryB() const
{
#ifdef Q_OS_LINUX
struct sysinfo i;
int r = sysinfo( &i );
if (r)
return qMakePair(0, 0.0);
if ( r )
{
return qMakePair( 0, 0.0 );
}
return qMakePair(quint64( i.mem_unit ) * quint64( i.totalram ), 1.1);
return qMakePair( quint64( i.mem_unit ) * quint64( i.totalram ), 1.1 );
#elif defined( Q_OS_FREEBSD )
unsigned long memsize;
size_t s = sizeof(memsize);
size_t s = sizeof( memsize );
int r = sysctlbyname("vm.kmem_size", &memsize, &s, NULL, 0);
if (r)
return qMakePair(0, 0.0);
int r = sysctlbyname( "vm.kmem_size", &memsize, &s, NULL, 0 );
if ( r )
{
return qMakePair( 0, 0.0 );
}
return qMakePair(memsize, 1.01);
return qMakePair( memsize, 1.01 );
#else
return qMakePair(0, 0.0); // Unsupported
return qMakePair( 0, 0.0 ); // Unsupported
#endif
}
@ -341,14 +360,14 @@ System::getCpuDescription() const
QString model;
#ifdef Q_OS_LINUX
QFile file("/proc/cpuinfo");
if ( file.open(QIODevice::ReadOnly | QIODevice::Text) )
QFile file( "/proc/cpuinfo" );
if ( file.open( QIODevice::ReadOnly | QIODevice::Text ) )
while ( !file.atEnd() )
{
QByteArray line = file.readLine();
if ( line.startsWith( "model name" ) && (line.indexOf( ':' ) > 0) )
if ( line.startsWith( "model name" ) && ( line.indexOf( ':' ) > 0 ) )
{
model = QString::fromLatin1( line.right(line.length() - line.indexOf( ':' ) ) );
model = QString::fromLatin1( line.right( line.length() - line.indexOf( ':' ) ) );
break;
}
}
@ -376,40 +395,45 @@ ProcessResult::explainProcess( int ec, const QString& command, const QString& ou
using Calamares::JobResult;
if ( ec == 0 )
{
return JobResult::ok();
}
QString outputMessage = output.isEmpty()
? QCoreApplication::translate( "ProcessResult", "\nThere was no output from the command.")
: (QCoreApplication::translate( "ProcessResult", "\nOutput:\n") + output);
? QCoreApplication::translate( "ProcessResult", "\nThere was no output from the command." )
: ( QCoreApplication::translate( "ProcessResult", "\nOutput:\n" ) + output );
if ( ec == static_cast<int>(ProcessResult::Code::Crashed) ) //Crash!
return JobResult::error( QCoreApplication::translate( "ProcessResult", "External command crashed." ),
QCoreApplication::translate( "ProcessResult", "Command <i>%1</i> crashed." )
.arg( command )
+ outputMessage );
if ( ec == static_cast< int >( ProcessResult::Code::Crashed ) ) //Crash!
return JobResult::error(
QCoreApplication::translate( "ProcessResult", "External command crashed." ),
QCoreApplication::translate( "ProcessResult", "Command <i>%1</i> crashed." ).arg( command )
+ outputMessage );
if ( ec == static_cast<int>(ProcessResult::Code::FailedToStart) )
return JobResult::error( QCoreApplication::translate( "ProcessResult", "External command failed to start." ),
QCoreApplication::translate( "ProcessResult", "Command <i>%1</i> failed to start." )
.arg( command ) );
if ( ec == static_cast< int >( ProcessResult::Code::FailedToStart ) )
return JobResult::error(
QCoreApplication::translate( "ProcessResult", "External command failed to start." ),
QCoreApplication::translate( "ProcessResult", "Command <i>%1</i> failed to start." ).arg( command ) );
if ( ec == static_cast<int>(ProcessResult::Code::NoWorkingDirectory) )
return JobResult::error( QCoreApplication::translate( "ProcessResult", "Internal error when starting command." ),
QCoreApplication::translate( "ProcessResult", "Bad parameters for process job call." ) );
if ( ec == static_cast< int >( ProcessResult::Code::NoWorkingDirectory ) )
return JobResult::error(
QCoreApplication::translate( "ProcessResult", "Internal error when starting command." ),
QCoreApplication::translate( "ProcessResult", "Bad parameters for process job call." ) );
if ( ec == static_cast<int>(ProcessResult::Code::TimedOut) )
return JobResult::error( QCoreApplication::translate( "ProcessResult", "External command failed to finish." ),
QCoreApplication::translate( "ProcessResult", "Command <i>%1</i> failed to finish in %2 seconds." )
.arg( command )
.arg( timeout.count() )
+ outputMessage );
if ( ec == static_cast< int >( ProcessResult::Code::TimedOut ) )
return JobResult::error(
QCoreApplication::translate( "ProcessResult", "External command failed to finish." ),
QCoreApplication::translate( "ProcessResult", "Command <i>%1</i> failed to finish in %2 seconds." )
.arg( command )
.arg( timeout.count() )
+ outputMessage );
//Any other exit code
return JobResult::error( QCoreApplication::translate( "ProcessResult", "External command finished with errors." ),
QCoreApplication::translate( "ProcessResult", "Command <i>%1</i> finished with exit code %2." )
.arg( command )
.arg( ec )
+ outputMessage );
return JobResult::error(
QCoreApplication::translate( "ProcessResult", "External command finished with errors." ),
QCoreApplication::translate( "ProcessResult", "Command <i>%1</i> finished with exit code %2." )
.arg( command )
.arg( ec )
+ outputMessage );
}
} // namespace
} // namespace CalamaresUtils

View File

@ -36,15 +36,21 @@ class ProcessResult : public QPair< int, QString >
public:
enum class Code : int
{
Crashed = -1, // Must match special return values from QProcess
Crashed = -1, // Must match special return values from QProcess
FailedToStart = -2, // Must match special return values from QProcess
NoWorkingDirectory = -3,
TimedOut = -4
} ;
};
/** @brief Implicit one-argument constructor has no output, only a return code */
ProcessResult( Code r ) : QPair< int, QString >( static_cast<int>(r), QString() ) {}
ProcessResult( int r, QString s ) : QPair< int, QString >( r, s ) {}
ProcessResult( Code r )
: QPair< int, QString >( static_cast< int >( r ), QString() )
{
}
ProcessResult( int r, QString s )
: QPair< int, QString >( r, s )
{
}
int getExitCode() const { return first; }
QString getOutput() const { return second; }
@ -62,7 +68,8 @@ public:
* @param timeout Timeout passed to the process runner, for explaining
* error code -4 (timeout).
*/
static Calamares::JobResult explainProcess( int errorCode, const QString& command, const QString& output, std::chrono::seconds timeout );
static Calamares::JobResult
explainProcess( int errorCode, const QString& command, const QString& output, std::chrono::seconds timeout );
/// @brief Convenience wrapper for explainProcess()
inline Calamares::JobResult explainProcess( const QString& command, std::chrono::seconds timeout ) const
@ -75,7 +82,7 @@ public:
{
return explainProcess( getExitCode(), command.join( ' ' ), getOutput(), timeout );
}
} ;
};
/**
* @brief The System class is a singleton with utility functions that perform
@ -116,7 +123,11 @@ public:
/** (Typed) Boolean describing where a particular command should be run,
* whether in the host (live) system or in the (chroot) target system.
*/
enum class RunLocation { RunInHost, RunInTarget };
enum class RunLocation
{
RunInHost,
RunInTarget
};
/**
* Runs the specified command in the chroot of the target system.
@ -135,37 +146,31 @@ public:
* NoWorkingDirectory = bad arguments
* TimedOut = QProcess timeout
*/
static DLLEXPORT ProcessResult runCommand(
RunLocation location,
const QStringList &args,
const QString& workingPath = QString(),
const QString& stdInput = QString(),
std::chrono::seconds timeoutSec = std::chrono::seconds(0) );
static DLLEXPORT ProcessResult runCommand( RunLocation location,
const QStringList& args,
const QString& workingPath = QString(),
const QString& stdInput = QString(),
std::chrono::seconds timeoutSec = std::chrono::seconds( 0 ) );
/** @brief Convenience wrapper for runCommand().
* Runs the command in the location specified through the boolean
* doChroot(), which is what you usually want for running commands
* during installation.
*/
inline ProcessResult targetEnvCommand(
const QStringList &args,
const QString& workingPath = QString(),
const QString& stdInput = QString(),
std::chrono::seconds timeoutSec = std::chrono::seconds(0) )
inline ProcessResult targetEnvCommand( const QStringList& args,
const QString& workingPath = QString(),
const QString& stdInput = QString(),
std::chrono::seconds timeoutSec = std::chrono::seconds( 0 ) )
{
return runCommand(
m_doChroot ? RunLocation::RunInTarget : RunLocation::RunInHost,
args,
workingPath,
stdInput,
timeoutSec );
m_doChroot ? RunLocation::RunInTarget : RunLocation::RunInHost, args, workingPath, stdInput, timeoutSec );
}
/** @brief Convenience wrapper for targetEnvCommand() which returns only the exit code */
inline int targetEnvCall( const QStringList& args,
const QString& workingPath = QString(),
const QString& stdInput = QString(),
std::chrono::seconds timeoutSec = std::chrono::seconds(0) )
std::chrono::seconds timeoutSec = std::chrono::seconds( 0 ) )
{
return targetEnvCommand( args, workingPath, stdInput, timeoutSec ).first;
}
@ -174,9 +179,9 @@ public:
inline int targetEnvCall( const QString& command,
const QString& workingPath = QString(),
const QString& stdInput = QString(),
std::chrono::seconds timeoutSec = std::chrono::seconds(0) )
std::chrono::seconds timeoutSec = std::chrono::seconds( 0 ) )
{
return targetEnvCall( QStringList{ command }, workingPath, stdInput, timeoutSec );
return targetEnvCall( QStringList { command }, workingPath, stdInput, timeoutSec );
}
/** @brief Convenience wrapper for targetEnvCommand() which returns only the exit code
@ -184,10 +189,10 @@ public:
* Places the called program's output in the @p output string.
*/
int targetEnvOutput( const QStringList& args,
QString& output,
const QString& workingPath = QString(),
const QString& stdInput = QString(),
std::chrono::seconds timeoutSec = std::chrono::seconds(0) )
QString& output,
const QString& workingPath = QString(),
const QString& stdInput = QString(),
std::chrono::seconds timeoutSec = std::chrono::seconds( 0 ) )
{
auto r = targetEnvCommand( args, workingPath, stdInput, timeoutSec );
output = r.second;
@ -202,9 +207,9 @@ public:
QString& output,
const QString& workingPath = QString(),
const QString& stdInput = QString(),
std::chrono::seconds timeoutSec = std::chrono::seconds(0) )
std::chrono::seconds timeoutSec = std::chrono::seconds( 0 ) )
{
return targetEnvOutput( QStringList{ command }, output, workingPath, stdInput, timeoutSec );
return targetEnvOutput( QStringList { command }, output, workingPath, stdInput, timeoutSec );
}
@ -255,7 +260,7 @@ public:
*
* @return size, guesstimate-factor
*/
DLLEXPORT QPair<quint64, float> getTotalMemoryB() const;
DLLEXPORT QPair< quint64, float > getTotalMemoryB() const;
/**
* @brief getCpuDescription returns a string describing the CPU.
@ -279,6 +284,6 @@ private:
bool m_doChroot;
};
} // namespace
} // namespace CalamaresUtils
#endif

View File

@ -32,34 +32,44 @@
namespace CalamaresUtils
{
static CommandLine get_variant_object( const QVariantMap& m )
static CommandLine
get_variant_object( const QVariantMap& m )
{
QString command = CalamaresUtils::getString( m, "command" );
int timeout = CalamaresUtils::getInteger( m, "timeout", -1 );
if ( !command.isEmpty() )
{
return CommandLine( command, timeout >= 0 ? std::chrono::seconds( timeout ) : CommandLine::TimeoutNotSet() );
}
cWarning() << "Bad CommandLine element" << m;
return CommandLine();
}
static CommandList_t get_variant_stringlist( const QVariantList& l )
static CommandList_t
get_variant_stringlist( const QVariantList& l )
{
CommandList_t retl;
unsigned int count = 0;
for ( const auto& v : l )
{
if ( v.type() == QVariant::String )
{
retl.append( CommandLine( v.toString(), CommandLine::TimeoutNotSet() ) );
}
else if ( v.type() == QVariant::Map )
{
auto command( get_variant_object( v.toMap() ) );
if ( command.isValid() )
{
retl.append( command );
}
// Otherwise warning is already given
}
else
{
cWarning() << "Bad CommandList element" << count << v.type() << v;
}
++count;
}
return retl;
@ -78,37 +88,48 @@ CommandList::CommandList::CommandList( const QVariant& v, bool doChroot, std::ch
{
const auto v_list = v.toList();
if ( v_list.count() )
{
append( get_variant_stringlist( v_list ) );
}
else
{
cWarning() << "Empty CommandList";
}
}
else if ( v.type() == QVariant::String )
{
append( v.toString() );
}
else if ( v.type() == QVariant::Map )
{
auto c( get_variant_object( v.toMap() ) );
if ( c.isValid() )
{
append( c );
}
// Otherwise warning is already given
}
else
{
cWarning() << "CommandList does not understand variant" << v.type();
}
}
CommandList::~CommandList()
{
}
CommandList::~CommandList() {}
static inline bool
findInCommands( const CommandList& l, const QString& needle )
{
for ( CommandList::const_iterator i = l.cbegin(); i != l.cend(); ++i )
if ( i->command().contains( needle ) )
{
return true;
}
return false;
}
Calamares::JobResult CommandList::run()
Calamares::JobResult
CommandList::run()
{
QLatin1Literal rootMagic( "@@ROOT@@" );
QLatin1Literal userMagic( "@@USER@@" );
@ -125,8 +146,11 @@ Calamares::JobResult CommandList::run()
if ( !gs || !gs->contains( "rootMountPoint" ) )
{
cError() << "No rootMountPoint defined.";
return Calamares::JobResult::error( QCoreApplication::translate( "CommandList", "Could not run command." ),
QCoreApplication::translate( "CommandList", "The command runs in the host environment and needs to know the root path, but no rootMountPoint is defined." ) );
return Calamares::JobResult::error(
QCoreApplication::translate( "CommandList", "Could not run command." ),
QCoreApplication::translate( "CommandList",
"The command runs in the host environment and needs to know the root "
"path, but no rootMountPoint is defined." ) );
}
root = gs->value( "rootMountPoint" ).toString();
}
@ -137,7 +161,8 @@ Calamares::JobResult CommandList::run()
cError() << "No username defined.";
return Calamares::JobResult::error(
QCoreApplication::translate( "CommandList", "Could not run command." ),
QCoreApplication::translate( "CommandList", "The command needs to know the user's name, but no username is defined." ) );
QCoreApplication::translate( "CommandList",
"The command needs to know the user's name, but no username is defined." ) );
}
QString user = gs->value( "username" ).toString(); // may be blank if unset
@ -156,15 +181,18 @@ Calamares::JobResult CommandList::run()
shell_cmd << processed_cmd;
std::chrono::seconds timeout = i->timeout() >= std::chrono::seconds::zero() ? i->timeout() : m_timeout;
ProcessResult r = System::runCommand(
location, shell_cmd, QString(), QString(), timeout );
ProcessResult r = System::runCommand( location, shell_cmd, QString(), QString(), timeout );
if ( r.getExitCode() != 0 )
{
if ( suppress_result )
{
cDebug() << "Error code" << r.getExitCode() << "ignored by CommandList configuration.";
}
else
{
return r.explainProcess( processed_cmd, timeout );
}
}
}
@ -177,4 +205,4 @@ CommandList::append( const QString& s )
append( CommandLine( s, m_timeout ) );
}
} // namespace
} // namespace CalamaresUtils

View File

@ -35,7 +35,7 @@ namespace CalamaresUtils
*/
struct CommandLine : public QPair< QString, std::chrono::seconds >
{
static inline constexpr std::chrono::seconds TimeoutNotSet() { return std::chrono::seconds(-1); }
static inline constexpr std::chrono::seconds TimeoutNotSet() { return std::chrono::seconds( -1 ); }
/// An invalid command line
CommandLine()
@ -49,25 +49,16 @@ struct CommandLine : public QPair< QString, std::chrono::seconds >
}
CommandLine( const QString& s, std::chrono::seconds t )
: QPair( s, t)
: QPair( s, t )
{
}
QString command() const
{
return first;
}
QString command() const { return first; }
std::chrono::seconds timeout() const
{
return second;
}
std::chrono::seconds timeout() const { return second; }
bool isValid() const
{
return !first.isEmpty();
}
} ;
bool isValid() const { return !first.isEmpty(); }
};
/** @brief Abbreviation, used internally. */
using CommandList_t = QList< CommandLine >;
@ -88,19 +79,16 @@ public:
CommandList( const QVariant& v, bool doChroot = true, std::chrono::seconds timeout = std::chrono::seconds( 10 ) );
~CommandList();
bool doChroot() const
{
return m_doChroot;
}
bool doChroot() const { return m_doChroot; }
Calamares::JobResult run();
using CommandList_t::isEmpty;
using CommandList_t::count;
using CommandList_t::at;
using CommandList_t::cbegin;
using CommandList_t::cend;
using CommandList_t::const_iterator;
using CommandList_t::at;
using CommandList_t::count;
using CommandList_t::isEmpty;
protected:
using CommandList_t::append;
@ -109,7 +97,7 @@ protected:
private:
bool m_doChroot;
std::chrono::seconds m_timeout;
} ;
};
} // namespace
} // namespace CalamaresUtils
#endif

View File

@ -101,16 +101,24 @@ mungeEnvironment( QStringList& l, const char* name, const char* defaultDirs )
QStringList dirs = QString( qgetenv( name ) ).split( ':' );
if ( dirs.isEmpty() )
{
dirs = QString( defaultDirs ).split( ':' );
}
for ( auto s : dirs )
{
if ( s.isEmpty() )
{
continue;
}
if ( s.endsWith( '/' ) )
{
l << ( s + calamaresSubdir ) << s;
}
else
{
l << ( s + '/' + calamaresSubdir ) << ( s + '/' );
}
}
}
@ -127,7 +135,9 @@ QStringList
extraConfigDirs()
{
if ( s_haveExtraDirs )
{
return s_extraConfigDirs;
}
return QStringList();
}
@ -135,7 +145,9 @@ QStringList
extraDataDirs()
{
if ( s_haveExtraDirs )
{
return s_extraDataDirs;
}
return QStringList();
}
@ -173,12 +185,16 @@ appLogDir()
QString path = QStandardPaths::writableLocation( QStandardPaths::CacheLocation );
QDir dir( path );
if ( isWritableDir( dir ) )
{
return dir;
}
cerr << "warning: Could not find a standard writable location for log dir, falling back to $HOME\n";
dir = QDir::home();
if ( isWritableDir( dir ) )
{
return dir;
}
cerr << "warning: Found no writable location for log dir, falling back to the temp dir\n";
return QDir::temp();
@ -191,4 +207,4 @@ setQmlModulesDir( const QDir& dir )
s_qmlModulesDir = dir;
}
} // namespace
} // namespace CalamaresUtils

View File

@ -31,43 +31,43 @@
namespace CalamaresUtils
{
DLLEXPORT QDir qmlModulesDir();
DLLEXPORT QDir qmlModulesDir();
/**
* @brief appDataDir returns the directory with common application data.
* Defaults to CMAKE_INSTALL_FULL_DATADIR (usually /usr/share/calamares).
*/
DLLEXPORT QDir appDataDir();
/**
* @brief appDataDir returns the directory with common application data.
* Defaults to CMAKE_INSTALL_FULL_DATADIR (usually /usr/share/calamares).
*/
DLLEXPORT QDir appDataDir();
/**
* @brief appLogDir returns the directory for Calamares logs.
* Defaults to QStandardPaths::CacheLocation (usually ~/.cache/Calamares).
*/
DLLEXPORT QDir appLogDir();
/**
* @brief appLogDir returns the directory for Calamares logs.
* Defaults to QStandardPaths::CacheLocation (usually ~/.cache/Calamares).
*/
DLLEXPORT QDir appLogDir();
/**
* @brief systemLibDir returns the system's lib directory.
* Defaults to CMAKE_INSTALL_FULL_LIBDIR (usually /usr/lib64 or /usr/lib).
*/
DLLEXPORT QDir systemLibDir();
/**
* @brief systemLibDir returns the system's lib directory.
* Defaults to CMAKE_INSTALL_FULL_LIBDIR (usually /usr/lib64 or /usr/lib).
*/
DLLEXPORT QDir systemLibDir();
/**
* Override app data dir. Only for testing purposes.
*/
DLLEXPORT void setAppDataDir( const QDir& dir );
DLLEXPORT bool isAppDataDirOverridden();
/**
* Override app data dir. Only for testing purposes.
*/
DLLEXPORT void setAppDataDir( const QDir& dir );
DLLEXPORT bool isAppDataDirOverridden();
DLLEXPORT void setQmlModulesDir( const QDir& dir );
DLLEXPORT void setQmlModulesDir( const QDir& dir );
/** @brief Setup extra config and data dirs from the XDG variables.
*/
DLLEXPORT void setXdgDirs();
/** @brief Are any extra directories configured? */
DLLEXPORT bool haveExtraDirs();
/** @brief XDG_CONFIG_DIRS, each guaranteed to end with / */
DLLEXPORT QStringList extraConfigDirs();
/** @brief XDG_DATA_DIRS, each guaranteed to end with / */
DLLEXPORT QStringList extraDataDirs();
} // namespace
/** @brief Setup extra config and data dirs from the XDG variables.
*/
DLLEXPORT void setXdgDirs();
/** @brief Are any extra directories configured? */
DLLEXPORT bool haveExtraDirs();
/** @brief XDG_CONFIG_DIRS, each guaranteed to end with / */
DLLEXPORT QStringList extraConfigDirs();
/** @brief XDG_DATA_DIRS, each guaranteed to end with / */
DLLEXPORT QStringList extraDataDirs();
} // namespace CalamaresUtils
#endif

View File

@ -20,8 +20,8 @@
#include "Logger.h"
#include <iostream>
#include <fstream>
#include <iostream>
#include <QCoreApplication>
#include <QDir>
@ -30,17 +30,17 @@
#include <QTime>
#include <QVariant>
#include "utils/Dirs.h"
#include "CalamaresVersion.h"
#include "utils/Dirs.h"
#define LOGFILE_SIZE 1024 * 256
static std::ofstream logfile;
static unsigned int s_threshold =
#ifdef QT_NO_DEBUG
Logger::LOG_DISABLE;
Logger::LOG_DISABLE;
#else
Logger::LOGEXTRA + 1; // Comparison is < in log() function
Logger::LOGEXTRA + 1; // Comparison is < in log() function
#endif
static QMutex s_mutex;
@ -48,15 +48,17 @@ namespace Logger
{
void
setupLogLevel(unsigned int level)
setupLogLevel( unsigned int level )
{
if ( level > LOGVERBOSE )
{
level = LOGVERBOSE;
}
s_threshold = level + 1; // Comparison is < in log() function
}
bool
logLevelEnabled(unsigned int level)
logLevelEnabled( unsigned int level )
{
return level < s_threshold;
}
@ -77,11 +79,9 @@ log( const char* msg, unsigned int debugLevel )
// If we don't format the date as a Qt::ISODate then we get a crash when
// logging at exit as Qt tries to use QLocale to format, but QLocale is
// on its way out.
logfile << QDate::currentDate().toString( Qt::ISODate ).toUtf8().data()
<< " - "
<< QTime::currentTime().toString().toUtf8().data()
<< " [" << QString::number( debugLevel ).toUtf8().data() << "]: "
<< msg << std::endl;
logfile << QDate::currentDate().toString( Qt::ISODate ).toUtf8().data() << " - "
<< QTime::currentTime().toString().toUtf8().data() << " ["
<< QString::number( debugLevel ).toUtf8().data() << "]: " << msg << std::endl;
logfile.flush();
}
@ -90,9 +90,8 @@ log( const char* msg, unsigned int debugLevel )
{
QMutexLocker lock( &s_mutex );
std::cout << QTime::currentTime().toString().toUtf8().data()
<< " [" << QString::number( debugLevel ).toUtf8().data() << "]: "
<< msg << std::endl;
std::cout << QTime::currentTime().toString().toUtf8().data() << " ["
<< QString::number( debugLevel ).toUtf8().data() << "]: " << msg << std::endl;
std::cout.flush();
}
}
@ -107,21 +106,21 @@ CalamaresLogHandler( QtMsgType type, const QMessageLogContext&, const QString& m
const char* message = ba.constData();
QMutexLocker locker( &s_mutex );
switch( type )
switch ( type )
{
case QtDebugMsg:
log( message, LOGVERBOSE );
break;
case QtDebugMsg:
log( message, LOGVERBOSE );
break;
case QtInfoMsg:
log( message, 1 );
break;
case QtInfoMsg:
log( message, 1 );
break;
case QtCriticalMsg:
case QtWarningMsg:
case QtFatalMsg:
log( message, 0 );
break;
case QtCriticalMsg:
case QtWarningMsg:
case QtFatalMsg:
log( message, 0 );
break;
}
}
@ -161,11 +160,13 @@ setupLogfile()
// Lock while (re-)opening the logfile
{
QMutexLocker lock( &s_mutex );
logfile.open( logFile().toLocal8Bit(), std::ios::app );
if ( logfile.tellp() )
logfile << "\n\n" << std::endl;
logfile << "=== START CALAMARES " << CALAMARES_VERSION << std::endl;
QMutexLocker lock( &s_mutex );
logfile.open( logFile().toLocal8Bit(), std::ios::app );
if ( logfile.tellp() )
{
logfile << "\n\n" << std::endl;
}
logfile << "=== START CALAMARES " << CALAMARES_VERSION << std::endl;
}
qInstallMessageHandler( CalamaresLogHandler );
@ -183,14 +184,13 @@ CLog::~CLog()
log( m_msg.toUtf8().data(), m_debugLevel );
}
CDebug::~CDebug()
{
}
CDebug::~CDebug() {}
const char Continuation[] = "\n ";
const char SubEntry[] = " .. ";
QString toString( const QVariant& v )
QString
toString( const QVariant& v )
{
auto t = v.type();
@ -199,11 +199,15 @@ QString toString( const QVariant& v )
QStringList s;
auto l = v.toList();
for ( auto lit = l.constBegin(); lit != l.constEnd(); ++lit )
{
s << lit->toString();
return s.join(", ");
}
return s.join( ", " );
}
else
{
return v.toString();
}
}
} // namespace
} // namespace Logger

View File

@ -27,169 +27,181 @@
namespace Logger
{
DLLEXPORT extern const char Continuation[];
DLLEXPORT extern const char SubEntry[];
DLLEXPORT extern const char Continuation[];
DLLEXPORT extern const char SubEntry[];
enum
enum
{
LOG_DISABLE = 0,
LOGERROR = 1,
LOGWARNING = 2,
LOGINFO = 3,
LOGEXTRA = 5,
LOGDEBUG = 6,
LOGVERBOSE = 8
};
class DLLEXPORT CLog : public QDebug
{
public:
explicit CLog( unsigned int debugLevel );
virtual ~CLog();
private:
QString m_msg;
unsigned int m_debugLevel;
};
class DLLEXPORT CDebug : public CLog
{
public:
CDebug( unsigned int debugLevel = LOGDEBUG )
: CLog( debugLevel )
{
LOG_DISABLE = 0,
LOGERROR = 1,
LOGWARNING = 2,
LOGINFO = 3,
LOGEXTRA = 5,
LOGDEBUG = 6,
LOGVERBOSE = 8
} ;
class DLLEXPORT CLog : public QDebug
{
public:
explicit CLog( unsigned int debugLevel );
virtual ~CLog();
private:
QString m_msg;
unsigned int m_debugLevel;
};
class DLLEXPORT CDebug : public CLog
{
public:
CDebug( unsigned int debugLevel = LOGDEBUG ) : CLog( debugLevel )
if ( debugLevel <= LOGERROR )
{
if ( debugLevel <= LOGERROR )
*this << "ERROR:";
else if ( debugLevel <= LOGWARNING )
*this << "WARNING:";
*this << "ERROR:";
}
virtual ~CDebug();
};
else if ( debugLevel <= LOGWARNING )
{
*this << "WARNING:";
}
}
virtual ~CDebug();
};
/**
* @brief The full path of the log file.
*/
DLLEXPORT QString logFile();
/**
* @brief The full path of the log file.
*/
DLLEXPORT QString logFile();
/**
* @brief Start logging to the log file.
*
* Call this (once) to start logging to the log file (usually
* ~/.cache/calamares/session.log ). An existing log file is
* rolled over if it is too large.
*/
DLLEXPORT void setupLogfile();
/**
* @brief Start logging to the log file.
*
* Call this (once) to start logging to the log file (usually
* ~/.cache/calamares/session.log ). An existing log file is
* rolled over if it is too large.
*/
DLLEXPORT void setupLogfile();
/**
* @brief Set a log level for future logging.
*
* Pass in a value from the LOG* enum, above. Use 0 to
* disable logging. Values greater than LOGVERBOSE are
* limited to LOGVERBOSE, which will log everything.
*
* Practical values are 0, 1, 2, and 6.
*/
DLLEXPORT void setupLogLevel( unsigned int level );
/**
* @brief Set a log level for future logging.
*
* Pass in a value from the LOG* enum, above. Use 0 to
* disable logging. Values greater than LOGVERBOSE are
* limited to LOGVERBOSE, which will log everything.
*
* Practical values are 0, 1, 2, and 6.
*/
DLLEXPORT void setupLogLevel( unsigned int level );
/** @brief Return the configured log-level. */
DLLEXPORT unsigned int logLevel();
/** @brief Return the configured log-level. */
DLLEXPORT unsigned int logLevel();
/** @brief Would the given @p level really be logged? */
DLLEXPORT bool logLevelEnabled( unsigned int level );
/** @brief Would the given @p level really be logged? */
DLLEXPORT bool logLevelEnabled( unsigned int level );
/**
* @brief Row-oriented formatted logging.
*
* Use DebugRow to produce multiple rows of 2-column output
* in a debugging statement. For instance,
* cDebug() << DebugRow<int,int>(1,12)
* << DebugRow<int,int>(2,24)
* will produce a single timestamped debug line with continuations.
* Each DebugRow produces one line of output, with the two values.
*/
template<typename T, typename U>
struct DebugRow
/**
* @brief Row-oriented formatted logging.
*
* Use DebugRow to produce multiple rows of 2-column output
* in a debugging statement. For instance,
* cDebug() << DebugRow<int,int>(1,12)
* << DebugRow<int,int>(2,24)
* will produce a single timestamped debug line with continuations.
* Each DebugRow produces one line of output, with the two values.
*/
template < typename T, typename U >
struct DebugRow
{
public:
explicit DebugRow( const T& t, const U& u )
: first( t )
, second( u )
{
public:
explicit DebugRow(const T& t, const U& u)
: first(t)
, second(u)
{}
const T& first;
const U& second;
} ;
/**
* @brief List-oriented formatted logging.
*
* Use DebugList to produce multiple rows of output in a debugging
* statement. For instance,
* cDebug() << DebugList( QStringList() << "foo" << "bar" )
* will produce a single timestamped debug line with continuations.
* Each element of the list of strings will be logged on a separate line.
*/
struct DebugList
{
explicit DebugList( const QStringList& l )
: list(l)
{}
const QStringList& list;
} ;
/**
* @brief Map-oriented formatted logging.
*
* Use DebugMap to produce multiple rows of output in a debugging
* statement from a map. The output is intentionally a bit-yaml-ish.
* cDebug() << DebugMap( map )
* will produce a single timestamped debug line with continuations.
* The continued lines will have a key (from the map) and a value
* on each line.
*/
struct DebugMap
{
public:
explicit DebugMap(const QVariantMap& m)
: map( m )
{}
const QVariantMap& map;
} ;
/** @brief output operator for DebugRow */
template<typename T, typename U>
inline QDebug&
operator <<( QDebug& s, const DebugRow<T, U>& t )
{
s << Continuation << t.first << ':' << ' ' << t.second;
return s;
}
/** @brief output operator for DebugList */
inline QDebug&
operator <<( QDebug& s, const DebugList& c )
const T& first;
const U& second;
};
/**
* @brief List-oriented formatted logging.
*
* Use DebugList to produce multiple rows of output in a debugging
* statement. For instance,
* cDebug() << DebugList( QStringList() << "foo" << "bar" )
* will produce a single timestamped debug line with continuations.
* Each element of the list of strings will be logged on a separate line.
*/
struct DebugList
{
explicit DebugList( const QStringList& l )
: list( l )
{
for( const auto& i : c.list )
s << Continuation << i;
return s;
}
/** @brief supporting method for outputting a DebugMap */
QString toString( const QVariant& v );
const QStringList& list;
};
/** @brief output operator for DebugMap */
inline QDebug&
operator <<( QDebug& s, const DebugMap& t )
/**
* @brief Map-oriented formatted logging.
*
* Use DebugMap to produce multiple rows of output in a debugging
* statement from a map. The output is intentionally a bit-yaml-ish.
* cDebug() << DebugMap( map )
* will produce a single timestamped debug line with continuations.
* The continued lines will have a key (from the map) and a value
* on each line.
*/
struct DebugMap
{
public:
explicit DebugMap( const QVariantMap& m )
: map( m )
{
for ( auto it = t.map.constBegin(); it != t.map.constEnd(); ++it )
s << Continuation << it.key().toUtf8().constData() << ':' << ' ' << toString( it.value() ).toUtf8().constData();
return s;
}
} // namespace
const QVariantMap& map;
};
/** @brief output operator for DebugRow */
template < typename T, typename U >
inline QDebug&
operator<<( QDebug& s, const DebugRow< T, U >& t )
{
s << Continuation << t.first << ':' << ' ' << t.second;
return s;
}
/** @brief output operator for DebugList */
inline QDebug&
operator<<( QDebug& s, const DebugList& c )
{
for ( const auto& i : c.list )
{
s << Continuation << i;
}
return s;
}
/** @brief supporting method for outputting a DebugMap */
QString toString( const QVariant& v );
/** @brief output operator for DebugMap */
inline QDebug&
operator<<( QDebug& s, const DebugMap& t )
{
for ( auto it = t.map.constBegin(); it != t.map.constEnd(); ++it )
{
s << Continuation << it.key().toUtf8().constData() << ':' << ' ' << toString( it.value() ).toUtf8().constData();
}
return s;
}
} // namespace Logger
#define cDebug Logger::CDebug
#define cWarning() Logger::CDebug(Logger::LOGWARNING)
#define cError() Logger::CDebug(Logger::LOGERROR)
#define cWarning() Logger::CDebug( Logger::LOGWARNING )
#define cError() Logger::CDebug( Logger::LOGERROR )
#endif

View File

@ -31,12 +31,12 @@
#include <QString>
#include <vector>
#include <type_traits>
#include <initializer_list>
#include <type_traits>
#include <vector>
/** @brief Type for collecting parts of a named enum. */
template<typename T>
template < typename T >
struct NamedEnumTable
{
using string_t = QString;
@ -53,7 +53,11 @@ struct NamedEnumTable
*
* static const NamedEnumTable<Colors> c{ {"red", Colors::Red } };
*/
NamedEnumTable( const std::initializer_list< pair_t >& v ) : table( v ) { /* static_assert( v.size() > 0 ); */ }
NamedEnumTable( const std::initializer_list< pair_t >& v )
: table( v )
{
/* static_assert( v.size() > 0 ); */
}
/** @brief Find a name @p s in the table.
*
@ -89,8 +93,8 @@ struct NamedEnumTable
{
ok = false;
for ( const auto &p : table )
if ( s == p.second)
for ( const auto& p : table )
if ( s == p.second )
{
ok = true;
return p.first;
@ -99,13 +103,14 @@ struct NamedEnumTable
// ok is still false
return string_t();
}
} ;
};
/** @brief Smashes an enum value to its underlying type. */
template<typename E>
constexpr typename std::underlying_type<E>::type smash( const E e )
template < typename E >
constexpr typename std::underlying_type< E >::type
smash( const E e )
{
return static_cast<typename std::underlying_type<E>::type>( e );
return static_cast< typename std::underlying_type< E >::type >( e );
}
#endif

View File

@ -42,7 +42,7 @@
#include "NamedEnum.h"
/** @brief Template that takes the enum type to work with and a special none-enum. */
template<typename T, T _none>
template < typename T, T _none >
class NamedSuffix
{
public:
@ -52,7 +52,7 @@ public:
/** @brief Empty value. */
NamedSuffix()
: m_value(0)
: m_value( 0 )
, m_unit( none )
{
}
@ -69,10 +69,10 @@ public:
* This parses the given string @p s by comparing with the suffixes
* in @p table and uses the first matching suffix as the unit.
*/
NamedSuffix( const NamedEnumTable<T>& table, const QString& s )
NamedSuffix( const NamedEnumTable< T >& table, const QString& s )
: NamedSuffix()
{
for( const auto& suffix : table.table )
for ( const auto& suffix : table.table )
if ( s.endsWith( suffix.first ) )
{
m_value = s.left( s.length() - suffix.first.length() ).toInt();

View File

@ -32,23 +32,24 @@ namespace Calamares
class PluginFactoryPrivate
{
Q_DECLARE_PUBLIC(PluginFactory)
Q_DECLARE_PUBLIC( PluginFactory )
protected:
typedef QPair<const QMetaObject *, PluginFactory::CreateInstanceFunction> Plugin;
typedef QPair< const QMetaObject*, PluginFactory::CreateInstanceFunction > Plugin;
PluginFactoryPrivate()
: catalogInitialized( false )
, q_ptr( nullptr )
{}
{
}
~PluginFactoryPrivate() {}
QHash<QString, Plugin> createInstanceHash;
QHash< QString, Plugin > createInstanceHash;
QString catalogName;
bool catalogInitialized;
PluginFactory *q_ptr;
PluginFactory* q_ptr;
};
} // namespace
} // namespace Calamares
#endif

View File

@ -26,27 +26,30 @@
#include <QTranslator>
namespace CalamaresUtils {
namespace CalamaresUtils
{
static QTranslator* s_brandingTranslator = nullptr;
static QTranslator* s_translator = nullptr;
static QString s_translatorLocaleName;
void
installTranslator( const QLocale& locale,
const QString& brandingTranslationsPrefix,
QObject* parent )
installTranslator( const QLocale& locale, const QString& brandingTranslationsPrefix, QObject* parent )
{
QString localeName = locale.name();
localeName.replace( "-", "_" );
if ( localeName == "C" )
{
localeName = "en";
}
// Special case of sr@latin
//
// See top-level CMakeLists.txt about special cases for translation loading.
if ( locale.language() == QLocale::Language::Serbian && locale.script() == QLocale::Script::LatinScript )
{
localeName = QStringLiteral( "sr@latin" );
}
cDebug() << "Looking for translations for" << localeName;
@ -56,19 +59,14 @@ installTranslator( const QLocale& locale,
if ( !brandingTranslationsPrefix.isEmpty() )
{
QString brandingTranslationsDirPath( brandingTranslationsPrefix );
brandingTranslationsDirPath.truncate( brandingTranslationsPrefix.lastIndexOf(
QDir::separator() ) );
brandingTranslationsDirPath.truncate( brandingTranslationsPrefix.lastIndexOf( QDir::separator() ) );
QDir brandingTranslationsDir( brandingTranslationsDirPath );
if ( brandingTranslationsDir.exists() )
{
QString filenameBase( brandingTranslationsPrefix );
filenameBase.remove( 0, brandingTranslationsPrefix.lastIndexOf(
QDir::separator() ) + 1 );
filenameBase.remove( 0, brandingTranslationsPrefix.lastIndexOf( QDir::separator() ) + 1 );
translator = new QTranslator( parent );
if ( translator->load( locale,
filenameBase,
"_",
brandingTranslationsDir.absolutePath() ) )
if ( translator->load( locale, filenameBase, "_", brandingTranslationsDir.absolutePath() ) )
{
cDebug() << Logger::SubEntry << "Branding using locale:" << localeName;
}
@ -121,19 +119,22 @@ translatorLocaleName()
}
void
Retranslator::attachRetranslator( QObject* parent,
std::function< void ( void ) > retranslateFunc )
Retranslator::attachRetranslator( QObject* parent, std::function< void( void ) > retranslateFunc )
{
Retranslator* r = nullptr;
for ( QObject* child : parent->children() )
{
r = qobject_cast< Retranslator* >( child );
if ( r )
{
break;
}
}
if ( !r )
{
r = new Retranslator( parent );
}
r->m_retranslateFuncList.append( retranslateFunc );
retranslateFunc();
@ -155,7 +156,9 @@ Retranslator::eventFilter( QObject* obj, QEvent* e )
if ( e->type() == QEvent::LanguageChange )
{
foreach ( std::function< void() > func, m_retranslateFuncList )
{
func();
}
}
}
// pass the event on to the base
@ -163,4 +166,4 @@ Retranslator::eventFilter( QObject* obj, QEvent* e )
}
} // namespace CalamaresUtils
} // namespace CalamaresUtils

View File

@ -32,24 +32,21 @@ class QLocale;
namespace CalamaresUtils
{
/**
* @brief installTranslator changes the application language.
* @param locale the new locale.
* @param brandingTranslationsPrefix the branding path prefix, from Calamares::Branding.
* @param parent the parent QObject.
*/
DLLEXPORT void installTranslator( const QLocale& locale,
const QString& brandingTranslationsPrefix,
QObject* parent );
/**
* @brief installTranslator changes the application language.
* @param locale the new locale.
* @param brandingTranslationsPrefix the branding path prefix, from Calamares::Branding.
* @param parent the parent QObject.
*/
DLLEXPORT void installTranslator( const QLocale& locale, const QString& brandingTranslationsPrefix, QObject* parent );
DLLEXPORT QString translatorLocaleName();
DLLEXPORT QString translatorLocaleName();
class Retranslator : public QObject
{
Q_OBJECT
public:
static void attachRetranslator( QObject* parent,
std::function< void( void ) > retranslateFunc );
static void attachRetranslator( QObject* parent, std::function< void( void ) > retranslateFunc );
void addRetranslateFunc( std::function< void( void ) > retranslateFunc );
@ -63,11 +60,10 @@ private:
};
} // namespace
} // namespace CalamaresUtils
#define CALAMARES_RETRANSLATE(body) \
CalamaresUtils::Retranslator::attachRetranslator( this, [=] { body } );
#define CALAMARES_RETRANSLATE_WIDGET(widget,body) \
#define CALAMARES_RETRANSLATE( body ) CalamaresUtils::Retranslator::attachRetranslator( this, [=] { body } );
#define CALAMARES_RETRANSLATE_WIDGET( widget, body ) \
CalamaresUtils::Retranslator::attachRetranslator( widget, [=] { body } );
#endif

View File

@ -74,7 +74,7 @@ removeDiacritics( const QString& string )
// *INDENT-ON*
QString output;
for ( const QChar &c : string )
for ( const QChar& c : string )
{
int i = diacriticLetters.indexOf( c );
if ( i < 0 )
@ -119,14 +119,14 @@ QString
obscure( const QString& string )
{
QString result;
const QChar *unicode = string.unicode();
const QChar* unicode = string.unicode();
for ( int i = 0; i < string.length(); ++i )
// yes, no typo. can't encode ' ' or '!' because
// they're the unicode BOM. stupid scrambling. stupid.
result += ( unicode[ i ].unicode() <= 0x21 ) ?
unicode[ i ] :
QChar( 0x1001F - unicode[ i ].unicode() );
// yes, no typo. can't encode ' ' or '!' because
// they're the unicode BOM. stupid scrambling. stupid.
{
result += ( unicode[ i ].unicode() <= 0x21 ) ? unicode[ i ] : QChar( 0x1001F - unicode[ i ].unicode() );
}
return result;
}
}
} // namespace CalamaresUtils

View File

@ -34,20 +34,20 @@
*/
namespace CalamaresUtils
{
/**
* @brief removeDiacritics replaces letters with diacritics and ligatures with
* alternative forms and digraphs.
* @param string the string to transform.
* @return the output string with plain characters.
*/
DLLEXPORT QString removeDiacritics( const QString& string );
/**
* @brief removeDiacritics replaces letters with diacritics and ligatures with
* alternative forms and digraphs.
* @param string the string to transform.
* @return the output string with plain characters.
*/
DLLEXPORT QString removeDiacritics( const QString& string );
/**
* @brief obscure is a bidirectional obfuscation function, from KStringHandler.
* @param string the input string.
* @return the obfuscated string.
*/
DLLEXPORT QString obscure( const QString& string );
} // namespace
/**
* @brief obscure is a bidirectional obfuscation function, from KStringHandler.
* @param string the input string.
* @return the obfuscated string.
*/
DLLEXPORT QString obscure( const QString& string );
} // namespace CalamaresUtils
#endif

View File

@ -26,76 +26,88 @@ namespace CalamaresUtils
{
/** User defined literals, 1_KiB is 1 KibiByte (= 2^10 bytes) */
constexpr qint64 operator ""_KiB( unsigned long long m )
constexpr qint64 operator""_KiB( unsigned long long m )
{
return qint64(m) * 1024;
return qint64( m ) * 1024;
}
/** User defined literals, 1_MiB is 1 MibiByte (= 2^20 bytes) */
constexpr qint64 operator ""_MiB( unsigned long long m )
constexpr qint64 operator""_MiB( unsigned long long m )
{
return operator ""_KiB(m) * 1024;
return operator""_KiB(m)*1024;
}
/** User defined literals, 1_GiB is 1 GibiByte (= 2^30 bytes) */
constexpr qint64 operator ""_GiB( unsigned long long m )
constexpr qint64 operator""_GiB( unsigned long long m )
{
return operator ""_MiB(m) * 1024;
return operator""_MiB(m)*1024;
}
constexpr qint64 KiBtoBytes( unsigned long long m )
constexpr qint64
KiBtoBytes( unsigned long long m )
{
return operator ""_KiB( m );
return operator""_KiB( m );
}
constexpr qint64 MiBtoBytes( unsigned long long m )
constexpr qint64
MiBtoBytes( unsigned long long m )
{
return operator ""_MiB( m );
return operator""_MiB( m );
}
constexpr qint64 GiBtoBytes( unsigned long long m )
constexpr qint64
GiBtoBytes( unsigned long long m )
{
return operator ""_GiB( m );
return operator""_GiB( m );
}
constexpr qint64 KiBtoBytes( double m )
constexpr qint64
KiBtoBytes( double m )
{
return qint64(m * 1024);
return qint64( m * 1024 );
}
constexpr qint64 MiBtoBytes( double m )
constexpr qint64
MiBtoBytes( double m )
{
return qint64(m * 1024 * 1024);
return qint64( m * 1024 * 1024 );
}
constexpr qint64 GiBtoBytes( double m )
constexpr qint64
GiBtoBytes( double m )
{
return qint64(m * 1024 * 1024 * 1024);
return qint64( m * 1024 * 1024 * 1024 );
}
constexpr int BytesToMiB( qint64 b )
constexpr int
BytesToMiB( qint64 b )
{
return int( b / 1024 / 1024 );
}
constexpr int BytesToGiB( qint64 b )
constexpr int
BytesToGiB( qint64 b )
{
return int( b / 1024 / 1024 / 1024 );
}
constexpr qint64 alignBytesToBlockSize( qint64 bytes, qint64 blocksize )
constexpr qint64
alignBytesToBlockSize( qint64 bytes, qint64 blocksize )
{
qint64 blocks = bytes / blocksize;
if ( blocks * blocksize != bytes )
{
++blocks;
}
return blocks * blocksize;
}
constexpr qint64 bytesToSectors( qint64 bytes, qint64 blocksize )
constexpr qint64
bytesToSectors( qint64 bytes, qint64 blocksize )
{
return alignBytesToBlockSize( alignBytesToBlockSize( bytes, blocksize), MiBtoBytes(1ULL) ) / blocksize;
return alignBytesToBlockSize( alignBytesToBlockSize( bytes, blocksize ), MiBtoBytes( 1ULL ) ) / blocksize;
}
} // namespace
} // namespace CalamaresUtils
#endif

View File

@ -39,20 +39,24 @@ getBool( const QVariantMap& map, const QString& key, bool d )
{
auto v = map.value( key );
if ( v.type() == QVariant::Bool )
{
result = v.toBool();
}
}
return result;
}
QString
getString(const QVariantMap& map, const QString& key)
getString( const QVariantMap& map, const QString& key )
{
if ( map.contains( key ) )
{
auto v = map.value( key );
if ( v.type() == QVariant::String )
{
return v.toString();
}
}
return QString();
}
@ -65,7 +69,9 @@ getInteger( const QVariantMap& map, const QString& key, int d )
{
auto v = map.value( key );
if ( v.type() == QVariant::Int )
{
result = v.toInt();
}
}
return result;
@ -79,9 +85,13 @@ getDouble( const QVariantMap& map, const QString& key, double d )
{
auto v = map.value( key );
if ( v.type() == QVariant::Int )
{
result = v.toInt();
}
else if ( v.type() == QVariant::Double )
{
result = v.toDouble();
}
}
return result;
@ -104,4 +114,4 @@ getSubMap( const QVariantMap& map, const QString& key, bool& success )
return QVariantMap();
}
}
} // namespace CalamaresUtils

View File

@ -27,36 +27,36 @@
namespace CalamaresUtils
{
/**
* Get a bool value from a mapping with a given key; returns the default
* if no value is stored in the map.
*/
DLLEXPORT bool getBool( const QVariantMap& map, const QString& key, bool d );
/**
* Get a bool value from a mapping with a given key; returns the default
* if no value is stored in the map.
*/
DLLEXPORT bool getBool( const QVariantMap& map, const QString& key, bool d );
/**
* Get a string value from a mapping; returns empty QString if no value.
*/
DLLEXPORT QString getString( const QVariantMap& map, const QString& key );
/**
* Get a string value from a mapping; returns empty QString if no value.
*/
DLLEXPORT QString getString( const QVariantMap& map, const QString& key );
/**
* Get an integer value from a mapping; returns @p d if no value.
*/
DLLEXPORT int getInteger( const QVariantMap& map, const QString& key, int d );
/**
* Get an integer value from a mapping; returns @p d if no value.
*/
DLLEXPORT int getInteger( const QVariantMap& map, const QString& key, int d );
/**
* Get a double value from a mapping (integers are converted); returns @p d if no value.
*/
DLLEXPORT double getDouble( const QVariantMap& map, const QString& key, double d );
/**
* Get a double value from a mapping (integers are converted); returns @p d if no value.
*/
DLLEXPORT double getDouble( const QVariantMap& map, const QString& key, double d );
/**
* Returns a sub-map (i.e. a nested map) from the given mapping with the
* given key. @p success is set to true if the @p key exists
* in @p map and converts to a map, false otherwise.
*
* Returns an empty map if there is no such key or it is not a map-value.
* (e.g. if @p success is false).
*/
DLLEXPORT QVariantMap getSubMap( const QVariantMap& map, const QString& key, bool& success );
} // namespace
/**
* Returns a sub-map (i.e. a nested map) from the given mapping with the
* given key. @p success is set to true if the @p key exists
* in @p map and converts to a map, false otherwise.
*
* Returns an empty map if there is no such key or it is not a map-value.
* (e.g. if @p success is false).
*/
DLLEXPORT QVariantMap getSubMap( const QVariantMap& map, const QString& key, bool& success );
} // namespace CalamaresUtils
#endif

View File

@ -70,13 +70,21 @@ yamlScalarToVariant( const YAML::Node& scalarNode )
std::string stdScalar = scalarNode.as< std::string >();
QString scalarString = QString::fromStdString( stdScalar );
if ( _yamlScalarTrueValues.exactMatch( scalarString ) )
{
return QVariant( true );
}
if ( _yamlScalarFalseValues.exactMatch( scalarString ) )
{
return QVariant( false );
}
if ( QRegExp( "[-+]?\\d+" ).exactMatch( scalarString ) )
{
return QVariant( scalarString.toInt() );
}
if ( QRegExp( "[-+]?\\d*\\.?\\d+" ).exactMatch( scalarString ) )
{
return QVariant( scalarString.toDouble() );
}
return QVariant( scalarString );
}
@ -85,8 +93,7 @@ QVariant
yamlSequenceToVariant( const YAML::Node& sequenceNode )
{
QVariantList vl;
for ( YAML::const_iterator it = sequenceNode.begin();
it != sequenceNode.end(); ++it )
for ( YAML::const_iterator it = sequenceNode.begin(); it != sequenceNode.end(); ++it )
{
vl << yamlToVariant( *it );
}
@ -98,17 +105,15 @@ QVariant
yamlMapToVariant( const YAML::Node& mapNode )
{
QVariantMap vm;
for ( YAML::const_iterator it = mapNode.begin();
it != mapNode.end(); ++it )
for ( YAML::const_iterator it = mapNode.begin(); it != mapNode.end(); ++it )
{
vm.insert( QString::fromStdString( it->first.as< std::string >() ),
yamlToVariant( it->second ) );
vm.insert( QString::fromStdString( it->first.as< std::string >() ), yamlToVariant( it->second ) );
}
return vm;
}
QStringList
yamlToStringList(const YAML::Node& listNode)
yamlToStringList( const YAML::Node& listNode )
{
QStringList l;
listNode >> l;
@ -117,7 +122,7 @@ yamlToStringList(const YAML::Node& listNode)
void
explainYamlException( const YAML::Exception& e, const QByteArray& yamlData, const char *label )
explainYamlException( const YAML::Exception& e, const QByteArray& yamlData, const char* label )
{
cWarning() << "YAML error " << e.what() << "in" << label << '.';
explainYamlException( e, yamlData );
@ -142,7 +147,9 @@ explainYamlException( const YAML::Exception& e, const QByteArray& yamlData )
linestart = yamlData.indexOf( '\n', linestart );
// No more \ns found, weird
if ( linestart < 0 )
{
break;
}
linestart += 1; // Skip that \n
}
int lineend = linestart;
@ -150,34 +157,43 @@ explainYamlException( const YAML::Exception& e, const QByteArray& yamlData )
{
lineend = yamlData.indexOf( '\n', linestart );
if ( lineend < 0 )
{
lineend = yamlData.length();
}
}
int rangestart = linestart;
int rangeend = lineend;
// Adjust range (linestart..lineend) so it's not too long
if ( ( linestart >= 0 ) && ( e.mark.column > 30 ) )
{
rangestart += ( e.mark.column - 30 );
}
if ( ( linestart >= 0 ) && ( rangeend - rangestart > 40 ) )
{
rangeend = rangestart + 40;
}
if ( linestart >= 0 )
cWarning() << "offending YAML data:" << yamlData.mid( rangestart, rangeend-rangestart ).constData();
{
cWarning() << "offending YAML data:" << yamlData.mid( rangestart, rangeend - rangestart ).constData();
}
}
}
QVariantMap
loadYaml(const QFileInfo& fi, bool* ok)
loadYaml( const QFileInfo& fi, bool* ok )
{
return loadYaml( fi.absoluteFilePath(), ok );
}
QVariantMap
loadYaml(const QString& filename, bool* ok)
loadYaml( const QString& filename, bool* ok )
{
if ( ok )
{
*ok = false;
}
QFile yamlFile( filename );
QVariant yamlContents;
@ -197,12 +213,12 @@ loadYaml(const QString& filename, bool* ok)
}
if ( yamlContents.isValid() &&
!yamlContents.isNull() &&
yamlContents.type() == QVariant::Map )
if ( yamlContents.isValid() && !yamlContents.isNull() && yamlContents.type() == QVariant::Map )
{
if ( ok )
{
*ok = true;
}
return yamlContents.toMap();
}
@ -214,7 +230,9 @@ static void
writeIndent( QFile& f, int indent )
{
while ( indent-- > 0 )
{
f.write( " " );
}
}
// forward declaration
@ -229,7 +247,9 @@ static void
dumpYamlElement( QFile& f, const QVariant& value, int indent )
{
if ( value.type() == QVariant::Type::Bool )
{
f.write( value.toBool() ? "true" : "false" );
}
else if ( value.type() == QVariant::Type::String )
{
f.write( quote );
@ -251,17 +271,19 @@ dumpYamlElement( QFile& f, const QVariant& value, int indent )
{
++c;
f.write( newline );
writeIndent( f, indent+1 );
writeIndent( f, indent + 1 );
f.write( "- " );
dumpYamlElement( f, it, indent+1 );
dumpYamlElement( f, it, indent + 1 );
}
if ( !c ) // i.e. list was empty
{
f.write( "[]" );
}
}
else if ( value.type() == QVariant::Type::Map )
{
f.write( newline );
dumpYaml( f, value.toMap(), indent+1 );
dumpYaml( f, value.toMap(), indent + 1 );
}
else
{
@ -293,12 +315,13 @@ saveYaml( const QString& filename, const QVariantMap& map )
{
QFile f( filename );
if ( !f.open( QFile::WriteOnly ) )
{
return false;
}
f.write( "# YAML dump\n---\n" );
return dumpYaml( f, map, 0 );
}
} // namespace
} // namespace CalamaresUtils

View File

@ -73,10 +73,10 @@ bool saveYaml( const QString& filename, const QVariantMap& map );
* what is going on in terms of the data passed to the parser.
* Uses @p label when labeling the data source (e.g. "netinstall data")
*/
void explainYamlException( const YAML::Exception& e, const QByteArray& data, const char *label );
void explainYamlException( const YAML::Exception& e, const QByteArray& data, const char* label );
void explainYamlException( const YAML::Exception& e, const QByteArray& data, const QString& label );
void explainYamlException( const YAML::Exception& e, const QByteArray& data );
} // namespace
} // namespace CalamaresUtils
#endif