Merge branch '8784-dir-listings'
[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 # If you change this file, you'll probably also want to make the same
6 # changes in apps/workbench/lib/app_version.rb.
7
8 class AppVersion
9   def self.git(*args, &block)
10     IO.popen(["git", "--git-dir", ".git"] + args, "r",
11              chdir: Rails.root.join('../..'),
12              err: "/dev/null",
13              &block)
14   end
15
16   def self.forget
17     @hash = nil
18   end
19
20   # Return abbrev commit hash for current code version: "abc1234", or
21   # "abc1234-modified" if there are uncommitted changes. If present,
22   # return contents of {root}/git-commit.version instead.
23   def self.hash
24     if (cached = Rails.configuration.source_version || @hash)
25       return cached
26     end
27
28     # Read the version from our package's git-commit.version file, if available.
29     begin
30       @hash = IO.read(Rails.root.join("git-commit.version")).strip
31     rescue Errno::ENOENT
32     end
33
34     if @hash.nil? or @hash.empty?
35       begin
36         local_modified = false
37         git("status", "--porcelain") do |git_pipe|
38           git_pipe.each_line do |_|
39             local_modified = true
40             # Continue reading the pipe so git doesn't get SIGPIPE.
41           end
42         end
43         if $?.success?
44           git("log", "-n1", "--format=%H") do |git_pipe|
45             git_pipe.each_line do |line|
46               @hash = line.chomp[0...8] + (local_modified ? '-modified' : '')
47             end
48           end
49         end
50       rescue SystemCallError
51       end
52     end
53
54     @hash || "unknown"
55   end
56 end