CombinedText
stringlengths
4
3.42M
# the bot will interface with most of our functionality module Doomybot module Client # constants # keeps marky happy even if there are no entries BASE_TEXT = 'common I am we is the word there their.' # gets all asks and replies to them def self.get_and_reply_to_asks # init tumblr client client = Tumblr::Client.new # get array of asks asks = (client.submissions USERNAME, limit: 3)['posts'] # create our ClientAsk objects asks_list = [] asks.each do |ask| # create the asks in a database and add them to an array to return asks_list << Ask.create(sentiment: (ask['question']).sentiments, user: User.find_or_create_by(username: ask['asking_name']), text: ask['question'].add_punctuation, tumblr_id: ask['id']) end reply_to_asks asks_list end # replys to asks. Takes an array of Ask objects def self.reply_to_asks asks # init tumblr client client = Tumblr::Client.new asks.each do |ask| puts client.edit(USERNAME, id: ask.tumblr_id, answer: generate_response, state: 'published', tags: "feeling #{get_sentiment(to_string: true)}") puts "Published ask from #{ask.user.username}!\n" end end # reblog a random text post def self.reblog_random_text_post client = Tumblr::Client.new if User.count > 0 # get a random user offset = rand(User.count) user = User.offset(offset).first # get a random post from the user post_hash = client.posts(user.username, type: 'text', limit: 1, offset: rand(1..100)) if post_hash # create a new TextPost object with our info post = TextPost.new(post_hash) # add the content of our text post to the database of asks post.content.each do |ask| Ask.create(sentiment: ask.sentiments, user: nil, text: ask.add_punctuation, tumblr_id: nil) end # finally reblog the post client.reblog(USERNAME, id: post.id, reblog_key: post.reblog_key, comment: generate_response, tags: "feeling #{get_sentiment(to_string: true)}") else # try again if no user posts are found reblog_random_text_post end end end # posts a pixelsorted image def self.post_pixelsort if Image.count > 0 client = Tumblr::Client.new # get a random image offset = rand(Image.count) image = Image.offset(offset).first path = download_image(image.url) path = sort_image(path) client.photo(USERNAME, {data: path, caption: generate_response}) end end private def self.download_image url # download image dirname = "#{ROOT_PATH}/images" FileUtils.mkdir_p(dirname) unless File.directory?(dirname) # open image and save it image = MiniMagick::Image.open(url) image.resize("640x") image.format 'png' if image.type != 'PNG' filename = "images/#{Time.now.to_i}.png" image.write filename return filename end # generate a markov response def self.generate_response(sentences: nil) # get our dictionary markov = MarkyMarkov::TemporaryDictionary.new(2) sentiment = get_sentiment # get our entries to choose from based on if the robot is happy or sad sentiment >= 0 ? sql = "sentiment >= 0" : sql = "sentiment < 0" corpus = (Ask.where(sql).map { |i| i.text }.join("\n") + BASE_TEXT ) # set the amount of sentences to generate sentences ||= rand(1..2) markov.parse_string corpus gen = markov.generate_n_sentences sentences markov.clear! return gen end # returns a number or string def self.get_sentiment(memory: 10, to_string: false) number = Ask.limit(memory).reverse_order.average(:sentiment).to_f number >= 0 ? emotional_state = 'happy' : emotional_state = 'sad' to_string ? emotional_state : number end # return random true or false def self.rb return [true,false].sample end # sorts an image def self.sort_image path type = rand(0..3) diagonal = [true,false].sample case type when 0 puts 'Generating brute sort...' Pxlsrt::Brute.brute(path, diagonal: diagonal, middle: rb, vertical: rb).save(path) when 1 puts 'Generating smart sort...' Pxlsrt::Smart.smart(path, threshold: rand(100..200), diagonal: diagonal).save(path) when 2 puts 'Generating kim sort...' Pxlsrt::Kim.kim(path).save(path) when 3 puts 'Generating seed sort...' Pxlsrt::Seed.seed(path, threshold: rand(0.1..10), distance: rand(20..50)).save(path) end puts 'Pixel sort successful, uploading...' return path end # classes end end fixed error when no post # the bot will interface with most of our functionality module Doomybot module Client # constants # keeps marky happy even if there are no entries BASE_TEXT = 'common I am we is the word there their.' # gets all asks and replies to them def self.get_and_reply_to_asks # init tumblr client client = Tumblr::Client.new # get array of asks asks = (client.submissions USERNAME, limit: 3)['posts'] # create our ClientAsk objects asks_list = [] asks.each do |ask| # create the asks in a database and add them to an array to return asks_list << Ask.create(sentiment: (ask['question']).sentiments, user: User.find_or_create_by(username: ask['asking_name']), text: ask['question'].add_punctuation, tumblr_id: ask['id']) end reply_to_asks asks_list end # replys to asks. Takes an array of Ask objects def self.reply_to_asks asks # init tumblr client client = Tumblr::Client.new asks.each do |ask| puts client.edit(USERNAME, id: ask.tumblr_id, answer: generate_response, state: 'published', tags: "feeling #{get_sentiment(to_string: true)}") puts "Published ask from #{ask.user.username}!\n" end end # reblog a random text post def self.reblog_random_text_post client = Tumblr::Client.new if User.count > 0 # get a random user offset = rand(User.count) user = User.offset(offset).first # get a random post from the user post_hash = client.posts(user.username, type: 'text', limit: 1, offset: rand(1..100)) if post_hash['posts'][0]['id'] # create a new TextPost object with our info post = TextPost.new(post_hash) # add the content of our text post to the database of asks post.content.each do |ask| Ask.create(sentiment: ask.sentiments, user: nil, text: ask.add_punctuation, tumblr_id: nil) end # finally reblog the post client.reblog(USERNAME, id: post.id, reblog_key: post.reblog_key, comment: generate_response, tags: "feeling #{get_sentiment(to_string: true)}") else # try again if no user posts are found reblog_random_text_post end end end # posts a pixelsorted image def self.post_pixelsort if Image.count > 0 client = Tumblr::Client.new # get a random image offset = rand(Image.count) image = Image.offset(offset).first path = download_image(image.url) path = sort_image(path) client.photo(USERNAME, {data: path, caption: generate_response}) end end private def self.download_image url # download image dirname = "#{ROOT_PATH}/images" FileUtils.mkdir_p(dirname) unless File.directory?(dirname) # open image and save it image = MiniMagick::Image.open(url) image.resize("640x") image.format 'png' if image.type != 'PNG' filename = "images/#{Time.now.to_i}.png" image.write filename return filename end # generate a markov response def self.generate_response(sentences: nil) # get our dictionary markov = MarkyMarkov::TemporaryDictionary.new(2) sentiment = get_sentiment # get our entries to choose from based on if the robot is happy or sad sentiment >= 0 ? sql = "sentiment >= 0" : sql = "sentiment < 0" corpus = (Ask.where(sql).map { |i| i.text }.join("\n") + BASE_TEXT ) # set the amount of sentences to generate sentences ||= rand(1..2) markov.parse_string corpus gen = markov.generate_n_sentences sentences markov.clear! return gen end # returns a number or string def self.get_sentiment(memory: 10, to_string: false) number = Ask.limit(memory).reverse_order.average(:sentiment).to_f number >= 0 ? emotional_state = 'happy' : emotional_state = 'sad' to_string ? emotional_state : number end # return random true or false def self.rb return [true,false].sample end # sorts an image def self.sort_image path type = rand(0..3) diagonal = [true,false].sample case type when 0 puts 'Generating brute sort...' Pxlsrt::Brute.brute(path, diagonal: diagonal, middle: rb, vertical: rb).save(path) when 1 puts 'Generating smart sort...' Pxlsrt::Smart.smart(path, threshold: rand(100..200), diagonal: diagonal).save(path) when 2 puts 'Generating kim sort...' Pxlsrt::Kim.kim(path).save(path) when 3 puts 'Generating seed sort...' Pxlsrt::Seed.seed(path, threshold: rand(0.1..10), distance: rand(20..50)).save(path) end puts 'Pixel sort successful, uploading...' return path end # classes end end
module Dragon class Narrator extend Forwardable def_delegators :terminal, :say attr_reader :terminal, :world, :city, :place, :scene, :player def initialize(terminal: nil, world: nil, city: nil, place: nil, scene: nil, player: nil) @terminal = terminal @world = world @city = city @place = place @scene = scene @player = player end def dramatize if scene dramatize_scene scene end if world describe player, prefix: "You are " describe world, prefix: "You are in the world of " end describe city, prefix: "You are visiting " if city dramatize_place(place) if place if player.inventory.any? player.inventory.each do |item| describe item, prefix: " - A " end end end def describe(entity, prefix: '', suffix: '', important: false, heading: false) description = prefix + entity.describe + suffix + '.' say capitalize_first_word(description), important: important, heading: heading end def dramatize_scene(scene) describe scene, prefix: "You are ", heading: true command = scene.last_command if command describe command, important: true end events = scene.last_events dramatize_events(events) if events.any? end def dramatize_events events if events.any? news = events.flatten.compact news.each do |event| simulate_delay_for_dramatic_purposes if news.length > 1 describe event, important: true end end end def dramatize_place(place) place_preposition = if place.is_a?(Room) 'in' elsif place.is_a?(Area) 'wandering near' elsif place.is_a?(Building) 'at' end if place.is_a?(Room) describe place, prefix: "You are #{place_preposition} the ", suffix: " of a #{place.building.describe}" else describe place, prefix: "You are #{place_preposition} the " end if place.people.any? say "There are people here." place.people.each do |person| describe person, prefix: "There is a person " end end end private def capitalize_first_word(sentence) words = sentence.split(' ') first = words.first.capitalize rest = words[1..-1] [first, rest].flatten.join(' ') end def simulate_delay_for_dramatic_purposes sleep 1.0 end end end cleanup inventory output module Dragon class Narrator extend Forwardable def_delegators :terminal, :say attr_reader :terminal, :world, :city, :place, :scene, :player def initialize(terminal: nil, world: nil, city: nil, place: nil, scene: nil, player: nil) @terminal = terminal @world = world @city = city @place = place @scene = scene @player = player end def dramatize if scene dramatize_scene scene end if world describe player, prefix: "You are " describe world, prefix: "You are in the world of " end describe city, prefix: "You are visiting " if city dramatize_place(place) if place if player.inventory.any? inventory_description = player.inventory.map(&:describe).join(', ') say "Your inventory includes: #{inventory_description}." end end def describe(entity, prefix: '', suffix: '', important: false, heading: false) description = prefix + entity.describe + suffix + '.' say capitalize_first_word(description), important: important, heading: heading end def dramatize_scene(scene) describe scene, prefix: "You are ", heading: true command = scene.last_command if command describe command, important: true end events = scene.last_events dramatize_events(events) if events.any? end def dramatize_events events if events.any? news = events.flatten.compact news.each do |event| simulate_delay_for_dramatic_purposes if news.length > 1 describe event, important: true end end end def dramatize_place(place) place_preposition = if place.is_a?(Room) 'in' elsif place.is_a?(Area) 'wandering near' elsif place.is_a?(Building) 'at' end if place.is_a?(Room) describe place, prefix: "You are #{place_preposition} the ", suffix: " of a #{place.building.describe}" else describe place, prefix: "You are #{place_preposition} the " end if place.people.any? say "There are people here." place.people.each do |person| describe person, prefix: "There is a person " end end end private def capitalize_first_word(sentence) words = sentence.split(' ') first = words.first.capitalize rest = words[1..-1] [first, rest].flatten.join(' ') end def simulate_delay_for_dramatic_purposes sleep 1.0 end end end
module Drydock # A project defines the methods available in a `Drydockfile`. When run using # the binary `drydock`, this object will be instantiated automatically for you. # # The contents of a `Drydockfile` is automatically evaluated in the context # of a project, so you don't need to instantiate the object manually. class Project DEFAULT_OPTIONS = { auto_remove: true, author: nil, cache: nil, event_handler: false, ignorefile: '.dockerignore' } # Create a new project. **Do not use directly.** # # @api private # @param [Hash] build_opts Build-time options # @option build_opts [Boolean] :auto_remove Whether intermediate images # created during the build of this project should be automatically removed. # @option build_opts [String] :author The default author field when an # author is not provided explicitly with {Project#author}. # @option build_opts [ObjectCaches::Base] :cache An object cache manager. # @option build_opts [#call] :event_handler A handler that responds to a # `#call` message with four arguments: `[event, is_new, serial_no, event_type]` # most useful to override logging. # @option build_opts [PhaseChain] :chain A phase chain manager. # @option build_opts [String] :ignorefile The name of the ignore-file to load. def initialize(build_opts = {}) @chain = build_opts.key?(:chain) && build_opts.delete(:chain).derive @plugins = {} @run_path = [] @serial = 0 @build_opts = DEFAULT_OPTIONS.clone build_opts.each_pair { |key, value| set(key, value) } @stream_monitor = build_opts[:event_handler] ? StreamMonitor.new(build_opts[:event_handler]) : nil end # Set the author for commits. This is not an instruction, per se, and only # takes into effect after instructions that cause a commit. # # This instruction affects **all instructions after it**, but nothing before it. # # At least one of `name` or `email` must be given. If one is provided, the # other is optional. # # If no author instruction is provided, the author field is left blank by default. # # @param [String] name The name of the author or maintainer of the image. # @param [String] email The email of the author or maintainer. # @raise [InvalidInstructionArgumentError] when neither name nor email is provided def author(name: nil, email: nil) if (name.nil? || name.empty?) && (email.nil? || name.empty?) fail InvalidInstructionArgumentError, 'at least one of `name:` or `email:` must be provided' end value = email ? "#{name} <#{email}>" : name.to_s set :author, value end # Retrieve the current build ID for this project. If no image has been built, # returns the string '0'. def build_id chain ? chain.serial : '0' end # Change directories for operations that require a directory. # # @param [String] path The path to change directories to. # @yield block containing instructions to run inside the new directory def cd(path = '/', &blk) @run_path << path blk.call if blk ensure @run_path.pop end # Set the command that is automatically executed by default when the image # is run through the `docker run` command. # # {#cmd} corresponds to the `CMD` Dockerfile instruction. This instruction # does **not** run the command, but rather provides the default command to # be run when the image is run without specifying a command. # # As with the `CMD` Dockerfile instruction, the {#cmd} instruction has three # forms: # # * `['executable', 'param1', 'param2', '...']`, which would run the # executable directly when the image is run; # * `['param1', 'param2', '...']`, which would pass the parameters to the # executable provided in the {#entrypoint} instruction; or # * `'executable param1 param2'`, which would run the executable inside # a subshell. # # The first two forms are preferred over the last one. See also {#entrypoint} # to see how the instruction interacts with this one. # # @param [String, Array<String>] command The command set to run. When a # `String` is provided, the command is run inside a shell (`/bin/sh`). # When an `Array` is given, the command is run as-is given. def cmd(command) requires_from!(:cmd) log_step('cmd', command) unless command.is_a?(Array) command = ['/bin/sh', '-c', command.to_s] end chain.run("# CMD #{command.inspect}", command: command) self end # Copies files from `source_path` on the the build machine, into `target_path` # in the container. This instruction automatically commits the result. # # The `copy` instruction always respects the `ignorefile`. # # When `no_cache` is `true` (also see parameter explanation below), then any # instruction after {#copy} will also be rebuilt *every time*. # # @param [String] source_path The source path on the build machine (where # `drydock` is running) from which to copy files. # @param [String] target_path The target path inside the image to which to # copy the files. This path **must already exist** before copying begins. # @param [Integer, Boolean] chmod When `false` (the default), the original file # mode from its source file is kept when copying into the container. Otherwise, # the mode provided (in integer octal form) will be used to override *all* # file and directory modes. # @param [Boolean] no_cache When `false` (the default), the hash digest of the # source path--taking into account all its files, directories, and contents--is # used as the cache key. When `true`, the image is rebuilt *every* time. # @param [Boolean] recursive When `true`, then `source_path` is expected to be # a directory, at which point all its contents would be recursively searched. # When `false`, then `source_path` is expected to be a file. # # @raise (see Instructions::Copy#run!) def copy(source_path, target_path, chmod: false, no_cache: false, recursive: true) requires_from!(:copy) log_step('copy', source_path, target_path, chmod: (chmod ? sprintf('%o', chmod) : false)) Instructions::Copy.new(chain, source_path, target_path).tap do |ins| ins.chmod = chmod if chmod ins.ignorefile = ignorefile ins.no_cache = no_cache ins.recursive = recursive ins.run! end self end # Destroy the images and containers created, and attempt to return the docker # state as it was before the project. # # @api private def destroy!(force: false) chain.destroy!(force: force) if chain finalize!(force: force) end # Meta instruction to signal to the builder that the build is done. # # @api private def done! throw :done end # Download (and cache) a file from `source_url`, and copy it into the # `target_path` in the container with a specific `chmod` (defaults to 0644). # # The cache currently cannot be disabled. def download_once(source_url, target_path, chmod: 0644) requires_from!(:download_once) unless cache.key?(source_url) cache.set(source_url) do |obj| chunked = proc do |chunk, _remaining_bytes, _total_bytes| obj.write(chunk) end Excon.get(source_url, response_block: chunked) end end log_step('download_once', source_url, target_path, chmod: sprintf('%o', chmod)) # TODO(rpasay): invalidate cache when the downloaded file changes, # and then force rebuild digest = Digest::MD5.hexdigest(source_url) chain.run("# DOWNLOAD file:md5:#{digest} #{target_path}") do |container| container.archive_put do |output| TarWriter.new(output) do |tar| cache.get(source_url) do |input| tar.add_file(target_path, chmod) do |tar_file| tar_file.write(input.read) end end end end end self end # **This instruction is *optional*, but if specified, must appear at the # beginning of the file.** # # This instruction is used to restrict the version of `drydock` required to # run the `Drydockfile`. When not specified, any version of `drydock` is # allowed to run the file. # # The version specifier understands any bundler-compatible (and therefore # [gem-compatible](http://guides.rubygems.org/patterns/#semantic-versioning)) # version specification; it even understands the twiddle-waka (`~>`) operator. # # @example # drydock '~> 0.5' # @param [String] version The version specification to use. def drydock(version = '>= 0') fail InvalidInstructionError, '`drydock` must be called before `from`' if chain log_step('drydock', version) requirement = Gem::Requirement.create(version) current = Gem::Version.create(Drydock.version) unless requirement.satisfied_by?(current) fail InsufficientVersionError, "build requires #{version.inspect}, but you're on #{Drydock.version.inspect}" end self end # Sets the entrypoint command for an image. # # {#entrypoint} corresponds to the `ENTRYPOINT` Dockerfile instruction. This # instruction does **not** run the command, but rather provides the default # command to be run when the image is run without specifying a command. # # As with the {#cmd} instruction, {#entrypoint} has three forms, of which the # first two forms are preferred over the last one. # # @param (see #cmd) def entrypoint(command) requires_from!(:entrypoint) log_step('entrypoint', command) unless command.is_a?(Array) command = ['/bin/sh', '-c', command.to_s] end chain.run("# ENTRYPOINT #{command.inspect}", entrypoint: command) self end # Set an environment variable, which will be persisted in future images # (unless it is specifically overwritten) and derived projects. # # Subsequent commands can refer to the environment variable by preceeding # the variable with a `$` sign, e.g.: # # ``` # env 'APP_ROOT', '/app' # mkdir '$APP_ROOT' # run ['some-command', '--install-into=$APP_ROOT'] # ``` # # Multiple calls to this instruction will build on top of one another. # That is, after the following two instructions: # # ``` # env 'APP_ROOT', '/app' # env 'BUILD_ROOT', '/build' # ``` # # the resulting image will have both `APP_ROOT` and `BUILD_ROOT` set. Later # instructions overwrites previous instructions of the same name: # # ``` # # 1 # env 'APP_ROOT', '/app' # # 2 # env 'APP_ROOT', '/home/jdoe/app' # # 3 # ``` # # At `#1`, `APP_ROOT` is not set (assuming no other instruction comes before # it). At `#2`, `APP_ROOT` is set to '/app'. At `#3`, `APP_ROOT` is set to # `/home/jdoe/app`, and its previous value is no longer available. # # Note that the environment variable is not evaluated in ruby; in fact, the # `$` sign should be passed as-is to the instruction. As with shell # programming, the variable name should **not** be preceeded by the `$` # sign when declared, but **must be** when referenced. # # @param [String] name The name of the environment variable. By convention, # the name should be uppercased and underscored. The name should **not** # be preceeded by a `$` sign in this context. # @param [String] value The value of the variable. No extra quoting should be # necessary here. def env(name, value) requires_from!(:env) log_step('env', name, value) chain.run("# SET ENV #{name}", env: ["#{name}=#{value}"]) self end # Set multiple environment variables at once. The values will be persisted in # future images and derived projects, unless specifically overwritten. # # The following instruction: # # ``` # envs APP_ROOT: '/app', BUILD_ROOT: '/tmp/build' # ``` # # is equivalent to the more verbose: # # ``` # env 'APP_ROOT', '/app' # env 'BUILD_ROOT', '/tmp/build' # ``` # # When the same key appears more than once in the same {#envs} instruction, # the same rules for ruby hashes are used, which most likely (but not guaranteed # between ruby version) means the last value set is used. # # See also notes for {#env}. # # @param [Hash, #map] pairs A hash-like enumerable, where `#map` yields exactly # two elements. See {#env} for any restrictions of the name (key) and value. def envs(pairs) requires_from!(:envs) log_step('envs', pairs) values = pairs.map { |name, value| "#{name}=#{value}" } chain.run("# SET ENVS #{pairs.inspect}", env: values) self end # Expose one or more ports. The values will be persisted in future images # # When `ports` is specified, the format must be: ##/type where ## is the port # number and type is either tcp or udp. For example, "80/tcp", "53/udp". # # Otherwise, when the `tcp` or `udp` options are specified, only the port # numbers are required. # # @example Different ways of exposing port 53 UDP and ports 80 and 443 TCP: # expose '53/udp', '80/tcp', '443/tcp' # expose udp: 53, tcp: [80, 443] # @param [Array<String>] ports An array of strings of port specifications. # Each port specification must look like `#/type`, where `#` is the port # number, and `type` is either `udp` or `tcp`. # @param [Integer, Array<Integer>] tcp A TCP port number to open, or an array # of TCP port numbers to open. # @param [Integer, Array<Integer>] udp A UDP port number to open, or an array # of UDP port numbers to open. def expose(*ports, tcp: [], udp: []) requires_from!(:expose) Array(tcp).flatten.each { |p| ports << "#{p}/tcp" } Array(udp).flatten.each { |p| ports << "#{p}/udp" } log_step('expose', *ports) chain.run("# SET PORTS #{ports.inspect}", expose: ports) end # Build on top of the `from` image. **This must be the first instruction of # the project,** although non-instructions may appear before this. # # If the `drydock` instruction is provided, `from` should come after it. # # @param [#to_s] repo The name of the repository, which may be any valid docker # repository name, and may optionally include the registry address, e.g., # `johndoe/thing` or `quay.io/jane/app`. The name *must not* contain the tag name. # @param [#to_s] tag The tag to use. def from(repo, tag = 'latest') fail InvalidInstructionError, '`from` must only be called once per project' if chain repo = repo.to_s tag = tag.to_s log_step('from', repo, tag) @chain = PhaseChain.from_repo(repo, tag) self end # Finalize everything. This will be automatically invoked at the end of # the build, and should not be called manually. # # @api private def finalize!(force: false) if chain chain.finalize!(force: force) end if stream_monitor stream_monitor.kill stream_monitor.join end self end # Derive a new project based on the current state of the current project. # This instruction returns the new project that can be referred to elsewhere, # and most useful when combined with other inter-project instructions, # such as {#import}. # # For example: # # ``` # from 'some-base-image' # # APP_ROOT = '/app' # mkdir APP_ROOT # # # 1: # ruby_build = derive { # copy 'Gemfile', APP_ROOT # run 'bundle install --path vendor' # } # # # 2: # js_build = derive { # copy 'package.json', APP_ROOT # run 'npm install' # } # # # 3: # derive { # import APP_ROOT, from: ruby_build # import APP_ROOT, from: js_build # tag 'jdoe/app', 'latest', force: true # } # ``` # # In the example above, an image is created with a new directory `/app`. # From there, the build branches out into three directions: # # 1. Create a new project referred to as `ruby_build`. The result of this # project is an image with `/app`, a `Gemfile` in it, and a `vendor` # directory containing vendored gems. # 2. Create a new project referred to as `js_build`. The result of this # project is an image with `/app`, a `package.json` in it, and a # `node_modules` directory containing vendored node.js modules. # This project does **not** contain any of the contents of `ruby_build`. # 3. Create an anonymous project containing only the empty `/app` directory. # Onto that, we'll import the contents of `/app` from `ruby_build` into # this anonymous project. We'll do the same with the contents of `/app` # from `js_build`. Finally, the resulting image is given the tag # `jdoe/app:latest`. # # Because each derived project lives on its own and only depends on the # root project (whose end state is essentially the {#mkdir} instruction), # when `Gemfile` changes but `package.json` does not, only the first # derived project will be rebuilt (and following that, the third as well). # # @param (see #initialize) # @option (see #initialize) def derive(opts = {}, &blk) clean_opts = build_opts.delete_if { |_, v| v.nil? } derive_opts = clean_opts.merge(opts).merge(chain: chain) Project.new(derive_opts).tap do |project| project.instance_eval(&blk) if blk end end # Access to the logger object. # # @return [Logger] A logger object on which one could call `#info`, `#error`, # and the likes. def logger Drydock.logger end # Import a `path` from a different project. The `from` option should be # project, usually the result of a `derive` instruction. # # @todo Add a #load method as an alternative to #import # Doing so would allow importing a full container, including things from # /etc, some of which may be mounted from the host. # # @todo Do not always append /. to the #archive_get calls # We must check the type of `path` inside the container first. # # @todo Break this large method into smaller ones. def import(path, from: nil, force: false, spool: false) mkdir(path) requires_from!(:import) fail InvalidInstructionError, 'cannot `import` from `/`' if path == '/' && !force fail InvalidInstructionError, '`import` requires a `from:` option' if from.nil? log_step('import', path, from: from.last_image.id) total_size = 0 if spool spool_file = Tempfile.new('drydock') log_info("Spooling to #{spool_file.path}") from.send(:chain).run("# EXPORT #{path}", no_commit: true) do |source_container| source_container.archive_get(path + "/.") do |chunk| spool_file.write(chunk.to_s).tap { |b| total_size += b } end end spool_file.rewind chain.run("# IMPORT #{path}", no_cache: true) do |target_container| target_container.archive_put(path) do |output| output.write(spool_file.read) end end spool_file.close else chain.run("# IMPORT #{path}", no_cache: true) do |target_container| target_container.archive_put(path) do |output| from.send(:chain).run("# EXPORT #{path}", no_commit: true) do |source_container| source_container.archive_get(path + "/.") do |chunk| output.write(chunk.to_s).tap { |b| total_size += b } end end end end end log_info("Imported #{Formatters.number(total_size)} bytes") end # Retrieve the last image object built in this project. # # If no image has been built, returns `nil`. def last_image chain ? chain.last_image : nil end # Create a new directory specified by `path` in the image. # # @param [String] path The path to create inside the image. # @param [String] chmod The mode to which the new directory will be chmodded. # If not specified, the default umask is used to determine the mode. def mkdir(path, chmod: nil) if chmod run "mkdir -p #{path} && chmod #{chmod} #{path}" else run "mkdir -p #{path}" end end # @todo on_build instructions should be deferred to the end. def on_build(instruction = nil, &_blk) requires_from!(:on_build) log_step('on_build', instruction) chain.run("# ON_BUILD #{instruction}", on_build: instruction) self end # This instruction is used to run the command `cmd` against the current # project. The `opts` may be one of: # # * `no_commit`, when true, the container will not be committed to a # new image. Most of the time, you want this to be false (default). # * `no_cache`, when true, the container will be rebuilt every time. # Most of the time, you want this to be false (default). When # `no_commit` is true, this option is automatically set to true. # * `env`, which can be used to specify a set of environment variables. # For normal usage, you should use the `env` or `envs` instructions. # * `expose`, which can be used to specify a set of ports to expose. For # normal usage, you should use the `expose` instruction instead. # * `on_build`, which can be used to specify low-level on-build options. For # normal usage, you should use the `on_build` instruction instead. # # Additional `opts` are also recognized: # # * `author`, a string, preferably in the format of "Name <email@domain.com>". # If provided, this overrides the author name set with {#author}. # * `comment`, an arbitrary string used as a comment for the resulting image # # If `run` results in a container being created and `&blk` is provided, the # container will be yielded to the block. def run(cmd, opts = {}, &blk) requires_from!(:run) cmd = build_cmd(cmd) run_opts = opts.dup run_opts[:author] = opts[:author] || build_opts[:author] run_opts[:comment] = opts[:comment] || build_opts[:comment] log_step('run', cmd, run_opts) chain.run(cmd, run_opts, &blk) self end # Set project options. def set(key, value = nil, &blk) key = key.to_sym fail ArgumentError, "unknown option #{key.inspect}" unless build_opts.key?(key) fail ArgumentError, "one of value or block is required" if value.nil? && blk.nil? fail ArgumentError, "only one of value or block may be provided" if value && blk build_opts[key] = value || blk end # Tag the current state of the project with a repo and tag. # # When `force` is false (default), this instruction will raise an error if # the tag already exists. When true, the tag will be overwritten without # any warnings. def tag(repo, tag = 'latest', force: false) requires_from!(:tag) log_step('tag', repo, tag, force: force) chain.tag(repo, tag, force: force) self end # Use a `plugin` to issue other commands. The block form can be used to issue # multiple commands: # # ``` # with Plugins::APK do |apk| # apk.update # end # ``` # # In cases of single commands, the above is the same as: # # ``` # with(Plugins::APK).update # ``` def with(plugin, &blk) (@plugins[plugin] ||= plugin.new(self)).tap do |instance| blk.call(instance) if blk end end private attr_reader :chain, :build_opts, :stream_monitor def build_cmd(cmd) if @run_path.empty? cmd.to_s.strip else "cd #{@run_path.join('/')} && #{cmd}".strip end end def cache build_opts[:cache] ||= ObjectCaches::NoCache.new end def ignorefile @ignorefile ||= IgnorefileDefinition.new(build_opts[:ignorefile]) end def log_info(msg, indent: 0) Drydock.logger.info(indent: indent, message: msg) end def log_step(op, *args) opts = args.last.is_a?(Hash) ? args.pop : {} optstr = opts.map { |k, v| "#{k}: #{v.inspect}" }.join(', ') argstr = args.map(&:inspect).join(', ') Drydock.logger.info("##{chain ? chain.serial : 0}: #{op}(#{argstr}#{optstr.empty? ? '' : ", #{optstr}"})") end def requires_from!(instruction) fail InvalidInstructionError, "`#{instruction}` cannot be called before `from`" unless chain end end end project: note on on_build module Drydock # A project defines the methods available in a `Drydockfile`. When run using # the binary `drydock`, this object will be instantiated automatically for you. # # The contents of a `Drydockfile` is automatically evaluated in the context # of a project, so you don't need to instantiate the object manually. class Project DEFAULT_OPTIONS = { auto_remove: true, author: nil, cache: nil, event_handler: false, ignorefile: '.dockerignore' } # Create a new project. **Do not use directly.** # # @api private # @param [Hash] build_opts Build-time options # @option build_opts [Boolean] :auto_remove Whether intermediate images # created during the build of this project should be automatically removed. # @option build_opts [String] :author The default author field when an # author is not provided explicitly with {Project#author}. # @option build_opts [ObjectCaches::Base] :cache An object cache manager. # @option build_opts [#call] :event_handler A handler that responds to a # `#call` message with four arguments: `[event, is_new, serial_no, event_type]` # most useful to override logging. # @option build_opts [PhaseChain] :chain A phase chain manager. # @option build_opts [String] :ignorefile The name of the ignore-file to load. def initialize(build_opts = {}) @chain = build_opts.key?(:chain) && build_opts.delete(:chain).derive @plugins = {} @run_path = [] @serial = 0 @build_opts = DEFAULT_OPTIONS.clone build_opts.each_pair { |key, value| set(key, value) } @stream_monitor = build_opts[:event_handler] ? StreamMonitor.new(build_opts[:event_handler]) : nil end # Set the author for commits. This is not an instruction, per se, and only # takes into effect after instructions that cause a commit. # # This instruction affects **all instructions after it**, but nothing before it. # # At least one of `name` or `email` must be given. If one is provided, the # other is optional. # # If no author instruction is provided, the author field is left blank by default. # # @param [String] name The name of the author or maintainer of the image. # @param [String] email The email of the author or maintainer. # @raise [InvalidInstructionArgumentError] when neither name nor email is provided def author(name: nil, email: nil) if (name.nil? || name.empty?) && (email.nil? || name.empty?) fail InvalidInstructionArgumentError, 'at least one of `name:` or `email:` must be provided' end value = email ? "#{name} <#{email}>" : name.to_s set :author, value end # Retrieve the current build ID for this project. If no image has been built, # returns the string '0'. def build_id chain ? chain.serial : '0' end # Change directories for operations that require a directory. # # @param [String] path The path to change directories to. # @yield block containing instructions to run inside the new directory def cd(path = '/', &blk) @run_path << path blk.call if blk ensure @run_path.pop end # Set the command that is automatically executed by default when the image # is run through the `docker run` command. # # {#cmd} corresponds to the `CMD` Dockerfile instruction. This instruction # does **not** run the command, but rather provides the default command to # be run when the image is run without specifying a command. # # As with the `CMD` Dockerfile instruction, the {#cmd} instruction has three # forms: # # * `['executable', 'param1', 'param2', '...']`, which would run the # executable directly when the image is run; # * `['param1', 'param2', '...']`, which would pass the parameters to the # executable provided in the {#entrypoint} instruction; or # * `'executable param1 param2'`, which would run the executable inside # a subshell. # # The first two forms are preferred over the last one. See also {#entrypoint} # to see how the instruction interacts with this one. # # @param [String, Array<String>] command The command set to run. When a # `String` is provided, the command is run inside a shell (`/bin/sh`). # When an `Array` is given, the command is run as-is given. def cmd(command) requires_from!(:cmd) log_step('cmd', command) unless command.is_a?(Array) command = ['/bin/sh', '-c', command.to_s] end chain.run("# CMD #{command.inspect}", command: command) self end # Copies files from `source_path` on the the build machine, into `target_path` # in the container. This instruction automatically commits the result. # # The `copy` instruction always respects the `ignorefile`. # # When `no_cache` is `true` (also see parameter explanation below), then any # instruction after {#copy} will also be rebuilt *every time*. # # @param [String] source_path The source path on the build machine (where # `drydock` is running) from which to copy files. # @param [String] target_path The target path inside the image to which to # copy the files. This path **must already exist** before copying begins. # @param [Integer, Boolean] chmod When `false` (the default), the original file # mode from its source file is kept when copying into the container. Otherwise, # the mode provided (in integer octal form) will be used to override *all* # file and directory modes. # @param [Boolean] no_cache When `false` (the default), the hash digest of the # source path--taking into account all its files, directories, and contents--is # used as the cache key. When `true`, the image is rebuilt *every* time. # @param [Boolean] recursive When `true`, then `source_path` is expected to be # a directory, at which point all its contents would be recursively searched. # When `false`, then `source_path` is expected to be a file. # # @raise (see Instructions::Copy#run!) def copy(source_path, target_path, chmod: false, no_cache: false, recursive: true) requires_from!(:copy) log_step('copy', source_path, target_path, chmod: (chmod ? sprintf('%o', chmod) : false)) Instructions::Copy.new(chain, source_path, target_path).tap do |ins| ins.chmod = chmod if chmod ins.ignorefile = ignorefile ins.no_cache = no_cache ins.recursive = recursive ins.run! end self end # Destroy the images and containers created, and attempt to return the docker # state as it was before the project. # # @api private def destroy!(force: false) chain.destroy!(force: force) if chain finalize!(force: force) end # Meta instruction to signal to the builder that the build is done. # # @api private def done! throw :done end # Download (and cache) a file from `source_url`, and copy it into the # `target_path` in the container with a specific `chmod` (defaults to 0644). # # The cache currently cannot be disabled. def download_once(source_url, target_path, chmod: 0644) requires_from!(:download_once) unless cache.key?(source_url) cache.set(source_url) do |obj| chunked = proc do |chunk, _remaining_bytes, _total_bytes| obj.write(chunk) end Excon.get(source_url, response_block: chunked) end end log_step('download_once', source_url, target_path, chmod: sprintf('%o', chmod)) # TODO(rpasay): invalidate cache when the downloaded file changes, # and then force rebuild digest = Digest::MD5.hexdigest(source_url) chain.run("# DOWNLOAD file:md5:#{digest} #{target_path}") do |container| container.archive_put do |output| TarWriter.new(output) do |tar| cache.get(source_url) do |input| tar.add_file(target_path, chmod) do |tar_file| tar_file.write(input.read) end end end end end self end # **This instruction is *optional*, but if specified, must appear at the # beginning of the file.** # # This instruction is used to restrict the version of `drydock` required to # run the `Drydockfile`. When not specified, any version of `drydock` is # allowed to run the file. # # The version specifier understands any bundler-compatible (and therefore # [gem-compatible](http://guides.rubygems.org/patterns/#semantic-versioning)) # version specification; it even understands the twiddle-waka (`~>`) operator. # # @example # drydock '~> 0.5' # @param [String] version The version specification to use. def drydock(version = '>= 0') fail InvalidInstructionError, '`drydock` must be called before `from`' if chain log_step('drydock', version) requirement = Gem::Requirement.create(version) current = Gem::Version.create(Drydock.version) unless requirement.satisfied_by?(current) fail InsufficientVersionError, "build requires #{version.inspect}, but you're on #{Drydock.version.inspect}" end self end # Sets the entrypoint command for an image. # # {#entrypoint} corresponds to the `ENTRYPOINT` Dockerfile instruction. This # instruction does **not** run the command, but rather provides the default # command to be run when the image is run without specifying a command. # # As with the {#cmd} instruction, {#entrypoint} has three forms, of which the # first two forms are preferred over the last one. # # @param (see #cmd) def entrypoint(command) requires_from!(:entrypoint) log_step('entrypoint', command) unless command.is_a?(Array) command = ['/bin/sh', '-c', command.to_s] end chain.run("# ENTRYPOINT #{command.inspect}", entrypoint: command) self end # Set an environment variable, which will be persisted in future images # (unless it is specifically overwritten) and derived projects. # # Subsequent commands can refer to the environment variable by preceeding # the variable with a `$` sign, e.g.: # # ``` # env 'APP_ROOT', '/app' # mkdir '$APP_ROOT' # run ['some-command', '--install-into=$APP_ROOT'] # ``` # # Multiple calls to this instruction will build on top of one another. # That is, after the following two instructions: # # ``` # env 'APP_ROOT', '/app' # env 'BUILD_ROOT', '/build' # ``` # # the resulting image will have both `APP_ROOT` and `BUILD_ROOT` set. Later # instructions overwrites previous instructions of the same name: # # ``` # # 1 # env 'APP_ROOT', '/app' # # 2 # env 'APP_ROOT', '/home/jdoe/app' # # 3 # ``` # # At `#1`, `APP_ROOT` is not set (assuming no other instruction comes before # it). At `#2`, `APP_ROOT` is set to '/app'. At `#3`, `APP_ROOT` is set to # `/home/jdoe/app`, and its previous value is no longer available. # # Note that the environment variable is not evaluated in ruby; in fact, the # `$` sign should be passed as-is to the instruction. As with shell # programming, the variable name should **not** be preceeded by the `$` # sign when declared, but **must be** when referenced. # # @param [String] name The name of the environment variable. By convention, # the name should be uppercased and underscored. The name should **not** # be preceeded by a `$` sign in this context. # @param [String] value The value of the variable. No extra quoting should be # necessary here. def env(name, value) requires_from!(:env) log_step('env', name, value) chain.run("# SET ENV #{name}", env: ["#{name}=#{value}"]) self end # Set multiple environment variables at once. The values will be persisted in # future images and derived projects, unless specifically overwritten. # # The following instruction: # # ``` # envs APP_ROOT: '/app', BUILD_ROOT: '/tmp/build' # ``` # # is equivalent to the more verbose: # # ``` # env 'APP_ROOT', '/app' # env 'BUILD_ROOT', '/tmp/build' # ``` # # When the same key appears more than once in the same {#envs} instruction, # the same rules for ruby hashes are used, which most likely (but not guaranteed # between ruby version) means the last value set is used. # # See also notes for {#env}. # # @param [Hash, #map] pairs A hash-like enumerable, where `#map` yields exactly # two elements. See {#env} for any restrictions of the name (key) and value. def envs(pairs) requires_from!(:envs) log_step('envs', pairs) values = pairs.map { |name, value| "#{name}=#{value}" } chain.run("# SET ENVS #{pairs.inspect}", env: values) self end # Expose one or more ports. The values will be persisted in future images # # When `ports` is specified, the format must be: ##/type where ## is the port # number and type is either tcp or udp. For example, "80/tcp", "53/udp". # # Otherwise, when the `tcp` or `udp` options are specified, only the port # numbers are required. # # @example Different ways of exposing port 53 UDP and ports 80 and 443 TCP: # expose '53/udp', '80/tcp', '443/tcp' # expose udp: 53, tcp: [80, 443] # @param [Array<String>] ports An array of strings of port specifications. # Each port specification must look like `#/type`, where `#` is the port # number, and `type` is either `udp` or `tcp`. # @param [Integer, Array<Integer>] tcp A TCP port number to open, or an array # of TCP port numbers to open. # @param [Integer, Array<Integer>] udp A UDP port number to open, or an array # of UDP port numbers to open. def expose(*ports, tcp: [], udp: []) requires_from!(:expose) Array(tcp).flatten.each { |p| ports << "#{p}/tcp" } Array(udp).flatten.each { |p| ports << "#{p}/udp" } log_step('expose', *ports) chain.run("# SET PORTS #{ports.inspect}", expose: ports) end # Build on top of the `from` image. **This must be the first instruction of # the project,** although non-instructions may appear before this. # # If the `drydock` instruction is provided, `from` should come after it. # # @param [#to_s] repo The name of the repository, which may be any valid docker # repository name, and may optionally include the registry address, e.g., # `johndoe/thing` or `quay.io/jane/app`. The name *must not* contain the tag name. # @param [#to_s] tag The tag to use. def from(repo, tag = 'latest') fail InvalidInstructionError, '`from` must only be called once per project' if chain repo = repo.to_s tag = tag.to_s log_step('from', repo, tag) @chain = PhaseChain.from_repo(repo, tag) self end # Finalize everything. This will be automatically invoked at the end of # the build, and should not be called manually. # # @api private def finalize!(force: false) if chain chain.finalize!(force: force) end if stream_monitor stream_monitor.kill stream_monitor.join end self end # Derive a new project based on the current state of the current project. # This instruction returns the new project that can be referred to elsewhere, # and most useful when combined with other inter-project instructions, # such as {#import}. # # For example: # # ``` # from 'some-base-image' # # APP_ROOT = '/app' # mkdir APP_ROOT # # # 1: # ruby_build = derive { # copy 'Gemfile', APP_ROOT # run 'bundle install --path vendor' # } # # # 2: # js_build = derive { # copy 'package.json', APP_ROOT # run 'npm install' # } # # # 3: # derive { # import APP_ROOT, from: ruby_build # import APP_ROOT, from: js_build # tag 'jdoe/app', 'latest', force: true # } # ``` # # In the example above, an image is created with a new directory `/app`. # From there, the build branches out into three directions: # # 1. Create a new project referred to as `ruby_build`. The result of this # project is an image with `/app`, a `Gemfile` in it, and a `vendor` # directory containing vendored gems. # 2. Create a new project referred to as `js_build`. The result of this # project is an image with `/app`, a `package.json` in it, and a # `node_modules` directory containing vendored node.js modules. # This project does **not** contain any of the contents of `ruby_build`. # 3. Create an anonymous project containing only the empty `/app` directory. # Onto that, we'll import the contents of `/app` from `ruby_build` into # this anonymous project. We'll do the same with the contents of `/app` # from `js_build`. Finally, the resulting image is given the tag # `jdoe/app:latest`. # # Because each derived project lives on its own and only depends on the # root project (whose end state is essentially the {#mkdir} instruction), # when `Gemfile` changes but `package.json` does not, only the first # derived project will be rebuilt (and following that, the third as well). # # @param (see #initialize) # @option (see #initialize) def derive(opts = {}, &blk) clean_opts = build_opts.delete_if { |_, v| v.nil? } derive_opts = clean_opts.merge(opts).merge(chain: chain) Project.new(derive_opts).tap do |project| project.instance_eval(&blk) if blk end end # Access to the logger object. # # @return [Logger] A logger object on which one could call `#info`, `#error`, # and the likes. def logger Drydock.logger end # Import a `path` from a different project. The `from` option should be # project, usually the result of a `derive` instruction. # # @todo Add a #load method as an alternative to #import # Doing so would allow importing a full container, including things from # /etc, some of which may be mounted from the host. # # @todo Do not always append /. to the #archive_get calls # We must check the type of `path` inside the container first. # # @todo Break this large method into smaller ones. def import(path, from: nil, force: false, spool: false) mkdir(path) requires_from!(:import) fail InvalidInstructionError, 'cannot `import` from `/`' if path == '/' && !force fail InvalidInstructionError, '`import` requires a `from:` option' if from.nil? log_step('import', path, from: from.last_image.id) total_size = 0 if spool spool_file = Tempfile.new('drydock') log_info("Spooling to #{spool_file.path}") from.send(:chain).run("# EXPORT #{path}", no_commit: true) do |source_container| source_container.archive_get(path + "/.") do |chunk| spool_file.write(chunk.to_s).tap { |b| total_size += b } end end spool_file.rewind chain.run("# IMPORT #{path}", no_cache: true) do |target_container| target_container.archive_put(path) do |output| output.write(spool_file.read) end end spool_file.close else chain.run("# IMPORT #{path}", no_cache: true) do |target_container| target_container.archive_put(path) do |output| from.send(:chain).run("# EXPORT #{path}", no_commit: true) do |source_container| source_container.archive_get(path + "/.") do |chunk| output.write(chunk.to_s).tap { |b| total_size += b } end end end end end log_info("Imported #{Formatters.number(total_size)} bytes") end # Retrieve the last image object built in this project. # # If no image has been built, returns `nil`. def last_image chain ? chain.last_image : nil end # Create a new directory specified by `path` in the image. # # @param [String] path The path to create inside the image. # @param [String] chmod The mode to which the new directory will be chmodded. # If not specified, the default umask is used to determine the mode. def mkdir(path, chmod: nil) if chmod run "mkdir -p #{path} && chmod #{chmod} #{path}" else run "mkdir -p #{path}" end end # **NOT SUPPORTED YET** # # @todo on_build instructions should be deferred to the end. def on_build(instruction = nil, &_blk) fail NotImplementedError, "on_build is not yet supported" requires_from!(:on_build) log_step('on_build', instruction) chain.run("# ON_BUILD #{instruction}", on_build: instruction) self end # This instruction is used to run the command `cmd` against the current # project. The `opts` may be one of: # # * `no_commit`, when true, the container will not be committed to a # new image. Most of the time, you want this to be false (default). # * `no_cache`, when true, the container will be rebuilt every time. # Most of the time, you want this to be false (default). When # `no_commit` is true, this option is automatically set to true. # * `env`, which can be used to specify a set of environment variables. # For normal usage, you should use the `env` or `envs` instructions. # * `expose`, which can be used to specify a set of ports to expose. For # normal usage, you should use the `expose` instruction instead. # * `on_build`, which can be used to specify low-level on-build options. For # normal usage, you should use the `on_build` instruction instead. # # Additional `opts` are also recognized: # # * `author`, a string, preferably in the format of "Name <email@domain.com>". # If provided, this overrides the author name set with {#author}. # * `comment`, an arbitrary string used as a comment for the resulting image # # If `run` results in a container being created and `&blk` is provided, the # container will be yielded to the block. def run(cmd, opts = {}, &blk) requires_from!(:run) cmd = build_cmd(cmd) run_opts = opts.dup run_opts[:author] = opts[:author] || build_opts[:author] run_opts[:comment] = opts[:comment] || build_opts[:comment] log_step('run', cmd, run_opts) chain.run(cmd, run_opts, &blk) self end # Set project options. def set(key, value = nil, &blk) key = key.to_sym fail ArgumentError, "unknown option #{key.inspect}" unless build_opts.key?(key) fail ArgumentError, "one of value or block is required" if value.nil? && blk.nil? fail ArgumentError, "only one of value or block may be provided" if value && blk build_opts[key] = value || blk end # Tag the current state of the project with a repo and tag. # # When `force` is false (default), this instruction will raise an error if # the tag already exists. When true, the tag will be overwritten without # any warnings. def tag(repo, tag = 'latest', force: false) requires_from!(:tag) log_step('tag', repo, tag, force: force) chain.tag(repo, tag, force: force) self end # Use a `plugin` to issue other commands. The block form can be used to issue # multiple commands: # # ``` # with Plugins::APK do |apk| # apk.update # end # ``` # # In cases of single commands, the above is the same as: # # ``` # with(Plugins::APK).update # ``` def with(plugin, &blk) (@plugins[plugin] ||= plugin.new(self)).tap do |instance| blk.call(instance) if blk end end private attr_reader :chain, :build_opts, :stream_monitor def build_cmd(cmd) if @run_path.empty? cmd.to_s.strip else "cd #{@run_path.join('/')} && #{cmd}".strip end end def cache build_opts[:cache] ||= ObjectCaches::NoCache.new end def ignorefile @ignorefile ||= IgnorefileDefinition.new(build_opts[:ignorefile]) end def log_info(msg, indent: 0) Drydock.logger.info(indent: indent, message: msg) end def log_step(op, *args) opts = args.last.is_a?(Hash) ? args.pop : {} optstr = opts.map { |k, v| "#{k}: #{v.inspect}" }.join(', ') argstr = args.map(&:inspect).join(', ') Drydock.logger.info("##{chain ? chain.serial : 0}: #{op}(#{argstr}#{optstr.empty? ? '' : ", #{optstr}"})") end def requires_from!(instruction) fail InvalidInstructionError, "`#{instruction}` cannot be called before `from`" unless chain end end end
# encoding: UTF-8 require 'fileutils' module Earthquake module Core def config @config ||= {} end def preferred_config @preferred_config ||= {} end def item_queue @item_queue ||= [] end def inits @inits ||= [] end def init(&block) inits << block end def onces @once ||= [] end def once(&block) onces << block end def _once onces.each { |block| class_eval(&block) } end def _init load_config load_plugins inits.each { |block| class_eval(&block) } inits.clear end def reload Gem.refresh loaded = ActiveSupport::Dependencies.loaded.dup ActiveSupport::Dependencies.clear loaded.each { |lib| require_dependency lib } rescue Exception => e error e ensure _init end def default_config consumer = YAML.load_file(File.expand_path('../../../consumer.yml', __FILE__)) dir = File.expand_path('~/.earthquake') { dir: dir, time_format: Time::DATE_FORMATS[:short], plugin_dir: File.join(dir, 'plugin'), file: File.join(dir, 'config'), prompt: '⚡ ', consumer_key: consumer['key'], consumer_secret: consumer['secret'], output_interval: 1, history_size: 1000, api: { :host => 'userstream.twitter.com', :path => '/2/user.json', :ssl => true }, confirm_type: :y, expand_url: false, thread_indent: " ", } end def load_config config.reverse_update(default_config) [config[:dir], config[:plugin_dir]].each do |dir| unless File.exists?(dir) FileUtils.mkdir_p(dir) end end if File.exists?(config[:file]) load config[:file] else File.open(config[:file], mode: 'w', perm: 0600).close end config.update(preferred_config) do |key, cur, new| if Hash === cur and Hash === new cur.merge(new) else new end end get_access_token unless self.config[:token] && self.config[:secret] end def load_plugins Dir[File.join(config[:plugin_dir], '*.rb')].each do |lib| begin require_dependency lib rescue Exception => e error e end end end def __init(options) config.merge!(options) _init _once end def invoke(command, options = {}) __init(options) input(command) end def start(options = {}) __init(options) restore_history EventMachine::run do Thread.start do while buf = Readline.readline(config[:prompt], true) unless Readline::HISTORY.count == 1 Readline::HISTORY.pop if buf.empty? || Readline::HISTORY[-1] == Readline::HISTORY[-2] end sync { reload store_history input(buf.strip) } end stop end EventMachine.add_periodic_timer(config[:output_interval]) do next unless Readline.line_buffer.nil? || Readline.line_buffer.empty? sync { output } end reconnect unless options[:'no-stream'] == true trap('INT') { stop } end end def reconnect item_queue.clear start_stream(config[:api]) end def start_stream(options) stop_stream options = { :oauth => config.slice(:consumer_key, :consumer_secret).merge( :access_key => config[:token], :access_secret => config[:secret], :proxy => ENV['http_proxy'] ) }.merge(options) @stream = ::Twitter::JSONStream.connect(options) @stream.each_item do |item| item_queue << JSON.parse(item) end @stream.on_error do |message| notify "error: #{message}" end @stream.on_reconnect do |timeout, retries| notify "reconnecting in: #{timeout} seconds" end @stream.on_max_reconnects do |timeout, retries| notify "Failed after #{retries} failed reconnects" end end def stop_stream @stream.stop if @stream end def stop stop_stream EventMachine.stop_event_loop end def store_history history_size = config[:history_size] File.open(File.join(config[:dir], 'history'), 'w') do |file| lines = Readline::HISTORY.to_a[([Readline::HISTORY.size - history_size, 0].max)..-1] file.print(lines.join("\n")) end end def restore_history history_file = File.join(config[:dir], 'history') begin File.read(history_file, :encoding => "BINARY"). encode!(:invalid => :replace, :undef => :replace). split(/\n/). each { |line| Readline::HISTORY << line } rescue Errno::ENOENT rescue Errno::EACCES => e error(e) end end def mutex @mutex ||= Mutex.new end def sync(&block) mutex.synchronize do block.call end end def async(&block) Thread.start do begin block.call rescue Exception => e error e end end end def error(e) notify "[ERROR] #{e.message}\n#{e.backtrace.join("\n")}" end def notify(message, options = {}) args = {:title => 'earthquake'}.update(options) title = args.delete(:title) message = message.is_a?(String) ? message : message.inspect # FIXME: Escaping should be done at Notify.notify Notify.notify title, message.e end alias_method :n, :notify def browse(url) Launchy.open(url) end end extend Core end use EventMachine.defer for input loop # encoding: UTF-8 require 'fileutils' module Earthquake module Core def config @config ||= {} end def preferred_config @preferred_config ||= {} end def item_queue @item_queue ||= [] end def inits @inits ||= [] end def init(&block) inits << block end def onces @once ||= [] end def once(&block) onces << block end def _once onces.each { |block| class_eval(&block) } end def _init load_config load_plugins inits.each { |block| class_eval(&block) } inits.clear end def reload Gem.refresh loaded = ActiveSupport::Dependencies.loaded.dup ActiveSupport::Dependencies.clear loaded.each { |lib| require_dependency lib } rescue Exception => e error e ensure _init end def default_config consumer = YAML.load_file(File.expand_path('../../../consumer.yml', __FILE__)) dir = File.expand_path('~/.earthquake') { dir: dir, time_format: Time::DATE_FORMATS[:short], plugin_dir: File.join(dir, 'plugin'), file: File.join(dir, 'config'), prompt: '⚡ ', consumer_key: consumer['key'], consumer_secret: consumer['secret'], output_interval: 1, history_size: 1000, api: { :host => 'userstream.twitter.com', :path => '/2/user.json', :ssl => true }, confirm_type: :y, expand_url: false, thread_indent: " ", } end def load_config config.reverse_update(default_config) [config[:dir], config[:plugin_dir]].each do |dir| unless File.exists?(dir) FileUtils.mkdir_p(dir) end end if File.exists?(config[:file]) load config[:file] else File.open(config[:file], mode: 'w', perm: 0600).close end config.update(preferred_config) do |key, cur, new| if Hash === cur and Hash === new cur.merge(new) else new end end get_access_token unless self.config[:token] && self.config[:secret] end def load_plugins Dir[File.join(config[:plugin_dir], '*.rb')].each do |lib| begin require_dependency lib rescue Exception => e error e end end end def __init(options) config.merge!(options) _init _once end def invoke(command, options = {}) __init(options) input(command) end def start(options = {}) __init(options) restore_history EventMachine::run do EventMachine.defer( lambda { while buf = Readline.readline(config[:prompt], true) unless Readline::HISTORY.count == 1 Readline::HISTORY.pop if buf.empty? || Readline::HISTORY[-1] == Readline::HISTORY[-2] end sync { reload store_history input(buf.strip) } end }, lambda { |_| # unexpected stop } ) EventMachine.add_periodic_timer(config[:output_interval]) do next unless Readline.line_buffer.nil? || Readline.line_buffer.empty? sync { output } end reconnect unless options[:'no-stream'] == true trap('INT') { stop } end end def reconnect item_queue.clear start_stream(config[:api]) end def start_stream(options) stop_stream options = { :oauth => config.slice(:consumer_key, :consumer_secret).merge( :access_key => config[:token], :access_secret => config[:secret], :proxy => ENV['http_proxy'] ) }.merge(options) @stream = ::Twitter::JSONStream.connect(options) @stream.each_item do |item| item_queue << JSON.parse(item) end @stream.on_error do |message| notify "error: #{message}" end @stream.on_reconnect do |timeout, retries| notify "reconnecting in: #{timeout} seconds" end @stream.on_max_reconnects do |timeout, retries| notify "Failed after #{retries} failed reconnects" end end def stop_stream @stream.stop if @stream end def stop stop_stream EventMachine.stop_event_loop end def store_history history_size = config[:history_size] File.open(File.join(config[:dir], 'history'), 'w') do |file| lines = Readline::HISTORY.to_a[([Readline::HISTORY.size - history_size, 0].max)..-1] file.print(lines.join("\n")) end end def restore_history history_file = File.join(config[:dir], 'history') begin File.read(history_file, :encoding => "BINARY"). encode!(:invalid => :replace, :undef => :replace). split(/\n/). each { |line| Readline::HISTORY << line } rescue Errno::ENOENT rescue Errno::EACCES => e error(e) end end def mutex @mutex ||= Mutex.new end def sync(&block) mutex.synchronize do block.call end end def async(&block) Thread.start do begin block.call rescue Exception => e error e end end end def error(e) notify "[ERROR] #{e.message}\n#{e.backtrace.join("\n")}" end def notify(message, options = {}) args = {:title => 'earthquake'}.update(options) title = args.delete(:title) message = message.is_a?(String) ? message : message.inspect # FIXME: Escaping should be done at Notify.notify Notify.notify title, message.e end alias_method :n, :notify def browse(url) Launchy.open(url) end end extend Core end
module EasyTable class Base attr_reader :columns, :items, :options, :model_class, :action_columns attr_accessor :presenter delegate :render, to: :presenter # options: # model_class: the class of the model, used for i18n, using with the human_attribute_name def initialize(items, options = {}) @items = items @options = options @columns = [] @action_columns = [] process_options end def tds(*names) names.each { |name| td(name) } end def td(name, options = {}, &block) @columns << Column.new(name, options, &block) end def action(&block) @action_columns << ActionColumn.new("", {}, &block) end def all_columns @all_columns ||= (columns + action_columns) end def process_options @model_class = options[:model_class] || NilModelClass.instance end class NilModelClass include Singleton def human_attribute_name(attribute) attribute.to_s end end end end support using custom column class module EasyTable class Base attr_reader :columns, :items, :options, :model_class, :action_columns attr_accessor :presenter delegate :render, to: :presenter # options: # model_class: the class of the model, used for i18n, using with the human_attribute_name def initialize(items, options = {}) @items = items @options = options @columns = [] @action_columns = [] process_options end def tds(*names) names.each { |name| td(name) } end # TODO: spec & doc for using option def td(name, options = {}, &block) column_class = options[:using] || Column @columns << column_class.new(name, options, &block) end def action(&block) @action_columns << ActionColumn.new("", {}, &block) end def all_columns @all_columns ||= (columns + action_columns) end def process_options @model_class = options[:model_class] || NilModelClass.instance end class NilModelClass include Singleton def human_attribute_name(attribute) attribute.to_s end end end end
module Edurange class Helper def self.startup_script File.open('my-user-script.sh', 'rb').read end # Creates Bash lines to create user account and set password file or password given users # # ==== Attributes # # * +users+ - Takes parsed users # def self.users_to_bash(users) puts "Got users in users to bash:" p users shell = "" users.each do |user| if user['password'] shell += "\n" shell += "sudo useradd -m #{user['login']} -s /bin/bash\n" # Regex for alphanum only in password input shell += "echo #{user['login']}:#{user['password'].gsub(/[^a-zA-Z0-9]/, "")} | chpasswd\n" # TODO - do something elsif user['pass_file'] name = user['login'] stuff = <<stuff useradd -m #{name} -g admin -s /bin/bash echo "#{name}:password" | chpasswd mkdir -p /home/#{name}/.ssh key='#{user['pass_file'].chomp}' gen_pub = '#{user["generated_pub"]}' gen_priv = '#{user["generated_priv"]}' echo $key >> /home/#{name}/.ssh/authorized_keys echo $gen_priv >> /home/#{name}/.ssh/id_rsa echo $gen_pub >> /home/#{name}/.ssh/id_rsa.pub chmod 600 /home/#{name}/.ssh/id_rsa chmod 600 /home/#{name}/.ssh/authorized_keys chmod 600 /home/#{name}/.ssh/id_rsa.pub chown -R #{name} /home/#{name}/.ssh stuff shell += stuff end end shell end def self.prep_nat_instance(players) # get nat instance ready data = <<data #!/bin/sh set -e set -x echo "Hello World. The time is now $(date -R)!" | tee /root/output.txt curl http://ccdc.boesen.me/edurange.txt > /etc/motd data players.each do |player| `rm id_rsa id_rsa.pub` `ssh-keygen -t rsa -f id_rsa -q -N ''` priv_key = File.open('id_rsa', 'rb').read pub_key = File.open('id_rsa.pub', 'rb').read player["generated_pub"] = pub_key player["generated_priv"] = pub_key data += <<data adduser -m #{player["login"]} mkdir -p /home/#{player["login"]}/.ssh echo '#{player["pass_file"]}' >> /home/#{player["login"]}/.ssh/authorized_keys echo '#{priv_key}' >> /home/#{player["login"]}/.ssh/id_rsa echo '#{pub_key}' >> /home/#{player["login"]}/.ssh/id_rsa.pub chmod 600 /home/#{player["login"]}/.ssh/id_rsa chmod 600 /home/#{player["login"]}/.ssh/authorized_keys chmod 600 /home/#{player["login"]}/.ssh/id_rsa.pub chown -R #{player["login"]} /home/#{player["login"]}/.ssh data end data end end end Oops, no spaces in bash variables.. module Edurange class Helper def self.startup_script File.open('my-user-script.sh', 'rb').read end # Creates Bash lines to create user account and set password file or password given users # # ==== Attributes # # * +users+ - Takes parsed users # def self.users_to_bash(users) puts "Got users in users to bash:" p users shell = "" users.each do |user| if user['password'] shell += "\n" shell += "sudo useradd -m #{user['login']} -s /bin/bash\n" # Regex for alphanum only in password input shell += "echo #{user['login']}:#{user['password'].gsub(/[^a-zA-Z0-9]/, "")} | chpasswd\n" # TODO - do something elsif user['pass_file'] name = user['login'] stuff = <<stuff useradd -m #{name} -g admin -s /bin/bash echo "#{name}:password" | chpasswd mkdir -p /home/#{name}/.ssh key='#{user['pass_file'].chomp}' gen_pub='#{user["generated_pub"]}' gen_priv='#{user["generated_priv"]}' echo $key >> /home/#{name}/.ssh/authorized_keys echo $gen_priv >> /home/#{name}/.ssh/id_rsa echo $gen_pub >> /home/#{name}/.ssh/id_rsa.pub chmod 600 /home/#{name}/.ssh/id_rsa chmod 600 /home/#{name}/.ssh/authorized_keys chmod 600 /home/#{name}/.ssh/id_rsa.pub chown -R #{name} /home/#{name}/.ssh stuff shell += stuff end end shell end def self.prep_nat_instance(players) # get nat instance ready data = <<data #!/bin/sh set -e set -x echo "Hello World. The time is now $(date -R)!" | tee /root/output.txt curl http://ccdc.boesen.me/edurange.txt > /etc/motd data players.each do |player| `rm id_rsa id_rsa.pub` `ssh-keygen -t rsa -f id_rsa -q -N ''` priv_key = File.open('id_rsa', 'rb').read pub_key = File.open('id_rsa.pub', 'rb').read player["generated_pub"] = pub_key player["generated_priv"] = pub_key data += <<data adduser -m #{player["login"]} mkdir -p /home/#{player["login"]}/.ssh echo '#{player["pass_file"]}' >> /home/#{player["login"]}/.ssh/authorized_keys echo '#{priv_key}' >> /home/#{player["login"]}/.ssh/id_rsa echo '#{pub_key}' >> /home/#{player["login"]}/.ssh/id_rsa.pub chmod 600 /home/#{player["login"]}/.ssh/id_rsa chmod 600 /home/#{player["login"]}/.ssh/authorized_keys chmod 600 /home/#{player["login"]}/.ssh/id_rsa.pub chown -R #{player["login"]} /home/#{player["login"]}/.ssh data end data end end end
require 'pp' require 'set' require 'tmpdir' require 'einhorn/command/interface' module Einhorn module Command def self.reap begin while true Einhorn.log_debug('Going to reap a child process') pid = Process.wait(-1, Process::WNOHANG) return unless pid mourn(pid) Einhorn::Event.break_loop end rescue Errno::ECHILD end end # Mourn the death of your child def self.mourn(pid) unless spec = Einhorn::State.children[pid] Einhorn.log_error("Could not find any config for exited child #{pid.inspect}! This probably indicates a bug in Einhorn.") return end Einhorn::State.children.delete(pid) # Unacked worker if spec[:type] == :worker && !spec[:acked] Einhorn::State.consecutive_deaths_before_ack += 1 extra = ' before it was ACKed' else extra = nil end case type = spec[:type] when :worker Einhorn.log_info("===> Exited worker #{pid.inspect}#{extra}") when :state_passer Einhorn.log_debug("===> Exited state passing process #{pid.inspect}") else Einhorn.log_error("===> Exited process #{pid.inspect} has unrecgonized type #{type.inspect}: #{spec.inspect}") end end def self.register_manual_ack(pid) ack_mode = Einhorn::State.ack_mode unless ack_mode[:type] == :manual Einhorn.log_error("Received a manual ACK for #{pid.inspect}, but ack_mode is #{ack_mode.inspect}. Ignoring ACK.") return end Einhorn.log_info("Received a manual ACK from #{pid.inspect}") register_ack(pid) end def self.register_timer_ack(time, pid) ack_mode = Einhorn::State.ack_mode unless ack_mode[:type] == :timer Einhorn.log_error("Received a timer ACK for #{pid.inspect}, but ack_mode is #{ack_mode.inspect}. Ignoring ACK.") return end unless Einhorn::State.children[pid] # TODO: Maybe cancel pending ACK timers upon death? Einhorn.log_debug("Worker #{pid.inspect} died before its timer ACK happened.") return end Einhorn.log_info("Worker #{pid.inspect} has been up for #{time}s, so we are considering it alive.") register_ack(pid) end def self.register_ack(pid) unless spec = Einhorn::State.children[pid] Einhorn.log_error("Could not find state for PID #{pid.inspect}; ignoring ACK.") return end if spec[:acked] Einhorn.log_error("Pid #{pid.inspect} already ACKed; ignoring new ACK.") return end if Einhorn::State.consecutive_deaths_before_ack > 0 extra = ", breaking the streak of #{Einhorn::State.consecutive_deaths_before_ack} consecutive unacked workers dying" else extra = nil end Einhorn::State.consecutive_deaths_before_ack = 0 spec[:acked] = true Einhorn.log_info("Up to #{Einhorn::WorkerPool.ack_count} / #{Einhorn::WorkerPool.ack_target} #{Einhorn::State.ack_mode[:type]} ACKs#{extra}") # Could call cull here directly instead, I believe. Einhorn::Event.break_loop end def self.signal_all(signal, children=nil, record=true) children ||= Einhorn::WorkerPool.workers signaled = [] Einhorn.log_info("Sending #{signal} to #{children.inspect}") children.each do |child| unless spec = Einhorn::State.children[child] Einhorn.log_error("Trying to send #{signal} to dead child #{child.inspect}. The fact we tried this probably indicates a bug in Einhorn.") next end if record if spec[:signaled].include?(signal) Einhorn.log_error("Re-sending #{signal} to already-signaled child #{child.inspect}. It may be slow to spin down, or it may be swallowing #{signal}s.") end spec[:signaled].add(signal) end begin Process.kill(signal, child) rescue Errno::ESRCH else signaled << child end end "Successfully sent #{signal}s to #{signaled.length} processes: #{signaled.inspect}" end def self.increment Einhorn::Event.break_loop old = Einhorn::State.config[:number] new = (Einhorn::State.config[:number] += 1) output = "Incrementing number of workers from #{old} -> #{new}" $stderr.puts(output) output end def self.decrement if Einhorn::State.config[:number] <= 1 output = "Can't decrease number of workers (already at #{Einhorn::State.config[:number]}). Run kill #{$$} if you really want to kill einhorn." $stderr.puts(output) return output end Einhorn::Event.break_loop old = Einhorn::State.config[:number] new = (Einhorn::State.config[:number] -= 1) output = "Decrementing number of workers from #{old} -> #{new}" $stderr.puts(output) output end def self.dumpable_state global_state = Einhorn::State.state descriptor_state = Einhorn::Event.persistent_descriptors.map do |descriptor| descriptor.to_state end plugin_state = {} Einhorn.plugins.each do |name, plugin| plugin_state[name] = plugin::State.state if plugin.const_defined?(:State) end { :state => global_state, :persistent_descriptors => descriptor_state, :plugins => plugin_state } end def self.reload unless Einhorn::State.respawn Einhorn.log_info("Not reloading einhorn because we're exiting") return end Einhorn.log_info("Reloading einhorn (#{Einhorn::TransientState.script_name})...") # In case there's anything lurking $stdout.flush # Spawn a child to pass the state through the pipe read, write = IO.pipe fork do Einhorn::TransientState.whatami = :state_passer Einhorn::State.generation += 1 Einhorn::State.children[$$] = { :type => :state_passer } read.close write.write(YAML.dump(dumpable_state)) write.close exit(0) end write.close # Reload the original environment ENV.clear ENV.update(Einhorn::TransientState.environ) begin exec [Einhorn::TransientState.script_name, Einhorn::TransientState.script_name], *(['--with-state-fd', read.fileno.to_s, '--'] + Einhorn::State.cmd) rescue SystemCallError => e Einhorn.log_error("Could not reload! Attempting to continue. Error was: #{e}") Einhorn::State.reloading_for_preload_upgrade = false read.close end end def self.spinup(cmd=nil) cmd ||= Einhorn::State.cmd if Einhorn::TransientState.preloaded pid = fork do Einhorn::TransientState.whatami = :worker prepare_child_process Einhorn.log_info('About to tear down Einhorn state and run einhorn_main') Einhorn::Command::Interface.uninit Einhorn::Event.close_all_for_worker Einhorn.set_argv(cmd, true) prepare_child_environment einhorn_main end else pid = fork do Einhorn::TransientState.whatami = :worker prepare_child_process Einhorn.log_info("About to exec #{cmd.inspect}") # Here's the only case where cloexec would help. Since we # have to track and manually close FDs for other cases, we # may as well just reuse close_all rather than also set # cloexec on everything. Einhorn::Event.close_all_for_worker prepare_child_environment exec [cmd[0], cmd[0]], *cmd[1..-1] end end Einhorn.log_info("===> Launched #{pid}") Einhorn::State.children[pid] = { :type => :worker, :version => Einhorn::State.version, :acked => false, :signaled => Set.new } Einhorn::State.last_spinup = Time.now # Set up whatever's needed for ACKing ack_mode = Einhorn::State.ack_mode case type = ack_mode[:type] when :timer Einhorn::Event::ACKTimer.open(ack_mode[:timeout], pid) when :manual else Einhorn.log_error("Unrecognized ACK mode #{type.inspect}") end end def self.prepare_child_environment # This is run from the child ENV['EINHORN_MASTER_PID'] = Process.ppid.to_s ENV['EINHORN_SOCK_PATH'] = Einhorn::Command::Interface.socket_path if Einhorn::State.command_socket_as_fd socket = UNIXSocket.open(Einhorn::Command::Interface.socket_path) Einhorn::TransientState.socket_handles << socket ENV['EINHORN_SOCK_FD'] = socket.fileno.to_s end ENV['EINHORN_FD_COUNT'] = Einhorn::State.bind_fds.length.to_s Einhorn::State.bind_fds.each_with_index {|fd, i| ENV["EINHORN_FD_#{i}"] = fd.to_s} # EINHORN_FDS is deprecated. It was originally an attempt to # match Upstart's nominal internal support for space-separated # FD lists, but nobody uses that in practice, and it makes # finding individual FDs more difficult ENV['EINHORN_FDS'] = Einhorn::State.bind_fds.map(&:to_s).join(' ') end def self.prepare_child_process Einhorn.renice_self end def self.full_upgrade if Einhorn::State.path && !Einhorn::State.reloading_for_preload_upgrade reload_for_preload_upgrade else upgrade_workers end end def self.reload_for_preload_upgrade Einhorn::State.reloading_for_preload_upgrade = true reload end def self.upgrade_workers if Einhorn::State.upgrading Einhorn.log_info("Currently upgrading (#{Einhorn::WorkerPool.ack_count} / #{Einhorn::WorkerPool.ack_target} ACKs; bumping version and starting over)...", :upgrade) else Einhorn::State.upgrading = true Einhorn.log_info("Starting upgrade from version #{Einhorn::State.version}...", :upgrade) end # Reset this, since we've just upgraded to a new universe (I'm # not positive this is the right behavior, but it's not # obviously wrong.) Einhorn::State.consecutive_deaths_before_ack = 0 Einhorn::State.last_upgraded = Time.now Einhorn::State.version += 1 replenish_immediately end def self.cull acked = Einhorn::WorkerPool.ack_count unsignaled_count = Einhorn::WorkerPool.unsignaled_count target = Einhorn::WorkerPool.ack_target if Einhorn::State.upgrading && acked >= target Einhorn::State.upgrading = false Einhorn.log_info("Upgraded successfully to version #{Einhorn::State.version} (Einhorn #{Einhorn::VERSION}).", :upgrade) Einhorn.send_tagged_message(:upgrade, "Upgrade done", true) end old_workers = Einhorn::WorkerPool.old_workers if !Einhorn::State.upgrading && old_workers.length > 0 Einhorn.log_info("Killing off #{old_workers.length} old workers.") signal_all("USR2", old_workers) end if unsignaled > target excess = Einhorn::WorkerPool.unsignaled_modern_workers_with_priority[0...(unsignaled_count-target)] Einhorn.log_info("Have too many workers at the current version, so killing off #{excess.length} of them.") signal_all("USR2", excess) end end def self.stop_respawning Einhorn::State.respawn = false Einhorn::Event.break_loop end def self.replenish return unless Einhorn::State.respawn if !Einhorn::State.last_spinup replenish_immediately else replenish_gradually end end def self.replenish_immediately missing = Einhorn::WorkerPool.missing_worker_count if missing <= 0 Einhorn.log_error("Missing is currently #{missing.inspect}, but should always be > 0 when replenish_immediately is called. This probably indicates a bug in Einhorn.") return end Einhorn.log_info("Launching #{missing} new workers") missing.times {spinup} end def self.replenish_gradually return if Einhorn::TransientState.has_outstanding_spinup_timer return unless Einhorn::WorkerPool.missing_worker_count > 0 # Exponentially backoff automated spinup if we're just having # things die before ACKing spinup_interval = Einhorn::State.config[:seconds] * (1.5 ** Einhorn::State.consecutive_deaths_before_ack) seconds_ago = (Time.now - Einhorn::State.last_spinup).to_f if seconds_ago > spinup_interval msg = "Last spinup was #{seconds_ago}s ago, and spinup_interval is #{spinup_interval}s, so spinning up a new process" if Einhorn::State.consecutive_deaths_before_ack > 0 Einhorn.log_info("#{msg} (there have been #{Einhorn::State.consecutive_deaths_before_ack} consecutive unacked worker deaths)") else Einhorn.log_debug(msg) end spinup else Einhorn.log_debug("Last spinup was #{seconds_ago}s ago, and spinup_interval is #{spinup_interval}s, so not spinning up a new process") end Einhorn::TransientState.has_outstanding_spinup_timer = true Einhorn::Event::Timer.open(spinup_interval) do Einhorn::TransientState.has_outstanding_spinup_timer = false replenish end end def self.quieter(log=true) Einhorn::State.verbosity += 1 if Einhorn::State.verbosity < 2 output = "Verbosity set to #{Einhorn::State.verbosity}" Einhorn.log_info(output) if log output end def self.louder(log=true) Einhorn::State.verbosity -= 1 if Einhorn::State.verbosity > 0 output = "Verbosity set to #{Einhorn::State.verbosity}" Einhorn.log_info(output) if log output end end end Rename variables to match style require 'pp' require 'set' require 'tmpdir' require 'einhorn/command/interface' module Einhorn module Command def self.reap begin while true Einhorn.log_debug('Going to reap a child process') pid = Process.wait(-1, Process::WNOHANG) return unless pid mourn(pid) Einhorn::Event.break_loop end rescue Errno::ECHILD end end # Mourn the death of your child def self.mourn(pid) unless spec = Einhorn::State.children[pid] Einhorn.log_error("Could not find any config for exited child #{pid.inspect}! This probably indicates a bug in Einhorn.") return end Einhorn::State.children.delete(pid) # Unacked worker if spec[:type] == :worker && !spec[:acked] Einhorn::State.consecutive_deaths_before_ack += 1 extra = ' before it was ACKed' else extra = nil end case type = spec[:type] when :worker Einhorn.log_info("===> Exited worker #{pid.inspect}#{extra}") when :state_passer Einhorn.log_debug("===> Exited state passing process #{pid.inspect}") else Einhorn.log_error("===> Exited process #{pid.inspect} has unrecgonized type #{type.inspect}: #{spec.inspect}") end end def self.register_manual_ack(pid) ack_mode = Einhorn::State.ack_mode unless ack_mode[:type] == :manual Einhorn.log_error("Received a manual ACK for #{pid.inspect}, but ack_mode is #{ack_mode.inspect}. Ignoring ACK.") return end Einhorn.log_info("Received a manual ACK from #{pid.inspect}") register_ack(pid) end def self.register_timer_ack(time, pid) ack_mode = Einhorn::State.ack_mode unless ack_mode[:type] == :timer Einhorn.log_error("Received a timer ACK for #{pid.inspect}, but ack_mode is #{ack_mode.inspect}. Ignoring ACK.") return end unless Einhorn::State.children[pid] # TODO: Maybe cancel pending ACK timers upon death? Einhorn.log_debug("Worker #{pid.inspect} died before its timer ACK happened.") return end Einhorn.log_info("Worker #{pid.inspect} has been up for #{time}s, so we are considering it alive.") register_ack(pid) end def self.register_ack(pid) unless spec = Einhorn::State.children[pid] Einhorn.log_error("Could not find state for PID #{pid.inspect}; ignoring ACK.") return end if spec[:acked] Einhorn.log_error("Pid #{pid.inspect} already ACKed; ignoring new ACK.") return end if Einhorn::State.consecutive_deaths_before_ack > 0 extra = ", breaking the streak of #{Einhorn::State.consecutive_deaths_before_ack} consecutive unacked workers dying" else extra = nil end Einhorn::State.consecutive_deaths_before_ack = 0 spec[:acked] = true Einhorn.log_info("Up to #{Einhorn::WorkerPool.ack_count} / #{Einhorn::WorkerPool.ack_target} #{Einhorn::State.ack_mode[:type]} ACKs#{extra}") # Could call cull here directly instead, I believe. Einhorn::Event.break_loop end def self.signal_all(signal, children=nil, record=true) children ||= Einhorn::WorkerPool.workers signaled = [] Einhorn.log_info("Sending #{signal} to #{children.inspect}") children.each do |child| unless spec = Einhorn::State.children[child] Einhorn.log_error("Trying to send #{signal} to dead child #{child.inspect}. The fact we tried this probably indicates a bug in Einhorn.") next end if record if spec[:signaled].include?(signal) Einhorn.log_error("Re-sending #{signal} to already-signaled child #{child.inspect}. It may be slow to spin down, or it may be swallowing #{signal}s.") end spec[:signaled].add(signal) end begin Process.kill(signal, child) rescue Errno::ESRCH else signaled << child end end "Successfully sent #{signal}s to #{signaled.length} processes: #{signaled.inspect}" end def self.increment Einhorn::Event.break_loop old = Einhorn::State.config[:number] new = (Einhorn::State.config[:number] += 1) output = "Incrementing number of workers from #{old} -> #{new}" $stderr.puts(output) output end def self.decrement if Einhorn::State.config[:number] <= 1 output = "Can't decrease number of workers (already at #{Einhorn::State.config[:number]}). Run kill #{$$} if you really want to kill einhorn." $stderr.puts(output) return output end Einhorn::Event.break_loop old = Einhorn::State.config[:number] new = (Einhorn::State.config[:number] -= 1) output = "Decrementing number of workers from #{old} -> #{new}" $stderr.puts(output) output end def self.dumpable_state global_state = Einhorn::State.state descriptor_state = Einhorn::Event.persistent_descriptors.map do |descriptor| descriptor.to_state end plugin_state = {} Einhorn.plugins.each do |name, plugin| plugin_state[name] = plugin::State.state if plugin.const_defined?(:State) end { :state => global_state, :persistent_descriptors => descriptor_state, :plugins => plugin_state } end def self.reload unless Einhorn::State.respawn Einhorn.log_info("Not reloading einhorn because we're exiting") return end Einhorn.log_info("Reloading einhorn (#{Einhorn::TransientState.script_name})...") # In case there's anything lurking $stdout.flush # Spawn a child to pass the state through the pipe read, write = IO.pipe fork do Einhorn::TransientState.whatami = :state_passer Einhorn::State.generation += 1 Einhorn::State.children[$$] = { :type => :state_passer } read.close write.write(YAML.dump(dumpable_state)) write.close exit(0) end write.close # Reload the original environment ENV.clear ENV.update(Einhorn::TransientState.environ) begin exec [Einhorn::TransientState.script_name, Einhorn::TransientState.script_name], *(['--with-state-fd', read.fileno.to_s, '--'] + Einhorn::State.cmd) rescue SystemCallError => e Einhorn.log_error("Could not reload! Attempting to continue. Error was: #{e}") Einhorn::State.reloading_for_preload_upgrade = false read.close end end def self.spinup(cmd=nil) cmd ||= Einhorn::State.cmd if Einhorn::TransientState.preloaded pid = fork do Einhorn::TransientState.whatami = :worker prepare_child_process Einhorn.log_info('About to tear down Einhorn state and run einhorn_main') Einhorn::Command::Interface.uninit Einhorn::Event.close_all_for_worker Einhorn.set_argv(cmd, true) prepare_child_environment einhorn_main end else pid = fork do Einhorn::TransientState.whatami = :worker prepare_child_process Einhorn.log_info("About to exec #{cmd.inspect}") # Here's the only case where cloexec would help. Since we # have to track and manually close FDs for other cases, we # may as well just reuse close_all rather than also set # cloexec on everything. Einhorn::Event.close_all_for_worker prepare_child_environment exec [cmd[0], cmd[0]], *cmd[1..-1] end end Einhorn.log_info("===> Launched #{pid}") Einhorn::State.children[pid] = { :type => :worker, :version => Einhorn::State.version, :acked => false, :signaled => Set.new } Einhorn::State.last_spinup = Time.now # Set up whatever's needed for ACKing ack_mode = Einhorn::State.ack_mode case type = ack_mode[:type] when :timer Einhorn::Event::ACKTimer.open(ack_mode[:timeout], pid) when :manual else Einhorn.log_error("Unrecognized ACK mode #{type.inspect}") end end def self.prepare_child_environment # This is run from the child ENV['EINHORN_MASTER_PID'] = Process.ppid.to_s ENV['EINHORN_SOCK_PATH'] = Einhorn::Command::Interface.socket_path if Einhorn::State.command_socket_as_fd socket = UNIXSocket.open(Einhorn::Command::Interface.socket_path) Einhorn::TransientState.socket_handles << socket ENV['EINHORN_SOCK_FD'] = socket.fileno.to_s end ENV['EINHORN_FD_COUNT'] = Einhorn::State.bind_fds.length.to_s Einhorn::State.bind_fds.each_with_index {|fd, i| ENV["EINHORN_FD_#{i}"] = fd.to_s} # EINHORN_FDS is deprecated. It was originally an attempt to # match Upstart's nominal internal support for space-separated # FD lists, but nobody uses that in practice, and it makes # finding individual FDs more difficult ENV['EINHORN_FDS'] = Einhorn::State.bind_fds.map(&:to_s).join(' ') end def self.prepare_child_process Einhorn.renice_self end def self.full_upgrade if Einhorn::State.path && !Einhorn::State.reloading_for_preload_upgrade reload_for_preload_upgrade else upgrade_workers end end def self.reload_for_preload_upgrade Einhorn::State.reloading_for_preload_upgrade = true reload end def self.upgrade_workers if Einhorn::State.upgrading Einhorn.log_info("Currently upgrading (#{Einhorn::WorkerPool.ack_count} / #{Einhorn::WorkerPool.ack_target} ACKs; bumping version and starting over)...", :upgrade) else Einhorn::State.upgrading = true Einhorn.log_info("Starting upgrade from version #{Einhorn::State.version}...", :upgrade) end # Reset this, since we've just upgraded to a new universe (I'm # not positive this is the right behavior, but it's not # obviously wrong.) Einhorn::State.consecutive_deaths_before_ack = 0 Einhorn::State.last_upgraded = Time.now Einhorn::State.version += 1 replenish_immediately end def self.cull acked = Einhorn::WorkerPool.ack_count unsignaled = Einhorn::WorkerPool.unsignaled_count target = Einhorn::WorkerPool.ack_target if Einhorn::State.upgrading && acked >= target Einhorn::State.upgrading = false Einhorn.log_info("Upgraded successfully to version #{Einhorn::State.version} (Einhorn #{Einhorn::VERSION}).", :upgrade) Einhorn.send_tagged_message(:upgrade, "Upgrade done", true) end old_workers = Einhorn::WorkerPool.old_workers if !Einhorn::State.upgrading && old_workers.length > 0 Einhorn.log_info("Killing off #{old_workers.length} old workers.") signal_all("USR2", old_workers) end if unsignaled > target excess = Einhorn::WorkerPool.unsignaled_modern_workers_with_priority[0...(unsignaled-target)] Einhorn.log_info("Have too many workers at the current version, so killing off #{excess.length} of them.") signal_all("USR2", excess) end end def self.stop_respawning Einhorn::State.respawn = false Einhorn::Event.break_loop end def self.replenish return unless Einhorn::State.respawn if !Einhorn::State.last_spinup replenish_immediately else replenish_gradually end end def self.replenish_immediately missing = Einhorn::WorkerPool.missing_worker_count if missing <= 0 Einhorn.log_error("Missing is currently #{missing.inspect}, but should always be > 0 when replenish_immediately is called. This probably indicates a bug in Einhorn.") return end Einhorn.log_info("Launching #{missing} new workers") missing.times {spinup} end def self.replenish_gradually return if Einhorn::TransientState.has_outstanding_spinup_timer return unless Einhorn::WorkerPool.missing_worker_count > 0 # Exponentially backoff automated spinup if we're just having # things die before ACKing spinup_interval = Einhorn::State.config[:seconds] * (1.5 ** Einhorn::State.consecutive_deaths_before_ack) seconds_ago = (Time.now - Einhorn::State.last_spinup).to_f if seconds_ago > spinup_interval msg = "Last spinup was #{seconds_ago}s ago, and spinup_interval is #{spinup_interval}s, so spinning up a new process" if Einhorn::State.consecutive_deaths_before_ack > 0 Einhorn.log_info("#{msg} (there have been #{Einhorn::State.consecutive_deaths_before_ack} consecutive unacked worker deaths)") else Einhorn.log_debug(msg) end spinup else Einhorn.log_debug("Last spinup was #{seconds_ago}s ago, and spinup_interval is #{spinup_interval}s, so not spinning up a new process") end Einhorn::TransientState.has_outstanding_spinup_timer = true Einhorn::Event::Timer.open(spinup_interval) do Einhorn::TransientState.has_outstanding_spinup_timer = false replenish end end def self.quieter(log=true) Einhorn::State.verbosity += 1 if Einhorn::State.verbosity < 2 output = "Verbosity set to #{Einhorn::State.verbosity}" Einhorn.log_info(output) if log output end def self.louder(log=true) Einhorn::State.verbosity -= 1 if Einhorn::State.verbosity > 0 output = "Verbosity set to #{Einhorn::State.verbosity}" Einhorn.log_info(output) if log output end end end
require File.expand_path("#{File.dirname(__FILE__)}/functional_spec_helper") describe "ScrewUnit" do attr_reader :stdout, :request before do @stdout = StringIO.new ScrewUnit::Client.const_set(:STDOUT, stdout) @request = "http request" end after do ScrewUnit::Client.__send__(:remove_const, :STDOUT) end it "runs a full passing Suite" do ScrewUnit::Client.run(:spec_url => "#{root_url}/specs/foo/passing_spec") stdout.string.strip.should == "SUCCESS" end it "runs a full failing Suite" do ScrewUnit::Client.run(:spec_url => "#{root_url}/specs/foo/failing_spec") stdout.string.strip.should include("FAILURE") stdout.string.strip.should include("A failing spec in foo fails: expected true to equal false") end end describe the constant, rather than a string. require File.expand_path("#{File.dirname(__FILE__)}/functional_spec_helper") describe ScrewUnit do attr_reader :stdout, :request before do @stdout = StringIO.new ScrewUnit::Client.const_set(:STDOUT, stdout) @request = "http request" end after do ScrewUnit::Client.__send__(:remove_const, :STDOUT) end it "runs a full passing Suite" do ScrewUnit::Client.run(:spec_url => "#{root_url}/specs/foo/passing_spec") stdout.string.strip.should == "SUCCESS" end it "runs a full failing Suite" do ScrewUnit::Client.run(:spec_url => "#{root_url}/specs/foo/failing_spec") stdout.string.strip.should include("FAILURE") stdout.string.strip.should include("A failing spec in foo fails: expected true to equal false") end end
# Inspired from Redmine and Discourse # http://www.redmine.org/projects/redmine/repository/entry/trunk/lib/redmine/plugin.rb module Ekylibre class PluginRequirementError < StandardError end class Plugin @registered_plugins = {} cattr_accessor :directory, :mirrored_assets_directory self.directory = Ekylibre.root.join('plugins') # Where the plugins assets are gathered for asset pipeline self.mirrored_assets_directory = Ekylibre.root.join('tmp', 'plugins', 'assets') # Returns a type (stylesheets, fonts...) directory for all plugins def self.type_assets_directory(type) mirrored_assets_directory.join(type) end class << self attr_accessor :registered_plugins def field_accessor(*names) class_eval do names.each do |name| define_method(name) do |*args| args.empty? ? instance_variable_get("@#{name}") : instance_variable_set("@#{name}", *args) end end end end # Load all plugins def load Dir.glob(File.join(directory, '*')).sort.each do |directory| next unless File.directory?(directory) load_plugin(directory) end end # Load a given plugin def load_plugin(path) plugfile = File.join(path, 'Plugfile') if File.file?(plugfile) plugin = new(plugfile) registered_plugins[plugin.name] = plugin Rails.logger.info "Load #{plugin.name} plugin" else Rails.logger.warn "No Plugfile found in #{path}" end end def load_integrations Dir.glob(File.join(directory, '*')).sort.each do |directory| next unless File.directory?(directory) Dir.glob(File.join(directory, 'app', 'integrations', '**', '*.rb')).sort.each do |integration| require integration end end end # Adds hooks for plugins # Must be done after load def plug # Adds helper 'plugins' for routes require 'ekylibre/plugin/routing' # Generate themes files generate_themes_stylesheets # Generate JS file generate_javascript_index # Load initializers run_initializers end def each registered_plugins.each do |_key, plugin| yield plugin end end # Generate a javascript for all plugins which refes by theme to add addons import. # This way permit to use natural sprocket cache approach without ERB filtering def generate_javascript_index base_dir = Rails.root.join('tmp', 'plugins', 'javascript-addons') Rails.application.config.assets.paths << base_dir.to_s script = "# This files contains JS addons from plugins\n" each do |plugin| plugin.javascripts.each do |path| script << "#= require #{path}\n" end end # <base_dir>/plugins.js.coffee file = base_dir.join('plugins.js.coffee') FileUtils.mkdir_p file.dirname File.write(file, script) end # Generate a stylesheet by theme to add addons import. # This way permit to use natural sprocket cache approach without ERB filtering def generate_themes_stylesheets base_dir = Rails.root.join('tmp', 'plugins', 'theme-addons') Rails.application.config.assets.paths << base_dir.to_s Ekylibre.themes.each do |theme| stylesheet = "// This files contains #{theme} theme addons from plugins\n\n" each do |plugin| plugin.themes_assets.each do |name, addons| next unless name == theme || name == '*' || (name.respond_to?(:match) && theme.match(name)) stylesheet << "// #{plugin.name}\n" next unless addons[:stylesheets] addons[:stylesheets].each do |file| stylesheet << "@import \"#{file}\";\n" end end end # <base_dir>/themes/<theme>/plugins.scss file = base_dir.join('themes', theme.to_s, 'plugins.scss') FileUtils.mkdir_p file.dirname File.write(file, stylesheet) end end # Run all initializers of plugins def run_initializers each do |plugin| plugin.initializers.each do |name, block| if block.is_a?(Pathname) Rails.logger.info "Require initializer #{name}" require block else Rails.logger.info "Run initialize #{name}" block.call(Rails.application) end end end end def after_login_plugin registered_plugins.values.detect(&:redirect_after_login?) end alias redirect_after_login? after_login_plugin # Call after_login_path on 'after login' plugin def after_login_path(resource) after_login_plugin.name.to_s.camelize.constantize.after_login_path(resource) end end attr_reader :root, :themes_assets, :routes, :javascripts, :initializers field_accessor :name, :summary, :description, :url, :author, :author_url, :version # Links plugin into app def initialize(plugfile_path) @root = Pathname.new(plugfile_path).dirname @view_path = @root.join('app', 'views') @themes_assets = {}.with_indifferent_access @javascripts = [] @initializers = {} lib = @root.join('lib') if File.directory?(lib) $LOAD_PATH.unshift lib ActiveSupport::Dependencies.autoload_paths += [lib] end instance_eval(File.read(plugfile_path), plugfile_path, 1) if @name @name = @name.to_sym else raise "Need a name for plugin #{plugfile_path}" end raise "Plugin name cannot be #{@name}." if [:ekylibre].include?(@name) # Adds lib @lib_dir = @root.join('lib') if @lib_dir.exist? $LOAD_PATH.unshift(@lib_dir.to_s) require @name.to_s unless @required.is_a?(FalseClass) end # Adds rights @right_file = root.join('config', 'rights.yml') Ekylibre::Access.load_file(@right_file) if @right_file.exist? # Adds aggregators @aggregators_path = @root.join('config', 'aggregators') if @aggregators_path.exist? Aggeratio.load_path += Dir.glob(@aggregators_path.join('**', '*.xml')) end # Adds initializers @initializers_path = @root.join('config', 'initializers') if @initializers_path.exist? Dir.glob(@initializers_path.join('**', '*.rb')).each do |file| path = Pathname.new(file) @initializers[path.relative_path_from(@initializers_path).to_s] = path end end # Adds locales (translation and reporting) @locales_path = @root.join('config', 'locales') if @locales_path.exist? Rails.application.config.i18n.load_path += Dir.glob(@locales_path.join('**', '*.{rb,yml}')) DocumentTemplate.load_path << @locales_path end # Adds view path if @view_path.directory? ActionController::Base.prepend_view_path(@view_path) ActionMailer::Base.prepend_view_path(@view_path) end # Adds the app/{controllers,helpers,models} directories of the plugin to the autoload path Dir.glob File.expand_path(@root.join('app', '{controllers,exchangers,guides,helpers,inputs,integrations,jobs,mailers,models}')) do |dir| ActiveSupport::Dependencies.autoload_paths += [dir] $LOAD_PATH.unshift(dir) if Dir.exist?(dir) end # Load all exchanger Dir.glob(@root.join('app', 'exchangers', '**', '*.rb')).each do |path| require path end # Adds the app/{controllers,helpers,models} concerns directories of the plugin to the autoload path Dir.glob File.expand_path(@root.join('app', '{controllers,models}/concerns')) do |dir| ActiveSupport::Dependencies.autoload_paths += [dir] end # Load helpers helpers_path = @root.join('app', 'helpers') Dir.glob File.expand_path(helpers_path.join('**', '*.rb')) do |dir| helper_module = Pathname.new(dir).relative_path_from(helpers_path).to_s.gsub(/\.rb$/, '').camelcase initializer "include helper #{helper_module}" do ::ActionView::Base.send(:include, helper_module.constantize) end end # Adds assets if assets_directory.exist? # Emulate "subdir by plugin" config # plugins/<plugin>/app/assets/*/ => tmp/plugins/assets/*/plugins/<plugin>/ Dir.chdir(assets_directory) do Dir.glob('*') do |type| unless Rails.application.config.assets.paths.include?(assets_directory.join(type).to_s) Rails.application.config.assets.paths << assets_directory.join(type).to_s end unless %w[javascript stylesheets].include? type files_to_compile = Dir[type + '/**/*'].select { |f| File.file? f }.map do |f| Pathname.new(f).relative_path_from(Pathname.new(type)).to_s unless f == type end Rails.application.config.assets.precompile += files_to_compile end end end end end # Accessors def redirect_after_login? @redirect_after_login end # TODO: externalize all following methods in a DSL module def app_version Ekylibre.version end # def gem # end # def plugin # end # Require app version, used for compatibility # app '1.0.0' # app '~> 1.0.0' # app '> 1.0.0' # app '>= 1.0.0', '< 2.0' def app(*requirements) options = requirements.extract_options! requirements.each do |requirement| unless requirement =~ /\A((~>|>=|>|<|<=)\s+)?\d.\d(\.[a-z0-9]+)*\z/ raise PluginRequirementError, "Invalid version requirement expression: #{requirement}" end end unless Gem::Requirement.new(*requirements) =~ Gem::Version.create(Ekylibre.version) raise PluginRequirementError, "Plugin (#{@name}) is incompatible with current version of app (#{Ekylibre.version} not #{requirements.inspect})" end true end # Adds a snippet in app (for side or help places) def snippet(name, options = {}) Ekylibre::Snippet.add("#{@name}-#{name}", snippets_directory.join(name.to_s), options) end # Require a JS file from application.js def require_javascript(path) @javascripts << path end # Adds a snippet in app (for side or help places) def add_stylesheet(name) Rails.application.config.assets.precompile << "plugins/#{@name}/#{name}" end # Adds a stylesheet inside a given theme def add_theme_stylesheet(theme, file) add_theme_asset(theme, file, :stylesheets) end # Adds routes to access controllers def add_routes(&block) @routes = block end def add_toolbar_addon(partial_path, options = {}) # Config main toolbar by default because with current tools, no way to specify # which toolbar use when many in the same page. Ekylibre::View::Addon.add(:main_toolbar, partial_path, options) end def add_cobble_addon(partial_path, options = {}) Ekylibre::View::Addon.add(:cobbler, partial_path, options) end # Adds menus with DSL in Ekylibre backend nav def extend_navigation(&block) Ekylibre::Navigation.exec_dsl(&block) end def initializer(name, &block) @initializers[name] = block end def register_manure_management_method(name, class_name) Calculus::ManureManagementPlan.register_method(name, class_name) end def subscribe(message, proc = nil, &block) Ekylibre::Hook.subscribe(message, proc, &block) end # Will call method MyPlugin.after_login_path to get url to redirect to # CAUTION: Only one plugin can use it. Only first plugin will be called # if many are using this directive. def redirect_after_login @redirect_after_login = true end # TODO: Add other callback for plugin integration # def add_cell # end # def add_theme(name) # end private def snippets_directory @view_path.join('snippets') end def assets_directory @root.join('app', 'assets') end def themes_directory @root.join('app', 'themes') end def add_theme_asset(theme, file, type) @themes_assets[theme] ||= {} @themes_assets[theme][type] ||= [] @themes_assets[theme][type] << file end end end Changed regular expression in Plugin version requirement parsing so we can handle n-digits major/minor version numbers. # Inspired from Redmine and Discourse # http://www.redmine.org/projects/redmine/repository/entry/trunk/lib/redmine/plugin.rb module Ekylibre class PluginRequirementError < StandardError end class Plugin @registered_plugins = {} cattr_accessor :directory, :mirrored_assets_directory self.directory = Ekylibre.root.join('plugins') # Where the plugins assets are gathered for asset pipeline self.mirrored_assets_directory = Ekylibre.root.join('tmp', 'plugins', 'assets') # Returns a type (stylesheets, fonts...) directory for all plugins def self.type_assets_directory(type) mirrored_assets_directory.join(type) end class << self attr_accessor :registered_plugins def field_accessor(*names) class_eval do names.each do |name| define_method(name) do |*args| args.empty? ? instance_variable_get("@#{name}") : instance_variable_set("@#{name}", *args) end end end end # Load all plugins def load Dir.glob(File.join(directory, '*')).sort.each do |directory| next unless File.directory?(directory) load_plugin(directory) end end # Load a given plugin def load_plugin(path) plugfile = File.join(path, 'Plugfile') if File.file?(plugfile) plugin = new(plugfile) registered_plugins[plugin.name] = plugin Rails.logger.info "Load #{plugin.name} plugin" else Rails.logger.warn "No Plugfile found in #{path}" end end def load_integrations Dir.glob(File.join(directory, '*')).sort.each do |directory| next unless File.directory?(directory) Dir.glob(File.join(directory, 'app', 'integrations', '**', '*.rb')).sort.each do |integration| require integration end end end # Adds hooks for plugins # Must be done after load def plug # Adds helper 'plugins' for routes require 'ekylibre/plugin/routing' # Generate themes files generate_themes_stylesheets # Generate JS file generate_javascript_index # Load initializers run_initializers end def each registered_plugins.each do |_key, plugin| yield plugin end end # Generate a javascript for all plugins which refes by theme to add addons import. # This way permit to use natural sprocket cache approach without ERB filtering def generate_javascript_index base_dir = Rails.root.join('tmp', 'plugins', 'javascript-addons') Rails.application.config.assets.paths << base_dir.to_s script = "# This files contains JS addons from plugins\n" each do |plugin| plugin.javascripts.each do |path| script << "#= require #{path}\n" end end # <base_dir>/plugins.js.coffee file = base_dir.join('plugins.js.coffee') FileUtils.mkdir_p file.dirname File.write(file, script) end # Generate a stylesheet by theme to add addons import. # This way permit to use natural sprocket cache approach without ERB filtering def generate_themes_stylesheets base_dir = Rails.root.join('tmp', 'plugins', 'theme-addons') Rails.application.config.assets.paths << base_dir.to_s Ekylibre.themes.each do |theme| stylesheet = "// This files contains #{theme} theme addons from plugins\n\n" each do |plugin| plugin.themes_assets.each do |name, addons| next unless name == theme || name == '*' || (name.respond_to?(:match) && theme.match(name)) stylesheet << "// #{plugin.name}\n" next unless addons[:stylesheets] addons[:stylesheets].each do |file| stylesheet << "@import \"#{file}\";\n" end end end # <base_dir>/themes/<theme>/plugins.scss file = base_dir.join('themes', theme.to_s, 'plugins.scss') FileUtils.mkdir_p file.dirname File.write(file, stylesheet) end end # Run all initializers of plugins def run_initializers each do |plugin| plugin.initializers.each do |name, block| if block.is_a?(Pathname) Rails.logger.info "Require initializer #{name}" require block else Rails.logger.info "Run initialize #{name}" block.call(Rails.application) end end end end def after_login_plugin registered_plugins.values.detect(&:redirect_after_login?) end alias redirect_after_login? after_login_plugin # Call after_login_path on 'after login' plugin def after_login_path(resource) after_login_plugin.name.to_s.camelize.constantize.after_login_path(resource) end end attr_reader :root, :themes_assets, :routes, :javascripts, :initializers field_accessor :name, :summary, :description, :url, :author, :author_url, :version # Links plugin into app def initialize(plugfile_path) @root = Pathname.new(plugfile_path).dirname @view_path = @root.join('app', 'views') @themes_assets = {}.with_indifferent_access @javascripts = [] @initializers = {} lib = @root.join('lib') if File.directory?(lib) $LOAD_PATH.unshift lib ActiveSupport::Dependencies.autoload_paths += [lib] end instance_eval(File.read(plugfile_path), plugfile_path, 1) if @name @name = @name.to_sym else raise "Need a name for plugin #{plugfile_path}" end raise "Plugin name cannot be #{@name}." if [:ekylibre].include?(@name) # Adds lib @lib_dir = @root.join('lib') if @lib_dir.exist? $LOAD_PATH.unshift(@lib_dir.to_s) require @name.to_s unless @required.is_a?(FalseClass) end # Adds rights @right_file = root.join('config', 'rights.yml') Ekylibre::Access.load_file(@right_file) if @right_file.exist? # Adds aggregators @aggregators_path = @root.join('config', 'aggregators') if @aggregators_path.exist? Aggeratio.load_path += Dir.glob(@aggregators_path.join('**', '*.xml')) end # Adds initializers @initializers_path = @root.join('config', 'initializers') if @initializers_path.exist? Dir.glob(@initializers_path.join('**', '*.rb')).each do |file| path = Pathname.new(file) @initializers[path.relative_path_from(@initializers_path).to_s] = path end end # Adds locales (translation and reporting) @locales_path = @root.join('config', 'locales') if @locales_path.exist? Rails.application.config.i18n.load_path += Dir.glob(@locales_path.join('**', '*.{rb,yml}')) DocumentTemplate.load_path << @locales_path end # Adds view path if @view_path.directory? ActionController::Base.prepend_view_path(@view_path) ActionMailer::Base.prepend_view_path(@view_path) end # Adds the app/{controllers,helpers,models} directories of the plugin to the autoload path Dir.glob File.expand_path(@root.join('app', '{controllers,exchangers,guides,helpers,inputs,integrations,jobs,mailers,models}')) do |dir| ActiveSupport::Dependencies.autoload_paths += [dir] $LOAD_PATH.unshift(dir) if Dir.exist?(dir) end # Load all exchanger Dir.glob(@root.join('app', 'exchangers', '**', '*.rb')).each do |path| require path end # Adds the app/{controllers,helpers,models} concerns directories of the plugin to the autoload path Dir.glob File.expand_path(@root.join('app', '{controllers,models}/concerns')) do |dir| ActiveSupport::Dependencies.autoload_paths += [dir] end # Load helpers helpers_path = @root.join('app', 'helpers') Dir.glob File.expand_path(helpers_path.join('**', '*.rb')) do |dir| helper_module = Pathname.new(dir).relative_path_from(helpers_path).to_s.gsub(/\.rb$/, '').camelcase initializer "include helper #{helper_module}" do ::ActionView::Base.send(:include, helper_module.constantize) end end # Adds assets if assets_directory.exist? # Emulate "subdir by plugin" config # plugins/<plugin>/app/assets/*/ => tmp/plugins/assets/*/plugins/<plugin>/ Dir.chdir(assets_directory) do Dir.glob('*') do |type| unless Rails.application.config.assets.paths.include?(assets_directory.join(type).to_s) Rails.application.config.assets.paths << assets_directory.join(type).to_s end unless %w[javascript stylesheets].include? type files_to_compile = Dir[type + '/**/*'].select { |f| File.file? f }.map do |f| Pathname.new(f).relative_path_from(Pathname.new(type)).to_s unless f == type end Rails.application.config.assets.precompile += files_to_compile end end end end end # Accessors def redirect_after_login? @redirect_after_login end # TODO: externalize all following methods in a DSL module def app_version Ekylibre.version end # def gem # end # def plugin # end # Require app version, used for compatibility # app '1.0.0' # app '~> 1.0.0' # app '> 1.0.0' # app '>= 1.0.0', '< 2.0' def app(*requirements) options = requirements.extract_options! requirements.each do |requirement| unless requirement =~ /\A((~>|>=|>|<|<=)\s+)?\d+.\d+(\.[a-z0-9]+)*\z/ raise PluginRequirementError, "Invalid version requirement expression: #{requirement}" end end unless Gem::Requirement.new(*requirements) =~ Gem::Version.create(Ekylibre.version) raise PluginRequirementError, "Plugin (#{@name}) is incompatible with current version of app (#{Ekylibre.version} not #{requirements.inspect})" end true end # Adds a snippet in app (for side or help places) def snippet(name, options = {}) Ekylibre::Snippet.add("#{@name}-#{name}", snippets_directory.join(name.to_s), options) end # Require a JS file from application.js def require_javascript(path) @javascripts << path end # Adds a snippet in app (for side or help places) def add_stylesheet(name) Rails.application.config.assets.precompile << "plugins/#{@name}/#{name}" end # Adds a stylesheet inside a given theme def add_theme_stylesheet(theme, file) add_theme_asset(theme, file, :stylesheets) end # Adds routes to access controllers def add_routes(&block) @routes = block end def add_toolbar_addon(partial_path, options = {}) # Config main toolbar by default because with current tools, no way to specify # which toolbar use when many in the same page. Ekylibre::View::Addon.add(:main_toolbar, partial_path, options) end def add_cobble_addon(partial_path, options = {}) Ekylibre::View::Addon.add(:cobbler, partial_path, options) end # Adds menus with DSL in Ekylibre backend nav def extend_navigation(&block) Ekylibre::Navigation.exec_dsl(&block) end def initializer(name, &block) @initializers[name] = block end def register_manure_management_method(name, class_name) Calculus::ManureManagementPlan.register_method(name, class_name) end def subscribe(message, proc = nil, &block) Ekylibre::Hook.subscribe(message, proc, &block) end # Will call method MyPlugin.after_login_path to get url to redirect to # CAUTION: Only one plugin can use it. Only first plugin will be called # if many are using this directive. def redirect_after_login @redirect_after_login = true end # TODO: Add other callback for plugin integration # def add_cell # end # def add_theme(name) # end private def snippets_directory @view_path.join('snippets') end def assets_directory @root.join('app', 'assets') end def themes_directory @root.join('app', 'themes') end def add_theme_asset(theme, file, type) @themes_assets[theme] ||= {} @themes_assets[theme][type] ||= [] @themes_assets[theme][type] << file end end end
require 'spec_helper' require 'spec/support/test/resource_service' require 'protobuf/rpc/service_directory' describe 'Functional ZMQ Client' do before(:all) do load "protobuf/zmq.rb" @runner = ::Protobuf::Rpc::ZmqRunner.new({ :host => "127.0.0.1", :port => 9399, :worker_port => 9408, :backlog => 100, :threshold => 100, :threads => 5 }) @server_thread = Thread.new(@runner) { |runner| runner.run } Thread.pass until @runner.running? end after(:all) do @runner.stop @server_thread.join end it 'runs fine when required fields are set' do expect { client = ::Test::ResourceService.client client.find(:name => 'Test Name', :active => true) do |c| c.on_success do |succ| succ.name.should eq("Test Name") succ.status.should eq(::Test::StatusType::ENABLED) end c.on_failure do |err| raise err.inspect end end }.to_not raise_error end it 'runs under heavy load' do 100.times do |x| 50.times.map do |y| Thread.new do client = ::Test::ResourceService.client client.find(:name => 'Test Name', :active => true) do |c| c.on_success do |succ| succ.name.should eq("Test Name") succ.status.should eq(::Test::StatusType::ENABLED) end c.on_failure do |err| raise err.inspect end end end end.each(&:join) end end context 'when a message is malformed' do it 'calls the on_failure callback' do error = nil request = ::Test::ResourceFindRequest.new(:active => true) client = ::Test::ResourceService.client client.find(request) do |c| c.on_success { raise "shouldn't pass" } c.on_failure {|e| error = e } end error.message.should match(/name.*required/) end end context 'when the request type is wrong' do it 'calls the on_failure callback' do error = nil request = ::Test::Resource.new(:name => 'Test Name') client = ::Test::ResourceService.client client.find(request) do |c| c.on_success { raise "shouldn't pass" } c.on_failure {|e| error = e} end error.message.should match(/expected request.*ResourceFindRequest.*Resource instead/i) end end context 'when the server takes too long to respond' do it 'responds with a timeout error' do error = nil client = ::Test::ResourceService.client(:timeout => 1) client.find_with_sleep(:sleep => 2) do |c| c.on_success { raise "shouldn't pass" } c.on_failure { |e| error = e } end error.message.should match(/The server repeatedly failed to respond/) end end end Drop heavy load constraints on zmq functional spec require 'spec_helper' require 'spec/support/test/resource_service' require 'protobuf/rpc/service_directory' describe 'Functional ZMQ Client' do before(:all) do load "protobuf/zmq.rb" @runner = ::Protobuf::Rpc::ZmqRunner.new({ :host => "127.0.0.1", :port => 9399, :worker_port => 9408, :backlog => 100, :threshold => 100, :threads => 5 }) @server_thread = Thread.new(@runner) { |runner| runner.run } Thread.pass until @runner.running? end after(:all) do @runner.stop @server_thread.join end it 'runs fine when required fields are set' do expect { client = ::Test::ResourceService.client client.find(:name => 'Test Name', :active => true) do |c| c.on_success do |succ| succ.name.should eq("Test Name") succ.status.should eq(::Test::StatusType::ENABLED) end c.on_failure do |err| raise err.inspect end end }.to_not raise_error end it 'runs under heavy load' do 10.times do |x| 5.times.map do |y| Thread.new do client = ::Test::ResourceService.client client.find(:name => 'Test Name', :active => true) do |c| c.on_success do |succ| succ.name.should eq("Test Name") succ.status.should eq(::Test::StatusType::ENABLED) end c.on_failure do |err| raise err.inspect end end end end.each(&:join) end end context 'when a message is malformed' do it 'calls the on_failure callback' do error = nil request = ::Test::ResourceFindRequest.new(:active => true) client = ::Test::ResourceService.client client.find(request) do |c| c.on_success { raise "shouldn't pass" } c.on_failure {|e| error = e } end error.message.should match(/name.*required/) end end context 'when the request type is wrong' do it 'calls the on_failure callback' do error = nil request = ::Test::Resource.new(:name => 'Test Name') client = ::Test::ResourceService.client client.find(request) do |c| c.on_success { raise "shouldn't pass" } c.on_failure {|e| error = e} end error.message.should match(/expected request.*ResourceFindRequest.*Resource instead/i) end end context 'when the server takes too long to respond' do it 'responds with a timeout error' do error = nil client = ::Test::ResourceService.client(:timeout => 1) client.find_with_sleep(:sleep => 2) do |c| c.on_success { raise "shouldn't pass" } c.on_failure { |e| error = e } end error.message.should match(/The server repeatedly failed to respond/) end end end
require 'spec_helper' module GoogleBooks module API describe Book do use_vcr_cassette 'google' subject { API.search('isbn:9781935182320').first } let(:item) do item = { 'volumeInfo' => {} } end it "should be able to handle a nil object passed" do lambda { Book.new(nil) }.should_not raise_error end it "should have a title" do subject.title.should eq "JQuery in Action" end it "should have an id" do subject.id.should eq "rokQngEACAAJ" end end it "should contain a subtitle in the title if there is one" do book = API.search('isbn:9780596517748').first book.title.should eq 'JavaScript: The Good Parts' end it "should have an array of authors with the correct names" do subject.authors.length.should eq 2 subject.authors[0].should eq "Bear Bibeault" subject.authors[1].should eq "Yehuda Katz" end describe "publisher" do it "should have a publisher" do subject.publisher.should_not be_nil subject.publisher.should include "Manning" end it "should standardize an Inc to Inc." do item['volumeInfo']['publisher'] = "Publisher Inc" book = Book.new(item) book.publisher.should eq "Publisher Inc." end it "should standardize an Llc to LLC." do item['volumeInfo']['publisher'] = "Publisher Llc" book = Book.new(item) book.publisher.should eq "Publisher LLC." end it "should standardize an Ltd to Ltd." do item['volumeInfo']['publisher'] = "Publisher Ltd" book = Book.new(item) book.publisher.should eq "Publisher Ltd." end it "should replace Intl with International anywhere in the name" do item['volumeInfo']['publisher'] = "Publisher Intl Clearing House" book = Book.new(item) book.publisher.should eq "Publisher International Clearing House" end it "should replace Pr with Press anywhere in the name" do item['volumeInfo']['publisher'] = "Publisher Pr House" book = Book.new(item) book.publisher.should eq "Publisher Press House" end it "should replace Pub with Publishers anywhere in the name" do item['volumeInfo']['publisher'] = "Publisher Pub, Inc" book = Book.new(item) book.publisher.should eq "Publisher Publishers Inc." end it "should replace Pubns with Publications anywhere in the name" do item['volumeInfo']['publisher'] = "Publisher Pubns Inc" book = Book.new(item) book.publisher.should eq "Publisher Publications Inc." end it "should replace Pub Group with Publishing Group anywhere in the name" do item['volumeInfo']['publisher'] = "Publisher Pub Group Inc" book = Book.new(item) book.publisher.should eq "Publisher Publishing Group Inc." end it "should replace Univ with University anywhere in the name" do item['volumeInfo']['publisher'] = "Publisher Univ Pr" book = Book.new(item) book.publisher.should eq "Publisher University Press" end it "should handle strings with apostrophes" do item['volumeInfo']['publisher'] = "O'Reilly Media, Inc." book = Book.new(item) book.publisher.should eq "O'Reilly Media Inc." end end describe "published_date" do it "should have a published date in sting format" do subject.published_date.should eq "2010-06-30" end it "should handle a published date that is only a year" do book = API.search('isbn:9781934356166').first book.published_date.should eq "2009" end # NOTE: This test was removed because this book no longer has just a month and year in Google's DB # It returns 2003-01-01. They may have added the first day of the month as a default for these dates # The spec is here for history, and in case a two digit date arises # it "should handle a published date that is only a month and a year" do # book = API.search('isbn:9780954344405').first # book.published_date.should eq "2003-01" # end end it "should have description (which may be blank)" do subject.description.should_not be_nil end it "should have an ISBN (13)" do subject.isbn.should eq '9781935182320' end it "should have an ISBN 10" do subject.isbn_10.should eq '1935182323' end it "should have a page count" do subject.page_count.should be_a Fixnum subject.page_count.should eq 452 end it "should have categories even if there aren't any" do subject.categories.should be_an Array end it "should fill in categories" do book = API.search('isbn:9780596517748').first book.categories.first.should eq "Computers" end it "should have an average rating" do subject.average_rating.should be_a Float end it "should have an ratings count" do subject.ratings_count.should be_a Fixnum end describe "covers" do it "should contain a covers hash" do subject.covers.should be_a Hash subject.covers.keys.should include :thumbnail subject.covers.keys.should include :small subject.covers.keys.should include :medium subject.covers.keys.should include :large subject.covers.keys.should include :extra_large end it "should not have curls on the cover urls" do subject.covers[:thumbnail].should_not include 'edge=curl' subject.covers[:small].should_not include 'edge=curl' subject.covers[:medium].should_not include 'edge=curl' subject.covers[:large].should_not include 'edge=curl' subject.covers[:extra_large].should_not include 'edge=curl' end it "should have the cover url zoom level" do subject.covers[:thumbnail].should include 'zoom=5' subject.covers[:small].should include 'zoom=1' subject.covers[:medium].should include 'zoom=2' subject.covers[:large].should include 'zoom=3' subject.covers[:extra_large].should include 'zoom=6' end end it "should contains a preview link" do subject.preview_link.should_not be_nil end it "should contains an info link" do subject.info_link.should_not be_nil end end end end Remove useless specs for published_date publishedDate will be always a string, and Book object only cast to string, no need to have different specs require 'spec_helper' module GoogleBooks module API describe Book do use_vcr_cassette 'google' subject { API.search('isbn:9781935182320').first } let(:item) do item = { 'volumeInfo' => {} } end it "should be able to handle a nil object passed" do lambda { Book.new(nil) }.should_not raise_error end it "should have a title" do subject.title.should eq "JQuery in Action" end it "should have an id" do subject.id.should eq "rokQngEACAAJ" end it "should have a published_date" do subject.published_date.should eq "2010" end it "should contain a subtitle in the title if there is one" do book = API.search('isbn:9780596517748').first book.title.should eq 'JavaScript: The Good Parts' end it "should have an array of authors with the correct names" do subject.authors.length.should eq 2 subject.authors[0].should eq "Bear Bibeault" subject.authors[1].should eq "Yehuda Katz" end describe "publisher" do it "should have a publisher" do subject.publisher.should_not be_nil subject.publisher.should include "Manning" end it "should standardize an Inc to Inc." do item['volumeInfo']['publisher'] = "Publisher Inc" book = Book.new(item) book.publisher.should eq "Publisher Inc." end it "should standardize an Llc to LLC." do item['volumeInfo']['publisher'] = "Publisher Llc" book = Book.new(item) book.publisher.should eq "Publisher LLC." end it "should standardize an Ltd to Ltd." do item['volumeInfo']['publisher'] = "Publisher Ltd" book = Book.new(item) book.publisher.should eq "Publisher Ltd." end it "should replace Intl with International anywhere in the name" do item['volumeInfo']['publisher'] = "Publisher Intl Clearing House" book = Book.new(item) book.publisher.should eq "Publisher International Clearing House" end it "should replace Pr with Press anywhere in the name" do item['volumeInfo']['publisher'] = "Publisher Pr House" book = Book.new(item) book.publisher.should eq "Publisher Press House" end it "should replace Pub with Publishers anywhere in the name" do item['volumeInfo']['publisher'] = "Publisher Pub, Inc" book = Book.new(item) book.publisher.should eq "Publisher Publishers Inc." end it "should replace Pubns with Publications anywhere in the name" do item['volumeInfo']['publisher'] = "Publisher Pubns Inc" book = Book.new(item) book.publisher.should eq "Publisher Publications Inc." end it "should replace Pub Group with Publishing Group anywhere in the name" do item['volumeInfo']['publisher'] = "Publisher Pub Group Inc" book = Book.new(item) book.publisher.should eq "Publisher Publishing Group Inc." end it "should replace Univ with University anywhere in the name" do item['volumeInfo']['publisher'] = "Publisher Univ Pr" book = Book.new(item) book.publisher.should eq "Publisher University Press" end it "should handle strings with apostrophes" do item['volumeInfo']['publisher'] = "O'Reilly Media, Inc." book = Book.new(item) book.publisher.should eq "O'Reilly Media Inc." end end it "should have description (which may be blank)" do subject.description.should_not be_nil end it "should have an ISBN (13)" do subject.isbn.should eq '9781935182320' end it "should have an ISBN 10" do subject.isbn_10.should eq '1935182323' end it "should have a page count" do subject.page_count.should be_a Fixnum subject.page_count.should eq 452 end it "should have categories even if there aren't any" do subject.categories.should be_an Array end it "should fill in categories" do book = API.search('isbn:9780596517748').first book.categories.first.should eq "Computers" end it "should have an average rating" do subject.average_rating.should be_a Float end it "should have an ratings count" do subject.ratings_count.should be_a Fixnum end describe "covers" do it "should contain a covers hash" do subject.covers.should be_a Hash subject.covers.keys.should include :thumbnail subject.covers.keys.should include :small subject.covers.keys.should include :medium subject.covers.keys.should include :large subject.covers.keys.should include :extra_large end it "should not have curls on the cover urls" do subject.covers[:thumbnail].should_not include 'edge=curl' subject.covers[:small].should_not include 'edge=curl' subject.covers[:medium].should_not include 'edge=curl' subject.covers[:large].should_not include 'edge=curl' subject.covers[:extra_large].should_not include 'edge=curl' end it "should have the cover url zoom level" do subject.covers[:thumbnail].should include 'zoom=5' subject.covers[:small].should include 'zoom=1' subject.covers[:medium].should include 'zoom=2' subject.covers[:large].should include 'zoom=3' subject.covers[:extra_large].should include 'zoom=6' end end it "should contains a preview link" do subject.preview_link.should_not be_nil end it "should contains an info link" do subject.info_link.should_not be_nil end end end end
require "formula" class JujuQuickstart < Formula homepage "https://launchpad.net/juju-quickstart" url "https://pypi.python.org/packages/source/j/juju-quickstart/juju-quickstart-2.1.0.tar.gz" sha1 "33f6b8abb157edffa802f7c756f1d78e607ad892" bottle do cellar :any sha256 "c5ffca2b77a5a2375cae07ce5b947b380155600d7f9f4b4e2c90094c9001c37e" => :yosemite sha256 "bcd29dbf01e04b48a1d976a5a0348e52aac4a242f6c2b675ae4c76ab724deb31" => :mavericks sha256 "3031583c25dd80d6c637c25819475dd2c000e190edb46949c3c2064a0b0e50ad" => :mountain_lion end depends_on :python if MacOS.version <= :snow_leopard depends_on "juju" def install ENV.prepend_create_path 'PYTHONPATH', libexec+'lib/python2.7/site-packages' system "python", "setup.py", "install", "--prefix=#{libexec}" bin.install Dir[libexec/'bin/juju-quickstart'] bin.env_script_all_files(libexec+'bin', :PYTHONPATH => ENV['PYTHONPATH']) end test do # While a --version test is noted to be a "bad" test it does # exercise that most of the packages can be imported, so it is # better than nothing. Can't really test the spinning up of Juju # environments on ec2 as part of installation, given that would # cost real money. system "#{bin}/juju-quickstart", "--version" end end juju-quickstart 2.1.1 Closes #39710. Signed-off-by: Brett Koonce <cbb63d51fa8fe93df04ca2da488d36daa92d0c44@gmail.com> require "formula" class JujuQuickstart < Formula homepage "https://launchpad.net/juju-quickstart" url "https://pypi.python.org/packages/source/j/juju-quickstart/juju-quickstart-2.1.1.tar.gz" sha1 "7743605cba0c41bab940ac9c03485ef087627327" bottle do cellar :any sha256 "c5ffca2b77a5a2375cae07ce5b947b380155600d7f9f4b4e2c90094c9001c37e" => :yosemite sha256 "bcd29dbf01e04b48a1d976a5a0348e52aac4a242f6c2b675ae4c76ab724deb31" => :mavericks sha256 "3031583c25dd80d6c637c25819475dd2c000e190edb46949c3c2064a0b0e50ad" => :mountain_lion end depends_on :python if MacOS.version <= :snow_leopard depends_on "juju" def install ENV.prepend_create_path 'PYTHONPATH', libexec+'lib/python2.7/site-packages' system "python", "setup.py", "install", "--prefix=#{libexec}" bin.install Dir[libexec/'bin/juju-quickstart'] bin.env_script_all_files(libexec+'bin', :PYTHONPATH => ENV['PYTHONPATH']) end test do # While a --version test is noted to be a "bad" test it does # exercise that most of the packages can be imported, so it is # better than nothing. Can't really test the spinning up of Juju # environments on ec2 as part of installation, given that would # cost real money. system "#{bin}/juju-quickstart", "--version" end end
require 'fileutils' # Handle Emailed Entries class EmailProcessor def initialize(email) @token = pick_meaningful_recipient(email.to, email.cc) @from = email.from[:email].downcase @subject = email.subject email.body.gsub!(/src=\"data\:image\/(jpeg|png)\;base64\,.*\"/, "src=\"\"") if email.body.present? email.body.gsub!(/url\(data\:image\/(jpeg|png)\;base64\,.*\)/, "url()") if email.body.present? email.raw_body.gsub!(/src=\"data\:image\/(jpeg|png)\;base64\,.*\"/, "src=\"\"") if email.raw_body.present? email.raw_body.gsub!(/url\(data\:image\/(jpeg|png)\;base64\,.*\)/, "url()") if email.raw_body.present? if email.raw_body.present? && email.raw_body.ascii_only? && email.body.ascii_only? @body = EmailReplyTrimmer.trim(email.body) else @body = email.body end @raw_body = email.raw_body @attachments = email.attachments @user = find_user_from_user_key(@token, @from) end def process unless @user.present? Sqreen.track('inbound_email_without_user') return false end if @user.is_admin? Rails.logger.warn("Email QA: #{@raw_body}") end best_attachment = nil if @user.is_pro? && @attachments.present? @attachments.each do |attachment| # Make sure attachments are at least 8kb so we're not saving a bunch of signuture/footer images file_size = File.size?(attachment.tempfile).to_i if @user.is_admin? Rails.logger.warn("Attachment QA: #{attachment.content_type} // #{file_size} // #{attachment.original_filename} // #{attachment.inspect}") end if (attachment.content_type == "application/octet-stream" || attachment.content_type =~ /^image\/(png|jpe?g|gif|heic)$/i || attachment.original_filename =~ /^.+\.(heic|HEIC|Heic)$/i) && (file_size <= 0 || file_size > 8000) best_attachment = attachment break end end end @body.gsub!(/\n\n\n/, "\n\n \n\n") # allow double line breaks @body = unfold_paragraphs(@body) unless @from.include?('yahoo.com') # fix wrapped plain text, but yahoo messes this up @body.gsub!(/(?:\n\r?|\r\n?)/, '<br>') # convert line breaks @body = "<p>#{@body}</p>" # basic formatting @body.gsub!(/\*(.+?)\*/i, '<b>\1</b>') # bold when bold needed @body.gsub!(/<(http[s]?:\/\/\S+)>/, "(\\1)") # convert links to show up @body.gsub!(/\[image\:\ Inline\ image\ [0-9]{1,2}\]/, '') # remove "inline image" text @body.gsub!(/\[image\:\ (.+)\.[a-zA-Z]{3,4}\](<br>)?/, '') # remove "inline image" text date = parse_subject_for_date(@subject) existing_entry = @user.existing_entry(date.to_s) inspiration_id = parse_body_for_inspiration_id(@raw_body) if existing_entry.present? existing_entry.body += "<hr>#{@body}" existing_entry.body = existing_entry.sanitized_body if @user.is_free? existing_entry.original_email_body = @raw_body existing_entry.inspiration_id = inspiration_id if inspiration_id.present? if existing_entry.image_url_cdn.blank? && best_attachment.present? existing_entry.image = best_attachment end begin existing_entry.save rescue existing_entry.body = existing_entry.body.force_encoding('iso-8859-1').encode('utf-8') existing_entry.original_email_body = existing_entry.original_email_body.force_encoding('iso-8859-1').encode('utf-8') existing_entry.save end track_ga_event('Merged') else begin entry = @user.entries.create!( date: date, body: @body, image: best_attachment, original_email_body: @raw_body, inspiration_id: inspiration_id ) rescue @body = @body.force_encoding('iso-8859-1').encode('utf-8') @raw_body = @raw_body.force_encoding('iso-8859-1').encode('utf-8') entry = @user.entries.create!( date: date, body: @body, image: best_attachment, original_email_body: @raw_body, inspiration_id: inspiration_id ) end entry.body = entry.sanitized_body if @user.is_free? entry.save track_ga_event('New') Sqreen.track('inbound_email') end @user.increment!(:emails_received) begin UserMailer.second_welcome_email(@user).deliver_later if @user.emails_received == 1 && @user.entries.count == 1 rescue StandardError => e Rails.logger.warn("Error sending second welcome email to #{@user.email}: #{e}") end end private def track_ga_event(action) if ENV['GOOGLE_ANALYTICS_ID'].present? tracker = Staccato.tracker(ENV['GOOGLE_ANALYTICS_ID']) tracker.event(category: 'Email Entry', action: action, label: @user.user_key) end end def pick_meaningful_recipient(to_recipients, cc_recipients) host_to = to_recipients.select {|k| k[:host] =~ /^(email|post)?\.?#{ENV['MAIN_DOMAIN'].gsub(".","\.")}$/i }.first if host_to.present? host_to[:token] elsif cc_recipients.present? # try CC's host_cc = cc_recipients.select {|k| k[:host] =~ /^(email|post)?\.?#{ENV['MAIN_DOMAIN'].gsub(".","\.")}$/i }.first host_cc[:token] if host_cc.present? end end def find_user_from_user_key(to_token, from_email) begin user = User.find_by user_key: to_token rescue JSON::ParserError => e end user.blank? ? User.find_by(email: from_email) : user end def parse_subject_for_date(subject) # Find the date from the subject "It's Sept 2. How was your day?" and figure out the best year now = Time.now.in_time_zone(@user.send_timezone) parsed_date = Time.parse(subject) rescue now dates = [parsed_date, parsed_date.prev_year] dates_to_use = [] dates.each do |d| dates_to_use << d if Time.now + 7.days - d > 0 end if dates_to_use.blank? now.strftime('%Y-%m-%d') else dates_to_use.min_by { |d| (d - now).abs }.strftime('%Y-%m-%d') end end def unfold_paragraphs(body) text = '' body.split(/\n/).each do |line| if /\S/ !~ line text << "\n\n" else if line.length < 60 || /^(\s+|[*])/ =~ line text << (line.rstrip + "\n") else text << (line.rstrip + ' ') end end end text.gsub("\n\n\n", "\n\n") end def parse_body_for_inspiration_id(raw_body) inspiration_id = nil begin Inspiration.without_imports_or_email_or_tips.each do |inspiration| if raw_body.include? inspiration.body.first(71) inspiration_id = inspiration.id break end end rescue end inspiration_id end end Remove QA check require 'fileutils' # Handle Emailed Entries class EmailProcessor def initialize(email) @token = pick_meaningful_recipient(email.to, email.cc) @from = email.from[:email].downcase @subject = email.subject email.body.gsub!(/src=\"data\:image\/(jpeg|png)\;base64\,.*\"/, "src=\"\"") if email.body.present? email.body.gsub!(/url\(data\:image\/(jpeg|png)\;base64\,.*\)/, "url()") if email.body.present? email.raw_body.gsub!(/src=\"data\:image\/(jpeg|png)\;base64\,.*\"/, "src=\"\"") if email.raw_body.present? email.raw_body.gsub!(/url\(data\:image\/(jpeg|png)\;base64\,.*\)/, "url()") if email.raw_body.present? if email.raw_body.present? && email.raw_body.ascii_only? && email.body.ascii_only? @body = EmailReplyTrimmer.trim(email.body) else @body = email.body end @raw_body = email.raw_body @attachments = email.attachments @user = find_user_from_user_key(@token, @from) end def process unless @user.present? Sqreen.track('inbound_email_without_user') return false end best_attachment = nil if @user.is_pro? && @attachments.present? @attachments.each do |attachment| # Make sure attachments are at least 8kb so we're not saving a bunch of signuture/footer images file_size = File.size?(attachment.tempfile).to_i if (attachment.content_type == "application/octet-stream" || attachment.content_type =~ /^image\/(png|jpe?g|gif|heic)$/i || attachment.original_filename =~ /^.+\.(heic|HEIC|Heic)$/i) && (file_size <= 0 || file_size > 8000) best_attachment = attachment break end end end @body.gsub!(/\n\n\n/, "\n\n \n\n") # allow double line breaks @body = unfold_paragraphs(@body) unless @from.include?('yahoo.com') # fix wrapped plain text, but yahoo messes this up @body.gsub!(/(?:\n\r?|\r\n?)/, '<br>') # convert line breaks @body = "<p>#{@body}</p>" # basic formatting @body.gsub!(/\*(.+?)\*/i, '<b>\1</b>') # bold when bold needed @body.gsub!(/<(http[s]?:\/\/\S+)>/, "(\\1)") # convert links to show up @body.gsub!(/\[image\:\ Inline\ image\ [0-9]{1,2}\]/, '') # remove "inline image" text @body.gsub!(/\[image\:\ (.+)\.[a-zA-Z]{3,4}\](<br>)?/, '') # remove "inline image" text date = parse_subject_for_date(@subject) existing_entry = @user.existing_entry(date.to_s) inspiration_id = parse_body_for_inspiration_id(@raw_body) if existing_entry.present? existing_entry.body += "<hr>#{@body}" existing_entry.body = existing_entry.sanitized_body if @user.is_free? existing_entry.original_email_body = @raw_body existing_entry.inspiration_id = inspiration_id if inspiration_id.present? if existing_entry.image_url_cdn.blank? && best_attachment.present? existing_entry.image = best_attachment end begin existing_entry.save rescue existing_entry.body = existing_entry.body.force_encoding('iso-8859-1').encode('utf-8') existing_entry.original_email_body = existing_entry.original_email_body.force_encoding('iso-8859-1').encode('utf-8') existing_entry.save end track_ga_event('Merged') else begin entry = @user.entries.create!( date: date, body: @body, image: best_attachment, original_email_body: @raw_body, inspiration_id: inspiration_id ) rescue @body = @body.force_encoding('iso-8859-1').encode('utf-8') @raw_body = @raw_body.force_encoding('iso-8859-1').encode('utf-8') entry = @user.entries.create!( date: date, body: @body, image: best_attachment, original_email_body: @raw_body, inspiration_id: inspiration_id ) end entry.body = entry.sanitized_body if @user.is_free? entry.save track_ga_event('New') Sqreen.track('inbound_email') end @user.increment!(:emails_received) begin UserMailer.second_welcome_email(@user).deliver_later if @user.emails_received == 1 && @user.entries.count == 1 rescue StandardError => e Rails.logger.warn("Error sending second welcome email to #{@user.email}: #{e}") end end private def track_ga_event(action) if ENV['GOOGLE_ANALYTICS_ID'].present? tracker = Staccato.tracker(ENV['GOOGLE_ANALYTICS_ID']) tracker.event(category: 'Email Entry', action: action, label: @user.user_key) end end def pick_meaningful_recipient(to_recipients, cc_recipients) host_to = to_recipients.select {|k| k[:host] =~ /^(email|post)?\.?#{ENV['MAIN_DOMAIN'].gsub(".","\.")}$/i }.first if host_to.present? host_to[:token] elsif cc_recipients.present? # try CC's host_cc = cc_recipients.select {|k| k[:host] =~ /^(email|post)?\.?#{ENV['MAIN_DOMAIN'].gsub(".","\.")}$/i }.first host_cc[:token] if host_cc.present? end end def find_user_from_user_key(to_token, from_email) begin user = User.find_by user_key: to_token rescue JSON::ParserError => e end user.blank? ? User.find_by(email: from_email) : user end def parse_subject_for_date(subject) # Find the date from the subject "It's Sept 2. How was your day?" and figure out the best year now = Time.now.in_time_zone(@user.send_timezone) parsed_date = Time.parse(subject) rescue now dates = [parsed_date, parsed_date.prev_year] dates_to_use = [] dates.each do |d| dates_to_use << d if Time.now + 7.days - d > 0 end if dates_to_use.blank? now.strftime('%Y-%m-%d') else dates_to_use.min_by { |d| (d - now).abs }.strftime('%Y-%m-%d') end end def unfold_paragraphs(body) text = '' body.split(/\n/).each do |line| if /\S/ !~ line text << "\n\n" else if line.length < 60 || /^(\s+|[*])/ =~ line text << (line.rstrip + "\n") else text << (line.rstrip + ' ') end end end text.gsub("\n\n\n", "\n\n") end def parse_body_for_inspiration_id(raw_body) inspiration_id = nil begin Inspiration.without_imports_or_email_or_tips.each do |inspiration| if raw_body.include? inspiration.body.first(71) inspiration_id = inspiration.id break end end rescue end inspiration_id end end
# frozen_string_literal: true require "spec_helper" class InMemoryBackend class Subscriptions < GraphQL::Subscriptions attr_reader :deliveries, :pushes, :extra, :queries, :events def initialize(schema:, extra:, **rest) super @extra = extra @queries = {} # { topic => { fingerprint => [sub_id, ... ] } } @events = Hash.new { |h,k| h[k] = Hash.new { |h2, k2| h2[k2] = [] } } @deliveries = Hash.new { |h, k| h[k] = [] } @pushes = [] end def write_subscription(query, events) subscription_id = query.context[:subscription_id] = build_id @queries[subscription_id] = query events.each do |ev| @events[ev.topic][ev.fingerprint] << subscription_id end end def each_subscription_id(event) @events[event.topic].each do |fp, sub_ids| sub_ids.each do |sub_id| yield(sub_id) end end end def read_subscription(subscription_id) query = @queries[subscription_id] if query { query_string: query.query_string, operation_name: query.operation_name, variables: query.provided_variables, context: { me: query.context[:me] }, transport: :socket, } else nil end end def delete_subscription(subscription_id) query = @queries.delete(subscription_id) @events.each do |topic, sub_ids_by_fp| sub_ids_by_fp.each do |fp, sub_ids| sub_ids.delete(subscription_id) if sub_ids.empty? sub_ids_by_fp.delete(fp) if sub_ids_by_fp.empty? @events.delete(topic) end end end end end def execute_all(event, object) topic = event.topic sub_ids_by_fp = @events[topic] sub_ids_by_fp.each do |fingerprint, sub_ids| result = execute_update(sub_ids.first, event, object) sub_ids.each do |sub_id| deliver(sub_id, result) end end end def deliver(subscription_id, result) query = @queries[subscription_id] socket = query.context[:socket] || subscription_id @deliveries[socket] << result end def execute_update(subscription_id, event, object) query = @queries[subscription_id] if query @pushes << query.context[:socket] end super end # Just for testing: def reset @queries.clear @events.clear @deliveries.clear @pushes.clear end end # Just a random stateful object for tracking what happens: class SubscriptionPayload attr_reader :str def initialize @str = "Update" @counter = 0 end def int @counter += 1 end end end class ClassBasedInMemoryBackend < InMemoryBackend class Payload < GraphQL::Schema::Object field :str, String, null: false field :int, Integer, null: false end class PayloadType < GraphQL::Schema::Enum graphql_name "PayloadType" # Arbitrary "kinds" of payloads which may be # subscribed to separately value "ONE" value "TWO" end class StreamInput < GraphQL::Schema::InputObject argument :user_id, ID, required: true, camelize: false argument :payload_type, PayloadType, required: false, default_value: "ONE", prepare: ->(e, ctx) { e ? e.downcase : e } end class EventSubscription < GraphQL::Schema::Subscription argument :user_id, ID, required: true argument :payload_type, PayloadType, required: false, default_value: "ONE", prepare: ->(e, ctx) { e ? e.downcase : e } field :payload, Payload, null: true end class Subscription < GraphQL::Schema::Object if !TESTING_INTERPRETER # Stub methods are required [:payload, :event, :my_event].each do |m| define_method(m) { |*a| nil } end end field :payload, Payload, null: false do argument :id, ID, required: true end field :event, Payload, null: true do argument :stream, StreamInput, required: false end field :event_subscription, subscription: EventSubscription field :my_event, Payload, null: true, subscription_scope: :me do argument :payload_type, PayloadType, required: false end field :failed_event, Payload, null: false do argument :id, ID, required: true end def failed_event(id:) raise GraphQL::ExecutionError.new("unauthorized") end end class Query < GraphQL::Schema::Object field :dummy, Integer, null: true end class Schema < GraphQL::Schema query(Query) subscription(Subscription) use InMemoryBackend::Subscriptions, extra: 123 if TESTING_INTERPRETER use GraphQL::Execution::Interpreter use GraphQL::Analysis::AST end end end class FromDefinitionInMemoryBackend < InMemoryBackend SchemaDefinition = <<-GRAPHQL type Subscription { payload(id: ID!): Payload! event(stream: StreamInput): Payload eventSubscription(userId: ID, payloadType: PayloadType = ONE): EventSubscriptionPayload myEvent(payloadType: PayloadType): Payload failedEvent(id: ID!): Payload! } type Payload { str: String! int: Int! } type EventSubscriptionPayload { payload: Payload } input StreamInput { user_id: ID! payloadType: PayloadType = ONE } # Arbitrary "kinds" of payloads which may be # subscribed to separately enum PayloadType { ONE TWO } type Query { dummy: Int } GRAPHQL DEFAULT_SUBSCRIPTION_RESOLVE = ->(o,a,c) { if c.query.subscription_update? o else c.skip end } Resolvers = { "Subscription" => { "payload" => DEFAULT_SUBSCRIPTION_RESOLVE, "myEvent" => DEFAULT_SUBSCRIPTION_RESOLVE, "event" => DEFAULT_SUBSCRIPTION_RESOLVE, "eventSubscription" => ->(o,a,c) { nil }, "failedEvent" => ->(o,a,c) { raise GraphQL::ExecutionError.new("unauthorized") }, }, } Schema = GraphQL::Schema.from_definition(SchemaDefinition, default_resolve: Resolvers, using: {InMemoryBackend::Subscriptions => { extra: 123 }}, interpreter: TESTING_INTERPRETER) # TODO don't hack this (no way to add metadata from IDL parser right now) Schema.get_field("Subscription", "myEvent").subscription_scope = :me end class ToParamUser def initialize(id) @id = id end def to_param @id end end describe GraphQL::Subscriptions do before do schema.subscriptions.reset end [ClassBasedInMemoryBackend, FromDefinitionInMemoryBackend].each do |in_memory_backend_class| describe "using #{in_memory_backend_class}" do let(:root_object) { OpenStruct.new( payload: in_memory_backend_class::SubscriptionPayload.new, ) } let(:schema) { in_memory_backend_class::Schema } let(:implementation) { schema.subscriptions } let(:deliveries) { implementation.deliveries } let(:subscriptions_by_topic) { implementation.events.each_with_object({}) do |(k, v), obj| obj[k] = v.size end } describe "pushing updates" do it "sends updated data" do query_str = <<-GRAPHQL subscription ($id: ID!){ firstPayload: payload(id: $id) { str, int } otherPayload: payload(id: "900") { int } } GRAPHQL # Initial subscriptions res_1 = schema.execute(query_str, context: { socket: "1" }, variables: { "id" => "100" }, root_value: root_object) res_2 = schema.execute(query_str, context: { socket: "2" }, variables: { "id" => "200" }, root_value: root_object) empty_response = TESTING_INTERPRETER ? {} : nil # Initial response is nil, no broadcasts yet assert_equal(empty_response, res_1["data"]) assert_equal(empty_response, res_2["data"]) assert_equal [], deliveries["1"] assert_equal [], deliveries["2"] # Application stuff happens. # The application signals graphql via `subscriptions.trigger`: schema.subscriptions.trigger(:payload, {"id" => "100"}, root_object.payload) schema.subscriptions.trigger("payload", {"id" => "200"}, root_object.payload) # Symbols are OK too schema.subscriptions.trigger(:payload, {:id => "100"}, root_object.payload) schema.subscriptions.trigger("payload", {"id" => "300"}, nil) # Let's see what GraphQL sent over the wire: assert_equal({"str" => "Update", "int" => 1}, deliveries["1"][0]["data"]["firstPayload"]) assert_equal({"str" => "Update", "int" => 2}, deliveries["2"][0]["data"]["firstPayload"]) assert_equal({"str" => "Update", "int" => 3}, deliveries["1"][1]["data"]["firstPayload"]) end end it "sends updated data for multifield subscriptions" do query_str = <<-GRAPHQL subscription ($id: ID!){ payload(id: $id) { str, int } event { int } } GRAPHQL # Initial subscriptions res = schema.execute(query_str, context: { socket: "1" }, variables: { "id" => "100" }, root_value: root_object) empty_response = TESTING_INTERPRETER ? {} : nil # Initial response is nil, no broadcasts yet assert_equal(empty_response, res["data"]) assert_equal [], deliveries["1"] # Application stuff happens. # The application signals graphql via `subscriptions.trigger`: schema.subscriptions.trigger(:payload, {"id" => "100"}, root_object.payload) # Let's see what GraphQL sent over the wire: assert_equal({"str" => "Update", "int" => 1}, deliveries["1"][0]["data"]["payload"]) assert_equal(nil, deliveries["1"][0]["data"]["event"]) if TESTING_INTERPRETER # double-subscriptions is broken on the old runtime # Trigger another field subscription schema.subscriptions.trigger(:event, {}, OpenStruct.new(int: 1)) # Now we should get result for another field assert_equal(nil, deliveries["1"][1]["data"]["payload"]) assert_equal({"int" => 1}, deliveries["1"][1]["data"]["event"]) end end describe "passing a document into #execute" do it "sends the updated data" do query_str = <<-GRAPHQL subscription ($id: ID!){ payload(id: $id) { str, int } } GRAPHQL document = GraphQL.parse(query_str) # Initial subscriptions response = schema.execute(nil, document: document, context: { socket: "1" }, variables: { "id" => "100" }, root_value: root_object) empty_response = TESTING_INTERPRETER ? {} : nil # Initial response is empty, no broadcasts yet assert_equal(empty_response, response["data"]) assert_equal [], deliveries["1"] # Application stuff happens. # The application signals graphql via `subscriptions.trigger`: schema.subscriptions.trigger(:payload, {"id" => "100"}, root_object.payload) # Symbols are OK too schema.subscriptions.trigger(:payload, {:id => "100"}, root_object.payload) schema.subscriptions.trigger("payload", {"id" => "300"}, nil) # Let's see what GraphQL sent over the wire: assert_equal({"str" => "Update", "int" => 1}, deliveries["1"][0]["data"]["payload"]) assert_equal({"str" => "Update", "int" => 2}, deliveries["1"][1]["data"]["payload"]) end end describe "subscribing" do it "doesn't call the subscriptions for invalid queries" do query_str = <<-GRAPHQL subscription ($id: ID){ payload(id: $id) { str, int } } GRAPHQL res = schema.execute(query_str, context: { socket: "1" }, variables: { "id" => "100" }, root_value: root_object) assert_equal true, res.key?("errors") assert_equal 0, implementation.events.size assert_equal 0, implementation.queries.size end end describe "trigger" do let(:error_payload_class) { Class.new { def int raise "Boom!" end def str raise GraphQL::ExecutionError.new("This is handled") end } } it "uses the provided queue" do query_str = <<-GRAPHQL subscription ($id: ID!){ payload(id: $id) { str, int } } GRAPHQL schema.execute(query_str, context: { socket: "1" }, variables: { "id" => "8" }, root_value: root_object) schema.subscriptions.trigger("payload", { "id" => "8"}, root_object.payload) assert_equal ["1"], implementation.pushes end it "pushes errors" do query_str = <<-GRAPHQL subscription ($id: ID!){ payload(id: $id) { str, int } } GRAPHQL schema.execute(query_str, context: { socket: "1" }, variables: { "id" => "8" }, root_value: root_object) schema.subscriptions.trigger("payload", { "id" => "8"}, OpenStruct.new(str: nil, int: nil)) delivery = deliveries["1"].first assert_nil delivery.fetch("data") assert_equal 1, delivery["errors"].length end it "unsubscribes when `read_subscription` returns nil" do query_str = <<-GRAPHQL subscription ($id: ID!){ payload(id: $id) { str, int } } GRAPHQL schema.execute(query_str, context: { socket: "1" }, variables: { "id" => "8" }, root_value: root_object) assert_equal 1, implementation.events.size sub_id = implementation.queries.keys.first # Mess with the private storage so that `read_subscription` will be nil implementation.queries.delete(sub_id) assert_equal 1, implementation.events.size assert_nil implementation.read_subscription(sub_id) # The trigger should clean up the lingering subscription: schema.subscriptions.trigger("payload", { "id" => "8"}, OpenStruct.new(str: nil, int: nil)) assert_equal 0, implementation.events.size assert_equal 0, implementation.queries.size end it "coerces args" do query_str = <<-GRAPHQL subscription($type: PayloadType) { e1: event(stream: { user_id: "3", payloadType: $type }) { int } } GRAPHQL # Subscribe with explicit `TYPE` schema.execute(query_str, context: { socket: "1" }, variables: { "type" => "ONE" }, root_value: root_object) # Subscribe with default `TYPE` schema.execute(query_str, context: { socket: "2" }, root_value: root_object) # Subscribe with non-matching `TYPE` schema.execute(query_str, context: { socket: "3" }, variables: { "type" => "TWO" }, root_value: root_object) # Subscribe with explicit null schema.execute(query_str, context: { socket: "4" }, variables: { "type" => nil }, root_value: root_object) # The class-based schema has a "prepare" behavior, so it expects these downcased values in `.trigger` if schema == ClassBasedInMemoryBackend::Schema one = "one" two = "two" else one = "ONE" two = "TWO" end # Trigger the subscription with coerceable args, different orders: schema.subscriptions.trigger("event", { "stream" => {"user_id" => 3, "payloadType" => one} }, OpenStruct.new(str: "", int: 1)) schema.subscriptions.trigger("event", { "stream" => {"payloadType" => one, "user_id" => "3"} }, OpenStruct.new(str: "", int: 2)) # This is a non-trigger schema.subscriptions.trigger("event", { "stream" => {"user_id" => "3", "payloadType" => two} }, OpenStruct.new(str: "", int: 3)) # These get default value of ONE (underscored / symbols are ok) schema.subscriptions.trigger("event", { stream: { user_id: "3"} }, OpenStruct.new(str: "", int: 4)) # Trigger with null updates subscriptions to null schema.subscriptions.trigger("event", { "stream" => {"user_id" => 3, "payloadType" => nil} }, OpenStruct.new(str: "", int: 5)) assert_equal [1,2,4], deliveries["1"].map { |d| d["data"]["e1"]["int"] } # Same as socket_1 assert_equal [1,2,4], deliveries["2"].map { |d| d["data"]["e1"]["int"] } # Received the "non-trigger" assert_equal [3], deliveries["3"].map { |d| d["data"]["e1"]["int"] } # Received the trigger with null assert_equal [5], deliveries["4"].map { |d| d["data"]["e1"]["int"] } end it "allows context-scoped subscriptions" do query_str = <<-GRAPHQL subscription($type: PayloadType) { myEvent(payloadType: $type) { int } } GRAPHQL # Subscriptions for user 1 schema.execute(query_str, context: { socket: "1", me: "1" }, variables: { "type" => "ONE" }, root_value: root_object) schema.execute(query_str, context: { socket: "2", me: "1" }, variables: { "type" => "TWO" }, root_value: root_object) # Subscription for user 2 schema.execute(query_str, context: { socket: "3", me: "2" }, variables: { "type" => "ONE" }, root_value: root_object) schema.subscriptions.trigger("myEvent", { "payloadType" => "ONE" }, OpenStruct.new(str: "", int: 1), scope: "1") schema.subscriptions.trigger("myEvent", { "payloadType" => "TWO" }, OpenStruct.new(str: "", int: 2), scope: "1") schema.subscriptions.trigger("myEvent", { "payloadType" => "ONE" }, OpenStruct.new(str: "", int: 3), scope: "2") # Delivered to user 1 assert_equal [1], deliveries["1"].map { |d| d["data"]["myEvent"]["int"] } assert_equal [2], deliveries["2"].map { |d| d["data"]["myEvent"]["int"] } # Delivered to user 2 assert_equal [3], deliveries["3"].map { |d| d["data"]["myEvent"]["int"] } end if defined?(GlobalID) it "allows complex object subscription scopes" do query_str = <<-GRAPHQL subscription($type: PayloadType) { myEvent(payloadType: $type) { int } } GRAPHQL # Global ID Backed User schema.execute(query_str, context: { socket: "1", me: GlobalIDUser.new(1) }, variables: { "type" => "ONE" }, root_value: root_object) schema.execute(query_str, context: { socket: "2", me: GlobalIDUser.new(1) }, variables: { "type" => "TWO" }, root_value: root_object) # ToParam Backed User schema.execute(query_str, context: { socket: "3", me: ToParamUser.new(2) }, variables: { "type" => "ONE" }, root_value: root_object) # Array of Objects schema.execute(query_str, context: { socket: "4", me: [GlobalIDUser.new(4), ToParamUser.new(5)] }, variables: { "type" => "ONE" }, root_value: root_object) schema.subscriptions.trigger("myEvent", { "payloadType" => "ONE" }, OpenStruct.new(str: "", int: 1), scope: GlobalIDUser.new(1)) schema.subscriptions.trigger("myEvent", { "payloadType" => "TWO" }, OpenStruct.new(str: "", int: 2), scope: GlobalIDUser.new(1)) schema.subscriptions.trigger("myEvent", { "payloadType" => "ONE" }, OpenStruct.new(str: "", int: 3), scope: ToParamUser.new(2)) schema.subscriptions.trigger("myEvent", { "payloadType" => "ONE" }, OpenStruct.new(str: "", int: 4), scope: [GlobalIDUser.new(4), ToParamUser.new(5)]) # Delivered to GlobalIDUser assert_equal [1], deliveries["1"].map { |d| d["data"]["myEvent"]["int"] } assert_equal [2], deliveries["2"].map { |d| d["data"]["myEvent"]["int"] } # Delivered to ToParamUser assert_equal [3], deliveries["3"].map { |d| d["data"]["myEvent"]["int"] } # Delivered to Array of GlobalIDUser and ToParamUser assert_equal [4], deliveries["4"].map { |d| d["data"]["myEvent"]["int"] } end end describe "building topic string when `prepare:` is given" do it "doesn't apply with a Subscription class" do query_str = <<-GRAPHQL subscription($type: PayloadType = TWO) { eventSubscription(userId: "3", payloadType: $type) { payload { int } } } GRAPHQL query_str_2 = <<-GRAPHQL subscription { eventSubscription(userId: "4", payloadType: ONE) { payload { int } } } GRAPHQL query_str_3 = <<-GRAPHQL subscription { eventSubscription(userId: "4") { payload { int } } } GRAPHQL # Value from variable schema.execute(query_str, context: { socket: "1" }, variables: { "type" => "ONE" }, root_value: root_object) # Default value for variable schema.execute(query_str, context: { socket: "1" }, root_value: root_object) # Query string literal value schema.execute(query_str_2, context: { socket: "1" }, root_value: root_object) # Schema default value schema.execute(query_str_3, context: { socket: "1" }, root_value: root_object) # There's no way to add `prepare:` when using SDL, so only the Ruby-defined schema has it expected_sub_count = if schema == ClassBasedInMemoryBackend::Schema if TESTING_INTERPRETER { ":eventSubscription:payloadType:one:userId:3" => 1, ":eventSubscription:payloadType:one:userId:4" => 2, ":eventSubscription:payloadType:two:userId:3" => 1, } else # Unfortunately, on the non-interpreter runtime, `prepare:` was _not_ applied here, { ":eventSubscription:payloadType:ONE:userId:3" => 1, ":eventSubscription:payloadType:ONE:userId:4" => 2, ":eventSubscription:payloadType:TWO:userId:3" => 1, } end else { ":eventSubscription:payloadType:ONE:userId:3" => 1, ":eventSubscription:payloadType:ONE:userId:4" => 2, ":eventSubscription:payloadType:TWO:userId:3" => 1, } end assert_equal expected_sub_count, subscriptions_by_topic end it "doesn't apply for plain fields" do query_str = <<-GRAPHQL subscription($type: PayloadType = TWO) { e1: event(stream: { user_id: "3", payloadType: $type }) { int } } GRAPHQL query_str_2 = <<-GRAPHQL subscription { event(stream: { user_id: "4", payloadType: ONE}) { int } } GRAPHQL query_str_3 = <<-GRAPHQL subscription { event(stream: { user_id: "4" }) { int } } GRAPHQL # Value from variable schema.execute(query_str, context: { socket: "1" }, variables: { "type" => "ONE" }, root_value: root_object) # Default value for variable schema.execute(query_str, context: { socket: "1" }, root_value: root_object) # Query string literal value schema.execute(query_str_2, context: { socket: "1" }, root_value: root_object) # Schema default value schema.execute(query_str_3, context: { socket: "1" }, root_value: root_object) # There's no way to add `prepare:` when using SDL, so only the Ruby-defined schema has it expected_sub_count = if schema == ClassBasedInMemoryBackend::Schema { ":event:stream:payloadType:one:user_id:3" => 1, ":event:stream:payloadType:two:user_id:3" => 1, ":event:stream:payloadType:one:user_id:4" => 2, } else { ":event:stream:payloadType:ONE:user_id:3" => 1, ":event:stream:payloadType:TWO:user_id:3" => 1, ":event:stream:payloadType:ONE:user_id:4" => 2, } end assert_equal expected_sub_count, subscriptions_by_topic end end describe "errors" do it "avoid subscription on resolver error" do res = schema.execute(<<-GRAPHQL, context: { socket: "1" }, variables: { "id" => "100" }) subscription ($id: ID!){ failedEvent(id: $id) { str, int } } GRAPHQL assert_equal nil, res["data"] assert_equal "unauthorized", res["errors"][0]["message"] assert_equal 0, subscriptions_by_topic.size end it "lets unhandled errors crash" do query_str = <<-GRAPHQL subscription($type: PayloadType) { myEvent(payloadType: $type) { int } } GRAPHQL schema.execute(query_str, context: { socket: "1", me: "1" }, variables: { "type" => "ONE" }, root_value: root_object) err = assert_raises(RuntimeError) { schema.subscriptions.trigger("myEvent", { "payloadType" => "ONE" }, error_payload_class.new, scope: "1") } assert_equal "Boom!", err.message end end it "sends query errors to the subscriptions" do query_str = <<-GRAPHQL subscription($type: PayloadType) { myEvent(payloadType: $type) { str } } GRAPHQL schema.execute(query_str, context: { socket: "1", me: "1" }, variables: { "type" => "ONE" }, root_value: root_object) schema.subscriptions.trigger("myEvent", { "payloadType" => "ONE" }, error_payload_class.new, scope: "1") res = deliveries["1"].first assert_equal "This is handled", res["errors"][0]["message"] end end describe "implementation" do it "is initialized with keywords" do assert_equal 123, schema.subscriptions.extra end end describe "#build_id" do it "returns a unique ID string" do assert_instance_of String, schema.subscriptions.build_id refute_equal schema.subscriptions.build_id, schema.subscriptions.build_id end end describe ".trigger" do it "raises when event name is not found" do err = assert_raises(GraphQL::Subscriptions::InvalidTriggerError) do schema.subscriptions.trigger(:nonsense_field, {}, nil) end assert_includes err.message, "trigger: nonsense_field" assert_includes err.message, "Subscription.nonsenseField" end it "raises when argument is not found" do err = assert_raises(GraphQL::Subscriptions::InvalidTriggerError) do schema.subscriptions.trigger(:event, { scream: {"user_id" => "😱"} }, nil) end assert_includes err.message, "arguments: scream" assert_includes err.message, "arguments of Subscription.event" err = assert_raises(GraphQL::Subscriptions::InvalidTriggerError) do schema.subscriptions.trigger(:event, { stream: { user_id_number: "😱"} }, nil) end assert_includes err.message, "arguments: user_id_number" assert_includes err.message, "arguments of StreamInput" end end end end describe "broadcast: true" do let(:schema) { BroadcastTrueSchema } before do BroadcastTrueSchema::COUNTERS.clear end class BroadcastTrueSchema < GraphQL::Schema COUNTERS = Hash.new(0) class Subscription < GraphQL::Schema::Object class BroadcastableCounter < GraphQL::Schema::Subscription field :value, Integer, null: false def update { value: COUNTERS[:broadcastable] += 1 } end end class IsolatedCounter < GraphQL::Schema::Subscription broadcastable(false) field :value, Integer, null: false def update { value: COUNTERS[:isolated] += 1 } end end field :broadcastable_counter, subscription: BroadcastableCounter field :isolated_counter, subscription: IsolatedCounter end class Query < GraphQL::Schema::Object field :int, Integer, null: false end query(Query) subscription(Subscription) use GraphQL::Execution::Interpreter use GraphQL::Analysis::AST use InMemoryBackend::Subscriptions, extra: nil, broadcast: true, default_broadcastable: true end def exec_query(query_str, **options) BroadcastTrueSchema.execute(query_str, **options) end it "broadcasts when possible" do assert_equal false, BroadcastTrueSchema.get_field("Subscription", "isolatedCounter").broadcastable? exec_query("subscription { counter: broadcastableCounter { value } }", context: { socket: "1" }) exec_query("subscription { counter: broadcastableCounter { value } }", context: { socket: "2" }) exec_query("subscription { counter: broadcastableCounter { value __typename } }", context: { socket: "3" }) exec_query("subscription { counter: isolatedCounter { value } }", context: { socket: "1" }) exec_query("subscription { counter: isolatedCounter { value } }", context: { socket: "2" }) exec_query("subscription { counter: isolatedCounter { value } }", context: { socket: "3" }) schema.subscriptions.trigger(:broadcastable_counter, {}, {}) schema.subscriptions.trigger(:isolated_counter, {}, {}) expected_counters = { broadcastable: 2, isolated: 3 } assert_equal expected_counters, BroadcastTrueSchema::COUNTERS delivered_values = schema.subscriptions.deliveries.map do |channel, results| results.map { |r| r["data"]["counter"]["value"] } end # Socket 1 received 1, 1 # Socket 2 received 1, 2 (same broadcast as Socket 1) # Socket 3 received 2, 3 expected_values = [[1,1], [1,2], [2,3]] assert_equal expected_values, delivered_values end end end Fix lint error # frozen_string_literal: true require "spec_helper" class InMemoryBackend class Subscriptions < GraphQL::Subscriptions attr_reader :deliveries, :pushes, :extra, :queries, :events def initialize(schema:, extra:, **rest) super @extra = extra @queries = {} # { topic => { fingerprint => [sub_id, ... ] } } @events = Hash.new { |h,k| h[k] = Hash.new { |h2, k2| h2[k2] = [] } } @deliveries = Hash.new { |h, k| h[k] = [] } @pushes = [] end def write_subscription(query, events) subscription_id = query.context[:subscription_id] = build_id @queries[subscription_id] = query events.each do |ev| @events[ev.topic][ev.fingerprint] << subscription_id end end def each_subscription_id(event) @events[event.topic].each do |fp, sub_ids| sub_ids.each do |sub_id| yield(sub_id) end end end def read_subscription(subscription_id) query = @queries[subscription_id] if query { query_string: query.query_string, operation_name: query.operation_name, variables: query.provided_variables, context: { me: query.context[:me] }, transport: :socket, } else nil end end def delete_subscription(subscription_id) @queries.delete(subscription_id) @events.each do |topic, sub_ids_by_fp| sub_ids_by_fp.each do |fp, sub_ids| sub_ids.delete(subscription_id) if sub_ids.empty? sub_ids_by_fp.delete(fp) if sub_ids_by_fp.empty? @events.delete(topic) end end end end end def execute_all(event, object) topic = event.topic sub_ids_by_fp = @events[topic] sub_ids_by_fp.each do |fingerprint, sub_ids| result = execute_update(sub_ids.first, event, object) sub_ids.each do |sub_id| deliver(sub_id, result) end end end def deliver(subscription_id, result) query = @queries[subscription_id] socket = query.context[:socket] || subscription_id @deliveries[socket] << result end def execute_update(subscription_id, event, object) query = @queries[subscription_id] if query @pushes << query.context[:socket] end super end # Just for testing: def reset @queries.clear @events.clear @deliveries.clear @pushes.clear end end # Just a random stateful object for tracking what happens: class SubscriptionPayload attr_reader :str def initialize @str = "Update" @counter = 0 end def int @counter += 1 end end end class ClassBasedInMemoryBackend < InMemoryBackend class Payload < GraphQL::Schema::Object field :str, String, null: false field :int, Integer, null: false end class PayloadType < GraphQL::Schema::Enum graphql_name "PayloadType" # Arbitrary "kinds" of payloads which may be # subscribed to separately value "ONE" value "TWO" end class StreamInput < GraphQL::Schema::InputObject argument :user_id, ID, required: true, camelize: false argument :payload_type, PayloadType, required: false, default_value: "ONE", prepare: ->(e, ctx) { e ? e.downcase : e } end class EventSubscription < GraphQL::Schema::Subscription argument :user_id, ID, required: true argument :payload_type, PayloadType, required: false, default_value: "ONE", prepare: ->(e, ctx) { e ? e.downcase : e } field :payload, Payload, null: true end class Subscription < GraphQL::Schema::Object if !TESTING_INTERPRETER # Stub methods are required [:payload, :event, :my_event].each do |m| define_method(m) { |*a| nil } end end field :payload, Payload, null: false do argument :id, ID, required: true end field :event, Payload, null: true do argument :stream, StreamInput, required: false end field :event_subscription, subscription: EventSubscription field :my_event, Payload, null: true, subscription_scope: :me do argument :payload_type, PayloadType, required: false end field :failed_event, Payload, null: false do argument :id, ID, required: true end def failed_event(id:) raise GraphQL::ExecutionError.new("unauthorized") end end class Query < GraphQL::Schema::Object field :dummy, Integer, null: true end class Schema < GraphQL::Schema query(Query) subscription(Subscription) use InMemoryBackend::Subscriptions, extra: 123 if TESTING_INTERPRETER use GraphQL::Execution::Interpreter use GraphQL::Analysis::AST end end end class FromDefinitionInMemoryBackend < InMemoryBackend SchemaDefinition = <<-GRAPHQL type Subscription { payload(id: ID!): Payload! event(stream: StreamInput): Payload eventSubscription(userId: ID, payloadType: PayloadType = ONE): EventSubscriptionPayload myEvent(payloadType: PayloadType): Payload failedEvent(id: ID!): Payload! } type Payload { str: String! int: Int! } type EventSubscriptionPayload { payload: Payload } input StreamInput { user_id: ID! payloadType: PayloadType = ONE } # Arbitrary "kinds" of payloads which may be # subscribed to separately enum PayloadType { ONE TWO } type Query { dummy: Int } GRAPHQL DEFAULT_SUBSCRIPTION_RESOLVE = ->(o,a,c) { if c.query.subscription_update? o else c.skip end } Resolvers = { "Subscription" => { "payload" => DEFAULT_SUBSCRIPTION_RESOLVE, "myEvent" => DEFAULT_SUBSCRIPTION_RESOLVE, "event" => DEFAULT_SUBSCRIPTION_RESOLVE, "eventSubscription" => ->(o,a,c) { nil }, "failedEvent" => ->(o,a,c) { raise GraphQL::ExecutionError.new("unauthorized") }, }, } Schema = GraphQL::Schema.from_definition(SchemaDefinition, default_resolve: Resolvers, using: {InMemoryBackend::Subscriptions => { extra: 123 }}, interpreter: TESTING_INTERPRETER) # TODO don't hack this (no way to add metadata from IDL parser right now) Schema.get_field("Subscription", "myEvent").subscription_scope = :me end class ToParamUser def initialize(id) @id = id end def to_param @id end end describe GraphQL::Subscriptions do before do schema.subscriptions.reset end [ClassBasedInMemoryBackend, FromDefinitionInMemoryBackend].each do |in_memory_backend_class| describe "using #{in_memory_backend_class}" do let(:root_object) { OpenStruct.new( payload: in_memory_backend_class::SubscriptionPayload.new, ) } let(:schema) { in_memory_backend_class::Schema } let(:implementation) { schema.subscriptions } let(:deliveries) { implementation.deliveries } let(:subscriptions_by_topic) { implementation.events.each_with_object({}) do |(k, v), obj| obj[k] = v.size end } describe "pushing updates" do it "sends updated data" do query_str = <<-GRAPHQL subscription ($id: ID!){ firstPayload: payload(id: $id) { str, int } otherPayload: payload(id: "900") { int } } GRAPHQL # Initial subscriptions res_1 = schema.execute(query_str, context: { socket: "1" }, variables: { "id" => "100" }, root_value: root_object) res_2 = schema.execute(query_str, context: { socket: "2" }, variables: { "id" => "200" }, root_value: root_object) empty_response = TESTING_INTERPRETER ? {} : nil # Initial response is nil, no broadcasts yet assert_equal(empty_response, res_1["data"]) assert_equal(empty_response, res_2["data"]) assert_equal [], deliveries["1"] assert_equal [], deliveries["2"] # Application stuff happens. # The application signals graphql via `subscriptions.trigger`: schema.subscriptions.trigger(:payload, {"id" => "100"}, root_object.payload) schema.subscriptions.trigger("payload", {"id" => "200"}, root_object.payload) # Symbols are OK too schema.subscriptions.trigger(:payload, {:id => "100"}, root_object.payload) schema.subscriptions.trigger("payload", {"id" => "300"}, nil) # Let's see what GraphQL sent over the wire: assert_equal({"str" => "Update", "int" => 1}, deliveries["1"][0]["data"]["firstPayload"]) assert_equal({"str" => "Update", "int" => 2}, deliveries["2"][0]["data"]["firstPayload"]) assert_equal({"str" => "Update", "int" => 3}, deliveries["1"][1]["data"]["firstPayload"]) end end it "sends updated data for multifield subscriptions" do query_str = <<-GRAPHQL subscription ($id: ID!){ payload(id: $id) { str, int } event { int } } GRAPHQL # Initial subscriptions res = schema.execute(query_str, context: { socket: "1" }, variables: { "id" => "100" }, root_value: root_object) empty_response = TESTING_INTERPRETER ? {} : nil # Initial response is nil, no broadcasts yet assert_equal(empty_response, res["data"]) assert_equal [], deliveries["1"] # Application stuff happens. # The application signals graphql via `subscriptions.trigger`: schema.subscriptions.trigger(:payload, {"id" => "100"}, root_object.payload) # Let's see what GraphQL sent over the wire: assert_equal({"str" => "Update", "int" => 1}, deliveries["1"][0]["data"]["payload"]) assert_equal(nil, deliveries["1"][0]["data"]["event"]) if TESTING_INTERPRETER # double-subscriptions is broken on the old runtime # Trigger another field subscription schema.subscriptions.trigger(:event, {}, OpenStruct.new(int: 1)) # Now we should get result for another field assert_equal(nil, deliveries["1"][1]["data"]["payload"]) assert_equal({"int" => 1}, deliveries["1"][1]["data"]["event"]) end end describe "passing a document into #execute" do it "sends the updated data" do query_str = <<-GRAPHQL subscription ($id: ID!){ payload(id: $id) { str, int } } GRAPHQL document = GraphQL.parse(query_str) # Initial subscriptions response = schema.execute(nil, document: document, context: { socket: "1" }, variables: { "id" => "100" }, root_value: root_object) empty_response = TESTING_INTERPRETER ? {} : nil # Initial response is empty, no broadcasts yet assert_equal(empty_response, response["data"]) assert_equal [], deliveries["1"] # Application stuff happens. # The application signals graphql via `subscriptions.trigger`: schema.subscriptions.trigger(:payload, {"id" => "100"}, root_object.payload) # Symbols are OK too schema.subscriptions.trigger(:payload, {:id => "100"}, root_object.payload) schema.subscriptions.trigger("payload", {"id" => "300"}, nil) # Let's see what GraphQL sent over the wire: assert_equal({"str" => "Update", "int" => 1}, deliveries["1"][0]["data"]["payload"]) assert_equal({"str" => "Update", "int" => 2}, deliveries["1"][1]["data"]["payload"]) end end describe "subscribing" do it "doesn't call the subscriptions for invalid queries" do query_str = <<-GRAPHQL subscription ($id: ID){ payload(id: $id) { str, int } } GRAPHQL res = schema.execute(query_str, context: { socket: "1" }, variables: { "id" => "100" }, root_value: root_object) assert_equal true, res.key?("errors") assert_equal 0, implementation.events.size assert_equal 0, implementation.queries.size end end describe "trigger" do let(:error_payload_class) { Class.new { def int raise "Boom!" end def str raise GraphQL::ExecutionError.new("This is handled") end } } it "uses the provided queue" do query_str = <<-GRAPHQL subscription ($id: ID!){ payload(id: $id) { str, int } } GRAPHQL schema.execute(query_str, context: { socket: "1" }, variables: { "id" => "8" }, root_value: root_object) schema.subscriptions.trigger("payload", { "id" => "8"}, root_object.payload) assert_equal ["1"], implementation.pushes end it "pushes errors" do query_str = <<-GRAPHQL subscription ($id: ID!){ payload(id: $id) { str, int } } GRAPHQL schema.execute(query_str, context: { socket: "1" }, variables: { "id" => "8" }, root_value: root_object) schema.subscriptions.trigger("payload", { "id" => "8"}, OpenStruct.new(str: nil, int: nil)) delivery = deliveries["1"].first assert_nil delivery.fetch("data") assert_equal 1, delivery["errors"].length end it "unsubscribes when `read_subscription` returns nil" do query_str = <<-GRAPHQL subscription ($id: ID!){ payload(id: $id) { str, int } } GRAPHQL schema.execute(query_str, context: { socket: "1" }, variables: { "id" => "8" }, root_value: root_object) assert_equal 1, implementation.events.size sub_id = implementation.queries.keys.first # Mess with the private storage so that `read_subscription` will be nil implementation.queries.delete(sub_id) assert_equal 1, implementation.events.size assert_nil implementation.read_subscription(sub_id) # The trigger should clean up the lingering subscription: schema.subscriptions.trigger("payload", { "id" => "8"}, OpenStruct.new(str: nil, int: nil)) assert_equal 0, implementation.events.size assert_equal 0, implementation.queries.size end it "coerces args" do query_str = <<-GRAPHQL subscription($type: PayloadType) { e1: event(stream: { user_id: "3", payloadType: $type }) { int } } GRAPHQL # Subscribe with explicit `TYPE` schema.execute(query_str, context: { socket: "1" }, variables: { "type" => "ONE" }, root_value: root_object) # Subscribe with default `TYPE` schema.execute(query_str, context: { socket: "2" }, root_value: root_object) # Subscribe with non-matching `TYPE` schema.execute(query_str, context: { socket: "3" }, variables: { "type" => "TWO" }, root_value: root_object) # Subscribe with explicit null schema.execute(query_str, context: { socket: "4" }, variables: { "type" => nil }, root_value: root_object) # The class-based schema has a "prepare" behavior, so it expects these downcased values in `.trigger` if schema == ClassBasedInMemoryBackend::Schema one = "one" two = "two" else one = "ONE" two = "TWO" end # Trigger the subscription with coerceable args, different orders: schema.subscriptions.trigger("event", { "stream" => {"user_id" => 3, "payloadType" => one} }, OpenStruct.new(str: "", int: 1)) schema.subscriptions.trigger("event", { "stream" => {"payloadType" => one, "user_id" => "3"} }, OpenStruct.new(str: "", int: 2)) # This is a non-trigger schema.subscriptions.trigger("event", { "stream" => {"user_id" => "3", "payloadType" => two} }, OpenStruct.new(str: "", int: 3)) # These get default value of ONE (underscored / symbols are ok) schema.subscriptions.trigger("event", { stream: { user_id: "3"} }, OpenStruct.new(str: "", int: 4)) # Trigger with null updates subscriptions to null schema.subscriptions.trigger("event", { "stream" => {"user_id" => 3, "payloadType" => nil} }, OpenStruct.new(str: "", int: 5)) assert_equal [1,2,4], deliveries["1"].map { |d| d["data"]["e1"]["int"] } # Same as socket_1 assert_equal [1,2,4], deliveries["2"].map { |d| d["data"]["e1"]["int"] } # Received the "non-trigger" assert_equal [3], deliveries["3"].map { |d| d["data"]["e1"]["int"] } # Received the trigger with null assert_equal [5], deliveries["4"].map { |d| d["data"]["e1"]["int"] } end it "allows context-scoped subscriptions" do query_str = <<-GRAPHQL subscription($type: PayloadType) { myEvent(payloadType: $type) { int } } GRAPHQL # Subscriptions for user 1 schema.execute(query_str, context: { socket: "1", me: "1" }, variables: { "type" => "ONE" }, root_value: root_object) schema.execute(query_str, context: { socket: "2", me: "1" }, variables: { "type" => "TWO" }, root_value: root_object) # Subscription for user 2 schema.execute(query_str, context: { socket: "3", me: "2" }, variables: { "type" => "ONE" }, root_value: root_object) schema.subscriptions.trigger("myEvent", { "payloadType" => "ONE" }, OpenStruct.new(str: "", int: 1), scope: "1") schema.subscriptions.trigger("myEvent", { "payloadType" => "TWO" }, OpenStruct.new(str: "", int: 2), scope: "1") schema.subscriptions.trigger("myEvent", { "payloadType" => "ONE" }, OpenStruct.new(str: "", int: 3), scope: "2") # Delivered to user 1 assert_equal [1], deliveries["1"].map { |d| d["data"]["myEvent"]["int"] } assert_equal [2], deliveries["2"].map { |d| d["data"]["myEvent"]["int"] } # Delivered to user 2 assert_equal [3], deliveries["3"].map { |d| d["data"]["myEvent"]["int"] } end if defined?(GlobalID) it "allows complex object subscription scopes" do query_str = <<-GRAPHQL subscription($type: PayloadType) { myEvent(payloadType: $type) { int } } GRAPHQL # Global ID Backed User schema.execute(query_str, context: { socket: "1", me: GlobalIDUser.new(1) }, variables: { "type" => "ONE" }, root_value: root_object) schema.execute(query_str, context: { socket: "2", me: GlobalIDUser.new(1) }, variables: { "type" => "TWO" }, root_value: root_object) # ToParam Backed User schema.execute(query_str, context: { socket: "3", me: ToParamUser.new(2) }, variables: { "type" => "ONE" }, root_value: root_object) # Array of Objects schema.execute(query_str, context: { socket: "4", me: [GlobalIDUser.new(4), ToParamUser.new(5)] }, variables: { "type" => "ONE" }, root_value: root_object) schema.subscriptions.trigger("myEvent", { "payloadType" => "ONE" }, OpenStruct.new(str: "", int: 1), scope: GlobalIDUser.new(1)) schema.subscriptions.trigger("myEvent", { "payloadType" => "TWO" }, OpenStruct.new(str: "", int: 2), scope: GlobalIDUser.new(1)) schema.subscriptions.trigger("myEvent", { "payloadType" => "ONE" }, OpenStruct.new(str: "", int: 3), scope: ToParamUser.new(2)) schema.subscriptions.trigger("myEvent", { "payloadType" => "ONE" }, OpenStruct.new(str: "", int: 4), scope: [GlobalIDUser.new(4), ToParamUser.new(5)]) # Delivered to GlobalIDUser assert_equal [1], deliveries["1"].map { |d| d["data"]["myEvent"]["int"] } assert_equal [2], deliveries["2"].map { |d| d["data"]["myEvent"]["int"] } # Delivered to ToParamUser assert_equal [3], deliveries["3"].map { |d| d["data"]["myEvent"]["int"] } # Delivered to Array of GlobalIDUser and ToParamUser assert_equal [4], deliveries["4"].map { |d| d["data"]["myEvent"]["int"] } end end describe "building topic string when `prepare:` is given" do it "doesn't apply with a Subscription class" do query_str = <<-GRAPHQL subscription($type: PayloadType = TWO) { eventSubscription(userId: "3", payloadType: $type) { payload { int } } } GRAPHQL query_str_2 = <<-GRAPHQL subscription { eventSubscription(userId: "4", payloadType: ONE) { payload { int } } } GRAPHQL query_str_3 = <<-GRAPHQL subscription { eventSubscription(userId: "4") { payload { int } } } GRAPHQL # Value from variable schema.execute(query_str, context: { socket: "1" }, variables: { "type" => "ONE" }, root_value: root_object) # Default value for variable schema.execute(query_str, context: { socket: "1" }, root_value: root_object) # Query string literal value schema.execute(query_str_2, context: { socket: "1" }, root_value: root_object) # Schema default value schema.execute(query_str_3, context: { socket: "1" }, root_value: root_object) # There's no way to add `prepare:` when using SDL, so only the Ruby-defined schema has it expected_sub_count = if schema == ClassBasedInMemoryBackend::Schema if TESTING_INTERPRETER { ":eventSubscription:payloadType:one:userId:3" => 1, ":eventSubscription:payloadType:one:userId:4" => 2, ":eventSubscription:payloadType:two:userId:3" => 1, } else # Unfortunately, on the non-interpreter runtime, `prepare:` was _not_ applied here, { ":eventSubscription:payloadType:ONE:userId:3" => 1, ":eventSubscription:payloadType:ONE:userId:4" => 2, ":eventSubscription:payloadType:TWO:userId:3" => 1, } end else { ":eventSubscription:payloadType:ONE:userId:3" => 1, ":eventSubscription:payloadType:ONE:userId:4" => 2, ":eventSubscription:payloadType:TWO:userId:3" => 1, } end assert_equal expected_sub_count, subscriptions_by_topic end it "doesn't apply for plain fields" do query_str = <<-GRAPHQL subscription($type: PayloadType = TWO) { e1: event(stream: { user_id: "3", payloadType: $type }) { int } } GRAPHQL query_str_2 = <<-GRAPHQL subscription { event(stream: { user_id: "4", payloadType: ONE}) { int } } GRAPHQL query_str_3 = <<-GRAPHQL subscription { event(stream: { user_id: "4" }) { int } } GRAPHQL # Value from variable schema.execute(query_str, context: { socket: "1" }, variables: { "type" => "ONE" }, root_value: root_object) # Default value for variable schema.execute(query_str, context: { socket: "1" }, root_value: root_object) # Query string literal value schema.execute(query_str_2, context: { socket: "1" }, root_value: root_object) # Schema default value schema.execute(query_str_3, context: { socket: "1" }, root_value: root_object) # There's no way to add `prepare:` when using SDL, so only the Ruby-defined schema has it expected_sub_count = if schema == ClassBasedInMemoryBackend::Schema { ":event:stream:payloadType:one:user_id:3" => 1, ":event:stream:payloadType:two:user_id:3" => 1, ":event:stream:payloadType:one:user_id:4" => 2, } else { ":event:stream:payloadType:ONE:user_id:3" => 1, ":event:stream:payloadType:TWO:user_id:3" => 1, ":event:stream:payloadType:ONE:user_id:4" => 2, } end assert_equal expected_sub_count, subscriptions_by_topic end end describe "errors" do it "avoid subscription on resolver error" do res = schema.execute(<<-GRAPHQL, context: { socket: "1" }, variables: { "id" => "100" }) subscription ($id: ID!){ failedEvent(id: $id) { str, int } } GRAPHQL assert_equal nil, res["data"] assert_equal "unauthorized", res["errors"][0]["message"] assert_equal 0, subscriptions_by_topic.size end it "lets unhandled errors crash" do query_str = <<-GRAPHQL subscription($type: PayloadType) { myEvent(payloadType: $type) { int } } GRAPHQL schema.execute(query_str, context: { socket: "1", me: "1" }, variables: { "type" => "ONE" }, root_value: root_object) err = assert_raises(RuntimeError) { schema.subscriptions.trigger("myEvent", { "payloadType" => "ONE" }, error_payload_class.new, scope: "1") } assert_equal "Boom!", err.message end end it "sends query errors to the subscriptions" do query_str = <<-GRAPHQL subscription($type: PayloadType) { myEvent(payloadType: $type) { str } } GRAPHQL schema.execute(query_str, context: { socket: "1", me: "1" }, variables: { "type" => "ONE" }, root_value: root_object) schema.subscriptions.trigger("myEvent", { "payloadType" => "ONE" }, error_payload_class.new, scope: "1") res = deliveries["1"].first assert_equal "This is handled", res["errors"][0]["message"] end end describe "implementation" do it "is initialized with keywords" do assert_equal 123, schema.subscriptions.extra end end describe "#build_id" do it "returns a unique ID string" do assert_instance_of String, schema.subscriptions.build_id refute_equal schema.subscriptions.build_id, schema.subscriptions.build_id end end describe ".trigger" do it "raises when event name is not found" do err = assert_raises(GraphQL::Subscriptions::InvalidTriggerError) do schema.subscriptions.trigger(:nonsense_field, {}, nil) end assert_includes err.message, "trigger: nonsense_field" assert_includes err.message, "Subscription.nonsenseField" end it "raises when argument is not found" do err = assert_raises(GraphQL::Subscriptions::InvalidTriggerError) do schema.subscriptions.trigger(:event, { scream: {"user_id" => "😱"} }, nil) end assert_includes err.message, "arguments: scream" assert_includes err.message, "arguments of Subscription.event" err = assert_raises(GraphQL::Subscriptions::InvalidTriggerError) do schema.subscriptions.trigger(:event, { stream: { user_id_number: "😱"} }, nil) end assert_includes err.message, "arguments: user_id_number" assert_includes err.message, "arguments of StreamInput" end end end end describe "broadcast: true" do let(:schema) { BroadcastTrueSchema } before do BroadcastTrueSchema::COUNTERS.clear end class BroadcastTrueSchema < GraphQL::Schema COUNTERS = Hash.new(0) class Subscription < GraphQL::Schema::Object class BroadcastableCounter < GraphQL::Schema::Subscription field :value, Integer, null: false def update { value: COUNTERS[:broadcastable] += 1 } end end class IsolatedCounter < GraphQL::Schema::Subscription broadcastable(false) field :value, Integer, null: false def update { value: COUNTERS[:isolated] += 1 } end end field :broadcastable_counter, subscription: BroadcastableCounter field :isolated_counter, subscription: IsolatedCounter end class Query < GraphQL::Schema::Object field :int, Integer, null: false end query(Query) subscription(Subscription) use GraphQL::Execution::Interpreter use GraphQL::Analysis::AST use InMemoryBackend::Subscriptions, extra: nil, broadcast: true, default_broadcastable: true end def exec_query(query_str, **options) BroadcastTrueSchema.execute(query_str, **options) end it "broadcasts when possible" do assert_equal false, BroadcastTrueSchema.get_field("Subscription", "isolatedCounter").broadcastable? exec_query("subscription { counter: broadcastableCounter { value } }", context: { socket: "1" }) exec_query("subscription { counter: broadcastableCounter { value } }", context: { socket: "2" }) exec_query("subscription { counter: broadcastableCounter { value __typename } }", context: { socket: "3" }) exec_query("subscription { counter: isolatedCounter { value } }", context: { socket: "1" }) exec_query("subscription { counter: isolatedCounter { value } }", context: { socket: "2" }) exec_query("subscription { counter: isolatedCounter { value } }", context: { socket: "3" }) schema.subscriptions.trigger(:broadcastable_counter, {}, {}) schema.subscriptions.trigger(:isolated_counter, {}, {}) expected_counters = { broadcastable: 2, isolated: 3 } assert_equal expected_counters, BroadcastTrueSchema::COUNTERS delivered_values = schema.subscriptions.deliveries.map do |channel, results| results.map { |r| r["data"]["counter"]["value"] } end # Socket 1 received 1, 1 # Socket 2 received 1, 2 (same broadcast as Socket 1) # Socket 3 received 2, 3 expected_values = [[1,1], [1,2], [2,3]] assert_equal expected_values, delivered_values end end end
New Formula: libgaiagraphics Libgaiagraphics is a utlity library that abstracts several libraries, such as TIFF, PNG and Cairo graphics, into a single API. require 'formula' class Libgaiagraphics < Formula homepage 'https://www.gaia-gis.it/fossil/libgaiagraphics/index' url 'http://www.gaia-gis.it/gaia-sins/libgaiagraphics-0.4b.tar.gz' md5 '6e7c703faad9de3beea296aa9508eec2' depends_on 'libgeotiff' depends_on 'jpeg' def install system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make install" end end
module Emerson VERSION = "0.1.0.pre.1" end Update pre-release version module Emerson VERSION = "0.1.0.pre.2" end
require "spec_helper" require "heroku/command/addons" module Heroku::Command describe Addons do include Support::Addons let(:addon) { build_addon(name: "my_addon", app: { name: "example" }) } before do @addons = prepare_command(Addons) stub_core.release("example", "current").returns( "name" => "v99" ) end describe "#index" do before(:each) do stub_core api.post_app("name" => "example", "stack" => "cedar") end after(:each) do api.delete_app("example") end it "should display no addons when none are configured" do Excon.stub(method: :get, path: '/apps/example/addons') do { body: "[]", status: 200 } end Excon.stub(method: :get, path: '/apps/example/addon-attachments') do { body: "[]", status: 200 } end stderr, stdout = execute("addons") expect(stderr).to eq("") expect(stdout).to eq <<-STDOUT === Resources for example There are no add-ons. === Attachments for example There are no attachments. STDOUT Excon.stubs.shift(2) end it "should list addons and attachments" do Excon.stub(method: :get, path: '/apps/example/addons') do hooks = build_addon( name: "swimming-nicely-42", plan: { name: "deployhooks:http", price: { cents: 0, unit: "month" }}, app: { name: "example" }) hpg = build_addon( name: "jumping-slowly-76", plan: { name: "heroku-postgresql:ronin", price: { cents: 20000, unit: "month" }}, app: { name: "example" }) { body: MultiJson.encode([hooks, hpg]), status: 200 } end Excon.stub(method: :get, path: '/apps/example/addon-attachments') do hpg = build_attachment( name: "HEROKU_POSTGRESQL_CYAN", addon: { name: "heroku-postgresql-12345", app: { name: "example" }}, app: { name: "example" }) { body: MultiJson.encode([hpg]), status: 200 } end stderr, stdout = execute("addons") expect(stderr).to eq("") expect(stdout).to eq <<-STDOUT === Resources for example Plan Name Price ----------------------- ------------------ ------------- deployhooks:http swimming-nicely-42 free heroku-postgresql:ronin jumping-slowly-76 $200.00/month === Attachments for example Name Add-on Billing App ---------------------- ----------------------- ----------- HEROKU_POSTGRESQL_CYAN heroku-postgresql-12345 example STDOUT Excon.stubs.shift(2) end end describe "list" do before do Excon.stub(method: :get, path: '/addon-services') do services = [ { "name" => "cloudcounter:basic", "state" => "alpha" }, { "name" => "cloudcounter:pro", "state" => "public" }, { "name" => "cloudcounter:gold", "state" => "public" }, { "name" => "cloudcounter:old", "state" => "disabled" }, { "name" => "cloudcounter:platinum", "state" => "beta" } ] { body: MultiJson.encode(services), status: 200 } end end after do Excon.stubs.shift end # TODO: plugin code doesn't support this. Do we need it? xit "sends region option to the server" do stub_request(:get, '/addon-services?region=eu'). to_return(:body => MultiJson.dump([])) execute("addons:list --region=eu") end describe "when using the deprecated `addons:list` command" do it "displays a deprecation warning" do stderr, stdout = execute("addons:list") expect(stderr).to eq("") expect(stdout).to include "WARNING: `heroku addons:list` has been deprecated. Please use `heroku addons:services` instead." end end describe "when using correct `addons:services` command" do it "displays all services" do stderr, stdout = execute("addons:services") expect(stderr).to eq("") expect(stdout).to eq <<-STDOUT Slug Name State --------------------- ---- -------- cloudcounter:basic alpha cloudcounter:pro public cloudcounter:gold public cloudcounter:old disabled cloudcounter:platinum beta See plans with `heroku addons:plans SERVICE` STDOUT end end end describe 'v1-style command line params' do before do Excon.stub(method: :post, path: '/apps/example/addons') do { body: MultiJson.encode(addon), status: 201 } end end after do Excon.stubs.shift end it "understands foo=baz" do allow(@addons).to receive(:args).and_return(%w(my_addon foo=baz)) allow(@addons.api).to receive(:request) { |params| expect(params[:body]).to include '"foo":"baz"' }.and_return(double(body: stringify(addon))) @addons.create end describe "addons:add" do before do Excon.stub(method: :get, path: '/apps/example/releases/current') do { body: MultiJson.dump({ 'name' => 'v99' }), status: 200 } end Excon.stub(method: :post, path: '/apps/example/addons/my_addon') do { body: MultiJson.encode(price: "free"), status: 200 } end end after do Excon.stubs.shift(2) end it "shows a deprecation warning about addon:add vs addons:create" do stderr, stdout = execute("addons:add my_addon --foo=bar extra=XXX") expect(stderr).to eq("") expect(stdout).to include "WARNING: `heroku addons:add` has been deprecated. Please use `heroku addons:create` instead." end it "shows a deprecation warning about non-unix params" do stderr, stdout = execute("addons:add my_addon --foo=bar extra=XXX") expect(stderr).to eq("") expect(stdout).to include "Warning: non-unix style params have been deprecated, use --extra=XXX instead" end end end describe 'unix-style command line params' do it "understands --foo=baz" do allow(@addons).to receive(:args).and_return(%w(my_addon --foo=baz)) allow(@addons).to receive(:request) { |args| expect(args[:body]).to include '"foo":"baz"' }.and_return(stringify(addon)) @addons.create end it "understands --foo baz" do allow(@addons).to receive(:args).and_return(%w(my_addon --foo baz)) expect(@addons).to receive(:request) { |args| expect(args[:body]).to include '"foo":"baz"' }.and_return(stringify(addon)) @addons.create end it "treats lone switches as true" do allow(@addons).to receive(:args).and_return(%w(my_addon --foo)) expect(@addons).to receive(:request) { |args| expect(args[:body]).to include '"foo":true' }.and_return(stringify(addon)) @addons.create end it "converts 'true' to boolean" do allow(@addons).to receive(:args).and_return(%w(my_addon --foo=true)) expect(@addons).to receive(:request) { |args| expect(args[:body]).to include '"foo":true' }.and_return(stringify(addon)) @addons.create end it "works with many config vars" do allow(@addons).to receive(:args).and_return(%w(my_addon --foo baz --bar yes --baz=foo --bab --bob=true)) expect(@addons).to receive(:request) { |args| expect(args[:body]).to include({ foo: 'baz', bar: 'yes', baz: 'foo', bab: true, bob: true }.to_json) }.and_return(stringify(addon)) @addons.create end it "raises an error for spurious arguments" do allow(@addons).to receive(:args).and_return(%w(my_addon spurious)) expect { @addons.create }.to raise_error(CommandFailed) end end describe "mixed options" do it "understands foo=bar and --baz=bar on the same line" do allow(@addons).to receive(:args).and_return(%w(my_addon foo=baz --baz=bar bob=true --bar)) expect(@addons).to receive(:request) { |args| expect(args[:body]).to include '"foo":"baz"' expect(args[:body]).to include '"baz":"bar"' expect(args[:body]).to include '"bar":true' expect(args[:body]).to include '"bob":true' }.and_return(stringify(addon)) @addons.create end it "sends the variables to the server" do Excon.stub(method: :post, path: '/apps/example/addons') do { body: MultiJson.encode(addon), status: 201 } end stderr, stdout = execute("addons:add my_addon foo=baz --baz=bar bob=true --bar") expect(stderr).to eq("") expect(stdout).to include("Warning: non-unix style params have been deprecated, use --foo=baz --bob=true instead") Excon.stubs.shift end end describe "fork, follow, and rollback switches" do it "should only resolve for heroku-postgresql addon" do %w{fork follow rollback}.each do |switch| allow(@addons).to receive(:args).and_return("addon --#{switch} HEROKU_POSTGRESQL_RED".split) allow(@addons).to receive(:request) { |args| expect(args[:body]).to include %("#{switch}":"HEROKU_POSTGRESQL_RED") }.and_return(stringify(addon)) @addons.create end end it "should NOT translate --fork and --follow if passed in a full postgres url even if there are no databases" do %w{fork follow}.each do |switch| allow(@addons).to receive(:app_config_vars).and_return({}) allow(@addons).to receive(:app_attachments).and_return([]) allow(@addons).to receive(:args).and_return("heroku-postgresql:ronin --#{switch} postgres://foo:yeah@awesome.com:234/bestdb".split) allow(@addons).to receive(:request) { |args| expect(args[:body]).to include %("#{switch}":"postgres://foo:yeah@awesome.com:234/bestdb") }.and_return(stringify(addon)) @addons.create end end # TODO: ? xit "should fail if fork / follow across applications and no plan is specified" do %w{fork follow}.each do |switch| allow(@addons).to receive(:app_config_vars).and_return({}) allow(@addons).to receive(:app_attachments).and_return([]) allow(@addons).to receive(:args).and_return("heroku-postgresql --#{switch} postgres://foo:yeah@awesome.com:234/bestdb".split) expect { @addons.create }.to raise_error(CommandFailed) end end end describe 'adding' do before do allow(@addons).to receive(:args).and_return(%w(my_addon)) Excon.stub( { :expects => 200, :method => :get, :path => '/apps/example/releases/current' }, { :body => MultiJson.dump({ 'name' => 'v99' }), :status => 200, } ) end after do Excon.stubs.shift end it "requires an addon name" do allow(@addons).to receive(:args).and_return([]) expect { @addons.create }.to raise_error(CommandFailed) end it "adds an addon" do allow(@addons).to receive(:args).and_return(%w(my_addon)) allow(@addons).to receive(:request) { |args| expect(args[:path]).to eq "/apps/example/addons" expect(args[:body]).to include '"name":"my_addon"' }.and_return(stringify(addon)) @addons.create end it "expands hgp:s0 to heroku-postgresql:standard-0" do allow(@addons).to receive(:args).and_return(%w(hpg:s0)) allow(@addons).to receive(:request) { |args| expect(args[:path]).to eq "/apps/example/addons" expect(args[:body]).to include '"name":"heroku-postgresql:standard-0"' }.and_return(stringify(addon)) @addons.create end it "adds an addon with a price" do Excon.stub(method: :post, path: '/apps/example/addons') do addon = build_addon( name: "my_addon", addon_service: { name: "my_addon" }, app: { name: "example" }) { body: MultiJson.encode(addon), status: 201 } end stderr, stdout = execute("addons:create my_addon") expect(stderr).to eq("") expect(stdout).to match /Creating my_addon... done/ Excon.stubs.shift end it "adds an addon with a price and message" do Excon.stub(method: :post, path: '/apps/example/addons') do addon = build_addon( name: "my_addon", addon_service: { name: "my_addon" }, app: { name: "example" } ).merge(provision_message: "OMG A MESSAGE", plan: { price: { 'cents' => 1000, 'unit' => 'month' }}) { body: MultiJson.encode(addon), status: 201 } end stderr, stdout = execute("addons:create my_addon") expect(stderr).to eq("") expect(stdout).to eq <<-OUTPUT Creating my_addon... done, ($10.00/month) Adding my_addon to example... done OMG A MESSAGE Use `heroku addons:docs my_addon` to view documentation. OUTPUT Excon.stubs.shift end it "excludes addon plan from docs message" do Excon.stub(method: :post, path: '/apps/example/addons') do addon = build_addon( name: "my_addon", addon_service: { name: "my_addon" }, app: { name: "example" }) { body: MultiJson.encode(addon), status: 201 } end stderr, stdout = execute("addons:create my_addon:test") expect(stderr).to eq("") expect(stdout).to eq <<-OUTPUT Creating my_addon... done, (free) Adding my_addon to example... done Use `heroku addons:docs my_addon` to view documentation. OUTPUT Excon.stubs.shift end it "adds an addon with a price and multiline message" do Excon.stub(method: :post, path: '/apps/example/addons') do addon = build_addon( name: "my_addon", addon_service: { name: "my_addon" }, app: { name: "example" } ).merge(provision_message: "foo\nbar") { body: MultiJson.encode(addon), status: 201 } end stderr, stdout = execute("addons:create my_addon") expect(stderr).to eq("") expect(stdout).to eq <<-OUTPUT Creating my_addon... done, (free) Adding my_addon to example... done foo bar Use `heroku addons:docs my_addon` to view documentation. OUTPUT Excon.stubs.shift end it "displays an error with unexpected options" do expect(Heroku::Command).to receive(:error).with("Unexpected arguments: bar", false) run("addons:add redistogo -a foo bar") end end describe 'upgrading' do let(:addon) do build_addon(name: "my_addon", app: { name: "example" }, plan: { name: "my_addon" }) end before do allow(@addons).to receive(:args).and_return(%w(my_addon)) Excon.stub( { :expects => 200, :method => :get, :path => '/apps/example/releases/current' }, { :body => MultiJson.dump({ 'name' => 'v99' }), :status => 200, } ) end after do Excon.stubs.shift end it "requires an addon name" do allow(@addons).to receive(:args).and_return([]) expect { @addons.upgrade }.to raise_error(CommandFailed) end it "upgrades an addon" do allow(@addons).to receive(:resolve_addon!).and_return(stringify(addon)) allow(@addons).to receive(:args).and_return(%w(my_addon)) expect(@addons.api).to receive(:request) { |args| expect(args[:method]).to eq :patch expect(args[:path]).to eq "/apps/example/addons/my_addon" }.and_return(OpenStruct.new(body: stringify(addon))) @addons.upgrade end # TODO: need this? xit "upgrade an addon with config vars" do allow(@addons).to receive(:resolve_addon!).and_return(stringify(addon)) allow(@addons).to receive(:args).and_return(%w(my_addon --foo=baz)) expect(@addons.heroku).to receive(:upgrade_addon).with('example', 'my_addon', { 'foo' => 'baz' }) @addons.upgrade end it "upgrades an addon with a price" do my_addon = build_addon( name: "my_addon", plan: { name: "my_plan" }, addon_service: { name: "my_service" }, app: { name: "example" }, price: { cents: 0, unit: "month" }) Excon.stub(method: :get, path: '/apps/example/addons') do { body: MultiJson.encode([my_addon]), status: 200 } end Excon.stub(method: :get, path: '/apps/example/addons/my_service') do { body: MultiJson.encode(my_addon), status: 200 } end Excon.stub(method: :patch, path: '/apps/example/addons/my_addon') do { body: MultiJson.encode(my_addon), status: 200 } end stderr, stdout = execute("addons:upgrade my_service") expect(stderr).to eq("") expect(stdout).to eq <<-OUTPUT WARNING: No add-on name specified (see `heroku help addons:upgrade`) Finding add-on from service my_service on app example... done Found my_addon (my_plan) on example. Changing my_addon plan to my_service... done, (free) OUTPUT Excon.stubs.shift(2) end it "adds an addon with a price and multiline message" do my_addon = build_addon( name: "my_addon", plan: { name: "my_plan" }, addon_service: { name: "my_service" }, app: { name: "example" }, price: { cents: 0, unit: "month" } ).merge(provision_message: "foo\nbar") Excon.stub(method: :get, path: '/apps/example/addons') do { body: MultiJson.encode([my_addon]), status: 200 } end Excon.stub(method: :get, path: '/apps/example/addons/my_service') do { body: MultiJson.encode(my_addon), status: 200 } end Excon.stub(method: :patch, path: '/apps/example/addons/my_addon') do { body: MultiJson.encode(my_addon), status: 200 } end stderr, stdout = execute("addons:upgrade my_service") expect(stderr).to eq("") expect(stdout).to eq <<-OUTPUT WARNING: No add-on name specified (see `heroku help addons:upgrade`) Finding add-on from service my_service on app example... done Found my_addon (my_plan) on example. Changing my_addon plan to my_service... done, (free) foo bar OUTPUT Excon.stubs.shift(2) end end describe 'downgrading' do let(:addon) do build_addon( name: "my_addon", addon_service: { name: "my_service" }, plan: { name: "my_plan" }, app: { name: "example" }) end before do Excon.stub( { :expects => 200, :method => :get, :path => '/apps/example/releases/current' }, { :body => MultiJson.dump({ 'name' => 'v99' }), :status => 200, } ) end after do Excon.stubs.shift end it "requires an addon name" do allow(@addons).to receive(:args).and_return([]) expect { @addons.downgrade }.to raise_error(CommandFailed) end it "downgrades an addon" do allow(@addons).to receive(:args).and_return(%w(my_service low_plan)) allow(@addons.api).to receive(:request) { |args| expect(args[:method]).to eq :patch expect(args[:path]).to eq "/apps/example/addons/my_service" }.and_return(OpenStruct.new(body: stringify(addon))) @addons.downgrade end it "downgrade an addon with config vars" do allow(@addons).to receive(:args).and_return(%w(my_service --foo=baz)) allow(@addons.api).to receive(:request) { |args| expect(args[:method]).to eq :patch expect(args[:path]).to eq "/apps/example/addons/my_service" }.and_return(OpenStruct.new(body: stringify(addon))) @addons.downgrade end describe "console output" do before do my_addon = build_addon( name: "my_addon", plan: { name: "my_plan" }, addon_service: { name: "my_service" }, app: { name: "example" }) Excon.stub(method: :get, path: '/apps/example/addons') do { body: MultiJson.encode([my_addon]), status: 200 } end Excon.stub(method: :patch, path: '/apps/example/addons/my_service') do { body: MultiJson.encode(my_addon), status: 200 } end Excon.stub(method: :patch, path: '/apps/example/addons/my_addon') do { body: MultiJson.encode(my_addon), status: 200 } end end after do Excon.stubs.shift(2) end it "downgrades an addon with a price" do stderr, stdout = execute("addons:downgrade my_service low_plan") expect(stderr).to eq("") expect(stdout).to eq <<-OUTPUT Changing my_service plan to low_plan... done, (free) OUTPUT end end end it "does not destroy addons with no confirm" do allow(@addons).to receive(:args).and_return(%w( addon1 )) allow(@addons).to receive(:resolve_addon!).and_return({"app" => { "name" => "example" }}) expect(@addons).to receive(:confirm_command).once.and_return(false) expect(@addons.api).not_to receive(:request).with(hash_including(method: :delete)) @addons.destroy end it "destroys addons after prompting for confirmation" do allow(@addons).to receive(:args).and_return(%w( addon1 )) expect(@addons).to receive(:confirm_command).once.and_return(true) allow(@addons).to receive(:get_attachments).and_return([]) allow(@addons).to receive(:resolve_addon!).and_return({ "id" => "abc123", "config_vars" => [], "app" => { "id" => "123", "name" => "example" } }) allow(@addons.api).to receive(:request) { |args| expect(args[:path]).to eq "/apps/123/addons/abc123" }.and_return(OpenStruct.new(body: stringify(addon))) @addons.destroy end it "destroys addons with confirm option" do allow(Heroku::Command).to receive(:current_options).and_return(:confirm => "example") allow(@addons).to receive(:args).and_return(%w( addon1 )) allow(@addons).to receive(:get_attachments).and_return([]) allow(@addons).to receive(:resolve_addon!).and_return({ "id" => "abc123", "config_vars" => [], "app" => { "id" => "123", "name" => "example" } }) allow(@addons.api).to receive(:request) { |args| expect(args[:path]).to eq "/apps/123/addons/abc123" }.and_return(OpenStruct.new(body: stringify(addon))) @addons.destroy end describe "opening add-on docs" do before(:each) do stub_core api.post_app("name" => "example", "stack" => "cedar") require "launchy" allow(Launchy).to receive(:open) end after(:each) do api.delete_app("example") end it "displays usage when no argument is specified" do stderr, stdout = execute('addons:docs') expect(stderr).to eq <<-STDERR ! Usage: heroku addons:docs ADDON ! Must specify ADDON to open docs for. STDERR expect(stdout).to eq('') end it "opens the addon if only one matches" do require("launchy") expect(Launchy).to receive(:open).with("https://devcenter.heroku.com/articles/redistogo").and_return(Thread.new {}) stderr, stdout = execute('addons:docs redistogo:nano') expect(stderr).to eq('') expect(stdout).to eq <<-STDOUT Opening redistogo docs... done STDOUT end it "complains when many_per_app" do addon1 = stringify(addon.merge(name: "my_addon1", addon_service: { name: "my_service" })) addon2 = stringify(addon.merge(name: "my_addon2", addon_service: { name: "my_service_2" })) Excon.stub(method: :get, path: '/addon-services/thing') do { status: 404, body:'{}' } end Excon.stub(method: :get, path: '/apps/example/addons/thing') do { status: 404, body:'{}' } end Excon.stub(method: :get, path: '/addons/thing') do { status: 422, body: MultiJson.encode( id: "multiple_matches", message: "Ambiguous identifier; multiple matching add-ons found: my_addon1 (my_service), my_addon2 (my_service_2)." ) } end stderr, stdout = execute('addons:docs thing') expect(stdout).to eq('') expect(stderr).to eq <<-STDERR ! Multiple add-ons match "my_service". ! Use the name of one of the add-on resources: ! ! - my_addon1 (my_service) ! - my_addon2 (my_service_2) STDERR end it "optimistically opens the page if nothing matches" do Excon.stub(method: :get, path: %r(/addons/unknown)) do { status: 404 } end Excon.stub(method: :get, path: '/apps/example/addons') do { body: "[]", status: 200 } end expect(Launchy).to receive(:open).with("https://devcenter.heroku.com/articles/unknown").and_return(Thread.new {}) stderr, stdout = execute('addons:docs unknown') expect(stdout).to eq "Opening unknown docs... done\n" Excon.stubs.shift(2) end end describe "opening an addon" do before(:each) do stub_core api.post_app("name" => "example", "stack" => "cedar") end after(:each) do api.delete_app("example") end it "displays usage when no argument is specified" do stderr, stdout = execute('addons:open') expect(stderr).to eq <<-STDERR ! Usage: heroku addons:open ADDON ! Must specify ADDON to open. STDERR expect(stdout).to eq('') end it "opens the addon if only one matches" do addon.merge!(addon_service: { name: "redistogo:nano" }) allow_any_instance_of(Heroku::Command::Addons).to receive(:resolve_addon).and_return([stringify(addon)]) require("launchy") expect(Launchy).to receive(:open).with("https://addons-sso.heroku.com/apps/example/addons/#{addon[:id]}").and_return(Thread.new {}) stderr, stdout = execute('addons:open redistogo:nano') expect(stderr).to eq('') expect(stdout).to eq <<-STDOUT Opening redistogo:nano (my_addon) for example... done STDOUT end it "complains about ambiguity" do addon.merge!(addon_service: { name: "deployhooks:email" }) email = stringify(addon.merge(name: "my_email", plan: { name: "email" })) http = stringify(addon.merge(name: "my_http", plan: { name: "http" })) allow_any_instance_of(Heroku::Command::Addons).to receive(:resolve_addon).and_return([email, http]) stderr, stdout = execute('addons:open deployhooks') expect(stderr).to eq <<-STDERR ! Multiple add-ons match "deployhooks". ! Use the name of add-on resource: ! ! - my_email (email) ! - my_http (http) STDERR expect(stdout).to eq('') end it "complains if no such addon exists" do stderr, stdout = execute('addons:open unknown') expect(stderr).to eq <<-STDERR ! Can not find add-on with "unknown" STDERR expect(stdout).to eq('') end it "complains if addon is not installed" do stderr, stdout = execute('addons:open deployhooks:http') expect(stderr).to eq <<-STDOUT ! Can not find add-on with "deployhooks:http" STDOUT expect(stdout).to eq('') end end end end Fix broken tests and remove irrelevant tests require "spec_helper" require "heroku/command/addons" module Heroku::Command describe Addons do include Support::Addons let(:addon) { build_addon(name: "my_addon", app: { name: "example" }) } before do @addons = prepare_command(Addons) stub_core.release("example", "current").returns( "name" => "v99" ) end describe "#index" do before(:each) do stub_core api.post_app("name" => "example", "stack" => "cedar") end after(:each) do api.delete_app("example") end it "should display no addons when none are configured" do Excon.stub(method: :get, path: '/apps/example/addons') do { body: "[]", status: 200 } end Excon.stub(method: :get, path: '/apps/example/addon-attachments') do { body: "[]", status: 200 } end stderr, stdout = execute("addons") expect(stderr).to eq("") expect(stdout).to eq <<-STDOUT === Resources for example There are no add-ons. === Attachments for example There are no attachments. STDOUT Excon.stubs.shift(2) end it "should list addons and attachments" do Excon.stub(method: :get, path: '/apps/example/addons') do hooks = build_addon( name: "swimming-nicely-42", plan: { name: "deployhooks:http", price: { cents: 0, unit: "month" }}, app: { name: "example" }) hpg = build_addon( name: "jumping-slowly-76", plan: { name: "heroku-postgresql:ronin", price: { cents: 20000, unit: "month" }}, app: { name: "example" }) { body: MultiJson.encode([hooks, hpg]), status: 200 } end Excon.stub(method: :get, path: '/apps/example/addon-attachments') do hpg = build_attachment( name: "HEROKU_POSTGRESQL_CYAN", addon: { name: "heroku-postgresql-12345", app: { name: "example" }}, app: { name: "example" }) { body: MultiJson.encode([hpg]), status: 200 } end stderr, stdout = execute("addons") expect(stderr).to eq("") expect(stdout).to eq <<-STDOUT === Resources for example Plan Name Price ----------------------- ------------------ ------------- deployhooks:http swimming-nicely-42 free heroku-postgresql:ronin jumping-slowly-76 $200.00/month === Attachments for example Name Add-on Billing App ---------------------- ----------------------- ----------- HEROKU_POSTGRESQL_CYAN heroku-postgresql-12345 example STDOUT Excon.stubs.shift(2) end end describe "list" do before do Excon.stub(method: :get, path: '/addon-services') do services = [ { "name" => "cloudcounter:basic", "state" => "alpha" }, { "name" => "cloudcounter:pro", "state" => "public" }, { "name" => "cloudcounter:gold", "state" => "public" }, { "name" => "cloudcounter:old", "state" => "disabled" }, { "name" => "cloudcounter:platinum", "state" => "beta" } ] { body: MultiJson.encode(services), status: 200 } end end after do Excon.stubs.shift end # TODO: plugin code doesn't support this. Do we need it? xit "sends region option to the server" do stub_request(:get, '/addon-services?region=eu'). to_return(:body => MultiJson.dump([])) execute("addons:list --region=eu") end describe "when using the deprecated `addons:list` command" do it "displays a deprecation warning" do stderr, stdout = execute("addons:list") expect(stderr).to eq("") expect(stdout).to include "WARNING: `heroku addons:list` has been deprecated. Please use `heroku addons:services` instead." end end describe "when using correct `addons:services` command" do it "displays all services" do stderr, stdout = execute("addons:services") expect(stderr).to eq("") expect(stdout).to eq <<-STDOUT Slug Name State --------------------- ---- -------- cloudcounter:basic alpha cloudcounter:pro public cloudcounter:gold public cloudcounter:old disabled cloudcounter:platinum beta See plans with `heroku addons:plans SERVICE` STDOUT end end end describe 'v1-style command line params' do before do Excon.stub(method: :post, path: '/apps/example/addons') do { body: MultiJson.encode(addon), status: 201 } end end after do Excon.stubs.shift end it "understands foo=baz" do allow(@addons).to receive(:args).and_return(%w(my_addon foo=baz)) allow(@addons.api).to receive(:request) { |params| expect(params[:body]).to include '"foo":"baz"' }.and_return(double(body: stringify(addon))) @addons.create end describe "addons:add" do before do Excon.stub(method: :get, path: '/apps/example/releases/current') do { body: MultiJson.dump({ 'name' => 'v99' }), status: 200 } end Excon.stub(method: :post, path: '/apps/example/addons/my_addon') do { body: MultiJson.encode(price: "free"), status: 200 } end end after do Excon.stubs.shift(2) end it "shows a deprecation warning about addon:add vs addons:create" do stderr, stdout = execute("addons:add my_addon --foo=bar extra=XXX") expect(stderr).to eq("") expect(stdout).to include "WARNING: `heroku addons:add` has been deprecated. Please use `heroku addons:create` instead." end it "shows a deprecation warning about non-unix params" do stderr, stdout = execute("addons:add my_addon --foo=bar extra=XXX") expect(stderr).to eq("") expect(stdout).to include "Warning: non-unix style params have been deprecated, use --extra=XXX instead" end end end describe 'unix-style command line params' do it "understands --foo=baz" do allow(@addons).to receive(:args).and_return(%w(my_addon --foo=baz)) allow(@addons).to receive(:request) { |args| expect(args[:body]).to include '"foo":"baz"' }.and_return(stringify(addon)) @addons.create end it "understands --foo baz" do allow(@addons).to receive(:args).and_return(%w(my_addon --foo baz)) expect(@addons).to receive(:request) { |args| expect(args[:body]).to include '"foo":"baz"' }.and_return(stringify(addon)) @addons.create end it "treats lone switches as true" do allow(@addons).to receive(:args).and_return(%w(my_addon --foo)) expect(@addons).to receive(:request) { |args| expect(args[:body]).to include '"foo":true' }.and_return(stringify(addon)) @addons.create end it "converts 'true' to boolean" do allow(@addons).to receive(:args).and_return(%w(my_addon --foo=true)) expect(@addons).to receive(:request) { |args| expect(args[:body]).to include '"foo":true' }.and_return(stringify(addon)) @addons.create end it "works with many config vars" do allow(@addons).to receive(:args).and_return(%w(my_addon --foo baz --bar yes --baz=foo --bab --bob=true)) expect(@addons).to receive(:request) { |args| expect(args[:body]).to include({ foo: 'baz', bar: 'yes', baz: 'foo', bab: true, bob: true }.to_json) }.and_return(stringify(addon)) @addons.create end it "raises an error for spurious arguments" do allow(@addons).to receive(:args).and_return(%w(my_addon spurious)) expect { @addons.create }.to raise_error(CommandFailed) end end describe "mixed options" do it "understands foo=bar and --baz=bar on the same line" do allow(@addons).to receive(:args).and_return(%w(my_addon foo=baz --baz=bar bob=true --bar)) expect(@addons).to receive(:request) { |args| expect(args[:body]).to include '"foo":"baz"' expect(args[:body]).to include '"baz":"bar"' expect(args[:body]).to include '"bar":true' expect(args[:body]).to include '"bob":true' }.and_return(stringify(addon)) @addons.create end it "sends the variables to the server" do Excon.stub(method: :post, path: '/apps/example/addons') do { body: MultiJson.encode(addon), status: 201 } end stderr, stdout = execute("addons:add my_addon foo=baz --baz=bar bob=true --bar") expect(stderr).to eq("") expect(stdout).to include("Warning: non-unix style params have been deprecated, use --foo=baz --bob=true instead") Excon.stubs.shift end end describe "fork, follow, and rollback switches" do it "should only resolve for heroku-postgresql addon" do %w{fork follow rollback}.each do |switch| allow(@addons).to receive(:args).and_return("addon --#{switch} HEROKU_POSTGRESQL_RED".split) allow(@addons).to receive(:request) { |args| expect(args[:body]).to include %("#{switch}":"HEROKU_POSTGRESQL_RED") }.and_return(stringify(addon)) @addons.create end end it "should NOT translate --fork and --follow if passed in a full postgres url even if there are no databases" do %w{fork follow}.each do |switch| allow(@addons).to receive(:app_config_vars).and_return({}) allow(@addons).to receive(:app_attachments).and_return([]) allow(@addons).to receive(:args).and_return("heroku-postgresql:ronin --#{switch} postgres://foo:yeah@awesome.com:234/bestdb".split) allow(@addons).to receive(:request) { |args| expect(args[:body]).to include %("#{switch}":"postgres://foo:yeah@awesome.com:234/bestdb") }.and_return(stringify(addon)) @addons.create end end # TODO: ? xit "should fail if fork / follow across applications and no plan is specified" do %w{fork follow}.each do |switch| allow(@addons).to receive(:app_config_vars).and_return({}) allow(@addons).to receive(:app_attachments).and_return([]) allow(@addons).to receive(:args).and_return("heroku-postgresql --#{switch} postgres://foo:yeah@awesome.com:234/bestdb".split) expect { @addons.create }.to raise_error(CommandFailed) end end end describe 'adding' do before do allow(@addons).to receive(:args).and_return(%w(my_addon)) Excon.stub( { :expects => 200, :method => :get, :path => '/apps/example/releases/current' }, { :body => MultiJson.dump({ 'name' => 'v99' }), :status => 200, } ) end after do Excon.stubs.shift end it "requires an addon name" do allow(@addons).to receive(:args).and_return([]) expect { @addons.create }.to raise_error(CommandFailed) end it "adds an addon" do allow(@addons).to receive(:args).and_return(%w(my_addon)) allow(@addons).to receive(:request) { |args| expect(args[:path]).to eq "/apps/example/addons" expect(args[:body]).to include '"name":"my_addon"' }.and_return(stringify(addon)) @addons.create end it "expands hgp:s0 to heroku-postgresql:standard-0" do allow(@addons).to receive(:args).and_return(%w(hpg:s0)) allow(@addons).to receive(:request) { |args| expect(args[:path]).to eq "/apps/example/addons" expect(args[:body]).to include '"name":"heroku-postgresql:standard-0"' }.and_return(stringify(addon)) @addons.create end it "adds an addon with a price" do Excon.stub(method: :post, path: '/apps/example/addons') do addon = build_addon( name: "my_addon", addon_service: { name: "my_addon" }, app: { name: "example" }) { body: MultiJson.encode(addon), status: 201 } end stderr, stdout = execute("addons:create my_addon") expect(stderr).to eq("") expect(stdout).to match /Creating my_addon... done/ Excon.stubs.shift end it "adds an addon with a price and message" do Excon.stub(method: :post, path: '/apps/example/addons') do addon = build_addon( name: "my_addon", addon_service: { name: "my_addon" }, app: { name: "example" } ).merge(provision_message: "OMG A MESSAGE", plan: { price: { 'cents' => 1000, 'unit' => 'month' }}) { body: MultiJson.encode(addon), status: 201 } end stderr, stdout = execute("addons:create my_addon") expect(stderr).to eq("") expect(stdout).to eq <<-OUTPUT Creating my_addon... done, ($10.00/month) Adding my_addon to example... done OMG A MESSAGE Use `heroku addons:docs my_addon` to view documentation. OUTPUT Excon.stubs.shift end it "excludes addon plan from docs message" do Excon.stub(method: :post, path: '/apps/example/addons') do addon = build_addon( name: "my_addon", addon_service: { name: "my_addon" }, app: { name: "example" }) { body: MultiJson.encode(addon), status: 201 } end stderr, stdout = execute("addons:create my_addon:test") expect(stderr).to eq("") expect(stdout).to eq <<-OUTPUT Creating my_addon... done, (free) Adding my_addon to example... done Use `heroku addons:docs my_addon` to view documentation. OUTPUT Excon.stubs.shift end it "adds an addon with a price and multiline message" do Excon.stub(method: :post, path: '/apps/example/addons') do addon = build_addon( name: "my_addon", addon_service: { name: "my_addon" }, app: { name: "example" } ).merge(provision_message: "foo\nbar") { body: MultiJson.encode(addon), status: 201 } end stderr, stdout = execute("addons:create my_addon") expect(stderr).to eq("") expect(stdout).to eq <<-OUTPUT Creating my_addon... done, (free) Adding my_addon to example... done foo bar Use `heroku addons:docs my_addon` to view documentation. OUTPUT Excon.stubs.shift end it "displays an error with unexpected options" do expect(Heroku::Command).to receive(:error).with("Unexpected arguments: bar", false) run("addons:add redistogo -a foo bar") end end describe 'upgrading' do let(:addon) do build_addon(name: "my_addon", app: { name: "example" }, plan: { name: "my_addon" }) end before do allow(@addons).to receive(:args).and_return(%w(my_addon)) Excon.stub( { :expects => 200, :method => :get, :path => '/apps/example/releases/current' }, { :body => MultiJson.dump({ 'name' => 'v99' }), :status => 200, } ) end after do Excon.stubs.shift end it "requires an addon name" do allow(@addons).to receive(:args).and_return([]) expect { @addons.upgrade }.to raise_error(CommandFailed) end it "upgrades an addon" do allow(@addons).to receive(:resolve_addon!).and_return(stringify(addon)) allow(@addons).to receive(:args).and_return(%w(my_addon)) expect(@addons.api).to receive(:request) { |args| expect(args[:method]).to eq :patch expect(args[:path]).to eq "/apps/example/addons/my_addon" }.and_return(OpenStruct.new(body: stringify(addon))) @addons.upgrade end # TODO: need this? xit "upgrade an addon with config vars" do allow(@addons).to receive(:resolve_addon!).and_return(stringify(addon)) allow(@addons).to receive(:args).and_return(%w(my_addon --foo=baz)) expect(@addons.heroku).to receive(:upgrade_addon).with('example', 'my_addon', { 'foo' => 'baz' }) @addons.upgrade end it "upgrades an addon with a price" do my_addon = build_addon( name: "my_addon", plan: { name: "my_plan" }, addon_service: { name: "my_service" }, app: { name: "example" }, price: { cents: 0, unit: "month" }) Excon.stub(method: :get, path: '/apps/example/addons') do { body: MultiJson.encode([my_addon]), status: 200 } end Excon.stub(method: :get, path: '/apps/example/addons/my_service') do { body: MultiJson.encode(my_addon), status: 200 } end Excon.stub(method: :patch, path: '/apps/example/addons/my_addon') do { body: MultiJson.encode(my_addon), status: 200 } end stderr, stdout = execute("addons:upgrade my_service") expect(stderr).to eq("") expect(stdout).to eq <<-OUTPUT WARNING: No add-on name specified (see `heroku help addons:upgrade`) Finding add-on from service my_service on app example... done Found my_addon (my_plan) on example. Changing my_addon plan to my_service... done, (free) OUTPUT Excon.stubs.shift(2) end it "adds an addon with a price and multiline message" do my_addon = build_addon( name: "my_addon", plan: { name: "my_plan" }, addon_service: { name: "my_service" }, app: { name: "example" }, price: { cents: 0, unit: "month" } ).merge(provision_message: "foo\nbar") Excon.stub(method: :get, path: '/apps/example/addons') do { body: MultiJson.encode([my_addon]), status: 200 } end Excon.stub(method: :get, path: '/apps/example/addons/my_service') do { body: MultiJson.encode(my_addon), status: 200 } end Excon.stub(method: :patch, path: '/apps/example/addons/my_addon') do { body: MultiJson.encode(my_addon), status: 200 } end stderr, stdout = execute("addons:upgrade my_service") expect(stderr).to eq("") expect(stdout).to eq <<-OUTPUT WARNING: No add-on name specified (see `heroku help addons:upgrade`) Finding add-on from service my_service on app example... done Found my_addon (my_plan) on example. Changing my_addon plan to my_service... done, (free) foo bar OUTPUT Excon.stubs.shift(2) end end describe 'downgrading' do let(:addon) do build_addon( name: "my_addon", addon_service: { name: "my_service" }, plan: { name: "my_plan" }, app: { name: "example" }) end before do Excon.stub( { :expects => 200, :method => :get, :path => '/apps/example/releases/current' }, { :body => MultiJson.dump({ 'name' => 'v99' }), :status => 200, } ) end after do Excon.stubs.shift end it "requires an addon name" do allow(@addons).to receive(:args).and_return([]) expect { @addons.downgrade }.to raise_error(CommandFailed) end it "downgrades an addon" do allow(@addons).to receive(:args).and_return(%w(my_service low_plan)) allow(@addons.api).to receive(:request) { |args| expect(args[:method]).to eq :patch expect(args[:path]).to eq "/apps/example/addons/my_service" }.and_return(OpenStruct.new(body: stringify(addon))) @addons.downgrade end it "downgrade an addon with config vars" do allow(@addons).to receive(:args).and_return(%w(my_service --foo=baz)) allow(@addons.api).to receive(:request) { |args| expect(args[:method]).to eq :patch expect(args[:path]).to eq "/apps/example/addons/my_service" }.and_return(OpenStruct.new(body: stringify(addon))) @addons.downgrade end describe "console output" do before do my_addon = build_addon( name: "my_addon", plan: { name: "my_plan" }, addon_service: { name: "my_service" }, app: { name: "example" }) Excon.stub(method: :get, path: '/apps/example/addons') do { body: MultiJson.encode([my_addon]), status: 200 } end Excon.stub(method: :patch, path: '/apps/example/addons/my_service') do { body: MultiJson.encode(my_addon), status: 200 } end Excon.stub(method: :patch, path: '/apps/example/addons/my_addon') do { body: MultiJson.encode(my_addon), status: 200 } end end after do Excon.stubs.shift(2) end it "downgrades an addon with a price" do stderr, stdout = execute("addons:downgrade my_service low_plan") expect(stderr).to eq("") expect(stdout).to eq <<-OUTPUT Changing my_service plan to low_plan... done, (free) OUTPUT end end end it "does not destroy addons with no confirm" do allow(@addons).to receive(:args).and_return(%w( addon1 )) allow(@addons).to receive(:resolve_addon!).and_return({"app" => { "name" => "example" }}) expect(@addons).to receive(:confirm_command).once.and_return(false) expect(@addons.api).not_to receive(:request).with(hash_including(method: :delete)) @addons.destroy end it "destroys addons after prompting for confirmation" do allow(@addons).to receive(:args).and_return(%w( addon1 )) expect(@addons).to receive(:confirm_command).once.and_return(true) allow(@addons).to receive(:get_attachments).and_return([]) allow(@addons).to receive(:resolve_addon!).and_return({ "id" => "abc123", "config_vars" => [], "app" => { "id" => "123", "name" => "example" } }) allow(@addons.api).to receive(:request) { |args| expect(args[:path]).to eq "/apps/123/addons/abc123" }.and_return(OpenStruct.new(body: stringify(addon))) @addons.destroy end it "destroys addons with confirm option" do allow(Heroku::Command).to receive(:current_options).and_return(:confirm => "example") allow(@addons).to receive(:args).and_return(%w( addon1 )) allow(@addons).to receive(:get_attachments).and_return([]) allow(@addons).to receive(:resolve_addon!).and_return({ "id" => "abc123", "config_vars" => [], "app" => { "id" => "123", "name" => "example" } }) allow(@addons.api).to receive(:request) { |args| expect(args[:path]).to eq "/apps/123/addons/abc123" }.and_return(OpenStruct.new(body: stringify(addon))) @addons.destroy end describe "opening add-on docs" do before(:each) do stub_core api.post_app("name" => "example", "stack" => "cedar") require "launchy" allow(Launchy).to receive(:open) end after(:each) do api.delete_app("example") end it "displays usage when no argument is specified" do stderr, stdout = execute('addons:docs') expect(stderr).to eq <<-STDERR ! Usage: heroku addons:docs ADDON ! Must specify ADDON to open docs for. STDERR expect(stdout).to eq('') end it "opens the addon if only one matches" do require("launchy") expect(Launchy).to receive(:open).with("https://devcenter.heroku.com/articles/redistogo").and_return(Thread.new {}) stderr, stdout = execute('addons:docs redistogo:nano') expect(stderr).to eq('') expect(stdout).to eq <<-STDOUT Opening redistogo docs... done STDOUT end it "complains when many_per_app" do addon1 = stringify(addon.merge(name: "my_addon1", addon_service: { name: "my_service" })) addon2 = stringify(addon.merge(name: "my_addon2", addon_service: { name: "my_service_2" })) Excon.stub(method: :get, path: '/addon-services/thing') do { status: 404, body:'{}' } end Excon.stub(method: :get, path: '/apps/example/addons/thing') do { status: 404, body:'{}' } end Excon.stub(method: :get, path: '/addons/thing') do { status: 422, body: MultiJson.encode( id: "multiple_matches", message: "Ambiguous identifier; multiple matching add-ons found: my_addon1 (my_service), my_addon2 (my_service_2)." ) } end expect { execute('addons:docs thing') }.to raise_error(Heroku::API::Errors::RequestFailed) end end describe "opening an addon" do before(:each) do stub_core api.post_app("name" => "example", "stack" => "cedar") end after(:each) do api.delete_app("example") end it "displays usage when no argument is specified" do stderr, stdout = execute('addons:open') expect(stderr).to eq <<-STDERR ! Usage: heroku addons:open ADDON ! Must specify ADDON to open. STDERR expect(stdout).to eq('') end it "opens the addon if only one matches" do addon.merge!(addon_service: { name: "redistogo:nano" }) allow_any_instance_of(Heroku::Command::Addons).to receive(:resolve_addon!).and_return(stringify(addon)) require("launchy") expect(Launchy).to receive(:open).with("https://addons-sso.heroku.com/apps/example/addons/#{addon[:id]}").and_return(Thread.new {}) stderr, stdout = execute('addons:open redistogo:nano') expect(stderr).to eq('') expect(stdout).to eq <<-STDOUT Opening redistogo:nano (my_addon) for example... done STDOUT end it "complains if no such addon exists" do Excon.stub(method: :get, path: %r'(/apps/example)?/addons/unknown') do { status: 404, body:'{"error": "hi"}' } end expect { execute('addons:open unknown') }.to raise_error(Heroku::API::Errors::NotFound) end it "complains if addon is not installed" do Excon.stub(method: :get, path: %r'(/apps/example)?/addons/deployhooks:http') do { status: 404, body:'{"error": "hi"}' } end expect { execute('addons:open deployhooks:http') }.to raise_error(Heroku::API::Errors::NotFound) end end end end
require "formula" require "language/haskell" class PandocCiteproc < Formula include Language::Haskell::Cabal homepage "https://github.com/jgm/pandoc-citeproc" url "https://hackage.haskell.org/package/pandoc-citeproc-0.4.0.1/pandoc-citeproc-0.4.0.1.tar.gz" sha1 "41c71939d78bfe52f4dd06ca3d7a6b4d824cdd47" bottle do sha1 "2618b1e023b264474fd89b9d6e824bca80397043" => :mavericks sha1 "7785694f8d11478a04f6cc6b02370655ba9a20bc" => :mountain_lion sha1 "f891ee011d1de27eca51e17e9f9e7dc9baf75e0f" => :lion end depends_on "ghc" => :build depends_on "cabal-install" => :build depends_on "gmp" depends_on "pandoc" => :recommended def install cabal_sandbox do cabal_install "--only-dependencies" cabal_install "--prefix=#{prefix}" end cabal_clean_lib end test do bib = testpath/"test.bib" bib.write <<-EOS.undent @Book{item1, author="John Doe", title="First Book", year="2005", address="Cambridge", publisher="Cambridge University Press" } EOS assert `pandoc-citeproc --bib2yaml #{bib}`.include? "- publisher-place: Cambridge" end end pandoc-citeproc: update 0.4.0.1 bottle. require "formula" require "language/haskell" class PandocCiteproc < Formula include Language::Haskell::Cabal homepage "https://github.com/jgm/pandoc-citeproc" url "https://hackage.haskell.org/package/pandoc-citeproc-0.4.0.1/pandoc-citeproc-0.4.0.1.tar.gz" sha1 "41c71939d78bfe52f4dd06ca3d7a6b4d824cdd47" bottle do sha1 "e1a339c04e78a4d7fba542336e655f24fa029bbe" => :mavericks sha1 "b00f823667e3a2775388758af7ed309ddc5a761e" => :mountain_lion sha1 "332eb0a1d2754606f74731e30ee3e76320947389" => :lion end depends_on "ghc" => :build depends_on "cabal-install" => :build depends_on "gmp" depends_on "pandoc" => :recommended def install cabal_sandbox do cabal_install "--only-dependencies" cabal_install "--prefix=#{prefix}" end cabal_clean_lib end test do bib = testpath/"test.bib" bib.write <<-EOS.undent @Book{item1, author="John Doe", title="First Book", year="2005", address="Cambridge", publisher="Cambridge University Press" } EOS assert `pandoc-citeproc --bib2yaml #{bib}`.include? "- publisher-place: Cambridge" end end
require 'spec_helper' module IBANTools describe Conversion do IBAN_FOR_TEST = { 'AD1200012030200359100100' => {bank_code: '1', branch_code: '2030', account_number: '200359100100'}, 'AE070331234567890123456' => {bank_code: '33', account_number: '1234567890123456'}, 'AL47212110090000000235698741' => {bank_code: '212', branch_code: '1100', check_digit: '9', account_number: '235698741'}, 'AT611904300234573201' => {bank_code: '19043', account_number: '234573201'}, 'AZ21NABZ00000000137010001944' => {bank_code: 'NABZ', account_number: '137010001944'}, 'BA391290079401028494' => {bank_code: '129', branch_code: '7', account_number: '94010284', check_digits: '94'}, 'BE68539007547034' => {bank_code: '539', account_number: '75470', check_digits: '34'}, 'BG80BNBG96611020345678' => {bank_code: 'BNBG', branch_code: '9661', account_type: '10', account_number: '20345678'}, 'BH67BMAG00001299123456' => {bank_code: 'BMAG', account_number: '1299123456'}, 'CH9300762011623852957' => {bank_code: '762', account_number: '11623852957'}, 'CY17002001280000001200527600' => {bank_code: '2', branch_code: '128', account_number: '1200527600'}, 'CZ6508000000192000145399' => {bank_code: '800', account_prefix: '19', account_number: '2000145399'}, 'DE89370400440532013000' => {blz: '37040044', account_number: '532013000'}, 'DK5000400440116243' => {bank_code: '40', account_number: '440116243'}, 'DO28BAGR00000001212453611324' => {bank_code: 'BAGR', account_number: '1212453611324'}, 'EE382200221020145685' => {bank_code: '22', branch_code: '0', account_number: '2210201456', check_digits: '85'}, 'ES9121000418450200051332' => {account_number: '21000418450200051332'}, 'FI2112345600000785' => {bank_code: '123456', account_number: '78', check_digit: '5'}, 'FO7630004440960235' => {bank_code: '3000', account_number: '444096023', check_digit: '5'}, 'FR1420041010050500013M02606' => {bank_code: '20041', branch_code: '1005', account_number: '500013M026', check_digits: '6'}, 'GB29NWBK60161331926819' => {bank_code: 'NWBK', branch_code: '601613', account_number: '31926819'}, 'GE29NB0000000101904917' => {bank_code: 'NB', account_number: '101904917'}, 'GI75NWBK000000007099453' => {bank_code: 'NWBK',account_number: '7099453'}, 'GL4330003330229543' => {bank_code: '3000', account_number: '3330229543'}, 'GR1601101250000000012300695' => {bank_code: '11', branch_code: '125', account_number: '12300695'}, 'HR1210010051863000160' => {bank_code: '1001005', account_number: '1863000160'}, 'HU42117730161111101800000000' => {bank_code: '117', branch_code: '7301', account_prefix: '6', account_number: '111110180000000', check_digit: '0'}, 'IE29AIBK93115212345678' => {bank_code: 'AIBK', branch_code: '931152', account_number: '12345678'}, 'IL620108000000099999999' => {bank_code: '10', branch_code: '800', account_number: '99999999'}, 'IS140159260076545510730339' => {bank_code: '159', branch_code: '26', account_number: '7654', kennitala: '5510730339'}, 'IT60X0542811101000000123456' => {check_char: 'X', bank_code: '5428', branch_code: '11101', account_number: '123456'}, 'JO94CBJO0010000000000131000302' => {bank_code: 'CBJO', branch_code: '10', zeros: '0', account_number: '131000302'}, 'KW81CBKU0000000000001234560101' => {bank_code: 'CBKU', account_number: '1234560101'}, 'KZ86125KZT5004100100' => {bank_code: '125', account_number: 'KZT5004100100'}, 'LB62099900000001001901229114' => {bank_code: '999', account_number: '1001901229114'}, 'LI21088100002324013AA' => {bank_code: '8810', account_number: '2324013AA'}, 'LT121000011101001000' => {bank_code: '10000', account_number: '11101001000'}, 'LU280019400644750000' => {bank_code: '1', account_number: '9400644750000'}, 'LV80BANK0000435195001' => {bank_code: 'BANK', account_number: '435195001'}, 'MC1112739000700011111000H79' => {bank_code: '12739',branch_code: '70', account_number: '11111000H', check_digits: '79'}, 'MD24AG000225100013104168' => {bank_code: 'AG', account_number: '225100013104168'}, 'ME25505000012345678951' => {bank_code: '505', account_number: '123456789', check_digits: '51'}, 'MK07300000000042425' => {bank_code: '300', account_number: '424', check_digits: '25'}, 'MR1300020001010000123456753' => {bank_code: '20', branch_code: '101', account_number: '1234567', check_digits: '53'}, 'MT84MALT011000012345MTLCAST001S' => {bank_code: 'MALT', branch_code: '1100', account_number: '12345MTLCAST001S'}, 'MU17BOMM0101101030300200000MUR' => {bank_code: 'BOMM01', branch_code: '1', account_number: '101030300200000MUR'}, 'NL91ABNA0417164300' => {bank_code: 'ABNA', account_number: '417164300'}, 'NO9386011117947' => {bank_code: '8601', account_number: '111794', check_digit: '7'}, 'PK36SCBL0000001123456702' => {bank_code: 'SCBL', account_number: '1123456702'}, 'PL27114020040000300201355387' => {bank_code: '114', branch_code: '200', check_digit: '4', account_number: '300201355387'}, 'PS92PALS000000000400123456702' => {bank_code: 'PALS', account_number: '400123456702'}, 'PT50000201231234567890154' => {bank_code: '2', branch_code: '123', account_number: '12345678901', check_digits: '54'}, 'QA58DOHB00001234567890ABCDEFG' => {bank_code: 'DOHB', account_number: '1234567890ABCDEFG'}, 'RO49AAAA1B31007593840000' => {bank_code: 'AAAA', account_number: '1B31007593840000'}, 'RS35260005601001611379' => {bank_code: '260', account_number: '56010016113', check_digits: '79'}, 'SA0380000000608010167519' => {bank_code: '80', account_number: '608010167519'}, 'SE3550000000054910000003' => {bank_code: '500', account_number: '5491000000', check_digit: '3'}, 'SI56191000000123438' => {bank_code: '19', branch_code: '100', account_number: '1234', check_digits: '38'}, 'SK3112000000198742637541' => {bank_code: '1200', account_prefix: '19', account_number: '8742637541'}, 'SM86U0322509800000000270100' => {check_char: 'U', bank_code: '3225', branch_code: '9800', account_number: '270100'}, 'TN5914207207100707129648' => {bank_code: '14', branch_code: '207', account_number: '207100707129648'}, 'TR330006100519786457841326' => {bank_code: '61', reserved: '0', account_number: '519786457841326'}, 'VG96VPVG0000012345678901' => {bank_code: 'VPVG', account_number: '12345678901'}, } describe '::local2iban' do context 'given valid data' do it 'returns valid IBAN' do iban = Conversion. local2iban('DE', :blz => '1234123', :account_number => '12341234') iban.should be_valid_check_digits end it 'returns valid IBAN, when checksum is <10' do iban = Conversion. local2iban('DE', :blz => '32050000', :account_number => '46463055') iban.should be_valid_check_digits end it 'returns valid IBAN for SK' do iban = Conversion. local2iban('SK', :account_number => '123456789', :bank_code => "5200", :account_prefix => "000000") iban.should be_valid_check_digits end it 'returns valid IBAN for ES' do iban = Conversion. local2iban('ES', :account_number => '20811234761234567890') iban.should be_valid_check_digits end IBAN_FOR_TEST.each do |iban,local| it "returns valid IBAN for #{iban}" do Conversion.local2iban(iban[0..1], local). should be_valid_check_digits end it "returns the correct IBAN for #{iban}" do Conversion.local2iban(iban[0..1], local).code. should == iban end end end it 'returns valid IBAN when numeric-partial has leading zeroes' do iban = Conversion.local2iban('DE', :blz => '01234567', :account_number => '0123456789') iban.code.should == 'DE81012345670123456789' iban.should be_valid_check_digits iban.validation_errors.should eq([]) end it 'returns valid IBAN when string-partials are included' do # pseudo conversion rule for ireland IE allow(Conversion).to receive(:load_config) do { prefix: ['\s{8}', "%08s"], numeric_suffix: ['\d{6}', "%010d"] } end iban = Conversion.local2iban('IE', :prefix => 'ABCD0123', :numeric_suffix => '0123456789') iban.code.should == 'IE83ABCD01230123456789' iban.should be_valid_check_digits iban.validation_errors.should eq([]) end end describe '::iban2local' do context 'given valid data' do it 'returns valid local data' do local = Conversion.iban2local 'DE', '012341230012341234' local.should == { :blz => '1234123', :account_number => '12341234' } end it 'returns valid local data for SK' do local = Conversion.iban2local 'SK', '52000000000123456789' local.should == { :account_number => '123456789', :bank_code => "5200", :account_prefix => "0" } end it 'returns valid local data for ES' do local = Conversion.iban2local 'ES', '20811234761234567890' local.should == { :account_number => '20811234761234567890' } end IBAN_FOR_TEST.each do |iban,local| it "returns valid local data for #{iban}" do Conversion.iban2local(iban[0..1], iban[4..-1]). should == local end end end end describe '::checksum' do IBAN_FOR_TEST.each_key do |iban_code| it "calculates correct checksum for #{iban_code}" do iban = IBAN.new iban_code Conversion.send(:checksum, iban.country_code, iban.bban). should == iban.check_digits.to_i end end end describe '::bban_format_to_format_string' do { '12!n' => '%012d', '12n' => '%012d', '12!a' => '%012s', '12a' => '%012s', '12!c' => '%012s', '12c' => '%012s', '2!e' => ' ', '2e' => ' ', }.each do |format,regexp| it "should parse #{format}" do Conversion.send(:bban_format_to_format_string, format). should == regexp end end it "should raise exception for blah" do expect { Conversion.send(:bban_format_to_regexp, "blah") }.to raise_error(ArgumentError) end end describe '::bban_format_to_regexp' do { '12!n' => '[0-9]{12}', '12n' => '[0-9]{,12}', '12!a' => '[A-Z]{12}', '12a' => '[A-Z]{,12}', '12!c' => '[a-zA-Z0-9]{12}', '12c' => '[a-zA-Z0-9]{,12}', '2!e' => '[ ]{2}', '2e' => '[ ]{,2}', }.each do |format,regexp| it "should parse #{format}" do Conversion.send(:bban_format_to_regexp, format). should == regexp end end it "should raise exception for blah" do expect { Conversion.send(:bban_format_to_regexp, "blah") }.to raise_error(ArgumentError) end end end end Use the new conversion format. require 'spec_helper' module IBANTools describe Conversion do IBAN_FOR_TEST = { 'AD1200012030200359100100' => {bank_code: '1', branch_code: '2030', account_number: '200359100100'}, 'AE070331234567890123456' => {bank_code: '33', account_number: '1234567890123456'}, 'AL47212110090000000235698741' => {bank_code: '212', branch_code: '1100', check_digit: '9', account_number: '235698741'}, 'AT611904300234573201' => {bank_code: '19043', account_number: '234573201'}, 'AZ21NABZ00000000137010001944' => {bank_code: 'NABZ', account_number: '137010001944'}, 'BA391290079401028494' => {bank_code: '129', branch_code: '7', account_number: '94010284', check_digits: '94'}, 'BE68539007547034' => {bank_code: '539', account_number: '75470', check_digits: '34'}, 'BG80BNBG96611020345678' => {bank_code: 'BNBG', branch_code: '9661', account_type: '10', account_number: '20345678'}, 'BH67BMAG00001299123456' => {bank_code: 'BMAG', account_number: '1299123456'}, 'CH9300762011623852957' => {bank_code: '762', account_number: '11623852957'}, 'CY17002001280000001200527600' => {bank_code: '2', branch_code: '128', account_number: '1200527600'}, 'CZ6508000000192000145399' => {bank_code: '800', account_prefix: '19', account_number: '2000145399'}, 'DE89370400440532013000' => {blz: '37040044', account_number: '532013000'}, 'DK5000400440116243' => {bank_code: '40', account_number: '440116243'}, 'DO28BAGR00000001212453611324' => {bank_code: 'BAGR', account_number: '1212453611324'}, 'EE382200221020145685' => {bank_code: '22', branch_code: '0', account_number: '2210201456', check_digits: '85'}, 'ES9121000418450200051332' => {account_number: '21000418450200051332'}, 'FI2112345600000785' => {bank_code: '123456', account_number: '78', check_digit: '5'}, 'FO7630004440960235' => {bank_code: '3000', account_number: '444096023', check_digit: '5'}, 'FR1420041010050500013M02606' => {bank_code: '20041', branch_code: '1005', account_number: '500013M026', check_digits: '6'}, 'GB29NWBK60161331926819' => {bank_code: 'NWBK', branch_code: '601613', account_number: '31926819'}, 'GE29NB0000000101904917' => {bank_code: 'NB', account_number: '101904917'}, 'GI75NWBK000000007099453' => {bank_code: 'NWBK',account_number: '7099453'}, 'GL4330003330229543' => {bank_code: '3000', account_number: '3330229543'}, 'GR1601101250000000012300695' => {bank_code: '11', branch_code: '125', account_number: '12300695'}, 'HR1210010051863000160' => {bank_code: '1001005', account_number: '1863000160'}, 'HU42117730161111101800000000' => {bank_code: '117', branch_code: '7301', account_prefix: '6', account_number: '111110180000000', check_digit: '0'}, 'IE29AIBK93115212345678' => {bank_code: 'AIBK', branch_code: '931152', account_number: '12345678'}, 'IL620108000000099999999' => {bank_code: '10', branch_code: '800', account_number: '99999999'}, 'IS140159260076545510730339' => {bank_code: '159', branch_code: '26', account_number: '7654', kennitala: '5510730339'}, 'IT60X0542811101000000123456' => {check_char: 'X', bank_code: '5428', branch_code: '11101', account_number: '123456'}, 'JO94CBJO0010000000000131000302' => {bank_code: 'CBJO', branch_code: '10', zeros: '0', account_number: '131000302'}, 'KW81CBKU0000000000001234560101' => {bank_code: 'CBKU', account_number: '1234560101'}, 'KZ86125KZT5004100100' => {bank_code: '125', account_number: 'KZT5004100100'}, 'LB62099900000001001901229114' => {bank_code: '999', account_number: '1001901229114'}, 'LI21088100002324013AA' => {bank_code: '8810', account_number: '2324013AA'}, 'LT121000011101001000' => {bank_code: '10000', account_number: '11101001000'}, 'LU280019400644750000' => {bank_code: '1', account_number: '9400644750000'}, 'LV80BANK0000435195001' => {bank_code: 'BANK', account_number: '435195001'}, 'MC1112739000700011111000H79' => {bank_code: '12739',branch_code: '70', account_number: '11111000H', check_digits: '79'}, 'MD24AG000225100013104168' => {bank_code: 'AG', account_number: '225100013104168'}, 'ME25505000012345678951' => {bank_code: '505', account_number: '123456789', check_digits: '51'}, 'MK07300000000042425' => {bank_code: '300', account_number: '424', check_digits: '25'}, 'MR1300020001010000123456753' => {bank_code: '20', branch_code: '101', account_number: '1234567', check_digits: '53'}, 'MT84MALT011000012345MTLCAST001S' => {bank_code: 'MALT', branch_code: '1100', account_number: '12345MTLCAST001S'}, 'MU17BOMM0101101030300200000MUR' => {bank_code: 'BOMM01', branch_code: '1', account_number: '101030300200000MUR'}, 'NL91ABNA0417164300' => {bank_code: 'ABNA', account_number: '417164300'}, 'NO9386011117947' => {bank_code: '8601', account_number: '111794', check_digit: '7'}, 'PK36SCBL0000001123456702' => {bank_code: 'SCBL', account_number: '1123456702'}, 'PL27114020040000300201355387' => {bank_code: '114', branch_code: '200', check_digit: '4', account_number: '300201355387'}, 'PS92PALS000000000400123456702' => {bank_code: 'PALS', account_number: '400123456702'}, 'PT50000201231234567890154' => {bank_code: '2', branch_code: '123', account_number: '12345678901', check_digits: '54'}, 'QA58DOHB00001234567890ABCDEFG' => {bank_code: 'DOHB', account_number: '1234567890ABCDEFG'}, 'RO49AAAA1B31007593840000' => {bank_code: 'AAAA', account_number: '1B31007593840000'}, 'RS35260005601001611379' => {bank_code: '260', account_number: '56010016113', check_digits: '79'}, 'SA0380000000608010167519' => {bank_code: '80', account_number: '608010167519'}, 'SE3550000000054910000003' => {bank_code: '500', account_number: '5491000000', check_digit: '3'}, 'SI56191000000123438' => {bank_code: '19', branch_code: '100', account_number: '1234', check_digits: '38'}, 'SK3112000000198742637541' => {bank_code: '1200', account_prefix: '19', account_number: '8742637541'}, 'SM86U0322509800000000270100' => {check_char: 'U', bank_code: '3225', branch_code: '9800', account_number: '270100'}, 'TN5914207207100707129648' => {bank_code: '14', branch_code: '207', account_number: '207100707129648'}, 'TR330006100519786457841326' => {bank_code: '61', reserved: '0', account_number: '519786457841326'}, 'VG96VPVG0000012345678901' => {bank_code: 'VPVG', account_number: '12345678901'}, } describe '::local2iban' do context 'given valid data' do it 'returns valid IBAN' do iban = Conversion. local2iban('DE', :blz => '1234123', :account_number => '12341234') iban.should be_valid_check_digits end it 'returns valid IBAN, when checksum is <10' do iban = Conversion. local2iban('DE', :blz => '32050000', :account_number => '46463055') iban.should be_valid_check_digits end it 'returns valid IBAN for SK' do iban = Conversion. local2iban('SK', :account_number => '123456789', :bank_code => "5200", :account_prefix => "000000") iban.should be_valid_check_digits end it 'returns valid IBAN for ES' do iban = Conversion. local2iban('ES', :account_number => '20811234761234567890') iban.should be_valid_check_digits end IBAN_FOR_TEST.each do |iban,local| it "returns valid IBAN for #{iban}" do Conversion.local2iban(iban[0..1], local). should be_valid_check_digits end it "returns the correct IBAN for #{iban}" do Conversion.local2iban(iban[0..1], local).code. should == iban end end end it 'returns valid IBAN when numeric-partial has leading zeroes' do iban = Conversion.local2iban('DE', :blz => '01234567', :account_number => '0123456789') iban.code.should == 'DE81012345670123456789' iban.should be_valid_check_digits iban.validation_errors.should eq([]) end it 'returns valid IBAN when string-partials are included' do # pseudo conversion rule for ireland IE allow(Conversion).to receive(:load_config) do { prefix: '8c', numeric_suffix: '10n' } end iban = Conversion.local2iban('IE', :prefix => 'ABCD0123', :numeric_suffix => '0123456789') iban.code.should == 'IE83ABCD01230123456789' iban.should be_valid_check_digits iban.validation_errors.should eq([]) end end describe '::iban2local' do context 'given valid data' do it 'returns valid local data' do local = Conversion.iban2local 'DE', '012341230012341234' local.should == { :blz => '1234123', :account_number => '12341234' } end it 'returns valid local data for SK' do local = Conversion.iban2local 'SK', '52000000000123456789' local.should == { :account_number => '123456789', :bank_code => "5200", :account_prefix => "0" } end it 'returns valid local data for ES' do local = Conversion.iban2local 'ES', '20811234761234567890' local.should == { :account_number => '20811234761234567890' } end IBAN_FOR_TEST.each do |iban,local| it "returns valid local data for #{iban}" do Conversion.iban2local(iban[0..1], iban[4..-1]). should == local end end end end describe '::checksum' do IBAN_FOR_TEST.each_key do |iban_code| it "calculates correct checksum for #{iban_code}" do iban = IBAN.new iban_code Conversion.send(:checksum, iban.country_code, iban.bban). should == iban.check_digits.to_i end end end describe '::bban_format_to_format_string' do { '12!n' => '%012d', '12n' => '%012d', '12!a' => '%012s', '12a' => '%012s', '12!c' => '%012s', '12c' => '%012s', '2!e' => ' ', '2e' => ' ', }.each do |format,regexp| it "should parse #{format}" do Conversion.send(:bban_format_to_format_string, format). should == regexp end end it "should raise exception for blah" do expect { Conversion.send(:bban_format_to_regexp, "blah") }.to raise_error(ArgumentError) end end describe '::bban_format_to_regexp' do { '12!n' => '[0-9]{12}', '12n' => '[0-9]{,12}', '12!a' => '[A-Z]{12}', '12a' => '[A-Z]{,12}', '12!c' => '[a-zA-Z0-9]{12}', '12c' => '[a-zA-Z0-9]{,12}', '2!e' => '[ ]{2}', '2e' => '[ ]{,2}', }.each do |format,regexp| it "should parse #{format}" do Conversion.send(:bban_format_to_regexp, format). should == regexp end end it "should raise exception for blah" do expect { Conversion.send(:bban_format_to_regexp, "blah") }.to raise_error(ArgumentError) end end end end
# typed: false # frozen_string_literal: true require "delegate" require "cli/args" module Homebrew module CLI # Helper class for loading formulae/casks from named arguments. # # @api private class NamedArgs < Array extend T::Sig def initialize(*args, parent: Args.new, override_spec: nil, force_bottle: false, flags: [], cask_options: false) require "cask/cask" require "cask/cask_loader" require "formulary" require "keg" require "missing_formula" @args = args @override_spec = override_spec @force_bottle = force_bottle @flags = flags @cask_options = cask_options @parent = parent super(@args) end attr_reader :parent def to_casks @to_casks ||= to_formulae_and_casks(only: :cask).freeze end def to_formulae @to_formulae ||= to_formulae_and_casks(only: :formula).freeze end # Convert named arguments to {Formula} or {Cask} objects. # If both a formula and cask with the same name exist, returns # the formula and prints a warning unless `only` is specified. sig { params( only: T.nilable(Symbol), ignore_unavailable: T.nilable(T::Boolean), method: T.nilable(Symbol), uniq: T::Boolean, ).returns(T::Array[T.any(Formula, Keg, Cask::Cask)]) } def to_formulae_and_casks(only: parent&.only_formula_or_cask, ignore_unavailable: nil, method: nil, uniq: true) @to_formulae_and_casks ||= {} @to_formulae_and_casks[only] ||= downcased_unique_named.flat_map do |name| load_formula_or_cask(name, only: only, method: method) rescue FormulaUnreadableError, FormulaClassUnavailableError, TapFormulaUnreadableError, TapFormulaClassUnavailableError, Cask::CaskUnreadableError # Need to rescue before `*UnavailableError` (superclass of this) # The formula/cask was found, but there's a problem with its implementation raise rescue NoSuchKegError, FormulaUnavailableError, Cask::CaskUnavailableError, FormulaOrCaskUnavailableError ignore_unavailable ? [] : raise end.freeze if uniq @to_formulae_and_casks[only].uniq.freeze else @to_formulae_and_casks[only] end end def to_formulae_to_casks(only: parent&.only_formula_or_cask, method: nil) @to_formulae_to_casks ||= {} @to_formulae_to_casks[[method, only]] = to_formulae_and_casks(only: only, method: method) .partition { |o| o.is_a?(Formula) } .map(&:freeze).freeze end def to_formulae_and_casks_and_unavailable(only: parent&.only_formula_or_cask, method: nil) @to_formulae_casks_unknowns ||= {} @to_formulae_casks_unknowns[method] = downcased_unique_named.map do |name| load_formula_or_cask(name, only: only, method: method) rescue FormulaOrCaskUnavailableError => e e end.uniq.freeze end def load_formula_or_cask(name, only: nil, method: nil) unreadable_error = nil if only != :cask begin formula = case method when nil, :factory Formulary.factory(name, *spec, force_bottle: @force_bottle, flags: @flags) when :resolve resolve_formula(name) when :latest_kegs resolve_latest_keg(name) when :keg # TODO: (3.2) Uncomment the following # odeprecated "`load_formula_or_cask` with `method: :keg`", # "`load_formula_or_cask` with `method: :default_kegs`" resolve_default_keg(name) when :default_kegs resolve_default_keg(name) when :kegs _, kegs = resolve_kegs(name) kegs else raise end warn_if_cask_conflicts(name, "formula") unless only == :formula return formula rescue FormulaUnreadableError, FormulaClassUnavailableError, TapFormulaUnreadableError, TapFormulaClassUnavailableError => e # Need to rescue before `FormulaUnavailableError` (superclass of this) # The formula was found, but there's a problem with its implementation unreadable_error ||= e rescue NoSuchKegError, FormulaUnavailableError => e raise e if only == :formula end end if only != :formula begin config = Cask::Config.from_args(@parent) if @cask_options cask = Cask::CaskLoader.load(name, config: config) if unreadable_error.present? onoe <<~EOS Failed to load formula: #{name} #{unreadable_error} EOS opoo "Treating #{name} as a cask." end return cask rescue Cask::CaskUnreadableError => e # Need to rescue before `CaskUnavailableError` (superclass of this) # The cask was found, but there's a problem with its implementation unreadable_error ||= e rescue Cask::CaskUnavailableError => e raise e if only == :cask end end raise unreadable_error if unreadable_error.present? user, repo, short_name = name.downcase.split("/", 3) if repo.present? && short_name.present? tap = Tap.fetch(user, repo) raise TapFormulaOrCaskUnavailableError.new(tap, short_name) end raise FormulaOrCaskUnavailableError, name end private :load_formula_or_cask def resolve_formula(name) Formulary.resolve(name, spec: spec, force_bottle: @force_bottle, flags: @flags) end private :resolve_formula sig { params(uniq: T::Boolean).returns(T::Array[Formula]) } def to_resolved_formulae(uniq: true) @to_resolved_formulae ||= to_formulae_and_casks(only: :formula, method: :resolve, uniq: uniq) .freeze end def to_resolved_formulae_to_casks(only: parent&.only_formula_or_cask) to_formulae_to_casks(only: only, method: :resolve) end def to_formulae_paths to_paths(only: :formula) end # Keep existing paths and try to convert others to tap, formula or cask paths. # If a cask and formula with the same name exist, includes both their paths # unless `only` is specified. sig { params(only: T.nilable(Symbol), recurse_tap: T::Boolean).returns(T::Array[Pathname]) } def to_paths(only: parent&.only_formula_or_cask, recurse_tap: false) @to_paths ||= {} @to_paths[only] ||= downcased_unique_named.flat_map do |name| if File.exist?(name) Pathname(name) elsif name.count("/") == 1 && !name.start_with?("./", "/") tap = Tap.fetch(name) if recurse_tap next tap.formula_files if only == :formula next tap.cask_files if only == :cask end tap.path else next Formulary.path(name) if only == :formula next Cask::CaskLoader.path(name) if only == :cask formula_path = Formulary.path(name) cask_path = Cask::CaskLoader.path(name) paths = [] paths << formula_path if formula_path.exist? paths << cask_path if cask_path.exist? paths.empty? ? Pathname(name) : paths end end.uniq.freeze end sig { returns(T::Array[Keg]) } def to_default_kegs @to_default_kegs ||= begin to_formulae_and_casks(only: :formula, method: :default_kegs).freeze rescue NoSuchKegError => e if (reason = MissingFormula.suggest_command(e.name, "uninstall")) $stderr.puts reason end raise e end end sig { returns(T::Array[Keg]) } def to_latest_kegs @to_latest_kegs ||= begin to_formulae_and_casks(only: :formula, method: :latest_kegs).freeze rescue NoSuchKegError => e if (reason = MissingFormula.suggest_command(e.name, "uninstall")) $stderr.puts reason end raise e end end sig { returns(T::Array[Keg]) } def to_kegs @to_kegs ||= begin to_formulae_and_casks(only: :formula, method: :kegs).freeze rescue NoSuchKegError => e if (reason = MissingFormula.suggest_command(e.name, "uninstall")) $stderr.puts reason end raise e end end sig { params(only: T.nilable(Symbol), ignore_unavailable: T.nilable(T::Boolean), all_kegs: T.nilable(T::Boolean)) .returns([T::Array[Keg], T::Array[Cask::Cask]]) } def to_kegs_to_casks(only: parent&.only_formula_or_cask, ignore_unavailable: nil, all_kegs: nil) method = all_kegs ? :kegs : :default_kegs @to_kegs_to_casks ||= {} @to_kegs_to_casks[method] ||= to_formulae_and_casks(only: only, ignore_unavailable: ignore_unavailable, method: method) .partition { |o| o.is_a?(Keg) } .map(&:freeze).freeze end sig { returns(T::Array[Tap]) } def to_taps @to_taps ||= downcased_unique_named.map { |name| Tap.fetch name }.uniq.freeze end sig { returns(T::Array[Tap]) } def to_installed_taps @to_installed_taps ||= to_taps.each do |tap| raise TapUnavailableError, tap.name unless tap.installed? end.uniq.freeze end sig { returns(T::Array[String]) } def homebrew_tap_cask_names downcased_unique_named.grep(HOMEBREW_CASK_TAP_CASK_REGEX) end private sig { returns(T::Array[String]) } def downcased_unique_named # Only lowercase names, not paths, bottle filenames or URLs map do |arg| if arg.include?("/") || arg.end_with?(".tar.gz") || File.exist?(arg) arg else arg.downcase end end.uniq end def spec @override_spec end private :spec def resolve_kegs(name) raise UsageError if name.blank? require "keg" rack = Formulary.to_rack(name.downcase) kegs = rack.directory? ? rack.subdirs.map { |d| Keg.new(d) } : [] raise NoSuchKegError, rack.basename if kegs.none? [rack, kegs] end def resolve_latest_keg(name) _, kegs = resolve_kegs(name) # Return keg if it is the only installed keg return kegs if kegs.length == 1 kegs.reject { |k| k.version.head? }.max_by(&:version) end def resolve_default_keg(name) rack, kegs = resolve_kegs(name) linked_keg_ref = HOMEBREW_LINKED_KEGS/rack.basename opt_prefix = HOMEBREW_PREFIX/"opt/#{rack.basename}" begin return Keg.new(opt_prefix.resolved_path) if opt_prefix.symlink? && opt_prefix.directory? return Keg.new(linked_keg_ref.resolved_path) if linked_keg_ref.symlink? && linked_keg_ref.directory? return kegs.first if kegs.length == 1 f = if name.include?("/") || File.exist?(name) Formulary.factory(name) else Formulary.from_rack(rack) end unless (prefix = f.latest_installed_prefix).directory? raise MultipleVersionsInstalledError, <<~EOS #{rack.basename} has multiple installed versions Run `brew uninstall --force #{rack.basename}` to remove all versions. EOS end Keg.new(prefix) rescue FormulaUnavailableError raise MultipleVersionsInstalledError, <<~EOS Multiple kegs installed to #{rack} However we don't know which one you refer to. Please delete (with rm -rf!) all but one and then try again. EOS end end def warn_if_cask_conflicts(ref, loaded_type) message = "Treating #{ref} as a #{loaded_type}." begin cask = Cask::CaskLoader.load ref message += " For the cask, use #{cask.tap.name}/#{cask.token}" if cask.tap.present? rescue Cask::CaskUnreadableError => e # Need to rescue before `CaskUnavailableError` (superclass of this) # The cask was found, but there's a problem with its implementation onoe <<~EOS Failed to load cask: #{ref} #{e} EOS rescue Cask::CaskUnavailableError # No ref conflict with a cask, do nothing return end opoo message.freeze end end end end Fix style # typed: false # frozen_string_literal: true require "delegate" require "cli/args" module Homebrew module CLI # Helper class for loading formulae/casks from named arguments. # # @api private class NamedArgs < Array extend T::Sig def initialize(*args, parent: Args.new, override_spec: nil, force_bottle: false, flags: [], cask_options: false) require "cask/cask" require "cask/cask_loader" require "formulary" require "keg" require "missing_formula" @args = args @override_spec = override_spec @force_bottle = force_bottle @flags = flags @cask_options = cask_options @parent = parent super(@args) end attr_reader :parent def to_casks @to_casks ||= to_formulae_and_casks(only: :cask).freeze end def to_formulae @to_formulae ||= to_formulae_and_casks(only: :formula).freeze end # Convert named arguments to {Formula} or {Cask} objects. # If both a formula and cask with the same name exist, returns # the formula and prints a warning unless `only` is specified. sig { params( only: T.nilable(Symbol), ignore_unavailable: T.nilable(T::Boolean), method: T.nilable(Symbol), uniq: T::Boolean, ).returns(T::Array[T.any(Formula, Keg, Cask::Cask)]) } def to_formulae_and_casks(only: parent&.only_formula_or_cask, ignore_unavailable: nil, method: nil, uniq: true) @to_formulae_and_casks ||= {} @to_formulae_and_casks[only] ||= downcased_unique_named.flat_map do |name| load_formula_or_cask(name, only: only, method: method) rescue FormulaUnreadableError, FormulaClassUnavailableError, TapFormulaUnreadableError, TapFormulaClassUnavailableError, Cask::CaskUnreadableError # Need to rescue before `*UnavailableError` (superclass of this) # The formula/cask was found, but there's a problem with its implementation raise rescue NoSuchKegError, FormulaUnavailableError, Cask::CaskUnavailableError, FormulaOrCaskUnavailableError ignore_unavailable ? [] : raise end.freeze if uniq @to_formulae_and_casks[only].uniq.freeze else @to_formulae_and_casks[only] end end def to_formulae_to_casks(only: parent&.only_formula_or_cask, method: nil) @to_formulae_to_casks ||= {} @to_formulae_to_casks[[method, only]] = to_formulae_and_casks(only: only, method: method) .partition { |o| o.is_a?(Formula) } .map(&:freeze).freeze end def to_formulae_and_casks_and_unavailable(only: parent&.only_formula_or_cask, method: nil) @to_formulae_casks_unknowns ||= {} @to_formulae_casks_unknowns[method] = downcased_unique_named.map do |name| load_formula_or_cask(name, only: only, method: method) rescue FormulaOrCaskUnavailableError => e e end.uniq.freeze end def load_formula_or_cask(name, only: nil, method: nil) unreadable_error = nil if only != :cask begin formula = case method when nil, :factory Formulary.factory(name, *spec, force_bottle: @force_bottle, flags: @flags) when :resolve resolve_formula(name) when :latest_kegs resolve_latest_keg(name) when :keg, :default_kegs # TODO: (3.2) Uncomment the following # odeprecated "`load_formula_or_cask` with `method: :keg`", # "`load_formula_or_cask` with `method: :default_kegs`" resolve_default_keg(name) when :kegs _, kegs = resolve_kegs(name) kegs else raise end warn_if_cask_conflicts(name, "formula") unless only == :formula return formula rescue FormulaUnreadableError, FormulaClassUnavailableError, TapFormulaUnreadableError, TapFormulaClassUnavailableError => e # Need to rescue before `FormulaUnavailableError` (superclass of this) # The formula was found, but there's a problem with its implementation unreadable_error ||= e rescue NoSuchKegError, FormulaUnavailableError => e raise e if only == :formula end end if only != :formula begin config = Cask::Config.from_args(@parent) if @cask_options cask = Cask::CaskLoader.load(name, config: config) if unreadable_error.present? onoe <<~EOS Failed to load formula: #{name} #{unreadable_error} EOS opoo "Treating #{name} as a cask." end return cask rescue Cask::CaskUnreadableError => e # Need to rescue before `CaskUnavailableError` (superclass of this) # The cask was found, but there's a problem with its implementation unreadable_error ||= e rescue Cask::CaskUnavailableError => e raise e if only == :cask end end raise unreadable_error if unreadable_error.present? user, repo, short_name = name.downcase.split("/", 3) if repo.present? && short_name.present? tap = Tap.fetch(user, repo) raise TapFormulaOrCaskUnavailableError.new(tap, short_name) end raise FormulaOrCaskUnavailableError, name end private :load_formula_or_cask def resolve_formula(name) Formulary.resolve(name, spec: spec, force_bottle: @force_bottle, flags: @flags) end private :resolve_formula sig { params(uniq: T::Boolean).returns(T::Array[Formula]) } def to_resolved_formulae(uniq: true) @to_resolved_formulae ||= to_formulae_and_casks(only: :formula, method: :resolve, uniq: uniq) .freeze end def to_resolved_formulae_to_casks(only: parent&.only_formula_or_cask) to_formulae_to_casks(only: only, method: :resolve) end def to_formulae_paths to_paths(only: :formula) end # Keep existing paths and try to convert others to tap, formula or cask paths. # If a cask and formula with the same name exist, includes both their paths # unless `only` is specified. sig { params(only: T.nilable(Symbol), recurse_tap: T::Boolean).returns(T::Array[Pathname]) } def to_paths(only: parent&.only_formula_or_cask, recurse_tap: false) @to_paths ||= {} @to_paths[only] ||= downcased_unique_named.flat_map do |name| if File.exist?(name) Pathname(name) elsif name.count("/") == 1 && !name.start_with?("./", "/") tap = Tap.fetch(name) if recurse_tap next tap.formula_files if only == :formula next tap.cask_files if only == :cask end tap.path else next Formulary.path(name) if only == :formula next Cask::CaskLoader.path(name) if only == :cask formula_path = Formulary.path(name) cask_path = Cask::CaskLoader.path(name) paths = [] paths << formula_path if formula_path.exist? paths << cask_path if cask_path.exist? paths.empty? ? Pathname(name) : paths end end.uniq.freeze end sig { returns(T::Array[Keg]) } def to_default_kegs @to_default_kegs ||= begin to_formulae_and_casks(only: :formula, method: :default_kegs).freeze rescue NoSuchKegError => e if (reason = MissingFormula.suggest_command(e.name, "uninstall")) $stderr.puts reason end raise e end end sig { returns(T::Array[Keg]) } def to_latest_kegs @to_latest_kegs ||= begin to_formulae_and_casks(only: :formula, method: :latest_kegs).freeze rescue NoSuchKegError => e if (reason = MissingFormula.suggest_command(e.name, "uninstall")) $stderr.puts reason end raise e end end sig { returns(T::Array[Keg]) } def to_kegs @to_kegs ||= begin to_formulae_and_casks(only: :formula, method: :kegs).freeze rescue NoSuchKegError => e if (reason = MissingFormula.suggest_command(e.name, "uninstall")) $stderr.puts reason end raise e end end sig { params(only: T.nilable(Symbol), ignore_unavailable: T.nilable(T::Boolean), all_kegs: T.nilable(T::Boolean)) .returns([T::Array[Keg], T::Array[Cask::Cask]]) } def to_kegs_to_casks(only: parent&.only_formula_or_cask, ignore_unavailable: nil, all_kegs: nil) method = all_kegs ? :kegs : :default_kegs @to_kegs_to_casks ||= {} @to_kegs_to_casks[method] ||= to_formulae_and_casks(only: only, ignore_unavailable: ignore_unavailable, method: method) .partition { |o| o.is_a?(Keg) } .map(&:freeze).freeze end sig { returns(T::Array[Tap]) } def to_taps @to_taps ||= downcased_unique_named.map { |name| Tap.fetch name }.uniq.freeze end sig { returns(T::Array[Tap]) } def to_installed_taps @to_installed_taps ||= to_taps.each do |tap| raise TapUnavailableError, tap.name unless tap.installed? end.uniq.freeze end sig { returns(T::Array[String]) } def homebrew_tap_cask_names downcased_unique_named.grep(HOMEBREW_CASK_TAP_CASK_REGEX) end private sig { returns(T::Array[String]) } def downcased_unique_named # Only lowercase names, not paths, bottle filenames or URLs map do |arg| if arg.include?("/") || arg.end_with?(".tar.gz") || File.exist?(arg) arg else arg.downcase end end.uniq end def spec @override_spec end private :spec def resolve_kegs(name) raise UsageError if name.blank? require "keg" rack = Formulary.to_rack(name.downcase) kegs = rack.directory? ? rack.subdirs.map { |d| Keg.new(d) } : [] raise NoSuchKegError, rack.basename if kegs.none? [rack, kegs] end def resolve_latest_keg(name) _, kegs = resolve_kegs(name) # Return keg if it is the only installed keg return kegs if kegs.length == 1 kegs.reject { |k| k.version.head? }.max_by(&:version) end def resolve_default_keg(name) rack, kegs = resolve_kegs(name) linked_keg_ref = HOMEBREW_LINKED_KEGS/rack.basename opt_prefix = HOMEBREW_PREFIX/"opt/#{rack.basename}" begin return Keg.new(opt_prefix.resolved_path) if opt_prefix.symlink? && opt_prefix.directory? return Keg.new(linked_keg_ref.resolved_path) if linked_keg_ref.symlink? && linked_keg_ref.directory? return kegs.first if kegs.length == 1 f = if name.include?("/") || File.exist?(name) Formulary.factory(name) else Formulary.from_rack(rack) end unless (prefix = f.latest_installed_prefix).directory? raise MultipleVersionsInstalledError, <<~EOS #{rack.basename} has multiple installed versions Run `brew uninstall --force #{rack.basename}` to remove all versions. EOS end Keg.new(prefix) rescue FormulaUnavailableError raise MultipleVersionsInstalledError, <<~EOS Multiple kegs installed to #{rack} However we don't know which one you refer to. Please delete (with rm -rf!) all but one and then try again. EOS end end def warn_if_cask_conflicts(ref, loaded_type) message = "Treating #{ref} as a #{loaded_type}." begin cask = Cask::CaskLoader.load ref message += " For the cask, use #{cask.tap.name}/#{cask.token}" if cask.tap.present? rescue Cask::CaskUnreadableError => e # Need to rescue before `CaskUnavailableError` (superclass of this) # The cask was found, but there's a problem with its implementation onoe <<~EOS Failed to load cask: #{ref} #{e} EOS rescue Cask::CaskUnavailableError # No ref conflict with a cask, do nothing return end opoo message.freeze end end end end
require 'spec_helper' describe Verbalize do let(:base_verbalize_class) do Class.new do include Verbalize end end describe '.verbalize' do it 'returns an ErrorResult on failure' do some_class = Class.new(base_verbalize_class) do def call fail!('Some error') end end expect(some_class.call).to be_an_instance_of(Verbalize::Failure) end it 'returns a SuccessResult on success' do some_class = Class.new(base_verbalize_class) do def call true end end expect(some_class.call).to be_an_instance_of(Verbalize::Success) end context 'with arguments' do it 'allows arguments to be defined and delegates the class method \ to the instance method' do some_class = Class.new(base_verbalize_class) do input :a, :b def call a + b end end result = some_class.call(a: 40, b: 2) expect(result).to be_success expect(result.value).to eql(42) end it 'allows class & instance method to be named differently' do some_class = Class.new(base_verbalize_class) do verbalize :some_method_name def some_method_name :some_method_result end end result = some_class.some_method_name expect(result).to be_success expect(result.value).to eql(:some_method_result) end it 'raises an error when you don’t specify a required argument' do some_class = Class.new(base_verbalize_class) do input :a, :b def call end end expect { some_class.call(a: 42) }.to raise_error(ArgumentError) end it 'allows you to specify an optional argument' do some_class = Class.new(base_verbalize_class) do input :a, optional: :b def call a + b end def b @b ||= 2 end end result = some_class.call(a: 40) expect(result).to be_success expect(result.value).to eql(42) end it 'allows you to fail an action and not execute remaining lines' do some_class = Class.new(base_verbalize_class) do input :a, :b def call fail! 'Are you crazy?!? You can’t divide by zero!' a / b end end result = some_class.call(a: 1, b: 0) expect(result).not_to be_success expect(result).to be_failed expect(result.value).to eql('Are you crazy?!? You can’t divide by zero!') end end context 'without_arguments' do it 'still does something' do some_class = Class.new(base_verbalize_class) do def call :some_behavior end end result = some_class.call expect(result).to be_success expect(result.value).to eql(:some_behavior) end it 'allows you to fail an action and not execute remaining lines' do some_class = Class.new(base_verbalize_class) do def call fail! 'Are you crazy?!? You can’t divide by zero!' 1 / 0 end end result = some_class.call expect(result).to be_failed expect(result.value).to eql('Are you crazy?!? You can’t divide by zero!') end it 'raises an error if you specify unrecognized keyword/value arguments' do expect do Class.new(base_verbalize_class) do input improper: :usage end end.to raise_error(ArgumentError) end end it 'fails up to a parent action' do some_inner_class = Class.new(base_verbalize_class) do def call fail! :some_failure_message end end some_outer_class = Class.new(base_verbalize_class) some_outer_class.class_exec(some_inner_class) do |interactor_class| define_method(:call) do interactor_class.call! end end result = some_outer_class.call expect(result).not_to be_success expect(result).to be_failed expect(result.value).to eq :some_failure_message end it 'stubbed failures are captured by parent actions' do some_inner_class = Class.new(base_verbalize_class) do def call fail! :some_failure_message end end some_outer_class = Class.new(base_verbalize_class) some_outer_class.class_exec(some_inner_class) do |interactor_class| define_method(:call) do interactor_class.call! end end allow(some_inner_class).to receive(:call!).and_throw(Verbalize::THROWN_SYMBOL, 'foo error') result = some_outer_class.call expect(result).not_to be_success expect(result).to be_failed expect(result.value).to eq 'foo error' end it 'fails up multiple levels' do some_inner_inner_class = Class.new(base_verbalize_class) do def call fail! :some_failure_message end end some_inner_class = Class.new(base_verbalize_class) some_inner_class.class_exec(some_inner_inner_class) do |interactor_class| define_method(:call) do interactor_class.call! end end some_outer_class = Class.new(base_verbalize_class) some_outer_class.class_exec(some_inner_class) do |interactor_class| define_method(:call) do interactor_class.call! end end outcome, value = some_outer_class.call expect(outcome).to eq :error expect(value).to eq :some_failure_message end it 'raises an error with a helpful message \ if an action fails without being handled' do some_class = Class.new(base_verbalize_class) do def call fail! :some_failure_message end end expect { some_class.call! }.to raise_error( Verbalize::VerbalizeError, 'Unhandled fail! called with: :some_failure_message.' ) end it 'raises an error with a helpful message if an action with keywords \ fails without being handled' do some_class = Class.new(base_verbalize_class) do input :a, :b def call fail! :some_failure_message if b.zero? end end expect { some_class.call!(a: 1, b: 0) }.to raise_error( Verbalize::VerbalizeError, 'Unhandled fail! called with: :some_failure_message.' ) end it 'fails up to a parent action with keywords' do some_inner_class = Class.new(base_verbalize_class) do input :a, :b def call fail! :some_failure_message if b.zero? end end some_outer_class = Class.new(base_verbalize_class) some_outer_class.class_exec(some_inner_class) do |interactor_class| input :a, :b define_method(:call) do interactor_class.call!(a: a, b: b) end end outcome, value = some_outer_class.call(a: 1, b: 0) expect(outcome).to eq :error expect(value).to eq :some_failure_message end end end Yet another rubocop fix require 'spec_helper' describe Verbalize do let(:base_verbalize_class) do Class.new do include Verbalize end end describe '.verbalize' do it 'returns an ErrorResult on failure' do some_class = Class.new(base_verbalize_class) do def call fail!('Some error') end end expect(some_class.call).to be_an_instance_of(Verbalize::Failure) end it 'returns a SuccessResult on success' do some_class = Class.new(base_verbalize_class) do def call true end end expect(some_class.call).to be_an_instance_of(Verbalize::Success) end context 'with arguments' do it 'allows arguments to be defined and delegates the class method \ to the instance method' do some_class = Class.new(base_verbalize_class) do input :a, :b def call a + b end end result = some_class.call(a: 40, b: 2) expect(result).to be_success expect(result.value).to eql(42) end it 'allows class & instance method to be named differently' do some_class = Class.new(base_verbalize_class) do verbalize :some_method_name def some_method_name :some_method_result end end result = some_class.some_method_name expect(result).to be_success expect(result.value).to eql(:some_method_result) end it 'raises an error when you don’t specify a required argument' do some_class = Class.new(base_verbalize_class) do input :a, :b def call; end end expect { some_class.call(a: 42) }.to raise_error(ArgumentError) end it 'allows you to specify an optional argument' do some_class = Class.new(base_verbalize_class) do input :a, optional: :b def call a + b end def b @b ||= 2 end end result = some_class.call(a: 40) expect(result).to be_success expect(result.value).to eql(42) end it 'allows you to fail an action and not execute remaining lines' do some_class = Class.new(base_verbalize_class) do input :a, :b def call fail! 'Are you crazy?!? You can’t divide by zero!' a / b end end result = some_class.call(a: 1, b: 0) expect(result).not_to be_success expect(result).to be_failed expect(result.value).to eql('Are you crazy?!? You can’t divide by zero!') end end context 'without_arguments' do it 'still does something' do some_class = Class.new(base_verbalize_class) do def call :some_behavior end end result = some_class.call expect(result).to be_success expect(result.value).to eql(:some_behavior) end it 'allows you to fail an action and not execute remaining lines' do some_class = Class.new(base_verbalize_class) do def call fail! 'Are you crazy?!? You can’t divide by zero!' 1 / 0 end end result = some_class.call expect(result).to be_failed expect(result.value).to eql('Are you crazy?!? You can’t divide by zero!') end it 'raises an error if you specify unrecognized keyword/value arguments' do expect do Class.new(base_verbalize_class) do input improper: :usage end end.to raise_error(ArgumentError) end end it 'fails up to a parent action' do some_inner_class = Class.new(base_verbalize_class) do def call fail! :some_failure_message end end some_outer_class = Class.new(base_verbalize_class) some_outer_class.class_exec(some_inner_class) do |interactor_class| define_method(:call) do interactor_class.call! end end result = some_outer_class.call expect(result).not_to be_success expect(result).to be_failed expect(result.value).to eq :some_failure_message end it 'stubbed failures are captured by parent actions' do some_inner_class = Class.new(base_verbalize_class) do def call fail! :some_failure_message end end some_outer_class = Class.new(base_verbalize_class) some_outer_class.class_exec(some_inner_class) do |interactor_class| define_method(:call) do interactor_class.call! end end allow(some_inner_class).to receive(:call!).and_throw(Verbalize::THROWN_SYMBOL, 'foo error') result = some_outer_class.call expect(result).not_to be_success expect(result).to be_failed expect(result.value).to eq 'foo error' end it 'fails up multiple levels' do some_inner_inner_class = Class.new(base_verbalize_class) do def call fail! :some_failure_message end end some_inner_class = Class.new(base_verbalize_class) some_inner_class.class_exec(some_inner_inner_class) do |interactor_class| define_method(:call) do interactor_class.call! end end some_outer_class = Class.new(base_verbalize_class) some_outer_class.class_exec(some_inner_class) do |interactor_class| define_method(:call) do interactor_class.call! end end outcome, value = some_outer_class.call expect(outcome).to eq :error expect(value).to eq :some_failure_message end it 'raises an error with a helpful message \ if an action fails without being handled' do some_class = Class.new(base_verbalize_class) do def call fail! :some_failure_message end end expect { some_class.call! }.to raise_error( Verbalize::VerbalizeError, 'Unhandled fail! called with: :some_failure_message.' ) end it 'raises an error with a helpful message if an action with keywords \ fails without being handled' do some_class = Class.new(base_verbalize_class) do input :a, :b def call fail! :some_failure_message if b.zero? end end expect { some_class.call!(a: 1, b: 0) }.to raise_error( Verbalize::VerbalizeError, 'Unhandled fail! called with: :some_failure_message.' ) end it 'fails up to a parent action with keywords' do some_inner_class = Class.new(base_verbalize_class) do input :a, :b def call fail! :some_failure_message if b.zero? end end some_outer_class = Class.new(base_verbalize_class) some_outer_class.class_exec(some_inner_class) do |interactor_class| input :a, :b define_method(:call) do interactor_class.call!(a: a, b: b) end end outcome, value = some_outer_class.call(a: 1, b: 0) expect(outcome).to eq :error expect(value).to eq :some_failure_message end end end
# frozen_string_literal: true module Excon CR_NL = "\r\n" DEFAULT_CA_FILE = File.expand_path(File.join(File.dirname(__FILE__), "..", "..", "data", "cacert.pem")) DEFAULT_CHUNK_SIZE = 1048576 # 1 megabyte # avoid overwrite if somebody has redefined unless const_defined?(:CHUNK_SIZE) CHUNK_SIZE = DEFAULT_CHUNK_SIZE end DEFAULT_RETRY_LIMIT = 4 FORCE_ENC = CR_NL.respond_to?(:force_encoding) HTTP_1_1 = " HTTP/1.1\r\n" HTTP_VERBS = %w{connect delete get head options patch post put trace} HTTPS = 'https' NO_ENTITY = [204, 205, 304].freeze REDACTED = 'REDACTED' UNIX = 'unix' USER_AGENT = "excon/#{VERSION}" VERSIONS = "#{USER_AGENT} (#{RUBY_PLATFORM}) ruby/#{RUBY_VERSION}" VALID_REQUEST_KEYS = [ :allow_unstubbed_requests, :body, :chunk_size, :debug_request, :debug_response, :headers, :instrumentor, # Used for setting logging within Connection :logger, :method, :middlewares, :password, :path, :persistent, :pipeline, :query, :read_timeout, :request_block, :response_block, :stubs, :user, :versions, :write_timeout ] VALID_CONNECTION_KEYS = VALID_REQUEST_KEYS + [ :ciphers, :client_key, :client_key_data, :client_key_pass, :client_cert, :client_cert_data, :certificate, :certificate_path, :disable_proxy, :private_key, :private_key_path, :connect_timeout, :family, :keepalive, :host, :hostname, :omit_default_port, :nonblock, :reuseaddr, :port, :proxy, :scheme, :socket, :ssl_ca_file, :ssl_ca_path, :ssl_cert_store, :ssl_verify_callback, :ssl_verify_peer, :ssl_verify_peer_host, :ssl_version, :ssl_min_version, :ssl_max_version, :ssl_uri_schemes, :tcp_nodelay, :thread_safe_sockets, :uri_parser, ] DEPRECATED_VALID_REQUEST_KEYS = { :captures => 'Mock', :expects => 'Expects', :idempotent => 'Idempotent', :instrumentor_name => 'Instrumentor', :mock => 'Mock', :retries_remaining => 'Idempotent', # referenced in Instrumentor, but only relevant with Idempotent :retry_limit => 'Idempotent', # referenced in Instrumentor, but only relevant with Idempotent :retry_interval => 'Idempotent' } unless ::IO.const_defined?(:WaitReadable) class ::IO module WaitReadable; end end end unless ::IO.const_defined?(:WaitWritable) class ::IO module WaitWritable; end end end # these come last as they rely on the above DEFAULTS = { :chunk_size => CHUNK_SIZE || DEFAULT_CHUNK_SIZE, # see https://wiki.mozilla.org/Security/Server_Side_TLS#Intermediate_compatibility_.28default.29 :ciphers => 'ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:DECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:ES-CBC3-SHA:!DSS', :connect_timeout => 60, :debug_request => false, :debug_response => false, :headers => { 'User-Agent' => USER_AGENT, 'Accept' => '*/*' }, :idempotent => false, :instrumentor_name => 'excon', :middlewares => [ Excon::Middleware::ResponseParser, Excon::Middleware::Expects, Excon::Middleware::Idempotent, Excon::Middleware::Instrumentor, Excon::Middleware::Mock ], :mock => false, :nonblock => true, :omit_default_port => false, :persistent => false, :read_timeout => 60, :retry_limit => DEFAULT_RETRY_LIMIT, :ssl_verify_peer => true, :ssl_uri_schemes => [HTTPS], :stubs => :global, :tcp_nodelay => false, :thread_safe_sockets => true, :uri_parser => URI, :versions => VERSIONS, :write_timeout => 60 } end fix typo and comment cipher changes # frozen_string_literal: true module Excon CR_NL = "\r\n" DEFAULT_CA_FILE = File.expand_path(File.join(File.dirname(__FILE__), "..", "..", "data", "cacert.pem")) DEFAULT_CHUNK_SIZE = 1048576 # 1 megabyte # avoid overwrite if somebody has redefined unless const_defined?(:CHUNK_SIZE) CHUNK_SIZE = DEFAULT_CHUNK_SIZE end DEFAULT_RETRY_LIMIT = 4 FORCE_ENC = CR_NL.respond_to?(:force_encoding) HTTP_1_1 = " HTTP/1.1\r\n" HTTP_VERBS = %w{connect delete get head options patch post put trace} HTTPS = 'https' NO_ENTITY = [204, 205, 304].freeze REDACTED = 'REDACTED' UNIX = 'unix' USER_AGENT = "excon/#{VERSION}" VERSIONS = "#{USER_AGENT} (#{RUBY_PLATFORM}) ruby/#{RUBY_VERSION}" VALID_REQUEST_KEYS = [ :allow_unstubbed_requests, :body, :chunk_size, :debug_request, :debug_response, :headers, :instrumentor, # Used for setting logging within Connection :logger, :method, :middlewares, :password, :path, :persistent, :pipeline, :query, :read_timeout, :request_block, :response_block, :stubs, :user, :versions, :write_timeout ] VALID_CONNECTION_KEYS = VALID_REQUEST_KEYS + [ :ciphers, :client_key, :client_key_data, :client_key_pass, :client_cert, :client_cert_data, :certificate, :certificate_path, :disable_proxy, :private_key, :private_key_path, :connect_timeout, :family, :keepalive, :host, :hostname, :omit_default_port, :nonblock, :reuseaddr, :port, :proxy, :scheme, :socket, :ssl_ca_file, :ssl_ca_path, :ssl_cert_store, :ssl_verify_callback, :ssl_verify_peer, :ssl_verify_peer_host, :ssl_version, :ssl_min_version, :ssl_max_version, :ssl_uri_schemes, :tcp_nodelay, :thread_safe_sockets, :uri_parser, ] DEPRECATED_VALID_REQUEST_KEYS = { :captures => 'Mock', :expects => 'Expects', :idempotent => 'Idempotent', :instrumentor_name => 'Instrumentor', :mock => 'Mock', :retries_remaining => 'Idempotent', # referenced in Instrumentor, but only relevant with Idempotent :retry_limit => 'Idempotent', # referenced in Instrumentor, but only relevant with Idempotent :retry_interval => 'Idempotent' } unless ::IO.const_defined?(:WaitReadable) class ::IO module WaitReadable; end end end unless ::IO.const_defined?(:WaitWritable) class ::IO module WaitWritable; end end end # these come last as they rely on the above DEFAULTS = { :chunk_size => CHUNK_SIZE || DEFAULT_CHUNK_SIZE, # see https://wiki.mozilla.org/Security/Server_Side_TLS#Intermediate_compatibility_.28default.29 # list provided then had DES related things sorted to the end :ciphers => 'ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA:EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:DES-CBC3-SHA:!DSS', :connect_timeout => 60, :debug_request => false, :debug_response => false, :headers => { 'User-Agent' => USER_AGENT, 'Accept' => '*/*' }, :idempotent => false, :instrumentor_name => 'excon', :middlewares => [ Excon::Middleware::ResponseParser, Excon::Middleware::Expects, Excon::Middleware::Idempotent, Excon::Middleware::Instrumentor, Excon::Middleware::Mock ], :mock => false, :nonblock => true, :omit_default_port => false, :persistent => false, :read_timeout => 60, :retry_limit => DEFAULT_RETRY_LIMIT, :ssl_verify_peer => true, :ssl_uri_schemes => [HTTPS], :stubs => :global, :tcp_nodelay => false, :thread_safe_sockets => true, :uri_parser => URI, :versions => VERSIONS, :write_timeout => 60 } end
# typed: false # frozen_string_literal: true require "formula" require "utils/bottles" require "tab" require "keg" require "formula_versions" require "cli/parser" require "utils/inreplace" require "erb" BOTTLE_ERB = <<-EOS bottle do <% if root_url != "#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}/bottles" %> root_url "<%= root_url %>" <% end %> <% if ![HOMEBREW_DEFAULT_PREFIX, HOMEBREW_MACOS_ARM_DEFAULT_PREFIX, HOMEBREW_LINUX_DEFAULT_PREFIX].include?(prefix) %> prefix "<%= prefix %>" <% end %> <% if cellar.is_a? Symbol %> cellar :<%= cellar %> <% elsif ![Homebrew::DEFAULT_MACOS_CELLAR, Homebrew::DEFAULT_MACOS_ARM_CELLAR, Homebrew::DEFAULT_LINUX_CELLAR].include?(cellar) %> cellar "<%= cellar %>" <% end %> <% if rebuild.positive? %> rebuild <%= rebuild %> <% end %> <% checksums.each do |checksum_type, checksum_values| %> <% checksum_values.each do |checksum_value| %> <% checksum, macos = checksum_value.shift %> <%= checksum_type %> "<%= checksum %>" => :<%= macos %> <% end %> <% end %> end EOS MAXIMUM_STRING_MATCHES = 100 module Homebrew extend T::Sig module_function sig { returns(CLI::Parser) } def bottle_args Homebrew::CLI::Parser.new do usage_banner <<~EOS `bottle` [<options>] <formula> Generate a bottle (binary package) from a formula that was installed with `--build-bottle`. If the formula specifies a rebuild version, it will be incremented in the generated DSL. Passing `--keep-old` will attempt to keep it at its original value, while `--no-rebuild` will remove it. EOS switch "--skip-relocation", description: "Do not check if the bottle can be marked as relocatable." switch "--force-core-tap", description: "Build a bottle even if <formula> is not in `homebrew/core` or any installed taps." switch "--no-rebuild", description: "If the formula specifies a rebuild version, remove it from the generated DSL." switch "--keep-old", description: "If the formula specifies a rebuild version, attempt to preserve its value in the "\ "generated DSL." switch "--json", description: "Write bottle information to a JSON file, which can be used as the value for "\ "`--merge`." switch "--merge", description: "Generate an updated bottle block for a formula and optionally merge it into the "\ "formula file. Instead of a formula name, requires the path to a JSON file generated with "\ "`brew bottle --json` <formula>." switch "--write", depends_on: "--merge", description: "Write changes to the formula file. A new commit will be generated unless "\ "`--no-commit` is passed." switch "--no-commit", depends_on: "--write", description: "When passed with `--write`, a new commit will not generated after writing changes "\ "to the formula file." flag "--root-url=", description: "Use the specified <URL> as the root of the bottle's URL instead of Homebrew's default." conflicts "--no-rebuild", "--keep-old" min_named 1 end end def bottle args = bottle_args.parse return merge(args: args) if args.merge? ensure_relocation_formulae_installed! unless args.skip_relocation? args.named.to_resolved_formulae.each do |f| bottle_formula f, args: args end end def ensure_relocation_formulae_installed! Keg.relocation_formulae.each do |f| next if Formula[f].latest_version_installed? ohai "Installing #{f}..." safe_system HOMEBREW_BREW_FILE, "install", f end end def keg_contain?(string, keg, ignores, formula_and_runtime_deps_names = nil, args:) @put_string_exists_header, @put_filenames = nil print_filename = lambda do |str, filename| unless @put_string_exists_header opoo "String '#{str}' still exists in these files:" @put_string_exists_header = true end @put_filenames ||= [] return if @put_filenames.include?(filename) puts Formatter.error(filename.to_s) @put_filenames << filename end result = false keg.each_unique_file_matching(string) do |file| next if Metafiles::EXTENSIONS.include?(file.extname) # Skip document files. linked_libraries = Keg.file_linked_libraries(file, string) result ||= !linked_libraries.empty? if args.verbose? print_filename.call(string, file) unless linked_libraries.empty? linked_libraries.each do |lib| puts " #{Tty.bold}-->#{Tty.reset} links to #{lib}" end end text_matches = [] # Use strings to search through the file for each string Utils.popen_read("strings", "-t", "x", "-", file.to_s) do |io| until io.eof? str = io.readline.chomp next if ignores.any? { |i| i =~ str } next unless str.include? string offset, match = str.split(" ", 2) next if linked_libraries.include? match # Don't bother reporting a string if it was found by otool # Do not report matches to files that do not exist. next unless File.exist? match # Do not report matches to build dependencies. if formula_and_runtime_deps_names.present? begin keg_name = Keg.for(Pathname.new(match)).name next unless formula_and_runtime_deps_names.include? keg_name rescue NotAKegError nil end end result = true text_matches << [match, offset] end end next unless args.verbose? && !text_matches.empty? print_filename.call(string, file) text_matches.first(MAXIMUM_STRING_MATCHES).each do |match, offset| puts " #{Tty.bold}-->#{Tty.reset} match '#{match}' at offset #{Tty.bold}0x#{offset}#{Tty.reset}" end if text_matches.size > MAXIMUM_STRING_MATCHES puts "Only the first #{MAXIMUM_STRING_MATCHES} matches were output." end end keg_contain_absolute_symlink_starting_with?(string, keg, args: args) || result end def keg_contain_absolute_symlink_starting_with?(string, keg, args:) absolute_symlinks_start_with_string = [] keg.find do |pn| next unless pn.symlink? && (link = pn.readlink).absolute? absolute_symlinks_start_with_string << pn if link.to_s.start_with?(string) end if args.verbose? && absolute_symlinks_start_with_string.present? opoo "Absolute symlink starting with #{string}:" absolute_symlinks_start_with_string.each do |pn| puts " #{pn} -> #{pn.resolved_path}" end end !absolute_symlinks_start_with_string.empty? end def bottle_output(bottle) erb = ERB.new BOTTLE_ERB erb.result(bottle.instance_eval { binding }).gsub(/^\s*$\n/, "") end def sudo_purge return unless ENV["HOMEBREW_BOTTLE_SUDO_PURGE"] system "/usr/bin/sudo", "--non-interactive", "/usr/sbin/purge" end def bottle_formula(f, args:) return ofail "Formula not installed or up-to-date: #{f.full_name}" unless f.latest_version_installed? unless tap = f.tap return ofail "Formula not from core or any installed taps: #{f.full_name}" unless args.force_core_tap? tap = CoreTap.instance end if f.bottle_disabled? ofail "Formula has disabled bottle: #{f.full_name}" puts f.bottle_disable_reason return end return ofail "Formula was not installed with --build-bottle: #{f.full_name}" unless Utils::Bottles.built_as? f return ofail "Formula has no stable version: #{f.full_name}" unless f.stable if args.no_rebuild? || !f.tap rebuild = 0 elsif args.keep_old? rebuild = f.bottle_specification.rebuild else ohai "Determining #{f.full_name} bottle rebuild..." versions = FormulaVersions.new(f) rebuilds = versions.bottle_version_map("origin/master")[f.pkg_version] rebuilds.pop if rebuilds.last.to_i.positive? rebuild = rebuilds.empty? ? 0 : rebuilds.max.to_i + 1 end filename = Bottle::Filename.create(f, Utils::Bottles.tag, rebuild) bottle_path = Pathname.pwd/filename tar_filename = filename.to_s.sub(/.gz$/, "") tar_path = Pathname.pwd/tar_filename prefix = HOMEBREW_PREFIX.to_s cellar = HOMEBREW_CELLAR.to_s ohai "Bottling #{filename}..." formula_and_runtime_deps_names = [f.name] + f.runtime_dependencies.map(&:name) keg = Keg.new(f.prefix) relocatable = T.let(false, T::Boolean) skip_relocation = T.let(false, T::Boolean) keg.lock do original_tab = nil changed_files = nil begin keg.delete_pyc_files! changed_files = keg.replace_locations_with_placeholders unless args.skip_relocation? Formula.clear_cache Keg.clear_cache Tab.clear_cache tab = Tab.for_keg(keg) original_tab = tab.dup tab.poured_from_bottle = false tab.HEAD = nil tab.time = nil tab.changed_files = changed_files tab.write keg.find do |file| if file.symlink? File.lutime(tab.source_modified_time, tab.source_modified_time, file) else file.utime(tab.source_modified_time, tab.source_modified_time) end end cd cellar do sudo_purge safe_system "tar", "cf", tar_path, "#{f.name}/#{f.pkg_version}" sudo_purge tar_path.utime(tab.source_modified_time, tab.source_modified_time) relocatable_tar_path = "#{f}-bottle.tar" mv tar_path, relocatable_tar_path # Use gzip, faster to compress than bzip2, faster to uncompress than bzip2 # or an uncompressed tarball (and more bandwidth friendly). safe_system "gzip", "-f", relocatable_tar_path sudo_purge mv "#{relocatable_tar_path}.gz", bottle_path end ohai "Detecting if #{filename} is relocatable..." if bottle_path.size > 1 * 1024 * 1024 prefix_check = if Homebrew.default_prefix?(prefix) File.join(prefix, "opt") else prefix end # Ignore matches to source code, which is not required at run time. # These matches may be caused by debugging symbols. ignores = [%r{/include/|\.(c|cc|cpp|h|hpp)$}] any_go_deps = f.deps.any? do |dep| dep.name =~ Version.formula_optionally_versioned_regex(:go) end if any_go_deps go_regex = Version.formula_optionally_versioned_regex(:go, full: false) ignores << %r{#{Regexp.escape(HOMEBREW_CELLAR)}/#{go_regex}/[\d.]+/libexec} end repository_reference = if HOMEBREW_PREFIX == HOMEBREW_REPOSITORY HOMEBREW_LIBRARY else HOMEBREW_REPOSITORY end.to_s if keg_contain?(repository_reference, keg, ignores, args: args) odie "Bottle contains non-relocatable reference to #{repository_reference}!" end relocatable = true if args.skip_relocation? skip_relocation = true else relocatable = false if keg_contain?(prefix_check, keg, ignores, formula_and_runtime_deps_names, args: args) relocatable = false if keg_contain?(cellar, keg, ignores, formula_and_runtime_deps_names, args: args) if keg_contain?(HOMEBREW_LIBRARY.to_s, keg, ignores, formula_and_runtime_deps_names, args: args) relocatable = false end if prefix != prefix_check relocatable = false if keg_contain_absolute_symlink_starting_with?(prefix, keg, args: args) relocatable = false if keg_contain?("#{prefix}/etc", keg, ignores, args: args) relocatable = false if keg_contain?("#{prefix}/var", keg, ignores, args: args) relocatable = false if keg_contain?("#{prefix}/share/vim", keg, ignores, args: args) end skip_relocation = relocatable && !keg.require_relocation? end puts if !relocatable && args.verbose? rescue Interrupt ignore_interrupts { bottle_path.unlink if bottle_path.exist? } raise ensure ignore_interrupts do original_tab&.write keg.replace_placeholders_with_locations changed_files unless args.skip_relocation? end end end root_url = args.root_url bottle = BottleSpecification.new bottle.tap = tap bottle.root_url(root_url) if root_url if relocatable if skip_relocation bottle.cellar :any_skip_relocation else bottle.cellar :any end else bottle.cellar cellar bottle.prefix prefix end bottle.rebuild rebuild sha256 = bottle_path.sha256 bottle.sha256 sha256 => Utils::Bottles.tag old_spec = f.bottle_specification if args.keep_old? && !old_spec.checksums.empty? mismatches = [:root_url, :prefix, :cellar, :rebuild].reject do |key| old_spec.send(key) == bottle.send(key) end if (old_spec.cellar == :any && bottle.cellar == :any_skip_relocation) || (old_spec.cellar == cellar && [:any, :any_skip_relocation].include?(bottle.cellar)) mismatches.delete(:cellar) bottle.cellar old_spec.cellar end unless mismatches.empty? bottle_path.unlink if bottle_path.exist? mismatches.map! do |key| old_value = old_spec.send(key).inspect value = bottle.send(key).inspect "#{key}: old: #{old_value}, new: #{value}" end odie <<~EOS --keep-old was passed but there are changes in: #{mismatches.join("\n")} EOS end end output = bottle_output bottle puts "./#{filename}" puts output return unless args.json? json = { f.full_name => { "formula" => { "pkg_version" => f.pkg_version.to_s, "path" => f.path.to_s.delete_prefix("#{HOMEBREW_REPOSITORY}/"), }, "bottle" => { "root_url" => bottle.root_url, "prefix" => bottle.prefix, "cellar" => bottle.cellar.to_s, "rebuild" => bottle.rebuild, "tags" => { Utils::Bottles.tag.to_s => { "filename" => filename.bintray, "local_filename" => filename.to_s, "sha256" => sha256, }, }, }, "bintray" => { "package" => Utils::Bottles::Bintray.package(f.name), "repository" => Utils::Bottles::Bintray.repository(tap), }, }, } File.open(filename.json, "w") do |file| file.write JSON.generate json end end def parse_json_files(filenames) filenames.map do |filename| JSON.parse(IO.read(filename)) end end def merge_json_files(json_files) json_files.reduce({}) do |hash, json_file| hash.deep_merge(json_file) do |key, first, second| if key == "cellar" # Prioritize HOMEBREW_CELLAR over :any over :any_skip_relocation cellars = [first, second] next HOMEBREW_CELLAR if cellars.include?(HOMEBREW_CELLAR) next first if first.start_with?("/") next second if second.start_with?("/") next "any" if cellars.include?("any") next "any_skip_relocation" if cellars.include?("any_skip_relocation") end second end end end def merge(args:) bottles_hash = merge_json_files(parse_json_files(args.named)) any_cellars = ["any", "any_skip_relocation"] bottles_hash.each do |formula_name, bottle_hash| ohai formula_name bottle = BottleSpecification.new bottle.root_url bottle_hash["bottle"]["root_url"] cellar = bottle_hash["bottle"]["cellar"] cellar = cellar.to_sym if any_cellars.include?(cellar) bottle.cellar cellar bottle.prefix bottle_hash["bottle"]["prefix"] bottle.rebuild bottle_hash["bottle"]["rebuild"] bottle_hash["bottle"]["tags"].each do |tag, tag_hash| bottle.sha256 tag_hash["sha256"] => tag.to_sym end output = bottle_output bottle if args.write? path = Pathname.new((HOMEBREW_REPOSITORY/bottle_hash["formula"]["path"]).to_s) update_or_add = T.let(nil, T.nilable(String)) Utils::Inreplace.inreplace(path) do |s| if s.inreplace_string.include? "bottle do" update_or_add = "update" if args.keep_old? mismatches = [] valid_keys = %w[root_url prefix cellar rebuild sha1 sha256] bottle_block_contents = s.inreplace_string[/ bottle do(.+?)end\n/m, 1] bottle_block_contents.lines.each do |line| line = line.strip next if line.empty? key, old_value_original, _, tag = line.split " ", 4 next unless valid_keys.include?(key) old_value = old_value_original.to_s.delete "'\"" old_value = old_value.to_s.delete ":" if key != "root_url" tag = tag.to_s.delete ":" unless tag.empty? if bottle_hash["bottle"]["tags"][tag].present? mismatches << "#{key} => #{tag}" else bottle.send(key, old_value => tag.to_sym) end next end value_original = bottle_hash["bottle"][key] value = value_original.to_s next if key == "cellar" && old_value == "any" && value == "any_skip_relocation" next unless old_value.empty? || value != old_value old_value = old_value_original.inspect value = value_original.inspect mismatches << "#{key}: old: #{old_value}, new: #{value}" end unless mismatches.empty? odie <<~EOS --keep-old was passed but there are changes in: #{mismatches.join("\n")} EOS end output = bottle_output bottle end puts output string = s.sub!(/ bottle do.+?end\n/m, output) odie "Bottle block update failed!" unless string else odie "--keep-old was passed but there was no existing bottle block!" if args.keep_old? puts output update_or_add = "add" Utils::Bottles.add_bottle_stanza!(s.inreplace_string, output) end end unless args.no_commit? Utils::Git.set_name_email! Utils::Git.setup_gpg! short_name = formula_name.split("/", -1).last pkg_version = bottle_hash["formula"]["pkg_version"] path.parent.cd do safe_system "git", "commit", "--no-edit", "--verbose", "--message=#{short_name}: #{update_or_add} #{pkg_version} bottle.", "--", path end end else puts output end end end end bottle: add merge_bottle_spec helper function # typed: false # frozen_string_literal: true require "formula" require "utils/bottles" require "tab" require "keg" require "formula_versions" require "cli/parser" require "utils/inreplace" require "erb" BOTTLE_ERB = <<-EOS bottle do <% if root_url != "#{HOMEBREW_BOTTLE_DEFAULT_DOMAIN}/bottles" %> root_url "<%= root_url %>" <% end %> <% if ![HOMEBREW_DEFAULT_PREFIX, HOMEBREW_MACOS_ARM_DEFAULT_PREFIX, HOMEBREW_LINUX_DEFAULT_PREFIX].include?(prefix) %> prefix "<%= prefix %>" <% end %> <% if cellar.is_a? Symbol %> cellar :<%= cellar %> <% elsif ![Homebrew::DEFAULT_MACOS_CELLAR, Homebrew::DEFAULT_MACOS_ARM_CELLAR, Homebrew::DEFAULT_LINUX_CELLAR].include?(cellar) %> cellar "<%= cellar %>" <% end %> <% if rebuild.positive? %> rebuild <%= rebuild %> <% end %> <% checksums.each do |checksum_type, checksum_values| %> <% checksum_values.each do |checksum_value| %> <% checksum, macos = checksum_value.shift %> <%= checksum_type %> "<%= checksum %>" => :<%= macos %> <% end %> <% end %> end EOS MAXIMUM_STRING_MATCHES = 100 module Homebrew extend T::Sig module_function sig { returns(CLI::Parser) } def bottle_args Homebrew::CLI::Parser.new do usage_banner <<~EOS `bottle` [<options>] <formula> Generate a bottle (binary package) from a formula that was installed with `--build-bottle`. If the formula specifies a rebuild version, it will be incremented in the generated DSL. Passing `--keep-old` will attempt to keep it at its original value, while `--no-rebuild` will remove it. EOS switch "--skip-relocation", description: "Do not check if the bottle can be marked as relocatable." switch "--force-core-tap", description: "Build a bottle even if <formula> is not in `homebrew/core` or any installed taps." switch "--no-rebuild", description: "If the formula specifies a rebuild version, remove it from the generated DSL." switch "--keep-old", description: "If the formula specifies a rebuild version, attempt to preserve its value in the "\ "generated DSL." switch "--json", description: "Write bottle information to a JSON file, which can be used as the value for "\ "`--merge`." switch "--merge", description: "Generate an updated bottle block for a formula and optionally merge it into the "\ "formula file. Instead of a formula name, requires the path to a JSON file generated with "\ "`brew bottle --json` <formula>." switch "--write", depends_on: "--merge", description: "Write changes to the formula file. A new commit will be generated unless "\ "`--no-commit` is passed." switch "--no-commit", depends_on: "--write", description: "When passed with `--write`, a new commit will not generated after writing changes "\ "to the formula file." flag "--root-url=", description: "Use the specified <URL> as the root of the bottle's URL instead of Homebrew's default." conflicts "--no-rebuild", "--keep-old" min_named 1 end end def bottle args = bottle_args.parse return merge(args: args) if args.merge? ensure_relocation_formulae_installed! unless args.skip_relocation? args.named.to_resolved_formulae.each do |f| bottle_formula f, args: args end end def ensure_relocation_formulae_installed! Keg.relocation_formulae.each do |f| next if Formula[f].latest_version_installed? ohai "Installing #{f}..." safe_system HOMEBREW_BREW_FILE, "install", f end end def keg_contain?(string, keg, ignores, formula_and_runtime_deps_names = nil, args:) @put_string_exists_header, @put_filenames = nil print_filename = lambda do |str, filename| unless @put_string_exists_header opoo "String '#{str}' still exists in these files:" @put_string_exists_header = true end @put_filenames ||= [] return if @put_filenames.include?(filename) puts Formatter.error(filename.to_s) @put_filenames << filename end result = false keg.each_unique_file_matching(string) do |file| next if Metafiles::EXTENSIONS.include?(file.extname) # Skip document files. linked_libraries = Keg.file_linked_libraries(file, string) result ||= !linked_libraries.empty? if args.verbose? print_filename.call(string, file) unless linked_libraries.empty? linked_libraries.each do |lib| puts " #{Tty.bold}-->#{Tty.reset} links to #{lib}" end end text_matches = [] # Use strings to search through the file for each string Utils.popen_read("strings", "-t", "x", "-", file.to_s) do |io| until io.eof? str = io.readline.chomp next if ignores.any? { |i| i =~ str } next unless str.include? string offset, match = str.split(" ", 2) next if linked_libraries.include? match # Don't bother reporting a string if it was found by otool # Do not report matches to files that do not exist. next unless File.exist? match # Do not report matches to build dependencies. if formula_and_runtime_deps_names.present? begin keg_name = Keg.for(Pathname.new(match)).name next unless formula_and_runtime_deps_names.include? keg_name rescue NotAKegError nil end end result = true text_matches << [match, offset] end end next unless args.verbose? && !text_matches.empty? print_filename.call(string, file) text_matches.first(MAXIMUM_STRING_MATCHES).each do |match, offset| puts " #{Tty.bold}-->#{Tty.reset} match '#{match}' at offset #{Tty.bold}0x#{offset}#{Tty.reset}" end if text_matches.size > MAXIMUM_STRING_MATCHES puts "Only the first #{MAXIMUM_STRING_MATCHES} matches were output." end end keg_contain_absolute_symlink_starting_with?(string, keg, args: args) || result end def keg_contain_absolute_symlink_starting_with?(string, keg, args:) absolute_symlinks_start_with_string = [] keg.find do |pn| next unless pn.symlink? && (link = pn.readlink).absolute? absolute_symlinks_start_with_string << pn if link.to_s.start_with?(string) end if args.verbose? && absolute_symlinks_start_with_string.present? opoo "Absolute symlink starting with #{string}:" absolute_symlinks_start_with_string.each do |pn| puts " #{pn} -> #{pn.resolved_path}" end end !absolute_symlinks_start_with_string.empty? end def bottle_output(bottle) erb = ERB.new BOTTLE_ERB erb.result(bottle.instance_eval { binding }).gsub(/^\s*$\n/, "") end def sudo_purge return unless ENV["HOMEBREW_BOTTLE_SUDO_PURGE"] system "/usr/bin/sudo", "--non-interactive", "/usr/sbin/purge" end def bottle_formula(f, args:) return ofail "Formula not installed or up-to-date: #{f.full_name}" unless f.latest_version_installed? unless tap = f.tap return ofail "Formula not from core or any installed taps: #{f.full_name}" unless args.force_core_tap? tap = CoreTap.instance end if f.bottle_disabled? ofail "Formula has disabled bottle: #{f.full_name}" puts f.bottle_disable_reason return end return ofail "Formula was not installed with --build-bottle: #{f.full_name}" unless Utils::Bottles.built_as? f return ofail "Formula has no stable version: #{f.full_name}" unless f.stable if args.no_rebuild? || !f.tap rebuild = 0 elsif args.keep_old? rebuild = f.bottle_specification.rebuild else ohai "Determining #{f.full_name} bottle rebuild..." versions = FormulaVersions.new(f) rebuilds = versions.bottle_version_map("origin/master")[f.pkg_version] rebuilds.pop if rebuilds.last.to_i.positive? rebuild = rebuilds.empty? ? 0 : rebuilds.max.to_i + 1 end filename = Bottle::Filename.create(f, Utils::Bottles.tag, rebuild) bottle_path = Pathname.pwd/filename tar_filename = filename.to_s.sub(/.gz$/, "") tar_path = Pathname.pwd/tar_filename prefix = HOMEBREW_PREFIX.to_s cellar = HOMEBREW_CELLAR.to_s ohai "Bottling #{filename}..." formula_and_runtime_deps_names = [f.name] + f.runtime_dependencies.map(&:name) keg = Keg.new(f.prefix) relocatable = T.let(false, T::Boolean) skip_relocation = T.let(false, T::Boolean) keg.lock do original_tab = nil changed_files = nil begin keg.delete_pyc_files! changed_files = keg.replace_locations_with_placeholders unless args.skip_relocation? Formula.clear_cache Keg.clear_cache Tab.clear_cache tab = Tab.for_keg(keg) original_tab = tab.dup tab.poured_from_bottle = false tab.HEAD = nil tab.time = nil tab.changed_files = changed_files tab.write keg.find do |file| if file.symlink? File.lutime(tab.source_modified_time, tab.source_modified_time, file) else file.utime(tab.source_modified_time, tab.source_modified_time) end end cd cellar do sudo_purge safe_system "tar", "cf", tar_path, "#{f.name}/#{f.pkg_version}" sudo_purge tar_path.utime(tab.source_modified_time, tab.source_modified_time) relocatable_tar_path = "#{f}-bottle.tar" mv tar_path, relocatable_tar_path # Use gzip, faster to compress than bzip2, faster to uncompress than bzip2 # or an uncompressed tarball (and more bandwidth friendly). safe_system "gzip", "-f", relocatable_tar_path sudo_purge mv "#{relocatable_tar_path}.gz", bottle_path end ohai "Detecting if #{filename} is relocatable..." if bottle_path.size > 1 * 1024 * 1024 prefix_check = if Homebrew.default_prefix?(prefix) File.join(prefix, "opt") else prefix end # Ignore matches to source code, which is not required at run time. # These matches may be caused by debugging symbols. ignores = [%r{/include/|\.(c|cc|cpp|h|hpp)$}] any_go_deps = f.deps.any? do |dep| dep.name =~ Version.formula_optionally_versioned_regex(:go) end if any_go_deps go_regex = Version.formula_optionally_versioned_regex(:go, full: false) ignores << %r{#{Regexp.escape(HOMEBREW_CELLAR)}/#{go_regex}/[\d.]+/libexec} end repository_reference = if HOMEBREW_PREFIX == HOMEBREW_REPOSITORY HOMEBREW_LIBRARY else HOMEBREW_REPOSITORY end.to_s if keg_contain?(repository_reference, keg, ignores, args: args) odie "Bottle contains non-relocatable reference to #{repository_reference}!" end relocatable = true if args.skip_relocation? skip_relocation = true else relocatable = false if keg_contain?(prefix_check, keg, ignores, formula_and_runtime_deps_names, args: args) relocatable = false if keg_contain?(cellar, keg, ignores, formula_and_runtime_deps_names, args: args) if keg_contain?(HOMEBREW_LIBRARY.to_s, keg, ignores, formula_and_runtime_deps_names, args: args) relocatable = false end if prefix != prefix_check relocatable = false if keg_contain_absolute_symlink_starting_with?(prefix, keg, args: args) relocatable = false if keg_contain?("#{prefix}/etc", keg, ignores, args: args) relocatable = false if keg_contain?("#{prefix}/var", keg, ignores, args: args) relocatable = false if keg_contain?("#{prefix}/share/vim", keg, ignores, args: args) end skip_relocation = relocatable && !keg.require_relocation? end puts if !relocatable && args.verbose? rescue Interrupt ignore_interrupts { bottle_path.unlink if bottle_path.exist? } raise ensure ignore_interrupts do original_tab&.write keg.replace_placeholders_with_locations changed_files unless args.skip_relocation? end end end root_url = args.root_url bottle = BottleSpecification.new bottle.tap = tap bottle.root_url(root_url) if root_url if relocatable if skip_relocation bottle.cellar :any_skip_relocation else bottle.cellar :any end else bottle.cellar cellar bottle.prefix prefix end bottle.rebuild rebuild sha256 = bottle_path.sha256 bottle.sha256 sha256 => Utils::Bottles.tag old_spec = f.bottle_specification if args.keep_old? && !old_spec.checksums.empty? mismatches = [:root_url, :prefix, :cellar, :rebuild].reject do |key| old_spec.send(key) == bottle.send(key) end if (old_spec.cellar == :any && bottle.cellar == :any_skip_relocation) || (old_spec.cellar == cellar && [:any, :any_skip_relocation].include?(bottle.cellar)) mismatches.delete(:cellar) bottle.cellar old_spec.cellar end unless mismatches.empty? bottle_path.unlink if bottle_path.exist? mismatches.map! do |key| old_value = old_spec.send(key).inspect value = bottle.send(key).inspect "#{key}: old: #{old_value}, new: #{value}" end odie <<~EOS --keep-old was passed but there are changes in: #{mismatches.join("\n")} EOS end end output = bottle_output bottle puts "./#{filename}" puts output return unless args.json? json = { f.full_name => { "formula" => { "pkg_version" => f.pkg_version.to_s, "path" => f.path.to_s.delete_prefix("#{HOMEBREW_REPOSITORY}/"), }, "bottle" => { "root_url" => bottle.root_url, "prefix" => bottle.prefix, "cellar" => bottle.cellar.to_s, "rebuild" => bottle.rebuild, "tags" => { Utils::Bottles.tag.to_s => { "filename" => filename.bintray, "local_filename" => filename.to_s, "sha256" => sha256, }, }, }, "bintray" => { "package" => Utils::Bottles::Bintray.package(f.name), "repository" => Utils::Bottles::Bintray.repository(tap), }, }, } File.open(filename.json, "w") do |file| file.write JSON.generate json end end def parse_json_files(filenames) filenames.map do |filename| JSON.parse(IO.read(filename)) end end def merge_json_files(json_files) json_files.reduce({}) do |hash, json_file| hash.deep_merge(json_file) do |key, first, second| if key == "cellar" # Prioritize HOMEBREW_CELLAR over :any over :any_skip_relocation cellars = [first, second] next HOMEBREW_CELLAR if cellars.include?(HOMEBREW_CELLAR) next first if first.start_with?("/") next second if second.start_with?("/") next "any" if cellars.include?("any") next "any_skip_relocation" if cellars.include?("any_skip_relocation") end second end end end def merge(args:) bottles_hash = merge_json_files(parse_json_files(args.named)) any_cellars = ["any", "any_skip_relocation"] bottles_hash.each do |formula_name, bottle_hash| ohai formula_name bottle = BottleSpecification.new bottle.root_url bottle_hash["bottle"]["root_url"] cellar = bottle_hash["bottle"]["cellar"] cellar = cellar.to_sym if any_cellars.include?(cellar) bottle.cellar cellar bottle.prefix bottle_hash["bottle"]["prefix"] bottle.rebuild bottle_hash["bottle"]["rebuild"] bottle_hash["bottle"]["tags"].each do |tag, tag_hash| bottle.sha256 tag_hash["sha256"] => tag.to_sym end output = bottle_output bottle if args.write? path = Pathname.new((HOMEBREW_REPOSITORY/bottle_hash["formula"]["path"]).to_s) update_or_add = T.let(nil, T.nilable(String)) Utils::Inreplace.inreplace(path) do |s| if s.inreplace_string.include? "bottle do" update_or_add = "update" if args.keep_old? old_bottle_spec = Formulary.factory(path).bottle_specification mismatches, checksums = merge_bottle_spec(old_bottle_spec, bottle_hash["bottle"]) if mismatches.present? odie <<~EOS --keep-old was passed but there are changes in: #{mismatches.join("\n")} EOS end checksums.each { |cksum| bottle.sha256(cksum) } output = bottle_output bottle end puts output string = s.sub!(/ bottle do.+?end\n/m, output) odie "Bottle block update failed!" unless string else odie "--keep-old was passed but there was no existing bottle block!" if args.keep_old? puts output update_or_add = "add" Utils::Bottles.add_bottle_stanza!(s.inreplace_string, output) end end unless args.no_commit? Utils::Git.set_name_email! Utils::Git.setup_gpg! short_name = formula_name.split("/", -1).last pkg_version = bottle_hash["formula"]["pkg_version"] path.parent.cd do safe_system "git", "commit", "--no-edit", "--verbose", "--message=#{short_name}: #{update_or_add} #{pkg_version} bottle.", "--", path end end else puts output end end end def merge_bottle_spec(old_bottle_spec, new_bottle_hash) mismatches = [] checksums = [] { root_url: new_bottle_hash["root_url"], prefix: new_bottle_hash["prefix"], cellar: new_bottle_hash["cellar"].to_sym, rebuild: new_bottle_hash["rebuild"], }.each do |key, new_value| old_value = old_bottle_spec.send(key) next if key == :cellar && old_value == :any && new_value == :any_skip_relocation next if old_value.present? && new_value == old_value mismatches << "#{key}: old: #{old_value.inspect}, new: #{new_value.inspect}" end old_bottle_spec.collector.each_key do |tag| old_value = old_bottle_spec.collector[tag].hexdigest new_value = new_bottle_hash["tags"][tag.to_s] if new_value.present? mismatches << "sha256 => #{tag}" else checksums << { old_value => tag } end end [mismatches, checksums] end end
require 'cuba' require 'json' Eye::Http::Router = Cuba.new do def json(result) res.headers['Content-Type'] = 'application/json; charset=utf-8' res.write({ result: result }.to_json) end on root do res.write Eye::ABOUT end on "api/info", param("filter") do |filter| json Eye::Control.command(:info_data, filter) end [:start, :stop, :restart, :delete, :unmonitor, :monitor].each do |act| on put, "api/#{act}", param("filter") do |filter| json Eye::Control.command(act, filter) end end end expose xinfo, oinfo and history commands require 'cuba' require 'json' Eye::Http::Router = Cuba.new do def json(result) res.headers['Content-Type'] = 'application/json; charset=utf-8' res.write({ result: result }.to_json) end on root do res.write Eye::ABOUT end [:info_data, :short_data, :debug_data, :history_data].each do |act| on "api/#{act.to_s.gsub(/_data$/, '')}", param("filter") do |filter| json Eye::Control.command(act, filter) end end [:start, :stop, :restart, :delete, :unmonitor, :monitor].each do |act| on put, "api/#{act}", param("filter") do |filter| json Eye::Control.command(act, filter) end end end
# -*- coding: utf-8 -*- require 'hardware' require 'os/mac' require 'extend/ENV/shared' module Stdenv include SharedEnvExtension SAFE_CFLAGS_FLAGS = "-w -pipe" DEFAULT_FLAGS = '-march=core2 -msse4' def self.extended(base) unless ORIGINAL_PATHS.include? HOMEBREW_PREFIX/'bin' base.prepend_path 'PATH', "#{HOMEBREW_PREFIX}/bin" end end def inherit? ARGV.include? "--env=inherit" end def setup_build_environment(formula=nil) reset unless inherit? if MacOS.version >= :mountain_lion # Mountain Lion's sed is stricter, and errors out when # it encounters files with mixed character sets delete('LC_ALL') self['LC_CTYPE']="C" end # Set the default pkg-config search path, overriding the built-in paths # Anything in PKG_CONFIG_PATH is searched before paths in this variable self['PKG_CONFIG_LIBDIR'] = determine_pkg_config_libdir # make any aclocal stuff installed in Homebrew available self['ACLOCAL_PATH'] = "#{HOMEBREW_PREFIX}/share/aclocal" if MacOS::Xcode.provides_autotools? self['MAKEFLAGS'] = "-j#{self.make_jobs}" unless HOMEBREW_PREFIX.to_s == '/usr/local' # /usr/local is already an -isystem and -L directory so we skip it self['CPPFLAGS'] = "-isystem#{HOMEBREW_PREFIX}/include" self['LDFLAGS'] = "-L#{HOMEBREW_PREFIX}/lib" # CMake ignores the variables above self['CMAKE_PREFIX_PATH'] = "#{HOMEBREW_PREFIX}" end if (HOMEBREW_PREFIX/'Frameworks').exist? append 'CPPFLAGS', "-F#{HOMEBREW_PREFIX}/Frameworks" append 'LDFLAGS', "-F#{HOMEBREW_PREFIX}/Frameworks" self['CMAKE_FRAMEWORK_PATH'] = HOMEBREW_PREFIX/"Frameworks" end # Os is the default Apple uses for all its stuff so let's trust them set_cflags "-Os #{SAFE_CFLAGS_FLAGS}" append 'LDFLAGS', '-Wl,-headerpad_max_install_names' if OS.mac? # Set the dynamic library search path if OS.linux? append "LDFLAGS", "-Wl,-rpath #{HOMEBREW_PREFIX}/lib" self["LD_RUN_PATH"] = "#{HOMEBREW_PREFIX}/lib" end if inherit? # Inherit CC, CXX and compiler flags from the parent environment. elsif respond_to?(compiler) send(compiler) else self.cc = determine_cc self.cxx = determine_cxx set_cpu_cflags end validate_cc!(formula) unless formula.nil? if !inherit? && cc =~ GNU_GCC_REGEXP warn_about_non_apple_gcc($1) gcc_formula = gcc_version_formula($1) append_path "PATH", gcc_formula.opt_bin.to_s end # Add lib and include etc. from the current macosxsdk to compiler flags: macosxsdk MacOS.version if MacOS::Xcode.without_clt? append_path "PATH", "#{MacOS::Xcode.prefix}/usr/bin" append_path "PATH", "#{MacOS::Xcode.toolchain_path}/usr/bin" end end def determine_pkg_config_libdir paths = [] paths << HOMEBREW_PREFIX/'lib/pkgconfig' paths << HOMEBREW_PREFIX/'share/pkgconfig' paths << HOMEBREW_REPOSITORY/"Library/ENV/pkgconfig/#{MacOS.version}" paths << '/usr/lib/pkgconfig' paths.select { |d| File.directory? d }.join(File::PATH_SEPARATOR) end def deparallelize remove 'MAKEFLAGS', /-j\d+/ end alias_method :j1, :deparallelize # These methods are no-ops for compatibility. %w{fast O4 Og}.each { |opt| define_method(opt) {} } %w{O3 O2 O1 O0 Os}.each do |opt| define_method opt do remove_from_cflags(/-O./) append_to_cflags "-#{opt}" end end def determine_cc s = super MacOS.locate(s) || Pathname.new(s) end def determine_cxx dir, base = determine_cc.split dir / base.to_s.sub("gcc", "g++").sub("clang", "clang++") end def gcc_4_0 super set_cpu_cflags '-march=nocona -mssse3' end alias_method :gcc_4_0_1, :gcc_4_0 def gcc super set_cpu_cflags end alias_method :gcc_4_2, :gcc GNU_GCC_VERSIONS.each do |n| define_method(:"gcc-4.#{n}") do super() set_cpu_cflags end end def llvm super set_cpu_cflags end def clang super replace_in_cflags(/-Xarch_#{Hardware::CPU.arch_32_bit} (-march=\S*)/, '\1') # Clang mistakenly enables AES-NI on plain Nehalem set_cpu_cflags '-march=native', :nehalem => '-march=native -Xclang -target-feature -Xclang -aes' end def remove_macosxsdk version=MacOS.version # Clear all lib and include dirs from CFLAGS, CPPFLAGS, LDFLAGS that were # previously added by macosxsdk version = version.to_s remove_from_cflags(/ ?-mmacosx-version-min=10\.\d/) delete('MACOSX_DEPLOYMENT_TARGET') delete('CPATH') remove 'LDFLAGS', "-L#{HOMEBREW_PREFIX}/lib" if (sdk = MacOS.sdk_path(version)) && !MacOS::CLT.installed? delete('SDKROOT') remove_from_cflags "-isysroot #{sdk}" remove 'CPPFLAGS', "-isysroot #{sdk}" remove 'LDFLAGS', "-isysroot #{sdk}" if HOMEBREW_PREFIX.to_s == '/usr/local' delete('CMAKE_PREFIX_PATH') else # It was set in setup_build_environment, so we have to restore it here. self['CMAKE_PREFIX_PATH'] = "#{HOMEBREW_PREFIX}" end remove 'CMAKE_FRAMEWORK_PATH', "#{sdk}/System/Library/Frameworks" end end def macosxsdk version=MacOS.version return unless OS.mac? # Sets all needed lib and include dirs to CFLAGS, CPPFLAGS, LDFLAGS. remove_macosxsdk version = version.to_s append_to_cflags("-mmacosx-version-min=#{version}") self['MACOSX_DEPLOYMENT_TARGET'] = version self['CPATH'] = "#{HOMEBREW_PREFIX}/include" prepend 'LDFLAGS', "-L#{HOMEBREW_PREFIX}/lib" if (sdk = MacOS.sdk_path(version)) && !MacOS::CLT.installed? # Extra setup to support Xcode 4.3+ without CLT. self['SDKROOT'] = sdk # Tell clang/gcc where system include's are: append_path 'CPATH', "#{sdk}/usr/include" # The -isysroot is needed, too, because of the Frameworks append_to_cflags "-isysroot #{sdk}" append 'CPPFLAGS', "-isysroot #{sdk}" # And the linker needs to find sdk/usr/lib append 'LDFLAGS', "-isysroot #{sdk}" # Needed to build cmake itself and perhaps some cmake projects: append_path 'CMAKE_PREFIX_PATH', "#{sdk}/usr" append_path 'CMAKE_FRAMEWORK_PATH', "#{sdk}/System/Library/Frameworks" end end def minimal_optimization set_cflags "-Os #{SAFE_CFLAGS_FLAGS}" macosxsdk unless MacOS::CLT.installed? end def no_optimization set_cflags SAFE_CFLAGS_FLAGS macosxsdk unless MacOS::CLT.installed? end # Some configure scripts won't find libxml2 without help def libxml2 if MacOS::CLT.installed? append 'CPPFLAGS', '-I/usr/include/libxml2' else # Use the includes form the sdk append 'CPPFLAGS', "-I#{MacOS.sdk_path}/usr/include/libxml2" end end def x11 # There are some config scripts here that should go in the PATH append_path 'PATH', MacOS::X11.bin # Append these to PKG_CONFIG_LIBDIR so they are searched # *after* our own pkgconfig directories, as we dupe some of the # libs in XQuartz. append_path 'PKG_CONFIG_LIBDIR', MacOS::X11.lib/'pkgconfig' append_path 'PKG_CONFIG_LIBDIR', MacOS::X11.share/'pkgconfig' append 'LDFLAGS', "-L#{MacOS::X11.lib}" append_path 'CMAKE_PREFIX_PATH', MacOS::X11.prefix append_path 'CMAKE_INCLUDE_PATH', MacOS::X11.include append_path 'CMAKE_INCLUDE_PATH', MacOS::X11.include/'freetype2' append 'CPPFLAGS', "-I#{MacOS::X11.include}" append 'CPPFLAGS', "-I#{MacOS::X11.include}/freetype2" append_path 'ACLOCAL_PATH', MacOS::X11.share/'aclocal' if MacOS::XQuartz.provided_by_apple? and not MacOS::CLT.installed? append_path 'CMAKE_PREFIX_PATH', MacOS.sdk_path/'usr/X11' end append 'CFLAGS', "-I#{MacOS::X11.include}" unless MacOS::CLT.installed? end alias_method :libpng, :x11 # we've seen some packages fail to build when warnings are disabled! def enable_warnings remove_from_cflags '-w' end def m64 append_to_cflags '-m64' append 'LDFLAGS', "-arch #{Hardware::CPU.arch_64_bit}" end def m32 append_to_cflags '-m32' append 'LDFLAGS', "-arch #{Hardware::CPU.arch_32_bit}" end def universal_binary append_to_cflags Hardware::CPU.universal_archs.as_arch_flags append 'LDFLAGS', Hardware::CPU.universal_archs.as_arch_flags if compiler != :clang && Hardware.is_32_bit? # Can't mix "-march" for a 32-bit CPU with "-arch x86_64" replace_in_cflags(/-march=\S*/, "-Xarch_#{Hardware::CPU.arch_32_bit} \\0") end end def cxx11 if compiler == :clang append 'CXX', '-std=c++11' append 'CXX', '-stdlib=libc++' elsif compiler =~ /gcc-4\.(8|9)/ append 'CXX', '-std=c++11' else raise "The selected compiler doesn't support C++11: #{compiler}" end end def libcxx if compiler == :clang append 'CXX', '-stdlib=libc++' end end def libstdcxx if compiler == :clang append 'CXX', '-stdlib=libstdc++' end end def replace_in_cflags before, after CC_FLAG_VARS.each do |key| self[key] = self[key].sub(before, after) if has_key?(key) end end # Convenience method to set all C compiler flags in one shot. def set_cflags val CC_FLAG_VARS.each { |key| self[key] = val } end # Sets architecture-specific flags for every environment variable # given in the list `flags`. def set_cpu_flags flags, default=DEFAULT_FLAGS, map=Hardware::CPU.optimization_flags cflags =~ %r{(-Xarch_#{Hardware::CPU.arch_32_bit} )-march=} xarch = $1.to_s remove flags, %r{(-Xarch_#{Hardware::CPU.arch_32_bit} )?-march=\S*} remove flags, %r{( -Xclang \S+)+} remove flags, %r{-mssse3} remove flags, %r{-msse4(\.\d)?} append flags, xarch unless xarch.empty? append flags, map.fetch(effective_arch, default) end def effective_arch if ARGV.build_bottle? ARGV.bottle_arch || Hardware.oldest_cpu elsif Hardware::CPU.intel? && !Hardware::CPU.sse4? # If the CPU doesn't support SSE4, we cannot trust -march=native or # -march=<cpu family> to do the right thing because we might be running # in a VM or on a Hackintosh. Hardware.oldest_cpu else Hardware::CPU.family end end def set_cpu_cflags default=DEFAULT_FLAGS, map=Hardware::CPU.optimization_flags set_cpu_flags CC_FLAG_VARS, default, map end def make_jobs # '-j' requires a positive integral argument if self['HOMEBREW_MAKE_JOBS'].to_i > 0 self['HOMEBREW_MAKE_JOBS'].to_i else Hardware::CPU.cores end end # This method does nothing in stdenv since there's no arg refurbishment def refurbish_args; end end Linuxbrew: Use commas in -Wl,-rpath,PATH Closes #119 # -*- coding: utf-8 -*- require 'hardware' require 'os/mac' require 'extend/ENV/shared' module Stdenv include SharedEnvExtension SAFE_CFLAGS_FLAGS = "-w -pipe" DEFAULT_FLAGS = '-march=core2 -msse4' def self.extended(base) unless ORIGINAL_PATHS.include? HOMEBREW_PREFIX/'bin' base.prepend_path 'PATH', "#{HOMEBREW_PREFIX}/bin" end end def inherit? ARGV.include? "--env=inherit" end def setup_build_environment(formula=nil) reset unless inherit? if MacOS.version >= :mountain_lion # Mountain Lion's sed is stricter, and errors out when # it encounters files with mixed character sets delete('LC_ALL') self['LC_CTYPE']="C" end # Set the default pkg-config search path, overriding the built-in paths # Anything in PKG_CONFIG_PATH is searched before paths in this variable self['PKG_CONFIG_LIBDIR'] = determine_pkg_config_libdir # make any aclocal stuff installed in Homebrew available self['ACLOCAL_PATH'] = "#{HOMEBREW_PREFIX}/share/aclocal" if MacOS::Xcode.provides_autotools? self['MAKEFLAGS'] = "-j#{self.make_jobs}" unless HOMEBREW_PREFIX.to_s == '/usr/local' # /usr/local is already an -isystem and -L directory so we skip it self['CPPFLAGS'] = "-isystem#{HOMEBREW_PREFIX}/include" self['LDFLAGS'] = "-L#{HOMEBREW_PREFIX}/lib" # CMake ignores the variables above self['CMAKE_PREFIX_PATH'] = "#{HOMEBREW_PREFIX}" end if (HOMEBREW_PREFIX/'Frameworks').exist? append 'CPPFLAGS', "-F#{HOMEBREW_PREFIX}/Frameworks" append 'LDFLAGS', "-F#{HOMEBREW_PREFIX}/Frameworks" self['CMAKE_FRAMEWORK_PATH'] = HOMEBREW_PREFIX/"Frameworks" end # Os is the default Apple uses for all its stuff so let's trust them set_cflags "-Os #{SAFE_CFLAGS_FLAGS}" append 'LDFLAGS', '-Wl,-headerpad_max_install_names' if OS.mac? # Set the dynamic library search path if OS.linux? append "LDFLAGS", "-Wl,-rpath,#{HOMEBREW_PREFIX}/lib" self["LD_RUN_PATH"] = "#{HOMEBREW_PREFIX}/lib" end if inherit? # Inherit CC, CXX and compiler flags from the parent environment. elsif respond_to?(compiler) send(compiler) else self.cc = determine_cc self.cxx = determine_cxx set_cpu_cflags end validate_cc!(formula) unless formula.nil? if !inherit? && cc =~ GNU_GCC_REGEXP warn_about_non_apple_gcc($1) gcc_formula = gcc_version_formula($1) append_path "PATH", gcc_formula.opt_bin.to_s end # Add lib and include etc. from the current macosxsdk to compiler flags: macosxsdk MacOS.version if MacOS::Xcode.without_clt? append_path "PATH", "#{MacOS::Xcode.prefix}/usr/bin" append_path "PATH", "#{MacOS::Xcode.toolchain_path}/usr/bin" end end def determine_pkg_config_libdir paths = [] paths << HOMEBREW_PREFIX/'lib/pkgconfig' paths << HOMEBREW_PREFIX/'share/pkgconfig' paths << HOMEBREW_REPOSITORY/"Library/ENV/pkgconfig/#{MacOS.version}" paths << '/usr/lib/pkgconfig' paths.select { |d| File.directory? d }.join(File::PATH_SEPARATOR) end def deparallelize remove 'MAKEFLAGS', /-j\d+/ end alias_method :j1, :deparallelize # These methods are no-ops for compatibility. %w{fast O4 Og}.each { |opt| define_method(opt) {} } %w{O3 O2 O1 O0 Os}.each do |opt| define_method opt do remove_from_cflags(/-O./) append_to_cflags "-#{opt}" end end def determine_cc s = super MacOS.locate(s) || Pathname.new(s) end def determine_cxx dir, base = determine_cc.split dir / base.to_s.sub("gcc", "g++").sub("clang", "clang++") end def gcc_4_0 super set_cpu_cflags '-march=nocona -mssse3' end alias_method :gcc_4_0_1, :gcc_4_0 def gcc super set_cpu_cflags end alias_method :gcc_4_2, :gcc GNU_GCC_VERSIONS.each do |n| define_method(:"gcc-4.#{n}") do super() set_cpu_cflags end end def llvm super set_cpu_cflags end def clang super replace_in_cflags(/-Xarch_#{Hardware::CPU.arch_32_bit} (-march=\S*)/, '\1') # Clang mistakenly enables AES-NI on plain Nehalem set_cpu_cflags '-march=native', :nehalem => '-march=native -Xclang -target-feature -Xclang -aes' end def remove_macosxsdk version=MacOS.version # Clear all lib and include dirs from CFLAGS, CPPFLAGS, LDFLAGS that were # previously added by macosxsdk version = version.to_s remove_from_cflags(/ ?-mmacosx-version-min=10\.\d/) delete('MACOSX_DEPLOYMENT_TARGET') delete('CPATH') remove 'LDFLAGS', "-L#{HOMEBREW_PREFIX}/lib" if (sdk = MacOS.sdk_path(version)) && !MacOS::CLT.installed? delete('SDKROOT') remove_from_cflags "-isysroot #{sdk}" remove 'CPPFLAGS', "-isysroot #{sdk}" remove 'LDFLAGS', "-isysroot #{sdk}" if HOMEBREW_PREFIX.to_s == '/usr/local' delete('CMAKE_PREFIX_PATH') else # It was set in setup_build_environment, so we have to restore it here. self['CMAKE_PREFIX_PATH'] = "#{HOMEBREW_PREFIX}" end remove 'CMAKE_FRAMEWORK_PATH', "#{sdk}/System/Library/Frameworks" end end def macosxsdk version=MacOS.version return unless OS.mac? # Sets all needed lib and include dirs to CFLAGS, CPPFLAGS, LDFLAGS. remove_macosxsdk version = version.to_s append_to_cflags("-mmacosx-version-min=#{version}") self['MACOSX_DEPLOYMENT_TARGET'] = version self['CPATH'] = "#{HOMEBREW_PREFIX}/include" prepend 'LDFLAGS', "-L#{HOMEBREW_PREFIX}/lib" if (sdk = MacOS.sdk_path(version)) && !MacOS::CLT.installed? # Extra setup to support Xcode 4.3+ without CLT. self['SDKROOT'] = sdk # Tell clang/gcc where system include's are: append_path 'CPATH', "#{sdk}/usr/include" # The -isysroot is needed, too, because of the Frameworks append_to_cflags "-isysroot #{sdk}" append 'CPPFLAGS', "-isysroot #{sdk}" # And the linker needs to find sdk/usr/lib append 'LDFLAGS', "-isysroot #{sdk}" # Needed to build cmake itself and perhaps some cmake projects: append_path 'CMAKE_PREFIX_PATH', "#{sdk}/usr" append_path 'CMAKE_FRAMEWORK_PATH', "#{sdk}/System/Library/Frameworks" end end def minimal_optimization set_cflags "-Os #{SAFE_CFLAGS_FLAGS}" macosxsdk unless MacOS::CLT.installed? end def no_optimization set_cflags SAFE_CFLAGS_FLAGS macosxsdk unless MacOS::CLT.installed? end # Some configure scripts won't find libxml2 without help def libxml2 if MacOS::CLT.installed? append 'CPPFLAGS', '-I/usr/include/libxml2' else # Use the includes form the sdk append 'CPPFLAGS', "-I#{MacOS.sdk_path}/usr/include/libxml2" end end def x11 # There are some config scripts here that should go in the PATH append_path 'PATH', MacOS::X11.bin # Append these to PKG_CONFIG_LIBDIR so they are searched # *after* our own pkgconfig directories, as we dupe some of the # libs in XQuartz. append_path 'PKG_CONFIG_LIBDIR', MacOS::X11.lib/'pkgconfig' append_path 'PKG_CONFIG_LIBDIR', MacOS::X11.share/'pkgconfig' append 'LDFLAGS', "-L#{MacOS::X11.lib}" append_path 'CMAKE_PREFIX_PATH', MacOS::X11.prefix append_path 'CMAKE_INCLUDE_PATH', MacOS::X11.include append_path 'CMAKE_INCLUDE_PATH', MacOS::X11.include/'freetype2' append 'CPPFLAGS', "-I#{MacOS::X11.include}" append 'CPPFLAGS', "-I#{MacOS::X11.include}/freetype2" append_path 'ACLOCAL_PATH', MacOS::X11.share/'aclocal' if MacOS::XQuartz.provided_by_apple? and not MacOS::CLT.installed? append_path 'CMAKE_PREFIX_PATH', MacOS.sdk_path/'usr/X11' end append 'CFLAGS', "-I#{MacOS::X11.include}" unless MacOS::CLT.installed? end alias_method :libpng, :x11 # we've seen some packages fail to build when warnings are disabled! def enable_warnings remove_from_cflags '-w' end def m64 append_to_cflags '-m64' append 'LDFLAGS', "-arch #{Hardware::CPU.arch_64_bit}" end def m32 append_to_cflags '-m32' append 'LDFLAGS', "-arch #{Hardware::CPU.arch_32_bit}" end def universal_binary append_to_cflags Hardware::CPU.universal_archs.as_arch_flags append 'LDFLAGS', Hardware::CPU.universal_archs.as_arch_flags if compiler != :clang && Hardware.is_32_bit? # Can't mix "-march" for a 32-bit CPU with "-arch x86_64" replace_in_cflags(/-march=\S*/, "-Xarch_#{Hardware::CPU.arch_32_bit} \\0") end end def cxx11 if compiler == :clang append 'CXX', '-std=c++11' append 'CXX', '-stdlib=libc++' elsif compiler =~ /gcc-4\.(8|9)/ append 'CXX', '-std=c++11' else raise "The selected compiler doesn't support C++11: #{compiler}" end end def libcxx if compiler == :clang append 'CXX', '-stdlib=libc++' end end def libstdcxx if compiler == :clang append 'CXX', '-stdlib=libstdc++' end end def replace_in_cflags before, after CC_FLAG_VARS.each do |key| self[key] = self[key].sub(before, after) if has_key?(key) end end # Convenience method to set all C compiler flags in one shot. def set_cflags val CC_FLAG_VARS.each { |key| self[key] = val } end # Sets architecture-specific flags for every environment variable # given in the list `flags`. def set_cpu_flags flags, default=DEFAULT_FLAGS, map=Hardware::CPU.optimization_flags cflags =~ %r{(-Xarch_#{Hardware::CPU.arch_32_bit} )-march=} xarch = $1.to_s remove flags, %r{(-Xarch_#{Hardware::CPU.arch_32_bit} )?-march=\S*} remove flags, %r{( -Xclang \S+)+} remove flags, %r{-mssse3} remove flags, %r{-msse4(\.\d)?} append flags, xarch unless xarch.empty? append flags, map.fetch(effective_arch, default) end def effective_arch if ARGV.build_bottle? ARGV.bottle_arch || Hardware.oldest_cpu elsif Hardware::CPU.intel? && !Hardware::CPU.sse4? # If the CPU doesn't support SSE4, we cannot trust -march=native or # -march=<cpu family> to do the right thing because we might be running # in a VM or on a Hackintosh. Hardware.oldest_cpu else Hardware::CPU.family end end def set_cpu_cflags default=DEFAULT_FLAGS, map=Hardware::CPU.optimization_flags set_cpu_flags CC_FLAG_VARS, default, map end def make_jobs # '-j' requires a positive integral argument if self['HOMEBREW_MAKE_JOBS'].to_i > 0 self['HOMEBREW_MAKE_JOBS'].to_i else Hardware::CPU.cores end end # This method does nothing in stdenv since there's no arg refurbishment def refurbish_args; end end
require 'puppet' # Possible values for an enabled repo are 'yes', '1', and 'true'. # Everything else is considered disabled. However, there is a # special case where a [repository] entry doesn't include an # entry for 'enabled'. YUM treats those as enabled repos, and in # the Puppet catalog, a yumrepo resource without an attribute has # that attribute marked as ':absent', so we need to look for that. def to_boolean(value) %w[absent yes true 1].include?(value.downcase) end Facter.add(:yumrepos) do confine osfamily: 'RedHat' enabled_repos = [] disabled_repos = [] Puppet::Type.type('yumrepo').instances.find_all do |repo| repo_value = repo.retrieve # Take the 'enabled' attribute of each repo, convert it to a boolean, and use that result # to the repo's name to the enabled or disabled list. enabled_repos << repo.name if to_boolean(repo_value[repo.property(:enabled)].to_s.strip) disabled_repos << repo.name unless to_boolean(repo_value[repo.property(:enabled)].to_s.strip) end repos_info = {} repos_info['enabled'] = enabled_repos repos_info['disabled'] = disabled_repos repos_info['count'] = { 'enabled' => enabled_repos.count, 'disabled' => disabled_repos.count, 'total' => enabled_repos.count + disabled_repos.count } setcode do repos_info end end Wrap setcode around everything Prior to this, the setcode block was only around the return value. It's best to put as much as possible inside the setcode block to prevent odd behavior. require 'puppet' # Possible values for an enabled repo are 'yes', '1', and 'true'. # Everything else is considered disabled. However, there is a # special case where a [repository] entry doesn't include an # entry for 'enabled'. YUM treats those as enabled repos, and in # the Puppet catalog, a yumrepo resource without an attribute has # that attribute marked as ':absent', so we need to look for that. def to_boolean(value) %w[absent yes true 1].include?(value.downcase) end Facter.add(:yumrepos) do confine osfamily: 'RedHat' setcode do enabled_repos = [] disabled_repos = [] Puppet::Type.type('yumrepo').instances.find_all do |repo| repo_value = repo.retrieve # Take the 'enabled' attribute of each repo, convert it to a boolean, and use that result # to the repo's name to the enabled or disabled list. enabled_repos << repo.name if to_boolean(repo_value[repo.property(:enabled)].to_s.strip) disabled_repos << repo.name unless to_boolean(repo_value[repo.property(:enabled)].to_s.strip) end repos_info = {} repos_info['enabled'] = enabled_repos repos_info['disabled'] = disabled_repos repos_info['count'] = { 'enabled' => enabled_repos.count, 'disabled' => disabled_repos.count, 'total' => enabled_repos.count + disabled_repos.count } repos_info end end
require 'tmpdir' require_relative '../../../lib/guard/rspec-jruby' module Guard describe RSpecJRubyRunner do let(:runner) { ::Guard::RSpecJRubyRunner.new } it 'returns true from run_via_shell when the specs pass' do Dir.mktmpdir do |dir| path = File.join(dir, 'passing_spec.rb') File.open(path, 'w') do |f| f.write <<-EOF describe 'a passing spec' do it 'is true that true is true' do true.should be_true end end EOF end runner.run_via_shell([path], {}).should be_true end end it 'returns false from run_via_shell whent he specs fail' do Dir.mktmpdir do |dir| path = File.join(dir, 'failing_spec.rb') File.open(path, 'w') do |f| f.write <<-EOF describe 'a failing spec' do it 'is false that false is true' do false.should be_true end end EOF end runner.run_via_shell([path], {}).should be_false end end it 'gracefully handles error ocurring with the container' do Dir.mktmpdir do |dir| path = File.join(dir, 'failing_spec.rb') File.open(path, 'w') do |f| f.write <<-EOF describe 'a spec with a syntax error' it 'is desirable that the guard not crash when syntax errors occur' do true.should be_true end end EOF end UI.should_receive(:error).with(/SyntaxError/) runner.run_via_shell([path], {}).should be_false end end end end adding mock scripting container to capture output from rspec under test require 'tmpdir' require_relative '../../../lib/guard/rspec-jruby' import java.io.StringWriter module Guard describe RSpecJRubyRunner do let(:runner) { ::Guard::RSpecJRubyRunner.new } class SpecScriptingContainer < ScriptingContainer def initialize(*args) super setOutput(StringWriter.new) setError(StringWriter.new) end end before(:each) do verbose, $VERBOSE = $VERBOSE, nil Object.const_set("ScriptingContainer", SpecScriptingContainer) Thread.stub(:new).and_return(nil) $VERBOSE = verbose end it 'returns true from run_via_shell when the specs pass' do Dir.mktmpdir do |dir| path = File.join(dir, 'passing_spec.rb') File.open(path, 'w') do |f| f.write <<-EOF describe 'a passing spec' do it 'is true that true is true' do true.should be_true end end EOF end runner.run_via_shell([path], {}).should be_true end end it 'returns false from run_via_shell when the specs fail' do Dir.mktmpdir do |dir| path = File.join(dir, 'failing_spec.rb') File.open(path, 'w') do |f| f.write <<-EOF describe 'a failing spec' do it 'is false that false is true' do false.should be_true end end EOF end runner.run_via_shell([path], {}).should be_false end end it 'gracefully handles errors ocurring within the container' do Dir.mktmpdir do |dir| path = File.join(dir, 'failing_spec.rb') File.open(path, 'w') do |f| f.write <<-EOF describe 'a spec with a syntax error' it 'is desirable that the guard not crash when syntax errors occur' do true.should doesnt_matter end end EOF end UI.should_receive(:error).with(/SyntaxError/) runner.run_via_shell([path], {}).should be_false end end end end
require "feedback_router/version" module FeedbackRouter def self.send(feedback_params, application_name) @base_url, @controller_route = set_up_destination @params = set_params(feedback_params, application_name) send_request end private def self.set_up_destination matches = ENV['FEEDBACK_LOCATION'].match(/(https?:\/\/[\w._:-]+)(.*)/) base_url = matches[1], controller_route = matches[2] end def self.set_params feedback_params['app_name'] = application_name end def self.send_request conn = Faraday.new(:url => @base_url) conn.post @controller_route, @params end end Update Argument Bug require "feedback_router/version" module FeedbackRouter def self.send(feedback_params, application_name) @base_url, @controller_route = set_up_destination @params = set_params(feedback_params, application_name) send_request end private def self.set_up_destination matches = ENV['FEEDBACK_LOCATION'].match(/(https?:\/\/[\w._:-]+)(.*)/) base_url = matches[1], controller_route = matches[2] end def self.set_params(feedback_params, application_name) feedback_params['app_name'] = application_name end def self.send_request conn = Faraday.new(:url => @base_url) conn.post @controller_route, @params end end
Add testing for `Statistics::Client` require 'rails_helper' require 'statistics' RSpec.describe Statistics::Client do include_context 'Use stubs for Faraday' context 'Connpass' do describe '#search' do subject { Statistics::Client::Connpass.new.search(keyword: 'coderdojo') } it do expect(subject).to be_instance_of(Hash) expect(subject['results_returned']).to eq 1 expect(subject['events'].size).to eq 1 expect(subject['events'].first['event_id']).to eq 12345 expect(subject['events'].first['series']['url']).to eq 'https://coderdojo-okutama.connpass.com/' expect(subject['events'].first['series']['id']).to eq 9876 end end describe '#fetch_events' do subject { Statistics::Client::Connpass.new.fetch_events(series_id: 9876) } it do expect(subject).to be_instance_of(Array) expect(subject.size).to eq 1 expect(subject.first['event_id']).to eq 12345 expect(subject.first['series']['url']).to eq 'https://coderdojo-okutama.connpass.com/' expect(subject.first['series']['id']).to eq 9876 end end end context 'Doorkeeper' do describe '#search' do subject { Statistics::Client::Doorkeeper.new.search(keyword: 'coderdojo') } it do expect(subject).to be_instance_of(Array) expect(subject.size).to eq 1 expect(subject.first['event']['id']).to eq 1234 expect(subject.first['event']['group']).to eq 5555 end end describe '#fetch_events' do subject { Statistics::Client::Doorkeeper.new.fetch_events(group_id: 5555) } it do expect(subject).to be_instance_of(Array) expect(subject.size).to eq 1 expect(subject.first['id']).to eq 1234 expect(subject.first['group']).to eq 5555 end end end end
require 'testing_env' require 'extend/ARGV' class ArgvExtensionTests < Test::Unit::TestCase def setup @argv = [].extend(HomebrewArgvExtension) end def test_argv_formulae @argv.unshift 'mxcl' assert_raises(FormulaUnavailableError) { @argv.formulae } end def test_argv_kegs keg = HOMEBREW_CELLAR + "mxcl/10.0" keg.mkpath @argv << 'mxcl' assert_equal 1, @argv.kegs.length ensure keg.rmtree end def test_argv_named @argv << 'mxcl' << '--debug' << '-v' assert_equal 1, @argv.named.length end def test_empty_argv assert_empty @argv.named assert_empty @argv.kegs assert_empty @argv.formulae assert_empty @argv end def test_switch? @argv << "-ns" << "-i" << "--bar" %w{n s i}.each { |s| assert @argv.switch?(s) } %w{b ns bar --bar -n}.each { |s| assert !@argv.switch?(s) } end def test_filter_for_dependencies_clears_flags @argv << "--debug" @argv.filter_for_dependencies { assert @argv.empty? } end def test_filter_for_dependencies_ensures_argv_restored @argv.expects(:replace).with(@argv.clone) begin @argv.filter_for_dependencies { raise Exception } rescue Exception end end def test_filter_for_dependencies_returns_block_value assert_equal 1, @argv.filter_for_dependencies { 1 } end end Add test for ARGV.flag? require 'testing_env' require 'extend/ARGV' class ArgvExtensionTests < Test::Unit::TestCase def setup @argv = [].extend(HomebrewArgvExtension) end def test_argv_formulae @argv.unshift 'mxcl' assert_raises(FormulaUnavailableError) { @argv.formulae } end def test_argv_kegs keg = HOMEBREW_CELLAR + "mxcl/10.0" keg.mkpath @argv << 'mxcl' assert_equal 1, @argv.kegs.length ensure keg.rmtree end def test_argv_named @argv << 'mxcl' << '--debug' << '-v' assert_equal 1, @argv.named.length end def test_empty_argv assert_empty @argv.named assert_empty @argv.kegs assert_empty @argv.formulae assert_empty @argv end def test_switch? @argv << "-ns" << "-i" << "--bar" %w{n s i}.each { |s| assert @argv.switch?(s) } %w{b ns bar --bar -n}.each { |s| assert !@argv.switch?(s) } end def test_flag? @argv << "--foo" << "-bq" << "--bar" assert @argv.flag?("--foo") assert @argv.flag?("--bar") assert @argv.flag?("--baz") assert @argv.flag?("--qux") assert !@argv.flag?("--frotz") assert !@argv.flag?("--debug") end def test_filter_for_dependencies_clears_flags @argv << "--debug" @argv.filter_for_dependencies { assert @argv.empty? } end def test_filter_for_dependencies_ensures_argv_restored @argv.expects(:replace).with(@argv.clone) begin @argv.filter_for_dependencies { raise Exception } rescue Exception end end def test_filter_for_dependencies_returns_block_value assert_equal 1, @argv.filter_for_dependencies { 1 } end end
require "net/http" require "json" class Firebell::Client attr_accessor :token def initialize(token = Firebell.configuration.token) @token = token end def notify(tag, body_or_params = nil, body = nil) if body_or_params if body_or_params.is_a?(Hash) attributes = { "tag" => tag, "parameters" => body_or_params } attributes.merge!("body" => body) if body else attributes = { "tag" => tag, "body" => body_or_params } end else attributes = { "tag" => tag } end send_request attributes if requestable? end private def send_request(attrs) if @token request = Net::HTTP::Post.new uri.request_uri, "Authorization" => "Token #{@token}" request.body = JSON.generate attrs http.request(request) else end end def http @http ||= begin http = Net::HTTP.new uri.host, uri.port http.use_ssl = true if uri.is_a?(URI::HTTPS) http end end def uri @uri ||= URI.parse Firebell.configuration.url end def requestable? if Firebell.configuration.notify_release_stages.any? Firebell.configuration.notify_release_stages.include? Firebell.configuration.release_stage else true end end end parse the response body require "net/http" require "json" class Firebell::Client attr_accessor :token def initialize(token = Firebell.configuration.token) @token = token end def notify(tag, body_or_params = nil, body = nil) if body_or_params if body_or_params.is_a?(Hash) attributes = { "tag" => tag, "parameters" => body_or_params } attributes.merge!("body" => body) if body else attributes = { "tag" => tag, "body" => body_or_params } end else attributes = { "tag" => tag } end send_request attributes if requestable? end private def send_request(attrs) if @token request = Net::HTTP::Post.new uri.request_uri, "Authorization" => "Token #{@token}" request.body = JSON.generate attrs response = http.request(request) if response.code.to_i == 201 JSON.parse response.body end else end end def http @http ||= begin http = Net::HTTP.new uri.host, uri.port http.use_ssl = true if uri.is_a?(URI::HTTPS) http end end def uri @uri ||= URI.parse Firebell.configuration.url end def requestable? if Firebell.configuration.notify_release_stages.any? Firebell.configuration.notify_release_stages.include? Firebell.configuration.release_stage else true end end end
require 'spec_helper' describe WP2Middleman::Post do let(:file) { Nokogiri::XML(File.open("#{ENV['PWD']}/spec/fixtures/fixture.xml")) } let(:post_one) { WP2Middleman::Post.new(file.css('item')[0]) } let(:post_two) { WP2Middleman::Post.new(file.css('item')[1]) } let(:post_three) { WP2Middleman::Post.new(file.css('item')[2]) } it "exists as a class within the WP2Middleman module" do expect(WP2Middleman::Post.class).to eq Class end describe "#title" do subject { post_one.title } it { should eq "A Title" } end describe "#post_date" do subject { post_one.post_date } it { should eq "2012-06-08 03:21:41" } end describe "#date_published" do subject { post_one.date_published } it { should eq "2012-06-08" } end describe "#status" do subject { post_three.status } it { should eq "private" } end describe "#field" do subject { post_one.field('wp:post_id') } it { should eq "84" } end describe "#published?" do subject { post_one.published? } it { should eq true } context "#status is not 'publish'" do subject { post_three.published? } it { should eq false } end end describe "#content" do subject { post_one.content } it { should eq "Paragraph one.\n\n Paragraph two.\n " } end describe "#tags" do subject { post_two.tags } it { should eq ["some_tag", "another tag", "tag"] } context "the post only has an 'Uncategorized' tag" do subject { post_one.tags } it { should eq [] } end end describe "#valid?" do def post(post_date: Date.new(2014,2,19), title: "Title", date_published: Date.new(2014,2,19), content: "content") post = WP2Middleman::Post.new(double) post.stub(:post_date).and_return(post_date) post.stub(:title).and_return(title) post.stub(:date_published).and_return(date_published) post.stub(:content).and_return(content) post end it "is valid with post_date, title, date_published, and content" do expect(post).to be_valid end it "is not valid without post_date" do expect(post(post_date: nil)).to_not be_valid end it "is not valid without a title" do expect(post(title: nil)).to_not be_valid end it "is not valid without a date_published" do expect(post(date_published: nil)).to_not be_valid end it "is not valid without content" do expect(post(content: nil)).to_not be_valid end end end removed stubs from post_spec require 'spec_helper' describe WP2Middleman::Post do let(:file) { Nokogiri::XML(File.open("#{ENV['PWD']}/spec/fixtures/fixture.xml")) } let(:post_one) { WP2Middleman::Post.new(file.css('item')[0]) } let(:post_two) { WP2Middleman::Post.new(file.css('item')[1]) } let(:post_three) { WP2Middleman::Post.new(file.css('item')[2]) } it "exists as a class within the WP2Middleman module" do expect(WP2Middleman::Post.class).to eq Class end describe "#title" do subject { post_one.title } it { should eq "A Title" } end describe "#post_date" do subject { post_one.post_date } it { should eq "2012-06-08 03:21:41" } end describe "#date_published" do subject { post_one.date_published } it { should eq "2012-06-08" } end describe "#status" do subject { post_three.status } it { should eq "private" } end describe "#field" do subject { post_one.field('wp:post_id') } it { should eq "84" } end describe "#published?" do subject { post_one.published? } it { should eq true } context "#status is not 'publish'" do subject { post_three.published? } it { should eq false } end end describe "#content" do subject { post_one.content } it { should eq "Paragraph one.\n\n Paragraph two.\n " } end describe "#tags" do subject { post_two.tags } it { should eq ["some_tag", "another tag", "tag"] } context "the post only has an 'Uncategorized' tag" do subject { post_one.tags } it { should eq [] } end end describe "#valid?" do def post(post_date: Date.new(2014,2,19), title: "Title", date_published: Date.new(2014,2,19), content: "content") post = WP2Middleman::Post.new(double) allow(post).to receive(:post_date) { post_date } allow(post).to receive(:title) { title } allow(post).to receive(:date_published) { date_published } allow(post).to receive(:content) { content } post end it "is valid with post_date, title, date_published, and content" do expect(post).to be_valid end it "is not valid without post_date" do expect(post(post_date: nil)).to_not be_valid end it "is not valid without a title" do expect(post(title: nil)).to_not be_valid end it "is not valid without a date_published" do expect(post(date_published: nil)).to_not be_valid end it "is not valid without content" do expect(post(content: nil)).to_not be_valid end end end
module Fitting VERSION = '0.4.2'.freeze end set v.1.0.0 module Fitting VERSION = '1.0.0'.freeze end
# frozen_string_literal: true require 'rails_helper' RSpec.describe Devise::Mailer, type: :mailer do describe 'send_confirmation_email' do let!(:user) { FactoryBot.create(:user) } let(:mail) { Devise.mailer.deliveries.last } before do user.send_confirmation_instructions end it 'renders the receiver email' do expect(mail.to).to eq([user.email]) end it 'renders the subject' do expect(mail.subject).to eql('Confirmation instructions') end it 'addresses the user' do expect(mail.body.encoded).to include(user.name) end it 'is polite' do expect(mail.body.encoded).to include('Thanks for signing up for EBWiki') end it 'prompts the user to confirm' do expect(mail.body.encoded).to match(/click here to confirm your account/i) end end end Updates mailer spec to account for user names with symbols # frozen_string_literal: true require 'rails_helper' RSpec.describe Devise::Mailer, type: :mailer do describe 'send_confirmation_email' do let!(:user) { FactoryBot.create(:user) } let(:mail) { Devise.mailer.deliveries.last } before do user.send_confirmation_instructions end it 'renders the receiver email' do expect(mail.to).to eq([user.email]) end it 'renders the subject' do expect(mail.subject).to eql('Confirmation instructions') end it 'addresses the user' do expect(mail.body).to include(CGI.escapeHTML(user.name)) end it 'is polite' do expect(mail.body.encoded).to include('Thanks for signing up for EBWiki') end it 'prompts the user to confirm' do expect(mail.body.encoded).to match(/click here to confirm your account/i) end end end
module Flatware class Worker class << self def context @context ||= ZMQ::Context.new 1 end def in_context(&block) yield context context.close end def listen! in_context do |context| dispatch = context.socket ZMQ::REQ dispatch.connect 'ipc://dispatch' die = context.socket ZMQ::SUB die.connect 'ipc://die' die.setsockopt ZMQ::SUBSCRIBE, '' dispatch.send 'hi' quit = false while !quit && (ready = ZMQ.select([dispatch, die])) messages = ready.flatten.compact.map(&:recv) for message in messages if message == 'seppuku' quit = true else out = err = StringIO.new Cucumber.run message, out, err result = out.tap(&:rewind).read dispatch.send result end end end dispatch.close die.close end end end end end Workers handle sigint module Flatware class Worker class << self def context @context ||= ZMQ::Context.new 1 end def in_context(&block) yield context context.close end def listen! in_context do |context| dispatch = context.socket ZMQ::REQ dispatch.connect 'ipc://dispatch' die = context.socket ZMQ::SUB die.connect 'ipc://die' die.setsockopt ZMQ::SUBSCRIBE, '' dispatch.send 'hi' quit = false Signal.trap("INT") do dispatch.setsockopt(ZMQ::LINGER, 0) dispatch.close die.close context.close return end while !quit && (ready = ZMQ.select([dispatch, die])) messages = ready.flatten.compact.map(&:recv) for message in messages if message == 'seppuku' quit = true else out = err = StringIO.new Cucumber.run message, out, err result = out.tap(&:rewind).read dispatch.send result end end end dispatch.close die.close end end end end end
require 'rails_helper' describe Aws::S3Storage do let(:subject) { Aws::S3Storage.new } let(:aws_env) { ENV['AWS_ENV'] || "local" } let(:object) { double } let(:bucket_name) { "bucket1" } let(:file_path) { File.dirname(__FILE__) } let(:key) { SecureRandom.uuid } let(:uri) { "urn:openhbx:terms:v1:file_storage:s3:bucket:dchbx-gluedb-#{bucket_name}-#{aws_env}##{key}" } let(:invalid_url) { "urn:openhbx:terms:v1:file_storage:s3:bucket:" } let(:file_content) { "test content" } describe "save()" do context "successful upload with explicit key" do it 'return the URI of saved file' do allow(object).to receive(:upload_file).with(file_path, :server_side_encryption => 'AES256').and_return(true) allow_any_instance_of(Aws::S3Storage).to receive(:get_object).and_return(object) expect(subject.save(file_path, bucket_name, key)).to eq(uri) end end context "successful upload without explicit key" do it 'return the URI of saved file' do allow(object).to receive(:upload_file).with(file_path, :server_side_encryption => 'AES256').and_return(true) allow_any_instance_of(Aws::S3Storage).to receive(:get_object).and_return(object) expect(subject.save(file_path, bucket_name)).to include("urn:openhbx:terms:v1:file_storage:s3:bucket:") end end context "failed upload" do it 'returns nil' do allow(object).to receive(:upload_file).with(file_path, :server_side_encryption => 'AES256').and_return(nil) allow_any_instance_of(Aws::S3Storage).to receive(:get_object).and_return(object) expect(subject.save(file_path, bucket_name)).to be_nil end end context "failed upload with exception" do it 'raises exception' do allow(object).to receive(:upload_file).with(file_path, :server_side_encryption => 'AES256').and_raise() allow_any_instance_of(Aws::S3Storage).to receive(:get_object).and_return(object) expect { subject.save(file_path, bucket_name) }.to raise_error end end end describe "find()" do context "success" do it "returns the file contents" do allow_any_instance_of(Aws::S3Storage).to receive(:get_object).and_return(object) allow_any_instance_of(Aws::S3Storage).to receive(:read_object).with(object).and_return(file_content) expect(subject.find(uri)).to eq(file_content) end end context "failure (invalid uri)" do it "returns nil" do allow_any_instance_of(Aws::S3Storage).to receive(:get_object).and_raise(Exception) expect(subject.find(invalid_url)).to be_nil end end end end Refs #14262 fixed spec require 'rails_helper' describe Aws::S3Storage do let(:subject) { allow_any_instance_of(Aws::S3Storage).to receive(:setup); Aws::S3Storage.new } let(:aws_env) { ENV['AWS_ENV'] || "local" } let(:object) { double } let(:bucket_name) { "bucket1" } let(:file_path) { File.dirname(__FILE__) } let(:key) { SecureRandom.uuid } let(:uri) { "urn:openhbx:terms:v1:file_storage:s3:bucket:dchbx-gluedb-#{bucket_name}-#{aws_env}##{key}" } let(:invalid_url) { "urn:openhbx:terms:v1:file_storage:s3:bucket:" } let(:file_content) { "test content" } describe "save()" do context "successful upload with explicit key" do it 'return the URI of saved file' do allow(object).to receive(:upload_file).with(file_path, :server_side_encryption => 'AES256').and_return(true) allow_any_instance_of(Aws::S3Storage).to receive(:get_object).and_return(object) expect(subject.save(file_path, bucket_name, key)).to eq(uri) end end context "successful upload without explicit key" do it 'return the URI of saved file' do allow(object).to receive(:upload_file).with(file_path, :server_side_encryption => 'AES256').and_return(true) allow_any_instance_of(Aws::S3Storage).to receive(:get_object).and_return(object) expect(subject.save(file_path, bucket_name)).to include("urn:openhbx:terms:v1:file_storage:s3:bucket:") end end context "failed upload" do it 'returns nil' do allow(object).to receive(:upload_file).with(file_path, :server_side_encryption => 'AES256').and_return(nil) allow_any_instance_of(Aws::S3Storage).to receive(:get_object).and_return(object) expect(subject.save(file_path, bucket_name)).to be_nil end end context "failed upload with exception" do let(:exception) {StandardError.new} it 'raises exception' do allow(object).to receive(:upload_file).with(file_path, :server_side_encryption => 'AES256').and_raise(exception) allow_any_instance_of(Aws::S3Storage).to receive(:get_object).and_return(object) expect { subject.save(file_path, bucket_name) }.to raise_error(exception) end end end describe "find()" do context "success" do it "returns the file contents" do allow_any_instance_of(Aws::S3Storage).to receive(:get_object).and_return(object) allow_any_instance_of(Aws::S3Storage).to receive(:read_object).with(object).and_return(file_content) expect(subject.find(uri)).to eq(file_content) end end context "failure (invalid uri)" do it "returns nil" do allow_any_instance_of(Aws::S3Storage).to receive(:get_object).and_raise(Exception) expect(subject.find(invalid_url)).to be_nil end end end end
describe FileDepotNfs do let(:ignore_uri) { "nfs://ignore.com/directory" } let(:actual_uri) { "nfs://actual_bucket/doo_directory" } let(:file_depot_nfs) { FileDepotNfs.new(:uri => uri) } it "should return a valid prefix" do expect(FileDepotNfs.uri_prefix).to eq "nfs" end describe "#merged_uri" do before do file_depot_nfs.uri = ignore_uri end it "should ignore the uri set on the depot object and return the uri parameter" do expect(file_depot_nfs.merged_uri(actual_uri, nil)).to eq actual_uri end end end Fix NFS File Depot Spec Test Tried to rename the "uri" attribute inadvertantly in previous incarnation of this test and broke it. Fixing now. describe FileDepotNfs do let(:uri) { "nfs://ignore.com/directory" } let(:actual_uri) { "nfs://actual_bucket/doo_directory" } let(:file_depot_nfs) { FileDepotNfs.new(:uri => uri) } it "should return a valid prefix" do expect(FileDepotNfs.uri_prefix).to eq "nfs" end describe "#merged_uri" do before do file_depot_nfs.uri = uri end it "should ignore the uri set on the depot object and return the uri parameter" do expect(file_depot_nfs.merged_uri(actual_uri, nil)).to eq actual_uri end end end
require File.expand_path('../../../spec_helper', __FILE__) describe Portal::Teacher do before(:each) do @nces_teacher = FactoryBot.create(:nces_portal_teacher) @virtual_teacher = FactoryBot.create(:portal_teacher) @virtual_teacher.clazzes << FactoryBot.create(:portal_clazz) end it "should support nces teachers" do expect(@nces_teacher).not_to be_nil end it "nces teachers should have at least one class" do expect(@nces_teacher.clazzes).not_to be_nil @nces_teacher.clazzes.size > 0 end it "nces teachers class should be 'real'" do expect(@nces_teacher.clazzes[0]).to be_real end it "virtual teachers should have virtual classes" do expect(@virtual_teacher.clazzes[0]).to be_virtual end # new policy: Teachers CAN change their real clazzes # TODO: If we want to lock classes we need to implement a different mechanism it "teachers with real clazzes should be able to change them" do expect(@nces_teacher.clazzes[0]).to be_changeable(@nces_teacher) end it "should support virtual teachers" do expect(@virtual_teacher).not_to be_nil end it "virtual teachers can have classes" do expect(@virtual_teacher.clazzes).not_to be_nil expect(@virtual_teacher.clazzes.size).not_to be(0) end it "virtual teachers class should not be real" do expect(@virtual_teacher.clazzes[0].real?).not_to be_truthy expect(@virtual_teacher.clazzes[0].virtual?).to be_truthy end it "Teachers in virtual schools should be able to change their clazzes" do expect(@virtual_teacher.clazzes[0]).to be_changeable(@virtual_teacher) end # Should we enforce the school requirement via a validation, or should it be done in the controller at registration? -- Cantina-CMH 6/9/10 # it "should not allow a teacher to exist without a school" do # @virtual_teacher.should be_valid # @virtual_teacher.schools = [] # @virtual_teacher.should_not be_valid # # @nces_teacher.should be_valid # @nces_teacher.schools = [] # @nces_teacher.should_not be_valid # end describe "possibly_add_authoring_role" do describe "when the portal allows teachers to author" do it "should add the authoring role to teachers when they are created" do allow(Admin::Settings).to receive_messages(:teachers_can_author? => true) teacher = FactoryBot.create(:portal_teacher) teacher.possibly_add_authoring_role expect(teacher.user).to have_role('author') end end describe "when the portal doesn't allow the teacher to author" do it "should not add the authoring role to teachers when they are created" do allow(Admin::Settings).to receive_messages(:teachers_can_author? => false) teacher = FactoryBot.create(:portal_teacher) teacher.possibly_add_authoring_role expect(teacher.user).not_to have_role('author') end end end describe '[default cohort support]' do let(:settings) { FactoryBot.create(:admin_settings) } let(:teacher) { FactoryBot.create(:portal_teacher) } before(:each) do allow(Admin::Settings).to receive(:default_settings).and_return(settings) end describe 'when default cohort is not specified in portal settings' do it 'has empty list of cohorts' do expect(teacher.cohorts.length).to eql(0) end end describe 'when default cohort is specified in portal settings' do let(:cohort) { FactoryBot.create(:admin_cohort) } let(:settings) { FactoryBot.create(:admin_settings, default_cohort: cohort) } it 'is added to the default cohort' do expect(teacher.cohorts.length).to eql(1) expect(teacher.cohorts[0]).to eql(cohort) end end end describe 'add_recent_collection_page' do before(:each) do project1 = FactoryBot.create(:project, name: 'Test Project One') @virtual_teacher.add_recent_collection_page(project1) end it 'adds project to the teachers list of recently visited collections pages' do expect(@virtual_teacher.recent_projects.length).to eql(1) end end # TODO: auto-generated describe '.LEFT_PANE_ITEM' do it 'LEFT_PANE_ITEM' do result = described_class.LEFT_PANE_ITEM expect(result).not_to be_nil end end # TODO: auto-generated describe '.save_left_pane_submenu_item' do it 'save_left_pane_submenu_item' do current_visitor = User.new item_value = '1' result = described_class.save_left_pane_submenu_item(current_visitor, item_value) expect(result).to be_nil end end # TODO: auto-generated describe '.can_author?' do it 'can_author?' do result = described_class.can_author? expect(result).not_to be_nil end end # TODO: auto-generated describe '.update_authoring_roles' do it 'update_authoring_roles' do result = described_class.update_authoring_roles expect(result).to be_nil end end # TODO: auto-generated describe '#save_left_pane_submenu_item' do xit 'save_left_pane_submenu_item' do teacher = described_class.new item_value = '1' result = teacher.save_left_pane_submenu_item(item_value) expect(result).not_to be_nil end end # TODO: auto-generated describe '#name' do it 'name' do teacher = described_class.new result = teacher.name expect(result).not_to be_nil end end # TODO: auto-generated describe '#list_name' do it 'list_name' do teacher = described_class.new result = teacher.list_name expect(result).not_to be_nil end end # TODO: auto-generated describe '#school_ids' do it 'school_ids' do teacher = described_class.new result = teacher.school_ids expect(result).not_to be_nil end end # TODO: auto-generated describe '#school_ids=' do xit 'school_ids=' do teacher = described_class.new ids = [1] result = teacher.school_ids=(ids) expect(result).not_to be_nil end end # TODO: auto-generated describe '#school_names' do it 'school_names' do teacher = described_class.new result = teacher.school_names expect(result).not_to be_nil end end # TODO: auto-generated describe '#children' do it 'children' do teacher = described_class.new result = teacher.children expect(result).not_to be_nil end end # TODO: auto-generated describe '#parent' do it 'parent' do teacher = described_class.new result = teacher.parent expect(result).to be_nil end end # TODO: auto-generated describe '#students' do it 'students' do teacher = described_class.new result = teacher.students expect(result).not_to be_nil end end # TODO: auto-generated describe '#has_clazz?' do it 'has_clazz?' do teacher = described_class.new clazz = nil result = teacher.has_clazz?(clazz) expect(result).to be_nil end end # TODO: auto-generated describe '#add_clazz' do xit 'add_clazz' do teacher = described_class.new clazz = nil result = teacher.add_clazz(clazz) expect(result).not_to be_nil end end # TODO: auto-generated describe '#remove_clazz' do xit 'remove_clazz' do teacher = described_class.new clazz = nil result = teacher.remove_clazz(clazz) expect(result).not_to be_nil end end # TODO: auto-generated describe '#school' do it 'school' do teacher = described_class.new result = teacher.school expect(result).to be_nil end end # TODO: auto-generated describe '#possibly_add_authoring_role' do it 'possibly_add_authoring_role' do teacher = described_class.new result = teacher.possibly_add_authoring_role expect(result).to be_nil end end # TODO: auto-generated describe '#my_classes_url' do xit 'my_classes_url' do teacher = described_class.new protocol = double('protocol') host = double('host') result = teacher.my_classes_url(protocol, host) expect(result).not_to be_nil end end end Improve teacher model test coverage. require File.expand_path('../../../spec_helper', __FILE__) describe Portal::Teacher do before(:each) do @nces_teacher = FactoryBot.create(:nces_portal_teacher) @virtual_teacher = FactoryBot.create(:portal_teacher) @virtual_teacher.clazzes << FactoryBot.create(:portal_clazz) end it "should support nces teachers" do expect(@nces_teacher).not_to be_nil end it "nces teachers should have at least one class" do expect(@nces_teacher.clazzes).not_to be_nil @nces_teacher.clazzes.size > 0 end it "nces teachers class should be 'real'" do expect(@nces_teacher.clazzes[0]).to be_real end it "virtual teachers should have virtual classes" do expect(@virtual_teacher.clazzes[0]).to be_virtual end # new policy: Teachers CAN change their real clazzes # TODO: If we want to lock classes we need to implement a different mechanism it "teachers with real clazzes should be able to change them" do expect(@nces_teacher.clazzes[0]).to be_changeable(@nces_teacher) end it "should support virtual teachers" do expect(@virtual_teacher).not_to be_nil end it "virtual teachers can have classes" do expect(@virtual_teacher.clazzes).not_to be_nil expect(@virtual_teacher.clazzes.size).not_to be(0) end it "virtual teachers class should not be real" do expect(@virtual_teacher.clazzes[0].real?).not_to be_truthy expect(@virtual_teacher.clazzes[0].virtual?).to be_truthy end it "Teachers in virtual schools should be able to change their clazzes" do expect(@virtual_teacher.clazzes[0]).to be_changeable(@virtual_teacher) end # Should we enforce the school requirement via a validation, or should it be done in the controller at registration? -- Cantina-CMH 6/9/10 # it "should not allow a teacher to exist without a school" do # @virtual_teacher.should be_valid # @virtual_teacher.schools = [] # @virtual_teacher.should_not be_valid # # @nces_teacher.should be_valid # @nces_teacher.schools = [] # @nces_teacher.should_not be_valid # end describe "possibly_add_authoring_role" do describe "when the portal allows teachers to author" do it "should add the authoring role to teachers when they are created" do allow(Admin::Settings).to receive_messages(:teachers_can_author? => true) teacher = FactoryBot.create(:portal_teacher) teacher.possibly_add_authoring_role expect(teacher.user).to have_role('author') end end describe "when the portal doesn't allow the teacher to author" do it "should not add the authoring role to teachers when they are created" do allow(Admin::Settings).to receive_messages(:teachers_can_author? => false) teacher = FactoryBot.create(:portal_teacher) teacher.possibly_add_authoring_role expect(teacher.user).not_to have_role('author') end end end describe '[default cohort support]' do let(:settings) { FactoryBot.create(:admin_settings) } let(:teacher) { FactoryBot.create(:portal_teacher) } before(:each) do allow(Admin::Settings).to receive(:default_settings).and_return(settings) end describe 'when default cohort is not specified in portal settings' do it 'has empty list of cohorts' do expect(teacher.cohorts.length).to eql(0) end end describe 'when default cohort is specified in portal settings' do let(:cohort) { FactoryBot.create(:admin_cohort) } let(:settings) { FactoryBot.create(:admin_settings, default_cohort: cohort) } it 'is added to the default cohort' do expect(teacher.cohorts.length).to eql(1) expect(teacher.cohorts[0]).to eql(cohort) end end end describe 'add_recent_collection_page' do before(:each) do @project1 = FactoryBot.create(:project, name: 'Test Project One') @project2 = FactoryBot.create(:project, name: 'Test Project Two') @project3 = FactoryBot.create(:project, name: 'Test Project Three') @project4 = FactoryBot.create(:project, name: 'Test Project Four') @virtual_teacher.add_recent_collection_page(@project1) end it 'adds an item to the teacher\'s list of recently visited collections pages' do expect(@virtual_teacher.recent_collections_pages.length).to eql(1) end it 'changes the updated_at value for an item in the teacher\'s list of recently visited collections pages if the teacher has already visited that project\'s collection page' do @rcp_updated_at = @virtual_teacher.recent_collections_pages[0].updated_at sleep(1.second) @virtual_teacher.add_recent_collection_page(@project1) @virtual_teacher.reload expect(@virtual_teacher.recent_collections_pages.length).to eql(1) expect(@virtual_teacher.recent_collections_pages[0].updated_at).to be > @rcp_updated_at end it 'does not add more than three items to the teacher\'s list of recently visited collections pages' do @virtual_teacher.add_recent_collection_page(@project2) @virtual_teacher.add_recent_collection_page(@project3) @virtual_teacher.add_recent_collection_page(@project4) @virtual_teacher.reload expect(@virtual_teacher.recent_collections_pages.length).to eql(3) end end # TODO: auto-generated describe '.LEFT_PANE_ITEM' do it 'LEFT_PANE_ITEM' do result = described_class.LEFT_PANE_ITEM expect(result).not_to be_nil end end # TODO: auto-generated describe '.save_left_pane_submenu_item' do it 'save_left_pane_submenu_item' do current_visitor = User.new item_value = '1' result = described_class.save_left_pane_submenu_item(current_visitor, item_value) expect(result).to be_nil end end # TODO: auto-generated describe '.can_author?' do it 'can_author?' do result = described_class.can_author? expect(result).not_to be_nil end end # TODO: auto-generated describe '.update_authoring_roles' do it 'update_authoring_roles' do result = described_class.update_authoring_roles expect(result).to be_nil end end # TODO: auto-generated describe '#save_left_pane_submenu_item' do xit 'save_left_pane_submenu_item' do teacher = described_class.new item_value = '1' result = teacher.save_left_pane_submenu_item(item_value) expect(result).not_to be_nil end end # TODO: auto-generated describe '#name' do it 'name' do teacher = described_class.new result = teacher.name expect(result).not_to be_nil end end # TODO: auto-generated describe '#list_name' do it 'list_name' do teacher = described_class.new result = teacher.list_name expect(result).not_to be_nil end end # TODO: auto-generated describe '#school_ids' do it 'school_ids' do teacher = described_class.new result = teacher.school_ids expect(result).not_to be_nil end end # TODO: auto-generated describe '#school_ids=' do xit 'school_ids=' do teacher = described_class.new ids = [1] result = teacher.school_ids=(ids) expect(result).not_to be_nil end end # TODO: auto-generated describe '#school_names' do it 'school_names' do teacher = described_class.new result = teacher.school_names expect(result).not_to be_nil end end # TODO: auto-generated describe '#children' do it 'children' do teacher = described_class.new result = teacher.children expect(result).not_to be_nil end end # TODO: auto-generated describe '#parent' do it 'parent' do teacher = described_class.new result = teacher.parent expect(result).to be_nil end end # TODO: auto-generated describe '#students' do it 'students' do teacher = described_class.new result = teacher.students expect(result).not_to be_nil end end # TODO: auto-generated describe '#has_clazz?' do it 'has_clazz?' do teacher = described_class.new clazz = nil result = teacher.has_clazz?(clazz) expect(result).to be_nil end end # TODO: auto-generated describe '#add_clazz' do xit 'add_clazz' do teacher = described_class.new clazz = nil result = teacher.add_clazz(clazz) expect(result).not_to be_nil end end # TODO: auto-generated describe '#remove_clazz' do xit 'remove_clazz' do teacher = described_class.new clazz = nil result = teacher.remove_clazz(clazz) expect(result).not_to be_nil end end # TODO: auto-generated describe '#school' do it 'school' do teacher = described_class.new result = teacher.school expect(result).to be_nil end end # TODO: auto-generated describe '#possibly_add_authoring_role' do it 'possibly_add_authoring_role' do teacher = described_class.new result = teacher.possibly_add_authoring_role expect(result).to be_nil end end # TODO: auto-generated describe '#my_classes_url' do xit 'my_classes_url' do teacher = described_class.new protocol = double('protocol') host = double('host') result = teacher.my_classes_url(protocol, host) expect(result).not_to be_nil end end end
require "spec_helper" describe Mongoid::Interceptable do class TestClass include Mongoid::Interceptable attr_reader :before_save_called, :after_save_called before_save do |object| @before_save_called = true end after_save do |object| @after_save_called = true end end describe ".included" do let(:klass) do TestClass end it "includes the before_create callback" do expect(klass).to respond_to(:before_create) end it "includes the after_create callback" do expect(klass).to respond_to(:after_create) end it "includes the before_destroy callback" do expect(klass).to respond_to(:before_destroy) end it "includes the after_destroy callback" do expect(klass).to respond_to(:after_destroy) end it "includes the before_save callback" do expect(klass).to respond_to(:before_save) end it "includes the after_save callback" do expect(klass).to respond_to(:after_save) end it "includes the before_update callback" do expect(klass).to respond_to(:before_update) end it "includes the after_update callback" do expect(klass).to respond_to(:after_update) end it "includes the before_validation callback" do expect(klass).to respond_to(:before_validation) end it "includes the after_validation callback" do expect(klass).to respond_to(:after_validation) end it "includes the after_initialize callback" do expect(klass).to respond_to(:after_initialize) end it "includes the after_build callback" do expect(klass).to respond_to(:after_build) end end describe ".after_find" do let!(:player) do Player.create end context "when the callback is on a root document" do context "when when the document is instantiated" do it "does not execute the callback" do expect(player.impressions).to eq(0) end end context "when the document is found via #find" do let(:from_db) do Player.find(player.id) end it "executes the callback" do expect(from_db.impressions).to eq(1) end end context "when the document is found in a criteria" do let(:from_db) do Player.where(id: player.id).first end it "executes the callback" do expect(from_db.impressions).to eq(1) end end context "when the document is reloaded" do let(:from_db) do Player.find(player.id) end before do from_db.reload end it "executes the callback" do expect(from_db.impressions).to eq(1) end end end context "when the callback is on an embedded document" do let!(:implant) do player.implants.create end context "when when the document is instantiated" do it "does not execute the callback" do expect(implant.impressions).to eq(0) end end context "when the document is found via #find" do let(:from_db) do Player.find(player.id).implants.first end it "executes the callback" do expect(from_db.impressions).to eq(1) end end context "when the document is found in a criteria" do let(:from_db) do Player.find(player.id).implants.find(implant.id) end it "executes the callback" do expect(from_db.impressions).to eq(1) end end end end describe ".after_initialize" do let(:game) do Game.new end it "runs after document instantiation" do expect(game.name).to eq("Testing") end context 'when the document is embedded' do before do Book.destroy_all end after do Book.destroy_all end let(:book) do book = Book.new({ :pages => [ { content: "Page 1", notes: [ { message: "Page 1 / Note A" }, { message: "Page 1 / Note B" } ] }, { content: "Page 2", notes: [ { message: "Page 2 / Note A" }, { message: "Page 2 / Note B" } ] } ] }) book.id = '123' book.save book end let(:new_message) do 'Note C' end before do book.pages.each do | page | page.notes.destroy_all page.notes.new(message: new_message) page.save end end let(:expected_messages) do book.reload.pages.reduce([]) do |messages, p| messages += p.notes.reduce([]) do |msgs, n| msgs << n.message end end end it 'runs the callback on the embedded documents and saves the parent document' do expect(expected_messages.all? { |m| m == new_message }).to be(true) end end end describe ".after_build" do let(:weapon) do Player.new(frags: 5).weapons.build end it "runs after document build (references_many)" do expect(weapon.name).to eq("Holy Hand Grenade (5)") end let(:implant) do Player.new(frags: 5).implants.build end it "runs after document build (embeds_many)" do expect(implant.name).to eq('Cochlear Implant (5)') end let(:powerup) do Player.new(frags: 5).build_powerup end it "runs after document build (references_one)" do expect(powerup.name).to eq("Quad Damage (5)") end let(:augmentation) do Player.new(frags: 5).build_augmentation end it "runs after document build (embeds_one)" do expect(augmentation.name).to eq("Infolink (5)") end end describe ".before_create" do let(:artist) do Artist.new(name: "Depeche Mode") end context "callback returns true" do before do expect(artist).to receive(:before_create_stub).once.and_return(true) artist.save end it "gets saved" do expect(artist.persisted?).to be true end end context "callback returns false" do before do expect(artist).to receive(:before_create_stub).once.and_return(false) artist.save end it "does not get saved" do expect(artist.persisted?).to be false end end end describe ".before_save" do context "when creating" do let(:artist) do Artist.new(name: "Depeche Mode") end after do artist.delete end context "when the callback returns true" do before do expect(artist).to receive(:before_save_stub).once.and_return(true) end it "the save returns true" do expect(artist.save).to be true end end context "when callback returns false" do before do expect(artist).to receive(:before_save_stub).once.and_return(false) end it "the save returns false" do expect(artist.save).to be false end end end context "when updating" do let(:artist) do Artist.create(name: "Depeche Mode").tap do |artist| artist.name = "The Mountain Goats" end end after do artist.delete end context "when the callback returns true" do before do expect(artist).to receive(:before_save_stub).once.and_return(true) end it "the save returns true" do expect(artist.save).to be true end end context "when the callback returns false" do before do expect(artist).to receive(:before_save_stub).once.and_return(false) end it "the save returns false" do expect(artist.save).to be false end end end end describe ".before_destroy" do let(:artist) do Artist.create(name: "Depeche Mode") end before do artist.name = "The Mountain Goats" end after do artist.delete end context "when the callback returns true" do before do expect(artist).to receive(:before_destroy_stub).once.and_return(true) end it "the destroy returns true" do expect(artist.destroy).to be true end end context "when the callback returns false" do before do expect(artist).to receive(:before_destroy_stub).once.and_return(false) end it "the destroy returns false" do expect(artist.destroy).to be false end end context "when cascading callbacks" do let!(:moderat) do Band.create!(name: "Moderat") end let!(:record) do moderat.records.create(name: "Moderat") end before do moderat.destroy end it "executes the child destroy callbacks" do expect(record.before_destroy_called).to be true end end end describe "#run_after_callbacks" do let(:object) do TestClass.new end before do object.run_after_callbacks(:save) end it "runs the after callbacks" do expect(object.after_save_called).to be true end it "does not run the before callbacks" do expect(object.before_save_called).to be nil end end describe "#run_before_callbacks" do let(:object) do TestClass.new end before do object.run_before_callbacks(:save) end it "runs the before callbacks" do expect(object.before_save_called).to be true end it "does not run the after callbacks" do expect(object.after_save_called).to be nil end end context "when cascading callbacks" do context "when the parent has a custom callback" do context "when the child does not have the same callback defined" do let(:band) do Band.new end let!(:record) do band.records.build end context "when running the callbacks directly" do before(:all) do Band.define_model_callbacks(:rearrange) Band.after_rearrange { } end after(:all) do Band.reset_callbacks(:rearrange) end it "does not cascade to the child" do expect(band.run_callbacks(:rearrange)).to be true end end context "when the callbacks get triggered by a destroy" do before(:all) do Band.define_model_callbacks(:rearrange) Band.set_callback(:validation, :before) do run_callbacks(:rearrange) end end after(:all) do Band.reset_callbacks(:rearrange) end let(:attributes) do { records_attributes: { "0" => { "_id" => record.id, "_destroy" => true } } } end it "does not cascade to the child" do Band.accepts_nested_attributes_for :records, allow_destroy: true expect(band.update_attributes(attributes)).to be true end end end end context "when a document can exist in more than 1 level" do let(:band) do Band.new end let(:record) do band.records.build end let(:note) do Note.new end context "when adding the document at multiple levels" do before do band.notes.push(note) record.notes.push(note) end context "when saving the root" do it "only executes the callbacks once for each embed" do expect(note).to receive(:update_saved).twice band.save end end end end context "when cascading after initialize" do let!(:person) do Person.create end before do person.services.create!(sid: 1) end it "doesn't cascade the initialize" do expect_any_instance_of(Service).to receive(:after_initialize_called=).never expect(Person.find(person.id)).to eq(person) end end context "when attempting to cascade on a referenced relation" do it "raises an error" do expect { Band.has_and_belongs_to_many :tags, cascade_callbacks: true }.to raise_error(Mongoid::Errors::InvalidOptions) end end context "when the documents are embedded one level" do describe "#after_create" do context "when the child is new" do context "when the parent is new" do let(:band) do Band.new(name: "Moderat") end let!(:label) do band.build_label(name: "Mute") end before do band.save end it "executes the callback" do expect(label.after_create_called).to be true end end context "when the parent is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:label) do band.build_label(name: "Mute") end before do band.save end it "executes the callback" do expect(label.after_create_called).to be true end end end context "when the child is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:label) do band.create_label(name: "Mute") end before do label.after_create_called = false band.save end it "does not execute the callback" do expect(label.after_create_called).to be false end end end describe "#after_save" do context "when the child is new" do context "when the parent is new" do let(:band) do Band.new(name: "Moderat") end let!(:label) do band.build_label(name: "Mute") end before do band.save end it "executes the callback" do expect(label.after_save_called).to be true end end context "when the parent is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:label) do band.build_label(name: "Mute") end before do band.save end it "executes the callback" do expect(label.after_save_called).to be true end end end context "when the child is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:label) do band.create_label(name: "Mute") end before do band.save end it "executes the callback" do expect(label.after_save_called).to be true end end end describe "#after_update" do context "when the child is new" do context "when the parent is new" do let(:band) do Band.new(name: "Moderat") end let!(:label) do band.build_label(name: "Mute") end before do band.save end it "does not execute the callback" do expect(label.after_update_called).to be false end end context "when the parent is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:label) do band.build_label(name: "Mute") end before do band.save end it "does not execute the callback" do expect(label.after_update_called).to be false end end end context "when the child is persisted" do let(:band) do Band.create(name: "Moderat") end context "when the child is dirty" do let!(:label) do band.create_label(name: "Mute") end before do label.name = "Nothing" band.save end it "executes the callback" do expect(label.after_update_called).to be true end end context "when the child is not dirty" do let!(:label) do band.build_label(name: "Mute") end before do band.save end it "does not execute the callback" do expect(label.after_update_called).to be false end end end end describe "#after_validation" do context "when the child is new" do context "when the parent is new" do let(:band) do Band.new(name: "Moderat") end let!(:label) do band.build_label(name: "Mute") end before do band.save end it "executes the callback" do expect(label.after_validation_called).to be true end end context "when the parent is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:label) do band.build_label(name: "Mute") end before do band.save end it "executes the callback" do expect(label.after_validation_called).to be true end end end context "when the child is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:label) do band.create_label(name: "Mute") end before do band.save end it "executes the callback" do expect(label.after_validation_called).to be true end end end describe "#before_create" do context "when the child is new" do context "when the parent is new" do let(:band) do Band.new(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end before do band.save end it "executes the callback" do expect(record.before_create_called).to be true end end context "when the parent is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end before do band.save end it "executes the callback" do expect(record.before_create_called).to be true end end end context "when the child is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.create(name: "Moderat") end before do record.before_create_called = false band.save end it "does not execute the callback" do expect(record.before_create_called).to be false end end end describe "#before_save" do context "when the child is new" do context "when the parent is new" do let(:band) do Band.new(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end before do band.save end it "executes the callback" do expect(record.before_save_called).to be true end it "persists the change" do expect(band.reload.records.first.before_save_called).to be true end end context "when the parent is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end before do band.save end it "executes the callback" do expect(record.before_save_called).to be true end it "persists the change" do expect(band.reload.records.first.before_save_called).to be true end end end context "when the child is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.create(name: "Moderat") end before do band.save end it "executes the callback" do expect(record.before_save_called).to be true end it "persists the change" do expect(band.reload.records.first.before_save_called).to be true end end context "when the child is created" do let!(:band) do Band.create end let!(:label) do band.create_label(name: 'Label') end it "only executes callback once" do expect(label.before_save_count).to be 1 end end end describe "#before_update" do context "when the child is new" do context "when the parent is new" do let(:band) do Band.new(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end before do band.save end it "does not execute the callback" do expect(record.before_update_called).to be false end end context "when the parent is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end before do band.save end it "does not execute the callback" do expect(record.before_update_called).to be false end end end context "when the child is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.create(name: "Moderat") end context "when the child is dirty" do before do record.name = "Nothing" band.save end it "executes the callback" do expect(record.before_update_called).to be true end it "persists the change" do expect(band.reload.records.first.before_update_called).to be true end end context "when the child is not dirty" do before do band.save end it "does not execute the callback" do expect(record.before_update_called).to be false end end end end describe "#before_validation" do context "when the child is new" do context "when the parent is new" do let(:band) do Band.new(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end before do band.save end it "executes the callback" do expect(record.before_validation_called).to be true end it "persists the change" do expect(band.reload.records.first.before_validation_called).to be true end end context "when the parent is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end before do band.save end it "executes the callback" do expect(record.before_validation_called).to be true end it "persists the change" do expect(band.reload.records.first.before_validation_called).to be true end end end context "when the child is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.create(name: "Moderat") end before do band.save end it "executes the callback" do expect(record.before_validation_called).to be true end it "persists the change" do expect(band.reload.records.first.before_validation_called).to be true end end end end context "when the document is embedded multiple levels" do describe "#before_create" do context "when the child is new" do context "when the root is new" do let(:band) do Band.new(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end let!(:track) do record.tracks.build(name: "Berlin") end before do band.save end it "executes the callback" do expect(track.before_create_called).to be true end end context "when the root is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end let!(:track) do record.tracks.build(name: "Berlin") end before do band.save end it "executes the callback" do expect(track.before_create_called).to be true end end end context "when the child is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.create(name: "Moderat") end let!(:track) do record.tracks.create(name: "Berlin") end before do track.before_create_called = false band.save end it "does not execute the callback" do expect(track.before_create_called).to be false end end end describe "#before_save" do context "when the child is new" do context "when the root is new" do let(:band) do Band.new(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end let!(:track) do record.tracks.build(name: "Berlin") end before do band.save end let(:reloaded) do band.reload.records.first end it "executes the callback" do expect(track.before_save_called).to be true end it "persists the change" do expect(reloaded.tracks.first.before_save_called).to be true end end context "when the parent is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end let!(:track) do record.tracks.build(name: "Berlin") end before do band.save end let(:reloaded) do band.reload.records.first end it "executes the callback" do expect(track.before_save_called).to be true end it "persists the change" do expect(reloaded.tracks.first.before_save_called).to be true end end end context "when the child is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.create(name: "Moderat") end let!(:track) do record.tracks.create(name: "Berlin") end before do band.save end let(:reloaded) do band.reload.records.first end it "executes the callback" do expect(track.before_save_called).to be true end it "persists the change" do expect(reloaded.tracks.first.before_save_called).to be true end end end describe "#before_update" do context "when the child is new" do context "when the parent is new" do let(:band) do Band.new(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end let!(:track) do record.tracks.build(name: "Berlin") end before do band.save end it "does not execute the callback" do expect(track.before_update_called).to be false end end context "when the parent is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end let!(:track) do record.tracks.build(name: "Berlin") end before do band.save end it "does not execute the callback" do expect(track.before_update_called).to be false end end end context "when the child is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.create(name: "Moderat") end let!(:track) do record.tracks.create(name: "Berlin") end context "when the child is dirty" do before do track.name = "Rusty Nails" band.save end let(:reloaded) do band.reload.records.first end it "executes the callback" do expect(track.before_update_called).to be true end it "persists the change" do expect(reloaded.tracks.first.before_update_called).to be true end end context "when the child is not dirty" do before do band.save end it "does not execute the callback" do expect(track.before_update_called).to be false end end end end describe "#before_validation" do context "when the child is new" do context "when the parent is new" do let(:band) do Band.new(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end let!(:track) do record.tracks.build(name: "Berlin") end before do band.save end it "executes the callback" do expect(track.before_validation_called).to be true end end context "when the parent is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end let!(:track) do record.tracks.build(name: "Berlin") end before do band.save end it "executes the callback" do expect(track.before_validation_called).to be true end end end context "when the child is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.create(name: "Moderat") end let!(:track) do record.tracks.create(name: "Berlin") end before do band.save end it "executes the callback" do expect(track.before_validation_called).to be true end end end end end context "callback on valid?" do it "goes in all validation callback in good order" do shin = ValidationCallback.new shin.valid? expect(shin.history).to eq([:before_validation, :validate, :after_validation]) end end context "when creating child documents in callbacks" do let(:parent) do ParentDoc.new end before do parent.save end it "does not duplicate the child documents" do parent.children.create(position: 1) expect(ParentDoc.find(parent.id).children.size).to eq(1) end end context "when callbacks cancel persistence" do let(:address) do Address.new(street: "123 Sesame") end before(:all) do Person.before_save do |doc| doc.mode != :prevent_save end end after(:all) do Person.reset_callbacks(:save) end context "when creating a document" do let(:person) do Person.new(mode: :prevent_save, title: "Associate", addresses: [ address ]) end it "fails to save" do expect(person).to be_valid expect(person.save).to be false end it "is a new record" do expect(person).to be_a_new_record expect { person.save }.not_to change { person.new_record? } end it "is left dirty" do expect(person).to be_changed expect { person.save }.not_to change { person.changed? } end it "child documents are left dirty" do expect(address).to be_changed expect { person.save }.not_to change { address.changed? } end end context "when updating a document" do let(:person) do Person.create.tap do |person| person.attributes = { mode: :prevent_save, title: "Associate", addresses: [ address ] } end end it "#save returns false" do expect(person).to be_valid expect(person.save).to be false end it "is a not a new record" do expect(person).to_not be_a_new_record expect { person.save }.not_to change { person.new_record? } end it "is left dirty" do expect(person).to be_changed expect { person.save }.not_to change { person.changed? } end it "child documents are left dirty" do expect(address).to be_changed expect { person.save }.not_to change { address.changed? } end end end context "when loading a model multiple times" do before do load "spec/app/models/callback_test.rb" load "spec/app/models/callback_test.rb" end let(:callback) do CallbackTest.new end context "when saving the document" do it "only executes the callbacks once" do expect(callback).to receive(:execute).once callback.save end end end end MONGOID-3326 Spacing and unnecessary collection purge require "spec_helper" describe Mongoid::Interceptable do class TestClass include Mongoid::Interceptable attr_reader :before_save_called, :after_save_called before_save do |object| @before_save_called = true end after_save do |object| @after_save_called = true end end describe ".included" do let(:klass) do TestClass end it "includes the before_create callback" do expect(klass).to respond_to(:before_create) end it "includes the after_create callback" do expect(klass).to respond_to(:after_create) end it "includes the before_destroy callback" do expect(klass).to respond_to(:before_destroy) end it "includes the after_destroy callback" do expect(klass).to respond_to(:after_destroy) end it "includes the before_save callback" do expect(klass).to respond_to(:before_save) end it "includes the after_save callback" do expect(klass).to respond_to(:after_save) end it "includes the before_update callback" do expect(klass).to respond_to(:before_update) end it "includes the after_update callback" do expect(klass).to respond_to(:after_update) end it "includes the before_validation callback" do expect(klass).to respond_to(:before_validation) end it "includes the after_validation callback" do expect(klass).to respond_to(:after_validation) end it "includes the after_initialize callback" do expect(klass).to respond_to(:after_initialize) end it "includes the after_build callback" do expect(klass).to respond_to(:after_build) end end describe ".after_find" do let!(:player) do Player.create end context "when the callback is on a root document" do context "when when the document is instantiated" do it "does not execute the callback" do expect(player.impressions).to eq(0) end end context "when the document is found via #find" do let(:from_db) do Player.find(player.id) end it "executes the callback" do expect(from_db.impressions).to eq(1) end end context "when the document is found in a criteria" do let(:from_db) do Player.where(id: player.id).first end it "executes the callback" do expect(from_db.impressions).to eq(1) end end context "when the document is reloaded" do let(:from_db) do Player.find(player.id) end before do from_db.reload end it "executes the callback" do expect(from_db.impressions).to eq(1) end end end context "when the callback is on an embedded document" do let!(:implant) do player.implants.create end context "when when the document is instantiated" do it "does not execute the callback" do expect(implant.impressions).to eq(0) end end context "when the document is found via #find" do let(:from_db) do Player.find(player.id).implants.first end it "executes the callback" do expect(from_db.impressions).to eq(1) end end context "when the document is found in a criteria" do let(:from_db) do Player.find(player.id).implants.find(implant.id) end it "executes the callback" do expect(from_db.impressions).to eq(1) end end end end describe ".after_initialize" do let(:game) do Game.new end it "runs after document instantiation" do expect(game.name).to eq("Testing") end context 'when the document is embedded' do after do Book.destroy_all end let(:book) do book = Book.new({ :pages => [ { content: "Page 1", notes: [ { message: "Page 1 / Note A" }, { message: "Page 1 / Note B" } ] }, { content: "Page 2", notes: [ { message: "Page 2 / Note A" }, { message: "Page 2 / Note B" } ] } ] }) book.id = '123' book.save book end let(:new_message) do 'Note C' end before do book.pages.each do | page | page.notes.destroy_all page.notes.new(message: new_message) page.save end end let(:expected_messages) do book.reload.pages.reduce([]) do |messages, p| messages += p.notes.reduce([]) do |msgs, n| msgs << n.message end end end it 'runs the callback on the embedded documents and saves the parent document' do expect(expected_messages.all? { |m| m == new_message }).to be(true) end end end describe ".after_build" do let(:weapon) do Player.new(frags: 5).weapons.build end it "runs after document build (references_many)" do expect(weapon.name).to eq("Holy Hand Grenade (5)") end let(:implant) do Player.new(frags: 5).implants.build end it "runs after document build (embeds_many)" do expect(implant.name).to eq('Cochlear Implant (5)') end let(:powerup) do Player.new(frags: 5).build_powerup end it "runs after document build (references_one)" do expect(powerup.name).to eq("Quad Damage (5)") end let(:augmentation) do Player.new(frags: 5).build_augmentation end it "runs after document build (embeds_one)" do expect(augmentation.name).to eq("Infolink (5)") end end describe ".before_create" do let(:artist) do Artist.new(name: "Depeche Mode") end context "callback returns true" do before do expect(artist).to receive(:before_create_stub).once.and_return(true) artist.save end it "gets saved" do expect(artist.persisted?).to be true end end context "callback returns false" do before do expect(artist).to receive(:before_create_stub).once.and_return(false) artist.save end it "does not get saved" do expect(artist.persisted?).to be false end end end describe ".before_save" do context "when creating" do let(:artist) do Artist.new(name: "Depeche Mode") end after do artist.delete end context "when the callback returns true" do before do expect(artist).to receive(:before_save_stub).once.and_return(true) end it "the save returns true" do expect(artist.save).to be true end end context "when callback returns false" do before do expect(artist).to receive(:before_save_stub).once.and_return(false) end it "the save returns false" do expect(artist.save).to be false end end end context "when updating" do let(:artist) do Artist.create(name: "Depeche Mode").tap do |artist| artist.name = "The Mountain Goats" end end after do artist.delete end context "when the callback returns true" do before do expect(artist).to receive(:before_save_stub).once.and_return(true) end it "the save returns true" do expect(artist.save).to be true end end context "when the callback returns false" do before do expect(artist).to receive(:before_save_stub).once.and_return(false) end it "the save returns false" do expect(artist.save).to be false end end end end describe ".before_destroy" do let(:artist) do Artist.create(name: "Depeche Mode") end before do artist.name = "The Mountain Goats" end after do artist.delete end context "when the callback returns true" do before do expect(artist).to receive(:before_destroy_stub).once.and_return(true) end it "the destroy returns true" do expect(artist.destroy).to be true end end context "when the callback returns false" do before do expect(artist).to receive(:before_destroy_stub).once.and_return(false) end it "the destroy returns false" do expect(artist.destroy).to be false end end context "when cascading callbacks" do let!(:moderat) do Band.create!(name: "Moderat") end let!(:record) do moderat.records.create(name: "Moderat") end before do moderat.destroy end it "executes the child destroy callbacks" do expect(record.before_destroy_called).to be true end end end describe "#run_after_callbacks" do let(:object) do TestClass.new end before do object.run_after_callbacks(:save) end it "runs the after callbacks" do expect(object.after_save_called).to be true end it "does not run the before callbacks" do expect(object.before_save_called).to be nil end end describe "#run_before_callbacks" do let(:object) do TestClass.new end before do object.run_before_callbacks(:save) end it "runs the before callbacks" do expect(object.before_save_called).to be true end it "does not run the after callbacks" do expect(object.after_save_called).to be nil end end context "when cascading callbacks" do context "when the parent has a custom callback" do context "when the child does not have the same callback defined" do let(:band) do Band.new end let!(:record) do band.records.build end context "when running the callbacks directly" do before(:all) do Band.define_model_callbacks(:rearrange) Band.after_rearrange { } end after(:all) do Band.reset_callbacks(:rearrange) end it "does not cascade to the child" do expect(band.run_callbacks(:rearrange)).to be true end end context "when the callbacks get triggered by a destroy" do before(:all) do Band.define_model_callbacks(:rearrange) Band.set_callback(:validation, :before) do run_callbacks(:rearrange) end end after(:all) do Band.reset_callbacks(:rearrange) end let(:attributes) do { records_attributes: { "0" => { "_id" => record.id, "_destroy" => true } } } end it "does not cascade to the child" do Band.accepts_nested_attributes_for :records, allow_destroy: true expect(band.update_attributes(attributes)).to be true end end end end context "when a document can exist in more than 1 level" do let(:band) do Band.new end let(:record) do band.records.build end let(:note) do Note.new end context "when adding the document at multiple levels" do before do band.notes.push(note) record.notes.push(note) end context "when saving the root" do it "only executes the callbacks once for each embed" do expect(note).to receive(:update_saved).twice band.save end end end end context "when cascading after initialize" do let!(:person) do Person.create end before do person.services.create!(sid: 1) end it "doesn't cascade the initialize" do expect_any_instance_of(Service).to receive(:after_initialize_called=).never expect(Person.find(person.id)).to eq(person) end end context "when attempting to cascade on a referenced relation" do it "raises an error" do expect { Band.has_and_belongs_to_many :tags, cascade_callbacks: true }.to raise_error(Mongoid::Errors::InvalidOptions) end end context "when the documents are embedded one level" do describe "#after_create" do context "when the child is new" do context "when the parent is new" do let(:band) do Band.new(name: "Moderat") end let!(:label) do band.build_label(name: "Mute") end before do band.save end it "executes the callback" do expect(label.after_create_called).to be true end end context "when the parent is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:label) do band.build_label(name: "Mute") end before do band.save end it "executes the callback" do expect(label.after_create_called).to be true end end end context "when the child is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:label) do band.create_label(name: "Mute") end before do label.after_create_called = false band.save end it "does not execute the callback" do expect(label.after_create_called).to be false end end end describe "#after_save" do context "when the child is new" do context "when the parent is new" do let(:band) do Band.new(name: "Moderat") end let!(:label) do band.build_label(name: "Mute") end before do band.save end it "executes the callback" do expect(label.after_save_called).to be true end end context "when the parent is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:label) do band.build_label(name: "Mute") end before do band.save end it "executes the callback" do expect(label.after_save_called).to be true end end end context "when the child is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:label) do band.create_label(name: "Mute") end before do band.save end it "executes the callback" do expect(label.after_save_called).to be true end end end describe "#after_update" do context "when the child is new" do context "when the parent is new" do let(:band) do Band.new(name: "Moderat") end let!(:label) do band.build_label(name: "Mute") end before do band.save end it "does not execute the callback" do expect(label.after_update_called).to be false end end context "when the parent is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:label) do band.build_label(name: "Mute") end before do band.save end it "does not execute the callback" do expect(label.after_update_called).to be false end end end context "when the child is persisted" do let(:band) do Band.create(name: "Moderat") end context "when the child is dirty" do let!(:label) do band.create_label(name: "Mute") end before do label.name = "Nothing" band.save end it "executes the callback" do expect(label.after_update_called).to be true end end context "when the child is not dirty" do let!(:label) do band.build_label(name: "Mute") end before do band.save end it "does not execute the callback" do expect(label.after_update_called).to be false end end end end describe "#after_validation" do context "when the child is new" do context "when the parent is new" do let(:band) do Band.new(name: "Moderat") end let!(:label) do band.build_label(name: "Mute") end before do band.save end it "executes the callback" do expect(label.after_validation_called).to be true end end context "when the parent is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:label) do band.build_label(name: "Mute") end before do band.save end it "executes the callback" do expect(label.after_validation_called).to be true end end end context "when the child is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:label) do band.create_label(name: "Mute") end before do band.save end it "executes the callback" do expect(label.after_validation_called).to be true end end end describe "#before_create" do context "when the child is new" do context "when the parent is new" do let(:band) do Band.new(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end before do band.save end it "executes the callback" do expect(record.before_create_called).to be true end end context "when the parent is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end before do band.save end it "executes the callback" do expect(record.before_create_called).to be true end end end context "when the child is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.create(name: "Moderat") end before do record.before_create_called = false band.save end it "does not execute the callback" do expect(record.before_create_called).to be false end end end describe "#before_save" do context "when the child is new" do context "when the parent is new" do let(:band) do Band.new(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end before do band.save end it "executes the callback" do expect(record.before_save_called).to be true end it "persists the change" do expect(band.reload.records.first.before_save_called).to be true end end context "when the parent is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end before do band.save end it "executes the callback" do expect(record.before_save_called).to be true end it "persists the change" do expect(band.reload.records.first.before_save_called).to be true end end end context "when the child is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.create(name: "Moderat") end before do band.save end it "executes the callback" do expect(record.before_save_called).to be true end it "persists the change" do expect(band.reload.records.first.before_save_called).to be true end end context "when the child is created" do let!(:band) do Band.create end let!(:label) do band.create_label(name: 'Label') end it "only executes callback once" do expect(label.before_save_count).to be 1 end end end describe "#before_update" do context "when the child is new" do context "when the parent is new" do let(:band) do Band.new(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end before do band.save end it "does not execute the callback" do expect(record.before_update_called).to be false end end context "when the parent is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end before do band.save end it "does not execute the callback" do expect(record.before_update_called).to be false end end end context "when the child is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.create(name: "Moderat") end context "when the child is dirty" do before do record.name = "Nothing" band.save end it "executes the callback" do expect(record.before_update_called).to be true end it "persists the change" do expect(band.reload.records.first.before_update_called).to be true end end context "when the child is not dirty" do before do band.save end it "does not execute the callback" do expect(record.before_update_called).to be false end end end end describe "#before_validation" do context "when the child is new" do context "when the parent is new" do let(:band) do Band.new(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end before do band.save end it "executes the callback" do expect(record.before_validation_called).to be true end it "persists the change" do expect(band.reload.records.first.before_validation_called).to be true end end context "when the parent is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end before do band.save end it "executes the callback" do expect(record.before_validation_called).to be true end it "persists the change" do expect(band.reload.records.first.before_validation_called).to be true end end end context "when the child is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.create(name: "Moderat") end before do band.save end it "executes the callback" do expect(record.before_validation_called).to be true end it "persists the change" do expect(band.reload.records.first.before_validation_called).to be true end end end end context "when the document is embedded multiple levels" do describe "#before_create" do context "when the child is new" do context "when the root is new" do let(:band) do Band.new(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end let!(:track) do record.tracks.build(name: "Berlin") end before do band.save end it "executes the callback" do expect(track.before_create_called).to be true end end context "when the root is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end let!(:track) do record.tracks.build(name: "Berlin") end before do band.save end it "executes the callback" do expect(track.before_create_called).to be true end end end context "when the child is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.create(name: "Moderat") end let!(:track) do record.tracks.create(name: "Berlin") end before do track.before_create_called = false band.save end it "does not execute the callback" do expect(track.before_create_called).to be false end end end describe "#before_save" do context "when the child is new" do context "when the root is new" do let(:band) do Band.new(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end let!(:track) do record.tracks.build(name: "Berlin") end before do band.save end let(:reloaded) do band.reload.records.first end it "executes the callback" do expect(track.before_save_called).to be true end it "persists the change" do expect(reloaded.tracks.first.before_save_called).to be true end end context "when the parent is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end let!(:track) do record.tracks.build(name: "Berlin") end before do band.save end let(:reloaded) do band.reload.records.first end it "executes the callback" do expect(track.before_save_called).to be true end it "persists the change" do expect(reloaded.tracks.first.before_save_called).to be true end end end context "when the child is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.create(name: "Moderat") end let!(:track) do record.tracks.create(name: "Berlin") end before do band.save end let(:reloaded) do band.reload.records.first end it "executes the callback" do expect(track.before_save_called).to be true end it "persists the change" do expect(reloaded.tracks.first.before_save_called).to be true end end end describe "#before_update" do context "when the child is new" do context "when the parent is new" do let(:band) do Band.new(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end let!(:track) do record.tracks.build(name: "Berlin") end before do band.save end it "does not execute the callback" do expect(track.before_update_called).to be false end end context "when the parent is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end let!(:track) do record.tracks.build(name: "Berlin") end before do band.save end it "does not execute the callback" do expect(track.before_update_called).to be false end end end context "when the child is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.create(name: "Moderat") end let!(:track) do record.tracks.create(name: "Berlin") end context "when the child is dirty" do before do track.name = "Rusty Nails" band.save end let(:reloaded) do band.reload.records.first end it "executes the callback" do expect(track.before_update_called).to be true end it "persists the change" do expect(reloaded.tracks.first.before_update_called).to be true end end context "when the child is not dirty" do before do band.save end it "does not execute the callback" do expect(track.before_update_called).to be false end end end end describe "#before_validation" do context "when the child is new" do context "when the parent is new" do let(:band) do Band.new(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end let!(:track) do record.tracks.build(name: "Berlin") end before do band.save end it "executes the callback" do expect(track.before_validation_called).to be true end end context "when the parent is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.build(name: "Moderat") end let!(:track) do record.tracks.build(name: "Berlin") end before do band.save end it "executes the callback" do expect(track.before_validation_called).to be true end end end context "when the child is persisted" do let(:band) do Band.create(name: "Moderat") end let!(:record) do band.records.create(name: "Moderat") end let!(:track) do record.tracks.create(name: "Berlin") end before do band.save end it "executes the callback" do expect(track.before_validation_called).to be true end end end end end context "callback on valid?" do it "goes in all validation callback in good order" do shin = ValidationCallback.new shin.valid? expect(shin.history).to eq([:before_validation, :validate, :after_validation]) end end context "when creating child documents in callbacks" do let(:parent) do ParentDoc.new end before do parent.save end it "does not duplicate the child documents" do parent.children.create(position: 1) expect(ParentDoc.find(parent.id).children.size).to eq(1) end end context "when callbacks cancel persistence" do let(:address) do Address.new(street: "123 Sesame") end before(:all) do Person.before_save do |doc| doc.mode != :prevent_save end end after(:all) do Person.reset_callbacks(:save) end context "when creating a document" do let(:person) do Person.new(mode: :prevent_save, title: "Associate", addresses: [ address ]) end it "fails to save" do expect(person).to be_valid expect(person.save).to be false end it "is a new record" do expect(person).to be_a_new_record expect { person.save }.not_to change { person.new_record? } end it "is left dirty" do expect(person).to be_changed expect { person.save }.not_to change { person.changed? } end it "child documents are left dirty" do expect(address).to be_changed expect { person.save }.not_to change { address.changed? } end end context "when updating a document" do let(:person) do Person.create.tap do |person| person.attributes = { mode: :prevent_save, title: "Associate", addresses: [ address ] } end end it "#save returns false" do expect(person).to be_valid expect(person.save).to be false end it "is a not a new record" do expect(person).to_not be_a_new_record expect { person.save }.not_to change { person.new_record? } end it "is left dirty" do expect(person).to be_changed expect { person.save }.not_to change { person.changed? } end it "child documents are left dirty" do expect(address).to be_changed expect { person.save }.not_to change { address.changed? } end end end context "when loading a model multiple times" do before do load "spec/app/models/callback_test.rb" load "spec/app/models/callback_test.rb" end let(:callback) do CallbackTest.new end context "when saving the document" do it "only executes the callbacks once" do expect(callback).to receive(:execute).once callback.save end end end end
motion_require '../spec_helper' class MockObservable attr_accessor :an_attribute end describe "NSRunloop aware Bacon" do describe "concerning `wait' with a fixed time" do it "allows the user to postpone execution of a block for n seconds, which will halt any further execution of specs" do started_at_1 = started_at_2 = started_at_3 = Time.now #number_of_specs_before = Bacon::Counter[:specifications] wait 0.5 (Time.now - started_at_1).should.be.close(0.5, 0.5) wait 1 do (Time.now - started_at_2).should.be.close(1.5, 0.5) wait 1.5 do (Time.now - started_at_3).should.be.close(3, 0.5) #Bacon::Counter[:specifications].should == number_of_specs_before end end end end describe "concerning `wait' without a fixed time" do def delegateCallbackMethod @delegateCallbackCalled = true resume end def delegateCallbackTookTooLongMethod raise "Oh noes, I must never be called!" end it "allows the user to postpone execution of a block until Context#resume is called, from for instance a delegate callback" do performSelector('delegateCallbackMethod', withObject:nil, afterDelay:0.1) @delegateCallbackCalled.should == nil wait { @delegateCallbackCalled.should == true } end ## This spec adds a failure to the ErrorLog! # it "has a default timeout of 1 second after which the spec will fail and further scheduled calls to the Context are cancelled" do # expect_spec_to_fail! # performSelector('delegateCallbackTookTooLongMethod', withObject:nil, afterDelay:1.2) # wait do # # we must never arrive here, because the default timeout of 1 second will have passed # raise "Oh noes, we shouldn't have arrived in this postponed block!" # end # end ## This spec adds a failure to the ErrorLog! # it "takes an explicit timeout" do # expect_spec_to_fail! # performSelector('delegateCallbackTookTooLongMethod', withObject:nil, afterDelay:0.8) # wait_max 0.3 do # # we must never arrive here, because the default timeout of 1 second will have passed # raise "Oh noes, we shouldn't have arrived in this postponed block!" # end # end end describe "concerning `wait_for_change'" do before { @observable = MockObservable.new } def triggerChange @observable.an_attribute = 'changed' end it "resumes the postponed block once an observed value changes" do value = nil performSelector('triggerChange', withObject:nil, afterDelay:0) wait_for_change @observable, 'an_attribute' do @observable.an_attribute.should == 'changed' end end ## This spec adds a failure to the ErrorLog! # it "has a default timeout of 1 second" do # expect_spec_to_fail! # wait_for_change(@observable, 'an_attribute') do # raise "Oh noes, I must never be called!" # end # performSelector('triggerChange', withObject:nil, afterDelay:1.1) # wait 1.2 do # # we must never arrive here, because the default timeout of 1 second will have passed # raise "Oh noes, we shouldn't have arrived in this postponed block!" # end # end ## This spec adds a failure to the ErrorLog! # it "takes an explicit timeout" do # expect_spec_to_fail! # wait_for_change(@observable, 'an_attribute', 0.3) do # raise "Oh noes, I must never be called!" # end # performSelector('triggerChange', withObject:nil, afterDelay:0.8) # wait 0.9 do # # we must never arrive here, because the default timeout of 1 second will have passed # raise "Oh noes, we shouldn't have arrived in this postponed block!" # end # end end describe "postponing blocks should work from before/after filters as well" do shared "waiting in before/after filters" do it "starts later because of postponed blocks in the before filter" do (Time.now - @started_at).should.be.close(1, 0.5) end # TODO this will never pass when run in concurrent mode, because it gets # executed around the same time as the above spec and take one second as # well. # #it "starts even later because of the postponed blocks in the after filter" do #(Time.now - @started_at).should.be.close(3, 0.5) #end end describe "with `wait'" do describe "and an explicit time" do before do @started_at ||= Time.now wait 0.5 do wait 0.5 do end end end after do wait 0.5 do wait 0.5 do @time ||= 0 @time += 2 (Time.now - @started_at).should.be.close(@time, 0.2) end end end behaves_like "waiting in before/after filters" end describe "and without explicit time" do before do @started_at ||= Time.now performSelector('resume', withObject:nil, afterDelay:0.5) wait do performSelector('resume', withObject:nil, afterDelay:0.5) wait do end end end after do performSelector('resume', withObject:nil, afterDelay:0.5) wait do performSelector('resume', withObject:nil, afterDelay:0.5) wait do @time ||= 0 @time += 2 (Time.now - @started_at).should.be.close(@time, 0.2) end end end behaves_like "waiting in before/after filters" end end describe "with `wait_for_change'" do before do @observable = MockObservable.new @started_at ||= Time.now performSelector('triggerChange', withObject:nil, afterDelay:0.5) wait_for_change @observable, 'an_attribute' do performSelector('triggerChange', withObject:nil, afterDelay:0.5) wait_for_change @observable, 'an_attribute' do end end end after do performSelector('triggerChange', withObject:nil, afterDelay:0.5) wait_for_change @observable, 'an_attribute' do performSelector('triggerChange', withObject:nil, afterDelay:0.5) wait_for_change @observable, 'an_attribute' do @time ||= 0 @time += 2 (Time.now - @started_at).should.be.close(@time, 1) end end end def triggerChange @observable.an_attribute = 'changed' end behaves_like "waiting in before/after filters" end end end # We make no promises about NIBs for the moment # # class WindowController < NSWindowController # attr_accessor :arrayController # attr_accessor :tableView # attr_accessor :textField # end # # describe "Nib helper" do # self.run_on_main_thread = true # # after do # @controller.close # end # # def verify_outlets! # @controller.arrayController.should.be.instance_of NSArrayController # @controller.tableView.should.be.instance_of NSTableView # @controller.textField.should.be.instance_of NSTextField # end # # it "takes a NIB path and instantiates the NIB with the given `owner' object" do # nib_path = File.expand_path("../fixtures/Window.nib", __FILE__) # @controller = WindowController.new # load_nib(nib_path, @controller) # verify_outlets! # end # # it "also returns an array or other top level objects" do # nib_path = File.expand_path("../fixtures/Window.nib", __FILE__) # @controller = WindowController.new # top_level_objects = load_nib(nib_path, @controller).sort_by { |o| o.class.name } # top_level_objects[0].should.be.instance_of NSApplication # top_level_objects[1].should.be.instance_of NSArrayController # top_level_objects[2].should.be.instance_of NSWindow # end # # it "converts a XIB to a tmp NIB before loading it and caches it" do # xib_path = File.expand_path("../fixtures/Window.xib", __FILE__) # @controller = WindowController.new # load_nib(xib_path, @controller) # verify_outlets! # @controller.close # # def self.system(cmd) # raise "Oh noes! Tried to convert again!" # end # # @controller = WindowController.new # load_nib(xib_path, @controller) # verify_outlets! # end # end wait calls require blocks motion_require '../spec_helper' class MockObservable attr_accessor :an_attribute end describe "NSRunloop aware Bacon" do describe "concerning `wait' with a fixed time" do it "allows the user to postpone execution of a block for n seconds, which will halt any further execution of specs" do started_at_1 = started_at_2 = started_at_3 = Time.now #number_of_specs_before = Bacon::Counter[:specifications] wait 0.5 { (Time.now - started_at_1).should.be.close(0.5, 0.5) } wait 1 do (Time.now - started_at_2).should.be.close(1.5, 0.5) wait 1.5 do (Time.now - started_at_3).should.be.close(3, 0.5) #Bacon::Counter[:specifications].should == number_of_specs_before end end end end describe "concerning `wait' without a fixed time" do def delegateCallbackMethod @delegateCallbackCalled = true resume end def delegateCallbackTookTooLongMethod raise "Oh noes, I must never be called!" end it "allows the user to postpone execution of a block until Context#resume is called, from for instance a delegate callback" do performSelector('delegateCallbackMethod', withObject:nil, afterDelay:0.1) @delegateCallbackCalled.should == nil wait { @delegateCallbackCalled.should == true } end ## This spec adds a failure to the ErrorLog! # it "has a default timeout of 1 second after which the spec will fail and further scheduled calls to the Context are cancelled" do # expect_spec_to_fail! # performSelector('delegateCallbackTookTooLongMethod', withObject:nil, afterDelay:1.2) # wait do # # we must never arrive here, because the default timeout of 1 second will have passed # raise "Oh noes, we shouldn't have arrived in this postponed block!" # end # end ## This spec adds a failure to the ErrorLog! # it "takes an explicit timeout" do # expect_spec_to_fail! # performSelector('delegateCallbackTookTooLongMethod', withObject:nil, afterDelay:0.8) # wait_max 0.3 do # # we must never arrive here, because the default timeout of 1 second will have passed # raise "Oh noes, we shouldn't have arrived in this postponed block!" # end # end end describe "concerning `wait_for_change'" do before { @observable = MockObservable.new } def triggerChange @observable.an_attribute = 'changed' end it "resumes the postponed block once an observed value changes" do value = nil performSelector('triggerChange', withObject:nil, afterDelay:0) wait_for_change @observable, 'an_attribute' do @observable.an_attribute.should == 'changed' end end ## This spec adds a failure to the ErrorLog! # it "has a default timeout of 1 second" do # expect_spec_to_fail! # wait_for_change(@observable, 'an_attribute') do # raise "Oh noes, I must never be called!" # end # performSelector('triggerChange', withObject:nil, afterDelay:1.1) # wait 1.2 do # # we must never arrive here, because the default timeout of 1 second will have passed # raise "Oh noes, we shouldn't have arrived in this postponed block!" # end # end ## This spec adds a failure to the ErrorLog! # it "takes an explicit timeout" do # expect_spec_to_fail! # wait_for_change(@observable, 'an_attribute', 0.3) do # raise "Oh noes, I must never be called!" # end # performSelector('triggerChange', withObject:nil, afterDelay:0.8) # wait 0.9 do # # we must never arrive here, because the default timeout of 1 second will have passed # raise "Oh noes, we shouldn't have arrived in this postponed block!" # end # end end describe "postponing blocks should work from before/after filters as well" do shared "waiting in before/after filters" do it "starts later because of postponed blocks in the before filter" do (Time.now - @started_at).should.be.close(1, 0.5) end # TODO this will never pass when run in concurrent mode, because it gets # executed around the same time as the above spec and take one second as # well. # #it "starts even later because of the postponed blocks in the after filter" do #(Time.now - @started_at).should.be.close(3, 0.5) #end end describe "with `wait'" do describe "and an explicit time" do before do @started_at ||= Time.now wait 0.5 do wait 0.5 do end end end after do wait 0.5 do wait 0.5 do @time ||= 0 @time += 2 (Time.now - @started_at).should.be.close(@time, 0.2) end end end behaves_like "waiting in before/after filters" end describe "and without explicit time" do before do @started_at ||= Time.now performSelector('resume', withObject:nil, afterDelay:0.5) wait do performSelector('resume', withObject:nil, afterDelay:0.5) wait do end end end after do performSelector('resume', withObject:nil, afterDelay:0.5) wait do performSelector('resume', withObject:nil, afterDelay:0.5) wait do @time ||= 0 @time += 2 (Time.now - @started_at).should.be.close(@time, 0.2) end end end behaves_like "waiting in before/after filters" end end describe "with `wait_for_change'" do before do @observable = MockObservable.new @started_at ||= Time.now performSelector('triggerChange', withObject:nil, afterDelay:0.5) wait_for_change @observable, 'an_attribute' do performSelector('triggerChange', withObject:nil, afterDelay:0.5) wait_for_change @observable, 'an_attribute' do end end end after do performSelector('triggerChange', withObject:nil, afterDelay:0.5) wait_for_change @observable, 'an_attribute' do performSelector('triggerChange', withObject:nil, afterDelay:0.5) wait_for_change @observable, 'an_attribute' do @time ||= 0 @time += 2 (Time.now - @started_at).should.be.close(@time, 1) end end end def triggerChange @observable.an_attribute = 'changed' end behaves_like "waiting in before/after filters" end end end # We make no promises about NIBs for the moment # # class WindowController < NSWindowController # attr_accessor :arrayController # attr_accessor :tableView # attr_accessor :textField # end # # describe "Nib helper" do # self.run_on_main_thread = true # # after do # @controller.close # end # # def verify_outlets! # @controller.arrayController.should.be.instance_of NSArrayController # @controller.tableView.should.be.instance_of NSTableView # @controller.textField.should.be.instance_of NSTextField # end # # it "takes a NIB path and instantiates the NIB with the given `owner' object" do # nib_path = File.expand_path("../fixtures/Window.nib", __FILE__) # @controller = WindowController.new # load_nib(nib_path, @controller) # verify_outlets! # end # # it "also returns an array or other top level objects" do # nib_path = File.expand_path("../fixtures/Window.nib", __FILE__) # @controller = WindowController.new # top_level_objects = load_nib(nib_path, @controller).sort_by { |o| o.class.name } # top_level_objects[0].should.be.instance_of NSApplication # top_level_objects[1].should.be.instance_of NSArrayController # top_level_objects[2].should.be.instance_of NSWindow # end # # it "converts a XIB to a tmp NIB before loading it and caches it" do # xib_path = File.expand_path("../fixtures/Window.xib", __FILE__) # @controller = WindowController.new # load_nib(xib_path, @controller) # verify_outlets! # @controller.close # # def self.system(cmd) # raise "Oh noes! Tried to convert again!" # end # # @controller = WindowController.new # load_nib(xib_path, @controller) # verify_outlets! # end # end
# encoding: utf-8 require 'spec_helper' describe OrchestrateIo::Search do let(:client){ OrchestrateIo::Client.new(apikey: 'abc') } describe "GET /:version/:collection" do it "returns a list of collection" do request_query = 'Genre:crime' request = client.search :get do collection "films" query request_query end response = request.perform expect(response.code).to eql 200 body = load_json(response.body)["results"].first["value"] expect(body["Genre"]).to eql "Crime, Drama" end it "raises ArgumentError if the query string is missing" do request = client.search(:get){ collection "films" } expect{ request.perform }.to raise_error(ArgumentError) end end end Get rid of ArgumenttError and :snake: # encoding: utf-8 require 'spec_helper' describe OrchestrateIo::Search do let(:client){ OrchestrateIo::Client.new(api_key: 'abc') } describe "GET /:version/:collection" do it "returns a list of collection" do request_query = 'Genre:crime' request = client.search :get do collection "films" query request_query end response = request.perform expect(response.code).to eql 200 body = load_json(response.body)["results"].first["value"] expect(body["Genre"]).to eql "Crime, Drama" end end end
require "spec_helper" # rubocop:disable Style/SpaceInsideBrackets,Style/MultilineArrayBraceLayout # rubocop:disable Style/MultilineMethodCallIndentation,Style/RedundantParentheses # rubocop:disable Style/ClosingParenthesisIndentation describe PuppetDBQuery::Parser do PARSER_DATA = [ [ 'hostname=\'puppetdb-mike-217922\'', [PuppetDBQuery::Term.new(PuppetDBQuery::Parser::EQUAL).add(:hostname, "puppetdb-mike-217922")] ], [ 'disable_puppet = true', [PuppetDBQuery::Term.new(PuppetDBQuery::Parser::EQUAL).add(:disable_puppet, :true)] ], [ 'fqdn~"app-dev" and group=develop and vertical~tracking and cluster_color~BLUE', [PuppetDBQuery::Term.new(PuppetDBQuery::Parser::AND) .add(PuppetDBQuery::Term.new(PuppetDBQuery::Parser::MATCH).add(:fqdn, "app-dev")) .add(PuppetDBQuery::Term.new(PuppetDBQuery::Parser::EQUAL).add(:group, :develop)) .add(PuppetDBQuery::Term.new(PuppetDBQuery::Parser::MATCH).add(:vertical, :tracking)) .add(PuppetDBQuery::Term.new(PuppetDBQuery::Parser::MATCH).add(:cluster_color, :BLUE)) ] ], [ 'a~"A" and g=G or v~t and c~B', [PuppetDBQuery::Term.new(PuppetDBQuery::Parser::OR) .add((PuppetDBQuery::Term.new(PuppetDBQuery::Parser::AND) .add(PuppetDBQuery::Term.new(PuppetDBQuery::Parser::MATCH).add(:a, "A")) .add(PuppetDBQuery::Term.new(PuppetDBQuery::Parser::EQUAL).add(:g, :G)) )).add((PuppetDBQuery::Term.new(PuppetDBQuery::Parser::AND) .add(PuppetDBQuery::Term.new(PuppetDBQuery::Parser::MATCH).add(:v, :t)) .add(PuppetDBQuery::Term.new(PuppetDBQuery::Parser::MATCH).add(:c, :B)) )) ] ], ].freeze PARSER_DATA.each do |q, a| it "translates correctly #{q.inspect}" do expect(subject.parse(q)).to eq(a) end end end fix rubocop again require "spec_helper" # rubocop:disable Style/SpaceInsideBrackets,Style/MultilineArrayBraceLayout # rubocop:disable Style/MultilineMethodCallIndentation,Style/RedundantParentheses # rubocop:disable Style/ClosingParenthesisIndentation describe PuppetDBQuery::Parser do PARSER_DATA = [ [ 'hostname=\'puppetdb-mike-217922\'', [PuppetDBQuery::Term.new(PuppetDBQuery::Parser::EQUAL).add(:hostname, "puppetdb-mike-217922")] ], [ 'disable_puppet = true', [PuppetDBQuery::Term.new(PuppetDBQuery::Parser::EQUAL).add(:disable_puppet, :true)] ], [ 'fqdn~"app-dev" and group=develop and vertical~tracking and cluster_color~BLUE', [PuppetDBQuery::Term.new(PuppetDBQuery::Parser::AND) .add(PuppetDBQuery::Term.new(PuppetDBQuery::Parser::MATCH).add(:fqdn, "app-dev")) .add(PuppetDBQuery::Term.new(PuppetDBQuery::Parser::EQUAL).add(:group, :develop)) .add(PuppetDBQuery::Term.new(PuppetDBQuery::Parser::MATCH).add(:vertical, :tracking)) .add(PuppetDBQuery::Term.new(PuppetDBQuery::Parser::MATCH).add(:cluster_color, :BLUE)) ] ], [ 'a~"A" and g=G or v~t and c~B', [PuppetDBQuery::Term.new(PuppetDBQuery::Parser::OR) .add((PuppetDBQuery::Term.new(PuppetDBQuery::Parser::AND) .add(PuppetDBQuery::Term.new(PuppetDBQuery::Parser::MATCH).add(:a, "A")) .add(PuppetDBQuery::Term.new(PuppetDBQuery::Parser::EQUAL).add(:g, :G)) )).add((PuppetDBQuery::Term.new(PuppetDBQuery::Parser::AND) .add(PuppetDBQuery::Term.new(PuppetDBQuery::Parser::MATCH).add(:v, :t)) .add(PuppetDBQuery::Term.new(PuppetDBQuery::Parser::MATCH).add(:c, :B)) )) ] ], ].freeze PARSER_DATA.each do |q, a| it "translates correctly #{q.inspect}" do expect(subject.parse(q)).to eq(a) end end end
First cut at tests for new SSE job feed # -*- indent-level: 4;indent-tabs-mode: nil; fill-column: 92 -*- # # Author:: Steven Grady (<steven.grady@erlang-solutions.com>) # @copyright Copyright 2014 Chef Software, Inc. All Rights Reserved. # # This file is provided to you under the Apache License, # Version 2.0 (the "License"); you may not use this file # except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # require 'httpclient' require 'pushy/spec_helper' require 'time' def d(s) p "#{Time.now}: #{s}" end describe "sse-test" do #describe "sse-test", :focus=>true do include_context "end_to_end_util" # to start clients SUMMARY_WAIT_TIME = 5 JOB_WAITING_AROUND_TIME = 60 let(:command) { 'sleep 1' } let(:quorum) { 1 } let(:run_timeout) { 2 } def job_to_run # use "def", because "let" caches, and we want to always get the latest version { 'command' => command, 'nodes' => nodes, 'run_timeout' => run_timeout } end after :each do if @clients @clients.each do |client_name, client| stop_client(client_name) if @clients[client_name][:client] end @clients = nil end end let(:feed_path) { "/pushy/job_status_feed"} def get_feed(id, &block) # SLG - things included via chef-pedant/lib/pedant/rspec/common.rb # SLG - "get" defined in chef-pedant/lib/pedant/request.rb # SLG - "api_url" defined in oc-chef-pedant/lib/pedant/multitenant/platform.rb # SLG = admin_user defined in rspec/common.rb feed_url = api_url("#{feed_path}/#{id}") headers = {'Accept' => 'text/event-stream'} get(feed_url, admin_user, :headers => headers, &block) end def uri_from_id(id) api_url("/pushy/jobs/#{id}") end def start_new_job(job) uri = post(api_url("/pushy/jobs"), admin_user, :payload => job) do |response| list = JSON.parse(response.body) list["uri"] end job_info_js = get(uri, admin_user) job_info = JSON.parse(job_info_js) job_info['id'] end # Modified from end_to_end_util:wait_for_job_status def wait_for_job_done(uri, options = {}) job = nil begin Timeout::timeout(options[:timeout] || JOB_STATUS_TIMEOUT_DEFAULT) do begin sleep(SLEEP_TIME) if job job = get_job(uri) end until ['complete', 'timed_out', 'quorum_failed'].include?(job['status']) end rescue Timeout::Error raise "Job never got a status -- actual job reported as #{job}" end job end def do_complete_job(job, options = {}) @id = start_new_job(job) wait_for_job_done(uri_from_id(@id), options) @id end def start_event_stream feed_url = api_url("#{feed_path}/#{@id}") feed_url.sub!("https://api.opscode.piab", "http://api.opscode.piab:10003") host = URI.parse(feed_url).host @evs = [] c = HTTPClient.new # Certificate is self-signing -- if we don't disable certificate verification, this won't work c.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_NONE @piper, @pipew = IO.pipe auth_headers = admin_user.signing_headers(:GET, feed_url, "") require 'chef/version' headers = { 'Accept' => 'text/event-stream', 'User-Agent' => 'chef-pedant rspec tests', 'X-Chef-Version' => Chef::VERSION, 'Host' => host } headers = headers.merge(auth_headers) @ep = EventParser.new Thread.new { conn = c.get_async(feed_url, :header => headers) resp = conn.pop content_io = resp.content while ! conn.finished? str = content_io.readpartial(4096) if str @pipew.write(str) end end @pipew.close } end def get_streaming_events evstr = @piper.readpartial(65536) @ep.feed(evstr) @evs += @ep.events_so_far @evs end def check_node(e, node) jnode = e.json['node'] if (node != :any) jnode.should == node end jnode end def expect_start(e, command, run_timeout, quorum, username) e.name.should == :start e.json['command'].should == command e.json['run_timeout'].should == run_timeout e.json['quorum'].should == quorum e.json['user'].should == username end def expect_quorum_vote(e, node, status) e.name.should == :quorum_vote e.json['status'].should == status check_node(e, node) end def expect_quorum_succeeded(e) e.name.should == :quorum_succeeded end def expect_run_start(e, node) e.name.should == :run_start check_node(e, node) end def expect_run_complete(e, node, status) e.name.should == :run_complete e.json['status'].should == status check_node(e, node) end def expect_job_complete(e, status) e.name.should == :job_complete e.json['status'].should == status end def expect_summary(e, command, status, run_timeout, succeeded, failed) e.name.should == :summary e.json['command'].should == command e.json['status'].should == status e.json['run_timeout'].should == run_timeout created_at = Time.parse(e.json['created_at']) updated_at = Time.parse(e.json['updated_at']) updated_at.should >= created_at e.json['nodes']['succeeded'].should == succeeded e.json['nodes']['failed'].should == failed end # Adapted from github.com/conjurinc/sse-client-ruby -- should really just use that package; # but based on code inspection, it will miss the last event if it doesn't end with a "\n\n". # I suspect it was assuming an infinite stream. class Event < Struct.new(:data, :name, :id, :json); end class EventParser def initialize @buffer = '' @events = [] end attr_reader :events def feed(chunk, final = false) @buffer << chunk process_events(final) end def process_events(final) while i = @buffer.index("\n\n") process_event(@buffer.slice!(0..i)) end if final process_event(@buffer) end end def process_event(evstr) data, id, name = [], nil, nil evstr.lines.map(&:chomp).each do |l| field, value = case l when /^:/ then next # comment, do nothing when /^(.*?):(.*)$/ then [$1, $2] else [l, ''] # this is what the spec says, I swear! end # spec allows one optional space after the colon value = value[1..-1] if value.start_with? ' ' case field when 'data' then data << value when 'id' then id = value when 'event' then name = value.to_sym when 'retry' then @retry = value.to_i end end @last_event_id = id @events << Event.new(data.join("\n"), name, id) end def events_so_far evs = @events @events = [] evs end end def parse_stream(s) ep = EventParser.new() ep.feed(s, true) ep.events end # Validate standard events; as a side-effect, save the parsed json field def validate_events(numEvents, evs) d evs evs.length.should == numEvents # All ids are unique evs.map(&:id).uniq.length.should == evs.length # All events have (parsable) json for data evs.each do |e| e.json = JSON.parse(e.data) end require 'pp' pp evs # All events have (parsable) timestamps ts = evs.map {|e| Time.parse(e.json['timestamp'])} # All timestamps are unique ts.uniq.length.should == ts.length # All timestamps are in increasing order ts.sort.should == ts # All timestamps are in (roughly) increasing order -- since pushy-server # is multi-threaded, there may be some events showing up before others, # but that's okay as long as delta is very small. #ts.each_index do |i| #next if i == 0 ## Check that time is forward, or no more than 1ms backward #(ts[i] - ts[i-1]).should > -0.001 #end end def expect_valid_response(numEvents, response) response.should look_like({ :status => 200 }) evs = parse_stream(response.body) validate_events(numEvents, evs) evs end context 'with no job,' do it "should respond to a non-existent job with a 404" do get_feed('nonexistent') do |response| response.should look_like({ :status => 404 }) end end it "should respond to a POST with a 405" do post(api_url("#{feed_path}/nonexistent"), admin_user) do |response| response.should look_like({ :status => 405 }) end end it 'should respond to an invalid user with a 401' do get(api_url("#{feed_path}/nonexistent"), invalid_user) do |response| response.should look_like({ :status => 401 }) end end end context 'with a job with one nonexistent node,' do let(:node) { 'nonexistent' } let(:nodes) { [node] } before :each do do_complete_job(job_to_run) end it "the events should be: start,quorum_vote(down),job_complete(quorum_failed)" do get_feed(@id) do |response| evs = expect_valid_response(3, response) expect_start(evs[0], command, run_timeout, quorum, admin_user.name) expect_quorum_vote(evs[1], node, 'down') expect_job_complete(evs[2], "quorum_failed") end end end context 'with a job with one node,' do let(:node) { 'DONKEY' } let(:nodes) { [node] } context "when the command succeeds" do before :each do start_new_clients(node) do_complete_job(job_to_run) end it "the events should be: start,quorum_vote(success),quorum_succeeded,run_start,run_complete(success),job_complete(complete)" do get_feed(@id) do |response| evs = expect_valid_response(6, response) expect_start(evs[0], command, run_timeout, quorum, admin_user.name) expect_quorum_vote(evs[1], node, 'success') expect_quorum_succeeded(evs[2]) expect_run_start(evs[3], node) expect_run_complete(evs[4], node, 'success') expect_job_complete(evs[5], "complete") end end end context "when the command fails" do let(:command) { 'this_oughta_fail' } before :each do start_new_clients(node) do_complete_job(job_to_run) end it "the events should be: start,quorum_vote(success),quorum_succeeded,run_start,run_complete(failure),job_complete(complete)" do get_feed(@id) do |response| evs = expect_valid_response(6, response) expect_start(evs[0], command, run_timeout, quorum, admin_user.name) expect_quorum_vote(evs[1], node, 'success') expect_quorum_succeeded(evs[2]) expect_run_start(evs[3], node) expect_run_complete(evs[4], node, 'failure') expect_job_complete(evs[5], "complete") end end end context "when the node nacks the quorum" do let(:command) { 'bad command' } before :each do start_new_clients(node) do_complete_job(job_to_run) end it "the events should be: start,quorum_vote(failure),job_complete(quorum_failed)" do get_feed(@id) do |response| evs = expect_valid_response(3, response) expect_start(evs[0], command, run_timeout, quorum, admin_user.name) expect_quorum_vote(evs[1], node, 'failure') expect_job_complete(evs[2], "quorum_failed") end end end # XX This test takes a minute or so to run. We need a way of telling the server to time # out more quickly. context "when the node ignores the quorum", :slow => true do before :each do class PushyClient alias old_commit commit def commit(job_id, command); nil; end end start_new_clients(node) do_complete_job(job_to_run, {:timeout => JOB_WAITING_AROUND_TIME+1}) end after :each do class PushyClient alias commit old_commit end end # It would be nice if pushy-server sent something different here, maybe "commit_timeout" or something it "the events should be: start,quorum_vote(voting_timeout),job_complete(quorum_failed)" do get_feed(@id) do |response| evs = expect_valid_response(3, response) expect_start(evs[0], command, run_timeout, quorum, admin_user.name) expect_quorum_vote(evs[1], node, 'voting_timeout') expect_job_complete(evs[2], "quorum_failed") end end end context "when the command nacks the run" do before :each do class PushyClient alias old_run run def run(job_id) self.send_command(:nack_run, job_id) end end start_new_clients(node) do_complete_job(job_to_run) end after :each do class PushyClient alias run old_run end end it "the events should be: start,quorum_vote(success),quorum_succeeded,run_complete(run_nacked),job_complete(complete)" do get_feed(@id) do |response| evs = expect_valid_response(5, response) expect_start(evs[0], command, run_timeout, quorum, admin_user.name) expect_quorum_vote(evs[1], node, 'success') expect_quorum_succeeded(evs[2]) expect_run_complete(evs[3], node, 'run_nacked') expect_job_complete(evs[4], "complete") end end end context "when the command times out" do before :each do class PushyClient alias old_run run def run(job_id); nil; end end start_new_clients(node) do_complete_job(job_to_run) end after :each do class PushyClient alias run old_run end end it "the events should be: start,quorum_vote(success),quorum_succeeded,job_complete(timed_out)" do get_feed(@id) do |response| evs = expect_valid_response(4, response) expect_start(evs[0], command, run_timeout, quorum, admin_user.name) expect_quorum_vote(evs[1], node, 'success') expect_quorum_succeeded(evs[2]) expect_job_complete(evs[3], "timed_out") end end end end context 'with a job with two nodes,' do let(:quorum) { 2 } let(:nodes) { ['DONKEY', 'FIONA'] } context "when the command succeeds on both" do before :each do start_new_clients(*nodes) do_complete_job(job_to_run) end it "the events should be: start,quorum_vote(A,success),quorum_vote(B,success),quorum_succeeded,run_start(A),run_start(B),run_complete(A,success),run_complete(B,success),job_complete(complete)" do get_feed(@id) do |response| evs = expect_valid_response(9, response) expect_start(evs[0], command, run_timeout, quorum, admin_user.name) n1 = expect_quorum_vote(evs[1], :any, 'success') n2 = expect_quorum_vote(evs[2], :any, 'success') [n1, n2].sort.should == nodes.sort expect_quorum_succeeded(evs[3]) n1 = expect_run_start(evs[4], :any) n2 = expect_run_start(evs[5], :any) [n1, n2].sort.should == nodes.sort n1 = expect_run_complete(evs[6], :any, 'success') n2 = expect_run_complete(evs[7], :any, 'success') [n1, n2].sort.should == nodes.sort expect_job_complete(evs[8], "complete") end end end context "when the command fails on both" do let(:command) { 'this_oughta_fail' } before :each do start_new_clients(*nodes) do_complete_job(job_to_run) end it "the events should be: start,quorum_vote(A,success),quorum_vote(B,success),quorum_succeeded,run_start(A),run_start(B),run_complete(A,failure),run_complete(B,failure),job_complete(complete)" do get_feed(@id) do |response| evs = expect_valid_response(9, response) expect_start(evs[0], command, run_timeout, quorum, admin_user.name) n1 = expect_quorum_vote(evs[1], :any, 'success') n2 = expect_quorum_vote(evs[2], :any, 'success') [n1, n2].sort.should == nodes.sort expect_quorum_succeeded(evs[3]) n1 = expect_run_start(evs[4], :any) n2 = expect_run_start(evs[5], :any) [n1, n2].sort.should == nodes.sort n1 = expect_run_complete(evs[6], :any, 'failure') n2 = expect_run_complete(evs[7], :any, 'failure') [n1, n2].sort.should == nodes.sort expect_job_complete(evs[8], "complete") end end end context "when the command fails on one" do before :each do start_new_clients(*nodes) # Do some ugly object hacking to get the clients to behave differently donkey = @clients['DONKEY'][:client] jr = donkey.instance_variable_get('@job_runner') class <<jr alias real_run run def run(job_id) @command = 'this_oughta_fail' real_run(job_id) end end do_complete_job(job_to_run) end it "the events should be: start,quorum_vote(A,success),quorum_vote(B,success),quorum_succeeded,run_start(A),run_start(B),run_complete(A,failure),run_complete(B,success),job_complete(complete)" do get_feed(@id) do |response| evs = expect_valid_response(9, response) expect_start(evs[0], command, run_timeout, quorum, admin_user.name) n1 = expect_quorum_vote(evs[1], :any, 'success') n2 = expect_quorum_vote(evs[2], :any, 'success') [n1, n2].sort.should == nodes.sort expect_quorum_succeeded(evs[3]) n1 = expect_run_start(evs[4], :any) n2 = expect_run_start(evs[5], :any) [n1, n2].sort.should == nodes.sort if (evs[6].json['node'] == 'DONKEY') then de, fe = evs[6], evs[7] else fe, de = evs[6], evs[7] end expect_run_complete(de, 'DONKEY', 'failure') expect_run_complete(fe, 'FIONA', 'success') expect_job_complete(evs[8], "complete") end end end context "when the one rejects the quorum," do before :each do start_new_clients(*nodes) # Do some ugly object hacking to get the clients to behave differently donkey = @clients['DONKEY'][:client] jr = donkey.instance_variable_get('@job_runner') class <<jr def commit(job_id, command) client.send_command(:nack_commit, job_id) return false end end job = job_to_run.merge({'quorum' => quorum}) do_complete_job(job) end context "when the quorum is 100%" do it "the events should be: start,quorum_vote(A,success),quorum_vote(B,failure),job_complete(quorum_failed)" do get_feed(@id) do |response| evs = expect_valid_response(4, response) expect_start(evs[0], command, run_timeout, quorum, admin_user.name) if (evs[1].json['node'] == 'DONKEY') then de, fe = evs[1], evs[2] else fe, de = evs[1], evs[2] end expect_quorum_vote(de, 'DONKEY', 'failure') expect_quorum_vote(fe, 'FIONA', 'success') expect_job_complete(evs[3], "quorum_failed") end end end context "when the quorum is 50%" do let(:quorum) { 1 } it "the events should be: start,quorum_vote(A,success),quorum_vote(B,failure),quorum_succeeded,run_complete(A,success),job_complete(success)" do get_feed(@id) do |response| evs = expect_valid_response(7, response) expect_start(evs[0], command, run_timeout, quorum, admin_user.name) if (evs[1].json['node'] == 'DONKEY') then de, fe = evs[1], evs[2] else fe, de = evs[1], evs[2] end expect_quorum_vote(de, 'DONKEY', 'failure') expect_quorum_vote(fe, 'FIONA', 'success') expect_quorum_succeeded(evs[3]) expect_run_start(evs[4], 'FIONA') expect_run_complete(evs[5], 'FIONA', 'success') expect_job_complete(evs[6], "complete") end end end end end context "with a job that has been complete for a while," do let(:nodes) { ['DONKEY'] } before :each do start_new_clients(*nodes) do_complete_job(job_to_run) sleep(SUMMARY_WAIT_TIME + 1) end it "the response to a feed request should just be the summary of the job" do get_feed(@id) do |response| evs = expect_valid_response(1, response) expect_summary(evs[0], command, 'complete', run_timeout, ['DONKEY'], nil) end end end context 'with a job with with a non-ASCII name,' do let(:command) { "echo '\u0110ONKEY'"} let(:node) { 'DONKEY' } let(:nodes) { [node] } before :each do start_new_clients(node) donkey = @clients['DONKEY'][:client] donkey.instance_variable_get('@whitelist').instance_variable_set('@whitelist', {command => command}) do_complete_job(job_to_run) end it "the events should be cleanly encoded" do get_feed(@id) do |response| evs = expect_valid_response(6, response) expect_start(evs[0], command, run_timeout, quorum, admin_user.name) expect_quorum_vote(evs[1], node, 'success') expect_quorum_succeeded(evs[2]) expect_run_start(evs[3], node) expect_run_complete(evs[4], node, 'success') expect_job_complete(evs[5], "complete") end end end context "with when reading an event stream,", :focus=>true do let(:node) { 'DONKEY' } let(:command) { 'sleep 5' } let(:run_timeout) { 10 } let(:nodes) { [node] } before :each do start_new_clients(node) @id = start_new_job(job_to_run) start_event_stream end it "the events become available as they happen" do evs = get_streaming_events validate_events(4, evs) expect_start(evs[0], command, run_timeout, quorum, admin_user.name) expect_quorum_vote(evs[1], node, 'success') expect_quorum_succeeded(evs[2]) expect_run_start(evs[3], node) sleep 5 evs = get_streaming_events validate_events(6, evs) expect_run_start(evs[3], node) expect_run_complete(evs[4], node, 'success') expect_job_complete(evs[5], "complete") end end end
require 'rails_helper' RSpec.describe 'marks#create', type: :request do let!(:goal) { create(:goal) } let!(:env) { nil } let!(:params) { attributes_for(:mark) } let!(:method) { :post } let!(:path) { goal_marks_path(goal) } before { send(method, path, params, env) } subject { response } its(:status) { is_expected.to be 201 } its(:body) do is_expected.to match_json_expression( id: Numeric, goal_id: goal.id, date: params[:date].iso8601, value: params[:value] ) end end fix marks#create spec require 'rails_helper' RSpec.describe 'marks#create', type: :request do let!(:goal) { create(:goal) } let!(:params) { attributes_for(:mark) } let!(:method) { :post } let!(:path) { goal_marks_path(goal) } context 'without authorization header' do let!(:env) { nil } before { send(method, path, params, env) } subject { response } its(:status) { is_expected.to be 401 } its(:body) { is_expected.to match_json_expression(status: 'error') } end context 'with authorization header' do let!(:env) { authorization_headers } before { send(method, path, params, env) } subject { response } its(:status) { is_expected.to be 201 } its(:body) do is_expected.to match_json_expression( id: Numeric, goal_id: goal.id, date: params[:date].iso8601, value: params[:value] ) end end end
describe :file_identical, :shared => true do before :each do @file1 = tmp('file_identical.txt') @file2 = tmp('file_identical2.txt') @link = tmp('file_identical.lnk') touch(@file1) { |f| f.puts "file1" } touch(@file2) { |f| f.puts "file2" } rm_r @link File.link(@file1, @link) end after :each do rm_r @link, @file1, @file2 end it "returns true for a file and its link" do @object.send(@method, @file1, @link).should == true end ruby_version_is "1.9" do it "accepts an object that has a #to_path method" do @object.send(@method, mock_to_path(@file1), mock_to_path(@link)).should == true end end it "raises an ArgumentError if not passed two arguments" do lambda { @object.send(@method, @file1, @file2, @link) }.should raise_error(ArgumentError) lambda { @object.send(@method, @file1) }.should raise_error(ArgumentError) end it "raises a TypeError if not passed String types" do lambda { @object.send(@method, 1,1) }.should raise_error(TypeError) end it "returns true if both named files are identical" do @object.send(@method, @file1, @file1).should be_true @object.send(@method, @link, @link).should be_true @object.send(@method, @file1, @file2).should be_false end end Updated File.identical? spec describe :file_identical, :shared => true do before :each do @file1 = tmp('file_identical.txt') @file2 = tmp('file_identical2.txt') @link = tmp('file_identical.lnk') @non_exist = 'non_exist' touch(@file1) { |f| f.puts "file1" } touch(@file2) { |f| f.puts "file2" } rm_r @link File.link(@file1, @link) end after :each do rm_r @link, @file1, @file2 end it "returns true for a file and its link" do @object.send(@method, @file1, @link).should == true end it "returns false if any of the files doesn't exist" do @object.send(@method, @file1, @non_exist).should be_false @object.send(@method, @non_exist, @file1).should be_false @object.send(@method, @non_exist, @non_exist).should be_false end ruby_version_is "1.9" do it "accepts an object that has a #to_path method" do @object.send(@method, mock_to_path(@file1), mock_to_path(@link)).should == true end end it "raises an ArgumentError if not passed two arguments" do lambda { @object.send(@method, @file1, @file2, @link) }.should raise_error(ArgumentError) lambda { @object.send(@method, @file1) }.should raise_error(ArgumentError) end it "raises a TypeError if not passed String types" do lambda { @object.send(@method, 1,1) }.should raise_error(TypeError) end it "returns true if both named files are identical" do @object.send(@method, @file1, @file1).should be_true @object.send(@method, @link, @link).should be_true @object.send(@method, @file1, @file2).should be_false end end
require 'rails_helper' RSpec.describe RateChecker do describe '#user_has_already_rated?' do subject { described_class.new(submission, user.id).user_has_already_rated? } context 'when the submmission has already been rated by the user' do let!(:submission) { FactoryGirl.create(:submission) } let!(:user) { FactoryGirl.create(:user) } it do submission.rates << Rate.new(user_id: user.id) expect(subject).to equal(true) end end context 'when the submmission has not been rated by the user yet' do let!(:submission) { FactoryGirl.create(:submission) } let!(:user) { FactoryGirl.create(:user) } let!(:user1) { FactoryGirl.create(:user) } it do submission.rates << Rate.new(user_id: user1.id) expect(subject).to equal(false) end end end end Remove obsolete spec
require 'spec_helper' require 'sisimai' require 'json' thatsonhold = './set-of-emails/to-be-debugged-because/reason-is-onhold' describe Sisimai do describe '.make' do mail = Sisimai.make(thatsonhold) subject { mail } it('is Array') { is_expected.to be_a Array } it('have data') { expect(mail.size).to be > 0 } mail.each do |ee| it 'contains Sisimai::Data' do expect(ee).to be_a Sisimai::Data end describe 'each accessor of Sisimai::Data' do example '#timestamp is Sisimai::Time' do expect(ee.timestamp).to be_a Sisimai::Time end example '#addresser is Sisimai::Address' do expect(ee.addresser).to be_a Sisimai::Address end example '#recipient is Sisimai::Address' do expect(ee.recipient).to be_a Sisimai::Address end example '#addresser#address returns String' do expect(ee.addresser.address).to be_a String expect(ee.addresser.address.size).to be > 0 end example '#recipient#address returns String' do expect(ee.recipient.address).to be_a String expect(ee.recipient.address.size).to be > 0 end example '#reason is "onhold"' do expect(ee.reason).to be_a String expect(ee.reason).to be == 'onhold' end example '#replycode returns String' do expect(ee.replycode).to be_a String end end describe 'each instance method of Sisimai::Data' do describe '#damn' do damn = ee.damn example '#damn returns Hash' do expect(damn).to be_a Hash expect(damn.each_key.size).to be > 0 end describe 'damned data' do example '["addresser"] is #addresser#address' do expect(damn['addresser']).to be == ee.addresser.address end example '["recipient"] is #recipient#address' do expect(damn['recipient']).to be == ee.recipient.address end damn.each_key do |eee| next if ee.send(eee).class.to_s =~ /\ASisimai::/ next if eee == 'subject' if eee == 'catch' example "['#{eee}'] is ''" do expect(damn[eee]).to be_empty end else example "['#{eee}'] is ##{eee}" do expect(damn[eee]).to be == ee.send(eee) end end end end end describe '#dump' do dump = ee.dump('json') example '#dump returns String' do expect(dump).to be_a String expect(dump.size).to be > 0 end end end end end describe '.dump' do jsonstring = Sisimai.dump(thatsonhold) it('returns String') { expect(jsonstring).to be_a String } it('is not empty') { expect(jsonstring.size).to be > 0 } end end Import changes from https://github.com/sisimai/p5-Sisimai/commit/fca58ed13cfb23cca7b2231cb5f78932edbb6664 require 'spec_helper' require 'sisimai' require 'json' require 'sisimai/reason/onhold' thatsonhold = './set-of-emails/to-be-debugged-because/reason-is-onhold' describe Sisimai do describe '.make' do mail = Sisimai.make(thatsonhold) subject { mail } it('is Array') { is_expected.to be_a Array } it('have data') { expect(mail.size).to be > 0 } mail.each do |ee| it 'contains Sisimai::Data' do expect(ee).to be_a Sisimai::Data end describe 'each accessor of Sisimai::Data' do example '#timestamp is Sisimai::Time' do expect(ee.timestamp).to be_a Sisimai::Time end example '#addresser is Sisimai::Address' do expect(ee.addresser).to be_a Sisimai::Address end example '#recipient is Sisimai::Address' do expect(ee.recipient).to be_a Sisimai::Address end example '#addresser#address returns String' do expect(ee.addresser.address).to be_a String expect(ee.addresser.address.size).to be > 0 end example '#recipient#address returns String' do expect(ee.recipient.address).to be_a String expect(ee.recipient.address.size).to be > 0 end example '#reason is "onhold"' do expect(ee.reason).to be_a String expect(ee.reason).to be == 'onhold' end example '#replycode returns String' do expect(ee.replycode).to be_a String end example 'Sisimai::Reason::OnHold.true returns true' do expect(Sisimai::Reason::OnHold.true(ee)).to be true end end describe 'each instance method of Sisimai::Data' do describe '#damn' do damn = ee.damn example '#damn returns Hash' do expect(damn).to be_a Hash expect(damn.each_key.size).to be > 0 end describe 'damned data' do example '["addresser"] is #addresser#address' do expect(damn['addresser']).to be == ee.addresser.address end example '["recipient"] is #recipient#address' do expect(damn['recipient']).to be == ee.recipient.address end damn.each_key do |eee| next if ee.send(eee).class.to_s =~ /\ASisimai::/ next if eee == 'subject' if eee == 'catch' example "['#{eee}'] is ''" do expect(damn[eee]).to be_empty end else example "['#{eee}'] is ##{eee}" do expect(damn[eee]).to be == ee.send(eee) end end end end end describe '#dump' do dump = ee.dump('json') example '#dump returns String' do expect(dump).to be_a String expect(dump.size).to be > 0 end end end end end describe '.dump' do jsonstring = Sisimai.dump(thatsonhold) it('returns String') { expect(jsonstring).to be_a String } it('is not empty') { expect(jsonstring.size).to be > 0 } end end
require File.dirname(__FILE__) + '/../../spec_helper' require File.dirname(__FILE__) + '/../../ruby_forker' describe "The bin/spec script" do include RubyForker it "should have no warnings" do pending "Hangs on JRuby" if PLATFORM =~ /java/ spec_path = "#{File.dirname(__FILE__)}/../../../bin/spec" output = ruby "-w #{spec_path} --help 2>&1" output.should_not =~ /warning/n end it "should show the help w/ no args" do pending "Hangs on JRuby" if PLATFORM =~ /java/ spec_path = "#{File.dirname(__FILE__)}/../../../bin/spec" output = ruby "-w #{spec_path} 2>&1" output.should =~ /^Usage: spec/ end end Changing references from PLATFORM to RUBY_PLATFORM for Ruby 1.9.1 compatibility require File.dirname(__FILE__) + '/../../spec_helper' require File.dirname(__FILE__) + '/../../ruby_forker' describe "The bin/spec script" do include RubyForker it "should have no warnings" do pending "Hangs on JRuby" if RUBY_PLATFORM =~ /java/ spec_path = "#{File.dirname(__FILE__)}/../../../bin/spec" output = ruby "-w #{spec_path} --help 2>&1" output.should_not =~ /warning/n end it "should show the help w/ no args" do pending "Hangs on JRuby" if RUBY_PLATFORM =~ /java/ spec_path = "#{File.dirname(__FILE__)}/../../../bin/spec" output = ruby "-w #{spec_path} 2>&1" output.should =~ /^Usage: spec/ end end
describe 'Standalone migrations' do def write(file, content) raise "cannot write nil" unless file file = tmp_file(file) folder = File.dirname(file) `mkdir -p #{folder}` unless File.exist?(folder) File.open(file, 'w') { |f| f.write content } end def read(file) File.read(tmp_file(file)) end def migration(name) m = `cd spec/tmp/db/migrations && ls`.split("\n").detect { |m| m =~ name } m ? "db/migrations/#{m}" : m end def tmp_file(file) "spec/tmp/#{file}" end def run(cmd) `cd spec/tmp && #{cmd} 2>&1 && echo SUCCESS` end def run_with_output(cmd) `cd spec/tmp && #{cmd} 2>&1` end def make_migration(name) migration = run("rake db:new_migration name=#{name}").match(%r{db/migrations/\d+.*.rb})[0] content = read(migration) content.sub!(/def self.down.*?\send/m, "def self.down;puts 'DOWN-#{name}';end") content.sub!(/def self.up.*?\send/m, "def self.up;puts 'UP-#{name}';end") write(migration, content) migration.match(/\d{14}/)[0] end def write_rakefile(config=nil) write 'Rakefile', <<-TXT $LOAD_PATH.unshift '#{File.expand_path('lib')}' begin require 'tasks/standalone_migrations' MigratorTasks.new do |t| t.log_level = Logger::INFO #{config} end rescue LoadError => e puts "gem install standalone_migrations to get db:migrate:* tasks! (Error: \#{e})" end TXT end def write_multiple_migrations write_rakefile %{t.migrations = "db/migrations", "db/migrations2"} write "db/migrations/20100509095815_create_tests.rb", <<-TXT class CreateTests < ActiveRecord::Migration def self.up puts "UP-CreateTests" end def self.down puts "DOWN-CreateTests" end end TXT write "db/migrations2/20100509095816_create_tests2.rb", <<-TXT class CreateTests2 < ActiveRecord::Migration def self.up puts "UP-CreateTests2" end def self.down puts "DOWN-CreateTests2" end end TXT end before do `rm -rf spec/tmp` if File.exist?('spec/tmp') `mkdir spec/tmp` write_rakefile write 'db/config.yml', <<-TXT development: adapter: sqlite3 database: db/development.sql test: adapter: sqlite3 database: db/test.sql TXT end describe 'db:create and drop' do it "should create the database and drop the database that was created" do run_with_output("rake db:create").should match /spec\/tmp\)$/ run_with_output("rake db:drop").should match /spec\/tmp\)$/ end end describe 'db:new_migration' do context "single migration path" do it "fails if i do not add a name" do run("rake db:new_migration").should_not =~ /SUCCESS/ end it "generates a new migration with this name and timestamp" do run("rake db:new_migration name=test_abc").should =~ %r{Created migration .*spec/tmp/db/migrations/\d+_test_abc\.rb} run("ls db/migrations").should =~ /^\d+_test_abc.rb$/ end end context "multiple migration paths" do before do write_rakefile %{t.migrations = "db/migrations", "db/migrations2"} end it "chooses the first path" do run("rake db:new_migration name=test_abc").should =~ %r{Created migration .*db/migrations/\d+_test_abc\.rb} end end end describe 'db:version' do it "should start with a new database version" do run("rake db:version").should =~ /Current version: 0/ end end describe 'db:migrate' do context "single migration path" do it "does nothing when no migrations are present" do run("rake db:migrate").should =~ /SUCCESS/ end it "migrates if i add a migration" do run("rake db:new_migration name=xxx") result = run("rake db:migrate") result.should =~ /SUCCESS/ result.should =~ /Migrating to Xxx \(#{Time.now.year}/ end end context "multiple migration paths" do before do write_multiple_migrations end it "runs the migrator on each migration path" do result = run("rake db:migrate") result.should =~ /Migrating to CreateTests \(2010/ result.should =~ /Migrating to CreateTests2 \(2010/ end end end describe 'db:migrate:down' do context "single migration path" do it "migrates down" do make_migration('xxx') sleep 1 version = make_migration('yyy') run 'rake db:migrate' result = run("rake db:migrate:down VERSION=#{version}") result.should =~ /SUCCESS/ result.should_not =~ /DOWN-xxx/ result.should =~ /DOWN-yyy/ end it "fails without version" do make_migration('yyy') result = run("rake db:migrate:down") result.should_not =~ /SUCCESS/ end end context "multiple migration paths" do before do write_multiple_migrations end it "runs down on the correct path" do run 'rake db:migrate' result = run 'rake db:migrate:down VERSION=20100509095815' result.should =~ /DOWN-CreateTests/ result.should_not =~ /DOWN-CreateTests2/ end it "fails if migration number isn't found" do run 'rake db:migrate' result = run 'rake db:migrate:down VERSION=20100509095820' result.should_not =~ /SUCCESS/ result.should =~ /wasn't found on path/ end end end describe 'db:migrate:up' do context "single migration path" do it "migrates up" do make_migration('xxx') run 'rake db:migrate' sleep 1 version = make_migration('yyy') result = run("rake db:migrate:up VERSION=#{version}") result.should =~ /SUCCESS/ result.should_not =~ /UP-xxx/ result.should =~ /UP-yyy/ end it "fails without version" do make_migration('yyy') result = run("rake db:migrate:up") result.should_not =~ /SUCCESS/ end end context "multiple migration paths" do before do write_multiple_migrations end it "runs down on the correct path" do result = run 'rake db:migrate:up VERSION=20100509095815' result.should =~ /UP-CreateTests/ result.should_not =~ /UP-CreateTests2/ end it "fails if migration number isn't found" do result = run 'rake db:migrate:up VERSION=20100509095820' result.should_not =~ /SUCCESS/ result.should =~ /wasn't found on path/ end end end describe 'schema:dump' do it "dumps the schema" do result = run('rake db:schema:dump') result.should =~ /SUCCESS/ read('db/schema.rb').should =~ /ActiveRecord/ end end describe 'db:schema:load' do it "loads the schema" do run('rake db:schema:dump') schema = "db/schema.rb" write(schema, read(schema)+"\nputs 'LOADEDDD'") result = run('rake db:schema:load') result.should =~ /SUCCESS/ result.should =~ /LOADEDDD/ end end describe 'db:abort_if_pending_migrations' do it "passes when no migrations are pending" do run("rake db:abort_if_pending_migrations").should_not =~ /try again/ end it "fails when migrations are pending" do make_migration('yyy') result = run("rake db:abort_if_pending_migrations") result.should =~ /try again/ result.should =~ /1 pending migration/ end end describe 'db:test:load' do it 'loads' do write("db/schema.rb", "puts 'LOADEDDD'") run("rake db:test:load").should =~ /LOADEDDD.*SUCCESS/m end it "fails without schema" do run("rake db:test:load").should =~ /no such file to load/ end end describe 'db:test:purge' do it "runs" do run('rake db:test:purge').should =~ /SUCCESS/ end end end Tests for sub-namespaced tasks describe 'Standalone migrations' do def write(file, content) raise "cannot write nil" unless file file = tmp_file(file) folder = File.dirname(file) `mkdir -p #{folder}` unless File.exist?(folder) File.open(file, 'w') { |f| f.write content } end def read(file) File.read(tmp_file(file)) end def migration(name) m = `cd spec/tmp/db/migrations && ls`.split("\n").detect { |m| m =~ name } m ? "db/migrations/#{m}" : m end def tmp_file(file) "spec/tmp/#{file}" end def run(cmd) `cd spec/tmp && #{cmd} 2>&1 && echo SUCCESS` end def run_with_output(cmd) `cd spec/tmp && #{cmd} 2>&1` end def make_migration(name, options={}) task_name = options[:task_name] || 'db:new_migration' migration = run("rake #{task_name} name=#{name}").match(%r{db/migrations/\d+.*.rb})[0] content = read(migration) content.sub!(/def self.down.*?\send/m, "def self.down;puts 'DOWN-#{name}';end") content.sub!(/def self.up.*?\send/m, "def self.up;puts 'UP-#{name}';end") write(migration, content) migration.match(/\d{14}/)[0] end def make_sub_namespaced_migration(namespace, name) # specify complete task name here to avoid conditionals in make_migration make_migration(name, :task_name => "db:#{namespace}:new_migration") end def write_rakefile(config=nil) write 'Rakefile', <<-TXT $LOAD_PATH.unshift '#{File.expand_path('lib')}' begin require 'tasks/standalone_migrations' MigratorTasks.new do |t| t.log_level = Logger::INFO #{config} end rescue LoadError => e puts "gem install standalone_migrations to get db:migrate:* tasks! (Error: \#{e})" end TXT end def write_multiple_migrations write_rakefile %{t.migrations = "db/migrations", "db/migrations2"} write "db/migrations/20100509095815_create_tests.rb", <<-TXT class CreateTests < ActiveRecord::Migration def self.up puts "UP-CreateTests" end def self.down puts "DOWN-CreateTests" end end TXT write "db/migrations2/20100509095816_create_tests2.rb", <<-TXT class CreateTests2 < ActiveRecord::Migration def self.up puts "UP-CreateTests2" end def self.down puts "DOWN-CreateTests2" end end TXT end before do `rm -rf spec/tmp` if File.exist?('spec/tmp') `mkdir spec/tmp` write_rakefile write 'db/config.yml', <<-TXT development: adapter: sqlite3 database: db/development.sql test: adapter: sqlite3 database: db/test.sql TXT end describe 'db:create and drop' do it "should create the database and drop the database that was created" do run_with_output("rake db:create").should match /spec\/tmp\)$/ run_with_output("rake db:drop").should match /spec\/tmp\)$/ end end describe 'db:new_migration' do context "single migration path" do it "fails if i do not add a name" do run("rake db:new_migration").should_not =~ /SUCCESS/ end it "generates a new migration with this name and timestamp" do run("rake db:new_migration name=test_abc").should =~ %r{Created migration .*spec/tmp/db/migrations/\d+_test_abc\.rb} run("ls db/migrations").should =~ /^\d+_test_abc.rb$/ end end context "multiple migration paths" do before do write_rakefile %{t.migrations = "db/migrations", "db/migrations2"} end it "chooses the first path" do run("rake db:new_migration name=test_abc").should =~ %r{Created migration .*db/migrations/\d+_test_abc\.rb} end end context 'sub-namespaced task' do before do write_rakefile %{t.sub_namespace = "widgets"} end it "fails if i do not add a name" do run("rake db:widgets:new_migration").should_not =~ /SUCCESS/ end it "generates a new migration with this name and timestamp" do run("rake db:widgets:new_migration name=test_widget").should =~ %r{Created migration .*spec/tmp/db/migrations/\d+_test_widget\.rb} run("ls db/migrations").should =~ /^\d+_test_widget.rb$/ end it 'does not create top level db:new_migration task' do run('rake db:new_migration').should =~ /Don't know how to build task 'db:new_migration'/ end end end describe 'db:version' do it "should start with a new database version" do run("rake db:version").should =~ /Current version: 0/ end end describe 'db:migrate' do context "single migration path" do it "does nothing when no migrations are present" do run("rake db:migrate").should =~ /SUCCESS/ end it "migrates if i add a migration" do run("rake db:new_migration name=xxx") result = run("rake db:migrate") result.should =~ /SUCCESS/ result.should =~ /Migrating to Xxx \(#{Time.now.year}/ end end context "multiple migration paths" do before do write_multiple_migrations end it "runs the migrator on each migration path" do result = run("rake db:migrate") result.should =~ /Migrating to CreateTests \(2010/ result.should =~ /Migrating to CreateTests2 \(2010/ end end context 'sub-namespaced task' do before do write_rakefile %{t.sub_namespace = "widgets"} end it 'runs the migrations' do run("rake db:widgets:new_migration name=new_widget") result = run("rake db:widgets:migrate") result.should =~ /SUCCESS/ result.should =~ /Migrating to NewWidget \(#{Time.now.year}/ end it 'does not create top level db:new_migration task' do run('rake db:migrate').should =~ /Don't know how to build task 'db:migrate'/ end end end describe 'db:migrate:down' do context "single migration path" do it "migrates down" do make_migration('xxx') sleep 1 version = make_migration('yyy') run 'rake db:migrate' result = run("rake db:migrate:down VERSION=#{version}") result.should =~ /SUCCESS/ result.should_not =~ /DOWN-xxx/ result.should =~ /DOWN-yyy/ end it "fails without version" do make_migration('yyy') result = run("rake db:migrate:down") result.should_not =~ /SUCCESS/ end end context "multiple migration paths" do before do write_multiple_migrations end it "runs down on the correct path" do run 'rake db:migrate' result = run 'rake db:migrate:down VERSION=20100509095815' result.should =~ /DOWN-CreateTests/ result.should_not =~ /DOWN-CreateTests2/ end it "fails if migration number isn't found" do run 'rake db:migrate' result = run 'rake db:migrate:down VERSION=20100509095820' result.should_not =~ /SUCCESS/ result.should =~ /wasn't found on path/ end end context 'sub-namespaced task' do before do write_rakefile %{t.sub_namespace = "widgets"} end it 'migrates down' do make_sub_namespaced_migration('widgets', 'widget_xxx') sleep 1 version = make_sub_namespaced_migration('widgets', 'widget_yyy') run 'rake db:widgets:migrate' result = run("rake db:widgets:migrate:down VERSION=#{version}") result.should =~ /SUCCESS/ result.should_not =~ /DOWN-widget_xxx/ result.should =~ /DOWN-widget_yyy/ end end end describe 'db:migrate:up' do context "single migration path" do it "migrates up" do make_migration('xxx') run 'rake db:migrate' sleep 1 version = make_migration('yyy') result = run("rake db:migrate:up VERSION=#{version}") result.should =~ /SUCCESS/ result.should_not =~ /UP-xxx/ result.should =~ /UP-yyy/ end it "fails without version" do make_migration('yyy') result = run("rake db:migrate:up") result.should_not =~ /SUCCESS/ end end context "multiple migration paths" do before do write_multiple_migrations end it "runs down on the correct path" do result = run 'rake db:migrate:up VERSION=20100509095815' result.should =~ /UP-CreateTests/ result.should_not =~ /UP-CreateTests2/ end it "fails if migration number isn't found" do result = run 'rake db:migrate:up VERSION=20100509095820' result.should_not =~ /SUCCESS/ result.should =~ /wasn't found on path/ end end context 'sub-namespaced task' do before do write_rakefile %{t.sub_namespace = "widgets"} end it 'migrates up' do make_sub_namespaced_migration('widgets', 'widget_xxx') run 'rake db:widgets:migrate' sleep 1 version = make_sub_namespaced_migration('widgets', 'widget_yyy') result = run("rake db:widgets:migrate:up VERSION=#{version}") result.should =~ /SUCCESS/ result.should_not =~ /UP-widget_xxx/ result.should =~ /UP-widget_yyy/ end end end describe 'schema:dump' do it "dumps the schema" do result = run('rake db:schema:dump') result.should =~ /SUCCESS/ read('db/schema.rb').should =~ /ActiveRecord/ end end describe 'db:schema:load' do it "loads the schema" do run('rake db:schema:dump') schema = "db/schema.rb" write(schema, read(schema)+"\nputs 'LOADEDDD'") result = run('rake db:schema:load') result.should =~ /SUCCESS/ result.should =~ /LOADEDDD/ end end describe 'db:abort_if_pending_migrations' do it "passes when no migrations are pending" do run("rake db:abort_if_pending_migrations").should_not =~ /try again/ end it "fails when migrations are pending" do make_migration('yyy') result = run("rake db:abort_if_pending_migrations") result.should =~ /try again/ result.should =~ /1 pending migration/ end end describe 'db:test:load' do it 'loads' do write("db/schema.rb", "puts 'LOADEDDD'") run("rake db:test:load").should =~ /LOADEDDD.*SUCCESS/m end it "fails without schema" do run("rake db:test:load").should =~ /no such file to load/ end end describe 'db:test:purge' do it "runs" do run('rake db:test:purge').should =~ /SUCCESS/ end end end
# encoding: UTF-8 module ControllerHelpers def login_user(options = {}) before(:each) do @request.env["devise.mapping"] = Devise.mappings[:login] @current_user = User.make!(options) sign_in @current_user.login end end end Adds basic fixtures to controller specs # encoding: UTF-8 module ControllerHelpers def login_user(options = {}) fixtures :users, :logins before(:each) do @request.env["devise.mapping"] = Devise.mappings[:login] @current_user = users(:abigale_balisteri) sign_in @current_user.login end end end
if RUBY_ENGINE == 'opal' module React module SpecHelpers `var ReactTestUtils = React.addons.TestUtils` def renderToDocument(type, options = {}) element = React.create_element(type, options) React::Test::Utils.render_into_document(element) end def build_element(type, options) component = React.create_element(type, options) element = `ReactTestUtils.renderIntoDocument(#{component.to_n})` `ReactDOM.findDOMNode(element)` # v0.15 and up end def expect_component_to_eventually(component_class, opts = {}, &block) # Calls block after each update of a component until it returns true. # When it does set the expectation to true. Uses the after_update # callback of the component_class, then instantiates an element of that # class The call back is only called on updates, so the call back is # manually called right after the element is created. Because React.rb # runs the callback inside the components context, we have to setup a # lambda to get back to correct context before executing run_async. # Because run_async can only be run once it is protected by clearing # element once the test passes. element = nil check_block = lambda do context = block.arity > 0 ? self : element run_async do element = nil; expect(true).to be(true) end if element and context.instance_exec(element, &block) end component_class.after_update { check_block.call } element = build_element component_class, opts check_block.call end end end end not used
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'omniauth-draugiem/version' Gem::Specification.new do |s| s.name = "omniauth-draugiem" s.version = Omniauth::Draugiem::VERSION s.authors = ["Edgars Beigarts", "Uldis Ziņģis"] s.email = ["edgars.beigarts@makit.lv", "uldis.zingis@makit.lv"] s.summary = "Draugiem.lv authentication strategy for OmniAuth" s.description = s.summary s.homepage = "http://github.com/mak-it/omniauth-draugiem" s.license = "MIT" s.files = `git ls-files`.split($/) s.executables = s.files.grep(%r{^bin/}) { |f| File.basename(f) } s.test_files = s.files.grep(%r{^spec/}) s.require_paths = ["lib"] s.add_runtime_dependency "omniauth", "~> 1.0" s.add_runtime_dependency "rest-client", "~> 1.8" s.add_runtime_dependency "multi_json", "~> 1.0" s.add_development_dependency "bundler", "~> 1.5" s.add_development_dependency "rake" s.add_development_dependency "rspec", "~> 3.0" s.add_development_dependency "simplecov" s.add_development_dependency "rack-test" s.add_development_dependency 'webmock' end Upgrade rest-client for >=ruby-2.4.x support # coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'omniauth-draugiem/version' Gem::Specification.new do |s| s.name = "omniauth-draugiem" s.version = Omniauth::Draugiem::VERSION s.authors = ["Edgars Beigarts", "Uldis Ziņģis"] s.email = ["edgars.beigarts@makit.lv", "uldis.zingis@makit.lv"] s.summary = "Draugiem.lv authentication strategy for OmniAuth" s.description = s.summary s.homepage = "http://github.com/mak-it/omniauth-draugiem" s.license = "MIT" s.files = `git ls-files`.split($/) s.executables = s.files.grep(%r{^bin/}) { |f| File.basename(f) } s.test_files = s.files.grep(%r{^spec/}) s.require_paths = ["lib"] s.add_runtime_dependency "omniauth", "~> 1.0" s.add_runtime_dependency "rest-client", "~> 2.0.1" s.add_runtime_dependency "multi_json", "~> 1.0" s.add_development_dependency "bundler", "~> 1.5" s.add_development_dependency "rake" s.add_development_dependency "rspec", "~> 3.0" s.add_development_dependency "simplecov" s.add_development_dependency "rack-test" s.add_development_dependency 'webmock' end
require 'opal_hot_reloader/reactrb_patches' require 'opal_hot_reloader/css_reloader' require 'opal-parser' # gives me 'eval', for hot-loading code require 'json' # Opal client to support hot reloading class OpalHotReloader def connect_to_websocket(port) host = `window.location.host`.sub(/:\d+/, '') host = '127.0.0.1' if host == '' ws_url = "#{host}:#{port}" puts "Hot-Reloader connecting to #{ws_url}" %x{ ws = new WebSocket('ws://' + #{ws_url}); // console.log(ws); ws.onmessage = #{lambda { |e| reload(e) }} } end def reload(e) reload_request = JSON.parse(`e.data`) if reload_request[:type] == "ruby" puts "Reloading ruby #{reload_request[:filename]}" eval reload_request[:source_code] if @reload_post_callback @reload_post_callback.call else puts "not reloading code" end end if reload_request[:type] == "css" @css_reloader.reload(reload_request, `document`) end end # @param port [Integer] opal hot reloader port to connect to # @param reload_post_callback [Proc] optional callback to be called after re evaluating a file for example in react.rb files we want to do a React::Component.force_update! def initialize(port=25222, &reload_post_callback) @port = port @reload_post_callback = reload_post_callback @css_reloader = CssReloader.new end # Opens a websocket connection that evaluates new files and runs the optional @reload_post_callback def listen connect_to_websocket(@port) end # convenience method to start a listen w/one line # @param port [Integer] opal hot reloader port to connect to. Defaults to 25222 to match opal-hot-loader default # @param reactrb [Boolean] whether or not the project runs reactrb. If true, the reactrb callback is automatically run after evaluation the updated code. Defaults to false. def self.listen(port=25222, reactrb=false) return if @server if reactrb if defined? ::React ReactrbPatches.patch! @server = OpalHotReloader.new(port) { React::Component.force_update! } else puts "This is not a React.rb app. No React.rb hooks will be applied" end else @server = OpalHotReloader.new(port) end @server.listen end end dirty fix for new eval-behaviour of opal require 'opal_hot_reloader/reactrb_patches' require 'opal_hot_reloader/css_reloader' require 'opal-parser' # gives me 'eval', for hot-loading code require 'json' # Opal client to support hot reloading $eval_proc = proc { |s| eval s } class OpalHotReloader def connect_to_websocket(port) host = `window.location.host`.sub(/:\d+/, '') host = '127.0.0.1' if host == '' ws_url = "#{host}:#{port}" puts "Hot-Reloader connecting to #{ws_url}" %x{ ws = new WebSocket('ws://' + #{ws_url}); // console.log(ws); ws.onmessage = #{lambda { |e| reload(e) }} } end def reload(e) reload_request = JSON.parse(`e.data`) if reload_request[:type] == "ruby" puts "Reloading ruby #{reload_request[:filename]}" $eval_proc.call reload_request[:source_code] if @reload_post_callback @reload_post_callback.call else puts "not reloading code" end end if reload_request[:type] == "css" @css_reloader.reload(reload_request, `document`) end end # @param port [Integer] opal hot reloader port to connect to # @param reload_post_callback [Proc] optional callback to be called after re evaluating a file for example in react.rb files we want to do a React::Component.force_update! def initialize(port=25222, &reload_post_callback) @port = port @reload_post_callback = reload_post_callback @css_reloader = CssReloader.new end # Opens a websocket connection that evaluates new files and runs the optional @reload_post_callback def listen connect_to_websocket(@port) end # convenience method to start a listen w/one line # @param port [Integer] opal hot reloader port to connect to. Defaults to 25222 to match opal-hot-loader default # @param reactrb [Boolean] whether or not the project runs reactrb. If true, the reactrb callback is automatically run after evaluation the updated code. Defaults to false. def self.listen(port=25222, reactrb=false) return if @server if reactrb if defined? ::React ReactrbPatches.patch! @server = OpalHotReloader.new(port) { React::Component.force_update! } else puts "This is not a React.rb app. No React.rb hooks will be applied" end else @server = OpalHotReloader.new(port) end @server.listen end end
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{opencongress-ruby} s.version = "0.1.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["David Shettler"] s.date = %q{2009-03-25} s.email = %q{dave@opencongress.org} s.extra_rdoc_files = ["README.rdoc", "LICENSE"] s.files = ["README.rdoc", "VERSION.yml", "lib/opencongress", "lib/opencongress/bill.rb", "lib/opencongress/blog_post.rb", "lib/opencongress/news_post.rb", "lib/opencongress/person.rb", "lib/opencongress/person_stat.rb", "lib/opencongress/roll_call.rb", "lib/opencongress/roll_call_comparison.rb", "lib/opencongress/voting_comparison.rb", "lib/opencongress_ruby.rb", "test/opencongress_ruby_test.rb", "test/test_helper.rb", "LICENSE"] s.has_rdoc = true s.homepage = %q{http://github.com/opencongress/opencongress-ruby} s.rdoc_options = ["--inline-source", "--charset=UTF-8"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.1} s.summary = %q{OpenCongress API ruby binding} if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 2 if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then else end else end end Regenerated gemspec for version 0.1.1 # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{opencongress-ruby} s.version = "0.1.1" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["David Shettler"] s.date = %q{2009-03-25} s.email = %q{dave@opencongress.org} s.extra_rdoc_files = ["README.rdoc", "LICENSE"] s.files = ["README.rdoc", "VERSION.yml", "lib/opencongress", "lib/opencongress/bill.rb", "lib/opencongress/blog_post.rb", "lib/opencongress/news_post.rb", "lib/opencongress/person.rb", "lib/opencongress/person_stat.rb", "lib/opencongress/roll_call.rb", "lib/opencongress/roll_call_comparison.rb", "lib/opencongress/voting_comparison.rb", "lib/opencongress_ruby.rb", "test/opencongress_ruby_test.rb", "test/test_helper.rb", "LICENSE"] s.has_rdoc = true s.homepage = %q{http://github.com/opencongress/opencongress-ruby} s.rdoc_options = ["--inline-source", "--charset=UTF-8"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.1} s.summary = %q{OpenCongress API ruby binding} if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 2 if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then else end else end end
require "spec_helper" describe Mongoid::Criteria do before do @criteria = Mongoid::Criteria.new(Person) end describe "#aggregate" do context "when klass provided" do before do @reduce = "function(obj, prev) { prev.count++; }" @criteria = Mongoid::Criteria.new(Person) @collection = mock Person.expects(:collection).returns(@collection) end it "calls group on the collection with the aggregate js" do @collection.expects(:group).with([:field1], {}, {:count => 0}, @reduce) @criteria.select(:field1).aggregate end end context "when klass not provided" do before do @reduce = "function(obj, prev) { prev.count++; }" @collection = mock Person.expects(:collection).returns(@collection) end it "calls group on the collection with the aggregate js" do @collection.expects(:group).with([:field1], {}, {:count => 0}, @reduce) @criteria.select(:field1).aggregate(Person) end end end describe "#all" do it "adds the $all query to the selector" do @criteria.all(:title => ["title1", "title2"]) @criteria.selector.should == { :title => { "$all" => ["title1", "title2"] } } end it "returns self" do @criteria.all(:title => [ "title1" ]).should == @criteria end end describe "#and" do context "when provided a hash" do it "adds the clause to the selector" do @criteria.and(:title => "Title", :text => "Text") @criteria.selector.should == { :title => "Title", :text => "Text" } end end context "when provided a string" do it "adds the $where clause to the selector" do @criteria.and("this.date < new Date()") @criteria.selector.should == { "$where" => "this.date < new Date()" } end end it "returns self" do @criteria.and.should == @criteria end end describe "#collect" do context "filtering" do before do @collection = mock Person.expects(:collection).returns(@collection) @criteria = Mongoid::Criteria.new(Person).extras(:page => 1, :per_page => 20) @collection.expects(:find).with(@criteria.selector, @criteria.options).returns([]) end it "filters out unused params" do @criteria.collect @criteria.options[:page].should be_nil @criteria.options[:per_page].should be_nil end end context "when type is :all" do before do @collection = mock Person.expects(:collection).returns(@collection) @criteria = Mongoid::Criteria.new(Person).extras(:page => 1, :per_page => 20) @cursor = stub(:count => 44, :collect => []) @collection.expects(:find).with(@criteria.selector, @criteria.options).returns(@cursor) end it "adds the count instance variable" do @criteria.collect.should == [] @criteria.count.should == 44 end end context "when type is :first" do end context "when type is not :first" do it "calls find on the collection with the selector and options" do criteria = Mongoid::Criteria.new(Person) collection = mock Person.expects(:collection).returns(collection) collection.expects(:find).with(@criteria.selector, @criteria.options).returns([]) criteria.collect.should == [] end end end describe "#count" do context "when criteria has not been executed" do before do @criteria.instance_variable_set(:@count, 34) end it "returns a count from the cursor" do @criteria.count.should == 34 end end context "when criteria has been executed" do before do @criteria = Mongoid::Criteria.new(Person) @selector = { :test => "Testing" } @criteria.where(@selector) @collection = mock @cursor = mock Person.expects(:collection).returns(@collection) end it "returns the count from the cursor without creating the documents" do @collection.expects(:find).with(@selector, {}).returns(@cursor) @cursor.expects(:count).returns(10) @criteria.count.should == 10 end end end describe "#each" do before do @criteria.where(:title => "Sir") @collection = stub @person = Person.new(:title => "Sir") @cursor = stub(:count => 10, :collect => [@person]) end context "when the criteria has not been executed" do before do Person.expects(:collection).returns(@collection) @collection.expects(:find).with({ :title => "Sir" }, {}).returns(@cursor) end it "executes the criteria" do @criteria.each do |person| person.should == @person end end end context "when the criteria has been executed" do before do Person.expects(:collection).returns(@collection) @collection.expects(:find).with({ :title => "Sir" }, {}).returns(@cursor) end it "calls each on the existing results" do @criteria.each @criteria.each do |person| person.should == @person end end end context "when no block is passed" do it "returns self" do @criteria.each.should == @criteria end end end describe "#excludes" do it "adds the $ne query to the selector" do @criteria.excludes(:title => "Bad Title", :text => "Bad Text") @criteria.selector.should == { :title => { "$ne" => "Bad Title"}, :text => { "$ne" => "Bad Text" } } end it "returns self" do @criteria.excludes(:title => "Bad").should == @criteria end end describe "#extras" do context "filtering" do context "when page is provided" do it "sets the limit and skip options" do @criteria.extras({ :page => "2" }) @criteria.page.should == 2 @criteria.options.should == { :skip => 20, :limit => 20 } end end context "when per_page is provided" do it "sets the limit and skip options" do @criteria.extras({ :per_page => 45 }) @criteria.options.should == { :skip => 0, :limit => 45 } end end context "when page and per_page both provided" do it "sets the limit and skip options" do @criteria.extras({ :per_page => 30, :page => "4" }) @criteria.options.should == { :skip => 90, :limit => 30 } @criteria.page.should == 4 end end end it "adds the extras to the options" do @criteria.extras({ :skip => 10 }) @criteria.options.should == { :skip => 10 } end it "returns self" do @criteria.extras({}).should == @criteria end end describe "#group" do before do @grouping = [{ "title" => "Sir", "group" => [{ "title" => "Sir", "age" => 30 }] }] end context "when klass provided" do before do @reduce = "function(obj, prev) { prev.group.push(obj); }" @criteria = Mongoid::Criteria.new(Person) @collection = mock Person.expects(:collection).returns(@collection) end it "calls group on the collection with the aggregate js" do @collection.expects(:group).with([:field1], {}, {:group => []}, @reduce).returns(@grouping) @criteria.select(:field1).group end end context "when klass not provided" do before do @reduce = "function(obj, prev) { prev.group.push(obj); }" @collection = mock Person.expects(:collection).returns(@collection) end it "calls group on the collection with the aggregate js" do @collection.expects(:group).with([:field1], {}, {:group => []}, @reduce).returns(@grouping) @criteria.select(:field1).group end end end describe "#id" do it "adds the _id query to the selector" do id = Mongo::ObjectID.new.to_s @criteria.id(id) @criteria.selector.should == { :_id => id } end it "returns self" do id = Mongo::ObjectID.new.to_s @criteria.id(id.to_s).should == @criteria end end describe "#in" do it "adds the $in clause to the selector" do @criteria.in(:title => ["title1", "title2"], :text => ["test"]) @criteria.selector.should == { :title => { "$in" => ["title1", "title2"] }, :text => { "$in" => ["test"] } } end it "returns self" do @criteria.in(:title => ["title1"]).should == @criteria end end describe "#last" do context "when documents exist" do before do @collection = mock Person.expects(:collection).returns(@collection) @collection.expects(:find_one).with(@criteria.selector, { :sort => [[:title, :desc]] }).returns({ :title => "Sir" }) end it "calls find on the collection with the selector and sort options reversed" do criteria = Mongoid::Criteria.new(Person) criteria.order_by([[:title, :asc]]) criteria.last.should be_a_kind_of(Person) end end context "when no documents exist" do before do @collection = mock Person.expects(:collection).returns(@collection) @collection.expects(:find_one).with(@criteria.selector, { :sort => [[:_id, :desc]] }).returns(nil) end it "returns nil" do criteria = Mongoid::Criteria.new(Person) criteria.last.should be_nil end end context "when no sorting options provided" do before do @collection = mock Person.expects(:collection).returns(@collection) @collection.expects(:find_one).with(@criteria.selector, { :sort => [[:_id, :desc]] }).returns({ :title => "Sir" }) end it "defaults to sort by id" do criteria = Mongoid::Criteria.new(Person) criteria.last end end end describe "#limit" do context "when value provided" do it "adds the limit to the options" do @criteria.limit(100) @criteria.options.should == { :limit => 100 } end end context "when value not provided" do it "defaults to 20" do @criteria.limit @criteria.options.should == { :limit => 20 } end end it "returns self" do @criteria.limit.should == @criteria end end describe "#merge" do before do @criteria.where(:title => "Sir", :age => 30).skip(40).limit(20) end context "with another criteria" do context "when the other has a selector and options" do before do @other = Mongoid::Criteria.new(Person) @other.where(:name => "Chloe").order_by([[:name, :asc]]) @selector = { :title => "Sir", :age => 30, :name => "Chloe" } @options = { :skip => 40, :limit => 20, :sort => [[:name, :asc]] } end it "merges the selector and options hashes together" do @criteria.merge(@other) @criteria.selector.should == @selector @criteria.options.should == @options end end context "when the other has no selector or options" do before do @other = Mongoid::Criteria.new(Person) @selector = { :title => "Sir", :age => 30 } @options = { :skip => 40, :limit => 20 } end it "merges the selector and options hashes together" do @criteria.merge(@other) @criteria.selector.should == @selector @criteria.options.should == @options end end end end describe "#method_missing" do before do @criteria = Mongoid::Criteria.new(Person) @criteria.where(:title => "Sir") end it "merges the criteria with the next one" do @new_criteria = @criteria.accepted @new_criteria.selector.should == { :title => "Sir", :terms => true } end context "chaining more than one scope" do before do @criteria = Person.accepted.old.knight end it "returns the final merged criteria" do @criteria.selector.should == { :title => "Sir", :terms => true, :age => { "$gt" => 50 } } end end context "when expecting behaviour of an array" do before do @array = mock @document = mock end describe "#[]" do it "collects the criteria and calls []" do @criteria.expects(:collect).returns([@document]) @criteria[0].should == @document end end describe "#rand" do it "collects the criteria and call rand" do @criteria.expects(:collect).returns(@array) @array.expects(:send).with(:rand).returns(@document) @criteria.rand end end end end describe "#not_in" do it "adds the exclusion to the selector" do @criteria.not_in(:title => ["title1", "title2"], :text => ["test"]) @criteria.selector.should == { :title => { "$nin" => ["title1", "title2"] }, :text => { "$nin" => ["test"] } } end it "returns self" do @criteria.not_in(:title => ["title1"]).should == @criteria end end describe "#offset" do context "when the per_page option exists" do before do @criteria = Mongoid::Criteria.new(Person).extras({ :per_page => 20, :page => 3 }) end it "returns the per_page option" do @criteria.offset.should == 40 end end context "when the skip option exists" do before do @criteria = Mongoid::Criteria.new(Person).extras({ :skip => 20 }) end it "returns the skip option" do @criteria.offset.should == 20 end end context "when no option exists" do context "when page option exists" do before do @criteria = Mongoid::Criteria.new(Person).extras({ :page => 2 }) end it "adds the skip option to the options and returns it" do @criteria.offset.should == 20 @criteria.options[:skip].should == 20 end end context "when page option does not exist" do before do @criteria = Mongoid::Criteria.new(Person) end it "returns nil" do @criteria.offset.should be_nil @criteria.options[:skip].should be_nil end end end end describe "#one" do context "when documents exist" do before do @collection = mock Person.expects(:collection).returns(@collection) @collection.expects(:find_one).with(@criteria.selector, @criteria.options).returns({ :title => "Sir" }) end it "calls find on the collection with the selector and options" do criteria = Mongoid::Criteria.new(Person) criteria.one.should be_a_kind_of(Person) end end context "when no documents exist" do before do @collection = mock Person.expects(:collection).returns(@collection) @collection.expects(:find_one).with(@criteria.selector, @criteria.options).returns(nil) end it "returns nil" do criteria = Mongoid::Criteria.new(Person) criteria.one.should be_nil end end end describe "#order_by" do context "when field names and direction specified" do it "adds the sort to the options" do @criteria.order_by([[:title, :asc], [:text, :desc]]) @criteria.options.should == { :sort => [[:title, :asc], [:text, :desc]] } end end it "returns self" do @criteria.order_by.should == @criteria end end describe "#page" do context "when the page option exists" do before do @criteria = Mongoid::Criteria.new(Person).extras({ :page => 5 }) end it "returns the page option" do @criteria.page.should == 5 end end context "when the page option does not exist" do before do @criteria = Mongoid::Criteria.new(Person) end it "returns 1" do @criteria.page.should == 1 end end end describe "#paginate" do before do @collection = mock Person.expects(:collection).returns(@collection) @criteria = Person.select.where(:_id => "1").skip(60).limit(20) @collection.expects(:find).with({:_id => "1"}, :skip => 60, :limit => 20).returns([]) @results = @criteria.paginate end it "executes and paginates the results" do @results.current_page.should == 4 @results.per_page.should == 20 end end describe "#per_page" do context "when the per_page option exists" do before do @criteria = Mongoid::Criteria.new(Person).extras({ :per_page => 10 }) end it "returns the per_page option" do @criteria.per_page.should == 10 end end context "when the per_page option does not exist" do before do @criteria = Mongoid::Criteria.new(Person) end it "returns 1" do @criteria.per_page.should == 20 end end end describe "#select" do context "when args are provided" do it "adds the options for limiting by fields" do @criteria.select(:title, :text) @criteria.options.should == { :fields => [ :title, :text ] } end it "returns self" do @criteria.select.should == @criteria end end context "when no args provided" do it "does not add the field option" do @criteria.select @criteria.options[:fields].should be_nil end end end describe "#skip" do context "when value provided" do it "adds the skip value to the options" do @criteria.skip(20) @criteria.options.should == { :skip => 20 } end end context "when value not provided" do it "defaults to zero" do @criteria.skip @criteria.options.should == { :skip => 0 } end end it "returns self" do @criteria.skip.should == @criteria end end describe ".translate" do context "with a single argument" do before do @id = Mongo::ObjectID.new.to_s @document = stub @criteria = mock Mongoid::Criteria.expects(:new).returns(@criteria) @criteria.expects(:id).with(@id).returns(@criteria) @criteria.expects(:one).returns(@document) end it "creates a criteria for a string" do Mongoid::Criteria.translate(Person, @id) end end context "multiple arguments" do context "when Person, :conditions => {}" do before do @criteria = Mongoid::Criteria.translate(Person, :conditions => { :title => "Test" }) end it "returns a criteria with a selector from the conditions" do @criteria.selector.should == { :title => "Test" } end it "returns a criteria with klass Person" do @criteria.klass.should == Person end end context "when :all, :conditions => {}" do before do @criteria = Mongoid::Criteria.translate(Person, :conditions => { :title => "Test" }) end it "returns a criteria with a selector from the conditions" do @criteria.selector.should == { :title => "Test" } end it "returns a criteria with klass Person" do @criteria.klass.should == Person end end context "when :last, :conditions => {}" do before do @criteria = Mongoid::Criteria.translate(Person, :conditions => { :title => "Test" }) end it "returns a criteria with a selector from the conditions" do @criteria.selector.should == { :title => "Test" } end it "returns a criteria with klass Person" do @criteria.klass.should == Person end end context "when options are provided" do before do @criteria = Mongoid::Criteria.translate(Person, :conditions => { :title => "Test" }, :skip => 10) end it "adds the criteria and the options" do @criteria.selector.should == { :title => "Test" } @criteria.options.should == { :skip => 10 } end end end end describe "#where" do context "when provided a hash" do it "adds the clause to the selector" do @criteria.where(:title => "Title", :text => "Text") @criteria.selector.should == { :title => "Title", :text => "Text" } end end context "when provided a string" do it "adds the $where clause to the selector" do @criteria.where("this.date < new Date()") @criteria.selector.should == { "$where" => "this.date < new Date()" } end end it "returns self" do @criteria.where.should == @criteria end end end Adding spec for array indexes require "spec_helper" describe Mongoid::Criteria do before do @criteria = Mongoid::Criteria.new(Person) end describe "#[]" do before do @criteria.where(:title => "Sir") @collection = stub @person = Person.new(:title => "Sir") @cursor = stub(:count => 10, :collect => [@person]) end context "when the criteria has not been executed" do before do Person.expects(:collection).returns(@collection) @collection.expects(:find).with({ :title => "Sir" }, {}).returns(@cursor) end it "executes the criteria and returns the element at the index" do @criteria[0].should == @person end end end describe "#aggregate" do context "when klass provided" do before do @reduce = "function(obj, prev) { prev.count++; }" @criteria = Mongoid::Criteria.new(Person) @collection = mock Person.expects(:collection).returns(@collection) end it "calls group on the collection with the aggregate js" do @collection.expects(:group).with([:field1], {}, {:count => 0}, @reduce) @criteria.select(:field1).aggregate end end context "when klass not provided" do before do @reduce = "function(obj, prev) { prev.count++; }" @collection = mock Person.expects(:collection).returns(@collection) end it "calls group on the collection with the aggregate js" do @collection.expects(:group).with([:field1], {}, {:count => 0}, @reduce) @criteria.select(:field1).aggregate(Person) end end end describe "#all" do it "adds the $all query to the selector" do @criteria.all(:title => ["title1", "title2"]) @criteria.selector.should == { :title => { "$all" => ["title1", "title2"] } } end it "returns self" do @criteria.all(:title => [ "title1" ]).should == @criteria end end describe "#and" do context "when provided a hash" do it "adds the clause to the selector" do @criteria.and(:title => "Title", :text => "Text") @criteria.selector.should == { :title => "Title", :text => "Text" } end end context "when provided a string" do it "adds the $where clause to the selector" do @criteria.and("this.date < new Date()") @criteria.selector.should == { "$where" => "this.date < new Date()" } end end it "returns self" do @criteria.and.should == @criteria end end describe "#collect" do context "filtering" do before do @collection = mock Person.expects(:collection).returns(@collection) @criteria = Mongoid::Criteria.new(Person).extras(:page => 1, :per_page => 20) @collection.expects(:find).with(@criteria.selector, @criteria.options).returns([]) end it "filters out unused params" do @criteria.collect @criteria.options[:page].should be_nil @criteria.options[:per_page].should be_nil end end context "when type is :all" do before do @collection = mock Person.expects(:collection).returns(@collection) @criteria = Mongoid::Criteria.new(Person).extras(:page => 1, :per_page => 20) @cursor = stub(:count => 44, :collect => []) @collection.expects(:find).with(@criteria.selector, @criteria.options).returns(@cursor) end it "adds the count instance variable" do @criteria.collect.should == [] @criteria.count.should == 44 end end context "when type is :first" do end context "when type is not :first" do it "calls find on the collection with the selector and options" do criteria = Mongoid::Criteria.new(Person) collection = mock Person.expects(:collection).returns(collection) collection.expects(:find).with(@criteria.selector, @criteria.options).returns([]) criteria.collect.should == [] end end end describe "#count" do context "when criteria has not been executed" do before do @criteria.instance_variable_set(:@count, 34) end it "returns a count from the cursor" do @criteria.count.should == 34 end end context "when criteria has been executed" do before do @criteria = Mongoid::Criteria.new(Person) @selector = { :test => "Testing" } @criteria.where(@selector) @collection = mock @cursor = mock Person.expects(:collection).returns(@collection) end it "returns the count from the cursor without creating the documents" do @collection.expects(:find).with(@selector, {}).returns(@cursor) @cursor.expects(:count).returns(10) @criteria.count.should == 10 end end end describe "#each" do before do @criteria.where(:title => "Sir") @collection = stub @person = Person.new(:title => "Sir") @cursor = stub(:count => 10, :collect => [@person]) end context "when the criteria has not been executed" do before do Person.expects(:collection).returns(@collection) @collection.expects(:find).with({ :title => "Sir" }, {}).returns(@cursor) end it "executes the criteria" do @criteria.each do |person| person.should == @person end end end context "when the criteria has been executed" do before do Person.expects(:collection).returns(@collection) @collection.expects(:find).with({ :title => "Sir" }, {}).returns(@cursor) end it "calls each on the existing results" do @criteria.each @criteria.each do |person| person.should == @person end end end context "when no block is passed" do it "returns self" do @criteria.each.should == @criteria end end end describe "#excludes" do it "adds the $ne query to the selector" do @criteria.excludes(:title => "Bad Title", :text => "Bad Text") @criteria.selector.should == { :title => { "$ne" => "Bad Title"}, :text => { "$ne" => "Bad Text" } } end it "returns self" do @criteria.excludes(:title => "Bad").should == @criteria end end describe "#extras" do context "filtering" do context "when page is provided" do it "sets the limit and skip options" do @criteria.extras({ :page => "2" }) @criteria.page.should == 2 @criteria.options.should == { :skip => 20, :limit => 20 } end end context "when per_page is provided" do it "sets the limit and skip options" do @criteria.extras({ :per_page => 45 }) @criteria.options.should == { :skip => 0, :limit => 45 } end end context "when page and per_page both provided" do it "sets the limit and skip options" do @criteria.extras({ :per_page => 30, :page => "4" }) @criteria.options.should == { :skip => 90, :limit => 30 } @criteria.page.should == 4 end end end it "adds the extras to the options" do @criteria.extras({ :skip => 10 }) @criteria.options.should == { :skip => 10 } end it "returns self" do @criteria.extras({}).should == @criteria end end describe "#group" do before do @grouping = [{ "title" => "Sir", "group" => [{ "title" => "Sir", "age" => 30 }] }] end context "when klass provided" do before do @reduce = "function(obj, prev) { prev.group.push(obj); }" @criteria = Mongoid::Criteria.new(Person) @collection = mock Person.expects(:collection).returns(@collection) end it "calls group on the collection with the aggregate js" do @collection.expects(:group).with([:field1], {}, {:group => []}, @reduce).returns(@grouping) @criteria.select(:field1).group end end context "when klass not provided" do before do @reduce = "function(obj, prev) { prev.group.push(obj); }" @collection = mock Person.expects(:collection).returns(@collection) end it "calls group on the collection with the aggregate js" do @collection.expects(:group).with([:field1], {}, {:group => []}, @reduce).returns(@grouping) @criteria.select(:field1).group end end end describe "#id" do it "adds the _id query to the selector" do id = Mongo::ObjectID.new.to_s @criteria.id(id) @criteria.selector.should == { :_id => id } end it "returns self" do id = Mongo::ObjectID.new.to_s @criteria.id(id.to_s).should == @criteria end end describe "#in" do it "adds the $in clause to the selector" do @criteria.in(:title => ["title1", "title2"], :text => ["test"]) @criteria.selector.should == { :title => { "$in" => ["title1", "title2"] }, :text => { "$in" => ["test"] } } end it "returns self" do @criteria.in(:title => ["title1"]).should == @criteria end end describe "#last" do context "when documents exist" do before do @collection = mock Person.expects(:collection).returns(@collection) @collection.expects(:find_one).with(@criteria.selector, { :sort => [[:title, :desc]] }).returns({ :title => "Sir" }) end it "calls find on the collection with the selector and sort options reversed" do criteria = Mongoid::Criteria.new(Person) criteria.order_by([[:title, :asc]]) criteria.last.should be_a_kind_of(Person) end end context "when no documents exist" do before do @collection = mock Person.expects(:collection).returns(@collection) @collection.expects(:find_one).with(@criteria.selector, { :sort => [[:_id, :desc]] }).returns(nil) end it "returns nil" do criteria = Mongoid::Criteria.new(Person) criteria.last.should be_nil end end context "when no sorting options provided" do before do @collection = mock Person.expects(:collection).returns(@collection) @collection.expects(:find_one).with(@criteria.selector, { :sort => [[:_id, :desc]] }).returns({ :title => "Sir" }) end it "defaults to sort by id" do criteria = Mongoid::Criteria.new(Person) criteria.last end end end describe "#limit" do context "when value provided" do it "adds the limit to the options" do @criteria.limit(100) @criteria.options.should == { :limit => 100 } end end context "when value not provided" do it "defaults to 20" do @criteria.limit @criteria.options.should == { :limit => 20 } end end it "returns self" do @criteria.limit.should == @criteria end end describe "#merge" do before do @criteria.where(:title => "Sir", :age => 30).skip(40).limit(20) end context "with another criteria" do context "when the other has a selector and options" do before do @other = Mongoid::Criteria.new(Person) @other.where(:name => "Chloe").order_by([[:name, :asc]]) @selector = { :title => "Sir", :age => 30, :name => "Chloe" } @options = { :skip => 40, :limit => 20, :sort => [[:name, :asc]] } end it "merges the selector and options hashes together" do @criteria.merge(@other) @criteria.selector.should == @selector @criteria.options.should == @options end end context "when the other has no selector or options" do before do @other = Mongoid::Criteria.new(Person) @selector = { :title => "Sir", :age => 30 } @options = { :skip => 40, :limit => 20 } end it "merges the selector and options hashes together" do @criteria.merge(@other) @criteria.selector.should == @selector @criteria.options.should == @options end end end end describe "#method_missing" do before do @criteria = Mongoid::Criteria.new(Person) @criteria.where(:title => "Sir") end it "merges the criteria with the next one" do @new_criteria = @criteria.accepted @new_criteria.selector.should == { :title => "Sir", :terms => true } end context "chaining more than one scope" do before do @criteria = Person.accepted.old.knight end it "returns the final merged criteria" do @criteria.selector.should == { :title => "Sir", :terms => true, :age => { "$gt" => 50 } } end end context "when expecting behaviour of an array" do before do @array = mock @document = mock end describe "#[]" do it "collects the criteria and calls []" do @criteria.expects(:collect).returns([@document]) @criteria[0].should == @document end end describe "#rand" do it "collects the criteria and call rand" do @criteria.expects(:collect).returns(@array) @array.expects(:send).with(:rand).returns(@document) @criteria.rand end end end end describe "#not_in" do it "adds the exclusion to the selector" do @criteria.not_in(:title => ["title1", "title2"], :text => ["test"]) @criteria.selector.should == { :title => { "$nin" => ["title1", "title2"] }, :text => { "$nin" => ["test"] } } end it "returns self" do @criteria.not_in(:title => ["title1"]).should == @criteria end end describe "#offset" do context "when the per_page option exists" do before do @criteria = Mongoid::Criteria.new(Person).extras({ :per_page => 20, :page => 3 }) end it "returns the per_page option" do @criteria.offset.should == 40 end end context "when the skip option exists" do before do @criteria = Mongoid::Criteria.new(Person).extras({ :skip => 20 }) end it "returns the skip option" do @criteria.offset.should == 20 end end context "when no option exists" do context "when page option exists" do before do @criteria = Mongoid::Criteria.new(Person).extras({ :page => 2 }) end it "adds the skip option to the options and returns it" do @criteria.offset.should == 20 @criteria.options[:skip].should == 20 end end context "when page option does not exist" do before do @criteria = Mongoid::Criteria.new(Person) end it "returns nil" do @criteria.offset.should be_nil @criteria.options[:skip].should be_nil end end end end describe "#one" do context "when documents exist" do before do @collection = mock Person.expects(:collection).returns(@collection) @collection.expects(:find_one).with(@criteria.selector, @criteria.options).returns({ :title => "Sir" }) end it "calls find on the collection with the selector and options" do criteria = Mongoid::Criteria.new(Person) criteria.one.should be_a_kind_of(Person) end end context "when no documents exist" do before do @collection = mock Person.expects(:collection).returns(@collection) @collection.expects(:find_one).with(@criteria.selector, @criteria.options).returns(nil) end it "returns nil" do criteria = Mongoid::Criteria.new(Person) criteria.one.should be_nil end end end describe "#order_by" do context "when field names and direction specified" do it "adds the sort to the options" do @criteria.order_by([[:title, :asc], [:text, :desc]]) @criteria.options.should == { :sort => [[:title, :asc], [:text, :desc]] } end end it "returns self" do @criteria.order_by.should == @criteria end end describe "#page" do context "when the page option exists" do before do @criteria = Mongoid::Criteria.new(Person).extras({ :page => 5 }) end it "returns the page option" do @criteria.page.should == 5 end end context "when the page option does not exist" do before do @criteria = Mongoid::Criteria.new(Person) end it "returns 1" do @criteria.page.should == 1 end end end describe "#paginate" do before do @collection = mock Person.expects(:collection).returns(@collection) @criteria = Person.select.where(:_id => "1").skip(60).limit(20) @collection.expects(:find).with({:_id => "1"}, :skip => 60, :limit => 20).returns([]) @results = @criteria.paginate end it "executes and paginates the results" do @results.current_page.should == 4 @results.per_page.should == 20 end end describe "#per_page" do context "when the per_page option exists" do before do @criteria = Mongoid::Criteria.new(Person).extras({ :per_page => 10 }) end it "returns the per_page option" do @criteria.per_page.should == 10 end end context "when the per_page option does not exist" do before do @criteria = Mongoid::Criteria.new(Person) end it "returns 1" do @criteria.per_page.should == 20 end end end describe "#select" do context "when args are provided" do it "adds the options for limiting by fields" do @criteria.select(:title, :text) @criteria.options.should == { :fields => [ :title, :text ] } end it "returns self" do @criteria.select.should == @criteria end end context "when no args provided" do it "does not add the field option" do @criteria.select @criteria.options[:fields].should be_nil end end end describe "#skip" do context "when value provided" do it "adds the skip value to the options" do @criteria.skip(20) @criteria.options.should == { :skip => 20 } end end context "when value not provided" do it "defaults to zero" do @criteria.skip @criteria.options.should == { :skip => 0 } end end it "returns self" do @criteria.skip.should == @criteria end end describe ".translate" do context "with a single argument" do before do @id = Mongo::ObjectID.new.to_s @document = stub @criteria = mock Mongoid::Criteria.expects(:new).returns(@criteria) @criteria.expects(:id).with(@id).returns(@criteria) @criteria.expects(:one).returns(@document) end it "creates a criteria for a string" do Mongoid::Criteria.translate(Person, @id) end end context "multiple arguments" do context "when Person, :conditions => {}" do before do @criteria = Mongoid::Criteria.translate(Person, :conditions => { :title => "Test" }) end it "returns a criteria with a selector from the conditions" do @criteria.selector.should == { :title => "Test" } end it "returns a criteria with klass Person" do @criteria.klass.should == Person end end context "when :all, :conditions => {}" do before do @criteria = Mongoid::Criteria.translate(Person, :conditions => { :title => "Test" }) end it "returns a criteria with a selector from the conditions" do @criteria.selector.should == { :title => "Test" } end it "returns a criteria with klass Person" do @criteria.klass.should == Person end end context "when :last, :conditions => {}" do before do @criteria = Mongoid::Criteria.translate(Person, :conditions => { :title => "Test" }) end it "returns a criteria with a selector from the conditions" do @criteria.selector.should == { :title => "Test" } end it "returns a criteria with klass Person" do @criteria.klass.should == Person end end context "when options are provided" do before do @criteria = Mongoid::Criteria.translate(Person, :conditions => { :title => "Test" }, :skip => 10) end it "adds the criteria and the options" do @criteria.selector.should == { :title => "Test" } @criteria.options.should == { :skip => 10 } end end end end describe "#where" do context "when provided a hash" do it "adds the clause to the selector" do @criteria.where(:title => "Title", :text => "Text") @criteria.selector.should == { :title => "Title", :text => "Text" } end end context "when provided a string" do it "adds the $where clause to the selector" do @criteria.where("this.date < new Date()") @criteria.selector.should == { "$where" => "this.date < new Date()" } end end it "returns self" do @criteria.where.should == @criteria end end end
require "foreman" require "rubygems" require "spoon" if RUBY_PLATFORM == "java" class Foreman::Process attr_reader :entry attr_reader :num attr_reader :pid attr_reader :port def initialize(entry, num, port) @entry = entry @num = num @port = port end def run(pipe, basedir, environment) with_environment(environment.merge("PORT" => port.to_s)) do run_process basedir, entry.command, pipe end end def name "%s.%s" % [ entry.name, num ] end private def jruby? defined?(RUBY_PLATFORM) and RUBY_PLATFORM == "java" end def fork_with_io(command, basedir) reader, writer = IO.pipe command = replace_command_env(command) pid = if jruby? Spoon.spawnp Foreman.runner, command Spoon.spawnp Foreman.runner, "-d", basedir, command else fork do trap("INT", "IGNORE") writer.sync = true $stdout.reopen writer $stderr.reopen writer reader.close exec Foreman.runner, "-d", basedir, command end end [ reader, pid ] end def run_process(basedir, command, pipe) io, @pid = fork_with_io(command, basedir) output pipe, "started with pid %d" % @pid Thread.new do until io.eof? output pipe, io.gets end end end def output(pipe, message) pipe.puts "%s,%s" % [ name, message ] end def replace_command_env(command) command.gsub(/\$(\w+)/) { |e| ENV[e[1..-1]] } end def with_environment(environment) old_env = ENV.each_pair.inject({}) { |h,(k,v)| h.update(k => v) } environment.each { |k,v| ENV[k] = v } ret = yield ENV.clear old_env.each { |k,v| ENV[k] = v} ret end end move the spoon require into the jruby branch require "foreman" require "rubygems" class Foreman::Process attr_reader :entry attr_reader :num attr_reader :pid attr_reader :port def initialize(entry, num, port) @entry = entry @num = num @port = port end def run(pipe, basedir, environment) with_environment(environment.merge("PORT" => port.to_s)) do run_process basedir, entry.command, pipe end end def name "%s.%s" % [ entry.name, num ] end private def jruby? defined?(RUBY_PLATFORM) and RUBY_PLATFORM == "java" end def fork_with_io(command, basedir) reader, writer = IO.pipe command = replace_command_env(command) pid = if jruby? require "spoon" Spoon.spawnp Foreman.runner, "-d", basedir, command else fork do trap("INT", "IGNORE") writer.sync = true $stdout.reopen writer $stderr.reopen writer reader.close exec Foreman.runner, "-d", basedir, command end end [ reader, pid ] end def run_process(basedir, command, pipe) io, @pid = fork_with_io(command, basedir) output pipe, "started with pid %d" % @pid Thread.new do until io.eof? output pipe, io.gets end end end def output(pipe, message) pipe.puts "%s,%s" % [ name, message ] end def replace_command_env(command) command.gsub(/\$(\w+)/) { |e| ENV[e[1..-1]] } end def with_environment(environment) old_env = ENV.each_pair.inject({}) { |h,(k,v)| h.update(k => v) } environment.each { |k,v| ENV[k] = v } ret = yield ENV.clear old_env.each { |k,v| ENV[k] = v} ret end end
require "erb" require "fpm/namespace" require "fpm/package" require "fpm/errors" require "fpm/util" require "backports" require "fileutils" require "digest" # Support for debian packages (.deb files) # # This class supports both input and output of packages. class FPM::Package::Deb < FPM::Package # Map of what scripts are named. SCRIPT_MAP = { :before_install => "preinst", :after_install => "postinst", :before_remove => "prerm", :after_remove => "postrm", } unless defined?(SCRIPT_MAP) # The list of supported compression types. Default is gz (gzip) COMPRESSION_TYPES = [ "gz", "bzip2", "xz" ] option "--ignore-iteration-in-dependencies", :flag, "For '=' (equal) dependencies, allow iterations on the specified " \ "version. Default is to be specific. This option allows the same " \ "version of a package but any iteration is permitted" option "--build-depends", "DEPENDENCY", "Add DEPENDENCY as a Build-Depends" do |dep| @build_depends ||= [] @build_depends << dep end option "--pre-depends", "DEPENDENCY", "Add DEPENDENCY as a Pre-Depends" do |dep| @pre_depends ||= [] @pre_depends << dep end option "--compression", "COMPRESSION", "The compression type to use, must " \ "be one of #{COMPRESSION_TYPES.join(", ")}.", :default => "gzip" do |value| if !COMPRESSION_TYPES.include?(value) raise ArgumentError, "deb compression value of '#{value}' is invalid. " \ "Must be one of #{COMPRESSION_TYPES.join(", ")}" end value end # Take care about the case when we want custom control file but still use fpm ... option "--custom-control", "FILEPATH", "Custom version of the Debian control file." do |control| File.expand_path(control) end # Add custom debconf config file option "--config", "SCRIPTPATH", "Add SCRIPTPATH as debconf config file." do |config| File.expand_path(config) end # Add custom debconf templates file option "--templates", "FILEPATH", "Add FILEPATH as debconf templates file." do |templates| File.expand_path(templates) end option "--installed-size", "KILOBYTES", "The installed size, in kilobytes. If omitted, this will be calculated " \ "automatically" do |value| value.to_i end option "--priority", "PRIORITY", "The debian package 'priority' value.", :default => "extra" option "--user", "USER", "The owner of files in this package", :default => 'root' option "--group", "GROUP", "The group owner of files in this package", :default => 'root' option "--changelog", "FILEPATH", "Add FILEPATH as debian changelog" do |file| File.expand_path(file) end option "--recommends", "PACKAGE", "Add PACKAGE to Recommends" do |pkg| @recommends ||= [] @recommends << pkg next @recommends end option "--suggests", "PACKAGE", "Add PACKAGE to Suggests" do |pkg| @suggests ||= [] @suggests << pkg next @suggests end option "--field", "'FIELD: VALUE'", "Add custom field to the control file" do |fv| @custom_fields ||= {} field, value = fv.split(/: */, 2) @custom_fields[field] = value next @custom_fields end option "--shlibs", "SHLIBS", "Include control/shlibs content. This flag " \ "expects a string that is used as the contents of the shlibs file. " \ "See the following url for a description of this file and its format: " \ "http://www.debian.org/doc/debian-policy/ch-sharedlibs.html#s-shlibs" option "--init", "FILEPATH", "Add FILEPATH as an init script", :multivalued => true do |file| next File.expand_path(file) end option "--default", "FILEPATH", "Add FILEPATH as /etc/default configuration", :multivalued => true do |file| next File.expand_path(file) end option "--upstart", "FILEPATH", "Add FILEPATH as an upstart script", :multivalued => true do |file| next File.expand_path(file) end def initialize(*args) super(*args) attributes[:deb_priority] = "extra" end # def initialize private # Return the architecture. This will default to native if not yet set. # It will also try to use dpkg and 'uname -m' to figure out what the # native 'architecture' value should be. def architecture if @architecture.nil? or @architecture == "native" # Default architecture should be 'native' which we'll need to ask the # system about. if program_in_path?("dpkg") @architecture = %x{dpkg --print-architecture 2> /dev/null}.chomp if $?.exitstatus != 0 or @architecture.empty? # if dpkg fails or emits nothing, revert back to uname -m @architecture = %x{uname -m}.chomp end else @architecture = %x{uname -m}.chomp end end case @architecture when "x86_64" # Debian calls x86_64 "amd64" @architecture = "amd64" when "noarch" # Debian calls noarch "all" @architecture = "all" end return @architecture end # def architecture # Get the name of this package. See also FPM::Package#name # # This accessor actually modifies the name if it has some invalid or unwise # characters. def name if @name =~ /[A-Z]/ @logger.warn("Debian tools (dpkg/apt) don't do well with packages " \ "that use capital letters in the name. In some cases it will " \ "automatically downcase them, in others it will not. It is confusing." \ " Best to not use any capital letters at all. I have downcased the " \ "package name for you just to be safe.", :oldname => @name, :fixedname => @name.downcase) @name = @name.downcase end if @name.include?("_") @logger.info("Debian package names cannot include underscores; " \ "automatically converting to dashes", :name => @name) @name = @name.gsub(/[_]/, "-") end return @name end # def name def prefix return (attributes[:prefix] or "/") end # def prefix def input(input_path) extract_info(input_path) extract_files(input_path) end # def input def extract_info(package) with(build_path("control")) do |path| FileUtils.mkdir(path) if !File.directory?(path) # Unpack the control tarball safesystem("ar p #{package} control.tar.gz | tar -zxf - -C #{path}") control = File.read(File.join(path, "control")) parse = lambda do |field| value = control[/^#{field.capitalize}: .*/] if value.nil? return nil else @logger.info("deb field", field => value.split(": ", 2).last) return value.split(": ",2).last end end # Parse 'epoch:version-iteration' in the version string version_re = /^(?:([0-9]+):)?(.+?)(?:-(.*))?$/ m = version_re.match(parse.call("Version")) if !m raise "Unsupported version string '#{parse.call("Version")}'" end self.epoch, self.version, self.iteration = m.captures self.architecture = parse.call("Architecture") self.category = parse.call("Section") self.license = parse.call("License") || self.license self.maintainer = parse.call("Maintainer") self.name = parse.call("Package") self.url = parse.call("Homepage") self.vendor = parse.call("Vendor") || self.vendor self.provides = parse.call("Provides") || self.provides # The description field is a special flower, parse it that way. # The description is the first line as a normal Description field, but also continues # on future lines indented by one space, until the end of the file. Blank # lines are marked as ' .' description = control[/^Description: .*/m].split(": ", 2).last self.description = description.gsub(/^ /, "").gsub(/^\.$/, "") #self.config_files = config_files self.dependencies += parse_depends(parse.call("Depends")) if !attributes[:no_auto_depends?] end end # def extract_info # Parse a 'depends' line from a debian control file. # # The expected input 'data' should be everything after the 'Depends: ' string # # Example: # # parse_depends("foo (>= 3), bar (= 5), baz") def parse_depends(data) return [] if data.nil? or data.empty? # parse dependencies. Debian dependencies come in one of two forms: # * name # * name (op version) # They are all on one line, separated by ", " dep_re = /^([^ ]+)(?: \(([>=<]+) ([^)]+)\))?$/ return data.split(/, */).collect do |dep| m = dep_re.match(dep) if m name, op, version = m.captures # deb uses ">>" and "<<" for greater and less than respectively. # fpm wants just ">" and "<" op = "<" if op == "<<" op = ">" if op == ">>" # this is the proper form of dependency "#{name} #{op} #{version}" else # Assume normal form dependency, "name op version". dep end end end # def parse_depends def extract_files(package) # Find out the compression type compression = `ar t #{package}`.split("\n").grep(/data.tar/).first.split(".").last case compression when "gz" datatar = "data.tar.gz" compression = "-z" when "bzip2" datatar = "data.tar.bz2" compression = "-j" when "xz" datatar = "data.tar.xz" compression = "-J" else raise FPM::InvalidPackageConfiguration, "Unknown compression type '#{self.attributes[:deb_compression]}' " "in deb source package #{package}" end # unpack the data.tar.{gz,bz2,xz} from the deb package into staging_path safesystem("ar p #{package} #{datatar} " \ "| tar #{compression} -xf - -C #{staging_path}") end # def extract_files def output(output_path) output_check(output_path) # Abort if the target path already exists. # create 'debian-binary' file, required to make a valid debian package File.write(build_path("debian-binary"), "2.0\n") # If we are given --deb-shlibs but no --after-install script, we # should implicitly create a before/after scripts that run ldconfig if attributes[:deb_shlibs] if !script?(:after_install) @logger.info("You gave --deb-shlibs but no --after-install, so " \ "I am adding an after-install script that runs " \ "ldconfig to update the system library cache") scripts[:after_install] = template("deb/ldconfig.sh.erb").result(binding) end if !script?(:after_remove) @logger.info("You gave --deb-shlibs but no --after-remove, so " \ "I am adding an after-remove script that runs " \ "ldconfig to update the system library cache") scripts[:after_remove] = template("deb/ldconfig.sh.erb").result(binding) end end write_control_tarball # Tar up the staging_path into data.tar.{compression type} case self.attributes[:deb_compression] when "gzip", nil datatar = build_path("data.tar.gz") compression = "-z" when "bzip2" datatar = build_path("data.tar.bz2") compression = "-j" when "xz" datatar = build_path("data.tar.xz") compression = "-J" else raise FPM::InvalidPackageConfiguration, "Unknown compression type '#{self.attributes[:deb_compression]}'" end tar_flags = [] if !attributes[:deb_user].nil? if attributes[:deb_user] == 'root' tar_flags += [ "--numeric-owner", "--owner", "0" ] else tar_flags += [ "--owner", attributes[:deb_user] ] end end if !attributes[:deb_group].nil? if attributes[:deb_group] == 'root' tar_flags += [ "--numeric-owner", "--group", "0" ] else tar_flags += [ "--group", attributes[:deb_group] ] end end if attributes[:deb_changelog] dest_changelog = File.join(staging_path, "usr/share/doc/#{name}/changelog.Debian") FileUtils.mkdir_p(File.dirname(dest_changelog)) FileUtils.cp attributes[:deb_changelog], dest_changelog File.chmod(0644, dest_changelog) safesystem("gzip", dest_changelog) end attributes.fetch(:deb_init_list, []).each do |init| name = File.basename(init, ".init") dest_init = File.join(staging_path, "etc/init.d/#{name}") FileUtils.mkdir_p(File.dirname(dest_init)) FileUtils.cp init, dest_init File.chmod(0755, dest_init) end attributes.fetch(:deb_default_list, []).each do |default| name = File.basename(default, ".default") dest_default = File.join(staging_path, "etc/default/#{name}") FileUtils.mkdir_p(File.dirname(dest_default)) FileUtils.cp default, dest_default File.chmod(0644, dest_default) end attributes.fetch(:deb_upstart_list, []).each do |upstart| name = File.basename(upstart, ".upstart") dest_upstart = staging_path("etc/init/#{name}.conf") FileUtils.mkdir_p(File.dirname(dest_upstart)) FileUtils.cp(upstart, dest_upstart) File.chmod(0644, dest_upstart) # Install an init.d shim that calls upstart dest_init = staging_path("/etc/init.d/#{name}") FileUtils.mkdir_p(File.dirname(dest_init)) FileUtils.ln_s("/lib/init/upstart-job", dest_init) end args = [ tar_cmd, "-C", staging_path, compression ] + tar_flags + [ "-cf", datatar, "." ] safesystem(*args) # pack up the .deb, which is just an 'ar' archive with 3 files # the 'debian-binary' file has to be first with(File.expand_path(output_path)) do |output_path| ::Dir.chdir(build_path) do safesystem("ar", "-qc", output_path, "debian-binary", "control.tar.gz", datatar) end end @logger.log("Created deb package", :path => output_path) end # def output def converted_from(origin) self.dependencies = self.dependencies.collect do |dep| fix_dependency(dep) end.flatten end # def converted_from def debianize_op(op) # Operators in debian packaging are <<, <=, =, >= and >> # So any operator like < or > must be replaced {:< => "<<", :> => ">>"}[op.to_sym] or op end def fix_dependency(dep) # Deb dependencies are: NAME (OP VERSION), like "zsh (> 3.0)" # Convert anything that looks like 'NAME OP VERSION' to this format. if dep =~ /[\(,\|]/ # Don't "fix" ones that could appear well formed already. else # Convert ones that appear to be 'name op version' name, op, version = dep.split(/ +/) if !version.nil? # Convert strings 'foo >= bar' to 'foo (>= bar)' dep = "#{name} (#{debianize_op(op)} #{version})" end end name_re = /^[^ \(]+/ name = dep[name_re] if name =~ /[A-Z]/ @logger.warn("Downcasing dependency '#{name}' because deb packages " \ " don't work so good with uppercase names") dep = dep.gsub(name_re) { |n| n.downcase } end if dep.include?("_") @logger.warn("Replacing underscores with dashes in '#{dep}' because " \ "debs don't like underscores") dep = dep.gsub("_", "-") end # Convert gem ~> X.Y.Z to '>= X.Y.Z' and << X.Y+1.0 if dep =~ /\(~>/ name, version = dep.gsub(/[()~>]/, "").split(/ +/)[0..1] nextversion = version.split(".").collect { |v| v.to_i } l = nextversion.length nextversion[l-2] += 1 nextversion[l-1] = 0 nextversion = nextversion.join(".") return ["#{name} (>= #{version})", "#{name} (<< #{nextversion})"] elsif (m = dep.match(/(\S+)\s+\(!= (.+)\)/)) # Move '!=' dependency specifications into 'Breaks' self.attributes[:deb_breaks] ||= [] self.attributes[:deb_breaks] << dep.gsub(/!=/,"=") return [] elsif (m = dep.match(/(\S+)\s+\(= (.+)\)/)) and self.attributes[:deb_ignore_iteration_in_dependencies?] # Convert 'foo (= x)' to 'foo (>= x)' and 'foo (<< x+1)' # but only when flag --ignore-iteration-in-dependencies is passed. name, version = m[1..2] nextversion = version.split('.').collect { |v| v.to_i } nextversion[-1] += 1 nextversion = nextversion.join(".") return ["#{name} (>= #{version})", "#{name} (<< #{nextversion})"] elsif (m = dep.match(/(\S+)\s+\(> (.+)\)/)) # Convert 'foo (> x) to 'foo (>> x)' name, version = m[1..2] return ["#{name} (>> #{version})"] else # otherwise the dep is probably fine return dep.rstrip end end # def fix_dependency def control_path(path=nil) @control_path ||= build_path("control") FileUtils.mkdir(@control_path) if !File.directory?(@control_path) if path.nil? return @control_path else return File.join(@control_path, path) end end # def control_path def write_control_tarball # Use custom Debian control file when given ... write_control # write the control file write_shlibs # write optional shlibs file write_scripts # write the maintainer scripts write_conffiles # write the conffiles write_debconf # write the debconf files write_md5sums # write the md5sums file # Make the control.tar.gz with(build_path("control.tar.gz")) do |controltar| @logger.info("Creating", :path => controltar, :from => control_path) args = [ tar_cmd, "-C", control_path, "-zcf", controltar, "--owner=0", "--group=0", "--numeric-owner", "." ] safesystem(*args) end @logger.debug("Removing no longer needed control dir", :path => control_path) ensure FileUtils.rm_r(control_path) end # def write_control_tarball def write_control # warn user if epoch is set @logger.warn("epoch in Version is set", :epoch => self.epoch) if self.epoch # calculate installed-size if necessary: if attributes[:deb_installed_size].nil? @logger.info("No deb_installed_size set, calculating now.") total = 0 Find.find(staging_path) do |path| stat = File.lstat(path) next if stat.directory? total += stat.size end # Per http://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-Installed-Size # "The disk space is given as the integer value of the estimated # installed size in bytes, divided by 1024 and rounded up." attributes[:deb_installed_size] = total / 1024 end # Write the control file with(control_path("control")) do |control| if attributes[:deb_custom_control] @logger.debug("Using '#{attributes[:deb_custom_control]}' template for the control file") control_data = File.read(attributes[:deb_custom_control]) else @logger.debug("Using 'deb.erb' template for the control file") control_data = template("deb.erb").result(binding) end @logger.debug("Writing control file", :path => control) File.write(control, control_data) edit_file(control) if attributes[:edit?] end end # def write_control # Write out the maintainer scripts # # SCRIPT_MAP is a map from the package ':after_install' to debian # 'post_install' names def write_scripts SCRIPT_MAP.each do |scriptname, filename| next unless script?(scriptname) with(control_path(filename)) do |controlscript| @logger.debug("Writing control script", :source => filename, :target => controlscript) File.write(controlscript, script(scriptname)) # deb maintainer scripts are required to be executable File.chmod(0755, controlscript) end end end # def write_scripts def write_conffiles return unless config_files.any? # scan all conf file paths for files and add them allconfigs = [] config_files.each do |path| cfg_path = File.expand_path(path, staging_path) begin Find.find(cfg_path) do |p| allconfigs << p.gsub("#{staging_path}/", '') if File.file? p end rescue Errno::ENOENT => e raise FPM::InvalidPackageConfiguration, "Error trying to use '#{cfg_path}' as a config file in the package. Does it exist?" end end allconfigs.sort!.uniq! File.open(control_path("conffiles"), "w") do |out| # 'config_files' comes from FPM::Package and is usually set with # FPM::Command's --config-files flag allconfigs.each { |cf| out.puts(cf) } end end # def write_conffiles def write_shlibs return unless attributes[:deb_shlibs] @logger.info("Adding shlibs", :content => attributes[:deb_shlibs]) File.open(control_path("shlibs"), "w") do |out| out.write(attributes[:deb_shlibs]) end end # def write_shlibs def write_debconf if attributes[:deb_config] FileUtils.cp(attributes[:deb_config], control_path("config")) File.chmod(0755, control_path("config")) end if attributes[:deb_templates] FileUtils.cp(attributes[:deb_templates], control_path("templates")) File.chmod(0755, control_path("templates")) end end # def write_debconf def write_md5sums md5_sums = {} Find.find(staging_path) do |path| if File.file?(path) && !File.symlink?(path) md5 = Digest::MD5.file(path).hexdigest md5_path = path.gsub("#{staging_path}/", "") md5_sums[md5_path] = md5 end end if not md5_sums.empty? File.open(control_path("md5sums"), "w") do |out| md5_sums.each do |path, md5| out.puts "#{md5} #{path}" end end end end # def write_md5sums def to_s(format=nil) # Default format if nil # git_1.7.9.3-1_amd64.deb return super("NAME_FULLVERSION_ARCH.TYPE") if format.nil? return super(format) end # def to_s public(:input, :output, :architecture, :name, :prefix, :converted_from, :to_s) end # class FPM::Target::Deb Correct permissions for `md5sums`. require "erb" require "fpm/namespace" require "fpm/package" require "fpm/errors" require "fpm/util" require "backports" require "fileutils" require "digest" # Support for debian packages (.deb files) # # This class supports both input and output of packages. class FPM::Package::Deb < FPM::Package # Map of what scripts are named. SCRIPT_MAP = { :before_install => "preinst", :after_install => "postinst", :before_remove => "prerm", :after_remove => "postrm", } unless defined?(SCRIPT_MAP) # The list of supported compression types. Default is gz (gzip) COMPRESSION_TYPES = [ "gz", "bzip2", "xz" ] option "--ignore-iteration-in-dependencies", :flag, "For '=' (equal) dependencies, allow iterations on the specified " \ "version. Default is to be specific. This option allows the same " \ "version of a package but any iteration is permitted" option "--build-depends", "DEPENDENCY", "Add DEPENDENCY as a Build-Depends" do |dep| @build_depends ||= [] @build_depends << dep end option "--pre-depends", "DEPENDENCY", "Add DEPENDENCY as a Pre-Depends" do |dep| @pre_depends ||= [] @pre_depends << dep end option "--compression", "COMPRESSION", "The compression type to use, must " \ "be one of #{COMPRESSION_TYPES.join(", ")}.", :default => "gzip" do |value| if !COMPRESSION_TYPES.include?(value) raise ArgumentError, "deb compression value of '#{value}' is invalid. " \ "Must be one of #{COMPRESSION_TYPES.join(", ")}" end value end # Take care about the case when we want custom control file but still use fpm ... option "--custom-control", "FILEPATH", "Custom version of the Debian control file." do |control| File.expand_path(control) end # Add custom debconf config file option "--config", "SCRIPTPATH", "Add SCRIPTPATH as debconf config file." do |config| File.expand_path(config) end # Add custom debconf templates file option "--templates", "FILEPATH", "Add FILEPATH as debconf templates file." do |templates| File.expand_path(templates) end option "--installed-size", "KILOBYTES", "The installed size, in kilobytes. If omitted, this will be calculated " \ "automatically" do |value| value.to_i end option "--priority", "PRIORITY", "The debian package 'priority' value.", :default => "extra" option "--user", "USER", "The owner of files in this package", :default => 'root' option "--group", "GROUP", "The group owner of files in this package", :default => 'root' option "--changelog", "FILEPATH", "Add FILEPATH as debian changelog" do |file| File.expand_path(file) end option "--recommends", "PACKAGE", "Add PACKAGE to Recommends" do |pkg| @recommends ||= [] @recommends << pkg next @recommends end option "--suggests", "PACKAGE", "Add PACKAGE to Suggests" do |pkg| @suggests ||= [] @suggests << pkg next @suggests end option "--field", "'FIELD: VALUE'", "Add custom field to the control file" do |fv| @custom_fields ||= {} field, value = fv.split(/: */, 2) @custom_fields[field] = value next @custom_fields end option "--shlibs", "SHLIBS", "Include control/shlibs content. This flag " \ "expects a string that is used as the contents of the shlibs file. " \ "See the following url for a description of this file and its format: " \ "http://www.debian.org/doc/debian-policy/ch-sharedlibs.html#s-shlibs" option "--init", "FILEPATH", "Add FILEPATH as an init script", :multivalued => true do |file| next File.expand_path(file) end option "--default", "FILEPATH", "Add FILEPATH as /etc/default configuration", :multivalued => true do |file| next File.expand_path(file) end option "--upstart", "FILEPATH", "Add FILEPATH as an upstart script", :multivalued => true do |file| next File.expand_path(file) end def initialize(*args) super(*args) attributes[:deb_priority] = "extra" end # def initialize private # Return the architecture. This will default to native if not yet set. # It will also try to use dpkg and 'uname -m' to figure out what the # native 'architecture' value should be. def architecture if @architecture.nil? or @architecture == "native" # Default architecture should be 'native' which we'll need to ask the # system about. if program_in_path?("dpkg") @architecture = %x{dpkg --print-architecture 2> /dev/null}.chomp if $?.exitstatus != 0 or @architecture.empty? # if dpkg fails or emits nothing, revert back to uname -m @architecture = %x{uname -m}.chomp end else @architecture = %x{uname -m}.chomp end end case @architecture when "x86_64" # Debian calls x86_64 "amd64" @architecture = "amd64" when "noarch" # Debian calls noarch "all" @architecture = "all" end return @architecture end # def architecture # Get the name of this package. See also FPM::Package#name # # This accessor actually modifies the name if it has some invalid or unwise # characters. def name if @name =~ /[A-Z]/ @logger.warn("Debian tools (dpkg/apt) don't do well with packages " \ "that use capital letters in the name. In some cases it will " \ "automatically downcase them, in others it will not. It is confusing." \ " Best to not use any capital letters at all. I have downcased the " \ "package name for you just to be safe.", :oldname => @name, :fixedname => @name.downcase) @name = @name.downcase end if @name.include?("_") @logger.info("Debian package names cannot include underscores; " \ "automatically converting to dashes", :name => @name) @name = @name.gsub(/[_]/, "-") end return @name end # def name def prefix return (attributes[:prefix] or "/") end # def prefix def input(input_path) extract_info(input_path) extract_files(input_path) end # def input def extract_info(package) with(build_path("control")) do |path| FileUtils.mkdir(path) if !File.directory?(path) # Unpack the control tarball safesystem("ar p #{package} control.tar.gz | tar -zxf - -C #{path}") control = File.read(File.join(path, "control")) parse = lambda do |field| value = control[/^#{field.capitalize}: .*/] if value.nil? return nil else @logger.info("deb field", field => value.split(": ", 2).last) return value.split(": ",2).last end end # Parse 'epoch:version-iteration' in the version string version_re = /^(?:([0-9]+):)?(.+?)(?:-(.*))?$/ m = version_re.match(parse.call("Version")) if !m raise "Unsupported version string '#{parse.call("Version")}'" end self.epoch, self.version, self.iteration = m.captures self.architecture = parse.call("Architecture") self.category = parse.call("Section") self.license = parse.call("License") || self.license self.maintainer = parse.call("Maintainer") self.name = parse.call("Package") self.url = parse.call("Homepage") self.vendor = parse.call("Vendor") || self.vendor self.provides = parse.call("Provides") || self.provides # The description field is a special flower, parse it that way. # The description is the first line as a normal Description field, but also continues # on future lines indented by one space, until the end of the file. Blank # lines are marked as ' .' description = control[/^Description: .*/m].split(": ", 2).last self.description = description.gsub(/^ /, "").gsub(/^\.$/, "") #self.config_files = config_files self.dependencies += parse_depends(parse.call("Depends")) if !attributes[:no_auto_depends?] end end # def extract_info # Parse a 'depends' line from a debian control file. # # The expected input 'data' should be everything after the 'Depends: ' string # # Example: # # parse_depends("foo (>= 3), bar (= 5), baz") def parse_depends(data) return [] if data.nil? or data.empty? # parse dependencies. Debian dependencies come in one of two forms: # * name # * name (op version) # They are all on one line, separated by ", " dep_re = /^([^ ]+)(?: \(([>=<]+) ([^)]+)\))?$/ return data.split(/, */).collect do |dep| m = dep_re.match(dep) if m name, op, version = m.captures # deb uses ">>" and "<<" for greater and less than respectively. # fpm wants just ">" and "<" op = "<" if op == "<<" op = ">" if op == ">>" # this is the proper form of dependency "#{name} #{op} #{version}" else # Assume normal form dependency, "name op version". dep end end end # def parse_depends def extract_files(package) # Find out the compression type compression = `ar t #{package}`.split("\n").grep(/data.tar/).first.split(".").last case compression when "gz" datatar = "data.tar.gz" compression = "-z" when "bzip2" datatar = "data.tar.bz2" compression = "-j" when "xz" datatar = "data.tar.xz" compression = "-J" else raise FPM::InvalidPackageConfiguration, "Unknown compression type '#{self.attributes[:deb_compression]}' " "in deb source package #{package}" end # unpack the data.tar.{gz,bz2,xz} from the deb package into staging_path safesystem("ar p #{package} #{datatar} " \ "| tar #{compression} -xf - -C #{staging_path}") end # def extract_files def output(output_path) output_check(output_path) # Abort if the target path already exists. # create 'debian-binary' file, required to make a valid debian package File.write(build_path("debian-binary"), "2.0\n") # If we are given --deb-shlibs but no --after-install script, we # should implicitly create a before/after scripts that run ldconfig if attributes[:deb_shlibs] if !script?(:after_install) @logger.info("You gave --deb-shlibs but no --after-install, so " \ "I am adding an after-install script that runs " \ "ldconfig to update the system library cache") scripts[:after_install] = template("deb/ldconfig.sh.erb").result(binding) end if !script?(:after_remove) @logger.info("You gave --deb-shlibs but no --after-remove, so " \ "I am adding an after-remove script that runs " \ "ldconfig to update the system library cache") scripts[:after_remove] = template("deb/ldconfig.sh.erb").result(binding) end end write_control_tarball # Tar up the staging_path into data.tar.{compression type} case self.attributes[:deb_compression] when "gzip", nil datatar = build_path("data.tar.gz") compression = "-z" when "bzip2" datatar = build_path("data.tar.bz2") compression = "-j" when "xz" datatar = build_path("data.tar.xz") compression = "-J" else raise FPM::InvalidPackageConfiguration, "Unknown compression type '#{self.attributes[:deb_compression]}'" end tar_flags = [] if !attributes[:deb_user].nil? if attributes[:deb_user] == 'root' tar_flags += [ "--numeric-owner", "--owner", "0" ] else tar_flags += [ "--owner", attributes[:deb_user] ] end end if !attributes[:deb_group].nil? if attributes[:deb_group] == 'root' tar_flags += [ "--numeric-owner", "--group", "0" ] else tar_flags += [ "--group", attributes[:deb_group] ] end end if attributes[:deb_changelog] dest_changelog = File.join(staging_path, "usr/share/doc/#{name}/changelog.Debian") FileUtils.mkdir_p(File.dirname(dest_changelog)) FileUtils.cp attributes[:deb_changelog], dest_changelog File.chmod(0644, dest_changelog) safesystem("gzip", dest_changelog) end attributes.fetch(:deb_init_list, []).each do |init| name = File.basename(init, ".init") dest_init = File.join(staging_path, "etc/init.d/#{name}") FileUtils.mkdir_p(File.dirname(dest_init)) FileUtils.cp init, dest_init File.chmod(0755, dest_init) end attributes.fetch(:deb_default_list, []).each do |default| name = File.basename(default, ".default") dest_default = File.join(staging_path, "etc/default/#{name}") FileUtils.mkdir_p(File.dirname(dest_default)) FileUtils.cp default, dest_default File.chmod(0644, dest_default) end attributes.fetch(:deb_upstart_list, []).each do |upstart| name = File.basename(upstart, ".upstart") dest_upstart = staging_path("etc/init/#{name}.conf") FileUtils.mkdir_p(File.dirname(dest_upstart)) FileUtils.cp(upstart, dest_upstart) File.chmod(0644, dest_upstart) # Install an init.d shim that calls upstart dest_init = staging_path("/etc/init.d/#{name}") FileUtils.mkdir_p(File.dirname(dest_init)) FileUtils.ln_s("/lib/init/upstart-job", dest_init) end args = [ tar_cmd, "-C", staging_path, compression ] + tar_flags + [ "-cf", datatar, "." ] safesystem(*args) # pack up the .deb, which is just an 'ar' archive with 3 files # the 'debian-binary' file has to be first with(File.expand_path(output_path)) do |output_path| ::Dir.chdir(build_path) do safesystem("ar", "-qc", output_path, "debian-binary", "control.tar.gz", datatar) end end @logger.log("Created deb package", :path => output_path) end # def output def converted_from(origin) self.dependencies = self.dependencies.collect do |dep| fix_dependency(dep) end.flatten end # def converted_from def debianize_op(op) # Operators in debian packaging are <<, <=, =, >= and >> # So any operator like < or > must be replaced {:< => "<<", :> => ">>"}[op.to_sym] or op end def fix_dependency(dep) # Deb dependencies are: NAME (OP VERSION), like "zsh (> 3.0)" # Convert anything that looks like 'NAME OP VERSION' to this format. if dep =~ /[\(,\|]/ # Don't "fix" ones that could appear well formed already. else # Convert ones that appear to be 'name op version' name, op, version = dep.split(/ +/) if !version.nil? # Convert strings 'foo >= bar' to 'foo (>= bar)' dep = "#{name} (#{debianize_op(op)} #{version})" end end name_re = /^[^ \(]+/ name = dep[name_re] if name =~ /[A-Z]/ @logger.warn("Downcasing dependency '#{name}' because deb packages " \ " don't work so good with uppercase names") dep = dep.gsub(name_re) { |n| n.downcase } end if dep.include?("_") @logger.warn("Replacing underscores with dashes in '#{dep}' because " \ "debs don't like underscores") dep = dep.gsub("_", "-") end # Convert gem ~> X.Y.Z to '>= X.Y.Z' and << X.Y+1.0 if dep =~ /\(~>/ name, version = dep.gsub(/[()~>]/, "").split(/ +/)[0..1] nextversion = version.split(".").collect { |v| v.to_i } l = nextversion.length nextversion[l-2] += 1 nextversion[l-1] = 0 nextversion = nextversion.join(".") return ["#{name} (>= #{version})", "#{name} (<< #{nextversion})"] elsif (m = dep.match(/(\S+)\s+\(!= (.+)\)/)) # Move '!=' dependency specifications into 'Breaks' self.attributes[:deb_breaks] ||= [] self.attributes[:deb_breaks] << dep.gsub(/!=/,"=") return [] elsif (m = dep.match(/(\S+)\s+\(= (.+)\)/)) and self.attributes[:deb_ignore_iteration_in_dependencies?] # Convert 'foo (= x)' to 'foo (>= x)' and 'foo (<< x+1)' # but only when flag --ignore-iteration-in-dependencies is passed. name, version = m[1..2] nextversion = version.split('.').collect { |v| v.to_i } nextversion[-1] += 1 nextversion = nextversion.join(".") return ["#{name} (>= #{version})", "#{name} (<< #{nextversion})"] elsif (m = dep.match(/(\S+)\s+\(> (.+)\)/)) # Convert 'foo (> x) to 'foo (>> x)' name, version = m[1..2] return ["#{name} (>> #{version})"] else # otherwise the dep is probably fine return dep.rstrip end end # def fix_dependency def control_path(path=nil) @control_path ||= build_path("control") FileUtils.mkdir(@control_path) if !File.directory?(@control_path) if path.nil? return @control_path else return File.join(@control_path, path) end end # def control_path def write_control_tarball # Use custom Debian control file when given ... write_control # write the control file write_shlibs # write optional shlibs file write_scripts # write the maintainer scripts write_conffiles # write the conffiles write_debconf # write the debconf files write_md5sums # write the md5sums file # Make the control.tar.gz with(build_path("control.tar.gz")) do |controltar| @logger.info("Creating", :path => controltar, :from => control_path) args = [ tar_cmd, "-C", control_path, "-zcf", controltar, "--owner=0", "--group=0", "--numeric-owner", "." ] safesystem(*args) end @logger.debug("Removing no longer needed control dir", :path => control_path) ensure FileUtils.rm_r(control_path) end # def write_control_tarball def write_control # warn user if epoch is set @logger.warn("epoch in Version is set", :epoch => self.epoch) if self.epoch # calculate installed-size if necessary: if attributes[:deb_installed_size].nil? @logger.info("No deb_installed_size set, calculating now.") total = 0 Find.find(staging_path) do |path| stat = File.lstat(path) next if stat.directory? total += stat.size end # Per http://www.debian.org/doc/debian-policy/ch-controlfields.html#s-f-Installed-Size # "The disk space is given as the integer value of the estimated # installed size in bytes, divided by 1024 and rounded up." attributes[:deb_installed_size] = total / 1024 end # Write the control file with(control_path("control")) do |control| if attributes[:deb_custom_control] @logger.debug("Using '#{attributes[:deb_custom_control]}' template for the control file") control_data = File.read(attributes[:deb_custom_control]) else @logger.debug("Using 'deb.erb' template for the control file") control_data = template("deb.erb").result(binding) end @logger.debug("Writing control file", :path => control) File.write(control, control_data) edit_file(control) if attributes[:edit?] end end # def write_control # Write out the maintainer scripts # # SCRIPT_MAP is a map from the package ':after_install' to debian # 'post_install' names def write_scripts SCRIPT_MAP.each do |scriptname, filename| next unless script?(scriptname) with(control_path(filename)) do |controlscript| @logger.debug("Writing control script", :source => filename, :target => controlscript) File.write(controlscript, script(scriptname)) # deb maintainer scripts are required to be executable File.chmod(0755, controlscript) end end end # def write_scripts def write_conffiles return unless config_files.any? # scan all conf file paths for files and add them allconfigs = [] config_files.each do |path| cfg_path = File.expand_path(path, staging_path) begin Find.find(cfg_path) do |p| allconfigs << p.gsub("#{staging_path}/", '') if File.file? p end rescue Errno::ENOENT => e raise FPM::InvalidPackageConfiguration, "Error trying to use '#{cfg_path}' as a config file in the package. Does it exist?" end end allconfigs.sort!.uniq! File.open(control_path("conffiles"), "w") do |out| # 'config_files' comes from FPM::Package and is usually set with # FPM::Command's --config-files flag allconfigs.each { |cf| out.puts(cf) } end end # def write_conffiles def write_shlibs return unless attributes[:deb_shlibs] @logger.info("Adding shlibs", :content => attributes[:deb_shlibs]) File.open(control_path("shlibs"), "w") do |out| out.write(attributes[:deb_shlibs]) end end # def write_shlibs def write_debconf if attributes[:deb_config] FileUtils.cp(attributes[:deb_config], control_path("config")) File.chmod(0755, control_path("config")) end if attributes[:deb_templates] FileUtils.cp(attributes[:deb_templates], control_path("templates")) File.chmod(0755, control_path("templates")) end end # def write_debconf def write_md5sums md5_sums = {} Find.find(staging_path) do |path| if File.file?(path) && !File.symlink?(path) md5 = Digest::MD5.file(path).hexdigest md5_path = path.gsub("#{staging_path}/", "") md5_sums[md5_path] = md5 end end if not md5_sums.empty? File.open(control_path("md5sums"), "w") do |out| md5_sums.each do |path, md5| out.puts "#{md5} #{path}" end end File.chmod(0644, control_path("md5sums")) end end # def write_md5sums def to_s(format=nil) # Default format if nil # git_1.7.9.3-1_amd64.deb return super("NAME_FULLVERSION_ARCH.TYPE") if format.nil? return super(format) end # def to_s public(:input, :output, :architecture, :name, :prefix, :converted_from, :to_s) end # class FPM::Target::Deb
require 'freshbooks/schema/mixin' require 'freshbooks/xml_serializer' module FreshBooks class Base include FreshBooks::Schema::Mixin def initialize(args = {}) args.each_pair {|k, v| send("#{k}=", v)} end @@connection = nil def self.connection @@connection end def self.establish_connection(account_url, auth_token, request_headers = {}) @@connection = Connection.new(account_url, auth_token, request_headers) end def self.new_from_xml(xml_root) object = self.new self.schema_definition.members.each do |member_name, member_options| node = xml_root.elements[member_name] next if node.nil? value = FreshBooks::XmlSerializer.to_value(node, member_options[:type]) object.send("#{member_name}=", value) end return object rescue => e raise ParseError.new(e, xml_root.to_s) end def to_xml(elem_name = nil) # The root element is the class name underscored elem_name ||= self.class.to_s.split('::').last.underscore root = REXML::Element.new(elem_name) # Add each member to the root elem self.schema_definition.members.each do |member_name, member_options| value = self.send(member_name) next if member_options[:read_only] || value.nil? element = FreshBooks::XmlSerializer.to_node(member_name, value, member_options[:type]) root.add_element(element) if element != nil end root.to_s end def primary_key "#{self.class.api_class_name}_id" end def primary_key_value send(primary_key) end def primary_key_value=(value) send("#{primary_key}=", value) end def self.api_class_name klass = class_of_freshbooks_base_descendant(self) # Remove module, underscore between words, lowercase klass.name. gsub(/^.*::/, ""). gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2'). downcase end def self.class_of_freshbooks_base_descendant(klass) if klass.superclass == Base klass elsif klass.superclass.nil? raise "#{name} doesn't belong in a hierarchy descending from ActiveRecord" else self.class_of_freshbooks_base_descendant(klass.superclass) end end def self.define_class_method(symbol, &block) self.class.send(:define_method, symbol, &block) end def self.actions(*operations) operations.each do |operation| method_name = operation.to_s api_action_name = method_name.camelize(:lower) case method_name when "list" define_class_method(method_name) do |*args| args << {} if args.empty? # first param is optional and default to empty hash api_list_action(api_action_name, *args) end when "get" define_class_method(method_name) do |object_id| api_get_action(api_action_name, object_id) end when "create" define_method(method_name) do api_create_action(api_action_name) end when "update" define_method(method_name) do api_update_action(api_action_name) end else define_method(method_name) do api_action(api_action_name) end end end end def self.api_list_action(action_name, options = {}) # Create the proc for the list proxy to retrieve the next page list_page_proc = proc do |page| options["page"] = page response = FreshBooks::Base.connection.call_api("#{api_class_name}.#{action_name}", options) raise FreshBooks::InternalError.new(response.error_msg) unless response.success? root = response.elements[1] array = root.elements.map { |item| self.new_from_xml(item) } current_page = Page.new(root.attributes['page'], root.attributes['per_page'], root.attributes['total'], array.size) [array, current_page] end ListProxy.new(list_page_proc) end def self.api_get_action(action_name, object_id) response = FreshBooks::Base.connection.call_api( "#{api_class_name}.#{action_name}", "#{api_class_name}_id" => object_id) response.success? ? self.new_from_xml(response.elements[1]) : nil end def api_action(action_name) response = FreshBooks::Base.connection.call_api( "#{self.class.api_class_name}.#{action_name}", "#{self.class.api_class_name}_id" => primary_key_value) response.success? end def api_create_action(action_name) response = FreshBooks::Base.connection.call_api( "#{self.class.api_class_name}.#{action_name}", self.class.api_class_name => self) self.primary_key_value = response.elements[1].text.to_i if response.success? response.success? end def api_update_action(action_name) response = FreshBooks::Base.connection.call_api( "#{self.class.api_class_name}.#{action_name}", self.class.api_class_name => self) response.success? end end end Fixed for Ruby 1.9.2 require 'freshbooks/schema/mixin' require 'freshbooks/xml_serializer' module FreshBooks class Base include FreshBooks::Schema::Mixin def initialize(args = {}) args.each_pair {|k, v| send("#{k}=", v)} end @@connection = nil def self.connection @@connection end def self.establish_connection(account_url, auth_token, request_headers = {}) @@connection = Connection.new(account_url, auth_token, request_headers) end def self.new_from_xml(xml_root) object = self.new() self.schema_definition.members.each do |member_name, member_options| node = xml_root.elements["//#{member_name}"] next if node.nil? value = FreshBooks::XmlSerializer.to_value(node, member_options[:type]) object.send("#{member_name}=", value) end return object rescue => e error = ParseError.new(e, xml_root.to_s) error.set_backtrace(e.backtrace) raise error # raise ParseError.new(e, xml_root.to_s) end def to_xml(elem_name = nil) # The root element is the class name underscored elem_name ||= self.class.to_s.split('::').last.underscore root = REXML::Element.new(elem_name) # Add each member to the root elem self.schema_definition.members.each do |member_name, member_options| value = self.send(member_name) next if member_options[:read_only] || value.nil? element = FreshBooks::XmlSerializer.to_node(member_name, value, member_options[:type]) root.add_element(element) if element != nil end root.to_s end def primary_key "#{self.class.api_class_name}_id" end def primary_key_value send(primary_key) end def primary_key_value=(value) send("#{primary_key}=", value) end def self.api_class_name klass = class_of_freshbooks_base_descendant(self) # Remove module, underscore between words, lowercase klass.name. gsub(/^.*::/, ""). gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2'). downcase end def self.class_of_freshbooks_base_descendant(klass) if klass.superclass == Base klass elsif klass.superclass.nil? raise "#{name} doesn't belong in a hierarchy descending from ActiveRecord" else self.class_of_freshbooks_base_descendant(klass.superclass) end end def self.define_class_method(symbol, &block) self.class.send(:define_method, symbol, &block) end def self.actions(*operations) operations.each do |operation| method_name = operation.to_s api_action_name = method_name.camelize(:lower) case method_name when "list" define_class_method(method_name) do |*args| args << {} if args.empty? # first param is optional and default to empty hash api_list_action(api_action_name, *args) end when "get" define_class_method(method_name) do |object_id| api_get_action(api_action_name, object_id) end when "create" define_method(method_name) do api_create_action(api_action_name) end when "update" define_method(method_name) do api_update_action(api_action_name) end else define_method(method_name) do api_action(api_action_name) end end end end def self.api_list_action(action_name, options = {}) # Create the proc for the list proxy to retrieve the next page list_page_proc = proc do |page| options["page"] = page response = FreshBooks::Base.connection.call_api("#{api_class_name}.#{action_name}", options) raise FreshBooks::InternalError.new(response.error_msg) unless response.success? root = response.elements[1] array = root.elements.map { |item| self.new_from_xml(item) } current_page = Page.new(root.attributes['page'], root.attributes['per_page'], root.attributes['total'], array.size) [array, current_page] end ListProxy.new(list_page_proc) end def self.api_get_action(action_name, object_id) response = FreshBooks::Base.connection.call_api( "#{api_class_name}.#{action_name}", "#{api_class_name}_id" => object_id) response.success? ? self.new_from_xml(response.elements[1]) : nil end def api_action(action_name) response = FreshBooks::Base.connection.call_api( "#{self.class.api_class_name}.#{action_name}", "#{self.class.api_class_name}_id" => primary_key_value) response.success? end def api_create_action(action_name) response = FreshBooks::Base.connection.call_api( "#{self.class.api_class_name}.#{action_name}", self.class.api_class_name => self) self.primary_key_value = response.elements[1].text.to_i if response.success? response.success? end def api_update_action(action_name) response = FreshBooks::Base.connection.call_api( "#{self.class.api_class_name}.#{action_name}", self.class.api_class_name => self) response.success? end end end
module Gatling VERSION = "1.0.7" end version 1.0.8 module Gatling VERSION = "1.0.8" end
require 'active_record' require 'attr_extras' require 'pasqual' require_relative 'geocode_records/version' require_relative 'geocode_records/dump_sql_to_csv' require_relative 'geocode_records/geocode_csv' require_relative 'geocode_records/update_table_from_csv' class GeocodeRecords attr_reader :records attr_reader :options def initialize(records, options = {}) records.is_a?(ActiveRecord::Relation) or raise(ArgumentError, "expected AR::Relation, got #{records.class}") @options = options || {} @records = records end def perform if records.count > 0 # $stderr.puts "GeocodeRecords: #{records.count} to go!" ungeocoded_path = DumpSqlToCsv.new(pasqual, to_sql, options).path geocoded_path = GeocodeCsv.new(ungeocoded_path, options).path UpdateTableFromCsv.new(connection, table_name, geocoded_path, options).perform set_the_geom File.unlink geocoded_path File.unlink ungeocoded_path end end private def glob !!options[:glob] end def set_the_geom records.update_all <<-SQL the_geom = ST_SetSRID(ST_MakePoint(longitude, latitude), 4326), the_geom_webmercator = ST_Transform(ST_SetSRID(ST_MakePoint(longitude, latitude), 4326), 3857) SQL end def to_sql c = connection c.unprepared_statement do if glob c.to_sql records.select('id', 'glob').arel, records.bind_values else c.to_sql records.select('id', 'house_number_and_street', 'house_number', 'unit_number', 'city', 'state', "left(regexp_replace(postcode, '.0$', ''), 5) AS postcode").arel, records.bind_values end end end def connection records.connection end def table_name options[:table_name] || records.engine.table_name end def pasqual @pasqual ||= Pasqual.for ENV.fetch('DATABASE_URL') end end Ensure that smartystreets is compatible before running require 'active_record' require 'attr_extras' require 'pasqual' require_relative 'geocode_records/version' require_relative 'geocode_records/dump_sql_to_csv' require_relative 'geocode_records/geocode_csv' require_relative 'geocode_records/update_table_from_csv' class GeocodeRecords attr_reader :records attr_reader :options def initialize(records, options = {}) records.is_a?(ActiveRecord::Relation) or raise(ArgumentError, "expected AR::Relation, got #{records.class}") @options = options || {} @records = records end def perform raise "smartystreets >= 1.3.2 is required" unless SmartyStreets.compatible? if records.count > 0 # $stderr.puts "GeocodeRecords: #{records.count} to go!" ungeocoded_path = DumpSqlToCsv.new(pasqual, to_sql, options).path geocoded_path = GeocodeCsv.new(ungeocoded_path, options).path UpdateTableFromCsv.new(connection, table_name, geocoded_path, options).perform set_the_geom File.unlink geocoded_path File.unlink ungeocoded_path end end private def glob !!options[:glob] end def set_the_geom records.update_all <<-SQL the_geom = ST_SetSRID(ST_MakePoint(longitude, latitude), 4326), the_geom_webmercator = ST_Transform(ST_SetSRID(ST_MakePoint(longitude, latitude), 4326), 3857) SQL end def to_sql c = connection c.unprepared_statement do if glob c.to_sql records.select('id', 'glob').arel, records.bind_values else c.to_sql records.select('id', 'house_number_and_street', 'house_number', 'unit_number', 'city', 'state', "left(regexp_replace(postcode, '.0$', ''), 5) AS postcode").arel, records.bind_values end end end def connection records.connection end def table_name options[:table_name] || records.engine.table_name end def pasqual @pasqual ||= Pasqual.for ENV.fetch('DATABASE_URL') end end
#require 'forwardable' module Geokit # Contains class and instance methods providing distance calcuation services. This # module is meant to be mixed into classes containing lat and lng attributes where # distance calculation is desired. # # At present, two forms of distance calculations are provided: # # * Pythagorean Theory (flat Earth) - which assumes the world is flat and loses accuracy over long distances. # * Haversine (sphere) - which is fairly accurate, but at a performance cost. # # Distance units supported are :miles, :kms, and :nms. module Mappable PI_DIV_RAD = 0.0174 KMS_PER_MILE = 1.609 NMS_PER_MILE = 0.868976242 EARTH_RADIUS_IN_MILES = 3963.19 EARTH_RADIUS_IN_KMS = EARTH_RADIUS_IN_MILES * KMS_PER_MILE EARTH_RADIUS_IN_NMS = EARTH_RADIUS_IN_MILES * NMS_PER_MILE MILES_PER_LATITUDE_DEGREE = 69.1 KMS_PER_LATITUDE_DEGREE = MILES_PER_LATITUDE_DEGREE * KMS_PER_MILE NMS_PER_LATITUDE_DEGREE = MILES_PER_LATITUDE_DEGREE * NMS_PER_MILE LATITUDE_DEGREES = EARTH_RADIUS_IN_MILES / MILES_PER_LATITUDE_DEGREE # Mix below class methods into the includer. def self.included(receiver) # :nodoc: receiver.extend ClassMethods end module ClassMethods #:nodoc: # Returns the distance between two points. The from and to parameters are # required to have lat and lng attributes. Valid options are: # :units - valid values are :miles, :kms, :nms (Geokit::default_units is the default) # :formula - valid values are :flat or :sphere (Geokit::default_formula is the default) def distance_between(from, to, options={}) from=Geokit::LatLng.normalize(from) to=Geokit::LatLng.normalize(to) return 0.0 if from == to # fixes a "zero-distance" bug units = options[:units] || Geokit::default_units formula = options[:formula] || Geokit::default_formula case formula when :sphere begin units_sphere_multiplier(units) * Math.acos( Math.sin(deg2rad(from.lat)) * Math.sin(deg2rad(to.lat)) + Math.cos(deg2rad(from.lat)) * Math.cos(deg2rad(to.lat)) * Math.cos(deg2rad(to.lng) - deg2rad(from.lng))) rescue Errno::EDOM 0.0 end when :flat Math.sqrt((units_per_latitude_degree(units)*(from.lat-to.lat))**2 + (units_per_longitude_degree(from.lat, units)*(from.lng-to.lng))**2) end end # Returns heading in degrees (0 is north, 90 is east, 180 is south, etc) # from the first point to the second point. Typicaly, the instance methods will be used # instead of this method. def heading_between(from,to) from=Geokit::LatLng.normalize(from) to=Geokit::LatLng.normalize(to) d_lng=deg2rad(to.lng-from.lng) from_lat=deg2rad(from.lat) to_lat=deg2rad(to.lat) y=Math.sin(d_lng) * Math.cos(to_lat) x=Math.cos(from_lat)*Math.sin(to_lat)-Math.sin(from_lat)*Math.cos(to_lat)*Math.cos(d_lng) heading=to_heading(Math.atan2(y,x)) end # Given a start point, distance, and heading (in degrees), provides # an endpoint. Returns a LatLng instance. Typically, the instance method # will be used instead of this method. def endpoint(start,heading, distance, options={}) units = options[:units] || Geokit::default_units radius = case units when :kms; EARTH_RADIUS_IN_KMS when :nms; EARTH_RADIUS_IN_NMS else EARTH_RADIUS_IN_MILES end start=Geokit::LatLng.normalize(start) lat=deg2rad(start.lat) lng=deg2rad(start.lng) heading=deg2rad(heading) distance=distance.to_f end_lat=Math.asin(Math.sin(lat)*Math.cos(distance/radius) + Math.cos(lat)*Math.sin(distance/radius)*Math.cos(heading)) end_lng=lng+Math.atan2(Math.sin(heading)*Math.sin(distance/radius)*Math.cos(lat), Math.cos(distance/radius)-Math.sin(lat)*Math.sin(end_lat)) LatLng.new(rad2deg(end_lat),rad2deg(end_lng)) end # Returns the midpoint, given two points. Returns a LatLng. # Typically, the instance method will be used instead of this method. # Valid option: # :units - valid values are :miles, :kms, or :nms (:miles is the default) def midpoint_between(from,to,options={}) from=Geokit::LatLng.normalize(from) units = options[:units] || Geokit::default_units heading=from.heading_to(to) distance=from.distance_to(to,options) midpoint=from.endpoint(heading,distance/2,options) end # Geocodes a location using the multi geocoder. def geocode(location, options = {}) res = Geocoders::MultiGeocoder.geocode(location, options) return res if res.success? raise Geokit::Geocoders::GeocodeError end protected def deg2rad(degrees) degrees.to_f / 180.0 * Math::PI end def rad2deg(rad) rad.to_f * 180.0 / Math::PI end def to_heading(rad) (rad2deg(rad)+360)%360 end # Returns the multiplier used to obtain the correct distance units. def units_sphere_multiplier(units) case units when :kms; EARTH_RADIUS_IN_KMS when :nms; EARTH_RADIUS_IN_NMS else EARTH_RADIUS_IN_MILES end end # Returns the number of units per latitude degree. def units_per_latitude_degree(units) case units when :kms; KMS_PER_LATITUDE_DEGREE when :nms; NMS_PER_LATITUDE_DEGREE else MILES_PER_LATITUDE_DEGREE end end # Returns the number units per longitude degree. def units_per_longitude_degree(lat, units) miles_per_longitude_degree = (LATITUDE_DEGREES * Math.cos(lat * PI_DIV_RAD)).abs case units when :kms; miles_per_longitude_degree * KMS_PER_MILE when :nms; miles_per_longitude_degree * NMS_PER_MILE else miles_per_longitude_degree end end end # ----------------------------------------------------------------------------------------------- # Instance methods below here # ----------------------------------------------------------------------------------------------- # Extracts a LatLng instance. Use with models that are acts_as_mappable def to_lat_lng return self if instance_of?(Geokit::LatLng) || instance_of?(Geokit::GeoLoc) return LatLng.new(send(self.class.lat_column_name),send(self.class.lng_column_name)) if self.class.respond_to?(:acts_as_mappable) nil end # Returns the distance from another point. The other point parameter is # required to have lat and lng attributes. Valid options are: # :units - valid values are :miles, :kms, :or :nms (:miles is the default) # :formula - valid values are :flat or :sphere (:sphere is the default) def distance_to(other, options={}) self.class.distance_between(self, other, options) end alias distance_from distance_to # Returns heading in degrees (0 is north, 90 is east, 180 is south, etc) # to the given point. The given point can be a LatLng or a string to be Geocoded def heading_to(other) self.class.heading_between(self,other) end # Returns heading in degrees (0 is north, 90 is east, 180 is south, etc) # FROM the given point. The given point can be a LatLng or a string to be Geocoded def heading_from(other) self.class.heading_between(other,self) end # Returns the endpoint, given a heading (in degrees) and distance. # Valid option: # :units - valid values are :miles, :kms, or :nms (:miles is the default) def endpoint(heading,distance,options={}) self.class.endpoint(self,heading,distance,options) end # Returns the midpoint, given another point on the map. # Valid option: # :units - valid values are :miles, :kms, or :nms (:miles is the default) def midpoint_to(other, options={}) self.class.midpoint_between(self,other,options) end end class LatLng include Mappable attr_accessor :lat, :lng # Accepts latitude and longitude or instantiates an empty instance # if lat and lng are not provided. Converted to floats if provided def initialize(lat=nil, lng=nil) lat = lat.to_f if lat && !lat.is_a?(Numeric) lng = lng.to_f if lng && !lng.is_a?(Numeric) @lat = lat @lng = lng end # Latitude attribute setter; stored as a float. def lat=(lat) @lat = lat.to_f if lat end # Longitude attribute setter; stored as a float; def lng=(lng) @lng=lng.to_f if lng end # Returns the lat and lng attributes as a comma-separated string. def ll "#{lat},#{lng}" end #returns a string with comma-separated lat,lng values def to_s ll end #returns a two-element array def to_a [lat,lng] end # Returns true if the candidate object is logically equal. Logical equivalence # is true if the lat and lng attributes are the same for both objects. def ==(other) other.is_a?(LatLng) ? self.lat == other.lat && self.lng == other.lng : false end def hash lat.hash + lng.hash end def eql?(other) self == other end # Returns true if both lat and lng attributes are defined def valid? self.lat and self.lng end # A *class* method to take anything which can be inferred as a point and generate # a LatLng from it. You should use this anything you're not sure what the input is, # and want to deal with it as a LatLng if at all possible. Can take: # 1) two arguments (lat,lng) # 2) a string in the format "37.1234,-129.1234" or "37.1234 -129.1234" # 3) a string which can be geocoded on the fly # 4) an array in the format [37.1234,-129.1234] # 5) a LatLng or GeoLoc (which is just passed through as-is) # 6) anything which acts_as_mappable -- a LatLng will be extracted from it def self.normalize(thing,other=nil) # if an 'other' thing is supplied, normalize the input by creating an array of two elements thing=[thing,other] if other if thing.is_a?(String) thing.strip! if match=thing.match(/(\-?\d+\.?\d*)[, ] ?(\-?\d+\.?\d*)$/) return Geokit::LatLng.new(match[1],match[2]) else res = Geokit::Geocoders::MultiGeocoder.geocode(thing) return res if res.success? raise Geokit::Geocoders::GeocodeError end elsif thing.is_a?(Array) && thing.size==2 return Geokit::LatLng.new(thing[0],thing[1]) elsif thing.is_a?(LatLng) # will also be true for GeoLocs return thing elsif thing.class.respond_to?(:acts_as_mappable) && thing.class.respond_to?(:distance_column_name) return thing.to_lat_lng elsif thing.respond_to? :to_lat_lng return thing.to_lat_lng end raise ArgumentError.new("#{thing} (#{thing.class}) cannot be normalized to a LatLng. We tried interpreting it as an array, string, Mappable, etc., but no dice.") end # Reverse geocodes a LatLng object using the MultiGeocoder (default), or optionally # using a geocoder of your choosing. Returns a new Geokit::GeoLoc object # # ==== Options # * :using - Specifies the geocoder to use for reverse geocoding. Defaults to # MultiGeocoder. Can be either the geocoder class (or any class that # implements do_reverse_geocode for that matter), or the name of # the class without the "Geocoder" part (e.g. :google) # # ==== Examples # LatLng.new(51.4578329, 7.0166848).reverse_geocode # => #<Geokit::GeoLoc:0x12dac20 @state...> # LatLng.new(51.4578329, 7.0166848).reverse_geocode(:using => :google) # => #<Geokit::GeoLoc:0x12dac20 @state...> # LatLng.new(51.4578329, 7.0166848).reverse_geocode(:using => Geokit::Geocoders::GoogleGeocoder) # => #<Geokit::GeoLoc:0x12dac20 @state...> def reverse_geocode(options = { :using => Geokit::Geocoders::MultiGeocoder }) if options[:using].is_a?(String) or options[:using].is_a?(Symbol) provider = Geokit::Geocoders.const_get("#{Geokit::Inflector::camelize(options[:using].to_s)}Geocoder") elsif options[:using].respond_to?(:do_reverse_geocode) provider = options[:using] else raise ArgumentError.new("#{options[:using]} is not a valid geocoder.") end provider.send(:reverse_geocode, self) end end # This class encapsulates the result of a geocoding call. # It's primary purpose is to homogenize the results of multiple # geocoding providers. It also provides some additional functionality, such as # the "full address" method for geocoders that do not provide a # full address in their results (for example, Yahoo), and the "is_us" method. # # Some geocoders can return multple results. Geoloc can capture multiple results through # its "all" method. # # For the geocoder setting the results, it would look something like this: # geo=GeoLoc.new(first_result) # geo.all.push(second_result) # geo.all.push(third_result) # # Then, for the user of the result: # # puts geo.full_address # just like usual # puts geo.all.size => 3 # there's three results total # puts geo.all.first # all is just an array or additional geolocs, # so do what you want with it class GeoLoc < LatLng # Location attributes. Full address is a concatenation of all values. For example: # 100 Spear St, San Francisco, CA, 94101, US # Street number and street name are extracted from the street address attribute if they don't exist attr_accessor :street_number, :street_name, :street_address, :city, :state, :zip, :country_code, :country attr_accessor :full_address, :all, :district, :province, :sub_premise # Attributes set upon return from geocoding. Success will be true for successful # geocode lookups. The provider will be set to the name of the providing geocoder. # Finally, precision is an indicator of the accuracy of the geocoding. attr_accessor :success, :provider, :precision, :suggested_bounds # accuracy is set for Yahoo and Google geocoders, it is a numeric value of the # precision. see http://code.google.com/apis/maps/documentation/geocoding/#GeocodingAccuracy attr_accessor :accuracy # FCC Attributes attr_accessor :district_fips, :state_fips, :block_fips # Constructor expects a hash of symbols to correspond with attributes. def initialize(h={}) @all = [self] @street_address=h[:street_address] @sub_premise=nil @street_number=nil @street_name=nil @city=h[:city] @state=h[:state] @zip=h[:zip] @country_code=h[:country_code] @province = h[:province] @success=false @precision='unknown' @full_address=nil super(h[:lat],h[:lng]) end # Returns true if geocoded to the United States. def is_us? country_code == 'US' end def success? success == true end # full_address is provided by google but not by yahoo. It is intended that the google # geocoding method will provide the full address, whereas for yahoo it will be derived # from the parts of the address we do have. def full_address @full_address ? @full_address : to_geocodeable_s end # Extracts the street number from the street address where possible. def street_number @street_number ||= street_address[/(\d*)/] if street_address @street_number end # Returns the street name portion of the street address where possible def street_name @street_name||=street_address[street_number.length, street_address.length].strip if street_address @street_name end # gives you all the important fields as key-value pairs def hash res={} [:success, :lat, :lng, :country_code, :city, :state, :zip, :street_address, :province, :district, :provider, :full_address, :is_us?, :ll, :precision, :district_fips, :state_fips, :block_fips, :sub_premise].each { |s| res[s] = self.send(s.to_s) } res end alias to_hash hash # Sets the city after capitalizing each word within the city name. def city=(city) @city = Geokit::Inflector::titleize(city) if city end # Sets the street address after capitalizing each word within the street address. def street_address=(address) if address and not ['google','google3'].include?(self.provider) @street_address = Geokit::Inflector::titleize(address) else @street_address = address end end # Returns a comma-delimited string consisting of the street address, city, state, # zip, and country code. Only includes those attributes that are non-blank. def to_geocodeable_s a=[street_address, district, city, province, state, zip, country_code].compact a.delete_if { |e| !e || e == '' } a.join(', ') end def to_yaml_properties (instance_variables - ['@all']).sort end # Returns a string representation of the instance. def to_s "Provider: #{provider}\nStreet: #{street_address}\nCity: #{city}\nState: #{state}\nZip: #{zip}\nLatitude: #{lat}\nLongitude: #{lng}\nCountry: #{country_code}\nSuccess: #{success}" end end # Bounds represents a rectangular bounds, defined by the SW and NE corners class Bounds # sw and ne are LatLng objects attr_accessor :sw, :ne # provide sw and ne to instantiate a new Bounds instance def initialize(sw,ne) raise ArgumentError if !(sw.is_a?(Geokit::LatLng) && ne.is_a?(Geokit::LatLng)) @sw,@ne=sw,ne end #returns the a single point which is the center of the rectangular bounds def center @sw.midpoint_to(@ne) end # a simple string representation:sw,ne def to_s "#{@sw.to_s},#{@ne.to_s}" end # a two-element array of two-element arrays: sw,ne def to_a [@sw.to_a, @ne.to_a] end # Returns true if the bounds contain the passed point. # allows for bounds which cross the meridian def contains?(point) point=Geokit::LatLng.normalize(point) res = point.lat > @sw.lat && point.lat < @ne.lat if crosses_meridian? res &= point.lng < @ne.lng || point.lng > @sw.lng else res &= point.lng < @ne.lng && point.lng > @sw.lng end res end # returns true if the bounds crosses the international dateline def crosses_meridian? @sw.lng > @ne.lng end # Returns true if the candidate object is logically equal. Logical equivalence # is true if the lat and lng attributes are the same for both objects. def ==(other) other.is_a?(Bounds) ? self.sw == other.sw && self.ne == other.ne : false end # Equivalent to Google Maps API's .toSpan() method on GLatLng's. # # Returns a LatLng object, whose coordinates represent the size of a rectangle # defined by these bounds. def to_span lat_span = (@ne.lat - @sw.lat).abs lng_span = (crosses_meridian? ? 360 + @ne.lng - @sw.lng : @ne.lng - @sw.lng).abs Geokit::LatLng.new(lat_span, lng_span) end class <<self # returns an instance of bounds which completely encompases the given circle def from_point_and_radius(point,radius,options={}) point=LatLng.normalize(point) p0=point.endpoint(0,radius,options) p90=point.endpoint(90,radius,options) p180=point.endpoint(180,radius,options) p270=point.endpoint(270,radius,options) sw=Geokit::LatLng.new(p180.lat,p270.lng) ne=Geokit::LatLng.new(p0.lat,p90.lng) Geokit::Bounds.new(sw,ne) end # Takes two main combinations of arguments to create a bounds: # point,point (this is the only one which takes two arguments # [point,point] # . . . where a point is anything LatLng#normalize can handle (which is quite a lot) # # NOTE: everything combination is assumed to pass points in the order sw, ne def normalize (thing,other=nil) # maybe this will be simple -- an actual bounds object is passed, and we can all go home return thing if thing.is_a? Bounds # no? OK, if there's no "other," the thing better be a two-element array thing,other=thing if !other && thing.is_a?(Array) && thing.size==2 # Now that we're set with a thing and another thing, let LatLng do the heavy lifting. # Exceptions may be thrown Bounds.new(Geokit::LatLng.normalize(thing),Geokit::LatLng.normalize(other)) end end end end ruby 1.9 returns Math::DomainError, not Errno::EDOM #require 'forwardable' module Geokit # Contains class and instance methods providing distance calcuation services. This # module is meant to be mixed into classes containing lat and lng attributes where # distance calculation is desired. # # At present, two forms of distance calculations are provided: # # * Pythagorean Theory (flat Earth) - which assumes the world is flat and loses accuracy over long distances. # * Haversine (sphere) - which is fairly accurate, but at a performance cost. # # Distance units supported are :miles, :kms, and :nms. module Mappable PI_DIV_RAD = 0.0174 KMS_PER_MILE = 1.609 NMS_PER_MILE = 0.868976242 EARTH_RADIUS_IN_MILES = 3963.19 EARTH_RADIUS_IN_KMS = EARTH_RADIUS_IN_MILES * KMS_PER_MILE EARTH_RADIUS_IN_NMS = EARTH_RADIUS_IN_MILES * NMS_PER_MILE MILES_PER_LATITUDE_DEGREE = 69.1 KMS_PER_LATITUDE_DEGREE = MILES_PER_LATITUDE_DEGREE * KMS_PER_MILE NMS_PER_LATITUDE_DEGREE = MILES_PER_LATITUDE_DEGREE * NMS_PER_MILE LATITUDE_DEGREES = EARTH_RADIUS_IN_MILES / MILES_PER_LATITUDE_DEGREE # Mix below class methods into the includer. def self.included(receiver) # :nodoc: receiver.extend ClassMethods end module ClassMethods #:nodoc: # Returns the distance between two points. The from and to parameters are # required to have lat and lng attributes. Valid options are: # :units - valid values are :miles, :kms, :nms (Geokit::default_units is the default) # :formula - valid values are :flat or :sphere (Geokit::default_formula is the default) def distance_between(from, to, options={}) from=Geokit::LatLng.normalize(from) to=Geokit::LatLng.normalize(to) return 0.0 if from == to # fixes a "zero-distance" bug units = options[:units] || Geokit::default_units formula = options[:formula] || Geokit::default_formula case formula when :sphere begin units_sphere_multiplier(units) * Math.acos( Math.sin(deg2rad(from.lat)) * Math.sin(deg2rad(to.lat)) + Math.cos(deg2rad(from.lat)) * Math.cos(deg2rad(to.lat)) * Math.cos(deg2rad(to.lng) - deg2rad(from.lng))) rescue Errno::EDOM, Math::DomainError 0.0 end when :flat Math.sqrt((units_per_latitude_degree(units)*(from.lat-to.lat))**2 + (units_per_longitude_degree(from.lat, units)*(from.lng-to.lng))**2) end end # Returns heading in degrees (0 is north, 90 is east, 180 is south, etc) # from the first point to the second point. Typicaly, the instance methods will be used # instead of this method. def heading_between(from,to) from=Geokit::LatLng.normalize(from) to=Geokit::LatLng.normalize(to) d_lng=deg2rad(to.lng-from.lng) from_lat=deg2rad(from.lat) to_lat=deg2rad(to.lat) y=Math.sin(d_lng) * Math.cos(to_lat) x=Math.cos(from_lat)*Math.sin(to_lat)-Math.sin(from_lat)*Math.cos(to_lat)*Math.cos(d_lng) heading=to_heading(Math.atan2(y,x)) end # Given a start point, distance, and heading (in degrees), provides # an endpoint. Returns a LatLng instance. Typically, the instance method # will be used instead of this method. def endpoint(start,heading, distance, options={}) units = options[:units] || Geokit::default_units radius = case units when :kms; EARTH_RADIUS_IN_KMS when :nms; EARTH_RADIUS_IN_NMS else EARTH_RADIUS_IN_MILES end start=Geokit::LatLng.normalize(start) lat=deg2rad(start.lat) lng=deg2rad(start.lng) heading=deg2rad(heading) distance=distance.to_f end_lat=Math.asin(Math.sin(lat)*Math.cos(distance/radius) + Math.cos(lat)*Math.sin(distance/radius)*Math.cos(heading)) end_lng=lng+Math.atan2(Math.sin(heading)*Math.sin(distance/radius)*Math.cos(lat), Math.cos(distance/radius)-Math.sin(lat)*Math.sin(end_lat)) LatLng.new(rad2deg(end_lat),rad2deg(end_lng)) end # Returns the midpoint, given two points. Returns a LatLng. # Typically, the instance method will be used instead of this method. # Valid option: # :units - valid values are :miles, :kms, or :nms (:miles is the default) def midpoint_between(from,to,options={}) from=Geokit::LatLng.normalize(from) units = options[:units] || Geokit::default_units heading=from.heading_to(to) distance=from.distance_to(to,options) midpoint=from.endpoint(heading,distance/2,options) end # Geocodes a location using the multi geocoder. def geocode(location, options = {}) res = Geocoders::MultiGeocoder.geocode(location, options) return res if res.success? raise Geokit::Geocoders::GeocodeError end protected def deg2rad(degrees) degrees.to_f / 180.0 * Math::PI end def rad2deg(rad) rad.to_f * 180.0 / Math::PI end def to_heading(rad) (rad2deg(rad)+360)%360 end # Returns the multiplier used to obtain the correct distance units. def units_sphere_multiplier(units) case units when :kms; EARTH_RADIUS_IN_KMS when :nms; EARTH_RADIUS_IN_NMS else EARTH_RADIUS_IN_MILES end end # Returns the number of units per latitude degree. def units_per_latitude_degree(units) case units when :kms; KMS_PER_LATITUDE_DEGREE when :nms; NMS_PER_LATITUDE_DEGREE else MILES_PER_LATITUDE_DEGREE end end # Returns the number units per longitude degree. def units_per_longitude_degree(lat, units) miles_per_longitude_degree = (LATITUDE_DEGREES * Math.cos(lat * PI_DIV_RAD)).abs case units when :kms; miles_per_longitude_degree * KMS_PER_MILE when :nms; miles_per_longitude_degree * NMS_PER_MILE else miles_per_longitude_degree end end end # ----------------------------------------------------------------------------------------------- # Instance methods below here # ----------------------------------------------------------------------------------------------- # Extracts a LatLng instance. Use with models that are acts_as_mappable def to_lat_lng return self if instance_of?(Geokit::LatLng) || instance_of?(Geokit::GeoLoc) return LatLng.new(send(self.class.lat_column_name),send(self.class.lng_column_name)) if self.class.respond_to?(:acts_as_mappable) nil end # Returns the distance from another point. The other point parameter is # required to have lat and lng attributes. Valid options are: # :units - valid values are :miles, :kms, :or :nms (:miles is the default) # :formula - valid values are :flat or :sphere (:sphere is the default) def distance_to(other, options={}) self.class.distance_between(self, other, options) end alias distance_from distance_to # Returns heading in degrees (0 is north, 90 is east, 180 is south, etc) # to the given point. The given point can be a LatLng or a string to be Geocoded def heading_to(other) self.class.heading_between(self,other) end # Returns heading in degrees (0 is north, 90 is east, 180 is south, etc) # FROM the given point. The given point can be a LatLng or a string to be Geocoded def heading_from(other) self.class.heading_between(other,self) end # Returns the endpoint, given a heading (in degrees) and distance. # Valid option: # :units - valid values are :miles, :kms, or :nms (:miles is the default) def endpoint(heading,distance,options={}) self.class.endpoint(self,heading,distance,options) end # Returns the midpoint, given another point on the map. # Valid option: # :units - valid values are :miles, :kms, or :nms (:miles is the default) def midpoint_to(other, options={}) self.class.midpoint_between(self,other,options) end end class LatLng include Mappable attr_accessor :lat, :lng # Accepts latitude and longitude or instantiates an empty instance # if lat and lng are not provided. Converted to floats if provided def initialize(lat=nil, lng=nil) lat = lat.to_f if lat && !lat.is_a?(Numeric) lng = lng.to_f if lng && !lng.is_a?(Numeric) @lat = lat @lng = lng end # Latitude attribute setter; stored as a float. def lat=(lat) @lat = lat.to_f if lat end # Longitude attribute setter; stored as a float; def lng=(lng) @lng=lng.to_f if lng end # Returns the lat and lng attributes as a comma-separated string. def ll "#{lat},#{lng}" end #returns a string with comma-separated lat,lng values def to_s ll end #returns a two-element array def to_a [lat,lng] end # Returns true if the candidate object is logically equal. Logical equivalence # is true if the lat and lng attributes are the same for both objects. def ==(other) other.is_a?(LatLng) ? self.lat == other.lat && self.lng == other.lng : false end def hash lat.hash + lng.hash end def eql?(other) self == other end # Returns true if both lat and lng attributes are defined def valid? self.lat and self.lng end # A *class* method to take anything which can be inferred as a point and generate # a LatLng from it. You should use this anything you're not sure what the input is, # and want to deal with it as a LatLng if at all possible. Can take: # 1) two arguments (lat,lng) # 2) a string in the format "37.1234,-129.1234" or "37.1234 -129.1234" # 3) a string which can be geocoded on the fly # 4) an array in the format [37.1234,-129.1234] # 5) a LatLng or GeoLoc (which is just passed through as-is) # 6) anything which acts_as_mappable -- a LatLng will be extracted from it def self.normalize(thing,other=nil) # if an 'other' thing is supplied, normalize the input by creating an array of two elements thing=[thing,other] if other if thing.is_a?(String) thing.strip! if match=thing.match(/(\-?\d+\.?\d*)[, ] ?(\-?\d+\.?\d*)$/) return Geokit::LatLng.new(match[1],match[2]) else res = Geokit::Geocoders::MultiGeocoder.geocode(thing) return res if res.success? raise Geokit::Geocoders::GeocodeError end elsif thing.is_a?(Array) && thing.size==2 return Geokit::LatLng.new(thing[0],thing[1]) elsif thing.is_a?(LatLng) # will also be true for GeoLocs return thing elsif thing.class.respond_to?(:acts_as_mappable) && thing.class.respond_to?(:distance_column_name) return thing.to_lat_lng elsif thing.respond_to? :to_lat_lng return thing.to_lat_lng end raise ArgumentError.new("#{thing} (#{thing.class}) cannot be normalized to a LatLng. We tried interpreting it as an array, string, Mappable, etc., but no dice.") end # Reverse geocodes a LatLng object using the MultiGeocoder (default), or optionally # using a geocoder of your choosing. Returns a new Geokit::GeoLoc object # # ==== Options # * :using - Specifies the geocoder to use for reverse geocoding. Defaults to # MultiGeocoder. Can be either the geocoder class (or any class that # implements do_reverse_geocode for that matter), or the name of # the class without the "Geocoder" part (e.g. :google) # # ==== Examples # LatLng.new(51.4578329, 7.0166848).reverse_geocode # => #<Geokit::GeoLoc:0x12dac20 @state...> # LatLng.new(51.4578329, 7.0166848).reverse_geocode(:using => :google) # => #<Geokit::GeoLoc:0x12dac20 @state...> # LatLng.new(51.4578329, 7.0166848).reverse_geocode(:using => Geokit::Geocoders::GoogleGeocoder) # => #<Geokit::GeoLoc:0x12dac20 @state...> def reverse_geocode(options = { :using => Geokit::Geocoders::MultiGeocoder }) if options[:using].is_a?(String) or options[:using].is_a?(Symbol) provider = Geokit::Geocoders.const_get("#{Geokit::Inflector::camelize(options[:using].to_s)}Geocoder") elsif options[:using].respond_to?(:do_reverse_geocode) provider = options[:using] else raise ArgumentError.new("#{options[:using]} is not a valid geocoder.") end provider.send(:reverse_geocode, self) end end # This class encapsulates the result of a geocoding call. # It's primary purpose is to homogenize the results of multiple # geocoding providers. It also provides some additional functionality, such as # the "full address" method for geocoders that do not provide a # full address in their results (for example, Yahoo), and the "is_us" method. # # Some geocoders can return multple results. Geoloc can capture multiple results through # its "all" method. # # For the geocoder setting the results, it would look something like this: # geo=GeoLoc.new(first_result) # geo.all.push(second_result) # geo.all.push(third_result) # # Then, for the user of the result: # # puts geo.full_address # just like usual # puts geo.all.size => 3 # there's three results total # puts geo.all.first # all is just an array or additional geolocs, # so do what you want with it class GeoLoc < LatLng # Location attributes. Full address is a concatenation of all values. For example: # 100 Spear St, San Francisco, CA, 94101, US # Street number and street name are extracted from the street address attribute if they don't exist attr_accessor :street_number, :street_name, :street_address, :city, :state, :zip, :country_code, :country attr_accessor :full_address, :all, :district, :province, :sub_premise # Attributes set upon return from geocoding. Success will be true for successful # geocode lookups. The provider will be set to the name of the providing geocoder. # Finally, precision is an indicator of the accuracy of the geocoding. attr_accessor :success, :provider, :precision, :suggested_bounds # accuracy is set for Yahoo and Google geocoders, it is a numeric value of the # precision. see http://code.google.com/apis/maps/documentation/geocoding/#GeocodingAccuracy attr_accessor :accuracy # FCC Attributes attr_accessor :district_fips, :state_fips, :block_fips # Constructor expects a hash of symbols to correspond with attributes. def initialize(h={}) @all = [self] @street_address=h[:street_address] @sub_premise=nil @street_number=nil @street_name=nil @city=h[:city] @state=h[:state] @zip=h[:zip] @country_code=h[:country_code] @province = h[:province] @success=false @precision='unknown' @full_address=nil super(h[:lat],h[:lng]) end # Returns true if geocoded to the United States. def is_us? country_code == 'US' end def success? success == true end # full_address is provided by google but not by yahoo. It is intended that the google # geocoding method will provide the full address, whereas for yahoo it will be derived # from the parts of the address we do have. def full_address @full_address ? @full_address : to_geocodeable_s end # Extracts the street number from the street address where possible. def street_number @street_number ||= street_address[/(\d*)/] if street_address @street_number end # Returns the street name portion of the street address where possible def street_name @street_name||=street_address[street_number.length, street_address.length].strip if street_address @street_name end # gives you all the important fields as key-value pairs def hash res={} [:success, :lat, :lng, :country_code, :city, :state, :zip, :street_address, :province, :district, :provider, :full_address, :is_us?, :ll, :precision, :district_fips, :state_fips, :block_fips, :sub_premise].each { |s| res[s] = self.send(s.to_s) } res end alias to_hash hash # Sets the city after capitalizing each word within the city name. def city=(city) @city = Geokit::Inflector::titleize(city) if city end # Sets the street address after capitalizing each word within the street address. def street_address=(address) if address and not ['google','google3'].include?(self.provider) @street_address = Geokit::Inflector::titleize(address) else @street_address = address end end # Returns a comma-delimited string consisting of the street address, city, state, # zip, and country code. Only includes those attributes that are non-blank. def to_geocodeable_s a=[street_address, district, city, province, state, zip, country_code].compact a.delete_if { |e| !e || e == '' } a.join(', ') end def to_yaml_properties (instance_variables - ['@all']).sort end # Returns a string representation of the instance. def to_s "Provider: #{provider}\nStreet: #{street_address}\nCity: #{city}\nState: #{state}\nZip: #{zip}\nLatitude: #{lat}\nLongitude: #{lng}\nCountry: #{country_code}\nSuccess: #{success}" end end # Bounds represents a rectangular bounds, defined by the SW and NE corners class Bounds # sw and ne are LatLng objects attr_accessor :sw, :ne # provide sw and ne to instantiate a new Bounds instance def initialize(sw,ne) raise ArgumentError if !(sw.is_a?(Geokit::LatLng) && ne.is_a?(Geokit::LatLng)) @sw,@ne=sw,ne end #returns the a single point which is the center of the rectangular bounds def center @sw.midpoint_to(@ne) end # a simple string representation:sw,ne def to_s "#{@sw.to_s},#{@ne.to_s}" end # a two-element array of two-element arrays: sw,ne def to_a [@sw.to_a, @ne.to_a] end # Returns true if the bounds contain the passed point. # allows for bounds which cross the meridian def contains?(point) point=Geokit::LatLng.normalize(point) res = point.lat > @sw.lat && point.lat < @ne.lat if crosses_meridian? res &= point.lng < @ne.lng || point.lng > @sw.lng else res &= point.lng < @ne.lng && point.lng > @sw.lng end res end # returns true if the bounds crosses the international dateline def crosses_meridian? @sw.lng > @ne.lng end # Returns true if the candidate object is logically equal. Logical equivalence # is true if the lat and lng attributes are the same for both objects. def ==(other) other.is_a?(Bounds) ? self.sw == other.sw && self.ne == other.ne : false end # Equivalent to Google Maps API's .toSpan() method on GLatLng's. # # Returns a LatLng object, whose coordinates represent the size of a rectangle # defined by these bounds. def to_span lat_span = (@ne.lat - @sw.lat).abs lng_span = (crosses_meridian? ? 360 + @ne.lng - @sw.lng : @ne.lng - @sw.lng).abs Geokit::LatLng.new(lat_span, lng_span) end class <<self # returns an instance of bounds which completely encompases the given circle def from_point_and_radius(point,radius,options={}) point=LatLng.normalize(point) p0=point.endpoint(0,radius,options) p90=point.endpoint(90,radius,options) p180=point.endpoint(180,radius,options) p270=point.endpoint(270,radius,options) sw=Geokit::LatLng.new(p180.lat,p270.lng) ne=Geokit::LatLng.new(p0.lat,p90.lng) Geokit::Bounds.new(sw,ne) end # Takes two main combinations of arguments to create a bounds: # point,point (this is the only one which takes two arguments # [point,point] # . . . where a point is anything LatLng#normalize can handle (which is quite a lot) # # NOTE: everything combination is assumed to pass points in the order sw, ne def normalize (thing,other=nil) # maybe this will be simple -- an actual bounds object is passed, and we can all go home return thing if thing.is_a? Bounds # no? OK, if there's no "other," the thing better be a two-element array thing,other=thing if !other && thing.is_a?(Array) && thing.size==2 # Now that we're set with a thing and another thing, let LatLng do the heavy lifting. # Exceptions may be thrown Bounds.new(Geokit::LatLng.normalize(thing),Geokit::LatLng.normalize(other)) end end end end
module Gitdocs VERSION = "0.1.1" end Bump to version 0.1.2 module Gitdocs VERSION = "0.1.2" end
require 'html/pipeline' module Gitlab # Custom parser for GitLab-flavored Markdown # # See the files in `lib/gitlab/markdown/` for specific processing information. module Markdown # Convert a Markdown String into an HTML-safe String of HTML # # Note that while the returned HTML will have been sanitized of dangerous # HTML, it may post a risk of information leakage if it's not also passed # through `post_process`. # # Also note that the returned String is always HTML, not XHTML. Views # requiring XHTML, such as Atom feeds, need to call `post_process` on the # result, providing the appropriate `pipeline` option. # # markdown - Markdown String # context - Hash of context options passed to our HTML Pipeline # # Returns an HTML-safe String def self.render(text, context = {}) context[:pipeline] ||= :full cache_key = context.delete(:cache_key) cache_key = full_cache_key(cache_key, context[:pipeline]) if cache_key Rails.cache.fetch(cache_key) do cacheless_render(text, context) end else cacheless_render(text, context) end end def self.render_result(text, context = {}) pipeline_type = context[:pipeline] ||= :full pipeline_by_type(pipeline_type).call(text, context) end # Perform post-processing on an HTML String # # This method is used to perform state-dependent changes to a String of # HTML, such as removing references that the current user doesn't have # permission to make (`RedactorFilter`). # # html - String to process # context - Hash of options to customize output # :pipeline - Symbol pipeline type # :project - Project # :user - User object # # Returns an HTML-safe String def self.post_process(html, context) pipeline = pipeline_by_type(:post_process) if context[:xhtml] pipeline.to_document(html, context).to_html(save_with: Nokogiri::XML::Node::SaveOptions::AS_XHTML) else pipeline.to_html(html, context) end.html_safe end private def self.cacheless_render(text, context = {}) result = render_result(text, context) output = result[:output] if output.respond_to?(:to_html) output.to_html else output.to_s end end def self.full_cache_key(cache_key, pipeline = :full) return unless cache_key ["markdown", *cache_key, pipeline] end def self.pipeline_by_type(pipeline_type) const_get("#{pipeline_type.to_s.camelize}Pipeline") end # Provide autoload paths for filters to prevent a circular dependency error autoload :AutolinkFilter, 'gitlab/markdown/autolink_filter' autoload :CommitRangeReferenceFilter, 'gitlab/markdown/commit_range_reference_filter' autoload :CommitReferenceFilter, 'gitlab/markdown/commit_reference_filter' autoload :EmojiFilter, 'gitlab/markdown/emoji_filter' autoload :ExternalIssueReferenceFilter, 'gitlab/markdown/external_issue_reference_filter' autoload :ExternalLinkFilter, 'gitlab/markdown/external_link_filter' autoload :IssueReferenceFilter, 'gitlab/markdown/issue_reference_filter' autoload :LabelReferenceFilter, 'gitlab/markdown/label_reference_filter' autoload :MarkdownFilter, 'gitlab/markdown/markdown_filter' autoload :MergeRequestReferenceFilter, 'gitlab/markdown/merge_request_reference_filter' autoload :RedactorFilter, 'gitlab/markdown/redactor_filter' autoload :RelativeLinkFilter, 'gitlab/markdown/relative_link_filter' autoload :SanitizationFilter, 'gitlab/markdown/sanitization_filter' autoload :SnippetReferenceFilter, 'gitlab/markdown/snippet_reference_filter' autoload :SyntaxHighlightFilter, 'gitlab/markdown/syntax_highlight_filter' autoload :TableOfContentsFilter, 'gitlab/markdown/table_of_contents_filter' autoload :TaskListFilter, 'gitlab/markdown/task_list_filter' autoload :UserReferenceFilter, 'gitlab/markdown/user_reference_filter' autoload :UploadLinkFilter, 'gitlab/markdown/upload_link_filter' autoload :AsciidocPipeline, 'gitlab/markdown/asciidoc_pipeline' autoload :AtomPipeline, 'gitlab/markdown/atom_pipeline' autoload :CombinedPipeline, 'gitlab/markdown/combined_pipeline' autoload :DescriptionPipeline, 'gitlab/markdown/description_pipeline' autoload :EmailPipeline, 'gitlab/markdown/email_pipeline' autoload :FullPipeline, 'gitlab/markdown/full_pipeline' autoload :GfmPipeline, 'gitlab/markdown/gfm_pipeline' autoload :NotePipeline, 'gitlab/markdown/note_pipeline' autoload :Pipeline, 'gitlab/markdown/pipeline' autoload :PlainMarkdownPipeline, 'gitlab/markdown/plain_markdown_pipeline' autoload :PostProcessPipeline, 'gitlab/markdown/post_process_pipeline' autoload :ReferenceExtractionPipeline, 'gitlab/markdown/reference_extraction_pipeline' autoload :SingleLinePipeline, 'gitlab/markdown/single_line_pipeline' end end Fix Markdown XHTML context param require 'html/pipeline' module Gitlab # Custom parser for GitLab-flavored Markdown # # See the files in `lib/gitlab/markdown/` for specific processing information. module Markdown # Convert a Markdown String into an HTML-safe String of HTML # # Note that while the returned HTML will have been sanitized of dangerous # HTML, it may post a risk of information leakage if it's not also passed # through `post_process`. # # Also note that the returned String is always HTML, not XHTML. Views # requiring XHTML, such as Atom feeds, need to call `post_process` on the # result, providing the appropriate `pipeline` option. # # markdown - Markdown String # context - Hash of context options passed to our HTML Pipeline # # Returns an HTML-safe String def self.render(text, context = {}) cache_key = context.delete(:cache_key) cache_key = full_cache_key(cache_key, context[:pipeline]) if cache_key Rails.cache.fetch(cache_key) do cacheless_render(text, context) end else cacheless_render(text, context) end end def self.render_result(text, context = {}) pipeline_by_name(context[:pipeline]).call(text, context) end # Perform post-processing on an HTML String # # This method is used to perform state-dependent changes to a String of # HTML, such as removing references that the current user doesn't have # permission to make (`RedactorFilter`). # # html - String to process # context - Hash of options to customize output # :pipeline - Symbol pipeline type # :project - Project # :user - User object # # Returns an HTML-safe String def self.post_process(html, context) pipeline = pipeline_by_name(context[:pipeline]) context = pipeline.transform_context(context) pipeline = pipeline_by_name(:post_process) if context[:xhtml] pipeline.to_document(html, context).to_html(save_with: Nokogiri::XML::Node::SaveOptions::AS_XHTML) else pipeline.to_html(html, context) end.html_safe end private def self.cacheless_render(text, context = {}) result = render_result(text, context) output = result[:output] if output.respond_to?(:to_html) output.to_html else output.to_s end end def self.full_cache_key(cache_key, pipeline_name) return unless cache_key pipeline_name ||= :full ["markdown", *cache_key, pipeline] end def self.pipeline_by_name(pipeline_name) pipeline_name ||= :full const_get("#{pipeline_name.to_s.camelize}Pipeline") end # Provide autoload paths for filters to prevent a circular dependency error autoload :AutolinkFilter, 'gitlab/markdown/autolink_filter' autoload :CommitRangeReferenceFilter, 'gitlab/markdown/commit_range_reference_filter' autoload :CommitReferenceFilter, 'gitlab/markdown/commit_reference_filter' autoload :EmojiFilter, 'gitlab/markdown/emoji_filter' autoload :ExternalIssueReferenceFilter, 'gitlab/markdown/external_issue_reference_filter' autoload :ExternalLinkFilter, 'gitlab/markdown/external_link_filter' autoload :IssueReferenceFilter, 'gitlab/markdown/issue_reference_filter' autoload :LabelReferenceFilter, 'gitlab/markdown/label_reference_filter' autoload :MarkdownFilter, 'gitlab/markdown/markdown_filter' autoload :MergeRequestReferenceFilter, 'gitlab/markdown/merge_request_reference_filter' autoload :RedactorFilter, 'gitlab/markdown/redactor_filter' autoload :RelativeLinkFilter, 'gitlab/markdown/relative_link_filter' autoload :SanitizationFilter, 'gitlab/markdown/sanitization_filter' autoload :SnippetReferenceFilter, 'gitlab/markdown/snippet_reference_filter' autoload :SyntaxHighlightFilter, 'gitlab/markdown/syntax_highlight_filter' autoload :TableOfContentsFilter, 'gitlab/markdown/table_of_contents_filter' autoload :TaskListFilter, 'gitlab/markdown/task_list_filter' autoload :UserReferenceFilter, 'gitlab/markdown/user_reference_filter' autoload :UploadLinkFilter, 'gitlab/markdown/upload_link_filter' autoload :AsciidocPipeline, 'gitlab/markdown/asciidoc_pipeline' autoload :AtomPipeline, 'gitlab/markdown/atom_pipeline' autoload :CombinedPipeline, 'gitlab/markdown/combined_pipeline' autoload :DescriptionPipeline, 'gitlab/markdown/description_pipeline' autoload :EmailPipeline, 'gitlab/markdown/email_pipeline' autoload :FullPipeline, 'gitlab/markdown/full_pipeline' autoload :GfmPipeline, 'gitlab/markdown/gfm_pipeline' autoload :NotePipeline, 'gitlab/markdown/note_pipeline' autoload :Pipeline, 'gitlab/markdown/pipeline' autoload :PlainMarkdownPipeline, 'gitlab/markdown/plain_markdown_pipeline' autoload :PostProcessPipeline, 'gitlab/markdown/post_process_pipeline' autoload :ReferenceExtractionPipeline, 'gitlab/markdown/reference_extraction_pipeline' autoload :SingleLinePipeline, 'gitlab/markdown/single_line_pipeline' end end
require 'tempfile' require File.join(File.dirname(__FILE__), 'config', 'repo') require File.join(File.dirname(__FILE__), 'config', 'group') module Gitolite class Config attr_accessor :repos, :groups, :filename def initialize(config) @repos = {} @groups = {} @filename = File.basename(config) process_config(config) end def self.init(filename = "gitolite.conf") file = Tempfile.new(filename) conf = self.new(file.path) conf.filename = filename #kill suffix added by Tempfile file.close(unlink_now = true) conf end #TODO: merge repo unless overwrite = true def add_repo(repo, overwrite = false) raise ArgumentError, "Repo must be of type Gitolite::Config::Repo!" unless repo.instance_of? Gitolite::Config::Repo @repos[repo.name] = repo end def rm_repo(repo) name = normalize_repo_name(repo) @repos.delete(name) end def has_repo?(repo) name = normalize_repo_name(repo) @repos.has_key?(name) end def get_repo(repo) name = normalize_repo_name(repo) @repos[name] end def add_group(group, overwrite = false) raise ArgumentError, "Group must be of type Gitolite::Config::Group!" unless group.instance_of? Gitolite::Config::Group @groups[group.name] = group end def rm_group(group) name = normalize_group_name(group) @groups.delete(name) end def has_group?(group) name = normalize_group_name(group) @groups.has_key?(name) end def get_group(group) name = normalize_group_name(group) @groups[name] end def to_file(path=".", filename=@filename) raise ArgumentError, "Path contains a filename or does not exist" unless File.directory?(path) new_conf = File.join(path, filename) File.open(new_conf, "w") do |f| #Output groups dep_order = build_groups_depgraph dep_order.each {|group| f.write group.to_s } gitweb_descs = [] @repos.each do |k, v| f.write v.to_s gwd = v.gitweb_description gitweb_descs.push(gwd) unless gwd.nil? end f.write gitweb_descs.join("\n") end new_conf end private #Based on #https://github.com/sitaramc/gitolite/blob/pu/src/gl-compile-conf#cleanup_conf_line def cleanup_config_line(line) #remove comments, even those that happen inline line.gsub!(/^((".*?"|[^#"])*)#.*/) {|m| m=$1} #fix whitespace line.gsub!('=', ' = ') line.gsub!(/\s+/, ' ') line.strip end def process_config(config) context = [] #will store our context for permissions or config declarations #Read each line of our config File.open(config, 'r').each do |l| line = cleanup_config_line(l) next if line.empty? #lines are empty if we killed a comment case line #found a repo definition when /^repo (.*)/ #Empty our current context context = [] repos = $1.split repos.each do |r| context << r @repos[r] = Repo.new(r) unless has_repo?(r) end #repo permissions when /^(-|C|R|RW\+?(?:C?D?|D?C?)M?) (.* )?= (.+)/ perm = $1 refex = $2 || "" users = $3.split context.each do |c| @repos[c].add_permission(perm, refex, users) end #repo git config when /^config (.+) = ?(.*)/ key = $1 value = $2 context.each do |c| @repos[c].set_git_config(key, value) end #group definition when /^#{Group::PREPEND_CHAR}(\S+) = ?(.*)/ group = $1 users = $2.split @groups[group] = Group.new(group) unless has_group?(group) @groups[group].add_users(users) #gitweb definition when /^(\S+)(?: "(.*?)")? = "(.*)"$/ repo = $1 owner = $2 description = $3 #Check for missing description raise ParseError, "Missing Gitweb description for repo: #{repo}" if description.nil? #Check for groups raise ParseError, "Gitweb descriptions cannot be set for groups" if repo =~ /@.+/ if has_repo? repo r = @repos[repo] else r = Repo.new(repo) add_repo(r) end r.owner = owner r.description = description when /^include "(.+)"/ #TODO: implement includes #ignore includes for now when /^subconf (\S+)$/ #TODO: implement subconfs #ignore subconfs for now else raise ParseError, "'#{line}' cannot be processed" end end end # Normalizes the various different input objects to Strings def normalize_name(context, constant = nil) case context when constant context.name when Symbol context.to_s else context end end def method_missing(meth, *args, &block) if meth.to_s =~ /normalize_(\w+)_name/ #Could use Object.const_get to figure out the constant here #but for only two cases, this is more readable case $1 when "repo" normalize_name(args[0], Gitolite::Config::Repo) when "group" normalize_name(args[0], Gitolite::Config::Group) end else super end end # Builds a dependency tree from the groups in order to ensure all groups # are defined before they are used def build_groups_depgraph dp = ::Plexus::Digraph.new # Add each group to the graph @groups.each_value do |group| dp.add_vertex! group # Select group names from the users subgroups = group.users.select {|u| u =~ /^#{Group::PREPEND_CHAR}.*$/}.map{|g| get_group g.gsub(Group::PREPEND_CHAR, '') } subgroups.each do |subgroup| dp.add_edge! subgroup, group end end # Figure out if we have a good depedency graph dep_order = dp.topsort if dep_order.empty? raise GroupDependencyError unless @groups.empty? end dep_order end #Raised when something in a config fails to parse properly class ParseError < RuntimeError end # Raised when group dependencies cannot be suitably resolved for output class GroupDependencyError < RuntimeError end end end Simplify gitolite.conf diffs by sorting repos and adding blank lines The original code changed the order of the entire gitolite.conf file after every commit; this meant that diffs (for e.g. security audits) were essentially useless. This fix includes two small changes that improve this situation greatly: * Sort the repo list on output (including gitweb description lines) so that (mostly) only changed repos show up in the diff * Add a blank line between each repo block and each file section, so that `git diff` will not be confused and make a single-line change to a repo's permissions appear to be a cascading reordering of lines across several consecutive repos with similar permissions The latter change also has the side benefit of making the conf file (and thus the diffs) more readable to humans. Still remaining to fix is the constant reordering of group definitions when there exists no unique dependency ordering between them. require 'tempfile' require File.join(File.dirname(__FILE__), 'config', 'repo') require File.join(File.dirname(__FILE__), 'config', 'group') module Gitolite class Config attr_accessor :repos, :groups, :filename def initialize(config) @repos = {} @groups = {} @filename = File.basename(config) process_config(config) end def self.init(filename = "gitolite.conf") file = Tempfile.new(filename) conf = self.new(file.path) conf.filename = filename #kill suffix added by Tempfile file.close(unlink_now = true) conf end #TODO: merge repo unless overwrite = true def add_repo(repo, overwrite = false) raise ArgumentError, "Repo must be of type Gitolite::Config::Repo!" unless repo.instance_of? Gitolite::Config::Repo @repos[repo.name] = repo end def rm_repo(repo) name = normalize_repo_name(repo) @repos.delete(name) end def has_repo?(repo) name = normalize_repo_name(repo) @repos.has_key?(name) end def get_repo(repo) name = normalize_repo_name(repo) @repos[name] end def add_group(group, overwrite = false) raise ArgumentError, "Group must be of type Gitolite::Config::Group!" unless group.instance_of? Gitolite::Config::Group @groups[group.name] = group end def rm_group(group) name = normalize_group_name(group) @groups.delete(name) end def has_group?(group) name = normalize_group_name(group) @groups.has_key?(name) end def get_group(group) name = normalize_group_name(group) @groups[name] end def to_file(path=".", filename=@filename) raise ArgumentError, "Path contains a filename or does not exist" unless File.directory?(path) new_conf = File.join(path, filename) File.open(new_conf, "w") do |f| #Output groups dep_order = build_groups_depgraph dep_order.each {|group| f.write group.to_s } gitweb_descs = [] @repos.sort.each do |k, v| f.write "\n" f.write v.to_s gwd = v.gitweb_description gitweb_descs.push(gwd) unless gwd.nil? end f.write "\n" f.write gitweb_descs.join("\n") end new_conf end private #Based on #https://github.com/sitaramc/gitolite/blob/pu/src/gl-compile-conf#cleanup_conf_line def cleanup_config_line(line) #remove comments, even those that happen inline line.gsub!(/^((".*?"|[^#"])*)#.*/) {|m| m=$1} #fix whitespace line.gsub!('=', ' = ') line.gsub!(/\s+/, ' ') line.strip end def process_config(config) context = [] #will store our context for permissions or config declarations #Read each line of our config File.open(config, 'r').each do |l| line = cleanup_config_line(l) next if line.empty? #lines are empty if we killed a comment case line #found a repo definition when /^repo (.*)/ #Empty our current context context = [] repos = $1.split repos.each do |r| context << r @repos[r] = Repo.new(r) unless has_repo?(r) end #repo permissions when /^(-|C|R|RW\+?(?:C?D?|D?C?)M?) (.* )?= (.+)/ perm = $1 refex = $2 || "" users = $3.split context.each do |c| @repos[c].add_permission(perm, refex, users) end #repo git config when /^config (.+) = ?(.*)/ key = $1 value = $2 context.each do |c| @repos[c].set_git_config(key, value) end #group definition when /^#{Group::PREPEND_CHAR}(\S+) = ?(.*)/ group = $1 users = $2.split @groups[group] = Group.new(group) unless has_group?(group) @groups[group].add_users(users) #gitweb definition when /^(\S+)(?: "(.*?)")? = "(.*)"$/ repo = $1 owner = $2 description = $3 #Check for missing description raise ParseError, "Missing Gitweb description for repo: #{repo}" if description.nil? #Check for groups raise ParseError, "Gitweb descriptions cannot be set for groups" if repo =~ /@.+/ if has_repo? repo r = @repos[repo] else r = Repo.new(repo) add_repo(r) end r.owner = owner r.description = description when /^include "(.+)"/ #TODO: implement includes #ignore includes for now when /^subconf (\S+)$/ #TODO: implement subconfs #ignore subconfs for now else raise ParseError, "'#{line}' cannot be processed" end end end # Normalizes the various different input objects to Strings def normalize_name(context, constant = nil) case context when constant context.name when Symbol context.to_s else context end end def method_missing(meth, *args, &block) if meth.to_s =~ /normalize_(\w+)_name/ #Could use Object.const_get to figure out the constant here #but for only two cases, this is more readable case $1 when "repo" normalize_name(args[0], Gitolite::Config::Repo) when "group" normalize_name(args[0], Gitolite::Config::Group) end else super end end # Builds a dependency tree from the groups in order to ensure all groups # are defined before they are used def build_groups_depgraph dp = ::Plexus::Digraph.new # Add each group to the graph @groups.each_value do |group| dp.add_vertex! group # Select group names from the users subgroups = group.users.select {|u| u =~ /^#{Group::PREPEND_CHAR}.*$/}.map{|g| get_group g.gsub(Group::PREPEND_CHAR, '') } subgroups.each do |subgroup| dp.add_edge! subgroup, group end end # Figure out if we have a good depedency graph dep_order = dp.topsort if dep_order.empty? raise GroupDependencyError unless @groups.empty? end dep_order end #Raised when something in a config fails to parse properly class ParseError < RuntimeError end # Raised when group dependencies cannot be suitably resolved for output class GroupDependencyError < RuntimeError end end end
module Glicko2 VERSION = "0.0.1" end Bump to version 0.1.0 module Glicko2 VERSION = "0.1.0" end
Add morse decoder advanced # https://www.codewars.com/kata/54b72c16cd7f5154e9000457 def decodeBits(bits) bits = bits.sub(/^0+(?=1)/, "").sub(/(?<=1)0+$/, "") len = [*bits.scan(/1+/), *bits.scan(/0+/)].min_by(&:size).size bits = normalize_bits(bits, len) words = bits.split(/0{7}/) letters = words.map{ |w| w.split(/0{3}/) .map{ |l| l.split("0").map{ |j| j.gsub(/111?/, "-").gsub(/1/, ".") }.join }.join(" ") } .join(" ") end def decodeMorse(morse) words = morse.split(" ") letters = words.map{ |w| w.split(" ").map{ |l| MORSE_CODE[l] }.join }.join(" ") letters.strip end def normalize_bits(bits, len) bits.chars.each_slice(len).reduce("") { |acc, el| acc << el[0] } end
require File.dirname(__FILE__) + '/../../spec_helper' require File.dirname(__FILE__) + '/fixtures/classes' # TODO: change to a.should be_equal(b) # TODO: write spec for cloning classes and calling private methods # TODO: write spec for private_methods not showing up via extended describe "Singleton._load" do it "is a private method" do # TODO: SingletonSpecs::MyClass.private_methods.sort.should include("_load") lambda { # TODO: remove when above works SingletonSpecs::MyClass._load("") }.should raise_error(NoMethodError) SingletonSpecs::MyClass.send(:_load, "" ).should_not == nil end it "returns the singleton instance for anything passed in" do klass = SingletonSpecs::MyClass klass.send(:_load, "" ).should equal(klass.instance) klass.send(:_load, "42").should equal(klass.instance) klass.send(:_load, 42 ).should equal(klass.instance) end it "returns the singleton instance for anything passed in to subclass" do subklass = SingletonSpecs::MyClassChild subklass.send(:_load, "" ).should equal(subklass.instance) subklass.send(:_load, "42").should equal(subklass.instance) subklass.send(:_load, 42 ).should equal(subklass.instance) end end Singleton._load is not a private method anymore. require File.dirname(__FILE__) + '/../../spec_helper' require File.dirname(__FILE__) + '/fixtures/classes' # TODO: change to a.should be_equal(b) # TODO: write spec for cloning classes and calling private methods # TODO: write spec for private_methods not showing up via extended describe "Singleton._load" do it "returns the singleton instance for anything passed in" do klass = SingletonSpecs::MyClass klass._load("").should equal(klass.instance) klass._load("42").should equal(klass.instance) klass._load(42).should equal(klass.instance) end it "returns the singleton instance for anything passed in to subclass" do subklass = SingletonSpecs::MyClassChild subklass._load("").should equal(subklass.instance) subklass._load("42").should equal(subklass.instance) subklass._load(42).should equal(subklass.instance) end end
module Snapshot # Responsible for collecting the generated screenshots and copying them over to the output directory class Collector # Returns true if it succeeds def self.fetch_screenshots(output, dir_name, device_type, launch_arguments_index) # Documentation about how this works in the project README containing = File.join(TestCommandGenerator.derived_data_path, "Logs", "Test") attachments_path = File.join(containing, "Attachments") to_store = attachments(containing) matches = output.scan(/snapshot: (.*)/) if to_store.count == 0 && matches.count == 0 return false end if matches.count != to_store.count UI.error "Looks like the number of screenshots (#{to_store.count}) doesn't match the number of names (#{matches.count})" end matches.each_with_index do |current, index| name = current[0] filename = to_store[index] language_folder = File.join(Snapshot.config[:output_directory], dir_name) FileUtils.mkdir_p(language_folder) device_name = device_type.delete(" ") components = [device_name, launch_arguments_index, name].delete_if { |a| a.to_s.length == 0 } output_path = File.join(language_folder, components.join("-") + ".png") from_path = File.join(attachments_path, filename) if $verbose UI.success "Copying file '#{from_path}' to '#{output_path}'..." else UI.success "Copying '#{output_path}'..." end FileUtils.cp(from_path, output_path) end return true end def self.attachments(containing) UI.message "Collecting screenshots..." plist_path = Dir[File.join(containing, "*.plist")].last # we clean the folder before each run return attachments_in_file(plist_path) end def self.attachments_in_file(plist_path) UI.verbose "Loading up '#{plist_path}'..." report = Plist.parse_xml(plist_path) to_store = [] # contains the names of all the attachments we want to use report["TestableSummaries"].each do |summary| (summary["Tests"] || []).each do |test| (test["Subtests"] || []).each do |subtest| (subtest["Subtests"] || []).each do |subtest2| (subtest2["Subtests"] || []).each do |subtest3| (subtest3["ActivitySummaries"] || []).each do |activity| check_activity(activity, to_store) end end end end end end UI.message "Found #{to_store.count} screenshots..." UI.verbose "Found #{to_store.join(', ')}" return to_store end def self.check_activity(activity, to_store) # On iOS, we look for the "Unknown" rotation gesture that signals a snapshot was taken here. # On tvOS, we look for "Browser" count. # These are both events that are not normally triggered by UI testing, making it easy for us to # locate where snapshot() was invoked. if activity["Title"] == "Set device orientation to Unknown" || activity["Title"] == "Get number of matches for: Children matching type Browser" if activity["Attachments"] to_store << activity["Attachments"].last["FileName"] else # Xcode 7.3 has stopped including 'Attachments', so we synthesize the filename manually to_store << "Screenshot_#{activity['UUID']}.png" end end (activity["SubActivities"] || []).each do |subactivity| check_activity(subactivity, to_store) end end end end [snapshot] fix issue with launch arguments during copy of screenshots (#7670) * [snapsho] fix issue with launch arguments during copy of screenshots * use dev-name-md5.png as a file name. module Snapshot # Responsible for collecting the generated screenshots and copying them over to the output directory class Collector # Returns true if it succeeds def self.fetch_screenshots(output, dir_name, device_type, launch_arguments_index) # Documentation about how this works in the project README containing = File.join(TestCommandGenerator.derived_data_path, "Logs", "Test") attachments_path = File.join(containing, "Attachments") to_store = attachments(containing) matches = output.scan(/snapshot: (.*)/) if to_store.count == 0 && matches.count == 0 return false end if matches.count != to_store.count UI.error "Looks like the number of screenshots (#{to_store.count}) doesn't match the number of names (#{matches.count})" end matches.each_with_index do |current, index| name = current[0] filename = to_store[index] language_folder = File.join(Snapshot.config[:output_directory], dir_name) FileUtils.mkdir_p(language_folder) device_name = device_type.delete(" ") components = [launch_arguments_index].delete_if { |a| a.to_s.length == 0 } screenshot_name = device_name + "-" + name + "-" + Digest::MD5.hexdigest(components.join("-")) + ".png" output_path = File.join(language_folder, screenshot_name) from_path = File.join(attachments_path, filename) if $verbose UI.success "Copying file '#{from_path}' to '#{output_path}'..." else UI.success "Copying '#{output_path}'..." end FileUtils.cp(from_path, output_path) end return true end def self.attachments(containing) UI.message "Collecting screenshots..." plist_path = Dir[File.join(containing, "*.plist")].last # we clean the folder before each run return attachments_in_file(plist_path) end def self.attachments_in_file(plist_path) UI.verbose "Loading up '#{plist_path}'..." report = Plist.parse_xml(plist_path) to_store = [] # contains the names of all the attachments we want to use report["TestableSummaries"].each do |summary| (summary["Tests"] || []).each do |test| (test["Subtests"] || []).each do |subtest| (subtest["Subtests"] || []).each do |subtest2| (subtest2["Subtests"] || []).each do |subtest3| (subtest3["ActivitySummaries"] || []).each do |activity| check_activity(activity, to_store) end end end end end end UI.message "Found #{to_store.count} screenshots..." UI.verbose "Found #{to_store.join(', ')}" return to_store end def self.check_activity(activity, to_store) # On iOS, we look for the "Unknown" rotation gesture that signals a snapshot was taken here. # On tvOS, we look for "Browser" count. # These are both events that are not normally triggered by UI testing, making it easy for us to # locate where snapshot() was invoked. if activity["Title"] == "Set device orientation to Unknown" || activity["Title"] == "Get number of matches for: Children matching type Browser" if activity["Attachments"] to_store << activity["Attachments"].last["FileName"] else # Xcode 7.3 has stopped including 'Attachments', so we synthesize the filename manually to_store << "Screenshot_#{activity['UUID']}.png" end end (activity["SubActivities"] || []).each do |subactivity| check_activity(subactivity, to_store) end end end end
module Gorilla VERSION = "0.0.5" end Release v0.0.6 module Gorilla VERSION = "0.0.6" end
module Hancock VERSION = '0.7.14' end bump to version 0.7.15 module Hancock VERSION = '0.7.15' end
#! /usr/local/bin/ruby -w require 'rvg/rvg' include Magick rvg = RVG.new(200, 250) do |canvas| canvas.background_fill = 'white' canvas.g do |grp| grp.text(20, 20, "default size") grp.text(20, 40, ":font_size=>14").styles(:font_size=>14) grp.text(20, 60, ":font_size=>16").styles(:font_size=>16) grp.text(20, 90, ":font_size=>24").styles(:font_size=>24) end canvas.g.styles(:font_size=>14) do |grp| grp.text(18, 110, ":font_family=>'Courier'").styles(:font_family=>'Courier') grp.text(20, 130, ":font_weight=>'bold'").styles(:font_weight=>'bold') grp.text(20, 150, ":font_stretch=>'normal'").styles(:font_stretch=>'normal') grp.text(20, 170, ":font_stretch=>'condensed'").styles(:font_stretch=>'condensed') grp.text(20, 190, ":font_style=>'italic'").styles(:font_style=>'italic') grp.text(20, 210, ":font_weight=>900").styles(:font_weight=>900) end canvas.rect(199, 249).styles(:fill=>'none', :stroke=>'blue') end rvg.draw.write('font_styles.gif') Minor changes #! /usr/local/bin/ruby -w require 'rvg/rvg' include Magick rvg = RVG.new(200, 250) do |canvas| canvas.background_fill = 'white' canvas.g do |grp| grp.text(10, 30, "default size") grp.text(10, 50, ":font_size=>14").styles(:font_size=>14) grp.text(10, 70, ":font_size=>16").styles(:font_size=>16) grp.text(10,100, ":font_size=>24").styles(:font_size=>24) end canvas.g.styles(:font_size=>14) do |grp| grp.text( 8, 120, ":font_family=>'Courier'").styles(:font_family=>'Courier') grp.text(10, 140, ":font_weight=>'bold'").styles(:font_weight=>'bold') grp.text(10, 160, ":font_stretch=>'normal'").styles(:font_stretch=>'normal') grp.text(10, 180, ":font_stretch=>'condensed'").styles(:font_stretch=>'condensed') grp.text(10, 200, ":font_style=>'italic'").styles(:font_style=>'italic') grp.text(10, 220, ":font_weight=>900").styles(:font_weight=>900) end canvas.rect(199, 249).styles(:fill=>'none', :stroke=>'blue') end rvg.draw.write('font_styles.gif')
require 'cfndsl' volume_name = "ECSDataVolume" if defined? ecs_data_volume_name volume_name = ecs_data_volume_name end volume_size = 100 if defined? ecs_data_volume_size volume_size = ecs_data_volume_size end CloudFormation { # Template metadata AWSTemplateFormatVersion "2010-09-09" Description "ciinabox - ECS Cluster v#{ciinabox_version}" # Parameters Parameter("ECSCluster"){ Type 'String' } Parameter("VPC"){ Type 'String' } Parameter("RouteTablePrivateA"){ Type 'String' } Parameter("RouteTablePrivateB"){ Type 'String' } Parameter("SubnetPublicA"){ Type 'String' } Parameter("SubnetPublicB"){ Type 'String' } Parameter("SecurityGroupBackplane"){ Type 'String' } # Global mappings Mapping('EnvironmentType', Mappings['EnvironmentType']) Mapping('ecsAMI', ecs_ami) availability_zones.each do |az| Resource("SubnetPrivate#{az}") { Type 'AWS::EC2::Subnet' Property('VpcId', Ref('VPC')) Property('CidrBlock', FnJoin( "", [ FnFindInMap('EnvironmentType','ciinabox','NetworkPrefix'), ".", FnFindInMap('EnvironmentType','ciinabox','StackOctet'), ".", ecs["SubnetOctet#{az}"], ".0/", FnFindInMap('EnvironmentType','ciinabox','SubnetMask') ] )) Property('AvailabilityZone', FnSelect(azId[az], FnGetAZs(Ref( "AWS::Region" )) )) } end availability_zones.each do |az| Resource("SubnetRouteTableAssociationPrivate#{az}") { Type 'AWS::EC2::SubnetRouteTableAssociation' Property('SubnetId', Ref("SubnetPrivate#{az}")) Property('RouteTableId', Ref("RouteTablePrivate#{az}")) } end Resource("Role") { Type 'AWS::IAM::Role' Property('AssumeRolePolicyDocument', { Statement: [ Effect: 'Allow', Principal: { Service: [ 'ec2.amazonaws.com' ] }, Action: [ 'sts:AssumeRole' ] ] }) Property('Path','/') Property('Policies', [ { PolicyName: 'assume-role', PolicyDocument: { Statement: [ { Effect: 'Allow', Action: [ 'sts:AssumeRole' ], Resource: '*' } ] } }, { PolicyName: 'read-only', PolicyDocument: { Statement: [ { Effect: 'Allow', Action: [ 'ec2:Describe*', 's3:Get*', 's3:List*'], Resource: '*' } ] } }, { PolicyName: 's3-write', PolicyDocument: { Statement: [ { Effect: 'Allow', Action: [ 's3:PutObject', 's3:PutObject*' ], Resource: '*' } ] } }, { PolicyName: 'ecsServiceRole', PolicyDocument: { Statement: [ { Effect: 'Allow', Action: [ "ecs:CreateCluster", "ecs:DeregisterContainerInstance", "ecs:DiscoverPollEndpoint", "ecs:Poll", "ecs:RegisterContainerInstance", "ecs:StartTelemetrySession", "ecs:Submit*", "ec2:AuthorizeSecurityGroupIngress", "ec2:Describe*", "elasticloadbalancing:DeregisterInstancesFromLoadBalancer", "elasticloadbalancing:Describe*", "elasticloadbalancing:RegisterInstancesWithLoadBalancer" ], Resource: '*' } ] } }, { 'PolicyName' => 'ssm-run-command', 'PolicyDocument' => { 'Statement' => [ { 'Effect' => 'Allow', 'Action' => [ "ssm:DescribeAssociation", "ssm:GetDocument", "ssm:ListAssociations", "ssm:UpdateAssociationStatus", "ssm:UpdateInstanceInformation", "ec2messages:AcknowledgeMessage", "ec2messages:DeleteMessage", "ec2messages:FailMessage", "ec2messages:GetEndpoint", "ec2messages:GetMessages", "ec2messages:SendReply", "cloudwatch:PutMetricData", "ec2:DescribeInstanceStatus", "ds:CreateComputer", "ds:DescribeDirectories", "logs:CreateLogGroup", "logs:CreateLogStream", "logs:DescribeLogGroups", "logs:DescribeLogStreams", "logs:PutLogEvents", "s3:PutObject", "s3:GetObject", "s3:AbortMultipartUpload", "s3:ListMultipartUploadParts", "s3:ListBucketMultipartUploads" ], 'Resource' => '*' } ] } }, { PolicyName: 'ecr', PolicyDocument: { Statement: [ { Effect: 'Allow', Action: [ 'ecr:*' ], Resource: '*' } ] } }, { PolicyName: 'packer', PolicyDocument: { Statement: [ { Effect: 'Allow', Action: [ 'cloudformation:*', 'ec2:AttachVolume', 'ec2:CreateVolume', 'ec2:DeleteVolume', 'ec2:CreateKeypair', 'ec2:DeleteKeypair', 'ec2:CreateSecurityGroup', 'ec2:DeleteSecurityGroup', 'ec2:AuthorizeSecurityGroupIngress', 'ec2:CreateImage', 'ec2:RunInstances', 'ec2:TerminateInstances', 'ec2:StopInstances', 'ec2:DescribeVolumes', 'ec2:DetachVolume', 'ec2:DescribeInstances', 'ec2:CreateSnapshot', 'ec2:DeleteSnapshot', 'ec2:DescribeSnapshots', 'ec2:DescribeImages', 'ec2:RegisterImage', 'ec2:CreateTags', 'ec2:ModifyImageAttribute', 'ec2:GetPasswordData', 'iam:PassRole' ], Resource: '*' } ] } } ]) } InstanceProfile("InstanceProfile") { Path '/' Roles [ Ref('Role') ] } Volume(volume_name) { DeletionPolicy 'Snapshot' Size volume_size VolumeType 'gp2' if defined? ecs_data_volume_snapshot SnapshotId ecs_data_volume_snapshot end AvailabilityZone FnSelect(0, FnGetAZs("")) addTag("Name", "ciinabox-ecs-data-xx") addTag("Environment", 'ciinabox') addTag("EnvironmentType", 'ciinabox') addTag("Role", "ciinabox-data") addTag("MakeSnapshot", "true") } LaunchConfiguration( :LaunchConfig ) { ImageId FnFindInMap('ecsAMI',Ref('AWS::Region'),'ami') IamInstanceProfile Ref('InstanceProfile') KeyName FnFindInMap('EnvironmentType','ciinabox','KeyName') SecurityGroups [ Ref('SecurityGroupBackplane') ] InstanceType FnFindInMap('EnvironmentType','ciinabox','ECSInstanceType') if defined? ecs_docker_volume_size and ecs_docker_volume_size > 22 Property("BlockDeviceMappings", [ { "DeviceName" => "/dev/xvdcz", "Ebs" => { "VolumeSize" => ecs_docker_volume_size, "VolumeType" => "gp2" } }]) end UserData FnBase64(FnJoin("",[ "#!/bin/bash\n", "echo ECS_CLUSTER=", Ref('ECSCluster'), " >> /etc/ecs/ecs.config\n", "INSTANCE_ID=`/opt/aws/bin/ec2-metadata -i | cut -f2 -d: | cut -f2 -d-`\n", "PRIVATE_IP=`/opt/aws/bin/ec2-metadata -o | cut -f2 -d: | cut -f2 -d-`\n", "yum install -y python-pip\n", "python-pip install --upgrade awscli\n", "/usr/local/bin/aws --region ", Ref("AWS::Region"), " ec2 attach-volume --volume-id ", Ref(volume_name), " --instance-id i-${INSTANCE_ID} --device /dev/sdf\n", "echo 'waiting for ECS Data volume to attach' && sleep 20\n", "echo '/dev/xvdf /data ext4 defaults,nofail 0 2' >> /etc/fstab\n", "mkdir -p /data\n", "mount /data && echo \"ECS Data volume already formatted\" || mkfs -t ext4 /dev/xvdf\n", "mount -a && echo 'mounting ECS Data volume' || echo 'failed to mount ECS Data volume'\n", "chmod -R 777 /data\n", "mkdir -p /data/jenkins\n", "chown -R 1000:1000 /data/jenkins\n", "ifconfig eth0 mtu 1500\n", "curl https://amazon-ssm-", Ref("AWS::Region"),".s3.amazonaws.com/latest/linux_amd64/amazon-ssm-agent.rpm -o /tmp/amazon-ssm-agent.rpm\n", "yum install -y /tmp/amazon-ssm-agent.rpm\n", "stop ecs\n", "service docker stop\n", "service docker start\n", "start ecs\n", "docker run --name jenkins-docker-slave --privileged=true -d -e PORT=4444 -p 4444:4444 -p 2223:22 -v /data/jenkins-dind/:/var/lib/docker base2/ciinabox-dind-slave\n", "echo 'done!!!!'\n" ])) } AutoScalingGroup("AutoScaleGroup") { UpdatePolicy("AutoScalingRollingUpdate", { "MinInstancesInService" => "0", "MaxBatchSize" => "1", }) LaunchConfigurationName Ref('LaunchConfig') HealthCheckGracePeriod '500' MinSize 1 MaxSize 1 DesiredCapacity 1 VPCZoneIdentifier [ Ref('SubnetPrivateA') ] addTag("Name", FnJoin("",["ciinabox-ecs-xx"]), true) addTag("Environment",'ciinabox', true) addTag("EnvironmentType", 'ciinabox', true) addTag("Role", "ciinabox-ecs", true) } if defined? scale_up_schedule Resource("ScheduledActionUp") { Type 'AWS::AutoScaling::ScheduledAction' Property('AutoScalingGroupName', Ref('AutoScaleGroup')) Property('MinSize','1') Property('MaxSize', '1') Property('DesiredCapacity', '1') Property('Recurrence', scale_up_schedule) } end if defined? scale_down_schedule Resource("ScheduledActionDown") { Type 'AWS::AutoScaling::ScheduledAction' Property('AutoScalingGroupName', Ref('AutoScaleGroup')) Property('MinSize','0') Property('MaxSize', '0') Property('DesiredCapacity', '0') Property('Recurrence', scale_down_schedule) } end availability_zones.each do |az| Output("ECSSubnetPrivate#{az}") { Value(Ref("SubnetPrivate#{az}")) } end Output("ECSRole") { Value(Ref('Role')) } Output("ECSInstanceProfile") { Value(Ref('InstanceProfile')) } } update userdata to run chmod once require 'cfndsl' volume_name = "ECSDataVolume" if defined? ecs_data_volume_name volume_name = ecs_data_volume_name end volume_size = 100 if defined? ecs_data_volume_size volume_size = ecs_data_volume_size end CloudFormation { # Template metadata AWSTemplateFormatVersion "2010-09-09" Description "ciinabox - ECS Cluster v#{ciinabox_version}" # Parameters Parameter("ECSCluster"){ Type 'String' } Parameter("VPC"){ Type 'String' } Parameter("RouteTablePrivateA"){ Type 'String' } Parameter("RouteTablePrivateB"){ Type 'String' } Parameter("SubnetPublicA"){ Type 'String' } Parameter("SubnetPublicB"){ Type 'String' } Parameter("SecurityGroupBackplane"){ Type 'String' } # Global mappings Mapping('EnvironmentType', Mappings['EnvironmentType']) Mapping('ecsAMI', ecs_ami) availability_zones.each do |az| Resource("SubnetPrivate#{az}") { Type 'AWS::EC2::Subnet' Property('VpcId', Ref('VPC')) Property('CidrBlock', FnJoin( "", [ FnFindInMap('EnvironmentType','ciinabox','NetworkPrefix'), ".", FnFindInMap('EnvironmentType','ciinabox','StackOctet'), ".", ecs["SubnetOctet#{az}"], ".0/", FnFindInMap('EnvironmentType','ciinabox','SubnetMask') ] )) Property('AvailabilityZone', FnSelect(azId[az], FnGetAZs(Ref( "AWS::Region" )) )) } end availability_zones.each do |az| Resource("SubnetRouteTableAssociationPrivate#{az}") { Type 'AWS::EC2::SubnetRouteTableAssociation' Property('SubnetId', Ref("SubnetPrivate#{az}")) Property('RouteTableId', Ref("RouteTablePrivate#{az}")) } end Resource("Role") { Type 'AWS::IAM::Role' Property('AssumeRolePolicyDocument', { Statement: [ Effect: 'Allow', Principal: { Service: [ 'ec2.amazonaws.com' ] }, Action: [ 'sts:AssumeRole' ] ] }) Property('Path','/') Property('Policies', [ { PolicyName: 'assume-role', PolicyDocument: { Statement: [ { Effect: 'Allow', Action: [ 'sts:AssumeRole' ], Resource: '*' } ] } }, { PolicyName: 'read-only', PolicyDocument: { Statement: [ { Effect: 'Allow', Action: [ 'ec2:Describe*', 's3:Get*', 's3:List*'], Resource: '*' } ] } }, { PolicyName: 's3-write', PolicyDocument: { Statement: [ { Effect: 'Allow', Action: [ 's3:PutObject', 's3:PutObject*' ], Resource: '*' } ] } }, { PolicyName: 'ecsServiceRole', PolicyDocument: { Statement: [ { Effect: 'Allow', Action: [ "ecs:CreateCluster", "ecs:DeregisterContainerInstance", "ecs:DiscoverPollEndpoint", "ecs:Poll", "ecs:RegisterContainerInstance", "ecs:StartTelemetrySession", "ecs:Submit*", "ec2:AuthorizeSecurityGroupIngress", "ec2:Describe*", "elasticloadbalancing:DeregisterInstancesFromLoadBalancer", "elasticloadbalancing:Describe*", "elasticloadbalancing:RegisterInstancesWithLoadBalancer" ], Resource: '*' } ] } }, { 'PolicyName' => 'ssm-run-command', 'PolicyDocument' => { 'Statement' => [ { 'Effect' => 'Allow', 'Action' => [ "ssm:DescribeAssociation", "ssm:GetDocument", "ssm:ListAssociations", "ssm:UpdateAssociationStatus", "ssm:UpdateInstanceInformation", "ec2messages:AcknowledgeMessage", "ec2messages:DeleteMessage", "ec2messages:FailMessage", "ec2messages:GetEndpoint", "ec2messages:GetMessages", "ec2messages:SendReply", "cloudwatch:PutMetricData", "ec2:DescribeInstanceStatus", "ds:CreateComputer", "ds:DescribeDirectories", "logs:CreateLogGroup", "logs:CreateLogStream", "logs:DescribeLogGroups", "logs:DescribeLogStreams", "logs:PutLogEvents", "s3:PutObject", "s3:GetObject", "s3:AbortMultipartUpload", "s3:ListMultipartUploadParts", "s3:ListBucketMultipartUploads" ], 'Resource' => '*' } ] } }, { PolicyName: 'ecr', PolicyDocument: { Statement: [ { Effect: 'Allow', Action: [ 'ecr:*' ], Resource: '*' } ] } }, { PolicyName: 'packer', PolicyDocument: { Statement: [ { Effect: 'Allow', Action: [ 'cloudformation:*', 'ec2:AttachVolume', 'ec2:CreateVolume', 'ec2:DeleteVolume', 'ec2:CreateKeypair', 'ec2:DeleteKeypair', 'ec2:CreateSecurityGroup', 'ec2:DeleteSecurityGroup', 'ec2:AuthorizeSecurityGroupIngress', 'ec2:CreateImage', 'ec2:RunInstances', 'ec2:TerminateInstances', 'ec2:StopInstances', 'ec2:DescribeVolumes', 'ec2:DetachVolume', 'ec2:DescribeInstances', 'ec2:CreateSnapshot', 'ec2:DeleteSnapshot', 'ec2:DescribeSnapshots', 'ec2:DescribeImages', 'ec2:RegisterImage', 'ec2:CreateTags', 'ec2:ModifyImageAttribute', 'ec2:GetPasswordData', 'iam:PassRole' ], Resource: '*' } ] } } ]) } InstanceProfile("InstanceProfile") { Path '/' Roles [ Ref('Role') ] } Volume(volume_name) { DeletionPolicy 'Snapshot' Size volume_size VolumeType 'gp2' if defined? ecs_data_volume_snapshot SnapshotId ecs_data_volume_snapshot end AvailabilityZone FnSelect(0, FnGetAZs("")) addTag("Name", "ciinabox-ecs-data-xx") addTag("Environment", 'ciinabox') addTag("EnvironmentType", 'ciinabox') addTag("Role", "ciinabox-data") addTag("MakeSnapshot", "true") } LaunchConfiguration( :LaunchConfig ) { ImageId FnFindInMap('ecsAMI',Ref('AWS::Region'),'ami') IamInstanceProfile Ref('InstanceProfile') KeyName FnFindInMap('EnvironmentType','ciinabox','KeyName') SecurityGroups [ Ref('SecurityGroupBackplane') ] InstanceType FnFindInMap('EnvironmentType','ciinabox','ECSInstanceType') if defined? ecs_docker_volume_size and ecs_docker_volume_size > 22 Property("BlockDeviceMappings", [ { "DeviceName" => "/dev/xvdcz", "Ebs" => { "VolumeSize" => ecs_docker_volume_size, "VolumeType" => "gp2" } }]) end UserData FnBase64(FnJoin("",[ "#!/bin/bash\n", "echo ECS_CLUSTER=", Ref('ECSCluster'), " >> /etc/ecs/ecs.config\n", "INSTANCE_ID=`/opt/aws/bin/ec2-metadata -i | cut -f2 -d: | cut -f2 -d-`\n", "PRIVATE_IP=`/opt/aws/bin/ec2-metadata -o | cut -f2 -d: | cut -f2 -d-`\n", "yum install -y python-pip\n", "python-pip install --upgrade awscli\n", "/usr/local/bin/aws --region ", Ref("AWS::Region"), " ec2 attach-volume --volume-id ", Ref(volume_name), " --instance-id i-${INSTANCE_ID} --device /dev/sdf\n", "echo 'waiting for ECS Data volume to attach' && sleep 20\n", "echo '/dev/xvdf /data ext4 defaults,nofail 0 2' >> /etc/fstab\n", "mkdir -p /data\n", "mount /data && echo \"ECS Data volume already formatted\" || mkfs -t ext4 /dev/xvdf\n", "mount -a && echo 'mounting ECS Data volume' || echo 'failed to mount ECS Data volume'\n", "export BOOTSTRAP=/data/bootstrap \n", "if [ ! -e \"$BOOTSTRAP\" ]; then echo \"boostrapping\"; chmod -R 777 /data; mkdir -p /data/jenkins; chown -R 1000:1000 /data/jenkins; touch $BOOTSTRAP; fi \n" "ifconfig eth0 mtu 1500\n", "curl https://amazon-ssm-", Ref("AWS::Region"),".s3.amazonaws.com/latest/linux_amd64/amazon-ssm-agent.rpm -o /tmp/amazon-ssm-agent.rpm\n", "yum install -y /tmp/amazon-ssm-agent.rpm\n", "stop ecs\n", "service docker stop\n", "service docker start\n", "start ecs\n", "docker run --name jenkins-docker-slave --privileged=true -d -e PORT=4444 -p 4444:4444 -p 2223:22 -v /data/jenkins-dind/:/var/lib/docker base2/ciinabox-dind-slave\n", "echo 'done!!!!'\n" ])) } AutoScalingGroup("AutoScaleGroup") { UpdatePolicy("AutoScalingRollingUpdate", { "MinInstancesInService" => "0", "MaxBatchSize" => "1", }) LaunchConfigurationName Ref('LaunchConfig') HealthCheckGracePeriod '500' MinSize 1 MaxSize 1 DesiredCapacity 1 VPCZoneIdentifier [ Ref('SubnetPrivateA') ] addTag("Name", FnJoin("",["ciinabox-ecs-xx"]), true) addTag("Environment",'ciinabox', true) addTag("EnvironmentType", 'ciinabox', true) addTag("Role", "ciinabox-ecs", true) } if defined? scale_up_schedule Resource("ScheduledActionUp") { Type 'AWS::AutoScaling::ScheduledAction' Property('AutoScalingGroupName', Ref('AutoScaleGroup')) Property('MinSize','1') Property('MaxSize', '1') Property('DesiredCapacity', '1') Property('Recurrence', scale_up_schedule) } end if defined? scale_down_schedule Resource("ScheduledActionDown") { Type 'AWS::AutoScaling::ScheduledAction' Property('AutoScalingGroupName', Ref('AutoScaleGroup')) Property('MinSize','0') Property('MaxSize', '0') Property('DesiredCapacity', '0') Property('Recurrence', scale_down_schedule) } end availability_zones.each do |az| Output("ECSSubnetPrivate#{az}") { Value(Ref("SubnetPrivate#{az}")) } end Output("ECSRole") { Value(Ref('Role')) } Output("ECSInstanceProfile") { Value(Ref('InstanceProfile')) } }
require 'backports' require_relative 'spec_helper' require 'fileutils' describe Sinatra::Reloader do # Returns the temporary directory. def tmp_dir File.expand_path('../../tmp', __FILE__) end # Returns the path of the Sinatra application file created by # +setup_example_app+. def app_file_path File.join(tmp_dir, "example_app_#{@@example_app_counter}.rb") end # Returns the name of the Sinatra application created by # +setup_example_app+: 'ExampleApp1' for the first application, # 'ExampleApp2' fo the second one, and so on... def app_name "ExampleApp#{@@example_app_counter}" end # Returns the (constant of the) Sinatra application created by # +setup_example_app+. def app_const Module.const_get(app_name) end # Writes a file with a Sinatra application using the template # located at <tt>specs/reloader/app.rb.erb</tt>. It expects an # +options+ hash, with an array of strings containing the # application's routes (+:routes+ key), a hash with the inline # template's names as keys and the bodys as values # (+:inline_templates+ key) and an optional application name # (+:name+) otherwise +app_name+ is used. # # It ensures to change the written file's mtime when it already # exists. def write_app_file(options={}) options[:routes] ||= ['get("/foo") { erb :foo }'] options[:inline_templates] ||= nil options[:extensions] ||= [] options[:middlewares] ||= [] options[:filters] ||= [] options[:errors] ||= {} options[:name] ||= app_name options[:enable_reloader] = true unless options[:enable_reloader] === false options[:parent] ||= 'Sinatra::Base' update_file(app_file_path) do |f| template_path = File.expand_path('../reloader/app.rb.erb', __FILE__) template = Tilt.new(template_path, nil, :trim => '<>') f.write template.render(Object.new, options) end end alias update_app_file write_app_file # It calls <tt>File.open(path, 'w', &block)</tt> all the times # needed to change the file's mtime. def update_file(path, &block) original_mtime = File.exist?(path) ? File.mtime(path) : Time.at(0) new_time = original_mtime + 1 File.open(path, 'w', &block) File.utime(new_time, new_time, path) end # Writes a Sinatra application to a file, requires the file, sets # the new application as the one being tested and enables the # reloader. def setup_example_app(options={}) @@example_app_counter ||= 0 @@example_app_counter += 1 FileUtils.mkdir_p(tmp_dir) write_app_file(options) $LOADED_FEATURES.delete app_file_path require app_file_path self.app = app_const app_const.enable :reloader end after(:all) { FileUtils.rm_rf(tmp_dir) } describe "default route reloading mechanism" do before(:each) do setup_example_app(:routes => ['get("/foo") { "foo" }']) end it "doesn't mess up the application" do get('/foo').body.should == 'foo' end it "knows when a route has been modified" do update_app_file(:routes => ['get("/foo") { "bar" }']) get('/foo').body.should == 'bar' end it "knows when a route has been added" do update_app_file( :routes => ['get("/foo") { "foo" }', 'get("/bar") { "bar" }'] ) get('/foo').body.should == 'foo' get('/bar').body.should == 'bar' end it "knows when a route has been removed" do update_app_file(:routes => ['get("/bar") { "bar" }']) get('/foo').status.should == 404 end it "doesn't try to reload a removed file" do update_app_file(:routes => ['get("/foo") { "i shall not be reloaded" }']) FileUtils.rm app_file_path get('/foo').body.strip.should == 'foo' end end describe "default inline templates reloading mechanism" do before(:each) do setup_example_app( :routes => ['get("/foo") { erb :foo }'], :inline_templates => { :foo => 'foo' } ) end it "doesn't mess up the application" do get('/foo').body.strip.should == 'foo' end it "reloads inline templates in the app file" do update_app_file( :routes => ['get("/foo") { erb :foo }'], :inline_templates => { :foo => 'bar' } ) get('/foo').body.strip.should == 'bar' end it "reloads inline templates in other file" do setup_example_app(:routes => ['get("/foo") { erb :foo }']) template_file_path = File.join(tmp_dir, 'templates.rb') File.open(template_file_path, 'w') do |f| f.write "__END__\n\n@@foo\nfoo" end require template_file_path app_const.inline_templates= template_file_path get('/foo').body.strip.should == 'foo' update_file(template_file_path) do |f| f.write "__END__\n\n@@foo\nbar" end get('/foo').body.strip.should == 'bar' end end describe "default middleware reloading mechanism" do it "knows when a middleware has been added" do setup_example_app(:routes => ['get("/foo") { "foo" }']) update_app_file( :routes => ['get("/foo") { "foo" }'], :middlewares => [Rack::Head] ) get('/foo') # ...to perform the reload app_const.middleware.should_not be_empty end it "knows when a middleware has been removed" do setup_example_app( :routes => ['get("/foo") { "foo" }'], :middlewares => [Rack::Head] ) update_app_file(:routes => ['get("/foo") { "foo" }']) get('/foo') # ...to perform the reload app_const.middleware.should be_empty end end describe "default filter reloading mechanism" do it "knows when a before filter has been added" do setup_example_app(:routes => ['get("/foo") { "foo" }']) expect { update_app_file( :routes => ['get("/foo") { "foo" }'], :filters => ['before { @hi = "hi" }'] ) get('/foo') # ...to perform the reload }.to change { app_const.filters[:before].size }.by(1) end it "knows when an after filter has been added" do setup_example_app(:routes => ['get("/foo") { "foo" }']) expect { update_app_file( :routes => ['get("/foo") { "foo" }'], :filters => ['after { @bye = "bye" }'] ) get('/foo') # ...to perform the reload }.to change { app_const.filters[:after].size }.by(1) end it "knows when a before filter has been removed" do setup_example_app( :routes => ['get("/foo") { "foo" }'], :filters => ['before { @hi = "hi" }'] ) expect { update_app_file(:routes => ['get("/foo") { "foo" }']) get('/foo') # ...to perform the reload }.to change { app_const.filters[:before].size }.by(-1) end it "knows when an after filter has been removed" do setup_example_app( :routes => ['get("/foo") { "foo" }'], :filters => ['after { @bye = "bye" }'] ) expect { update_app_file(:routes => ['get("/foo") { "foo" }']) get('/foo') # ...to perform the reload }.to change { app_const.filters[:after].size }.by(-1) end end describe "error reloading" do before do setup_example_app( :routes => ['get("/secret") { 403 }'], :errors => { 403 => "'Access forbiden'" } ) end it "doesn't mess up the application" do get('/secret').should be_client_error get('/secret').body.strip.should == 'Access forbiden' end it "knows when a error has been added" do update_app_file(:errors => { 404 => "'Nowhere'" }) get('/nowhere').should be_not_found get('/nowhere').body.should == 'Nowhere' end it "knows when a error has been removed" do update_app_file(:routes => ['get("/secret") { 403 }']) get('/secret').should be_client_error get('/secret').body.should_not == 'Access forbiden' end it "knows when a error has been modified" do update_app_file( :routes => ['get("/secret") { 403 }'], :errors => { 403 => "'What are you doing here?'" } ) get('/secret').should be_client_error get('/secret').body.should == 'What are you doing here?' end end describe "extension reloading" do it "doesn't duplicate routes with every reload" do module ::RouteExtension def self.registered(klass) klass.get('/bar') { 'bar' } end end setup_example_app( :routes => ['get("/foo") { "foo" }'], :extensions => ['RouteExtension'] ) expect { update_app_file( :routes => ['get("/foo") { "foo" }'], :extensions => ['RouteExtension'] ) get('/foo') # ...to perform the reload }.to_not change { app_const.routes['GET'].size } end it "doesn't duplicate middleware with every reload" do module ::MiddlewareExtension def self.registered(klass) klass.use Rack::Head end end setup_example_app( :routes => ['get("/foo") { "foo" }'], :extensions => ['MiddlewareExtension'] ) expect { update_app_file( :routes => ['get("/foo") { "foo" }'], :extensions => ['MiddlewareExtension'] ) get('/foo') # ...to perform the reload }.to_not change { app_const.middleware.size } end it "doesn't duplicate before filters with every reload" do module ::BeforeFilterExtension def self.registered(klass) klass.before { @hi = 'hi' } end end setup_example_app( :routes => ['get("/foo") { "foo" }'], :extensions => ['BeforeFilterExtension'] ) expect { update_app_file( :routes => ['get("/foo") { "foo" }'], :extensions => ['BeforeFilterExtension'] ) get('/foo') # ...to perform the reload }.to_not change { app_const.filters[:before].size } end it "doesn't duplicate after filters with every reload" do module ::AfterFilterExtension def self.registered(klass) klass.after { @bye = 'bye' } end end setup_example_app( :routes => ['get("/foo") { "foo" }'], :extensions => ['AfterFilterExtension'] ) expect { update_app_file( :routes => ['get("/foo") { "foo" }'], :extensions => ['AfterFilterExtension'] ) get('/foo') # ...to perform the reload }.to_not change { app_const.filters[:after].size } end end describe ".dont_reload" do before(:each) do setup_example_app( :routes => ['get("/foo") { erb :foo }'], :inline_templates => { :foo => 'foo' } ) end it "allows to specify a file to stop from being reloaded" do app_const.dont_reload app_file_path update_app_file(:routes => ['get("/foo") { "bar" }']) get('/foo').body.strip.should == 'foo' end it "allows to specify a glob to stop matching files from being reloaded" do app_const.dont_reload '**/*.rb' update_app_file(:routes => ['get("/foo") { "bar" }']) get('/foo').body.strip.should == 'foo' end it "doesn't interfere with other application's reloading policy" do app_const.dont_reload '**/*.rb' setup_example_app(:routes => ['get("/foo") { "foo" }']) update_app_file(:routes => ['get("/foo") { "bar" }']) get('/foo').body.strip.should == 'bar' end end describe ".also_reload" do before(:each) do setup_example_app(:routes => ['get("/foo") { Foo.foo }']) @foo_path = File.join(tmp_dir, 'foo.rb') update_file(@foo_path) do |f| f.write 'class Foo; def self.foo() "foo" end end' end $LOADED_FEATURES.delete @foo_path require @foo_path app_const.also_reload @foo_path end it "allows to specify a file to be reloaded" do get('/foo').body.strip.should == 'foo' update_file(@foo_path) do |f| f.write 'class Foo; def self.foo() "bar" end end' end get('/foo').body.strip.should == 'bar' end it "allows to specify glob to reaload matching files" do get('/foo').body.strip.should == 'foo' update_file(@foo_path) do |f| f.write 'class Foo; def self.foo() "bar" end end' end get('/foo').body.strip.should == 'bar' end it "doesn't try to reload a removed file" do update_file(@foo_path) do |f| f.write 'class Foo; def self.foo() "bar" end end' end FileUtils.rm @foo_path get('/foo').body.strip.should == 'foo' end it "doesn't interfere with other application's reloading policy" do app_const.also_reload '**/*.rb' setup_example_app(:routes => ['get("/foo") { Foo.foo }']) get('/foo').body.strip.should == 'foo' update_file(@foo_path) do |f| f.write 'class Foo; def self.foo() "bar" end end' end get('/foo').body.strip.should == 'foo' end end it "automatically registers the reloader in the subclasses" do class ::Parent < Sinatra::Base register Sinatra::Reloader enable :reloader end setup_example_app( :routes => ['get("/foo") { "foo" }'], :enable_reloader => false, :parent => 'Parent' ) update_app_file( :routes => ['get("/foo") { "bar" }'], :enable_reloader => false, :parent => 'Parent' ) get('/foo').body.should == 'bar' end end Use global rather than class vars in reloader spec The use of class variables in the Reloader spec would trigger warnings in Ruby 1.9.3 and (I believe) cause the Rubinius failures in same specs. Related bug: http://bugs.ruby-lang.org/issues/3080 require 'backports' require_relative 'spec_helper' require 'fileutils' describe Sinatra::Reloader do # Returns the temporary directory. def tmp_dir File.expand_path('../../tmp', __FILE__) end # Returns the path of the Sinatra application file created by # +setup_example_app+. def app_file_path File.join(tmp_dir, "example_app_#{$example_app_counter}.rb") end # Returns the name of the Sinatra application created by # +setup_example_app+: 'ExampleApp1' for the first application, # 'ExampleApp2' fo the second one, and so on... def app_name "ExampleApp#{$example_app_counter}" end # Returns the (constant of the) Sinatra application created by # +setup_example_app+. def app_const Module.const_get(app_name) end # Writes a file with a Sinatra application using the template # located at <tt>specs/reloader/app.rb.erb</tt>. It expects an # +options+ hash, with an array of strings containing the # application's routes (+:routes+ key), a hash with the inline # template's names as keys and the bodys as values # (+:inline_templates+ key) and an optional application name # (+:name+) otherwise +app_name+ is used. # # It ensures to change the written file's mtime when it already # exists. def write_app_file(options={}) options[:routes] ||= ['get("/foo") { erb :foo }'] options[:inline_templates] ||= nil options[:extensions] ||= [] options[:middlewares] ||= [] options[:filters] ||= [] options[:errors] ||= {} options[:name] ||= app_name options[:enable_reloader] = true unless options[:enable_reloader] === false options[:parent] ||= 'Sinatra::Base' update_file(app_file_path) do |f| template_path = File.expand_path('../reloader/app.rb.erb', __FILE__) template = Tilt.new(template_path, nil, :trim => '<>') f.write template.render(Object.new, options) end end alias update_app_file write_app_file # It calls <tt>File.open(path, 'w', &block)</tt> all the times # needed to change the file's mtime. def update_file(path, &block) original_mtime = File.exist?(path) ? File.mtime(path) : Time.at(0) new_time = original_mtime + 1 File.open(path, 'w', &block) File.utime(new_time, new_time, path) end # Writes a Sinatra application to a file, requires the file, sets # the new application as the one being tested and enables the # reloader. def setup_example_app(options={}) $example_app_counter ||= 0 $example_app_counter += 1 FileUtils.mkdir_p(tmp_dir) write_app_file(options) $LOADED_FEATURES.delete app_file_path require app_file_path self.app = app_const app_const.enable :reloader end after(:all) { FileUtils.rm_rf(tmp_dir) } describe "default route reloading mechanism" do before(:each) do setup_example_app(:routes => ['get("/foo") { "foo" }']) end it "doesn't mess up the application" do get('/foo').body.should == 'foo' end it "knows when a route has been modified" do update_app_file(:routes => ['get("/foo") { "bar" }']) get('/foo').body.should == 'bar' end it "knows when a route has been added" do update_app_file( :routes => ['get("/foo") { "foo" }', 'get("/bar") { "bar" }'] ) get('/foo').body.should == 'foo' get('/bar').body.should == 'bar' end it "knows when a route has been removed" do update_app_file(:routes => ['get("/bar") { "bar" }']) get('/foo').status.should == 404 end it "doesn't try to reload a removed file" do update_app_file(:routes => ['get("/foo") { "i shall not be reloaded" }']) FileUtils.rm app_file_path get('/foo').body.strip.should == 'foo' end end describe "default inline templates reloading mechanism" do before(:each) do setup_example_app( :routes => ['get("/foo") { erb :foo }'], :inline_templates => { :foo => 'foo' } ) end it "doesn't mess up the application" do get('/foo').body.strip.should == 'foo' end it "reloads inline templates in the app file" do update_app_file( :routes => ['get("/foo") { erb :foo }'], :inline_templates => { :foo => 'bar' } ) get('/foo').body.strip.should == 'bar' end it "reloads inline templates in other file" do setup_example_app(:routes => ['get("/foo") { erb :foo }']) template_file_path = File.join(tmp_dir, 'templates.rb') File.open(template_file_path, 'w') do |f| f.write "__END__\n\n@@foo\nfoo" end require template_file_path app_const.inline_templates= template_file_path get('/foo').body.strip.should == 'foo' update_file(template_file_path) do |f| f.write "__END__\n\n@@foo\nbar" end get('/foo').body.strip.should == 'bar' end end describe "default middleware reloading mechanism" do it "knows when a middleware has been added" do setup_example_app(:routes => ['get("/foo") { "foo" }']) update_app_file( :routes => ['get("/foo") { "foo" }'], :middlewares => [Rack::Head] ) get('/foo') # ...to perform the reload app_const.middleware.should_not be_empty end it "knows when a middleware has been removed" do setup_example_app( :routes => ['get("/foo") { "foo" }'], :middlewares => [Rack::Head] ) update_app_file(:routes => ['get("/foo") { "foo" }']) get('/foo') # ...to perform the reload app_const.middleware.should be_empty end end describe "default filter reloading mechanism" do it "knows when a before filter has been added" do setup_example_app(:routes => ['get("/foo") { "foo" }']) expect { update_app_file( :routes => ['get("/foo") { "foo" }'], :filters => ['before { @hi = "hi" }'] ) get('/foo') # ...to perform the reload }.to change { app_const.filters[:before].size }.by(1) end it "knows when an after filter has been added" do setup_example_app(:routes => ['get("/foo") { "foo" }']) expect { update_app_file( :routes => ['get("/foo") { "foo" }'], :filters => ['after { @bye = "bye" }'] ) get('/foo') # ...to perform the reload }.to change { app_const.filters[:after].size }.by(1) end it "knows when a before filter has been removed" do setup_example_app( :routes => ['get("/foo") { "foo" }'], :filters => ['before { @hi = "hi" }'] ) expect { update_app_file(:routes => ['get("/foo") { "foo" }']) get('/foo') # ...to perform the reload }.to change { app_const.filters[:before].size }.by(-1) end it "knows when an after filter has been removed" do setup_example_app( :routes => ['get("/foo") { "foo" }'], :filters => ['after { @bye = "bye" }'] ) expect { update_app_file(:routes => ['get("/foo") { "foo" }']) get('/foo') # ...to perform the reload }.to change { app_const.filters[:after].size }.by(-1) end end describe "error reloading" do before do setup_example_app( :routes => ['get("/secret") { 403 }'], :errors => { 403 => "'Access forbiden'" } ) end it "doesn't mess up the application" do get('/secret').should be_client_error get('/secret').body.strip.should == 'Access forbiden' end it "knows when a error has been added" do update_app_file(:errors => { 404 => "'Nowhere'" }) get('/nowhere').should be_not_found get('/nowhere').body.should == 'Nowhere' end it "knows when a error has been removed" do update_app_file(:routes => ['get("/secret") { 403 }']) get('/secret').should be_client_error get('/secret').body.should_not == 'Access forbiden' end it "knows when a error has been modified" do update_app_file( :routes => ['get("/secret") { 403 }'], :errors => { 403 => "'What are you doing here?'" } ) get('/secret').should be_client_error get('/secret').body.should == 'What are you doing here?' end end describe "extension reloading" do it "doesn't duplicate routes with every reload" do module ::RouteExtension def self.registered(klass) klass.get('/bar') { 'bar' } end end setup_example_app( :routes => ['get("/foo") { "foo" }'], :extensions => ['RouteExtension'] ) expect { update_app_file( :routes => ['get("/foo") { "foo" }'], :extensions => ['RouteExtension'] ) get('/foo') # ...to perform the reload }.to_not change { app_const.routes['GET'].size } end it "doesn't duplicate middleware with every reload" do module ::MiddlewareExtension def self.registered(klass) klass.use Rack::Head end end setup_example_app( :routes => ['get("/foo") { "foo" }'], :extensions => ['MiddlewareExtension'] ) expect { update_app_file( :routes => ['get("/foo") { "foo" }'], :extensions => ['MiddlewareExtension'] ) get('/foo') # ...to perform the reload }.to_not change { app_const.middleware.size } end it "doesn't duplicate before filters with every reload" do module ::BeforeFilterExtension def self.registered(klass) klass.before { @hi = 'hi' } end end setup_example_app( :routes => ['get("/foo") { "foo" }'], :extensions => ['BeforeFilterExtension'] ) expect { update_app_file( :routes => ['get("/foo") { "foo" }'], :extensions => ['BeforeFilterExtension'] ) get('/foo') # ...to perform the reload }.to_not change { app_const.filters[:before].size } end it "doesn't duplicate after filters with every reload" do module ::AfterFilterExtension def self.registered(klass) klass.after { @bye = 'bye' } end end setup_example_app( :routes => ['get("/foo") { "foo" }'], :extensions => ['AfterFilterExtension'] ) expect { update_app_file( :routes => ['get("/foo") { "foo" }'], :extensions => ['AfterFilterExtension'] ) get('/foo') # ...to perform the reload }.to_not change { app_const.filters[:after].size } end end describe ".dont_reload" do before(:each) do setup_example_app( :routes => ['get("/foo") { erb :foo }'], :inline_templates => { :foo => 'foo' } ) end it "allows to specify a file to stop from being reloaded" do app_const.dont_reload app_file_path update_app_file(:routes => ['get("/foo") { "bar" }']) get('/foo').body.strip.should == 'foo' end it "allows to specify a glob to stop matching files from being reloaded" do app_const.dont_reload '**/*.rb' update_app_file(:routes => ['get("/foo") { "bar" }']) get('/foo').body.strip.should == 'foo' end it "doesn't interfere with other application's reloading policy" do app_const.dont_reload '**/*.rb' setup_example_app(:routes => ['get("/foo") { "foo" }']) update_app_file(:routes => ['get("/foo") { "bar" }']) get('/foo').body.strip.should == 'bar' end end describe ".also_reload" do before(:each) do setup_example_app(:routes => ['get("/foo") { Foo.foo }']) @foo_path = File.join(tmp_dir, 'foo.rb') update_file(@foo_path) do |f| f.write 'class Foo; def self.foo() "foo" end end' end $LOADED_FEATURES.delete @foo_path require @foo_path app_const.also_reload @foo_path end it "allows to specify a file to be reloaded" do get('/foo').body.strip.should == 'foo' update_file(@foo_path) do |f| f.write 'class Foo; def self.foo() "bar" end end' end get('/foo').body.strip.should == 'bar' end it "allows to specify glob to reaload matching files" do get('/foo').body.strip.should == 'foo' update_file(@foo_path) do |f| f.write 'class Foo; def self.foo() "bar" end end' end get('/foo').body.strip.should == 'bar' end it "doesn't try to reload a removed file" do update_file(@foo_path) do |f| f.write 'class Foo; def self.foo() "bar" end end' end FileUtils.rm @foo_path get('/foo').body.strip.should == 'foo' end it "doesn't interfere with other application's reloading policy" do app_const.also_reload '**/*.rb' setup_example_app(:routes => ['get("/foo") { Foo.foo }']) get('/foo').body.strip.should == 'foo' update_file(@foo_path) do |f| f.write 'class Foo; def self.foo() "bar" end end' end get('/foo').body.strip.should == 'foo' end end it "automatically registers the reloader in the subclasses" do class ::Parent < Sinatra::Base register Sinatra::Reloader enable :reloader end setup_example_app( :routes => ['get("/foo") { "foo" }'], :enable_reloader => false, :parent => 'Parent' ) update_app_file( :routes => ['get("/foo") { "bar" }'], :enable_reloader => false, :parent => 'Parent' ) get('/foo').body.should == 'bar' end end
updated install.rb
require 'yaml' def build_cmd(docker_tag) cmd = 'clear && docker exec -it $1 sh' yaml_file = File.expand_path('~/.docker-exec.yml') if File.exist?(yaml_file) config = YAML.load_file(yaml_file) cmd_pieces = [] if config.key?('env') config['env'].each { |key, value| cmd_pieces << "export #{key.upcase}='#{value}'" } end if config.key?('bashrc') cmd_pieces << 'if [[ ! -e ~/.bashrc ]]; then touch ~/.bashrc; fi' cmd_pieces << 'if [[ ! -e ~/.bashrc-backup ]]; then cp ~/.bashrc ~/.bashrc-backup; fi' cmd_pieces << 'if [[ -e ~/.bashrc-docker-exec ]]; then cp ~/.bashrc-backup ~/.bashrc; fi' cmd_pieces << 'rm -f ~/.bashrc-docker-exec' config['bashrc'].each { |line| cmd_pieces << "echo \\\"#{line.tr('"', "'")}\\\" >> ~/.bashrc-docker-exec" } cmd_pieces << 'echo \\"source ~/.bashrc-docker-exec\\" >> ~/.bashrc' end if config.key?('cmd') config['cmd'].each { |line| cmd_pieces << line.gsub('"', '\\"') } end unless cmd_pieces.empty? cmd_pieces << 'bash' cmd += " -c \"#{cmd_pieces.join(' && ')}\"" end end docker_tag = ARGV[ARGV.length - 1] cmd.gsub(/\$1/, docker_tag).gsub(/\$2/, docker_tag.tr('_', '-')) end if __FILE__ == $PROGRAM_NAME if ARGV.empty? puts 'You need to pass in a docker tag name' exit end puts build_cmd(ARGV[ARGV.length - 1]) end have docker exec use bash instead of sh require 'yaml' def build_cmd(docker_tag) cmd = 'clear && docker exec -it $1 bash' yaml_file = File.expand_path('~/.docker-exec.yml') if File.exist?(yaml_file) config = YAML.load_file(yaml_file) cmd_pieces = [] if config.key?('env') config['env'].each { |key, value| cmd_pieces << "export #{key.upcase}='#{value}'" } end if config.key?('bashrc') cmd_pieces << 'if [[ ! -e ~/.bashrc ]]; then touch ~/.bashrc; fi' cmd_pieces << 'if [[ ! -e ~/.bashrc-backup ]]; then cp ~/.bashrc ~/.bashrc-backup; fi' cmd_pieces << 'if [[ -e ~/.bashrc-docker-exec ]]; then cp ~/.bashrc-backup ~/.bashrc; fi' cmd_pieces << 'rm -f ~/.bashrc-docker-exec' config['bashrc'].each { |line| cmd_pieces << "echo \\\"#{line.tr('"', "'")}\\\" >> ~/.bashrc-docker-exec" } cmd_pieces << 'echo \\"source ~/.bashrc-docker-exec\\" >> ~/.bashrc' end if config.key?('cmd') config['cmd'].each { |line| cmd_pieces << line.gsub('"', '\\"') } end unless cmd_pieces.empty? cmd_pieces << 'bash' cmd += " -c \"#{cmd_pieces.join(' && ')}\"" end end docker_tag = ARGV[ARGV.length - 1] cmd.gsub(/\$1/, docker_tag).gsub(/\$2/, docker_tag.tr('_', '-')) end if __FILE__ == $PROGRAM_NAME if ARGV.empty? puts 'You need to pass in a docker tag name' exit end puts build_cmd(ARGV[ARGV.length - 1]) end
Pod::Spec.new do |s| s.name = 'AFFAlertView' s.version = '0.0.1' s.authors = { 'Jeremy Fuellert' => 'jfuellert@gmail.com' } s.summary = 'AFFAlertView is customizable iOS 6+ UIAlertView alternative that supports subclassing. The default alert view style is based on the iOS 7 UIAlertView.' s.homepage = 'https://github.com/jfuellert/AFFAlertView' s.license = 'MIT' s.ios.deployment_target = ‘6.0’ s.source = { :git => 'https://github.com/jfuellert/AFFAlertView.git', :tag => '0.0.1' } s.source_files = 'AFFAlertView/AFFAlertView/*/*.{h,m}' s.public_header_files = 'AFFAlertView/AFFAlertView/*/*.h' s.requires_arc = true end Updated podspec Pod::Spec.new do |s| s.name = 'AFFAlertView' s.version = '0.0.1' s.authors = { 'Jeremy Fuellert' => 'jfuellert@gmail.com' } s.summary = 'AFFAlertView is customizable iOS 7 styled UIAlertView alternative that supports subclassing.' s.homepage = 'https://github.com/jfuellert/AFFAlertView' s.license = 'MIT' s.ios.deployment_target = '6.0' s.source = { :git => 'https://github.com/jfuellert/AFFAlertView.git', :tag => '0.0.1' } s.source_files = 'AFFAlertView/AFFAlertView/*/*.{h,m}' s.public_header_files = 'AFFAlertView/AFFAlertView/*/*.h' s.requires_arc = true end
module WaveFile FORMAT = "WAVE" SUB_CHUNK1_SIZE = 16 PCM = 1 DATA_CHUNK_ID = "data" HEADER_SIZE = 36 CHUNK_IDS = {:header => "RIFF", :format => "fmt ", :data => "data", :fact => "fact", :silence => "slnt", :cue => "cue ", :playlist => "plst", :list => "list", :label => "labl", :labeled_text => "ltxt", :note => "note", :sample => "smpl", :instrument => "inst" } PACK_CODES = {8 => "C*", 16 => "s*", 32 => "V*"} class WaveFileInfo def initialize(file_name, format, sample_count) @file_name = file_name @channels = format.channels @bits_per_sample = format.bits_per_sample @sample_rate = format.sample_rate @byte_rate = format.byte_rate @block_align = format.block_align @sample_count = sample_count @duration = calculate_duration() end attr_reader :file_name, :channels, :bits_per_sample, :sample_rate, :byte_rate, :block_align, :sample_count, :duration private def calculate_duration() total_samples = @sample_count samples_per_millisecond = sample_rate / 1000.0 samples_per_second = sample_rate samples_per_minute = samples_per_second * 60 samples_per_hour = samples_per_minute * 60 hours, minutes, seconds, milliseconds = 0, 0, 0, 0 if(total_samples >= samples_per_hour) hours = total_samples / samples_per_hour total_samples -= samples_per_hour * hours end if(total_samples >= samples_per_minute) minutes = total_samples / samples_per_minute total_samples -= samples_per_minute * minutes end if(total_samples >= samples_per_second) seconds = total_samples / samples_per_second total_samples -= samples_per_second * seconds end milliseconds = (total_samples / samples_per_millisecond).floor @duration = { :hours => hours, :minutes => minutes, :seconds => seconds, :milliseconds => milliseconds } end end class WaveFileFormat def initialize(channels, bits_per_sample, sample_rate) @channels = channels @bits_per_sample = bits_per_sample @sample_rate = sample_rate end def byte_rate() return (@bits_per_sample / 8) * sample_rate end def block_align() return (@bits_per_sample / 8) * @channels end attr_accessor :channels, :bits_per_sample, :sample_rate end class WaveFileBuffer def initialize(samples, format) @samples = samples set_format(format) end def convert(new_format) return WaveFileBuffer.new(@samples, new_format) end def convert!(new_format) set_format(format) return self end attr_reader :samples, :channels, :bits_per_sample, :sample_rate private def set_format(format) @channels = format.channels @bits_per_sample = format.bits_per_sample @sample_rate = format.sample_rate end end class WaveFileReader def initialize(file_name) @file_name = file_name @file = File.open(file_name, "r") read_header() end def read(buffer_size, format=@format) samples = @file.sysread(buffer_size).unpack(PACK_CODES[format.bits_per_sample]) buffer = WaveFileBuffer.new(samples, @format) return buffer.convert(format) end def close() @file.close() end attr_reader :info private def read_header() header = {} # Read RIFF header riff_header = @file.sysread(12).unpack("a4Va4") header[:chunk_id] = riff_header[0] header[:chunk_size] = riff_header[1] header[:format] = riff_header[2] # Read format subchunk header[:sub_chunk1_id], header[:sub_chunk1_size] = read_to_chunk(CHUNK_IDS[:format]) format_subchunk_str = @file.sysread(header[:sub_chunk1_size]) format_subchunk = format_subchunk_str.unpack("vvVVvv") # Any extra parameters are ignored header[:audio_format] = format_subchunk[0] header[:channels] = format_subchunk[1] header[:sample_rate] = format_subchunk[2] header[:byte_rate] = format_subchunk[3] header[:block_align] = format_subchunk[4] header[:bits_per_sample] = format_subchunk[5] # Read data subchunk header[:sub_chunk2_id], header[:sub_chunk2_size] = read_to_chunk(CHUNK_IDS[:data]) validate_header(header) sample_count = header[:sub_chunk2_size] / header[:block_align] @format = WaveFileFormat.new(header[:channels], header[:bits_per_sample], header[:sample_rate]) @info = WaveFileInfo.new(@file_name, @format, sample_count) end def read_to_chunk(expected_chunk_id) chunk_id = @file.sysread(4) chunk_size = @file.sysread(4).unpack("V")[0] while chunk_id != expected_chunk_id # Skip chunk file.sysread(chunk_size) chunk_id = @file.sysread(4) chunk_size = @file.sysread(4).unpack("V")[0] end return chunk_id, chunk_size end def validate_header(header) return true end end class WaveFileWriter def initialize(file_name, format) @file = File.open(file_name, "w") @format = format @sample_count = 0 @pack_code = PACK_CODES[format.bits_per_sample] write_header(0) end def write(buffer) samples = buffer.convert(@format).samples @file.syswrite(samples.pack(@pack_code)) @sample_count += samples.length end def close() @file.sysseek(0) write_header(@sample_count) @file.close() end private def write_header(sample_data_size) header = CHUNK_IDS[:header] header += [HEADER_SIZE + sample_data_size].pack("V") header += FORMAT header += CHUNK_IDS[:format] header += [SUB_CHUNK1_SIZE].pack("V") header += [PCM].pack("v") header += [@format.channels].pack("v") header += [@format.sample_rate].pack("V") header += [@format.byte_rate].pack("V") header += [@format.block_align].pack("v") header += [@format.bits_per_sample].pack("v") header += CHUNK_IDS[:data] header += [sample_data_size].pack("V") @file.syswrite(header) end end end Fixing bug in WaveFileFormat.byte_rate() module WaveFile FORMAT = "WAVE" SUB_CHUNK1_SIZE = 16 PCM = 1 DATA_CHUNK_ID = "data" HEADER_SIZE = 36 CHUNK_IDS = {:header => "RIFF", :format => "fmt ", :data => "data", :fact => "fact", :silence => "slnt", :cue => "cue ", :playlist => "plst", :list => "list", :label => "labl", :labeled_text => "ltxt", :note => "note", :sample => "smpl", :instrument => "inst" } PACK_CODES = {8 => "C*", 16 => "s*", 32 => "V*"} class WaveFileInfo def initialize(file_name, format, sample_count) @file_name = file_name @channels = format.channels @bits_per_sample = format.bits_per_sample @sample_rate = format.sample_rate @byte_rate = format.byte_rate @block_align = format.block_align @sample_count = sample_count @duration = calculate_duration() end attr_reader :file_name, :channels, :bits_per_sample, :sample_rate, :byte_rate, :block_align, :sample_count, :duration private def calculate_duration() total_samples = @sample_count samples_per_millisecond = sample_rate / 1000.0 samples_per_second = sample_rate samples_per_minute = samples_per_second * 60 samples_per_hour = samples_per_minute * 60 hours, minutes, seconds, milliseconds = 0, 0, 0, 0 if(total_samples >= samples_per_hour) hours = total_samples / samples_per_hour total_samples -= samples_per_hour * hours end if(total_samples >= samples_per_minute) minutes = total_samples / samples_per_minute total_samples -= samples_per_minute * minutes end if(total_samples >= samples_per_second) seconds = total_samples / samples_per_second total_samples -= samples_per_second * seconds end milliseconds = (total_samples / samples_per_millisecond).floor @duration = { :hours => hours, :minutes => minutes, :seconds => seconds, :milliseconds => milliseconds } end end class WaveFileFormat def initialize(channels, bits_per_sample, sample_rate) @channels = channels @bits_per_sample = bits_per_sample @sample_rate = sample_rate end def byte_rate() return (@bits_per_sample / 8) * @sample_rate end def block_align() return (@bits_per_sample / 8) * @channels end attr_accessor :channels, :bits_per_sample, :sample_rate end class WaveFileBuffer def initialize(samples, format) @samples = samples set_format(format) end def convert(new_format) return WaveFileBuffer.new(@samples, new_format) end def convert!(new_format) set_format(format) return self end attr_reader :samples, :channels, :bits_per_sample, :sample_rate private def set_format(format) @channels = format.channels @bits_per_sample = format.bits_per_sample @sample_rate = format.sample_rate end end class WaveFileReader def initialize(file_name) @file_name = file_name @file = File.open(file_name, "r") read_header() end def read(buffer_size, format=@format) samples = @file.sysread(buffer_size).unpack(PACK_CODES[format.bits_per_sample]) buffer = WaveFileBuffer.new(samples, @format) return buffer.convert(format) end def close() @file.close() end attr_reader :info private def read_header() header = {} # Read RIFF header riff_header = @file.sysread(12).unpack("a4Va4") header[:chunk_id] = riff_header[0] header[:chunk_size] = riff_header[1] header[:format] = riff_header[2] # Read format subchunk header[:sub_chunk1_id], header[:sub_chunk1_size] = read_to_chunk(CHUNK_IDS[:format]) format_subchunk_str = @file.sysread(header[:sub_chunk1_size]) format_subchunk = format_subchunk_str.unpack("vvVVvv") # Any extra parameters are ignored header[:audio_format] = format_subchunk[0] header[:channels] = format_subchunk[1] header[:sample_rate] = format_subchunk[2] header[:byte_rate] = format_subchunk[3] header[:block_align] = format_subchunk[4] header[:bits_per_sample] = format_subchunk[5] # Read data subchunk header[:sub_chunk2_id], header[:sub_chunk2_size] = read_to_chunk(CHUNK_IDS[:data]) validate_header(header) sample_count = header[:sub_chunk2_size] / header[:block_align] @format = WaveFileFormat.new(header[:channels], header[:bits_per_sample], header[:sample_rate]) @info = WaveFileInfo.new(@file_name, @format, sample_count) end def read_to_chunk(expected_chunk_id) chunk_id = @file.sysread(4) chunk_size = @file.sysread(4).unpack("V")[0] while chunk_id != expected_chunk_id # Skip chunk file.sysread(chunk_size) chunk_id = @file.sysread(4) chunk_size = @file.sysread(4).unpack("V")[0] end return chunk_id, chunk_size end def validate_header(header) return true end end class WaveFileWriter def initialize(file_name, format) @file = File.open(file_name, "w") @format = format @sample_count = 0 @pack_code = PACK_CODES[format.bits_per_sample] write_header(0) end def write(buffer) samples = buffer.convert(@format).samples @file.syswrite(samples.pack(@pack_code)) @sample_count += samples.length end def close() @file.sysseek(0) write_header(@sample_count) @file.close() end private def write_header(sample_data_size) header = CHUNK_IDS[:header] header += [HEADER_SIZE + sample_data_size].pack("V") header += FORMAT header += CHUNK_IDS[:format] header += [SUB_CHUNK1_SIZE].pack("V") header += [PCM].pack("v") header += [@format.channels].pack("v") header += [@format.sample_rate].pack("V") header += [@format.byte_rate].pack("V") header += [@format.block_align].pack("v") header += [@format.bits_per_sample].pack("v") header += CHUNK_IDS[:data] header += [sample_data_size].pack("V") @file.syswrite(header) end end end
module Uphold module Command module_function def run(cmd) logger.debug "Running command '#{cmd}'" log_command = "#{cmd.split(' ')[0]}" Open3.popen3(cmd) do |_stdin, stdout, stderr, thread| # read each stream from a new thread { out: stdout, err: stderr }.each do |key, stream| Thread.new do until (line = stream.gets).nil? do # yield the block depending on the stream if key == :out logger.debug(log_command) { line.chomp } unless line.nil? else logger.error(log_command) { line.chomp } unless line.nil? end end end end thread.join # don't exit until the external process is done return thread.value end end end end rename to be move obvious module Uphold module Command module_function def run_command(cmd) logger.debug "Running command '#{cmd}'" log_command = "#{cmd.split(' ')[0]}" Open3.popen3(cmd) do |_stdin, stdout, stderr, thread| # read each stream from a new thread { out: stdout, err: stderr }.each do |key, stream| Thread.new do until (line = stream.gets).nil? do # yield the block depending on the stream if key == :out logger.debug(log_command) { line.chomp } unless line.nil? else logger.error(log_command) { line.chomp } unless line.nil? end end end end thread.join # don't exit until the external process is done return thread.value end end end end
module Heroics VERSION = '0.0.13' end Bump version. module Heroics VERSION = '0.0.14' end
class Heroku::JSPlugin extend Heroku::Helpers def self.setup? @is_setup ||= File.exists? bin end def self.load! return unless setup? this = self topics.each do |topic| Heroku::Command.register_namespace( :name => topic['name'], :description => " #{topic['description']}" ) unless Heroku::Command.namespaces.include?(topic['name']) end commands.each do |plugin| help = "\n\n #{plugin['fullHelp'].split("\n").join("\n ")}" klass = Class.new do def initialize(args, opts) @args = args @opts = opts end end klass.send(:define_method, :run) do this.run(plugin['topic'], plugin['command'], ARGV[1..-1]) end Heroku::Command.register_command( :command => plugin['command'] ? "#{plugin['topic']}:#{plugin['command']}" : plugin['topic'], :namespace => plugin['topic'], :klass => klass, :method => :run, :banner => plugin['usage'], :summary => " #{plugin['description']}", :help => help ) end end def self.plugins return [] unless setup? @plugins ||= `#{bin} plugins`.lines.map do |line| name, version = line.split { :name => name, :version => version } end end def self.is_plugin_installed?(name) plugins.any? { |p| p[:name] == name } end def self.topics commands_info['topics'] rescue $stderr.puts "error loading plugin topics" return [] end def self.commands commands_info['commands'] rescue $stderr.puts "error loading plugin commands" return [] end def self.commands_info @commands_info ||= json_decode(`#{bin} commands --json`) end def self.install(name) system "#{bin} plugins:install #{name}" end def self.uninstall(name) system "#{bin} plugins:uninstall #{name}" end def self.version `#{bin} version` end def self.bin if os == 'windows' File.join(Heroku::Helpers.home_directory, ".heroku", "heroku-cli.exe") else File.join(Heroku::Helpers.home_directory, ".heroku", "heroku-cli") end end def self.setup return if File.exist? bin $stderr.print "Installing Heroku Toolbelt v4..." FileUtils.mkdir_p File.dirname(bin) resp = Excon.get(url, :middlewares => Excon.defaults[:middlewares] + [Excon::Middleware::Decompress]) open(bin, "wb") do |file| file.write(resp.body) end File.chmod(0755, bin) if Digest::SHA1.file(bin).hexdigest != manifest['builds'][os][arch]['sha1'] File.delete bin raise 'SHA mismatch for heroku-cli' end $stderr.puts " done" end def self.run(topic, command, args) cmd = command ? "#{topic}:#{command}" : topic exec self.bin, cmd, *args end def self.platform RbConfig::CONFIG['host_os'] end def self.arch case platform when /i386/ "386" when /x64/ else "amd64" end end def self.os case platform when /darwin|mac os/ "darwin" when /linux/ "linux" when /mswin|msys|mingw|cygwin|bccwin|wince|emc/ "windows" when /openbsd/ "openbsd" else raise "unsupported on #{platform}" end end def self.manifest @manifest ||= JSON.parse(Excon.get("http://d1gvo455cekpjp.cloudfront.net/master/manifest.json").body) end def self.url manifest['builds'][os][arch]['url'] + ".gz" end end fix os and arch detection class Heroku::JSPlugin extend Heroku::Helpers def self.setup? @is_setup ||= File.exists? bin end def self.load! return unless setup? this = self topics.each do |topic| Heroku::Command.register_namespace( :name => topic['name'], :description => " #{topic['description']}" ) unless Heroku::Command.namespaces.include?(topic['name']) end commands.each do |plugin| help = "\n\n #{plugin['fullHelp'].split("\n").join("\n ")}" klass = Class.new do def initialize(args, opts) @args = args @opts = opts end end klass.send(:define_method, :run) do this.run(plugin['topic'], plugin['command'], ARGV[1..-1]) end Heroku::Command.register_command( :command => plugin['command'] ? "#{plugin['topic']}:#{plugin['command']}" : plugin['topic'], :namespace => plugin['topic'], :klass => klass, :method => :run, :banner => plugin['usage'], :summary => " #{plugin['description']}", :help => help ) end end def self.plugins return [] unless setup? @plugins ||= `#{bin} plugins`.lines.map do |line| name, version = line.split { :name => name, :version => version } end end def self.is_plugin_installed?(name) plugins.any? { |p| p[:name] == name } end def self.topics commands_info['topics'] rescue $stderr.puts "error loading plugin topics" return [] end def self.commands commands_info['commands'] rescue $stderr.puts "error loading plugin commands" return [] end def self.commands_info @commands_info ||= json_decode(`#{bin} commands --json`) end def self.install(name) system "#{bin} plugins:install #{name}" end def self.uninstall(name) system "#{bin} plugins:uninstall #{name}" end def self.version `#{bin} version` end def self.bin if os == 'windows' File.join(Heroku::Helpers.home_directory, ".heroku", "heroku-cli.exe") else File.join(Heroku::Helpers.home_directory, ".heroku", "heroku-cli") end end def self.setup return if File.exist? bin $stderr.print "Installing Heroku Toolbelt v4..." FileUtils.mkdir_p File.dirname(bin) resp = Excon.get(url, :middlewares => Excon.defaults[:middlewares] + [Excon::Middleware::Decompress]) open(bin, "wb") do |file| file.write(resp.body) end File.chmod(0755, bin) if Digest::SHA1.file(bin).hexdigest != manifest['builds'][os][arch]['sha1'] File.delete bin raise 'SHA mismatch for heroku-cli' end $stderr.puts " done" end def self.run(topic, command, args) cmd = command ? "#{topic}:#{command}" : topic exec self.bin, cmd, *args end def self.arch case RbConfig::CONFIG['host_cpu'] when /x86_64/ "amd64" else "386" end end def self.os case RbConfig::CONFIG['host_os'] when /darwin|mac os/ "darwin" when /linux/ "linux" when /mswin|msys|mingw|cygwin|bccwin|wince|emc/ "windows" when /openbsd/ "openbsd" else raise "unsupported on #{RbConfig::CONFIG['host_os']}" end end def self.manifest @manifest ||= JSON.parse(Excon.get("http://d1gvo455cekpjp.cloudfront.net/master/manifest.json").body) end def self.url manifest['builds'][os][arch]['url'] + ".gz" end end
require 'uri' require 'net/http' require 'hessian2' module Hessian2 class Client attr_accessor :user, :password attr_reader :scheme, :host, :port, :path, :proxy def initialize(url, options = {}) uri = URI.parse(url) @scheme, @host, @port, @path = uri.scheme, uri.host, uri.port, uri.path.empty? ? '/' : uri.path @path += "?#{uri.query}" if uri.query raise "Unsupported Hessian protocol: #{@scheme}" unless %w(http https).include?(@scheme) @async = options.delete(:async) @fiber_aware = options.delete(:fiber_aware) if @async || @fiber_aware require 'em-synchrony/em-http' end @proxy = options end def method_missing(id, *args) return invoke(id.id2name, args) end private def invoke(method, args) req_head = { 'Content-Type' => 'application/binary' } req_body = Hessian2.call(method, args) if @async EM::HttpRequest.new("#{@scheme}://#{@host}:#{@port}#{@path}").apost(body: req_body, head: req_head) elsif @fiber_aware http = EM::HttpRequest.new("#{@scheme}://#{@host}:#{@port}#{@path}").post(body: req_body, head: req_head) Hessian2.parse_rpc(http.response) else req = Net::HTTP::Post.new(@path, req_head) req.basic_auth @user, @password if @user conn = Net::HTTP.new(@host, @port, *@proxy.values_at(:host, :port, :user, :password)) conn.use_ssl = true and conn.verify_mode = OpenSSL::SSL::VERIFY_NONE if @scheme == 'https' conn.start do |http| res = http.request(req, req_body) Hessian2.parse_rpc(res.body) end end end end end rescue em-synchrony load error require 'uri' require 'net/http' require 'hessian2' module Hessian2 class Client attr_accessor :user, :password attr_reader :scheme, :host, :port, :path, :proxy def initialize(url, options = {}) uri = URI.parse(url) @scheme, @host, @port, @path = uri.scheme, uri.host, uri.port, uri.path.empty? ? '/' : uri.path @path += "?#{uri.query}" if uri.query raise "Unsupported Hessian protocol: #{@scheme}" unless %w(http https).include?(@scheme) @async = options.delete(:async) @fiber_aware = options.delete(:fiber_aware) if @async || @fiber_aware begin require 'em-synchrony/em-http' rescue LoadError => error raise "Missing EM-Synchrony dependency: gem install em-synchrony em-http-request" end end @proxy = options end def method_missing(id, *args) return invoke(id.id2name, args) end private def invoke(method, args) req_head = { 'Content-Type' => 'application/binary' } req_body = Hessian2.call(method, args) if @async EM::HttpRequest.new("#{@scheme}://#{@host}:#{@port}#{@path}").apost(body: req_body, head: req_head) elsif @fiber_aware http = EM::HttpRequest.new("#{@scheme}://#{@host}:#{@port}#{@path}").post(body: req_body, head: req_head) Hessian2.parse_rpc(http.response) else req = Net::HTTP::Post.new(@path, req_head) req.basic_auth @user, @password if @user conn = Net::HTTP.new(@host, @port, *@proxy.values_at(:host, :port, :user, :password)) conn.use_ssl = true and conn.verify_mode = OpenSSL::SSL::VERIFY_NONE if @scheme == 'https' conn.start do |http| res = http.request(req, req_body) Hessian2.parse_rpc(res.body) end end end end end
module HopHop VERSION = "0.0.4" end bumping version module HopHop VERSION = "0.0.5" end
#!/usr/bin/env ruby require "fileutils" require "dogapi" require "json" require "sqlite3" module Hotdog module Commands SQLITE_LIMIT_COMPOUND_SELECT = 500 # TODO: get actual value from `sqlite3_limit()`? class BaseCommand PERSISTENT_DB = "persistent.db" MASK_DATABASE = 0xffff0000 MASK_QUERY = 0x0000ffff def initialize(application) @application = application @logger = application.options[:logger] @options = application.options @dog = Dogapi::Client.new(options[:api_key], options[:application_key]) @prepared_statements = {} end attr_reader :application attr_reader :logger attr_reader :options def run(args=[]) raise(NotImplementedError) end def execute(query, args=[]) update_db q = query.strip if 0 < args.length q += " -- VALUES (#{args.map { |arg| Array === arg ? "(#{arg.join(", ")})" : arg.inspect }.join(", ")})" end logger.debug(q) prepare(@db, query).execute(args) end def fixed_string?() @options[:fixed_string] end def reload(options={}) if @db close_db(@db) @db = nil end update_db(options) end private def prepare(db, query) k = (db.hash & MASK_DATABASE) | (query.hash & MASK_QUERY) @prepared_statements[k] ||= db.prepare(query) end def format(result, options={}) @options[:formatter].format(result, @options.merge(options)) end def optparse() @application.optparse end def glob?(s) s.index('*') or s.index('?') or s.index('[') or s.index(']') end def get_hosts(host_ids, tags=nil) tags ||= @options[:tags] update_db if host_ids.empty? [[], []] else if 0 < tags.length fields = tags.map { |tag| tag_name, tag_value = split_tag(tag) tag_name } fields_without_host = fields.reject { |tag_name| tag_name == "host" } if fields == fields_without_host host_names = {} else host_names = Hash[ host_ids.each_slice(SQLITE_LIMIT_COMPOUND_SELECT).flat_map { |host_ids| execute("SELECT id, name FROM hosts WHERE id IN (%s)" % host_ids.map { "?" }.join(", "), host_ids).map { |row| row.to_a } } ] end q1 = [] q1 << "SELECT tags.name, GROUP_CONCAT(tags.value, ',') FROM hosts_tags" q1 << "INNER JOIN hosts ON hosts_tags.host_id = hosts.id" q1 << "INNER JOIN tags ON hosts_tags.tag_id = tags.id" q1 << "WHERE hosts_tags.host_id = ? AND tags.name IN (%s)" q1 << "GROUP BY tags.name;" result = host_ids.map { |host_id| tag_values = Hash[ fields_without_host.each_slice(SQLITE_LIMIT_COMPOUND_SELECT - 1).flat_map { |fields_without_host| execute(q1.join(" ") % fields_without_host.map { "?" }.join(", "), [host_id] + fields_without_host).map { |row| row.to_a } } ] fields.map { |tag_name| if tag_name == "host" host_names.fetch(host_id, "") else tag_values.fetch(tag_name, "") end } } [result, fields] else if @options[:listing] q1 = [] q1 << "SELECT DISTINCT tags.name FROM hosts_tags" q1 << "INNER JOIN tags ON hosts_tags.tag_id = tags.id" q1 << "WHERE hosts_tags.host_id IN (%s);" if @options[:primary_tag] fields = [ @options[:primary_tag], "host", ] + host_ids.each_slice(SQLITE_LIMIT_COMPOUND_SELECT).flat_map { |host_ids| execute(q1.join(" ") % host_ids.map { "?" }.join(", "), host_ids).map { |row| row.first }.reject { |tag_name| tag_name == @options[:primary_tag] } } else fields = [ "host", ] + host_ids.each_slice(SQLITE_LIMIT_COMPOUND_SELECT).flat_map { |host_ids| execute(q1.join(" ") % host_ids.map { "?" }.join(", "), host_ids).map { |row| row.first } } end host_names = Hash[ host_ids.each_slice(SQLITE_LIMIT_COMPOUND_SELECT).flat_map { |host_ids| execute("SELECT id, name FROM hosts WHERE id IN (%s)" % host_ids.map { "?" }.join(", "), host_ids).map { |row| row.to_a } } ] q2 = [] q2 << "SELECT tags.name, GROUP_CONCAT(tags.value, ',') FROM hosts_tags" q2 << "INNER JOIN tags ON hosts_tags.tag_id = tags.id" q2 << "WHERE hosts_tags.host_id = ? AND tags.name IN (%s)" q2 << "GROUP BY tags.name;" fields_without_host = fields.reject { |tag_name| tag_name == "host" } result = host_ids.map { |host_id| tag_values = Hash[ fields_without_host.each_slice(SQLITE_LIMIT_COMPOUND_SELECT - 1).flat_map { |fields_without_host| execute(q2.join(" ") % fields_without_host.map { "?" }.join(", "), [host_id] + fields_without_host).map { |row| row.to_a } } ] fields.map { |tag_name| if tag_name == "host" host_names.fetch(host_id, "") else tag_values.fetch(tag_name, "") end } } [result, fields] else if @options[:primary_tag] fields = [@options[:primary_tag]] q1 = [] q1 << "SELECT tags.value FROM hosts_tags" q1 << "INNER JOIN hosts ON hosts_tags.host_id = hosts.id" q1 << "INNER JOIN tags ON hosts_tags.tag_id = tags.id" q1 << "WHERE hosts_tags.host_id IN (%s) AND tags.name = ?;" result = host_ids.each_slice(SQLITE_LIMIT_COMPOUND_SELECT - 1).flat_map { |host_ids| execute(q1.join(" ") % host_ids.map { "?" }.join(", "), host_ids + [@options[:primary_tag]]).map { |row| row.to_a } } [result, fields] else fields = ["host"] result = host_ids.each_slice(SQLITE_LIMIT_COMPOUND_SELECT).flat_map { |host_ids| execute("SELECT name FROM hosts WHERE id IN (%s)" % host_ids.map { "?" }.join(", "), host_ids).map { |row| row.to_a } } [result, fields] end end end end end def close_db(db, options={}) @prepared_statements = @prepared_statements.reject { |k, statement| (db.hash & MASK_DATABASE == k & MASK_DATABASE).tap do |delete_p| statement.close() if delete_p end } db.close() end def update_db(options={}) options = @options.merge(options) if @db.nil? FileUtils.mkdir_p(options[:confdir]) persistent = File.join(options[:confdir], PERSISTENT_DB) if not options[:force] and File.exist?(persistent) and Time.new < File.mtime(persistent) + options[:expiry] begin persistent_db = SQLite3::Database.new(persistent) persistent_db.execute("SELECT id, name FROM hosts LIMIT 1") persistent_db.execute("SELECT id, name, value FROM tags LIMIT 1") persistent_db.execute("SELECT host_id, tag_id FROM hosts_tags LIMIT 1") @db = persistent_db return rescue SQLite3::SQLException persistent_db.close() end end memory_db = SQLite3::Database.new(":memory:") create_table_hosts(memory_db) create_index_hosts(memory_db) create_table_tags(memory_db) create_index_tags(memory_db) create_table_hosts_tags(memory_db) create_index_hosts_tags(memory_db) all_tags = get_all_tags() memory_db.transaction do known_tags = all_tags.keys.map { |tag| split_tag(tag) }.uniq known_tags.each_slice(SQLITE_LIMIT_COMPOUND_SELECT / 2) do |known_tags| prepare(memory_db, "INSERT OR IGNORE INTO tags (name, value) VALUES %s" % known_tags.map { "(?, ?)" }.join(", ")).execute(known_tags) end known_hosts = all_tags.values.reduce(:+).uniq known_hosts.each_slice(SQLITE_LIMIT_COMPOUND_SELECT) do |known_hosts| prepare(memory_db, "INSERT OR IGNORE INTO hosts (name) VALUES %s" % known_hosts.map { "(?)" }.join(", ")).execute(known_hosts) end all_tags.each do |tag, hosts| q = [] q << "INSERT OR REPLACE INTO hosts_tags (host_id, tag_id)" q << "SELECT host.id, tag.id FROM" q << "( SELECT id FROM hosts WHERE name IN (%s) ) AS host," q << "( SELECT id FROM tags WHERE name = ? AND value = ? LIMIT 1 ) AS tag;" hosts.each_slice(SQLITE_LIMIT_COMPOUND_SELECT - 2) do |hosts| prepare(memory_db, q.join(" ") % hosts.map { "?" }.join(", ")).execute(hosts + split_tag(tag)) end end end # backup in-memory db to file FileUtils.rm_f(persistent) persistent_db = SQLite3::Database.new(persistent) copy_db(memory_db, persistent_db) close_db(persistent_db) @db = memory_db else @db end end def get_all_tags() #==> Hash<Tag,Array<Host>> code, all_tags = @dog.all_tags() logger.debug("dog.all_tags() #==> [%s, ...]" % [code.inspect]) if code.to_i / 100 != 2 raise("dog.all_tags() returns [%s, ...]" % [code.inspect]) end code, all_downtimes = @dog.get_all_downtimes() logger.debug("dog.get_all_downtimes() #==> [%s, ...]" % [code.inspect]) if code.to_i / 100 != 2 raise("dog.get_all_downtimes() returns [%s, ...]" % [code.inspect]) end now = Time.new.to_i downtimes = all_downtimes.select { |downtime| # active downtimes downtime["active"] and ( downtime["start"].nil? or downtime["start"] < now ) and ( downtime["end"].nil? or now <= downtime["end"] ) }.flat_map { |downtime| # find host scopes downtime["scope"].select { |scope| scope.start_with?("host:") }.map { |scope| scope.sub(/\Ahost:/, "") } } if not downtimes.empty? logger.info("ignore host(s) with scheduled downtimes: #{downtimes.inspect}") end Hash[all_tags["tags"].map { |tag, hosts| [tag, hosts.reject { |host| downtimes.include?(host) }] }] end def split_tag(tag) tag_name, tag_value = tag.split(":", 2) [tag_name, tag_value || ""] end def copy_db(src, dst) # create index later for better insert performance dst.transaction do create_table_hosts(dst) create_table_tags(dst) create_table_hosts_tags(dst) hosts = prepare(src, "SELECT id, name FROM hosts").execute().to_a hosts.each_slice(SQLITE_LIMIT_COMPOUND_SELECT / 2) do |hosts| prepare(dst, "INSERT INTO hosts (id, name) VALUES %s" % hosts.map { "(?, ?)" }.join(", ")).execute(hosts) end tags = prepare(src, "SELECT id, name, value FROM tags").execute().to_a tags.each_slice(SQLITE_LIMIT_COMPOUND_SELECT / 3) do |tags| prepare(dst, "INSERT INTO tags (id, name, value) VALUES %s" % tags.map { "(?, ?, ?)" }.join(", ")).execute(tags) end hosts_tags = prepare(src, "SELECT host_id, tag_id FROM hosts_tags").to_a hosts_tags.each_slice(SQLITE_LIMIT_COMPOUND_SELECT / 2) do |hosts_tags| prepare(dst, "INSERT INTO hosts_tags (host_id, tag_id) VALUES %s" % hosts_tags.map { "(?, ?)" }.join(", ")).execute(hosts_tags) end create_index_hosts(dst) create_index_tags(dst) create_index_hosts_tags(dst) end end def create_table_hosts(db) logger.debug("create_table_hosts()") q = [] q << "CREATE TABLE IF NOT EXISTS hosts (" q << "id INTEGER PRIMARY KEY AUTOINCREMENT," q << "name VARCHAR(255) NOT NULL COLLATE NOCASE" q << ");" db.execute(q.join(" ")) end def create_index_hosts(db) logger.debug("create_index_hosts()") db.execute("CREATE UNIQUE INDEX IF NOT EXISTS hosts_name ON hosts ( name )") end def create_table_tags(db) logger.debug("create_table_tags()") q = [] q << "CREATE TABLE IF NOT EXISTS tags (" q << "id INTEGER PRIMARY KEY AUTOINCREMENT," q << "name VARCHAR(200) NOT NULL COLLATE NOCASE," q << "value VARCHAR(200) NOT NULL COLLATE NOCASE" q << ");" db.execute(q.join(" ")) end def create_index_tags(db) logger.debug("create_index_tags()") db.execute("CREATE UNIQUE INDEX IF NOT EXISTS tags_name_value ON tags ( name, value )") end def create_table_hosts_tags(db) logger.debug("create_table_hosts_tags()") q = [] q << "CREATE TABLE IF NOT EXISTS hosts_tags (" q << "host_id INTEGER NOT NULL," q << "tag_id INTEGER NOT NULL" q << ");" db.execute(q.join(" ")) end def create_index_hosts_tags(db) logger.debug("create_index_hosts_tags()") db.execute("CREATE UNIQUE INDEX IF NOT EXISTS hosts_tags_host_id_tag_id ON hosts_tags ( host_id, tag_id )") end end end end # vim:set ft=ruby : show `CREATE TABLE` and `CREATE INDEX` queries on debug log #!/usr/bin/env ruby require "fileutils" require "dogapi" require "json" require "sqlite3" module Hotdog module Commands SQLITE_LIMIT_COMPOUND_SELECT = 500 # TODO: get actual value from `sqlite3_limit()`? class BaseCommand PERSISTENT_DB = "persistent.db" MASK_DATABASE = 0xffff0000 MASK_QUERY = 0x0000ffff def initialize(application) @application = application @logger = application.options[:logger] @options = application.options @dog = Dogapi::Client.new(options[:api_key], options[:application_key]) @prepared_statements = {} end attr_reader :application attr_reader :logger attr_reader :options def run(args=[]) raise(NotImplementedError) end def execute(query, args=[]) update_db q = query.strip if 0 < args.length q += " -- VALUES (#{args.map { |arg| Array === arg ? "(#{arg.join(", ")})" : arg.inspect }.join(", ")})" end logger.debug(q) prepare(@db, query).execute(args) end def fixed_string?() @options[:fixed_string] end def reload(options={}) if @db close_db(@db) @db = nil end update_db(options) end private def prepare(db, query) k = (db.hash & MASK_DATABASE) | (query.hash & MASK_QUERY) @prepared_statements[k] ||= db.prepare(query) end def format(result, options={}) @options[:formatter].format(result, @options.merge(options)) end def optparse() @application.optparse end def glob?(s) s.index('*') or s.index('?') or s.index('[') or s.index(']') end def get_hosts(host_ids, tags=nil) tags ||= @options[:tags] update_db if host_ids.empty? [[], []] else if 0 < tags.length fields = tags.map { |tag| tag_name, tag_value = split_tag(tag) tag_name } fields_without_host = fields.reject { |tag_name| tag_name == "host" } if fields == fields_without_host host_names = {} else host_names = Hash[ host_ids.each_slice(SQLITE_LIMIT_COMPOUND_SELECT).flat_map { |host_ids| execute("SELECT id, name FROM hosts WHERE id IN (%s)" % host_ids.map { "?" }.join(", "), host_ids).map { |row| row.to_a } } ] end q1 = [] q1 << "SELECT tags.name, GROUP_CONCAT(tags.value, ',') FROM hosts_tags" q1 << "INNER JOIN hosts ON hosts_tags.host_id = hosts.id" q1 << "INNER JOIN tags ON hosts_tags.tag_id = tags.id" q1 << "WHERE hosts_tags.host_id = ? AND tags.name IN (%s)" q1 << "GROUP BY tags.name;" result = host_ids.map { |host_id| tag_values = Hash[ fields_without_host.each_slice(SQLITE_LIMIT_COMPOUND_SELECT - 1).flat_map { |fields_without_host| execute(q1.join(" ") % fields_without_host.map { "?" }.join(", "), [host_id] + fields_without_host).map { |row| row.to_a } } ] fields.map { |tag_name| if tag_name == "host" host_names.fetch(host_id, "") else tag_values.fetch(tag_name, "") end } } [result, fields] else if @options[:listing] q1 = [] q1 << "SELECT DISTINCT tags.name FROM hosts_tags" q1 << "INNER JOIN tags ON hosts_tags.tag_id = tags.id" q1 << "WHERE hosts_tags.host_id IN (%s);" if @options[:primary_tag] fields = [ @options[:primary_tag], "host", ] + host_ids.each_slice(SQLITE_LIMIT_COMPOUND_SELECT).flat_map { |host_ids| execute(q1.join(" ") % host_ids.map { "?" }.join(", "), host_ids).map { |row| row.first }.reject { |tag_name| tag_name == @options[:primary_tag] } } else fields = [ "host", ] + host_ids.each_slice(SQLITE_LIMIT_COMPOUND_SELECT).flat_map { |host_ids| execute(q1.join(" ") % host_ids.map { "?" }.join(", "), host_ids).map { |row| row.first } } end host_names = Hash[ host_ids.each_slice(SQLITE_LIMIT_COMPOUND_SELECT).flat_map { |host_ids| execute("SELECT id, name FROM hosts WHERE id IN (%s)" % host_ids.map { "?" }.join(", "), host_ids).map { |row| row.to_a } } ] q2 = [] q2 << "SELECT tags.name, GROUP_CONCAT(tags.value, ',') FROM hosts_tags" q2 << "INNER JOIN tags ON hosts_tags.tag_id = tags.id" q2 << "WHERE hosts_tags.host_id = ? AND tags.name IN (%s)" q2 << "GROUP BY tags.name;" fields_without_host = fields.reject { |tag_name| tag_name == "host" } result = host_ids.map { |host_id| tag_values = Hash[ fields_without_host.each_slice(SQLITE_LIMIT_COMPOUND_SELECT - 1).flat_map { |fields_without_host| execute(q2.join(" ") % fields_without_host.map { "?" }.join(", "), [host_id] + fields_without_host).map { |row| row.to_a } } ] fields.map { |tag_name| if tag_name == "host" host_names.fetch(host_id, "") else tag_values.fetch(tag_name, "") end } } [result, fields] else if @options[:primary_tag] fields = [@options[:primary_tag]] q1 = [] q1 << "SELECT tags.value FROM hosts_tags" q1 << "INNER JOIN hosts ON hosts_tags.host_id = hosts.id" q1 << "INNER JOIN tags ON hosts_tags.tag_id = tags.id" q1 << "WHERE hosts_tags.host_id IN (%s) AND tags.name = ?;" result = host_ids.each_slice(SQLITE_LIMIT_COMPOUND_SELECT - 1).flat_map { |host_ids| execute(q1.join(" ") % host_ids.map { "?" }.join(", "), host_ids + [@options[:primary_tag]]).map { |row| row.to_a } } [result, fields] else fields = ["host"] result = host_ids.each_slice(SQLITE_LIMIT_COMPOUND_SELECT).flat_map { |host_ids| execute("SELECT name FROM hosts WHERE id IN (%s)" % host_ids.map { "?" }.join(", "), host_ids).map { |row| row.to_a } } [result, fields] end end end end end def close_db(db, options={}) @prepared_statements = @prepared_statements.reject { |k, statement| (db.hash & MASK_DATABASE == k & MASK_DATABASE).tap do |delete_p| statement.close() if delete_p end } db.close() end def update_db(options={}) options = @options.merge(options) if @db.nil? FileUtils.mkdir_p(options[:confdir]) persistent = File.join(options[:confdir], PERSISTENT_DB) if not options[:force] and File.exist?(persistent) and Time.new < File.mtime(persistent) + options[:expiry] begin persistent_db = SQLite3::Database.new(persistent) persistent_db.execute("SELECT id, name FROM hosts LIMIT 1") persistent_db.execute("SELECT id, name, value FROM tags LIMIT 1") persistent_db.execute("SELECT host_id, tag_id FROM hosts_tags LIMIT 1") @db = persistent_db return rescue SQLite3::SQLException persistent_db.close() end end memory_db = SQLite3::Database.new(":memory:") create_table_hosts(memory_db) create_index_hosts(memory_db) create_table_tags(memory_db) create_index_tags(memory_db) create_table_hosts_tags(memory_db) create_index_hosts_tags(memory_db) all_tags = get_all_tags() memory_db.transaction do known_tags = all_tags.keys.map { |tag| split_tag(tag) }.uniq known_tags.each_slice(SQLITE_LIMIT_COMPOUND_SELECT / 2) do |known_tags| prepare(memory_db, "INSERT OR IGNORE INTO tags (name, value) VALUES %s" % known_tags.map { "(?, ?)" }.join(", ")).execute(known_tags) end known_hosts = all_tags.values.reduce(:+).uniq known_hosts.each_slice(SQLITE_LIMIT_COMPOUND_SELECT) do |known_hosts| prepare(memory_db, "INSERT OR IGNORE INTO hosts (name) VALUES %s" % known_hosts.map { "(?)" }.join(", ")).execute(known_hosts) end all_tags.each do |tag, hosts| q = [] q << "INSERT OR REPLACE INTO hosts_tags (host_id, tag_id)" q << "SELECT host.id, tag.id FROM" q << "( SELECT id FROM hosts WHERE name IN (%s) ) AS host," q << "( SELECT id FROM tags WHERE name = ? AND value = ? LIMIT 1 ) AS tag;" hosts.each_slice(SQLITE_LIMIT_COMPOUND_SELECT - 2) do |hosts| prepare(memory_db, q.join(" ") % hosts.map { "?" }.join(", ")).execute(hosts + split_tag(tag)) end end end # backup in-memory db to file FileUtils.rm_f(persistent) persistent_db = SQLite3::Database.new(persistent) copy_db(memory_db, persistent_db) close_db(persistent_db) @db = memory_db else @db end end def get_all_tags() #==> Hash<Tag,Array<Host>> code, all_tags = @dog.all_tags() logger.debug("dog.all_tags() #==> [%s, ...]" % [code.inspect]) if code.to_i / 100 != 2 raise("dog.all_tags() returns [%s, ...]" % [code.inspect]) end code, all_downtimes = @dog.get_all_downtimes() logger.debug("dog.get_all_downtimes() #==> [%s, ...]" % [code.inspect]) if code.to_i / 100 != 2 raise("dog.get_all_downtimes() returns [%s, ...]" % [code.inspect]) end now = Time.new.to_i downtimes = all_downtimes.select { |downtime| # active downtimes downtime["active"] and ( downtime["start"].nil? or downtime["start"] < now ) and ( downtime["end"].nil? or now <= downtime["end"] ) }.flat_map { |downtime| # find host scopes downtime["scope"].select { |scope| scope.start_with?("host:") }.map { |scope| scope.sub(/\Ahost:/, "") } } if not downtimes.empty? logger.info("ignore host(s) with scheduled downtimes: #{downtimes.inspect}") end Hash[all_tags["tags"].map { |tag, hosts| [tag, hosts.reject { |host| downtimes.include?(host) }] }] end def split_tag(tag) tag_name, tag_value = tag.split(":", 2) [tag_name, tag_value || ""] end def copy_db(src, dst) # create index later for better insert performance dst.transaction do create_table_hosts(dst) create_table_tags(dst) create_table_hosts_tags(dst) hosts = prepare(src, "SELECT id, name FROM hosts").execute().to_a hosts.each_slice(SQLITE_LIMIT_COMPOUND_SELECT / 2) do |hosts| prepare(dst, "INSERT INTO hosts (id, name) VALUES %s" % hosts.map { "(?, ?)" }.join(", ")).execute(hosts) end tags = prepare(src, "SELECT id, name, value FROM tags").execute().to_a tags.each_slice(SQLITE_LIMIT_COMPOUND_SELECT / 3) do |tags| prepare(dst, "INSERT INTO tags (id, name, value) VALUES %s" % tags.map { "(?, ?, ?)" }.join(", ")).execute(tags) end hosts_tags = prepare(src, "SELECT host_id, tag_id FROM hosts_tags").to_a hosts_tags.each_slice(SQLITE_LIMIT_COMPOUND_SELECT / 2) do |hosts_tags| prepare(dst, "INSERT INTO hosts_tags (host_id, tag_id) VALUES %s" % hosts_tags.map { "(?, ?)" }.join(", ")).execute(hosts_tags) end create_index_hosts(dst) create_index_tags(dst) create_index_hosts_tags(dst) end end def create_table_hosts(db) q = "CREATE TABLE IF NOT EXISTS hosts (" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + "name VARCHAR(255) NOT NULL COLLATE NOCASE" + ");" logger.debug(q) db.execute(q) end def create_index_hosts(db) q = "CREATE UNIQUE INDEX IF NOT EXISTS hosts_name ON hosts ( name );" logger.debug(q) db.execute(q) end def create_table_tags(db) q = "CREATE TABLE IF NOT EXISTS tags (" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + "name VARCHAR(200) NOT NULL COLLATE NOCASE," + "value VARCHAR(200) NOT NULL COLLATE NOCASE" + ");" logger.debug(q) db.execute(q) end def create_index_tags(db) q = "CREATE UNIQUE INDEX IF NOT EXISTS tags_name_value ON tags ( name, value );" logger.debug(q) db.execute(q) end def create_table_hosts_tags(db) q = "CREATE TABLE IF NOT EXISTS hosts_tags (" + "host_id INTEGER NOT NULL," + "tag_id INTEGER NOT NULL" + ");" logger.debug(q) db.execute(q) end def create_index_hosts_tags(db) q = "CREATE UNIQUE INDEX IF NOT EXISTS hosts_tags_host_id_tag_id ON hosts_tags ( host_id, tag_id );" logger.debug(q) db.execute(q) end end end end # vim:set ft=ruby :
require 'contracts' require 'csv' require 'prawn' require 'prawn/table' module HowIs class UnsupportedExportFormat < StandardError def initialize(format) super("Unsupported export format: #{format}") end end ## # Represents a completed report. class Report < Struct.new(:analysis, :file) def to_h analysis.to_h end alias :to_hash :to_h def export_csv!(filename=file) hash = to_h CSV.open(filename, "wb") do |csv| csv << hash.keys csv << hash.values end end def export_json!(filename=file) File.open(filename, 'rw') do |f| f.write to_h.to_json end end def export_pdf!(filename=file) oldest_date_format = "%b %e, %Y" a = analysis Prawn::Document.generate(filename) do font("Helvetica") span(450, position: :center) do pad(10) { text "How is #{a.repository}?", size: 25 } pad(5) { text "Issues" } text issue_or_pr_summary(a, "issue", "issue") pad(5) { text "Pull Requests" } text issue_or_pr_summary(a, "pull", "pull request") pad(10) { text "Issues per label" } table a.issues_with_label.to_a.sort_by { |(k, v)| v.to_i }.reverse # TODO: GitHub's API doesn't include labels for PRs but does for issues?! pad(10) { text "Pull Requests per label" } text "TODO." #table a.pulls_with_label.to_a end end end def export!(filename=file) extension = filename.split('.').last if extension == 'csv' export_csv!(filename) elsif extension == 'pdf' export_pdf!(filename) else raise UnsupportedExportFormat, filename.split('.').last end end private def issue_or_pr_summary(analysis, type, type_label) a = analysis "#{a.repository} has #{a.send("number_of_#{type}s")} #{type_label}s open. " + "The average #{type_label} age is #{a.send("average_#{type}_age")}, and the " + "oldest #{type_label} was opened on #{a.send("oldest_#{type}_date").strftime(oldest_date_format)}" end end class Reporter include Contracts::Core ## # Given an Analysis, generate a Report Contract Analysis, String => Report def call(analysis, report_file) Report.new(analysis, report_file) end end end Make export!() automagically handle new formats. require 'contracts' require 'csv' require 'prawn' require 'prawn/table' module HowIs class UnsupportedExportFormat < StandardError def initialize(format) super("Unsupported export format: #{format}") end end ## # Represents a completed report. class Report < Struct.new(:analysis, :file) def to_h analysis.to_h end alias :to_hash :to_h def export_csv!(filename=file) hash = to_h CSV.open(filename, "wb") do |csv| csv << hash.keys csv << hash.values end end def export_json!(filename=file) File.open(filename, 'rw') do |f| f.write to_h.to_json end end def export_pdf!(filename=file) oldest_date_format = "%b %e, %Y" a = analysis Prawn::Document.generate(filename) do font("Helvetica") span(450, position: :center) do pad(10) { text "How is #{a.repository}?", size: 25 } pad(5) { text "Issues" } text issue_or_pr_summary(a, "issue", "issue") pad(5) { text "Pull Requests" } text issue_or_pr_summary(a, "pull", "pull request") pad(10) { text "Issues per label" } table a.issues_with_label.to_a.sort_by { |(k, v)| v.to_i }.reverse # TODO: GitHub's API doesn't include labels for PRs but does for issues?! pad(10) { text "Pull Requests per label" } text "TODO." #table a.pulls_with_label.to_a end end end def export!(filename=file) extension = filename.split('.').last method_name = "export_#{extension}!" if respond_to?(method_name) send(method_name, filename) else raise UnsupportedExportFormat, filename.split('.').last end end private def issue_or_pr_summary(analysis, type, type_label) a = analysis "#{a.repository} has #{a.send("number_of_#{type}s")} #{type_label}s open. " + "The average #{type_label} age is #{a.send("average_#{type}_age")}, and the " + "oldest #{type_label} was opened on #{a.send("oldest_#{type}_date").strftime(oldest_date_format)}" end end class Reporter include Contracts::Core ## # Given an Analysis, generate a Report Contract Analysis, String => Report def call(analysis, report_file) Report.new(analysis, report_file) end end end
module Hstatic VERSION = "0.0.5" end gem: version bump module Hstatic VERSION = "0.1.0" end
require "gerencianet" require_relative "./credentials" options = { client_id: CREDENTIALS::CLIENT_ID, client_secret: CREDENTIALS::CLIENT_SECRET, sandbox: CREDENTIALS::SANDBOX } params = { name: "My Plan", limit: 1, offset: 0 } gerencianet = Gerencianet.new(options) puts gerencianet.get_plans(params: params) Added: API Pix endpoints require "gerencianet" require_relative "../../credentials" options = { client_id: CREDENTIALS::CLIENT_ID, client_secret: CREDENTIALS::CLIENT_SECRET, sandbox: CREDENTIALS::SANDBOX } params = { name: "My Plan", limit: 1, offset: 0 } gerencianet = Gerencianet.new(options) puts gerencianet.get_plans(params: params)
Add example how to install MySQL from source # Install the latest MySQL database from source package :mysql do requires :mysql_dependencies, :mysql_user_group, :mysql_user, :mysql_core end package :mysql_dependencies do description 'MySQL dependencies' apt 'cmake' end package :mysql_user_group do description 'MySQL user group' group 'mysql' verify do has_group 'mysql' end end package :mysql_user do description 'MySQL user' requires :mysql_user_group runner 'useradd -r -g mysql mysql' verify do has_user 'mysql' end end package :mysql_core do description 'MySQL database' version '5.5.25a' requires :mysql_dependencies, :mysql_user_group, :mysql_user source "http://dev.mysql.com/get/Downloads/MySQL-5.5/mysql-#{version}.tar.gz/from/http://cdn.mysql.com/" do custom_archive "mysql-#{version}.tar.gz" configure_command 'cmake .' post :install, '/usr/local/mysql/scripts/mysql_install_db --user=mysql --basedir=/usr/local/mysql' post :install, 'chown -R mysql:mysql /usr/local/mysql/data' end verify do has_executable '/usr/local/mysql/bin/mysql' end end
# # Cookbook Name:: bcpc # Recipe:: keystone # # Copyright 2013, Bloomberg Finance L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # include_recipe "bcpc::mysql-head" include_recipe "bcpc::openstack" include_recipe "bcpc::apache2" # Override keystone from starting cookbook_file "/etc/init/keystone.override" do owner "root" group "root" mode "0644" source "keystone/init.keystone.override" end ruby_block "initialize-keystone-config" do block do # TODO(kamidzi): this is all suspect now... # Essentially prefer ldap-backed identities for admin? make_config('mysql-keystone-user', "keystone") make_config('mysql-keystone-password', secure_password) make_config('keystone-admin-token', secure_password) make_config('keystone-local-admin-password', secure_password) make_config('keystone-admin-user', node["bcpc"]["ldap"]["admin_user"] || node["bcpc"]["keystone"]["admin"]["username"]) make_config('keystone-admin-password', node["bcpc"]["ldap"]["admin_pass"] || get_config('keystone-local-admin-password')) make_config('keystone-admin-project-name', node['bcpc']['ldap']['admin_project_name'] || node["bcpc"]["keystone"]["admin"]["project_name"]) make_config('keystone-admin-project-domain', node['bcpc']['ldap']['admin_project_domain'] || node["bcpc"]["keystone"]["admin"]["project_domain"]) make_config('keystone-admin-user-domain', node['bcpc']['ldap']['admin_user_domain'] || node["bcpc"]["keystone"]["admin"]["user_domain"]) begin get_config('keystone-pki-certificate') rescue temp = %x[openssl req -new -x509 -passout pass:temp_passwd -newkey rsa:2048 -out /dev/stdout -keyout /dev/stdout -days 1095 -subj "/C=#{node['bcpc']['country']}/ST=#{node['bcpc']['state']}/L=#{node['bcpc']['location']}/O=#{node['bcpc']['organization']}/OU=#{node['bcpc']['region_name']}/CN=keystone.#{node['bcpc']['cluster_domain']}/emailAddress=#{node['bcpc']['keystone']['admin_email']}"] make_config('keystone-pki-private-key', %x[echo "#{temp}" | openssl rsa -passin pass:temp_passwd -out /dev/stdout]) make_config('keystone-pki-certificate', %x[echo "#{temp}" | openssl x509]) end end end package 'python-ldappool' do action :upgrade end package 'keystone' do action :upgrade notifies :run, 'bash[flush-memcached]', :immediately end # sometimes the way tokens are stored changes and causes issues, # so flush memcached if Keystone is upgraded bash 'flush-memcached' do code "echo flush_all | nc #{node['bcpc']['management']['ip']} 11211" action :nothing end # these packages need to be updated in Liberty but are not upgraded when Keystone is upgraded %w( python-oslo.i18n python-oslo.serialization python-pyasn1 ).each do |pkg| package pkg do action :upgrade notifies :restart, "service[apache2]", :immediately end end # do not run or try to start standalone keystone service since it is now served by WSGI service "keystone" do action [:disable, :stop] end # if on Liberty, generate Fernet keys and persist the keys in the data bag (if not already # generated) fernet_key_directory = '/etc/keystone/fernet-keys' directory fernet_key_directory do owner 'keystone' group 'keystone' mode "0700" end # write out keys if defined in the data bag # (there should always be at least 0 (staged) and 1 (primary) in the data bag) ruby_block 'write-out-fernet-keys-from-data-bag' do block do (0..2).each do |idx| if config_defined("keystone-fernet-key-#{idx}") key_path = ::File.join(fernet_key_directory, idx.to_s) key_in_databag = get_config("keystone-fernet-key-#{idx}") ::File.write(key_path, key_in_databag) end end # remove any other keys present in the directory (not 0, 1, or 2) ::Dir.glob(::File.join(fernet_key_directory, '*')).reject do |path| path.end_with?(*(0..2).collect(&:to_s)) end.each do |file_to_delete| ::File.delete(file_to_delete) end end # if any key needs to be rewritten, then we'll rewrite them all only_if do need_to_write_keys = [] (0..2).each do |idx| key_path = ::File.join(fernet_key_directory, idx.to_s) if ::File.exist?(key_path) key_on_disk = ::File.read(key_path) if config_defined("keystone-fernet-key-#{idx}") need_to_write_keys << (key_on_disk != get_config("keystone-fernet-key-#{idx}")) end else # key does not exist on disk, ensure that it is written out need_to_write_keys << true end end need_to_write_keys.any? end notifies :restart, 'service[apache2]', :immediately end # generate Fernet keys if there are not any on disk (first time setup) ruby_block 'first-time-fernet-key-generation' do block do Mixlib::ShellOut.new('keystone-manage fernet_setup --keystone-user keystone --keystone-group keystone').run_command.error! make_config('keystone-fernet-last-rotation', Time.now) end not_if { ::File.exist?(::File.join(fernet_key_directory, '0')) } notifies :restart, 'service[apache2]', :immediately end # if the staged key's mtime is at least this many days old and the data bag # has recorded a last rotation timestamp , execute a rotation ruby_block 'rotate-fernet-keys' do block do fernet_keys = ::Dir.glob(::File.join(fernet_key_directory, '*')).sort # the current staged key (0) will become the new master new_master_key = ::File.read(fernet_keys.first) # the current master key (highest index) will become a secondary key old_master_key = ::File.read(fernet_keys.last) # execute a rotation via keystone-manage so that we get a new staging key Mixlib::ShellOut.new('keystone-manage fernet_rotate --keystone-user keystone --keystone-group keystone').run_command.error! # 0 is now the new staging key so read that file again new_staging_key = ::File.read(fernet_keys.first) # destroy the on-disk keys before we rewrite them to disk ::Dir.glob(::File.join(fernet_key_directory, '*')).each do |fk| ::File.delete(fk) end # write new master key to 2 ::File.write(::File.join(fernet_key_directory, '2'), new_master_key) # write staging key to 0 ::File.write(::File.join(fernet_key_directory, '0'), new_staging_key) # write old master key to 1 ::File.write(::File.join(fernet_key_directory, '1'), old_master_key) # re-permission all keys to ensure they are owned by keystone and chmod 600 Mixlib::ShellOut.new('chown keystone:keystone /etc/keystone/fernet-keys/*').run_command.error! Mixlib::ShellOut.new('chmod 0600 /etc/keystone/fernet-keys/*').run_command.error! # update keystone-fernet-last-rotation timestamp make_config('keystone-fernet-last-rotation', Time.now.to_i, force=true) # (writing these keys into the data bag will be done by the add-fernet-keys-to-data-bag resource) end only_if do # if key rotation is disabled then skip out if node['bcpc']['keystone']['rotate_fernet_tokens'] if config_defined('keystone-fernet-last-rotation') Time.now.to_i - get_config('keystone-fernet-last-rotation').to_i > node['bcpc']['keystone']['fernet_token_max_age_seconds'] else # always run if keystone-fernet-last-rotation is not defined # (upgrade from 6.0.0) true end else false end end notifies :restart, 'service[apache2]', :immediately end # key indexes in the data bag will not necessarily match the files on disk # (staged key is always key 0, primary key is the highest-indexed one, any # keys in between are former primary keys that can only decrypt) ruby_block 'add-fernet-keys-to-data-bag' do block do fernet_keys = ::Dir.glob(::File.join(fernet_key_directory, '*')).sort fernet_keys.each_with_index do |key_path, idx| db_key = "keystone-fernet-key-#{idx}" disk_key_value = ::File.read(key_path) begin db_key_value = get_config(db_key) make_config(db_key, disk_key_value, force=true) unless db_key_value == disk_key_value # save old key to backup slot Just In Case make_config("#{db_key}-backup", db_key_value, force=true) rescue make_config(db_key, disk_key_value) end end end only_if do need_to_add_keys = [] (0..2).each do |idx| key_path = ::File.join(fernet_key_directory, idx.to_s) if ::File.exist?(key_path) key_on_disk = ::File.read(key_path) if config_defined("keystone-fernet-key-#{idx}") need_to_add_keys << (key_on_disk != get_config("keystone-fernet-key-#{idx}")) else need_to_add_keys << true end end end need_to_add_keys.any? end end # standalone Keystone service has a window to start up in and create keystone.log with # wrong permissions, so ensure it's owned by keystone:keystone file "/var/log/keystone/keystone.log" do owner "keystone" group "keystone" notifies :restart, "service[apache2]", :immediately end domain_config_dir = node['bcpc']['keystone']['domain_config_dir'] directory domain_config_dir do owner "keystone" group "keystone" mode "2700" end template "/etc/keystone/keystone.conf" do source "keystone/keystone.conf.erb" owner "keystone" group "keystone" mode "0600" variables( lazy { { :servers => get_head_nodes } } ) notifies :restart, "service[apache2]", :immediately end cookbook_file "/etc/keystone/keystone-paste.ini" do source "keystone/keystone-paste.ini" owner "keystone" group "keystone" mode "0600" notifies :restart, "service[apache2]", :immediately end node['bcpc']['keystone']['domains'].each do |domain, config| config_file = File.join domain_config_dir, "keystone.#{domain}.conf" template config_file do source "keystone/keystone.domain.conf.erb" owner "keystone" group "keystone" mode "0600" variables( :domain => config ) # should this be here..? notifies :restart, "service[apache2]", :delayed end end template "/etc/keystone/default_catalog.templates" do source "keystone-default_catalog.templates.erb" owner "keystone" group "keystone" mode "0644" notifies :restart, "service[apache2]", :delayed end template "/etc/keystone/cert.pem" do source "keystone-cert.pem.erb" owner "keystone" group "keystone" mode "0644" notifies :restart, "service[apache2]", :delayed end template "/etc/keystone/key.pem" do source "keystone-key.pem.erb" owner "keystone" group "keystone" mode "0600" notifies :restart, "service[apache2]", :delayed end template "/etc/keystone/policy.json" do source "keystone-policy.json.erb" owner "keystone" group "keystone" mode "0600" variables(:policy => JSON.pretty_generate(node['bcpc']['keystone']['policy'])) end template "/root/api_versionsrc" do source "api_versionsrc.erb" owner "root" group "root" mode "0600" end template "/root/keystonerc" do source "keystonerc.erb" owner "root" group "root" mode "0600" end # configure WSGI # /var/www created by apache2 package, /var/www/cgi-bin created in bcpc::apache2 #wsgi_keystone_dir = "/var/www/cgi-bin/keystone" #directory wsgi_keystone_dir do # action :create # owner "root" # group "root" # mode "0755" #end #%w{main admin}.each do |wsgi_link| # link ::File.join(wsgi_keystone_dir, wsgi_link) do # action :create # to "/usr/share/keystone/wsgi.py" # end #end template "/etc/apache2/sites-available/wsgi-keystone.conf" do source "keystone/apache-wsgi-keystone.conf.erb" owner "root" group "root" mode "0644" variables( :processes => node['bcpc']['keystone']['wsgi']['processes'], :threads => node['bcpc']['keystone']['wsgi']['threads'] ) notifies :restart, "service[apache2]", :immediately end bash "a2ensite-enable-wsgi-keystone" do user "root" code "a2ensite wsgi-keystone" not_if "test -r /etc/apache2/sites-enabled/wsgi-keystone.conf" notifies :restart, "service[apache2]", :immediately end ruby_block "keystone-database-creation" do block do %x[ export MYSQL_PWD=#{get_config('mysql-root-password')}; mysql -uroot -e "CREATE DATABASE #{node['bcpc']['dbname']['keystone']};" mysql -uroot -e "GRANT ALL ON #{node['bcpc']['dbname']['keystone']}.* TO '#{get_config('mysql-keystone-user')}'@'%' IDENTIFIED BY '#{get_config('mysql-keystone-password')}';" mysql -uroot -e "GRANT ALL ON #{node['bcpc']['dbname']['keystone']}.* TO '#{get_config('mysql-keystone-user')}'@'localhost' IDENTIFIED BY '#{get_config('mysql-keystone-password')}';" mysql -uroot -e "FLUSH PRIVILEGES;" ] self.notifies :run, "bash[keystone-database-sync]", :immediately self.resolve_notification_references end not_if { system "MYSQL_PWD=#{get_config('mysql-root-password')} mysql -uroot -e 'SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = \"#{node['bcpc']['dbname']['keystone']}\"'|grep \"#{node['bcpc']['dbname']['keystone']}\" >/dev/null" } end ruby_block 'update-keystone-db-schema' do block do self.notifies :run, "bash[keystone-database-sync]", :immediately self.resolve_notification_references end only_if { ::File.exist?('/usr/local/etc/openstack_upgrade') and not has_unregistered_migration? } end bash "keystone-database-sync" do action :nothing user "root" code "keystone-manage db_sync" notifies :restart, "service[apache2]", :immediately end ruby_block "keystone-region-creation" do block do %x[ export MYSQL_PWD=#{get_config('mysql-root-password')}; mysql -uroot -e "INSERT INTO keystone.region (id, extra) VALUES(\'#{node['bcpc']['region_name']}\', '{}');" ] end not_if { system "MYSQL_PWD=#{get_config('mysql-root-password')} mysql -uroot -e 'SELECT id FROM keystone.region WHERE id = \"#{node['bcpc']['region_name']}\"' | grep \"#{node['bcpc']['region_name']}\" >/dev/null" } end # this is a synchronization resource that polls Keystone on the VIP to verify that it's not returning 503s, # if something above has restarted Apache and Keystone isn't ready to play yet ruby_block "wait-for-keystone-to-become-operational" do delay = 1 retries = (node['bcpc']['keystone']['wait_for_keystone_timeout']/delay).ceil block do r = execute_in_keystone_admin_context("openstack region list -fvalue") raise Exception.new('Still waiting for keystone') if r.strip.empty? end retry_delay delay retries retries end # TODO(kamidzi): each service should create its *own* catalog entry # create services and endpoint catalog = node['bcpc']['catalog'].dup catalog.delete('network') unless node['bcpc']['enabled']['neutron'] catalog.each do |svc, svcprops| # attempt to delete endpoints that no longer match the environment # (keys off the service type, so it is possible to orphan endpoints if you remove an # entry from the environment service catalog) ruby_block "keystone-delete-outdated-#{svc}-endpoint" do block do svc_endpoints_raw = execute_in_keystone_admin_context('openstack endpoint list -f json') begin #puts svc_endpoints_raw svc_endpoints = JSON.parse(svc_endpoints_raw) #puts svc_endpoints svc_ids = svc_endpoints.select { |k| k['Service Type'] == svc }.collect { |v| v['ID'] } #puts svc_ids svc_ids.each do |svc_id| execute_in_keystone_admin_context("openstack endpoint delete #{svc_id} 2>&1") end rescue JSON::ParserError end end not_if { svc_endpoints_raw = execute_in_keystone_admin_context('openstack endpoint list -f json') begin svc_endpoints = JSON.parse(svc_endpoints_raw) next if svc_endpoints.empty? svcs = svc_endpoints.select { |k| k['Service Type'] == svc } next if svcs.empty? adminurl_raw = svcs.select { |v| v['URL'] if v['Interface'] == 'admin' } adminurl = adminurl_raw.empty? ? nil : adminurl_raw[0]['URL'] internalurl_raw = svcs.select { |v| v['URL'] if v['Interface'] == 'internal' } internalurl = internalurl_raw.empty? ? nil : internalurl_raw[0]['URL'] publicurl_raw = svcs.select { |v| v['URL'] if v['Interface'] == 'public' } publicurl = publicurl_raw.empty? ? nil : publicurl_raw[0]['URL'] adminurl_match = adminurl.nil? ? true : (adminurl == generate_service_catalog_uri(svcprops, 'admin')) internalurl_match = internalurl.nil? ? true : (internalurl == generate_service_catalog_uri(svcprops, 'internal')) publicurl_match = publicurl.nil? ? true : (publicurl == generate_service_catalog_uri(svcprops, 'public')) adminurl_match && internalurl_match && publicurl_match rescue JSON::ParserError false end } end # why no corresponding deletion for out of date services? # services don't get outdated in the way endpoints do (since endpoints encode version numbers and ports), # services just say that service X is present in the catalog, not how to access it ruby_block "keystone-create-#{svc}-service" do block do execute_in_keystone_admin_context("openstack service create --name '#{svcprops['name']}' --description '#{svcprops['description']}' #{svc}") end only_if { services_raw = execute_in_keystone_admin_context('openstack service list -f json') services = JSON.parse(services_raw) services.select { |s| s['Type'] == svc }.length.zero? } end # openstack command syntax changes between identity API v2 and v3, so calculate the endpoint creation command ahead of time identity_api_version = node['bcpc']['catalog']['identity']['uris']['public'].scan(/^[^\d]*(\d+)/)[0][0].to_i if identity_api_version == 3 endpoint_create_cmd = <<-EOH openstack endpoint create \ --region '#{node['bcpc']['region_name']}' #{svc} public "#{generate_service_catalog_uri(svcprops, 'public')}" ; openstack endpoint create \ --region '#{node['bcpc']['region_name']}' #{svc} internal "#{generate_service_catalog_uri(svcprops, 'internal')}" ; openstack endpoint create \ --region '#{node['bcpc']['region_name']}' #{svc} admin "#{generate_service_catalog_uri(svcprops, 'admin')}" ; EOH else endpoint_create_cmd = <<-EOH openstack endpoint create \ --region '#{node['bcpc']['region_name']}' \ --publicurl "#{generate_service_catalog_uri(svcprops, 'public')}" \ --adminurl "#{generate_service_catalog_uri(svcprops, 'admin')}" \ --internalurl "#{generate_service_catalog_uri(svcprops, 'internal')}" \ #{svc} EOH end ruby_block "keystone-create-#{svc}-endpoint" do block do execute_in_keystone_admin_context(endpoint_create_cmd) end only_if { endpoints_raw = execute_in_keystone_admin_context('openstack endpoint list -f json') endpoints = JSON.parse(endpoints_raw) endpoints.select { |e| e['Service Type'] == svc }.length.zero? } end end # Create domains, projects, and roles # NOTE(kamidzi): this is using legacy attribute. Maybe should change it? default_domain = node['bcpc']['keystone']['default_domain'] member_role_name = node['bcpc']['keystone']['member_role'] service_project_name = node['bcpc']['keystone']['service_project']['name'] service_project_domain = node['bcpc']['keystone']['service_project']['domain'] admin_project_name = node['bcpc']['keystone']['admin']['project_name'] admin_role_name = node['bcpc']['keystone']['admin_role'] admin_username = node['bcpc']['keystone']['admin']['username'] # NB(kamidzi): Make sure admin project is in same domain as service project! admin_project_domain = node['bcpc']['keystone']['admin']['project_domain'] admin_user_domain = node['bcpc']['keystone']['admin']['user_domain'] # For case... mostly migratory where ldap-backed domain already exists, sql-backed is added admin_config = { sql: { project_name: admin_project_name, project_domain: admin_project_domain, user_domain: admin_user_domain, user_name: admin_username }, } # Create the domains ruby_block "keystone-create-domains" do block do node['bcpc']['keystone']['domains'].each do |domain, attrs| name = "keystone-create-domain::#{domain}" desc = attrs['description'] || '' run_context.resource_collection << dom_create = Chef::Resource::RubyBlock.new(name, run_context) dom_create.block { execute_in_keystone_admin_context("openstack domain create --description '#{desc}' #{domain}") } # TODO(kamidzi): if domain changes, guard will not detect dom_create.not_if { s = execute_in_keystone_admin_context("openstack domain show #{domain}"){|o,e,s| s} s.success? } # Configure them name = "keystone-configure-domain::#{domain}" # Use domain_config_upload for now run_context.resource_collection << dom_configure = Chef::Resource::RubyBlock.new(name, run_context) dom_configure.block { %x{ keystone-manage domain_config_upload --domain "#{domain}"} } # TODO(kamidzi): need a conditional... end end end ruby_block "keystone-create-admin-projects" do block do admin_config[:ldap] = { project_name: get_config('keystone-admin-project-name'), project_domain: get_config('keystone-admin-project-domain'), user_domain: get_config('keystone-admin-user-domain'), user_name: get_config('keystone-admin-user') } admin_config.each do |backend, config| name = "keystone-create-admin-project::#{config[:project_name]}" run_context.resource_collection << project_create = Chef::Resource::RubyBlock.new(name, run_context) project_create.block { execute_in_keystone_admin_context("openstack project create --domain #{config[:project_domain]} " + "--description 'Admin Project' #{config[:project_name]}") } project_create.not_if { cmd = "openstack project show --domain #{config[:project_domain]} " + "#{config[:project_name]}" s = execute_in_keystone_admin_context(cmd){|o,e,s| s} s.success? } end end end ruby_block "keystone-create-admin-user" do block do execute_in_keystone_admin_context("openstack user create --domain #{admin_project_domain} --password " + "#{get_config('keystone-local-admin-password')} #{admin_username}") end not_if { cmd = "openstack user show --domain #{admin_project_domain} #{admin_username}" s = execute_in_keystone_admin_context(cmd){|o,e,s| s} s.success? } end # FYI: https://blueprints.launchpad.net/keystone/+spec/domain-specific-roles ruby_block "keystone-create-admin-role" do block do execute_in_keystone_admin_context("openstack role create #{admin_role_name}") end not_if { s = execute_in_keystone_admin_context("openstack role show #{admin_role_name}"){|o,e,s| s} s.success? } end ruby_block "keystone-assign-admin-roles" do block do admin_config[:ldap] = { project_name: get_config('keystone-admin-project-name'), project_domain: get_config('keystone-admin-project-domain'), user_domain: get_config('keystone-admin-user-domain'), user_name: get_config('keystone-admin-user') } admin_config.each do |backend, config| name = "keystone-assign-admin-role::#{config[:user_domain]}::#{config[:user_name]}" a_cmd = "openstack role add" a_opts = [ "--user-domain #{config[:user_domain]}", "--user #{config[:user_name]}", "--project-domain #{config[:project_domain]}", "--project #{config[:project_name]}" ] a_args = [admin_role_name] g_cmd = "openstack role assignment list" g_opts = a_opts + [ "-fjson", "--role #{admin_role_name}", ] assign_cmd = ([a_cmd] + a_opts + a_args).join(' ') guard_cmd = ([g_cmd] + g_opts).join(' ') run_context.resource_collection << admin_assign = Chef::Resource::RubyBlock.new(name, run_context) admin_assign.block { execute_in_keystone_admin_context(assign_cmd) } admin_assign.only_if { begin r = JSON.parse execute_in_keystone_admin_context(guard_cmd) r.empty? rescue JSON::ParserError true end } end end end ruby_block "keystone-create-service-project" do block do execute_in_keystone_admin_context("openstack project create --domain #{service_project_domain} --description 'Service Project' #{service_project_name}") end not_if { cmd = "openstack project show --domain #{service_project_domain} #{service_project_name}" s = execute_in_keystone_admin_context(cmd){|o,e,s| s} s.success? } end ruby_block "keystone-create-member-role" do block do execute_in_keystone_admin_context("openstack role create #{member_role_name}") end not_if { s = execute_in_keystone_admin_context("openstack role show #{member_role_name}"){|o,e,s| s} s.success? } end # FIXME(kamidzi): this is another level of indirection because of preference to ldap # This is legacy credentials file template "/root/adminrc" do source "keystone/openrc.erb" owner "root" group "root" mode "0600" variables( lazy { { username: get_config('keystone-admin-user'), password: get_config('keystone-admin-password'), project_name: get_config('keystone-admin-project-name'), user_domain: get_config('keystone-admin-user-domain'), project_domain: get_config('keystone-admin-project-domain') } } ) end # This is a *domain* admin in separate domain along with service accounts template "/root/admin-openrc" do source "keystone/openrc.erb" owner "keystone" group "keystone" mode "0600" variables( lazy { { username: admin_username, password: get_config('keystone-local-admin-password'), project_name: admin_project_name, user_domain: admin_user_domain, project_domain: admin_project_domain } } ) end # # Cleanup actions # file "/var/lib/keystone/keystone.db" do action :delete end # Migration for user ids # This is necessary when existing admin user is a member of an ldap-backed domain # in single-domain deployment which then migrates to multi-domain deployment. Even # if domain name remains the same, the user is re-issued an id. This new id needs to # be permissioned cookbook_file "/usr/lib/python2.7/dist-packages/keystone/common/sql/migrate_repo/versions/098_migrate_single_to_multi_domain_user_ids.py" do source "keystone/098_migrate_single_to_multi_domain_user_ids.py" owner "root" group "root" mode "0644" end # User records need to be accessed to populate database with new, stable public IDs ruby_block "keystone-list-admin-domain-users" do block do execute_in_keystone_admin_context("openstack user list --domain #{get_config('keystone-admin-user-domain')}") end notifies :run, "bash[keystone-database-sync]", :immediately not_if { %x[bash -c '. /root/adminrc && openstack token issue'] ; $?.success? and keystone_db_version == '98' } end Re-factor databag config initialisation for Keystone Some variables are needed immediately, so no need to tarry with ruby_block resource. # # Cookbook Name:: bcpc # Recipe:: keystone # # Copyright 2013, Bloomberg Finance L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # include_recipe "bcpc::mysql-head" include_recipe "bcpc::openstack" include_recipe "bcpc::apache2" # Override keystone from starting cookbook_file "/etc/init/keystone.override" do owner "root" group "root" mode "0644" source "keystone/init.keystone.override" end begin make_config('mysql-keystone-user', "keystone") make_config('mysql-keystone-password', secure_password) make_config('keystone-admin-token', secure_password) make_config('keystone-local-admin-password', secure_password) make_config('keystone-admin-user', node["bcpc"]["ldap"]["admin_user"] || node["bcpc"]["keystone"]["admin"]["username"]) make_config('keystone-admin-password', node["bcpc"]["ldap"]["admin_pass"] || get_config('keystone-local-admin-password')) make_config('keystone-admin-project-name', node['bcpc']['ldap']['admin_project_name'] || node["bcpc"]["keystone"]["admin"]["project_name"]) make_config('keystone-admin-project-domain', node['bcpc']['ldap']['admin_project_domain'] || node["bcpc"]["keystone"]["admin"]["project_domain"]) make_config('keystone-admin-user-domain', node['bcpc']['ldap']['admin_user_domain'] || node["bcpc"]["keystone"]["admin"]["user_domain"]) begin get_config('keystone-pki-certificate') rescue temp = %x[openssl req -new -x509 -passout pass:temp_passwd -newkey rsa:2048 -out /dev/stdout -keyout /dev/stdout -days 1095 -subj "/C=#{node['bcpc']['country']}/ST=#{node['bcpc']['state']}/L=#{node['bcpc']['location']}/O=#{node['bcpc']['organization']}/OU=#{node['bcpc']['region_name']}/CN=keystone.#{node['bcpc']['cluster_domain']}/emailAddress=#{node['bcpc']['keystone']['admin_email']}"] make_config('keystone-pki-private-key', %x[echo "#{temp}" | openssl rsa -passin pass:temp_passwd -out /dev/stdout]) make_config('keystone-pki-certificate', %x[echo "#{temp}" | openssl x509]) end end package 'python-ldappool' do action :upgrade end package 'keystone' do action :upgrade notifies :run, 'bash[flush-memcached]', :immediately end # sometimes the way tokens are stored changes and causes issues, # so flush memcached if Keystone is upgraded bash 'flush-memcached' do code "echo flush_all | nc #{node['bcpc']['management']['ip']} 11211" action :nothing end # these packages need to be updated in Liberty but are not upgraded when Keystone is upgraded %w( python-oslo.i18n python-oslo.serialization python-pyasn1 ).each do |pkg| package pkg do action :upgrade notifies :restart, "service[apache2]", :immediately end end # do not run or try to start standalone keystone service since it is now served by WSGI service "keystone" do action [:disable, :stop] end # if on Liberty, generate Fernet keys and persist the keys in the data bag (if not already # generated) fernet_key_directory = '/etc/keystone/fernet-keys' directory fernet_key_directory do owner 'keystone' group 'keystone' mode "0700" end # write out keys if defined in the data bag # (there should always be at least 0 (staged) and 1 (primary) in the data bag) ruby_block 'write-out-fernet-keys-from-data-bag' do block do (0..2).each do |idx| if config_defined("keystone-fernet-key-#{idx}") key_path = ::File.join(fernet_key_directory, idx.to_s) key_in_databag = get_config("keystone-fernet-key-#{idx}") ::File.write(key_path, key_in_databag) end end # remove any other keys present in the directory (not 0, 1, or 2) ::Dir.glob(::File.join(fernet_key_directory, '*')).reject do |path| path.end_with?(*(0..2).collect(&:to_s)) end.each do |file_to_delete| ::File.delete(file_to_delete) end end # if any key needs to be rewritten, then we'll rewrite them all only_if do need_to_write_keys = [] (0..2).each do |idx| key_path = ::File.join(fernet_key_directory, idx.to_s) if ::File.exist?(key_path) key_on_disk = ::File.read(key_path) if config_defined("keystone-fernet-key-#{idx}") need_to_write_keys << (key_on_disk != get_config("keystone-fernet-key-#{idx}")) end else # key does not exist on disk, ensure that it is written out need_to_write_keys << true end end need_to_write_keys.any? end notifies :restart, 'service[apache2]', :immediately end # generate Fernet keys if there are not any on disk (first time setup) ruby_block 'first-time-fernet-key-generation' do block do Mixlib::ShellOut.new('keystone-manage fernet_setup --keystone-user keystone --keystone-group keystone').run_command.error! make_config('keystone-fernet-last-rotation', Time.now) end not_if { ::File.exist?(::File.join(fernet_key_directory, '0')) } notifies :restart, 'service[apache2]', :immediately end # if the staged key's mtime is at least this many days old and the data bag # has recorded a last rotation timestamp , execute a rotation ruby_block 'rotate-fernet-keys' do block do fernet_keys = ::Dir.glob(::File.join(fernet_key_directory, '*')).sort # the current staged key (0) will become the new master new_master_key = ::File.read(fernet_keys.first) # the current master key (highest index) will become a secondary key old_master_key = ::File.read(fernet_keys.last) # execute a rotation via keystone-manage so that we get a new staging key Mixlib::ShellOut.new('keystone-manage fernet_rotate --keystone-user keystone --keystone-group keystone').run_command.error! # 0 is now the new staging key so read that file again new_staging_key = ::File.read(fernet_keys.first) # destroy the on-disk keys before we rewrite them to disk ::Dir.glob(::File.join(fernet_key_directory, '*')).each do |fk| ::File.delete(fk) end # write new master key to 2 ::File.write(::File.join(fernet_key_directory, '2'), new_master_key) # write staging key to 0 ::File.write(::File.join(fernet_key_directory, '0'), new_staging_key) # write old master key to 1 ::File.write(::File.join(fernet_key_directory, '1'), old_master_key) # re-permission all keys to ensure they are owned by keystone and chmod 600 Mixlib::ShellOut.new('chown keystone:keystone /etc/keystone/fernet-keys/*').run_command.error! Mixlib::ShellOut.new('chmod 0600 /etc/keystone/fernet-keys/*').run_command.error! # update keystone-fernet-last-rotation timestamp make_config('keystone-fernet-last-rotation', Time.now.to_i, force=true) # (writing these keys into the data bag will be done by the add-fernet-keys-to-data-bag resource) end only_if do # if key rotation is disabled then skip out if node['bcpc']['keystone']['rotate_fernet_tokens'] if config_defined('keystone-fernet-last-rotation') Time.now.to_i - get_config('keystone-fernet-last-rotation').to_i > node['bcpc']['keystone']['fernet_token_max_age_seconds'] else # always run if keystone-fernet-last-rotation is not defined # (upgrade from 6.0.0) true end else false end end notifies :restart, 'service[apache2]', :immediately end # key indexes in the data bag will not necessarily match the files on disk # (staged key is always key 0, primary key is the highest-indexed one, any # keys in between are former primary keys that can only decrypt) ruby_block 'add-fernet-keys-to-data-bag' do block do fernet_keys = ::Dir.glob(::File.join(fernet_key_directory, '*')).sort fernet_keys.each_with_index do |key_path, idx| db_key = "keystone-fernet-key-#{idx}" disk_key_value = ::File.read(key_path) begin db_key_value = get_config(db_key) make_config(db_key, disk_key_value, force=true) unless db_key_value == disk_key_value # save old key to backup slot Just In Case make_config("#{db_key}-backup", db_key_value, force=true) rescue make_config(db_key, disk_key_value) end end end only_if do need_to_add_keys = [] (0..2).each do |idx| key_path = ::File.join(fernet_key_directory, idx.to_s) if ::File.exist?(key_path) key_on_disk = ::File.read(key_path) if config_defined("keystone-fernet-key-#{idx}") need_to_add_keys << (key_on_disk != get_config("keystone-fernet-key-#{idx}")) else need_to_add_keys << true end end end need_to_add_keys.any? end end # standalone Keystone service has a window to start up in and create keystone.log with # wrong permissions, so ensure it's owned by keystone:keystone file "/var/log/keystone/keystone.log" do owner "keystone" group "keystone" notifies :restart, "service[apache2]", :immediately end domain_config_dir = node['bcpc']['keystone']['domain_config_dir'] directory domain_config_dir do owner "keystone" group "keystone" mode "2700" end template "/etc/keystone/keystone.conf" do source "keystone/keystone.conf.erb" owner "keystone" group "keystone" mode "0600" variables( lazy { { :servers => get_head_nodes } } ) notifies :restart, "service[apache2]", :immediately end cookbook_file "/etc/keystone/keystone-paste.ini" do source "keystone/keystone-paste.ini" owner "keystone" group "keystone" mode "0600" notifies :restart, "service[apache2]", :immediately end node['bcpc']['keystone']['domains'].each do |domain, config| config_file = File.join domain_config_dir, "keystone.#{domain}.conf" template config_file do source "keystone/keystone.domain.conf.erb" owner "keystone" group "keystone" mode "0600" variables( :domain => config ) # should this be here..? notifies :restart, "service[apache2]", :delayed end end template "/etc/keystone/default_catalog.templates" do source "keystone-default_catalog.templates.erb" owner "keystone" group "keystone" mode "0644" notifies :restart, "service[apache2]", :delayed end template "/etc/keystone/cert.pem" do source "keystone-cert.pem.erb" owner "keystone" group "keystone" mode "0644" notifies :restart, "service[apache2]", :delayed end template "/etc/keystone/key.pem" do source "keystone-key.pem.erb" owner "keystone" group "keystone" mode "0600" notifies :restart, "service[apache2]", :delayed end template "/etc/keystone/policy.json" do source "keystone-policy.json.erb" owner "keystone" group "keystone" mode "0600" variables(:policy => JSON.pretty_generate(node['bcpc']['keystone']['policy'])) end template "/root/api_versionsrc" do source "api_versionsrc.erb" owner "root" group "root" mode "0600" end template "/root/keystonerc" do source "keystonerc.erb" owner "root" group "root" mode "0600" end # configure WSGI # /var/www created by apache2 package, /var/www/cgi-bin created in bcpc::apache2 #wsgi_keystone_dir = "/var/www/cgi-bin/keystone" #directory wsgi_keystone_dir do # action :create # owner "root" # group "root" # mode "0755" #end #%w{main admin}.each do |wsgi_link| # link ::File.join(wsgi_keystone_dir, wsgi_link) do # action :create # to "/usr/share/keystone/wsgi.py" # end #end template "/etc/apache2/sites-available/wsgi-keystone.conf" do source "keystone/apache-wsgi-keystone.conf.erb" owner "root" group "root" mode "0644" variables( :processes => node['bcpc']['keystone']['wsgi']['processes'], :threads => node['bcpc']['keystone']['wsgi']['threads'] ) notifies :restart, "service[apache2]", :immediately end bash "a2ensite-enable-wsgi-keystone" do user "root" code "a2ensite wsgi-keystone" not_if "test -r /etc/apache2/sites-enabled/wsgi-keystone.conf" notifies :restart, "service[apache2]", :immediately end ruby_block "keystone-database-creation" do block do %x[ export MYSQL_PWD=#{get_config('mysql-root-password')}; mysql -uroot -e "CREATE DATABASE #{node['bcpc']['dbname']['keystone']};" mysql -uroot -e "GRANT ALL ON #{node['bcpc']['dbname']['keystone']}.* TO '#{get_config('mysql-keystone-user')}'@'%' IDENTIFIED BY '#{get_config('mysql-keystone-password')}';" mysql -uroot -e "GRANT ALL ON #{node['bcpc']['dbname']['keystone']}.* TO '#{get_config('mysql-keystone-user')}'@'localhost' IDENTIFIED BY '#{get_config('mysql-keystone-password')}';" mysql -uroot -e "FLUSH PRIVILEGES;" ] self.notifies :run, "bash[keystone-database-sync]", :immediately self.resolve_notification_references end not_if { system "MYSQL_PWD=#{get_config('mysql-root-password')} mysql -uroot -e 'SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = \"#{node['bcpc']['dbname']['keystone']}\"'|grep \"#{node['bcpc']['dbname']['keystone']}\" >/dev/null" } end ruby_block 'update-keystone-db-schema' do block do self.notifies :run, "bash[keystone-database-sync]", :immediately self.resolve_notification_references end only_if { ::File.exist?('/usr/local/etc/openstack_upgrade') and not has_unregistered_migration? } end bash "keystone-database-sync" do action :nothing user "root" code "keystone-manage db_sync" notifies :restart, "service[apache2]", :immediately end ruby_block "keystone-region-creation" do block do %x[ export MYSQL_PWD=#{get_config('mysql-root-password')}; mysql -uroot -e "INSERT INTO keystone.region (id, extra) VALUES(\'#{node['bcpc']['region_name']}\', '{}');" ] end not_if { system "MYSQL_PWD=#{get_config('mysql-root-password')} mysql -uroot -e 'SELECT id FROM keystone.region WHERE id = \"#{node['bcpc']['region_name']}\"' | grep \"#{node['bcpc']['region_name']}\" >/dev/null" } end # this is a synchronization resource that polls Keystone on the VIP to verify that it's not returning 503s, # if something above has restarted Apache and Keystone isn't ready to play yet ruby_block "wait-for-keystone-to-become-operational" do delay = 1 retries = (node['bcpc']['keystone']['wait_for_keystone_timeout']/delay).ceil block do r = execute_in_keystone_admin_context("openstack region list -fvalue") raise Exception.new('Still waiting for keystone') if r.strip.empty? end retry_delay delay retries retries end # TODO(kamidzi): each service should create its *own* catalog entry # create services and endpoint catalog = node['bcpc']['catalog'].dup catalog.delete('network') unless node['bcpc']['enabled']['neutron'] catalog.each do |svc, svcprops| # attempt to delete endpoints that no longer match the environment # (keys off the service type, so it is possible to orphan endpoints if you remove an # entry from the environment service catalog) ruby_block "keystone-delete-outdated-#{svc}-endpoint" do block do svc_endpoints_raw = execute_in_keystone_admin_context('openstack endpoint list -f json') begin #puts svc_endpoints_raw svc_endpoints = JSON.parse(svc_endpoints_raw) #puts svc_endpoints svc_ids = svc_endpoints.select { |k| k['Service Type'] == svc }.collect { |v| v['ID'] } #puts svc_ids svc_ids.each do |svc_id| execute_in_keystone_admin_context("openstack endpoint delete #{svc_id} 2>&1") end rescue JSON::ParserError end end not_if { svc_endpoints_raw = execute_in_keystone_admin_context('openstack endpoint list -f json') begin svc_endpoints = JSON.parse(svc_endpoints_raw) next if svc_endpoints.empty? svcs = svc_endpoints.select { |k| k['Service Type'] == svc } next if svcs.empty? adminurl_raw = svcs.select { |v| v['URL'] if v['Interface'] == 'admin' } adminurl = adminurl_raw.empty? ? nil : adminurl_raw[0]['URL'] internalurl_raw = svcs.select { |v| v['URL'] if v['Interface'] == 'internal' } internalurl = internalurl_raw.empty? ? nil : internalurl_raw[0]['URL'] publicurl_raw = svcs.select { |v| v['URL'] if v['Interface'] == 'public' } publicurl = publicurl_raw.empty? ? nil : publicurl_raw[0]['URL'] adminurl_match = adminurl.nil? ? true : (adminurl == generate_service_catalog_uri(svcprops, 'admin')) internalurl_match = internalurl.nil? ? true : (internalurl == generate_service_catalog_uri(svcprops, 'internal')) publicurl_match = publicurl.nil? ? true : (publicurl == generate_service_catalog_uri(svcprops, 'public')) adminurl_match && internalurl_match && publicurl_match rescue JSON::ParserError false end } end # why no corresponding deletion for out of date services? # services don't get outdated in the way endpoints do (since endpoints encode version numbers and ports), # services just say that service X is present in the catalog, not how to access it ruby_block "keystone-create-#{svc}-service" do block do execute_in_keystone_admin_context("openstack service create --name '#{svcprops['name']}' --description '#{svcprops['description']}' #{svc}") end only_if { services_raw = execute_in_keystone_admin_context('openstack service list -f json') services = JSON.parse(services_raw) services.select { |s| s['Type'] == svc }.length.zero? } end # openstack command syntax changes between identity API v2 and v3, so calculate the endpoint creation command ahead of time identity_api_version = node['bcpc']['catalog']['identity']['uris']['public'].scan(/^[^\d]*(\d+)/)[0][0].to_i if identity_api_version == 3 endpoint_create_cmd = <<-EOH openstack endpoint create \ --region '#{node['bcpc']['region_name']}' #{svc} public "#{generate_service_catalog_uri(svcprops, 'public')}" ; openstack endpoint create \ --region '#{node['bcpc']['region_name']}' #{svc} internal "#{generate_service_catalog_uri(svcprops, 'internal')}" ; openstack endpoint create \ --region '#{node['bcpc']['region_name']}' #{svc} admin "#{generate_service_catalog_uri(svcprops, 'admin')}" ; EOH else endpoint_create_cmd = <<-EOH openstack endpoint create \ --region '#{node['bcpc']['region_name']}' \ --publicurl "#{generate_service_catalog_uri(svcprops, 'public')}" \ --adminurl "#{generate_service_catalog_uri(svcprops, 'admin')}" \ --internalurl "#{generate_service_catalog_uri(svcprops, 'internal')}" \ #{svc} EOH end ruby_block "keystone-create-#{svc}-endpoint" do block do execute_in_keystone_admin_context(endpoint_create_cmd) end only_if { endpoints_raw = execute_in_keystone_admin_context('openstack endpoint list -f json') endpoints = JSON.parse(endpoints_raw) endpoints.select { |e| e['Service Type'] == svc }.length.zero? } end end # Create domains, projects, and roles # NOTE(kamidzi): this is using legacy attribute. Maybe should change it? default_domain = node['bcpc']['keystone']['default_domain'] member_role_name = node['bcpc']['keystone']['member_role'] service_project_name = node['bcpc']['keystone']['service_project']['name'] service_project_domain = node['bcpc']['keystone']['service_project']['domain'] admin_project_name = node['bcpc']['keystone']['admin']['project_name'] admin_role_name = node['bcpc']['keystone']['admin_role'] admin_username = node['bcpc']['keystone']['admin']['username'] # NB(kamidzi): Make sure admin project is in same domain as service project! admin_project_domain = node['bcpc']['keystone']['admin']['project_domain'] admin_user_domain = node['bcpc']['keystone']['admin']['user_domain'] # For case... mostly migratory where ldap-backed domain already exists, sql-backed is added admin_config = { sql: { project_name: admin_project_name, project_domain: admin_project_domain, user_domain: admin_user_domain, user_name: admin_username }, ldap: { project_name: get_config('keystone-admin-project-name'), project_domain: get_config('keystone-admin-project-domain'), user_domain: get_config('keystone-admin-user-domain'), user_name: get_config('keystone-admin-user') } } # Create the domains ruby_block "keystone-create-domains" do block do node['bcpc']['keystone']['domains'].each do |domain, attrs| name = "keystone-create-domain::#{domain}" desc = attrs['description'] || '' run_context.resource_collection << dom_create = Chef::Resource::RubyBlock.new(name, run_context) dom_create.block { execute_in_keystone_admin_context("openstack domain create --description '#{desc}' #{domain}") } # TODO(kamidzi): if domain changes, guard will not detect dom_create.not_if { s = execute_in_keystone_admin_context("openstack domain show #{domain}"){|o,e,s| s} s.success? } # Configure them name = "keystone-configure-domain::#{domain}" # Use domain_config_upload for now run_context.resource_collection << dom_configure = Chef::Resource::RubyBlock.new(name, run_context) dom_configure.block { %x{ keystone-manage domain_config_upload --domain "#{domain}"} } # TODO(kamidzi): need a conditional... end end end ruby_block "keystone-create-admin-projects" do block do admin_config.each do |backend, config| name = "keystone-create-admin-project::#{config[:project_name]}" run_context.resource_collection << project_create = Chef::Resource::RubyBlock.new(name, run_context) project_create.block { execute_in_keystone_admin_context("openstack project create --domain #{config[:project_domain]} " + "--description 'Admin Project' #{config[:project_name]}") } project_create.not_if { cmd = "openstack project show --domain #{config[:project_domain]} " + "#{config[:project_name]}" s = execute_in_keystone_admin_context(cmd){|o,e,s| s} s.success? } end end end ruby_block "keystone-create-admin-user" do block do execute_in_keystone_admin_context("openstack user create --domain #{admin_project_domain} --password " + "#{get_config('keystone-local-admin-password')} #{admin_username}") end not_if { cmd = "openstack user show --domain #{admin_project_domain} #{admin_username}" s = execute_in_keystone_admin_context(cmd){|o,e,s| s} s.success? } end # FYI: https://blueprints.launchpad.net/keystone/+spec/domain-specific-roles ruby_block "keystone-create-admin-role" do block do execute_in_keystone_admin_context("openstack role create #{admin_role_name}") end not_if { s = execute_in_keystone_admin_context("openstack role show #{admin_role_name}"){|o,e,s| s} s.success? } end ruby_block "keystone-assign-admin-roles" do block do admin_config.each do |backend, config| name = "keystone-assign-admin-role::#{config[:user_domain]}::#{config[:user_name]}" a_cmd = "openstack role add" a_opts = [ "--user-domain #{config[:user_domain]}", "--user #{config[:user_name]}", "--project-domain #{config[:project_domain]}", "--project #{config[:project_name]}" ] a_args = [admin_role_name] g_cmd = "openstack role assignment list" g_opts = a_opts + [ "-fjson", "--role #{admin_role_name}", ] assign_cmd = ([a_cmd] + a_opts + a_args).join(' ') guard_cmd = ([g_cmd] + g_opts).join(' ') run_context.resource_collection << admin_assign = Chef::Resource::RubyBlock.new(name, run_context) admin_assign.block { execute_in_keystone_admin_context(assign_cmd) } admin_assign.only_if { begin r = JSON.parse execute_in_keystone_admin_context(guard_cmd) r.empty? rescue JSON::ParserError true end } end end end ruby_block "keystone-create-service-project" do block do execute_in_keystone_admin_context("openstack project create --domain #{service_project_domain} --description 'Service Project' #{service_project_name}") end not_if { cmd = "openstack project show --domain #{service_project_domain} #{service_project_name}" s = execute_in_keystone_admin_context(cmd){|o,e,s| s} s.success? } end ruby_block "keystone-create-member-role" do block do execute_in_keystone_admin_context("openstack role create #{member_role_name}") end not_if { s = execute_in_keystone_admin_context("openstack role show #{member_role_name}"){|o,e,s| s} s.success? } end # FIXME(kamidzi): this is another level of indirection because of preference to ldap # This is legacy credentials file template "/root/adminrc" do source "keystone/openrc.erb" owner "root" group "root" mode "0600" variables( lazy { { username: get_config('keystone-admin-user'), password: get_config('keystone-admin-password'), project_name: get_config('keystone-admin-project-name'), user_domain: get_config('keystone-admin-user-domain'), project_domain: get_config('keystone-admin-project-domain') } } ) end # This is a *domain* admin in separate domain along with service accounts template "/root/admin-openrc" do source "keystone/openrc.erb" owner "keystone" group "keystone" mode "0600" variables( lazy { { username: admin_username, password: get_config('keystone-local-admin-password'), project_name: admin_project_name, user_domain: admin_user_domain, project_domain: admin_project_domain } } ) end # # Cleanup actions # file "/var/lib/keystone/keystone.db" do action :delete end # Migration for user ids # This is necessary when existing admin user is a member of an ldap-backed domain # in single-domain deployment which then migrates to multi-domain deployment. Even # if domain name remains the same, the user is re-issued an id. This new id needs to # be permissioned cookbook_file "/usr/lib/python2.7/dist-packages/keystone/common/sql/migrate_repo/versions/098_migrate_single_to_multi_domain_user_ids.py" do source "keystone/098_migrate_single_to_multi_domain_user_ids.py" owner "root" group "root" mode "0644" end # User records need to be accessed to populate database with new, stable public IDs ruby_block "keystone-list-admin-domain-users" do block do execute_in_keystone_admin_context("openstack user list --domain #{get_config('keystone-admin-user-domain')}") end notifies :run, "bash[keystone-database-sync]", :immediately not_if { %x[bash -c '. /root/adminrc && openstack token issue'] ; $?.success? and keystone_db_version == '98' } end
# # Cookbook Name:: dmon # Recipe:: frontend # # Copyright (c) 2016 Bogdan-Constantin Irimie, All Rights Reserved. # Install the required packages package "mos-oracle-java-jdk-8" package "mos-mongodb-org" package "mos-rabbitmq-server" # Download remote archive. remote_file node['dmon']['frontend']['archive_path'] do source "#{node['dmon']['frontend']['remote_location']}" owner 'root' group 'root' mode '0755' action :create # not_if {::File.exists?("~/specs_monitoring_nmap_frontend.tar.gz") } end # Extract the archive. execute 'extract_frontend' do command "tar -xvzf #{node['dmon']['frontend']['archive_path']}" cwd "#{node['dmon']['frontend']['deployment_directory']}" end # Remove the archive. file node['dmon']['frontend']['archive_path'] do action :delete end # Create specs_monitoring_nmap_frontend/etc directory if it does not exit. directory node['dmon']['frontend']['etc_directory'] do action :create not_if {::File.exists?("#{node['dmon']['frontend']['etc_directory']}")} end # Create config file. template node['dmon']['frontend']['conf_file'] do action :create source 'frontend.conf.properties.erb' end Start RabbitMQ server and create new user. # # Cookbook Name:: dmon # Recipe:: frontend # # Copyright (c) 2016 Bogdan-Constantin Irimie, All Rights Reserved. # Install the required packages package "mos-oracle-java-jdk-8" package "mos-mongodb-org" package "mos-rabbitmq-server" #Start RabbitMQ server service "mos-rabbitmq-server_start" do not_if do ::File.exists?("/var/run/rabbitmq/pid") end provider Chef::Provider::Service::Systemd service_name "rabbitmq-server" action :start end #Create RabbitMQ user. bash 'create_rabbitmq_user' do user "root" code <<-EOH rabbitmqctl add_user bogdan constantin rabbitmqctl set_user_tags bogdan administrator rabbitmqctl set_permissions -p / bogdan ".*" ".*" ".*" EOH end # Download remote archive. remote_file node['dmon']['frontend']['archive_path'] do source "#{node['dmon']['frontend']['remote_location']}" owner 'root' group 'root' mode '0755' action :create # not_if {::File.exists?("~/specs_monitoring_nmap_frontend.tar.gz") } end # Extract the archive. execute 'extract_frontend' do command "tar -xvzf #{node['dmon']['frontend']['archive_path']}" cwd "#{node['dmon']['frontend']['deployment_directory']}" end # Remove the archive. file node['dmon']['frontend']['archive_path'] do action :delete end # Create specs_monitoring_nmap_frontend/etc directory if it does not exit. directory node['dmon']['frontend']['etc_directory'] do action :create not_if {::File.exists?("#{node['dmon']['frontend']['etc_directory']}")} end # Create config file. template node['dmon']['frontend']['conf_file'] do action :create source 'frontend.conf.properties.erb' end
cask '1password' cask 'alfred' cask 'appcleaner' cask 'bartender' cask 'docker' cask 'firefox' cask 'gitify' cask 'gitter' cask 'google-cloud-sdk' cask 'gyazo' cask 'iterm2' cask 'minikube' cask 'postman' cask 'quitter' cask 'skype' cask 'slack' cask 'vimr' Add notion app cask '1password' cask 'alfred' cask 'appcleaner' cask 'bartender' cask 'docker' cask 'firefox' cask 'gitify' cask 'gitter' cask 'google-cloud-sdk' cask 'gyazo' cask 'iterm2' cask 'minikube' cask 'notion' cask 'postman' cask 'quitter' cask 'skype' cask 'slack' cask 'vimr'
package "monit" if platform?("ubuntu") cookbook_file "/etc/default/monit" do source "monit.default" owner "root" group "root" mode 0644 end end service "monit" do # action [:enable, :start] # enabled true supports [:start, :restart, :stop] end directory "/etc/monit/conf.d/" do owner 'root' group 'root' mode 0755 action :create recursive true end directory "/var/monit" do owner 'root' group 'root' mode 0750 action :create recursive true end template "/etc/monit/monitrc" do owner "root" group "root" mode 0700 source 'monitrc.erb' end file "/etc/monit.conf" do action :delete end template "/etc/monit.conf" do owner "root" group "root" mode 0700 source 'monit.conf.erb' notifies :restart, "service[monit]" end OK delay that shit package "monit" if platform?("ubuntu") cookbook_file "/etc/default/monit" do source "monit.default" owner "root" group "root" mode 0644 end end service "monit" do # action [:enable, :start] # enabled true supports [:start, :restart, :stop] end directory "/etc/monit/conf.d/" do owner 'root' group 'root' mode 0755 action :create recursive true end directory "/var/monit" do owner 'root' group 'root' mode 0750 action :create recursive true end file "/etc/monit.conf" do action :delete end template "/etc/monit/monitrc" do owner "root" group "root" mode 0700 source 'monitrc.erb' notifies :restart, "service[monit]", :delayed end template "/etc/monit.conf" do owner "root" group "root" mode 0700 source 'monit.conf.erb' notifies :restart, "service[monit]", :delayed end
# # Cookbook Name:: nginx # Recipe:: default # # Copyright 2016, YOUR_COMPANY_NAME # # All rights reserved - Do Not Redistribute # include_recipe "apt" package 'nginx' do action :install end service 'nginx' do action [ :enable, :start ] end cookbook_file "/usr/share/nginx/www/index.html" do source "index.html" mode "0644" end ngnix configure with port 80 # # Cookbook Name:: nginx # Recipe:: default # # Copyright 2016, YOUR_COMPANY_NAME # # All rights reserved - Do Not Redistribute # include_recipe "apt" package 'nginx' do action :install end service 'nginx' do action [ :enable, :start ] end cookbook_file "/usr/share/nginx/www/index.html" do source "index.html" mode "0644" end # open port 80 bash "allowing nginx traffic through firewall" do user "root" code "ufw allow 80 && ufw allow 443" end execute "restart-nginx" do command "/etc/init.d/nginx restart" action :nothing end
# # Cookbook Name:: squid # Recipe:: default # # Copyright 2011, OpenStreetMap Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # if node[:squid][:version] == "3" apt_package "squid" do action :unlock end apt_package "squid-common" do action :unlock end apt_package "squid" do action :purge only_if "dpkg-query -W squid | fgrep -q 2." end apt_package "squid-common" do action :purge only_if "dpkg-query -W squid-common | fgrep -q 2." end file "/store/squid/coss-01" do action :delete backup false end package "squidclient" do action :upgrade end end package "squid" package "squidclient" template "/etc/squid/squid.conf" do source "squid.conf.erb" owner "root" group "root" mode 0o644 end directory "/etc/squid/squid.conf.d" do owner "root" group "root" mode 0o755 end if node[:squid][:cache_dir] =~ /^coss (\S+) / cache_dir = File.dirname(Regexp.last_match(1)) elsif node[:squid][:cache_dir] =~ /^\S+ (\S+) / cache_dir = Regexp.last_match(1) end directory cache_dir do owner "proxy" group "proxy" mode 0o750 recursive true end systemd_tmpfile "/var/run/squid" do type "d" owner "proxy" group "proxy" mode "0755" end systemd_service "squid" do description "Squid caching proxy" after ["network.target", "nss-lookup.target"] type "forking" limit_nofile 98304 exec_start_pre "/usr/sbin/squid -N -z" exec_start "/usr/sbin/squid -Y" exec_reload "/usr/sbin/squid -k reconfigure" exec_stop "/usr/sbin/squid -k shutdown" private_tmp true private_devices true protect_system "full" protect_home true restart "on-failure" timeout_sec 0 end service "squid" do action [:enable, :start] subscribes :restart, "systemd_service[squid]" subscribes :restart, "directory[#{cache_dir}]" subscribes :reload, "template[/etc/squid/squid.conf]" subscribes :reload, "template[/etc/resolv.conf]" end log "squid-restart" do message "Restarting squid due to counter wraparound" notifies :restart, "service[squid]" only_if do IO.popen(["squidclient", "--host=127.0.0.1", "--port=80", "mgr:counters"]) do |io| io.each.grep(/^[a-z][a-z_.]+ = -[0-9]+$/).count.positive? end end end munin_plugin "squid_cache" munin_plugin "squid_times" munin_plugin "squid_icp" munin_plugin "squid_objectsize" munin_plugin "squid_requests" munin_plugin "squid_traffic" munin_plugin "squid_delay_pools" do action :delete end munin_plugin "squid_delay_pools_noreferer" do action :delete end Allow multiple squid cache dirs to be specified # # Cookbook Name:: squid # Recipe:: default # # Copyright 2011, OpenStreetMap Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # if node[:squid][:version] == "3" apt_package "squid" do action :unlock end apt_package "squid-common" do action :unlock end apt_package "squid" do action :purge only_if "dpkg-query -W squid | fgrep -q 2." end apt_package "squid-common" do action :purge only_if "dpkg-query -W squid-common | fgrep -q 2." end file "/store/squid/coss-01" do action :delete backup false end package "squidclient" do action :upgrade end end package "squid" package "squidclient" template "/etc/squid/squid.conf" do source "squid.conf.erb" owner "root" group "root" mode 0o644 end directory "/etc/squid/squid.conf.d" do owner "root" group "root" mode 0o755 end Array(node[:squid][:cache_dir]).each do |cache_dir| if cache_dir =~ /^coss (\S+) / cache_dir = File.dirname(Regexp.last_match(1)) elsif cache_dir =~ /^\S+ (\S+) / cache_dir = Regexp.last_match(1) end directory cache_dir do owner "proxy" group "proxy" mode 0o750 recursive true notifies :restart, "service[squid]" end end systemd_tmpfile "/var/run/squid" do type "d" owner "proxy" group "proxy" mode "0755" end systemd_service "squid" do description "Squid caching proxy" after ["network.target", "nss-lookup.target"] type "forking" limit_nofile 98304 exec_start_pre "/usr/sbin/squid -N -z" exec_start "/usr/sbin/squid -Y" exec_reload "/usr/sbin/squid -k reconfigure" exec_stop "/usr/sbin/squid -k shutdown" private_tmp true private_devices true protect_system "full" protect_home true restart "on-failure" timeout_sec 0 end service "squid" do action [:enable, :start] subscribes :restart, "systemd_service[squid]" subscribes :reload, "template[/etc/squid/squid.conf]" subscribes :reload, "template[/etc/resolv.conf]" end log "squid-restart" do message "Restarting squid due to counter wraparound" notifies :restart, "service[squid]" only_if do IO.popen(["squidclient", "--host=127.0.0.1", "--port=80", "mgr:counters"]) do |io| io.each.grep(/^[a-z][a-z_.]+ = -[0-9]+$/).count.positive? end end end munin_plugin "squid_cache" munin_plugin "squid_times" munin_plugin "squid_icp" munin_plugin "squid_objectsize" munin_plugin "squid_requests" munin_plugin "squid_traffic" munin_plugin "squid_delay_pools" do action :delete end munin_plugin "squid_delay_pools_noreferer" do action :delete end
# :markup: markdown require 'http/cookie' ## # This class is used to manage the Cookies that have been returned from # any particular website. class HTTP::CookieJar require 'http/cookie_jar/abstract_store' require 'http/cookie_jar/abstract_saver' attr_reader :store # Generates a new cookie jar. # # Available option keywords are as below: # # :store # : The store class that backs this jar. (default: `:hash`) # A symbol or an instance of a store class is accepted. Symbols are # mapped to store classes, like `:hash` to # `HTTP::CookieJar::HashStore` and `:mozilla` to # `HTTP::CookieJar::MozillaStore`. # # Any options given are passed through to the initializer of the # specified store class. For example, the `:mozilla` # (`HTTP::CookieJar::MozillaStore`) store class requires a # `:filename` option. See individual store classes for details. def initialize(options = nil) opthash = { :store => :hash, } opthash.update(options) if options case store = opthash[:store] when Symbol @store = AbstractStore.implementation(store).new(opthash) when AbstractStore @store = store else raise TypeError, 'wrong object given as cookie store: %s' % store.inspect end end def initialize_copy(other) @store = other.instance_eval { @store.dup } end # Adds a cookie to the jar and return self. If a given cookie has # no domain or path attribute values and the origin is unknown, # ArgumentError is raised. # # ### Compatibility Note for Mechanize::Cookie users # # In HTTP::Cookie, each cookie object can store its origin URI # (cf. #origin). While the origin URI of a cookie can be set # manually by #origin=, one is typically given in its generation. # To be more specific, HTTP::Cookie.new and HTTP::Cookie.parse both # take an :origin option. # # `HTTP::Cookie.parse`. Compare these: # # # Mechanize::Cookie # jar.add(origin, cookie) # jar.add!(cookie) # no acceptance check is performed # # # HTTP::Cookie # jar.origin = origin # if it doesn't have one # jar.add(cookie) # acceptance check is performed def add(cookie) if cookie.domain.nil? || cookie.path.nil? raise ArgumentError, "a cookie with unknown domain or path cannot be added" end @store.add(cookie) self end alias << add # Gets an array of cookies that should be sent for the URL/URI. def cookies(url) now = Time.now each(url).select { |cookie| !cookie.expired? && (cookie.accessed_at = now) }.sort end # Tests if the jar is empty. If `url` is given, tests if there is # no cookie for the URL. def empty?(url = nil) if url each(url) { return false } return true else @store.empty? end end # Iterates over all cookies that are not expired. # # An optional argument `uri` specifies a URI/URL indicating the # destination of the cookies being selected. Every cookie yielded # should be good to send to the given URI, # i.e. cookie.valid_for_uri?(uri) evaluates to true. # # If (and only if) the `uri` option is given, last access time of # each cookie is updated to the current time. def each(uri = nil, &block) block_given? or return enum_for(__method__, uri) if uri uri = URI(uri) return self unless URI::HTTP === uri && uri.host end @store.each(uri, &block) self end include Enumerable # call-seq: # jar.save(filename_or_io, **options) # jar.save(filename_or_io, format = :yaml, **options) # # Saves the cookie jar into a file or an IO in the format specified # and return self. If a given object responds to #write it is taken # as an IO, or taken as a filename otherwise. # # Available option keywords are below: # # * `:format` # <dl class="rdoc-list note-list"> # <dt>:yaml</dt> # <dd>YAML structure (default)</dd> # <dt>:cookiestxt</dt> # <dd>: Mozilla's cookies.txt format</dd> # </dl> # # * `:session` # <dl class="rdoc-list note-list"> # <dt>true</dt> # <dd>Save session cookies as well.</dd> # <dt>false</dt> # <dd>Do not save session cookies. (default)</dd> # </dl> # # All options given are passed through to the underlying cookie # saver module. def save(writable, *options) opthash = { :format => :yaml, :session => false, } case options.size when 0 when 1 case options = options.first when Symbol opthash[:format] = options else opthash.update(options) if options end when 2 opthash[:format], options = options opthash.update(options) if options else raise ArgumentError, 'wrong number of arguments (%d for 1-3)' % (1 + options.size) end begin saver = AbstractSaver.implementation(opthash[:format]).new(opthash) rescue IndexError => e raise ArgumentError, e.message end if writable.respond_to?(:write) saver.save(writable, self) else File.open(writable, 'w') { |io| saver.save(io, self) } end self end # call-seq: # jar.load(filename_or_io, **options) # jar.load(filename_or_io, format = :yaml, **options) # # Loads cookies recorded in a file or an IO in the format specified # into the jar and return self. If a given object responds to #read # it is taken as an IO, or taken as a filename otherwise. # # Available option keywords are below: # # * `:format` # <dl class="rdoc-list note-list"> # <dt>:yaml</dt> # <dd>YAML structure (default)</dd> # <dt>:cookiestxt</dt> # <dd>: Mozilla's cookies.txt format</dd> # </dl> # # All options given are passed through to the underlying cookie # saver module. def load(readable, *options) opthash = { :format => :yaml, :session => false, } case options.size when 0 when 1 case options = options.first when Symbol opthash[:format] = options else opthash.update(options) if options end when 2 opthash[:format], options = options opthash.update(options) if options else raise ArgumentError, 'wrong number of arguments (%d for 1-3)' % (1 + options.size) end begin saver = AbstractSaver.implementation(opthash[:format]).new(opthash) rescue IndexError => e raise ArgumentError, e.message end if readable.respond_to?(:write) saver.load(readable, self) else File.open(readable, 'r') { |io| saver.load(io, self) } end self end # Clears the cookie jar and return self. def clear @store.clear self end # Removes expired cookies and return self. def cleanup(session = false) @store.cleanup session self end end Add a utility shorthand method HTTP::CookieJar#parse. # :markup: markdown require 'http/cookie' ## # This class is used to manage the Cookies that have been returned from # any particular website. class HTTP::CookieJar require 'http/cookie_jar/abstract_store' require 'http/cookie_jar/abstract_saver' attr_reader :store # Generates a new cookie jar. # # Available option keywords are as below: # # :store # : The store class that backs this jar. (default: `:hash`) # A symbol or an instance of a store class is accepted. Symbols are # mapped to store classes, like `:hash` to # `HTTP::CookieJar::HashStore` and `:mozilla` to # `HTTP::CookieJar::MozillaStore`. # # Any options given are passed through to the initializer of the # specified store class. For example, the `:mozilla` # (`HTTP::CookieJar::MozillaStore`) store class requires a # `:filename` option. See individual store classes for details. def initialize(options = nil) opthash = { :store => :hash, } opthash.update(options) if options case store = opthash[:store] when Symbol @store = AbstractStore.implementation(store).new(opthash) when AbstractStore @store = store else raise TypeError, 'wrong object given as cookie store: %s' % store.inspect end end def initialize_copy(other) @store = other.instance_eval { @store.dup } end # Adds a cookie to the jar and return self. If a given cookie has # no domain or path attribute values and the origin is unknown, # ArgumentError is raised. # # ### Compatibility Note for Mechanize::Cookie users # # In HTTP::Cookie, each cookie object can store its origin URI # (cf. #origin). While the origin URI of a cookie can be set # manually by #origin=, one is typically given in its generation. # To be more specific, HTTP::Cookie.new and HTTP::Cookie.parse both # take an :origin option. # # `HTTP::Cookie.parse`. Compare these: # # # Mechanize::Cookie # jar.add(origin, cookie) # jar.add!(cookie) # no acceptance check is performed # # # HTTP::Cookie # jar.origin = origin # if it doesn't have one # jar.add(cookie) # acceptance check is performed def add(cookie) if cookie.domain.nil? || cookie.path.nil? raise ArgumentError, "a cookie with unknown domain or path cannot be added" end @store.add(cookie) self end alias << add # Gets an array of cookies that should be sent for the URL/URI. def cookies(url) now = Time.now each(url).select { |cookie| !cookie.expired? && (cookie.accessed_at = now) }.sort end # Tests if the jar is empty. If `url` is given, tests if there is # no cookie for the URL. def empty?(url = nil) if url each(url) { return false } return true else @store.empty? end end # Iterates over all cookies that are not expired. # # An optional argument `uri` specifies a URI/URL indicating the # destination of the cookies being selected. Every cookie yielded # should be good to send to the given URI, # i.e. cookie.valid_for_uri?(uri) evaluates to true. # # If (and only if) the `uri` option is given, last access time of # each cookie is updated to the current time. def each(uri = nil, &block) block_given? or return enum_for(__method__, uri) if uri uri = URI(uri) return self unless URI::HTTP === uri && uri.host end @store.each(uri, &block) self end include Enumerable # Parses a Set-Cookie field value `set_cookie` sent from a URI # `origin` and adds the cookies parsed as valid to the jar. Returns # an array of cookies that have been added. If a block is given, it # is called after each cookie is added. # # `jar.parse(set_cookie, origin)` is a shorthand for this: # # HTTP::Cookie.parse(set_cookie, origin) { |cookie| # jar.add(cookie) # } # # See HTTP::Cookie.parse for available options. def parse(set_cookie, origin, options = nil) # :yield: cookie if block_given? HTTP::Cookie.parse(set_cookie, origin, options) { |cookie| add(cookie) yield cookie } else HTTP::Cookie.parse(set_cookie, origin, options, &method(:add)) end end # call-seq: # jar.save(filename_or_io, **options) # jar.save(filename_or_io, format = :yaml, **options) # # Saves the cookie jar into a file or an IO in the format specified # and return self. If a given object responds to #write it is taken # as an IO, or taken as a filename otherwise. # # Available option keywords are below: # # * `:format` # <dl class="rdoc-list note-list"> # <dt>:yaml</dt> # <dd>YAML structure (default)</dd> # <dt>:cookiestxt</dt> # <dd>: Mozilla's cookies.txt format</dd> # </dl> # # * `:session` # <dl class="rdoc-list note-list"> # <dt>true</dt> # <dd>Save session cookies as well.</dd> # <dt>false</dt> # <dd>Do not save session cookies. (default)</dd> # </dl> # # All options given are passed through to the underlying cookie # saver module. def save(writable, *options) opthash = { :format => :yaml, :session => false, } case options.size when 0 when 1 case options = options.first when Symbol opthash[:format] = options else opthash.update(options) if options end when 2 opthash[:format], options = options opthash.update(options) if options else raise ArgumentError, 'wrong number of arguments (%d for 1-3)' % (1 + options.size) end begin saver = AbstractSaver.implementation(opthash[:format]).new(opthash) rescue IndexError => e raise ArgumentError, e.message end if writable.respond_to?(:write) saver.save(writable, self) else File.open(writable, 'w') { |io| saver.save(io, self) } end self end # call-seq: # jar.load(filename_or_io, **options) # jar.load(filename_or_io, format = :yaml, **options) # # Loads cookies recorded in a file or an IO in the format specified # into the jar and return self. If a given object responds to #read # it is taken as an IO, or taken as a filename otherwise. # # Available option keywords are below: # # * `:format` # <dl class="rdoc-list note-list"> # <dt>:yaml</dt> # <dd>YAML structure (default)</dd> # <dt>:cookiestxt</dt> # <dd>: Mozilla's cookies.txt format</dd> # </dl> # # All options given are passed through to the underlying cookie # saver module. def load(readable, *options) opthash = { :format => :yaml, :session => false, } case options.size when 0 when 1 case options = options.first when Symbol opthash[:format] = options else opthash.update(options) if options end when 2 opthash[:format], options = options opthash.update(options) if options else raise ArgumentError, 'wrong number of arguments (%d for 1-3)' % (1 + options.size) end begin saver = AbstractSaver.implementation(opthash[:format]).new(opthash) rescue IndexError => e raise ArgumentError, e.message end if readable.respond_to?(:write) saver.load(readable, self) else File.open(readable, 'r') { |io| saver.load(io, self) } end self end # Clears the cookie jar and return self. def clear @store.clear self end # Removes expired cookies and return self. def cleanup(session = false) @store.cleanup session self end end
module Humdrum # http://semver.org/ VERSION = "0.0.5" end version 0.0.6 release module Humdrum # http://semver.org/ VERSION = "0.0.6" end
module BrowserHelper # Makes use of the browser gem: # https://github.com/fnando/browser def browser_supported? return true if browser_preferred? browser.safari? end def browser_preferred? browser.chrome? or browser.firefox? end end Added Opera to semi-supported browsers module BrowserHelper # Makes use of the browser gem: # https://github.com/fnando/browser def browser_supported? return true if browser_preferred? browser.safari? or browser.opera? end def browser_preferred? browser.chrome? or browser.firefox? end end
require File.expand_path('../../../spec_helper', __FILE__) require File.expand_path('../fixtures/classes', __FILE__) require File.expand_path('../../../fixtures/reflection', __FILE__) # TODO: rewrite describe "Kernel#public_methods" do ruby_version_is ""..."1.9" do it "returns a list of the names of publicly accessible methods in the object" do KernelSpecs::Methods.public_methods(false).sort.should include("allocate", "hachi", "ichi", "juu", "juu_ni", "new", "roku", "san", "shi", "superclass") KernelSpecs::Methods.new.public_methods(false).sort.should include("juu_san", "ni") end it "returns a list of names without protected accessible methods in the object" do KernelSpecs::Methods.public_methods(false).sort.should_not include("juu_ichi") KernelSpecs::Methods.new.public_methods(false).sort.should_not include("ku") end it "returns a list of the names of publicly accessible methods in the object and its ancestors and mixed-in modules" do (KernelSpecs::Methods.public_methods(false) & KernelSpecs::Methods.public_methods).sort.should include( "allocate", "hachi", "ichi", "juu", "juu_ni", "new", "roku", "san", "shi", "superclass") m = KernelSpecs::Methods.new.public_methods m.should include('ni', 'juu_san') end it "returns public methods mixed in to the metaclass" do m = KernelSpecs::Methods.new m.extend(KernelSpecs::Methods::MetaclassMethods) m.public_methods.should include('peekaboo') end end ruby_version_is "1.9" do it "returns a list of the names of publicly accessible methods in the object" do KernelSpecs::Methods.public_methods(false).sort.should include(:hachi, :ichi, :juu, :juu_ni, :roku, :san, :shi) KernelSpecs::Methods.new.public_methods(false).sort.should include(:juu_san, :ni) end it "returns a list of names without protected accessible methods in the object" do KernelSpecs::Methods.public_methods(false).sort.should_not include(:juu_ichi) KernelSpecs::Methods.new.public_methods(false).sort.should_not include(:ku) end it "returns a list of the names of publicly accessible methods in the object and its ancestors and mixed-in modules" do (KernelSpecs::Methods.public_methods(false) & KernelSpecs::Methods.public_methods).sort.should include( :hachi, :ichi, :juu, :juu_ni, :roku, :san, :shi) m = KernelSpecs::Methods.new.public_methods m.should include(:ni, :juu_san) end it "returns methods mixed in to the metaclass" do m = KernelSpecs::Methods.new m.extend(KernelSpecs::Methods::MetaclassMethods) m.public_methods.should include(:peekaboo) end end end describe :kernel_public_methods_supers, :shared => true do it "returns a unique list for an object extended by a module" do m = ReflectSpecs.oed.public_methods(*@object) m.select { |x| x == stasy(:pub) }.sort.should == [stasy(:pub)] end it "returns a unique list for a class including a module" do m = ReflectSpecs::D.new.public_methods(*@object) m.select { |x| x == stasy(:pub) }.sort.should == [stasy(:pub)] end it "returns a unique list for a subclass of a class that includes a module" do m = ReflectSpecs::E.new.public_methods(*@object) m.select { |x| x == stasy(:pub) }.sort.should == [stasy(:pub)] end end describe "Kernel#public_methods" do describe "when not passed an argument" do it_behaves_like :kernel_public_methods_supers, nil, [] end describe "when passed true" do it_behaves_like :kernel_public_methods_supers, nil, true end end Add failing spec for Fixnum#public_methods require File.expand_path('../../../spec_helper', __FILE__) require File.expand_path('../fixtures/classes', __FILE__) require File.expand_path('../../../fixtures/reflection', __FILE__) # TODO: rewrite describe "Kernel#public_methods" do ruby_version_is ""..."1.9" do it "returns a list of the names of publicly accessible methods in the object" do KernelSpecs::Methods.public_methods(false).sort.should include("allocate", "hachi", "ichi", "juu", "juu_ni", "new", "roku", "san", "shi", "superclass") KernelSpecs::Methods.new.public_methods(false).sort.should include("juu_san", "ni") end it "returns a list of names without protected accessible methods in the object" do KernelSpecs::Methods.public_methods(false).sort.should_not include("juu_ichi") KernelSpecs::Methods.new.public_methods(false).sort.should_not include("ku") end it "returns a list of the names of publicly accessible methods in the object and its ancestors and mixed-in modules" do (KernelSpecs::Methods.public_methods(false) & KernelSpecs::Methods.public_methods).sort.should include( "allocate", "hachi", "ichi", "juu", "juu_ni", "new", "roku", "san", "shi", "superclass") m = KernelSpecs::Methods.new.public_methods m.should include('ni', 'juu_san') end it "returns public methods mixed in to the metaclass" do m = KernelSpecs::Methods.new m.extend(KernelSpecs::Methods::MetaclassMethods) m.public_methods.should include('peekaboo') end it "returns public methods for immediates" do 10.public_methods.should include('divmod') end end ruby_version_is "1.9" do it "returns a list of the names of publicly accessible methods in the object" do KernelSpecs::Methods.public_methods(false).sort.should include(:hachi, :ichi, :juu, :juu_ni, :roku, :san, :shi) KernelSpecs::Methods.new.public_methods(false).sort.should include(:juu_san, :ni) end it "returns a list of names without protected accessible methods in the object" do KernelSpecs::Methods.public_methods(false).sort.should_not include(:juu_ichi) KernelSpecs::Methods.new.public_methods(false).sort.should_not include(:ku) end it "returns a list of the names of publicly accessible methods in the object and its ancestors and mixed-in modules" do (KernelSpecs::Methods.public_methods(false) & KernelSpecs::Methods.public_methods).sort.should include( :hachi, :ichi, :juu, :juu_ni, :roku, :san, :shi) m = KernelSpecs::Methods.new.public_methods m.should include(:ni, :juu_san) end it "returns methods mixed in to the metaclass" do m = KernelSpecs::Methods.new m.extend(KernelSpecs::Methods::MetaclassMethods) m.public_methods.should include(:peekaboo) end it "returns public methods for immediates" do 10.public_methods.should include(:divmod) end end end describe :kernel_public_methods_supers, :shared => true do it "returns a unique list for an object extended by a module" do m = ReflectSpecs.oed.public_methods(*@object) m.select { |x| x == stasy(:pub) }.sort.should == [stasy(:pub)] end it "returns a unique list for a class including a module" do m = ReflectSpecs::D.new.public_methods(*@object) m.select { |x| x == stasy(:pub) }.sort.should == [stasy(:pub)] end it "returns a unique list for a subclass of a class that includes a module" do m = ReflectSpecs::E.new.public_methods(*@object) m.select { |x| x == stasy(:pub) }.sort.should == [stasy(:pub)] end end describe "Kernel#public_methods" do describe "when not passed an argument" do it_behaves_like :kernel_public_methods_supers, nil, [] end describe "when passed true" do it_behaves_like :kernel_public_methods_supers, nil, true end end
require_relative 'sse_client' Plugin.create(:mastodon) do pm = Plugin::Mastodon # ストリーム開始&直近取得イベント defevent :mastodon_start_stream, prototype: [String, String, String, pm::World, Integer] def datasource_used?(slug, include_all = false) return false if UserConfig[:extract_tabs].nil? UserConfig[:extract_tabs].any? do |setting| setting[:sources].any? do |ds| ds == slug || include_all && ds == :mastodon_appear_toots end end end on_mastodon_start_stream do |domain, type, slug, world, list_id| next if !UserConfig[:mastodon_enable_streaming] Thread.new { sleep(rand(10)) token = nil if world.is_a? pm::World token = world.access_token end base_url = 'https://' + domain + '/api/v1/streaming/' params = {} case type when 'user' uri = Diva::URI.new(base_url + 'user') when 'public' uri = Diva::URI.new(base_url + 'public') when 'public:media' uri = Diva::URI.new(base_url + 'public') params[:only_media] = true when 'public:local' uri = Diva::URI.new(base_url + 'public/local') when 'public:local:media' uri = Diva::URI.new(base_url + 'public/local') params[:only_media] = true when 'list' uri = Diva::URI.new(base_url + 'list') params[:list] = list_id when 'direct' uri = Diva::URI.new(base_url + 'direct') end headers = {} if token headers["Authorization"] = "Bearer " + token end Plugin.call(:sse_create, slug, :get, uri, headers, params, domain: domain, type: type, token: token) } end on_mastodon_stop_stream do |slug| Plugin.call(:sse_kill_connection, slug) end # mikutterにとって自明に60秒以上過去となる任意の日時 @last_all_restarted = Time.new(2007, 8, 31, 0, 0, 0, "+09:00") @waiting = false restarter = Proc.new do if @waiting Plugin.call(:sse_kill_all, :mastodon_start_all_streams) atomic { @last_all_restarted = Time.new @waiting = false } end atomic { @waiting = false } Reserver.new(60, &restarter) end on_mastodon_restart_all_streams do now = Time.new atomic { @waiting = true } if (now - @last_all_restarted) >= 60 restarter.call end end on_mastodon_start_all_streams do worlds, = Plugin.filtering(:mastodon_worlds, nil) worlds.each do |world| Thread.new { world.update_mutes! Plugin.call(:mastodon_init_auth_stream, world) } end UserConfig[:mastodon_instances].map do |domain, setting| Plugin.call(:mastodon_init_instance_stream, domain) end end # サーバーを必要に応じて再起動 on_mastodon_restart_instance_stream do |domain, retrieve = true| Thread.new { instance = pm::Instance.load(domain) if instance.retrieve != retrieve instance.retrieve = retrieve instance.store end Plugin.call(:mastodon_remove_instance_stream, domain) if retrieve Plugin.call(:mastodon_init_instance_stream, domain) end } end on_mastodon_init_instance_stream do |domain| Thread.new { instance = pm::Instance.load(domain) pm::Instance.add_datasources(domain) ftl_slug = pm::Instance.datasource_slug(domain, :federated) ftl_media_slug = pm::Instance.datasource_slug(domain, :federated_media) ltl_slug = pm::Instance.datasource_slug(domain, :local) ltl_media_slug = pm::Instance.datasource_slug(domain, :local_media) # ストリーム開始 Plugin.call(:mastodon_start_stream, domain, 'public', ftl_slug) if datasource_used?(ftl_slug, true) Plugin.call(:mastodon_start_stream, domain, 'public:media', ftl_media_slug) if datasource_used?(ftl_media_slug) Plugin.call(:mastodon_start_stream, domain, 'public:local', ltl_slug) if datasource_used?(ltl_slug) Plugin.call(:mastodon_start_stream, domain, 'public:local:media', ltl_media_slug) if datasource_used?(ltl_media_slug) } end on_mastodon_remove_instance_stream do |domain| Plugin.call(:mastodon_stop_stream, pm::Instance.datasource_slug(domain, :federated)) Plugin.call(:mastodon_stop_stream, pm::Instance.datasource_slug(domain, :local)) pm::Instance.remove_datasources(domain) end on_mastodon_init_auth_stream do |world| Thread.new { lists = world.get_lists! filter_extract_datasources do |dss| instance = pm::Instance.load(world.domain) datasources = { world.datasource_slug(:home) => "Mastodonホームタイムライン(Mastodon)/#{world.account.acct}", world.datasource_slug(:direct) => "Mastodon DM(Mastodon)/#{world.account.acct}", } lists.to_a.each do |l| slug = world.datasource_slug(:list, l[:id]) datasources[slug] = "Mastodonリスト(Mastodon)/#{world.account.acct}/#{l[:title]}" end [datasources.merge(dss)] end # ストリーム開始 if datasource_used?(world.datasource_slug(:home), true) Plugin.call(:mastodon_start_stream, world.domain, 'user', world.datasource_slug(:home), world) end if datasource_used?(world.datasource_slug(:direct), true) Plugin.call(:mastodon_start_stream, world.domain, 'direct', world.datasource_slug(:direct), world) end lists.to_a.each do |l| id = l[:id].to_i slug = world.datasource_slug(:list, id) if datasource_used?(world.datasource_slug(:list, id)) Plugin.call(:mastodon_start_stream, world.domain, 'list', world.datasource_slug(:list, id), world, id) end end } end on_mastodon_remove_auth_stream do |world| slugs = [] slugs.push world.datasource_slug(:home) slugs.push world.datasource_slug(:direct) lists = world.get_lists! lists.to_a.each do |l| id = l[:id].to_i slugs.push world.datasource_slug(:list, id) end slugs.each do |slug| Plugin.call(:mastodon_stop_stream, slug) end filter_extract_datasources do |datasources| slugs.each do |slug| datasources.delete slug end [datasources] end end on_mastodon_restart_sse_stream do |slug| Thread.new { connection, = Plugin.filtering(:sse_connection, slug) if connection.nil? # 終了済み next end Plugin.call(:sse_kill_connection, slug) sleep(rand(3..10)) Plugin.call(:sse_create, slug, :get, connection[:uri], connection[:headers], connection[:params], connection[:opts]) } end on_sse_connection_opening do |slug| notice "SSE: connection open for #{slug.to_s}" end on_sse_connection_failure do |slug, response| error "SSE: connection failure for #{slug.to_s}" pm::Util.ppf response if Mopt.error_level >= 1 if (response.status / 100) == 4 # 4xx系レスポンスはリトライせず終了する Plugin.call(:sse_kill_connection, slug) else Plugin.call(:mastodon_restart_sse_stream, slug) end end on_sse_connection_closed do |slug| warn "SSE: connection closed for #{slug.to_s}" Plugin.call(:mastodon_restart_sse_stream, slug) end on_sse_connection_error do |slug, e| error "SSE: connection error for #{slug.to_s}" pp e if Mopt.error_level >= 1 Plugin.call(:mastodon_restart_sse_stream, slug) end on_sse_on_update do |slug, json| Thread.new { data = JSON.parse(json, symbolize_names: true) update_handler(slug, data) } end on_sse_on_notification do |slug, json| Thread.new { data = JSON.parse(json, symbolize_names: true) notification_handler(slug, data) } end on_sse_on_delete do |slug, id| # 消す必要ある? # pawooは一定時間後(1分~7日後)に自動消滅するtootができる拡張をしている。 # また、手動で即座に消す人もいる。 # これは後からアクセスすることはできないがTLに流れてきたものは、 # フォローした人々には見えている、という前提があるように思う。 # だから消さないよ。 end on_unload do Plugin.call(:sse_kill_all) end def stream_world(domain, access_token) Enumerator.new{|y| Plugin.filtering(:mastodon_worlds, nil).first }.lazy.select{|world| world.domain == domain && world.access_token == access_token }.first end def update_handler(datasource_slug, payload) pm = Plugin::Mastodon connection, = Plugin.filtering(:sse_connection, datasource_slug) domain = connection[:opts][:domain] access_token = connection[:opts][:token] status = pm::Status.build(domain, [payload]).first return if status.nil? Plugin.call(:extract_receive_message, datasource_slug, [status]) world = stream_world(domain, access_token) Plugin.call(:update, world, [status]) if (status&.reblog).is_a?(pm::Status) Plugin.call(:retweet, [status]) world = status.to_me_world if !world.nil? Plugin.call(:mention, world, [status]) end end end def notification_handler(datasource_slug, payload) pm = Plugin::Mastodon connection, = Plugin.filtering(:sse_connection, datasource_slug) domain = connection[:opts][:domain] access_token = connection[:opts][:token] case payload[:type] when 'mention' status = pm::Status.build(domain, [payload[:status]]).first return if status.nil? Plugin.call(:extract_receive_message, datasource_slug, [status]) world = status.to_me_world if !world.nil? Plugin.call(:mention, world, [status]) end when 'reblog' user_id = payload[:account][:id] user_statuses = pm::API.call(:get, domain, "/api/v1/accounts/#{user_id}/statuses", access_token) if user_statuses.nil? error "Mastodon: ブーストStatusの取得に失敗" return end idx = user_statuses.value.index do |hash| hash[:reblog] && hash[:reblog][:uri] == payload[:status][:uri] end if idx.nil? error "Mastodon: ブーストStatusの取得に失敗(流れ速すぎ?)" return end status = pm::Status.build(domain, [user_statuses[idx]]).first return if status.nil? Plugin.call(:retweet, [status]) world = status.to_me_world if world Plugin.call(:mention, world, [status]) end when 'favourite' user = pm::Account.new(payload[:account]) status = pm::Status.build(domain, [payload[:status]]).first return if status.nil? status.favorite_accts << user.acct world = status.from_me_world status.set_modified(Time.now.localtime) if UserConfig[:favorited_by_anyone_age] and (UserConfig[:favorited_by_myself_age] or world.user_obj != user) if user && status && world Plugin.call(:favorite, world, user, status) end when 'follow' user = pm::Account.new payload[:account] world = stream_world(domain, access_token) if !world.nil? Plugin.call(:followers_created, world, [user]) end when 'poll' status = pm::Status.build(domain, [payload[:status]]).first return unless status activity(:poll, '投票が終了しました', description: "#{status.uri}") else # 未知の通知 warn 'unknown notification' pm::Util.ppf payload if Mopt.error_level >= 2 end end end [mastodon] SSE関連でよくエラーになる refs #1326 require_relative 'sse_client' Plugin.create(:mastodon) do pm = Plugin::Mastodon # ストリーム開始&直近取得イベント defevent :mastodon_start_stream, prototype: [String, String, String, pm::World, Integer] def datasource_used?(slug, include_all = false) return false if UserConfig[:extract_tabs].nil? UserConfig[:extract_tabs].any? do |setting| setting[:sources].any? do |ds| ds == slug || include_all && ds == :mastodon_appear_toots end end end on_mastodon_start_stream do |domain, type, slug, world, list_id| next if !UserConfig[:mastodon_enable_streaming] Thread.new { sleep(rand(10)) token = nil if world.is_a? pm::World token = world.access_token end base_url = 'https://' + domain + '/api/v1/streaming/' params = {} case type when 'user' uri = Diva::URI.new(base_url + 'user') when 'public' uri = Diva::URI.new(base_url + 'public') when 'public:media' uri = Diva::URI.new(base_url + 'public') params[:only_media] = true when 'public:local' uri = Diva::URI.new(base_url + 'public/local') when 'public:local:media' uri = Diva::URI.new(base_url + 'public/local') params[:only_media] = true when 'list' uri = Diva::URI.new(base_url + 'list') params[:list] = list_id when 'direct' uri = Diva::URI.new(base_url + 'direct') end headers = {} if token headers["Authorization"] = "Bearer " + token end Plugin.call(:sse_create, slug, :get, uri, headers, params, domain: domain, type: type, token: token) } end on_mastodon_stop_stream do |slug| Plugin.call(:sse_kill_connection, slug) end # mikutterにとって自明に60秒以上過去となる任意の日時 @last_all_restarted = Time.new(2007, 8, 31, 0, 0, 0, "+09:00") @waiting = false restarter = Proc.new do if @waiting Plugin.call(:sse_kill_all, :mastodon_start_all_streams) atomic { @last_all_restarted = Time.new @waiting = false } end atomic { @waiting = false } Reserver.new(60, &restarter) end on_mastodon_restart_all_streams do now = Time.new atomic { @waiting = true } if (now - @last_all_restarted) >= 60 restarter.call end end on_mastodon_start_all_streams do worlds, = Plugin.filtering(:mastodon_worlds, nil) worlds.each do |world| Thread.new { world.update_mutes! Plugin.call(:mastodon_init_auth_stream, world) } end UserConfig[:mastodon_instances].map do |domain, setting| Plugin.call(:mastodon_init_instance_stream, domain) end end # サーバーを必要に応じて再起動 on_mastodon_restart_instance_stream do |domain, retrieve = true| Thread.new { instance = pm::Instance.load(domain) if instance.retrieve != retrieve instance.retrieve = retrieve instance.store end Plugin.call(:mastodon_remove_instance_stream, domain) if retrieve Plugin.call(:mastodon_init_instance_stream, domain) end } end on_mastodon_init_instance_stream do |domain| Thread.new { instance = pm::Instance.load(domain) pm::Instance.add_datasources(domain) ftl_slug = pm::Instance.datasource_slug(domain, :federated) ftl_media_slug = pm::Instance.datasource_slug(domain, :federated_media) ltl_slug = pm::Instance.datasource_slug(domain, :local) ltl_media_slug = pm::Instance.datasource_slug(domain, :local_media) # ストリーム開始 Plugin.call(:mastodon_start_stream, domain, 'public', ftl_slug) if datasource_used?(ftl_slug, true) Plugin.call(:mastodon_start_stream, domain, 'public:media', ftl_media_slug) if datasource_used?(ftl_media_slug) Plugin.call(:mastodon_start_stream, domain, 'public:local', ltl_slug) if datasource_used?(ltl_slug) Plugin.call(:mastodon_start_stream, domain, 'public:local:media', ltl_media_slug) if datasource_used?(ltl_media_slug) } end on_mastodon_remove_instance_stream do |domain| Plugin.call(:mastodon_stop_stream, pm::Instance.datasource_slug(domain, :federated)) Plugin.call(:mastodon_stop_stream, pm::Instance.datasource_slug(domain, :local)) pm::Instance.remove_datasources(domain) end on_mastodon_init_auth_stream do |world| Thread.new { lists = world.get_lists! filter_extract_datasources do |dss| instance = pm::Instance.load(world.domain) datasources = { world.datasource_slug(:home) => "Mastodonホームタイムライン(Mastodon)/#{world.account.acct}", world.datasource_slug(:direct) => "Mastodon DM(Mastodon)/#{world.account.acct}", } lists.to_a.each do |l| slug = world.datasource_slug(:list, l[:id]) datasources[slug] = "Mastodonリスト(Mastodon)/#{world.account.acct}/#{l[:title]}" end [datasources.merge(dss)] end # ストリーム開始 if datasource_used?(world.datasource_slug(:home), true) Plugin.call(:mastodon_start_stream, world.domain, 'user', world.datasource_slug(:home), world) end if datasource_used?(world.datasource_slug(:direct), true) Plugin.call(:mastodon_start_stream, world.domain, 'direct', world.datasource_slug(:direct), world) end lists.to_a.each do |l| id = l[:id].to_i slug = world.datasource_slug(:list, id) if datasource_used?(world.datasource_slug(:list, id)) Plugin.call(:mastodon_start_stream, world.domain, 'list', world.datasource_slug(:list, id), world, id) end end } end on_mastodon_remove_auth_stream do |world| slugs = [] slugs.push world.datasource_slug(:home) slugs.push world.datasource_slug(:direct) lists = world.get_lists! lists.to_a.each do |l| id = l[:id].to_i slugs.push world.datasource_slug(:list, id) end slugs.each do |slug| Plugin.call(:mastodon_stop_stream, slug) end filter_extract_datasources do |datasources| slugs.each do |slug| datasources.delete slug end [datasources] end end on_mastodon_restart_sse_stream do |slug| Thread.new { connection, = Plugin.filtering(:sse_connection, slug) if connection.nil? # 終了済み next end Plugin.call(:sse_kill_connection, slug) sleep(rand(3..10)) Plugin.call(:sse_create, slug, :get, connection[:uri], connection[:headers], connection[:params], connection[:opts]) } end on_sse_connection_opening do |slug| notice "SSE: connection open for #{slug.to_s}" end on_sse_connection_failure do |slug, response| error "SSE: connection failure for #{slug.to_s}" pm::Util.ppf response if Mopt.error_level >= 1 if (response.status / 100) == 4 # 4xx系レスポンスはリトライせず終了する Plugin.call(:sse_kill_connection, slug) else Plugin.call(:mastodon_restart_sse_stream, slug) end end on_sse_connection_closed do |slug| warn "SSE: connection closed for #{slug.to_s}" Plugin.call(:mastodon_restart_sse_stream, slug) end on_sse_connection_error do |slug, e| error "SSE: connection error for #{slug.to_s}" pp e if Mopt.error_level >= 1 Plugin.call(:mastodon_restart_sse_stream, slug) end on_sse_on_update do |slug, json| Thread.new { data = JSON.parse(json, symbolize_names: true) update_handler(slug, data) } end on_sse_on_notification do |slug, json| Thread.new { data = JSON.parse(json, symbolize_names: true) notification_handler(slug, data) } end on_sse_on_delete do |slug, id| # 消す必要ある? # pawooは一定時間後(1分~7日後)に自動消滅するtootができる拡張をしている。 # また、手動で即座に消す人もいる。 # これは後からアクセスすることはできないがTLに流れてきたものは、 # フォローした人々には見えている、という前提があるように思う。 # だから消さないよ。 end on_unload do Plugin.call(:sse_kill_all) end def stream_world(domain, access_token) Enumerator.new{|y| Plugin.filtering(:mastodon_worlds, nil).first }.lazy.select{|world| world.domain == domain && world.access_token == access_token }.first end def update_handler(datasource_slug, payload) pm = Plugin::Mastodon connection, = Plugin.filtering(:sse_connection, datasource_slug) return unless connection domain = connection[:opts][:domain] access_token = connection[:opts][:token] status = pm::Status.build(domain, [payload]).first return if status.nil? Plugin.call(:extract_receive_message, datasource_slug, [status]) world = stream_world(domain, access_token) Plugin.call(:update, world, [status]) if (status&.reblog).is_a?(pm::Status) Plugin.call(:retweet, [status]) world = status.to_me_world if !world.nil? Plugin.call(:mention, world, [status]) end end end def notification_handler(datasource_slug, payload) pm = Plugin::Mastodon connection, = Plugin.filtering(:sse_connection, datasource_slug) return unless connection domain = connection[:opts][:domain] access_token = connection[:opts][:token] case payload[:type] when 'mention' status = pm::Status.build(domain, [payload[:status]]).first return if status.nil? Plugin.call(:extract_receive_message, datasource_slug, [status]) world = status.to_me_world if !world.nil? Plugin.call(:mention, world, [status]) end when 'reblog' user_id = payload[:account][:id] user_statuses = pm::API.call(:get, domain, "/api/v1/accounts/#{user_id}/statuses", access_token) if user_statuses.nil? error "Mastodon: ブーストStatusの取得に失敗" return end idx = user_statuses.value.index do |hash| hash[:reblog] && hash[:reblog][:uri] == payload[:status][:uri] end if idx.nil? error "Mastodon: ブーストStatusの取得に失敗(流れ速すぎ?)" return end status = pm::Status.build(domain, [user_statuses[idx]]).first return if status.nil? Plugin.call(:retweet, [status]) world = status.to_me_world if world Plugin.call(:mention, world, [status]) end when 'favourite' user = pm::Account.new(payload[:account]) status = pm::Status.build(domain, [payload[:status]]).first return if status.nil? status.favorite_accts << user.acct world = status.from_me_world status.set_modified(Time.now.localtime) if UserConfig[:favorited_by_anyone_age] and (UserConfig[:favorited_by_myself_age] or world.user_obj != user) if user && status && world Plugin.call(:favorite, world, user, status) end when 'follow' user = pm::Account.new payload[:account] world = stream_world(domain, access_token) if !world.nil? Plugin.call(:followers_created, world, [user]) end when 'poll' status = pm::Status.build(domain, [payload[:status]]).first return unless status activity(:poll, '投票が終了しました', description: "#{status.uri}") else # 未知の通知 warn 'unknown notification' pm::Util.ppf payload if Mopt.error_level >= 2 end end end
#encoding: utf-8 require 'cucumber' require 'cucumber/rake/task' Cucumber::Rake::Task.new(:features) do |t| t.profile = 'default' t.cucumber_opts = "*/features --format json --out report.json" end task :default => :features #update trying some changes to rake #encoding: utf-8 require 'cucumber' require 'cucumber/rake/task' Cucumber::Rake::Task.new(:features) do |t| t.profile = 'default' t.cucumber_opts = "-r */features --format json --out report.json" end task :default => :features #update
require 'spec_helper' describe LoadDsl do it "should add beliefs" do subject.run do user "merijn", "merijn@gmail.com", "123hoi", "Merijn Terheggen" user "tomdev", "tom@factlink.com", "123hoi", "Tom de Vries" user "mark", "mark@example.com", "123hoi", "Mark IJbema" as_user "mark" do fact "something is true", "http://example.org/" do believers "merijn","tomdev" disbelievers "mark" end end end # shouldn't raise end it "should throw an error if a user with a non-unique email is added" do expect do subject.run do user "tom", "tom@codigy.nl", "123hoi", "Mark IJbema" user "tomdev", "tom@codigy.nl", "123hoi", "Tom de Vries" end end.to raise_error end end Test load_dsl properly require 'spec_helper' describe LoadDsl do it "should add beliefs" do subject.run do user "merijn", "merijn@gmail.com", "123hoi", "Merijn Terheggen" user "tomdev", "tom@factlink.com", "123hoi", "Tom de Vries" user "mark", "mark@example.com", "123hoi", "Mark IJbema" as_user "mark" do fact "something is true", "http://example.org/" do believers "merijn","tomdev" disbelievers "mark" end end end # shouldn't raise end it "should throw an error if a user with a non-unique email is added" do expect do subject.run do user "tom", "tom@codigy.nl", "123hoi", "Mark IJbema" user "tomdev", "tom@codigy.nl", "123hoi", "Tom de Vries" end end.to raise_error end it "doesn't crash in our setup" do require File.expand_path('../../../db/init.rb', __FILE__) end end