From b6974614974842020be591adccf8ebbe5c50ee13 Mon Sep 17 00:00:00 2001 From: Adriaan de Groot Date: Fri, 5 Jul 2019 11:29:14 +0200 Subject: [PATCH] [libcalamares] Add System::createTargetFile() - Calamares may need to create files in the target system; provide a convenient API for doing so. - This is mostly intended for small files with constant contents. --- .../utils/CalamaresUtilsSystem.cpp | 51 +++++++++++++++++++ src/libcalamares/utils/CalamaresUtilsSystem.h | 14 +++++ 2 files changed, 65 insertions(+) diff --git a/src/libcalamares/utils/CalamaresUtilsSystem.cpp b/src/libcalamares/utils/CalamaresUtilsSystem.cpp index 5990fbc42..698a96f30 100644 --- a/src/libcalamares/utils/CalamaresUtilsSystem.cpp +++ b/src/libcalamares/utils/CalamaresUtilsSystem.cpp @@ -243,6 +243,57 @@ System::runCommand( return ProcessResult(r, output); } +QString +System::createTargetFile( const QString& path, const QByteArray& contents ) +{ + QString completePath; + + if ( doChroot() ) + { + Calamares::GlobalStorage* gs = Calamares::JobQueue::instance() ? Calamares::JobQueue::instance()->globalStorage() : nullptr; + + if ( !gs || !gs->contains( "rootMountPoint" ) ) + { + cWarning() << "No rootMountPoint in global storage, cannot create target file" << path; + return QString(); + } + + completePath = gs->value( "rootMountPoint" ).toString() + '/' + path; + } + else + { + completePath = QStringLiteral( "/" ) + path; + } + + QFile f( completePath ); + if ( f.exists() ) + { + return QString(); + } + + QIODevice::OpenMode m = +#if QT_VERSION >= QT_VERSION_CHECK( 5, 11, 0 ) + // New flag from Qt 5.11, implies WriteOnly + QIODevice::NewOnly | +#endif + QIODevice::WriteOnly | QIODevice::Truncate; + + if ( !f.open( m ) ) + { + return QString(); + } + + if ( f.write( contents ) != contents.size() ) + { + f.close(); + f.remove(); + return QString(); + } + + f.close(); + return QFileInfo( f ).canonicalFilePath(); +} + QPair System::getTotalMemoryB() const diff --git a/src/libcalamares/utils/CalamaresUtilsSystem.h b/src/libcalamares/utils/CalamaresUtilsSystem.h index c17d52e93..8c8e61a5e 100644 --- a/src/libcalamares/utils/CalamaresUtilsSystem.h +++ b/src/libcalamares/utils/CalamaresUtilsSystem.h @@ -205,6 +205,20 @@ public: return targetEnvOutput( QStringList{ command }, output, workingPath, stdInput, timeoutSec ); } + /** @brief Create a (small-ish) file in the target system. + * + * @param path Path to the file; this is **always** interpreted + * from the root of the target system (whatever that may be, + * but / in the chroot, or / in OEM modes). + * @param contents Actual content of the file. + * + * Will not overwrite files. Returns an empty string if the + * target file already exists. + * + * @return The complete canonical path to the target file, or empty on failure. + */ + QString createTargetFile( const QString& path, const QByteArray& contents ); + /** * @brief getTotalMemoryB returns the total main memory, in bytes. *