void AdiumxtraProtocolHandler::install()
{
    if (m_url.isEmpty()) {
        Q_EMIT finished();
        return; // BundleInstaller:: xxxxx
    }

    QUrl url = QUrl::fromUserInput(m_url);
    if(url.scheme() == QLatin1String("adiumxtra")) {
        url.setScheme(QStringLiteral("http"));
    }

    QTemporaryFile *tmpFile = new QTemporaryFile();
    if (tmpFile->open()) {
        KIO::Job* getJob = KIO::file_copy(url, QUrl::fromLocalFile(tmpFile->fileName()), -1,
                                          KIO::Overwrite | KIO::HideProgressInfo);
        if (getJob->exec()) {
            qWarning() << "Download failed";
            Q_EMIT finished();
            return; // BundleInstaller::BundleCannotOpen;
        }
        getJob->deleteLater();
    }

    KArchive *archive = 0L;

    QMimeDatabase db;

    QString currentBundleMimeType =  db.mimeTypeForFile(tmpFile->fileName()).name();
    if (currentBundleMimeType == QLatin1String("application/zip")) {
        archive = new KZip(tmpFile->fileName());
    } else if (currentBundleMimeType == QLatin1String("application/x-compressed-tar") ||
               currentBundleMimeType == QLatin1String("application/x-bzip-compressed-tar") ||
               currentBundleMimeType == QLatin1String("application/x-gzip") ||
               currentBundleMimeType == QLatin1String("application/x-bzip")) {
        archive = new KTar(tmpFile->fileName());
    } else {
        KNotification *notification = new KNotification(QLatin1String("packagenotrecognized"), NULL, KNotification::Persistent);
        notification->setText( i18n("Package type not recognized or not supported") );
        notification->setActions( QStringList() << i18n("OK") );
        QObject::connect(notification, SIGNAL(action1Activated()), notification, SLOT(close()));
        QObject::connect(notification, SIGNAL(ignored()), notification, SLOT(close()));
        notification->setComponentName(ktelepathyComponentName());
        notification->sendEvent();
        qWarning() << "Unsupported file type" << currentBundleMimeType;
        Q_EMIT finished();
        return;// BundleInstaller::BundleNotValid;
    }

    if (!archive->open(QIODevice::ReadOnly)) {
        delete archive;
        qWarning() << "Cannot open theme file";
        Q_EMIT finished();
        return;// BundleInstaller::BundleCannotOpen;
    }

    ChatStyleInstaller *chatStyleInstaller = new ChatStyleInstaller(archive, tmpFile);
    if (chatStyleInstaller->validate() == BundleInstaller::BundleValid) {
        chatStyleInstaller->showRequest();

        QObject::connect(chatStyleInstaller, SIGNAL(finished(BundleInstaller::BundleStatus)),
                         chatStyleInstaller, SLOT(showResult()));
        QObject::connect(chatStyleInstaller, SIGNAL(showedResult()), this, SIGNAL(finished()));
        QObject::connect(chatStyleInstaller, SIGNAL(showedResult()),
                         chatStyleInstaller, SLOT(deleteLater()));
        QObject::connect(chatStyleInstaller, SIGNAL(ignoredRequest()), this, SIGNAL(finished()));
        QObject::connect(chatStyleInstaller, SIGNAL(ignoredRequest()),
                         chatStyleInstaller, SLOT(deleteLater()));

        return;// BundleInstaller::BundleValid;
    }
    delete chatStyleInstaller;

    EmoticonSetInstaller *emoticonSetInstaller = new EmoticonSetInstaller(archive, tmpFile);
    if(emoticonSetInstaller->validate() == BundleInstaller::BundleValid) {
        emoticonSetInstaller->showRequest();

        QObject::connect(emoticonSetInstaller, SIGNAL(finished(BundleInstaller::BundleStatus)),
                         emoticonSetInstaller, SLOT(showResult()));
        QObject::connect(emoticonSetInstaller, SIGNAL(showedResult()), this, SIGNAL(finished()));
        QObject::connect(emoticonSetInstaller, SIGNAL(showedResult()),
                         emoticonSetInstaller, SLOT(deleteLater()));
        QObject::connect(emoticonSetInstaller, SIGNAL(ignoredRequest()), this, SIGNAL(finished()));
        QObject::connect(emoticonSetInstaller, SIGNAL(ignoredRequest()),
                         emoticonSetInstaller, SLOT(deleteLater()));

        return;// BundleInstaller::BundleValid;
    }
    delete emoticonSetInstaller;

    KNotification *notification = new KNotification(QLatin1String("packagenotrecognized"),
                                                    NULL,
                                                    KNotification::Persistent);
    notification->setText( i18n("Package type not recognized or not supported") );
    QObject::connect(notification, SIGNAL(action1Activated()), notification, SLOT(close()));
    QObject::connect(notification, SIGNAL(ignored()), notification, SLOT(close()));
    notification->setActions( QStringList() << i18n("OK") );
    notification->setComponentName(ktelepathyComponentName());
    notification->sendEvent();

    Q_EMIT finished();
    return;// BundleInstaller::BundleUnknownError;
}
Пример #2
0
int main(int argc, char *argv[])
{
	QCoreApplication a(argc, argv);
	QStringList args = a.arguments();
	if (args.size() < 4) {
		out << "Usage: " << args[0] << " <version> <qtdir> <platform> [load]\n" << flush;
		return 1;
	}
	const QString version = args[1];
	const QDir qtdir = QDir(args[2]);
	const QString platform = args[3];
	if (args.size() > 5) {
		if (args[4] == "load") {
			silent = false;
		}
	}
	if (!QRegularExpression("\\d\\.\\d\\.\\d").match(version).hasMatch()) {
		out << "<version> has to be in the format #.#.#\n" << flush;
		return 1;
	}

	const QString short_version = version.left(3);

	GetFiles::version = version;

	// mappings etc.
	QList<FileGroup> mappings;
	mappings.append(FileGroup("bin", &GetFiles::binaryFiles));
	mappings.append(FileGroup("doc", &GetFiles::docFiles));
	mappings.append(FileGroup("examples", &GetFiles::exampleFiles));
	mappings.append(FileGroup("imports", &GetFiles::importsFiles));
	mappings.append(FileGroup("include", &GetFiles::includeFolders));
	mappings.append(FileGroup("lib", &GetFiles::libFiles));
	mappings.append(FileGroup("libexec", &GetFiles::libExecFiles));
	mappings.append(FileGroup("mkspecs", &GetFiles::mkSpecFiles));
	mappings.append(FileGroup("phrasebooks", &GetFiles::phrasebookFiles));
	mappings.append(FileGroup("plugins", &GetFiles::pluginNames));
	mappings.append(FileGroup("qml", &GetFiles::qmlFiles));
	mappings.append(FileGroup("translations", &GetFiles::translationFiles));
	QStringList modules;
	for (const FileGroup &files : mappings) {
		modules.append((files.fileGetter)().keys());
	}
	modules.removeDuplicates();

	out << "Copying files for the following modules: " << modules.join(", ") << "\n" << flush;

	QDir baseDir;
	for (const QString &module : modules) {
		if (baseDir.exists(module + ".tar.gz")) {
			out << "Skiping already existing module " << module << "\n" << flush;
			continue;
		}
		out << "Copying files for module " << module << "\n" << flush;
		baseDir.mkdir(module);
		QDir dir(baseDir);
		dir.cd(module);

		for (const FileGroup &files : mappings) {
			QStringList fs = (files.fileGetter)()[module];
			if (fs.isEmpty()) {
				continue;
			}
			out << "  Copying " << files.name << " files...\n" << flush;
			QDir fromDir(qtdir);
			fromDir.cd(files.name);
			QDir toDir(dir);
			toDir.mkdir(files.name);
			toDir.cd(files.name);
			copyFiles(fs, fromDir, toDir);
		}

		out << "  Creating install file for module " << module << "...\n" << flush;
		{
			QFile installFile(dir.absoluteFilePath("install.js"));
			if (!installFile.open(QFile::WriteOnly | QFile::Truncate)) {
				out << "Error opening install file: " << installFile.errorString() << "\n";
				return -1;
			}

			QTextStream js(&installFile);

			js << "FileSystem.mkpath(Paths.installPath);\n";
			for (const FileGroup &groups : mappings) {
				if (groups.fileGetter().contains(module)) {
					js << "FileSystem.install(\"" << groups.name
					   << "\", Paths.installPath + \"/" << groups.name << "\");\n";
				}
			}
			js << "\n";

			js.flush();
			installFile.close();
		}

		out << "  Creating removal file for module " << module << "...\n" << flush;
		{
			QFile removalFile(dir.absoluteFilePath("remove.js"));
			if (!removalFile.open(QFile::WriteOnly | QFile::Truncate)) {
				out << "Error opening remove file: " << removalFile.errorString() << "\n";
				return -1;
			}

			QTextStream js(&removalFile);

			for (const FileGroup &group : mappings) {
				QStringList files = (group.fileGetter)()[module];
				for (const QString &file : files) {
					js << "FileSystem.remove(Paths.installPath + \"/" << group.name << "/"
					   << file << "\");\n";
				}
			}
			js << "\n";

			js.flush();
			removalFile.close();
		}

		out << "  Creating archive for module " << module << "...\n" << flush;
		{
			KArchive *arch = new KTar(baseDir.absoluteFilePath(
				QString("%1-%2-%3.tar.gz").arg(module, version, platform)));
			arch->open(QIODevice::ReadWrite);
			for (const QString &directory : dir.entryList(QDir::NoDotAndDotDot | QDir::Dirs)) {
				arch->addLocalDirectory(dir.absoluteFilePath(directory), directory);
			}
			for (const QString &file : dir.entryList(QDir::NoDotAndDotDot | QDir::Files)) {
				arch->addLocalFile(dir.absoluteFilePath(file), file);
			}
			arch->close();
		}
	}

	out << "Creating metadata file...\n" << flush;
	{
		QFile meta(baseDir.absoluteFilePath("meta.json"));
		meta.open(QFile::WriteOnly | QFile::Truncate);
		QMap<QString, QString> descs = GetFiles::descriptions();
		QMap<QString, QStringList> deps = GetFiles::dependencies();
		QMap<QString, QMap<QString, QStringList>> ndeps = GetFiles::nativeDependencies();
		QJsonArray root;
		for (const QString &module : modules) {
			QStringList dependencies = deps[module];
			dependencies.removeAll("");
			dependencies.removeDuplicates();
			QMap<QString, QStringList> nDependencies = ndeps[module];
			QJsonObject m;
			m.insert("id", module);
			m.insert("description", descs[module]);
			m.insert("version", version);
			m.insert("platform", platform);
			m.insert("url", QString("http://localhost/soqute/archives/%1-%2-%3.tar.gz")
								.arg(module, version, platform));
			QJsonArray deps;
			for (const QString &dep : dependencies) {
				QJsonObject obj;
				obj.insert("id", dep);
				obj.insert("version", version);
				deps.append(obj);
			}
			m.insert("dependencies", deps);
			QJsonObject nativeDependencies;
			for (const QString &manager : nDependencies.keys()) {
				QJsonArray packages = QJsonArray::fromStringList(nDependencies[manager]);
				nativeDependencies.insert(manager, packages);
			}
			m.insert("nativeDependencies", nativeDependencies);
			root.append(m);
		}
		meta.write(QJsonDocument(root).toJson());
	}

	out << "Installing files to server...\n" << flush;
	{
		QDir serverRoot("/var/www");
		if (!serverRoot.exists("soqute")) {
			serverRoot.mkdir("soqute");
		}
		serverRoot.cd("soqute");
		if (!serverRoot.exists("archives")) {
			serverRoot.mkdir("archives");
		}
		serverRoot.cd("archives");
		for (const QString &archive :
			 baseDir.entryList(QStringList() << "*.tar.gz", QDir::Files)) {
			out << "  Installing " << archive << " to server...\n" << flush;
			if (serverRoot.exists(archive)) {
				serverRoot.remove(archive);
			}
			QFile::copy(baseDir.absoluteFilePath(archive),
						serverRoot.absoluteFilePath(archive));
		}
		serverRoot.cdUp();
		out << "  Installing meta.json to server...\n" << flush;
		if (serverRoot.exists("meta.json")) {
			QFile server(serverRoot.absoluteFilePath("meta.json"));
			Q_ASSERT(server.open(QFile::ReadOnly | QFile::Truncate));
			QFile local(baseDir.absoluteFilePath("meta.json"));
			Q_ASSERT(local.open(QFile::ReadOnly));
			QJsonDocument serverDoc = QJsonDocument::fromJson(server.readAll());
			server.close();
			QJsonArray serverArray = serverDoc.array();
			QJsonDocument localDoc = QJsonDocument::fromJson(local.readAll());
			local.close();
			QJsonArray localArray = localDoc.array();
			QVariantList res = serverArray.toVariantList();
			res.append(localArray.toVariantList());
			Q_ASSERT(server.open(QFile::WriteOnly | QFile::Truncate));
			server.write(QJsonDocument(QJsonArray::fromVariantList(res)).toJson());
			server.close();
		} else {
			QFile::copy(baseDir.absoluteFilePath("meta.json"),
						serverRoot.absoluteFilePath("meta.json"));
		}
	}

	out << "Done\n" << flush;
	return 0;
}
Пример #3
0
QStringList KEmoticons::installTheme(const QString &archiveName)
{
    QStringList foundThemes;
    KArchiveEntry *currentEntry = 0L;
    KArchiveDirectory* currentDir = 0L;
    KArchive *archive = 0L;

    QString localThemesDir(KStandardDirs::locateLocal("emoticons", QString()));

    if (localThemesDir.isEmpty()) {
        kError() << "Could not find a suitable place in which to install the emoticon theme";
        return QStringList();
    }

    const QString currentBundleMimeType = KMimeType::findByPath(archiveName, 0, false)->name();

    if (currentBundleMimeType == "application/zip" ||
            currentBundleMimeType == "application/x-zip" ||
            currentBundleMimeType == "application/x-zip-compressed") {
        archive = new KZip(archiveName);
    } else if (currentBundleMimeType == "application/x-compressed-tar" ||
               currentBundleMimeType == "application/x-bzip-compressed-tar" ||
               currentBundleMimeType == "application/x-lzma-compressed-tar" ||
               currentBundleMimeType == "application/x-xz-compressed-tar" ||
               currentBundleMimeType == "application/x-gzip" ||
               currentBundleMimeType == "application/x-bzip" ||
               currentBundleMimeType == "application/x-lzma" ||
	       currentBundleMimeType == "application/x-xz") {
        archive = new KTar(archiveName);
    } else if (archiveName.endsWith(QLatin1String("jisp")) || archiveName.endsWith(QLatin1String("zip"))) {
        archive = new KZip(archiveName);
    } else {
        archive = new KTar(archiveName);
    }

    if (!archive || !archive->open(QIODevice::ReadOnly)) {
        kError() << "Could not open" << archiveName << "for unpacking";
        delete archive;
        return QStringList();
    }

    const KArchiveDirectory* rootDir = archive->directory();

    // iterate all the dirs looking for an emoticons.xml file
    const QStringList entries = rootDir->entries();
    for (QStringList::ConstIterator it = entries.begin(); it != entries.end(); ++it) {
        currentEntry = const_cast<KArchiveEntry*>(rootDir->entry(*it));

        if (currentEntry->isDirectory()) {
            currentDir = dynamic_cast<KArchiveDirectory*>(currentEntry);

            for (int i = 0; i < d->m_loaded.size(); ++i) {
                QString fName = d->m_loaded.at(i)->property("X-KDE-EmoticonsFileName").toString();

                if (currentDir && currentDir->entry(fName) != NULL) {
                    foundThemes.append(currentDir->name());
                }
            }
        }
    }

    if (foundThemes.isEmpty()) {
        kError() << "The file" << archiveName << "is not a valid emoticon theme archive";
        archive->close();
        delete archive;
        return QStringList();
    }

    for (int themeIndex = 0; themeIndex < foundThemes.size(); ++themeIndex) {
        const QString &theme = foundThemes[themeIndex];

        currentEntry = const_cast<KArchiveEntry *>(rootDir->entry(theme));
        if (currentEntry == 0) {
            kDebug() << "couldn't get next archive entry";
            continue;
        }

        if (currentEntry->isDirectory()) {
            currentDir = dynamic_cast<KArchiveDirectory*>(currentEntry);

            if (currentDir == 0) {
                kDebug() << "couldn't cast archive entry to KArchiveDirectory";
                continue;
            }

            currentDir->copyTo(localThemesDir + theme);
        }
    }

    archive->close();
    delete archive;

    return foundThemes;
}
Пример #4
0
void MyView::startFolderEncode(TQStringList selec,TQStringList encryptOptions,bool ,bool symetric)
{
TQString extension;

if (compressionScheme==0)
	extension=".zip";
	else if (compressionScheme==1)
	extension=".tar.gz";
	else
	extension=".tar.bz2";

if (encryptOptions.find("armor")!=encryptOptions.end () )
                extension+=".asc";
        else if (KGpgSettings::pgpExtension())
                extension+=".pgp";
        else
                extension+=".gpg";

KURL encryptedFile(droppedUrls.first().path()+extension);
TQFile encryptedFolder(droppedUrls.first().path()+extension);
if (encryptedFolder.exists()) {
			dialogue->hide();
			TDEIO::RenameDlg *over=new TDEIO::RenameDlg(0,i18n("File Already Exists"),TQString(),encryptedFile.path(),TDEIO::M_OVERWRITE);
		    	if (over->exec()==TQDialog::Rejected)
	    		{
                	delete over;
                	return;
            		}
	    		encryptedFile=over->newDestURL();
	    		delete over;
			dialogue->show();   /////// strange, but if dialogue is hidden, the passive popup is not displayed...
                }

pop = new KPassivePopup();
	pop->setView(i18n("Processing folder compression and encryption"),i18n("Please wait..."),TDEGlobal::iconLoader()->loadIcon("kgpg",TDEIcon::Desktop));
	pop->setAutoDelete(false);
	pop->show();
	kapp->processEvents();
	dialogue->slotAccept();
	dialogue=0L;

	KArchive *arch;
	if (compressionScheme==0)
	arch=new KZip(kgpgfoldertmp->name());
	else if (compressionScheme==1)
	arch=new KTar(kgpgfoldertmp->name(), "application/x-gzip");
	else
	arch=new KTar(kgpgfoldertmp->name(), "application/x-bzip2");

        if (!arch->open( IO_WriteOnly )) {
                KMessageBox::sorry(0,i18n("Unable to create temporary file"));
		delete arch;
                return;
        }
        arch->addLocalDirectory (droppedUrls.first().path(),droppedUrls.first().fileName());
        arch->close();
        delete arch;

        KgpgInterface *folderprocess=new KgpgInterface();
        folderprocess->KgpgEncryptFile(selec,KURL(kgpgfoldertmp->name()),encryptedFile,encryptOptions,symetric);
        connect(folderprocess,TQT_SIGNAL(encryptionfinished(KURL)),TQT_TQOBJECT(this),TQT_SLOT(slotFolderFinished(KURL)));
        connect(folderprocess,TQT_SIGNAL(errormessage(TQString)),TQT_TQOBJECT(this),TQT_SLOT(slotFolderFinishedError(TQString)));
}
Пример #5
0
bool PackageJobThread::installPackage(const QString &src, const QString &dest, OperationType operation)
{
    QDir root(dest);
    if (!root.exists()) {
        QDir().mkpath(dest);
        if (!root.exists()) {
            d->errorMessage = i18n("Could not create package root directory: %1", dest);
            d->errorCode = Package::JobError::RootCreationError;
            //qWarning() << "Could not create package root directory: " << dest;
            return false;
        }
    }

    QFileInfo fileInfo(src);
    if (!fileInfo.exists()) {
        d->errorMessage = i18n("No such file: %1", src);
        d->errorCode = Package::JobError::PackageFileNotFoundError;
        return false;
    }

    QString path;
    QTemporaryDir tempdir;
    bool archivedPackage = false;

    if (fileInfo.isDir()) {
        // we have a directory, so let's just install what is in there
        path = src;
        // make sure we end in a slash!
        if (!path.endsWith('/')) {
            path.append('/');
        }
    } else {
        KArchive *archive = 0;
        QMimeDatabase db;
        QMimeType mimetype = db.mimeTypeForFile(src);
        if (mimetype.inherits(QStringLiteral("application/zip"))) {
            archive = new KZip(src);
        } else if (mimetype.inherits(QStringLiteral("application/x-compressed-tar")) ||
                   mimetype.inherits(QStringLiteral("application/x-tar")) ||
                   mimetype.inherits(QStringLiteral("application/x-bzip-compressed-tar")) ||
                   mimetype.inherits(QStringLiteral("application/x-xz")) ||
                   mimetype.inherits(QStringLiteral("application/x-lzma"))) {
            archive = new KTar(src);
        } else {
            //qWarning() << "Could not open package file, unsupported archive format:" << src << mimetype.name();
            d->errorMessage = i18n("Could not open package file, unsupported archive format: %1 %2", src, mimetype.name());
            d->errorCode = Package::JobError::UnsupportedArchiveFormatError;
            return false;
        }

        if (!archive->open(QIODevice::ReadOnly)) {
            //qWarning() << "Could not open package file:" << src;
            delete archive;
            d->errorMessage = i18n("Could not open package file: %1", src);
            d->errorCode = Package::JobError::PackageOpenError;
            return false;
        }

        archivedPackage = true;
        path = tempdir.path() + '/';

        d->installPath = path;

        const KArchiveDirectory *source = archive->directory();
        source->copyTo(path);

        QStringList entries = source->entries();
        if (entries.count() == 1) {
            const KArchiveEntry *entry = source->entry(entries[0]);
            if (entry->isDirectory()) {
                path.append(entry->name()).append("/");
            }
        }

        delete archive;
    }

    QDir packageDir(path);
    QFileInfoList entries = packageDir.entryInfoList(*metaDataFiles);
    KPluginMetaData meta;
    if (!entries.isEmpty()) {
        const QString metadataFilePath = entries.first().filePath();
        if (metadataFilePath.endsWith(QLatin1String(".desktop")))
            meta = KPluginMetaData(metadataFilePath);
        else {
            QFile f(metadataFilePath);
            if(!f.open(QIODevice::ReadOnly)){
                qWarning() << "Couldn't open metadata file" << src << path;
                d->errorMessage = i18n("Could not open metadata file: %1", src);
                d->errorCode = Package::JobError::MetadataFileMissingError;
                return false;
            }
            QJsonObject metadataObject = QJsonDocument::fromJson(f.readAll()).object();
            meta = KPluginMetaData(metadataObject, QString(), metadataFilePath);
        }
    }

    if (!meta.isValid()) {
        qDebug() << "No metadata file in package" << src << path;
        d->errorMessage = i18n("No metadata file in package: %1", src);
        d->errorCode = Package::JobError::MetadataFileMissingError;
        return false;
    }


    QString pluginName = meta.pluginId();
    qDebug() << "pluginname: " << meta.pluginId();
    if (pluginName.isEmpty()) {
        //qWarning() << "Package plugin name not specified";
        d->errorMessage = i18n("Package plugin name not specified: %1", src);
        d->errorCode = Package::JobError::PluginNameMissingError;
        return false;
    }

    // Ensure that package names are safe so package uninstall can't inject
    // bad characters into the paths used for removal.
    QRegExp validatePluginName("^[\\w-\\.]+$"); // Only allow letters, numbers, underscore and period.
    if (!validatePluginName.exactMatch(pluginName)) {
        //qDebug() << "Package plugin name " << pluginName << "contains invalid characters";
        d->errorMessage = i18n("Package plugin name %1 contains invalid characters", pluginName);
        d->errorCode = Package::JobError::PluginNameInvalidError;
        return false;
    }

    QString targetName = dest;
    if (targetName[targetName.size() - 1] != '/') {
        targetName.append('/');
    }
    targetName.append(pluginName);

    if (QFile::exists(targetName)) {
        if (operation == Update) {
            KPluginMetaData oldMeta(targetName + QLatin1String("/metadata.desktop"));

            if (oldMeta.serviceTypes() != meta.serviceTypes()) {
                d->errorMessage = i18n("The new package has a different type from the old version already installed.", meta.version(), meta.pluginId(), oldMeta.version());
                d->errorCode = Package::JobError::UpdatePackageTypeMismatchError;
            } else if (isVersionNewer(oldMeta.version(), meta.version())) {
                const bool ok = uninstallPackage(targetName);
                if (!ok) {
                    d->errorMessage = i18n("Impossible to remove the old installation of %1 located at %2. error: %3", pluginName, targetName, d->errorMessage);
                    d->errorCode = Package::JobError::OldVersionRemovalError;
                }
            } else {
                d->errorMessage = i18n("Not installing version %1 of %2. Version %3 already installed.", meta.version(), meta.pluginId(), oldMeta.version());
                d->errorCode = Package::JobError::NewerVersionAlreadyInstalledError;
            }
        } else {
            d->errorMessage = i18n("%1 already exists", targetName);
            d->errorCode = Package::JobError::PackageAlreadyInstalledError;
        }

        if (d->errorCode != KJob::NoError) {
            d->installPath = targetName;
            return false;
        }
    }

    //install dependencies
    const QStringList dependencies = KPluginMetaData::readStringList(meta.rawData(), QStringLiteral("X-KPackage-Dependencies"));
    for(const QString &dep : dependencies) {
        QUrl depUrl(dep);
        if (!installDependency(depUrl)) {
            d->errorMessage = i18n("Could not install dependency: %1", dep);
            d->errorCode = Package::JobError::PackageCopyError;
            return false;
        }
    }

    if (archivedPackage) {
        // it's in a temp dir, so just move it over.
        const bool ok = copyFolder(path, targetName);
        removeFolder(path);
        if (!ok) {
            //qWarning() << "Could not move package to destination:" << targetName;
            d->errorMessage = i18n("Could not move package to destination: %1", targetName);
            d->errorCode = Package::JobError::PackageMoveError;
            return false;
        }
    } else {
        // it's a directory containing the stuff, so copy the contents rather
        // than move them
        const bool ok = copyFolder(path, targetName);
        if (!ok) {
            //qWarning() << "Could not copy package to destination:" << targetName;
            d->errorMessage = i18n("Could not copy package to destination: %1", targetName);
            d->errorCode = Package::JobError::PackageCopyError;
            return false;
        }
    }

    if (archivedPackage) {
        // no need to remove the temp dir (which has been successfully moved if it's an archive)
        tempdir.setAutoRemove(false);
    }


    indexDirectory(dest, QStringLiteral("kpluginindex.json"));


    d->installPath = targetName;

    //qWarning() << "Not updating kbuildsycoca4, since that will go away. Do it yourself for now if needed.";
    return true;
}
Пример #6
0
QString AppWizardPlugin::createProject(const ApplicationInfo& info)
{
    QFileInfo templateInfo(info.appTemplate);
    if (!templateInfo.exists()) {
        qWarning() << "Project app template does not exist:" << info.appTemplate;
        return QString();
    }

    QString templateName = templateInfo.baseName();
    QString templateArchive;
    const QStringList filters = {templateName + QStringLiteral(".*")};
    const QStringList matchesPaths = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("kdevappwizard/templates/"), QStandardPaths::LocateDirectory);
    foreach(const QString& matchesPath, matchesPaths) {
        const QStringList files = QDir(matchesPath).entryList(filters);
        if(!files.isEmpty()) {
            templateArchive = matchesPath + files.first();
        }
    }

    if(templateArchive.isEmpty()) {
        qWarning() << "Template name does not exist in the template list";
        return QString();
    }

    QUrl dest = info.location;

    //prepare variable substitution hash
    m_variables.clear();
    m_variables[QStringLiteral("APPNAME")] = info.name;
    m_variables[QStringLiteral("APPNAMEUC")] = info.name.toUpper();
    m_variables[QStringLiteral("APPNAMELC")] = info.name.toLower();
    m_variables[QStringLiteral("APPNAMEID")] = generateIdentifier(info.name);
    m_variables[QStringLiteral("PROJECTDIR")] = dest.toLocalFile();
    // backwards compatibility
    m_variables[QStringLiteral("dest")] = m_variables[QStringLiteral("PROJECTDIR")];
    m_variables[QStringLiteral("PROJECTDIRNAME")] = dest.fileName();
    m_variables[QStringLiteral("VERSIONCONTROLPLUGIN")] = info.vcsPluginName;

    KArchive* arch = nullptr;
    if( templateArchive.endsWith(QLatin1String(".zip")) )
    {
        arch = new KZip(templateArchive);
    }
    else
    {
        arch = new KTar(templateArchive, QStringLiteral("application/x-bzip"));
    }
    if (arch->open(QIODevice::ReadOnly))
    {
        QTemporaryDir tmpdir;
        QString unpackDir = tmpdir.path(); //the default value for all Centralized VCS
        IPlugin* plugin = core()->pluginController()->loadPlugin( info.vcsPluginName );
        if( info.vcsPluginName.isEmpty() || ( plugin && plugin->extension<KDevelop::IDistributedVersionControl>() ) )
        {
            if( !QFileInfo::exists( dest.toLocalFile() ) )
            {
                QDir::root().mkpath( dest.toLocalFile() );
            }
            unpackDir = dest.toLocalFile(); //in DVCS we unpack template directly to the project's directory
        }
        else
        {
            QUrl url = KIO::upUrl(dest);
            if(!QFileInfo::exists(url.toLocalFile())) {
                QDir::root().mkpath(url.toLocalFile());
            }
        }

        if ( !unpackArchive( arch->directory(), unpackDir ) )
        {
            QString errorMsg = i18n("Could not create new project");
            vcsError(errorMsg, tmpdir, QUrl::fromLocalFile(unpackDir));
            return QString();
        }

        if( !info.vcsPluginName.isEmpty() )
        {
            if (!plugin)
            {
                // Red Alert, serious program corruption.
                // This should never happen, the vcs dialog presented a list of vcs
                // systems and now the chosen system doesn't exist anymore??
                tmpdir.remove();
                return QString();
            }

            IDistributedVersionControl* dvcs = toDVCS(plugin);
            ICentralizedVersionControl* cvcs = toCVCS(plugin);
            bool success = false;
            if (dvcs)
            {
                success = initializeDVCS(dvcs, info, tmpdir);
            }
            else if (cvcs)
            {
                success = initializeCVCS(cvcs, info, tmpdir);
            }
            else
            {
                if (KMessageBox::Continue ==
                    KMessageBox::warningContinueCancel(nullptr,
                    QStringLiteral("Failed to initialize version control system, "
                    "plugin is neither VCS nor DVCS.")))
                    success = true;
            }
            if (!success) return QString();
        }
        tmpdir.remove();
    }else
    {
        qCDebug(PLUGIN_APPWIZARD) << "failed to open template archive";
        return QString();
    }

    QString projectFileName = QDir::cleanPath( dest.toLocalFile() + '/' + info.name + ".kdev4" );

    // Loop through the new project directory and try to detect the first .kdev4 file.
    // If one is found this file will be used. So .kdev4 file can be stored in any subdirectory and the
    // project templates can be more complex.
    QDirIterator it(QDir::cleanPath( dest.toLocalFile()), QStringList() << QStringLiteral("*.kdev4"), QDir::NoFilter, QDirIterator::Subdirectories);
    if(it.hasNext() == true)
    {
        projectFileName = it.next();
    }

    qCDebug(PLUGIN_APPWIZARD) << "Returning" << projectFileName << QFileInfo::exists( projectFileName ) ;

    if( ! QFileInfo::exists( projectFileName ) )
    {
        qCDebug(PLUGIN_APPWIZARD) << "creating .kdev4 file";
        KSharedConfigPtr cfg = KSharedConfig::openConfig( projectFileName, KConfig::SimpleConfig );
        KConfigGroup project = cfg->group( "Project" );
        project.writeEntry( "Name", info.name );
        QString manager = QStringLiteral("KDevGenericManager");

        QDir d( dest.toLocalFile() );
        auto data = ICore::self()->pluginController()->queryExtensionPlugins(QStringLiteral("org.kdevelop.IProjectFileManager"));
        foreach(const KPluginMetaData& info, data) {
            QStringList filter = KPluginMetaData::readStringList(info.rawData(), QStringLiteral("X-KDevelop-ProjectFilesFilter"));
            if (!filter.isEmpty()) {
                if (!d.entryList(filter).isEmpty()) {
                    manager = info.pluginId();
                    break;
                }
            }
        }