lib/svelte_on_rails/installer/javascript.rb



module SvelteOnRails
  module Installer
    module Javascript

      # check if import statement already exists and, if not, append it after the last import statement of that file
      #

      def self.append_import_statement(file_path, package_name_for_test_existence, import_statement)

        # Read the file content
        content = File.read(file_path)

        # Split content into lines
        lines = content.lines

        already_exist = []
        lines.each do |line|
          if line.match(/^\s*import\s+.*['"]#{package_name_for_test_existence}['";].*$/)
            already_exist.push(line)
          end
        end

        if already_exist.present?
          puts "skipping: #{import_statement} already exists in #{File.basename(file_path)}, found: «#{already_exist.join(' // ').strip}»."
        else

          # Find the index of the last import statement
          last_import_index = -1
          lines.each_with_index do |line, index|
            if line.match?(/^\s*import\s+.*$/)
              last_import_index = index
            end
          end

          # Insert the import statement after the last import
          if last_import_index >= 0
            lines.insert(last_import_index + 1, import_statement)
          else
            # If no import statements, add at the beginning
            lines.unshift(import_statement)
          end

          # Write the modified content back to the file
          begin
            File.write(file_path, lines.map{|l|l.gsub(/\n/, '')}.join("\n"))
            puts "Successfully inserted «#{import_statement}» into '#{file_path}' on line #{last_import_index + 2}."
          rescue => e
            raise "Error writing to #{file_path} => «#{e.message}»"
          end
        end
      end

    end
  end
end