2 * This file is part of the vng project
3 * Copyright (C) 2008 Thomas Zander <tzander@trolltech.com>
4 * Copyright (C) 2002-2004 David Roundy
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 #include "CommandLineParser.h"
21 #include "GitRunner.h"
22 #include "hunks/ChangeSet.h"
23 #include "hunks/HunksCursor.h"
25 #include "Interview.h"
32 # define getpid() rand()
34 # include <sys/types.h>
39 static const CommandLineOption options
[] = {
40 {"-a, --all", "answer yes to all patches"},
41 {"-i, --interactive", "prompt user interactively"},
42 {"-m, --patch-name PATCHNAME", "name of patch"},
43 {"-A, --author EMAIL", "specify author id"},
44 //{"--logfile FILE", "give patch name and comment in file"},
45 //{"--delete-logfile", "delete the logfile when done"},
46 //{"--no-test", "don't run the test script"},
47 //{"--test", "run the test script"},
48 //{"--leave-test-directory", "don't remove the test directory"},
49 //{"--remove-test-directory", "remove the test directory"},
50 //{"--edit-long-comment", "Edit the long comment by default"},
51 //{"--skip-long-comment", "Don't give a long comment"},
52 //{"--prompt-long-comment", "Prompt for whether to edit the long comment"},
53 //{"-l, --look-for-adds", "Also look for files that are potentially pending addition"},
54 //{"--dont-look-for-adds", "Don't look for any files that could be added"},
55 //{"--umask UMASK", "specify umask to use when writing."},
56 //{"--posthook COMMAND", "specify command to run after this vng command."},
57 //{"--no-posthook", "Do not run posthook command."},
58 //{"--prompt-posthook", "Prompt before running posthook. [DEFAULT]"},
59 //{"--run-posthook", "Run posthook command without prompting."},
63 static AbstractCommand::ReturnCodes
copyFile(QIODevice
&from
, QIODevice
&to
) {
64 to
.open(QIODevice::WriteOnly
);
67 from
.waitForReadyRead(-1);
68 qint64 len
= from
.read(buf
, sizeof(buf
));
69 if (len
<= 0) { // done!
74 qint64 written
= to
.write(buf
, len
);
75 if (written
== -1) // write error!
76 return AbstractCommand::WriteError
;
80 return AbstractCommand::Ok
;
85 : AbstractCommand("record")
87 CommandLineParser::addOptionDefinitions(options
);
88 CommandLineParser::setArgumentDefinition("record [FILE or DIRECTORY]" );
91 QString
Record::argumentDescription() const
93 return "[FILE or DIRECTORY]";
96 QString
Record::commandDescription() const
98 return "Record is used to name a set of changes and record the patch to the repository.\n";
101 AbstractCommand::ReturnCodes
Record::run()
103 if (! checkInRepository())
107 CommandLineParser
*args
= CommandLineParser::instance();
108 const bool all
= m_config
.isEmptyRepo() || m_config
.contains("all")
109 && !args
->contains("interactive") || args
->contains("all");
112 changeSet
.fillFromCurrentChanges(rebasedArguments());
114 bool shouldDoRecord
= changeSet
.count() > 0;
115 if (!shouldDoRecord
) {
116 Logger::info() << "No changes!" << endl
;
120 QString email
= args
->optionArgument("author", m_config
.optionArgument("author", getenv("EMAIL")));
121 QStringList environment
;
122 if (! email
.isEmpty()) {
123 QRegExp
re("(.*) <([@\\S]+)>");
124 if (re
.exactMatch(email
)) { // meaning its an email AND name
125 environment
<< "GIT_AUTHOR_NAME="+ re
.cap(1);
126 environment
<< "GIT_AUTHOR_EMAIL="+ re
.cap(2);
128 else if (!args
->contains("author")) // if its an account or shell wide option; just use the git defs.
129 environment
<< "GIT_AUTHOR_EMAIL="+ email
;
131 Logger::error() << "Author format invalid. Please provide author formatted like; `name <email@host>\n";
132 return InvalidOptions
;
136 if (shouldDoRecord
&& !all
) { // then do interview
137 HunksCursor
cursor(changeSet
);
138 cursor
.setConfiguration(m_config
);
139 Interview
interview(cursor
, name());
140 interview
.setUsePager(shouldUsePager());
141 if (! interview
.start()) {
142 Logger::info() << "Record cancelled." << endl
;
147 if (shouldDoRecord
&& !all
) { // check if there is anything selected
148 shouldDoRecord
= changeSet
.hasAcceptedChanges();
149 if (! shouldDoRecord
) {
150 Logger::info() << "Ok, if you don't want to record anything, that's fine!" <<endl
;
155 QString patchName
= args
->optionArgument("patch-name", m_config
.optionArgument("patch-name"));
156 if (patchName
.isEmpty())
157 patchName
= Interview::ask("What is the patch name? ");
161 ReturnCodes rc
= addFilesPerAcceptance(changeSet
, all
);
165 QStringList arguments
;
166 arguments
<< "write-tree";
168 GitRunner
runner(git
, arguments
);
169 rc
= runner
.start(GitRunner::WaitForStandardOutput
);
171 Logger::error() << "Git write-tree failed!, aborting commit\n";
175 Vng::readLine(&git
, buf
, sizeof(buf
));
177 git
.waitForFinished(); // patiently wait for it to finish..
178 Logger::debug() << "The tree got git ref; " << tree
;
179 Logger::debug().flush(); // flush since we do an ask next
182 git
.setEnvironment(environment
);
185 // parent = git-cat-file commit HEAD | grep parent
186 // if .git/MERGE_HEAD exists its a merge
187 // then we have multiple heads, one additional per line in .git/MERGE_HEAD
188 // also use .git/MERGE_MSG
190 arguments
<< "commit-tree" << tree
.left(40);
191 if (!m_config
.isEmptyRepo())
192 arguments
<< "-p" << "HEAD" ;
194 runner
.setArguments(arguments
);
195 rc
= runner
.start(GitRunner::WaitUntilReadyForWrite
);
197 Logger::error() << "Git commit-tree failed!, aborting commit\n";
200 git
.write(patchName
.toUtf8());
202 git
.closeWriteChannel();
203 Vng::readLine(&git
, buf
, sizeof(buf
));
205 Logger::debug() << "commit is ref; " << commit
;
206 git
.waitForFinished(); // patiently wait for it to finish..
207 if (commit
.isEmpty()) {
208 Logger::error() << "Git update-ref failed to produce a reference!, aborting commit\n";
213 arguments
<< "update-ref" << "HEAD" << commit
.left(40);
214 runner
.setArguments(arguments
);
215 rc
= runner
.start(GitRunner::WaitUntilFinished
);
217 Logger::error() << "Git update-ref failed!, aborting commit\n";
221 // We removed files from the index in case they were freshly added, but the user didn't want it in this commit.
222 // we have to re-add those files.
224 arguments
<< "update-index" << "--add";
225 foreach (File file
, changeSet
.files()) {
226 if (! file
.oldFileName().isEmpty())
227 continue; // not a new added file.
228 if (file
.renameAcceptance() == Vng::Rejected
)
229 arguments
.append(file
.fileName());
231 if (arguments
.count() > 2) {
232 runner
.setArguments(arguments
);
233 runner
.start(GitRunner::WaitUntilFinished
);
236 Logger::info() << "Finished recording patch `" << patchName
<< "'" << endl
;
240 AbstractCommand::ReturnCodes
Record::addFilesPerAcceptance(const ChangeSet
&changeSet
, bool allChanges
)
242 typedef QPair
<QString
, QString
> NamePair
;
247 foreach(NamePair pair
, m_fileNames
) {
248 QFile
copy(pair
.second
);
250 if (! pair
.first
.isEmpty()) {
251 QFile
orig(pair
.first
);
252 orig
.rename(copy
.fileName());
256 void append(const QString
&orig
, const QString
©
) {
257 QPair
<QString
, QString
> pair(orig
, copy
);
258 m_fileNames
.append(pair
);
262 QList
< QPair
<QString
, QString
> > m_fileNames
;
264 RevertCopier reverter
;// this will revert all file changes we make when we exit the scope of this method.
265 ChangeSet patchChanges
;
267 QStringList filesForAdd
;
268 foreach (File file
, changeSet
.files()) {
269 bool someEnabled
= false;
270 bool allEnabled
= true;
271 const bool renamed
= file
.fileName() != file
.oldFileName();
272 const bool protectionChanged
= !renamed
&& file
.protection() != file
.oldProtection();
273 if (file
.renameAcceptance() == Vng::Accepted
&& renamed
274 || file
.protectionAcceptance() == Vng::Accepted
&& protectionChanged
) // record it.
277 foreach (Hunk hunk
, file
.hunks()) {
278 Vng::Acceptance a
= hunk
.acceptance();
279 if (a
== Vng::Accepted
|| a
== Vng::MixedAcceptance
)
283 if (someEnabled
&& !allEnabled
)
286 const bool removeFromIndex
= !allChanges
&& !someEnabled
; // user said 'no', lets make sure none of the changes are left in the index.
287 if (removeFromIndex
&& ! file
.fileName().isEmpty() && ! file
.oldFileName().isEmpty()) // just ignore file.
289 const bool addUnaltered
= allChanges
|| allEnabled
;
290 Logger::debug() << file
.fileName() << "] addUnaltered: " << addUnaltered
<< ", removeFromIndex: "
291 << removeFromIndex
<< ", someChangesAccepted: " << someEnabled
<< ", allAccepted: " << allEnabled
<< endl
;
292 if (file
.fileName().isEmpty())
293 filesForAdd
<< file
.oldFileName();
295 filesForAdd
<< file
.fileName();
298 continue; // thats easy; whole file to add.
299 if (removeFromIndex
&& file
.fileName().isEmpty()) { // user said no about recording a deleted file.
300 // this is a funny situation; *just* in case the user already somehow added the deletion to the index
301 // we need to reset that to make the index have the full file again. Notice that we need to remove the file afterwards.
302 Q_ASSERT(!file
.oldFileName().isEmpty());
304 QStringList arguments
;
305 arguments
<< "cat-file" << "blob" << file
.oldSha1();
306 GitRunner
runner(git
, arguments
);
307 ReturnCodes rc
= runner
.start(GitRunner::WaitForStandardOutput
);
309 reverter
.append(QString(), file
.oldFileName());
310 QFile
deletedFile(file
.oldFileName());
311 Q_ASSERT(! deletedFile
.exists());
312 deletedFile
.open(QIODevice::WriteOnly
);
313 rc
= copyFile(git
, deletedFile
);
314 git
.waitForFinished();
322 // for the case where only some patches are selected we make a safety copy of the file.
323 QFile
sourceFile(file
.fileName());
324 Q_ASSERT(sourceFile
.exists());
325 QString fileName
= file
.fileName();
326 for(int i
=0; i
< 10; i
++) {
327 fileName
= fileName
+ ".orig";
328 if (sourceFile
.rename(fileName
))
329 break; // successful!
331 reverter
.append(fileName
, file
.fileName());
332 if (removeFromIndex
) // need to rename it only, we won't patch it.
335 patchChanges
.addFile(file
);
336 Logger::debug() << "cp " << fileName
<< " =>" << file
.fileName() << endl
;
337 QFile
orig(fileName
);
338 orig
.open(QIODevice::ReadOnly
);
339 copyFile(orig
, sourceFile
);
340 sourceFile
.setPermissions(file
.permissions());
343 QFile
patch(".vng.record." + QString::number(getpid()) + ".diff");
344 patchChanges
.writeDiff(patch
, ChangeSet::InvertedUserSelection
);
347 if (patch
.size() != 0) {
349 QStringList arguments
;
350 arguments
<< "apply" << "--apply" << "--reverse" << patch
.fileName();
351 GitRunner
runner(git
, arguments
);
352 ReturnCodes rc
= runner
.start(GitRunner::WaitUntilFinished
);
354 Logger::error() << "internal error; failed to patch, sorry, aborting commit\n";
355 return rc
; // note that copied files will be moved back to avoid partially patched files lying around.
360 // git add of all files.
362 QStringList arguments
;
363 arguments
<< "update-index" << "--remove" << filesForAdd
;
364 GitRunner
runner(git
, arguments
);
365 ReturnCodes rc
= runner
.start(GitRunner::WaitForStandardOutput
);
367 Logger::error() << "Adding files to the git index failed, aborting commit\n";
371 return Ok
; // exiting scope will revert all files in the local filesystem. We use the index from here on.