OSDN Git Service

Allow the user to set the version number used for the build deb package.
[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 {
63     const QLatin1String PackagingEnabledKey("Packaging Enabled");
64     const QLatin1String DefaultVersionNumber("0.0.1");
65     const QLatin1String VersionNumberKey("Version Number");
66 }
67
68 using namespace ProjectExplorer::Constants;
69 using ProjectExplorer::BuildConfiguration;
70 using ProjectExplorer::BuildStepConfigWidget;
71 using ProjectExplorer::Task;
72
73 namespace Qt4ProjectManager {
74 namespace Internal {
75
76 MaemoPackageCreationStep::MaemoPackageCreationStep(BuildConfiguration *buildConfig)
77     : ProjectExplorer::BuildStep(buildConfig, CreatePackageId),
78       m_packageContents(new MaemoPackageContents(this)),
79       m_packagingEnabled(true),
80       m_versionString(DefaultVersionNumber)
81 {
82 }
83
84 MaemoPackageCreationStep::MaemoPackageCreationStep(BuildConfiguration *buildConfig,
85     MaemoPackageCreationStep *other)
86     : BuildStep(buildConfig, other),
87       m_packageContents(new MaemoPackageContents(this)),
88       m_packagingEnabled(other->m_packagingEnabled),
89       m_versionString(other->m_versionString)
90 {
91 }
92
93 bool MaemoPackageCreationStep::init()
94 {
95     return true;
96 }
97
98 QVariantMap MaemoPackageCreationStep::toMap() const
99 {
100     QVariantMap map(ProjectExplorer::BuildStep::toMap());
101     map.insert(PackagingEnabledKey, m_packagingEnabled);
102     map.insert(VersionNumberKey, m_versionString);
103     return map.unite(m_packageContents->toMap());
104 }
105
106 bool MaemoPackageCreationStep::fromMap(const QVariantMap &map)
107 {
108     m_packageContents->fromMap(map);
109     m_packagingEnabled = map.value(PackagingEnabledKey, true).toBool();
110     m_versionString = map.value(VersionNumberKey, DefaultVersionNumber).toString();
111     return ProjectExplorer::BuildStep::fromMap(map);
112 }
113
114 void MaemoPackageCreationStep::run(QFutureInterface<bool> &fi)
115 {
116     fi.reportResult(m_packagingEnabled ? createPackage() : true);
117 }
118
119 BuildStepConfigWidget *MaemoPackageCreationStep::createConfigWidget()
120 {
121     return new MaemoPackageCreationWidget(this);
122 }
123
124 bool MaemoPackageCreationStep::createPackage()
125 {
126     if (!packagingNeeded())
127         return true;
128
129     QTextCharFormat textCharFormat;
130     emit addOutput(tr("Creating package file ..."), textCharFormat);
131     QFile configFile(targetRoot() % QLatin1String("/config.sh"));
132     if (!configFile.open(QIODevice::ReadOnly)) {
133         raiseError(tr("Cannot open MADDE config file '%1'.")
134                    .arg(nativePath(configFile)));
135         return false;
136     }
137
138     QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
139     const QString &path = QDir::toNativeSeparators(maddeRoot() + QLatin1Char('/'));
140
141     const QLatin1String key("PATH");
142     QString colon = QLatin1String(":");
143 #ifdef Q_OS_WIN
144     colon = QLatin1String(";");
145     env.insert(key, targetRoot() % "/bin" % colon % env.value(key));
146     env.insert(key, path % QLatin1String("bin") % colon % env.value(key));
147 #endif
148     env.insert(key, path % QLatin1String("madbin") % colon % env.value(key));
149     env.insert(QLatin1String("PERL5LIB"), path % QLatin1String("madlib/perl5"));
150
151     const QString buildDir = QFileInfo(localExecutableFilePath()).absolutePath();
152     env.insert(QLatin1String("PWD"), buildDir);
153
154     const QRegExp envPattern(QLatin1String("([^=]+)=[\"']?([^;\"']+)[\"']? ;.*"));
155     QByteArray line;
156     do {
157         line = configFile.readLine(200);
158         if (envPattern.exactMatch(line))
159             env.insert(envPattern.cap(1), envPattern.cap(2));
160     } while (!line.isEmpty());
161     
162     QProcess buildProc;
163     buildProc.setProcessEnvironment(env);
164     buildProc.setWorkingDirectory(buildDir);
165
166     if (!QFileInfo(buildDir + QLatin1String("/debian")).exists()) {
167         const QString command = QLatin1String("dh_make -s -n -p ")
168             % executableFileName().toLower() % QLatin1Char('_') % versionString();
169         if (!runCommand(buildProc, command))
170             return false;
171
172         QFile rulesFile(buildDir + QLatin1String("/debian/rules"));
173         if (!rulesFile.open(QIODevice::ReadWrite)) {
174             raiseError(tr("Packaging Error: Cannot open file '%1'.")
175                        .arg(nativePath(rulesFile)));
176             return false;
177         }
178
179         QByteArray rulesContents = rulesFile.readAll();
180         rulesContents.replace("DESTDIR", "INSTALL_ROOT");
181         rulesFile.resize(0);
182         rulesFile.write(rulesContents);
183         if (rulesFile.error() != QFile::NoError) {
184             raiseError(tr("Packaging Error: Cannot write file '%1'.")
185                        .arg(nativePath(rulesFile)));
186             return false;
187         }
188     }
189
190     {
191         QFile changeLog(buildDir + QLatin1String("/debian/changelog"));
192         if (changeLog.open(QIODevice::ReadWrite)) {
193             QString content = QString::fromUtf8(changeLog.readAll());
194             content.replace(QRegExp("\\([a-zA-Z0-9_\\.]+\\)"),
195                 QLatin1Char('(') % versionString() % QLatin1Char(')'));
196             changeLog.resize(0);
197             changeLog.write(content.toUtf8());
198         }
199     }
200
201     if (!runCommand(buildProc, QLatin1String("dh_installdirs")))
202         return false;
203     
204     const QDir debianRoot = QDir(buildDir % QLatin1String("/debian/")
205                                  % executableFileName().toLower());
206     for (int i = 0; i < m_packageContents->rowCount(); ++i) {
207         const MaemoDeployable &d = m_packageContents->deployableAt(i);
208         const QString targetFile = debianRoot.path() + '/' + d.remoteFilePath;
209         const QString absTargetDir = QFileInfo(targetFile).dir().path();
210         const QString relTargetDir = debianRoot.relativeFilePath(absTargetDir);
211         if (!debianRoot.exists(relTargetDir)
212             && !debianRoot.mkpath(relTargetDir)) {
213             raiseError(tr("Packaging Error: Could not create directory '%1'.")
214                        .arg(QDir::toNativeSeparators(absTargetDir)));
215             return false;
216         }
217         if (QFile::exists(targetFile) && !QFile::remove(targetFile)) {
218             raiseError(tr("Packaging Error: Could not replace file '%1'.")
219                        .arg(QDir::toNativeSeparators(targetFile)));
220             return false;
221         }
222
223         if (!QFile::copy(d.localFilePath, targetFile)) {
224             raiseError(tr("Packaging Error: Could not copy '%1' to '%2'.")
225                        .arg(QDir::toNativeSeparators(d.localFilePath))
226                        .arg(QDir::toNativeSeparators(targetFile)));
227             return false;
228         }
229     }
230
231     const QStringList commands = QStringList() << QLatin1String("dh_link")
232         << QLatin1String("dh_fixperms") << QLatin1String("dh_installdeb")
233         << QLatin1String("dh_shlibdeps") << QLatin1String("dh_gencontrol")
234         << QLatin1String("dh_md5sums") << QLatin1String("dh_builddeb --destdir=.");
235     foreach (const QString &command, commands) {
236         if (!runCommand(buildProc, command))
237             return false;
238     }
239
240     emit addOutput(tr("Package created."), textCharFormat);
241     m_packageContents->setUnModified();
242     return true;
243 }
244
245 bool MaemoPackageCreationStep::runCommand(QProcess &proc, const QString &command)
246 {
247     QTextCharFormat textCharFormat;
248     emit addOutput(tr("Package Creation: Running command '%1'.").arg(command), textCharFormat);
249     QString perl;
250 #ifdef Q_OS_WIN
251     perl = maddeRoot() + QLatin1String("/bin/perl.exe ");
252 #endif
253     proc.start(perl + maddeRoot() % QLatin1String("/madbin/") % command);
254     if (!proc.waitForStarted()) {
255         raiseError(tr("Packaging failed."),
256             tr("Packaging error: Could not start command '%1'. Reason: %2")
257             .arg(command).arg(proc.errorString()));
258         return false;
259     }
260     proc.write("\n"); // For dh_make
261     proc.waitForFinished(-1);
262     if (proc.error() != QProcess::UnknownError || proc.exitCode() != 0) {
263         QString mainMessage = tr("Packaging Error: Command '%1' failed.")
264             .arg(command);
265         if (proc.error() != QProcess::UnknownError)
266             mainMessage += tr(" Reason: %1").arg(proc.errorString());
267         raiseError(mainMessage, mainMessage + QLatin1Char('\n')
268                    + tr("Output was: ") + proc.readAllStandardError()
269                    + QLatin1Char('\n') + proc.readAllStandardOutput());
270         return false;
271     }
272     return true;
273 }
274
275 const Qt4BuildConfiguration *MaemoPackageCreationStep::qt4BuildConfiguration() const
276 {
277     return static_cast<Qt4BuildConfiguration *>(buildConfiguration());
278 }
279
280 QString MaemoPackageCreationStep::localExecutableFilePath() const
281 {
282     const TargetInformation &ti = qt4BuildConfiguration()->qt4Target()
283         ->qt4Project()->rootProjectNode()->targetInformation();
284     if (!ti.valid)
285         return QString();
286
287     return QDir::toNativeSeparators(QDir::cleanPath(ti.workingDir
288         + QLatin1Char('/') + ti.target));
289 }
290
291 QString MaemoPackageCreationStep::executableFileName() const
292 {
293     return QFileInfo(localExecutableFilePath()).fileName();
294 }
295
296 const MaemoToolChain *MaemoPackageCreationStep::maemoToolChain() const
297 {
298     return static_cast<MaemoToolChain *>(qt4BuildConfiguration()->toolChain());
299 }
300
301 QString MaemoPackageCreationStep::maddeRoot() const
302 {
303     return maemoToolChain()->maddeRoot();
304 }
305
306 QString MaemoPackageCreationStep::targetRoot() const
307 {
308     return maemoToolChain()->targetRoot();
309 }
310
311 bool MaemoPackageCreationStep::packagingNeeded() const
312 {
313     QFileInfo packageInfo(packageFilePath());
314     if (!packageInfo.exists() || m_packageContents->isModified())
315         return true;
316
317     for (int i = 0; i < m_packageContents->rowCount(); ++i) {
318         if (packageInfo.lastModified()
319             <= QFileInfo(m_packageContents->deployableAt(i).localFilePath)
320                .lastModified())
321             return true;
322     }
323
324     return false;
325 }
326
327 QString MaemoPackageCreationStep::packageFilePath() const
328 {
329     QFileInfo execInfo(localExecutableFilePath());
330     return execInfo.path() % QDir::separator() % execInfo.fileName().toLower()
331         % QLatin1Char('_') % versionString() % QLatin1String("_armel.deb");
332 }
333
334 QString MaemoPackageCreationStep::versionString() const
335 {
336     return m_versionString;
337 }
338
339 void MaemoPackageCreationStep::setVersionString(const QString &version)
340 {
341     m_versionString = version;
342 }
343
344 QString MaemoPackageCreationStep::nativePath(const QFile &file) const
345 {
346     return QDir::toNativeSeparators(QFileInfo(file).filePath());
347 }
348
349 void MaemoPackageCreationStep::raiseError(const QString &shortMsg,
350                                           const QString &detailedMsg)
351 {
352     QTextCharFormat textCharFormat;
353     emit addOutput(detailedMsg.isNull() ? shortMsg : detailedMsg, textCharFormat);
354     emit addTask(Task(Task::Error, shortMsg, QString(), -1,
355                       TASK_CATEGORY_BUILDSYSTEM));
356 }
357
358 const QLatin1String MaemoPackageCreationStep::CreatePackageId("Qt4ProjectManager.MaemoPackageCreationStep");
359
360 } // namespace Internal
361 } // namespace Qt4ProjectManager