1# -*- coding: utf-8 -*- 2 3# Copyright(C) 2010-2012 Nicolas Duhamel, Laurent Bachelier 4# 5# This file is part of weboob. 6# 7# weboob is free software: you can redistribute it and/or modify 8# it under the terms of the GNU Lesser General Public License as published by 9# the Free Software Foundation, either version 3 of the License, or 10# (at your option) any later version. 11# 12# weboob is distributed in the hope that it will be useful, 13# but WITHOUT ANY WARRANTY; without even the implied warranty of 14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15# GNU Lesser General Public License for more details. 16# 17# You should have received a copy of the GNU Lesser General Public License 18# along with weboob. If not, see <http://www.gnu.org/licenses/>. 19from copy import copy 20from posixpath import sep, join 21 22from .compat import StrConv, unicode 23 24 25class WorkingPath(StrConv, object): 26 def __init__(self): 27 self.split_path = [] 28 self.previous = copy(self.split_path) 29 30 def cd1(self, user_input): 31 """ 32 Append *one* level to the current path. 33 This means that separators (/) will get escaped. 34 """ 35 split_path = self.get() 36 split_path.append(user_input) 37 self.location(split_path) 38 39 def location(self, split_path): 40 """ 41 Go to a new path, and store the previous path. 42 """ 43 self.previous = self.get() 44 self.split_path = split_path 45 46 def restore(self): 47 """ 48 Go to the previous path 49 """ 50 self.split_path, self.previous = self.previous, self.split_path 51 52 def home(self): 53 """ 54 Go to the root 55 """ 56 self.location([]) 57 58 def up(self): 59 """ 60 Go up one directory 61 """ 62 self.location(self.split_path[:-1]) 63 64 def get(self): 65 """ 66 Get the current working path 67 """ 68 return copy(self.split_path) 69 70 def __unicode__(self): 71 return join(sep, *[s.replace(u'/', u'\/') for s in self.split_path]) 72 73 74def test(): 75 wp = WorkingPath() 76 assert wp.get() == [] 77 assert unicode(wp) == u'/' 78 wp.cd1(u'lol') 79 assert wp.get() == [u'lol'] 80 assert unicode(wp) == u'/lol' 81 wp.cd1(u'cat') 82 assert wp.get() == [u'lol', u'cat'] 83 assert unicode(wp) == u'/lol/cat' 84 wp.restore() 85 assert unicode(wp) == u'/lol' 86 wp.home() 87 assert wp.get() == [] 88 assert unicode(wp) == u'/' 89 wp.up() 90 assert wp.get() == [] 91 assert unicode(wp) == u'/' 92 wp.location(['aa / aa', 'bbbb']) 93 assert unicode(wp) == u'/aa \/ aa/bbbb' 94 wp.up() 95 assert unicode(wp) == u'/aa \/ aa' 96 wp.cd1(u'héhé/hé') 97 assert unicode(wp) == u'/aa \/ aa/héhé\/hé' 98