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