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.

Repository.java 56KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825
  1. /*
  2. * Copyright (C) 2007, Dave Watson <dwatson@mimvista.com>
  3. * Copyright (C) 2008-2010, Google Inc.
  4. * Copyright (C) 2006-2010, Robin Rosenberg <robin.rosenberg@dewire.com>
  5. * Copyright (C) 2006-2012, Shawn O. Pearce <spearce@spearce.org>
  6. * Copyright (C) 2012, Daniel Megert <daniel_megert@ch.ibm.com>
  7. * and other copyright owners as documented in the project's IP log.
  8. *
  9. * This program and the accompanying materials are made available
  10. * under the terms of the Eclipse Distribution License v1.0 which
  11. * accompanies this distribution, is reproduced below, and is
  12. * available at http://www.eclipse.org/org/documents/edl-v10.php
  13. *
  14. * All rights reserved.
  15. *
  16. * Redistribution and use in source and binary forms, with or
  17. * without modification, are permitted provided that the following
  18. * conditions are met:
  19. *
  20. * - Redistributions of source code must retain the above copyright
  21. * notice, this list of conditions and the following disclaimer.
  22. *
  23. * - Redistributions in binary form must reproduce the above
  24. * copyright notice, this list of conditions and the following
  25. * disclaimer in the documentation and/or other materials provided
  26. * with the distribution.
  27. *
  28. * - Neither the name of the Eclipse Foundation, Inc. nor the
  29. * names of its contributors may be used to endorse or promote
  30. * products derived from this software without specific prior
  31. * written permission.
  32. *
  33. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  34. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  35. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  36. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  37. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  38. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  39. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  40. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  41. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  42. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  43. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  44. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  45. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  46. */
  47. package org.eclipse.jgit.lib;
  48. import java.io.BufferedOutputStream;
  49. import java.io.File;
  50. import java.io.FileNotFoundException;
  51. import java.io.FileOutputStream;
  52. import java.io.IOException;
  53. import java.net.URISyntaxException;
  54. import java.text.MessageFormat;
  55. import java.util.Collection;
  56. import java.util.Collections;
  57. import java.util.HashMap;
  58. import java.util.HashSet;
  59. import java.util.LinkedList;
  60. import java.util.List;
  61. import java.util.Map;
  62. import java.util.Set;
  63. import java.util.concurrent.atomic.AtomicInteger;
  64. import org.eclipse.jgit.annotations.NonNull;
  65. import org.eclipse.jgit.annotations.Nullable;
  66. import org.eclipse.jgit.attributes.AttributesNodeProvider;
  67. import org.eclipse.jgit.dircache.DirCache;
  68. import org.eclipse.jgit.errors.AmbiguousObjectException;
  69. import org.eclipse.jgit.errors.CorruptObjectException;
  70. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  71. import org.eclipse.jgit.errors.MissingObjectException;
  72. import org.eclipse.jgit.errors.NoWorkTreeException;
  73. import org.eclipse.jgit.errors.RevisionSyntaxException;
  74. import org.eclipse.jgit.events.IndexChangedEvent;
  75. import org.eclipse.jgit.events.IndexChangedListener;
  76. import org.eclipse.jgit.events.ListenerList;
  77. import org.eclipse.jgit.events.RepositoryEvent;
  78. import org.eclipse.jgit.internal.JGitText;
  79. import org.eclipse.jgit.revwalk.RevBlob;
  80. import org.eclipse.jgit.revwalk.RevCommit;
  81. import org.eclipse.jgit.revwalk.RevObject;
  82. import org.eclipse.jgit.revwalk.RevTree;
  83. import org.eclipse.jgit.revwalk.RevWalk;
  84. import org.eclipse.jgit.transport.RefSpec;
  85. import org.eclipse.jgit.transport.RemoteConfig;
  86. import org.eclipse.jgit.treewalk.TreeWalk;
  87. import org.eclipse.jgit.util.FS;
  88. import org.eclipse.jgit.util.FileUtils;
  89. import org.eclipse.jgit.util.IO;
  90. import org.eclipse.jgit.util.RawParseUtils;
  91. import org.eclipse.jgit.util.SystemReader;
  92. import org.eclipse.jgit.util.io.SafeBufferedOutputStream;
  93. /**
  94. * Represents a Git repository.
  95. * <p>
  96. * A repository holds all objects and refs used for managing source code (could
  97. * be any type of file, but source code is what SCM's are typically used for).
  98. * <p>
  99. * This class is thread-safe.
  100. */
  101. public abstract class Repository implements AutoCloseable {
  102. private static final ListenerList globalListeners = new ListenerList();
  103. /** @return the global listener list observing all events in this JVM. */
  104. public static ListenerList getGlobalListenerList() {
  105. return globalListeners;
  106. }
  107. /** Use counter */
  108. final AtomicInteger useCnt = new AtomicInteger(1);
  109. /** Metadata directory holding the repository's critical files. */
  110. private final File gitDir;
  111. /** File abstraction used to resolve paths. */
  112. private final FS fs;
  113. private final ListenerList myListeners = new ListenerList();
  114. /** If not bare, the top level directory of the working files. */
  115. private final File workTree;
  116. /** If not bare, the index file caching the working file states. */
  117. private final File indexFile;
  118. /**
  119. * Initialize a new repository instance.
  120. *
  121. * @param options
  122. * options to configure the repository.
  123. */
  124. protected Repository(final BaseRepositoryBuilder options) {
  125. gitDir = options.getGitDir();
  126. fs = options.getFS();
  127. workTree = options.getWorkTree();
  128. indexFile = options.getIndexFile();
  129. }
  130. /** @return listeners observing only events on this repository. */
  131. @NonNull
  132. public ListenerList getListenerList() {
  133. return myListeners;
  134. }
  135. /**
  136. * Fire an event to all registered listeners.
  137. * <p>
  138. * The source repository of the event is automatically set to this
  139. * repository, before the event is delivered to any listeners.
  140. *
  141. * @param event
  142. * the event to deliver.
  143. */
  144. public void fireEvent(RepositoryEvent<?> event) {
  145. event.setRepository(this);
  146. myListeners.dispatch(event);
  147. globalListeners.dispatch(event);
  148. }
  149. /**
  150. * Create a new Git repository.
  151. * <p>
  152. * Repository with working tree is created using this method. This method is
  153. * the same as {@code create(false)}.
  154. *
  155. * @throws IOException
  156. * @see #create(boolean)
  157. */
  158. public void create() throws IOException {
  159. create(false);
  160. }
  161. /**
  162. * Create a new Git repository initializing the necessary files and
  163. * directories.
  164. *
  165. * @param bare
  166. * if true, a bare repository (a repository without a working
  167. * directory) is created.
  168. * @throws IOException
  169. * in case of IO problem
  170. */
  171. public abstract void create(boolean bare) throws IOException;
  172. /**
  173. * @return local metadata directory; {@code null} if repository isn't local.
  174. */
  175. /*
  176. * TODO This method should be annotated as Nullable, because in some
  177. * specific configurations metadata is not located in the local file system
  178. * (for example in memory databases). In "usual" repositories this
  179. * annotation would only cause compiler errors at places where the actual
  180. * directory can never be null.
  181. */
  182. public File getDirectory() {
  183. return gitDir;
  184. }
  185. /**
  186. * @return the object database which stores this repository's data.
  187. */
  188. @NonNull
  189. public abstract ObjectDatabase getObjectDatabase();
  190. /** @return a new inserter to create objects in {@link #getObjectDatabase()} */
  191. @NonNull
  192. public ObjectInserter newObjectInserter() {
  193. return getObjectDatabase().newInserter();
  194. }
  195. /** @return a new reader to read objects from {@link #getObjectDatabase()} */
  196. @NonNull
  197. public ObjectReader newObjectReader() {
  198. return getObjectDatabase().newReader();
  199. }
  200. /** @return the reference database which stores the reference namespace. */
  201. @NonNull
  202. public abstract RefDatabase getRefDatabase();
  203. /**
  204. * @return the configuration of this repository
  205. */
  206. @NonNull
  207. public abstract StoredConfig getConfig();
  208. /**
  209. * @return a new {@link AttributesNodeProvider}. This
  210. * {@link AttributesNodeProvider} is lazy loaded only once. It means
  211. * that it will not be updated after loading. Prefer creating new
  212. * instance for each use.
  213. * @since 4.2
  214. */
  215. @NonNull
  216. public abstract AttributesNodeProvider createAttributesNodeProvider();
  217. /**
  218. * @return the used file system abstraction, or or {@code null} if
  219. * repository isn't local.
  220. */
  221. /*
  222. * TODO This method should be annotated as Nullable, because in some
  223. * specific configurations metadata is not located in the local file system
  224. * (for example in memory databases). In "usual" repositories this
  225. * annotation would only cause compiler errors at places where the actual
  226. * directory can never be null.
  227. */
  228. public FS getFS() {
  229. return fs;
  230. }
  231. /**
  232. * @param objectId
  233. * @return true if the specified object is stored in this repo or any of the
  234. * known shared repositories.
  235. */
  236. public boolean hasObject(AnyObjectId objectId) {
  237. try {
  238. return getObjectDatabase().has(objectId);
  239. } catch (IOException e) {
  240. // Legacy API, assume error means "no"
  241. return false;
  242. }
  243. }
  244. /**
  245. * Open an object from this repository.
  246. * <p>
  247. * This is a one-shot call interface which may be faster than allocating a
  248. * {@link #newObjectReader()} to perform the lookup.
  249. *
  250. * @param objectId
  251. * identity of the object to open.
  252. * @return a {@link ObjectLoader} for accessing the object.
  253. * @throws MissingObjectException
  254. * the object does not exist.
  255. * @throws IOException
  256. * the object store cannot be accessed.
  257. */
  258. @NonNull
  259. public ObjectLoader open(final AnyObjectId objectId)
  260. throws MissingObjectException, IOException {
  261. return getObjectDatabase().open(objectId);
  262. }
  263. /**
  264. * Open an object from this repository.
  265. * <p>
  266. * This is a one-shot call interface which may be faster than allocating a
  267. * {@link #newObjectReader()} to perform the lookup.
  268. *
  269. * @param objectId
  270. * identity of the object to open.
  271. * @param typeHint
  272. * hint about the type of object being requested, e.g.
  273. * {@link Constants#OBJ_BLOB}; {@link ObjectReader#OBJ_ANY} if
  274. * the object type is not known, or does not matter to the
  275. * caller.
  276. * @return a {@link ObjectLoader} for accessing the object.
  277. * @throws MissingObjectException
  278. * the object does not exist.
  279. * @throws IncorrectObjectTypeException
  280. * typeHint was not OBJ_ANY, and the object's actual type does
  281. * not match typeHint.
  282. * @throws IOException
  283. * the object store cannot be accessed.
  284. */
  285. @NonNull
  286. public ObjectLoader open(AnyObjectId objectId, int typeHint)
  287. throws MissingObjectException, IncorrectObjectTypeException,
  288. IOException {
  289. return getObjectDatabase().open(objectId, typeHint);
  290. }
  291. /**
  292. * Create a command to update, create or delete a ref in this repository.
  293. *
  294. * @param ref
  295. * name of the ref the caller wants to modify.
  296. * @return an update command. The caller must finish populating this command
  297. * and then invoke one of the update methods to actually make a
  298. * change.
  299. * @throws IOException
  300. * a symbolic ref was passed in and could not be resolved back
  301. * to the base ref, as the symbolic ref could not be read.
  302. */
  303. @NonNull
  304. public RefUpdate updateRef(final String ref) throws IOException {
  305. return updateRef(ref, false);
  306. }
  307. /**
  308. * Create a command to update, create or delete a ref in this repository.
  309. *
  310. * @param ref
  311. * name of the ref the caller wants to modify.
  312. * @param detach
  313. * true to create a detached head
  314. * @return an update command. The caller must finish populating this command
  315. * and then invoke one of the update methods to actually make a
  316. * change.
  317. * @throws IOException
  318. * a symbolic ref was passed in and could not be resolved back
  319. * to the base ref, as the symbolic ref could not be read.
  320. */
  321. @NonNull
  322. public RefUpdate updateRef(final String ref, final boolean detach) throws IOException {
  323. return getRefDatabase().newUpdate(ref, detach);
  324. }
  325. /**
  326. * Create a command to rename a ref in this repository
  327. *
  328. * @param fromRef
  329. * name of ref to rename from
  330. * @param toRef
  331. * name of ref to rename to
  332. * @return an update command that knows how to rename a branch to another.
  333. * @throws IOException
  334. * the rename could not be performed.
  335. *
  336. */
  337. @NonNull
  338. public RefRename renameRef(final String fromRef, final String toRef) throws IOException {
  339. return getRefDatabase().newRename(fromRef, toRef);
  340. }
  341. /**
  342. * Parse a git revision string and return an object id.
  343. *
  344. * Combinations of these operators are supported:
  345. * <ul>
  346. * <li><b>HEAD</b>, <b>MERGE_HEAD</b>, <b>FETCH_HEAD</b></li>
  347. * <li><b>SHA-1</b>: a complete or abbreviated SHA-1</li>
  348. * <li><b>refs/...</b>: a complete reference name</li>
  349. * <li><b>short-name</b>: a short reference name under {@code refs/heads},
  350. * {@code refs/tags}, or {@code refs/remotes} namespace</li>
  351. * <li><b>tag-NN-gABBREV</b>: output from describe, parsed by treating
  352. * {@code ABBREV} as an abbreviated SHA-1.</li>
  353. * <li><i>id</i><b>^</b>: first parent of commit <i>id</i>, this is the same
  354. * as {@code id^1}</li>
  355. * <li><i>id</i><b>^0</b>: ensure <i>id</i> is a commit</li>
  356. * <li><i>id</i><b>^n</b>: n-th parent of commit <i>id</i></li>
  357. * <li><i>id</i><b>~n</b>: n-th historical ancestor of <i>id</i>, by first
  358. * parent. {@code id~3} is equivalent to {@code id^1^1^1} or {@code id^^^}.</li>
  359. * <li><i>id</i><b>:path</b>: Lookup path under tree named by <i>id</i></li>
  360. * <li><i>id</i><b>^{commit}</b>: ensure <i>id</i> is a commit</li>
  361. * <li><i>id</i><b>^{tree}</b>: ensure <i>id</i> is a tree</li>
  362. * <li><i>id</i><b>^{tag}</b>: ensure <i>id</i> is a tag</li>
  363. * <li><i>id</i><b>^{blob}</b>: ensure <i>id</i> is a blob</li>
  364. * </ul>
  365. *
  366. * <p>
  367. * The following operators are specified by Git conventions, but are not
  368. * supported by this method:
  369. * <ul>
  370. * <li><b>ref@{n}</b>: n-th version of ref as given by its reflog</li>
  371. * <li><b>ref@{time}</b>: value of ref at the designated time</li>
  372. * </ul>
  373. *
  374. * @param revstr
  375. * A git object references expression
  376. * @return an ObjectId or {@code null} if revstr can't be resolved to any
  377. * ObjectId
  378. * @throws AmbiguousObjectException
  379. * {@code revstr} contains an abbreviated ObjectId and this
  380. * repository contains more than one object which match to the
  381. * input abbreviation.
  382. * @throws IncorrectObjectTypeException
  383. * the id parsed does not meet the type required to finish
  384. * applying the operators in the expression.
  385. * @throws RevisionSyntaxException
  386. * the expression is not supported by this implementation, or
  387. * does not meet the standard syntax.
  388. * @throws IOException
  389. * on serious errors
  390. */
  391. @Nullable
  392. public ObjectId resolve(final String revstr)
  393. throws AmbiguousObjectException, IncorrectObjectTypeException,
  394. RevisionSyntaxException, IOException {
  395. try (RevWalk rw = new RevWalk(this)) {
  396. Object resolved = resolve(rw, revstr);
  397. if (resolved instanceof String) {
  398. final Ref ref = getRef((String)resolved);
  399. return ref != null ? ref.getLeaf().getObjectId() : null;
  400. } else {
  401. return (ObjectId) resolved;
  402. }
  403. }
  404. }
  405. /**
  406. * Simplify an expression, but unlike {@link #resolve(String)} it will not
  407. * resolve a branch passed or resulting from the expression, such as @{-}.
  408. * Thus this method can be used to process an expression to a method that
  409. * expects a branch or revision id.
  410. *
  411. * @param revstr
  412. * @return object id or ref name from resolved expression or {@code null} if
  413. * given expression cannot be resolved
  414. * @throws AmbiguousObjectException
  415. * @throws IOException
  416. */
  417. @Nullable
  418. public String simplify(final String revstr)
  419. throws AmbiguousObjectException, IOException {
  420. try (RevWalk rw = new RevWalk(this)) {
  421. Object resolved = resolve(rw, revstr);
  422. if (resolved != null)
  423. if (resolved instanceof String)
  424. return (String) resolved;
  425. else
  426. return ((AnyObjectId) resolved).getName();
  427. return null;
  428. }
  429. }
  430. @Nullable
  431. private Object resolve(final RevWalk rw, final String revstr)
  432. throws IOException {
  433. char[] revChars = revstr.toCharArray();
  434. RevObject rev = null;
  435. String name = null;
  436. int done = 0;
  437. for (int i = 0; i < revChars.length; ++i) {
  438. switch (revChars[i]) {
  439. case '^':
  440. if (rev == null) {
  441. if (name == null)
  442. if (done == 0)
  443. name = new String(revChars, done, i);
  444. else {
  445. done = i + 1;
  446. break;
  447. }
  448. rev = parseSimple(rw, name);
  449. name = null;
  450. if (rev == null)
  451. return null;
  452. }
  453. if (i + 1 < revChars.length) {
  454. switch (revChars[i + 1]) {
  455. case '0':
  456. case '1':
  457. case '2':
  458. case '3':
  459. case '4':
  460. case '5':
  461. case '6':
  462. case '7':
  463. case '8':
  464. case '9':
  465. int j;
  466. rev = rw.parseCommit(rev);
  467. for (j = i + 1; j < revChars.length; ++j) {
  468. if (!Character.isDigit(revChars[j]))
  469. break;
  470. }
  471. String parentnum = new String(revChars, i + 1, j - i
  472. - 1);
  473. int pnum;
  474. try {
  475. pnum = Integer.parseInt(parentnum);
  476. } catch (NumberFormatException e) {
  477. throw new RevisionSyntaxException(
  478. JGitText.get().invalidCommitParentNumber,
  479. revstr);
  480. }
  481. if (pnum != 0) {
  482. RevCommit commit = (RevCommit) rev;
  483. if (pnum > commit.getParentCount())
  484. rev = null;
  485. else
  486. rev = commit.getParent(pnum - 1);
  487. }
  488. i = j - 1;
  489. done = j;
  490. break;
  491. case '{':
  492. int k;
  493. String item = null;
  494. for (k = i + 2; k < revChars.length; ++k) {
  495. if (revChars[k] == '}') {
  496. item = new String(revChars, i + 2, k - i - 2);
  497. break;
  498. }
  499. }
  500. i = k;
  501. if (item != null)
  502. if (item.equals("tree")) { //$NON-NLS-1$
  503. rev = rw.parseTree(rev);
  504. } else if (item.equals("commit")) { //$NON-NLS-1$
  505. rev = rw.parseCommit(rev);
  506. } else if (item.equals("blob")) { //$NON-NLS-1$
  507. rev = rw.peel(rev);
  508. if (!(rev instanceof RevBlob))
  509. throw new IncorrectObjectTypeException(rev,
  510. Constants.TYPE_BLOB);
  511. } else if (item.equals("")) { //$NON-NLS-1$
  512. rev = rw.peel(rev);
  513. } else
  514. throw new RevisionSyntaxException(revstr);
  515. else
  516. throw new RevisionSyntaxException(revstr);
  517. done = k;
  518. break;
  519. default:
  520. rev = rw.peel(rev);
  521. if (rev instanceof RevCommit) {
  522. RevCommit commit = ((RevCommit) rev);
  523. if (commit.getParentCount() == 0)
  524. rev = null;
  525. else
  526. rev = commit.getParent(0);
  527. } else
  528. throw new IncorrectObjectTypeException(rev,
  529. Constants.TYPE_COMMIT);
  530. }
  531. } else {
  532. rev = rw.peel(rev);
  533. if (rev instanceof RevCommit) {
  534. RevCommit commit = ((RevCommit) rev);
  535. if (commit.getParentCount() == 0)
  536. rev = null;
  537. else
  538. rev = commit.getParent(0);
  539. } else
  540. throw new IncorrectObjectTypeException(rev,
  541. Constants.TYPE_COMMIT);
  542. }
  543. done = i + 1;
  544. break;
  545. case '~':
  546. if (rev == null) {
  547. if (name == null)
  548. if (done == 0)
  549. name = new String(revChars, done, i);
  550. else {
  551. done = i + 1;
  552. break;
  553. }
  554. rev = parseSimple(rw, name);
  555. name = null;
  556. if (rev == null)
  557. return null;
  558. }
  559. rev = rw.peel(rev);
  560. if (!(rev instanceof RevCommit))
  561. throw new IncorrectObjectTypeException(rev,
  562. Constants.TYPE_COMMIT);
  563. int l;
  564. for (l = i + 1; l < revChars.length; ++l) {
  565. if (!Character.isDigit(revChars[l]))
  566. break;
  567. }
  568. int dist;
  569. if (l - i > 1) {
  570. String distnum = new String(revChars, i + 1, l - i - 1);
  571. try {
  572. dist = Integer.parseInt(distnum);
  573. } catch (NumberFormatException e) {
  574. throw new RevisionSyntaxException(
  575. JGitText.get().invalidAncestryLength, revstr);
  576. }
  577. } else
  578. dist = 1;
  579. while (dist > 0) {
  580. RevCommit commit = (RevCommit) rev;
  581. if (commit.getParentCount() == 0) {
  582. rev = null;
  583. break;
  584. }
  585. commit = commit.getParent(0);
  586. rw.parseHeaders(commit);
  587. rev = commit;
  588. --dist;
  589. }
  590. i = l - 1;
  591. done = l;
  592. break;
  593. case '@':
  594. if (rev != null)
  595. throw new RevisionSyntaxException(revstr);
  596. if (i + 1 < revChars.length && revChars[i + 1] != '{')
  597. continue;
  598. int m;
  599. String time = null;
  600. for (m = i + 2; m < revChars.length; ++m) {
  601. if (revChars[m] == '}') {
  602. time = new String(revChars, i + 2, m - i - 2);
  603. break;
  604. }
  605. }
  606. if (time != null) {
  607. if (time.equals("upstream")) { //$NON-NLS-1$
  608. if (name == null)
  609. name = new String(revChars, done, i);
  610. if (name.equals("")) //$NON-NLS-1$
  611. // Currently checked out branch, HEAD if
  612. // detached
  613. name = Constants.HEAD;
  614. if (!Repository.isValidRefName("x/" + name)) //$NON-NLS-1$
  615. throw new RevisionSyntaxException(revstr);
  616. Ref ref = getRef(name);
  617. name = null;
  618. if (ref == null)
  619. return null;
  620. if (ref.isSymbolic())
  621. ref = ref.getLeaf();
  622. name = ref.getName();
  623. RemoteConfig remoteConfig;
  624. try {
  625. remoteConfig = new RemoteConfig(getConfig(),
  626. "origin"); //$NON-NLS-1$
  627. } catch (URISyntaxException e) {
  628. throw new RevisionSyntaxException(revstr);
  629. }
  630. String remoteBranchName = getConfig()
  631. .getString(
  632. ConfigConstants.CONFIG_BRANCH_SECTION,
  633. Repository.shortenRefName(ref.getName()),
  634. ConfigConstants.CONFIG_KEY_MERGE);
  635. List<RefSpec> fetchRefSpecs = remoteConfig
  636. .getFetchRefSpecs();
  637. for (RefSpec refSpec : fetchRefSpecs) {
  638. if (refSpec.matchSource(remoteBranchName)) {
  639. RefSpec expandFromSource = refSpec
  640. .expandFromSource(remoteBranchName);
  641. name = expandFromSource.getDestination();
  642. break;
  643. }
  644. }
  645. if (name == null)
  646. throw new RevisionSyntaxException(revstr);
  647. } else if (time.matches("^-\\d+$")) { //$NON-NLS-1$
  648. if (name != null)
  649. throw new RevisionSyntaxException(revstr);
  650. else {
  651. String previousCheckout = resolveReflogCheckout(-Integer
  652. .parseInt(time));
  653. if (ObjectId.isId(previousCheckout))
  654. rev = parseSimple(rw, previousCheckout);
  655. else
  656. name = previousCheckout;
  657. }
  658. } else {
  659. if (name == null)
  660. name = new String(revChars, done, i);
  661. if (name.equals("")) //$NON-NLS-1$
  662. name = Constants.HEAD;
  663. if (!Repository.isValidRefName("x/" + name)) //$NON-NLS-1$
  664. throw new RevisionSyntaxException(revstr);
  665. Ref ref = getRef(name);
  666. name = null;
  667. if (ref == null)
  668. return null;
  669. // @{n} means current branch, not HEAD@{1} unless
  670. // detached
  671. if (ref.isSymbolic())
  672. ref = ref.getLeaf();
  673. rev = resolveReflog(rw, ref, time);
  674. }
  675. i = m;
  676. } else
  677. throw new RevisionSyntaxException(revstr);
  678. break;
  679. case ':': {
  680. RevTree tree;
  681. if (rev == null) {
  682. if (name == null)
  683. name = new String(revChars, done, i);
  684. if (name.equals("")) //$NON-NLS-1$
  685. name = Constants.HEAD;
  686. rev = parseSimple(rw, name);
  687. name = null;
  688. }
  689. if (rev == null)
  690. return null;
  691. tree = rw.parseTree(rev);
  692. if (i == revChars.length - 1)
  693. return tree.copy();
  694. TreeWalk tw = TreeWalk.forPath(rw.getObjectReader(),
  695. new String(revChars, i + 1, revChars.length - i - 1),
  696. tree);
  697. return tw != null ? tw.getObjectId(0) : null;
  698. }
  699. default:
  700. if (rev != null)
  701. throw new RevisionSyntaxException(revstr);
  702. }
  703. }
  704. if (rev != null)
  705. return rev.copy();
  706. if (name != null)
  707. return name;
  708. if (done == revstr.length())
  709. return null;
  710. name = revstr.substring(done);
  711. if (!Repository.isValidRefName("x/" + name)) //$NON-NLS-1$
  712. throw new RevisionSyntaxException(revstr);
  713. if (getRef(name) != null)
  714. return name;
  715. return resolveSimple(name);
  716. }
  717. private static boolean isHex(char c) {
  718. return ('0' <= c && c <= '9') //
  719. || ('a' <= c && c <= 'f') //
  720. || ('A' <= c && c <= 'F');
  721. }
  722. private static boolean isAllHex(String str, int ptr) {
  723. while (ptr < str.length()) {
  724. if (!isHex(str.charAt(ptr++)))
  725. return false;
  726. }
  727. return true;
  728. }
  729. @Nullable
  730. private RevObject parseSimple(RevWalk rw, String revstr) throws IOException {
  731. ObjectId id = resolveSimple(revstr);
  732. return id != null ? rw.parseAny(id) : null;
  733. }
  734. @Nullable
  735. private ObjectId resolveSimple(final String revstr) throws IOException {
  736. if (ObjectId.isId(revstr))
  737. return ObjectId.fromString(revstr);
  738. if (Repository.isValidRefName("x/" + revstr)) { //$NON-NLS-1$
  739. Ref r = getRefDatabase().getRef(revstr);
  740. if (r != null)
  741. return r.getObjectId();
  742. }
  743. if (AbbreviatedObjectId.isId(revstr))
  744. return resolveAbbreviation(revstr);
  745. int dashg = revstr.indexOf("-g"); //$NON-NLS-1$
  746. if ((dashg + 5) < revstr.length() && 0 <= dashg
  747. && isHex(revstr.charAt(dashg + 2))
  748. && isHex(revstr.charAt(dashg + 3))
  749. && isAllHex(revstr, dashg + 4)) {
  750. // Possibly output from git describe?
  751. String s = revstr.substring(dashg + 2);
  752. if (AbbreviatedObjectId.isId(s))
  753. return resolveAbbreviation(s);
  754. }
  755. return null;
  756. }
  757. @Nullable
  758. private String resolveReflogCheckout(int checkoutNo)
  759. throws IOException {
  760. ReflogReader reader = getReflogReader(Constants.HEAD);
  761. if (reader == null) {
  762. return null;
  763. }
  764. List<ReflogEntry> reflogEntries = reader.getReverseEntries();
  765. for (ReflogEntry entry : reflogEntries) {
  766. CheckoutEntry checkout = entry.parseCheckout();
  767. if (checkout != null)
  768. if (checkoutNo-- == 1)
  769. return checkout.getFromBranch();
  770. }
  771. return null;
  772. }
  773. private RevCommit resolveReflog(RevWalk rw, Ref ref, String time)
  774. throws IOException {
  775. int number;
  776. try {
  777. number = Integer.parseInt(time);
  778. } catch (NumberFormatException nfe) {
  779. throw new RevisionSyntaxException(MessageFormat.format(
  780. JGitText.get().invalidReflogRevision, time));
  781. }
  782. assert number >= 0;
  783. ReflogReader reader = getReflogReader(ref.getName());
  784. if (reader == null) {
  785. throw new RevisionSyntaxException(
  786. MessageFormat.format(JGitText.get().reflogEntryNotFound,
  787. Integer.valueOf(number), ref.getName()));
  788. }
  789. ReflogEntry entry = reader.getReverseEntry(number);
  790. if (entry == null)
  791. throw new RevisionSyntaxException(MessageFormat.format(
  792. JGitText.get().reflogEntryNotFound,
  793. Integer.valueOf(number), ref.getName()));
  794. return rw.parseCommit(entry.getNewId());
  795. }
  796. @Nullable
  797. private ObjectId resolveAbbreviation(final String revstr) throws IOException,
  798. AmbiguousObjectException {
  799. AbbreviatedObjectId id = AbbreviatedObjectId.fromString(revstr);
  800. try (ObjectReader reader = newObjectReader()) {
  801. Collection<ObjectId> matches = reader.resolve(id);
  802. if (matches.size() == 0)
  803. return null;
  804. else if (matches.size() == 1)
  805. return matches.iterator().next();
  806. else
  807. throw new AmbiguousObjectException(id, matches);
  808. }
  809. }
  810. /** Increment the use counter by one, requiring a matched {@link #close()}. */
  811. public void incrementOpen() {
  812. useCnt.incrementAndGet();
  813. }
  814. /** Decrement the use count, and maybe close resources. */
  815. public void close() {
  816. if (useCnt.decrementAndGet() == 0) {
  817. doClose();
  818. RepositoryCache.unregister(this);
  819. }
  820. }
  821. /**
  822. * Invoked when the use count drops to zero during {@link #close()}.
  823. * <p>
  824. * The default implementation closes the object and ref databases.
  825. */
  826. protected void doClose() {
  827. getObjectDatabase().close();
  828. getRefDatabase().close();
  829. }
  830. @NonNull
  831. @SuppressWarnings("nls")
  832. public String toString() {
  833. String desc;
  834. File directory = getDirectory();
  835. if (directory != null)
  836. desc = directory.getPath();
  837. else
  838. desc = getClass().getSimpleName() + "-" //$NON-NLS-1$
  839. + System.identityHashCode(this);
  840. return "Repository[" + desc + "]"; //$NON-NLS-1$
  841. }
  842. /**
  843. * Get the name of the reference that {@code HEAD} points to.
  844. * <p>
  845. * This is essentially the same as doing:
  846. *
  847. * <pre>
  848. * return exactRef(Constants.HEAD).getTarget().getName()
  849. * </pre>
  850. *
  851. * Except when HEAD is detached, in which case this method returns the
  852. * current ObjectId in hexadecimal string format.
  853. *
  854. * @return name of current branch (for example {@code refs/heads/master}),
  855. * an ObjectId in hex format if the current branch is detached, or
  856. * {@code null} if the repository is corrupt and has no HEAD
  857. * reference.
  858. * @throws IOException
  859. */
  860. @Nullable
  861. public String getFullBranch() throws IOException {
  862. Ref head = exactRef(Constants.HEAD);
  863. if (head == null) {
  864. return null;
  865. }
  866. if (head.isSymbolic()) {
  867. return head.getTarget().getName();
  868. }
  869. ObjectId objectId = head.getObjectId();
  870. if (objectId != null) {
  871. return objectId.name();
  872. }
  873. return null;
  874. }
  875. /**
  876. * Get the short name of the current branch that {@code HEAD} points to.
  877. * <p>
  878. * This is essentially the same as {@link #getFullBranch()}, except the
  879. * leading prefix {@code refs/heads/} is removed from the reference before
  880. * it is returned to the caller.
  881. *
  882. * @return name of current branch (for example {@code master}), an ObjectId
  883. * in hex format if the current branch is detached, or {@code null}
  884. * if the repository is corrupt and has no HEAD reference.
  885. * @throws IOException
  886. */
  887. @Nullable
  888. public String getBranch() throws IOException {
  889. String name = getFullBranch();
  890. if (name != null)
  891. return shortenRefName(name);
  892. return null;
  893. }
  894. /**
  895. * Objects known to exist but not expressed by {@link #getAllRefs()}.
  896. * <p>
  897. * When a repository borrows objects from another repository, it can
  898. * advertise that it safely has that other repository's references, without
  899. * exposing any other details about the other repository. This may help
  900. * a client trying to push changes avoid pushing more than it needs to.
  901. *
  902. * @return unmodifiable collection of other known objects.
  903. */
  904. @NonNull
  905. public Set<ObjectId> getAdditionalHaves() {
  906. return Collections.emptySet();
  907. }
  908. /**
  909. * Get a ref by name.
  910. *
  911. * @param name
  912. * the name of the ref to lookup. May be a short-hand form, e.g.
  913. * "master" which is is automatically expanded to
  914. * "refs/heads/master" if "refs/heads/master" already exists.
  915. * @return the Ref with the given name, or {@code null} if it does not exist
  916. * @throws IOException
  917. * @deprecated Use {@link #exactRef(String)} or {@link #findRef(String)}
  918. * instead.
  919. */
  920. @Deprecated
  921. @Nullable
  922. public Ref getRef(final String name) throws IOException {
  923. return findRef(name);
  924. }
  925. /**
  926. * Get a ref by name.
  927. *
  928. * @param name
  929. * the name of the ref to lookup. Must not be a short-hand
  930. * form; e.g., "master" is not automatically expanded to
  931. * "refs/heads/master".
  932. * @return the Ref with the given name, or {@code null} if it does not exist
  933. * @throws IOException
  934. * @since 4.2
  935. */
  936. @Nullable
  937. public Ref exactRef(String name) throws IOException {
  938. return getRefDatabase().exactRef(name);
  939. }
  940. /**
  941. * Search for a ref by (possibly abbreviated) name.
  942. *
  943. * @param name
  944. * the name of the ref to lookup. May be a short-hand form, e.g.
  945. * "master" which is is automatically expanded to
  946. * "refs/heads/master" if "refs/heads/master" already exists.
  947. * @return the Ref with the given name, or {@code null} if it does not exist
  948. * @throws IOException
  949. * @since 4.2
  950. */
  951. @Nullable
  952. public Ref findRef(String name) throws IOException {
  953. return getRefDatabase().getRef(name);
  954. }
  955. /**
  956. * @return mutable map of all known refs (heads, tags, remotes).
  957. */
  958. @NonNull
  959. public Map<String, Ref> getAllRefs() {
  960. try {
  961. return getRefDatabase().getRefs(RefDatabase.ALL);
  962. } catch (IOException e) {
  963. return new HashMap<String, Ref>();
  964. }
  965. }
  966. /**
  967. * @return mutable map of all tags; key is short tag name ("v1.0") and value
  968. * of the entry contains the ref with the full tag name
  969. * ("refs/tags/v1.0").
  970. */
  971. @NonNull
  972. public Map<String, Ref> getTags() {
  973. try {
  974. return getRefDatabase().getRefs(Constants.R_TAGS);
  975. } catch (IOException e) {
  976. return new HashMap<String, Ref>();
  977. }
  978. }
  979. /**
  980. * Peel a possibly unpeeled reference to an annotated tag.
  981. * <p>
  982. * If the ref cannot be peeled (as it does not refer to an annotated tag)
  983. * the peeled id stays null, but {@link Ref#isPeeled()} will be true.
  984. *
  985. * @param ref
  986. * The ref to peel
  987. * @return <code>ref</code> if <code>ref.isPeeled()</code> is true; else a
  988. * new Ref object representing the same data as Ref, but isPeeled()
  989. * will be true and getPeeledObjectId will contain the peeled object
  990. * (or null).
  991. */
  992. @NonNull
  993. public Ref peel(final Ref ref) {
  994. try {
  995. return getRefDatabase().peel(ref);
  996. } catch (IOException e) {
  997. // Historical accident; if the reference cannot be peeled due
  998. // to some sort of repository access problem we claim that the
  999. // same as if the reference was not an annotated tag.
  1000. return ref;
  1001. }
  1002. }
  1003. /**
  1004. * @return a map with all objects referenced by a peeled ref.
  1005. */
  1006. @NonNull
  1007. public Map<AnyObjectId, Set<Ref>> getAllRefsByPeeledObjectId() {
  1008. Map<String, Ref> allRefs = getAllRefs();
  1009. Map<AnyObjectId, Set<Ref>> ret = new HashMap<AnyObjectId, Set<Ref>>(allRefs.size());
  1010. for (Ref ref : allRefs.values()) {
  1011. ref = peel(ref);
  1012. AnyObjectId target = ref.getPeeledObjectId();
  1013. if (target == null)
  1014. target = ref.getObjectId();
  1015. // We assume most Sets here are singletons
  1016. Set<Ref> oset = ret.put(target, Collections.singleton(ref));
  1017. if (oset != null) {
  1018. // that was not the case (rare)
  1019. if (oset.size() == 1) {
  1020. // Was a read-only singleton, we must copy to a new Set
  1021. oset = new HashSet<Ref>(oset);
  1022. }
  1023. ret.put(target, oset);
  1024. oset.add(ref);
  1025. }
  1026. }
  1027. return ret;
  1028. }
  1029. /**
  1030. * @return the index file location or {@code null} if repository isn't
  1031. * local.
  1032. * @throws NoWorkTreeException
  1033. * if this is bare, which implies it has no working directory.
  1034. * See {@link #isBare()}.
  1035. */
  1036. @NonNull
  1037. public File getIndexFile() throws NoWorkTreeException {
  1038. if (isBare())
  1039. throw new NoWorkTreeException();
  1040. return indexFile;
  1041. }
  1042. /**
  1043. * Create a new in-core index representation and read an index from disk.
  1044. * <p>
  1045. * The new index will be read before it is returned to the caller. Read
  1046. * failures are reported as exceptions and therefore prevent the method from
  1047. * returning a partially populated index.
  1048. *
  1049. * @return a cache representing the contents of the specified index file (if
  1050. * it exists) or an empty cache if the file does not exist.
  1051. * @throws NoWorkTreeException
  1052. * if this is bare, which implies it has no working directory.
  1053. * See {@link #isBare()}.
  1054. * @throws IOException
  1055. * the index file is present but could not be read.
  1056. * @throws CorruptObjectException
  1057. * the index file is using a format or extension that this
  1058. * library does not support.
  1059. */
  1060. @NonNull
  1061. public DirCache readDirCache() throws NoWorkTreeException,
  1062. CorruptObjectException, IOException {
  1063. return DirCache.read(this);
  1064. }
  1065. /**
  1066. * Create a new in-core index representation, lock it, and read from disk.
  1067. * <p>
  1068. * The new index will be locked and then read before it is returned to the
  1069. * caller. Read failures are reported as exceptions and therefore prevent
  1070. * the method from returning a partially populated index.
  1071. *
  1072. * @return a cache representing the contents of the specified index file (if
  1073. * it exists) or an empty cache if the file does not exist.
  1074. * @throws NoWorkTreeException
  1075. * if this is bare, which implies it has no working directory.
  1076. * See {@link #isBare()}.
  1077. * @throws IOException
  1078. * the index file is present but could not be read, or the lock
  1079. * could not be obtained.
  1080. * @throws CorruptObjectException
  1081. * the index file is using a format or extension that this
  1082. * library does not support.
  1083. */
  1084. @NonNull
  1085. public DirCache lockDirCache() throws NoWorkTreeException,
  1086. CorruptObjectException, IOException {
  1087. // we want DirCache to inform us so that we can inform registered
  1088. // listeners about index changes
  1089. IndexChangedListener l = new IndexChangedListener() {
  1090. public void onIndexChanged(IndexChangedEvent event) {
  1091. notifyIndexChanged();
  1092. }
  1093. };
  1094. return DirCache.lock(this, l);
  1095. }
  1096. static byte[] gitInternalSlash(byte[] bytes) {
  1097. if (File.separatorChar == '/')
  1098. return bytes;
  1099. for (int i=0; i<bytes.length; ++i)
  1100. if (bytes[i] == File.separatorChar)
  1101. bytes[i] = '/';
  1102. return bytes;
  1103. }
  1104. /**
  1105. * @return an important state
  1106. */
  1107. @NonNull
  1108. public RepositoryState getRepositoryState() {
  1109. if (isBare() || getDirectory() == null)
  1110. return RepositoryState.BARE;
  1111. // Pre Git-1.6 logic
  1112. if (new File(getWorkTree(), ".dotest").exists()) //$NON-NLS-1$
  1113. return RepositoryState.REBASING;
  1114. if (new File(getDirectory(), ".dotest-merge").exists()) //$NON-NLS-1$
  1115. return RepositoryState.REBASING_INTERACTIVE;
  1116. // From 1.6 onwards
  1117. if (new File(getDirectory(),"rebase-apply/rebasing").exists()) //$NON-NLS-1$
  1118. return RepositoryState.REBASING_REBASING;
  1119. if (new File(getDirectory(),"rebase-apply/applying").exists()) //$NON-NLS-1$
  1120. return RepositoryState.APPLY;
  1121. if (new File(getDirectory(),"rebase-apply").exists()) //$NON-NLS-1$
  1122. return RepositoryState.REBASING;
  1123. if (new File(getDirectory(),"rebase-merge/interactive").exists()) //$NON-NLS-1$
  1124. return RepositoryState.REBASING_INTERACTIVE;
  1125. if (new File(getDirectory(),"rebase-merge").exists()) //$NON-NLS-1$
  1126. return RepositoryState.REBASING_MERGE;
  1127. // Both versions
  1128. if (new File(getDirectory(), Constants.MERGE_HEAD).exists()) {
  1129. // we are merging - now check whether we have unmerged paths
  1130. try {
  1131. if (!readDirCache().hasUnmergedPaths()) {
  1132. // no unmerged paths -> return the MERGING_RESOLVED state
  1133. return RepositoryState.MERGING_RESOLVED;
  1134. }
  1135. } catch (IOException e) {
  1136. // Can't decide whether unmerged paths exists. Return
  1137. // MERGING state to be on the safe side (in state MERGING
  1138. // you are not allow to do anything)
  1139. }
  1140. return RepositoryState.MERGING;
  1141. }
  1142. if (new File(getDirectory(), "BISECT_LOG").exists()) //$NON-NLS-1$
  1143. return RepositoryState.BISECTING;
  1144. if (new File(getDirectory(), Constants.CHERRY_PICK_HEAD).exists()) {
  1145. try {
  1146. if (!readDirCache().hasUnmergedPaths()) {
  1147. // no unmerged paths
  1148. return RepositoryState.CHERRY_PICKING_RESOLVED;
  1149. }
  1150. } catch (IOException e) {
  1151. // fall through to CHERRY_PICKING
  1152. }
  1153. return RepositoryState.CHERRY_PICKING;
  1154. }
  1155. if (new File(getDirectory(), Constants.REVERT_HEAD).exists()) {
  1156. try {
  1157. if (!readDirCache().hasUnmergedPaths()) {
  1158. // no unmerged paths
  1159. return RepositoryState.REVERTING_RESOLVED;
  1160. }
  1161. } catch (IOException e) {
  1162. // fall through to REVERTING
  1163. }
  1164. return RepositoryState.REVERTING;
  1165. }
  1166. return RepositoryState.SAFE;
  1167. }
  1168. /**
  1169. * Check validity of a ref name. It must not contain character that has
  1170. * a special meaning in a Git object reference expression. Some other
  1171. * dangerous characters are also excluded.
  1172. *
  1173. * For portability reasons '\' is excluded
  1174. *
  1175. * @param refName
  1176. *
  1177. * @return true if refName is a valid ref name
  1178. */
  1179. public static boolean isValidRefName(final String refName) {
  1180. final int len = refName.length();
  1181. if (len == 0)
  1182. return false;
  1183. if (refName.endsWith(".lock")) //$NON-NLS-1$
  1184. return false;
  1185. // Refs may be stored as loose files so invalid paths
  1186. // on the local system must also be invalid refs.
  1187. try {
  1188. SystemReader.getInstance().checkPath(refName);
  1189. } catch (CorruptObjectException e) {
  1190. return false;
  1191. }
  1192. int components = 1;
  1193. char p = '\0';
  1194. for (int i = 0; i < len; i++) {
  1195. final char c = refName.charAt(i);
  1196. if (c <= ' ')
  1197. return false;
  1198. switch (c) {
  1199. case '.':
  1200. switch (p) {
  1201. case '\0': case '/': case '.':
  1202. return false;
  1203. }
  1204. if (i == len -1)
  1205. return false;
  1206. break;
  1207. case '/':
  1208. if (i == 0 || i == len - 1)
  1209. return false;
  1210. if (p == '/')
  1211. return false;
  1212. components++;
  1213. break;
  1214. case '{':
  1215. if (p == '@')
  1216. return false;
  1217. break;
  1218. case '~': case '^': case ':':
  1219. case '?': case '[': case '*':
  1220. case '\\':
  1221. case '\u007F':
  1222. return false;
  1223. }
  1224. p = c;
  1225. }
  1226. return components > 1;
  1227. }
  1228. /**
  1229. * Strip work dir and return normalized repository path.
  1230. *
  1231. * @param workDir Work dir
  1232. * @param file File whose path shall be stripped of its workdir
  1233. * @return normalized repository relative path or the empty
  1234. * string if the file is not relative to the work directory.
  1235. */
  1236. @NonNull
  1237. public static String stripWorkDir(File workDir, File file) {
  1238. final String filePath = file.getPath();
  1239. final String workDirPath = workDir.getPath();
  1240. if (filePath.length() <= workDirPath.length() ||
  1241. filePath.charAt(workDirPath.length()) != File.separatorChar ||
  1242. !filePath.startsWith(workDirPath)) {
  1243. File absWd = workDir.isAbsolute() ? workDir : workDir.getAbsoluteFile();
  1244. File absFile = file.isAbsolute() ? file : file.getAbsoluteFile();
  1245. if (absWd == workDir && absFile == file)
  1246. return ""; //$NON-NLS-1$
  1247. return stripWorkDir(absWd, absFile);
  1248. }
  1249. String relName = filePath.substring(workDirPath.length() + 1);
  1250. if (File.separatorChar != '/')
  1251. relName = relName.replace(File.separatorChar, '/');
  1252. return relName;
  1253. }
  1254. /**
  1255. * @return true if this is bare, which implies it has no working directory.
  1256. */
  1257. public boolean isBare() {
  1258. return workTree == null;
  1259. }
  1260. /**
  1261. * @return the root directory of the working tree, where files are checked
  1262. * out for viewing and editing.
  1263. * @throws NoWorkTreeException
  1264. * if this is bare, which implies it has no working directory.
  1265. * See {@link #isBare()}.
  1266. */
  1267. @NonNull
  1268. public File getWorkTree() throws NoWorkTreeException {
  1269. if (isBare())
  1270. throw new NoWorkTreeException();
  1271. return workTree;
  1272. }
  1273. /**
  1274. * Force a scan for changed refs.
  1275. *
  1276. * @throws IOException
  1277. */
  1278. public abstract void scanForRepoChanges() throws IOException;
  1279. /**
  1280. * Notify that the index changed
  1281. */
  1282. public abstract void notifyIndexChanged();
  1283. /**
  1284. * @param refName
  1285. *
  1286. * @return a more user friendly ref name
  1287. */
  1288. @NonNull
  1289. public static String shortenRefName(String refName) {
  1290. if (refName.startsWith(Constants.R_HEADS))
  1291. return refName.substring(Constants.R_HEADS.length());
  1292. if (refName.startsWith(Constants.R_TAGS))
  1293. return refName.substring(Constants.R_TAGS.length());
  1294. if (refName.startsWith(Constants.R_REMOTES))
  1295. return refName.substring(Constants.R_REMOTES.length());
  1296. return refName;
  1297. }
  1298. /**
  1299. * @param refName
  1300. * @return the remote branch name part of <code>refName</code>, i.e. without
  1301. * the <code>refs/remotes/&lt;remote&gt;</code> prefix, if
  1302. * <code>refName</code> represents a remote tracking branch;
  1303. * otherwise {@code null}.
  1304. * @since 3.4
  1305. */
  1306. @Nullable
  1307. public String shortenRemoteBranchName(String refName) {
  1308. for (String remote : getRemoteNames()) {
  1309. String remotePrefix = Constants.R_REMOTES + remote + "/"; //$NON-NLS-1$
  1310. if (refName.startsWith(remotePrefix))
  1311. return refName.substring(remotePrefix.length());
  1312. }
  1313. return null;
  1314. }
  1315. /**
  1316. * @param refName
  1317. * @return the remote name part of <code>refName</code>, i.e. without the
  1318. * <code>refs/remotes/&lt;remote&gt;</code> prefix, if
  1319. * <code>refName</code> represents a remote tracking branch;
  1320. * otherwise {@code null}.
  1321. * @since 3.4
  1322. */
  1323. @Nullable
  1324. public String getRemoteName(String refName) {
  1325. for (String remote : getRemoteNames()) {
  1326. String remotePrefix = Constants.R_REMOTES + remote + "/"; //$NON-NLS-1$
  1327. if (refName.startsWith(remotePrefix))
  1328. return remote;
  1329. }
  1330. return null;
  1331. }
  1332. /**
  1333. * @param refName
  1334. * @return a {@link ReflogReader} for the supplied refname, or {@code null}
  1335. * if the named ref does not exist.
  1336. * @throws IOException
  1337. * the ref could not be accessed.
  1338. * @since 3.0
  1339. */
  1340. @Nullable
  1341. public abstract ReflogReader getReflogReader(String refName)
  1342. throws IOException;
  1343. /**
  1344. * Return the information stored in the file $GIT_DIR/MERGE_MSG. In this
  1345. * file operations triggering a merge will store a template for the commit
  1346. * message of the merge commit.
  1347. *
  1348. * @return a String containing the content of the MERGE_MSG file or
  1349. * {@code null} if this file doesn't exist
  1350. * @throws IOException
  1351. * @throws NoWorkTreeException
  1352. * if this is bare, which implies it has no working directory.
  1353. * See {@link #isBare()}.
  1354. */
  1355. @Nullable
  1356. public String readMergeCommitMsg() throws IOException, NoWorkTreeException {
  1357. return readCommitMsgFile(Constants.MERGE_MSG);
  1358. }
  1359. /**
  1360. * Write new content to the file $GIT_DIR/MERGE_MSG. In this file operations
  1361. * triggering a merge will store a template for the commit message of the
  1362. * merge commit. If <code>null</code> is specified as message the file will
  1363. * be deleted.
  1364. *
  1365. * @param msg
  1366. * the message which should be written or <code>null</code> to
  1367. * delete the file
  1368. *
  1369. * @throws IOException
  1370. */
  1371. public void writeMergeCommitMsg(String msg) throws IOException {
  1372. File mergeMsgFile = new File(gitDir, Constants.MERGE_MSG);
  1373. writeCommitMsg(mergeMsgFile, msg);
  1374. }
  1375. /**
  1376. * Return the information stored in the file $GIT_DIR/COMMIT_EDITMSG. In
  1377. * this file hooks triggered by an operation may read or modify the current
  1378. * commit message.
  1379. *
  1380. * @return a String containing the content of the COMMIT_EDITMSG file or
  1381. * {@code null} if this file doesn't exist
  1382. * @throws IOException
  1383. * @throws NoWorkTreeException
  1384. * if this is bare, which implies it has no working directory.
  1385. * See {@link #isBare()}.
  1386. * @since 4.0
  1387. */
  1388. @Nullable
  1389. public String readCommitEditMsg() throws IOException, NoWorkTreeException {
  1390. return readCommitMsgFile(Constants.COMMIT_EDITMSG);
  1391. }
  1392. /**
  1393. * Write new content to the file $GIT_DIR/COMMIT_EDITMSG. In this file hooks
  1394. * triggered by an operation may read or modify the current commit message.
  1395. * If {@code null} is specified as message the file will be deleted.
  1396. *
  1397. * @param msg
  1398. * the message which should be written or {@code null} to delete
  1399. * the file
  1400. *
  1401. * @throws IOException
  1402. * @since 4.0
  1403. */
  1404. public void writeCommitEditMsg(String msg) throws IOException {
  1405. File commiEditMsgFile = new File(gitDir, Constants.COMMIT_EDITMSG);
  1406. writeCommitMsg(commiEditMsgFile, msg);
  1407. }
  1408. /**
  1409. * Return the information stored in the file $GIT_DIR/MERGE_HEAD. In this
  1410. * file operations triggering a merge will store the IDs of all heads which
  1411. * should be merged together with HEAD.
  1412. *
  1413. * @return a list of commits which IDs are listed in the MERGE_HEAD file or
  1414. * {@code null} if this file doesn't exist. Also if the file exists
  1415. * but is empty {@code null} will be returned
  1416. * @throws IOException
  1417. * @throws NoWorkTreeException
  1418. * if this is bare, which implies it has no working directory.
  1419. * See {@link #isBare()}.
  1420. */
  1421. @Nullable
  1422. public List<ObjectId> readMergeHeads() throws IOException, NoWorkTreeException {
  1423. if (isBare() || getDirectory() == null)
  1424. throw new NoWorkTreeException();
  1425. byte[] raw = readGitDirectoryFile(Constants.MERGE_HEAD);
  1426. if (raw == null)
  1427. return null;
  1428. LinkedList<ObjectId> heads = new LinkedList<ObjectId>();
  1429. for (int p = 0; p < raw.length;) {
  1430. heads.add(ObjectId.fromString(raw, p));
  1431. p = RawParseUtils
  1432. .nextLF(raw, p + Constants.OBJECT_ID_STRING_LENGTH);
  1433. }
  1434. return heads;
  1435. }
  1436. /**
  1437. * Write new merge-heads into $GIT_DIR/MERGE_HEAD. In this file operations
  1438. * triggering a merge will store the IDs of all heads which should be merged
  1439. * together with HEAD. If <code>null</code> is specified as list of commits
  1440. * the file will be deleted
  1441. *
  1442. * @param heads
  1443. * a list of commits which IDs should be written to
  1444. * $GIT_DIR/MERGE_HEAD or <code>null</code> to delete the file
  1445. * @throws IOException
  1446. */
  1447. public void writeMergeHeads(List<? extends ObjectId> heads) throws IOException {
  1448. writeHeadsFile(heads, Constants.MERGE_HEAD);
  1449. }
  1450. /**
  1451. * Return the information stored in the file $GIT_DIR/CHERRY_PICK_HEAD.
  1452. *
  1453. * @return object id from CHERRY_PICK_HEAD file or {@code null} if this file
  1454. * doesn't exist. Also if the file exists but is empty {@code null}
  1455. * will be returned
  1456. * @throws IOException
  1457. * @throws NoWorkTreeException
  1458. * if this is bare, which implies it has no working directory.
  1459. * See {@link #isBare()}.
  1460. */
  1461. @Nullable
  1462. public ObjectId readCherryPickHead() throws IOException,
  1463. NoWorkTreeException {
  1464. if (isBare() || getDirectory() == null)
  1465. throw new NoWorkTreeException();
  1466. byte[] raw = readGitDirectoryFile(Constants.CHERRY_PICK_HEAD);
  1467. if (raw == null)
  1468. return null;
  1469. return ObjectId.fromString(raw, 0);
  1470. }
  1471. /**
  1472. * Return the information stored in the file $GIT_DIR/REVERT_HEAD.
  1473. *
  1474. * @return object id from REVERT_HEAD file or {@code null} if this file
  1475. * doesn't exist. Also if the file exists but is empty {@code null}
  1476. * will be returned
  1477. * @throws IOException
  1478. * @throws NoWorkTreeException
  1479. * if this is bare, which implies it has no working directory.
  1480. * See {@link #isBare()}.
  1481. */
  1482. @Nullable
  1483. public ObjectId readRevertHead() throws IOException, NoWorkTreeException {
  1484. if (isBare() || getDirectory() == null)
  1485. throw new NoWorkTreeException();
  1486. byte[] raw = readGitDirectoryFile(Constants.REVERT_HEAD);
  1487. if (raw == null)
  1488. return null;
  1489. return ObjectId.fromString(raw, 0);
  1490. }
  1491. /**
  1492. * Write cherry pick commit into $GIT_DIR/CHERRY_PICK_HEAD. This is used in
  1493. * case of conflicts to store the cherry which was tried to be picked.
  1494. *
  1495. * @param head
  1496. * an object id of the cherry commit or <code>null</code> to
  1497. * delete the file
  1498. * @throws IOException
  1499. */
  1500. public void writeCherryPickHead(ObjectId head) throws IOException {
  1501. List<ObjectId> heads = (head != null) ? Collections.singletonList(head)
  1502. : null;
  1503. writeHeadsFile(heads, Constants.CHERRY_PICK_HEAD);
  1504. }
  1505. /**
  1506. * Write revert commit into $GIT_DIR/REVERT_HEAD. This is used in case of
  1507. * conflicts to store the revert which was tried to be picked.
  1508. *
  1509. * @param head
  1510. * an object id of the revert commit or <code>null</code> to
  1511. * delete the file
  1512. * @throws IOException
  1513. */
  1514. public void writeRevertHead(ObjectId head) throws IOException {
  1515. List<ObjectId> heads = (head != null) ? Collections.singletonList(head)
  1516. : null;
  1517. writeHeadsFile(heads, Constants.REVERT_HEAD);
  1518. }
  1519. /**
  1520. * Write original HEAD commit into $GIT_DIR/ORIG_HEAD.
  1521. *
  1522. * @param head
  1523. * an object id of the original HEAD commit or <code>null</code>
  1524. * to delete the file
  1525. * @throws IOException
  1526. */
  1527. public void writeOrigHead(ObjectId head) throws IOException {
  1528. List<ObjectId> heads = head != null ? Collections.singletonList(head)
  1529. : null;
  1530. writeHeadsFile(heads, Constants.ORIG_HEAD);
  1531. }
  1532. /**
  1533. * Return the information stored in the file $GIT_DIR/ORIG_HEAD.
  1534. *
  1535. * @return object id from ORIG_HEAD file or {@code null} if this file
  1536. * doesn't exist. Also if the file exists but is empty {@code null}
  1537. * will be returned
  1538. * @throws IOException
  1539. * @throws NoWorkTreeException
  1540. * if this is bare, which implies it has no working directory.
  1541. * See {@link #isBare()}.
  1542. */
  1543. @Nullable
  1544. public ObjectId readOrigHead() throws IOException, NoWorkTreeException {
  1545. if (isBare() || getDirectory() == null)
  1546. throw new NoWorkTreeException();
  1547. byte[] raw = readGitDirectoryFile(Constants.ORIG_HEAD);
  1548. return raw != null ? ObjectId.fromString(raw, 0) : null;
  1549. }
  1550. /**
  1551. * Return the information stored in the file $GIT_DIR/SQUASH_MSG. In this
  1552. * file operations triggering a squashed merge will store a template for the
  1553. * commit message of the squash commit.
  1554. *
  1555. * @return a String containing the content of the SQUASH_MSG file or
  1556. * {@code null} if this file doesn't exist
  1557. * @throws IOException
  1558. * @throws NoWorkTreeException
  1559. * if this is bare, which implies it has no working directory.
  1560. * See {@link #isBare()}.
  1561. */
  1562. @Nullable
  1563. public String readSquashCommitMsg() throws IOException {
  1564. return readCommitMsgFile(Constants.SQUASH_MSG);
  1565. }
  1566. /**
  1567. * Write new content to the file $GIT_DIR/SQUASH_MSG. In this file
  1568. * operations triggering a squashed merge will store a template for the
  1569. * commit message of the squash commit. If <code>null</code> is specified as
  1570. * message the file will be deleted.
  1571. *
  1572. * @param msg
  1573. * the message which should be written or <code>null</code> to
  1574. * delete the file
  1575. *
  1576. * @throws IOException
  1577. */
  1578. public void writeSquashCommitMsg(String msg) throws IOException {
  1579. File squashMsgFile = new File(gitDir, Constants.SQUASH_MSG);
  1580. writeCommitMsg(squashMsgFile, msg);
  1581. }
  1582. @Nullable
  1583. private String readCommitMsgFile(String msgFilename) throws IOException {
  1584. if (isBare() || getDirectory() == null)
  1585. throw new NoWorkTreeException();
  1586. File mergeMsgFile = new File(getDirectory(), msgFilename);
  1587. try {
  1588. return RawParseUtils.decode(IO.readFully(mergeMsgFile));
  1589. } catch (FileNotFoundException e) {
  1590. if (mergeMsgFile.exists()) {
  1591. throw e;
  1592. }
  1593. // the file has disappeared in the meantime ignore it
  1594. return null;
  1595. }
  1596. }
  1597. private void writeCommitMsg(File msgFile, String msg) throws IOException {
  1598. if (msg != null) {
  1599. FileOutputStream fos = new FileOutputStream(msgFile);
  1600. try {
  1601. fos.write(msg.getBytes(Constants.CHARACTER_ENCODING));
  1602. } finally {
  1603. fos.close();
  1604. }
  1605. } else {
  1606. FileUtils.delete(msgFile, FileUtils.SKIP_MISSING);
  1607. }
  1608. }
  1609. /**
  1610. * Read a file from the git directory.
  1611. *
  1612. * @param filename
  1613. * @return the raw contents or {@code null} if the file doesn't exist or is
  1614. * empty
  1615. * @throws IOException
  1616. */
  1617. @Nullable
  1618. private byte[] readGitDirectoryFile(String filename) throws IOException {
  1619. File file = new File(getDirectory(), filename);
  1620. try {
  1621. byte[] raw = IO.readFully(file);
  1622. return raw.length > 0 ? raw : null;
  1623. } catch (FileNotFoundException notFound) {
  1624. if (file.exists()) {
  1625. throw notFound;
  1626. }
  1627. return null;
  1628. }
  1629. }
  1630. /**
  1631. * Write the given heads to a file in the git directory.
  1632. *
  1633. * @param heads
  1634. * a list of object ids to write or null if the file should be
  1635. * deleted.
  1636. * @param filename
  1637. * @throws FileNotFoundException
  1638. * @throws IOException
  1639. */
  1640. private void writeHeadsFile(List<? extends ObjectId> heads, String filename)
  1641. throws FileNotFoundException, IOException {
  1642. File headsFile = new File(getDirectory(), filename);
  1643. if (heads != null) {
  1644. BufferedOutputStream bos = new SafeBufferedOutputStream(
  1645. new FileOutputStream(headsFile));
  1646. try {
  1647. for (ObjectId id : heads) {
  1648. id.copyTo(bos);
  1649. bos.write('\n');
  1650. }
  1651. } finally {
  1652. bos.close();
  1653. }
  1654. } else {
  1655. FileUtils.delete(headsFile, FileUtils.SKIP_MISSING);
  1656. }
  1657. }
  1658. /**
  1659. * Read a file formatted like the git-rebase-todo file. The "done" file is
  1660. * also formatted like the git-rebase-todo file. These files can be found in
  1661. * .git/rebase-merge/ or .git/rebase-append/ folders.
  1662. *
  1663. * @param path
  1664. * path to the file relative to the repository's git-dir. E.g.
  1665. * "rebase-merge/git-rebase-todo" or "rebase-append/done"
  1666. * @param includeComments
  1667. * <code>true</code> if also comments should be reported
  1668. * @return the list of steps
  1669. * @throws IOException
  1670. * @since 3.2
  1671. */
  1672. @NonNull
  1673. public List<RebaseTodoLine> readRebaseTodo(String path,
  1674. boolean includeComments)
  1675. throws IOException {
  1676. return new RebaseTodoFile(this).readRebaseTodo(path, includeComments);
  1677. }
  1678. /**
  1679. * Write a file formatted like a git-rebase-todo file.
  1680. *
  1681. * @param path
  1682. * path to the file relative to the repository's git-dir. E.g.
  1683. * "rebase-merge/git-rebase-todo" or "rebase-append/done"
  1684. * @param steps
  1685. * the steps to be written
  1686. * @param append
  1687. * whether to append to an existing file or to write a new file
  1688. * @throws IOException
  1689. * @since 3.2
  1690. */
  1691. public void writeRebaseTodoFile(String path, List<RebaseTodoLine> steps,
  1692. boolean append)
  1693. throws IOException {
  1694. new RebaseTodoFile(this).writeRebaseTodoFile(path, steps, append);
  1695. }
  1696. /**
  1697. * @return the names of all known remotes
  1698. * @since 3.4
  1699. */
  1700. @NonNull
  1701. public Set<String> getRemoteNames() {
  1702. return getConfig()
  1703. .getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
  1704. }
  1705. }