1 /* 2 * Copyright 2013, Ingo Weinhold, ingo_weinhold@gmx.de. 3 * Distributed under the terms of the MIT License. 4 */ 5 #ifndef FS_TRANSACTION_H 6 #define FS_TRANSACTION_H 7 8 9 #include <string> 10 #include <vector> 11 12 #include "FSUtils.h" 13 14 15 class FSTransaction { 16 public: 17 typedef FSUtils::Entry Entry; 18 19 class Operation; 20 class CreateOperation; 21 class RemoveOperation; 22 class MoveOperation; 23 24 public: 25 FSTransaction(); 26 ~FSTransaction(); 27 28 void RollBack(); 29 30 int32 CreateEntry(const Entry& entry, 31 int32 modifiedOperation = -1); 32 int32 RemoveEntry(const Entry& entry, 33 const Entry& backupEntry, 34 int32 modifiedOperation = -1); 35 int32 MoveEntry(const Entry& fromEntry, 36 const Entry& toEntry, 37 int32 modifiedOperation = -1); 38 39 void RemoveOperationAt(int32 index); 40 41 private: 42 struct OperationInfo; 43 typedef std::vector<OperationInfo> OperationList; 44 45 private: 46 static std::string _GetPath(const Entry& entry); 47 48 private: 49 OperationList fOperations; 50 }; 51 52 53 class FSTransaction::Operation { 54 public: 55 Operation(FSTransaction* transaction, int32 operation) 56 : 57 fTransaction(transaction), 58 fOperation(operation) 59 { 60 } 61 62 ~Operation() 63 { 64 if (fTransaction != NULL && fOperation >= 0 && !fIsFinished) 65 fTransaction->RemoveOperationAt(fOperation); 66 } 67 68 /*! Arms the operation rollback, i.e. rolling back the transaction will 69 revert this operation. 70 */ 71 void Finished() 72 { 73 fIsFinished = true; 74 } 75 76 /*! Unregisters the operation rollback, i.e. rolling back the transaction 77 will not revert this operation. 78 */ 79 void Unregister() 80 { 81 if (fTransaction != NULL && fOperation >= 0) { 82 fTransaction->RemoveOperationAt(fOperation); 83 fIsFinished = false; 84 fTransaction = NULL; 85 fOperation = -1; 86 } 87 } 88 89 private: 90 FSTransaction* fTransaction; 91 int32 fOperation; 92 bool fIsFinished; 93 }; 94 95 96 class FSTransaction::CreateOperation : public FSTransaction::Operation { 97 public: 98 CreateOperation(FSTransaction* transaction, const Entry& entry, 99 int32 modifiedOperation = -1) 100 : 101 Operation(transaction, 102 transaction->CreateEntry(entry, modifiedOperation)) 103 { 104 } 105 }; 106 107 108 class FSTransaction::RemoveOperation : public FSTransaction::Operation { 109 public: 110 RemoveOperation(FSTransaction* transaction, const Entry& entry, 111 const Entry& backupEntry, int32 modifiedOperation = -1) 112 : 113 Operation(transaction, 114 transaction->RemoveEntry(entry, backupEntry, modifiedOperation)) 115 { 116 } 117 }; 118 119 120 class FSTransaction::MoveOperation : public FSTransaction::Operation { 121 public: 122 MoveOperation(FSTransaction* transaction, const Entry& fromEntry, 123 const Entry& toEntry, int32 modifiedOperation = -1) 124 : 125 Operation(transaction, 126 transaction->MoveEntry(fromEntry, toEntry, modifiedOperation)) 127 { 128 } 129 }; 130 131 132 #endif // FS_TRANSACTION_H 133