Browse Source

Ensure reading is done in one place only

Instead of having reading being split across the lines_iter
method and the raw_content property just have it occur in
a common function so that it can be done once and only once.

Change-Id: I603bc4e85ad489d5397a78d6c987e15a0515f7ea
Joshua Harlow 4 years ago
parent
commit
beed9aa8b8
1 changed files with 16 additions and 6 deletions
  1. 16
    6
      doc8/parser.py

+ 16
- 6
doc8/parser.py View File

@@ -16,6 +16,7 @@
16 16
 
17 17
 import errno
18 18
 import os
19
+import threading
19 20
 
20 21
 import chardet
21 22
 from docutils import frontend
@@ -36,7 +37,9 @@ class ParsedFile(object):
36 37
         self._doc = None
37 38
         self._errors = None
38 39
         self._lines = None
40
+        self._has_read = False
39 41
         self._extension = os.path.splitext(filename)[1]
42
+        self._read_lock = threading.Lock()
40 43
 
41 44
     @property
42 45
     def errors(self):
@@ -72,10 +75,19 @@ class ParsedFile(object):
72 75
             self._doc = doc
73 76
         return self._doc
74 77
 
78
+    def _read(self):
79
+        if self._has_read:
80
+            return
81
+        with self._read_lock:
82
+            if not self._has_read:
83
+                with open(self.filename, 'rb') as fh:
84
+                    self._lines = list(fh)
85
+                    fh.seek(0)
86
+                    self._raw_content = fh.read()
87
+                self._has_read = True
88
+
75 89
     def lines_iter(self, remove_trailing_newline=True):
76
-        if self._lines is None:
77
-            with open(self.filename, 'rb') as fh:
78
-                self._lines = list(fh)
90
+        self._read()
79 91
         for line in self._lines:
80 92
             line = six.text_type(line, encoding=self.encoding)
81 93
             if remove_trailing_newline and line.endswith("\n"):
@@ -101,9 +113,7 @@ class ParsedFile(object):
101 113
 
102 114
     @property
103 115
     def raw_contents(self):
104
-        if self._raw_content is None:
105
-            with open(self.filename, 'rb') as fh:
106
-                self._raw_content = fh.read()
116
+        self._read()
107 117
         return self._raw_content
108 118
 
109 119
     @property

Loading…
Cancel
Save