ls.py 2.6 KB

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