[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 "CalamaresUtilsSystem.h"
#include "utils/Logger.h"
#include "GlobalStorage.h" #include "GlobalStorage.h"
#include "JobQueue.h" #include "JobQueue.h"
#include "Settings.h" #include "Settings.h"
#include "utils/Logger.h"
#include <QCoreApplication> #include <QCoreApplication>
#include <QDir> #include <QDir>
@ -34,8 +34,8 @@
#endif #endif
#ifdef Q_OS_FREEBSD #ifdef Q_OS_FREEBSD
#include <sys/types.h>
#include <sys/sysctl.h> #include <sys/sysctl.h>
#include <sys/types.h>
#endif #endif
/** @brief When logging commands, don't log everything. /** @brief When logging commands, don't log everything.
@ -63,12 +63,18 @@ operator<<( QDebug& s, const RedactedList& l )
{ {
for ( const auto& item : l.list ) for ( const auto& item : l.list )
if ( item.startsWith( "$6$" ) ) if ( item.startsWith( "$6$" ) )
{
s << "<password>"; s << "<password>";
else
s << item;
} }
else else
{
s << item;
}
}
else
{
s << l.list; s << l.list;
}
return s; return s;
} }
@ -92,8 +98,7 @@ System::System( bool doChroot, QObject* parent )
} }
System::~System() System::~System() {}
{}
System* System*
@ -118,9 +123,13 @@ System::mount( const QString& devicePath,
if ( devicePath.isEmpty() || mountPoint.isEmpty() ) if ( devicePath.isEmpty() || mountPoint.isEmpty() )
{ {
if ( devicePath.isEmpty() ) if ( devicePath.isEmpty() )
{
cWarning() << "Can't mount an empty device."; cWarning() << "Can't mount an empty device.";
}
if ( mountPoint.isEmpty() ) if ( mountPoint.isEmpty() )
{
cWarning() << "Can't mount on an empty mountpoint."; cWarning() << "Can't mount on an empty mountpoint.";
}
return static_cast< int >( ProcessResult::Code::NoWorkingDirectory ); return static_cast< int >( ProcessResult::Code::NoWorkingDirectory );
} }
@ -140,17 +149,20 @@ System::mount( const QString& devicePath,
QStringList args = { devicePath, mountPoint }; QStringList args = { devicePath, mountPoint };
if ( !filesystemName.isEmpty() ) if ( !filesystemName.isEmpty() )
{
args << "-t" << filesystemName; args << "-t" << filesystemName;
}
if ( !options.isEmpty() ) if ( !options.isEmpty() )
{
args << "-o" << options; args << "-o" << options;
}
return QProcess::execute( program, args ); return QProcess::execute( program, args );
} }
ProcessResult ProcessResult
System::runCommand( System::runCommand( System::RunLocation location,
System::RunLocation location,
const QStringList& args, const QStringList& args,
const QString& workingPath, const QString& workingPath,
const QString& stdInput, const QString& stdInput,
@ -158,10 +170,10 @@ System::runCommand(
{ {
QString output; 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 ) && if ( ( location == System::RunLocation::RunInTarget ) && ( !gs || !gs->contains( "rootMountPoint" ) ) )
( !gs || !gs->contains( "rootMountPoint" ) ) )
{ {
cWarning() << "No rootMountPoint in global storage"; cWarning() << "No rootMountPoint in global storage";
return ProcessResult::Code::NoWorkingDirectory; return ProcessResult::Code::NoWorkingDirectory;
@ -197,7 +209,9 @@ System::runCommand(
if ( !workingPath.isEmpty() ) if ( !workingPath.isEmpty() )
{ {
if ( QDir( workingPath ).exists() ) if ( QDir( workingPath ).exists() )
{
process.setWorkingDirectory( QDir( workingPath ).absolutePath() ); process.setWorkingDirectory( QDir( workingPath ).absolutePath() );
}
else else
{ {
cWarning() << "Invalid working directory:" << workingPath; cWarning() << "Invalid working directory:" << workingPath;
@ -219,10 +233,10 @@ System::runCommand(
} }
process.closeWriteChannel(); 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" << cWarning().noquote().nospace() << "Timed out. Output so far:\n" << process.readAllStandardOutput();
process.readAllStandardOutput();
return ProcessResult::Code::TimedOut; return ProcessResult::Code::TimedOut;
} }
@ -252,7 +266,8 @@ System::targetPath( const QString& path ) const
if ( doChroot() ) 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" ) ) if ( !gs || !gs->contains( "rootMountPoint" ) )
{ {
@ -317,7 +332,9 @@ System::getTotalMemoryB() const
int r = sysinfo( &i ); int r = sysinfo( &i );
if ( r ) if ( r )
{
return qMakePair( 0, 0.0 ); 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 ) #elif defined( Q_OS_FREEBSD )
@ -326,7 +343,9 @@ System::getTotalMemoryB() const
int r = sysctlbyname( "vm.kmem_size", &memsize, &s, NULL, 0 ); int r = sysctlbyname( "vm.kmem_size", &memsize, &s, NULL, 0 );
if ( r ) if ( r )
{
return qMakePair( 0, 0.0 ); return qMakePair( 0, 0.0 );
}
return qMakePair( memsize, 1.01 ); return qMakePair( memsize, 1.01 );
#else #else
@ -376,40 +395,45 @@ ProcessResult::explainProcess( int ec, const QString& command, const QString& ou
using Calamares::JobResult; using Calamares::JobResult;
if ( ec == 0 ) if ( ec == 0 )
{
return JobResult::ok(); return JobResult::ok();
}
QString outputMessage = output.isEmpty() QString outputMessage = output.isEmpty()
? QCoreApplication::translate( "ProcessResult", "\nThere was no output from the command." ) ? QCoreApplication::translate( "ProcessResult", "\nThere was no output from the command." )
: ( QCoreApplication::translate( "ProcessResult", "\nOutput:\n" ) + output ); : ( QCoreApplication::translate( "ProcessResult", "\nOutput:\n" ) + output );
if ( ec == static_cast< int >( ProcessResult::Code::Crashed ) ) //Crash! if ( ec == static_cast< int >( ProcessResult::Code::Crashed ) ) //Crash!
return JobResult::error( QCoreApplication::translate( "ProcessResult", "External command crashed." ), return JobResult::error(
QCoreApplication::translate( "ProcessResult", "Command <i>%1</i> crashed." ) QCoreApplication::translate( "ProcessResult", "External command crashed." ),
.arg( command ) QCoreApplication::translate( "ProcessResult", "Command <i>%1</i> crashed." ).arg( command )
+ outputMessage ); + outputMessage );
if ( ec == static_cast< int >( ProcessResult::Code::FailedToStart ) ) if ( ec == static_cast< int >( ProcessResult::Code::FailedToStart ) )
return JobResult::error( QCoreApplication::translate( "ProcessResult", "External command failed to start." ), return JobResult::error(
QCoreApplication::translate( "ProcessResult", "Command <i>%1</i> failed to start." ) QCoreApplication::translate( "ProcessResult", "External command failed to start." ),
.arg( command ) ); QCoreApplication::translate( "ProcessResult", "Command <i>%1</i> failed to start." ).arg( command ) );
if ( ec == static_cast< int >( ProcessResult::Code::NoWorkingDirectory ) ) if ( ec == static_cast< int >( ProcessResult::Code::NoWorkingDirectory ) )
return JobResult::error( QCoreApplication::translate( "ProcessResult", "Internal error when starting command." ), return JobResult::error(
QCoreApplication::translate( "ProcessResult", "Internal error when starting command." ),
QCoreApplication::translate( "ProcessResult", "Bad parameters for process job call." ) ); QCoreApplication::translate( "ProcessResult", "Bad parameters for process job call." ) );
if ( ec == static_cast< int >( ProcessResult::Code::TimedOut ) ) if ( ec == static_cast< int >( ProcessResult::Code::TimedOut ) )
return JobResult::error( QCoreApplication::translate( "ProcessResult", "External command failed to finish." ), return JobResult::error(
QCoreApplication::translate( "ProcessResult", "External command failed to finish." ),
QCoreApplication::translate( "ProcessResult", "Command <i>%1</i> failed to finish in %2 seconds." ) QCoreApplication::translate( "ProcessResult", "Command <i>%1</i> failed to finish in %2 seconds." )
.arg( command ) .arg( command )
.arg( timeout.count() ) .arg( timeout.count() )
+ outputMessage ); + outputMessage );
//Any other exit code //Any other exit code
return JobResult::error( QCoreApplication::translate( "ProcessResult", "External command finished with errors." ), return JobResult::error(
QCoreApplication::translate( "ProcessResult", "External command finished with errors." ),
QCoreApplication::translate( "ProcessResult", "Command <i>%1</i> finished with exit code %2." ) QCoreApplication::translate( "ProcessResult", "Command <i>%1</i> finished with exit code %2." )
.arg( command ) .arg( command )
.arg( ec ) .arg( ec )
+ outputMessage ); + outputMessage );
} }
} // namespace } // namespace CalamaresUtils

View File

@ -43,8 +43,14 @@ public:
}; };
/** @brief Implicit one-argument constructor has no output, only a return code */ /** @brief Implicit one-argument constructor has no output, only a return code */
ProcessResult( Code r ) : QPair< int, QString >( static_cast<int>(r), QString() ) {} ProcessResult( Code r )
ProcessResult( int r, QString s ) : QPair< int, QString >( r, s ) {} : QPair< int, QString >( static_cast< int >( r ), QString() )
{
}
ProcessResult( int r, QString s )
: QPair< int, QString >( r, s )
{
}
int getExitCode() const { return first; } int getExitCode() const { return first; }
QString getOutput() const { return second; } QString getOutput() const { return second; }
@ -62,7 +68,8 @@ public:
* @param timeout Timeout passed to the process runner, for explaining * @param timeout Timeout passed to the process runner, for explaining
* error code -4 (timeout). * 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() /// @brief Convenience wrapper for explainProcess()
inline Calamares::JobResult explainProcess( const QString& command, std::chrono::seconds timeout ) const inline Calamares::JobResult explainProcess( const QString& command, std::chrono::seconds timeout ) const
@ -116,7 +123,11 @@ public:
/** (Typed) Boolean describing where a particular command should be run, /** (Typed) Boolean describing where a particular command should be run,
* whether in the host (live) system or in the (chroot) target system. * 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. * Runs the specified command in the chroot of the target system.
@ -135,8 +146,7 @@ public:
* NoWorkingDirectory = bad arguments * NoWorkingDirectory = bad arguments
* TimedOut = QProcess timeout * TimedOut = QProcess timeout
*/ */
static DLLEXPORT ProcessResult runCommand( static DLLEXPORT ProcessResult runCommand( RunLocation location,
RunLocation location,
const QStringList& args, const QStringList& args,
const QString& workingPath = QString(), const QString& workingPath = QString(),
const QString& stdInput = QString(), const QString& stdInput = QString(),
@ -147,18 +157,13 @@ public:
* doChroot(), which is what you usually want for running commands * doChroot(), which is what you usually want for running commands
* during installation. * during installation.
*/ */
inline ProcessResult targetEnvCommand( inline ProcessResult targetEnvCommand( const QStringList& args,
const QStringList &args,
const QString& workingPath = QString(), const QString& workingPath = QString(),
const QString& stdInput = QString(), const QString& stdInput = QString(),
std::chrono::seconds timeoutSec = std::chrono::seconds( 0 ) ) std::chrono::seconds timeoutSec = std::chrono::seconds( 0 ) )
{ {
return runCommand( return runCommand(
m_doChroot ? RunLocation::RunInTarget : RunLocation::RunInHost, m_doChroot ? RunLocation::RunInTarget : RunLocation::RunInHost, args, workingPath, stdInput, timeoutSec );
args,
workingPath,
stdInput,
timeoutSec );
} }
/** @brief Convenience wrapper for targetEnvCommand() which returns only the exit code */ /** @brief Convenience wrapper for targetEnvCommand() which returns only the exit code */
@ -279,6 +284,6 @@ private:
bool m_doChroot; bool m_doChroot;
}; };
} // namespace } // namespace CalamaresUtils
#endif #endif

