Design Pattern Examples
Overview of object-oriented design patterns
composite_fileaccess.py
Go to the documentation of this file.
6
7from .composite_filedirentry import FileDirEntry, FileDirEntryList, FileEntry, DirEntry
8from datetime import datetime
9
10
16
18
19 # ! [Python Composite_FileAccess directory tree]
20 _rootEntry = \
21 DirEntry("root", datetime.now(), [ \
22 FileEntry("FileA.txt", 101, datetime.now()),
23 FileEntry("FileB.txt", 102, datetime.now()),
24 FileEntry("FileC.txt", 103, datetime.now()),
25 DirEntry("subdir1", datetime.now(), [ \
26 FileEntry("FileD.txt", 104, datetime.now()),
27 FileEntry("FileE.txt", 105, datetime.now()),
28 DirEntry("subdir2", datetime.now(), [ \
29 FileEntry("FileF.txt", 106, datetime.now()),
30 FileEntry("FileG.txt", 107, datetime.now())
31 ]),
32 ]),
33 ])
34 # ! [Python Composite_FileAccess directory tree]
35
36
37
45 def _FindEntry(filepath : str) -> FileDirEntry:
46 root = Composite_FileAccess._rootEntry # type: FileDirEntry
47 found = False
48
49 pathComponents = filepath.split('/')
50 numComponents = len(pathComponents)
51 for index in range(0, numComponents):
52 found = False
53 if root.Name != pathComponents[index]:
54 # Mismatch in path to this entry, bad path
55 root = None
56 break
57
58 if index + 1 >= numComponents:
59 # Reached end of path so we found what was asked for.
60 found = True
61 break
62
63 # Still haven't reached end of specified path, look at
64 # the current root for children.
65
66 children = root.Children
67 if not children:
68 # Path included leaf in the middle, bad path
69 found = False
70 break
71
72 root = None # assume we won't find anything
73 # Look ahead in the path for a matching child.
74 childComponent = pathComponents[index + 1] # type: str
75 for child in children:
76 if childComponent == child.Name:
77 root = child
78 found = True
79 break
80 if not found:
81 # Couldn't find matching child, bad path
82 break
83 return root
84
85
86
98 def GetEntry(filepath : str) -> FileDirEntry:
99 filepath = filepath.replace('\\', '/')
100 fileDirEntry = Composite_FileAccess._FindEntry(filepath)
101 if not fileDirEntry:
102 raise FileNotFoundError(2, "Unable to find entry", filepath)
103
104 return fileDirEntry
Class containing static functions for accessing a hardcoded "file" and "directory" hierarchy.
FileDirEntry _FindEntry(str filepath)
Helper method to search the static data list for the specified file/dir entry.
FileDirEntry GetEntry(str filepath)
Retrieve a FileDirEntry object representing the specified file "path" in an internal list of data ent...
Represents a Directory entry.
Represents a File entry.