reflog.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. # reflog.py -- Parsing and writing reflog files
  2. # Copyright (C) 2015 Jelmer Vernooij and others.
  3. #
  4. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  5. # General Public License as public by the Free Software Foundation; version 2.0
  6. # or (at your option) any later version. You can redistribute it and/or
  7. # modify it under the terms of either of these two licenses.
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. #
  15. # You should have received a copy of the licenses; if not, see
  16. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  17. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  18. # License, Version 2.0.
  19. #
  20. """Utilities for reading and generating reflogs.
  21. """
  22. import collections
  23. from dulwich.objects import (
  24. format_timezone,
  25. parse_timezone,
  26. ZERO_SHA,
  27. )
  28. Entry = collections.namedtuple(
  29. "Entry",
  30. ["old_sha", "new_sha", "committer", "timestamp", "timezone", "message"],
  31. )
  32. def format_reflog_line(old_sha, new_sha, committer, timestamp, timezone, message):
  33. """Generate a single reflog line.
  34. Args:
  35. old_sha: Old Commit SHA
  36. new_sha: New Commit SHA
  37. committer: Committer name and e-mail
  38. timestamp: Timestamp
  39. timezone: Timezone
  40. message: Message
  41. """
  42. if old_sha is None:
  43. old_sha = ZERO_SHA
  44. return (
  45. old_sha
  46. + b" "
  47. + new_sha
  48. + b" "
  49. + committer
  50. + b" "
  51. + str(int(timestamp)).encode("ascii")
  52. + b" "
  53. + format_timezone(timezone)
  54. + b"\t"
  55. + message
  56. )
  57. def parse_reflog_line(line):
  58. """Parse a reflog line.
  59. Args:
  60. line: Line to parse
  61. Returns: Tuple of (old_sha, new_sha, committer, timestamp, timezone,
  62. message)
  63. """
  64. (begin, message) = line.split(b"\t", 1)
  65. (old_sha, new_sha, rest) = begin.split(b" ", 2)
  66. (committer, timestamp_str, timezone_str) = rest.rsplit(b" ", 2)
  67. return Entry(
  68. old_sha,
  69. new_sha,
  70. committer,
  71. int(timestamp_str),
  72. parse_timezone(timezone_str)[0],
  73. message,
  74. )
  75. def read_reflog(f):
  76. """Read reflog.
  77. Args:
  78. f: File-like object
  79. Returns: Iterator over Entry objects
  80. """
  81. for line in f:
  82. yield parse_reflog_line(line)