]> git.lyx.org Git - lyx.git/blob - src/VCBackend.cpp
revert r37459 and add a note to the sources:
[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/Path.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, 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 /////////////////////////////////////////////////////////////////////
103 //
104 // RCS
105 //
106 /////////////////////////////////////////////////////////////////////
107
108 RCS::RCS(FileName const & m)
109 {
110         master_ = m;
111         scanMaster();
112 }
113
114
115 FileName const RCS::findFile(FileName const & file)
116 {
117         // Check if *,v exists.
118         FileName tmp(file.absFileName() + ",v");
119         LYXERR(Debug::LYXVC, "LyXVC: Checking if file is under rcs: " << tmp);
120         if (tmp.isReadableFile()) {
121                 LYXERR(Debug::LYXVC, "Yes, " << file << " is under rcs.");
122                 return tmp;
123         }
124
125         // Check if RCS/*,v exists.
126         tmp = FileName(addName(addPath(onlyPath(file.absFileName()), "RCS"), file.absFileName()) + ",v");
127         LYXERR(Debug::LYXVC, "LyXVC: Checking if file is under rcs: " << tmp);
128         if (tmp.isReadableFile()) {
129                 LYXERR(Debug::LYXVC, "Yes, " << file << " is under rcs.");
130                 return tmp;
131         }
132
133         return FileName();
134 }
135
136
137 void RCS::retrieve(FileName const & file)
138 {
139         LYXERR(Debug::LYXVC, "LyXVC::RCS: retrieve.\n\t" << file);
140         doVCCommandCall("co -q -r " + quoteName(file.toFilesystemEncoding()),
141                          FileName());
142 }
143
144
145 void RCS::scanMaster()
146 {
147         if (master_.empty())
148                 return;
149
150         LYXERR(Debug::LYXVC, "LyXVC::RCS: scanMaster: " << master_);
151
152         ifstream ifs(master_.toFilesystemEncoding().c_str());
153
154         string token;
155         bool read_enough = false;
156
157         while (!read_enough && ifs >> token) {
158                 LYXERR(Debug::LYXVC, "LyXVC::scanMaster: current lex text: `"
159                         << token << '\'');
160
161                 if (token.empty())
162                         continue;
163                 else if (token == "head") {
164                         // get version here
165                         string tmv;
166                         ifs >> tmv;
167                         tmv = rtrim(tmv, ";");
168                         version_ = tmv;
169                         LYXERR(Debug::LYXVC, "LyXVC: version found to be " << tmv);
170                 } else if (contains(token, "access")
171                            || contains(token, "symbols")
172                            || contains(token, "strict")) {
173                         // nothing
174                 } else if (contains(token, "locks")) {
175                         // get locker here
176                         if (contains(token, ';')) {
177                                 locker_ = "Unlocked";
178                                 vcstatus = UNLOCKED;
179                                 continue;
180                         }
181                         string tmpt;
182                         string s1;
183                         string s2;
184                         do {
185                                 ifs >> tmpt;
186                                 s1 = rtrim(tmpt, ";");
187                                 // tmp is now in the format <user>:<version>
188                                 s1 = split(s1, s2, ':');
189                                 // s2 is user, and s1 is version
190                                 if (s1 == version_) {
191                                         locker_ = s2;
192                                         vcstatus = LOCKED;
193                                         break;
194                                 }
195                         } while (!contains(tmpt, ';'));
196
197                 } else if (token == "comment") {
198                         // we don't need to read any further than this.
199                         read_enough = true;
200                 } else {
201                         // unexpected
202                         LYXERR(Debug::LYXVC, "LyXVC::scanMaster(): unexpected token");
203                 }
204         }
205 }
206
207
208 void RCS::registrer(string const & msg)
209 {
210         string cmd = "ci -q -u -i -t-\"";
211         cmd += msg;
212         cmd += "\" ";
213         cmd += quoteName(onlyFileName(owner_->absFileName()));
214         doVCCommand(cmd, FileName(owner_->filePath()));
215 }
216
217
218 string RCS::checkIn(string const & msg)
219 {
220         int ret = doVCCommand("ci -q -u -m\"" + msg + "\" "
221                     + quoteName(onlyFileName(owner_->absFileName())),
222                     FileName(owner_->filePath()));
223         return ret ? string() : "RCS: Proceeded";
224 }
225
226
227 bool RCS::checkInEnabled()
228 {
229         return owner_ && !owner_->isReadonly();
230 }
231
232
233 bool RCS::isCheckInWithConfirmation()
234 {
235         // FIXME one day common getDiff for all backends
236         // docstring diff;
237         // if (getDiff(file, diff) && diff.empty())
238         //      return false;
239
240         FileName tmpf = FileName::tempName("lyxvcout");
241         if (tmpf.empty()) {
242                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
243                 return true;
244         }
245
246         doVCCommandCall("rcsdiff " + quoteName(owner_->absFileName())
247                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
248                 FileName(owner_->filePath()));
249
250         docstring diff = tmpf.fileContents("UTF-8");
251         tmpf.erase();
252
253         if (diff.empty())
254                 return false;
255
256         return true;
257 }
258
259
260 string RCS::checkOut()
261 {
262         owner_->markClean();
263         int ret = doVCCommand("co -q -l " + quoteName(onlyFileName(owner_->absFileName())),
264                     FileName(owner_->filePath()));
265         return ret ? string() : "RCS: Proceeded";
266 }
267
268
269 bool RCS::checkOutEnabled()
270 {
271         return owner_ && owner_->isReadonly();
272 }
273
274
275 string RCS::repoUpdate()
276 {
277         lyxerr << "Sorry, not implemented." << endl;
278         return string();
279 }
280
281
282 bool RCS::repoUpdateEnabled()
283 {
284         return false;
285 }
286
287
288 string RCS::lockingToggle()
289 {
290         //FIXME this might be actually possible, study rcs -U, rcs -L.
291         //State should be easy to get inside scanMaster.
292         //It would fix #4370 and make rcs/svn usage even more closer.
293         lyxerr << "Sorry, not implemented." << endl;
294         return string();
295 }
296
297
298 bool RCS::lockingToggleEnabled()
299 {
300         return false;
301 }
302
303
304 bool RCS::revert()
305 {
306         if (doVCCommand("co -f -u" + version_ + " "
307                     + quoteName(onlyFileName(owner_->absFileName())),
308                     FileName(owner_->filePath())))
309                 return false;
310         // We ignore changes and just reload!
311         owner_->markClean();
312         return true;
313 }
314
315
316 bool RCS::isRevertWithConfirmation()
317 {
318         //FIXME owner && diff ?
319         return true;
320 }
321
322
323 void RCS::undoLast()
324 {
325         LYXERR(Debug::LYXVC, "LyXVC: undoLast");
326         doVCCommand("rcs -o" + version_ + " "
327                     + quoteName(onlyFileName(owner_->absFileName())),
328                     FileName(owner_->filePath()));
329 }
330
331
332 bool RCS::undoLastEnabled()
333 {
334         return true;
335 }
336
337
338 void RCS::getLog(FileName const & tmpf)
339 {
340         doVCCommand("rlog " + quoteName(onlyFileName(owner_->absFileName()))
341                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
342                     FileName(owner_->filePath()));
343 }
344
345
346 bool RCS::toggleReadOnlyEnabled()
347 {
348         // This got broken somewhere along lfuns dispatch reorganization.
349         // reloadBuffer would be needed after this, but thats problematic
350         // since we are inside Buffer::dispatch.
351         // return true;
352         return false;
353 }
354
355 string RCS::revisionInfo(LyXVC::RevisionInfo const info)
356 {
357         if (info == LyXVC::File)
358                 return version_;
359         return string();
360 }
361
362
363 bool RCS::prepareFileRevision(string const &revis, string & f)
364 {
365         string rev = revis;
366         if (!VCS::makeRCSRevision(version_, rev))
367                 return false;
368
369         FileName tmpf = FileName::tempName("lyxvcrev_" + rev + "_");
370         if (tmpf.empty()) {
371                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
372                 return N_("Error: Could not generate logfile.");
373         }
374
375         doVCCommand("co -p" + rev + " "
376                       + quoteName(onlyFileName(owner_->absFileName()))
377                       + " > " + quoteName(tmpf.toFilesystemEncoding()),
378                 FileName(owner_->filePath()));
379         if (tmpf.isFileEmpty())
380                 return false;
381
382         f = tmpf.absFileName();
383         return true;
384 }
385
386
387 bool RCS::prepareFileRevisionEnabled()
388 {
389         return true;
390 }
391
392
393 /////////////////////////////////////////////////////////////////////
394 //
395 // CVS
396 //
397 /////////////////////////////////////////////////////////////////////
398
399 CVS::CVS(FileName const & m, FileName const & f)
400 {
401         master_ = m;
402         file_ = f;
403         have_rev_info_ = false;
404         scanMaster();
405 }
406
407
408 FileName const CVS::findFile(FileName const & file)
409 {
410         // First we look for the CVS/Entries in the same dir
411         // where we have file.
412         FileName const entries(onlyPath(file.absFileName()) + "/CVS/Entries");
413         string const tmpf = '/' + onlyFileName(file.absFileName()) + '/';
414         LYXERR(Debug::LYXVC, "LyXVC: Checking if file is under cvs in `" << entries
415                              << "' for `" << tmpf << '\'');
416         if (entries.isReadableFile()) {
417                 // Ok we are at least in a CVS dir. Parse the CVS/Entries
418                 // and see if we can find this file. We do a fast and
419                 // dirty parse here.
420                 ifstream ifs(entries.toFilesystemEncoding().c_str());
421                 string line;
422                 while (getline(ifs, line)) {
423                         LYXERR(Debug::LYXVC, "\tEntries: " << line);
424                         if (contains(line, tmpf))
425                                 return entries;
426                 }
427         }
428         return FileName();
429 }
430
431
432 void CVS::scanMaster()
433 {
434         LYXERR(Debug::LYXVC, "LyXVC::CVS: scanMaster. \n     Checking: " << master_);
435         // Ok now we do the real scan...
436         ifstream ifs(master_.toFilesystemEncoding().c_str());
437         string name = onlyFileName(file_.absFileName());
438         string tmpf = '/' + name + '/';
439         LYXERR(Debug::LYXVC, "\tlooking for `" << tmpf << '\'');
440         string line;
441         static regex const reg("/(.*)/(.*)/(.*)/(.*)/(.*)");
442         while (getline(ifs, line)) {
443                 LYXERR(Debug::LYXVC, "\t  line: " << line);
444                 if (contains(line, tmpf)) {
445                         // Ok extract the fields.
446                         smatch sm;
447
448                         regex_match(line, sm, reg);
449
450                         //sm[0]; // whole matched string
451                         //sm[1]; // filename
452                         version_ = sm.str(2);
453                         string const file_date = sm.str(3);
454
455                         //sm[4]; // options
456                         //sm[5]; // tag or tagdate
457                         if (file_.isReadableFile()) {
458                                 time_t mod = file_.lastModified();
459                                 string mod_date = rtrim(asctime(gmtime(&mod)), "\n");
460                                 LYXERR(Debug::LYXVC, "Date in Entries: `" << file_date
461                                         << "'\nModification date of file: `" << mod_date << '\'');
462                                 if (file_.isReadOnly()) {
463                                         // readonly checkout is unlocked
464                                         vcstatus = UNLOCKED;
465                                 } else {
466                                         FileName bdir(addPath(master_.onlyPath().absFileName(),"Base"));
467                                         FileName base(addName(bdir.absFileName(),name));
468                                         // if base version is existent "cvs edit" was used to lock
469                                         vcstatus = base.isReadableFile() ? LOCKED : NOLOCKING;
470                                 }
471                         } else {
472                                 vcstatus = NOLOCKING;
473                         }
474                         break;
475                 }
476         }
477 }
478
479
480 string const CVS::getTarget(OperationMode opmode) const
481 {
482         switch(opmode) {
483         case Directory:
484                 // in client server mode CVS does not like full path operand for directory operation
485                 // since LyX switches to the repo dir "." is good enough as target
486                 return ".";
487         case File:
488                 return quoteName(onlyFileName(owner_->absFileName()));
489         }
490         return string();
491 }
492
493
494 docstring CVS::toString(CvsStatus status) const
495 {
496         switch (status) {
497         case UpToDate:
498                 return _("Up-to-date");
499         case LocallyModified:
500                 return _("Locally Modified");
501         case LocallyAdded:
502                 return _("Locally Added");
503         case NeedsMerge:
504                 return _("Needs Merge");
505         case NeedsCheckout:
506                 return _("Needs Checkout");
507         case NoCvsFile:
508                 return _("No CVS file");
509         case StatusError:
510                 return _("Cannot retrieve CVS status");
511         }
512         return 0;
513 }
514
515
516 int CVS::doVCCommandWithOutput(string const & cmd, FileName const & path,
517         FileName const & output, bool reportError)
518 {
519         string redirection = output.empty() ? "" : " > " + quoteName(output.toFilesystemEncoding());
520         return doVCCommand(cmd + redirection, path, reportError);
521 }
522
523
524 int CVS::doVCCommandCallWithOutput(std::string const & cmd,
525         support::FileName const & path,
526         support::FileName const & output)
527 {
528         string redirection = output.empty() ? "" : " > " + quoteName(output.toFilesystemEncoding());
529         return doVCCommandCall(cmd + redirection, path);
530 }
531
532
533 CVS::CvsStatus CVS::getStatus()
534 {
535         FileName tmpf = FileName::tempName("lyxvcout");
536         if (tmpf.empty()) {
537                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
538                 return StatusError;
539         }
540
541         if (doVCCommandCallWithOutput("cvs status " + getTarget(File),
542                 FileName(owner_->filePath()), tmpf)) {
543                 tmpf.removeFile();
544                 return StatusError;
545         }
546
547         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
548         CvsStatus status = NoCvsFile;
549
550         while (ifs) {
551                 string line;
552                 getline(ifs, line);
553                 LYXERR(Debug::LYXVC, line << "\n");
554                 if (prefixIs(line, "File:")) {
555                         if (contains(line, "Up-to-date"))
556                                 status = UpToDate;
557                         else if (contains(line, "Locally Modified"))
558                                 status = LocallyModified;
559                         else if (contains(line, "Locally Added"))
560                                 status = LocallyAdded;
561                         else if (contains(line, "Needs Merge"))
562                                 status = NeedsMerge;
563                         else if (contains(line, "Needs Checkout"))
564                                 status = NeedsCheckout;
565                 }
566         }
567         tmpf.removeFile();
568         return status;
569 }
570
571 void CVS::getRevisionInfo()
572 {
573         if (have_rev_info_)
574                 return;
575         have_rev_info_ = true;
576         FileName tmpf = FileName::tempName("lyxvcout");
577         if (tmpf.empty()) {
578                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
579                 return;
580         }
581         
582         int rc = doVCCommandCallWithOutput("cvs log -r" + version_ 
583                 + " " + getTarget(File),
584                 FileName(owner_->filePath()), tmpf);
585         if (rc) {
586                 tmpf.removeFile();
587                 LYXERR(Debug::LYXVC, "cvs log failed with exit code " << rc);
588                 return;
589         }
590         
591         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
592         static regex const reg("date: (.*) (.*) (.*);  author: (.*);  state: (.*);(.*)");
593
594         while (ifs) {
595                 string line;
596                 getline(ifs, line);
597                 LYXERR(Debug::LYXVC, line << "\n");
598                 if (prefixIs(line, "date:")) {
599                         smatch sm;
600                         regex_match(line, sm, reg);
601                         //sm[0]; // whole matched string
602                         rev_date_cache_ = sm[1];
603                         rev_time_cache_ = sm[2];
604                         //sm[3]; // GMT offset
605                         rev_author_cache_ = sm[4];
606                         break;
607                 }
608         }
609         tmpf.removeFile();
610         if (rev_author_cache_.empty())
611                 LYXERR(Debug::LYXVC,
612                    "Could not retrieve revision info for " << version_ <<
613                    " of " << getTarget(File));
614 }
615
616
617 void CVS::registrer(string const & msg)
618 {
619         doVCCommand("cvs -q add -m \"" + msg + "\" "
620                 + getTarget(File),
621                 FileName(owner_->filePath()));
622 }
623
624
625 void CVS::getDiff(OperationMode opmode, FileName const & tmpf)
626 {
627         doVCCommandWithOutput("cvs diff " + getTarget(opmode),
628                 FileName(owner_->filePath()), tmpf, false);
629 }
630
631
632 int CVS::edit()
633 {
634         vcstatus = LOCKED;
635         return doVCCommand("cvs -q edit " + getTarget(File),
636                 FileName(owner_->filePath()));
637 }
638
639
640 int CVS::unedit()
641 {
642         vcstatus = UNLOCKED;
643         return doVCCommand("cvs -q unedit " + getTarget(File),
644                 FileName(owner_->filePath()));
645 }
646
647
648 int CVS::update(OperationMode opmode, FileName const & tmpf)
649 {
650         return doVCCommandWithOutput("cvs -q update "
651                 + getTarget(opmode),
652                 FileName(owner_->filePath()), tmpf, false);
653 }
654
655
656 string CVS::scanLogFile(FileName const & f, string & status)
657 {
658         ifstream ifs(f.toFilesystemEncoding().c_str());
659
660         while (ifs) {
661                 string line;
662                 getline(ifs, line);
663                 LYXERR(Debug::LYXVC, line << "\n");
664                 if (!line.empty())
665                         status += line + "; ";
666                 if (prefixIs(line, "C ")) {
667                         ifs.close();
668                         return line;
669                 }
670         }
671         ifs.close();
672         return string();
673 }
674         
675         
676 string CVS::checkIn(string const & msg)
677 {
678         CvsStatus status = getStatus();
679         switch (status) {
680         case UpToDate:
681                 if (vcstatus != NOLOCKING)
682                         unedit();
683                 return "CVS: Proceeded";
684         case LocallyModified:
685         case LocallyAdded: {
686                 int rc = doVCCommand("cvs -q commit -m \"" + msg + "\" "
687                         + getTarget(File),
688                     FileName(owner_->filePath()));
689                 return rc ? string() : "CVS: Proceeded";
690         }
691         case NeedsMerge:
692         case NeedsCheckout:
693                 frontend::Alert::error(_("Revision control error."),
694                         _("The repository version is newer then the current check out.\n"
695                           "You have to update from repository first or revert your changes.")) ;
696                 break;
697         default:
698                 frontend::Alert::error(_("Revision control error."),
699                         bformat(_("Bad status when checking in changes.\n"
700                                           "\n'%1$s'\n\n"),
701                                 toString(status)));
702                 break;
703         }
704         return string();
705 }
706
707
708 bool CVS::isLocked() const
709 {
710         FileName fn(owner_->absFileName());
711         fn.refresh();
712         return !fn.isReadOnly();
713 }
714
715
716 bool CVS::checkInEnabled()
717 {
718         if (vcstatus != NOLOCKING)
719                 return isLocked();
720         else
721                 return true;
722 }
723
724
725 bool CVS::isCheckInWithConfirmation()
726 {
727         CvsStatus status = getStatus();
728         return status == LocallyModified || status == LocallyAdded;
729 }
730
731
732 string CVS::checkOut()
733 {
734         if (vcstatus != NOLOCKING && edit())
735                 return string();
736         FileName tmpf = FileName::tempName("lyxvcout");
737         if (tmpf.empty()) {
738                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
739                 return string();
740         }
741         
742         int rc = update(File, tmpf);
743         string log;
744         string const res = scanLogFile(tmpf, log);
745         if (!res.empty()) {
746                 frontend::Alert::error(_("Revision control error."),
747                         bformat(_("Error when updating from repository.\n"
748                                 "You have to manually resolve the conflicts NOW!\n'%1$s'.\n\n"
749                                 "After pressing OK, LyX will try to reopen the resolved document."),
750                                 from_local8bit(res)));
751                 rc = 0;
752         }
753         
754         tmpf.erase();
755         return rc ? string() : log.empty() ? "CVS: Proceeded" : "CVS: " + log;
756 }
757
758
759 bool CVS::checkOutEnabled()
760 {
761         if (vcstatus != NOLOCKING)
762                 return !isLocked();
763         else
764                 return true;
765 }
766
767
768 string CVS::repoUpdate()
769 {
770         FileName tmpf = FileName::tempName("lyxvcout");
771         if (tmpf.empty()) {
772                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
773                 return string();
774         }
775         
776         getDiff(Directory, tmpf);
777         docstring res = tmpf.fileContents("UTF-8");
778         if (!res.empty()) {
779                 LYXERR(Debug::LYXVC, "Diff detected:\n" << res);
780                 docstring const file = from_utf8(owner_->filePath());
781                 docstring text = bformat(_("There were detected changes "
782                                 "in the working directory:\n%1$s\n\n"
783                                 "Possible file conflicts must be then resolved manually "
784                                 "or you will need to revert back to the repository version."), file);
785                 int ret = frontend::Alert::prompt(_("Changes detected"),
786                                 text, 0, 1, _("&Continue"), _("&Abort"), _("View &Log ..."));
787                 if (ret == 2 ) {
788                         dispatch(FuncRequest(LFUN_DIALOG_SHOW, "file " + tmpf.absFileName()));
789                         ret = frontend::Alert::prompt(_("Changes detected"),
790                                 text, 0, 1, _("&Continue"), _("&Abort"));
791                         hideDialogs("file", 0);
792                 }
793                 if (ret == 1 ) {
794                         tmpf.removeFile();
795                         return string();
796                 }
797         }
798
799         int rc = update(Directory, tmpf);
800         res += "Update log:\n" + tmpf.fileContents("UTF-8");
801         LYXERR(Debug::LYXVC, res);
802
803         string log;
804         string sres = scanLogFile(tmpf, log);
805         if (!sres.empty()) {
806                 docstring const file = owner_->fileName().displayName(20);
807                 frontend::Alert::error(_("Revision control error."),
808                         bformat(_("Error when updating document %1$s from repository.\n"
809                                           "You have to manually resolve the conflicts NOW!\n'%2$s'.\n\n"
810                                           "After pressing OK, LyX will try to reopen the resolved document."),
811                                 file, from_local8bit(sres)));
812                 rc = 0;
813         }
814         
815         tmpf.removeFile();
816
817         return rc ? string() : log.empty() ? "CVS: Proceeded" : "CVS: " + log;
818 }
819
820
821 bool CVS::repoUpdateEnabled()
822 {
823         return true;
824 }
825
826
827 string CVS::lockingToggle()
828 {
829         lyxerr << "Sorry, not implemented." << endl;
830         return string();
831 }
832
833
834 bool CVS::lockingToggleEnabled()
835 {
836         return false;
837 }
838
839
840 bool CVS::isRevertWithConfirmation()
841 {
842         CvsStatus status = getStatus();
843         return !owner_->isClean() || status == LocallyModified || status == NeedsMerge;
844 }
845
846
847 bool CVS::revert()
848 {
849         // Reverts to the version in CVS repository and
850         // gets the updated version from the repository.
851         CvsStatus status = getStatus();
852         switch (status) {
853         case UpToDate:
854                 if (vcstatus != NOLOCKING)
855                         return 0 == unedit();
856                 break;
857         case NeedsMerge:
858         case NeedsCheckout:
859         case LocallyModified: {
860                 FileName f(owner_->absFileName());
861                 f.removeFile();
862                 update(File, FileName());
863                 owner_->markClean();
864                 break;
865         }
866         case LocallyAdded: {
867                 docstring const file = owner_->fileName().displayName(20);
868                 frontend::Alert::error(_("Revision control error."),
869                         bformat(_("The document %1$s is not in repository.\n"
870                                   "You have to check in the first revision before you can revert."),
871                                 file)) ;
872                 return false;
873         }
874         default: {
875                 docstring const file = owner_->fileName().displayName(20);
876                 frontend::Alert::error(_("Revision control error."),
877                         bformat(_("Cannot revert document %1$s to repository version.\n"
878                                   "The status '%2$s' is unexpected."),
879                                 file, toString(status)));
880                 return false;
881                 }
882         }
883         return true;
884 }
885
886
887 void CVS::undoLast()
888 {
889         // merge the current with the previous version
890         // in a reverse patch kind of way, so that the
891         // result is to revert the last changes.
892         lyxerr << "Sorry, not implemented." << endl;
893 }
894
895
896 bool CVS::undoLastEnabled()
897 {
898         return false;
899 }
900
901
902 void CVS::getLog(FileName const & tmpf)
903 {
904         doVCCommandWithOutput("cvs log " + getTarget(File),
905                 FileName(owner_->filePath()),
906                 tmpf);
907 }
908
909
910 bool CVS::toggleReadOnlyEnabled()
911 {
912         return false;
913 }
914
915
916 string CVS::revisionInfo(LyXVC::RevisionInfo const info)
917 {
918         if (!version_.empty()) {
919                 getRevisionInfo();
920                 switch (info) {
921                 case LyXVC::File:
922                         return version_;
923                 case LyXVC::Author:
924                         return rev_author_cache_;
925                 case LyXVC::Date:
926                         return rev_date_cache_;
927                 case LyXVC::Time:
928                         return rev_time_cache_;
929                 default: ;
930                 }
931         }
932         return string();
933 }
934
935
936 bool CVS::prepareFileRevision(string const & revis, string & f)
937 {
938         string rev = revis;
939         if (!VCS::makeRCSRevision(version_, rev))
940                 return false;
941
942         FileName tmpf = FileName::tempName("lyxvcrev_" + rev + "_");
943         if (tmpf.empty()) {
944                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
945                 return false;
946         }
947
948         doVCCommandWithOutput("cvs update -p -r" + rev + " "
949                 + getTarget(File),
950                 FileName(owner_->filePath()), tmpf);
951         if (tmpf.isFileEmpty())
952                 return false;
953
954         f = tmpf.absFileName();
955         return true;
956 }
957
958
959 bool CVS::prepareFileRevisionEnabled()
960 {
961         return true;
962 }
963
964
965 /////////////////////////////////////////////////////////////////////
966 //
967 // SVN
968 //
969 /////////////////////////////////////////////////////////////////////
970
971 SVN::SVN(FileName const & m, FileName const & f)
972 {
973         owner_ = 0;
974         master_ = m;
975         file_ = f;
976         locked_mode_ = 0;
977         scanMaster();
978 }
979
980
981 FileName const SVN::findFile(FileName const & file)
982 {
983         // First we look for the .svn/entries in the same dir
984         // where we have file.
985         FileName const entries(onlyPath(file.absFileName()) + "/.svn/entries");
986         string const tmpf = onlyFileName(file.absFileName());
987         LYXERR(Debug::LYXVC, "LyXVC: Checking if file is under svn in `" << entries
988                              << "' for `" << tmpf << '\'');
989         if (entries.isReadableFile()) {
990                 // Ok we are at least in a SVN dir. Parse the .svn/entries
991                 // and see if we can find this file. We do a fast and
992                 // dirty parse here.
993                 ifstream ifs(entries.toFilesystemEncoding().c_str());
994                 string line, oldline;
995                 while (getline(ifs, line)) {
996                         if (line == "dir" || line == "file")
997                                 LYXERR(Debug::LYXVC, "\tEntries: " << oldline);
998                         if (oldline == tmpf && line == "file")
999                                 return entries;
1000                         oldline = line;
1001                 }
1002         }
1003         return FileName();
1004 }
1005
1006
1007 void SVN::scanMaster()
1008 {
1009         // vcstatus code is somewhat superflous, until we want
1010         // to implement read-only toggle for svn.
1011         vcstatus = NOLOCKING;
1012         if (checkLockMode()) {
1013                 if (isLocked()) {
1014                         vcstatus = LOCKED;
1015                 } else {
1016                         vcstatus = UNLOCKED;
1017                 }
1018         }
1019 }
1020
1021
1022 bool SVN::checkLockMode()
1023 {
1024         FileName tmpf = FileName::tempName("lyxvcout");
1025         if (tmpf.empty()){
1026                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1027                 return N_("Error: Could not generate logfile.");
1028         }
1029
1030         LYXERR(Debug::LYXVC, "Detecting locking mode...");
1031         if (doVCCommandCall("svn proplist " + quoteName(file_.onlyFileName())
1032                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1033                     file_.onlyPath()))
1034                 return false;
1035
1036         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
1037         string line;
1038         bool ret = false;
1039
1040         while (ifs) {
1041                 getline(ifs, line);
1042                 LYXERR(Debug::LYXVC, line);
1043                 if (contains(line, "svn:needs-lock"))
1044                         ret = true;
1045         }
1046         LYXERR(Debug::LYXVC, "Locking enabled: " << ret);
1047         ifs.close();
1048         locked_mode_ = ret;
1049         return ret;
1050
1051 }
1052
1053
1054 bool SVN::isLocked() const
1055 {
1056         file_.refresh();
1057         return !file_.isReadOnly();
1058 }
1059
1060
1061 void SVN::registrer(string const & /*msg*/)
1062 {
1063         doVCCommand("svn add -q " + quoteName(onlyFileName(owner_->absFileName())),
1064                     FileName(owner_->filePath()));
1065 }
1066
1067
1068 string SVN::checkIn(string const & msg)
1069 {
1070         FileName tmpf = FileName::tempName("lyxvcout");
1071         if (tmpf.empty()){
1072                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1073                 return N_("Error: Could not generate logfile.");
1074         }
1075
1076         doVCCommand("svn commit -m \"" + msg + "\" "
1077                     + quoteName(onlyFileName(owner_->absFileName()))
1078                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1079                     FileName(owner_->filePath()));
1080
1081         string log;
1082         string res = scanLogFile(tmpf, log);
1083         if (!res.empty())
1084                 frontend::Alert::error(_("Revision control error."),
1085                                 _("Error when committing to repository.\n"
1086                                 "You have to manually resolve the problem.\n"
1087                                 "LyX will reopen the document after you press OK."));
1088         else
1089                 fileLock(false, tmpf, log);
1090
1091         tmpf.erase();
1092         return log.empty() ? string() : "SVN: " + log;
1093 }
1094
1095
1096 bool SVN::checkInEnabled()
1097 {
1098         if (locked_mode_)
1099                 return isLocked();
1100         else
1101                 return true;
1102 }
1103
1104
1105 bool SVN::isCheckInWithConfirmation()
1106 {
1107         // FIXME one day common getDiff and perhaps OpMode for all backends
1108
1109         FileName tmpf = FileName::tempName("lyxvcout");
1110         if (tmpf.empty()) {
1111                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1112                 return true;
1113         }
1114
1115         doVCCommandCall("svn diff " + quoteName(owner_->absFileName())
1116                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1117                 FileName(owner_->filePath()));
1118
1119         docstring diff = tmpf.fileContents("UTF-8");
1120         tmpf.erase();
1121
1122         if (diff.empty())
1123                 return false;
1124
1125         return true;
1126 }
1127
1128
1129 // FIXME Correctly return code should be checked instead of this.
1130 // This would need another solution than just plain startscript.
1131 // Hint from Andre': QProcess::readAllStandardError()...
1132 string SVN::scanLogFile(FileName const & f, string & status)
1133 {
1134         ifstream ifs(f.toFilesystemEncoding().c_str());
1135         string line;
1136
1137         while (ifs) {
1138                 getline(ifs, line);
1139                 LYXERR(Debug::LYXVC, line << "\n");
1140                 if (!line.empty()) 
1141                         status += line + "; ";
1142                 if (prefixIs(line, "C ") || prefixIs(line, "CU ")
1143                                          || contains(line, "Commit failed")) {
1144                         ifs.close();
1145                         return line;
1146                 }
1147                 if (contains(line, "svn:needs-lock")) {
1148                         ifs.close();
1149                         return line;
1150                 }
1151         }
1152         ifs.close();
1153         return string();
1154 }
1155
1156
1157 void SVN::fileLock(bool lock, FileName const & tmpf, string &status)
1158 {
1159         if (!locked_mode_ || (isLocked() == lock))
1160                 return;
1161
1162         string const arg = lock ? "lock " : "unlock ";
1163         doVCCommand("svn "+ arg + quoteName(onlyFileName(owner_->absFileName()))
1164                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1165                     FileName(owner_->filePath()));
1166
1167         // Lock error messages go unfortunately on stderr and are unreachible this way.
1168         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
1169         string line;
1170         while (ifs) {
1171                 getline(ifs, line);
1172                 if (!line.empty()) status += line + "; ";
1173         }
1174         ifs.close();
1175
1176         if (!isLocked() && lock)
1177                 frontend::Alert::error(_("Revision control error."),
1178                         _("Error while acquiring write lock.\n"
1179                         "Another user is most probably editing\n"
1180                         "the current document now!\n"
1181                         "Also check the access to the repository."));
1182         if (isLocked() && !lock)
1183                 frontend::Alert::error(_("Revision control error."),
1184                         _("Error while releasing write lock.\n"
1185                         "Check the access to the repository."));
1186 }
1187
1188
1189 string SVN::checkOut()
1190 {
1191         FileName tmpf = FileName::tempName("lyxvcout");
1192         if (tmpf.empty()) {
1193                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1194                 return N_("Error: Could not generate logfile.");
1195         }
1196
1197         doVCCommand("svn update --non-interactive " + quoteName(onlyFileName(owner_->absFileName()))
1198                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1199                     FileName(owner_->filePath()));
1200
1201         string log;
1202         string const res = scanLogFile(tmpf, log);
1203         if (!res.empty())
1204                 frontend::Alert::error(_("Revision control error."),
1205                         bformat(_("Error when updating from repository.\n"
1206                                 "You have to manually resolve the conflicts NOW!\n'%1$s'.\n\n"
1207                                 "After pressing OK, LyX will try to reopen the resolved document."),
1208                         from_local8bit(res)));
1209
1210         fileLock(true, tmpf, log);
1211
1212         tmpf.erase();
1213         return log.empty() ? string() : "SVN: " + log;
1214 }
1215
1216
1217 bool SVN::checkOutEnabled()
1218 {
1219         if (locked_mode_)
1220                 return !isLocked();
1221         else
1222                 return true;
1223 }
1224
1225
1226 string SVN::repoUpdate()
1227 {
1228         FileName tmpf = FileName::tempName("lyxvcout");
1229         if (tmpf.empty()) {
1230                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1231                 return N_("Error: Could not generate logfile.");
1232         }
1233
1234         doVCCommand("svn diff " + quoteName(owner_->filePath())
1235                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1236                 FileName(owner_->filePath()));
1237         docstring res = tmpf.fileContents("UTF-8");
1238         if (!res.empty()) {
1239                 LYXERR(Debug::LYXVC, "Diff detected:\n" << res);
1240                 docstring const file = from_utf8(owner_->filePath());
1241                 docstring text = bformat(_("There were detected changes "
1242                                 "in the working directory:\n%1$s\n\n"
1243                                 "In case of file conflict version of the local directory files "
1244                                 "will be preferred."
1245                                 "\n\nContinue?"), file);
1246                 int ret = frontend::Alert::prompt(_("Changes detected"),
1247                                 text, 0, 1, _("&Yes"), _("&No"), _("View &Log ..."));
1248                 if (ret == 2 ) {
1249                         dispatch(FuncRequest(LFUN_DIALOG_SHOW, "file " + tmpf.absFileName()));
1250                         ret = frontend::Alert::prompt(_("Changes detected"),
1251                                 text, 0, 1, _("&Yes"), _("&No"));
1252                         hideDialogs("file", 0);
1253                 }
1254                 if (ret == 1 ) {
1255                         tmpf.erase();
1256                         return string();
1257                 }
1258         }
1259
1260         // Reverting looks too harsh, see bug #6255.
1261         // doVCCommand("svn revert -R " + quoteName(owner_->filePath())
1262         // + " > " + quoteName(tmpf.toFilesystemEncoding()),
1263         // FileName(owner_->filePath()));
1264         // res = "Revert log:\n" + tmpf.fileContents("UTF-8");
1265         doVCCommand("svn update --accept mine-full " + quoteName(owner_->filePath())
1266                 + " > " + quoteName(tmpf.toFilesystemEncoding()),
1267                 FileName(owner_->filePath()));
1268         res += "Update log:\n" + tmpf.fileContents("UTF-8");
1269
1270         LYXERR(Debug::LYXVC, res);
1271         tmpf.erase();
1272         return to_utf8(res);
1273 }
1274
1275
1276 bool SVN::repoUpdateEnabled()
1277 {
1278         return true;
1279 }
1280
1281
1282 string SVN::lockingToggle()
1283 {
1284         FileName tmpf = FileName::tempName("lyxvcout");
1285         if (tmpf.empty()) {
1286                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1287                 return N_("Error: Could not generate logfile.");
1288         }
1289
1290         int ret = doVCCommand("svn proplist " + quoteName(onlyFileName(owner_->absFileName()))
1291                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1292                     FileName(owner_->filePath()));
1293         if (ret)
1294                 return string();
1295
1296         string log;
1297         string res = scanLogFile(tmpf, log);
1298         bool locking = contains(res, "svn:needs-lock");
1299         if (!locking)
1300                 ret = doVCCommand("svn propset svn:needs-lock ON "
1301                     + quoteName(onlyFileName(owner_->absFileName()))
1302                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1303                     FileName(owner_->filePath()));
1304         else
1305                 ret = doVCCommand("svn propdel svn:needs-lock "
1306                     + quoteName(onlyFileName(owner_->absFileName()))
1307                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1308                     FileName(owner_->filePath()));
1309         if (ret)
1310                 return string();
1311
1312         tmpf.erase();
1313         frontend::Alert::warning(_("VCN File Locking"),
1314                 (locking ? _("Locking property unset.") : _("Locking property set.")) + "\n"
1315                 + _("Do not forget to commit the locking property into the repository."),
1316                 true);
1317
1318         return string("SVN: ") +  N_("Locking property set.");
1319 }
1320
1321
1322 bool SVN::lockingToggleEnabled()
1323 {
1324         return true;
1325 }
1326
1327
1328 bool SVN::revert()
1329 {
1330         // Reverts to the version in SVN repository and
1331         // gets the updated version from the repository.
1332         string const fil = quoteName(onlyFileName(owner_->absFileName()));
1333
1334         if (doVCCommand("svn revert -q " + fil,
1335                     FileName(owner_->filePath())))
1336                 return false;
1337         owner_->markClean();
1338         return true;
1339 }
1340
1341
1342 bool SVN::isRevertWithConfirmation()
1343 {
1344         //FIXME owner && diff
1345         return true;
1346 }
1347
1348
1349 void SVN::undoLast()
1350 {
1351         // merge the current with the previous version
1352         // in a reverse patch kind of way, so that the
1353         // result is to revert the last changes.
1354         lyxerr << "Sorry, not implemented." << endl;
1355 }
1356
1357
1358 bool SVN::undoLastEnabled()
1359 {
1360         return false;
1361 }
1362
1363
1364 string SVN::revisionInfo(LyXVC::RevisionInfo const info)
1365 {
1366         if (info == LyXVC::Tree) {
1367                         if (rev_tree_cache_.empty())
1368                                 if (!getTreeRevisionInfo())
1369                                         rev_tree_cache_ = "?";
1370                         if (rev_tree_cache_ == "?")
1371                                 return string();
1372
1373                         return rev_tree_cache_;
1374         }
1375
1376         // fill the rest of the attributes for a single file
1377         if (rev_file_cache_.empty())
1378                 if (!getFileRevisionInfo())
1379                         rev_file_cache_ = "?";
1380
1381         switch (info) {
1382                 case LyXVC::File:
1383                         if (rev_file_cache_ == "?")
1384                                 return string();
1385                         return rev_file_cache_;
1386                 case LyXVC::Author:
1387                         return rev_author_cache_;
1388                 case LyXVC::Date:
1389                         return rev_date_cache_;
1390                 case LyXVC::Time:
1391                         return rev_time_cache_;
1392                 default: ;
1393
1394         }
1395
1396         return string();
1397 }
1398
1399
1400 bool SVN::getFileRevisionInfo()
1401 {
1402         FileName tmpf = FileName::tempName("lyxvcout");
1403         if (tmpf.empty()) {
1404                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1405                 return N_("Error: Could not generate logfile.");
1406         }
1407
1408         doVCCommand("svn info --xml " + quoteName(onlyFileName(owner_->absFileName()))
1409                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1410                     FileName(owner_->filePath()));
1411
1412         if (tmpf.empty())
1413                 return false;
1414
1415         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
1416         string line;
1417         // commit log part
1418         bool c = false;
1419         string rev;
1420
1421         while (ifs) {
1422                 getline(ifs, line);
1423                 LYXERR(Debug::LYXVC, line);
1424                 if (prefixIs(line, "<commit"))
1425                         c = true;
1426                 if (c && prefixIs(line, "   revision=\"") && suffixIs(line, "\">")) {
1427                         string l1 = subst(line, "revision=\"", "");
1428                         string l2 = trim(subst(l1, "\">", ""));
1429                         if (isStrInt(l2))
1430                                 rev_file_cache_ = rev = l2;
1431                 }
1432                 if (c && prefixIs(line, "<author>") && suffixIs(line, "</author>")) {
1433                         string l1 = subst(line, "<author>", "");
1434                         string l2 = subst(l1, "</author>", "");
1435                         rev_author_cache_ = l2;
1436                 }
1437                 if (c && prefixIs(line, "<date>") && suffixIs(line, "</date>")) {
1438                         string l1 = subst(line, "<date>", "");
1439                         string l2 = subst(l1, "</date>", "");
1440                         l2 = split(l2, l1, 'T');
1441                         rev_date_cache_ = l1;
1442                         l2 = split(l2, l1, '.');
1443                         rev_time_cache_ = l1;
1444                 }
1445         }
1446
1447         ifs.close();
1448         tmpf.erase();
1449         return !rev.empty();
1450 }
1451
1452
1453 bool SVN::getTreeRevisionInfo()
1454 {
1455         FileName tmpf = FileName::tempName("lyxvcout");
1456         if (tmpf.empty()) {
1457                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1458                 return N_("Error: Could not generate logfile.");
1459         }
1460
1461         doVCCommand("svnversion -n . > " + quoteName(tmpf.toFilesystemEncoding()),
1462                     FileName(owner_->filePath()));
1463
1464         if (tmpf.empty())
1465                 return false;
1466
1467         // only first line in case something bad happens.
1468         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
1469         string line;
1470         getline(ifs, line);
1471         ifs.close();
1472         tmpf.erase();
1473
1474         rev_tree_cache_ = line;
1475         return !line.empty();
1476 }
1477
1478
1479 void SVN::getLog(FileName const & tmpf)
1480 {
1481         doVCCommand("svn log " + quoteName(onlyFileName(owner_->absFileName()))
1482                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1483                     FileName(owner_->filePath()));
1484 }
1485
1486
1487 bool SVN::prepareFileRevision(string const & revis, string & f)
1488 {
1489         if (!isStrInt(revis))
1490                 return false;
1491
1492         int rev = convert<int>(revis);
1493         if (rev <= 0)
1494                 if (!getFileRevisionInfo())
1495                         return false;
1496         if (rev == 0)
1497                 rev = convert<int>(rev_file_cache_);
1498         // go back for minus rev
1499         else if (rev < 0) {
1500                 rev = rev + convert<int>(rev_file_cache_);
1501                 if (rev < 1)
1502                         return false;
1503         }
1504
1505         string revname = convert<string>(rev);
1506         FileName tmpf = FileName::tempName("lyxvcrev_" + revname + "_");
1507         if (tmpf.empty()) {
1508                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1509                 return false;
1510         }
1511
1512         doVCCommand("svn cat -r " + revname + " "
1513                       + quoteName(onlyFileName(owner_->absFileName()))
1514                       + " > " + quoteName(tmpf.toFilesystemEncoding()),
1515                 FileName(owner_->filePath()));
1516         if (tmpf.isFileEmpty())
1517                 return false;
1518
1519         f = tmpf.absFileName();
1520         return true;
1521 }
1522
1523
1524 bool SVN::prepareFileRevisionEnabled()
1525 {
1526         return true;
1527 }
1528
1529
1530
1531 bool SVN::toggleReadOnlyEnabled()
1532 {
1533         return false;
1534 }
1535
1536
1537 } // namespace lyx