def listRentedBooks(commandInPieces): repoCaller = Repo() listOfRentedBooks = repoCaller.getListOfRentals() s = "Rented: \n" for iterator in listOfRentedBooks: s += Rental.printRental(iterator) return s
def validateRental(ghostBook, ghostClient): inBookList = False repoCaller = Repo() listOfBooks = repoCaller.getListOfBooks() listOfRentedBooks = repoCaller.getListOfRentals() listOfClients = repoCaller.getListOfClients() for iterator in listOfBooks: if Book.getBookId(iterator) == Book.getBookId(ghostBook): inBookList = True break if inBookList == False: raise BookAlreadyRentedOrDoesntExistError # bookIsRented=True for books in listOfRentedBooks: if Book.getBookId(ghostBook) == Rental.getBookId( books) and Rental.getReturnDate(books) == "notRented": for iterator in listOfRentedBooks: if Book.getBookId(iterator) == Book.getBookId(ghostBook): raise BookAlreadyRentedOrDoesntExistError clientFound = False for iterator in listOfClients: if Client.getClientId(iterator) == Client.getClientId(ghostClient): clientFound = True if clientFound == False: raise ClientAlreadyExistsError
def get_commit_log(git_repo, viewvc_url, author_in_commit_body=False): repo = Repo(git_repo) log = repo.commits(config.EMAIL_GREP, search_body=author_in_commit_body) for commit in log[:]: if author_in_commit_body: name_match = re.search( '(Contributed|Patch) (from|by) [^<]*<{name_re}>'.format(name_re=config.EMAIL_RE), commit.body) if not name_match: review_match = re.search('R=.*{}'.format(config.EMAIL_RE), commit.body) if review_match: # Skip stuff only reviewed log.remove(commit) continue raise Exception("Didn't find {} in commit msg ({})".format(config.EMAIL_RE, commit.body)) commit.author = name_match.group('full_email') commit.stripped_author = name_match.group('name') else: name_match = re.match(config.EMAIL_RE, commit.author) if name_match: commit.stripped_author = name_match.group('name') else: commit.stripped_author = commit.author commit.viewvc = viewvc_url.format(rev=commit.sha) return log
def validateABook(newBook): # checks if a book is already registred # input - instance of a book bookCaller = Book repoCaller = Repo() listOfBooks = repoCaller.getListOfBooks() for iterator in listOfBooks: if bookCaller.getBookId(iterator) == bookCaller.getBookId(newBook): raise BookAlreadyExistsError()
def validateAClient(newClient): # checks if a client is already registred # input - instance of a client clientCaller = Client repoCaller = Repo() listOfClients = repoCaller.getListOfClients() for iterator in listOfClients: if clientCaller.getClientId(iterator) == clientCaller.getClientId( newClient): raise ClientAlreadyExistsError
def listAllClients(commandInPieces): # lists clients in repository # input - not important / not used repoCaller = Repo() listOfClients = repoCaller.getListOfClients() s = "" s += "Clients: \n" for iterator in listOfClients: s += Client.clientToString(iterator) + "\n" return s
def listAllBooks(commandInPieces): # lists books in repository # input - not important/ not used repoCaller = Repo() listOfBooks = repoCaller.getListOfBooks() s = "" s += "Books: \n" for iterator in listOfBooks: s += Book.bookToString(iterator) + "\n" return s
def test_remove_book(self): repoBooks = Repo("Repobooks:") repoBooks.add(Book(1, "The Secret Crusade", "Oliver Bowden")) repoBooks.add(Book(2, "The Illustrated Man", "Ray Bradbury")) repoBooks.remove(Book(1, None, None)) assert(repoBooks.size() == 1) assert(repoBooks.get_all()[0].bookID == 2) with self.assertRaises(RepositoryError) as context: repoBooks.remove(Book(22, None, None)) self.assertTrue("\n[REPOSITORY ERROR] -> Repobooks: Inexistend ID!\n" in str(context.exception))
def searchAClient(commandInPieces): repoCaller = Repo() keyToSearch = commandInPieces[1] listOfClients = repoCaller.getListOfClients() s = "" s += "Clients: \n" for client in listOfClients: if keyToSearch.lower() == Client.getClientId(client).lower(): s += Client.clientToString(client) + "\n" elif keyToSearch.lower() == Client.getClientName(client).lower(): s += Client.clientToString(client) + "\n" return s
def searchABook(commandInPieces): repoCaller = Repo() keyToSearch = commandInPieces[1] listOfBooks = repoCaller.getListOfBooks() s = "" s = "Books: \n" for book in listOfBooks: if keyToSearch.lower() in Book.getBookId(book).lower(): s += Book.bookToString(book) + "\n" elif keyToSearch.lower() in Book.getBookAuthor(book).lower(): s += Book.bookToString(book) + "\n" elif keyToSearch.lower() in Book.getBookName(book).lower(): s += Book.bookToString(book) + "\n" return s
def test_remove_client(self): repoClients = Repo("Repoclients:") repoClients.add(Client(20, "John Wright")) repoClients.add(Client(40, "Andrei Ivan")) repoClients.remove(Client(40, None)) assert(repoClients.size() == 1) assert(repoClients.get_all()[0].clientID == 20)
def test_update_book(self): repoBooks = Repo("Repobooks:") repoBooks.add(Book(1, "The Secret Crusade", "Oliver Bowden")) repoBooks.add(Book(2, "The Illustrated Man", "Ray Bradbury")) repoBooks.update(Book(1, "New", "New2")) assert(repoBooks.get_all()[0].bookTitle == "New") assert(repoBooks.get_all()[0].bookAuthor == "New2") self.assertRaises(RepositoryError, lambda : repoBooks.update(Book(20, None, None)))
def test_update_client(self): repoClients = Repo("Repoclients:") repoClients.add(Client(20, "John Wright")) repoClients.add(Client(40, "Andrei Ivan")) repoClients.update(Client(40, "New")) assert(repoClients.get_all()[1].clientName == "New")
def get_commit_log(git_repo, viewvc_url, author_in_commit_body=False): repo = Repo(git_repo) log = repo.commits(config.BODY_REGEX, search_body=author_in_commit_body) for commit in log[:]: author_match = re.search(config.AUTHOR_REGEX, commit.author) if author_match: commit.stripped_author = author_match.group('name') else: body_match = re.search(config.AUTHOR_REGEX, commit.body) if not body_match: raise Exception( "Unable to determine original author of commit " + commit.sha) guessed_author = body_match.group('name') commit.stripped_author = guessed_author commit.viewvc = viewvc_url.format(rev=commit.sha) return log
def get_commit_log(git_repo): is_v8 = 'v8' in git_repo repo = Repo(git_repo) log = repo.commits(is_v8) for commit in log: m = re.search(r'git-svn-id: ([^\s]+)', commit.body) if not m: # Found nothing! raise Exception("Didn't find git-svn-id in the commit body! Rev {0}" "".format(commit.sha)) id = m.group(1) if is_v8: # e.g. https://v8.googlecode.com/svn/branches/bleeding_edge@18761 m2 = re.match(r'https://v8.googlecode.com/svn/([^/]+)/[^@]*@(\d+)', id) m3 = re.search('(Contributed|Patch) (from|by) [^<]*<(?P<name>[^@]+)@opera\.com>', commit.body) if not m3: raise Exception("Didn't find opera employee in commit msg ({})".format(commit.body)) author = m3.group('name') else: # e.g. svn://svn.chromium.org/blink/trunk@165617 m2 = re.match(r'svn://svn.chromium.org/([^/]+)/[^@]*@(\d+)', id) author = commit.author.replace('@opera.com', '') if not m2: # Found nothing! raise Exception("Didn't find product and revision in the svn URL! " "URL {0}, rev {1}.".format(id, commit.sha)) commit.product = m2.group(1) commit.svn_revision = m2.group(2) if is_v8: commit.viewvc = ( "https://code.google.com/p/v8/source/detail?r={rev}" .format(rev=commit.svn_revision) ) else: commit.viewvc = ( "http://src.chromium.org/viewvc/{prod}?revision={rev}&" "view=revision" .format(prod=commit.product, rev=commit.svn_revision) ) commit.author_stripped = author return log
def test_add_book(self): repoBooks = Repo("Repobooks:") repoBooks.add(Book(1, "The Secret Crusade", "Oliver Bowden")) repoBooks.add(Book(2, "The Illustrated Man", "Ray Bradbury")) self.assertRaises(RepositoryError, lambda:repoBooks.add(Book(1, None, None))) assert(repoBooks.size() == 2) assert(repoBooks.get_all()[0].bookID == 1) assert(repoBooks.get_all()[1].bookID == 2) assert(repoBooks.get_all()[0].bookTitle == "The Secret Crusade") assert(repoBooks.get_all()[1].bookTitle == "The Illustrated Man") assert(repoBooks.get_all()[0].bookAuthor == "Oliver Bowden") assert(repoBooks.get_all()[1].bookAuthor == "Ray Bradbury")
def get_commit_log(git_repo, viewvc_url, author_in_commit_body=False): repo = Repo(git_repo) log = repo.commits(config.BODY_REGEX, search_body=author_in_commit_body) for commit in log[:]: author_match = re.search(config.AUTHOR_REGEX, commit.author) if author_match: commit.stripped_author = author_match.group('name') else: body_match = re.search(config.AUTHOR_REGEX, commit.body) if not body_match: # Might be someone at Vewd calling themselves Opera by mistake # in the code review system. The regexps differ in that one # checks with <email> and the other do not so there is no # guarantee that both hits. continue guessed_author = body_match.group('name') commit.stripped_author = guessed_author commit.viewvc = viewvc_url.format(rev=commit.sha) return log
def test_add_client(self): repoClients = Repo("Repoclients:") repoClients.add(Client(20, "John Wright")) repoClients.add(Client(40, "Andrei Ivan")) assert(repoClients.size() == 2) assert(repoClients.get_all()[0].clientID == 20) assert(repoClients.get_all()[1].clientID == 40) assert(repoClients.get_all()[0].clientName == "John Wright") assert(repoClients.get_all()[1].clientName == "Andrei Ivan")
def test_search_book(self): repoBooks = Repo("Repobooks:") repoBooks.add(Book(1, "Title11", "Title12")) repoBooks.add(Book(2, "Title21", "Title22")) self.assertRaises(RepositoryError, lambda:repoBooks.search(Book(4, None, None))) b = repoBooks.search(Book(1, None, None)) assert(b.bookTitle == "Title11") assert(b.bookAuthor == "Title12")
def returnABook(commandInPieces): repoCaller = Repo() idBook = commandInPieces[1] idClient = commandInPieces[2] returnDateString = commandInPieces[3].split('/') returnDate = datetime.datetime(int(returnDateString[0]), int(returnDateString[1]), int(returnDateString[2])) listOfRentedBooks = repoCaller.getListOfRentals() for iterator in listOfRentedBooks: if Rental.getBookId(iterator) == idBook and Rental.getClientId( iterator) == idClient: Rental.setReturnDate(iterator, returnDate) repoCaller.loadIntoFiles() repoCaller.loadIntoPickle() return False
def performUndo(null): repoCaller = Repo() indexOfOperations = repoCaller.getIndexOfOperations() listOfOperations = repoCaller.getListOfOperations() commands = { "removeB": removeABook, "removeC": removeAClient, "addB": addABook, "addC": addAClient, "updateB": updateABook, "updateC": updateAClient } if indexOfOperations >= 0: commands[Undo.getFuntion(listOfOperations[indexOfOperations])]( Undo.getParameters(listOfOperations[indexOfOperations])) repoCaller.decrementIndex() repoCaller.setRedoTrue() else: return "Cannot undo anymore" return False
def rentABook(commandInPieces): repoCaller = Repo() ghostBook = Book(commandInPieces[1], " ", " ") ghostClient = Client(commandInPieces[2], " ") rentDateString = commandInPieces[3].split('/') rentDate = datetime.datetime(int(rentDateString[0]), int(rentDateString[1]), int(rentDateString[2])) try: validateRental(ghostBook, ghostClient) newRental = Rental("1", Book.getBookId(ghostBook), Client.getClientId(ghostClient), rentDate, "notReturned") repoCaller.insertIntoRentals(newRental) repoCaller.loadIntoFiles() repoCaller.loadIntoPickle() except BookAlreadyRentedOrDoesntExistError: print(BookAlreadyRentedOrDoesntExistError()) except ClientAlreadyExistsError: print(ClientAlreadyExistsError()) return False
def performRedo(null): repoCaller = Repo() listOfOperations = repoCaller.getListOfOperations() canRedo = repoCaller.getRedoState() if canRedo == True: repoCaller.incrementIndex() index = repoCaller.getIndexOfOperations() commands = { "removeB": addABook, "removeC": addAClient, "addB": removeABook, "addC": removeAClient, "updateB": updateABook, "updateC": updateAClient } if "update" in Undo.getFuntion(listOfOperations[index]): commands[Undo.getFuntion(listOfOperations[index])]( Undo.getParametersUpdate(listOfOperations[index])) else: commands[Undo.getFuntion(listOfOperations[index])]( Undo.getParameters(listOfOperations[index])) return False
def removeABook(commandInPieces): # removes a book from the repository # input - details about the book to be removed (id) repoCaller = Repo() listOfBooks = repoCaller.getListOfBooks() idToRemove = commandInPieces[1] position = 0 removed = False for iterator in listOfBooks: if Book.getBookId(iterator) == idToRemove: if commandInPieces[0] != "undo": undoFunction = Undo("addB", [ "undo", Book.getBookId(iterator), Book.getBookName(iterator), Book.getBookAuthor(iterator) ]) repoCaller.addToListOfOperations(undoFunction) repoCaller.setRedoFalse() repoCaller.removeBookFromPosition(position) repoCaller.loadIntoFiles() repoCaller.loadIntoPickle() removed = True position += 1 if removed == False: print(IdOfBookDoesntExist()) return False
def addABook(commandInPieces): # adds a book to the repository # input - details about the book as a list bookId = commandInPieces[1] repoCaller = Repo() bookTitle = commandInPieces[2] bookAuthor = commandInPieces[3] newBook = Book(bookId, bookTitle, bookAuthor) undoFunction = Undo("removeB", ["undo", bookId, bookTitle, bookAuthor]) if commandInPieces[0] != "undo": repoCaller.addToListOfOperations(undoFunction) repoCaller.setRedoFalse() try: validateABook(newBook) repoCaller.addTheBookToTheRepo(newBook) repoCaller.loadIntoFiles() repoCaller.loadIntoPickle() except BookAlreadyExistsError: print(str(BookAlreadyExistsError())) return False
def showStatistics(null): repoCaller = Repo() listOfRentedBooks = repoCaller.getListOfRentals() mostRentedBooks = repoCaller.getListOfMostRentedBooks() mostRentedAuthors = repoCaller.getListOfMostRentedAuthors() mostActiveClients = repoCaller.getListOfMostActiveClients() listOfBooks = repoCaller.getListOfBooks() listOfClients = repoCaller.getListOfClients() booksStatistics = "Books statistic:\n" authorStatistics = "Author statistics:\n" clientsStatistics = "Clients statistics:\n" for rentedBooks in listOfRentedBooks: try: mostRentedAuthors[Rental.getBookId(rentedBooks)] += 1 except KeyError: mostRentedAuthors[Rental.getBookId(rentedBooks)] = 1 for rentedBooks in listOfRentedBooks: try: mostRentedBooks[Rental.getBookId(rentedBooks)] += 1 except KeyError: mostRentedBooks[Rental.getBookId(rentedBooks)] = 1 mostRentedAuthorsList = sorted(mostRentedAuthors.items(), key=lambda x: x[1], reverse=True) mostRentedBooksList = sorted(mostRentedBooks.items(), key=lambda x: x[1], reverse=True) for rentedBooks in mostRentedBooksList: booksStatistics += "Id of book: " + str( rentedBooks[0]) + " Rented: " + str( rentedBooks[1]) + " times" + "\n" for rentedBooks in mostRentedAuthorsList: for books in listOfBooks: if (Book.getBookId(books) == rentedBooks[0]): authorStatistics += "Author: " + str( Book.getBookAuthor(books)) + " Rented: " + str( rentedBooks[1]) + " times" + "\n" for client in listOfClients: total = 0 for rent in listOfRentedBooks: if Client.getClientId(client) == Rental.getClientId( rent) and rent.getReturnDate() != "notReturned": difference = Rental.getReturnDate(rent) - Rental.getRentDate( rent) total += difference.total_seconds() / 86400 try: mostActiveClients[Client.getClientName(client)] += total except KeyError: repoCaller.addToMostActiveClients(client, total) mostActiveClientsList = sorted(mostActiveClients.items(), key=lambda x: x[1], reverse=True) for client in mostActiveClientsList: clientsStatistics += "Name: " + str( client[0]) + " Total rental days: " + str(client[1]) + "\n" return [booksStatistics, authorStatistics, clientsStatistics]
def main(): repo = Repo() repo.readInputMethod() while True: commands = { "addbook": addABook, "addclient": addAClient, "listclients": listAllClients, "listbooks": listAllBooks, "removebook": removeABook, "removeclient": removeAClient, "updateclient": updateAClient, "updatebook": updateABook, "rentbook": rentABook, "returnbook": returnABook, "listrented": listRentedBooks, "searchclient": searchAClient, "searchbook": searchABook, "showstatistics": showStatistics, "undo": performUndo, "redo": performRedo } print("Available commands: ") print(" 1. addbook ") print(" 2. addclient") print(" 3. listclients") print(" 4. listbooks") print(" 5. removeclient") print(" 6. removebook") print(" 7. updateclient") print(" 8. updatebook ") print(" 9. rentbook ") print(" 10. returnbook") print(" 11. listrented") print(" 12. searchclient [id/name]") print(" 13. searchbook [id/author/title]") print(" 14. showstatistics") print(" 15. undo") print(" 15. redo") command = input(">>>") if command == "1": command = [] id = input(">>[id] ") title = input(">>[title] ") author = input(">>[author] ") command.append("addbook") command.append(id) command.append(title) command.append(author) if command == "2": command = [] id = input(">>[id] ") name = input(">>[name] ") command.append(id) command.append(name) command.insert(0, "addclient") if command == "3": command = ["listclients"] if command == "4": command = ["listbooks"] if command == "5": command = [] id = input(">>[id] ") command.append(id) command.insert(0, "removeclient") if command == "6": command = [] id = input(">>[id] ") command.append(id) command.insert(0, "removebook") if command == "7": command = [] id = input(">>[old ID] ") newId = input(">>[new ID] ") newName = input(">>[new Name] ") command.append(id) command.append(newId) command.append(newName) command.insert(0, "updateclient") if command == "8": command = [] id = input(">>[old ID] ") newId = input(">>[new ID] ") newTitle = input(">>[new Title] ") newAuthor = input(">>[new Author] ") command.append(id) command.append(newId) command.append(newTitle) command.append(newAuthor) command.insert(0, "updatebook") if command == "9": command = [] bID = input(">>[book ID] ") cID = input(">>[client ID] ") rentDate = input(">>[rent date] (rent date format: dd/mm/yyyy)") command.append(bID) command.append(cID) command.append(rentDate) command.insert(0, "rentbook") if command == "10": command = [] bID = input(">>[book ID] ") cID = input(">>[client ID] ") returnDate = input( ">>[return date] (return date format: dd/mm/yyyy) ") command.append(bID) command.append(cID) command.append(returnDate) command.insert(0, "returnbook") if command == "11": command = ["listrented"] if command == "12": command = input(">>[id/name]>>") command = command.split(" ") command.insert(0, "searchclient") if command == "13": command = input(">>[id/name/author]>>") command = command.split(" ") command.insert(0, "searchbook") if command == "14": command = ["showstatistics"] if command == "15": command = ["undo"] if command == "16": command = ["redo"] try: output = commands[command[0]](command) if output != False: if len(output) == 3: print(output[0]) print(output[1]) print(output[2]) else: print(output) except KeyError: print("Invalid command")
def addAClient(commandInPieces): # adds a client to the repository # input - details about the client as a list repoCaller = Repo() clientId = commandInPieces[1] clientName = commandInPieces[2] undoFunction = Undo("removeC", ["undo", clientId, clientName]) if commandInPieces[0] != "undo": repoCaller.addToListOfOperations(undoFunction) repoCaller.setRedoFalse() newClient = Client(clientId, clientName) try: validateAClient(newClient) repoCaller.addTheClientToTheRepo(newClient) repoCaller.loadIntoFiles() repoCaller.loadIntoPickle() except ClientAlreadyExistsError: print(str(ClientAlreadyExistsError())) return False
def updateABook(commandInPieces): # updates a book from the repository # input - details about the book that must be updated(id) and the values that must be edited repoCaller = Repo() listOfBooks = repoCaller.getListOfBooks() idToUpdate = commandInPieces[1] newBookId = commandInPieces[2] newTitle = commandInPieces[3] newAuthor = commandInPieces[4] updatedBook = Book(newBookId, newTitle, newAuthor) position = 0 try: validateABook(updatedBook) for iterator in listOfBooks: if Book.getBookId(iterator) == idToUpdate: if commandInPieces[0] != "undo": undoFunction = Undo("updateB", [ "undo", newBookId, Book.getBookId(iterator), Book.getBookName(iterator), Book.getBookAuthor(iterator), "undo", idToUpdate, newBookId, newTitle, newAuthor ]) repoCaller.addToListOfOperations(undoFunction) repoCaller.setRedoFalse() repoCaller.removeBookFromPosition(position) repoCaller.insertBookIntoPosition(position, updatedBook) repoCaller.loadIntoFiles() repoCaller.loadIntoPickle() break position += 1 except BookAlreadyExistsError: print(BookAlreadyExistsError()) return False
def updateAClient(commandInPieces): # updates a client that is already in the repository # input - details about the client to be updated (id) and the values that must be edited repoCaller = Repo() listOfClients = repoCaller.getListOfClients() idToUpdate = commandInPieces[1] newId = commandInPieces[2] newName = commandInPieces[3] updatedClient = Client(newId, newName) position = 0 try: validateAClient(updatedClient) for iterator in listOfClients: if Client.getClientId(iterator) == idToUpdate: if commandInPieces[0] != "undo": undoFunction = Undo("updateC", [ "undo", newId, Client.getClientId(iterator), Client.getClientName(iterator), "undo", Client.getClientId(iterator), newId, newName ]) repoCaller.addToListOfOperations(undoFunction) repoCaller.setRedoFalse() repoCaller.removeClientFromPosition(position) repoCaller.insertClientIntoPosition(position, updatedClient) repoCaller.loadIntoFiles() repoCaller.loadIntoPickle() break position += 1 except ClientAlreadyExistsError: print(ClientAlreadyExistsError()) return False
def create(cls): cls.db = TinyDB('D:\\Mobile\\Server\\data\\db.json') cls.repo = Repo(cls.db) cls.userRepo = UserRepo(cls.db)
def removeAClient(commandInPieces): # removes a client from the repository # input - details about the client (id) repoCaller = Repo() idToRemove = commandInPieces[1] position = 0 removed = False for iterator in Repo.listOfClients: if Client.getClientId(iterator) == idToRemove: if commandInPieces[0] != "undo": undoFunction = Undo("addC", [ "undo", Client.getClientId(iterator), Client.getClientName(iterator) ]) repoCaller.addToListOfOperations(undoFunction) repoCaller.setRedoFalse() repoCaller.removeClientFromPosition(position) repoCaller.loadIntoFiles() repoCaller.loadIntoPickle() removed = True position += 1 if removed == False: print(IdOfClientDoesntExist()) return False