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