-
-
Save pmyjavec/039999b52e8f199aeaae0dce1d22e480 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Packages | |
# Holds packages, calculates and validates a package dependency graph | |
# Only one instance of each package may be present | |
class Repository | |
include Enumerable | |
def initialize(*packages) | |
@packages = packages | |
end | |
def query(name) | |
package = find(name) | |
raise OperationError, "Package does not exist in repository" if package.nil? | |
package | |
end | |
def index(name, dependencies: []) | |
return find(name) if find(name) | |
dependencies.flatten! if dependencies.is_a? Array | |
dependencies = [dependencies] if dependencies.is_a? String | |
raise OperationError, "Package can't depend on itself" if dependencies.include?(name) | |
raise OperationError, "Package depdency not yet indexed" unless dependencies_available? dependencies | |
pkg = Package.new(name, dependencies) | |
@packages << pkg | |
pkg | |
end | |
def remove(name) | |
pkg = find(name) | |
raise OperationError, "remove failed, package depended on" if package_dependents(name).count > 0 | |
@packages.delete_if { |p| p == pkg } | |
pkg | |
end | |
def each(&block) | |
@packages.each(&block) | |
end | |
def list | |
each.map(&:name) | |
end | |
private | |
def find(name) | |
find { |pkg| pkg.name == name } | |
end | |
# Find packages that depend | |
def package_dependents(name) | |
@packages.select { |p| p.dependencies.include?(name) } | |
end | |
def dependencies_available?(deps) | |
(deps - list).empty? | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment