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 52KB

Rewrite reference handling to be abstract and accurate This commit actually does three major changes to the way references are handled within JGit. Unfortunately they were easier to do as a single massive commit than to break them up into smaller units. Disambiguate symbolic references: --------------------------------- Reporting a symbolic reference such as HEAD as though it were any other normal reference like refs/heads/master causes subtle programming errors. We have been bitten by this error on several occasions, as have some downstream applications written by myself. Instead of reporting HEAD as a reference whose name differs from its "original name", report it as an actual SymbolicRef object that the application can test the type and examine the target of. With this change, Ref is now an abstract type with different subclasses for the different types. In the classical example of "HEAD" being a symbolic reference to branch "refs/heads/master", the Repository.getAllRefs() method will now return: Map<String, Ref> all = repository.getAllRefs(); SymbolicRef HEAD = (SymbolicRef) all.get("HEAD"); ObjectIdRef master = (ObjectIdRef) all.get("refs/heads/master"); assertSame(master, HEAD.getTarget()); assertSame(master.getObjectId(), HEAD.getObjectId()); assertEquals("HEAD", HEAD.getName()); assertEquals("refs/heads/master", master.getName()); A nice side-effect of this change is the storage type of the symbolic reference is no longer ambiguous with the storge type of the underlying reference it targets. In the above example, if master was only available in the packed-refs file, then the following is also true: assertSame(Ref.Storage.LOOSE, HEAD.getStorage()); assertSame(Ref.Storage.PACKED, master.getStorage()); (Prior to this change we returned the ambiguous storage of LOOSE_PACKED for HEAD, which was confusing since it wasn't actually true on disk). Another nice side-effect of this change is all intermediate symbolic references are preserved, and are therefore visible to the application when they walk the target chain. We can now correctly inspect chains of symbolic references. As a result of this change the Ref.getOrigName() method has been removed from the API. Applications should identify a symbolic reference by testing for isSymbolic() and not by using an arcane string comparsion between properties. Abstract the RefDatabase storage: --------------------------------- RefDatabase is now abstract, similar to ObjectDatabase, and a new concrete implementation called RefDirectory is used for the traditional on-disk storage layout. In the future we plan to support additional implementations, such as a pure in-memory RefDatabase for unit testing purposes. Optimize RefDirectory: ---------------------- The implementation of the in-memory reference cache, reading, and update routines has been completely rewritten. Much of the code was heavily borrowed or cribbed from the prior implementation, so copyright notices have been left intact as much as possible. The RefDirectory cache no longer confuses symbolic references with normal references. This permits the cache to resolve the value of a symbolic reference as late as possible, ensuring it is always current, without needing to maintain reverse pointers. The cache is now 2 sorted RefLists, rather than 3 HashMaps. Using sorted lists allows the implementation to reduce the in-memory footprint when storing many refs. Using specialized types for the elements allows the code to avoid additional map lookups for auxiliary stat information. To improve scan time during getRefs(), the lists are returned via a copy-on-write contract. Most callers of getRefs() do not modify the returned collections, so the copy-on-write semantics improves access on repositories with a large number of packed references. Iterator traversals of the returned Map<String,Ref> are performed using a simple merge-join of the two cache lists, ensuring we can perform the entire traversal in linear time as a function of the number of references: O(PackedRefs + LooseRefs). Scans of the loose reference space to update the cache run in O(LooseRefs log LooseRefs) time, as the directory contents are sorted before being merged against the in-memory cache. Since the majority of stable references are kept packed, there typically are only a handful of reference names to be sorted, so the sorting cost should not be very high. Locking is reduced during getRefs() by taking advantage of the copy-on-write semantics of the improved cache data structure. This permits concurrent readers to pull back references without blocking each other. If there is contention updating the cache during a scan, one or more updates are simply skipped and will get picked up again in a future scan. Writing to the $GIT_DIR/packed-refs during reference delete is now fully atomic. The file is locked, reparsed fresh, and written back out if a change is necessary. This avoids all race conditions with concurrent external updates of the packed-refs file. The RefLogWriter class has been fully folded into RefDirectory and is therefore deleted. Maintaining the reference's log is the responsiblity of the database implementation, and not all implementations will use java.io for access. Future work still remains to be done to abstract the ReflogReader class away from local disk IO. Change-Id: I26b9287c45a4b2d2be35ba2849daa316f5eec85d Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
14 yıl önce
Redo event listeners to be more generic Replace the old crude event listener system with a much more generic implementation, patterned after the event dispatch techniques used in Google Web Toolkit 1.5 and later. Each event delivers to an interface that defines a single method, and the event itself is what performs the delivery in a type-safe way through its own dispatch method. Listeners are registered in a generic listener list, indexed by the interface they implement and wish to receive an event for. Delivery of events is performed by looping through all listeners implementing the event's corresponding listener interface, and using the event's own dispatch method to deliver the event. This is the classical "double dispatch" pattern for event delivery. Listeners can be unregistered by invoking remove() on their registration handle. This change therefore requires application code to track the handle if it wishes to remove the listener at a later point in time. Event delivery is now exposed as a generic public method on the Repository class, making it easier for any type of message to be sent out to any type of listener that has registered, without needing to pre-arrange for type-safe fireFoo() methods. New event types can be added in the future simply by defining a new RepositoryEvent subclass and a corresponding RepositoryListener interface that it dispatches to. By always adding new events through a new interface, we never need to worry about defining an Adapter to provide default no-op implementations of new event methods. Change-Id: I651417b3098b9afc93d91085e9f0b2265df8fc81 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
14 yıl önce
Redo event listeners to be more generic Replace the old crude event listener system with a much more generic implementation, patterned after the event dispatch techniques used in Google Web Toolkit 1.5 and later. Each event delivers to an interface that defines a single method, and the event itself is what performs the delivery in a type-safe way through its own dispatch method. Listeners are registered in a generic listener list, indexed by the interface they implement and wish to receive an event for. Delivery of events is performed by looping through all listeners implementing the event's corresponding listener interface, and using the event's own dispatch method to deliver the event. This is the classical "double dispatch" pattern for event delivery. Listeners can be unregistered by invoking remove() on their registration handle. This change therefore requires application code to track the handle if it wishes to remove the listener at a later point in time. Event delivery is now exposed as a generic public method on the Repository class, making it easier for any type of message to be sent out to any type of listener that has registered, without needing to pre-arrange for type-safe fireFoo() methods. New event types can be added in the future simply by defining a new RepositoryEvent subclass and a corresponding RepositoryListener interface that it dispatches to. By always adding new events through a new interface, we never need to worry about defining an Adapter to provide default no-op implementations of new event methods. Change-Id: I651417b3098b9afc93d91085e9f0b2265df8fc81 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
14 yıl önce
Redo event listeners to be more generic Replace the old crude event listener system with a much more generic implementation, patterned after the event dispatch techniques used in Google Web Toolkit 1.5 and later. Each event delivers to an interface that defines a single method, and the event itself is what performs the delivery in a type-safe way through its own dispatch method. Listeners are registered in a generic listener list, indexed by the interface they implement and wish to receive an event for. Delivery of events is performed by looping through all listeners implementing the event's corresponding listener interface, and using the event's own dispatch method to deliver the event. This is the classical "double dispatch" pattern for event delivery. Listeners can be unregistered by invoking remove() on their registration handle. This change therefore requires application code to track the handle if it wishes to remove the listener at a later point in time. Event delivery is now exposed as a generic public method on the Repository class, making it easier for any type of message to be sent out to any type of listener that has registered, without needing to pre-arrange for type-safe fireFoo() methods. New event types can be added in the future simply by defining a new RepositoryEvent subclass and a corresponding RepositoryListener interface that it dispatches to. By always adding new events through a new interface, we never need to worry about defining an Adapter to provide default no-op implementations of new event methods. Change-Id: I651417b3098b9afc93d91085e9f0b2265df8fc81 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
14 yıl önce
Redo event listeners to be more generic Replace the old crude event listener system with a much more generic implementation, patterned after the event dispatch techniques used in Google Web Toolkit 1.5 and later. Each event delivers to an interface that defines a single method, and the event itself is what performs the delivery in a type-safe way through its own dispatch method. Listeners are registered in a generic listener list, indexed by the interface they implement and wish to receive an event for. Delivery of events is performed by looping through all listeners implementing the event's corresponding listener interface, and using the event's own dispatch method to deliver the event. This is the classical "double dispatch" pattern for event delivery. Listeners can be unregistered by invoking remove() on their registration handle. This change therefore requires application code to track the handle if it wishes to remove the listener at a later point in time. Event delivery is now exposed as a generic public method on the Repository class, making it easier for any type of message to be sent out to any type of listener that has registered, without needing to pre-arrange for type-safe fireFoo() methods. New event types can be added in the future simply by defining a new RepositoryEvent subclass and a corresponding RepositoryListener interface that it dispatches to. By always adding new events through a new interface, we never need to worry about defining an Adapter to provide default no-op implementations of new event methods. Change-Id: I651417b3098b9afc93d91085e9f0b2265df8fc81 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
14 yıl önce
Redo event listeners to be more generic Replace the old crude event listener system with a much more generic implementation, patterned after the event dispatch techniques used in Google Web Toolkit 1.5 and later. Each event delivers to an interface that defines a single method, and the event itself is what performs the delivery in a type-safe way through its own dispatch method. Listeners are registered in a generic listener list, indexed by the interface they implement and wish to receive an event for. Delivery of events is performed by looping through all listeners implementing the event's corresponding listener interface, and using the event's own dispatch method to deliver the event. This is the classical "double dispatch" pattern for event delivery. Listeners can be unregistered by invoking remove() on their registration handle. This change therefore requires application code to track the handle if it wishes to remove the listener at a later point in time. Event delivery is now exposed as a generic public method on the Repository class, making it easier for any type of message to be sent out to any type of listener that has registered, without needing to pre-arrange for type-safe fireFoo() methods. New event types can be added in the future simply by defining a new RepositoryEvent subclass and a corresponding RepositoryListener interface that it dispatches to. By always adding new events through a new interface, we never need to worry about defining an Adapter to provide default no-op implementations of new event methods. Change-Id: I651417b3098b9afc93d91085e9f0b2265df8fc81 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
14 yıl önce
Redo event listeners to be more generic Replace the old crude event listener system with a much more generic implementation, patterned after the event dispatch techniques used in Google Web Toolkit 1.5 and later. Each event delivers to an interface that defines a single method, and the event itself is what performs the delivery in a type-safe way through its own dispatch method. Listeners are registered in a generic listener list, indexed by the interface they implement and wish to receive an event for. Delivery of events is performed by looping through all listeners implementing the event's corresponding listener interface, and using the event's own dispatch method to deliver the event. This is the classical "double dispatch" pattern for event delivery. Listeners can be unregistered by invoking remove() on their registration handle. This change therefore requires application code to track the handle if it wishes to remove the listener at a later point in time. Event delivery is now exposed as a generic public method on the Repository class, making it easier for any type of message to be sent out to any type of listener that has registered, without needing to pre-arrange for type-safe fireFoo() methods. New event types can be added in the future simply by defining a new RepositoryEvent subclass and a corresponding RepositoryListener interface that it dispatches to. By always adding new events through a new interface, we never need to worry about defining an Adapter to provide default no-op implementations of new event methods. Change-Id: I651417b3098b9afc93d91085e9f0b2265df8fc81 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
14 yıl önce
Redo event listeners to be more generic Replace the old crude event listener system with a much more generic implementation, patterned after the event dispatch techniques used in Google Web Toolkit 1.5 and later. Each event delivers to an interface that defines a single method, and the event itself is what performs the delivery in a type-safe way through its own dispatch method. Listeners are registered in a generic listener list, indexed by the interface they implement and wish to receive an event for. Delivery of events is performed by looping through all listeners implementing the event's corresponding listener interface, and using the event's own dispatch method to deliver the event. This is the classical "double dispatch" pattern for event delivery. Listeners can be unregistered by invoking remove() on their registration handle. This change therefore requires application code to track the handle if it wishes to remove the listener at a later point in time. Event delivery is now exposed as a generic public method on the Repository class, making it easier for any type of message to be sent out to any type of listener that has registered, without needing to pre-arrange for type-safe fireFoo() methods. New event types can be added in the future simply by defining a new RepositoryEvent subclass and a corresponding RepositoryListener interface that it dispatches to. By always adding new events through a new interface, we never need to worry about defining an Adapter to provide default no-op implementations of new event methods. Change-Id: I651417b3098b9afc93d91085e9f0b2265df8fc81 Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
14 yıl önce
Rewrite reference handling to be abstract and accurate This commit actually does three major changes to the way references are handled within JGit. Unfortunately they were easier to do as a single massive commit than to break them up into smaller units. Disambiguate symbolic references: --------------------------------- Reporting a symbolic reference such as HEAD as though it were any other normal reference like refs/heads/master causes subtle programming errors. We have been bitten by this error on several occasions, as have some downstream applications written by myself. Instead of reporting HEAD as a reference whose name differs from its "original name", report it as an actual SymbolicRef object that the application can test the type and examine the target of. With this change, Ref is now an abstract type with different subclasses for the different types. In the classical example of "HEAD" being a symbolic reference to branch "refs/heads/master", the Repository.getAllRefs() method will now return: Map<String, Ref> all = repository.getAllRefs(); SymbolicRef HEAD = (SymbolicRef) all.get("HEAD"); ObjectIdRef master = (ObjectIdRef) all.get("refs/heads/master"); assertSame(master, HEAD.getTarget()); assertSame(master.getObjectId(), HEAD.getObjectId()); assertEquals("HEAD", HEAD.getName()); assertEquals("refs/heads/master", master.getName()); A nice side-effect of this change is the storage type of the symbolic reference is no longer ambiguous with the storge type of the underlying reference it targets. In the above example, if master was only available in the packed-refs file, then the following is also true: assertSame(Ref.Storage.LOOSE, HEAD.getStorage()); assertSame(Ref.Storage.PACKED, master.getStorage()); (Prior to this change we returned the ambiguous storage of LOOSE_PACKED for HEAD, which was confusing since it wasn't actually true on disk). Another nice side-effect of this change is all intermediate symbolic references are preserved, and are therefore visible to the application when they walk the target chain. We can now correctly inspect chains of symbolic references. As a result of this change the Ref.getOrigName() method has been removed from the API. Applications should identify a symbolic reference by testing for isSymbolic() and not by using an arcane string comparsion between properties. Abstract the RefDatabase storage: --------------------------------- RefDatabase is now abstract, similar to ObjectDatabase, and a new concrete implementation called RefDirectory is used for the traditional on-disk storage layout. In the future we plan to support additional implementations, such as a pure in-memory RefDatabase for unit testing purposes. Optimize RefDirectory: ---------------------- The implementation of the in-memory reference cache, reading, and update routines has been completely rewritten. Much of the code was heavily borrowed or cribbed from the prior implementation, so copyright notices have been left intact as much as possible. The RefDirectory cache no longer confuses symbolic references with normal references. This permits the cache to resolve the value of a symbolic reference as late as possible, ensuring it is always current, without needing to maintain reverse pointers. The cache is now 2 sorted RefLists, rather than 3 HashMaps. Using sorted lists allows the implementation to reduce the in-memory footprint when storing many refs. Using specialized types for the elements allows the code to avoid additional map lookups for auxiliary stat information. To improve scan time during getRefs(), the lists are returned via a copy-on-write contract. Most callers of getRefs() do not modify the returned collections, so the copy-on-write semantics improves access on repositories with a large number of packed references. Iterator traversals of the returned Map<String,Ref> are performed using a simple merge-join of the two cache lists, ensuring we can perform the entire traversal in linear time as a function of the number of references: O(PackedRefs + LooseRefs). Scans of the loose reference space to update the cache run in O(LooseRefs log LooseRefs) time, as the directory contents are sorted before being merged against the in-memory cache. Since the majority of stable references are kept packed, there typically are only a handful of reference names to be sorted, so the sorting cost should not be very high. Locking is reduced during getRefs() by taking advantage of the copy-on-write semantics of the improved cache data structure. This permits concurrent readers to pull back references without blocking each other. If there is contention updating the cache during a scan, one or more updates are simply skipped and will get picked up again in a future scan. Writing to the $GIT_DIR/packed-refs during reference delete is now fully atomic. The file is locked, reparsed fresh, and written back out if a change is necessary. This avoids all race conditions with concurrent external updates of the packed-refs file. The RefLogWriter class has been fully folded into RefDirectory and is therefore deleted. Maintaining the reference's log is the responsiblity of the database implementation, and not all implementations will use java.io for access. Future work still remains to be done to abstract the ReflogReader class away from local disk IO. Change-Id: I26b9287c45a4b2d2be35ba2849daa316f5eec85d Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
14 yıl önce
Rewrite reference handling to be abstract and accurate This commit actually does three major changes to the way references are handled within JGit. Unfortunately they were easier to do as a single massive commit than to break them up into smaller units. Disambiguate symbolic references: --------------------------------- Reporting a symbolic reference such as HEAD as though it were any other normal reference like refs/heads/master causes subtle programming errors. We have been bitten by this error on several occasions, as have some downstream applications written by myself. Instead of reporting HEAD as a reference whose name differs from its "original name", report it as an actual SymbolicRef object that the application can test the type and examine the target of. With this change, Ref is now an abstract type with different subclasses for the different types. In the classical example of "HEAD" being a symbolic reference to branch "refs/heads/master", the Repository.getAllRefs() method will now return: Map<String, Ref> all = repository.getAllRefs(); SymbolicRef HEAD = (SymbolicRef) all.get("HEAD"); ObjectIdRef master = (ObjectIdRef) all.get("refs/heads/master"); assertSame(master, HEAD.getTarget()); assertSame(master.getObjectId(), HEAD.getObjectId()); assertEquals("HEAD", HEAD.getName()); assertEquals("refs/heads/master", master.getName()); A nice side-effect of this change is the storage type of the symbolic reference is no longer ambiguous with the storge type of the underlying reference it targets. In the above example, if master was only available in the packed-refs file, then the following is also true: assertSame(Ref.Storage.LOOSE, HEAD.getStorage()); assertSame(Ref.Storage.PACKED, master.getStorage()); (Prior to this change we returned the ambiguous storage of LOOSE_PACKED for HEAD, which was confusing since it wasn't actually true on disk). Another nice side-effect of this change is all intermediate symbolic references are preserved, and are therefore visible to the application when they walk the target chain. We can now correctly inspect chains of symbolic references. As a result of this change the Ref.getOrigName() method has been removed from the API. Applications should identify a symbolic reference by testing for isSymbolic() and not by using an arcane string comparsion between properties. Abstract the RefDatabase storage: --------------------------------- RefDatabase is now abstract, similar to ObjectDatabase, and a new concrete implementation called RefDirectory is used for the traditional on-disk storage layout. In the future we plan to support additional implementations, such as a pure in-memory RefDatabase for unit testing purposes. Optimize RefDirectory: ---------------------- The implementation of the in-memory reference cache, reading, and update routines has been completely rewritten. Much of the code was heavily borrowed or cribbed from the prior implementation, so copyright notices have been left intact as much as possible. The RefDirectory cache no longer confuses symbolic references with normal references. This permits the cache to resolve the value of a symbolic reference as late as possible, ensuring it is always current, without needing to maintain reverse pointers. The cache is now 2 sorted RefLists, rather than 3 HashMaps. Using sorted lists allows the implementation to reduce the in-memory footprint when storing many refs. Using specialized types for the elements allows the code to avoid additional map lookups for auxiliary stat information. To improve scan time during getRefs(), the lists are returned via a copy-on-write contract. Most callers of getRefs() do not modify the returned collections, so the copy-on-write semantics improves access on repositories with a large number of packed references. Iterator traversals of the returned Map<String,Ref> are performed using a simple merge-join of the two cache lists, ensuring we can perform the entire traversal in linear time as a function of the number of references: O(PackedRefs + LooseRefs). Scans of the loose reference space to update the cache run in O(LooseRefs log LooseRefs) time, as the directory contents are sorted before being merged against the in-memory cache. Since the majority of stable references are kept packed, there typically are only a handful of reference names to be sorted, so the sorting cost should not be very high. Locking is reduced during getRefs() by taking advantage of the copy-on-write semantics of the improved cache data structure. This permits concurrent readers to pull back references without blocking each other. If there is contention updating the cache during a scan, one or more updates are simply skipped and will get picked up again in a future scan. Writing to the $GIT_DIR/packed-refs during reference delete is now fully atomic. The file is locked, reparsed fresh, and written back out if a change is necessary. This avoids all race conditions with concurrent external updates of the packed-refs file. The RefLogWriter class has been fully folded into RefDirectory and is therefore deleted. Maintaining the reference's log is the responsiblity of the database implementation, and not all implementations will use java.io for access. Future work still remains to be done to abstract the ReflogReader class away from local disk IO. Change-Id: I26b9287c45a4b2d2be35ba2849daa316f5eec85d Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
14 yıl önce
Rewrite reference handling to be abstract and accurate This commit actually does three major changes to the way references are handled within JGit. Unfortunately they were easier to do as a single massive commit than to break them up into smaller units. Disambiguate symbolic references: --------------------------------- Reporting a symbolic reference such as HEAD as though it were any other normal reference like refs/heads/master causes subtle programming errors. We have been bitten by this error on several occasions, as have some downstream applications written by myself. Instead of reporting HEAD as a reference whose name differs from its "original name", report it as an actual SymbolicRef object that the application can test the type and examine the target of. With this change, Ref is now an abstract type with different subclasses for the different types. In the classical example of "HEAD" being a symbolic reference to branch "refs/heads/master", the Repository.getAllRefs() method will now return: Map<String, Ref> all = repository.getAllRefs(); SymbolicRef HEAD = (SymbolicRef) all.get("HEAD"); ObjectIdRef master = (ObjectIdRef) all.get("refs/heads/master"); assertSame(master, HEAD.getTarget()); assertSame(master.getObjectId(), HEAD.getObjectId()); assertEquals("HEAD", HEAD.getName()); assertEquals("refs/heads/master", master.getName()); A nice side-effect of this change is the storage type of the symbolic reference is no longer ambiguous with the storge type of the underlying reference it targets. In the above example, if master was only available in the packed-refs file, then the following is also true: assertSame(Ref.Storage.LOOSE, HEAD.getStorage()); assertSame(Ref.Storage.PACKED, master.getStorage()); (Prior to this change we returned the ambiguous storage of LOOSE_PACKED for HEAD, which was confusing since it wasn't actually true on disk). Another nice side-effect of this change is all intermediate symbolic references are preserved, and are therefore visible to the application when they walk the target chain. We can now correctly inspect chains of symbolic references. As a result of this change the Ref.getOrigName() method has been removed from the API. Applications should identify a symbolic reference by testing for isSymbolic() and not by using an arcane string comparsion between properties. Abstract the RefDatabase storage: --------------------------------- RefDatabase is now abstract, similar to ObjectDatabase, and a new concrete implementation called RefDirectory is used for the traditional on-disk storage layout. In the future we plan to support additional implementations, such as a pure in-memory RefDatabase for unit testing purposes. Optimize RefDirectory: ---------------------- The implementation of the in-memory reference cache, reading, and update routines has been completely rewritten. Much of the code was heavily borrowed or cribbed from the prior implementation, so copyright notices have been left intact as much as possible. The RefDirectory cache no longer confuses symbolic references with normal references. This permits the cache to resolve the value of a symbolic reference as late as possible, ensuring it is always current, without needing to maintain reverse pointers. The cache is now 2 sorted RefLists, rather than 3 HashMaps. Using sorted lists allows the implementation to reduce the in-memory footprint when storing many refs. Using specialized types for the elements allows the code to avoid additional map lookups for auxiliary stat information. To improve scan time during getRefs(), the lists are returned via a copy-on-write contract. Most callers of getRefs() do not modify the returned collections, so the copy-on-write semantics improves access on repositories with a large number of packed references. Iterator traversals of the returned Map<String,Ref> are performed using a simple merge-join of the two cache lists, ensuring we can perform the entire traversal in linear time as a function of the number of references: O(PackedRefs + LooseRefs). Scans of the loose reference space to update the cache run in O(LooseRefs log LooseRefs) time, as the directory contents are sorted before being merged against the in-memory cache. Since the majority of stable references are kept packed, there typically are only a handful of reference names to be sorted, so the sorting cost should not be very high. Locking is reduced during getRefs() by taking advantage of the copy-on-write semantics of the improved cache data structure. This permits concurrent readers to pull back references without blocking each other. If there is contention updating the cache during a scan, one or more updates are simply skipped and will get picked up again in a future scan. Writing to the $GIT_DIR/packed-refs during reference delete is now fully atomic. The file is locked, reparsed fresh, and written back out if a change is necessary. This avoids all race conditions with concurrent external updates of the packed-refs file. The RefLogWriter class has been fully folded into RefDirectory and is therefore deleted. Maintaining the reference's log is the responsiblity of the database implementation, and not all implementations will use java.io for access. Future work still remains to be done to abstract the ReflogReader class away from local disk IO. Change-Id: I26b9287c45a4b2d2be35ba2849daa316f5eec85d Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
14 yıl önce
Rewrite reference handling to be abstract and accurate This commit actually does three major changes to the way references are handled within JGit. Unfortunately they were easier to do as a single massive commit than to break them up into smaller units. Disambiguate symbolic references: --------------------------------- Reporting a symbolic reference such as HEAD as though it were any other normal reference like refs/heads/master causes subtle programming errors. We have been bitten by this error on several occasions, as have some downstream applications written by myself. Instead of reporting HEAD as a reference whose name differs from its "original name", report it as an actual SymbolicRef object that the application can test the type and examine the target of. With this change, Ref is now an abstract type with different subclasses for the different types. In the classical example of "HEAD" being a symbolic reference to branch "refs/heads/master", the Repository.getAllRefs() method will now return: Map<String, Ref> all = repository.getAllRefs(); SymbolicRef HEAD = (SymbolicRef) all.get("HEAD"); ObjectIdRef master = (ObjectIdRef) all.get("refs/heads/master"); assertSame(master, HEAD.getTarget()); assertSame(master.getObjectId(), HEAD.getObjectId()); assertEquals("HEAD", HEAD.getName()); assertEquals("refs/heads/master", master.getName()); A nice side-effect of this change is the storage type of the symbolic reference is no longer ambiguous with the storge type of the underlying reference it targets. In the above example, if master was only available in the packed-refs file, then the following is also true: assertSame(Ref.Storage.LOOSE, HEAD.getStorage()); assertSame(Ref.Storage.PACKED, master.getStorage()); (Prior to this change we returned the ambiguous storage of LOOSE_PACKED for HEAD, which was confusing since it wasn't actually true on disk). Another nice side-effect of this change is all intermediate symbolic references are preserved, and are therefore visible to the application when they walk the target chain. We can now correctly inspect chains of symbolic references. As a result of this change the Ref.getOrigName() method has been removed from the API. Applications should identify a symbolic reference by testing for isSymbolic() and not by using an arcane string comparsion between properties. Abstract the RefDatabase storage: --------------------------------- RefDatabase is now abstract, similar to ObjectDatabase, and a new concrete implementation called RefDirectory is used for the traditional on-disk storage layout. In the future we plan to support additional implementations, such as a pure in-memory RefDatabase for unit testing purposes. Optimize RefDirectory: ---------------------- The implementation of the in-memory reference cache, reading, and update routines has been completely rewritten. Much of the code was heavily borrowed or cribbed from the prior implementation, so copyright notices have been left intact as much as possible. The RefDirectory cache no longer confuses symbolic references with normal references. This permits the cache to resolve the value of a symbolic reference as late as possible, ensuring it is always current, without needing to maintain reverse pointers. The cache is now 2 sorted RefLists, rather than 3 HashMaps. Using sorted lists allows the implementation to reduce the in-memory footprint when storing many refs. Using specialized types for the elements allows the code to avoid additional map lookups for auxiliary stat information. To improve scan time during getRefs(), the lists are returned via a copy-on-write contract. Most callers of getRefs() do not modify the returned collections, so the copy-on-write semantics improves access on repositories with a large number of packed references. Iterator traversals of the returned Map<String,Ref> are performed using a simple merge-join of the two cache lists, ensuring we can perform the entire traversal in linear time as a function of the number of references: O(PackedRefs + LooseRefs). Scans of the loose reference space to update the cache run in O(LooseRefs log LooseRefs) time, as the directory contents are sorted before being merged against the in-memory cache. Since the majority of stable references are kept packed, there typically are only a handful of reference names to be sorted, so the sorting cost should not be very high. Locking is reduced during getRefs() by taking advantage of the copy-on-write semantics of the improved cache data structure. This permits concurrent readers to pull back references without blocking each other. If there is contention updating the cache during a scan, one or more updates are simply skipped and will get picked up again in a future scan. Writing to the $GIT_DIR/packed-refs during reference delete is now fully atomic. The file is locked, reparsed fresh, and written back out if a change is necessary. This avoids all race conditions with concurrent external updates of the packed-refs file. The RefLogWriter class has been fully folded into RefDirectory and is therefore deleted. Maintaining the reference's log is the responsiblity of the database implementation, and not all implementations will use java.io for access. Future work still remains to be done to abstract the ReflogReader class away from local disk IO. Change-Id: I26b9287c45a4b2d2be35ba2849daa316f5eec85d Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
14 yıl önce
Rewrite reference handling to be abstract and accurate This commit actually does three major changes to the way references are handled within JGit. Unfortunately they were easier to do as a single massive commit than to break them up into smaller units. Disambiguate symbolic references: --------------------------------- Reporting a symbolic reference such as HEAD as though it were any other normal reference like refs/heads/master causes subtle programming errors. We have been bitten by this error on several occasions, as have some downstream applications written by myself. Instead of reporting HEAD as a reference whose name differs from its "original name", report it as an actual SymbolicRef object that the application can test the type and examine the target of. With this change, Ref is now an abstract type with different subclasses for the different types. In the classical example of "HEAD" being a symbolic reference to branch "refs/heads/master", the Repository.getAllRefs() method will now return: Map<String, Ref> all = repository.getAllRefs(); SymbolicRef HEAD = (SymbolicRef) all.get("HEAD"); ObjectIdRef master = (ObjectIdRef) all.get("refs/heads/master"); assertSame(master, HEAD.getTarget()); assertSame(master.getObjectId(), HEAD.getObjectId()); assertEquals("HEAD", HEAD.getName()); assertEquals("refs/heads/master", master.getName()); A nice side-effect of this change is the storage type of the symbolic reference is no longer ambiguous with the storge type of the underlying reference it targets. In the above example, if master was only available in the packed-refs file, then the following is also true: assertSame(Ref.Storage.LOOSE, HEAD.getStorage()); assertSame(Ref.Storage.PACKED, master.getStorage()); (Prior to this change we returned the ambiguous storage of LOOSE_PACKED for HEAD, which was confusing since it wasn't actually true on disk). Another nice side-effect of this change is all intermediate symbolic references are preserved, and are therefore visible to the application when they walk the target chain. We can now correctly inspect chains of symbolic references. As a result of this change the Ref.getOrigName() method has been removed from the API. Applications should identify a symbolic reference by testing for isSymbolic() and not by using an arcane string comparsion between properties. Abstract the RefDatabase storage: --------------------------------- RefDatabase is now abstract, similar to ObjectDatabase, and a new concrete implementation called RefDirectory is used for the traditional on-disk storage layout. In the future we plan to support additional implementations, such as a pure in-memory RefDatabase for unit testing purposes. Optimize RefDirectory: ---------------------- The implementation of the in-memory reference cache, reading, and update routines has been completely rewritten. Much of the code was heavily borrowed or cribbed from the prior implementation, so copyright notices have been left intact as much as possible. The RefDirectory cache no longer confuses symbolic references with normal references. This permits the cache to resolve the value of a symbolic reference as late as possible, ensuring it is always current, without needing to maintain reverse pointers. The cache is now 2 sorted RefLists, rather than 3 HashMaps. Using sorted lists allows the implementation to reduce the in-memory footprint when storing many refs. Using specialized types for the elements allows the code to avoid additional map lookups for auxiliary stat information. To improve scan time during getRefs(), the lists are returned via a copy-on-write contract. Most callers of getRefs() do not modify the returned collections, so the copy-on-write semantics improves access on repositories with a large number of packed references. Iterator traversals of the returned Map<String,Ref> are performed using a simple merge-join of the two cache lists, ensuring we can perform the entire traversal in linear time as a function of the number of references: O(PackedRefs + LooseRefs). Scans of the loose reference space to update the cache run in O(LooseRefs log LooseRefs) time, as the directory contents are sorted before being merged against the in-memory cache. Since the majority of stable references are kept packed, there typically are only a handful of reference names to be sorted, so the sorting cost should not be very high. Locking is reduced during getRefs() by taking advantage of the copy-on-write semantics of the improved cache data structure. This permits concurrent readers to pull back references without blocking each other. If there is contention updating the cache during a scan, one or more updates are simply skipped and will get picked up again in a future scan. Writing to the $GIT_DIR/packed-refs during reference delete is now fully atomic. The file is locked, reparsed fresh, and written back out if a change is necessary. This avoids all race conditions with concurrent external updates of the packed-refs file. The RefLogWriter class has been fully folded into RefDirectory and is therefore deleted. Maintaining the reference's log is the responsiblity of the database implementation, and not all implementations will use java.io for access. Future work still remains to be done to abstract the ReflogReader class away from local disk IO. Change-Id: I26b9287c45a4b2d2be35ba2849daa316f5eec85d Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
14 yıl önce
Rewrite reference handling to be abstract and accurate This commit actually does three major changes to the way references are handled within JGit. Unfortunately they were easier to do as a single massive commit than to break them up into smaller units. Disambiguate symbolic references: --------------------------------- Reporting a symbolic reference such as HEAD as though it were any other normal reference like refs/heads/master causes subtle programming errors. We have been bitten by this error on several occasions, as have some downstream applications written by myself. Instead of reporting HEAD as a reference whose name differs from its "original name", report it as an actual SymbolicRef object that the application can test the type and examine the target of. With this change, Ref is now an abstract type with different subclasses for the different types. In the classical example of "HEAD" being a symbolic reference to branch "refs/heads/master", the Repository.getAllRefs() method will now return: Map<String, Ref> all = repository.getAllRefs(); SymbolicRef HEAD = (SymbolicRef) all.get("HEAD"); ObjectIdRef master = (ObjectIdRef) all.get("refs/heads/master"); assertSame(master, HEAD.getTarget()); assertSame(master.getObjectId(), HEAD.getObjectId()); assertEquals("HEAD", HEAD.getName()); assertEquals("refs/heads/master", master.getName()); A nice side-effect of this change is the storage type of the symbolic reference is no longer ambiguous with the storge type of the underlying reference it targets. In the above example, if master was only available in the packed-refs file, then the following is also true: assertSame(Ref.Storage.LOOSE, HEAD.getStorage()); assertSame(Ref.Storage.PACKED, master.getStorage()); (Prior to this change we returned the ambiguous storage of LOOSE_PACKED for HEAD, which was confusing since it wasn't actually true on disk). Another nice side-effect of this change is all intermediate symbolic references are preserved, and are therefore visible to the application when they walk the target chain. We can now correctly inspect chains of symbolic references. As a result of this change the Ref.getOrigName() method has been removed from the API. Applications should identify a symbolic reference by testing for isSymbolic() and not by using an arcane string comparsion between properties. Abstract the RefDatabase storage: --------------------------------- RefDatabase is now abstract, similar to ObjectDatabase, and a new concrete implementation called RefDirectory is used for the traditional on-disk storage layout. In the future we plan to support additional implementations, such as a pure in-memory RefDatabase for unit testing purposes. Optimize RefDirectory: ---------------------- The implementation of the in-memory reference cache, reading, and update routines has been completely rewritten. Much of the code was heavily borrowed or cribbed from the prior implementation, so copyright notices have been left intact as much as possible. The RefDirectory cache no longer confuses symbolic references with normal references. This permits the cache to resolve the value of a symbolic reference as late as possible, ensuring it is always current, without needing to maintain reverse pointers. The cache is now 2 sorted RefLists, rather than 3 HashMaps. Using sorted lists allows the implementation to reduce the in-memory footprint when storing many refs. Using specialized types for the elements allows the code to avoid additional map lookups for auxiliary stat information. To improve scan time during getRefs(), the lists are returned via a copy-on-write contract. Most callers of getRefs() do not modify the returned collections, so the copy-on-write semantics improves access on repositories with a large number of packed references. Iterator traversals of the returned Map<String,Ref> are performed using a simple merge-join of the two cache lists, ensuring we can perform the entire traversal in linear time as a function of the number of references: O(PackedRefs + LooseRefs). Scans of the loose reference space to update the cache run in O(LooseRefs log LooseRefs) time, as the directory contents are sorted before being merged against the in-memory cache. Since the majority of stable references are kept packed, there typically are only a handful of reference names to be sorted, so the sorting cost should not be very high. Locking is reduced during getRefs() by taking advantage of the copy-on-write semantics of the improved cache data structure. This permits concurrent readers to pull back references without blocking each other. If there is contention updating the cache during a scan, one or more updates are simply skipped and will get picked up again in a future scan. Writing to the $GIT_DIR/packed-refs during reference delete is now fully atomic. The file is locked, reparsed fresh, and written back out if a change is necessary. This avoids all race conditions with concurrent external updates of the packed-refs file. The RefLogWriter class has been fully folded into RefDirectory and is therefore deleted. Maintaining the reference's log is the responsiblity of the database implementation, and not all implementations will use java.io for access. Future work still remains to be done to abstract the ReflogReader class away from local disk IO. Change-Id: I26b9287c45a4b2d2be35ba2849daa316f5eec85d Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
14 yıl önce
Rewrite reference handling to be abstract and accurate This commit actually does three major changes to the way references are handled within JGit. Unfortunately they were easier to do as a single massive commit than to break them up into smaller units. Disambiguate symbolic references: --------------------------------- Reporting a symbolic reference such as HEAD as though it were any other normal reference like refs/heads/master causes subtle programming errors. We have been bitten by this error on several occasions, as have some downstream applications written by myself. Instead of reporting HEAD as a reference whose name differs from its "original name", report it as an actual SymbolicRef object that the application can test the type and examine the target of. With this change, Ref is now an abstract type with different subclasses for the different types. In the classical example of "HEAD" being a symbolic reference to branch "refs/heads/master", the Repository.getAllRefs() method will now return: Map<String, Ref> all = repository.getAllRefs(); SymbolicRef HEAD = (SymbolicRef) all.get("HEAD"); ObjectIdRef master = (ObjectIdRef) all.get("refs/heads/master"); assertSame(master, HEAD.getTarget()); assertSame(master.getObjectId(), HEAD.getObjectId()); assertEquals("HEAD", HEAD.getName()); assertEquals("refs/heads/master", master.getName()); A nice side-effect of this change is the storage type of the symbolic reference is no longer ambiguous with the storge type of the underlying reference it targets. In the above example, if master was only available in the packed-refs file, then the following is also true: assertSame(Ref.Storage.LOOSE, HEAD.getStorage()); assertSame(Ref.Storage.PACKED, master.getStorage()); (Prior to this change we returned the ambiguous storage of LOOSE_PACKED for HEAD, which was confusing since it wasn't actually true on disk). Another nice side-effect of this change is all intermediate symbolic references are preserved, and are therefore visible to the application when they walk the target chain. We can now correctly inspect chains of symbolic references. As a result of this change the Ref.getOrigName() method has been removed from the API. Applications should identify a symbolic reference by testing for isSymbolic() and not by using an arcane string comparsion between properties. Abstract the RefDatabase storage: --------------------------------- RefDatabase is now abstract, similar to ObjectDatabase, and a new concrete implementation called RefDirectory is used for the traditional on-disk storage layout. In the future we plan to support additional implementations, such as a pure in-memory RefDatabase for unit testing purposes. Optimize RefDirectory: ---------------------- The implementation of the in-memory reference cache, reading, and update routines has been completely rewritten. Much of the code was heavily borrowed or cribbed from the prior implementation, so copyright notices have been left intact as much as possible. The RefDirectory cache no longer confuses symbolic references with normal references. This permits the cache to resolve the value of a symbolic reference as late as possible, ensuring it is always current, without needing to maintain reverse pointers. The cache is now 2 sorted RefLists, rather than 3 HashMaps. Using sorted lists allows the implementation to reduce the in-memory footprint when storing many refs. Using specialized types for the elements allows the code to avoid additional map lookups for auxiliary stat information. To improve scan time during getRefs(), the lists are returned via a copy-on-write contract. Most callers of getRefs() do not modify the returned collections, so the copy-on-write semantics improves access on repositories with a large number of packed references. Iterator traversals of the returned Map<String,Ref> are performed using a simple merge-join of the two cache lists, ensuring we can perform the entire traversal in linear time as a function of the number of references: O(PackedRefs + LooseRefs). Scans of the loose reference space to update the cache run in O(LooseRefs log LooseRefs) time, as the directory contents are sorted before being merged against the in-memory cache. Since the majority of stable references are kept packed, there typically are only a handful of reference names to be sorted, so the sorting cost should not be very high. Locking is reduced during getRefs() by taking advantage of the copy-on-write semantics of the improved cache data structure. This permits concurrent readers to pull back references without blocking each other. If there is contention updating the cache during a scan, one or more updates are simply skipped and will get picked up again in a future scan. Writing to the $GIT_DIR/packed-refs during reference delete is now fully atomic. The file is locked, reparsed fresh, and written back out if a change is necessary. This avoids all race conditions with concurrent external updates of the packed-refs file. The RefLogWriter class has been fully folded into RefDirectory and is therefore deleted. Maintaining the reference's log is the responsiblity of the database implementation, and not all implementations will use java.io for access. Future work still remains to be done to abstract the ReflogReader class away from local disk IO. Change-Id: I26b9287c45a4b2d2be35ba2849daa316f5eec85d Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
14 yıl önce
Rewrite reference handling to be abstract and accurate This commit actually does three major changes to the way references are handled within JGit. Unfortunately they were easier to do as a single massive commit than to break them up into smaller units. Disambiguate symbolic references: --------------------------------- Reporting a symbolic reference such as HEAD as though it were any other normal reference like refs/heads/master causes subtle programming errors. We have been bitten by this error on several occasions, as have some downstream applications written by myself. Instead of reporting HEAD as a reference whose name differs from its "original name", report it as an actual SymbolicRef object that the application can test the type and examine the target of. With this change, Ref is now an abstract type with different subclasses for the different types. In the classical example of "HEAD" being a symbolic reference to branch "refs/heads/master", the Repository.getAllRefs() method will now return: Map<String, Ref> all = repository.getAllRefs(); SymbolicRef HEAD = (SymbolicRef) all.get("HEAD"); ObjectIdRef master = (ObjectIdRef) all.get("refs/heads/master"); assertSame(master, HEAD.getTarget()); assertSame(master.getObjectId(), HEAD.getObjectId()); assertEquals("HEAD", HEAD.getName()); assertEquals("refs/heads/master", master.getName()); A nice side-effect of this change is the storage type of the symbolic reference is no longer ambiguous with the storge type of the underlying reference it targets. In the above example, if master was only available in the packed-refs file, then the following is also true: assertSame(Ref.Storage.LOOSE, HEAD.getStorage()); assertSame(Ref.Storage.PACKED, master.getStorage()); (Prior to this change we returned the ambiguous storage of LOOSE_PACKED for HEAD, which was confusing since it wasn't actually true on disk). Another nice side-effect of this change is all intermediate symbolic references are preserved, and are therefore visible to the application when they walk the target chain. We can now correctly inspect chains of symbolic references. As a result of this change the Ref.getOrigName() method has been removed from the API. Applications should identify a symbolic reference by testing for isSymbolic() and not by using an arcane string comparsion between properties. Abstract the RefDatabase storage: --------------------------------- RefDatabase is now abstract, similar to ObjectDatabase, and a new concrete implementation called RefDirectory is used for the traditional on-disk storage layout. In the future we plan to support additional implementations, such as a pure in-memory RefDatabase for unit testing purposes. Optimize RefDirectory: ---------------------- The implementation of the in-memory reference cache, reading, and update routines has been completely rewritten. Much of the code was heavily borrowed or cribbed from the prior implementation, so copyright notices have been left intact as much as possible. The RefDirectory cache no longer confuses symbolic references with normal references. This permits the cache to resolve the value of a symbolic reference as late as possible, ensuring it is always current, without needing to maintain reverse pointers. The cache is now 2 sorted RefLists, rather than 3 HashMaps. Using sorted lists allows the implementation to reduce the in-memory footprint when storing many refs. Using specialized types for the elements allows the code to avoid additional map lookups for auxiliary stat information. To improve scan time during getRefs(), the lists are returned via a copy-on-write contract. Most callers of getRefs() do not modify the returned collections, so the copy-on-write semantics improves access on repositories with a large number of packed references. Iterator traversals of the returned Map<String,Ref> are performed using a simple merge-join of the two cache lists, ensuring we can perform the entire traversal in linear time as a function of the number of references: O(PackedRefs + LooseRefs). Scans of the loose reference space to update the cache run in O(LooseRefs log LooseRefs) time, as the directory contents are sorted before being merged against the in-memory cache. Since the majority of stable references are kept packed, there typically are only a handful of reference names to be sorted, so the sorting cost should not be very high. Locking is reduced during getRefs() by taking advantage of the copy-on-write semantics of the improved cache data structure. This permits concurrent readers to pull back references without blocking each other. If there is contention updating the cache during a scan, one or more updates are simply skipped and will get picked up again in a future scan. Writing to the $GIT_DIR/packed-refs during reference delete is now fully atomic. The file is locked, reparsed fresh, and written back out if a change is necessary. This avoids all race conditions with concurrent external updates of the packed-refs file. The RefLogWriter class has been fully folded into RefDirectory and is therefore deleted. Maintaining the reference's log is the responsiblity of the database implementation, and not all implementations will use java.io for access. Future work still remains to be done to abstract the ReflogReader class away from local disk IO. Change-Id: I26b9287c45a4b2d2be35ba2849daa316f5eec85d Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
14 yıl önce
Rewrite reference handling to be abstract and accurate This commit actually does three major changes to the way references are handled within JGit. Unfortunately they were easier to do as a single massive commit than to break them up into smaller units. Disambiguate symbolic references: --------------------------------- Reporting a symbolic reference such as HEAD as though it were any other normal reference like refs/heads/master causes subtle programming errors. We have been bitten by this error on several occasions, as have some downstream applications written by myself. Instead of reporting HEAD as a reference whose name differs from its "original name", report it as an actual SymbolicRef object that the application can test the type and examine the target of. With this change, Ref is now an abstract type with different subclasses for the different types. In the classical example of "HEAD" being a symbolic reference to branch "refs/heads/master", the Repository.getAllRefs() method will now return: Map<String, Ref> all = repository.getAllRefs(); SymbolicRef HEAD = (SymbolicRef) all.get("HEAD"); ObjectIdRef master = (ObjectIdRef) all.get("refs/heads/master"); assertSame(master, HEAD.getTarget()); assertSame(master.getObjectId(), HEAD.getObjectId()); assertEquals("HEAD", HEAD.getName()); assertEquals("refs/heads/master", master.getName()); A nice side-effect of this change is the storage type of the symbolic reference is no longer ambiguous with the storge type of the underlying reference it targets. In the above example, if master was only available in the packed-refs file, then the following is also true: assertSame(Ref.Storage.LOOSE, HEAD.getStorage()); assertSame(Ref.Storage.PACKED, master.getStorage()); (Prior to this change we returned the ambiguous storage of LOOSE_PACKED for HEAD, which was confusing since it wasn't actually true on disk). Another nice side-effect of this change is all intermediate symbolic references are preserved, and are therefore visible to the application when they walk the target chain. We can now correctly inspect chains of symbolic references. As a result of this change the Ref.getOrigName() method has been removed from the API. Applications should identify a symbolic reference by testing for isSymbolic() and not by using an arcane string comparsion between properties. Abstract the RefDatabase storage: --------------------------------- RefDatabase is now abstract, similar to ObjectDatabase, and a new concrete implementation called RefDirectory is used for the traditional on-disk storage layout. In the future we plan to support additional implementations, such as a pure in-memory RefDatabase for unit testing purposes. Optimize RefDirectory: ---------------------- The implementation of the in-memory reference cache, reading, and update routines has been completely rewritten. Much of the code was heavily borrowed or cribbed from the prior implementation, so copyright notices have been left intact as much as possible. The RefDirectory cache no longer confuses symbolic references with normal references. This permits the cache to resolve the value of a symbolic reference as late as possible, ensuring it is always current, without needing to maintain reverse pointers. The cache is now 2 sorted RefLists, rather than 3 HashMaps. Using sorted lists allows the implementation to reduce the in-memory footprint when storing many refs. Using specialized types for the elements allows the code to avoid additional map lookups for auxiliary stat information. To improve scan time during getRefs(), the lists are returned via a copy-on-write contract. Most callers of getRefs() do not modify the returned collections, so the copy-on-write semantics improves access on repositories with a large number of packed references. Iterator traversals of the returned Map<String,Ref> are performed using a simple merge-join of the two cache lists, ensuring we can perform the entire traversal in linear time as a function of the number of references: O(PackedRefs + LooseRefs). Scans of the loose reference space to update the cache run in O(LooseRefs log LooseRefs) time, as the directory contents are sorted before being merged against the in-memory cache. Since the majority of stable references are kept packed, there typically are only a handful of reference names to be sorted, so the sorting cost should not be very high. Locking is reduced during getRefs() by taking advantage of the copy-on-write semantics of the improved cache data structure. This permits concurrent readers to pull back references without blocking each other. If there is contention updating the cache during a scan, one or more updates are simply skipped and will get picked up again in a future scan. Writing to the $GIT_DIR/packed-refs during reference delete is now fully atomic. The file is locked, reparsed fresh, and written back out if a change is necessary. This avoids all race conditions with concurrent external updates of the packed-refs file. The RefLogWriter class has been fully folded into RefDirectory and is therefore deleted. Maintaining the reference's log is the responsiblity of the database implementation, and not all implementations will use java.io for access. Future work still remains to be done to abstract the ReflogReader class away from local disk IO. Change-Id: I26b9287c45a4b2d2be35ba2849daa316f5eec85d Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
14 yıl önce
Rewrite reference handling to be abstract and accurate This commit actually does three major changes to the way references are handled within JGit. Unfortunately they were easier to do as a single massive commit than to break them up into smaller units. Disambiguate symbolic references: --------------------------------- Reporting a symbolic reference such as HEAD as though it were any other normal reference like refs/heads/master causes subtle programming errors. We have been bitten by this error on several occasions, as have some downstream applications written by myself. Instead of reporting HEAD as a reference whose name differs from its "original name", report it as an actual SymbolicRef object that the application can test the type and examine the target of. With this change, Ref is now an abstract type with different subclasses for the different types. In the classical example of "HEAD" being a symbolic reference to branch "refs/heads/master", the Repository.getAllRefs() method will now return: Map<String, Ref> all = repository.getAllRefs(); SymbolicRef HEAD = (SymbolicRef) all.get("HEAD"); ObjectIdRef master = (ObjectIdRef) all.get("refs/heads/master"); assertSame(master, HEAD.getTarget()); assertSame(master.getObjectId(), HEAD.getObjectId()); assertEquals("HEAD", HEAD.getName()); assertEquals("refs/heads/master", master.getName()); A nice side-effect of this change is the storage type of the symbolic reference is no longer ambiguous with the storge type of the underlying reference it targets. In the above example, if master was only available in the packed-refs file, then the following is also true: assertSame(Ref.Storage.LOOSE, HEAD.getStorage()); assertSame(Ref.Storage.PACKED, master.getStorage()); (Prior to this change we returned the ambiguous storage of LOOSE_PACKED for HEAD, which was confusing since it wasn't actually true on disk). Another nice side-effect of this change is all intermediate symbolic references are preserved, and are therefore visible to the application when they walk the target chain. We can now correctly inspect chains of symbolic references. As a result of this change the Ref.getOrigName() method has been removed from the API. Applications should identify a symbolic reference by testing for isSymbolic() and not by using an arcane string comparsion between properties. Abstract the RefDatabase storage: --------------------------------- RefDatabase is now abstract, similar to ObjectDatabase, and a new concrete implementation called RefDirectory is used for the traditional on-disk storage layout. In the future we plan to support additional implementations, such as a pure in-memory RefDatabase for unit testing purposes. Optimize RefDirectory: ---------------------- The implementation of the in-memory reference cache, reading, and update routines has been completely rewritten. Much of the code was heavily borrowed or cribbed from the prior implementation, so copyright notices have been left intact as much as possible. The RefDirectory cache no longer confuses symbolic references with normal references. This permits the cache to resolve the value of a symbolic reference as late as possible, ensuring it is always current, without needing to maintain reverse pointers. The cache is now 2 sorted RefLists, rather than 3 HashMaps. Using sorted lists allows the implementation to reduce the in-memory footprint when storing many refs. Using specialized types for the elements allows the code to avoid additional map lookups for auxiliary stat information. To improve scan time during getRefs(), the lists are returned via a copy-on-write contract. Most callers of getRefs() do not modify the returned collections, so the copy-on-write semantics improves access on repositories with a large number of packed references. Iterator traversals of the returned Map<String,Ref> are performed using a simple merge-join of the two cache lists, ensuring we can perform the entire traversal in linear time as a function of the number of references: O(PackedRefs + LooseRefs). Scans of the loose reference space to update the cache run in O(LooseRefs log LooseRefs) time, as the directory contents are sorted before being merged against the in-memory cache. Since the majority of stable references are kept packed, there typically are only a handful of reference names to be sorted, so the sorting cost should not be very high. Locking is reduced during getRefs() by taking advantage of the copy-on-write semantics of the improved cache data structure. This permits concurrent readers to pull back references without blocking each other. If there is contention updating the cache during a scan, one or more updates are simply skipped and will get picked up again in a future scan. Writing to the $GIT_DIR/packed-refs during reference delete is now fully atomic. The file is locked, reparsed fresh, and written back out if a change is necessary. This avoids all race conditions with concurrent external updates of the packed-refs file. The RefLogWriter class has been fully folded into RefDirectory and is therefore deleted. Maintaining the reference's log is the responsiblity of the database implementation, and not all implementations will use java.io for access. Future work still remains to be done to abstract the ReflogReader class away from local disk IO. Change-Id: I26b9287c45a4b2d2be35ba2849daa316f5eec85d Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
14 yıl önce
Rewrite reference handling to be abstract and accurate This commit actually does three major changes to the way references are handled within JGit. Unfortunately they were easier to do as a single massive commit than to break them up into smaller units. Disambiguate symbolic references: --------------------------------- Reporting a symbolic reference such as HEAD as though it were any other normal reference like refs/heads/master causes subtle programming errors. We have been bitten by this error on several occasions, as have some downstream applications written by myself. Instead of reporting HEAD as a reference whose name differs from its "original name", report it as an actual SymbolicRef object that the application can test the type and examine the target of. With this change, Ref is now an abstract type with different subclasses for the different types. In the classical example of "HEAD" being a symbolic reference to branch "refs/heads/master", the Repository.getAllRefs() method will now return: Map<String, Ref> all = repository.getAllRefs(); SymbolicRef HEAD = (SymbolicRef) all.get("HEAD"); ObjectIdRef master = (ObjectIdRef) all.get("refs/heads/master"); assertSame(master, HEAD.getTarget()); assertSame(master.getObjectId(), HEAD.getObjectId()); assertEquals("HEAD", HEAD.getName()); assertEquals("refs/heads/master", master.getName()); A nice side-effect of this change is the storage type of the symbolic reference is no longer ambiguous with the storge type of the underlying reference it targets. In the above example, if master was only available in the packed-refs file, then the following is also true: assertSame(Ref.Storage.LOOSE, HEAD.getStorage()); assertSame(Ref.Storage.PACKED, master.getStorage()); (Prior to this change we returned the ambiguous storage of LOOSE_PACKED for HEAD, which was confusing since it wasn't actually true on disk). Another nice side-effect of this change is all intermediate symbolic references are preserved, and are therefore visible to the application when they walk the target chain. We can now correctly inspect chains of symbolic references. As a result of this change the Ref.getOrigName() method has been removed from the API. Applications should identify a symbolic reference by testing for isSymbolic() and not by using an arcane string comparsion between properties. Abstract the RefDatabase storage: --------------------------------- RefDatabase is now abstract, similar to ObjectDatabase, and a new concrete implementation called RefDirectory is used for the traditional on-disk storage layout. In the future we plan to support additional implementations, such as a pure in-memory RefDatabase for unit testing purposes. Optimize RefDirectory: ---------------------- The implementation of the in-memory reference cache, reading, and update routines has been completely rewritten. Much of the code was heavily borrowed or cribbed from the prior implementation, so copyright notices have been left intact as much as possible. The RefDirectory cache no longer confuses symbolic references with normal references. This permits the cache to resolve the value of a symbolic reference as late as possible, ensuring it is always current, without needing to maintain reverse pointers. The cache is now 2 sorted RefLists, rather than 3 HashMaps. Using sorted lists allows the implementation to reduce the in-memory footprint when storing many refs. Using specialized types for the elements allows the code to avoid additional map lookups for auxiliary stat information. To improve scan time during getRefs(), the lists are returned via a copy-on-write contract. Most callers of getRefs() do not modify the returned collections, so the copy-on-write semantics improves access on repositories with a large number of packed references. Iterator traversals of the returned Map<String,Ref> are performed using a simple merge-join of the two cache lists, ensuring we can perform the entire traversal in linear time as a function of the number of references: O(PackedRefs + LooseRefs). Scans of the loose reference space to update the cache run in O(LooseRefs log LooseRefs) time, as the directory contents are sorted before being merged against the in-memory cache. Since the majority of stable references are kept packed, there typically are only a handful of reference names to be sorted, so the sorting cost should not be very high. Locking is reduced during getRefs() by taking advantage of the copy-on-write semantics of the improved cache data structure. This permits concurrent readers to pull back references without blocking each other. If there is contention updating the cache during a scan, one or more updates are simply skipped and will get picked up again in a future scan. Writing to the $GIT_DIR/packed-refs during reference delete is now fully atomic. The file is locked, reparsed fresh, and written back out if a change is necessary. This avoids all race conditions with concurrent external updates of the packed-refs file. The RefLogWriter class has been fully folded into RefDirectory and is therefore deleted. Maintaining the reference's log is the responsiblity of the database implementation, and not all implementations will use java.io for access. Future work still remains to be done to abstract the ReflogReader class away from local disk IO. Change-Id: I26b9287c45a4b2d2be35ba2849daa316f5eec85d Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
14 yıl önce
Rewrite reference handling to be abstract and accurate This commit actually does three major changes to the way references are handled within JGit. Unfortunately they were easier to do as a single massive commit than to break them up into smaller units. Disambiguate symbolic references: --------------------------------- Reporting a symbolic reference such as HEAD as though it were any other normal reference like refs/heads/master causes subtle programming errors. We have been bitten by this error on several occasions, as have some downstream applications written by myself. Instead of reporting HEAD as a reference whose name differs from its "original name", report it as an actual SymbolicRef object that the application can test the type and examine the target of. With this change, Ref is now an abstract type with different subclasses for the different types. In the classical example of "HEAD" being a symbolic reference to branch "refs/heads/master", the Repository.getAllRefs() method will now return: Map<String, Ref> all = repository.getAllRefs(); SymbolicRef HEAD = (SymbolicRef) all.get("HEAD"); ObjectIdRef master = (ObjectIdRef) all.get("refs/heads/master"); assertSame(master, HEAD.getTarget()); assertSame(master.getObjectId(), HEAD.getObjectId()); assertEquals("HEAD", HEAD.getName()); assertEquals("refs/heads/master", master.getName()); A nice side-effect of this change is the storage type of the symbolic reference is no longer ambiguous with the storge type of the underlying reference it targets. In the above example, if master was only available in the packed-refs file, then the following is also true: assertSame(Ref.Storage.LOOSE, HEAD.getStorage()); assertSame(Ref.Storage.PACKED, master.getStorage()); (Prior to this change we returned the ambiguous storage of LOOSE_PACKED for HEAD, which was confusing since it wasn't actually true on disk). Another nice side-effect of this change is all intermediate symbolic references are preserved, and are therefore visible to the application when they walk the target chain. We can now correctly inspect chains of symbolic references. As a result of this change the Ref.getOrigName() method has been removed from the API. Applications should identify a symbolic reference by testing for isSymbolic() and not by using an arcane string comparsion between properties. Abstract the RefDatabase storage: --------------------------------- RefDatabase is now abstract, similar to ObjectDatabase, and a new concrete implementation called RefDirectory is used for the traditional on-disk storage layout. In the future we plan to support additional implementations, such as a pure in-memory RefDatabase for unit testing purposes. Optimize RefDirectory: ---------------------- The implementation of the in-memory reference cache, reading, and update routines has been completely rewritten. Much of the code was heavily borrowed or cribbed from the prior implementation, so copyright notices have been left intact as much as possible. The RefDirectory cache no longer confuses symbolic references with normal references. This permits the cache to resolve the value of a symbolic reference as late as possible, ensuring it is always current, without needing to maintain reverse pointers. The cache is now 2 sorted RefLists, rather than 3 HashMaps. Using sorted lists allows the implementation to reduce the in-memory footprint when storing many refs. Using specialized types for the elements allows the code to avoid additional map lookups for auxiliary stat information. To improve scan time during getRefs(), the lists are returned via a copy-on-write contract. Most callers of getRefs() do not modify the returned collections, so the copy-on-write semantics improves access on repositories with a large number of packed references. Iterator traversals of the returned Map<String,Ref> are performed using a simple merge-join of the two cache lists, ensuring we can perform the entire traversal in linear time as a function of the number of references: O(PackedRefs + LooseRefs). Scans of the loose reference space to update the cache run in O(LooseRefs log LooseRefs) time, as the directory contents are sorted before being merged against the in-memory cache. Since the majority of stable references are kept packed, there typically are only a handful of reference names to be sorted, so the sorting cost should not be very high. Locking is reduced during getRefs() by taking advantage of the copy-on-write semantics of the improved cache data structure. This permits concurrent readers to pull back references without blocking each other. If there is contention updating the cache during a scan, one or more updates are simply skipped and will get picked up again in a future scan. Writing to the $GIT_DIR/packed-refs during reference delete is now fully atomic. The file is locked, reparsed fresh, and written back out if a change is necessary. This avoids all race conditions with concurrent external updates of the packed-refs file. The RefLogWriter class has been fully folded into RefDirectory and is therefore deleted. Maintaining the reference's log is the responsiblity of the database implementation, and not all implementations will use java.io for access. Future work still remains to be done to abstract the ReflogReader class away from local disk IO. Change-Id: I26b9287c45a4b2d2be35ba2849daa316f5eec85d Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
14 yıl önce
Rewrite reference handling to be abstract and accurate This commit actually does three major changes to the way references are handled within JGit. Unfortunately they were easier to do as a single massive commit than to break them up into smaller units. Disambiguate symbolic references: --------------------------------- Reporting a symbolic reference such as HEAD as though it were any other normal reference like refs/heads/master causes subtle programming errors. We have been bitten by this error on several occasions, as have some downstream applications written by myself. Instead of reporting HEAD as a reference whose name differs from its "original name", report it as an actual SymbolicRef object that the application can test the type and examine the target of. With this change, Ref is now an abstract type with different subclasses for the different types. In the classical example of "HEAD" being a symbolic reference to branch "refs/heads/master", the Repository.getAllRefs() method will now return: Map<String, Ref> all = repository.getAllRefs(); SymbolicRef HEAD = (SymbolicRef) all.get("HEAD"); ObjectIdRef master = (ObjectIdRef) all.get("refs/heads/master"); assertSame(master, HEAD.getTarget()); assertSame(master.getObjectId(), HEAD.getObjectId()); assertEquals("HEAD", HEAD.getName()); assertEquals("refs/heads/master", master.getName()); A nice side-effect of this change is the storage type of the symbolic reference is no longer ambiguous with the storge type of the underlying reference it targets. In the above example, if master was only available in the packed-refs file, then the following is also true: assertSame(Ref.Storage.LOOSE, HEAD.getStorage()); assertSame(Ref.Storage.PACKED, master.getStorage()); (Prior to this change we returned the ambiguous storage of LOOSE_PACKED for HEAD, which was confusing since it wasn't actually true on disk). Another nice side-effect of this change is all intermediate symbolic references are preserved, and are therefore visible to the application when they walk the target chain. We can now correctly inspect chains of symbolic references. As a result of this change the Ref.getOrigName() method has been removed from the API. Applications should identify a symbolic reference by testing for isSymbolic() and not by using an arcane string comparsion between properties. Abstract the RefDatabase storage: --------------------------------- RefDatabase is now abstract, similar to ObjectDatabase, and a new concrete implementation called RefDirectory is used for the traditional on-disk storage layout. In the future we plan to support additional implementations, such as a pure in-memory RefDatabase for unit testing purposes. Optimize RefDirectory: ---------------------- The implementation of the in-memory reference cache, reading, and update routines has been completely rewritten. Much of the code was heavily borrowed or cribbed from the prior implementation, so copyright notices have been left intact as much as possible. The RefDirectory cache no longer confuses symbolic references with normal references. This permits the cache to resolve the value of a symbolic reference as late as possible, ensuring it is always current, without needing to maintain reverse pointers. The cache is now 2 sorted RefLists, rather than 3 HashMaps. Using sorted lists allows the implementation to reduce the in-memory footprint when storing many refs. Using specialized types for the elements allows the code to avoid additional map lookups for auxiliary stat information. To improve scan time during getRefs(), the lists are returned via a copy-on-write contract. Most callers of getRefs() do not modify the returned collections, so the copy-on-write semantics improves access on repositories with a large number of packed references. Iterator traversals of the returned Map<String,Ref> are performed using a simple merge-join of the two cache lists, ensuring we can perform the entire traversal in linear time as a function of the number of references: O(PackedRefs + LooseRefs). Scans of the loose reference space to update the cache run in O(LooseRefs log LooseRefs) time, as the directory contents are sorted before being merged against the in-memory cache. Since the majority of stable references are kept packed, there typically are only a handful of reference names to be sorted, so the sorting cost should not be very high. Locking is reduced during getRefs() by taking advantage of the copy-on-write semantics of the improved cache data structure. This permits concurrent readers to pull back references without blocking each other. If there is contention updating the cache during a scan, one or more updates are simply skipped and will get picked up again in a future scan. Writing to the $GIT_DIR/packed-refs during reference delete is now fully atomic. The file is locked, reparsed fresh, and written back out if a change is necessary. This avoids all race conditions with concurrent external updates of the packed-refs file. The RefLogWriter class has been fully folded into RefDirectory and is therefore deleted. Maintaining the reference's log is the responsiblity of the database implementation, and not all implementations will use java.io for access. Future work still remains to be done to abstract the ReflogReader class away from local disk IO. Change-Id: I26b9287c45a4b2d2be35ba2849daa316f5eec85d Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
14 yıl önce
Rewrite reference handling to be abstract and accurate This commit actually does three major changes to the way references are handled within JGit. Unfortunately they were easier to do as a single massive commit than to break them up into smaller units. Disambiguate symbolic references: --------------------------------- Reporting a symbolic reference such as HEAD as though it were any other normal reference like refs/heads/master causes subtle programming errors. We have been bitten by this error on several occasions, as have some downstream applications written by myself. Instead of reporting HEAD as a reference whose name differs from its "original name", report it as an actual SymbolicRef object that the application can test the type and examine the target of. With this change, Ref is now an abstract type with different subclasses for the different types. In the classical example of "HEAD" being a symbolic reference to branch "refs/heads/master", the Repository.getAllRefs() method will now return: Map<String, Ref> all = repository.getAllRefs(); SymbolicRef HEAD = (SymbolicRef) all.get("HEAD"); ObjectIdRef master = (ObjectIdRef) all.get("refs/heads/master"); assertSame(master, HEAD.getTarget()); assertSame(master.getObjectId(), HEAD.getObjectId()); assertEquals("HEAD", HEAD.getName()); assertEquals("refs/heads/master", master.getName()); A nice side-effect of this change is the storage type of the symbolic reference is no longer ambiguous with the storge type of the underlying reference it targets. In the above example, if master was only available in the packed-refs file, then the following is also true: assertSame(Ref.Storage.LOOSE, HEAD.getStorage()); assertSame(Ref.Storage.PACKED, master.getStorage()); (Prior to this change we returned the ambiguous storage of LOOSE_PACKED for HEAD, which was confusing since it wasn't actually true on disk). Another nice side-effect of this change is all intermediate symbolic references are preserved, and are therefore visible to the application when they walk the target chain. We can now correctly inspect chains of symbolic references. As a result of this change the Ref.getOrigName() method has been removed from the API. Applications should identify a symbolic reference by testing for isSymbolic() and not by using an arcane string comparsion between properties. Abstract the RefDatabase storage: --------------------------------- RefDatabase is now abstract, similar to ObjectDatabase, and a new concrete implementation called RefDirectory is used for the traditional on-disk storage layout. In the future we plan to support additional implementations, such as a pure in-memory RefDatabase for unit testing purposes. Optimize RefDirectory: ---------------------- The implementation of the in-memory reference cache, reading, and update routines has been completely rewritten. Much of the code was heavily borrowed or cribbed from the prior implementation, so copyright notices have been left intact as much as possible. The RefDirectory cache no longer confuses symbolic references with normal references. This permits the cache to resolve the value of a symbolic reference as late as possible, ensuring it is always current, without needing to maintain reverse pointers. The cache is now 2 sorted RefLists, rather than 3 HashMaps. Using sorted lists allows the implementation to reduce the in-memory footprint when storing many refs. Using specialized types for the elements allows the code to avoid additional map lookups for auxiliary stat information. To improve scan time during getRefs(), the lists are returned via a copy-on-write contract. Most callers of getRefs() do not modify the returned collections, so the copy-on-write semantics improves access on repositories with a large number of packed references. Iterator traversals of the returned Map<String,Ref> are performed using a simple merge-join of the two cache lists, ensuring we can perform the entire traversal in linear time as a function of the number of references: O(PackedRefs + LooseRefs). Scans of the loose reference space to update the cache run in O(LooseRefs log LooseRefs) time, as the directory contents are sorted before being merged against the in-memory cache. Since the majority of stable references are kept packed, there typically are only a handful of reference names to be sorted, so the sorting cost should not be very high. Locking is reduced during getRefs() by taking advantage of the copy-on-write semantics of the improved cache data structure. This permits concurrent readers to pull back references without blocking each other. If there is contention updating the cache during a scan, one or more updates are simply skipped and will get picked up again in a future scan. Writing to the $GIT_DIR/packed-refs during reference delete is now fully atomic. The file is locked, reparsed fresh, and written back out if a change is necessary. This avoids all race conditions with concurrent external updates of the packed-refs file. The RefLogWriter class has been fully folded into RefDirectory and is therefore deleted. Maintaining the reference's log is the responsiblity of the database implementation, and not all implementations will use java.io for access. Future work still remains to be done to abstract the ReflogReader class away from local disk IO. Change-Id: I26b9287c45a4b2d2be35ba2849daa316f5eec85d Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
14 yıl önce
Rewrite reference handling to be abstract and accurate This commit actually does three major changes to the way references are handled within JGit. Unfortunately they were easier to do as a single massive commit than to break them up into smaller units. Disambiguate symbolic references: --------------------------------- Reporting a symbolic reference such as HEAD as though it were any other normal reference like refs/heads/master causes subtle programming errors. We have been bitten by this error on several occasions, as have some downstream applications written by myself. Instead of reporting HEAD as a reference whose name differs from its "original name", report it as an actual SymbolicRef object that the application can test the type and examine the target of. With this change, Ref is now an abstract type with different subclasses for the different types. In the classical example of "HEAD" being a symbolic reference to branch "refs/heads/master", the Repository.getAllRefs() method will now return: Map<String, Ref> all = repository.getAllRefs(); SymbolicRef HEAD = (SymbolicRef) all.get("HEAD"); ObjectIdRef master = (ObjectIdRef) all.get("refs/heads/master"); assertSame(master, HEAD.getTarget()); assertSame(master.getObjectId(), HEAD.getObjectId()); assertEquals("HEAD", HEAD.getName()); assertEquals("refs/heads/master", master.getName()); A nice side-effect of this change is the storage type of the symbolic reference is no longer ambiguous with the storge type of the underlying reference it targets. In the above example, if master was only available in the packed-refs file, then the following is also true: assertSame(Ref.Storage.LOOSE, HEAD.getStorage()); assertSame(Ref.Storage.PACKED, master.getStorage()); (Prior to this change we returned the ambiguous storage of LOOSE_PACKED for HEAD, which was confusing since it wasn't actually true on disk). Another nice side-effect of this change is all intermediate symbolic references are preserved, and are therefore visible to the application when they walk the target chain. We can now correctly inspect chains of symbolic references. As a result of this change the Ref.getOrigName() method has been removed from the API. Applications should identify a symbolic reference by testing for isSymbolic() and not by using an arcane string comparsion between properties. Abstract the RefDatabase storage: --------------------------------- RefDatabase is now abstract, similar to ObjectDatabase, and a new concrete implementation called RefDirectory is used for the traditional on-disk storage layout. In the future we plan to support additional implementations, such as a pure in-memory RefDatabase for unit testing purposes. Optimize RefDirectory: ---------------------- The implementation of the in-memory reference cache, reading, and update routines has been completely rewritten. Much of the code was heavily borrowed or cribbed from the prior implementation, so copyright notices have been left intact as much as possible. The RefDirectory cache no longer confuses symbolic references with normal references. This permits the cache to resolve the value of a symbolic reference as late as possible, ensuring it is always current, without needing to maintain reverse pointers. The cache is now 2 sorted RefLists, rather than 3 HashMaps. Using sorted lists allows the implementation to reduce the in-memory footprint when storing many refs. Using specialized types for the elements allows the code to avoid additional map lookups for auxiliary stat information. To improve scan time during getRefs(), the lists are returned via a copy-on-write contract. Most callers of getRefs() do not modify the returned collections, so the copy-on-write semantics improves access on repositories with a large number of packed references. Iterator traversals of the returned Map<String,Ref> are performed using a simple merge-join of the two cache lists, ensuring we can perform the entire traversal in linear time as a function of the number of references: O(PackedRefs + LooseRefs). Scans of the loose reference space to update the cache run in O(LooseRefs log LooseRefs) time, as the directory contents are sorted before being merged against the in-memory cache. Since the majority of stable references are kept packed, there typically are only a handful of reference names to be sorted, so the sorting cost should not be very high. Locking is reduced during getRefs() by taking advantage of the copy-on-write semantics of the improved cache data structure. This permits concurrent readers to pull back references without blocking each other. If there is contention updating the cache during a scan, one or more updates are simply skipped and will get picked up again in a future scan. Writing to the $GIT_DIR/packed-refs during reference delete is now fully atomic. The file is locked, reparsed fresh, and written back out if a change is necessary. This avoids all race conditions with concurrent external updates of the packed-refs file. The RefLogWriter class has been fully folded into RefDirectory and is therefore deleted. Maintaining the reference's log is the responsiblity of the database implementation, and not all implementations will use java.io for access. Future work still remains to be done to abstract the ReflogReader class away from local disk IO. Change-Id: I26b9287c45a4b2d2be35ba2849daa316f5eec85d Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
14 yıl önce
Rewrite reference handling to be abstract and accurate This commit actually does three major changes to the way references are handled within JGit. Unfortunately they were easier to do as a single massive commit than to break them up into smaller units. Disambiguate symbolic references: --------------------------------- Reporting a symbolic reference such as HEAD as though it were any other normal reference like refs/heads/master causes subtle programming errors. We have been bitten by this error on several occasions, as have some downstream applications written by myself. Instead of reporting HEAD as a reference whose name differs from its "original name", report it as an actual SymbolicRef object that the application can test the type and examine the target of. With this change, Ref is now an abstract type with different subclasses for the different types. In the classical example of "HEAD" being a symbolic reference to branch "refs/heads/master", the Repository.getAllRefs() method will now return: Map<String, Ref> all = repository.getAllRefs(); SymbolicRef HEAD = (SymbolicRef) all.get("HEAD"); ObjectIdRef master = (ObjectIdRef) all.get("refs/heads/master"); assertSame(master, HEAD.getTarget()); assertSame(master.getObjectId(), HEAD.getObjectId()); assertEquals("HEAD", HEAD.getName()); assertEquals("refs/heads/master", master.getName()); A nice side-effect of this change is the storage type of the symbolic reference is no longer ambiguous with the storge type of the underlying reference it targets. In the above example, if master was only available in the packed-refs file, then the following is also true: assertSame(Ref.Storage.LOOSE, HEAD.getStorage()); assertSame(Ref.Storage.PACKED, master.getStorage()); (Prior to this change we returned the ambiguous storage of LOOSE_PACKED for HEAD, which was confusing since it wasn't actually true on disk). Another nice side-effect of this change is all intermediate symbolic references are preserved, and are therefore visible to the application when they walk the target chain. We can now correctly inspect chains of symbolic references. As a result of this change the Ref.getOrigName() method has been removed from the API. Applications should identify a symbolic reference by testing for isSymbolic() and not by using an arcane string comparsion between properties. Abstract the RefDatabase storage: --------------------------------- RefDatabase is now abstract, similar to ObjectDatabase, and a new concrete implementation called RefDirectory is used for the traditional on-disk storage layout. In the future we plan to support additional implementations, such as a pure in-memory RefDatabase for unit testing purposes. Optimize RefDirectory: ---------------------- The implementation of the in-memory reference cache, reading, and update routines has been completely rewritten. Much of the code was heavily borrowed or cribbed from the prior implementation, so copyright notices have been left intact as much as possible. The RefDirectory cache no longer confuses symbolic references with normal references. This permits the cache to resolve the value of a symbolic reference as late as possible, ensuring it is always current, without needing to maintain reverse pointers. The cache is now 2 sorted RefLists, rather than 3 HashMaps. Using sorted lists allows the implementation to reduce the in-memory footprint when storing many refs. Using specialized types for the elements allows the code to avoid additional map lookups for auxiliary stat information. To improve scan time during getRefs(), the lists are returned via a copy-on-write contract. Most callers of getRefs() do not modify the returned collections, so the copy-on-write semantics improves access on repositories with a large number of packed references. Iterator traversals of the returned Map<String,Ref> are performed using a simple merge-join of the two cache lists, ensuring we can perform the entire traversal in linear time as a function of the number of references: O(PackedRefs + LooseRefs). Scans of the loose reference space to update the cache run in O(LooseRefs log LooseRefs) time, as the directory contents are sorted before being merged against the in-memory cache. Since the majority of stable references are kept packed, there typically are only a handful of reference names to be sorted, so the sorting cost should not be very high. Locking is reduced during getRefs() by taking advantage of the copy-on-write semantics of the improved cache data structure. This permits concurrent readers to pull back references without blocking each other. If there is contention updating the cache during a scan, one or more updates are simply skipped and will get picked up again in a future scan. Writing to the $GIT_DIR/packed-refs during reference delete is now fully atomic. The file is locked, reparsed fresh, and written back out if a change is necessary. This avoids all race conditions with concurrent external updates of the packed-refs file. The RefLogWriter class has been fully folded into RefDirectory and is therefore deleted. Maintaining the reference's log is the responsiblity of the database implementation, and not all implementations will use java.io for access. Future work still remains to be done to abstract the ReflogReader class away from local disk IO. Change-Id: I26b9287c45a4b2d2be35ba2849daa316f5eec85d Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
14 yıl önce
Rewrite reference handling to be abstract and accurate This commit actually does three major changes to the way references are handled within JGit. Unfortunately they were easier to do as a single massive commit than to break them up into smaller units. Disambiguate symbolic references: --------------------------------- Reporting a symbolic reference such as HEAD as though it were any other normal reference like refs/heads/master causes subtle programming errors. We have been bitten by this error on several occasions, as have some downstream applications written by myself. Instead of reporting HEAD as a reference whose name differs from its "original name", report it as an actual SymbolicRef object that the application can test the type and examine the target of. With this change, Ref is now an abstract type with different subclasses for the different types. In the classical example of "HEAD" being a symbolic reference to branch "refs/heads/master", the Repository.getAllRefs() method will now return: Map<String, Ref> all = repository.getAllRefs(); SymbolicRef HEAD = (SymbolicRef) all.get("HEAD"); ObjectIdRef master = (ObjectIdRef) all.get("refs/heads/master"); assertSame(master, HEAD.getTarget()); assertSame(master.getObjectId(), HEAD.getObjectId()); assertEquals("HEAD", HEAD.getName()); assertEquals("refs/heads/master", master.getName()); A nice side-effect of this change is the storage type of the symbolic reference is no longer ambiguous with the storge type of the underlying reference it targets. In the above example, if master was only available in the packed-refs file, then the following is also true: assertSame(Ref.Storage.LOOSE, HEAD.getStorage()); assertSame(Ref.Storage.PACKED, master.getStorage()); (Prior to this change we returned the ambiguous storage of LOOSE_PACKED for HEAD, which was confusing since it wasn't actually true on disk). Another nice side-effect of this change is all intermediate symbolic references are preserved, and are therefore visible to the application when they walk the target chain. We can now correctly inspect chains of symbolic references. As a result of this change the Ref.getOrigName() method has been removed from the API. Applications should identify a symbolic reference by testing for isSymbolic() and not by using an arcane string comparsion between properties. Abstract the RefDatabase storage: --------------------------------- RefDatabase is now abstract, similar to ObjectDatabase, and a new concrete implementation called RefDirectory is used for the traditional on-disk storage layout. In the future we plan to support additional implementations, such as a pure in-memory RefDatabase for unit testing purposes. Optimize RefDirectory: ---------------------- The implementation of the in-memory reference cache, reading, and update routines has been completely rewritten. Much of the code was heavily borrowed or cribbed from the prior implementation, so copyright notices have been left intact as much as possible. The RefDirectory cache no longer confuses symbolic references with normal references. This permits the cache to resolve the value of a symbolic reference as late as possible, ensuring it is always current, without needing to maintain reverse pointers. The cache is now 2 sorted RefLists, rather than 3 HashMaps. Using sorted lists allows the implementation to reduce the in-memory footprint when storing many refs. Using specialized types for the elements allows the code to avoid additional map lookups for auxiliary stat information. To improve scan time during getRefs(), the lists are returned via a copy-on-write contract. Most callers of getRefs() do not modify the returned collections, so the copy-on-write semantics improves access on repositories with a large number of packed references. Iterator traversals of the returned Map<String,Ref> are performed using a simple merge-join of the two cache lists, ensuring we can perform the entire traversal in linear time as a function of the number of references: O(PackedRefs + LooseRefs). Scans of the loose reference space to update the cache run in O(LooseRefs log LooseRefs) time, as the directory contents are sorted before being merged against the in-memory cache. Since the majority of stable references are kept packed, there typically are only a handful of reference names to be sorted, so the sorting cost should not be very high. Locking is reduced during getRefs() by taking advantage of the copy-on-write semantics of the improved cache data structure. This permits concurrent readers to pull back references without blocking each other. If there is contention updating the cache during a scan, one or more updates are simply skipped and will get picked up again in a future scan. Writing to the $GIT_DIR/packed-refs during reference delete is now fully atomic. The file is locked, reparsed fresh, and written back out if a change is necessary. This avoids all race conditions with concurrent external updates of the packed-refs file. The RefLogWriter class has been fully folded into RefDirectory and is therefore deleted. Maintaining the reference's log is the responsiblity of the database implementation, and not all implementations will use java.io for access. Future work still remains to be done to abstract the ReflogReader class away from local disk IO. Change-Id: I26b9287c45a4b2d2be35ba2849daa316f5eec85d Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
14 yıl önce
Rewrite reference handling to be abstract and accurate This commit actually does three major changes to the way references are handled within JGit. Unfortunately they were easier to do as a single massive commit than to break them up into smaller units. Disambiguate symbolic references: --------------------------------- Reporting a symbolic reference such as HEAD as though it were any other normal reference like refs/heads/master causes subtle programming errors. We have been bitten by this error on several occasions, as have some downstream applications written by myself. Instead of reporting HEAD as a reference whose name differs from its "original name", report it as an actual SymbolicRef object that the application can test the type and examine the target of. With this change, Ref is now an abstract type with different subclasses for the different types. In the classical example of "HEAD" being a symbolic reference to branch "refs/heads/master", the Repository.getAllRefs() method will now return: Map<String, Ref> all = repository.getAllRefs(); SymbolicRef HEAD = (SymbolicRef) all.get("HEAD"); ObjectIdRef master = (ObjectIdRef) all.get("refs/heads/master"); assertSame(master, HEAD.getTarget()); assertSame(master.getObjectId(), HEAD.getObjectId()); assertEquals("HEAD", HEAD.getName()); assertEquals("refs/heads/master", master.getName()); A nice side-effect of this change is the storage type of the symbolic reference is no longer ambiguous with the storge type of the underlying reference it targets. In the above example, if master was only available in the packed-refs file, then the following is also true: assertSame(Ref.Storage.LOOSE, HEAD.getStorage()); assertSame(Ref.Storage.PACKED, master.getStorage()); (Prior to this change we returned the ambiguous storage of LOOSE_PACKED for HEAD, which was confusing since it wasn't actually true on disk). Another nice side-effect of this change is all intermediate symbolic references are preserved, and are therefore visible to the application when they walk the target chain. We can now correctly inspect chains of symbolic references. As a result of this change the Ref.getOrigName() method has been removed from the API. Applications should identify a symbolic reference by testing for isSymbolic() and not by using an arcane string comparsion between properties. Abstract the RefDatabase storage: --------------------------------- RefDatabase is now abstract, similar to ObjectDatabase, and a new concrete implementation called RefDirectory is used for the traditional on-disk storage layout. In the future we plan to support additional implementations, such as a pure in-memory RefDatabase for unit testing purposes. Optimize RefDirectory: ---------------------- The implementation of the in-memory reference cache, reading, and update routines has been completely rewritten. Much of the code was heavily borrowed or cribbed from the prior implementation, so copyright notices have been left intact as much as possible. The RefDirectory cache no longer confuses symbolic references with normal references. This permits the cache to resolve the value of a symbolic reference as late as possible, ensuring it is always current, without needing to maintain reverse pointers. The cache is now 2 sorted RefLists, rather than 3 HashMaps. Using sorted lists allows the implementation to reduce the in-memory footprint when storing many refs. Using specialized types for the elements allows the code to avoid additional map lookups for auxiliary stat information. To improve scan time during getRefs(), the lists are returned via a copy-on-write contract. Most callers of getRefs() do not modify the returned collections, so the copy-on-write semantics improves access on repositories with a large number of packed references. Iterator traversals of the returned Map<String,Ref> are performed using a simple merge-join of the two cache lists, ensuring we can perform the entire traversal in linear time as a function of the number of references: O(PackedRefs + LooseRefs). Scans of the loose reference space to update the cache run in O(LooseRefs log LooseRefs) time, as the directory contents are sorted before being merged against the in-memory cache. Since the majority of stable references are kept packed, there typically are only a handful of reference names to be sorted, so the sorting cost should not be very high. Locking is reduced during getRefs() by taking advantage of the copy-on-write semantics of the improved cache data structure. This permits concurrent readers to pull back references without blocking each other. If there is contention updating the cache during a scan, one or more updates are simply skipped and will get picked up again in a future scan. Writing to the $GIT_DIR/packed-refs during reference delete is now fully atomic. The file is locked, reparsed fresh, and written back out if a change is necessary. This avoids all race conditions with concurrent external updates of the packed-refs file. The RefLogWriter class has been fully folded into RefDirectory and is therefore deleted. Maintaining the reference's log is the responsiblity of the database implementation, and not all implementations will use java.io for access. Future work still remains to be done to abstract the ReflogReader class away from local disk IO. Change-Id: I26b9287c45a4b2d2be35ba2849daa316f5eec85d Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
14 yıl önce
Rewrite reference handling to be abstract and accurate This commit actually does three major changes to the way references are handled within JGit. Unfortunately they were easier to do as a single massive commit than to break them up into smaller units. Disambiguate symbolic references: --------------------------------- Reporting a symbolic reference such as HEAD as though it were any other normal reference like refs/heads/master causes subtle programming errors. We have been bitten by this error on several occasions, as have some downstream applications written by myself. Instead of reporting HEAD as a reference whose name differs from its "original name", report it as an actual SymbolicRef object that the application can test the type and examine the target of. With this change, Ref is now an abstract type with different subclasses for the different types. In the classical example of "HEAD" being a symbolic reference to branch "refs/heads/master", the Repository.getAllRefs() method will now return: Map<String, Ref> all = repository.getAllRefs(); SymbolicRef HEAD = (SymbolicRef) all.get("HEAD"); ObjectIdRef master = (ObjectIdRef) all.get("refs/heads/master"); assertSame(master, HEAD.getTarget()); assertSame(master.getObjectId(), HEAD.getObjectId()); assertEquals("HEAD", HEAD.getName()); assertEquals("refs/heads/master", master.getName()); A nice side-effect of this change is the storage type of the symbolic reference is no longer ambiguous with the storge type of the underlying reference it targets. In the above example, if master was only available in the packed-refs file, then the following is also true: assertSame(Ref.Storage.LOOSE, HEAD.getStorage()); assertSame(Ref.Storage.PACKED, master.getStorage()); (Prior to this change we returned the ambiguous storage of LOOSE_PACKED for HEAD, which was confusing since it wasn't actually true on disk). Another nice side-effect of this change is all intermediate symbolic references are preserved, and are therefore visible to the application when they walk the target chain. We can now correctly inspect chains of symbolic references. As a result of this change the Ref.getOrigName() method has been removed from the API. Applications should identify a symbolic reference by testing for isSymbolic() and not by using an arcane string comparsion between properties. Abstract the RefDatabase storage: --------------------------------- RefDatabase is now abstract, similar to ObjectDatabase, and a new concrete implementation called RefDirectory is used for the traditional on-disk storage layout. In the future we plan to support additional implementations, such as a pure in-memory RefDatabase for unit testing purposes. Optimize RefDirectory: ---------------------- The implementation of the in-memory reference cache, reading, and update routines has been completely rewritten. Much of the code was heavily borrowed or cribbed from the prior implementation, so copyright notices have been left intact as much as possible. The RefDirectory cache no longer confuses symbolic references with normal references. This permits the cache to resolve the value of a symbolic reference as late as possible, ensuring it is always current, without needing to maintain reverse pointers. The cache is now 2 sorted RefLists, rather than 3 HashMaps. Using sorted lists allows the implementation to reduce the in-memory footprint when storing many refs. Using specialized types for the elements allows the code to avoid additional map lookups for auxiliary stat information. To improve scan time during getRefs(), the lists are returned via a copy-on-write contract. Most callers of getRefs() do not modify the returned collections, so the copy-on-write semantics improves access on repositories with a large number of packed references. Iterator traversals of the returned Map<String,Ref> are performed using a simple merge-join of the two cache lists, ensuring we can perform the entire traversal in linear time as a function of the number of references: O(PackedRefs + LooseRefs). Scans of the loose reference space to update the cache run in O(LooseRefs log LooseRefs) time, as the directory contents are sorted before being merged against the in-memory cache. Since the majority of stable references are kept packed, there typically are only a handful of reference names to be sorted, so the sorting cost should not be very high. Locking is reduced during getRefs() by taking advantage of the copy-on-write semantics of the improved cache data structure. This permits concurrent readers to pull back references without blocking each other. If there is contention updating the cache during a scan, one or more updates are simply skipped and will get picked up again in a future scan. Writing to the $GIT_DIR/packed-refs during reference delete is now fully atomic. The file is locked, reparsed fresh, and written back out if a change is necessary. This avoids all race conditions with concurrent external updates of the packed-refs file. The RefLogWriter class has been fully folded into RefDirectory and is therefore deleted. Maintaining the reference's log is the responsiblity of the database implementation, and not all implementations will use java.io for access. Future work still remains to be done to abstract the ReflogReader class away from local disk IO. Change-Id: I26b9287c45a4b2d2be35ba2849daa316f5eec85d Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
14 yıl önce
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683
  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.dircache.DirCache;
  65. import org.eclipse.jgit.errors.AmbiguousObjectException;
  66. import org.eclipse.jgit.errors.CorruptObjectException;
  67. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  68. import org.eclipse.jgit.errors.MissingObjectException;
  69. import org.eclipse.jgit.errors.NoWorkTreeException;
  70. import org.eclipse.jgit.errors.RevisionSyntaxException;
  71. import org.eclipse.jgit.events.IndexChangedEvent;
  72. import org.eclipse.jgit.events.IndexChangedListener;
  73. import org.eclipse.jgit.events.ListenerList;
  74. import org.eclipse.jgit.events.RepositoryEvent;
  75. import org.eclipse.jgit.internal.JGitText;
  76. import org.eclipse.jgit.revwalk.RevBlob;
  77. import org.eclipse.jgit.revwalk.RevCommit;
  78. import org.eclipse.jgit.revwalk.RevObject;
  79. import org.eclipse.jgit.revwalk.RevTree;
  80. import org.eclipse.jgit.revwalk.RevWalk;
  81. import org.eclipse.jgit.transport.RefSpec;
  82. import org.eclipse.jgit.transport.RemoteConfig;
  83. import org.eclipse.jgit.treewalk.TreeWalk;
  84. import org.eclipse.jgit.util.FS;
  85. import org.eclipse.jgit.util.FileUtils;
  86. import org.eclipse.jgit.util.IO;
  87. import org.eclipse.jgit.util.RawParseUtils;
  88. import org.eclipse.jgit.util.SystemReader;
  89. import org.eclipse.jgit.util.io.SafeBufferedOutputStream;
  90. /**
  91. * Represents a Git repository.
  92. * <p>
  93. * A repository holds all objects and refs used for managing source code (could
  94. * be any type of file, but source code is what SCM's are typically used for).
  95. * <p>
  96. * This class is thread-safe.
  97. */
  98. public abstract class Repository implements AutoCloseable {
  99. private static final ListenerList globalListeners = new ListenerList();
  100. /** @return the global listener list observing all events in this JVM. */
  101. public static ListenerList getGlobalListenerList() {
  102. return globalListeners;
  103. }
  104. private final AtomicInteger useCnt = new AtomicInteger(1);
  105. /** Metadata directory holding the repository's critical files. */
  106. private final File gitDir;
  107. /** File abstraction used to resolve paths. */
  108. private final FS fs;
  109. private final ListenerList myListeners = new ListenerList();
  110. /** If not bare, the top level directory of the working files. */
  111. private final File workTree;
  112. /** If not bare, the index file caching the working file states. */
  113. private final File indexFile;
  114. /**
  115. * Initialize a new repository instance.
  116. *
  117. * @param options
  118. * options to configure the repository.
  119. */
  120. protected Repository(final BaseRepositoryBuilder options) {
  121. gitDir = options.getGitDir();
  122. fs = options.getFS();
  123. workTree = options.getWorkTree();
  124. indexFile = options.getIndexFile();
  125. }
  126. /** @return listeners observing only events on this repository. */
  127. public ListenerList getListenerList() {
  128. return myListeners;
  129. }
  130. /**
  131. * Fire an event to all registered listeners.
  132. * <p>
  133. * The source repository of the event is automatically set to this
  134. * repository, before the event is delivered to any listeners.
  135. *
  136. * @param event
  137. * the event to deliver.
  138. */
  139. public void fireEvent(RepositoryEvent<?> event) {
  140. event.setRepository(this);
  141. myListeners.dispatch(event);
  142. globalListeners.dispatch(event);
  143. }
  144. /**
  145. * Create a new Git repository.
  146. * <p>
  147. * Repository with working tree is created using this method. This method is
  148. * the same as {@code create(false)}.
  149. *
  150. * @throws IOException
  151. * @see #create(boolean)
  152. */
  153. public void create() throws IOException {
  154. create(false);
  155. }
  156. /**
  157. * Create a new Git repository initializing the necessary files and
  158. * directories.
  159. *
  160. * @param bare
  161. * if true, a bare repository (a repository without a working
  162. * directory) is created.
  163. * @throws IOException
  164. * in case of IO problem
  165. */
  166. public abstract void create(boolean bare) throws IOException;
  167. /** @return local metadata directory; null if repository isn't local. */
  168. public File getDirectory() {
  169. return gitDir;
  170. }
  171. /**
  172. * @return the object database which stores this repository's data.
  173. */
  174. public abstract ObjectDatabase getObjectDatabase();
  175. /** @return a new inserter to create objects in {@link #getObjectDatabase()} */
  176. public ObjectInserter newObjectInserter() {
  177. return getObjectDatabase().newInserter();
  178. }
  179. /** @return a new reader to read objects from {@link #getObjectDatabase()} */
  180. public ObjectReader newObjectReader() {
  181. return getObjectDatabase().newReader();
  182. }
  183. /** @return the reference database which stores the reference namespace. */
  184. public abstract RefDatabase getRefDatabase();
  185. /**
  186. * @return the configuration of this repository
  187. */
  188. public abstract StoredConfig getConfig();
  189. /**
  190. * @return the used file system abstraction
  191. */
  192. public FS getFS() {
  193. return fs;
  194. }
  195. /**
  196. * @param objectId
  197. * @return true if the specified object is stored in this repo or any of the
  198. * known shared repositories.
  199. */
  200. public boolean hasObject(AnyObjectId objectId) {
  201. try {
  202. return getObjectDatabase().has(objectId);
  203. } catch (IOException e) {
  204. // Legacy API, assume error means "no"
  205. return false;
  206. }
  207. }
  208. /**
  209. * Open an object from this repository.
  210. * <p>
  211. * This is a one-shot call interface which may be faster than allocating a
  212. * {@link #newObjectReader()} to perform the lookup.
  213. *
  214. * @param objectId
  215. * identity of the object to open.
  216. * @return a {@link ObjectLoader} for accessing the object.
  217. * @throws MissingObjectException
  218. * the object does not exist.
  219. * @throws IOException
  220. * the object store cannot be accessed.
  221. */
  222. public ObjectLoader open(final AnyObjectId objectId)
  223. throws MissingObjectException, IOException {
  224. return getObjectDatabase().open(objectId);
  225. }
  226. /**
  227. * Open an object from this repository.
  228. * <p>
  229. * This is a one-shot call interface which may be faster than allocating a
  230. * {@link #newObjectReader()} to perform the lookup.
  231. *
  232. * @param objectId
  233. * identity of the object to open.
  234. * @param typeHint
  235. * hint about the type of object being requested, e.g.
  236. * {@link Constants#OBJ_BLOB}; {@link ObjectReader#OBJ_ANY} if
  237. * the object type is not known, or does not matter to the
  238. * caller.
  239. * @return a {@link ObjectLoader} for accessing the object.
  240. * @throws MissingObjectException
  241. * the object does not exist.
  242. * @throws IncorrectObjectTypeException
  243. * typeHint was not OBJ_ANY, and the object's actual type does
  244. * not match typeHint.
  245. * @throws IOException
  246. * the object store cannot be accessed.
  247. */
  248. public ObjectLoader open(AnyObjectId objectId, int typeHint)
  249. throws MissingObjectException, IncorrectObjectTypeException,
  250. IOException {
  251. return getObjectDatabase().open(objectId, typeHint);
  252. }
  253. /**
  254. * Create a command to update, create or delete a ref in this repository.
  255. *
  256. * @param ref
  257. * name of the ref the caller wants to modify.
  258. * @return an update command. The caller must finish populating this command
  259. * and then invoke one of the update methods to actually make a
  260. * change.
  261. * @throws IOException
  262. * a symbolic ref was passed in and could not be resolved back
  263. * to the base ref, as the symbolic ref could not be read.
  264. */
  265. public RefUpdate updateRef(final String ref) throws IOException {
  266. return updateRef(ref, false);
  267. }
  268. /**
  269. * Create a command to update, create or delete a ref in this repository.
  270. *
  271. * @param ref
  272. * name of the ref the caller wants to modify.
  273. * @param detach
  274. * true to create a detached head
  275. * @return an update command. The caller must finish populating this command
  276. * and then invoke one of the update methods to actually make a
  277. * change.
  278. * @throws IOException
  279. * a symbolic ref was passed in and could not be resolved back
  280. * to the base ref, as the symbolic ref could not be read.
  281. */
  282. public RefUpdate updateRef(final String ref, final boolean detach) throws IOException {
  283. return getRefDatabase().newUpdate(ref, detach);
  284. }
  285. /**
  286. * Create a command to rename a ref in this repository
  287. *
  288. * @param fromRef
  289. * name of ref to rename from
  290. * @param toRef
  291. * name of ref to rename to
  292. * @return an update command that knows how to rename a branch to another.
  293. * @throws IOException
  294. * the rename could not be performed.
  295. *
  296. */
  297. public RefRename renameRef(final String fromRef, final String toRef) throws IOException {
  298. return getRefDatabase().newRename(fromRef, toRef);
  299. }
  300. /**
  301. * Parse a git revision string and return an object id.
  302. *
  303. * Combinations of these operators are supported:
  304. * <ul>
  305. * <li><b>HEAD</b>, <b>MERGE_HEAD</b>, <b>FETCH_HEAD</b></li>
  306. * <li><b>SHA-1</b>: a complete or abbreviated SHA-1</li>
  307. * <li><b>refs/...</b>: a complete reference name</li>
  308. * <li><b>short-name</b>: a short reference name under {@code refs/heads},
  309. * {@code refs/tags}, or {@code refs/remotes} namespace</li>
  310. * <li><b>tag-NN-gABBREV</b>: output from describe, parsed by treating
  311. * {@code ABBREV} as an abbreviated SHA-1.</li>
  312. * <li><i>id</i><b>^</b>: first parent of commit <i>id</i>, this is the same
  313. * as {@code id^1}</li>
  314. * <li><i>id</i><b>^0</b>: ensure <i>id</i> is a commit</li>
  315. * <li><i>id</i><b>^n</b>: n-th parent of commit <i>id</i></li>
  316. * <li><i>id</i><b>~n</b>: n-th historical ancestor of <i>id</i>, by first
  317. * parent. {@code id~3} is equivalent to {@code id^1^1^1} or {@code id^^^}.</li>
  318. * <li><i>id</i><b>:path</b>: Lookup path under tree named by <i>id</i></li>
  319. * <li><i>id</i><b>^{commit}</b>: ensure <i>id</i> is a commit</li>
  320. * <li><i>id</i><b>^{tree}</b>: ensure <i>id</i> is a tree</li>
  321. * <li><i>id</i><b>^{tag}</b>: ensure <i>id</i> is a tag</li>
  322. * <li><i>id</i><b>^{blob}</b>: ensure <i>id</i> is a blob</li>
  323. * </ul>
  324. *
  325. * <p>
  326. * The following operators are specified by Git conventions, but are not
  327. * supported by this method:
  328. * <ul>
  329. * <li><b>ref@{n}</b>: n-th version of ref as given by its reflog</li>
  330. * <li><b>ref@{time}</b>: value of ref at the designated time</li>
  331. * </ul>
  332. *
  333. * @param revstr
  334. * A git object references expression
  335. * @return an ObjectId or null if revstr can't be resolved to any ObjectId
  336. * @throws AmbiguousObjectException
  337. * {@code revstr} contains an abbreviated ObjectId and this
  338. * repository contains more than one object which match to the
  339. * input abbreviation.
  340. * @throws IncorrectObjectTypeException
  341. * the id parsed does not meet the type required to finish
  342. * applying the operators in the expression.
  343. * @throws RevisionSyntaxException
  344. * the expression is not supported by this implementation, or
  345. * does not meet the standard syntax.
  346. * @throws IOException
  347. * on serious errors
  348. */
  349. public ObjectId resolve(final String revstr)
  350. throws AmbiguousObjectException, IncorrectObjectTypeException,
  351. RevisionSyntaxException, IOException {
  352. try (RevWalk rw = new RevWalk(this)) {
  353. Object resolved = resolve(rw, revstr);
  354. if (resolved instanceof String) {
  355. final Ref ref = getRef((String)resolved);
  356. return ref != null ? ref.getLeaf().getObjectId() : null;
  357. } else {
  358. return (ObjectId) resolved;
  359. }
  360. }
  361. }
  362. /**
  363. * Simplify an expression, but unlike {@link #resolve(String)} it will not
  364. * resolve a branch passed or resulting from the expression, such as @{-}.
  365. * Thus this method can be used to process an expression to a method that
  366. * expects a branch or revision id.
  367. *
  368. * @param revstr
  369. * @return object id or ref name from resolved expression
  370. * @throws AmbiguousObjectException
  371. * @throws IOException
  372. */
  373. public String simplify(final String revstr)
  374. throws AmbiguousObjectException, IOException {
  375. try (RevWalk rw = new RevWalk(this)) {
  376. Object resolved = resolve(rw, revstr);
  377. if (resolved != null)
  378. if (resolved instanceof String)
  379. return (String) resolved;
  380. else
  381. return ((AnyObjectId) resolved).getName();
  382. return null;
  383. }
  384. }
  385. private Object resolve(final RevWalk rw, final String revstr)
  386. throws IOException {
  387. char[] revChars = revstr.toCharArray();
  388. RevObject rev = null;
  389. String name = null;
  390. int done = 0;
  391. for (int i = 0; i < revChars.length; ++i) {
  392. switch (revChars[i]) {
  393. case '^':
  394. if (rev == null) {
  395. if (name == null)
  396. if (done == 0)
  397. name = new String(revChars, done, i);
  398. else {
  399. done = i + 1;
  400. break;
  401. }
  402. rev = parseSimple(rw, name);
  403. name = null;
  404. if (rev == null)
  405. return null;
  406. }
  407. if (i + 1 < revChars.length) {
  408. switch (revChars[i + 1]) {
  409. case '0':
  410. case '1':
  411. case '2':
  412. case '3':
  413. case '4':
  414. case '5':
  415. case '6':
  416. case '7':
  417. case '8':
  418. case '9':
  419. int j;
  420. rev = rw.parseCommit(rev);
  421. for (j = i + 1; j < revChars.length; ++j) {
  422. if (!Character.isDigit(revChars[j]))
  423. break;
  424. }
  425. String parentnum = new String(revChars, i + 1, j - i
  426. - 1);
  427. int pnum;
  428. try {
  429. pnum = Integer.parseInt(parentnum);
  430. } catch (NumberFormatException e) {
  431. throw new RevisionSyntaxException(
  432. JGitText.get().invalidCommitParentNumber,
  433. revstr);
  434. }
  435. if (pnum != 0) {
  436. RevCommit commit = (RevCommit) rev;
  437. if (pnum > commit.getParentCount())
  438. rev = null;
  439. else
  440. rev = commit.getParent(pnum - 1);
  441. }
  442. i = j - 1;
  443. done = j;
  444. break;
  445. case '{':
  446. int k;
  447. String item = null;
  448. for (k = i + 2; k < revChars.length; ++k) {
  449. if (revChars[k] == '}') {
  450. item = new String(revChars, i + 2, k - i - 2);
  451. break;
  452. }
  453. }
  454. i = k;
  455. if (item != null)
  456. if (item.equals("tree")) { //$NON-NLS-1$
  457. rev = rw.parseTree(rev);
  458. } else if (item.equals("commit")) { //$NON-NLS-1$
  459. rev = rw.parseCommit(rev);
  460. } else if (item.equals("blob")) { //$NON-NLS-1$
  461. rev = rw.peel(rev);
  462. if (!(rev instanceof RevBlob))
  463. throw new IncorrectObjectTypeException(rev,
  464. Constants.TYPE_BLOB);
  465. } else if (item.equals("")) { //$NON-NLS-1$
  466. rev = rw.peel(rev);
  467. } else
  468. throw new RevisionSyntaxException(revstr);
  469. else
  470. throw new RevisionSyntaxException(revstr);
  471. done = k;
  472. break;
  473. default:
  474. rev = rw.peel(rev);
  475. if (rev instanceof RevCommit) {
  476. RevCommit commit = ((RevCommit) rev);
  477. if (commit.getParentCount() == 0)
  478. rev = null;
  479. else
  480. rev = commit.getParent(0);
  481. } else
  482. throw new IncorrectObjectTypeException(rev,
  483. Constants.TYPE_COMMIT);
  484. }
  485. } else {
  486. rev = rw.peel(rev);
  487. if (rev instanceof RevCommit) {
  488. RevCommit commit = ((RevCommit) rev);
  489. if (commit.getParentCount() == 0)
  490. rev = null;
  491. else
  492. rev = commit.getParent(0);
  493. } else
  494. throw new IncorrectObjectTypeException(rev,
  495. Constants.TYPE_COMMIT);
  496. }
  497. done = i + 1;
  498. break;
  499. case '~':
  500. if (rev == null) {
  501. if (name == null)
  502. if (done == 0)
  503. name = new String(revChars, done, i);
  504. else {
  505. done = i + 1;
  506. break;
  507. }
  508. rev = parseSimple(rw, name);
  509. name = null;
  510. if (rev == null)
  511. return null;
  512. }
  513. rev = rw.peel(rev);
  514. if (!(rev instanceof RevCommit))
  515. throw new IncorrectObjectTypeException(rev,
  516. Constants.TYPE_COMMIT);
  517. int l;
  518. for (l = i + 1; l < revChars.length; ++l) {
  519. if (!Character.isDigit(revChars[l]))
  520. break;
  521. }
  522. int dist;
  523. if (l - i > 1) {
  524. String distnum = new String(revChars, i + 1, l - i - 1);
  525. try {
  526. dist = Integer.parseInt(distnum);
  527. } catch (NumberFormatException e) {
  528. throw new RevisionSyntaxException(
  529. JGitText.get().invalidAncestryLength, revstr);
  530. }
  531. } else
  532. dist = 1;
  533. while (dist > 0) {
  534. RevCommit commit = (RevCommit) rev;
  535. if (commit.getParentCount() == 0) {
  536. rev = null;
  537. break;
  538. }
  539. commit = commit.getParent(0);
  540. rw.parseHeaders(commit);
  541. rev = commit;
  542. --dist;
  543. }
  544. i = l - 1;
  545. done = l;
  546. break;
  547. case '@':
  548. if (rev != null)
  549. throw new RevisionSyntaxException(revstr);
  550. if (i + 1 < revChars.length && revChars[i + 1] != '{')
  551. continue;
  552. int m;
  553. String time = null;
  554. for (m = i + 2; m < revChars.length; ++m) {
  555. if (revChars[m] == '}') {
  556. time = new String(revChars, i + 2, m - i - 2);
  557. break;
  558. }
  559. }
  560. if (time != null) {
  561. if (time.equals("upstream")) { //$NON-NLS-1$
  562. if (name == null)
  563. name = new String(revChars, done, i);
  564. if (name.equals("")) //$NON-NLS-1$
  565. // Currently checked out branch, HEAD if
  566. // detached
  567. name = Constants.HEAD;
  568. if (!Repository.isValidRefName("x/" + name)) //$NON-NLS-1$
  569. throw new RevisionSyntaxException(revstr);
  570. Ref ref = getRef(name);
  571. name = null;
  572. if (ref == null)
  573. return null;
  574. if (ref.isSymbolic())
  575. ref = ref.getLeaf();
  576. name = ref.getName();
  577. RemoteConfig remoteConfig;
  578. try {
  579. remoteConfig = new RemoteConfig(getConfig(),
  580. "origin"); //$NON-NLS-1$
  581. } catch (URISyntaxException e) {
  582. throw new RevisionSyntaxException(revstr);
  583. }
  584. String remoteBranchName = getConfig()
  585. .getString(
  586. ConfigConstants.CONFIG_BRANCH_SECTION,
  587. Repository.shortenRefName(ref.getName()),
  588. ConfigConstants.CONFIG_KEY_MERGE);
  589. List<RefSpec> fetchRefSpecs = remoteConfig
  590. .getFetchRefSpecs();
  591. for (RefSpec refSpec : fetchRefSpecs) {
  592. if (refSpec.matchSource(remoteBranchName)) {
  593. RefSpec expandFromSource = refSpec
  594. .expandFromSource(remoteBranchName);
  595. name = expandFromSource.getDestination();
  596. break;
  597. }
  598. }
  599. if (name == null)
  600. throw new RevisionSyntaxException(revstr);
  601. } else if (time.matches("^-\\d+$")) { //$NON-NLS-1$
  602. if (name != null)
  603. throw new RevisionSyntaxException(revstr);
  604. else {
  605. String previousCheckout = resolveReflogCheckout(-Integer
  606. .parseInt(time));
  607. if (ObjectId.isId(previousCheckout))
  608. rev = parseSimple(rw, previousCheckout);
  609. else
  610. name = previousCheckout;
  611. }
  612. } else {
  613. if (name == null)
  614. name = new String(revChars, done, i);
  615. if (name.equals("")) //$NON-NLS-1$
  616. name = Constants.HEAD;
  617. if (!Repository.isValidRefName("x/" + name)) //$NON-NLS-1$
  618. throw new RevisionSyntaxException(revstr);
  619. Ref ref = getRef(name);
  620. name = null;
  621. if (ref == null)
  622. return null;
  623. // @{n} means current branch, not HEAD@{1} unless
  624. // detached
  625. if (ref.isSymbolic())
  626. ref = ref.getLeaf();
  627. rev = resolveReflog(rw, ref, time);
  628. }
  629. i = m;
  630. } else
  631. throw new RevisionSyntaxException(revstr);
  632. break;
  633. case ':': {
  634. RevTree tree;
  635. if (rev == null) {
  636. if (name == null)
  637. name = new String(revChars, done, i);
  638. if (name.equals("")) //$NON-NLS-1$
  639. name = Constants.HEAD;
  640. rev = parseSimple(rw, name);
  641. name = null;
  642. }
  643. if (rev == null)
  644. return null;
  645. tree = rw.parseTree(rev);
  646. if (i == revChars.length - 1)
  647. return tree.copy();
  648. TreeWalk tw = TreeWalk.forPath(rw.getObjectReader(),
  649. new String(revChars, i + 1, revChars.length - i - 1),
  650. tree);
  651. return tw != null ? tw.getObjectId(0) : null;
  652. }
  653. default:
  654. if (rev != null)
  655. throw new RevisionSyntaxException(revstr);
  656. }
  657. }
  658. if (rev != null)
  659. return rev.copy();
  660. if (name != null)
  661. return name;
  662. if (done == revstr.length())
  663. return null;
  664. name = revstr.substring(done);
  665. if (!Repository.isValidRefName("x/" + name)) //$NON-NLS-1$
  666. throw new RevisionSyntaxException(revstr);
  667. if (getRef(name) != null)
  668. return name;
  669. return resolveSimple(name);
  670. }
  671. private static boolean isHex(char c) {
  672. return ('0' <= c && c <= '9') //
  673. || ('a' <= c && c <= 'f') //
  674. || ('A' <= c && c <= 'F');
  675. }
  676. private static boolean isAllHex(String str, int ptr) {
  677. while (ptr < str.length()) {
  678. if (!isHex(str.charAt(ptr++)))
  679. return false;
  680. }
  681. return true;
  682. }
  683. private RevObject parseSimple(RevWalk rw, String revstr) throws IOException {
  684. ObjectId id = resolveSimple(revstr);
  685. return id != null ? rw.parseAny(id) : null;
  686. }
  687. private ObjectId resolveSimple(final String revstr) throws IOException {
  688. if (ObjectId.isId(revstr))
  689. return ObjectId.fromString(revstr);
  690. if (Repository.isValidRefName("x/" + revstr)) { //$NON-NLS-1$
  691. Ref r = getRefDatabase().getRef(revstr);
  692. if (r != null)
  693. return r.getObjectId();
  694. }
  695. if (AbbreviatedObjectId.isId(revstr))
  696. return resolveAbbreviation(revstr);
  697. int dashg = revstr.indexOf("-g"); //$NON-NLS-1$
  698. if ((dashg + 5) < revstr.length() && 0 <= dashg
  699. && isHex(revstr.charAt(dashg + 2))
  700. && isHex(revstr.charAt(dashg + 3))
  701. && isAllHex(revstr, dashg + 4)) {
  702. // Possibly output from git describe?
  703. String s = revstr.substring(dashg + 2);
  704. if (AbbreviatedObjectId.isId(s))
  705. return resolveAbbreviation(s);
  706. }
  707. return null;
  708. }
  709. private String resolveReflogCheckout(int checkoutNo)
  710. throws IOException {
  711. List<ReflogEntry> reflogEntries = getReflogReader(Constants.HEAD)
  712. .getReverseEntries();
  713. for (ReflogEntry entry : reflogEntries) {
  714. CheckoutEntry checkout = entry.parseCheckout();
  715. if (checkout != null)
  716. if (checkoutNo-- == 1)
  717. return checkout.getFromBranch();
  718. }
  719. return null;
  720. }
  721. private RevCommit resolveReflog(RevWalk rw, Ref ref, String time)
  722. throws IOException {
  723. int number;
  724. try {
  725. number = Integer.parseInt(time);
  726. } catch (NumberFormatException nfe) {
  727. throw new RevisionSyntaxException(MessageFormat.format(
  728. JGitText.get().invalidReflogRevision, time));
  729. }
  730. assert number >= 0;
  731. ReflogReader reader = getReflogReader(ref.getName());
  732. ReflogEntry entry = reader.getReverseEntry(number);
  733. if (entry == null)
  734. throw new RevisionSyntaxException(MessageFormat.format(
  735. JGitText.get().reflogEntryNotFound,
  736. Integer.valueOf(number), ref.getName()));
  737. return rw.parseCommit(entry.getNewId());
  738. }
  739. private ObjectId resolveAbbreviation(final String revstr) throws IOException,
  740. AmbiguousObjectException {
  741. AbbreviatedObjectId id = AbbreviatedObjectId.fromString(revstr);
  742. try (ObjectReader reader = newObjectReader()) {
  743. Collection<ObjectId> matches = reader.resolve(id);
  744. if (matches.size() == 0)
  745. return null;
  746. else if (matches.size() == 1)
  747. return matches.iterator().next();
  748. else
  749. throw new AmbiguousObjectException(id, matches);
  750. }
  751. }
  752. /** Increment the use counter by one, requiring a matched {@link #close()}. */
  753. public void incrementOpen() {
  754. useCnt.incrementAndGet();
  755. }
  756. /** Decrement the use count, and maybe close resources. */
  757. public void close() {
  758. if (useCnt.decrementAndGet() == 0) {
  759. doClose();
  760. }
  761. }
  762. /**
  763. * Invoked when the use count drops to zero during {@link #close()}.
  764. * <p>
  765. * The default implementation closes the object and ref databases.
  766. */
  767. protected void doClose() {
  768. getObjectDatabase().close();
  769. getRefDatabase().close();
  770. }
  771. @SuppressWarnings("nls")
  772. public String toString() {
  773. String desc;
  774. if (getDirectory() != null)
  775. desc = getDirectory().getPath();
  776. else
  777. desc = getClass().getSimpleName() + "-" //$NON-NLS-1$
  778. + System.identityHashCode(this);
  779. return "Repository[" + desc + "]"; //$NON-NLS-1$
  780. }
  781. /**
  782. * Get the name of the reference that {@code HEAD} points to.
  783. * <p>
  784. * This is essentially the same as doing:
  785. *
  786. * <pre>
  787. * return getRef(Constants.HEAD).getTarget().getName()
  788. * </pre>
  789. *
  790. * Except when HEAD is detached, in which case this method returns the
  791. * current ObjectId in hexadecimal string format.
  792. *
  793. * @return name of current branch (for example {@code refs/heads/master}) or
  794. * an ObjectId in hex format if the current branch is detached.
  795. * @throws IOException
  796. */
  797. public String getFullBranch() throws IOException {
  798. Ref head = getRef(Constants.HEAD);
  799. if (head == null)
  800. return null;
  801. if (head.isSymbolic())
  802. return head.getTarget().getName();
  803. if (head.getObjectId() != null)
  804. return head.getObjectId().name();
  805. return null;
  806. }
  807. /**
  808. * Get the short name of the current branch that {@code HEAD} points to.
  809. * <p>
  810. * This is essentially the same as {@link #getFullBranch()}, except the
  811. * leading prefix {@code refs/heads/} is removed from the reference before
  812. * it is returned to the caller.
  813. *
  814. * @return name of current branch (for example {@code master}), or an
  815. * ObjectId in hex format if the current branch is detached.
  816. * @throws IOException
  817. */
  818. public String getBranch() throws IOException {
  819. String name = getFullBranch();
  820. if (name != null)
  821. return shortenRefName(name);
  822. return name;
  823. }
  824. /**
  825. * Objects known to exist but not expressed by {@link #getAllRefs()}.
  826. * <p>
  827. * When a repository borrows objects from another repository, it can
  828. * advertise that it safely has that other repository's references, without
  829. * exposing any other details about the other repository. This may help
  830. * a client trying to push changes avoid pushing more than it needs to.
  831. *
  832. * @return unmodifiable collection of other known objects.
  833. */
  834. public Set<ObjectId> getAdditionalHaves() {
  835. return Collections.emptySet();
  836. }
  837. /**
  838. * Get a ref by name.
  839. *
  840. * @param name
  841. * the name of the ref to lookup. May be a short-hand form, e.g.
  842. * "master" which is is automatically expanded to
  843. * "refs/heads/master" if "refs/heads/master" already exists.
  844. * @return the Ref with the given name, or null if it does not exist
  845. * @throws IOException
  846. */
  847. public Ref getRef(final String name) throws IOException {
  848. return getRefDatabase().getRef(name);
  849. }
  850. /**
  851. * @return mutable map of all known refs (heads, tags, remotes).
  852. */
  853. public Map<String, Ref> getAllRefs() {
  854. try {
  855. return getRefDatabase().getRefs(RefDatabase.ALL);
  856. } catch (IOException e) {
  857. return new HashMap<String, Ref>();
  858. }
  859. }
  860. /**
  861. * @return mutable map of all tags; key is short tag name ("v1.0") and value
  862. * of the entry contains the ref with the full tag name
  863. * ("refs/tags/v1.0").
  864. */
  865. public Map<String, Ref> getTags() {
  866. try {
  867. return getRefDatabase().getRefs(Constants.R_TAGS);
  868. } catch (IOException e) {
  869. return new HashMap<String, Ref>();
  870. }
  871. }
  872. /**
  873. * Peel a possibly unpeeled reference to an annotated tag.
  874. * <p>
  875. * If the ref cannot be peeled (as it does not refer to an annotated tag)
  876. * the peeled id stays null, but {@link Ref#isPeeled()} will be true.
  877. *
  878. * @param ref
  879. * The ref to peel
  880. * @return <code>ref</code> if <code>ref.isPeeled()</code> is true; else a
  881. * new Ref object representing the same data as Ref, but isPeeled()
  882. * will be true and getPeeledObjectId will contain the peeled object
  883. * (or null).
  884. */
  885. public Ref peel(final Ref ref) {
  886. try {
  887. return getRefDatabase().peel(ref);
  888. } catch (IOException e) {
  889. // Historical accident; if the reference cannot be peeled due
  890. // to some sort of repository access problem we claim that the
  891. // same as if the reference was not an annotated tag.
  892. return ref;
  893. }
  894. }
  895. /**
  896. * @return a map with all objects referenced by a peeled ref.
  897. */
  898. public Map<AnyObjectId, Set<Ref>> getAllRefsByPeeledObjectId() {
  899. Map<String, Ref> allRefs = getAllRefs();
  900. Map<AnyObjectId, Set<Ref>> ret = new HashMap<AnyObjectId, Set<Ref>>(allRefs.size());
  901. for (Ref ref : allRefs.values()) {
  902. ref = peel(ref);
  903. AnyObjectId target = ref.getPeeledObjectId();
  904. if (target == null)
  905. target = ref.getObjectId();
  906. // We assume most Sets here are singletons
  907. Set<Ref> oset = ret.put(target, Collections.singleton(ref));
  908. if (oset != null) {
  909. // that was not the case (rare)
  910. if (oset.size() == 1) {
  911. // Was a read-only singleton, we must copy to a new Set
  912. oset = new HashSet<Ref>(oset);
  913. }
  914. ret.put(target, oset);
  915. oset.add(ref);
  916. }
  917. }
  918. return ret;
  919. }
  920. /**
  921. * @return the index file location
  922. * @throws NoWorkTreeException
  923. * if this is bare, which implies it has no working directory.
  924. * See {@link #isBare()}.
  925. */
  926. public File getIndexFile() throws NoWorkTreeException {
  927. if (isBare())
  928. throw new NoWorkTreeException();
  929. return indexFile;
  930. }
  931. /**
  932. * Create a new in-core index representation and read an index from disk.
  933. * <p>
  934. * The new index will be read before it is returned to the caller. Read
  935. * failures are reported as exceptions and therefore prevent the method from
  936. * returning a partially populated index.
  937. *
  938. * @return a cache representing the contents of the specified index file (if
  939. * it exists) or an empty cache if the file does not exist.
  940. * @throws NoWorkTreeException
  941. * if this is bare, which implies it has no working directory.
  942. * See {@link #isBare()}.
  943. * @throws IOException
  944. * the index file is present but could not be read.
  945. * @throws CorruptObjectException
  946. * the index file is using a format or extension that this
  947. * library does not support.
  948. */
  949. public DirCache readDirCache() throws NoWorkTreeException,
  950. CorruptObjectException, IOException {
  951. return DirCache.read(this);
  952. }
  953. /**
  954. * Create a new in-core index representation, lock it, and read from disk.
  955. * <p>
  956. * The new index will be locked and then read before it is returned to the
  957. * caller. Read failures are reported as exceptions and therefore prevent
  958. * the method from returning a partially populated index.
  959. *
  960. * @return a cache representing the contents of the specified index file (if
  961. * it exists) or an empty cache if the file does not exist.
  962. * @throws NoWorkTreeException
  963. * if this is bare, which implies it has no working directory.
  964. * See {@link #isBare()}.
  965. * @throws IOException
  966. * the index file is present but could not be read, or the lock
  967. * could not be obtained.
  968. * @throws CorruptObjectException
  969. * the index file is using a format or extension that this
  970. * library does not support.
  971. */
  972. public DirCache lockDirCache() throws NoWorkTreeException,
  973. CorruptObjectException, IOException {
  974. // we want DirCache to inform us so that we can inform registered
  975. // listeners about index changes
  976. IndexChangedListener l = new IndexChangedListener() {
  977. public void onIndexChanged(IndexChangedEvent event) {
  978. notifyIndexChanged();
  979. }
  980. };
  981. return DirCache.lock(this, l);
  982. }
  983. static byte[] gitInternalSlash(byte[] bytes) {
  984. if (File.separatorChar == '/')
  985. return bytes;
  986. for (int i=0; i<bytes.length; ++i)
  987. if (bytes[i] == File.separatorChar)
  988. bytes[i] = '/';
  989. return bytes;
  990. }
  991. /**
  992. * @return an important state
  993. */
  994. public RepositoryState getRepositoryState() {
  995. if (isBare() || getDirectory() == null)
  996. return RepositoryState.BARE;
  997. // Pre Git-1.6 logic
  998. if (new File(getWorkTree(), ".dotest").exists()) //$NON-NLS-1$
  999. return RepositoryState.REBASING;
  1000. if (new File(getDirectory(), ".dotest-merge").exists()) //$NON-NLS-1$
  1001. return RepositoryState.REBASING_INTERACTIVE;
  1002. // From 1.6 onwards
  1003. if (new File(getDirectory(),"rebase-apply/rebasing").exists()) //$NON-NLS-1$
  1004. return RepositoryState.REBASING_REBASING;
  1005. if (new File(getDirectory(),"rebase-apply/applying").exists()) //$NON-NLS-1$
  1006. return RepositoryState.APPLY;
  1007. if (new File(getDirectory(),"rebase-apply").exists()) //$NON-NLS-1$
  1008. return RepositoryState.REBASING;
  1009. if (new File(getDirectory(),"rebase-merge/interactive").exists()) //$NON-NLS-1$
  1010. return RepositoryState.REBASING_INTERACTIVE;
  1011. if (new File(getDirectory(),"rebase-merge").exists()) //$NON-NLS-1$
  1012. return RepositoryState.REBASING_MERGE;
  1013. // Both versions
  1014. if (new File(getDirectory(), Constants.MERGE_HEAD).exists()) {
  1015. // we are merging - now check whether we have unmerged paths
  1016. try {
  1017. if (!readDirCache().hasUnmergedPaths()) {
  1018. // no unmerged paths -> return the MERGING_RESOLVED state
  1019. return RepositoryState.MERGING_RESOLVED;
  1020. }
  1021. } catch (IOException e) {
  1022. // Can't decide whether unmerged paths exists. Return
  1023. // MERGING state to be on the safe side (in state MERGING
  1024. // you are not allow to do anything)
  1025. }
  1026. return RepositoryState.MERGING;
  1027. }
  1028. if (new File(getDirectory(), "BISECT_LOG").exists()) //$NON-NLS-1$
  1029. return RepositoryState.BISECTING;
  1030. if (new File(getDirectory(), Constants.CHERRY_PICK_HEAD).exists()) {
  1031. try {
  1032. if (!readDirCache().hasUnmergedPaths()) {
  1033. // no unmerged paths
  1034. return RepositoryState.CHERRY_PICKING_RESOLVED;
  1035. }
  1036. } catch (IOException e) {
  1037. // fall through to CHERRY_PICKING
  1038. }
  1039. return RepositoryState.CHERRY_PICKING;
  1040. }
  1041. if (new File(getDirectory(), Constants.REVERT_HEAD).exists()) {
  1042. try {
  1043. if (!readDirCache().hasUnmergedPaths()) {
  1044. // no unmerged paths
  1045. return RepositoryState.REVERTING_RESOLVED;
  1046. }
  1047. } catch (IOException e) {
  1048. // fall through to REVERTING
  1049. }
  1050. return RepositoryState.REVERTING;
  1051. }
  1052. return RepositoryState.SAFE;
  1053. }
  1054. /**
  1055. * Check validity of a ref name. It must not contain character that has
  1056. * a special meaning in a Git object reference expression. Some other
  1057. * dangerous characters are also excluded.
  1058. *
  1059. * For portability reasons '\' is excluded
  1060. *
  1061. * @param refName
  1062. *
  1063. * @return true if refName is a valid ref name
  1064. */
  1065. public static boolean isValidRefName(final String refName) {
  1066. final int len = refName.length();
  1067. if (len == 0)
  1068. return false;
  1069. if (refName.endsWith(".lock")) //$NON-NLS-1$
  1070. return false;
  1071. // Refs may be stored as loose files so invalid paths
  1072. // on the local system must also be invalid refs.
  1073. try {
  1074. SystemReader.getInstance().checkPath(refName);
  1075. } catch (CorruptObjectException e) {
  1076. return false;
  1077. }
  1078. int components = 1;
  1079. char p = '\0';
  1080. for (int i = 0; i < len; i++) {
  1081. final char c = refName.charAt(i);
  1082. if (c <= ' ')
  1083. return false;
  1084. switch (c) {
  1085. case '.':
  1086. switch (p) {
  1087. case '\0': case '/': case '.':
  1088. return false;
  1089. }
  1090. if (i == len -1)
  1091. return false;
  1092. break;
  1093. case '/':
  1094. if (i == 0 || i == len - 1)
  1095. return false;
  1096. if (p == '/')
  1097. return false;
  1098. components++;
  1099. break;
  1100. case '{':
  1101. if (p == '@')
  1102. return false;
  1103. break;
  1104. case '~': case '^': case ':':
  1105. case '?': case '[': case '*':
  1106. case '\\':
  1107. case '\u007F':
  1108. return false;
  1109. }
  1110. p = c;
  1111. }
  1112. return components > 1;
  1113. }
  1114. /**
  1115. * Strip work dir and return normalized repository path.
  1116. *
  1117. * @param workDir Work dir
  1118. * @param file File whose path shall be stripped of its workdir
  1119. * @return normalized repository relative path or the empty
  1120. * string if the file is not relative to the work directory.
  1121. */
  1122. public static String stripWorkDir(File workDir, File file) {
  1123. final String filePath = file.getPath();
  1124. final String workDirPath = workDir.getPath();
  1125. if (filePath.length() <= workDirPath.length() ||
  1126. filePath.charAt(workDirPath.length()) != File.separatorChar ||
  1127. !filePath.startsWith(workDirPath)) {
  1128. File absWd = workDir.isAbsolute() ? workDir : workDir.getAbsoluteFile();
  1129. File absFile = file.isAbsolute() ? file : file.getAbsoluteFile();
  1130. if (absWd == workDir && absFile == file)
  1131. return ""; //$NON-NLS-1$
  1132. return stripWorkDir(absWd, absFile);
  1133. }
  1134. String relName = filePath.substring(workDirPath.length() + 1);
  1135. if (File.separatorChar != '/')
  1136. relName = relName.replace(File.separatorChar, '/');
  1137. return relName;
  1138. }
  1139. /**
  1140. * @return true if this is bare, which implies it has no working directory.
  1141. */
  1142. public boolean isBare() {
  1143. return workTree == null;
  1144. }
  1145. /**
  1146. * @return the root directory of the working tree, where files are checked
  1147. * out for viewing and editing.
  1148. * @throws NoWorkTreeException
  1149. * if this is bare, which implies it has no working directory.
  1150. * See {@link #isBare()}.
  1151. */
  1152. public File getWorkTree() throws NoWorkTreeException {
  1153. if (isBare())
  1154. throw new NoWorkTreeException();
  1155. return workTree;
  1156. }
  1157. /**
  1158. * Force a scan for changed refs.
  1159. *
  1160. * @throws IOException
  1161. */
  1162. public abstract void scanForRepoChanges() throws IOException;
  1163. /**
  1164. * Notify that the index changed
  1165. */
  1166. public abstract void notifyIndexChanged();
  1167. /**
  1168. * @param refName
  1169. *
  1170. * @return a more user friendly ref name
  1171. */
  1172. public static String shortenRefName(String refName) {
  1173. if (refName.startsWith(Constants.R_HEADS))
  1174. return refName.substring(Constants.R_HEADS.length());
  1175. if (refName.startsWith(Constants.R_TAGS))
  1176. return refName.substring(Constants.R_TAGS.length());
  1177. if (refName.startsWith(Constants.R_REMOTES))
  1178. return refName.substring(Constants.R_REMOTES.length());
  1179. return refName;
  1180. }
  1181. /**
  1182. * @param refName
  1183. * @return the remote branch name part of <code>refName</code>, i.e. without
  1184. * the <code>refs/remotes/&lt;remote&gt;</code> prefix, if
  1185. * <code>refName</code> represents a remote tracking branch;
  1186. * otherwise null.
  1187. * @since 3.4
  1188. */
  1189. public String shortenRemoteBranchName(String refName) {
  1190. for (String remote : getRemoteNames()) {
  1191. String remotePrefix = Constants.R_REMOTES + remote + "/"; //$NON-NLS-1$
  1192. if (refName.startsWith(remotePrefix))
  1193. return refName.substring(remotePrefix.length());
  1194. }
  1195. return null;
  1196. }
  1197. /**
  1198. * @param refName
  1199. * @return the remote name part of <code>refName</code>, i.e. without the
  1200. * <code>refs/remotes/&lt;remote&gt;</code> prefix, if
  1201. * <code>refName</code> represents a remote tracking branch;
  1202. * otherwise null.
  1203. * @since 3.4
  1204. */
  1205. public String getRemoteName(String refName) {
  1206. for (String remote : getRemoteNames()) {
  1207. String remotePrefix = Constants.R_REMOTES + remote + "/"; //$NON-NLS-1$
  1208. if (refName.startsWith(remotePrefix))
  1209. return remote;
  1210. }
  1211. return null;
  1212. }
  1213. /**
  1214. * @param refName
  1215. * @return a {@link ReflogReader} for the supplied refname, or null if the
  1216. * named ref does not exist.
  1217. * @throws IOException
  1218. * the ref could not be accessed.
  1219. * @since 3.0
  1220. */
  1221. public abstract ReflogReader getReflogReader(String refName)
  1222. throws IOException;
  1223. /**
  1224. * Return the information stored in the file $GIT_DIR/MERGE_MSG. In this
  1225. * file operations triggering a merge will store a template for the commit
  1226. * message of the merge commit.
  1227. *
  1228. * @return a String containing the content of the MERGE_MSG file or
  1229. * {@code null} if this file doesn't exist
  1230. * @throws IOException
  1231. * @throws NoWorkTreeException
  1232. * if this is bare, which implies it has no working directory.
  1233. * See {@link #isBare()}.
  1234. */
  1235. public String readMergeCommitMsg() throws IOException, NoWorkTreeException {
  1236. return readCommitMsgFile(Constants.MERGE_MSG);
  1237. }
  1238. /**
  1239. * Write new content to the file $GIT_DIR/MERGE_MSG. In this file operations
  1240. * triggering a merge will store a template for the commit message of the
  1241. * merge commit. If <code>null</code> is specified as message the file will
  1242. * be deleted.
  1243. *
  1244. * @param msg
  1245. * the message which should be written or <code>null</code> to
  1246. * delete the file
  1247. *
  1248. * @throws IOException
  1249. */
  1250. public void writeMergeCommitMsg(String msg) throws IOException {
  1251. File mergeMsgFile = new File(gitDir, Constants.MERGE_MSG);
  1252. writeCommitMsg(mergeMsgFile, msg);
  1253. }
  1254. /**
  1255. * Return the information stored in the file $GIT_DIR/COMMIT_EDITMSG. In
  1256. * this file hooks triggered by an operation may read or modify the current
  1257. * commit message.
  1258. *
  1259. * @return a String containing the content of the COMMIT_EDITMSG file or
  1260. * {@code null} if this file doesn't exist
  1261. * @throws IOException
  1262. * @throws NoWorkTreeException
  1263. * if this is bare, which implies it has no working directory.
  1264. * See {@link #isBare()}.
  1265. * @since 4.0
  1266. */
  1267. public String readCommitEditMsg() throws IOException, NoWorkTreeException {
  1268. return readCommitMsgFile(Constants.COMMIT_EDITMSG);
  1269. }
  1270. /**
  1271. * Write new content to the file $GIT_DIR/COMMIT_EDITMSG. In this file hooks
  1272. * triggered by an operation may read or modify the current commit message.
  1273. * If {@code null} is specified as message the file will be deleted.
  1274. *
  1275. * @param msg
  1276. * the message which should be written or {@code null} to delete
  1277. * the file
  1278. *
  1279. * @throws IOException
  1280. * @since 4.0
  1281. */
  1282. public void writeCommitEditMsg(String msg) throws IOException {
  1283. File commiEditMsgFile = new File(gitDir, Constants.COMMIT_EDITMSG);
  1284. writeCommitMsg(commiEditMsgFile, msg);
  1285. }
  1286. /**
  1287. * Return the information stored in the file $GIT_DIR/MERGE_HEAD. In this
  1288. * file operations triggering a merge will store the IDs of all heads which
  1289. * should be merged together with HEAD.
  1290. *
  1291. * @return a list of commits which IDs are listed in the MERGE_HEAD file or
  1292. * {@code null} if this file doesn't exist. Also if the file exists
  1293. * but is empty {@code null} will be returned
  1294. * @throws IOException
  1295. * @throws NoWorkTreeException
  1296. * if this is bare, which implies it has no working directory.
  1297. * See {@link #isBare()}.
  1298. */
  1299. public List<ObjectId> readMergeHeads() throws IOException, NoWorkTreeException {
  1300. if (isBare() || getDirectory() == null)
  1301. throw new NoWorkTreeException();
  1302. byte[] raw = readGitDirectoryFile(Constants.MERGE_HEAD);
  1303. if (raw == null)
  1304. return null;
  1305. LinkedList<ObjectId> heads = new LinkedList<ObjectId>();
  1306. for (int p = 0; p < raw.length;) {
  1307. heads.add(ObjectId.fromString(raw, p));
  1308. p = RawParseUtils
  1309. .nextLF(raw, p + Constants.OBJECT_ID_STRING_LENGTH);
  1310. }
  1311. return heads;
  1312. }
  1313. /**
  1314. * Write new merge-heads into $GIT_DIR/MERGE_HEAD. In this file operations
  1315. * triggering a merge will store the IDs of all heads which should be merged
  1316. * together with HEAD. If <code>null</code> is specified as list of commits
  1317. * the file will be deleted
  1318. *
  1319. * @param heads
  1320. * a list of commits which IDs should be written to
  1321. * $GIT_DIR/MERGE_HEAD or <code>null</code> to delete the file
  1322. * @throws IOException
  1323. */
  1324. public void writeMergeHeads(List<? extends ObjectId> heads) throws IOException {
  1325. writeHeadsFile(heads, Constants.MERGE_HEAD);
  1326. }
  1327. /**
  1328. * Return the information stored in the file $GIT_DIR/CHERRY_PICK_HEAD.
  1329. *
  1330. * @return object id from CHERRY_PICK_HEAD file or {@code null} if this file
  1331. * doesn't exist. Also if the file exists but is empty {@code null}
  1332. * will be returned
  1333. * @throws IOException
  1334. * @throws NoWorkTreeException
  1335. * if this is bare, which implies it has no working directory.
  1336. * See {@link #isBare()}.
  1337. */
  1338. public ObjectId readCherryPickHead() throws IOException,
  1339. NoWorkTreeException {
  1340. if (isBare() || getDirectory() == null)
  1341. throw new NoWorkTreeException();
  1342. byte[] raw = readGitDirectoryFile(Constants.CHERRY_PICK_HEAD);
  1343. if (raw == null)
  1344. return null;
  1345. return ObjectId.fromString(raw, 0);
  1346. }
  1347. /**
  1348. * Return the information stored in the file $GIT_DIR/REVERT_HEAD.
  1349. *
  1350. * @return object id from REVERT_HEAD file or {@code null} if this file
  1351. * doesn't exist. Also if the file exists but is empty {@code null}
  1352. * will be returned
  1353. * @throws IOException
  1354. * @throws NoWorkTreeException
  1355. * if this is bare, which implies it has no working directory.
  1356. * See {@link #isBare()}.
  1357. */
  1358. public ObjectId readRevertHead() throws IOException, NoWorkTreeException {
  1359. if (isBare() || getDirectory() == null)
  1360. throw new NoWorkTreeException();
  1361. byte[] raw = readGitDirectoryFile(Constants.REVERT_HEAD);
  1362. if (raw == null)
  1363. return null;
  1364. return ObjectId.fromString(raw, 0);
  1365. }
  1366. /**
  1367. * Write cherry pick commit into $GIT_DIR/CHERRY_PICK_HEAD. This is used in
  1368. * case of conflicts to store the cherry which was tried to be picked.
  1369. *
  1370. * @param head
  1371. * an object id of the cherry commit or <code>null</code> to
  1372. * delete the file
  1373. * @throws IOException
  1374. */
  1375. public void writeCherryPickHead(ObjectId head) throws IOException {
  1376. List<ObjectId> heads = (head != null) ? Collections.singletonList(head)
  1377. : null;
  1378. writeHeadsFile(heads, Constants.CHERRY_PICK_HEAD);
  1379. }
  1380. /**
  1381. * Write revert commit into $GIT_DIR/REVERT_HEAD. This is used in case of
  1382. * conflicts to store the revert which was tried to be picked.
  1383. *
  1384. * @param head
  1385. * an object id of the revert commit or <code>null</code> to
  1386. * delete the file
  1387. * @throws IOException
  1388. */
  1389. public void writeRevertHead(ObjectId head) throws IOException {
  1390. List<ObjectId> heads = (head != null) ? Collections.singletonList(head)
  1391. : null;
  1392. writeHeadsFile(heads, Constants.REVERT_HEAD);
  1393. }
  1394. /**
  1395. * Write original HEAD commit into $GIT_DIR/ORIG_HEAD.
  1396. *
  1397. * @param head
  1398. * an object id of the original HEAD commit or <code>null</code>
  1399. * to delete the file
  1400. * @throws IOException
  1401. */
  1402. public void writeOrigHead(ObjectId head) throws IOException {
  1403. List<ObjectId> heads = head != null ? Collections.singletonList(head)
  1404. : null;
  1405. writeHeadsFile(heads, Constants.ORIG_HEAD);
  1406. }
  1407. /**
  1408. * Return the information stored in the file $GIT_DIR/ORIG_HEAD.
  1409. *
  1410. * @return object id from ORIG_HEAD file or {@code null} if this file
  1411. * doesn't exist. Also if the file exists but is empty {@code null}
  1412. * will be returned
  1413. * @throws IOException
  1414. * @throws NoWorkTreeException
  1415. * if this is bare, which implies it has no working directory.
  1416. * See {@link #isBare()}.
  1417. */
  1418. public ObjectId readOrigHead() throws IOException, NoWorkTreeException {
  1419. if (isBare() || getDirectory() == null)
  1420. throw new NoWorkTreeException();
  1421. byte[] raw = readGitDirectoryFile(Constants.ORIG_HEAD);
  1422. return raw != null ? ObjectId.fromString(raw, 0) : null;
  1423. }
  1424. /**
  1425. * Return the information stored in the file $GIT_DIR/SQUASH_MSG. In this
  1426. * file operations triggering a squashed merge will store a template for the
  1427. * commit message of the squash commit.
  1428. *
  1429. * @return a String containing the content of the SQUASH_MSG file or
  1430. * {@code null} if this file doesn't exist
  1431. * @throws IOException
  1432. * @throws NoWorkTreeException
  1433. * if this is bare, which implies it has no working directory.
  1434. * See {@link #isBare()}.
  1435. */
  1436. public String readSquashCommitMsg() throws IOException {
  1437. return readCommitMsgFile(Constants.SQUASH_MSG);
  1438. }
  1439. /**
  1440. * Write new content to the file $GIT_DIR/SQUASH_MSG. In this file
  1441. * operations triggering a squashed merge will store a template for the
  1442. * commit message of the squash commit. If <code>null</code> is specified as
  1443. * message the file will be deleted.
  1444. *
  1445. * @param msg
  1446. * the message which should be written or <code>null</code> to
  1447. * delete the file
  1448. *
  1449. * @throws IOException
  1450. */
  1451. public void writeSquashCommitMsg(String msg) throws IOException {
  1452. File squashMsgFile = new File(gitDir, Constants.SQUASH_MSG);
  1453. writeCommitMsg(squashMsgFile, msg);
  1454. }
  1455. private String readCommitMsgFile(String msgFilename) throws IOException {
  1456. if (isBare() || getDirectory() == null)
  1457. throw new NoWorkTreeException();
  1458. File mergeMsgFile = new File(getDirectory(), msgFilename);
  1459. try {
  1460. return RawParseUtils.decode(IO.readFully(mergeMsgFile));
  1461. } catch (FileNotFoundException e) {
  1462. // the file has disappeared in the meantime ignore it
  1463. return null;
  1464. }
  1465. }
  1466. private void writeCommitMsg(File msgFile, String msg) throws IOException {
  1467. if (msg != null) {
  1468. FileOutputStream fos = new FileOutputStream(msgFile);
  1469. try {
  1470. fos.write(msg.getBytes(Constants.CHARACTER_ENCODING));
  1471. } finally {
  1472. fos.close();
  1473. }
  1474. } else {
  1475. FileUtils.delete(msgFile, FileUtils.SKIP_MISSING);
  1476. }
  1477. }
  1478. /**
  1479. * Read a file from the git directory.
  1480. *
  1481. * @param filename
  1482. * @return the raw contents or null if the file doesn't exist or is empty
  1483. * @throws IOException
  1484. */
  1485. private byte[] readGitDirectoryFile(String filename) throws IOException {
  1486. File file = new File(getDirectory(), filename);
  1487. try {
  1488. byte[] raw = IO.readFully(file);
  1489. return raw.length > 0 ? raw : null;
  1490. } catch (FileNotFoundException notFound) {
  1491. return null;
  1492. }
  1493. }
  1494. /**
  1495. * Write the given heads to a file in the git directory.
  1496. *
  1497. * @param heads
  1498. * a list of object ids to write or null if the file should be
  1499. * deleted.
  1500. * @param filename
  1501. * @throws FileNotFoundException
  1502. * @throws IOException
  1503. */
  1504. private void writeHeadsFile(List<? extends ObjectId> heads, String filename)
  1505. throws FileNotFoundException, IOException {
  1506. File headsFile = new File(getDirectory(), filename);
  1507. if (heads != null) {
  1508. BufferedOutputStream bos = new SafeBufferedOutputStream(
  1509. new FileOutputStream(headsFile));
  1510. try {
  1511. for (ObjectId id : heads) {
  1512. id.copyTo(bos);
  1513. bos.write('\n');
  1514. }
  1515. } finally {
  1516. bos.close();
  1517. }
  1518. } else {
  1519. FileUtils.delete(headsFile, FileUtils.SKIP_MISSING);
  1520. }
  1521. }
  1522. /**
  1523. * Read a file formatted like the git-rebase-todo file. The "done" file is
  1524. * also formatted like the git-rebase-todo file. These files can be found in
  1525. * .git/rebase-merge/ or .git/rebase-append/ folders.
  1526. *
  1527. * @param path
  1528. * path to the file relative to the repository's git-dir. E.g.
  1529. * "rebase-merge/git-rebase-todo" or "rebase-append/done"
  1530. * @param includeComments
  1531. * <code>true</code> if also comments should be reported
  1532. * @return the list of steps
  1533. * @throws IOException
  1534. * @since 3.2
  1535. */
  1536. public List<RebaseTodoLine> readRebaseTodo(String path,
  1537. boolean includeComments)
  1538. throws IOException {
  1539. return new RebaseTodoFile(this).readRebaseTodo(path, includeComments);
  1540. }
  1541. /**
  1542. * Write a file formatted like a git-rebase-todo file.
  1543. *
  1544. * @param path
  1545. * path to the file relative to the repository's git-dir. E.g.
  1546. * "rebase-merge/git-rebase-todo" or "rebase-append/done"
  1547. * @param steps
  1548. * the steps to be written
  1549. * @param append
  1550. * whether to append to an existing file or to write a new file
  1551. * @throws IOException
  1552. * @since 3.2
  1553. */
  1554. public void writeRebaseTodoFile(String path, List<RebaseTodoLine> steps,
  1555. boolean append)
  1556. throws IOException {
  1557. new RebaseTodoFile(this).writeRebaseTodoFile(path, steps, append);
  1558. }
  1559. /**
  1560. * @return the names of all known remotes
  1561. * @since 3.4
  1562. */
  1563. public Set<String> getRemoteNames() {
  1564. return getConfig()
  1565. .getSubsections(ConfigConstants.CONFIG_REMOTE_SECTION);
  1566. }
  1567. }