Esempio n. 1
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
Esempio n. 2
0
 def add_patch(patch):
     def apply_patch(patch_file, patch_args):
         if not os.path.exists(patch_file) or os.path.getsize(patch_file) == 0:
             return cmd_result.Result(0, '', '')
         return putils.apply_patch(patch_file, patch_args=patch_args)
     tmp = None
     patch_file = patchfns.patch_file_name(patch)
     output.write('Applying patch %s\n' % patchfns.print_patch(patch))
     try:
         pp_args = push_patch_args(patch, reverse=False)
         prefix = os.path.join(patchfns.QUILT_PC, patch)
         if not args.opt_leave_rejects:
             tmp = patchfns.gen_tempfile()
             trf = '-r %s' % tmp
         else:
             trf = ''
         patch_args = '%s --backup --prefix="%s/" %s -E %s' % (pp_args, prefix, trf, more_patch_args)
         result = apply_patch(patch_file, patch_args=patch_args)
         if not args.opt_quiet or result.eflags != 0:
             if do_colorize:
                 output.error(colorize(cleanup_patch_output(result.stderr, args)))
                 output.write(colorize(cleanup_patch_output(result.stdout, args)))
             else:
                 output.error(cleanup_patch_output(result.stderr, args))
                 output.write(cleanup_patch_output(result.stdout, args))
     except KeyboardInterrupt:
         rollback_patch(patch)
         output.error('Interrupted by user; patch %s was not applied.\n' % patchfns.print_patch(patch))
         return False
     finally:
         if tmp:
             os.remove(tmp)
     if result.eflags == 0 or (result.eflags == 1 and args.opt_force):
         patchfns.add_to_db(patch)
         refresh_file = os.path.join(patchfns.QUILT_PC, patch + '~refresh')
         if result.eflags == 0:
             if os.path.exists(refresh_file):
                 os.remove(refresh_file)
         else:
             fsutils.touch(refresh_file)
         patch_dir = os.path.join(patchfns.QUILT_PC, patch)
         if os.path.exists(patch_dir):
             fsutils.touch(os.path.join(patch_dir, '.timestamp'))
         else:
             os.mkdir(patch_dir)
         if not os.path.exists(patch_file):
             output.write('Patch %s does not exist; applied empty patch\n' % patchfns.print_patch(patch))
         elif not putils.get_patch_diff(patch_file):
             output.write('Patch %s appears to be empty; applied\n' % patchfns.print_patch(patch))
         elif result.eflags != 0:
             output.write('Applied patch %s (forced; needs refresh)\n' % patchfns.print_patch(patch))
             return False
     else:
         rollback_patch(patch)
         tmp = patchfns.gen_tempfile()
         trf = '-r %s' % tmp
         pp_args = push_patch_args(patch, reverse=True)
         patch_args = '%s --backup --prefix="%s/" %s -E %s' % (pp_args, prefix, trf, more_patch_args)
         result = apply_patch(patch_file, patch_args=patch_args)
         if result.eflags == 0:
             output.write('Patch %s can be reverse-applied\n' % patchfns.print_patch(patch))
         else:
             output.write('Patch %s does not apply (enforce with -f)\n' % patchfns.print_patch(patch))
         rollback_patch(patch)
         os.remove(tmp)
         return False
     return True
