def initialize(): current_file_path = os.path.dirname(os.path.abspath(__file__)) project_root = os.path.abspath(os.path.join(current_file_path, '..', '..')) project_parent_path, _, parent_directory_name = project_root.rpartition( os.path.sep) os.chdir(project_root) sys.path.append(os.path.join(project_root, '_CI/library')) setdebug() return Project(parent_directory_name, project_root, project_parent_path)
def patch(self, diff): """ Apply patch data from 'diff' to the file at 'path'. 'diff' must contain unified diff data. """ patch.setdebug() patcher = patch.fromstring(diff) if not patcher.apply(): self.error("couldn't apply patch")
def execute(self, phase, patch_uri, build_args, **state): # Build our environment variables env = dict(os.environ) # Merge in extra env if 'env' in build_args: env.update(build_args['env']) # We need the actual source path to actually apply a patch if 'source' in state: src_path = state['source'] base_src = os.path.basename(src_path) status_path = os.path.join(state['patches_dir'], '{}.json'.format(base_src)) logs_path = os.path.join(state['logs_dir'], base_src) else: raise Exception('Unable to apply a patch without a source directory') # Load the status file status = get_status(status_path) if phase not in status or not status[phase]: os.makedirs(logs_path, exist_ok=True) with open(os.path.join(logs_path, '{}_{}.log'.format(base_src, phase)), 'w') as logfile: if is_sequence(patch_uri): patch_uris = patch_uri else: patch_uris = [patch_uri] errors = False for patch_uri in patch_uris: try: if patch_uri.startswith(('http', 'ftp')): cprint( indent('Applying patch from URL to "{}"'.format(base_src), 8), 'white', attrs=['bold'] ) logfile.write('Applying patch from URL "{}" to "{}"\n'.format(patch_uri, base_src)) pset = patch.fromurl(patch_uri) elif os.path.exists(patch_uri): cprint( indent('Applying patch from local file to "{}"'.format(base_src), 8), 'white', attrs=['bold'] ) logfile.write( 'Applying patch from local file "{}" to "{}"\n'.format(patch_uri, base_src) ) pset = patch.fromfile(patch_uri) else: cprint( indent('Applying patch from string to "{}"'.format(base_src), 8), 'white', attrs=['bold'] ) logfile.write('Applying patch from string "{}" to "{}"\n'.format(patch_uri, base_src)) # Strings have to be bytes encoded pset = patch.fromstring(patch_uri.encode('utf-8')) except: pset = False pass if not pset: errors = True cprint(indent('Failed to load patch "{}"'.format(patch_uri), 8), 'red', attrs=['bold']) root_folder = build_args.get('patch_root', src_path) patch.streamhandler = patch.logging.StreamHandler(stream=logfile) patch.setdebug() if pset and not pset.apply(root=root_folder): errors = True cprint( indent('Failed to apply patch "{}" to "{}"'.format(patch_uri, base_src), 8), 'red', attrs=['bold'] ) if errors: raise Exception('{} step for {} failed to apply patches'.format(phase, base_src)) else: status = update_status(status_path, {phase: True}) else: cprint( indent('{} step for {} complete... Skipping...'.format(phase, base_src), 8), 'yellow', attrs=['bold'] )
venv = subprocess.check_output('poetry env info --path', shell=True).decode() except subprocess.CalledProcessError: print('poetry not found, please add it to the environment variable PATH') sys.exit(1) if os.name == 'nt': venv = Path(venv) / 'Lib' elif os.name == 'posix': venv = Path(venv) / 'lib' / 'python{}.{}'.format(sys.version_info.major, sys.version_info.minor) else: print('Unknown OS {}'.format(os.name)) sys.exit(1) patchdir = os.path.dirname(os.path.abspath(__file__)) patchset = patch.fromfile(Path(patchdir) / 'robot.diff') try: ret = patchset.apply(root=venv) # ret = patchset.revert(root=venv) if not ret: print('Patching failed') raise AssertionError() except: print(sys.exc_info()) print('Debug log:') patch.setdebug() patchset.apply(root=venv) else: print('successfully patched')
def main(): import argparse tParser = argparse.ArgumentParser( description='Apply diffs and copy files to patch a source tree.') tParser.add_argument( '-w', '--working-folder', dest='strWorkingFolder', required=True, help='use PATH as the working folder', metavar='PATH' ) tParser.add_argument( '-p', '--patch-folder', dest='strPatchFolder', required=False, default=None, help='scan PATH for .diff files and apply them to the working folder', metavar='PATH' ) tParser.add_argument( '-s', '--strip', dest='uiStrip', required=False, default=0, metavar='N', type=int, help='strip N levels from the paths in all patch files' ) tParser.add_argument( '-c', '--copy-folder', dest='strCopyFolder', required=False, default=None, help='copy the contents of PATH recursively over the working folder', metavar='PATH' ) tParser.add_argument( '-l', '--copy-list', dest='strCopyList', required=False, default=None, help='process FILE as a list of SOURCE,DESTINATION entries of files to copy', metavar='PATH' ) aOptions = tParser.parse_args() print 'Using patch %s by %s.' % (patch.__version__, patch.__author__) # verbosity levels = logging.WARNING, logging.INFO, logging.DEBUG logformat = "%(message)s" patch.logger.setLevel(logging.DEBUG) patch.streamhandler.setFormatter(logging.Formatter(logformat)) patch.setdebug() # Check if the working folder exists. if os.path.exists(aOptions.strWorkingFolder) != True: raise Exception( 'The working folder "%s" does not exist or is not accessible.' % aOptions.strWorkingFolder ) if os.path.isdir(aOptions.strWorkingFolder) != True: raise Exception( 'The working folder "%s" is no folder.' % aOptions.strWorkingFolder ) # Is the patch folder defined? if aOptions.strPatchFolder is not None: if os.path.exists(aOptions.strPatchFolder) != True: raise Exception( 'The patch folder "%s" does not exist or is not accessible.' % aOptions.strPatchFolder ) if os.path.isdir(aOptions.strPatchFolder) != True: raise Exception( 'The patch folder "%s" is no folder.' % aOptions.strPatchFolder ) apply_diffs(aOptions.strWorkingFolder, aOptions.strPatchFolder, aOptions.uiStrip) # Is the copy folder defined? if aOptions.strCopyFolder is not None: if os.path.exists(aOptions.strCopyFolder) != True: raise Exception( 'The copy folder "%s" does not exist or is not accessible.' % aOptions.strCopyFolder ) if os.path.isdir(aOptions.strCopyFolder) != True: raise Exception( 'The copy folder "%s" is no folder.' % aOptions.strCopyFolder ) copy_files(aOptions.strWorkingFolder, aOptions.strCopyFolder) # Is the copy list defined? if aOptions.strCopyList is not None: if os.path.exists(aOptions.strCopyList) != True: raise Exception( 'The copy list "%s" does not exist or is not accessible.' % aOptions.strCopyList ) if os.path.isfile(aOptions.strCopyList) != True: raise Exception( 'The copy list "%s" is no regular file.' % aOptions.strCopyList ) copy_list(aOptions.strWorkingFolder, aOptions.strCopyList)