View File

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

View File

@ -53,20 +53,11 @@ struct CommandLine : public QPair< QString, std::chrono::seconds >
{ {
} }
QString command() const QString command() const { return first; }
{
return first;
}
std::chrono::seconds timeout() const std::chrono::seconds timeout() const { return second; }
{
return second;
}
bool isValid() const bool isValid() const { return !first.isEmpty(); }
{
return !first.isEmpty();
}
}; };
/** @brief Abbreviation, used internally. */ /** @brief Abbreviation, used internally. */
@ -88,19 +79,16 @@ public:
CommandList( const QVariant& v, bool doChroot = true, std::chrono::seconds timeout = std::chrono::seconds( 10 ) ); CommandList( const QVariant& v, bool doChroot = true, std::chrono::seconds timeout = std::chrono::seconds( 10 ) );
~CommandList(); ~CommandList();
bool doChroot() const bool doChroot() const { return m_doChroot; }
{
return m_doChroot;
}
Calamares::JobResult run(); Calamares::JobResult run();
using CommandList_t::isEmpty; using CommandList_t::at;
using CommandList_t::count;
using CommandList_t::cbegin; using CommandList_t::cbegin;
using CommandList_t::cend; using CommandList_t::cend;
using CommandList_t::const_iterator; using CommandList_t::const_iterator;
using CommandList_t::at; using CommandList_t::count;
using CommandList_t::isEmpty;
protected: protected:
using CommandList_t::append; using CommandList_t::append;
@ -111,5 +99,5 @@ private:
std::chrono::seconds m_timeout; std::chrono::seconds m_timeout;
}; };
} // namespace } // namespace CalamaresUtils
#endif #endif

