Class: FPM::Package::CPAN

Inherits:
FPM::Package show all
Defined in:
lib/fpm/package/cpan.rb

Instance Attribute Summary

Attributes inherited from FPM::Package

#architecture, #attributes, #attrs, #category, #config_files, #conflicts, #dependencies, #description, #directories, #epoch, #iteration, #license, #maintainer, #name, #provides, #replaces, #scripts, #url, #vendor, #version

Instance Method Summary collapse

Methods inherited from FPM::Package

apply_options, #build_path, #cleanup, #cleanup_build, #cleanup_staging, #convert, #converted_from, default_attributes, #edit_file, #files, inherited, #initialize, option, #output, #script, #staging_path, #to_s, #type, type, types

Methods included from Util

#ar_cmd, #ar_cmd_deterministic?, #copied_entries, #copy_entry, #copy_metadata, #default_shell, #execmd, #expand_pessimistic_constraints, #logger, #mknod_w, #program_exists?, #program_in_path?, #safesystem, #safesystemout, #tar_cmd, #tar_cmd_supports_sort_names_and_set_mtime?

Constructor Details

This class inherits a constructor from FPM::Package

Instance Method Details

#input(package) ⇒ Object



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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
# File 'lib/fpm/package/cpan.rb', line 41

def input(package)
  #if RUBY_VERSION =~ /^1\.8/
    #raise FPM::Package::InvalidArgument,
      #"Sorry, CPAN support requires ruby 1.9 or higher. You have " \
      #"#{RUBY_VERSION}. If this negatively impacts you, please let " \
      #"me know by filing an issue: " \
      #"https://github.com/jordansissel/fpm/issues"
  #end
  #require "ftw" # for http access
  require "net/http"
  require "json"

  if File.exist?(package)
    moduledir = package
    result = {}
  else
    result = search(package)
    tarball = download(result, version)
    moduledir = unpack(tarball)
  end

  # Read package metadata (name, version, etc)
  if File.exist?(File.join(moduledir, "META.json"))
     = JSON.parse(File.read(File.join(moduledir, ("META.json"))))
  elsif File.exist?(File.join(moduledir, ("META.yml")))
    require "yaml"
     = YAML.load_file(File.join(moduledir, ("META.yml")))
  elsif File.exist?(File.join(moduledir, "MYMETA.json"))
     = JSON.parse(File.read(File.join(moduledir, ("MYMETA.json"))))
  elsif File.exist?(File.join(moduledir, ("MYMETA.yml")))
    require "yaml"
     = YAML.load_file(File.join(moduledir, ("MYMETA.yml")))
  end

  # Merge the MetaCPAN query result and the metadata pulled from the local
  # META file(s).  The local data overwrites the query data for all keys the
  # two hashes have in common.  Merge with an empty hash if there was no
  # local META file.
   = result.merge( || {})

  if .empty?
    raise FPM::InvalidPackageConfiguration,
      "Could not find package metadata. Checked for META.json, META.yml, and MetaCPAN API data"
  end

  self.version = ["version"]
  self.description = ["abstract"]

  self.license = case ["license"]
    when Array; ["license"].first
    when nil; "unknown"
    else; ["license"]
  end

  unless ["distribution"].nil?
    logger.info("Setting package name from 'distribution'",
                 :distribution => ["distribution"])
    self.name = fix_name(["distribution"])
  else
    logger.info("Setting package name from 'name'",
                 :name => ["name"])
    self.name = fix_name(["name"])
  end

  unless ["module"].nil?
    ["module"].each do |m|
      self.provides << cap_name(m["name"]) + " = #{self.version}"
    end
  end

  # author is not always set or it may be a string instead of an array
  self.vendor = case ["author"]
    when String; ["author"]
    when Array; ["author"].join(", ")
    else
      raise FPM::InvalidPackageConfiguration, "Unexpected CPAN 'author' field type: #{["author"].class}. This is a bug."
  end if .include?("author")

  self.url = ["resources"]["homepage"] rescue "unknown"

  # TODO(sissel): figure out if this perl module compiles anything
  # and set the architecture appropriately.
  self.architecture = "all"

  # Install any build/configure dependencies with cpanm.
  # We'll install to a temporary directory.
  logger.info("Installing any build or configure dependencies")

  if attributes[:cpan_sandbox_non_core?]
    cpanm_flags = ["-L", build_path("cpan"), moduledir]
  else
    cpanm_flags = ["-l", build_path("cpan"), moduledir]
  end

  # This flag causes cpanm to ONLY download dependencies, skipping the target
  # module itself.  This is fine, because the target module has already been
  # downloaded, and there's no need to download twice, test twice, etc.
  cpanm_flags += ["--installdeps"]
  cpanm_flags += ["-n"] if !attributes[:cpan_test?]
  cpanm_flags += ["--mirror", "#{attributes[:cpan_mirror]}"] if !attributes[:cpan_mirror].nil?
  cpanm_flags += ["--mirror-only"] if attributes[:cpan_mirror_only?] && !attributes[:cpan_mirror].nil?
  cpanm_flags += ["--force"] if attributes[:cpan_cpanm_force?]
  cpanm_flags += ["--verbose"] if attributes[:cpan_verbose?]

  safesystem(attributes[:cpan_cpanm_bin], *cpanm_flags)

  if !attributes[:no_auto_depends?]
   found_dependencies = {}
   if ["requires"]
     found_dependencies.merge!(["requires"])
   end
   if ["prereqs"]
     if ["prereqs"]["runtime"]
       if ["prereqs"]["runtime"]["requires"]
         found_dependencies.merge!(["prereqs"]["runtime"]["requires"])
       end
     end
   end
   unless found_dependencies.empty?
     found_dependencies.each do |dep_name, version|
        # Special case for representing perl core as a version.
        if dep_name == "perl"
          m = version.to_s.match(/^(\d)\.(\d{3})(\d{3})$/)
          if m
             version = m[1] + '.' + m[2].sub(/^0*/, '') + '.' + m[3].sub(/^0*/, '')
          end
          self.dependencies << "#{dep_name} >= #{version}"
          next
        end
        dep = search(dep_name)

        name = cap_name(dep_name)

        if version.to_s == "0"
          # Assume 'Foo = 0' means any version?
          self.dependencies << "#{name}"
        else
          # The 'version' string can be something complex like:
          #   ">= 0, != 1.0, != 1.2"
          # If it is not specified explicitly, require the given
          # version or newer, as that is all CPAN itself enforces
          if version.is_a?(String)
            version.split(/\s*,\s*/).each do |v|
              if v =~ /\s*[><=]/
                self.dependencies << "#{name} #{v}"
              else
                self.dependencies << "#{name} >= #{v}"
              end
            end
          else
            self.dependencies << "#{name} >= #{version}"
          end
        end
      end
    end
  end #no_auto_depends

  ::Dir.chdir(moduledir) do
    # TODO(sissel): install build and config dependencies to resolve
    # build/configure requirements.
    # META.yml calls it 'configure_requires' and 'build_requires'
    # META.json calls it prereqs/build and prereqs/configure

    prefix = attributes[:prefix] || "/usr/local"
    # TODO(sissel): Set default INSTALL path?

    # Try Makefile.PL, Build.PL
    #
    if File.exist?("Build.PL")
      # Module::Build is in use here; different actions required.
      safesystem(attributes[:cpan_perl_bin],
                 "-Mlocal::lib=#{build_path("cpan")}",
                 "Build.PL")
      safesystem(attributes[:cpan_perl_bin],
                 "-Mlocal::lib=#{build_path("cpan")}",
                 "./Build")

      if attributes[:cpan_test?]
        safesystem(attributes[:cpan_perl_bin],
                 "-Mlocal::lib=#{build_path("cpan")}",
                 "./Build", "test")
      end
      if attributes[:cpan_perl_lib_path]
        perl_lib_path = attributes[:cpan_perl_lib_path]
        safesystem("./Build install --install_path lib=#{perl_lib_path} \
                   --destdir #{staging_path} --prefix #{prefix} --destdir #{staging_path}")
      else
         safesystem("./Build", "install",
                   "--prefix", prefix, "--destdir", staging_path,
                   # Empty install_base to avoid local::lib being used.
                   "--install_base", "")
      end
    elsif File.exist?("Makefile.PL")
      if attributes[:cpan_perl_lib_path]
        perl_lib_path = attributes[:cpan_perl_lib_path]
        safesystem(attributes[:cpan_perl_bin],
                   "-Mlocal::lib=#{build_path("cpan")}",
                   "Makefile.PL", "PREFIX=#{prefix}", "LIB=#{perl_lib_path}",
                   # Empty install_base to avoid local::lib being used.
                   "INSTALL_BASE=")
      else
        safesystem(attributes[:cpan_perl_bin],
                   "-Mlocal::lib=#{build_path("cpan")}",
                   "Makefile.PL", "PREFIX=#{prefix}",
                   # Empty install_base to avoid local::lib being used.
                   "INSTALL_BASE=")
      end
      make = [ "env", "PERL5LIB=#{build_path("cpan/lib/perl5")}", "make" ]
      safesystem(*make)
      safesystem(*(make + ["test"])) if attributes[:cpan_test?]
      safesystem(*(make + ["DESTDIR=#{staging_path}", "install"]))


    else
      raise FPM::InvalidPackageConfiguration,
        "I don't know how to build #{name}. No Makefile.PL nor " \
        "Build.PL found"
    end

    # Fix any files likely to cause conflicts that are duplicated
    # across packages.
    # https://github.com/jordansissel/fpm/issues/443
    # https://github.com/jordansissel/fpm/issues/510
    glob_prefix = attributes[:cpan_perl_lib_path] || prefix
    ::Dir.glob(File.join(staging_path, glob_prefix, "**/perllocal.pod")).each do |path|
      logger.debug("Removing useless file.",
                    :path => path.gsub(staging_path, ""))
      File.unlink(path)
    end

    # Remove useless .packlist files and their empty parent folders
    # https://github.com/jordansissel/fpm/issues/1179
    ::Dir.glob(File.join(staging_path, glob_prefix, "**/.packlist")).each do |path|
      logger.debug("Removing useless file.",
                    :path => path.gsub(staging_path, ""))
      File.unlink(path)
      Pathname.new(path).parent.ascend do |parent|
        if ::Dir.entries(parent).sort == ['.', '..'].sort
          FileUtils.rmdir parent
        else
          break
        end
      end
    end
  end


  # TODO(sissel): figure out if this perl module compiles anything
  # and set the architecture appropriately.
  self.architecture = "all"

  # Find any shared objects in the staging directory to set architecture as
  # native if found; otherwise keep the 'all' default.
  Find.find(staging_path) do |path|
    if path =~ /\.so$/
      logger.info("Found shared library, setting architecture=native",
                   :path => path)
      self.architecture = "native"
    end
  end
end