@@ -64,8 +64,9 @@ class Git:
6464 A single parent class containing all of the individual git methods in it.
6565 """
6666
67- def __init__ (self , root_dir ):
68- self .root_dir = os .path .expanduser (root_dir )
67+ def __init__ (self , contents_manager ):
68+ self .contents_manager = contents_manager
69+ self .root_dir = os .path .realpath (os .path .expanduser (contents_manager .root_dir ))
6970
7071 def config (self , top_repo_path , ** kwargs ):
7172 """Get or set Git options.
@@ -892,3 +893,58 @@ def _get_tag(self, current_path, commit_sha):
892893 error .decode ("utf-8" ), " " .join (command )
893894 )
894895 )
896+
897+ def show (self , filename , ref , top_repo_path ):
898+ """
899+ Execute git show<ref:filename> command & return the result.
900+ """
901+ command = ["git" , "show" , '{}:{}' .format (ref , filename )]
902+ p = subprocess .Popen (
903+ command ,
904+ stdout = PIPE ,
905+ stderr = PIPE ,
906+ cwd = top_repo_path
907+ )
908+ output , error = p .communicate ()
909+
910+ error_messages = map (lambda n : n .lower (), [
911+ "fatal: Path '{}' exists on disk, but not in '{}'" .format (filename , ref ),
912+ "fatal: Path '{}' does not exist (neither on disk nor in the index)" .format (filename )
913+ ])
914+ lower_error = error .decode ('utf-8' ).lower ()
915+ if p .returncode == 0 :
916+ return output .decode ('utf-8' )
917+ elif any ([msg in lower_error for msg in error_messages ]):
918+ return ""
919+ else :
920+ raise Exception ('Error [{}] occurred while executing [{}] command to retrieve plaintext diff.' .format (
921+ error .decode ('utf-8' ),
922+ ' ' .join (command )
923+ ))
924+
925+ def get_content (self , filename , top_repo_path ):
926+ """
927+ Get the file content of filename.
928+ """
929+ relative_repo = os .path .relpath (top_repo_path , self .root_dir )
930+ model = self .contents_manager .get (path = os .path .join (relative_repo , filename ))
931+ return model ['content' ]
932+
933+ def diff_content (self , filename , prev_ref , curr_ref , top_repo_path ):
934+ """
935+ Collect get content of prev and curr and return.
936+ """
937+ try :
938+ prev_content = self .show (filename , prev_ref ["git" ], top_repo_path )
939+ if "special" in curr_ref :
940+ if curr_ref ["special" ] == "WORKING" :
941+ curr_content = self .get_content (filename , top_repo_path )
942+ elif curr_ref ["special" ] == "INDEX" :
943+ curr_content = self .show (filename , "" , top_repo_path )
944+ else :
945+ raise Exception ("Error while retrieving plaintext diff, unknown special ref '{}'." .format (curr_ref ["specialref" ]))
946+ else :
947+ curr_content = self .show (filename , curr_ref ["git" ], top_repo_path )
948+ return {"prev_content" : prev_content , "curr_content" : curr_content }
949+ except :
950+ raise
0 commit comments