/cmd/newliner-cmd.py

http://github.com/apenwarr/bup · Python · 48 lines · 43 code · 4 blank · 1 comment · 14 complexity · 76b91de17c4b15fdc9cf582ae103b6e2 MD5 · raw file

  1. #!/usr/bin/env python
  2. import sys, os, re
  3. from bup import options
  4. from bup import _helpers # fixes up sys.argv on import
  5. optspec = """
  6. bup newliner
  7. """
  8. o = options.Options(optspec)
  9. (opt, flags, extra) = o.parse(sys.argv[1:])
  10. if extra:
  11. o.fatal("no arguments expected")
  12. r = re.compile(r'([\r\n])')
  13. lastlen = 0
  14. all = ''
  15. width = options._tty_width() or 78
  16. while 1:
  17. l = r.split(all, 1)
  18. if len(l) <= 1:
  19. if len(all) >= 160:
  20. sys.stdout.write('%s\n' % all[:78])
  21. sys.stdout.flush()
  22. all = all[78:]
  23. try:
  24. b = os.read(sys.stdin.fileno(), 4096)
  25. except KeyboardInterrupt:
  26. break
  27. if not b:
  28. break
  29. all += b
  30. else:
  31. assert(len(l) == 3)
  32. (line, splitchar, all) = l
  33. if splitchar == '\r':
  34. line = line[:width]
  35. sys.stdout.write('%-*s%s' % (lastlen, line, splitchar))
  36. if splitchar == '\r':
  37. lastlen = len(line)
  38. else:
  39. lastlen = 0
  40. sys.stdout.flush()
  41. if lastlen:
  42. sys.stdout.write('%-*s\r' % (lastlen, ''))
  43. if all:
  44. sys.stdout.write('%s\n' % all)