View File

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

View File

@ -68,6 +68,6 @@ namespace CalamaresUtils
DLLEXPORT QStringList extraConfigDirs(); DLLEXPORT QStringList extraConfigDirs();
/** @brief XDG_DATA_DIRS, each guaranteed to end with / */ /** @brief XDG_DATA_DIRS, each guaranteed to end with / */
DLLEXPORT QStringList extraDataDirs(); DLLEXPORT QStringList extraDataDirs();
} // namespace } // namespace CalamaresUtils
#endif #endif

View File

@ -20,8 +20,8 @@
#include "Logger.h" #include "Logger.h"
#include <iostream>
#include <fstream> #include <fstream>
#include <iostream>
#include <QCoreApplication> #include <QCoreApplication>
#include <QDir> #include <QDir>
@ -30,8 +30,8 @@
#include <QTime> #include <QTime>
#include <QVariant> #include <QVariant>
#include "utils/Dirs.h"
#include "CalamaresVersion.h" #include "CalamaresVersion.h"
#include "utils/Dirs.h"
#define LOGFILE_SIZE 1024 * 256 #define LOGFILE_SIZE 1024 * 256
@ -51,7 +51,9 @@ void
setupLogLevel( unsigned int level ) setupLogLevel( unsigned int level )
{ {
if ( level > LOGVERBOSE ) if ( level > LOGVERBOSE )
{
level = LOGVERBOSE; level = LOGVERBOSE;
}
s_threshold = level + 1; // Comparison is < in log() function s_threshold = level + 1; // Comparison is < in log() function
} }
@ -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 // 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 // logging at exit as Qt tries to use QLocale to format, but QLocale is
// on its way out. // on its way out.
logfile << QDate::currentDate().toString( Qt::ISODate ).toUtf8().data() logfile << QDate::currentDate().toString( Qt::ISODate ).toUtf8().data() << " - "
<< " - " << QTime::currentTime().toString().toUtf8().data() << " ["
<< QTime::currentTime().toString().toUtf8().data() << QString::number( debugLevel ).toUtf8().data() << "]: " << msg << std::endl;
<< " [" << QString::number( debugLevel ).toUtf8().data() << "]: "
<< msg << std::endl;
logfile.flush(); logfile.flush();
} }
@ -90,9 +90,8 @@ log( const char* msg, unsigned int debugLevel )
{ {
QMutexLocker lock( &s_mutex ); QMutexLocker lock( &s_mutex );
std::cout << QTime::currentTime().toString().toUtf8().data() std::cout << QTime::currentTime().toString().toUtf8().data() << " ["
<< " [" << QString::number( debugLevel ).toUtf8().data() << "]: " << QString::number( debugLevel ).toUtf8().data() << "]: " << msg << std::endl;
<< msg << std::endl;
std::cout.flush(); std::cout.flush();
} }
} }
@ -164,7 +163,9 @@ setupLogfile()
QMutexLocker lock( &s_mutex ); QMutexLocker lock( &s_mutex );
logfile.open( logFile().toLocal8Bit(), std::ios::app ); logfile.open( logFile().toLocal8Bit(), std::ios::app );
if ( logfile.tellp() ) if ( logfile.tellp() )
{
logfile << "\n\n" << std::endl; logfile << "\n\n" << std::endl;
}
logfile << "=== START CALAMARES " << CALAMARES_VERSION << std::endl; logfile << "=== START CALAMARES " << CALAMARES_VERSION << std::endl;
} }
@ -183,14 +184,13 @@ CLog::~CLog()
log( m_msg.toUtf8().data(), m_debugLevel ); log( m_msg.toUtf8().data(), m_debugLevel );
} }
CDebug::~CDebug() CDebug::~CDebug() {}
{
}
const char Continuation[] = "\n "; const char Continuation[] = "\n ";
const char SubEntry[] = " .. "; const char SubEntry[] = " .. ";
QString toString( const QVariant& v ) QString
toString( const QVariant& v )
{ {
auto t = v.type(); auto t = v.type();
@ -199,11 +199,15 @@ QString toString( const QVariant& v )
QStringList s; QStringList s;
auto l = v.toList(); auto l = v.toList();
for ( auto lit = l.constBegin(); lit != l.constEnd(); ++lit ) for ( auto lit = l.constBegin(); lit != l.constEnd(); ++lit )
{
s << lit->toString(); s << lit->toString();
}
return s.join( ", " ); return s.join( ", " );
} }
else else
{
return v.toString(); return v.toString();
} }
}
} // namespace } // namespace Logger

View File

@ -55,13 +55,18 @@ namespace Logger
class DLLEXPORT CDebug : public CLog class DLLEXPORT CDebug : public CLog
{ {
public: public:
CDebug( unsigned int debugLevel = LOGDEBUG ) : CLog( debugLevel ) CDebug( unsigned int debugLevel = LOGDEBUG )
: CLog( debugLevel )
{ {
if ( debugLevel <= LOGERROR ) if ( debugLevel <= LOGERROR )
{
*this << "ERROR:"; *this << "ERROR:";
}
else if ( debugLevel <= LOGWARNING ) else if ( debugLevel <= LOGWARNING )
{
*this << "WARNING:"; *this << "WARNING:";
} }
}
virtual ~CDebug(); virtual ~CDebug();
}; };
@ -113,7 +118,8 @@ namespace Logger
explicit DebugRow( const T& t, const U& u ) explicit DebugRow( const T& t, const U& u )
: first( t ) : first( t )
, second( u ) , second( u )
{} {
}
const T& first; const T& first;
const U& second; const U& second;
@ -132,7 +138,8 @@ namespace Logger
{ {
explicit DebugList( const QStringList& l ) explicit DebugList( const QStringList& l )
: list( l ) : list( l )
{} {
}
const QStringList& list; const QStringList& list;
}; };
@ -152,7 +159,8 @@ namespace Logger
public: public:
explicit DebugMap( const QVariantMap& m ) explicit DebugMap( const QVariantMap& m )
: map( m ) : map( m )
{} {
}
const QVariantMap& map; const QVariantMap& map;
}; };
@ -171,7 +179,9 @@ namespace Logger
operator<<( QDebug& s, const DebugList& c ) operator<<( QDebug& s, const DebugList& c )
{ {
for ( const auto& i : c.list ) for ( const auto& i : c.list )
{
s << Continuation << i; s << Continuation << i;
}
return s; return s;
} }
@ -183,10 +193,12 @@ namespace Logger
operator<<( QDebug& s, const DebugMap& t ) operator<<( QDebug& s, const DebugMap& t )
{ {
for ( auto it = t.map.constBegin(); it != t.map.constEnd(); ++it ) for ( auto it = t.map.constBegin(); it != t.map.constEnd(); ++it )
{
s << Continuation << it.key().toUtf8().constData() << ':' << ' ' << toString( it.value() ).toUtf8().constData(); s << Continuation << it.key().toUtf8().constData() << ':' << ' ' << toString( it.value() ).toUtf8().constData();
}
return s; return s;
} }
} // namespace } // namespace Logger
#define cDebug Logger::CDebug #define cDebug Logger::CDebug
#define cWarning() Logger::CDebug( Logger::LOGWARNING ) #define cWarning() Logger::CDebug( Logger::LOGWARNING )

View File

@ -31,9 +31,9 @@
#include <QString> #include <QString>
#include <vector>
#include <type_traits>
#include <initializer_list> #include <initializer_list>
#include <type_traits>
#include <vector>
/** @brief Type for collecting parts of a named enum. */ /** @brief Type for collecting parts of a named enum. */
template < typename T > template < typename T >
@ -53,7 +53,11 @@ struct NamedEnumTable
* *
* static const NamedEnumTable<Colors> c{ {"red", Colors::Red } }; * 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. /** @brief Find a name @p s in the table.
* *
@ -103,7 +107,8 @@ struct NamedEnumTable
/** @brief Smashes an enum value to its underlying type. */ /** @brief Smashes an enum value to its underlying type. */
template < typename E > template < typename E >
constexpr typename std::underlying_type<E>::type smash( const E 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 );
} }

View File

@ -39,7 +39,8 @@ protected:
PluginFactoryPrivate() PluginFactoryPrivate()
: catalogInitialized( false ) : catalogInitialized( false )
, q_ptr( nullptr ) , q_ptr( nullptr )
{} {
}
~PluginFactoryPrivate() {} ~PluginFactoryPrivate() {}
QHash< QString, Plugin > createInstanceHash; QHash< QString, Plugin > createInstanceHash;
@ -49,6 +50,6 @@ protected:
PluginFactory* q_ptr; PluginFactory* q_ptr;
}; };
} // namespace } // namespace Calamares
#endif #endif

