Beispiel #1
0
def run_pop(args):
    number = stop_at_patch = None
    patchfns.chdir_to_base_dir()
    if args.patchnamornum:
        if args.patchnamornum.isdigit():
            number = int(args.patchnamornum)
        else:
            stop_at_patch = patchfns.find_applied_patch(args.patchnamornum)
            if not stop_at_patch:
                return cmd_result.ERROR
    elif not args.opt_all:
        number = 1
    silent = args.opt_quiet
    if patchfns.top_patch_needs_refresh() and not args.opt_force:
        output.error('The topmost patch %s needs to be refreshed first.\n' % patchfns.print_top_patch())
        return cmd_result.ERROR | cmd_result.SUGGEST_FORCE_OR_REFRESH
    patches = list_patches(number=number, stop_at_patch=stop_at_patch)
    if not patches:
        output.error('No patch removed\n')
        return cmd_result.ERROR
    is_ok = True
    for patch in patches:
        result = remove_patch(patch, force=args.opt_force, check=args.opt_remove, silent=silent)
        if result is not True:
            return cmd_result.ERROR if result is False else result
        if not args.opt_quiet:
            output.write('\n')
    if not patchfns.top_patch():
        output.write('No patches applied\n')
    else:
        output.write('Now at patch %s\n' % patchfns.print_top_patch())
    return cmd_result.OK if is_ok is True else cmd_result.ERROR
Beispiel #2
0
def set_file_contents(filename, text):
    '''
    Set the contents of filename to text after applying compression
    as indicated by filename's suffix.
    '''
    _root, ext = os.path.splitext(filename)
    res = 0
    if ext == '.gz':
        try:
            gzip.open(filename, 'wb').write(text)
            return True
        except (IOError, zlib.error):
            return False
    elif ext == '.bz2':
        try:
            bz2f = bz2.BZ2File(filename, 'w')
            text = bz2f.write(text)
            bz2f.close()
            return True
        except IOError:
            return False
    elif ext == '.xz':
        res, text, serr = shell.run_cmd('xz -c', text)
    elif ext == '.lzma':
        res, text, serr = shell.run_cmd('lzma -c', text)
    if res != 0:
        output.error(serr)
        return False
    try:
        open(filename, 'w').write(text)
    except IOError:
        return False
    return True
Beispiel #3
0
def run_fork(args):
    patchfns.chdir_to_base_dir()
    top_patch = patchfns.find_top_patch()
    if not top_patch:
        return cmd_result.ERROR
    new_patch = args.arg_new_name if args.arg_new_name else patchfns.next_filename(top_patch)
    new_patch_file = patchfns.patch_file_name(new_patch)
    new_patch_dir = os.path.join(patchfns.QUILT_PC, new_patch)
    if patchfns.patch_in_series(new_patch) or os.path.isdir(new_patch_dir) or os.path.exists(new_patch_file):
        output.error('Patch %s exists already, please choose a new name\n' % patchfns.print_patch(new_patch))
        return cmd_result.ERROR | cmd_result.SUGGEST_RENAME
    is_ok = patchfns.rename_in_db(top_patch, new_patch)
    is_ok = is_ok if not is_ok else patchfns.rename_in_series(top_patch, new_patch)
    if is_ok:
        top_patch_dir = os.path.join(patchfns.QUILT_PC, top_patch)
        try:
            os.rename(top_patch_dir, new_patch_dir)
        except OSError:
            is_ok = False
    if is_ok:
        top_patch_file = patchfns.patch_file_name(top_patch)
        if os.path.exists(top_patch_file):
            try:
                shutil.copy2(top_patch_file, new_patch_file)
            except Exception:
                is_ok = False
    if not is_ok:
        output.write('Fork of patch %s to patch %s failed\n' % (patchfns.print_patch(top_patch), patchfns.print_patch(new_patch)))
    else:
        output.error('Fork of patch %s created as %s\n' % (patchfns.print_patch(top_patch), patchfns.print_patch(new_patch)))
    return cmd_result.OK if is_ok else cmd_result.ERROR