Esempio n. 3
0
def run_refresh(args):
    workdir = None
    def clean_up(status):
        if workdir and os.path.isdir(workdir):
            shutil.rmtree(workdir)
        return status
    patchfns.chdir_to_base_dir()
    patch = patchfns.find_applied_patch(args.patchname)
    if not patch:
        return cmd_result.ERROR
    if not args.opt_sort:
        files = patchfns.files_in_patch_ordered(patch)
    else:
        files = patchfns.files_in_patch(patch)
    if args.opt_new_name:
        if args.patchname:
            output.error('Can only refresh the topmost patch with -z currently\n')
            return cmd_result.ERROR
        old_patch = patch
        old_patch_args = patchfns.patch_args(old_patch)
        if args.opt_new_name is True:
            patch = patchfns.next_filename(patch)
        else:
            patch = args.opt_new_name
        if os.path.exists(patchfns.patch_file_name(patch)):
            output.error('Patch %s exists already\n' % patchfns.print_patch(patch))
            return cmd_result.ERROR
    if args.opt_strip_level is None:
        args.opt_strip_level = patchfns.patch_strip_level(patch)
    if args.opt_strip_level in ['0', '1']:
        num_strip_level = args.opt_strip_level
    elif args.opt_strip_level == 'ab':
        num_strip_level = '1'
    else:
        output.error('Cannot refresh patches with -p%s, please specify -p0 or -p1 instead\n' % args.opt_strip_level)
        return cmd_result.ERROR
    if args.opt_new_name:
        workdir = patchfns.gen_tempfile(asdir=True, template=os.path.join(os.getcwd(), 'quilt'))
        if not patchfns.apply_patch_temporarily(workdir, old_patch):
            return clean_up(cmd_result.ERROR)
    patch_content = ''
    files_were_shadowed = False
    for filn in files:
        if args.opt_new_name:
            old_file = os.path.join(workdir, filn)
            new_file = filn
        else:
            old_file = patchfns.backup_file_name(patch, filn)
            next_patch = patchfns.next_patch_for_file(patch, filn)
            if not next_patch:
                new_file = filn
            else:
                new_file = patchfns.backup_file_name(next_patch, filn)
                files_were_shadowed = True
        result = diff.diff_file(filn, old_file, new_file, args)
        if result.eflags > 1:
            output.error('\n'.join(result.stderr, 'Diff failed, aborting\n'))
            return clean_up(cmd_result.ERROR)
        elif result.eflags == 0 or not result.stdout:
            continue
        else:
            patch_content += result.stdout
    patch_file = patchfns.patch_file_name(patch)
    prev_patch_file = patch_file if os.path.isfile(patch_file) else '/dev/null'
    result_content = patchfns.patch_header(prev_patch_file)
    if not patch_content:
        output.error('Nothing in patch %s\n' % patchfns.print_patch(patch))
    else:
        if files_were_shadowed:
            if not args.opt_force:
                output.error('More recent patches modify files in patch %s. Enforce refresh with -f.\n' % patchfns.print_patch(patch))
                return clean_up(cmd_result.ERROR_SUGGEST_FORCE)
            if args.opt_strip_trailing_whitespace:
                output.error('Cannot use --strip-trailing-whitespace on a patch that has shadowed files.\n')
        if args.opt_strip_trailing_whitespace and not files_were_shadowed:
            result = putils.remove_trailing_ws(patch_content, num_strip_level)
            if result.eflags == cmd_result.OK:
                patch_content = result.stdout
            if result.stderr:
                output.error(result.stderr)
        else:
            result = putils.remove_trailing_ws(patch_content, num_strip_level, dry_run=True)
            if result.stderr:
                output.error(result.stderr)
        if args.opt_diffstat:
            diffstat_text = diffstat.get_diffstat(patch_content, num_strip_level)
            result_content += diffstat_text
        result_content += patch_content
    patch_file_dir = os.path.dirname(patch_file)
    if not os.path.exists(patch_file_dir):
        os.makedirs(patch_file_dir)
    is_ok = True
    QUILT_PC = customization.get_config('QUILT_PC')
    if fsutils.file_contents_equal(patch_file, result_content):
        output.write('Patch %s is unchanged\n' % patchfns.print_patch(patch))
    else:
        if args.opt_backup and os.path.isfile(patch_file):
            try:
                os.rename(patch_file, patch_file + '~')
            except OSError:
                output.error('Failed to create backup %s\n' % patch_file + '~')
                is_ok = False
        if is_ok:
            is_ok = fsutils.set_file_contents(patch_file, result_content)
        if is_ok and args.opt_new_name:
            insert_ok = patchfns.insert_in_series(patch, old_patch_args)
            if not insert_ok:
                output.error('Failed to insert patch %s into file series\n' % patchfns.print_patch(patch))
                return clean_up(cmd_result.ERROR)
            try:
                patch_dir = os.path.join(QUILT_PC, patch)
                if os.path.exists(patch_dir):
                    shutil.rmtree(patch_dir)
                os.rename(workdir, patch_dir)
                open(patchfns.DB, 'a').write(patch + '\n')
            except:
                output.error('Failed to create patch %s\n' % patchfns.print_patch(patch))
                return clean_up(cmd_result.ERROR)
            output.write('Fork of patch %s created as %s\n' % (patchfns.print_patch(old_patch), patchfns.print_patch(patch)))
        elif is_ok and patch_content:
            output.write('Refreshed patch %s\n' % patchfns.print_patch(patch))
        fsutils.touch(os.path.join(QUILT_PC, patch, '.timestamp'))
    if is_ok:
        tagf = os.path.join(QUILT_PC, patch + '~refresh')
        if os.path.exists(tagf):
            os.remove(tagf)
        is_ok = patchfns.change_db_strip_level('-p%s' % num_strip_level, patch)
    return clean_up(cmd_result.OK if is_ok and patch_content else cmd_result.ERROR)