View File

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

View File

@ -38,9 +38,7 @@ namespace CalamaresUtils
* @param brandingTranslationsPrefix the branding path prefix, from Calamares::Branding. * @param brandingTranslationsPrefix the branding path prefix, from Calamares::Branding.
* @param parent the parent QObject. * @param parent the parent QObject.
*/ */
DLLEXPORT void installTranslator( const QLocale& locale, DLLEXPORT void installTranslator( const QLocale& locale, const QString& brandingTranslationsPrefix, QObject* parent );
const QString& brandingTranslationsPrefix,
QObject* parent );
DLLEXPORT QString translatorLocaleName(); DLLEXPORT QString translatorLocaleName();
@ -48,8 +46,7 @@ class Retranslator : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
static void attachRetranslator( QObject* parent, static void attachRetranslator( QObject* parent, std::function< void( void ) > retranslateFunc );
std::function< void( void ) > retranslateFunc );
void addRetranslateFunc( std::function< void( void ) > retranslateFunc ); void addRetranslateFunc( std::function< void( void ) > retranslateFunc );
@ -63,10 +60,9 @@ private:
}; };
} // namespace } // namespace CalamaresUtils
#define CALAMARES_RETRANSLATE(body) \ #define CALAMARES_RETRANSLATE( body ) CalamaresUtils::Retranslator::attachRetranslator( this, [=] { body } );
CalamaresUtils::Retranslator::attachRetranslator( this, [=] { body } );
#define CALAMARES_RETRANSLATE_WIDGET( widget, body ) \ #define CALAMARES_RETRANSLATE_WIDGET( widget, body ) \
CalamaresUtils::Retranslator::attachRetranslator( widget, [=] { body } ); CalamaresUtils::Retranslator::attachRetranslator( widget, [=] { body } );