Beispiel #4
0
def run_rename(args):
    patchfns.chdir_to_base_dir()
    patch = patchfns.find_patch_in_series(args.opt_patch)
    if not patch:
        return cmd_result.ERROR
    new_patch = patchfns.patch_name_base(args.new_name)
    new_patch_exists = patchfns.patch_in_series(new_patch)
    new_patch_exists = True if new_patch_exists else os.path.isdir(os.path.join(patchfns.QUILT_PC, new_patch))
    new_patch_exists = True if new_patch_exists else os.path.exists(patchfns.patch_file_name(new_patch))
    if new_patch_exists:
        output.error('Patch %s exists already, please choose a different name\n' % patchfns.print_patch(new_patch))
        return cmd_result.ERROR
    is_ok = True
    if patchfns.is_applied(patch):
        is_ok = patchfns.rename_in_db(patch, new_patch)
        if is_ok:
            is_ok = move_file(os.path.join(patchfns.QUILT_PC, patch), os.path.join(patchfns.QUILT_PC, new_patch))
    if is_ok:
        is_ok = patchfns.rename_in_series(patch, new_patch)
        if is_ok and os.path.exists(patchfns.patch_file_name(patch)):
            is_ok = move_file(patchfns.patch_file_name(patch), patchfns.patch_file_name(new_patch))
    if is_ok:
        output.write('Patch %s renamed to %s\n' % (patchfns.print_patch(patch), patchfns.print_patch(new_patch)))
        return cmd_result.OK
    else:
        output.error('Renaming of patch %s to %s failed\n' % (patchfns.print_patch(patch), patchfns.print_patch(new_patch)))
        return cmd_result.ERROR
Beispiel #5
0
def remove_patch(patch, force, check, silent):
    try:
        status = True
        if not force and (check or files_may_have_changed(patch)):
            status = check_for_pending_changes(patch)
        if status is True:
            patchdir = os.path.join(patchfns.QUILT_PC, patch)
            try:
                os.remove(os.path.join(patchdir, '.timestamp'))
            except OSError:
                pass
            if not os.path.exists(patchdir) or not os.listdir(patchdir):
                output.write('Patch %s appears to be empty, removing\n' % patchfns.print_patch(patch))
                try:
                    os.rmdir(patchdir)
                except OSError as edata:
                    if edata.errno != errno.ENOENT:
                        output.error('%s: %s\n' % (patchdir, edata.errstring))
                        status = False
            else:
                output.write('Removing patch %s\n' % patchfns.print_patch(patch))
                if not backup.restore(patchdir, touch=True, verbose=not silent):
                    status = False
            patchfns.remove_from_db(patch)
            try:
                os.remove(os.path.join(patchdir + '~refresh'))
            except OSError as edata:
                if edata.errno != errno.ENOENT:
                    output.error('%s: %s\n' % (patchdir, edata.errstring))
                    status = False
        return status
    except KeyboardInterrupt:
        return False
Beispiel #6
0
def find_first_patch():
    patches = _get_series()
    if len(patches) > 0:
        return patches[0]
    if os.path.isfile(SERIES):
        output.error('No patches in series\n')
    else:
        output.error('No series file found\n')
    return False
Beispiel #7
0
def get_diffstat(text, strip_level, quiet=True):
    if not PARSER:
        make_parser()
    diffstat_options = customization.get_default_opts('diffstat')
    args, leftovers = PARSER.parse_known_args(diffstat_options.split())
    if leftovers and not quiet:
        output.error('diffstat default options: %; ignored\n' % ' '.join(leftovers))
    obj = patchlib.Patch.parse_text(text)
    stats_list = obj.get_diffstat_stats(int(strip_level))
    return stats_list.list_format_string(quiet=args.opt_quiet, comment=args.opt_comment, max_width=int(args.opt_max_width))
Beispiel #8
0
def in_valid_dir(filename):
    '''Is (relative) filename in a valid directory?'''
    dirpath = os.path.dirname(filename)
    while dirpath:
        for invalid_dir in [QUILT_PATCHES, QUILT_PC]:
            if os.path.samefile(dirpath, invalid_dir):
                output.error('File %s is located below %s\n' % (filename, invalid_dir + os.sep))
                return False
        dirpath = os.path.dirname(dirpath)
    return True
Beispiel #9
0
def run_header(args):
    def read_input():
        text = sys.stdin.read()
        if args.opt_strip_trailing_whitespace:
            return _trim_trailing_ws(text)
        return text
    def get_text(pfile):
        text = putils.get_patch_hdr(pfile, omit_diffstat=args.opt_strip_diffstat)
        if args.opt_strip_trailing_whitespace:
            return _trim_trailing_ws(text)
        return text
    def set_text(pfile, text):
        if args.opt_backup:
            try:
                shutil.copy2(pfile, pfile + '~')
            except Exception as edata:
                output.perror(edata)
        if args.opt_strip_trailing_whitespace:
            text = _trim_trailing_ws(text)
        putils.set_patch_hdr(pfile, text, omit_diffstat=args.opt_strip_diffstat)
    patchfns.chdir_to_base_dir()
    if not args.opt_backup:
        args.opt_backup = customization.get_config('QUILT_BACKUP')
    patch = patchfns.find_patch_in_series(args.arg_patch)
    if not patch:
        return cmd_result.ERROR
    patch_file = patchfns.patch_file_name(patch)
    if args.opt_replace:
        set_text(patch_file, read_input())
        output.write('Replaced header of patch %s\n' % patchfns.print_patch(patch))
    elif args.opt_append:
        set_text(patch_file, get_text(patch_file) + read_input())
        output.write('Appended text to header of patch %s\n' % patchfns.print_patch(patch))
    elif args.opt_edit:
        savelang = os.getenv('LANG', None)
        os.environ['LANG'] = patchfns.ORIGINAL_LANG
        tempfile = patchfns.gen_tempfile()
        result = shell.run_cmd('%s %s' % (os.getenv('EDITOR'), tempfile))
        if savelang:
            os.environ['LANG'] = savelang
        output.error(result.stderr)
        output.write(result.stdout)
        text = open(tempfile).read()
        os.remove(tempfile)
        if result.eflags != 0:
            return cmd_result.ERROR
        set_text(patch_file, text)
        output.write('Replaced header of patch %s\n' % patchfns.print_patch(patch))
    else:
        if not os.path.exists(patch_file):
            return cmd_result.OK
        output.start_pager()
        output.write(get_text(patch_file))
        output.wait_for_pager()
    return cmd_result.OK
Beispiel #10
0
def version_check():
    if not os.path.isdir(QUILT_PC):
        return True
    ver_file = os.path.join(QUILT_PC, '.version')
    if os.path.isfile(ver_file):
        version = int(open(ver_file).read().strip())
        if version > DB_VERSION:
            output.error('The quilt meta-data in this tree has version %s, but this version of quilt can only handle meta-data formats up to and including version %s. Please pop all the patches using the version of quilt used to push them before downgrading.\n' % (version, DB_VERSION))
            sys.exit(cmd_result.ERROR)
        return version == DB_VERSION
    return False
Beispiel #11
0
def find_applied_patch(patchname=None):
    if patchname:
        patch = find_patch(patchname)
        if patch:
            if not is_applied(patch):
                output.error('Patch %s is not applied\n' % print_patch(patch))
                return False
            return patch
        else:
            return False
    else:
        return find_top_patch()
Beispiel #12
0
def find_patch_file(name):
    """Find the patch file with the given name"""
    rname = filename_rel_base(name)
    if os.path.exists(rname) and os.access(rname, os.R_OK):
        return rname
    output.set_swallow_errors(True)
    patch = find_patch_in_series(name)
    output.set_swallow_errors(False)
    if not patch:
        output.error('Patch %s does not exist\n' % name)
        return False
    return patch_file_name(patch)
Beispiel #13
0
def run_fold(args):
    patchfns.chdir_to_base_dir()
    if not args.opt_strip_level:
        args.opt_strip_level = '1'
    opt_patch_args = '' if not args.opt_quiet else ' -s'
    if not args.opt_force or args.opt_quiet:
        opt_patch_args += ' -f'
    if args.opt_reverse:
        opt_patch_args += ' -R'
    top = patchfns.find_top_patch()
    if not top:
        return cmd_result.ERROR
    failed = suggest_force = False
    try:
        workdir = patchfns.gen_tempfile(template=os.getcwd(), asdir=True)
        if patchfns.SUBDIR:
            subdir = patchfns.SUBDIR
            prefix = os.path.join(workdir, patchfns.SUBDIR) + os.sep
        else:
            subdir = '.'
            prefix = workdir + os.sep
        patch_args = '-p%s --backup --prefix="%s" -E %s' % (args.opt_strip_level, prefix, opt_patch_args)
        patch_text = sys.stdin.read()
        result = putils.apply_patch_text(patch_text, indir=subdir, patch_args=patch_args)
        output.write(result.stdout)
        output.error(result.stderr)
        if result.eflags != 0 and not args.opt_force:
            suggest_force = True
            failed = True
        if not failed:
            for filename in fsutils.files_in_dir(workdir):
                backup_file = patchfns.backup_file_name(top, filename)
                if not os.path.exists(backup_file):
                    try:
                        backup_file_dir = os.path.dirname(backup_file)
                        if backup_file_dir and not os.path.exists(backup_file_dir):
                            os.makedirs(backup_file_dir)
                        os.link(os.path.join(workdir, filename), backup_file)
                    except OSError as edata:
                        failed = True
                        break
    except KeyboardInterrupt:
        failed = True
    if failed:
        for filename in fsutils.files_in_dir(workdir):
            try:
                shutil.move(os.path.join(workdir, filename), filename)
            except OSError:
                output.error('File %s may be corrupted\n' % filename)
    if os.path.exists(workdir):
        shutil.rmtree(workdir)
    return cmd_result.OK if not failed else cmd_result.ERROR_SUGGEST_FORCE if suggest_force else cmd_result.ERROR
Beispiel #14
0
def run_new(args):
    patchfns.chdir_to_base_dir()
    patch = patchfns.patch_name_base(args.patchname)
    if patchfns.patch_in_series(patch):
        output.error('Patch "%s" exists already\n' % patchfns.print_patch(patch))
        return cmd_result.ERROR | cmd_result.SUGGEST_RENAME
    patchfns.create_db()
    if not patchfns.insert_in_series(patch) or not patchfns.add_to_db(patch):
        output.error('Failed to create patch %s\n' % patchfns.print_patch(patch))
        return cmd_result.ERROR
    else:
        output.write('Patch %s is now on top\n' % patchfns.print_patch(patch))
        return cmd_result.OK
Beispiel #15
0
def find_patch(patchname):
    if os.path.exists(SERIES):
        if not os.path.isfile(SERIES):
            output.error('%s is not a regular file\n' % SERIES)
            return False
        can_pacthname = _canonical_patchname(patchname)
        matcher = _re_for_finding_patch_in_series(can_pacthname)
        candidates = []
        for line in open(SERIES).readlines():
            reres = matcher.match(line)
            if reres:
                candidates.append(reres.group(1))
        if len(candidates) == 1:
            return candidates[0]
        elif len(candidates) > 1:
            for candidate in candidates:
                # We may have an exact match, which overrides
                # extension expansion.  Otherwise we're confused
                if candidate == can_pacthname:
                    return candidate
            output.error('%s has too many matches in series:\n' % patchname)
            for candidate in candidates:
                 output.error('\t%s\n' % candidate)
            return False
    if find_first_patch():
        output.error('Patch %s is not in series\n' % patchname)
    return False
Beispiel #16
0
def run_add(args):
    patchfns.chdir_to_base_dir()
    patch = patchfns.find_applied_patch(args.opt_patch)
    if not patch:
        return 1
    patch_dir = os.path.join(patchfns.QUILT_PC, patch)
    status = 0
    for filename in args.filelist:
        filename = patchfns.filename_rel_base(filename)
        if not patchfns.in_valid_dir(filename):
            status = 1
            continue
        if patchfns.file_in_patch(patch, filename):
            output.error('File %s is already in patch %s\n' % (filename, patchfns.print_patch(patch)))
            status = 2 if status != 1 else 1
        next_patch = patchfns.next_patch_for_file(patch, filename)
        if next_patch is not None:
            output.error('File %s modified by patch %s\n' % (filename, patchfns.print_patch(next_patch)))
            status = 1
            continue
        if os.path.islink(filename):
            output.error('Cannot add symbolic link %s\n' % filename)
            status = 1
            continue
        if not backup.backup(patch_dir, [filename]):
            output.error('Failed to back up file %s\n' % filename)
            status = 1
            continue
        if os.path.exists(filename):
            # The original tree may be read-only.
            os.chmod(filename, os.stat(filename).st_mode|stat.S_IWUSR)
        output.write('File %s added to patch %s\n' % (filename, patchfns.print_patch(patch)))
    return status
Beispiel #17
0
def _create_parents(filename):
    last_sep = filename.rfind(os.sep)
    if last_sep == -1 or os.path.exists(filename[:last_sep]):
        return
    next_sep = filename.find(os.sep)
    while next_sep != -1:
        dirname = filename[:next_sep]
        if not os.path.isdir(dirname):
            try:
                os.mkdir(dirname, 0777)
            except OSError:
                output.error('Could not create directory %s.\n' % dirname)
                sys.exit(1)
        next_sep = filename.find(os.sep, next_sep + 1)
Beispiel #18
0
def run_edit(args):
    patchfns.chdir_to_base_dir()
    if patchfns.pyquilt_command('add %s' % ' '.join(args.filelist)) not in [0, 2]:
        return cmd_result.ERROR
    efilelist = args.filelist if not patchfns.SUBDIR else [os.path.join(patchfns.SUBDIR, fnm) for fnm in args.filelist]
    os.environ['LANG'] = patchfns.ORIGINAL_LANG
    result = shell.run_cmd('%s %s' % (os.getenv('EDITOR'), ' '.join(efilelist)))
    output.error(result.stderr)
    output.write(result.stdout)
    status = cmd_result.OK if result.eflags == 0 else cmd_result.ERROR
    for filename in args.filelist:
        efname = filename if not patchfns.SUBDIR else os.path.join(patchfns.SUBDIR, filename)
        if not os.path.exists(efname):
            patchfns.pyquilt_command('revert %s' % filename)
            status = cmd_result.ERROR
    return status
Beispiel #19
0
def run_files(args):
    patchfns.chdir_to_base_dir()
    first_patch = None
    if args.opt_combine:
        args.opt_all = True
        if args.opt_combine != '-':
            first_patch = patchfns.find_patch_in_series(args.opt_combine)
            if not first_patch:
                return cmd_result.ERROR
    last_patch = patchfns.find_applied_patch(args.patch)
    if not last_patch:
        return cmd_result.ERROR
    if args.opt_all:
        if not first_patch:
            first_patch = patchfns.applied_patches()[0]
        patches = patchfns.patches_before(last_patch) + [last_patch]
        if first_patch not in patches:
            output.error('Patch %s not applied before patch %s\n' % (patchfns.print_patch(first_patch), patchfns.print_patch(last_patch)))
            return cmd_result.ERROR
        patches = patches[patches.index(first_patch):]
    else:
        patches = [last_patch]
    use_status = args.opt_verbose and not args.opt_labels
    # Note: If opt_labels is set, then use_status is not set.
    output.start_pager()
    for patch in patches:
        if args.opt_all and args.opt_verbose and not args.opt_labels:
            output.write('%s\n' % patch)
        for filename in sorted(patchfns.files_in_patch(patch)):
            if args.opt_labels:
                if args.opt_verbose:
                    output.write('[%s] ' % patch)
                else:
                    output.write('%s ' % patch)
            if not use_status:
                output.write('%s\n' % filename)
            else:
                status = ' '
                buname = patchfns.backup_file_name(patch, filename)
                if os.path.exists(buname) and os.path.getsize(buname) > 0:
                    if not os.path.exists(filename) or os.path.getsize(filename) == 0:
                        status = '-'
                elif os.path.exists(filename) or os.path.getsize(filename) > 0:
                    status = '+'
                output.write('%s %s\n' % (status, filename))
    output.wait_for_pager()
    return cmd_result.OK
Beispiel #20
0
def check_for_existing_directories(args, script):
    status=False
    dircty_set = set()
    for action in script:
        if action[0] == 'patch':
            if args.prefix:
                dircty_set.add(os.path.join(args.prefix, action[1]))
            else:
                dircty_set.add(action[1])
    last_dir = None
    for dircty in dircty_set:
        if dircty == ".":
            continue
        if os.path.exists(dircty):
            output.error('Directory %s exists\n' % dircty)
            status = True
    return status
Beispiel #21
0
def apply_patch_temporarily(workdir, patch, files=None):
    patch_file = patch_file_name(patch)
    args = patch_args(patch)
    srcdir = os.path.join(QUILT_PC, patch)
    if not backup.restore(srcdir, to_dir=workdir, filelist=files, keep=True):
        output.error('Failed to copy files to temporary directory\n')
        return False
    if os.path.isfile(patch_file) and os.path.getsize(patch_file) > 0:
        text = fsutils.get_file_contents(patch_file)
        result = putils.apply_patch(indir=workdir, patch_args=' '.join(args) + ' --no-backup-if-mismatch -Ef', patch_file=patch_file)
        if result.eflags != 0:
            # Generating a relative diff for a subset of files in
            # the patch will fail. Also, if a patch was force
            # applied, we know that it won't apply cleanly. In
            # all other cases, print a warning.
            if not os.path.isfile(os.path.join(QUILT_PC, patch + '~refresh')) and len(files) == 0:
                output.error('Failed to patch temporary files\n')
                return False
    return True
Beispiel #22
0
def check_for_existing_files(args, script):
    status=False
    dircty_set = set()
    for action in script:
        if action[0] == 'patch':
            if args.prefix:
                dircty_set.add(os.path.join(args.prefix, action[1]))
            else:
                dircty_set.add(action[1])
    for dircty in dircty_set:
        patch_dir = os.path.join(dircty, patchfns.QUILT_PATCHES)
        if os.path.exists(patch_dir):
            output.error('Directory %s exists\n' % patch_dir)
            status = True
        series_file = os.path.join(dircty, patchfns.QUILT_SERIES)
        if os.path.exists(series_file):
            output.error('File %s exists\n' % series_file)
            status = True
    return status
Beispiel #23
0
def process_mail(message, args):
    if args.opt_send:
        sendmail_cmd = '%s %s --f %s ' % (os.getenv('QUILT_SENDMAIL', 'sendmail'), os.getenv('QUILT_SENDMAIL_ARGS', ''), args.opt_sender)
        sendmail_cmd += extract_recipients(message)
        output.write(sendmail_cmd)
        del message['Bcc']
        result = shell.run_cmd(sendmail_cmd, message.as_string(False))
        output.write(result.stdout)
        output.error(result.stderr)
    else:
        from_date = time.strftime('+%a %b %e %H:%M:%S %Y')
        fobj = open(args.opt_mbox, 'a')
        fobj.write('From %s %s\n' % (args.opt_sender_address, from_date))
        for field, value in message.items():
            fobj.write('%s: %s\n' % (field, value))
        fobj.write('\n')
        for line in message.get_payload().splitlines(True):
            fobj.write(re.sub('^From ', '>From ', line))
        fobj.close()
