]> git.lyx.org Git - lyx.git/blob - src/VCBackend.cpp
Merge branch 'master' of git.lyx.org:lyx
[lyx.git] / src / VCBackend.cpp
1 /**
2  * \file VCBackend.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Pavel Sanda
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "VCBackend.h"
15 #include "Buffer.h"
16 #include "DispatchResult.h"
17 #include "LyX.h"
18 #include "FuncRequest.h"
19
20 #include "frontends/alert.h"
21 #include "frontends/Application.h"
22
23 #include "support/convert.h"
24 #include "support/debug.h"
25 #include "support/filetools.h"
26 #include "support/gettext.h"
27 #include "support/lstrings.h"
28 #include "support/PathChanger.h"
29 #include "support/Systemcall.h"
30 #include "support/regex.h"
31 #include "support/TempFile.h"
32
33 #include <fstream>
34
35 using namespace std;
36 using namespace lyx::support;
37
38
39 namespace lyx {
40
41
42 int VCS::doVCCommandCall(string const & cmd, FileName const & path)
43 {
44         LYXERR(Debug::LYXVC, "doVCCommandCall: " << cmd);
45         Systemcall one;
46         support::PathChanger p(path);
47         return one.startscript(Systemcall::Wait, cmd, string(), string(), false);
48 }
49
50
51 int VCS::doVCCommand(string const & cmd, FileName const & path, bool reportError)
52 {
53         if (owner_)
54                 owner_->setBusy(true);
55
56         int const ret = doVCCommandCall(cmd, path);
57
58         if (owner_)
59                 owner_->setBusy(false);
60         if (ret && reportError)
61                 frontend::Alert::error(_("Revision control error."),
62                         bformat(_("Some problem occurred while running the command:\n"
63                                   "'%1$s'."),
64                         from_utf8(cmd)));
65         return ret;
66 }
67
68
69 bool VCS::makeRCSRevision(string const &version, string &revis) const
70 {
71         string rev = revis;
72
73         if (isStrInt(rev)) {
74                 int back = convert<int>(rev);
75                 // if positive use as the last number in the whole revision string
76                 if (back > 0) {
77                         string base;
78                         rsplit(version, base , '.');
79                         rev = base + '.' + rev;
80                 }
81                 if (back == 0)
82                         rev = version;
83                 // we care about the last number from revision string
84                 // in case of backward indexing
85                 if (back < 0) {
86                         string cur, base;
87                         cur = rsplit(version, base , '.');
88                         if (!isStrInt(cur))
89                                 return false;
90                         int want = convert<int>(cur) + back;
91                         if (want <= 0)
92                                 return false;
93
94                         rev = base + '.' + convert<string>(want);
95                 }
96         }
97
98         revis = rev;
99         return true;
100 }
101
102
103 bool VCS::checkparentdirs(FileName const & file, std::string const & vcsdir)
104 {
105         FileName dirname = file.onlyPath();
106         do {
107                 FileName tocheck = FileName(addName(dirname.absFileName(), vcsdir));
108                 LYXERR(Debug::LYXVC, "check file: " << tocheck.absFileName());
109                 if (tocheck.exists())
110                         return true;
111                 //this construct because of #8295
112                 dirname = FileName(dirname.absFileName()).parentPath();
113         } while (!dirname.empty());
114         return false;
115 }
116
117
118 /////////////////////////////////////////////////////////////////////
119 //
120 // RCS
121 //
122 /////////////////////////////////////////////////////////////////////
123
124 RCS::RCS(FileName const & m, Buffer * b) : VCS(b)
125 {
126         // Here we know that the buffer file is either already in RCS or
127         // about to be registered
128         master_ = m;
129         scanMaster();
130 }
131
132
133 FileName const RCS::findFile(FileName const & file)
134 {
135         // Check if *,v exists.
136         FileName tmp(file.absFileName() + ",v");
137         LYXERR(Debug::LYXVC, "LyXVC: Checking if file is under rcs: " << tmp);
138         if (tmp.isReadableFile()) {
139                 LYXERR(Debug::LYXVC, "Yes, " << file << " is under rcs.");
140                 return tmp;
141         }
142
143         // Check if RCS/*,v exists.
144         tmp = FileName(addName(addPath(onlyPath(file.absFileName()), "RCS"), file.absFileName()) + ",v");
145         LYXERR(Debug::LYXVC, "LyXVC: Checking if file is under rcs: " << tmp);
146         if (tmp.isReadableFile()) {
147                 LYXERR(Debug::LYXVC, "Yes, " << file << " is under rcs.");
148                 return tmp;
149         }
150
151         return FileName();
152 }
153
154
155 bool RCS::retrieve(FileName const & file)
156 {
157         LYXERR(Debug::LYXVC, "LyXVC::RCS: retrieve.\n\t" << file);
158         // The caller ensures that file does not exist, so no need to check that.
159         return doVCCommandCall("co -q -r " + quoteName(file.toFilesystemEncoding()),
160                                FileName()) == 0;
161 }
162
163
164 void RCS::scanMaster()
165 {
166         if (master_.empty())
167                 return;
168
169         LYXERR(Debug::LYXVC, "LyXVC::RCS: scanMaster: " << master_);
170
171         ifstream ifs(master_.toFilesystemEncoding().c_str());
172
173         string token;
174         bool read_enough = false;
175
176         while (!read_enough && ifs >> token) {
177                 LYXERR(Debug::LYXVC, "LyXVC::scanMaster: current lex text: `"
178                         << token << '\'');
179
180                 if (token.empty())
181                         continue;
182                 else if (token == "head") {
183                         // get version here
184                         string tmv;
185                         ifs >> tmv;
186                         tmv = rtrim(tmv, ";");
187                         version_ = tmv;
188                         LYXERR(Debug::LYXVC, "LyXVC: version found to be " << tmv);
189                 } else if (contains(token, "access")
190                            || contains(token, "symbols")
191                            || contains(token, "strict")) {
192                         // nothing
193                 } else if (contains(token, "locks")) {
194                         // get locker here
195                         if (contains(token, ';')) {
196                                 locker_ = "Unlocked";
197                                 vcstatus = UNLOCKED;
198                                 continue;
199                         }
200                         string tmpt;
201                         string s1;
202                         string s2;
203                         do {
204                                 ifs >> tmpt;
205                                 s1 = rtrim(tmpt, ";");
206                                 // tmp is now in the format <user>:<version>
207                                 s1 = split(s1, s2, ':');
208                                 // s2 is user, and s1 is version
209                                 if (s1 == version_) {
210                                         locker_ = s2;
211                                         vcstatus = LOCKED;
212                                         break;
213                                 }
214                         } while (!contains(tmpt, ';'));
215
216                 } else if (token == "comment") {
217                         // we don't need to read any further than this.
218                         read_enough = true;
219                 } else {
220                         // unexpected
221                         LYXERR(Debug::LYXVC, "LyXVC::scanMaster(): unexpected token");
222                 }
223         }
224 }
225
226
227 void RCS::registrer(string const & msg)
228 {
229         string cmd = "ci -q -u -i -t-\"";
230         cmd += msg;
231         cmd += "\" ";
232         cmd += quoteName(onlyFileName(owner_->absFileName()));
233         doVCCommand(cmd, FileName(owner_->filePath()));
234 }
235
236
237 bool RCS::renameEnabled()
238 {
239         return false;
240 }
241
242
243 string RCS::rename(support::FileName const & /*newFile*/, string const & /*msg*/)
244 {
245         // not implemented, since a left-over file.lyx,v would be confusing.
246         return string();
247 }
248
249
250 bool RCS::copyEnabled()
251 {
252         return true;
253 }
254
255
256 string RCS::copy(support::FileName const & newFile, string const & msg)
257 {
258         // RCS has no real copy command, so we create a poor mans version
259         support::FileName const oldFile(owner_->absFileName());
260         if (!oldFile.copyTo(newFile))
261                 return string();
262         FileName path(oldFile.onlyPath());
263         string relFile(to_utf8(newFile.relPath(path.absFileName())));
264         string cmd = "ci -q -u -i -t-\"";
265         cmd += msg;
266         cmd += "\" ";
267         cmd += quoteName(relFile);
268         return doVCCommand(cmd, path) ? string() : "RCS: Proceeded";
269 }
270
271
272 LyXVC::CommandResult RCS::checkIn(string const & msg, string & log)
273 {
274         int ret = doVCCommand("ci -q -u -m\"" + msg + "\" "
275                     + quoteName(onlyFileName(owner_->absFileName())),
276                     FileName(owner_->filePath()));
277         if (ret)
278                 return LyXVC::ErrorCommand;
279         log = "RCS: Proceeded";
280         return LyXVC::VCSuccess;
281 }
282
283
284 bool RCS::checkInEnabled()
285 {
286         return owner_ && !owner_->isReadonly();
287 }
288
289
290 bool RCS::isCheckInWithConfirmation()
291 {
292         // FIXME one day common getDiff for all backends
293         // docstring diff;
294         // if (getDiff(file, diff) && diff.empty())
295         //      return false;
296
297         TempFile tempfile("lyxvcout");
298         FileName tmpf = tempfile.name();
299         if (tmpf.empty()) {
300                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
301                 return true;
302         }
303
304         doVCCommandCall("rcsdiff " + quoteName(owner_->absFileName())
305                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
306                 FileName(owner_->filePath()));
307
308         docstring diff = tmpf.fileContents("UTF-8");
309
310         if (diff.empty())
311                 return false;
312
313         return true;
314 }
315
316
317 string RCS::checkOut()
318 {
319         owner_->markClean();
320         int ret = doVCCommand("co -q -l " + quoteName(onlyFileName(owner_->absFileName())),
321                     FileName(owner_->filePath()));
322         return ret ? string() : "RCS: Proceeded";
323 }
324
325
326 bool RCS::checkOutEnabled()
327 {
328         return owner_ && owner_->isReadonly();
329 }
330
331
332 string RCS::repoUpdate()
333 {
334         lyxerr << "Sorry, not implemented." << endl;
335         return string();
336 }
337
338
339 bool RCS::repoUpdateEnabled()
340 {
341         return false;
342 }
343
344
345 string RCS::lockingToggle()
346 {
347         //FIXME this might be actually possible, study rcs -U, rcs -L.
348         //State should be easy to get inside scanMaster.
349         //It would fix #4370 and make rcs/svn usage even more closer.
350         lyxerr << "Sorry, not implemented." << endl;
351         return string();
352 }
353
354
355 bool RCS::lockingToggleEnabled()
356 {
357         return false;
358 }
359
360
361 bool RCS::revert()
362 {
363         if (doVCCommand("co -f -u" + version_ + ' '
364                     + quoteName(onlyFileName(owner_->absFileName())),
365                     FileName(owner_->filePath())))
366                 return false;
367         // We ignore changes and just reload!
368         owner_->markClean();
369         return true;
370 }
371
372
373 bool RCS::isRevertWithConfirmation()
374 {
375         //FIXME owner && diff ?
376         return true;
377 }
378
379
380 void RCS::undoLast()
381 {
382         LYXERR(Debug::LYXVC, "LyXVC: undoLast");
383         doVCCommand("rcs -o" + version_ + ' '
384                     + quoteName(onlyFileName(owner_->absFileName())),
385                     FileName(owner_->filePath()));
386 }
387
388
389 bool RCS::undoLastEnabled()
390 {
391         return true;
392 }
393
394
395 void RCS::getLog(FileName const & tmpf)
396 {
397         doVCCommand("rlog " + quoteName(onlyFileName(owner_->absFileName()))
398                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
399                     FileName(owner_->filePath()));
400 }
401
402
403 bool RCS::toggleReadOnlyEnabled()
404 {
405         // This got broken somewhere along lfuns dispatch reorganization.
406         // reloadBuffer would be needed after this, but thats problematic
407         // since we are inside Buffer::dispatch.
408         // return true;
409         return false;
410 }
411
412
413 string RCS::revisionInfo(LyXVC::RevisionInfo const info)
414 {
415         if (info == LyXVC::File)
416                 return version_;
417         // fill the rest of the attributes for a single file
418         if (rev_date_cache_.empty())
419                 if (!getRevisionInfo())
420                         return string();
421
422         switch (info) {
423                 case LyXVC::Author:
424                         return rev_author_cache_;
425                 case LyXVC::Date:
426                         return rev_date_cache_;
427                 case LyXVC::Time:
428                         return rev_time_cache_;
429                 default: ;
430         }
431
432         return string();
433 }
434
435
436 bool RCS::getRevisionInfo()
437 {
438         TempFile tempfile("lyxvcout");
439         FileName tmpf = tempfile.name();
440         if (tmpf.empty()) {
441                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
442                 return false;
443         }
444         doVCCommand("rlog -r " + quoteName(onlyFileName(owner_->absFileName()))
445                 + " > " + quoteName(tmpf.toFilesystemEncoding()),
446                 FileName(owner_->filePath()));
447
448         if (tmpf.empty())
449                 return false;
450
451         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
452         string line;
453
454         // we reached to the entry, i.e. after initial log message
455         bool entry=false;
456         // line with critical info, e.g:
457         //"date: 2011/07/02 11:02:54;  author: sanda;  state: Exp;  lines: +17 -2"
458         string result;
459
460         while (ifs) {
461                 getline(ifs, line);
462                 LYXERR(Debug::LYXVC, line);
463                 if (entry && prefixIs(line, "date:")) {
464                         result = line;
465                         break;
466                 }
467                 if (prefixIs(line, "revision"))
468                         entry = true;
469         }
470         if (result.empty())
471                 return false;
472
473         rev_date_cache_ = token(result, ' ', 1);
474         rev_time_cache_ = rtrim(token(result, ' ', 2), ";");
475         rev_author_cache_ = trim(token(token(result, ';', 1), ':', 1));
476
477         return !rev_author_cache_.empty();
478 }
479
480 bool RCS::prepareFileRevision(string const &revis, string & f)
481 {
482         string rev = revis;
483         if (!VCS::makeRCSRevision(version_, rev))
484                 return false;
485
486         TempFile tempfile("lyxvcrev_" + rev + '_');
487         tempfile.setAutoRemove(false);
488         FileName tmpf = tempfile.name();
489         if (tmpf.empty()) {
490                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
491                 return false;
492         }
493
494         doVCCommand("co -p" + rev + ' '
495                       + quoteName(onlyFileName(owner_->absFileName()))
496                       + " > " + quoteName(tmpf.toFilesystemEncoding()),
497                 FileName(owner_->filePath()));
498         tmpf.refresh();
499         if (tmpf.isFileEmpty())
500                 return false;
501
502         f = tmpf.absFileName();
503         return true;
504 }
505
506
507 bool RCS::prepareFileRevisionEnabled()
508 {
509         return true;
510 }
511
512
513 /////////////////////////////////////////////////////////////////////
514 //
515 // CVS
516 //
517 /////////////////////////////////////////////////////////////////////
518
519 CVS::CVS(FileName const & m, Buffer * b) : VCS(b)
520 {
521         // Here we know that the buffer file is either already in CVS or
522         // about to be registered
523         master_ = m;
524         have_rev_info_ = false;
525         scanMaster();
526 }
527
528
529 FileName const CVS::findFile(FileName const & file)
530 {
531         // First we look for the CVS/Entries in the same dir
532         // where we have file.
533         FileName const entries(onlyPath(file.absFileName()) + "/CVS/Entries");
534         string const tmpf = '/' + onlyFileName(file.absFileName()) + '/';
535         LYXERR(Debug::LYXVC, "LyXVC: Checking if file is under cvs in `" << entries
536                              << "' for `" << tmpf << '\'');
537         if (entries.isReadableFile()) {
538                 // Ok we are at least in a CVS dir. Parse the CVS/Entries
539                 // and see if we can find this file. We do a fast and
540                 // dirty parse here.
541                 ifstream ifs(entries.toFilesystemEncoding().c_str());
542                 string line;
543                 while (getline(ifs, line)) {
544                         LYXERR(Debug::LYXVC, "\tEntries: " << line);
545                         if (contains(line, tmpf))
546                                 return entries;
547                 }
548         }
549         return FileName();
550 }
551
552
553 void CVS::scanMaster()
554 {
555         LYXERR(Debug::LYXVC, "LyXVC::CVS: scanMaster. \n     Checking: " << master_);
556         // Ok now we do the real scan...
557         ifstream ifs(master_.toFilesystemEncoding().c_str());
558         string name = onlyFileName(owner_->absFileName());
559         string tmpf = '/' + name + '/';
560         LYXERR(Debug::LYXVC, "\tlooking for `" << tmpf << '\'');
561         string line;
562         static regex const reg("/(.*)/(.*)/(.*)/(.*)/(.*)");
563         while (getline(ifs, line)) {
564                 LYXERR(Debug::LYXVC, "\t  line: " << line);
565                 if (contains(line, tmpf)) {
566                         // Ok extract the fields.
567                         smatch sm;
568
569                         // false positive from coverity
570                         // coverity[CHECKED_RETURN]
571                         regex_match(line, sm, reg);
572
573                         //sm[0]; // whole matched string
574                         //sm[1]; // filename
575                         version_ = sm.str(2);
576                         string const file_date = sm.str(3);
577
578                         //sm[4]; // options
579                         //sm[5]; // tag or tagdate
580                         FileName file(owner_->absFileName());
581                         if (file.isReadableFile()) {
582                                 time_t mod = file.lastModified();
583                                 string mod_date = rtrim(asctime(gmtime(&mod)), "\n");
584                                 LYXERR(Debug::LYXVC, "Date in Entries: `" << file_date
585                                         << "'\nModification date of file: `" << mod_date << '\'');
586                                 if (file.isReadOnly()) {
587                                         // readonly checkout is unlocked
588                                         vcstatus = UNLOCKED;
589                                 } else {
590                                         FileName bdir(addPath(master_.onlyPath().absFileName(),"Base"));
591                                         FileName base(addName(bdir.absFileName(),name));
592                                         // if base version is existent "cvs edit" was used to lock
593                                         vcstatus = base.isReadableFile() ? LOCKED : NOLOCKING;
594                                 }
595                         } else {
596                                 vcstatus = NOLOCKING;
597                         }
598                         break;
599                 }
600         }
601 }
602
603
604 bool CVS::retrieve(FileName const & file)
605 {
606         LYXERR(Debug::LYXVC, "LyXVC::CVS: retrieve.\n\t" << file);
607         // The caller ensures that file does not exist, so no need to check that.
608         return doVCCommandCall("cvs -q update " + quoteName(file.toFilesystemEncoding()),
609                                file.onlyPath()) == 0;
610 }
611
612
613 string const CVS::getTarget(OperationMode opmode) const
614 {
615         switch(opmode) {
616         case Directory:
617                 // in client server mode CVS does not like full path operand for directory operation
618                 // since LyX switches to the repo dir "." is good enough as target
619                 return ".";
620         case File:
621                 return quoteName(onlyFileName(owner_->absFileName()));
622         }
623         return string();
624 }
625
626
627 docstring CVS::toString(CvsStatus status) const
628 {
629         switch (status) {
630         case UpToDate:
631                 return _("Up-to-date");
632         case LocallyModified:
633                 return _("Locally Modified");
634         case LocallyAdded:
635                 return _("Locally Added");
636         case NeedsMerge:
637                 return _("Needs Merge");
638         case NeedsCheckout:
639                 return _("Needs Checkout");
640         case NoCvsFile:
641                 return _("No CVS file");
642         case StatusError:
643                 return _("Cannot retrieve CVS status");
644         }
645         return docstring();
646 }
647
648
649 int CVS::doVCCommandWithOutput(string const & cmd, FileName const & path,
650         FileName const & output, bool reportError)
651 {
652         string redirection = output.empty() ? "" : " > " + quoteName(output.toFilesystemEncoding());
653         return doVCCommand(cmd + redirection, path, reportError);
654 }
655
656
657 int CVS::doVCCommandCallWithOutput(std::string const & cmd,
658         support::FileName const & path,
659         support::FileName const & output)
660 {
661         string redirection = output.empty() ? "" : " > " + quoteName(output.toFilesystemEncoding());
662         return doVCCommandCall(cmd + redirection, path);
663 }
664
665
666 CVS::CvsStatus CVS::getStatus()
667 {
668         TempFile tempfile("lyxvout");
669         FileName tmpf = tempfile.name();
670         if (tmpf.empty()) {
671                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
672                 return StatusError;
673         }
674
675         if (doVCCommandCallWithOutput("cvs status " + getTarget(File),
676                 FileName(owner_->filePath()), tmpf)) {
677                 return StatusError;
678         }
679
680         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
681         CvsStatus status = NoCvsFile;
682
683         while (ifs) {
684                 string line;
685                 getline(ifs, line);
686                 LYXERR(Debug::LYXVC, line << '\n');
687                 if (prefixIs(line, "File:")) {
688                         if (contains(line, "Up-to-date"))
689                                 status = UpToDate;
690                         else if (contains(line, "Locally Modified"))
691                                 status = LocallyModified;
692                         else if (contains(line, "Locally Added"))
693                                 status = LocallyAdded;
694                         else if (contains(line, "Needs Merge"))
695                                 status = NeedsMerge;
696                         else if (contains(line, "Needs Checkout"))
697                                 status = NeedsCheckout;
698                 }
699         }
700         return status;
701 }
702
703 void CVS::getRevisionInfo()
704 {
705         if (have_rev_info_)
706                 return;
707         have_rev_info_ = true;
708         TempFile tempfile("lyxvout");
709         FileName tmpf = tempfile.name();
710         if (tmpf.empty()) {
711                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
712                 return;
713         }
714
715         int rc = doVCCommandCallWithOutput("cvs log -r" + version_
716                 + ' ' + getTarget(File),
717                 FileName(owner_->filePath()), tmpf);
718         if (rc) {
719                 LYXERR(Debug::LYXVC, "cvs log failed with exit code " << rc);
720                 return;
721         }
722
723         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
724         static regex const reg("date: (.*) (.*) (.*);  author: (.*);  state: (.*);(.*)");
725
726         while (ifs) {
727                 string line;
728                 getline(ifs, line);
729                 LYXERR(Debug::LYXVC, line << '\n');
730                 if (prefixIs(line, "date:")) {
731                         smatch sm;
732                         regex_match(line, sm, reg);
733                         //sm[0]; // whole matched string
734                         rev_date_cache_ = sm[1];
735                         rev_time_cache_ = sm[2];
736                         //sm[3]; // GMT offset
737                         rev_author_cache_ = sm[4];
738                         break;
739                 }
740         }
741         if (rev_author_cache_.empty())
742                 LYXERR(Debug::LYXVC,
743                    "Could not retrieve revision info for " << version_ <<
744                    " of " << getTarget(File));
745 }
746
747
748 void CVS::registrer(string const & msg)
749 {
750         doVCCommand("cvs -q add -m \"" + msg + "\" "
751                 + getTarget(File),
752                 FileName(owner_->filePath()));
753 }
754
755
756 bool CVS::renameEnabled()
757 {
758         return true;
759 }
760
761
762 string CVS::rename(support::FileName const & newFile, string const & msg)
763 {
764         // CVS has no real rename command, so we create a poor mans version
765         support::FileName const oldFile(owner_->absFileName());
766         string ret = copy(newFile, msg);
767         if (ret.empty())
768                 return ret;
769         string cmd = "cvs -q remove -m \"" + msg + "\" " +
770                 quoteName(oldFile.onlyFileName());
771         FileName path(oldFile.onlyPath());
772         return doVCCommand(cmd, path) ? string() : ret;
773 }
774
775
776 bool CVS::copyEnabled()
777 {
778         return true;
779 }
780
781
782 string CVS::copy(support::FileName const & newFile, string const & msg)
783 {
784         // CVS has no real copy command, so we create a poor mans version
785         support::FileName const oldFile(owner_->absFileName());
786         if (!oldFile.copyTo(newFile))
787                 return string();
788         FileName path(oldFile.onlyPath());
789         string relFile(to_utf8(newFile.relPath(path.absFileName())));
790         string cmd("cvs -q add -m \"" + msg + "\" " + quoteName(relFile));
791         return doVCCommand(cmd, path) ? string() : "CVS: Proceeded";
792 }
793
794
795 void CVS::getDiff(OperationMode opmode, FileName const & tmpf)
796 {
797         doVCCommandWithOutput("cvs diff " + getTarget(opmode),
798                 FileName(owner_->filePath()), tmpf, false);
799 }
800
801
802 int CVS::edit()
803 {
804         vcstatus = LOCKED;
805         return doVCCommand("cvs -q edit " + getTarget(File),
806                 FileName(owner_->filePath()));
807 }
808
809
810 int CVS::unedit()
811 {
812         vcstatus = UNLOCKED;
813         return doVCCommand("cvs -q unedit " + getTarget(File),
814                 FileName(owner_->filePath()));
815 }
816
817
818 int CVS::update(OperationMode opmode, FileName const & tmpf)
819 {
820         return doVCCommandWithOutput("cvs -q update "
821                 + getTarget(opmode),
822                 FileName(owner_->filePath()), tmpf, false);
823 }
824
825
826 string CVS::scanLogFile(FileName const & f, string & status)
827 {
828         ifstream ifs(f.toFilesystemEncoding().c_str());
829
830         while (ifs) {
831                 string line;
832                 getline(ifs, line);
833                 LYXERR(Debug::LYXVC, line << '\n');
834                 if (!line.empty())
835                         status += line + "; ";
836                 if (prefixIs(line, "C ")) {
837                         ifs.close();
838                         return line;
839                 }
840         }
841         ifs.close();
842         return string();
843 }
844
845
846 LyXVC::CommandResult CVS::checkIn(string const & msg, string & log)
847 {
848         CvsStatus status = getStatus();
849         switch (status) {
850         case UpToDate:
851                 if (vcstatus != NOLOCKING)
852                         if (unedit())
853                                 return LyXVC::ErrorCommand;
854                 log = "CVS: Proceeded";
855                 return LyXVC::VCSuccess;
856         case LocallyModified:
857         case LocallyAdded: {
858                 int rc = doVCCommand("cvs -q commit -m \"" + msg + "\" "
859                         + getTarget(File),
860                     FileName(owner_->filePath()));
861                 if (rc)
862                         return LyXVC::ErrorCommand;
863                 log = "CVS: Proceeded";
864                 return LyXVC::VCSuccess;
865         }
866         case NeedsMerge:
867         case NeedsCheckout:
868                 frontend::Alert::error(_("Revision control error."),
869                         _("The repository version is newer then the current check out.\n"
870                           "You have to update from repository first or revert your changes.")) ;
871                 break;
872         default:
873                 frontend::Alert::error(_("Revision control error."),
874                         bformat(_("Bad status when checking in changes.\n"
875                                           "\n'%1$s'\n\n"),
876                                 toString(status)));
877                 break;
878         }
879         return LyXVC::ErrorBefore;
880 }
881
882
883 bool CVS::isLocked() const
884 {
885         FileName fn(owner_->absFileName());
886         fn.refresh();
887         return !fn.isReadOnly();
888 }
889
890
891 bool CVS::checkInEnabled()
892 {
893         if (vcstatus != NOLOCKING)
894                 return isLocked();
895         else
896                 return true;
897 }
898
899
900 bool CVS::isCheckInWithConfirmation()
901 {
902         CvsStatus status = getStatus();
903         return status == LocallyModified || status == LocallyAdded;
904 }
905
906
907 string CVS::checkOut()
908 {
909         if (vcstatus != NOLOCKING && edit())
910                 return string();
911         TempFile tempfile("lyxvout");
912         FileName tmpf = tempfile.name();
913         if (tmpf.empty()) {
914                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
915                 return string();
916         }
917
918         int rc = update(File, tmpf);
919         string log;
920         string const res = scanLogFile(tmpf, log);
921         if (!res.empty()) {
922                 frontend::Alert::error(_("Revision control error."),
923                         bformat(_("Error when updating from repository.\n"
924                                 "You have to manually resolve the conflicts NOW!\n'%1$s'.\n\n"
925                                 "After pressing OK, LyX will try to reopen the resolved document."),
926                                 from_local8bit(res)));
927                 rc = 0;
928         }
929
930         return rc ? string() : log.empty() ? "CVS: Proceeded" : "CVS: " + log;
931 }
932
933
934 bool CVS::checkOutEnabled()
935 {
936         if (vcstatus != NOLOCKING)
937                 return !isLocked();
938         else
939                 return true;
940 }
941
942
943 string CVS::repoUpdate()
944 {
945         TempFile tempfile("lyxvout");
946         FileName tmpf = tempfile.name();
947         if (tmpf.empty()) {
948                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
949                 return string();
950         }
951
952         getDiff(Directory, tmpf);
953         docstring res = tmpf.fileContents("UTF-8");
954         if (!res.empty()) {
955                 LYXERR(Debug::LYXVC, "Diff detected:\n" << res);
956                 docstring const file = from_utf8(owner_->filePath());
957                 docstring text = bformat(_("There were detected changes "
958                                 "in the working directory:\n%1$s\n\n"
959                                 "Possible file conflicts must be then resolved manually "
960                                 "or you will need to revert back to the repository version."), file);
961                 int ret = frontend::Alert::prompt(_("Changes detected"),
962                                 text, 0, 1, _("&Continue"), _("&Abort"), _("View &Log ..."));
963                 if (ret == 2) {
964                         dispatch(FuncRequest(LFUN_DIALOG_SHOW, "file " + tmpf.absFileName()));
965                         ret = frontend::Alert::prompt(_("Changes detected"),
966                                 text, 0, 1, _("&Continue"), _("&Abort"));
967                         hideDialogs("file", 0);
968                 }
969                 if (ret == 1)
970                         return string();
971         }
972
973         int rc = update(Directory, tmpf);
974         res += "Update log:\n" + tmpf.fileContents("UTF-8");
975         LYXERR(Debug::LYXVC, res);
976
977         string log;
978         string sres = scanLogFile(tmpf, log);
979         if (!sres.empty()) {
980                 docstring const file = owner_->fileName().displayName(20);
981                 frontend::Alert::error(_("Revision control error."),
982                         bformat(_("Error when updating document %1$s from repository.\n"
983                                           "You have to manually resolve the conflicts NOW!\n'%2$s'.\n\n"
984                                           "After pressing OK, LyX will try to reopen the resolved document."),
985                                 file, from_local8bit(sres)));
986                 rc = 0;
987         }
988
989         return rc ? string() : log.empty() ? "CVS: Proceeded" : "CVS: " + log;
990 }
991
992
993 bool CVS::repoUpdateEnabled()
994 {
995         return true;
996 }
997
998
999 string CVS::lockingToggle()
1000 {
1001         lyxerr << "Sorry, not implemented." << endl;
1002         return string();
1003 }
1004
1005
1006 bool CVS::lockingToggleEnabled()
1007 {
1008         return false;
1009 }
1010
1011
1012 bool CVS::isRevertWithConfirmation()
1013 {
1014         CvsStatus status = getStatus();
1015         return !owner_->isClean() || status == LocallyModified || status == NeedsMerge;
1016 }
1017
1018
1019 bool CVS::revert()
1020 {
1021         // Reverts to the version in CVS repository and
1022         // gets the updated version from the repository.
1023         CvsStatus status = getStatus();
1024         switch (status) {
1025         case UpToDate:
1026                 if (vcstatus != NOLOCKING)
1027                         return 0 == unedit();
1028                 break;
1029         case NeedsMerge:
1030         case NeedsCheckout:
1031         case LocallyModified: {
1032                 FileName f(owner_->absFileName());
1033                 f.removeFile();
1034                 update(File, FileName());
1035                 owner_->markClean();
1036                 break;
1037         }
1038         case LocallyAdded: {
1039                 docstring const file = owner_->fileName().displayName(20);
1040                 frontend::Alert::error(_("Revision control error."),
1041                         bformat(_("The document %1$s is not in repository.\n"
1042                                   "You have to check in the first revision before you can revert."),
1043                                 file)) ;
1044                 return false;
1045         }
1046         default: {
1047                 docstring const file = owner_->fileName().displayName(20);
1048                 frontend::Alert::error(_("Revision control error."),
1049                         bformat(_("Cannot revert document %1$s to repository version.\n"
1050                                   "The status '%2$s' is unexpected."),
1051                                 file, toString(status)));
1052                 return false;
1053                 }
1054         }
1055         return true;
1056 }
1057
1058
1059 void CVS::undoLast()
1060 {
1061         // merge the current with the previous version
1062         // in a reverse patch kind of way, so that the
1063         // result is to revert the last changes.
1064         lyxerr << "Sorry, not implemented." << endl;
1065 }
1066
1067
1068 bool CVS::undoLastEnabled()
1069 {
1070         return false;
1071 }
1072
1073
1074 void CVS::getLog(FileName const & tmpf)
1075 {
1076         doVCCommandWithOutput("cvs log " + getTarget(File),
1077                 FileName(owner_->filePath()),
1078                 tmpf);
1079 }
1080
1081
1082 bool CVS::toggleReadOnlyEnabled()
1083 {
1084         return false;
1085 }
1086
1087
1088 string CVS::revisionInfo(LyXVC::RevisionInfo const info)
1089 {
1090         if (!version_.empty()) {
1091                 getRevisionInfo();
1092                 switch (info) {
1093                 case LyXVC::File:
1094                         return version_;
1095                 case LyXVC::Author:
1096                         return rev_author_cache_;
1097                 case LyXVC::Date:
1098                         return rev_date_cache_;
1099                 case LyXVC::Time:
1100                         return rev_time_cache_;
1101                 default: ;
1102                 }
1103         }
1104         return string();
1105 }
1106
1107
1108 bool CVS::prepareFileRevision(string const & revis, string & f)
1109 {
1110         string rev = revis;
1111         if (!VCS::makeRCSRevision(version_, rev))
1112                 return false;
1113
1114         TempFile tempfile("lyxvcrev_" + rev + '_');
1115         tempfile.setAutoRemove(false);
1116         FileName tmpf = tempfile.name();
1117         if (tmpf.empty()) {
1118                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1119                 return false;
1120         }
1121
1122         doVCCommandWithOutput("cvs update -p -r" + rev + ' '
1123                 + getTarget(File),
1124                 FileName(owner_->filePath()), tmpf);
1125         tmpf.refresh();
1126         if (tmpf.isFileEmpty())
1127                 return false;
1128
1129         f = tmpf.absFileName();
1130         return true;
1131 }
1132
1133
1134 bool CVS::prepareFileRevisionEnabled()
1135 {
1136         return true;
1137 }
1138
1139
1140 /////////////////////////////////////////////////////////////////////
1141 //
1142 // SVN
1143 //
1144 /////////////////////////////////////////////////////////////////////
1145
1146 SVN::SVN(FileName const & m, Buffer * b) : VCS(b)
1147 {
1148         // Here we know that the buffer file is either already in SVN or
1149         // about to be registered
1150         master_ = m;
1151         locked_mode_ = 0;
1152         scanMaster();
1153 }
1154
1155
1156 FileName const SVN::findFile(FileName const & file)
1157 {
1158         // First we check the existence of repository meta data.
1159         if (!VCS::checkparentdirs(file, ".svn")) {
1160                 LYXERR(Debug::LYXVC, "Cannot find SVN meta data for " << file);
1161                 return FileName();
1162         }
1163
1164         // Now we check the status of the file.
1165         TempFile tempfile("lyxvcout");
1166         FileName tmpf = tempfile.name();
1167         if (tmpf.empty()) {
1168                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1169                 return FileName();
1170         }
1171
1172         string const fname = onlyFileName(file.absFileName());
1173         LYXERR(Debug::LYXVC, "LyXVC: Checking if file is under svn control for `" << fname << '\'');
1174         bool found = 0 == doVCCommandCall("svn info " + quoteName(fname)
1175                                                 + " > " + quoteName(tmpf.toFilesystemEncoding()),
1176                                                 file.onlyPath());
1177         LYXERR(Debug::LYXVC, "SVN control: " << (found ? "enabled" : "disabled"));
1178         return found ? file : FileName();
1179 }
1180
1181
1182 void SVN::scanMaster()
1183 {
1184         // vcstatus code is somewhat superflous,
1185         // until we want to implement read-only toggle for svn.
1186         vcstatus = NOLOCKING;
1187         if (checkLockMode()) {
1188                 if (isLocked())
1189                         vcstatus = LOCKED;
1190                 else
1191                         vcstatus = UNLOCKED;
1192         }
1193 }
1194
1195
1196 bool SVN::checkLockMode()
1197 {
1198         TempFile tempfile("lyxvcout");
1199         FileName tmpf = tempfile.name();
1200         if (tmpf.empty()){
1201                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1202                 return false;
1203         }
1204
1205         LYXERR(Debug::LYXVC, "Detecting locking mode...");
1206         if (doVCCommandCall("svn proplist " + quoteName(onlyFileName(owner_->absFileName()))
1207                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1208                     FileName(owner_->filePath())))
1209                 return false;
1210
1211         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
1212         string line;
1213         bool ret = false;
1214
1215         while (ifs && !ret) {
1216                 getline(ifs, line);
1217                 LYXERR(Debug::LYXVC, line);
1218                 if (contains(line, "svn:needs-lock"))
1219                         ret = true;
1220         }
1221         LYXERR(Debug::LYXVC, "Locking enabled: " << ret);
1222         ifs.close();
1223         locked_mode_ = ret;
1224         return ret;
1225
1226 }
1227
1228
1229 bool SVN::isLocked() const
1230 {
1231         FileName file(owner_->absFileName());
1232         file.refresh();
1233         return !file.isReadOnly();
1234 }
1235
1236
1237 bool SVN::retrieve(FileName const & file)
1238 {
1239         LYXERR(Debug::LYXVC, "LyXVC::SVN: retrieve.\n\t" << file);
1240         // The caller ensures that file does not exist, so no need to check that.
1241         return doVCCommandCall("svn update -q --non-interactive " + quoteName(file.onlyFileName()),
1242                                file.onlyPath()) == 0;
1243 }
1244
1245
1246 void SVN::registrer(string const & /*msg*/)
1247 {
1248         doVCCommand("svn add -q " + quoteName(onlyFileName(owner_->absFileName())),
1249                     FileName(owner_->filePath()));
1250 }
1251
1252
1253 bool SVN::renameEnabled()
1254 {
1255         return true;
1256 }
1257
1258
1259 string SVN::rename(support::FileName const & newFile, string const & msg)
1260 {
1261         // svn move does not require a log message, since it does not commit.
1262         // In LyX we commit immediately afterwards, otherwise it could be
1263         // confusing to the user to have two uncommitted files.
1264         FileName path(owner_->filePath());
1265         string relFile(to_utf8(newFile.relPath(path.absFileName())));
1266         string cmd("svn move -q " + quoteName(onlyFileName(owner_->absFileName())) +
1267                    ' ' + quoteName(relFile));
1268         if (doVCCommand(cmd, path)) {
1269                 cmd = "svn revert -q " +
1270                         quoteName(onlyFileName(owner_->absFileName())) + ' ' +
1271                         quoteName(relFile);
1272                 doVCCommand(cmd, path);
1273                 if (newFile.exists())
1274                         newFile.removeFile();
1275                 return string();
1276         }
1277         vector<support::FileName> f;
1278         f.push_back(owner_->fileName());
1279         f.push_back(newFile);
1280         string log;
1281         if (checkIn(f, msg, log) != LyXVC::VCSuccess) {
1282                 cmd = "svn revert -q " +
1283                         quoteName(onlyFileName(owner_->absFileName())) + ' ' +
1284                         quoteName(relFile);
1285                 doVCCommand(cmd, path);
1286                 if (newFile.exists())
1287                         newFile.removeFile();
1288                 return string();
1289         }
1290         return log;
1291 }
1292
1293
1294 bool SVN::copyEnabled()
1295 {
1296         return true;
1297 }
1298
1299
1300 string SVN::copy(support::FileName const & newFile, string const & msg)
1301 {
1302         // svn copy does not require a log message, since it does not commit.
1303         // In LyX we commit immediately afterwards, otherwise it could be
1304         // confusing to the user to have an uncommitted file.
1305         FileName path(owner_->filePath());
1306         string relFile(to_utf8(newFile.relPath(path.absFileName())));
1307         string cmd("svn copy -q " + quoteName(onlyFileName(owner_->absFileName())) +
1308                    ' ' + quoteName(relFile));
1309         if (doVCCommand(cmd, path))
1310                 return string();
1311         vector<support::FileName> f(1, newFile);
1312         string log;
1313         if (checkIn(f, msg, log) == LyXVC::VCSuccess)
1314                 return log;
1315         return string();
1316 }
1317
1318
1319 LyXVC::CommandResult SVN::checkIn(string const & msg, string & log)
1320 {
1321         vector<support::FileName> f(1, owner_->fileName());
1322         return checkIn(f, msg, log);
1323 }
1324
1325
1326 LyXVC::CommandResult
1327 SVN::checkIn(vector<support::FileName> const & f, string const & msg, string & log)
1328 {
1329         TempFile tempfile("lyxvcout");
1330         FileName tmpf = tempfile.name();
1331         if (tmpf.empty()){
1332                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1333                 log = N_("Error: Could not generate logfile.");
1334                 return LyXVC::ErrorBefore;
1335         }
1336
1337         ostringstream os;
1338         os << "svn commit -m \"" << msg << '"';
1339         for (size_t i = 0; i < f.size(); ++i)
1340                 os << ' ' << quoteName(f[i].onlyFileName());
1341         os << " > " << quoteName(tmpf.toFilesystemEncoding());
1342         LyXVC::CommandResult ret =
1343                 doVCCommand(os.str(), FileName(owner_->filePath())) ?
1344                         LyXVC::ErrorCommand : LyXVC::VCSuccess;
1345
1346         string res = scanLogFile(tmpf, log);
1347         if (!res.empty()) {
1348                 frontend::Alert::error(_("Revision control error."),
1349                                 _("Error when committing to repository.\n"
1350                                 "You have to manually resolve the problem.\n"
1351                                 "LyX will reopen the document after you press OK."));
1352                 ret = LyXVC::ErrorCommand;
1353         }
1354         else
1355                 if (!fileLock(false, tmpf, log))
1356                         ret = LyXVC::ErrorCommand;
1357
1358         if (!log.empty())
1359                 log.insert(0, "SVN: ");
1360         if (ret == LyXVC::VCSuccess && log.empty())
1361                 log = "SVN: Proceeded";
1362         return ret;
1363 }
1364
1365
1366 bool SVN::checkInEnabled()
1367 {
1368         if (locked_mode_)
1369                 return isLocked();
1370         else
1371                 return true;
1372 }
1373
1374
1375 bool SVN::isCheckInWithConfirmation()
1376 {
1377         // FIXME one day common getDiff and perhaps OpMode for all backends
1378
1379         TempFile tempfile("lyxvcout");
1380         FileName tmpf = tempfile.name();
1381         if (tmpf.empty()) {
1382                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1383                 return true;
1384         }
1385
1386         doVCCommandCall("svn diff " + quoteName(owner_->absFileName())
1387                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1388                 FileName(owner_->filePath()));
1389
1390         docstring diff = tmpf.fileContents("UTF-8");
1391
1392         if (diff.empty())
1393                 return false;
1394
1395         return true;
1396 }
1397
1398
1399 // FIXME Correctly return code should be checked instead of this.
1400 // This would need another solution than just plain startscript.
1401 // Hint from Andre': QProcess::readAllStandardError()...
1402 string SVN::scanLogFile(FileName const & f, string & status)
1403 {
1404         ifstream ifs(f.toFilesystemEncoding().c_str());
1405         string line;
1406
1407         while (ifs) {
1408                 getline(ifs, line);
1409                 LYXERR(Debug::LYXVC, line << '\n');
1410                 if (!line.empty())
1411                         status += line + "; ";
1412                 if (prefixIs(line, "C ") || prefixIs(line, "CU ")
1413                                          || contains(line, "Commit failed")) {
1414                         ifs.close();
1415                         return line;
1416                 }
1417                 if (contains(line, "svn:needs-lock")) {
1418                         ifs.close();
1419                         return line;
1420                 }
1421         }
1422         ifs.close();
1423         return string();
1424 }
1425
1426
1427 bool SVN::fileLock(bool lock, FileName const & tmpf, string &status)
1428 {
1429         if (!locked_mode_ || (isLocked() == lock))
1430                 return true;
1431
1432         string const arg = lock ? "lock " : "unlock ";
1433         doVCCommand("svn "+ arg + quoteName(onlyFileName(owner_->absFileName()))
1434                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1435                     FileName(owner_->filePath()));
1436
1437         // Lock error messages go unfortunately on stderr and are unreachible this way.
1438         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
1439         string line;
1440         while (ifs) {
1441                 getline(ifs, line);
1442                 if (!line.empty()) status += line + "; ";
1443         }
1444         ifs.close();
1445
1446         if (isLocked() == lock)
1447                 return true;
1448
1449         if (lock)
1450                 frontend::Alert::error(_("Revision control error."),
1451                         _("Error while acquiring write lock.\n"
1452                         "Another user is most probably editing\n"
1453                         "the current document now!\n"
1454                         "Also check the access to the repository."));
1455         else
1456                 frontend::Alert::error(_("Revision control error."),
1457                         _("Error while releasing write lock.\n"
1458                         "Check the access to the repository."));
1459         return false;
1460 }
1461
1462
1463 string SVN::checkOut()
1464 {
1465         TempFile tempfile("lyxvcout");
1466         FileName tmpf = tempfile.name();
1467         if (tmpf.empty()) {
1468                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1469                 return N_("Error: Could not generate logfile.");
1470         }
1471
1472         doVCCommand("svn update --non-interactive " + quoteName(onlyFileName(owner_->absFileName()))
1473                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1474                     FileName(owner_->filePath()));
1475
1476         string log;
1477         string const res = scanLogFile(tmpf, log);
1478         if (!res.empty())
1479                 frontend::Alert::error(_("Revision control error."),
1480                         bformat(_("Error when updating from repository.\n"
1481                                 "You have to manually resolve the conflicts NOW!\n'%1$s'.\n\n"
1482                                 "After pressing OK, LyX will try to reopen the resolved document."),
1483                         from_local8bit(res)));
1484
1485         fileLock(true, tmpf, log);
1486
1487         return log.empty() ? string() : "SVN: " + log;
1488 }
1489
1490
1491 bool SVN::checkOutEnabled()
1492 {
1493         if (locked_mode_)
1494                 return !isLocked();
1495         else
1496                 return true;
1497 }
1498
1499
1500 string SVN::repoUpdate()
1501 {
1502         TempFile tempfile("lyxvcout");
1503         FileName tmpf = tempfile.name();
1504         if (tmpf.empty()) {
1505                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1506                 return N_("Error: Could not generate logfile.");
1507         }
1508
1509         doVCCommand("svn diff " + quoteName(owner_->filePath())
1510                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1511                 FileName(owner_->filePath()));
1512         docstring res = tmpf.fileContents("UTF-8");
1513         if (!res.empty()) {
1514                 LYXERR(Debug::LYXVC, "Diff detected:\n" << res);
1515                 docstring const file = from_utf8(owner_->filePath());
1516                 docstring text = bformat(_("There were detected changes "
1517                                 "in the working directory:\n%1$s\n\n"
1518                                 "In case of file conflict version of the local directory files "
1519                                 "will be preferred."
1520                                 "\n\nContinue?"), file);
1521                 int ret = frontend::Alert::prompt(_("Changes detected"),
1522                                 text, 0, 1, _("&Yes"), _("&No"), _("View &Log ..."));
1523                 if (ret == 2) {
1524                         dispatch(FuncRequest(LFUN_DIALOG_SHOW, "file " + tmpf.absFileName()));
1525                         ret = frontend::Alert::prompt(_("Changes detected"),
1526                                 text, 0, 1, _("&Yes"), _("&No"));
1527                         hideDialogs("file", 0);
1528                 }
1529                 if (ret == 1)
1530                         return string();
1531         }
1532
1533         // Reverting looks too harsh, see bug #6255.
1534         // doVCCommand("svn revert -R " + quoteName(owner_->filePath())
1535         // + " > " + quoteName(tmpf.toFilesystemEncoding()),
1536         // FileName(owner_->filePath()));
1537         // res = "Revert log:\n" + tmpf.fileContents("UTF-8");
1538         doVCCommand("svn update --accept mine-full " + quoteName(owner_->filePath())
1539                 + " > " + quoteName(tmpf.toFilesystemEncoding()),
1540                 FileName(owner_->filePath()));
1541         res += "Update log:\n" + tmpf.fileContents("UTF-8");
1542
1543         LYXERR(Debug::LYXVC, res);
1544         return to_utf8(res);
1545 }
1546
1547
1548 bool SVN::repoUpdateEnabled()
1549 {
1550         return true;
1551 }
1552
1553
1554 string SVN::lockingToggle()
1555 {
1556         TempFile tempfile("lyxvcout");
1557         FileName tmpf = tempfile.name();
1558         if (tmpf.empty()) {
1559                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1560                 return N_("Error: Could not generate logfile.");
1561         }
1562
1563         int ret = doVCCommand("svn proplist " + quoteName(onlyFileName(owner_->absFileName()))
1564                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1565                     FileName(owner_->filePath()));
1566         if (ret)
1567                 return string();
1568
1569         string log;
1570         string res = scanLogFile(tmpf, log);
1571         bool locking = contains(res, "svn:needs-lock");
1572         if (!locking)
1573                 ret = doVCCommand("svn propset svn:needs-lock ON "
1574                     + quoteName(onlyFileName(owner_->absFileName()))
1575                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1576                     FileName(owner_->filePath()));
1577         else
1578                 ret = doVCCommand("svn propdel svn:needs-lock "
1579                     + quoteName(onlyFileName(owner_->absFileName()))
1580                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1581                     FileName(owner_->filePath()));
1582         if (ret)
1583                 return string();
1584
1585         frontend::Alert::warning(_("SVN File Locking"),
1586                 (locking ? _("Locking property unset.") : _("Locking property set.")) + '\n'
1587                 + _("Do not forget to commit the locking property into the repository."),
1588                 true);
1589
1590         return string("SVN: ") + (locking ?
1591                 N_("Locking property unset.") : N_("Locking property set."));
1592 }
1593
1594
1595 bool SVN::lockingToggleEnabled()
1596 {
1597         return true;
1598 }
1599
1600
1601 bool SVN::revert()
1602 {
1603         // Reverts to the version in SVN repository and
1604         // gets the updated version from the repository.
1605         string const fil = quoteName(onlyFileName(owner_->absFileName()));
1606
1607         if (doVCCommand("svn revert -q " + fil,
1608                     FileName(owner_->filePath())))
1609                 return false;
1610         owner_->markClean();
1611         return true;
1612 }
1613
1614
1615 bool SVN::isRevertWithConfirmation()
1616 {
1617         //FIXME owner && diff
1618         return true;
1619 }
1620
1621
1622 void SVN::undoLast()
1623 {
1624         // merge the current with the previous version
1625         // in a reverse patch kind of way, so that the
1626         // result is to revert the last changes.
1627         lyxerr << "Sorry, not implemented." << endl;
1628 }
1629
1630
1631 bool SVN::undoLastEnabled()
1632 {
1633         return false;
1634 }
1635
1636
1637 string SVN::revisionInfo(LyXVC::RevisionInfo const info)
1638 {
1639         if (info == LyXVC::Tree) {
1640                 if (rev_tree_cache_.empty())
1641                         if (!getTreeRevisionInfo())
1642                                 rev_tree_cache_ = "?";
1643                 if (rev_tree_cache_ == "?")
1644                         return string();
1645
1646                 return rev_tree_cache_;
1647         }
1648
1649         // fill the rest of the attributes for a single file
1650         if (rev_file_cache_.empty())
1651                 if (!getFileRevisionInfo())
1652                         rev_file_cache_ = "?";
1653
1654         switch (info) {
1655                 case LyXVC::File:
1656                         if (rev_file_cache_ == "?")
1657                                 return string();
1658                         return rev_file_cache_;
1659                 case LyXVC::Author:
1660                         return rev_author_cache_;
1661                 case LyXVC::Date:
1662                         return rev_date_cache_;
1663                 case LyXVC::Time:
1664                         return rev_time_cache_;
1665                 default: ;
1666
1667         }
1668
1669         return string();
1670 }
1671
1672
1673 bool SVN::getFileRevisionInfo()
1674 {
1675         TempFile tempfile("lyxvcout");
1676         FileName tmpf = tempfile.name();
1677         if (tmpf.empty()) {
1678                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1679                 return false;
1680         }
1681
1682         doVCCommand("svn info --xml " + quoteName(onlyFileName(owner_->absFileName()))
1683                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1684                     FileName(owner_->filePath()));
1685
1686         if (tmpf.empty())
1687                 return false;
1688
1689         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
1690         string line;
1691         // commit log part
1692         bool c = false;
1693         string rev;
1694
1695         while (ifs) {
1696                 getline(ifs, line);
1697                 LYXERR(Debug::LYXVC, line);
1698                 if (prefixIs(line, "<commit"))
1699                         c = true;
1700                 if (c && prefixIs(line, "   revision=\"") && suffixIs(line, "\">")) {
1701                         string l1 = subst(line, "revision=\"", "");
1702                         string l2 = trim(subst(l1, "\">", ""));
1703                         if (isStrInt(l2))
1704                                 rev_file_cache_ = rev = l2;
1705                 }
1706                 if (c && prefixIs(line, "<author>") && suffixIs(line, "</author>")) {
1707                         string l1 = subst(line, "<author>", "");
1708                         string l2 = subst(l1, "</author>", "");
1709                         rev_author_cache_ = l2;
1710                 }
1711                 if (c && prefixIs(line, "<date>") && suffixIs(line, "</date>")) {
1712                         string l1 = subst(line, "<date>", "");
1713                         string l2 = subst(l1, "</date>", "");
1714                         l2 = split(l2, l1, 'T');
1715                         rev_date_cache_ = l1;
1716                         l2 = split(l2, l1, '.');
1717                         rev_time_cache_ = l1;
1718                 }
1719         }
1720
1721         ifs.close();
1722         return !rev.empty();
1723 }
1724
1725
1726 bool SVN::getTreeRevisionInfo()
1727 {
1728         TempFile tempfile("lyxvcout");
1729         FileName tmpf = tempfile.name();
1730         if (tmpf.empty()) {
1731                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1732                 return false;
1733         }
1734
1735         doVCCommand("svnversion -n . > " + quoteName(tmpf.toFilesystemEncoding()),
1736                     FileName(owner_->filePath()));
1737
1738         if (tmpf.empty())
1739                 return false;
1740
1741         // only first line in case something bad happens.
1742         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
1743         string line;
1744         getline(ifs, line);
1745         ifs.close();
1746
1747         rev_tree_cache_ = line;
1748         return !line.empty();
1749 }
1750
1751
1752 void SVN::getLog(FileName const & tmpf)
1753 {
1754         doVCCommand("svn log " + quoteName(onlyFileName(owner_->absFileName()))
1755                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1756                     FileName(owner_->filePath()));
1757 }
1758
1759
1760 bool SVN::prepareFileRevision(string const & revis, string & f)
1761 {
1762         if (!isStrInt(revis))
1763                 return false;
1764
1765         int rev = convert<int>(revis);
1766         if (rev <= 0)
1767                 if (!getFileRevisionInfo())
1768                         return false;
1769         if (rev == 0)
1770                 rev = convert<int>(rev_file_cache_);
1771         // go back for minus rev
1772         else if (rev < 0) {
1773                 rev = rev + convert<int>(rev_file_cache_);
1774                 if (rev < 1)
1775                         return false;
1776         }
1777
1778         string revname = convert<string>(rev);
1779         TempFile tempfile("lyxvcrev_" + revname + '_');
1780         tempfile.setAutoRemove(false);
1781         FileName tmpf = tempfile.name();
1782         if (tmpf.empty()) {
1783                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1784                 return false;
1785         }
1786
1787         doVCCommand("svn cat -r " + revname + ' '
1788                       + quoteName(onlyFileName(owner_->absFileName()))
1789                       + " > " + quoteName(tmpf.toFilesystemEncoding()),
1790                 FileName(owner_->filePath()));
1791         tmpf.refresh();
1792         if (tmpf.isFileEmpty())
1793                 return false;
1794
1795         f = tmpf.absFileName();
1796         return true;
1797 }
1798
1799
1800 bool SVN::prepareFileRevisionEnabled()
1801 {
1802         return true;
1803 }
1804
1805
1806
1807 bool SVN::toggleReadOnlyEnabled()
1808 {
1809         return false;
1810 }
1811
1812
1813 /////////////////////////////////////////////////////////////////////
1814 //
1815 // GIT
1816 //
1817 /////////////////////////////////////////////////////////////////////
1818
1819 GIT::GIT(FileName const & m, Buffer * b) : VCS(b)
1820 {
1821         // Here we know that the buffer file is either already in GIT or
1822         // about to be registered
1823         master_ = m;
1824         scanMaster();
1825 }
1826
1827
1828 FileName const GIT::findFile(FileName const & file)
1829 {
1830         // First we check the existence of repository meta data.
1831         if (!VCS::checkparentdirs(file, ".git")) {
1832                 LYXERR(Debug::LYXVC, "Cannot find GIT meta data for " << file);
1833                 return FileName();
1834         }
1835
1836         // Now we check the status of the file.
1837         TempFile tempfile("lyxvcout");
1838         FileName tmpf = tempfile.name();
1839         if (tmpf.empty()) {
1840                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1841                 return FileName();
1842         }
1843
1844         string const fname = onlyFileName(file.absFileName());
1845         LYXERR(Debug::LYXVC, "LyXVC: Checking if file is under git control for `"
1846                         << fname << '\'');
1847         doVCCommandCall("git ls-files " +
1848                         quoteName(fname) + " > " +
1849                         quoteName(tmpf.toFilesystemEncoding()),
1850                         file.onlyPath());
1851         tmpf.refresh();
1852         bool found = !tmpf.isFileEmpty();
1853         LYXERR(Debug::LYXVC, "GIT control: " << (found ? "enabled" : "disabled"));
1854         return found ? file : FileName();
1855 }
1856
1857
1858 void GIT::scanMaster()
1859 {
1860         // vcstatus code is somewhat superflous,
1861         // until we want to implement read-only toggle for git.
1862         vcstatus = NOLOCKING;
1863 }
1864
1865
1866 bool GIT::retrieve(FileName const & file)
1867 {
1868         LYXERR(Debug::LYXVC, "LyXVC::GIT: retrieve.\n\t" << file);
1869         // The caller ensures that file does not exist, so no need to check that.
1870         return doVCCommandCall("git checkout -q " + quoteName(file.onlyFileName()),
1871                                file.onlyPath()) == 0;
1872 }
1873
1874
1875 void GIT::registrer(string const & /*msg*/)
1876 {
1877         doVCCommand("git add " + quoteName(onlyFileName(owner_->absFileName())),
1878                     FileName(owner_->filePath()));
1879 }
1880
1881
1882 bool GIT::renameEnabled()
1883 {
1884         return true;
1885 }
1886
1887
1888 string GIT::rename(support::FileName const & newFile, string const & msg)
1889 {
1890         // git mv does not require a log message, since it does not commit.
1891         // In LyX we commit immediately afterwards, otherwise it could be
1892         // confusing to the user to have two uncommitted files.
1893         FileName path(owner_->filePath());
1894         string relFile(to_utf8(newFile.relPath(path.absFileName())));
1895         string cmd("git mv " + quoteName(onlyFileName(owner_->absFileName())) +
1896                    ' ' + quoteName(relFile));
1897         if (doVCCommand(cmd, path)) {
1898                 cmd = "git checkout -q " +
1899                         quoteName(onlyFileName(owner_->absFileName())) + ' ' +
1900                         quoteName(relFile);
1901                 doVCCommand(cmd, path);
1902                 if (newFile.exists())
1903                         newFile.removeFile();
1904                 return string();
1905         }
1906         vector<support::FileName> f;
1907         f.push_back(owner_->fileName());
1908         f.push_back(newFile);
1909         string log;
1910         if (checkIn(f, msg, log) != LyXVC::VCSuccess) {
1911                 cmd = "git checkout -q " +
1912                         quoteName(onlyFileName(owner_->absFileName())) + ' ' +
1913                         quoteName(relFile);
1914                 doVCCommand(cmd, path);
1915                 if (newFile.exists())
1916                         newFile.removeFile();
1917                 return string();
1918         }
1919         return log;
1920 }
1921
1922
1923 bool GIT::copyEnabled()
1924 {
1925         return false;
1926 }
1927
1928
1929 string GIT::copy(support::FileName const & /*newFile*/, string const & /*msg*/)
1930 {
1931         // git does not support copy with history preservation
1932         return string();
1933 }
1934
1935
1936 LyXVC::CommandResult GIT::checkIn(string const & msg, string & log)
1937 {
1938         vector<support::FileName> f(1, owner_->fileName());
1939         return checkIn(f, msg, log);
1940 }
1941
1942
1943 LyXVC::CommandResult
1944 GIT::checkIn(vector<support::FileName> const & f, string const & msg, string & log)
1945 {
1946         TempFile tempfile("lyxvcout");
1947         FileName tmpf = tempfile.name();
1948         if (tmpf.empty()){
1949                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1950                 log = N_("Error: Could not generate logfile.");
1951                 return LyXVC::ErrorBefore;
1952         }
1953
1954         ostringstream os;
1955         os << "git commit -m \"" << msg << '"';
1956         for (size_t i = 0; i < f.size(); ++i)
1957                 os << ' ' << quoteName(f[i].onlyFileName());
1958         os << " > " << quoteName(tmpf.toFilesystemEncoding());
1959         LyXVC::CommandResult ret =
1960                 doVCCommand(os.str(), FileName(owner_->filePath())) ?
1961                         LyXVC::ErrorCommand : LyXVC::VCSuccess;
1962
1963         string res = scanLogFile(tmpf, log);
1964         if (!res.empty()) {
1965                 frontend::Alert::error(_("Revision control error."),
1966                                 _("Error when committing to repository.\n"
1967                                 "You have to manually resolve the problem.\n"
1968                                 "LyX will reopen the document after you press OK."));
1969                 ret = LyXVC::ErrorCommand;
1970         }
1971
1972         if (!log.empty())
1973                 log.insert(0, "GIT: ");
1974         if (ret == LyXVC::VCSuccess && log.empty())
1975                 log = "GIT: Proceeded";
1976         return ret;
1977 }
1978
1979
1980 bool GIT::checkInEnabled()
1981 {
1982         return true;
1983 }
1984
1985
1986 bool GIT::isCheckInWithConfirmation()
1987 {
1988         // FIXME one day common getDiff and perhaps OpMode for all backends
1989
1990         TempFile tempfile("lyxvcout");
1991         FileName tmpf = tempfile.name();
1992         if (tmpf.empty()) {
1993                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1994                 return true;
1995         }
1996
1997         doVCCommandCall("git diff " + quoteName(owner_->absFileName())
1998                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1999                 FileName(owner_->filePath()));
2000
2001         docstring diff = tmpf.fileContents("UTF-8");
2002
2003         if (diff.empty())
2004                 return false;
2005
2006         return true;
2007 }
2008
2009
2010 // FIXME Correctly return code should be checked instead of this.
2011 // This would need another solution than just plain startscript.
2012 // Hint from Andre': QProcess::readAllStandardError()...
2013 string GIT::scanLogFile(FileName const & f, string & status)
2014 {
2015         ifstream ifs(f.toFilesystemEncoding().c_str());
2016         string line;
2017
2018         while (ifs) {
2019                 getline(ifs, line);
2020                 LYXERR(Debug::LYXVC, line << "\n");
2021                 if (!line.empty())
2022                         status += line + "; ";
2023                 if (prefixIs(line, "C ") || prefixIs(line, "CU ")
2024                                          || contains(line, "Commit failed")) {
2025                         ifs.close();
2026                         return line;
2027                 }
2028         }
2029         ifs.close();
2030         return string();
2031 }
2032
2033
2034 string GIT::checkOut()
2035 {
2036         return string();
2037 }
2038
2039
2040 bool GIT::checkOutEnabled()
2041 {
2042         return false;
2043 }
2044
2045
2046 string GIT::repoUpdate()
2047 {
2048         return string();
2049 }
2050
2051
2052 bool GIT::repoUpdateEnabled()
2053 {
2054         return false;
2055 }
2056
2057
2058 string GIT::lockingToggle()
2059 {
2060         return string();
2061 }
2062
2063
2064 bool GIT::lockingToggleEnabled()
2065 {
2066         return false;
2067 }
2068
2069
2070 bool GIT::revert()
2071 {
2072         // Reverts to the version in GIT repository and
2073         // gets the updated version from the repository.
2074         string const fil = quoteName(onlyFileName(owner_->absFileName()));
2075
2076         if (doVCCommand("git checkout -q " + fil,
2077                     FileName(owner_->filePath())))
2078                 return false;
2079         owner_->markClean();
2080         return true;
2081 }
2082
2083
2084 bool GIT::isRevertWithConfirmation()
2085 {
2086         //FIXME owner && diff
2087         return true;
2088 }
2089
2090
2091 void GIT::undoLast()
2092 {
2093         // merge the current with the previous version
2094         // in a reverse patch kind of way, so that the
2095         // result is to revert the last changes.
2096         lyxerr << "Sorry, not implemented." << endl;
2097 }
2098
2099
2100 bool GIT::undoLastEnabled()
2101 {
2102         return false;
2103 }
2104
2105
2106 string GIT::revisionInfo(LyXVC::RevisionInfo const info)
2107 {
2108         if (info == LyXVC::Tree) {
2109                 if (rev_tree_cache_.empty())
2110                         if (!getTreeRevisionInfo())
2111                                 rev_tree_cache_ = "?";
2112                 if (rev_tree_cache_ == "?")
2113                         return string();
2114
2115                 return rev_tree_cache_;
2116         }
2117
2118         // fill the rest of the attributes for a single file
2119         if (rev_file_cache_.empty())
2120                 if (!getFileRevisionInfo())
2121                         rev_file_cache_ = "?";
2122
2123         switch (info) {
2124                 case LyXVC::File:
2125                         if (rev_file_cache_ == "?")
2126                                 return string();
2127                         return rev_file_cache_;
2128                 case LyXVC::Author:
2129                         return rev_author_cache_;
2130                 case LyXVC::Date:
2131                         return rev_date_cache_;
2132                 case LyXVC::Time:
2133                         return rev_time_cache_;
2134                 default: ;
2135
2136         }
2137
2138         return string();
2139 }
2140
2141
2142 bool GIT::getFileRevisionInfo()
2143 {
2144         TempFile tempfile("lyxvcout");
2145         FileName tmpf = tempfile.name();
2146         if (tmpf.empty()) {
2147                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
2148                 return false;
2149         }
2150
2151         doVCCommand("git log -n 1 --pretty=format:%H%n%an%n%ai " + quoteName(onlyFileName(owner_->absFileName()))
2152                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
2153                     FileName(owner_->filePath()));
2154
2155         if (tmpf.empty())
2156                 return false;
2157
2158         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
2159
2160         if (ifs)
2161                 getline(ifs, rev_file_cache_);
2162         if (ifs)
2163                 getline(ifs, rev_author_cache_);
2164         if (ifs) {
2165                 string line;
2166                 getline(ifs, line);
2167                 rev_time_cache_ = split(line, rev_date_cache_, ' ');
2168         }
2169
2170         ifs.close();
2171         return !rev_file_cache_.empty();
2172 }
2173
2174
2175 bool GIT::getTreeRevisionInfo()
2176 {
2177         TempFile tempfile("lyxvcout");
2178         FileName tmpf = tempfile.name();
2179         if (tmpf.empty()) {
2180                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
2181                 return false;
2182         }
2183
2184         doVCCommand("git describe --abbrev --dirty --long > " + quoteName(tmpf.toFilesystemEncoding()),
2185                     FileName(owner_->filePath()));
2186
2187         if (tmpf.empty())
2188                 return false;
2189
2190         // only first line in case something bad happens.
2191         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
2192         getline(ifs, rev_tree_cache_);
2193         ifs.close();
2194
2195         return !rev_tree_cache_.empty();
2196 }
2197
2198
2199 void GIT::getLog(FileName const & tmpf)
2200 {
2201         doVCCommand("git log " + quoteName(onlyFileName(owner_->absFileName()))
2202                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
2203                     FileName(owner_->filePath()));
2204 }
2205
2206
2207 //at this moment we don't accept revision SHA, but just number of revision steps back
2208 //GUI and infrastucture needs to be changed first
2209 bool GIT::prepareFileRevision(string const & revis, string & f)
2210 {
2211         // anything positive means we got hash, not "0" or minus revision
2212         int rev = 1;
2213
2214         // hash is rarely number and should be long
2215         if (isStrInt(revis) && revis.length()<20)
2216                 rev = convert<int>(revis);
2217
2218         // revision and filename
2219         string pointer;
2220
2221         // go back for "minus" revisions
2222         if (rev <= 0)
2223                 pointer = "HEAD~" + convert<string>(-rev);
2224         // normal hash
2225         else
2226                 pointer = revis;
2227
2228         pointer += ':';
2229
2230         TempFile tempfile("lyxvcrev_" + revis + '_');
2231         tempfile.setAutoRemove(false);
2232         FileName tmpf = tempfile.name();
2233         if (tmpf.empty()) {
2234                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
2235                 return false;
2236         }
2237
2238         doVCCommand("git show " + pointer + "./"
2239                       + quoteName(onlyFileName(owner_->absFileName()))
2240                       + " > " + quoteName(tmpf.toFilesystemEncoding()),
2241                 FileName(owner_->filePath()));
2242         tmpf.refresh();
2243         if (tmpf.isFileEmpty())
2244                 return false;
2245
2246         f = tmpf.absFileName();
2247         return true;
2248 }
2249
2250
2251 bool GIT::prepareFileRevisionEnabled()
2252 {
2253         return true;
2254 }
2255
2256
2257 bool GIT::toggleReadOnlyEnabled()
2258 {
2259         return true;
2260 }
2261
2262
2263 } // namespace lyx