diff --git a/src/Database.cpp b/src/Database.cpp index 640a127b..e6245149 100644 --- a/src/Database.cpp +++ b/src/Database.cpp @@ -176,7 +176,9 @@ void Database::modifyInterval (const Interval& from, const Interval& to) void Database::undoTxnStart () { if (_txn == 0) - _undo.push_back ("txn:"); + { + _currentTransaction = std::make_shared (); + } ++_txn; } @@ -191,16 +193,18 @@ void Database::undoTxnEnd () if (_txn == 0) { File undo (_location + "/undo.data"); + if (undo.open ()) { - for (auto& line : _undo) - undo.append (line + "\n"); + undo.append (_currentTransaction->toString()); undo.close (); - _undo.clear (); + _currentTransaction.reset (); } else + { throw format ("Unable to write the undo transaction to {1}", undo._data); + } } } @@ -213,9 +217,7 @@ void Database::undoTxn ( const std::string& before, const std::string& after) { - _undo.push_back (" type: " + type); - _undo.push_back (" before: " + before); - _undo.push_back (" after: " + after); + _currentTransaction->addUndoAction (type, before, after); } //////////////////////////////////////////////////////////////////////////////// diff --git a/src/Database.h b/src/Database.h index 26e0e80c..01e0779e 100644 --- a/src/Database.h +++ b/src/Database.h @@ -30,6 +30,7 @@ #include #include #include +#include #include #include @@ -62,8 +63,9 @@ private: private: std::string _location {"~/.timewarrior/data"}; std::vector _files {}; - std::vector _undo {}; int _txn {0}; + + std::shared_ptr _currentTransaction = nullptr; }; #endif diff --git a/src/Transaction.cpp b/src/Transaction.cpp index 93fc1635..194d8416 100644 --- a/src/Transaction.cpp +++ b/src/Transaction.cpp @@ -34,3 +34,15 @@ void Transaction::addUndoAction ( { _actions.emplace_back (type, before, after); } + +std::string Transaction::toString () +{ + std::string output = "txn:\n"; + + for (auto& action : _actions) + { + output += action.toString (); + } + + return output; +} diff --git a/src/Transaction.h b/src/Transaction.h index e58c851d..4a1dce86 100644 --- a/src/Transaction.h +++ b/src/Transaction.h @@ -35,6 +35,8 @@ class Transaction public: void addUndoAction(const std::string&, const std::string&, const std::string&); + std::string toString(); + private: std::vector _actions {}; }; diff --git a/src/UndoAction.cpp b/src/UndoAction.cpp index 4b989f06..5b6d9d02 100644 --- a/src/UndoAction.cpp +++ b/src/UndoAction.cpp @@ -35,3 +35,10 @@ UndoAction::UndoAction ( _before = before; _after = after; } + +std::string UndoAction::toString () +{ + return " type: " + _type + "\n" + + " before: " + _before + "\n" + + " after: " + _after + "\n"; +} diff --git a/src/UndoAction.h b/src/UndoAction.h index 3236505f..97ebd27a 100644 --- a/src/UndoAction.h +++ b/src/UndoAction.h @@ -34,6 +34,8 @@ class UndoAction public: UndoAction(const std::string&, const std::string&, const std::string&); + std::string toString (); + private: std::string _type; std::string _before;