Esempio n. 4
0
def run_mail(args):
    patchfns.chdir_to_base_dir()
    if not shell.which('formail'):
        output.write("You have to install 'formail' to use 'quilt mail'")
        return cmd_result.ERROR
    if not args.opt_signature or args.opt_signature == '-':
        args.opt_signature = None
    else:
        try:
            args.opt_signature = open(args.opt_signature).read()
        except IOError as edata:
            output.perror(edata)
    if args.first_patch:
        args.first_patch = patchfns.find_first_patch() if args.first_patch == '-' else patchfns.find_patch(args.first_patch)
        if not args.first_patch:
            return cmd_result.ERROR
        if not args.last_patch:
            args.last_patch = args.first_patch
        else:
            args.last_patch = patchfns.find_last_patch() if args.last_patch == '-' else patchfns.find_patch(args.last_patch)
            if not args.last_patch:
                return cmd_result.ERROR
    if not args.opt_sender:
        hostname = socket.gethostname()
        args.opt_sender = '%s@%s' % (get_login_name(), hostname)
        if not re.match('^\S+@\S+\.\S+$', args.opt_sender):
            output.error('Could not determine the envelope sender address. Please use --sender.\n')
            return cmd_result.ERROR
    _dummy, args.opt_sender_address = email.utils.parseaddr(args.opt_sender)
    if not args.opt_charset:
        lc_all = os.getenv('LC_ALL', patchfns.ORIGINAL_LANG)
        if lc_all and lc_all.endswith('UTF-8'):
            args.opt_charset = 'UTF-8'
        else:
            args.opt_charset = 'ISO-8859-15'
    patches = patchfns.cat_series()
    if args.first_patch:
        first_index = patches.index(args.first_patch)
        last_index = patches.index(args.last_patch)
        if last_index < first_index:
            output.error('Patch %s not applied before patch %s\n' % (patchfns.print_patch(args.first_patch), patchfns.print_patch(args.first_patch)))
            return cmd_result.ERROR
        patches = patches[first_index:last_index + 1]
    total = len(patches)
    tmpdir = patchfns.gen_tempfile(asdir=True)
    atexit.register(lambda: not os.path.exists(tmpdir) or shutil.rmtree(tmpdir, ignore_errors=True))
    subject_map = {}
    patch_msgs = []
    for patch in patches:
        contents = fsutils.get_file_contents(patchfns.patch_file_name(patch))
        mailmsg = message_from_patch(contents, args.opt_charset)
        if mailmsg is False:
            subject = None
        else:
            patch_msgs.append(mailmsg)
            subject = mailmsg['Replace-Subject']
        if mailmsg is False or not subject:
            output.error('Unable to extract a subject header from %s\n' % patchfns.print_patch(patch))
            return cmd_result.ERROR
        if subject in subject_map:
            subject_map[subject].append(patch)
        else:
            subject_map[subject] = [patch]
    if len(subject_map) != len(patches):
        duplicates = []
        for key in sorted(subject_map):
            plist = subject_map[key]
            if len(plist) > 1:
                duplicates += plist
        output.error('Patches %s have duplicate subject headers.\n' % ', '.join([patchfns.print_patch(dup) for dup in duplicates]))
        return cmd_result.ERROR
    if args.opt_reply_to:
        if not os.path.exists(args.opt_reply_to):
            output.error('File %s does not exist\n' % args.opt_reply_to)
            return cmd_result.ERROR
        args.opt_reply_to = email.message_from_string(open(args.opt_reply_to).read())
        if not args.opt_subject:
            repto_subject = args.opt_reply_to['Subject']
            args.opt_subject = 'Re: %s' % re.sub('^([ \t]*[rR][eE]:[ \t]*)', '', repto_subject)
    intro = 'Message-Id: <%s>\n' % msgid(args)
    intro += 'User-Agent: pyquilt\n'
    last_ts = time.localtime()
    intro += time.strftime('Date: %a, %d %b %Y %H:%M:%S %z\n', last_ts)
    intro += 'From: %s\n' % (args.opt_from if args.opt_from else args.opt_sender)
    intro += 'To: %s\n' % (', '.join(args.opt_to) if args.opt_to else '')
    intro += 'Cc: %s\n' % (', '.join(args.opt_cc) if args.opt_cc else '')
    intro += 'Bcc: %s\n' % (', '.join(args.opt_bcc) if args.opt_bcc else '')
    if args.opt_reply_to:
        intro += in_reply_to_header(args.opt_reply_to)
        intro += references_header(args.opt_reply_to)
    intro += 'Subject-Prefix: [%s @num@/@total@]\n' % args.opt_prefix
    intro += 'Subject: %s\n\n' % (args.opt_subject if args.opt_subject else '')
    intro += ('%s\n\n' % args.opt_message) if args.opt_message else ''
    intro += ('-- \n%s\n' % args.opt_signature) if args.opt_signature else ''
    intro_message = email.message_from_string(intro)
    intro_message.set_charset(args.opt_charset)
    if not args.opt_message:
        introfile = patchfns.gen_tempfile()
        open(introfile, 'w').write(intro_message.as_string())
        result = shell.run_cmd('%s %s' % (os.getenv('EDITOR'), introfile))
        output.write(result.stdout)
        output.error(result.stderr)
        intro_message = email.message_from_string(open(introfile).read(), charset=args.opt_charset)
        os.remove(introfile)
        if result.eflags != 0:
            return cmd_result.ERROR
    subject = join_lines(intro_message['Subject'])
    if not subject:
        if not args.opt_message:
            savefile = patchfns.gen_tempfile()
            open(savefile, 'w').write(intro_message.as_string())
            output.error('Introduction has no subject header (saved as %s)\n' % savefile)
        else:
            output.error('Introduction has no subject header\n')
        return cmd_result.ERROR
    if args.opt_mbox:
        fsutils.touch(args.opt_mbox)
    subject_prefix = email.utils.quote(join_lines(intro_message['Subject-Prefix']))
    subject_prefix += ' ' if subject_prefix else ''
    subject_prefix = re.sub('@total@', str(total), subject_prefix)
    del intro_message['Subject-Prefix']
    pnum_fmt = '{0:0%s}' % len(str(total))
    pfx = re.sub('@num@', pnum_fmt.format(0), subject_prefix)
    intro_message.replace_header('Subject', pfx + intro_message['Subject'])
    remove_empty_headers(intro_message)
    for key in ['To', 'Cc', 'Bcc']:
        # Consolidate up the various recipient fields
        values = intro_message.get_all(key)
        if values:
            del intro_message[key]
            intro_message[key] = ', '.join(values)
    process_mail(intro_message, args)
    pnum = 0
    for msg in patch_msgs:
        msg.add_header('Content-Disposition', 'inline',  filename=patches[pnum])
        for key in intro_message.keys():
            if key.lower() not in ['message-id', 'references', 'in-reply-to', 'subject']:
                for value in intro_message.get_all(key):
                    msg[key] = value
        msg['References'] = get_reference_to(intro_message)
        msg.set_charset(args.opt_charset)
        for aclass in ['To', 'Cc', 'Bcc']:
            rclass = 'Recipient-' + aclass
            if msg.has_key(rclass):
                msg[aclass] = ',\n '.join(msg.get_all(rclass))
                del msg[rclass]
        pnum += 1
        ppfx = re.sub('@num@', pnum_fmt.format(pnum), subject_prefix)
        msg['Message-Id'] = msgid(args)
        msg['Subject'] = '%s%s' % (ppfx, msg['Replace-Subject']) if ppfx else msg['Replace-Subject']
        del msg['Replace-Subject']
        remove_empty_headers(msg)
        process_mail(msg, args)
    return cmd_result.OK