Beispiel #24
0
def run_delete(args):
    patchfns.chdir_to_base_dir()
    if args.patch:
        patch = patchfns.find_patch(args.patch)
        if not patch:
            return cmd_result.ERROR
    else:
        patch = patchfns.top_patch()
    if args.opt_next:
        patch =patchfns.patch_after(patch)
        if not patch:
            output.error('No next patch\n')
            return cmd_result.ERROR
    if not patch:
        patchfns.find_top_patch()
        return cmd_result.ERROR
    if patchfns.is_applied(patch):
        if patch != patchfns.top_patch():
            output.error('Patch %s is currently applied\n' % patchfns.print_patch(patch))
            return cmd_result.ERROR
        if patchfns.pyquilt_command('pop -qf') != cmd_result.OK:
            return cmd_result.ERROR
    if patchfns.remove_from_series(patch):
        output.write('Removed patch %s\n' % patchfns.print_patch(patch))
    else:
        output.error('Failed to remove patch %s\n' % patchfns.print_patch(patch))
        return cmd_result.ERROR
    patch_file = patchfns.patch_file_name(patch)
    if args.opt_remove and os.path.exists(patch_file):
        if args.opt_backup:
            try:
                os.rename(patch_file, patch_file + '~')
            except IOError:
                output.error('Failed to backup patch file %s\n' % patch_file)
                return cmd_result.ERROR
        else:
            try:
                os.remove(patch_file)
            except IOError:
                output.error('Failed to remove patch file %s\n' % patch_file)
                return cmd_result.ERROR
    return cmd_result.OK
Beispiel #25
0
def create_db(dirpath=None):
    if dirpath is not None:
        saved_dir = os.getcwd()
        os.chdir(dirpath)
    if not os.path.isdir(QUILT_PC):
        if os.path.exists(QUILT_PC):
            output.error('%s is not a directory.\n' % QUILT_PC)
            sys.exit(cmd_result.ERROR)
        try:
            os.mkdir(QUILT_PC)
        except OSError:
            output.error('Could not create directory %s.\n' % QUILT_PC)
            sys.exit(cmd_result.ERROR)
        open(os.path.join(QUILT_PC, '.version'), 'w').write('%s\n' % DB_VERSION)
    if not os.path.isfile(os.path.join(QUILT_PC, '.quilt_patches')):
        open(os.path.join(QUILT_PC, '.quilt_patches'), 'w').write(QUILT_PATCHES + '\n')
    if not os.path.isfile(os.path.join(QUILT_PC, '.quilt_series')):
        open(os.path.join(QUILT_PC, '.quilt_series'), 'w').write(QUILT_SERIES + '\n')
    if dirpath is not None:
        os.chdir(saved_dir)
Beispiel #26
0
def annotation_for(old_file, new_file, annotation):
    """Return diff for annotation for changes from osd_file to new_file"""
    if not os.path.exists(old_file) or os.path.getsize(old_file) == 0:
        old_file = '/dev/null'
    if not os.path.exists(new_file) or os.path.getsize(new_file) == 0:
        new_file = '/dev/null'
    result = shell.run_cmd('diff -e "%s" "%s"' % (old_file, new_file))
    if result.eflags > 1:
        output.error(result.stderr)
        sys.exit(result.eflags)
    difftxt = ''
    start_cre = re.compile('^(\d+)(,\d+)?([acd])$')
    end_cre = re.compile('^\.$')
    lines = result.stdout.splitlines(True)
    index = 0
    aline = '%s\n' % annotation
    while index < len(lines):
        match = start_cre.match(lines[index])
        if match:
            difftxt += lines[index]
            start = int(match.group(1))
            if match.group(3) == 'a':
                index += 1
                while end_cre.match(lines[index]) is None:
                    difftxt += aline
                    index += 1
                difftxt += lines[index]
            elif match.group(3) == 'c':
                end = int(match.group(2)[1:]) if match.group(2) is not None else start
                cnt = end - start + 1
                index += cnt + 1
                difftxt += aline * cnt
                assert end_cre.match(lines[index])
                difftxt += lines[index]
            else:
                assert match.group(3) == 'd'
            index += 1
        else:
            assert False
            index += 1
    return difftxt
