Class: Pkgr::App

Inherits:
Object
  • Object
show all
Includes:
RakeFileUtils
Defined in:
lib/pkgr/app.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root, config_path) ⇒ App

root: the root directory of the app. config a Configuration object, hosting the parameters defined in ‘config/pkgr.yml`.



15
16
17
18
19
# File 'lib/pkgr/app.rb', line 15

def initialize(root, config_path)
  @root = root
  load_config(config_path)
  @errors = []
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



11
12
13
# File 'lib/pkgr/app.rb', line 11

def config
  @config
end

#errorsObject (readonly)

Returns the value of attribute errors.



10
11
12
# File 'lib/pkgr/app.rb', line 10

def errors
  @errors
end

#rootObject (readonly)

Returns the value of attribute root.



9
10
11
# File 'lib/pkgr/app.rb', line 9

def root
  @root
end

Instance Method Details

#architectureObject



90
91
92
# File 'lib/pkgr/app.rb', line 90

def architecture
  @config['architecture'] || "all"
end

#author_emailObject



62
63
64
# File 'lib/pkgr/app.rb', line 62

def author_email
  @author_email ||= `git config --get user.email`.chomp
end

#author_nameObject



58
59
60
# File 'lib/pkgr/app.rb', line 58

def author_name
  @author_name ||= `git config --get user.name`.chomp
end

#build_debian_package(host) ⇒ Object



205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/pkgr/app.rb', line 205

def build_debian_package(host)
  puts "Building debian package on '#{host}'..."
  Dir.chdir(root) do
    Pkgr.mkdir("pkg")
    archive = "#{name}-#{version}"
    sh "scp #{File.expand_path("../data/config/pre_boot.rb", __FILE__)} #{host}:/tmp/"
    cmd = %Q{
      git archive #{git_ref} --prefix=#{archive}/ | ssh #{host} 'cat - > /tmp/#{archive}.tar &&
        set -x && rm -rf /tmp/#{archive} &&
        cd /tmp && tar xf #{archive}.tar && cd #{archive} &&
        cat config/boot.rb >> /tmp/pre_boot.rb && cp -f /tmp/pre_boot.rb config/boot.rb &&
        #{debian_steps.join(" &&\n")}'
    }
    sh cmd
    # Fetch all package files, and put it in the `pkg` directory
    sh "scp #{host}:/tmp/#{name}_#{version}* pkg/"
  end
end

#bump!(version_index = :patch, new_version = nil) ⇒ Object

FIXME: this is ugly



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/pkgr/app.rb', line 154

def bump!(version_index = :patch, new_version = nil)
  unless version_index == :custom
    indices = [:major, :minor, :patch]
    index = indices.index(version_index) || raise(ArgumentError, "The given version index is not valid (#{version_index})")
    fragments = version.split(".")
    fragments[index] = fragments[index].to_i+1
    ((index+1)..2).each{|i|
      fragments[i] = 0
    }
    new_version = fragments.join(".")
  else
    raise ArgumentError, "new_version must not be nil when bumping with a :custom version" if new_version.nil?
  end

  changelog = File.read(debian_file("changelog"))
  dist = (changelog.scan(/#{name} \(#{new_version}-(\d+)\)/).flatten[0].to_i)
  dist += 1 if new_version == version
  dist = 1 if dist == 0

  last_commit = changelog.scan(/\s+\* ([a-z0-9]{7}) /).flatten[0]

  cmd = "git log --oneline"
  cmd << " #{last_commit}..#{git_ref}" unless last_commit.nil?
  result = %x{#{cmd}}
  ok = $?.exitstatus == 0
  if !ok
    raise "Command failed. Aborting."
  else
    content_changelog = [
      "#{name} (#{new_version}-#{dist}) unstable; urgency=low",
      "",
      result.split("\n").reject{|l| l =~ / v#{version}/}.map{|l| "  * #{l}"}.join("\n"),
      "",
      " -- #{author_name} <#{author_email}>  #{Time.now.strftime("%a, %d %b %Y %H:%M:%S %z")}",
      "",
      changelog
    ].join("\n")

    File.open(debian_file("changelog"), "w+") do |f|
      f << content_changelog
    end

    @config['version'] = new_version
    write_config

    puts "Committing changelog and version file..."
    files_to_commit = [debian_file('changelog'), @config['_path']]
    sh "git add #{files_to_commit.join(" ")} && git commit -m '[pkgr] v#{new_version}-#{dist}' #{files_to_commit.join(" ")}"
  end
end

#config_filesObject



98
99
100
# File 'lib/pkgr/app.rb', line 98

def config_files
  @config['config_files'] || []
end

#debian_build_dependencies(installable_only = false) ⇒ Object



74
75
76
77
78
79
80
# File 'lib/pkgr/app.rb', line 74

def debian_build_dependencies(installable_only = false)
  deps = @config['debian_build_dependencies'] || []
  if installable_only
    deps = deps.reject{|d| d =~ /[\$\{\}]/}.map{|d| d.split(/\s/)[0]}
  end
  deps
end

#debian_runtime_dependencies(installable_only = false) ⇒ Object



82
83
84
85
86
87
88
# File 'lib/pkgr/app.rb', line 82

def debian_runtime_dependencies(installable_only = false)
  deps = @config['debian_runtime_dependencies'] || []
  if installable_only
    deps = deps.reject{|d| d =~ /[\$\{\}]/}.map{|d| d.split(/\s/)[0]}
  end
  deps
end

#debian_stepsObject



224
225
226
227
228
229
230
231
232
233
234
235
# File 'lib/pkgr/app.rb', line 224

def debian_steps
  target_vendor = "vendor/bundle/ruby/1.9.1"
  [
    # "sudo apt-get install #{debian_runtime_dependencies(true).join(" ")} -y",
    "sudo apt-get install #{debian_build_dependencies(true).join(" ")} -y",
    # Vendor bundler
    "gem1.9.1 install bundler --no-ri --no-rdoc --version #{bundler_version} -i #{target_vendor}",
    "GEM_HOME='#{target_vendor}' #{target_vendor}/bin/bundle install --deployment --without test development",
    "rm -rf #{target_vendor}/{cache,doc}",
    "dpkg-buildpackage -us -uc -d"
  ]
end

#descriptionObject



70
71
72
# File 'lib/pkgr/app.rb', line 70

def description
  @config['description'] || ""
end

#generate_required_filesObject



45
46
47
48
# File 'lib/pkgr/app.rb', line 45

def generate_required_files
  setup_debian
  setup_binary
end

#git_refObject



50
51
52
# File 'lib/pkgr/app.rb', line 50

def git_ref
  @config.fetch('git_ref') { 'HEAD' }
end

#groupObject



110
111
112
# File 'lib/pkgr/app.rb', line 110

def group
  @config.fetch('group') { name }
end

#homepageObject



94
95
96
# File 'lib/pkgr/app.rb', line 94

def homepage
  @config['homepage'] || ""
end

#load_config(path) ⇒ Object

Raises:

  • (ArgumentError)


21
22
23
24
25
26
# File 'lib/pkgr/app.rb', line 21

def load_config(path)
  @config = YAML::load_file(path)
  raise ArgumentError, "The given configuration file at '#{path}' is not a well-formed YAML file. Please fix it or remove it and run 'rake pkgr:setup'" unless @config.kind_of?(Hash)
  @config['_path'] = path
  normalize_name!
end

#nameObject



66
67
68
# File 'lib/pkgr/app.rb', line 66

def name
  @config['name']
end

#pkg_prefixObject

prefix without the leading slash.



115
116
117
# File 'lib/pkgr/app.rb', line 115

def pkg_prefix
  prefix[1..-1]
end

#prefixObject



54
55
56
# File 'lib/pkgr/app.rb', line 54

def prefix
  @config.fetch('prefix') { "/opt/local" }
end

#release_debian_package(host, apt_directory = nil) ⇒ Object



237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/pkgr/app.rb', line 237

def release_debian_package(host, apt_directory = nil)
  apt_directory ||= "/var/www/#{name}"
  latest = Dir[File.join(root, "pkg", "*.deb")].find{|file| file =~ /#{version}/}
  raise "No .deb available in pkg/" if latest.nil?
  latest_name = File.basename(latest)
  sh "scp #{latest} #{host}:/tmp/"
  sh "ssh #{host} 'sudo mkdir -p #{apt_directory} && sudo chown $USER #{apt_directory} && mv /tmp/#{latest_name} #{apt_directory} && cd #{apt_directory} && ( which dpkg-scanpackages || sudo apt-get update && sudo apt-get install dpkg-dev -y ) && dpkg-scanpackages . | gzip -f9 > Packages.gz'"
  puts "****"
  puts "Now you just need to serve the '#{apt_directory}' directory over HTTP, and add a new source to your APT configuration on the production server:"
  puts "$ cat /etc/apt/sources.list.d/#{name}.list"
  puts "deb http://apt-server.ltd/#{name} /"
  puts
  puts "And then:"
  puts "$ sudo apt-get update && sudo apt-get install #{name}"
  puts "****"
end

#setup_binaryObject

Creates an executable file for easy launch of the server/console/rake tasks once it is installed. E.g. /usr/bin/my-app console, /usr/bin/my-app server start -p 8080



145
146
147
148
149
150
151
# File 'lib/pkgr/app.rb', line 145

def setup_binary
  target = File.join(root, "bin", name)
  Pkgr.mkdir(File.dirname(target))
  FileUtils.cp(File.expand_path("../data/bin/executable", __FILE__), target, :verbose => true)
  FileUtils.chmod 0755, target, :verbose => true
  puts "Correctly set up executable file. Try running './bin/#{name} console'."
end

#setup_debianObject



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/pkgr/app.rb', line 119

def setup_debian
  target = File.join(root, Pkgr::DEBIAN_DIR)
  Pkgr.mkdir(target)

  Dir[File.expand_path("../data/debian/*", __FILE__)].each do |file|
    case File.extname(file)
    when ".erb"
      file_target = File.join(target, File.basename(file, ".erb"))
      File.open(file_target, "w+") do |f|
        f << ERB.new(File.read(file)).result(binding)
      end
    else
      file_target = File.join(target, File.basename(file))
      if File.exist?(file_target)
        puts "File #{file_target} already exists. Skipped."
      else
        FileUtils.cp(file, file_target, :verbose => true)
      end
    end
  end

  puts "Correctly set up debian files."
end

#userObject



106
107
108
# File 'lib/pkgr/app.rb', line 106

def user
  @config.fetch('user') { name }
end

#valid?Boolean

Returns true if the app is correctly configured. Else otherwise.

Returns:

  • (Boolean)


35
36
37
38
39
40
41
42
43
# File 'lib/pkgr/app.rb', line 35

def valid?
  @errors.clear
  @errors.push("is not a valid git repository") unless File.exist?(File.join(@root, ".git", "HEAD"))
  @errors.push("must have a name") unless @config.fetch('name')
  @errors.push("must have a valid name ([a-zA-Z0-9_-])") unless @config.fetch('name').scan(/[^a-z0-9\_\-]/i)
  @errors.push("must have a version") unless @config.fetch('version')
  @errors.push("must have a valid target architecture") unless @config.fetch('architecture')
  @errors.empty?
end

#versionObject



102
103
104
# File 'lib/pkgr/app.rb', line 102

def version
  @config['version']
end

#write_configObject



28
29
30
31
32
# File 'lib/pkgr/app.rb', line 28

def write_config
  File.open(@config['_path'] || raise("Don't know where to save myself!"), "w+") {|f|
    YAML.dump(@config.reject{|k,v| k == '_path'}, f)
  }
end