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