You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RawParseUtils.java 32KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066
  1. /*
  2. * Copyright (C) 2008-2009, Google Inc.
  3. * Copyright (C) 2006-2008, Shawn O. Pearce <spearce@spearce.org>
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package org.eclipse.jgit.util;
  45. import static org.eclipse.jgit.lib.ObjectChecker.author;
  46. import static org.eclipse.jgit.lib.ObjectChecker.committer;
  47. import static org.eclipse.jgit.lib.ObjectChecker.encoding;
  48. import static org.eclipse.jgit.lib.ObjectChecker.tagger;
  49. import java.nio.ByteBuffer;
  50. import java.nio.charset.CharacterCodingException;
  51. import java.nio.charset.Charset;
  52. import java.nio.charset.CharsetDecoder;
  53. import java.nio.charset.CodingErrorAction;
  54. import java.util.Arrays;
  55. import org.eclipse.jgit.lib.Constants;
  56. import org.eclipse.jgit.lib.PersonIdent;
  57. /** Handy utility functions to parse raw object contents. */
  58. public final class RawParseUtils {
  59. private static final byte[] digits10;
  60. private static final byte[] digits16;
  61. private static final byte[] footerLineKeyChars;
  62. static {
  63. digits10 = new byte['9' + 1];
  64. Arrays.fill(digits10, (byte) -1);
  65. for (char i = '0'; i <= '9'; i++)
  66. digits10[i] = (byte) (i - '0');
  67. digits16 = new byte['f' + 1];
  68. Arrays.fill(digits16, (byte) -1);
  69. for (char i = '0'; i <= '9'; i++)
  70. digits16[i] = (byte) (i - '0');
  71. for (char i = 'a'; i <= 'f'; i++)
  72. digits16[i] = (byte) ((i - 'a') + 10);
  73. for (char i = 'A'; i <= 'F'; i++)
  74. digits16[i] = (byte) ((i - 'A') + 10);
  75. footerLineKeyChars = new byte['z' + 1];
  76. footerLineKeyChars['-'] = 1;
  77. for (char i = '0'; i <= '9'; i++)
  78. footerLineKeyChars[i] = 1;
  79. for (char i = 'A'; i <= 'Z'; i++)
  80. footerLineKeyChars[i] = 1;
  81. for (char i = 'a'; i <= 'z'; i++)
  82. footerLineKeyChars[i] = 1;
  83. }
  84. /**
  85. * Determine if b[ptr] matches src.
  86. *
  87. * @param b
  88. * the buffer to scan.
  89. * @param ptr
  90. * first position within b, this should match src[0].
  91. * @param src
  92. * the buffer to test for equality with b.
  93. * @return ptr + src.length if b[ptr..src.length] == src; else -1.
  94. */
  95. public static final int match(final byte[] b, int ptr, final byte[] src) {
  96. if (ptr + src.length > b.length)
  97. return -1;
  98. for (int i = 0; i < src.length; i++, ptr++)
  99. if (b[ptr] != src[i])
  100. return -1;
  101. return ptr;
  102. }
  103. private static final byte[] base10byte = { '0', '1', '2', '3', '4', '5',
  104. '6', '7', '8', '9' };
  105. /**
  106. * Format a base 10 numeric into a temporary buffer.
  107. * <p>
  108. * Formatting is performed backwards. The method starts at offset
  109. * <code>o-1</code> and ends at <code>o-1-digits</code>, where
  110. * <code>digits</code> is the number of positions necessary to store the
  111. * base 10 value.
  112. * <p>
  113. * The argument and return values from this method make it easy to chain
  114. * writing, for example:
  115. * </p>
  116. *
  117. * <pre>
  118. * final byte[] tmp = new byte[64];
  119. * int ptr = tmp.length;
  120. * tmp[--ptr] = '\n';
  121. * ptr = RawParseUtils.formatBase10(tmp, ptr, 32);
  122. * tmp[--ptr] = ' ';
  123. * ptr = RawParseUtils.formatBase10(tmp, ptr, 18);
  124. * tmp[--ptr] = 0;
  125. * final String str = new String(tmp, ptr, tmp.length - ptr);
  126. * </pre>
  127. *
  128. * @param b
  129. * buffer to write into.
  130. * @param o
  131. * one offset past the location where writing will begin; writing
  132. * proceeds towards lower index values.
  133. * @param value
  134. * the value to store.
  135. * @return the new offset value <code>o</code>. This is the position of
  136. * the last byte written. Additional writing should start at one
  137. * position earlier.
  138. */
  139. public static int formatBase10(final byte[] b, int o, int value) {
  140. if (value == 0) {
  141. b[--o] = '0';
  142. return o;
  143. }
  144. final boolean isneg = value < 0;
  145. if (isneg)
  146. value = -value;
  147. while (value != 0) {
  148. b[--o] = base10byte[value % 10];
  149. value /= 10;
  150. }
  151. if (isneg)
  152. b[--o] = '-';
  153. return o;
  154. }
  155. /**
  156. * Parse a base 10 numeric from a sequence of ASCII digits into an int.
  157. * <p>
  158. * Digit sequences can begin with an optional run of spaces before the
  159. * sequence, and may start with a '+' or a '-' to indicate sign position.
  160. * Any other characters will cause the method to stop and return the current
  161. * result to the caller.
  162. *
  163. * @param b
  164. * buffer to scan.
  165. * @param ptr
  166. * position within buffer to start parsing digits at.
  167. * @param ptrResult
  168. * optional location to return the new ptr value through. If null
  169. * the ptr value will be discarded.
  170. * @return the value at this location; 0 if the location is not a valid
  171. * numeric.
  172. */
  173. public static final int parseBase10(final byte[] b, int ptr,
  174. final MutableInteger ptrResult) {
  175. int r = 0;
  176. int sign = 0;
  177. try {
  178. final int sz = b.length;
  179. while (ptr < sz && b[ptr] == ' ')
  180. ptr++;
  181. if (ptr >= sz)
  182. return 0;
  183. switch (b[ptr]) {
  184. case '-':
  185. sign = -1;
  186. ptr++;
  187. break;
  188. case '+':
  189. ptr++;
  190. break;
  191. }
  192. while (ptr < sz) {
  193. final byte v = digits10[b[ptr]];
  194. if (v < 0)
  195. break;
  196. r = (r * 10) + v;
  197. ptr++;
  198. }
  199. } catch (ArrayIndexOutOfBoundsException e) {
  200. // Not a valid digit.
  201. }
  202. if (ptrResult != null)
  203. ptrResult.value = ptr;
  204. return sign < 0 ? -r : r;
  205. }
  206. /**
  207. * Parse a base 10 numeric from a sequence of ASCII digits into a long.
  208. * <p>
  209. * Digit sequences can begin with an optional run of spaces before the
  210. * sequence, and may start with a '+' or a '-' to indicate sign position.
  211. * Any other characters will cause the method to stop and return the current
  212. * result to the caller.
  213. *
  214. * @param b
  215. * buffer to scan.
  216. * @param ptr
  217. * position within buffer to start parsing digits at.
  218. * @param ptrResult
  219. * optional location to return the new ptr value through. If null
  220. * the ptr value will be discarded.
  221. * @return the value at this location; 0 if the location is not a valid
  222. * numeric.
  223. */
  224. public static final long parseLongBase10(final byte[] b, int ptr,
  225. final MutableInteger ptrResult) {
  226. long r = 0;
  227. int sign = 0;
  228. try {
  229. final int sz = b.length;
  230. while (ptr < sz && b[ptr] == ' ')
  231. ptr++;
  232. if (ptr >= sz)
  233. return 0;
  234. switch (b[ptr]) {
  235. case '-':
  236. sign = -1;
  237. ptr++;
  238. break;
  239. case '+':
  240. ptr++;
  241. break;
  242. }
  243. while (ptr < sz) {
  244. final byte v = digits10[b[ptr]];
  245. if (v < 0)
  246. break;
  247. r = (r * 10) + v;
  248. ptr++;
  249. }
  250. } catch (ArrayIndexOutOfBoundsException e) {
  251. // Not a valid digit.
  252. }
  253. if (ptrResult != null)
  254. ptrResult.value = ptr;
  255. return sign < 0 ? -r : r;
  256. }
  257. /**
  258. * Parse 4 character base 16 (hex) formatted string to unsigned integer.
  259. * <p>
  260. * The number is read in network byte order, that is, most significant
  261. * nybble first.
  262. *
  263. * @param bs
  264. * buffer to parse digits from; positions {@code [p, p+4)} will
  265. * be parsed.
  266. * @param p
  267. * first position within the buffer to parse.
  268. * @return the integer value.
  269. * @throws ArrayIndexOutOfBoundsException
  270. * if the string is not hex formatted.
  271. */
  272. public static final int parseHexInt16(final byte[] bs, final int p) {
  273. int r = digits16[bs[p]] << 4;
  274. r |= digits16[bs[p + 1]];
  275. r <<= 4;
  276. r |= digits16[bs[p + 2]];
  277. r <<= 4;
  278. r |= digits16[bs[p + 3]];
  279. if (r < 0)
  280. throw new ArrayIndexOutOfBoundsException();
  281. return r;
  282. }
  283. /**
  284. * Parse 8 character base 16 (hex) formatted string to unsigned integer.
  285. * <p>
  286. * The number is read in network byte order, that is, most significant
  287. * nybble first.
  288. *
  289. * @param bs
  290. * buffer to parse digits from; positions {@code [p, p+8)} will
  291. * be parsed.
  292. * @param p
  293. * first position within the buffer to parse.
  294. * @return the integer value.
  295. * @throws ArrayIndexOutOfBoundsException
  296. * if the string is not hex formatted.
  297. */
  298. public static final int parseHexInt32(final byte[] bs, final int p) {
  299. int r = digits16[bs[p]] << 4;
  300. r |= digits16[bs[p + 1]];
  301. r <<= 4;
  302. r |= digits16[bs[p + 2]];
  303. r <<= 4;
  304. r |= digits16[bs[p + 3]];
  305. r <<= 4;
  306. r |= digits16[bs[p + 4]];
  307. r <<= 4;
  308. r |= digits16[bs[p + 5]];
  309. r <<= 4;
  310. r |= digits16[bs[p + 6]];
  311. final int last = digits16[bs[p + 7]];
  312. if (r < 0 || last < 0)
  313. throw new ArrayIndexOutOfBoundsException();
  314. return (r << 4) | last;
  315. }
  316. /**
  317. * Parse a single hex digit to its numeric value (0-15).
  318. *
  319. * @param digit
  320. * hex character to parse.
  321. * @return numeric value, in the range 0-15.
  322. * @throws ArrayIndexOutOfBoundsException
  323. * if the input digit is not a valid hex digit.
  324. */
  325. public static final int parseHexInt4(final byte digit) {
  326. final byte r = digits16[digit];
  327. if (r < 0)
  328. throw new ArrayIndexOutOfBoundsException();
  329. return r;
  330. }
  331. /**
  332. * Parse a Git style timezone string.
  333. * <p>
  334. * The sequence "-0315" will be parsed as the numeric value -195, as the
  335. * lower two positions count minutes, not 100ths of an hour.
  336. *
  337. * @param b
  338. * buffer to scan.
  339. * @param ptr
  340. * position within buffer to start parsing digits at.
  341. * @return the timezone at this location, expressed in minutes.
  342. */
  343. public static final int parseTimeZoneOffset(final byte[] b, int ptr) {
  344. final int v = parseBase10(b, ptr, null);
  345. final int tzMins = v % 100;
  346. final int tzHours = v / 100;
  347. return tzHours * 60 + tzMins;
  348. }
  349. /**
  350. * Locate the first position after a given character.
  351. *
  352. * @param b
  353. * buffer to scan.
  354. * @param ptr
  355. * position within buffer to start looking for chrA at.
  356. * @param chrA
  357. * character to find.
  358. * @return new position just after chrA.
  359. */
  360. public static final int next(final byte[] b, int ptr, final char chrA) {
  361. final int sz = b.length;
  362. while (ptr < sz) {
  363. if (b[ptr++] == chrA)
  364. return ptr;
  365. }
  366. return ptr;
  367. }
  368. /**
  369. * Locate the first position after the next LF.
  370. * <p>
  371. * This method stops on the first '\n' it finds.
  372. *
  373. * @param b
  374. * buffer to scan.
  375. * @param ptr
  376. * position within buffer to start looking for LF at.
  377. * @return new position just after the first LF found.
  378. */
  379. public static final int nextLF(final byte[] b, int ptr) {
  380. return next(b, ptr, '\n');
  381. }
  382. /**
  383. * Locate the first position after either the given character or LF.
  384. * <p>
  385. * This method stops on the first match it finds from either chrA or '\n'.
  386. *
  387. * @param b
  388. * buffer to scan.
  389. * @param ptr
  390. * position within buffer to start looking for chrA or LF at.
  391. * @param chrA
  392. * character to find.
  393. * @return new position just after the first chrA or LF to be found.
  394. */
  395. public static final int nextLF(final byte[] b, int ptr, final char chrA) {
  396. final int sz = b.length;
  397. while (ptr < sz) {
  398. final byte c = b[ptr++];
  399. if (c == chrA || c == '\n')
  400. return ptr;
  401. }
  402. return ptr;
  403. }
  404. /**
  405. * Locate the first position before a given character.
  406. *
  407. * @param b
  408. * buffer to scan.
  409. * @param ptr
  410. * position within buffer to start looking for chrA at.
  411. * @param chrA
  412. * character to find.
  413. * @return new position just before chrA, -1 for not found
  414. */
  415. public static final int prev(final byte[] b, int ptr, final char chrA) {
  416. if (ptr == b.length)
  417. --ptr;
  418. while (ptr >= 0) {
  419. if (b[ptr--] == chrA)
  420. return ptr;
  421. }
  422. return ptr;
  423. }
  424. /**
  425. * Locate the first position before the previous LF.
  426. * <p>
  427. * This method stops on the first '\n' it finds.
  428. *
  429. * @param b
  430. * buffer to scan.
  431. * @param ptr
  432. * position within buffer to start looking for LF at.
  433. * @return new position just before the first LF found, -1 for not found
  434. */
  435. public static final int prevLF(final byte[] b, int ptr) {
  436. return prev(b, ptr, '\n');
  437. }
  438. /**
  439. * Locate the previous position before either the given character or LF.
  440. * <p>
  441. * This method stops on the first match it finds from either chrA or '\n'.
  442. *
  443. * @param b
  444. * buffer to scan.
  445. * @param ptr
  446. * position within buffer to start looking for chrA or LF at.
  447. * @param chrA
  448. * character to find.
  449. * @return new position just before the first chrA or LF to be found, -1 for
  450. * not found
  451. */
  452. public static final int prevLF(final byte[] b, int ptr, final char chrA) {
  453. if (ptr == b.length)
  454. --ptr;
  455. while (ptr >= 0) {
  456. final byte c = b[ptr--];
  457. if (c == chrA || c == '\n')
  458. return ptr;
  459. }
  460. return ptr;
  461. }
  462. /**
  463. * Index the region between <code>[ptr, end)</code> to find line starts.
  464. * <p>
  465. * The returned list is 1 indexed. Index 0 contains
  466. * {@link Integer#MIN_VALUE} to pad the list out.
  467. * <p>
  468. * Using a 1 indexed list means that line numbers can be directly accessed
  469. * from the list, so <code>list.get(1)</code> (aka get line 1) returns
  470. * <code>ptr</code>.
  471. * <p>
  472. * The last element (index <code>map.size()-1</code>) always contains
  473. * <code>end</code>.
  474. *
  475. * @param buf
  476. * buffer to scan.
  477. * @param ptr
  478. * position within the buffer corresponding to the first byte of
  479. * line 1.
  480. * @param end
  481. * 1 past the end of the content within <code>buf</code>.
  482. * @return a line map indexing the start position of each line.
  483. */
  484. public static final IntList lineMap(final byte[] buf, int ptr, int end) {
  485. // Experimentally derived from multiple source repositories
  486. // the average number of bytes/line is 36. Its a rough guess
  487. // to initially size our map close to the target.
  488. //
  489. final IntList map = new IntList((end - ptr) / 36);
  490. map.fillTo(1, Integer.MIN_VALUE);
  491. for (; ptr < end; ptr = nextLF(buf, ptr))
  492. map.add(ptr);
  493. map.add(end);
  494. return map;
  495. }
  496. /**
  497. * Locate the "author " header line data.
  498. *
  499. * @param b
  500. * buffer to scan.
  501. * @param ptr
  502. * position in buffer to start the scan at. Most callers should
  503. * pass 0 to ensure the scan starts from the beginning of the
  504. * commit buffer and does not accidentally look at message body.
  505. * @return position just after the space in "author ", so the first
  506. * character of the author's name. If no author header can be
  507. * located -1 is returned.
  508. */
  509. public static final int author(final byte[] b, int ptr) {
  510. final int sz = b.length;
  511. if (ptr == 0)
  512. ptr += 46; // skip the "tree ..." line.
  513. while (ptr < sz && b[ptr] == 'p')
  514. ptr += 48; // skip this parent.
  515. return match(b, ptr, author);
  516. }
  517. /**
  518. * Locate the "committer " header line data.
  519. *
  520. * @param b
  521. * buffer to scan.
  522. * @param ptr
  523. * position in buffer to start the scan at. Most callers should
  524. * pass 0 to ensure the scan starts from the beginning of the
  525. * commit buffer and does not accidentally look at message body.
  526. * @return position just after the space in "committer ", so the first
  527. * character of the committer's name. If no committer header can be
  528. * located -1 is returned.
  529. */
  530. public static final int committer(final byte[] b, int ptr) {
  531. final int sz = b.length;
  532. if (ptr == 0)
  533. ptr += 46; // skip the "tree ..." line.
  534. while (ptr < sz && b[ptr] == 'p')
  535. ptr += 48; // skip this parent.
  536. if (ptr < sz && b[ptr] == 'a')
  537. ptr = nextLF(b, ptr);
  538. return match(b, ptr, committer);
  539. }
  540. /**
  541. * Locate the "tagger " header line data.
  542. *
  543. * @param b
  544. * buffer to scan.
  545. * @param ptr
  546. * position in buffer to start the scan at. Most callers should
  547. * pass 0 to ensure the scan starts from the beginning of the tag
  548. * buffer and does not accidentally look at message body.
  549. * @return position just after the space in "tagger ", so the first
  550. * character of the tagger's name. If no tagger header can be
  551. * located -1 is returned.
  552. */
  553. public static final int tagger(final byte[] b, int ptr) {
  554. final int sz = b.length;
  555. if (ptr == 0)
  556. ptr += 48; // skip the "object ..." line.
  557. while (ptr < sz) {
  558. if (b[ptr] == '\n')
  559. return -1;
  560. final int m = match(b, ptr, tagger);
  561. if (m >= 0)
  562. return m;
  563. ptr = nextLF(b, ptr);
  564. }
  565. return -1;
  566. }
  567. /**
  568. * Locate the "encoding " header line.
  569. *
  570. * @param b
  571. * buffer to scan.
  572. * @param ptr
  573. * position in buffer to start the scan at. Most callers should
  574. * pass 0 to ensure the scan starts from the beginning of the
  575. * buffer and does not accidentally look at the message body.
  576. * @return position just after the space in "encoding ", so the first
  577. * character of the encoding's name. If no encoding header can be
  578. * located -1 is returned (and UTF-8 should be assumed).
  579. */
  580. public static final int encoding(final byte[] b, int ptr) {
  581. final int sz = b.length;
  582. while (ptr < sz) {
  583. if (b[ptr] == '\n')
  584. return -1;
  585. if (b[ptr] == 'e')
  586. break;
  587. ptr = nextLF(b, ptr);
  588. }
  589. return match(b, ptr, encoding);
  590. }
  591. /**
  592. * Parse the "encoding " header into a character set reference.
  593. * <p>
  594. * Locates the "encoding " header (if present) by first calling
  595. * {@link #encoding(byte[], int)} and then returns the proper character set
  596. * to apply to this buffer to evaluate its contents as character data.
  597. * <p>
  598. * If no encoding header is present, {@link Constants#CHARSET} is assumed.
  599. *
  600. * @param b
  601. * buffer to scan.
  602. * @return the Java character set representation. Never null.
  603. */
  604. public static Charset parseEncoding(final byte[] b) {
  605. final int enc = encoding(b, 0);
  606. if (enc < 0)
  607. return Constants.CHARSET;
  608. final int lf = nextLF(b, enc);
  609. return Charset.forName(decode(Constants.CHARSET, b, enc, lf - 1));
  610. }
  611. /**
  612. * Parse a name string (e.g. author, committer, tagger) into a PersonIdent.
  613. * <p>
  614. * Leading spaces won't be trimmed from the string, i.e. will show up in the
  615. * parsed name afterwards.
  616. *
  617. * @param in
  618. * the string to parse a name from.
  619. * @return the parsed identity or null in case the identity could not be
  620. * parsed.
  621. */
  622. public static PersonIdent parsePersonIdent(final String in) {
  623. return parsePersonIdent(Constants.encode(in), 0);
  624. }
  625. /**
  626. * Parse a name line (e.g. author, committer, tagger) into a PersonIdent.
  627. * <p>
  628. * When passing in a value for <code>nameB</code> callers should use the
  629. * return value of {@link #author(byte[], int)} or
  630. * {@link #committer(byte[], int)}, as these methods provide the proper
  631. * position within the buffer.
  632. *
  633. * @param raw
  634. * the buffer to parse character data from.
  635. * @param nameB
  636. * first position of the identity information. This should be the
  637. * first position after the space which delimits the header field
  638. * name (e.g. "author" or "committer") from the rest of the
  639. * identity line.
  640. * @return the parsed identity or null in case the identity could not be
  641. * parsed.
  642. */
  643. public static PersonIdent parsePersonIdent(final byte[] raw, final int nameB) {
  644. final Charset cs = parseEncoding(raw);
  645. final int emailB = nextLF(raw, nameB, '<');
  646. final int emailE = nextLF(raw, emailB, '>');
  647. if (emailB >= raw.length || raw[emailB] == '\n' ||
  648. (emailE >= raw.length - 1 && raw[emailE - 1] != '>'))
  649. return null;
  650. final int nameEnd = emailB - 2 >= 0 && raw[emailB - 2] == ' ' ? emailB - 2
  651. : emailB - 1;
  652. final String name = decode(cs, raw, nameB, nameEnd);
  653. final String email = decode(cs, raw, emailB, emailE - 1);
  654. // Start searching from end of line, as after first name-email pair,
  655. // another name-email pair may occur. We will ignore all kinds of
  656. // "junk" following the first email.
  657. //
  658. // We've to use (emailE - 1) for the case that raw[email] is LF,
  659. // otherwise we would run too far. "-2" is necessary to position
  660. // before the LF in case of LF termination resp. the penultimate
  661. // character if there is no trailing LF.
  662. final int tzBegin = lastIndexOfTrim(raw, ' ',
  663. nextLF(raw, emailE - 1) - 2) + 1;
  664. if (tzBegin <= emailE) // No time/zone, still valid
  665. return new PersonIdent(name, email, 0, 0);
  666. final int whenBegin = Math.max(emailE,
  667. lastIndexOfTrim(raw, ' ', tzBegin - 1) + 1);
  668. if (whenBegin >= tzBegin - 1) // No time/zone, still valid
  669. return new PersonIdent(name, email, 0, 0);
  670. final long when = parseLongBase10(raw, whenBegin, null);
  671. final int tz = parseTimeZoneOffset(raw, tzBegin);
  672. return new PersonIdent(name, email, when * 1000L, tz);
  673. }
  674. /**
  675. * Parse a name data (e.g. as within a reflog) into a PersonIdent.
  676. * <p>
  677. * When passing in a value for <code>nameB</code> callers should use the
  678. * return value of {@link #author(byte[], int)} or
  679. * {@link #committer(byte[], int)}, as these methods provide the proper
  680. * position within the buffer.
  681. *
  682. * @param raw
  683. * the buffer to parse character data from.
  684. * @param nameB
  685. * first position of the identity information. This should be the
  686. * first position after the space which delimits the header field
  687. * name (e.g. "author" or "committer") from the rest of the
  688. * identity line.
  689. * @return the parsed identity. Never null.
  690. */
  691. public static PersonIdent parsePersonIdentOnly(final byte[] raw,
  692. final int nameB) {
  693. int stop = nextLF(raw, nameB);
  694. int emailB = nextLF(raw, nameB, '<');
  695. int emailE = nextLF(raw, emailB, '>');
  696. final String name;
  697. final String email;
  698. if (emailE < stop) {
  699. email = decode(raw, emailB, emailE - 1);
  700. } else {
  701. email = "invalid";
  702. }
  703. if (emailB < stop)
  704. name = decode(raw, nameB, emailB - 2);
  705. else
  706. name = decode(raw, nameB, stop);
  707. final MutableInteger ptrout = new MutableInteger();
  708. long when;
  709. int tz;
  710. if (emailE < stop) {
  711. when = parseLongBase10(raw, emailE + 1, ptrout);
  712. tz = parseTimeZoneOffset(raw, ptrout.value);
  713. } else {
  714. when = 0;
  715. tz = 0;
  716. }
  717. return new PersonIdent(name, email, when * 1000L, tz);
  718. }
  719. /**
  720. * Locate the end of a footer line key string.
  721. * <p>
  722. * If the region at {@code raw[ptr]} matches {@code ^[A-Za-z0-9-]+:} (e.g.
  723. * "Signed-off-by: A. U. Thor\n") then this method returns the position of
  724. * the first ':'.
  725. * <p>
  726. * If the region at {@code raw[ptr]} does not match {@code ^[A-Za-z0-9-]+:}
  727. * then this method returns -1.
  728. *
  729. * @param raw
  730. * buffer to scan.
  731. * @param ptr
  732. * first position within raw to consider as a footer line key.
  733. * @return position of the ':' which terminates the footer line key if this
  734. * is otherwise a valid footer line key; otherwise -1.
  735. */
  736. public static int endOfFooterLineKey(final byte[] raw, int ptr) {
  737. try {
  738. for (;;) {
  739. final byte c = raw[ptr];
  740. if (footerLineKeyChars[c] == 0) {
  741. if (c == ':')
  742. return ptr;
  743. return -1;
  744. }
  745. ptr++;
  746. }
  747. } catch (ArrayIndexOutOfBoundsException e) {
  748. return -1;
  749. }
  750. }
  751. /**
  752. * Decode a buffer under UTF-8, if possible.
  753. *
  754. * If the byte stream cannot be decoded that way, the platform default is tried
  755. * and if that too fails, the fail-safe ISO-8859-1 encoding is tried.
  756. *
  757. * @param buffer
  758. * buffer to pull raw bytes from.
  759. * @return a string representation of the range <code>[start,end)</code>,
  760. * after decoding the region through the specified character set.
  761. */
  762. public static String decode(final byte[] buffer) {
  763. return decode(buffer, 0, buffer.length);
  764. }
  765. /**
  766. * Decode a buffer under UTF-8, if possible.
  767. *
  768. * If the byte stream cannot be decoded that way, the platform default is
  769. * tried and if that too fails, the fail-safe ISO-8859-1 encoding is tried.
  770. *
  771. * @param buffer
  772. * buffer to pull raw bytes from.
  773. * @param start
  774. * start position in buffer
  775. * @param end
  776. * one position past the last location within the buffer to take
  777. * data from.
  778. * @return a string representation of the range <code>[start,end)</code>,
  779. * after decoding the region through the specified character set.
  780. */
  781. public static String decode(final byte[] buffer, final int start,
  782. final int end) {
  783. return decode(Constants.CHARSET, buffer, start, end);
  784. }
  785. /**
  786. * Decode a buffer under the specified character set if possible.
  787. *
  788. * If the byte stream cannot be decoded that way, the platform default is tried
  789. * and if that too fails, the fail-safe ISO-8859-1 encoding is tried.
  790. *
  791. * @param cs
  792. * character set to use when decoding the buffer.
  793. * @param buffer
  794. * buffer to pull raw bytes from.
  795. * @return a string representation of the range <code>[start,end)</code>,
  796. * after decoding the region through the specified character set.
  797. */
  798. public static String decode(final Charset cs, final byte[] buffer) {
  799. return decode(cs, buffer, 0, buffer.length);
  800. }
  801. /**
  802. * Decode a region of the buffer under the specified character set if possible.
  803. *
  804. * If the byte stream cannot be decoded that way, the platform default is tried
  805. * and if that too fails, the fail-safe ISO-8859-1 encoding is tried.
  806. *
  807. * @param cs
  808. * character set to use when decoding the buffer.
  809. * @param buffer
  810. * buffer to pull raw bytes from.
  811. * @param start
  812. * first position within the buffer to take data from.
  813. * @param end
  814. * one position past the last location within the buffer to take
  815. * data from.
  816. * @return a string representation of the range <code>[start,end)</code>,
  817. * after decoding the region through the specified character set.
  818. */
  819. public static String decode(final Charset cs, final byte[] buffer,
  820. final int start, final int end) {
  821. try {
  822. return decodeNoFallback(cs, buffer, start, end);
  823. } catch (CharacterCodingException e) {
  824. // Fall back to an ISO-8859-1 style encoding. At least all of
  825. // the bytes will be present in the output.
  826. //
  827. return extractBinaryString(buffer, start, end);
  828. }
  829. }
  830. /**
  831. * Decode a region of the buffer under the specified character set if
  832. * possible.
  833. *
  834. * If the byte stream cannot be decoded that way, the platform default is
  835. * tried and if that too fails, an exception is thrown.
  836. *
  837. * @param cs
  838. * character set to use when decoding the buffer.
  839. * @param buffer
  840. * buffer to pull raw bytes from.
  841. * @param start
  842. * first position within the buffer to take data from.
  843. * @param end
  844. * one position past the last location within the buffer to take
  845. * data from.
  846. * @return a string representation of the range <code>[start,end)</code>,
  847. * after decoding the region through the specified character set.
  848. * @throws CharacterCodingException
  849. * the input is not in any of the tested character sets.
  850. */
  851. public static String decodeNoFallback(final Charset cs,
  852. final byte[] buffer, final int start, final int end)
  853. throws CharacterCodingException {
  854. final ByteBuffer b = ByteBuffer.wrap(buffer, start, end - start);
  855. b.mark();
  856. // Try our built-in favorite. The assumption here is that
  857. // decoding will fail if the data is not actually encoded
  858. // using that encoder.
  859. //
  860. try {
  861. return decode(b, Constants.CHARSET);
  862. } catch (CharacterCodingException e) {
  863. b.reset();
  864. }
  865. if (!cs.equals(Constants.CHARSET)) {
  866. // Try the suggested encoding, it might be right since it was
  867. // provided by the caller.
  868. //
  869. try {
  870. return decode(b, cs);
  871. } catch (CharacterCodingException e) {
  872. b.reset();
  873. }
  874. }
  875. // Try the default character set. A small group of people
  876. // might actually use the same (or very similar) locale.
  877. //
  878. final Charset defcs = Charset.defaultCharset();
  879. if (!defcs.equals(cs) && !defcs.equals(Constants.CHARSET)) {
  880. try {
  881. return decode(b, defcs);
  882. } catch (CharacterCodingException e) {
  883. b.reset();
  884. }
  885. }
  886. throw new CharacterCodingException();
  887. }
  888. /**
  889. * Decode a region of the buffer under the ISO-8859-1 encoding.
  890. *
  891. * Each byte is treated as a single character in the 8859-1 character
  892. * encoding, performing a raw binary->char conversion.
  893. *
  894. * @param buffer
  895. * buffer to pull raw bytes from.
  896. * @param start
  897. * first position within the buffer to take data from.
  898. * @param end
  899. * one position past the last location within the buffer to take
  900. * data from.
  901. * @return a string representation of the range <code>[start,end)</code>.
  902. */
  903. public static String extractBinaryString(final byte[] buffer,
  904. final int start, final int end) {
  905. final StringBuilder r = new StringBuilder(end - start);
  906. for (int i = start; i < end; i++)
  907. r.append((char) (buffer[i] & 0xff));
  908. return r.toString();
  909. }
  910. private static String decode(final ByteBuffer b, final Charset charset)
  911. throws CharacterCodingException {
  912. final CharsetDecoder d = charset.newDecoder();
  913. d.onMalformedInput(CodingErrorAction.REPORT);
  914. d.onUnmappableCharacter(CodingErrorAction.REPORT);
  915. return d.decode(b).toString();
  916. }
  917. /**
  918. * Locate the position of the commit message body.
  919. *
  920. * @param b
  921. * buffer to scan.
  922. * @param ptr
  923. * position in buffer to start the scan at. Most callers should
  924. * pass 0 to ensure the scan starts from the beginning of the
  925. * commit buffer.
  926. * @return position of the user's message buffer.
  927. */
  928. public static final int commitMessage(final byte[] b, int ptr) {
  929. final int sz = b.length;
  930. if (ptr == 0)
  931. ptr += 46; // skip the "tree ..." line.
  932. while (ptr < sz && b[ptr] == 'p')
  933. ptr += 48; // skip this parent.
  934. // Skip any remaining header lines, ignoring what their actual
  935. // header line type is. This is identical to the logic for a tag.
  936. //
  937. return tagMessage(b, ptr);
  938. }
  939. /**
  940. * Locate the position of the tag message body.
  941. *
  942. * @param b
  943. * buffer to scan.
  944. * @param ptr
  945. * position in buffer to start the scan at. Most callers should
  946. * pass 0 to ensure the scan starts from the beginning of the tag
  947. * buffer.
  948. * @return position of the user's message buffer.
  949. */
  950. public static final int tagMessage(final byte[] b, int ptr) {
  951. final int sz = b.length;
  952. if (ptr == 0)
  953. ptr += 48; // skip the "object ..." line.
  954. while (ptr < sz && b[ptr] != '\n')
  955. ptr = nextLF(b, ptr);
  956. if (ptr < sz && b[ptr] == '\n')
  957. return ptr + 1;
  958. return -1;
  959. }
  960. /**
  961. * Locate the end of a paragraph.
  962. * <p>
  963. * A paragraph is ended by two consecutive LF bytes.
  964. *
  965. * @param b
  966. * buffer to scan.
  967. * @param start
  968. * position in buffer to start the scan at. Most callers will
  969. * want to pass the first position of the commit message (as
  970. * found by {@link #commitMessage(byte[], int)}.
  971. * @return position of the LF at the end of the paragraph;
  972. * <code>b.length</code> if no paragraph end could be located.
  973. */
  974. public static final int endOfParagraph(final byte[] b, final int start) {
  975. int ptr = start;
  976. final int sz = b.length;
  977. while (ptr < sz && b[ptr] != '\n')
  978. ptr = nextLF(b, ptr);
  979. while (0 < ptr && start < ptr && b[ptr - 1] == '\n')
  980. ptr--;
  981. return ptr;
  982. }
  983. private static int lastIndexOfTrim(byte[] raw, char ch, int pos) {
  984. while (pos >= 0 && raw[pos] == ' ')
  985. pos--;
  986. while (pos >= 0 && raw[pos] != ch)
  987. pos--;
  988. return pos;
  989. }
  990. private RawParseUtils() {
  991. // Don't create instances of a static only utility.
  992. }
  993. }