OSDN Git Service

Merge remote branch 'origin/2.0'
[qt-creator-jp/qt-creator-jp.git] / src / plugins / qt4projectmanager / qt-maemo / maemopackagecreationstep.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
6 **
7 ** This file is part of Qt Creator.
8 **
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** No Commercial Usage
11 ** This file contains pre-release code and may not be distributed.
12 ** You may use this file in accordance with the terms and conditions
13 ** contained in the Technology Preview License Agreement accompanying
14 ** this package.
15 **
16 ** GNU Lesser General Public License Usage
17 ** Alternatively, this file may be used under the terms of the GNU Lesser
18 ** General Public License version 2.1 as published by the Free Software
19 ** Foundation and appearing in the file LICENSE.LGPL included in the
20 ** packaging of this file.  Please review the following information to
21 ** ensure the GNU Lesser General Public License version 2.1 requirements
22 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23 **
24 ** In addition, as a special exception, Nokia gives you certain additional
25 ** rights.  These rights are described in the Nokia Qt LGPL Exception
26 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27 **
28 ** If you have questions regarding the use of this file, please contact
29 ** Nokia at qt-info@nokia.com.
30 **
31 **
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "maemopackagecreationstep.h"
43
44 #include "maemoconstants.h"
45 #include "maemopackagecreationwidget.h"
46 #include "maemopackagecontents.h"
47 #include "maemotoolchain.h"
48
49 #include <projectexplorer/projectexplorerconstants.h>
50 #include <qt4buildconfiguration.h>
51 #include <qt4project.h>
52 #include <qt4target.h>
53
54 #include <QtCore/QDir>
55 #include <QtCore/QFile>
56 #include <QtCore/QFileInfo>
57 #include <QtCore/QProcess>
58 #include <QtCore/QProcessEnvironment>
59 #include <QtCore/QStringBuilder>
60 #include <QtGui/QWidget>
61
62 namespace { const QLatin1String PackagingEnabledKey("Packaging Enabled"); }
63
64 using namespace ProjectExplorer::Constants;
65 using ProjectExplorer::BuildConfiguration;
66 using ProjectExplorer::BuildStepConfigWidget;
67 using ProjectExplorer::Task;
68
69 namespace Qt4ProjectManager {
70 namespace Internal {
71
72 MaemoPackageCreationStep::MaemoPackageCreationStep(BuildConfiguration *buildConfig)
73     : ProjectExplorer::BuildStep(buildConfig, CreatePackageId),
74       m_packageContents(new MaemoPackageContents(this)),
75       m_packagingEnabled(true)
76 {
77 }
78
79 MaemoPackageCreationStep::MaemoPackageCreationStep(BuildConfiguration *buildConfig,
80     MaemoPackageCreationStep *other)
81     : BuildStep(buildConfig, other),
82       m_packageContents(new MaemoPackageContents(this)),
83       m_packagingEnabled(other->m_packagingEnabled)
84
85 {
86
87 }
88
89 bool MaemoPackageCreationStep::init()
90 {
91     return true;
92 }
93
94 QVariantMap MaemoPackageCreationStep::toMap() const
95 {
96     QVariantMap map(ProjectExplorer::BuildStep::toMap());
97     map.insert(PackagingEnabledKey, m_packagingEnabled);
98     return map;
99 }
100
101 bool MaemoPackageCreationStep::fromMap(const QVariantMap &map)
102 {
103     m_packagingEnabled = map.value(PackagingEnabledKey, true).toBool();
104     return ProjectExplorer::BuildStep::fromMap(map);
105 }
106
107 void MaemoPackageCreationStep::run(QFutureInterface<bool> &fi)
108 {
109     fi.reportResult(m_packagingEnabled ? createPackage() : true);
110 }
111
112 BuildStepConfigWidget *MaemoPackageCreationStep::createConfigWidget()
113 {
114     return new MaemoPackageCreationWidget(this);
115 }
116
117 bool MaemoPackageCreationStep::createPackage()
118 {
119     if (!packagingNeeded())
120         return true;
121
122     QTextCharFormat textCharFormat;
123     emit addOutput(tr("Creating package file ..."), textCharFormat);
124     QFile configFile(targetRoot() % QLatin1String("/config.sh"));
125     if (!configFile.open(QIODevice::ReadOnly)) {
126         raiseError(tr("Cannot open MADDE config file '%1'.")
127                    .arg(nativePath(configFile)));
128         return false;
129     }
130
131     QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
132     const QString &path = QDir::toNativeSeparators(maddeRoot() + QLatin1Char('/'));
133
134     const QLatin1String key("PATH");
135     QString colon = QLatin1String(":");
136 #ifdef Q_OS_WIN
137     colon = QLatin1String(";");
138     env.insert(key, targetRoot() % "/bin" % colon % env.value(key));
139     env.insert(key, path % QLatin1String("bin") % colon % env.value(key));
140 #endif
141     env.insert(key, path % QLatin1String("madbin") % colon % env.value(key));
142     env.insert(QLatin1String("PERL5LIB"), path % QLatin1String("madlib/perl5"));
143
144     const QString buildDir = QFileInfo(localExecutableFilePath()).absolutePath();
145     env.insert(QLatin1String("PWD"), buildDir);
146
147     const QRegExp envPattern(QLatin1String("([^=]+)=[\"']?([^;\"']+)[\"']? ;.*"));
148     QByteArray line;
149     do {
150         line = configFile.readLine(200);
151         if (envPattern.exactMatch(line))
152             env.insert(envPattern.cap(1), envPattern.cap(2));
153     } while (!line.isEmpty());
154     
155     QProcess buildProc;
156     buildProc.setProcessEnvironment(env);
157     buildProc.setWorkingDirectory(buildDir);
158
159     if (!QFileInfo(buildDir + QLatin1String("/debian")).exists()) {
160         const QString command = QLatin1String("dh_make -s -n -p ")
161             % executableFileName().toLower() % versionString();
162         if (!runCommand(buildProc, command))
163             return false;
164         QFile rulesFile(buildDir + QLatin1String("/debian/rules"));
165         if (!rulesFile.open(QIODevice::ReadWrite)) {
166             raiseError(tr("Packaging Error: Cannot open file '%1'.")
167                        .arg(nativePath(rulesFile)));
168             return false;
169         }
170
171         QByteArray rulesContents = rulesFile.readAll();
172         rulesContents.replace("DESTDIR", "INSTALL_ROOT");
173         rulesFile.resize(0);
174         rulesFile.write(rulesContents);
175         if (rulesFile.error() != QFile::NoError) {
176             raiseError(tr("Packaging Error: Cannot write file '%1'.")
177                        .arg(nativePath(rulesFile)));
178             return false;
179         }
180     }
181
182     if (!runCommand(buildProc, QLatin1String("dh_installdirs")))
183         return false;
184     
185     const QDir debianRoot = QDir(buildDir % QLatin1String("/debian/")
186                                  % executableFileName().toLower());
187     for (int i = 0; i < m_packageContents->rowCount(); ++i) {
188         const MaemoPackageContents::Deployable &d
189             = m_packageContents->deployableAt(i);
190         const QString absTargetDir = debianRoot.path() + '/' + d.remoteDir;
191         const QString targetFile
192             = absTargetDir + '/' + QFileInfo(d.localFilePath).fileName();
193         const QString relTargetDir = debianRoot.relativeFilePath(absTargetDir);
194         if (!debianRoot.exists(relTargetDir)
195             && !debianRoot.mkpath(relTargetDir)) {
196             raiseError(tr("Packaging Error: Could not create directory '%1'.")
197                        .arg(QDir::toNativeSeparators(absTargetDir)));
198             return false;
199         }
200         if (QFile::exists(targetFile) && !QFile::remove(targetFile)) {
201             raiseError(tr("Packaging Error: Could not replace file '%1'.")
202                        .arg(QDir::toNativeSeparators(targetFile)));
203             return false;
204         }
205
206         if (!QFile::copy(d.localFilePath, targetFile)) {
207             raiseError(tr("Packaging Error: Could not copy '%1' to '%2'.")
208                        .arg(QDir::toNativeSeparators(d.localFilePath))
209                        .arg(QDir::toNativeSeparators(targetFile)));
210             return false;
211         }
212     }
213
214     const QStringList commands = QStringList() << QLatin1String("dh_link")
215         << QLatin1String("dh_fixperms") << QLatin1String("dh_installdeb")
216         << QLatin1String("dh_shlibdeps") << QLatin1String("dh_gencontrol")
217         << QLatin1String("dh_md5sums") << QLatin1String("dh_builddeb --destdir=.");
218     foreach (const QString &command, commands) {
219         if (!runCommand(buildProc, command))
220             return false;
221     }
222
223     emit addOutput(tr("Package created."), textCharFormat);
224     m_packageContents->setUnModified();
225     return true;
226 }
227
228 bool MaemoPackageCreationStep::runCommand(QProcess &proc, const QString &command)
229 {
230     QTextCharFormat textCharFormat;
231     emit addOutput(tr("Package Creation: Running command '%1'.").arg(command), textCharFormat);
232     QString perl;
233 #ifdef Q_OS_WIN
234     perl = maddeRoot() + QLatin1String("/bin/perl.exe ");
235 #endif
236     proc.start(perl + maddeRoot() % QLatin1String("/madbin/") % command);
237     if (!proc.waitForStarted()) {
238         raiseError(tr("Packaging failed."),
239             tr("Packaging error: Could not start command '%1'. Reason: %2")
240             .arg(command).arg(proc.errorString()));
241         return false;
242     }
243     proc.write("\n"); // For dh_make
244     proc.waitForFinished(-1);
245     if (proc.error() != QProcess::UnknownError || proc.exitCode() != 0) {
246         QString mainMessage = tr("Packaging Error: Command '%1' failed.")
247             .arg(command);
248         if (proc.error() != QProcess::UnknownError)
249             mainMessage += tr(" Reason: %1").arg(proc.errorString());
250         raiseError(mainMessage, mainMessage + QLatin1Char('\n')
251                    + tr("Output was: ") + proc.readAllStandardError()
252                    + QLatin1Char('\n') + proc.readAllStandardOutput());
253         return false;
254     }
255     return true;
256 }
257
258 const Qt4BuildConfiguration *MaemoPackageCreationStep::qt4BuildConfiguration() const
259 {
260     return static_cast<Qt4BuildConfiguration *>(buildConfiguration());
261 }
262
263 QString MaemoPackageCreationStep::localExecutableFilePath() const
264 {
265     const TargetInformation &ti = qt4BuildConfiguration()->qt4Target()
266         ->qt4Project()->rootProjectNode()->targetInformation();
267     if (!ti.valid)
268         return QString();
269     return QDir::toNativeSeparators(QDir::cleanPath(ti.workingDir
270         + QLatin1Char('/') + executableFileName()));
271 }
272
273 QString MaemoPackageCreationStep::executableFileName() const
274 {
275     const Qt4Project * const project
276         = qt4BuildConfiguration()->qt4Target()->qt4Project();
277     const TargetInformation &ti
278         = project->rootProjectNode()->targetInformation();
279     if (!ti.valid)
280         return QString();
281
282     return project->rootProjectNode()->projectType() == LibraryTemplate
283         ? QLatin1String("lib") + ti.target + QLatin1String(".so")
284         : ti.target;
285 }
286
287 const MaemoToolChain *MaemoPackageCreationStep::maemoToolChain() const
288 {
289     return static_cast<MaemoToolChain *>(qt4BuildConfiguration()->toolChain());
290 }
291
292 QString MaemoPackageCreationStep::maddeRoot() const
293 {
294     return maemoToolChain()->maddeRoot();
295 }
296
297 QString MaemoPackageCreationStep::targetRoot() const
298 {
299     return maemoToolChain()->targetRoot();
300 }
301
302 bool MaemoPackageCreationStep::packagingNeeded() const
303 {
304     QFileInfo packageInfo(packageFilePath());
305     if (!packageInfo.exists() || m_packageContents->isModified())
306         return true;
307
308     for (int i = 0; i < m_packageContents->rowCount(); ++i) {
309         if (packageInfo.lastModified()
310             <= QFileInfo(m_packageContents->deployableAt(i).localFilePath)
311                .lastModified())
312             return true;
313     }
314
315     return false;
316 }
317
318 QString MaemoPackageCreationStep::packageFilePath() const
319 {
320     QFileInfo execInfo(localExecutableFilePath());
321     return execInfo.path() % QDir::separator() % execInfo.fileName().toLower()
322         % versionString() % QLatin1String("_armel.deb");
323 }
324
325 QString MaemoPackageCreationStep::versionString() const
326 {
327     return QLatin1String("_0.1");
328 }
329
330 QString MaemoPackageCreationStep::nativePath(const QFile &file) const
331 {
332     return QDir::toNativeSeparators(QFileInfo(file).filePath());
333 }
334
335 void MaemoPackageCreationStep::raiseError(const QString &shortMsg,
336                                           const QString &detailedMsg)
337 {
338     QTextCharFormat textCharFormat;
339     emit addOutput(detailedMsg.isNull() ? shortMsg : detailedMsg, textCharFormat);
340     emit addTask(Task(Task::Error, shortMsg, QString(), -1,
341                       TASK_CATEGORY_BUILDSYSTEM));
342 }
343
344 const QLatin1String MaemoPackageCreationStep::CreatePackageId("Qt4ProjectManager.MaemoPackageCreationStep");
345
346 } // namespace Internal
347 } // namespace Qt4ProjectManager