]> git.lyx.org Git - lyx.git/blob - src/VCBackend.cpp
b3d5e97507fefb4639766b2ac4fcd8ebc57e9816
[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         scanMaster();
370 }
371
372
373 FileName const CVS::findFile(FileName const & file)
374 {
375         // First we look for the CVS/Entries in the same dir
376         // where we have file.
377         FileName const entries(onlyPath(file.absFileName()) + "/CVS/Entries");
378         string const tmpf = '/' + onlyFileName(file.absFileName()) + '/';
379         LYXERR(Debug::LYXVC, "LyXVC: Checking if file is under cvs in `" << entries
380                              << "' for `" << tmpf << '\'');
381         if (entries.isReadableFile()) {
382                 // Ok we are at least in a CVS dir. Parse the CVS/Entries
383                 // and see if we can find this file. We do a fast and
384                 // dirty parse here.
385                 ifstream ifs(entries.toFilesystemEncoding().c_str());
386                 string line;
387                 while (getline(ifs, line)) {
388                         LYXERR(Debug::LYXVC, "\tEntries: " << line);
389                         if (contains(line, tmpf))
390                                 return entries;
391                 }
392         }
393         return FileName();
394 }
395
396
397 void CVS::scanMaster()
398 {
399         LYXERR(Debug::LYXVC, "LyXVC::CVS: scanMaster. \n     Checking: " << master_);
400         // Ok now we do the real scan...
401         ifstream ifs(master_.toFilesystemEncoding().c_str());
402         string name = onlyFileName(file_.absFileName());
403         string tmpf = '/' + name + '/';
404         LYXERR(Debug::LYXVC, "\tlooking for `" << tmpf << '\'');
405         string line;
406         static regex const reg("/(.*)/(.*)/(.*)/(.*)/(.*)");
407         while (getline(ifs, line)) {
408                 LYXERR(Debug::LYXVC, "\t  line: " << line);
409                 if (contains(line, tmpf)) {
410                         // Ok extract the fields.
411                         smatch sm;
412
413                         regex_match(line, sm, reg);
414
415                         //sm[0]; // whole matched string
416                         //sm[1]; // filename
417                         version_ = sm.str(2);
418                         string const file_date = sm.str(3);
419
420                         //sm[4]; // options
421                         //sm[5]; // tag or tagdate
422                         if (file_.isReadableFile()) {
423                                 time_t mod = file_.lastModified();
424                                 string mod_date = rtrim(asctime(gmtime(&mod)), "\n");
425                                 LYXERR(Debug::LYXVC, "Date in Entries: `" << file_date
426                                         << "'\nModification date of file: `" << mod_date << '\'');
427                                 if (file_.isReadOnly()) {
428                                         // readonly checkout is unlocked
429                                         vcstatus = UNLOCKED;
430                                 } else {
431                                         FileName bdir(addPath(master_.onlyPath().absFileName(),"Base"));
432                                         FileName base(addName(bdir.absFileName(),name));
433                                         // if base version is existent "cvs edit" was used to lock
434                                         vcstatus = base.isReadableFile() ? LOCKED : NOLOCKING;
435                                 }
436                         } else {
437                                 vcstatus = NOLOCKING;
438                         }
439                         break;
440                 }
441         }
442 }
443
444
445 string const CVS::getTarget(OperationMode opmode) const
446 {
447         switch(opmode) {
448         case Directory:
449                 // in client server mode CVS does not like full path operand for directory operation
450                 // since LyX switches to the repo dir "." is good enough as target
451                 return ".";
452         case File:
453                 return quoteName(onlyFileName(owner_->absFileName()));
454         }
455         return string();
456 }
457
458
459 docstring CVS::toString(CvsStatus status) const
460 {
461         switch (status) {
462         case UpToDate:
463                 return _("Up-to-date");
464         case LocallyModified:
465                 return _("Locally Modified");
466         case LocallyAdded:
467                 return _("Locally Added");
468         case NeedsMerge:
469                 return _("Needs Merge");
470         case NeedsCheckout:
471                 return _("Needs Checkout");
472         case NoCvsFile:
473                 return _("No CVS file");
474         case StatusError:
475                 return _("Cannot retrieve CVS status");
476         }
477         return 0;
478 }
479
480
481 CVS::CvsStatus CVS::getStatus()
482 {
483         FileName tmpf = FileName::tempName("lyxvcout");
484         if (tmpf.empty()) {
485                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
486                 return StatusError;
487         }
488
489         if (doVCCommand("cvs status " + getTarget(File)
490                 + " > " + quoteName(tmpf.toFilesystemEncoding()),
491                 FileName(owner_->filePath()))) {
492                 tmpf.removeFile();
493                 return StatusError;
494         }
495
496         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
497         CvsStatus status = NoCvsFile;
498
499         while (ifs) {
500                 string line;
501                 getline(ifs, line);
502                 LYXERR(Debug::LYXVC, line << "\n");
503                 if (prefixIs(line, "File:")) {
504                         if (contains(line, "Up-to-date"))
505                                 status = UpToDate;
506                         else if (contains(line, "Locally Modified"))
507                                 status = LocallyModified;
508                         else if (contains(line, "Locally Added"))
509                                 status = LocallyAdded;
510                         else if (contains(line, "Needs Merge"))
511                                 status = NeedsMerge;
512                         else if (contains(line, "Needs Checkout"))
513                                 status = NeedsCheckout;
514                 }
515         }
516         tmpf.removeFile();
517         return status;
518 }
519
520
521 void CVS::registrer(string const & msg)
522 {
523         doVCCommand("cvs -q add -m \"" + msg + "\" "
524                 + getTarget(File),
525                 FileName(owner_->filePath()));
526 }
527
528
529 void CVS::getDiff(OperationMode opmode, FileName const & tmpf)
530 {
531         doVCCommand("cvs diff " + getTarget(opmode)
532                 + " > " + quoteName(tmpf.toFilesystemEncoding()),
533                 FileName(owner_->filePath()), false);
534 }
535
536
537 int CVS::edit()
538 {
539         vcstatus = LOCKED;
540         return doVCCommand("cvs -q edit " + getTarget(File),
541                 FileName(owner_->filePath()));
542 }
543
544
545 int CVS::unedit()
546 {
547         vcstatus = UNLOCKED;
548         return doVCCommand("cvs -q unedit " + getTarget(File),
549                 FileName(owner_->filePath()));
550 }
551
552
553 int CVS::update(OperationMode opmode, FileName const & tmpf)
554 {
555         string const redirection = tmpf.empty() ? ""
556                 : " > " + quoteName(tmpf.toFilesystemEncoding());
557
558         return doVCCommand("cvs -q update "
559                 + getTarget(opmode) + redirection,
560                 FileName(owner_->filePath()));
561 }
562
563
564 string CVS::scanLogFile(FileName const & f, string & status)
565 {
566         ifstream ifs(f.toFilesystemEncoding().c_str());
567
568         while (ifs) {
569                 string line;
570                 getline(ifs, line);
571                 LYXERR(Debug::LYXVC, line << "\n");
572                 if (!line.empty())
573                         status += line + "; ";
574                 if (prefixIs(line, "C ")) {
575                         ifs.close();
576                         return line;
577                 }
578         }
579         ifs.close();
580         return string();
581 }
582         
583         
584 string CVS::checkIn(string const & msg)
585 {
586         CvsStatus status = getStatus();
587         switch (status) {
588         case UpToDate:
589                 if (vcstatus != NOLOCKING)
590                         unedit();
591                 return "CVS: Proceeded";
592         case LocallyModified:
593         case LocallyAdded: {
594                 int rc = doVCCommand("cvs -q commit -m \"" + msg + "\" "
595                         + getTarget(File),
596                     FileName(owner_->filePath()));
597                 return rc ? string() : "CVS: Proceeded";
598         }
599         case NeedsMerge:
600         case NeedsCheckout:
601                 frontend::Alert::error(_("Revision control error."),
602                         _("The repository version is newer then the current check out.\n"
603                           "You have to update from repository first or revert your changes.")) ;
604                 break;
605         default:
606                 frontend::Alert::error(_("Revision control error."),
607                         bformat(_("Bad status when checking in changes.\n"
608                                           "\n'%1$s'\n\n"),
609                                 toString(status)));
610                 break;
611         }
612         return string();
613 }
614
615
616 bool CVS::isLocked() const
617 {
618         FileName fn(owner_->absFileName());
619         fn.refresh();
620         return !fn.isReadOnly();
621 }
622
623
624 bool CVS::checkInEnabled()
625 {
626         if (vcstatus != NOLOCKING)
627                 return isLocked();
628         else
629                 return true;
630 }
631
632
633 bool CVS::isCheckInWithConfirmation()
634 {
635         CvsStatus status = getStatus();
636         return status == LocallyModified || status == LocallyAdded;
637 }
638
639
640 string CVS::checkOut()
641 {
642         if (vcstatus != NOLOCKING && edit())
643                 return string();
644         FileName tmpf = FileName::tempName("lyxvcout");
645         if (tmpf.empty()) {
646                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
647                 return string();
648         }
649         
650         int rc = update(File, tmpf);
651         string log;
652         string const res = scanLogFile(tmpf, log);
653         if (!res.empty())
654                 frontend::Alert::error(_("Revision control error."),
655                         bformat(_("Error when updating from repository.\n"
656                                 "You have to manually resolve the conflicts NOW!\n'%1$s'.\n\n"
657                                 "After pressing OK, LyX will try to reopen the resolved document."),
658                                 from_local8bit(res)));
659         
660         tmpf.erase();
661         return rc ? string() : log.empty() ? "CVS: Proceeded" : "CVS: " + log;
662 }
663
664
665 bool CVS::checkOutEnabled()
666 {
667         if (vcstatus != NOLOCKING)
668                 return !isLocked();
669         else
670                 return true;
671 }
672
673
674 string CVS::repoUpdate()
675 {
676         FileName tmpf = FileName::tempName("lyxvcout");
677         if (tmpf.empty()) {
678                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
679                 return string();
680         }
681         
682         getDiff(Directory, tmpf);
683         docstring res = tmpf.fileContents("UTF-8");
684         if (!res.empty()) {
685                 LYXERR(Debug::LYXVC, "Diff detected:\n" << res);
686                 docstring const file = from_utf8(owner_->filePath());
687                 docstring text = bformat(_("There were detected changes "
688                                 "in the working directory:\n%1$s\n\n"
689                                 "In case of file conflict you have to resolve them "
690                                 "manually or revert to repository version later."), file);
691                 int ret = frontend::Alert::prompt(_("Changes detected"),
692                                 text, 0, 1, _("&Continue"), _("&Abort"), _("View &Log ..."));
693                 if (ret == 2 ) {
694                         dispatch(FuncRequest(LFUN_DIALOG_SHOW, "file " + tmpf.absFileName()));
695                         ret = frontend::Alert::prompt(_("Changes detected"),
696                                 text, 0, 1, _("&Continue"), _("&Abort"));
697                         hideDialogs("file", 0);
698                 }
699                 if (ret == 1 ) {
700                         tmpf.removeFile();
701                         return string();
702                 }
703         }
704
705         int rc = update(Directory, tmpf);
706         res += "Update log:\n" + tmpf.fileContents("UTF-8");
707         tmpf.removeFile();
708
709         LYXERR(Debug::LYXVC, res);
710         return rc ? string() : "CVS: Proceeded" ;
711 }
712
713
714 bool CVS::repoUpdateEnabled()
715 {
716         return true;
717 }
718
719
720 string CVS::lockingToggle()
721 {
722         lyxerr << "Sorry, not implemented." << endl;
723         return string();
724 }
725
726
727 bool CVS::lockingToggleEnabled()
728 {
729         return false;
730 }
731
732
733 bool CVS::isRevertWithConfirmation()
734 {
735         CvsStatus status = getStatus();
736         return !owner_->isClean() || status == LocallyModified || status == NeedsMerge;
737 }
738
739
740 void CVS::revert()
741 {
742         // Reverts to the version in CVS repository and
743         // gets the updated version from the repository.
744         CvsStatus status = getStatus();
745         switch (status) {
746         case UpToDate:
747                 if (vcstatus != NOLOCKING)
748                         unedit();
749                 break;
750         case NeedsMerge:
751         case NeedsCheckout:
752         case LocallyModified: {
753                 FileName f(owner_->absFileName());
754                 f.removeFile();
755                 update(File, FileName());
756                 owner_->markClean();
757                 break;
758         }
759         case LocallyAdded: {
760                 docstring const file = owner_->fileName().displayName(20);
761                 frontend::Alert::error(_("Revision control error."),
762                         bformat(_("The document %1$s is not in repository.\n"
763                                   "You have to check in the first revision before you can revert."),
764                                 file)) ;
765                 break;
766         }
767         default: {
768                 docstring const file = owner_->fileName().displayName(20);
769                 frontend::Alert::error(_("Revision control error."),
770                         bformat(_("Cannot revert document %1$s to repository version.\n"
771                                   "The status '%2$s' is unexpected."),
772                                 file, toString(status)));
773                 break;
774                 }
775         }
776 }
777
778
779 void CVS::undoLast()
780 {
781         // merge the current with the previous version
782         // in a reverse patch kind of way, so that the
783         // result is to revert the last changes.
784         lyxerr << "Sorry, not implemented." << endl;
785 }
786
787
788 bool CVS::undoLastEnabled()
789 {
790         return false;
791 }
792
793
794 void CVS::getLog(FileName const & tmpf)
795 {
796         doVCCommand("cvs log " + getTarget(File)
797                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
798                     FileName(owner_->filePath()));
799 }
800
801
802 bool CVS::toggleReadOnlyEnabled()
803 {
804         return false;
805 }
806
807
808 string CVS::revisionInfo(LyXVC::RevisionInfo const info)
809 {
810         if (info == LyXVC::File)
811                 return version_;
812         return string();
813 }
814
815
816 bool CVS::prepareFileRevision(string const &, string &)
817 {
818         return false;
819 }
820
821
822 bool CVS::prepareFileRevisionEnabled()
823 {
824         return false;
825 }
826
827
828 /////////////////////////////////////////////////////////////////////
829 //
830 // SVN
831 //
832 /////////////////////////////////////////////////////////////////////
833
834 SVN::SVN(FileName const & m, FileName const & f)
835 {
836         owner_ = 0;
837         master_ = m;
838         file_ = f;
839         locked_mode_ = 0;
840         scanMaster();
841 }
842
843
844 FileName const SVN::findFile(FileName const & file)
845 {
846         // First we look for the .svn/entries in the same dir
847         // where we have file.
848         FileName const entries(onlyPath(file.absFileName()) + "/.svn/entries");
849         string const tmpf = onlyFileName(file.absFileName());
850         LYXERR(Debug::LYXVC, "LyXVC: Checking if file is under svn in `" << entries
851                              << "' for `" << tmpf << '\'');
852         if (entries.isReadableFile()) {
853                 // Ok we are at least in a SVN dir. Parse the .svn/entries
854                 // and see if we can find this file. We do a fast and
855                 // dirty parse here.
856                 ifstream ifs(entries.toFilesystemEncoding().c_str());
857                 string line, oldline;
858                 while (getline(ifs, line)) {
859                         if (line == "dir" || line == "file")
860                                 LYXERR(Debug::LYXVC, "\tEntries: " << oldline);
861                         if (oldline == tmpf && line == "file")
862                                 return entries;
863                         oldline = line;
864                 }
865         }
866         return FileName();
867 }
868
869
870 void SVN::scanMaster()
871 {
872         // vcstatus code is somewhat superflous, until we want
873         // to implement read-only toggle for svn.
874         vcstatus = NOLOCKING;
875         if (checkLockMode()) {
876                 if (isLocked()) {
877                         vcstatus = LOCKED;
878                 } else {
879                         vcstatus = UNLOCKED;
880                 }
881         }
882 }
883
884
885 bool SVN::checkLockMode()
886 {
887         FileName tmpf = FileName::tempName("lyxvcout");
888         if (tmpf.empty()){
889                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
890                 return N_("Error: Could not generate logfile.");
891         }
892
893         LYXERR(Debug::LYXVC, "Detecting locking mode...");
894         if (doVCCommandCall("svn proplist " + quoteName(file_.onlyFileName())
895                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
896                     file_.onlyPath()))
897                 return false;
898
899         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
900         string line;
901         bool ret = false;
902
903         while (ifs) {
904                 getline(ifs, line);
905                 LYXERR(Debug::LYXVC, line);
906                 if (contains(line, "svn:needs-lock"))
907                         ret = true;
908         }
909         LYXERR(Debug::LYXVC, "Locking enabled: " << ret);
910         ifs.close();
911         locked_mode_ = ret;
912         return ret;
913
914 }
915
916
917 bool SVN::isLocked() const
918 {
919         file_.refresh();
920         return !file_.isReadOnly();
921 }
922
923
924 void SVN::registrer(string const & /*msg*/)
925 {
926         doVCCommand("svn add -q " + quoteName(onlyFileName(owner_->absFileName())),
927                     FileName(owner_->filePath()));
928 }
929
930
931 string SVN::checkIn(string const & msg)
932 {
933         FileName tmpf = FileName::tempName("lyxvcout");
934         if (tmpf.empty()){
935                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
936                 return N_("Error: Could not generate logfile.");
937         }
938
939         doVCCommand("svn commit -m \"" + msg + "\" "
940                     + quoteName(onlyFileName(owner_->absFileName()))
941                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
942                     FileName(owner_->filePath()));
943
944         string log;
945         string res = scanLogFile(tmpf, log);
946         if (!res.empty())
947                 frontend::Alert::error(_("Revision control error."),
948                                 _("Error when committing to repository.\n"
949                                 "You have to manually resolve the problem.\n"
950                                 "LyX will reopen the document after you press OK."));
951         else
952                 fileLock(false, tmpf, log);
953
954         tmpf.erase();
955         return log.empty() ? string() : "SVN: " + log;
956 }
957
958
959 bool SVN::checkInEnabled()
960 {
961         if (locked_mode_)
962                 return isLocked();
963         else
964                 return true;
965 }
966
967
968 bool SVN::isCheckInWithConfirmation()
969 {
970         //FIXME diff
971         return true;
972 }
973
974
975 // FIXME Correctly return code should be checked instead of this.
976 // This would need another solution than just plain startscript.
977 // Hint from Andre': QProcess::readAllStandardError()...
978 string SVN::scanLogFile(FileName const & f, string & status)
979 {
980         ifstream ifs(f.toFilesystemEncoding().c_str());
981         string line;
982
983         while (ifs) {
984                 getline(ifs, line);
985                 LYXERR(Debug::LYXVC, line << "\n");
986                 if (!line.empty()) 
987                         status += line + "; ";
988                 if (prefixIs(line, "C ") || prefixIs(line, "CU ")
989                                          || contains(line, "Commit failed")) {
990                         ifs.close();
991                         return line;
992                 }
993                 if (contains(line, "svn:needs-lock")) {
994                         ifs.close();
995                         return line;
996                 }
997         }
998         ifs.close();
999         return string();
1000 }
1001
1002
1003 void SVN::fileLock(bool lock, FileName const & tmpf, string &status)
1004 {
1005         if (!locked_mode_ || (isLocked() == lock))
1006                 return;
1007
1008         string const arg = lock ? "lock " : "unlock ";
1009         doVCCommand("svn "+ arg + quoteName(onlyFileName(owner_->absFileName()))
1010                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1011                     FileName(owner_->filePath()));
1012
1013         // Lock error messages go unfortunately on stderr and are unreachible this way.
1014         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
1015         string line;
1016         while (ifs) {
1017                 getline(ifs, line);
1018                 if (!line.empty()) status += line + "; ";
1019         }
1020         ifs.close();
1021
1022         if (!isLocked() && lock)
1023                 frontend::Alert::error(_("Revision control error."),
1024                         _("Error while acquiring write lock.\n"
1025                         "Another user is most probably editing\n"
1026                         "the current document now!\n"
1027                         "Also check the access to the repository."));
1028         if (isLocked() && !lock)
1029                 frontend::Alert::error(_("Revision control error."),
1030                         _("Error while releasing write lock.\n"
1031                         "Check the access to the repository."));
1032 }
1033
1034
1035 string SVN::checkOut()
1036 {
1037         FileName tmpf = FileName::tempName("lyxvcout");
1038         if (tmpf.empty()) {
1039                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1040                 return N_("Error: Could not generate logfile.");
1041         }
1042
1043         doVCCommand("svn update --non-interactive " + quoteName(onlyFileName(owner_->absFileName()))
1044                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1045                     FileName(owner_->filePath()));
1046
1047         string log;
1048         string const res = scanLogFile(tmpf, log);
1049         if (!res.empty())
1050                 frontend::Alert::error(_("Revision control error."),
1051                         bformat(_("Error when updating from repository.\n"
1052                                 "You have to manually resolve the conflicts NOW!\n'%1$s'.\n\n"
1053                                 "After pressing OK, LyX will try to reopen the resolved document."),
1054                         from_local8bit(res)));
1055
1056         fileLock(true, tmpf, log);
1057
1058         tmpf.erase();
1059         return log.empty() ? string() : "SVN: " + log;
1060 }
1061
1062
1063 bool SVN::checkOutEnabled()
1064 {
1065         if (locked_mode_)
1066                 return !isLocked();
1067         else
1068                 return true;
1069 }
1070
1071
1072 string SVN::repoUpdate()
1073 {
1074         FileName tmpf = FileName::tempName("lyxvcout");
1075         if (tmpf.empty()) {
1076                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1077                 return N_("Error: Could not generate logfile.");
1078         }
1079
1080         doVCCommand("svn diff " + quoteName(owner_->filePath())
1081                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1082                 FileName(owner_->filePath()));
1083         docstring res = tmpf.fileContents("UTF-8");
1084         if (!res.empty()) {
1085                 LYXERR(Debug::LYXVC, "Diff detected:\n" << res);
1086                 docstring const file = from_utf8(owner_->filePath());
1087                 docstring text = bformat(_("There were detected changes "
1088                                 "in the working directory:\n%1$s\n\n"
1089                                 "In case of file conflict version of the local directory files "
1090                                 "will be preferred."
1091                                 "\n\nContinue?"), file);
1092                 int ret = frontend::Alert::prompt(_("Changes detected"),
1093                                 text, 0, 1, _("&Yes"), _("&No"), _("View &Log ..."));
1094                 if (ret == 2 ) {
1095                         dispatch(FuncRequest(LFUN_DIALOG_SHOW, "file " + tmpf.absFileName()));
1096                         ret = frontend::Alert::prompt(_("Changes detected"),
1097                                 text, 0, 1, _("&Yes"), _("&No"));
1098                         hideDialogs("file", 0);
1099                 }
1100                 if (ret == 1 ) {
1101                         tmpf.erase();
1102                         return string();
1103                 }
1104         }
1105
1106         // Reverting looks too harsh, see bug #6255.
1107         // doVCCommand("svn revert -R " + quoteName(owner_->filePath())
1108         // + " > " + quoteName(tmpf.toFilesystemEncoding()),
1109         // FileName(owner_->filePath()));
1110         // res = "Revert log:\n" + tmpf.fileContents("UTF-8");
1111         doVCCommand("svn update --accept mine-full " + quoteName(owner_->filePath())
1112                 + " > " + quoteName(tmpf.toFilesystemEncoding()),
1113                 FileName(owner_->filePath()));
1114         res += "Update log:\n" + tmpf.fileContents("UTF-8");
1115
1116         LYXERR(Debug::LYXVC, res);
1117         tmpf.erase();
1118         return to_utf8(res);
1119 }
1120
1121
1122 bool SVN::repoUpdateEnabled()
1123 {
1124         return true;
1125 }
1126
1127
1128 string SVN::lockingToggle()
1129 {
1130         FileName tmpf = FileName::tempName("lyxvcout");
1131         if (tmpf.empty()) {
1132                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1133                 return N_("Error: Could not generate logfile.");
1134         }
1135
1136         int ret = doVCCommand("svn proplist " + quoteName(onlyFileName(owner_->absFileName()))
1137                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1138                     FileName(owner_->filePath()));
1139         if (ret)
1140                 return string();
1141
1142         string log;
1143         string res = scanLogFile(tmpf, log);
1144         bool locking = contains(res, "svn:needs-lock");
1145         if (!locking)
1146                 ret = doVCCommand("svn propset svn:needs-lock ON "
1147                     + quoteName(onlyFileName(owner_->absFileName()))
1148                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1149                     FileName(owner_->filePath()));
1150         else
1151                 ret = doVCCommand("svn propdel svn:needs-lock "
1152                     + quoteName(onlyFileName(owner_->absFileName()))
1153                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1154                     FileName(owner_->filePath()));
1155         if (ret)
1156                 return string();
1157
1158         tmpf.erase();
1159         frontend::Alert::warning(_("VCN File Locking"),
1160                 (locking ? _("Locking property unset.") : _("Locking property set.")) + "\n"
1161                 + _("Do not forget to commit the locking property into the repository."),
1162                 true);
1163
1164         return string("SVN: ") +  N_("Locking property set.");
1165 }
1166
1167
1168 bool SVN::lockingToggleEnabled()
1169 {
1170         return true;
1171 }
1172
1173
1174 void SVN::revert()
1175 {
1176         // Reverts to the version in SVN repository and
1177         // gets the updated version from the repository.
1178         string const fil = quoteName(onlyFileName(owner_->absFileName()));
1179
1180         doVCCommand("svn revert -q " + fil,
1181                     FileName(owner_->filePath()));
1182         owner_->markClean();
1183 }
1184
1185
1186 bool SVN::isRevertWithConfirmation()
1187 {
1188         //FIXME owner && diff
1189         return true;
1190 }
1191
1192
1193 void SVN::undoLast()
1194 {
1195         // merge the current with the previous version
1196         // in a reverse patch kind of way, so that the
1197         // result is to revert the last changes.
1198         lyxerr << "Sorry, not implemented." << endl;
1199 }
1200
1201
1202 bool SVN::undoLastEnabled()
1203 {
1204         return false;
1205 }
1206
1207
1208 string SVN::revisionInfo(LyXVC::RevisionInfo const info)
1209 {
1210         if (info == LyXVC::Tree) {
1211                         if (rev_tree_cache_.empty())
1212                                 if (!getTreeRevisionInfo())
1213                                         rev_tree_cache_ = "?";
1214                         if (rev_tree_cache_ == "?")
1215                                 return string();
1216
1217                         return rev_tree_cache_;
1218         }
1219
1220         // fill the rest of the attributes for a single file
1221         if (rev_file_cache_.empty())
1222                 if (!getFileRevisionInfo())
1223                         rev_file_cache_ = "?";
1224
1225         switch (info) {
1226                 case LyXVC::File:
1227                         if (rev_file_cache_ == "?")
1228                                 return string();
1229                         return rev_file_cache_;
1230                 case LyXVC::Author:
1231                         return rev_author_cache_;
1232                 case LyXVC::Date:
1233                         return rev_date_cache_;
1234                 case LyXVC::Time:
1235                         return rev_time_cache_;
1236                 default: ;
1237
1238         }
1239
1240         return string();
1241 }
1242
1243
1244 bool SVN::getFileRevisionInfo()
1245 {
1246         FileName tmpf = FileName::tempName("lyxvcout");
1247         if (tmpf.empty()) {
1248                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1249                 return N_("Error: Could not generate logfile.");
1250         }
1251
1252         doVCCommand("svn info --xml " + quoteName(onlyFileName(owner_->absFileName()))
1253                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1254                     FileName(owner_->filePath()));
1255
1256         if (tmpf.empty())
1257                 return false;
1258
1259         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
1260         string line;
1261         // commit log part
1262         bool c = false;
1263         string rev;
1264
1265         while (ifs) {
1266                 getline(ifs, line);
1267                 LYXERR(Debug::LYXVC, line);
1268                 if (prefixIs(line, "<commit"))
1269                         c = true;
1270                 if (c && prefixIs(line, "   revision=\"") && suffixIs(line, "\">")) {
1271                         string l1 = subst(line, "revision=\"", "");
1272                         string l2 = trim(subst(l1, "\">", ""));
1273                         if (isStrInt(l2))
1274                                 rev_file_cache_ = rev = l2;
1275                 }
1276                 if (c && prefixIs(line, "<author>") && suffixIs(line, "</author>")) {
1277                         string l1 = subst(line, "<author>", "");
1278                         string l2 = subst(l1, "</author>", "");
1279                         rev_author_cache_ = l2;
1280                 }
1281                 if (c && prefixIs(line, "<date>") && suffixIs(line, "</date>")) {
1282                         string l1 = subst(line, "<date>", "");
1283                         string l2 = subst(l1, "</date>", "");
1284                         l2 = split(l2, l1, 'T');
1285                         rev_date_cache_ = l1;
1286                         l2 = split(l2, l1, '.');
1287                         rev_time_cache_ = l1;
1288                 }
1289         }
1290
1291         ifs.close();
1292         tmpf.erase();
1293         return !rev.empty();
1294 }
1295
1296
1297 bool SVN::getTreeRevisionInfo()
1298 {
1299         FileName tmpf = FileName::tempName("lyxvcout");
1300         if (tmpf.empty()) {
1301                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1302                 return N_("Error: Could not generate logfile.");
1303         }
1304
1305         doVCCommand("svnversion -n . > " + quoteName(tmpf.toFilesystemEncoding()),
1306                     FileName(owner_->filePath()));
1307
1308         if (tmpf.empty())
1309                 return false;
1310
1311         // only first line in case something bad happens.
1312         ifstream ifs(tmpf.toFilesystemEncoding().c_str());
1313         string line;
1314         getline(ifs, line);
1315         ifs.close();
1316         tmpf.erase();
1317
1318         rev_tree_cache_ = line;
1319         return !line.empty();
1320 }
1321
1322
1323 void SVN::getLog(FileName const & tmpf)
1324 {
1325         doVCCommand("svn log " + quoteName(onlyFileName(owner_->absFileName()))
1326                     + " > " + quoteName(tmpf.toFilesystemEncoding()),
1327                     FileName(owner_->filePath()));
1328 }
1329
1330
1331 bool SVN::prepareFileRevision(string const & revis, string & f)
1332 {
1333         if (!isStrInt(revis))
1334                 return false;
1335
1336         int rev = convert<int>(revis);
1337         if (rev <= 0)
1338                 if (!getFileRevisionInfo())
1339                         return false;
1340         if (rev == 0)
1341                 rev = convert<int>(rev_file_cache_);
1342         // go back for minus rev
1343         else if (rev < 0) {
1344                 rev = rev + convert<int>(rev_file_cache_);
1345                 if (rev < 1)
1346                         return false;
1347         }
1348
1349         string revname = convert<string>(rev);
1350         FileName tmpf = FileName::tempName("lyxvcrev_" + revname + "_");
1351         if (tmpf.empty()) {
1352                 LYXERR(Debug::LYXVC, "Could not generate logfile " << tmpf);
1353                 return N_("Error: Could not generate logfile.");
1354         }
1355
1356         doVCCommand("svn cat -r " + revname + " "
1357                       + quoteName(onlyFileName(owner_->absFileName()))
1358                       + " > " + quoteName(tmpf.toFilesystemEncoding()),
1359                 FileName(owner_->filePath()));
1360         if (tmpf.isFileEmpty())
1361                 return false;
1362
1363         f = tmpf.absFileName();
1364         return true;
1365 }
1366
1367
1368 bool SVN::prepareFileRevisionEnabled()
1369 {
1370         return true;
1371 }
1372
1373
1374
1375 bool SVN::toggleReadOnlyEnabled()
1376 {
1377         return false;
1378 }
1379
1380
1381 } // namespace lyx