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
);
90 QString
Record::argumentDescription() const
92 return "[FILE or DIRECTORY]";
95 QString
Record::commandDescription() const
97 return "Record is used to name a set of changes and record the patch to the repository.\n";
100 AbstractCommand::ReturnCodes
Record::run()
102 if (! checkInRepository())
104 CommandLineParser
*args
= CommandLineParser::instance();
105 const bool all
= m_config
.isEmptyRepo() || m_config
.contains("all")
106 && !args
->contains("interactive") || args
->contains("all");
109 changeSet
.fillFromCurrentChanges(rebasedArguments());
111 bool shouldDoRecord
= changeSet
.count() > 0;
112 if (!shouldDoRecord
) {
113 Logger::info() << "No changes!" << endl
;
117 QString email
= args
->optionArgument("author", m_config
.optionArgument("author", getenv("EMAIL")));
118 QStringList environment
;
119 if (! email
.isEmpty()) {
120 QRegExp
re("(.*) <([@\\S]+)>");
121 if (re
.exactMatch(email
)) { // meaning its an email AND name
122 environment
<< "GIT_AUTHOR_NAME="+ re
.cap(1);
123 environment
<< "GIT_AUTHOR_EMAIL="+ re
.cap(2);
125 else if (!args
->contains("author")) // if its an account or shell wide option; just use the git defs.
126 environment
<< "GIT_AUTHOR_EMAIL="+ email
;
128 Logger::error() << "Author format invalid. Please provide author formatted like; `name <email@host>\n";
129 return InvalidOptions
;
133 if (shouldDoRecord
&& !all
) { // then do interview
134 HunksCursor
cursor(changeSet
);
135 cursor
.setConfiguration(m_config
);
136 Interview
interview(cursor
, name());
137 interview
.setUsePager(shouldUsePager());
138 if (! interview
.start()) {
139 Logger::info() << "Record cancelled." << endl
;
144 if (shouldDoRecord
&& !all
) { // check if there is anything selected
145 shouldDoRecord
= changeSet
.hasAcceptedChanges();
146 if (! shouldDoRecord
) {
147 Logger::info() << "Ok, if you don't want to record anything, that's fine!" <<endl
;
152 QString patchName
= args
->optionArgument("patch-name", m_config
.optionArgument("patch-name"));
153 if (patchName
.isEmpty())
154 patchName
= Interview::ask("What is the patch name? ");
158 ReturnCodes rc
= addFilesPerAcceptance(changeSet
, all
);
162 QStringList arguments
;
163 arguments
<< "write-tree";
165 GitRunner
runner(git
, arguments
);
166 rc
= runner
.start(GitRunner::WaitForStandardOutput
);
168 Logger::error() << "Git write-tree failed!, aborting commit\n";
172 Vng::readLine(&git
, buf
, sizeof(buf
));
174 git
.waitForFinished(); // patiently wait for it to finish..
175 Logger::debug() << "The tree got git ref; " << tree
;
176 Logger::debug().flush(); // flush since we do an ask next
179 git
.setEnvironment(environment
);
182 // parent = git-cat-file commit HEAD | grep parent
183 // if .git/MERGE_HEAD exists its a merge
184 // then we have multiple heads, one additional per line in .git/MERGE_HEAD
185 // also use .git/MERGE_MSG
187 arguments
<< "commit-tree" << tree
.left(40);
188 if (!m_config
.isEmptyRepo())
189 arguments
<< "-p" << "HEAD" ;
191 runner
.setArguments(arguments
);
192 rc
= runner
.start(GitRunner::WaitUntilReadyForWrite
);
194 Logger::error() << "Git commit-tree failed!, aborting commit\n";
197 git
.write(patchName
.toUtf8());
199 git
.closeWriteChannel();
200 Vng::readLine(&git
, buf
, sizeof(buf
));
202 Logger::debug() << "commit is ref; " << commit
;
203 git
.waitForFinished(); // patiently wait for it to finish..
204 if (commit
.isEmpty()) {
205 Logger::error() << "Git update-ref failed to produce a reference!, aborting commit\n";
210 arguments
<< "update-ref" << "HEAD" << commit
.left(40);
211 runner
.setArguments(arguments
);
212 rc
= runner
.start(GitRunner::WaitUntilFinished
);
214 Logger::error() << "Git update-ref failed!, aborting commit\n";
218 // We removed files from the index in case they were freshly added, but the user didn't want it in this commit.
219 // we have to re-add those files.
221 arguments
<< "update-index" << "--add";
222 foreach (File file
, changeSet
.files()) {
223 if (! file
.oldFileName().isEmpty())
224 continue; // not a new added file.
225 if (file
.renameAcceptance() == Vng::Rejected
)
226 arguments
.append(file
.fileName());
228 if (arguments
.count() > 2) {
229 runner
.setArguments(arguments
);
230 runner
.start(GitRunner::WaitUntilFinished
);
233 Logger::info() << "Finished recording patch `" << patchName
<< "'" << endl
;
237 AbstractCommand::ReturnCodes
Record::addFilesPerAcceptance(const ChangeSet
&changeSet
, bool allChanges
)
239 typedef QPair
<QString
, QString
> NamePair
;
244 foreach(NamePair pair
, m_fileNames
) {
245 QFile
copy(pair
.second
);
247 if (! pair
.first
.isEmpty()) {
248 QFile
orig(pair
.first
);
249 orig
.rename(copy
.fileName());
253 void append(const QString
&orig
, const QString
©
) {
254 QPair
<QString
, QString
> pair(orig
, copy
);
255 m_fileNames
.append(pair
);
259 QList
< QPair
<QString
, QString
> > m_fileNames
;
261 RevertCopier reverter
;// this will revert all file changes we make when we exit the scope of this method.
262 ChangeSet patchChanges
;
264 QStringList filesForAdd
;
265 foreach (File file
, changeSet
.files()) {
266 bool someEnabled
= false;
267 bool allEnabled
= true;
268 const bool renamed
= file
.fileName() != file
.oldFileName();
269 const bool protectionChanged
= !renamed
&& file
.protection() != file
.oldProtection();
270 if (file
.renameAcceptance() == Vng::Accepted
&& renamed
271 || file
.protectionAcceptance() == Vng::Accepted
&& protectionChanged
) // record it.
274 foreach (Hunk hunk
, file
.hunks()) {
275 Vng::Acceptance a
= hunk
.acceptance();
276 if (a
== Vng::Accepted
|| a
== Vng::MixedAcceptance
)
280 if (someEnabled
&& !allEnabled
)
283 const bool removeFromIndex
= !allChanges
&& !someEnabled
; // user said 'no', lets make sure none of the changes are left in the index.
284 const bool addUnaltered
= allChanges
|| allEnabled
;
285 if (file
.fileName().isEmpty())
286 filesForAdd
<< file
.oldFileName();
288 filesForAdd
<< file
.fileName();
291 continue; // thats easy; whole file to add.
292 if (removeFromIndex
&& file
.fileName().isEmpty()) { // user said no about recording a deleted file.
293 // this is a funny situation; *just* in case the user already somehow added the deletion to the index
294 // we need to reset that to make the index have the full file again. Notice that we need to remove the file afterwards.
295 Q_ASSERT(!file
.oldFileName().isEmpty());
297 QStringList arguments
;
298 arguments
<< "cat-file" << "blob" << file
.oldSha1();
299 GitRunner
runner(git
, arguments
);
300 ReturnCodes rc
= runner
.start(GitRunner::WaitForStandardOutput
);
302 reverter
.append(QString(), file
.oldFileName());
303 QFile
deletedFile(file
.oldFileName());
304 Q_ASSERT(! deletedFile
.exists());
305 deletedFile
.open(QIODevice::WriteOnly
);
306 rc
= copyFile(git
, deletedFile
);
307 git
.waitForFinished();
314 // for the case where only some patches are selected we make a safety copy of the file.
315 QFile
sourceFile(file
.fileName());
316 Q_ASSERT(sourceFile
.exists());
317 QString fileName
= file
.fileName();
318 for(int i
=0; i
< 10; i
++) {
319 fileName
= fileName
+ ".orig";
320 if (sourceFile
.rename(fileName
))
321 break; // successful!
323 reverter
.append(fileName
, file
.fileName());
324 if (removeFromIndex
) // need to rename it only, we won't patch it.
327 patchChanges
.addFile(file
);
328 sourceFile
.open(QIODevice::WriteOnly
);
329 Logger::debug() << "cp " << fileName
<< " =>" << file
.fileName() << endl
;
330 QFile
orig(fileName
);
331 orig
.open(QIODevice::ReadOnly
);
332 copyFile(orig
, sourceFile
);
333 sourceFile
.setPermissions(file
.permissions());
336 QFile
patch(".vng.record." + QString::number(getpid()) + ".diff");
337 patchChanges
.writeDiff(patch
, ChangeSet::InvertedUserSelection
);
340 if (patch
.size() != 0) {
342 QStringList arguments
;
343 arguments
<< "apply" << "--apply" << "--reverse" << patch
.fileName();
344 GitRunner
runner(git
, arguments
);
345 ReturnCodes rc
= runner
.start(GitRunner::WaitUntilFinished
);
347 Logger::error() << "internal error; failed to patch, sorry, aborting commit\n";
348 return rc
; // note that copied files will be moved back to avoid partially patched files lying around.
353 // git add of all files.
355 QStringList arguments
;
356 arguments
<< "update-index" << "--remove" << filesForAdd
;
357 GitRunner
runner(git
, arguments
);
358 ReturnCodes rc
= runner
.start(GitRunner::WaitForStandardOutput
);
360 Logger::error() << "Adding files to the git index failed, aborting commit\n";
364 return Ok
; // exiting scope will revert all files in the local filesystem. We use the index from here on.