# frozen_string_literal: true require "find" require "pathname" #require "gitignore" # This module provides classes for the Makit gem. module Makit # This class provide methods for working with Directories/ # # Example: # # Makit::Directory.find_directory_with_pattern("/home/user", "*.rb") # class Directory def self.get_line_count(file) line_count = 0 File.foreach(file) { line_count += 1 } line_count end def self.find_directory_with_patterns(starting_directory, patterns) patterns.each do |pattern| result = find_directory_with_pattern(starting_directory, pattern) if (Dir.exist?(result)) return result end end nil end def self.find_directory_with_pattern(starting_directory, pattern) current_directory = File.expand_path(starting_directory) loop do return current_directory if contains_pattern?(current_directory, pattern) parent_directory = File.dirname(current_directory) break if parent_directory == current_directory # Reached the root directory current_directory = parent_directory end nil end def self.contains_pattern?(directory, pattern) Dir.foreach(directory) do |entry| next if [".", ".."].include?(entry) return true if File.fnmatch(pattern, entry) end false end def self.get_size(directory) total_size = 0 Find.find(directory) do |file| total_size += File.size(file) if File.file?(file) end total_size end def self.get_humanized_size(size_in_bytes, precision = 2) end def self.zip_source_files(directory_path, zip_file_name) raise ArgumentError, "Directory path cannot be nil" if directory_path.nil? raise ArgumentError, "Zip file name cannot be nil or empty" if zip_file_name.nil? || zip_file_name.strip.empty? unless Dir.exist?(directory_path) raise ArgumentError, "Directory '#{directory_path}' does not exist." end tracked_files = get_git_tracked_files(directory_path) if tracked_files.empty? raise "No tracked files found in the directory." end Zip::File.open(zip_file_name, Zip::File::CREATE) do |zipfile| tracked_files.each do |file| full_path = File.join(directory_path, file) if File.exist?(full_path) zipfile.add(file, full_path) end end end end def self.get_git_tracked_files(directory_path) output, status = Open3.capture2("git ls-files", chdir: directory_path) raise "Failed to list git-tracked files" unless status.success? output.split("\n") end # Normalize the path by removing any leading or trailing slashes # and replacing any backslashes with forward slashes def self.normalize(path) path = path.gsub("\\", "/") #path = path[1..-1] if path.start_with?("/") path = path[0..-2] if path.end_with?("/") path end # for a given path, collect all the subdirectories that match a version pattern. # for example 2.57.0, 2.62, or 2.65.0 def self.get_version_directories(path) version_directories = [] Dir.foreach(path) do |entry| next if [".", ".."].include?(entry) version_directories << entry if entry.match?(/^\d+\.\d+\.\d+$/) end version_directories end end end