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