aboutsummaryrefslogtreecommitdiffstats
path: root/app/models/chouette/command.rb
blob: b735747bf9bd3dc61bf39929f6db6f9318d40f41 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
require 'tmpdir'

#if RUBY_PLATFORM == "java"
  # FIXME disable remove_entry_secure because incompatible with jruby ?! 
  # See http://jira.codehaus.org/browse/JRUBY-4082
  module FileUtils
    def self.remove_entry_secure(*args)
      self.remove_entry *args
    end
  end
#end

module Chouette
  class Command

    include Chouette::CommandLineSupport

    @@command = "chouette"
    cattr_accessor :command

    attr_accessor :database, :schema, :host, :user, :password, :port

    def initialize(options = {})
      database_options_from_active_record.merge(options).each do |k,v|
        send "#{k}=", v
      end
    end

    def database_options_from_active_record
      config = Chouette::ActiveRecord.connection_pool.spec.config
      { 
        :database => config[:database], 
        :user => config[:username],
        :password => config[:password],
        :port => config[:port],
        :host => (config[:host] or "localhost")
      }
    end


    def run!(options = {})
      Dir.mktmpdir do |config_dir|
        chouette_properties = File.join(config_dir, "chouette.properties")
        open(chouette_properties, "w") do |f|
          f.puts "database.name = #{database}"
          f.puts "database.schema = #{schema}"
          #f.puts "database.showsql = true"
          f.puts "hibernate.username = #{user}"
          f.puts "hibernate.password = #{password}"
          f.puts "jdbc.url=jdbc:postgresql://#{host}:#{port}/#{database}"
          f.puts "jdbc.username = #{user}"
          f.puts "jdbc.password = #{password}"
          #f.puts "database.hbm2ddl.auto=update"
        end

        logger.debug "Chouette properties: #{File.readlines(chouette_properties).collect(&:strip).join(', ')}"

        command_line = "#{command} -classpath #{config_dir} #{command_options(options)}"
        logger.debug "Execute '#{command_line}'"

        execute! command_line
      end
    end

    class Option

      attr_accessor :key, :value

      def initialize(key, value)
        @key, @value = key.to_s, value
      end

      def command_key
        key.camelize(:lower) 
      end

      def to_s
        unless value == true
          "-#{command_key} #{value}"
        else
          "-#{command_key}"
        end
      end

    end

    def command_options(options)
      options.collect do |key, value|
        Option.new(key, value)
      end.sort_by(&:key).join(' ')
    end

  end
end