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