summaryrefslogtreecommitdiff
path: root/lib/up2date.rb
blob: d9eab155d4175eebc0e3c6d7e5dbfe7234530ccb (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
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.

# frozen_string_literal: true

require 'net/http'
require 'json'
require_relative '../config/config'
require 'term/ansicolor'

module SlackBuilder
  extend Term::ANSIColor

  # Remote repository for a single package.
  class Repository
    # Request the latest tag in the given repository.
    def latest
      raise NotImplementedError
    end
  end

  # Reads the list fo tags from the GitHub API.
  class GitHub < Repository
    def initialize(owner, name, version_transform = nil)
      super()

      @owner = owner
      @name = name
      @version_transform = version_transform
    end

    def latest
      `./bin/slackbuilder github #{@owner} #{@name} #{@version_transform}`.strip
    end
  end

  # Request the latest version from the packagist API.
  class Packagist < Repository
    def initialize(vendor, name)
      super()

      @vendor = vendor
      @name = name
    end

    def latest
      `./bin/slackbuilder packagist #{@vendor} #{@name}`.strip
    end
  end

  # Reads a remote LATEST file.
  class LatestText < Repository
    def initialize(latest_url)
      super()

      @latest_url = latest_url
    end

    def latest
      `./bin/slackbuilder text #{@latest_url}`.strip
    end
  end

  module_function

  # Checks if there is a new version for the package and returns the latest
  # version if an update is available, otherwise returns nil.
  def check_for_latest(package_name, repository)
    package = find_package_info package_name
    latest_version = repository.latest

    if package.version == latest_version
      puts green "#{package_name} is up to date (Version #{package.version})."
      nil
    else
      puts red "#{package_name}: Current version is #{package.version}, #{latest_version} is available."
      latest_version
    end
  end

  private_class_method def find_package_info(package_name)
    package_path = Pathname.new Dir.glob("#{CONFIG[:repository]}/*/#{package_name}").first
    package_category = package_path.dirname.basename.to_s
    Package.parse("#{package_category}/#{package_name}", File.read("#{package_path}/#{package_name}.info"))
  end
end