1use gix_hash::ObjectId;
2
3use crate::{log::Line, store_impl::file::log::LineRef};
4
5impl LineRef<'_> {
6 pub fn to_owned(&self) -> Line {
8 (*self).into()
9 }
10}
11
12mod write {
13 use std::io;
14
15 use gix_object::bstr::{BStr, ByteSlice};
16
17 use crate::log::Line;
18
19 #[derive(Debug, thiserror::Error)]
21 #[allow(missing_docs)]
22 enum Error {
23 #[error(r"Messages must not contain newlines (\n)")]
24 IllegalCharacter,
25 }
26
27 impl From<Error> for io::Error {
28 fn from(err: Error) -> Self {
29 io::Error::other(err)
30 }
31 }
32
33 impl Line {
35 pub fn write_to(&self, out: &mut dyn io::Write) -> io::Result<()> {
37 write!(out, "{} {} ", self.previous_oid, self.new_oid)?;
38 self.signature.write_to(out)?;
39 writeln!(out, "\t{}", check_newlines(self.message.as_ref())?)
40 }
41 }
42
43 fn check_newlines(input: &BStr) -> Result<&BStr, Error> {
44 if input.find_byte(b'\n').is_some() {
45 return Err(Error::IllegalCharacter);
46 }
47 Ok(input)
48 }
49}
50
51impl LineRef<'_> {
52 pub fn previous_oid(&self) -> ObjectId {
55 ObjectId::from_hex(self.previous_oid).expect("parse validation")
56 }
57 pub fn new_oid(&self) -> ObjectId {
59 ObjectId::from_hex(self.new_oid).expect("parse validation")
60 }
61}
62
63impl<'a> From<LineRef<'a>> for Line {
64 fn from(v: LineRef<'a>) -> Self {
65 Line {
66 previous_oid: v.previous_oid(),
67 new_oid: v.new_oid(),
68 signature: v.signature.into(),
69 message: v.message.into(),
70 }
71 }
72}
73
74pub mod decode {
76 use gix_object::bstr::{BStr, ByteSlice};
77 use winnow::{
78 combinator::{alt, eof, fail, opt, preceded, terminated},
79 error::{AddContext, ParserError, StrContext},
80 prelude::*,
81 token::{rest, take_while},
82 };
83
84 use crate::{file::log::LineRef, parse::hex_hash};
85
86 mod error {
88 use gix_object::bstr::{BString, ByteSlice};
89
90 #[derive(Debug)]
92 pub struct Error {
93 pub input: BString,
94 }
95
96 impl std::fmt::Display for Error {
97 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98 write!(
99 f,
100 r"{:?} did not match '<old-hexsha> <new-hexsha> <name> <<email>> <timestamp> <tz>\t<message>'",
101 self.input
102 )
103 }
104 }
105
106 impl std::error::Error for Error {}
107
108 impl Error {
109 pub(crate) fn new(input: &[u8]) -> Self {
110 Error {
111 input: input.as_bstr().to_owned(),
112 }
113 }
114 }
115 }
116 pub use error::Error;
117
118 impl<'a> LineRef<'a> {
119 pub fn from_bytes(mut input: &'a [u8]) -> Result<LineRef<'a>, Error> {
121 one::<()>(&mut input).map_err(|_| Error::new(input))
122 }
123 }
124
125 fn message<'a, E: ParserError<&'a [u8]>>(i: &mut &'a [u8]) -> ModalResult<&'a BStr, E> {
126 if i.is_empty() {
127 rest.map(ByteSlice::as_bstr).parse_next(i)
128 } else {
129 terminated(take_while(0.., |c| c != b'\n'), opt(b'\n'))
130 .map(ByteSlice::as_bstr)
131 .parse_next(i)
132 }
133 }
134
135 fn one<'a, E: ParserError<&'a [u8]> + AddContext<&'a [u8], StrContext>>(
136 bytes: &mut &'a [u8],
137 ) -> ModalResult<LineRef<'a>, E> {
138 let mut tokens = bytes.splitn(2, |b| *b == b'\t');
139 if let (Some(mut first), Some(mut second)) = (tokens.next(), tokens.next()) {
140 let (old, new, signature) = (
141 terminated(hex_hash, b" ").context(StrContext::Expected("<old-hexsha>".into())),
142 terminated(hex_hash, b" ").context(StrContext::Expected("<new-hexsha>".into())),
143 gix_actor::signature::decode.context(StrContext::Expected("<name> <<email>> <timestamp>".into())),
144 )
145 .context(StrContext::Expected(
146 r"<old-hexsha> <new-hexsha> <name> <<email>> <timestamp> <tz>\t<message>".into(),
147 ))
148 .parse_next(&mut first)?;
149
150 message.parse_next(bytes)?;
152 let message = message(&mut second)?;
153 Ok(LineRef {
154 previous_oid: old,
155 new_oid: new,
156 signature,
157 message,
158 })
159 } else {
160 (
161 (
162 terminated(hex_hash, b" ").context(StrContext::Expected("<old-hexsha>".into())),
163 terminated(hex_hash, b" ").context(StrContext::Expected("<new-hexsha>".into())),
164 gix_actor::signature::decode.context(StrContext::Expected("<name> <<email>> <timestamp>".into())),
165 )
166 .context(StrContext::Expected(
167 r"<old-hexsha> <new-hexsha> <name> <<email>> <timestamp> <tz>\t<message>".into(),
168 )),
169 alt((
170 preceded(
171 b'\t',
172 message.context(StrContext::Expected("<optional message>".into())),
173 ),
174 b'\n'.value(Default::default()),
175 eof.value(Default::default()),
176 fail.context(StrContext::Expected(
177 "log message must be separated from signature with whitespace".into(),
178 )),
179 )),
180 )
181 .map(|((old, new, signature), message)| LineRef {
182 previous_oid: old,
183 new_oid: new,
184 signature,
185 message,
186 })
187 .parse_next(bytes)
188 }
189 }
190
191 #[cfg(test)]
192 mod test {
193 use super::*;
194
195 fn hex_to_oid(hex: &str) -> gix_hash::ObjectId {
197 gix_hash::ObjectId::from_hex(hex.as_bytes()).expect("40 bytes hex")
198 }
199
200 fn with_newline(mut v: Vec<u8>) -> Vec<u8> {
201 v.push(b'\n');
202 v
203 }
204
205 mod invalid {
206 use gix_testtools::to_bstr_err;
207 use winnow::{error::TreeError, prelude::*};
208
209 use super::one;
210
211 #[test]
212 fn completely_bogus_shows_error_with_context() {
213 let err = one::<TreeError<&[u8], _>>
214 .parse_peek(b"definitely not a log entry")
215 .map_err(to_bstr_err)
216 .expect_err("this should fail");
217 assert!(err.to_string().contains("<old-hexsha> <new-hexsha>"));
218 }
219
220 #[test]
221 fn missing_whitespace_between_signature_and_message() {
222 let line = "0000000000000000000000000000000000000000 0000000000000000000000000000000000000000 one <foo@example.com> 1234567890 -0000message";
223 let err = one::<TreeError<&[u8], _>>
224 .parse_peek(line.as_bytes())
225 .map_err(to_bstr_err)
226 .expect_err("this should fail");
227 assert!(
228 err.to_string()
229 .contains("log message must be separated from signature with whitespace"),
230 "expected\n `log message must be separated from signature with whitespace`\nin\n```\n{err}\n```"
231 );
232 }
233 }
234
235 const NULL_SHA1: &[u8] = b"0000000000000000000000000000000000000000";
236
237 #[test]
238 fn entry_with_empty_message() {
239 let line_without_nl: Vec<_> = b"0000000000000000000000000000000000000000 0000000000000000000000000000000000000000 name <foo@example.com> 1234567890 -0000".to_vec();
240 let line_with_nl = with_newline(line_without_nl.clone());
241 for input in &[line_without_nl, line_with_nl] {
242 assert_eq!(
243 one::<winnow::error::InputError<_>>
244 .parse_peek(input)
245 .expect("successful parsing")
246 .1,
247 LineRef {
248 previous_oid: NULL_SHA1.as_bstr(),
249 new_oid: NULL_SHA1.as_bstr(),
250 signature: gix_actor::SignatureRef {
251 name: b"name".as_bstr(),
252 email: b"foo@example.com".as_bstr(),
253 time: "1234567890 -0000"
254 },
255 message: b"".as_bstr(),
256 }
257 );
258 }
259 }
260
261 #[test]
262 fn entry_with_message_without_newline_and_with_newline() {
263 let line_without_nl: Vec<_> = b"a5828ae6b52137b913b978e16cd2334482eb4c1f 89b43f80a514aee58b662ad606e6352e03eaeee4 Sebastian Thiel <foo@example.com> 1618030561 +0800\tpull --ff-only: Fast-forward".to_vec();
264 let line_with_nl = with_newline(line_without_nl.clone());
265
266 for input in &[line_without_nl, line_with_nl] {
267 let (remaining, res) = one::<winnow::error::InputError<_>>
268 .parse_peek(input)
269 .expect("successful parsing");
270 assert!(remaining.is_empty(), "all consuming even without trailing newline");
271 let actual = LineRef {
272 previous_oid: b"a5828ae6b52137b913b978e16cd2334482eb4c1f".as_bstr(),
273 new_oid: b"89b43f80a514aee58b662ad606e6352e03eaeee4".as_bstr(),
274 signature: gix_actor::SignatureRef {
275 name: b"Sebastian Thiel".as_bstr(),
276 email: b"foo@example.com".as_bstr(),
277 time: "1618030561 +0800",
278 },
279 message: b"pull --ff-only: Fast-forward".as_bstr(),
280 };
281 assert_eq!(res, actual);
282 assert_eq!(
283 actual.previous_oid(),
284 hex_to_oid("a5828ae6b52137b913b978e16cd2334482eb4c1f")
285 );
286 assert_eq!(actual.new_oid(), hex_to_oid("89b43f80a514aee58b662ad606e6352e03eaeee4"));
287 }
288 }
289
290 #[test]
291 fn two_lines_in_a_row_with_and_without_newline() {
292 let lines = b"0000000000000000000000000000000000000000 0000000000000000000000000000000000000000 one <foo@example.com> 1234567890 -0000\t\n0000000000000000000000000000000000000000 0000000000000000000000000000000000000000 two <foo@example.com> 1234567890 -0000\thello";
293 let (remainder, parsed) = one::<winnow::error::InputError<_>>
294 .parse_peek(lines)
295 .expect("parse single line");
296 assert_eq!(parsed.message, b"".as_bstr(), "first message is empty");
297
298 let (remainder, parsed) = one::<winnow::error::InputError<_>>
299 .parse_peek(remainder)
300 .expect("parse single line");
301 assert_eq!(
302 parsed.message,
303 b"hello".as_bstr(),
304 "second message is not and contains no newline"
305 );
306 assert!(remainder.is_empty());
307 }
308 }
309}