File: util.py

package info (click to toggle)
mupdf 1.27.0%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 29,224 kB
  • sloc: ansic: 335,320; python: 20,906; java: 7,520; javascript: 2,213; makefile: 1,152; xml: 675; cpp: 639; sh: 513; cs: 307; awk: 10; sed: 7; lisp: 3
file content (50 lines) | stat: -rw-r--r-- 1,547 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
'''
Utility fns.
'''

import os

import jlib

def clip( text, prefixes, suffixes=''):
    '''
    Returns <text> with prefix(s) and suffix(s) removed if present.
    '''
    if isinstance( prefixes, str):
        prefixes = prefixes,
    if isinstance( suffixes, str):
        suffixes = suffixes,
    while 1:
        for prefix in prefixes:
            if text.startswith( prefix):
                text = text[ len( prefix):]
                break
        else:
            break
    while 1:
        for suffix in suffixes:
            if suffix and text.endswith( suffix):
                text = text[ :-len( suffix)]
                break
        else:
            break
    return text


def update_file_regress( text, filename, check_regression):
    '''
    Behaves like jlib.fs_update(), but if check_regression is true and
    <filename> already exists with different content from <text>, we show a
    diff and return an exception.
    '''
    text_old = jlib.fs_update( text, filename, check_regression)
    if check_regression:
        if text_old is not None:
            # Existing content differs and <check_regression> is true.
            with open( f'{filename}-2', 'w') as f:
                f.write( text)
            message = f'File would have changed: {os.path.relpath(filename)}'
            jlib.log( message)
            jlib.system( f'diff -u {filename} {filename}-2', verbose=True, raise_errors=False, prefix=f'diff {os.path.relpath(filename)}: ', out='log')
            return Exception( message)
    return text_old