npolar/api.npolar.no

View on GitHub
bin/npolar-api-migrator

Summary

Maintainability
Test Coverage
#!/usr/bin/env ruby

# Npolar::Api::Migrator runner

# Example, running a migration:
#   ./bin/npolar-api-migrator https://api.npolar.no/publication PublicationMigration0 --really=false > /dev/null
# Set --really=true to POST the migrated documents back into the API

require "bundler/setup"
require "yajl/json_gem"
require "logger"
require "openssl"
require "logger"
require_relative "./../load"

require_relative "./../lib/npolar/http"
#require_relative "./../lib/npolar/api/client"
require_relative "./../lib/npolar/validation/multi_json_schema_validator"
require_relative "./../lib/npolar/factory"
require_relative "./../lib/npolar/api/migrator"

configfile = File.dirname(__FILE__)+"/../config/config.rb"
if File.exists? configfile
  require configfile
end

Dir.glob(File.dirname(__FILE__)+"/../migration/*.rb").each do | file |
  require file
end
Dir.glob(File.dirname(__FILE__)+"/../migration/**/*.rb").each do | file |
  require file
end

module Npolar

  begin
  
    unless ARGV.size >= 3
      puts "Usage: \n #{__FILE__} {URI} {Migration} --really[=true|false] [--debug]\n"
      exit(1)
    end
    
    uri = ARGV[0].gsub(/\/$/, "")
    
    migration = ARGV[1]
    migration = Factory.constantize(migration).new
    
    really = false
    if ARGV.any? {|a| a =~ /^--really=(true|false)$/}
      really = ($1 == "true") ? true : false
    end
    
    log_level = Logger::INFO
    if ARGV.index {|a| a =~ /^--log-level=(.+)/ }
      log_level = case $1
      when /warn/i
        Logger::WARN
      when /fatal/i
        Logger::FATAL
      when /error/i
        Logger::ERROR
      when /debug/i
        Logger::DEBUG
      else
        log_level
      end
    end

    log = Logger.new(STDERR)
    log.level = log_level
    batch = `uuidgen -r /dev/random`.chomp
    log.debug "#{migration} about to start in #{File.absolute_path(__FILE__)}"
    
    if migration.respond_to? :log
      migration.log = log
    end

    client = Api::Client::JsonApiClient.new(uri)
    client.log = log
    
    if migration.respond_to? :model
      client.model = migration.model
    end
    
    migrator = Api::Migrator.new
    
    migrator.log = log
    migrator.uri = uri
    migrator.client = client
    migrator.migrations = migration.migrations # Array of lambdas
    
    # Set migrator's documents to a lambda to a subset of documents, e.g. corresponding to a database view
    if migration.respond_to? :documents
      migrator.documents = migration.documents
    end
      
    migrator.select = migration.respond_to?(:select) ? migration.select : lambda {|d| true }
    migrator.batch = batch
    migrator.run(really)

    exit(0)
  
  rescue => e
    raise e
    exit(1)
  end 

end