ls.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. # -*- test-case-name: twisted.conch.test.test_cftp -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. import array
  5. import stat
  6. from time import time, strftime, localtime
  7. from twisted.python.compat import _PY3
  8. # Locale-independent month names to use instead of strftime's
  9. _MONTH_NAMES = dict(list(zip(
  10. list(range(1, 13)),
  11. "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split())))
  12. def lsLine(name, s):
  13. """
  14. Build an 'ls' line for a file ('file' in its generic sense, it
  15. can be of any type).
  16. """
  17. mode = s.st_mode
  18. perms = array.array('B', b'-'*10)
  19. ft = stat.S_IFMT(mode)
  20. if stat.S_ISDIR(ft): perms[0] = ord('d')
  21. elif stat.S_ISCHR(ft): perms[0] = ord('c')
  22. elif stat.S_ISBLK(ft): perms[0] = ord('b')
  23. elif stat.S_ISREG(ft): perms[0] = ord('-')
  24. elif stat.S_ISFIFO(ft): perms[0] = ord('f')
  25. elif stat.S_ISLNK(ft): perms[0] = ord('l')
  26. elif stat.S_ISSOCK(ft): perms[0] = ord('s')
  27. else: perms[0] = ord('!')
  28. # User
  29. if mode&stat.S_IRUSR:perms[1] = ord('r')
  30. if mode&stat.S_IWUSR:perms[2] = ord('w')
  31. if mode&stat.S_IXUSR:perms[3] = ord('x')
  32. # Group
  33. if mode&stat.S_IRGRP:perms[4] = ord('r')
  34. if mode&stat.S_IWGRP:perms[5] = ord('w')
  35. if mode&stat.S_IXGRP:perms[6] = ord('x')
  36. # Other
  37. if mode&stat.S_IROTH:perms[7] = ord('r')
  38. if mode&stat.S_IWOTH:perms[8] = ord('w')
  39. if mode&stat.S_IXOTH:perms[9] = ord('x')
  40. # Suid/sgid
  41. if mode&stat.S_ISUID:
  42. if perms[3] == ord('x'): perms[3] = ord('s')
  43. else: perms[3] = ord('S')
  44. if mode&stat.S_ISGID:
  45. if perms[6] == ord('x'): perms[6] = ord('s')
  46. else: perms[6] = ord('S')
  47. if _PY3:
  48. if isinstance(name, bytes):
  49. name = name.decode("utf-8")
  50. lsPerms = perms.tobytes()
  51. lsPerms = lsPerms.decode("utf-8")
  52. else:
  53. lsPerms = perms.tostring()
  54. lsresult = [
  55. lsPerms,
  56. str(s.st_nlink).rjust(5),
  57. ' ',
  58. str(s.st_uid).ljust(9),
  59. str(s.st_gid).ljust(9),
  60. str(s.st_size).rjust(8),
  61. ' ',
  62. ]
  63. # Need to specify the month manually, as strftime depends on locale
  64. ttup = localtime(s.st_mtime)
  65. sixmonths = 60 * 60 * 24 * 7 * 26
  66. if s.st_mtime + sixmonths < time(): # Last edited more than 6mo ago
  67. strtime = strftime("%%s %d %Y ", ttup)
  68. else:
  69. strtime = strftime("%%s %d %H:%M ", ttup)
  70. lsresult.append(strtime % (_MONTH_NAMES[ttup[1]],))
  71. lsresult.append(name)
  72. return ''.join(lsresult)
  73. __all__ = ['lsLine']