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