Merge branch '21126-trash-when-ro'
[arvados.git] / services / api / lib / app_version.rb
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: AGPL-3.0
4
5 class AppVersion
6   def self.git(*args, &block)
7     IO.popen(["git", "--git-dir", ".git"] + args, "r",
8              chdir: Rails.root.join('../..'),
9              err: "/dev/null",
10              &block)
11   end
12
13   def self.forget
14     @hash = nil
15     @package_version = nil
16   end
17
18   # Return abbrev commit hash for current code version: "abc1234", or
19   # "abc1234-modified" if there are uncommitted changes. If present,
20   # return contents of {root}/git-commit.version instead.
21   def self.hash
22     if (cached = Rails.configuration.source_version || @hash)
23       return cached
24     end
25
26     # Read the version from our package's git-commit.version file, if available.
27     begin
28       @hash = IO.read(Rails.root.join("git-commit.version")).strip
29     rescue Errno::ENOENT
30     end
31
32     if @hash.nil? or @hash.empty?
33       begin
34         local_modified = false
35         git("status", "--porcelain") do |git_pipe|
36           git_pipe.each_line do |_|
37             local_modified = true
38             # Continue reading the pipe so git doesn't get SIGPIPE.
39           end
40         end
41         if $?.success?
42           git("log", "-n1", "--format=%H") do |git_pipe|
43             git_pipe.each_line do |line|
44               @hash = line.chomp[0...8] + (local_modified ? '-modified' : '')
45             end
46           end
47         end
48       rescue SystemCallError
49       end
50     end
51
52     @hash || "unknown"
53   end
54
55   def self.package_version
56     if (cached = Rails.configuration.package_version || @package_version)
57       return cached
58     end
59
60     begin
61       @package_version = IO.read(Rails.root.join("package-build.version")).strip
62     rescue Errno::ENOENT
63       @package_version = "unknown"
64     end
65
66     @package_version
67   end
68 end