Beispiel #27
0
def run_remove(args):
    patchfns.chdir_to_base_dir()
    patch = patchfns.find_applied_patch(args.opt_patch)
    if not patch:
        return cmd_result.ERROR
    prpatch = patchfns.print_patch(patch)
    patchfn = patchfns.patch_file_name(patch)
    patchrefrfile = os.path.join(patchfns.QUILT_PC, patch + '~refresh')
    patchrefrdir = os.path.dirname(patchrefrfile)
    budir = patchfns.backup_dir_name(patch)
    is_ok = True
    for filename in args.file_list:
        if patchfns.SUBDIR:
            filename = os.path.join(patchfns.SUBDIR, filename)
        if not patchfns.file_in_patch(filename, patch):
            output.error('File %s is not in patch %s\n' % (filename, prpatch))
            is_ok = False
            continue
        next_patch = patchfns.next_patch_for_file(patch, filename)
        if next_patch:
            output.error('File %s modified by patch %s\n' % (filename, patchfns.print_patch(next_patch)))
            is_ok = False
            continue
        # Restore file from backup
        if not backup.restore(budir, filelist=[filename], touch=True):
            output.error('Failed to remove file %s from patch %s\n' % (filename, prpatch))
            is_ok = False
            continue
        if os.path.exists(patchrefrdir) and os.path.exists(patchfn):
            fsutils.touch(patchrefrfile)
        output.write('File %s removed from patch %s\n' % (filename, prpatch))
    return cmd_result.OK if is_ok else cmd_result.ERROR
Beispiel #28
0
def merge_patches(old, new, opt_desc):
    """Return the merge of the old and new patches"""
    old_desc = patchfns.gen_tempfile()
    open(old_desc, 'w').write(putils.get_patch_descr(old))
    new_desc = patchfns.gen_tempfile()
    open(new_desc, 'w').write(putils.get_patch_descr(new))
    if opt_desc is None:
        if os.path.getsize(old_desc) == 0:
            opt_desc = 'n'
        elif os.path.getsize(new_desc) == 0:
            opt_desc = 'o'
        if opt_desc is None:
            result = shell.run_cmd('diff -u %s %s' % (old_desc, new_desc))
            diff_lines = result.stdout.splitlines(True)
            if len(diff_lines) > 2:
                output.error('Patch headers differ:\n')
                output.error(''.join(diff_lines[2:]))
                output.error('Please use -d {o|a|n} to specify which patch header(s) to keep.\n')
                os.remove(old_desc)
                os.remove(new_desc)
                return False
    patchtext = open(old_desc).read() if opt_desc != 'n' else ''
    if opt_desc == 'a':
        patchtext += '---\n'
    if opt_desc == 'o':
        patchtext += putils.get_patch_diff(new)
    else:
        patchtext += fsutils.get_file_contents(new)
    os.remove(old_desc)
    os.remove(new_desc)
    return patchtext
Beispiel #29
0
def do_diff(filename, old_file, new_file, args):
    """Output the diff for the nominated files"""
    if args.opt_reverse:
        old_file, new_file = new_file, old_file
    if args.opt_diff:
        if not os.path.exists(old_file):
            old_file = '/dev/null'
        if not os.path.exists(new_file):
            new_file = '/dev/null'
        if not diff.same_contents(old_file, new_file):
            os.environ['LANG'] = patchfns.ORIGINAL_LANG
            shell.run_cmd('%s %s %s' % (args.opt_diff, old_file, new_file))
            os.environ['LANG'] = 'POSIX'
            return True
    else:
        result = diff.diff_file(filename, old_file, new_file, args)
        output.error(result.stderr)
        if args.opt_color:
            output.write(colorize(result.stdout))
        else:
            output.write(result.stdout)
        return result.eflags < 2
Beispiel #30
0
def run_grep(args):
    patchfns.chdir_to_base_dir()
    problem_args = [] # i.e. those wit optional arguments
    for arg in ['--color', '--colour']:
        while arg in args.remainder_of_args:
            problem_args.append(arg)
            args.remainder_of_args.remove(arg)
    grep_opts, grep_args = getopt.getopt(args.remainder_of_args, grep_options, grep_long_options)
    opt_list = make_opt_list(grep_opts) + problem_args
    if expect_pattern(grep_opts):
        files = grep_args[1:]
        opt_list += grep_args[0:1]
    else:
        files = grep_args
    if not files:
        files = get_files()
    if len(files) == 1 and '-h' not in opt_list and '--no-filename' not in opt_list:
        opt_list.append('-H')
    result = shell.run_cmd(['grep'] + opt_list + files)
    output.write(result.stdout)
    output.error(result.stderr)
    return result.eflags