forked from shawwn/scrap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
abbreviate-file-name
executable file
·124 lines (104 loc) · 3.66 KB
/
abbreviate-file-name
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#!/usr/bin/env python3
#==============================================================================
# Functionality
#==============================================================================
import pdb
import sys
import os
import re
import json
import importlib
from pprint import pprint as pp
# utility funcs, classes, etc go here.
def asserting(cond):
if not cond:
pdb.set_trace()
assert(cond)
def has_stdin():
return not sys.stdin.isatty()
def reg(pat, flags=0):
return re.compile(pat, re.VERBOSE | flags)
# https://stackoverflow.com/a/56090741
def import_path(path):
module_name = os.path.basename(path).replace('-', '_')
if module_name in sys.modules:
return sys.modules[module_name]
spec = importlib.util.spec_from_loader(
module_name,
importlib.machinery.SourceFileLoader(module_name, os.path.join(os.path.dirname(__file__), path))
)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
sys.modules[module_name] = module
return module
def function(path, name=None):
if callable(path):
return path
if path.startswith('lambda') and ':' in path:
f = eval(compile(path, '<lambda>', mode='eval'))
f.__name__ = path
f.__qualname__ = f'function(' + repr(path) + ')'
return f
module = import_path(path)
return getattr(module, module.__name__ if name is None else name)
def abbreviate_file_name(filename):
"""Return a version of FILENAME shortened by substituting "~" for
the user's home directory."""
filename = function('expand-file-name')(filename)
home = os.path.expanduser('~')
if filename.startswith(home):
filename = '~' + filename[len(home):]
return filename
#==============================================================================
# Cmdline
#==============================================================================
import argparse
def get_parser(parser=None):
if parser is None:
parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter,
description=abbreviate_file_name.__doc__.strip())
parser.add_argument('-v', '--verbose',
action="store_true",
help="verbose output" )
parser.add_argument('-0', '--print0',
action="store_true",
help="Prints \\0 after each result rather than newline" )
return parser
args = None
#==============================================================================
# Main
#==============================================================================
def run():
if args.verbose:
print(args, file=sys.stderr)
if len(args.args) <= 0 and not has_stdin():
# if there were no args and there was no input, prompt user.
print('Enter input (press Ctrl-D when done):')
if len(args.args) <= 0 or has_stdin():
indata = sys.stdin.read()
args.args.extend(indata.split('\0') if '\0' in indata else indata.splitlines())
# for each arg on cmdline...
for arg in args.args:
result = abbreviate_file_name(arg)
print(result, end='\0' if args.print0 else '\n')
def main():
try:
global args
if not args:
args, leftovers = get_parser().parse_known_args()
args.args = leftovers
return run()
except IOError:
# http://stackoverflow.com/questions/15793886/how-to-avoid-a-broken-pipe-error-when-printing-a-large-amount-of-formatted-data
if e.errno != 32:
raise
try:
sys.stdout.close()
except IOError:
pass
try:
sys.stderr.close()
except IOError:
pass
if __name__ == "__main__":
main()