David Brazdil | 2c27f2c | 2015-05-12 18:06:38 +0100 | [diff] [blame^] | 1 | # Copyright (C) 2014 The Android Open Source Project |
| 2 | # |
| 3 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | # you may not use this file except in compliance with the License. |
| 5 | # You may obtain a copy of the License at |
| 6 | # |
| 7 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | # |
| 9 | # Unless required by applicable law or agreed to in writing, software |
| 10 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | # See the License for the specific language governing permissions and |
| 13 | # limitations under the License. |
| 14 | |
| 15 | def SplitStream(stream, fnProcessLine, fnLineOutsideChunk): |
| 16 | """ Reads the given input stream and splits it into chunks based on |
| 17 | information extracted from individual lines. |
| 18 | |
| 19 | Arguments: |
| 20 | - fnProcessLine: Called on each line with the text and line number. Must |
| 21 | return a pair, name of the chunk started on this line and data extracted |
| 22 | from this line (or None in both cases). |
| 23 | - fnLineOutsideChunk: Called on attempt to attach data prior to creating |
| 24 | a chunk. |
| 25 | """ |
| 26 | lineNo = 0 |
| 27 | allChunks = [] |
| 28 | currentChunk = None |
| 29 | |
| 30 | for line in stream: |
| 31 | lineNo += 1 |
| 32 | line = line.strip() |
| 33 | if not line: |
| 34 | continue |
| 35 | |
| 36 | # Let the child class process the line and return information about it. |
| 37 | # The _processLine method can modify the content of the line (or delete it |
| 38 | # entirely) and specify whether it starts a new group. |
| 39 | processedLine, newChunkName = fnProcessLine(line, lineNo) |
| 40 | if newChunkName is not None: |
| 41 | currentChunk = (newChunkName, [], lineNo) |
| 42 | allChunks.append(currentChunk) |
| 43 | if processedLine is not None: |
| 44 | if currentChunk is not None: |
| 45 | currentChunk[1].append(processedLine) |
| 46 | else: |
| 47 | fnLineOutsideChunk(line, lineNo) |
| 48 | return allChunks |