View File

@ -123,10 +123,10 @@ obscure( const QString& string )
for ( int i = 0; i < string.length(); ++i ) for ( int i = 0; i < string.length(); ++i )
// yes, no typo. can't encode ' ' or '!' because // yes, no typo. can't encode ' ' or '!' because
// they're the unicode BOM. stupid scrambling. stupid. // they're the unicode BOM. stupid scrambling. stupid.
result += ( unicode[ i ].unicode() <= 0x21 ) ? {
unicode[ i ] : result += ( unicode[ i ].unicode() <= 0x21 ) ? unicode[ i ] : QChar( 0x1001F - unicode[ i ].unicode() );
QChar( 0x1001F - unicode[ i ].unicode() ); }
return result; return result;
} }
} } // namespace CalamaresUtils

View File

@ -48,6 +48,6 @@ namespace CalamaresUtils
* @return the obfuscated string. * @return the obfuscated string.
*/ */
DLLEXPORT QString obscure( const QString& string ); DLLEXPORT QString obscure( const QString& string );
} // namespace } // namespace CalamaresUtils
#endif #endif

View File

@ -43,59 +43,71 @@ 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 ); return int( b / 1024 / 1024 );
} }
constexpr int BytesToGiB( qint64 b ) constexpr int
BytesToGiB( qint64 b )
{ {
return int( b / 1024 / 1024 / 1024 ); return int( b / 1024 / 1024 / 1024 );
} }
constexpr qint64 alignBytesToBlockSize( qint64 bytes, qint64 blocksize ) constexpr qint64
alignBytesToBlockSize( qint64 bytes, qint64 blocksize )
{ {
qint64 blocks = bytes / blocksize; qint64 blocks = bytes / blocksize;
if ( blocks * blocksize != bytes ) if ( blocks * blocksize != bytes )
{
++blocks; ++blocks;
}
return blocks * blocksize; 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 #endif

View File

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

View File

@ -57,6 +57,6 @@ namespace CalamaresUtils
* (e.g. if @p success is false). * (e.g. if @p success is false).
*/ */
DLLEXPORT QVariantMap getSubMap( const QVariantMap& map, const QString& key, bool& success ); DLLEXPORT QVariantMap getSubMap( const QVariantMap& map, const QString& key, bool& success );
} // namespace } // namespace CalamaresUtils
#endif #endif

View File

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

View File

@ -77,6 +77,6 @@ void explainYamlException( const YAML::Exception& e, const QByteArray& data, con
void explainYamlException( const YAML::Exception& e, const QByteArray& data, const QString& label ); void explainYamlException( const YAML::Exception& e, const QByteArray& data, const QString& label );
void explainYamlException( const YAML::Exception& e, const QByteArray& data ); void explainYamlException( const YAML::Exception& e, const QByteArray& data );
} // namespace } // namespace CalamaresUtils
#endif #endif