Last active
March 25, 2020 04:27
-
-
Save lourot/5946b81640dfcfb37b1f to your computer and use it in GitHub Desktop.
tree4streams.py, 'p4 streams' as tree - Calls 'p4 streams', parses the output, and prints all streams as a tree.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import shlex | |
import StringIO | |
import subprocess | |
class P4Stream: | |
def __init__(self, parent_name=None): | |
self.parent_name = parent_name | |
self.children_names = set() # will be initialized when the whole tree is known | |
class P4StreamTree: | |
def __init__(self): | |
self.__streams = {} # all streams known | |
self.__root_stream_names = set() # all streams without parent known | |
self.__immutable = False | |
def __str__(self): | |
if not self.__immutable: | |
raise RuntimeError('Tree shall be built first') | |
result = '' | |
for root_stream_name in sorted(self.__root_stream_names): | |
result += self.__stream_and_its_children_to_string(root_stream_name) | |
return result | |
def add_stream(self, stream_name, parent_stream_name): | |
if self.__immutable: | |
raise RuntimeError('Tree is immutable') | |
child_stream = P4Stream(parent_stream_name if parent_stream_name != 'none' else None) | |
self.__streams[stream_name] = child_stream | |
if parent_stream_name == 'none': | |
self.__root_stream_names.add(stream_name) | |
def build(self): | |
"""Initializes the links parent -> child. Afterwards, the tree will be immutable. | |
""" | |
self.__immutable = True | |
for child_stream_name, child_stream in self.__streams.iteritems(): | |
parent_stream_name = child_stream.parent_name | |
if parent_stream_name is not None: | |
self.__streams[parent_stream_name].children_names.add(child_stream_name) | |
def __stream_and_its_children_to_string(self, stream_name, indentation=0): | |
result = '%s%s\n' % (' ' * indentation, stream_name) | |
indentation += 2 | |
for child_stream_name in sorted(self.__streams[stream_name].children_names): | |
result += self.__stream_and_its_children_to_string(child_stream_name, indentation) | |
return result | |
def _main(): | |
"""Calls 'p4 stream', parses the output, and prints all streams as a tree. | |
""" | |
p4_streams = subprocess.check_output(shlex.split('p4 streams')) | |
tree = P4StreamTree() | |
for line in StringIO.StringIO(p4_streams): | |
# Such a line looks like | |
# "Stream //my-depot/my-child-stream type //my-depot/my-parent-stream 'description'" | |
info = line.split() | |
tree.add_stream(info[1], info[3]) | |
tree.build() | |
print(tree) | |
if __name__ == "__main__": | |
_main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment