# frozen_string_literal: true module Groundskeeper # The `version.rb` file in an application. class RailsVersion APPLICATION_CONFIG_FILE = "%sconfig/application.rb" INITIAL_VERSION = "0.0.0" MODULE_NAME_EXPRESSION = /module (\w+)/ NAMESPACE_FILE = "%slib/%s.rb" MODULE_DIRECTORY = "%slib/%s" VERSION_FILE = "#{MODULE_DIRECTORY}/version.rb" VERSION_EXPRESSION = /(?<=VERSION = ")([^"]+)(?=")/ attr_reader :config_file, :namespace_file, :project_name, :relative_path, :version_file # rubocop:disable Metrics/MethodLength def self.build(relative_path = "") config_file_path = format(APPLICATION_CONFIG_FILE, relative_path) config_file = Groundskeeper::Document.new(config_file_path) project_name = config_file.match(MODULE_NAME_EXPRESSION) folder_namespace = StringUtils.underscore(project_name) namespace_file_path = format(NAMESPACE_FILE, relative_path, folder_namespace) version_file_path = format(VERSION_FILE, relative_path, folder_namespace) new( relative_path, project_name: project_name, config_file: config_file, namespace_file: Groundskeeper::Document.new(namespace_file_path), version_file: Groundskeeper::Document.new(version_file_path) ) end # rubocop:enable Metrics/MethodLength def initialize( relative_path = "", project_name: "", config_file: nil, namespace_file:, version_file: nil ) @relative_path = relative_path @project_name = project_name @config_file = config_file || find_config_file @namespace_file = namespace_file @version_file = version_file || find_version_file end def current_version version_file.match(VERSION_EXPRESSION) || "" end def update_version!(value) version_file.gsub_file VERSION_EXPRESSION, value end def rails? config_file.exists? end def exists? version_file.exists? end # rubocop:disable Metrics/MethodLength def create_initial_version! version_file.make_parent_directory! version_file.write_file( <<~RB # frozen_string_literal: true # Version string. module #{project_name} VERSION = "#{INITIAL_VERSION}" end RB ) namespace_file.write_file( <<~RB # frozen_string_literal: true require_relative "./#{folder_namespace}/version" # nodoc module #{project_name} end RB ) end # rubocop:enable Metrics/MethodLength private def find_config_file @config_file = Groundskeeper::Document.new(config_file_path) end def find_version_file @version_file = Groundskeeper::Document.new(version_file_path) end def config_file_path format APPLICATION_CONFIG_FILE, relative_path end def version_file_path format VERSION_FILE, relative_path, folder_namespace end def folder_namespace StringUtils.underscore(config_file.match(MODULE_NAME_EXPRESSION)) end end end