Skip to content

Instantly share code, notes, and snippets.

@pyokagan
Created October 25, 2012 07:11
Show Gist options
  • Select an option

  • Save pyokagan/3951083 to your computer and use it in GitHub Desktop.

Select an option

Save pyokagan/3951083 to your computer and use it in GitHub Desktop.
#! /usr/bin/python2.6
"""
trunc -n LENGTH -k 0,1,2,3... COMPONENTS...
"""
from __future__ import print_function,unicode_literals
from argparse import ArgumentParser
from math import floor
def shorten(length, x, suffix = "..."):
if len(x) <= length:
return x
#Do word splitting
y = x[:max(0, length - len(suffix))]
#Get the closest whitespace to strip.
index = y.rfind(" ")
if index == -1:
return x[:length].rstrip()
else:
return x[:index] + suffix
def main():
p = ArgumentParser()
p.add_argument("-n", dest = "length", default = 140, type = int)
p.add_argument("-k", dest = "keys", default = "")
p.add_argument("components", nargs = "+")
args = p.parse_args()
keys = [int(x) for x in args.keys.split(",") if x]
def mark_comp(i, x):
return (x, True) if i in keys else (x, False)
components = [mark_comp(i, x) for i, x in enumerate(args.components)]
flex_comp_len = len([x for x in components if x[1]])
fixed_comp_str_len = sum(len(x[0]) for x in components if not x[1])
flex_comp_str_len = max(0, floor((args.length - fixed_comp_str_len) / flex_comp_len))
extra = 0
out = list()
for x, y in components:
if y:
z = shorten(flex_comp_str_len + extra, x)
extra += flex_comp_str_len - len(z)
out.append(z)
else:
out.append(x)
x = ''.join(out)
print(shorten(args.length, x), end = '')
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment