Class: Isort::FileSorter

Inherits:
Object
  • Object
show all
Defined in:
lib/isort.rb

Instance Method Summary collapse

Constructor Details

#initialize(file_path) ⇒ FileSorter

Returns a new instance of FileSorter.



8
9
10
# File 'lib/isort.rb', line 8

def initialize(file_path)
  @file_path = file_path
end

Instance Method Details

#sort_and_format_importsObject



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/isort.rb', line 30

def sort_and_format_imports
  # Read the file content
  lines = File.readlines(@file_path)

  # Separate and group lines
  requires = extract_lines_with_comments(lines, /^require\s/)
  require_relatives = extract_lines_with_comments(lines, /^require_relative\s/)
  includes = extract_lines_with_comments(lines, /^include\s/)
  extends = extract_lines_with_comments(lines, /^extend\s/)
  autoloads = extract_lines_with_comments(lines, /^autoload\s/)
  usings = extract_lines_with_comments(lines, /^using\s/)
  others = lines.reject { |line| [requires, require_relatives, includes, extends, autoloads, usings].flatten.include?(line) }

  # Format and sort each group
  formatted_imports = []
  formatted_imports << format_group("require", requires)
  formatted_imports << format_group("require_relative", require_relatives)
  formatted_imports << format_group("include", includes)
  formatted_imports << format_group("extend", extends)
  formatted_imports << format_group("autoload", autoloads)
  formatted_imports << format_group("using", usings)

  return if [requires, require_relatives, includes, extends, autoloads, usings].all?(&:empty?)

  # Combine formatted imports with the rest of the file
  sorted_content = "#{formatted_imports.reject(&:empty?).join("\n")}\n#{others.join}".strip

  # Add a trailing newline only if imports exist
  sorted_content = "#{sorted_content.rstrip}\n" if !formatted_imports.empty? && !sorted_content.empty?

  # Write the sorted content back to the file only if imports exist
  File.write(@file_path, sorted_content) unless formatted_imports.empty? && sorted_content.empty?
end

#sort_importsObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/isort.rb', line 12

def sort_imports
  # Read the file content
  lines = File.readlines(@file_path, chomp: true).map { |line| line.gsub("\r", "") }

  # Separate import-related lines and other content
  imports = lines.select { |line| line =~ /^\s*(require|require_relative|include)\s/ }
  non_imports = lines.reject { |line| line =~ /^\s*(require|require_relative|include)\s/ }

  # Sort the import lines alphabetically
  sorted_imports = imports.sort

  # Combine sorted imports with other lines
  sorted_content = (sorted_imports + non_imports).join

  # Write the sorted content back to the file
  File.write(@file_path, sorted_content)
end