#NEWLINE# def _apply_patch( source , patch_text , forwards , name ) : #NEWLINE# #INDENT# try : #NEWLINE# #INDENT# return _patching_cache . retrieve ( source , patch_text , forwards ) #NEWLINE# #UNINDENT# except KeyError : #NEWLINE# #INDENT# pass #NEWLINE# #UNINDENT# tempdir = mkdtemp ( prefix = 'patchy' ) #NEWLINE# try : #NEWLINE# #INDENT# source_path = os . path . join ( tempdir , ( name + '.py' ) ) #NEWLINE# with open ( source_path , 'w' ) as source_file : #NEWLINE# #INDENT# source_file . write ( source ) #NEWLINE# #UNINDENT# patch_path = os . path . join ( tempdir , ( name + '.patch' ) ) #NEWLINE# with open ( patch_path , 'w' ) as patch_file : #NEWLINE# #INDENT# patch_file . write ( patch_text ) #NEWLINE# if ( not patch_text . endswith ( '\n' ) ) : #NEWLINE# #INDENT# patch_file . write ( '\n' ) #NEWLINE# #UNINDENT# #UNINDENT# command = [ 'patch' ] #NEWLINE# if ( not forwards ) : #NEWLINE# #INDENT# command . append ( '--reverse' ) #NEWLINE# #UNINDENT# command . extend ( [ source_path , patch_path ] ) #NEWLINE# proc = subprocess . Popen ( command , stderr = subprocess . PIPE , stdout = subprocess . PIPE ) #NEWLINE# ( stdout , stderr ) = proc . communicate ( ) #NEWLINE# if ( proc . returncode != 0 ) : #NEWLINE# #INDENT# msg = "Could not {action} the patch {prep} '{name}'." . format ( action = ( 'apply' if forwards else 'unapply' ) , prep = ( 'to' if forwards else 'from' ) , name = name ) #NEWLINE# if ( stdout or stderr ) : #NEWLINE# #INDENT# msg += ' The message from `patch` was:\n{}\n{}' . format ( stdout . decode ( 'utf-8' ) , stderr . decode ( 'utf-8' ) ) #NEWLINE# #UNINDENT# msg += '\nThe code to patch was:\n{}\nThe patch was:\n{}' . format ( source , patch_text ) #NEWLINE# raise ValueError ( msg ) #NEWLINE# #UNINDENT# with open ( source_path , 'r' ) as source_file : #NEWLINE# #INDENT# new_source = source_file . read ( ) #NEWLINE# #UNINDENT# #UNINDENT# finally : #NEWLINE# #INDENT# shutil . rmtree ( tempdir ) #NEWLINE# #UNINDENT# _patching_cache . store ( source , patch_text , forwards , new_source ) #NEWLINE# return new_source